summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorTyler Cipriani <tcipriani@wikimedia.org>2018-11-02 09:40:58 -0600
committerTyler Cipriani <tcipriani@wikimedia.org>2018-12-10 17:33:15 -0700
commit56e830f6417fe1ebda1bdc2cf7810dcccd9a7da6 (patch)
treea081badcc905a516c3421f9534555fe916b961e3
parent6597c943b6af809cc30e80070ad42953cab05dc4 (diff)
downloadblubber-56e830f6417fe1ebda1bdc2cf7810dcccd9a7da6.tar.gz
Use JSON as canonical config format
Uses the github.com/ghodss/yaml library to convert YAML to JSON before unmarshaling for the purposes of supporting YAML and JSON input while converting to only support JSON internally. Bug: T207694 Change-Id: I00668014907e9ea54917f5d5067cac08d0668053
-rw-r--r--.gitignore1
-rw-r--r--.pipeline/blubber.yaml2
-rw-r--r--CONTRIBUTING.md4
-rw-r--r--Gopkg.lock48
-rw-r--r--Gopkg.toml8
-rw-r--r--cmd/blubberoid/main.go2
-rw-r--r--config/apt.go2
-rw-r--r--config/apt_test.go2
-rw-r--r--config/artifacts.go6
-rw-r--r--config/artifacts_test.go8
-rw-r--r--config/builder.go4
-rw-r--r--config/builder_test.go2
-rw-r--r--config/common.go16
-rw-r--r--config/common_test.go2
-rw-r--r--config/config.go6
-rw-r--r--config/config_test.go2
-rw-r--r--config/flag.go9
-rw-r--r--config/flag_test.go2
-rw-r--r--config/lives.go4
-rw-r--r--config/lives_test.go4
-rw-r--r--config/node.go4
-rw-r--r--config/node_test.go2
-rw-r--r--config/policy.go39
-rw-r--r--config/policy_test.go6
-rw-r--r--config/python.go4
-rw-r--r--config/python_test.go6
-rw-r--r--config/reader.go49
-rw-r--r--config/reader_test.go20
-rw-r--r--config/runs.go6
-rw-r--r--config/runs_test.go2
-rw-r--r--config/user.go6
-rw-r--r--config/validation.go6
-rw-r--r--config/variant.go8
-rw-r--r--config/variant_test.go14
-rw-r--r--config/version.go2
-rw-r--r--config/version_test.go2
-rw-r--r--docker/compiler_test.go8
-rw-r--r--vendor/github.com/davecgh/go-spew/.gitignore22
-rw-r--r--vendor/github.com/davecgh/go-spew/.travis.yml14
-rw-r--r--vendor/github.com/davecgh/go-spew/README.md205
-rw-r--r--vendor/github.com/davecgh/go-spew/cov_report.sh22
-rw-r--r--vendor/github.com/davecgh/go-spew/spew/common_test.go298
-rw-r--r--vendor/github.com/davecgh/go-spew/spew/dump_test.go1042
-rw-r--r--vendor/github.com/davecgh/go-spew/spew/dumpcgo_test.go99
-rw-r--r--vendor/github.com/davecgh/go-spew/spew/dumpnocgo_test.go26
-rw-r--r--vendor/github.com/davecgh/go-spew/spew/example_test.go226
-rw-r--r--vendor/github.com/davecgh/go-spew/spew/format_test.go1558
-rw-r--r--vendor/github.com/davecgh/go-spew/spew/internal_test.go87
-rw-r--r--vendor/github.com/davecgh/go-spew/spew/internalunsafe_test.go102
-rw-r--r--vendor/github.com/davecgh/go-spew/spew/spew_test.go320
-rw-r--r--vendor/github.com/davecgh/go-spew/test_coverage.txt61
-rw-r--r--vendor/github.com/docker/distribution/.gitignore37
-rw-r--r--vendor/github.com/docker/distribution/.mailmap19
-rw-r--r--vendor/github.com/docker/distribution/BUILDING.md119
-rw-r--r--vendor/github.com/docker/distribution/CHANGELOG.md114
-rw-r--r--vendor/github.com/docker/distribution/CONTRIBUTING.md140
-rw-r--r--vendor/github.com/docker/distribution/Dockerfile18
-rw-r--r--vendor/github.com/docker/distribution/MAINTAINERS58
-rw-r--r--vendor/github.com/docker/distribution/Makefile109
-rw-r--r--vendor/github.com/docker/distribution/README.md131
-rw-r--r--vendor/github.com/docker/distribution/RELEASE-CHECKLIST.md36
-rw-r--r--vendor/github.com/docker/distribution/ROADMAP.md267
-rw-r--r--vendor/github.com/docker/distribution/blobs.go257
-rw-r--r--vendor/github.com/docker/distribution/circle.yml93
-rwxr-xr-xvendor/github.com/docker/distribution/coverpkg.sh7
-rw-r--r--vendor/github.com/docker/distribution/digest/digest_test.go82
-rw-r--r--vendor/github.com/docker/distribution/digest/digester_resumable_test.go21
-rw-r--r--vendor/github.com/docker/distribution/digest/set_test.go368
-rw-r--r--vendor/github.com/docker/distribution/digest/verifiers_test.go49
-rw-r--r--vendor/github.com/docker/distribution/doc.go7
-rw-r--r--vendor/github.com/docker/distribution/errors.go115
-rw-r--r--vendor/github.com/docker/distribution/manifests.go125
-rw-r--r--vendor/github.com/docker/distribution/reference/reference_test.go661
-rw-r--r--vendor/github.com/docker/distribution/reference/regexp_test.go489
-rw-r--r--vendor/github.com/docker/distribution/registry.go97
-rw-r--r--vendor/github.com/docker/distribution/tags.go27
-rw-r--r--vendor/github.com/ghodss/yaml/LICENSE50
-rw-r--r--vendor/github.com/ghodss/yaml/fields.go501
-rw-r--r--vendor/github.com/ghodss/yaml/yaml.go277
-rw-r--r--vendor/github.com/go-playground/locales/.gitignore24
-rw-r--r--vendor/github.com/go-playground/locales/README.md172
-rw-r--r--vendor/github.com/go-playground/locales/cu/cu.go609
-rw-r--r--vendor/github.com/go-playground/locales/cu/cu_test.go1120
-rw-r--r--vendor/github.com/go-playground/locales/logo.pngbin37360 -> 0 bytes
-rw-r--r--vendor/github.com/go-playground/universal-translator/.gitignore24
-rw-r--r--vendor/github.com/go-playground/universal-translator/README.md90
-rw-r--r--vendor/github.com/go-playground/universal-translator/benchmarks_test.go110
-rw-r--r--vendor/github.com/go-playground/universal-translator/import_export_test.go789
-rw-r--r--vendor/github.com/go-playground/universal-translator/logo.pngbin16598 -> 0 bytes
-rw-r--r--vendor/github.com/go-playground/universal-translator/translator_test.go858
-rw-r--r--vendor/github.com/pborman/getopt/CONTRIBUTING.md10
-rw-r--r--vendor/github.com/pborman/getopt/README.md226
-rw-r--r--vendor/github.com/pborman/getopt/bool.go74
-rw-r--r--vendor/github.com/pborman/getopt/bool_test.go106
-rw-r--r--vendor/github.com/pborman/getopt/breakup_test.go34
-rw-r--r--vendor/github.com/pborman/getopt/counter.go81
-rw-r--r--vendor/github.com/pborman/getopt/counter_test.go91
-rw-r--r--vendor/github.com/pborman/getopt/duration.go56
-rw-r--r--vendor/github.com/pborman/getopt/duration_test.go73
-rw-r--r--vendor/github.com/pborman/getopt/enum.go73
-rw-r--r--vendor/github.com/pborman/getopt/enum_test.go66
-rw-r--r--vendor/github.com/pborman/getopt/error.go93
-rw-r--r--vendor/github.com/pborman/getopt/getopt.go537
-rw-r--r--vendor/github.com/pborman/getopt/int.go67
-rw-r--r--vendor/github.com/pborman/getopt/int16.go67
-rw-r--r--vendor/github.com/pborman/getopt/int16_test.go84
-rw-r--r--vendor/github.com/pborman/getopt/int32.go67
-rw-r--r--vendor/github.com/pborman/getopt/int32_test.go84
-rw-r--r--vendor/github.com/pborman/getopt/int64.go67
-rw-r--r--vendor/github.com/pborman/getopt/int64_test.go84
-rw-r--r--vendor/github.com/pborman/getopt/int_test.go84
-rw-r--r--vendor/github.com/pborman/getopt/list.go69
-rw-r--r--vendor/github.com/pborman/getopt/list_test.go99
-rw-r--r--vendor/github.com/pborman/getopt/option.go193
-rw-r--r--vendor/github.com/pborman/getopt/set.go268
-rw-r--r--vendor/github.com/pborman/getopt/signed.go110
-rw-r--r--vendor/github.com/pborman/getopt/signed_test.go97
-rw-r--r--vendor/github.com/pborman/getopt/string.go53
-rw-r--r--vendor/github.com/pborman/getopt/string_test.go77
-rw-r--r--vendor/github.com/pborman/getopt/uint.go67
-rw-r--r--vendor/github.com/pborman/getopt/uint16.go67
-rw-r--r--vendor/github.com/pborman/getopt/uint16_test.go84
-rw-r--r--vendor/github.com/pborman/getopt/uint32.go67
-rw-r--r--vendor/github.com/pborman/getopt/uint32_test.go84
-rw-r--r--vendor/github.com/pborman/getopt/uint64.go67
-rw-r--r--vendor/github.com/pborman/getopt/uint64_test.go84
-rw-r--r--vendor/github.com/pborman/getopt/uint_test.go84
-rw-r--r--vendor/github.com/pborman/getopt/unsigned.go111
-rw-r--r--vendor/github.com/pborman/getopt/unsigned_test.go97
-rw-r--r--vendor/github.com/pborman/getopt/util_test.go87
-rw-r--r--vendor/github.com/pborman/getopt/v2/bool_test.go106
-rw-r--r--vendor/github.com/pborman/getopt/v2/breakup_test.go34
-rw-r--r--vendor/github.com/pborman/getopt/v2/counter_test.go76
-rw-r--r--vendor/github.com/pborman/getopt/v2/duration_test.go73
-rw-r--r--vendor/github.com/pborman/getopt/v2/enum_test.go79
-rw-r--r--vendor/github.com/pborman/getopt/v2/generic_test.go319
-rw-r--r--vendor/github.com/pborman/getopt/v2/int_test.go595
-rw-r--r--vendor/github.com/pborman/getopt/v2/list_test.go99
-rw-r--r--vendor/github.com/pborman/getopt/v2/signed_test.go97
-rw-r--r--vendor/github.com/pborman/getopt/v2/string_test.go77
-rw-r--r--vendor/github.com/pborman/getopt/v2/unsigned_test.go97
-rw-r--r--vendor/github.com/pborman/getopt/v2/util_test.go85
-rw-r--r--vendor/github.com/pborman/getopt/var.go63
-rw-r--r--vendor/github.com/pmezard/go-difflib/.travis.yml5
-rw-r--r--vendor/github.com/pmezard/go-difflib/README.md50
-rw-r--r--vendor/github.com/pmezard/go-difflib/difflib/difflib_test.go426
-rw-r--r--vendor/github.com/stretchr/testify/.gitignore24
-rw-r--r--vendor/github.com/stretchr/testify/.travis.yml16
-rw-r--r--vendor/github.com/stretchr/testify/README.md332
-rw-r--r--vendor/github.com/stretchr/testify/assert/assertion_forward.go.tmpl4
-rw-r--r--vendor/github.com/stretchr/testify/assert/assertions_test.go1210
-rw-r--r--vendor/github.com/stretchr/testify/assert/forward_assertions_test.go611
-rw-r--r--vendor/github.com/stretchr/testify/assert/http_assertions_test.go86
-rw-r--r--vendor/github.com/stretchr/testify/doc.go22
-rw-r--r--vendor/github.com/stretchr/testify/package_test.go12
-rw-r--r--vendor/github.com/utahta/go-openuri/openuri_test.go74
-rw-r--r--vendor/gopkg.in/go-playground/validator.v9/.gitignore29
-rw-r--r--vendor/gopkg.in/go-playground/validator.v9/README.md151
-rw-r--r--vendor/gopkg.in/go-playground/validator.v9/benchmarks_test.go1210
-rw-r--r--vendor/gopkg.in/go-playground/validator.v9/examples_test.go83
-rw-r--r--vendor/gopkg.in/go-playground/validator.v9/logo.pngbin13443 -> 0 bytes
-rw-r--r--vendor/gopkg.in/go-playground/validator.v9/validator_test.go7723
-rw-r--r--vendor/gopkg.in/yaml.v2/.travis.yml9
-rw-r--r--vendor/gopkg.in/yaml.v2/README.md133
-rw-r--r--vendor/gopkg.in/yaml.v2/decode_test.go1017
-rw-r--r--vendor/gopkg.in/yaml.v2/encode_test.go501
-rw-r--r--vendor/gopkg.in/yaml.v2/example_embedded_test.go41
-rw-r--r--vendor/gopkg.in/yaml.v2/suite_test.go12
168 files changed, 1026 insertions, 31014 deletions
diff --git a/.gitignore b/.gitignore
index e5224f2..b386588 100644
--- a/.gitignore
+++ b/.gitignore
@@ -2,5 +2,6 @@
/.lint-*
/bin
/blubber
+/blubberoid
/blubber.git
/_release
diff --git a/.pipeline/blubber.yaml b/.pipeline/blubber.yaml
index 81efaf6..ebf374d 100644
--- a/.pipeline/blubber.yaml
+++ b/.pipeline/blubber.yaml
@@ -5,7 +5,7 @@ lives:
variants:
build:
- base: golang:1.9-stretch
+ base: golang:1.10-stretch
test:
includes: [build]
runs: { insecurely: true }
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index d9214a2..e6b68b3 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -51,13 +51,13 @@ at `localhost:9999/pkg/gerrit.wikimedia.org/r/blubber`.
Dealing with Go project dependencies is kind of a moving target at the moment,
but for now we've opted to commit a minimal `vendor` directory which contains
all the required packages. It has been automatically populated by `dep
-ensure && dep prune` according to our `Gopkg.toml` and `Gopkg.lock` files.
+ensure` according to our `Gopkg.toml` and `Gopkg.lock` files.
If you're not making any changes to `Gopkg.toml`, adding, updating, or
removing dependencies, you should already be good to go.
If you do update `Gopkg.toml` to add, update, or remove a dependency, simply
-run `dep ensure && dep prune` after doing so, and commit the resulting
+run `dep ensure` after doing so, and commit the resulting
`vendor` directory changes.
## Running tests and linters
diff --git a/Gopkg.lock b/Gopkg.lock
index 65b35a4..ce4ad61 100644
--- a/Gopkg.lock
+++ b/Gopkg.lock
@@ -2,68 +2,110 @@
[[projects]]
+ digest = "1:a2c1d0e43bd3baaa071d1b9ed72c27d78169b2b269f71c105ac4ba34b1be4a39"
name = "github.com/davecgh/go-spew"
packages = ["spew"]
+ pruneopts = "NUT"
revision = "346938d642f2ec3594ed81d874461961cd0faa76"
version = "v1.1.0"
[[projects]]
+ digest = "1:3cabbabc9e0e4aa7e12b882bdc213f41cf8bd2b2ce2a7b5e0aceaf8a6a78049b"
name = "github.com/docker/distribution"
- packages = ["digest","reference"]
+ packages = [
+ "digest",
+ "reference",
+ ]
+ pruneopts = "NUT"
revision = "48294d928ced5dd9b378f7fd7c6f5da3ff3f2c89"
version = "v2.6.2"
[[projects]]
+ digest = "1:81466b4218bf6adddac2572a30ac733a9255919bc2f470b4827a317bd4ee1756"
+ name = "github.com/ghodss/yaml"
+ packages = ["."]
+ pruneopts = "NUT"
+ revision = "0ca9ea5df5451ffdf184b4428c902747c2c11cd7"
+ version = "v1.0.0"
+
+[[projects]]
+ digest = "1:672bdbde3b59017aba3b328d0ec42dc30e0ab80ff48681947596785738c00ff1"
name = "github.com/go-playground/locales"
- packages = [".","currency"]
+ packages = [
+ ".",
+ "currency",
+ ]
+ pruneopts = "NUT"
revision = "e4cbcb5d0652150d40ad0646651076b6bd2be4f6"
version = "v0.11.2"
[[projects]]
+ digest = "1:1683152827ebac377858b53a6ad0be90fb1711061c7e580c5dc719834a349162"
name = "github.com/go-playground/universal-translator"
packages = ["."]
+ pruneopts = "NUT"
revision = "b32fa301c9fe55953584134cb6853a13c87ec0a1"
version = "v0.16.0"
[[projects]]
branch = "v2"
+ digest = "1:981e58364d2283b4f5931e7a1c4a2c3c09f1336bacf2d64c63ca9356fd9a0099"
name = "github.com/pborman/getopt"
packages = ["v2"]
+ pruneopts = "NUT"
revision = "0fd4e972e7f7285fbae5863470524ece4ae99d78"
[[projects]]
+ digest = "1:0028cb19b2e4c3112225cd871870f2d9cf49b9b4276531f03438a88e94be86fe"
name = "github.com/pmezard/go-difflib"
packages = ["difflib"]
+ pruneopts = "NUT"
revision = "792786c7400a136282c1664665ae0a8db921c6c2"
version = "v1.0.0"
[[projects]]
+ digest = "1:b5c8b4a0ad5f65a85eb2a9f89e30c638ef8b99f8a3f078467cea778869757666"
name = "github.com/stretchr/testify"
packages = ["assert"]
+ pruneopts = "NUT"
revision = "69483b4bd14f5845b5a1e55bca19e954e827f1d0"
version = "v1.1.4"
[[projects]]
+ digest = "1:67eb9fdb94a67a723deaef120f1ec70cfdb1553ca6ccea38e0650d7b1747c6ac"
name = "github.com/utahta/go-openuri"
packages = ["."]
+ pruneopts = "NUT"
revision = "e3e1c475535dd7256d67286b1c8c223721aafa05"
version = "v0.1.0"
[[projects]]
+ digest = "1:e396e0963c85b8a2b437e419b55aa0169a212eb06a7c88fd2bf16e5e5cfce2f2"
name = "gopkg.in/go-playground/validator.v9"
packages = ["."]
+ pruneopts = "NUT"
revision = "1b8c8e19cd250435025214492d9a08411d760fdd"
version = "v9.12.0"
[[projects]]
branch = "v2"
+ digest = "1:c85dc78b3426641ebf2a0bbf5b731b5c4613ddb5987dbe218f7e75468dcd56f5"
name = "gopkg.in/yaml.v2"
packages = ["."]
+ pruneopts = "NUT"
revision = "eb3733d160e74a9c7e442f435eb3bea458e1d19f"
[solve-meta]
analyzer-name = "dep"
analyzer-version = 1
- inputs-digest = "8cdb40365412638a73ba10e3c82296098a85b4df74a25186aec4bd7b3a8c50e4"
+ input-imports = [
+ "github.com/docker/distribution/reference",
+ "github.com/ghodss/yaml",
+ "github.com/pborman/getopt/v2",
+ "github.com/stretchr/testify/assert",
+ "github.com/utahta/go-openuri",
+ "gopkg.in/go-playground/validator.v9",
+ "gopkg.in/yaml.v2",
+ ]
solver-name = "gps-cdcl"
solver-version = 1
diff --git a/Gopkg.toml b/Gopkg.toml
index ab06d50..137c406 100644
--- a/Gopkg.toml
+++ b/Gopkg.toml
@@ -1,5 +1,9 @@
# Refer to https://github.com/golang/dep/blob/master/docs/Gopkg.toml.md
# for detailed Gopkg.toml documentation.
+[prune]
+ non-go = true
+ go-tests = true
+ unused-packages = true
[[constraint]]
name = "github.com/docker/distribution"
@@ -24,3 +28,7 @@
[[constraint]]
branch = "v2"
name = "github.com/pborman/getopt"
+
+[[constraint]]
+ name = "github.com/ghodss/yaml"
+ version = "1.0.0"
diff --git a/cmd/blubberoid/main.go b/cmd/blubberoid/main.go
index f342a57..73b10a6 100644
--- a/cmd/blubberoid/main.go
+++ b/cmd/blubberoid/main.go
@@ -71,7 +71,7 @@ func blubberoid(res http.ResponseWriter, req *http.Request) {
return
}
- cfg, err := config.ReadConfig(body)
+ cfg, err := config.ReadYAMLConfig(body)
if err != nil {
if config.IsValidationError(err) {
diff --git a/config/apt.go b/config/apt.go
index 34a0d4a..b31239a 100644
--- a/config/apt.go
+++ b/config/apt.go
@@ -8,7 +8,7 @@ import (
// existing APT sources.
//
type AptConfig struct {
- Packages []string `yaml:"packages" validate:"dive,debianpackage"`
+ Packages []string `json:"packages" validate:"dive,debianpackage"`
}
// Merge takes another AptConfig and combines the packages declared within
diff --git a/config/apt_test.go b/config/apt_test.go
index 1bff48e..9704c67 100644
--- a/config/apt_test.go
+++ b/config/apt_test.go
@@ -11,7 +11,7 @@ import (
)
func TestAptConfigYAML(t *testing.T) {
- cfg, err := config.ReadConfig([]byte(`---
+ cfg, err := config.ReadYAMLConfig([]byte(`---
version: v3
apt:
packages:
diff --git a/config/artifacts.go b/config/artifacts.go
index 982f8ab..32cdfff 100644
--- a/config/artifacts.go
+++ b/config/artifacts.go
@@ -15,9 +15,9 @@ import (
// VariantConfig.Copies.
//
type ArtifactsConfig struct {
- From string `yaml:"from" validate:"required,variantref"` // source variant from which to copy
- Source string `yaml:"source" validate:"required"` // source variant path from which to copy
- Destination string `yaml:"destination" validate:"required"` // destination path within current variant
+ From string `json:"from" validate:"required,variantref"` // source variant from which to copy
+ Source string `json:"source" validate:"required"` // source variant path from which to copy
+ Destination string `json:"destination" validate:"required"` // destination path within current variant
}
// InstructionsForPhase injects instructions into the given build phase that
diff --git a/config/artifacts_test.go b/config/artifacts_test.go
index 44dd89c..465d5ea 100644
--- a/config/artifacts_test.go
+++ b/config/artifacts_test.go
@@ -10,7 +10,7 @@ import (
)
func TestArtifactsConfigYAML(t *testing.T) {
- cfg, err := config.ReadConfig([]byte(`---
+ cfg, err := config.ReadYAMLConfig([]byte(`---
version: v3
base: foo
variants:
@@ -79,7 +79,7 @@ func TestArtifactsConfigInstructions(t *testing.T) {
func TestArtifactsConfigValidation(t *testing.T) {
t.Run("from", func(t *testing.T) {
t.Run("ok", func(t *testing.T) {
- _, err := config.ReadConfig([]byte(`---
+ _, err := config.ReadYAMLConfig([]byte(`---
version: v3
variants:
build: {}
@@ -93,7 +93,7 @@ func TestArtifactsConfigValidation(t *testing.T) {
})
t.Run("missing", func(t *testing.T) {
- _, err := config.ReadConfig([]byte(`---
+ _, err := config.ReadYAMLConfig([]byte(`---
version: v3
variants:
build: {}
@@ -111,7 +111,7 @@ func TestArtifactsConfigValidation(t *testing.T) {
})
t.Run("bad", func(t *testing.T) {
- _, err := config.ReadConfig([]byte(`---
+ _, err := config.ReadYAMLConfig([]byte(`---
version: v3
variants:
build: {}
diff --git a/config/builder.go b/config/builder.go
index c2e95b2..0f92d24 100644
--- a/config/builder.go
+++ b/config/builder.go
@@ -8,8 +8,8 @@ import (
// build command and the files required to successfully execute the command.
//
type BuilderConfig struct {
- Command []string `yaml:"command"`
- Requirements []string `yaml:"requirements"`
+ Command []string `json:"command"`
+ Requirements []string `json:"requirements"`
}
// Merge takes another BuilderConfig and merges its fields into this one's,
diff --git a/config/builder_test.go b/config/builder_test.go
index 0785f7a..b8e95f5 100644
--- a/config/builder_test.go
+++ b/config/builder_test.go
@@ -10,7 +10,7 @@ import (
)
func TestBuilderConfigYAML(t *testing.T) {
- cfg, err := config.ReadConfig([]byte(`---
+ cfg, err := config.ReadYAMLConfig([]byte(`---
version: v3
base: foo
builder:
diff --git a/config/common.go b/config/common.go
index 90c9c5b..5421830 100644
--- a/config/common.go
+++ b/config/common.go
@@ -8,14 +8,14 @@ import (
// and each configured variant.
//
type CommonConfig struct {
- Base string `yaml:"base" validate:"omitempty,baseimage"` // name/path to base image
- Apt AptConfig `yaml:"apt"` // APT related
- Node NodeConfig `yaml:"node"` // Node related
- Python PythonConfig `yaml:"python"` // Python related
- Builder BuilderConfig `yaml:"builder"` // Builder related
- Lives LivesConfig `yaml:"lives"` // application owner/dir
- Runs RunsConfig `yaml:"runs"` // runtime environment
- EntryPoint []string `yaml:"entrypoint"` // entry-point executable
+ Base string `json:"base" validate:"omitempty,baseimage"` // name/path to base image
+ Apt AptConfig `json:"apt"` // APT related
+ Node NodeConfig `json:"node"` // Node related
+ Python PythonConfig `json:"python"` // Python related
+ Builder BuilderConfig `json:"builder"` // Builder related
+ Lives LivesConfig `json:"lives"` // application owner/dir
+ Runs RunsConfig `json:"runs"` // runtime environment
+ EntryPoint []string `json:"entrypoint"` // entry-point executable
}
// Merge takes another CommonConfig and merges its fields this one's.
diff --git a/config/common_test.go b/config/common_test.go
index d22bcff..5ea3b35 100644
--- a/config/common_test.go
+++ b/config/common_test.go
@@ -9,7 +9,7 @@ import (
)
func TestCommonConfigYAML(t *testing.T) {
- cfg, err := config.ReadConfig([]byte(`---
+ cfg, err := config.ReadYAMLConfig([]byte(`---
version: v3
base: fooimage
entrypoint: ["/bin/foo"]
diff --git a/config/config.go b/config/config.go
index 695759f..8fa6844 100644
--- a/config/config.go
+++ b/config/config.go
@@ -7,7 +7,7 @@ package config
// Config holds the root fields of a Blubber configuration.
//
type Config struct {
- CommonConfig `yaml:",inline"`
- Variants map[string]VariantConfig `yaml:"variants" validate:"variants,dive"`
- VersionConfig `yaml:",inline"`
+ CommonConfig `json:",inline"`
+ Variants map[string]VariantConfig `json:"variants" validate:"variants,dive"`
+ VersionConfig `json:",inline"`
}
diff --git a/config/config_test.go b/config/config_test.go
index 45151bc..8b6e28c 100644
--- a/config/config_test.go
+++ b/config/config_test.go
@@ -9,7 +9,7 @@ import (
)
func TestConfigYAML(t *testing.T) {
- cfg, err := config.ReadConfig([]byte(`---
+ cfg, err := config.ReadYAMLConfig([]byte(`---
version: v3
variants:
foo: {}`))
diff --git a/config/flag.go b/config/flag.go
index 6fb9e72..01fa6dd 100644
--- a/config/flag.go
+++ b/config/flag.go
@@ -1,4 +1,5 @@
package config
+import "strconv"
// Flag represents a nullable boolean value that is considered null until
// either parsed from YAML or merged in from another Flag value.
@@ -8,11 +9,13 @@ type Flag struct {
set bool
}
-// UnmarshalYAML implements yaml.Unmarshaler to parse the underlying boolean
+// UnmarshalJSON implements json.Unmarshaler to parse the underlying boolean
// value and detect that the Flag should no longer be considered null.
//
-func (flag *Flag) UnmarshalYAML(unmarshal func(interface{}) error) error {
- if err := unmarshal(&flag.True); err != nil {
+func (flag *Flag) UnmarshalJSON(unmarshal []byte) error {
+ var err error
+ flag.True, err = strconv.ParseBool(string(unmarshal))
+ if err != nil {
return err
}
diff --git a/config/flag_test.go b/config/flag_test.go
index b70174d..bb77027 100644
--- a/config/flag_test.go
+++ b/config/flag_test.go
@@ -9,7 +9,7 @@ import (
)
func TestFlagMerge(t *testing.T) {
- cfg, err := config.ReadConfig([]byte(`---
+ cfg, err := config.ReadYAMLConfig([]byte(`---
version: v3
base: foo
runs: { insecurely: true }
diff --git a/config/lives.go b/config/lives.go
index 0e45247..3be4eb5 100644
--- a/config/lives.go
+++ b/config/lives.go
@@ -13,8 +13,8 @@ const LocalLibPrefix = "/opt/lib"
// installed dependencies and application files.
//
type LivesConfig struct {
- In string `yaml:"in" validate:"omitempty,abspath"` // application directory
- UserConfig `yaml:",inline"`
+ In string `json:"in" validate:"omitempty,abspath"` // application directory
+ UserConfig `json:",inline"`
}
// Merge takes another LivesConfig and overwrites this struct's fields.
diff --git a/config/lives_test.go b/config/lives_test.go
index 2220652..db76fce 100644
--- a/config/lives_test.go
+++ b/config/lives_test.go
@@ -10,7 +10,7 @@ import (
)
func TestLivesConfigYAML(t *testing.T) {
- cfg, err := config.ReadConfig([]byte(`---
+ cfg, err := config.ReadYAMLConfig([]byte(`---
version: v3
base: foo
lives:
@@ -39,7 +39,7 @@ func TestLivesConfigYAML(t *testing.T) {
}
func TestLivesConfigDefaults(t *testing.T) {
- cfg, err := config.ReadConfig([]byte(`---
+ cfg, err := config.ReadYAMLConfig([]byte(`---
version: v3
base: foo`))
diff --git a/config/node.go b/config/node.go
index a6a22ea..d15cf89 100644
--- a/config/node.go
+++ b/config/node.go
@@ -8,8 +8,8 @@ import (
// whether/how to install NPM packages.
//
type NodeConfig struct {
- Requirements []string `yaml:"requirements"` // install requirements from given files
- Env string `yaml:"env" validate:"omitempty,nodeenv"` // environment name ("production" install)
+ Requirements []string `json:"requirements"` // install requirements from given files
+ Env string `json:"env" validate:"omitempty,nodeenv"` // environment name ("production" install)
}
// Merge takes another NodeConfig and merges its fields into this one's,
diff --git a/config/node_test.go b/config/node_test.go
index ef29ee5..9267474 100644
--- a/config/node_test.go
+++ b/config/node_test.go
@@ -10,7 +10,7 @@ import (
)
func TestNodeConfigYAML(t *testing.T) {
- cfg, err := config.ReadConfig([]byte(`---
+ cfg, err := config.ReadYAMLConfig([]byte(`---
version: v3
base: foo
node:
diff --git a/config/policy.go b/config/policy.go
index f143f1a..ade4e71 100644
--- a/config/policy.go
+++ b/config/policy.go
@@ -2,19 +2,20 @@ package config
import (
"errors"
+ "encoding/json"
"fmt"
"io/ioutil"
"reflect"
"strings"
"github.com/utahta/go-openuri"
- "gopkg.in/yaml.v2"
+ "github.com/ghodss/yaml"
)
// Policy validates a number of rules against a given configuration.
//
type Policy struct {
- Enforcements []Enforcement `yaml:"enforcements"`
+ Enforcements []Enforcement `json:"enforcements"`
}
// Validate checks the given config against all policy enforcements.
@@ -23,7 +24,7 @@ func (pol Policy) Validate(config Config) error {
validate := newValidator()
for _, enforcement := range pol.Enforcements {
- cfg, err := ResolveYAMLPath(enforcement.Path, config)
+ cfg, err := ResolveJSONPath(enforcement.Path, config)
if err != nil {
// If the path resolved nothing, there's nothing to enforce
@@ -52,16 +53,26 @@ func (pol Policy) Validate(config Config) error {
// Enforcement represents a policy rule and config path on which to apply it.
//
type Enforcement struct {
- Path string `yaml:"path"`
- Rule string `yaml:"rule"`
+ Path string `json:"path"`
+ Rule string `json:"rule"`
}
-// ReadPolicy unmarshals the given YAML bytes into a new Policy struct.
+// ReadYAMLPolicy converts YAML input to JSON and returns a new Policy struct.
+//
+func ReadYAMLPolicy(data []byte) (*Policy, error) {
+ jsonData, err := yaml.YAMLToJSON(data)
+ if err != nil {
+ return nil, err
+ }
+
+ return ReadPolicy(jsonData)
+}
+
+// ReadPolicy unmarshals the given YAML/json bytes into a new Policy struct.
//
func ReadPolicy(data []byte) (*Policy, error) {
var policy Policy
-
- err := yaml.Unmarshal(data, &policy)
+ err := json.Unmarshal(data, &policy)
if err != nil {
return nil, err
@@ -88,13 +99,13 @@ func ReadPolicyFromURI(uri string) (*Policy, error) {
return nil, err
}
- return ReadPolicy(data)
+ return ReadYAMLPolicy(data)
}
-// ResolveYAMLPath returns the config value found at the given YAML-ish
+// ResolveJSONPath returns the config value found at the given JSON-ish
// namespace/path (e.g. "variants.production.runs.as").
//
-func ResolveYAMLPath(path string, cfg interface{}) (interface{}, error) {
+func ResolveJSONPath(path string, cfg interface{}) (interface{}, error) {
parts := strings.SplitN(path, ".", 2)
name := parts[0]
@@ -107,12 +118,12 @@ func ResolveYAMLPath(path string, cfg interface{}) (interface{}, error) {
case reflect.Struct:
for i := 0; i < t.NumField(); i++ {
if t.Field(i).Anonymous {
- if subsubcfg, err := ResolveYAMLPath(path, v.Field(i).Interface()); err == nil {
+ if subsubcfg, err := ResolveJSONPath(path, v.Field(i).Interface()); err == nil {
return subsubcfg, nil
}
}
- if name == resolveYAMLTagName(t.Field(i)) {
+ if name == resolveJSONTagName(t.Field(i)) {
subcfg = v.Field(i).Interface()
break
}
@@ -134,7 +145,7 @@ func ResolveYAMLPath(path string, cfg interface{}) (interface{}, error) {
}
if len(parts) > 1 {
- return ResolveYAMLPath(parts[1], subcfg)
+ return ResolveJSONPath(parts[1], subcfg)
}
return subcfg, nil
diff --git a/config/policy_test.go b/config/policy_test.go
index 09d838c..95eb655 100644
--- a/config/policy_test.go
+++ b/config/policy_test.go
@@ -9,7 +9,7 @@ import (
)
func TestPolicyRead(t *testing.T) {
- policy, err := config.ReadPolicy([]byte(`---
+ policy, err := config.ReadYAMLPolicy([]byte(`---
enforcements:
- path: variants.production.runs.as
rule: ne=root
@@ -94,7 +94,7 @@ func TestEnforcementOnFlag(t *testing.T) {
}
-func TestResolveYAMLPath(t *testing.T) {
+func TestResolveJSONPath(t *testing.T) {
cfg := config.Config{
Variants: map[string]config.VariantConfig{
"foo": config.VariantConfig{
@@ -109,7 +109,7 @@ func TestResolveYAMLPath(t *testing.T) {
},
}
- val, err := config.ResolveYAMLPath("variants.foo.runs.as", cfg)
+ val, err := config.ResolveJSONPath("variants.foo.runs.as", cfg)
if assert.NoError(t, err) {
assert.Equal(t, "root", val)
diff --git a/config/python.go b/config/python.go
index c2927e3..9329f6e 100644
--- a/config/python.go
+++ b/config/python.go
@@ -20,8 +20,8 @@ const PythonSiteBin = PythonSitePackages + "/bin"
// dependencies via PIP.
//
type PythonConfig struct {
- Version string `yaml:"version"` // Python binary to use when installing dependencies
- Requirements []string `yaml:"requirements"` // install requirements from given files
+ Version string `json:"version"` // Python binary to use when installing dependencies
+ Requirements []string `json:"requirements"` // install requirements from given files
}
// Merge takes another PythonConfig and merges its fields into this one's,
diff --git a/config/python_test.go b/config/python_test.go
index 3ece2e5..02d6259 100644
--- a/config/python_test.go
+++ b/config/python_test.go
@@ -10,7 +10,7 @@ import (
)
func TestPythonConfigYAMLMerge(t *testing.T) {
- cfg, err := config.ReadConfig([]byte(`---
+ cfg, err := config.ReadYAMLConfig([]byte(`---
version: v3
base: foo
python:
@@ -36,7 +36,7 @@ func TestPythonConfigYAMLMerge(t *testing.T) {
}
func TestPythonConfigYAMLMergeEmpty(t *testing.T) {
- cfg, err := config.ReadConfig([]byte(`---
+ cfg, err := config.ReadYAMLConfig([]byte(`---
version: v3
base: foo
python:
@@ -58,7 +58,7 @@ func TestPythonConfigYAMLMergeEmpty(t *testing.T) {
}
func TestPythonConfigYAMLDoNotMergeNil(t *testing.T) {
- cfg, err := config.ReadConfig([]byte(`---
+ cfg, err := config.ReadYAMLConfig([]byte(`---
version: v3
base: foo
python:
diff --git a/config/reader.go b/config/reader.go
index 4386aa7..4dddfdc 100644
--- a/config/reader.go
+++ b/config/reader.go
@@ -1,26 +1,29 @@
package config
import (
+ "bytes"
"errors"
+ "encoding/json"
"fmt"
"io/ioutil"
- "gopkg.in/yaml.v2"
+ "github.com/ghodss/yaml"
)
// DefaultConfig contains YAML that is applied before the user's
// configuration.
//
-const DefaultConfig = `---
-lives:
- in: /srv/app
- as: somebody
- uid: 65533
- gid: 65533
-runs:
- as: runuser
- uid: 900
- gid: 900`
+const DefaultConfig = `{
+"lives": {
+ "in": "/srv/app",
+ "as": "somebody",
+ "uid": 65533,
+ "gid": 65533
+},
+"runs": {
+ "as": "runuser",
+ "uid": 900,
+ "gid": 900}}`
// ResolveIncludes iterates over and recurses through a given variant's
// includes to build a flat slice of variant names in the correct order by
@@ -87,6 +90,16 @@ func ExpandVariant(config *Config, name string) (*VariantConfig, error) {
return expanded, nil
}
+// ReadYAMLConfig converts YAML bytes to json and returns new Config struct.
+//
+func ReadYAMLConfig(data []byte) (*Config, error) {
+ jsonData, err := yaml.YAMLToJSON(data)
+ if err != nil {
+ return nil, err
+ }
+
+ return ReadConfig(jsonData)
+}
// ReadConfig unmarshals the given YAML bytes into a new Config struct.
//
@@ -96,8 +109,8 @@ func ReadConfig(data []byte) (*Config, error) {
config Config
)
- // Unmarshal (un-strictly) config version first for pre-validation
- err := yaml.Unmarshal(data, &version)
+ // Unmarshal config version first for pre-validation
+ err := json.Unmarshal(data, &version)
if err != nil {
return nil, err
@@ -108,10 +121,12 @@ func ReadConfig(data []byte) (*Config, error) {
}
// Unmarshal the default config
- yaml.Unmarshal([]byte(DefaultConfig), &config)
+ json.Unmarshal([]byte(DefaultConfig), &config)
- // And finally strictly unmarshal the entire user-provided config
- err = yaml.UnmarshalStrict(data, &config)
+ // And finally strictly decode the entire user-provided config
+ dec := json.NewDecoder(bytes.NewReader(data))
+ dec.DisallowUnknownFields()
+ err = dec.Decode(&config)
if err != nil {
return nil, err
@@ -132,5 +147,5 @@ func ReadConfigFile(path string) (*Config, error) {
return nil, err
}
- return ReadConfig(data)
+ return ReadYAMLConfig(data)
}
diff --git a/config/reader_test.go b/config/reader_test.go
index 1a7d529..0c1f1ed 100644
--- a/config/reader_test.go
+++ b/config/reader_test.go
@@ -10,7 +10,7 @@ import (
)
func ExampleResolveIncludes() {
- cfg, _ := config.ReadConfig([]byte(`---
+ cfg, _ := config.ReadYAMLConfig([]byte(`---
version: v3
variants:
varA: { includes: [varB, varC] }
@@ -27,8 +27,8 @@ func ExampleResolveIncludes() {
// Output: [varF varD varE varB varC varA]
}
-func TestReadConfigErrorsOnUnknownYAML(t *testing.T) {
- _, err := config.ReadConfig([]byte(`---
+func TestReadYAMLConfigErrorsOnUnknownYAML(t *testing.T) {
+ _, err := config.ReadYAMLConfig([]byte(`---
version: v3
newphone: whodis
variants:
@@ -36,13 +36,11 @@ func TestReadConfigErrorsOnUnknownYAML(t *testing.T) {
assert.EqualError(t,
err,
- "yaml: unmarshal errors:\n"+
- " line 2: field newphone not found in struct config.Config",
- )
+ `json: unknown field "newphone"`)
}
-func TestReadConfigValidateVersionBeforeStrictUnmarshal(t *testing.T) {
- _, err := config.ReadConfig([]byte(`---
+func TestReadYAMLConfigValidateVersionBeforeStrictUnmarshal(t *testing.T) {
+ _, err := config.ReadYAMLConfig([]byte(`---
version: foo
newphone: whodis
variants:
@@ -56,7 +54,7 @@ func TestReadConfigValidateVersionBeforeStrictUnmarshal(t *testing.T) {
}
func TestResolveIncludesPreventsInfiniteRecursion(t *testing.T) {
- cfg, err := config.ReadConfig([]byte(`---
+ cfg, err := config.ReadYAMLConfig([]byte(`---
version: v3
variants:
varA: { includes: [varB] }
@@ -70,7 +68,7 @@ func TestResolveIncludesPreventsInfiniteRecursion(t *testing.T) {
}
func TestMultiLevelIncludes(t *testing.T) {
- cfg, err := config.ReadConfig([]byte(`---
+ cfg, err := config.ReadYAMLConfig([]byte(`---
version: v3
base: foo-slim
variants:
@@ -102,7 +100,7 @@ func TestMultiLevelIncludes(t *testing.T) {
}
func TestMultiIncludes(t *testing.T) {
- cfg, err := config.ReadConfig([]byte(`---
+ cfg, err := config.ReadYAMLConfig([]byte(`---
version: v3
variants:
mammal:
diff --git a/config/runs.go b/config/runs.go
index 9657303..35b7efb 100644
--- a/config/runs.go
+++ b/config/runs.go
@@ -8,9 +8,9 @@ import (
// runtime environment.
//
type RunsConfig struct {
- UserConfig `yaml:",inline"`
- Insecurely Flag `yaml:"insecurely"` // runs user owns application files
- Environment map[string]string `yaml:"environment" validate:"envvars"` // environment variables
+ UserConfig `json:",inline"`
+ Insecurely Flag `json:"insecurely"` // runs user owns application files
+ Environment map[string]string `json:"environment" validate:"envvars"` // environment variables
}
// Merge takes another RunsConfig and overwrites this struct's fields. All
diff --git a/config/runs_test.go b/config/runs_test.go
index 8d685c7..74f7158 100644
--- a/config/runs_test.go
+++ b/config/runs_test.go
@@ -10,7 +10,7 @@ import (
)
func TestRunsConfigYAML(t *testing.T) {
- cfg, err := config.ReadConfig([]byte(`---
+ cfg, err := config.ReadYAMLConfig([]byte(`---
version: v3
base: foo
runs:
diff --git a/config/user.go b/config/user.go
index f42fbf7..b43161a 100644
--- a/config/user.go
+++ b/config/user.go
@@ -3,9 +3,9 @@ package config
// UserConfig holds configuration fields related to a user account.
//
type UserConfig struct {
- As string `yaml:"as" validate:"omitempty,username"` // user name
- UID uint `yaml:"uid"` // user ID
- GID uint `yaml:"gid"` // group ID
+ As string `json:"as" validate:"omitempty,username"` // user name
+ UID uint `json:"uid"` // user ID
+ GID uint `json:"gid"` // group ID
}
// Merge takes another UserConfig and overwrites this struct's fields.
diff --git a/config/validation.go b/config/validation.go
index 2529e00..26c447e 100644
--- a/config/validation.go
+++ b/config/validation.go
@@ -71,7 +71,7 @@ const rootCfgCtx ctxKey = iota
func newValidator() *validator.Validate {
validate := validator.New()
- validate.RegisterTagNameFunc(resolveYAMLTagName)
+ validate.RegisterTagNameFunc(resolveJSONTagName)
for name, tags := range validatorAliases {
validate.RegisterAlias(name, tags)
@@ -207,6 +207,6 @@ func isVariantReference(ctx context.Context, fl validator.FieldLevel) bool {
return false
}
-func resolveYAMLTagName(field reflect.StructField) string {
- return strings.SplitN(field.Tag.Get("yaml"), ",", 2)[0]
+func resolveJSONTagName(field reflect.StructField) string {
+ return strings.SplitN(field.Tag.Get("json"), ",", 2)[0]
}
diff --git a/config/variant.go b/config/variant.go
index cc4d802..8d6b7bc 100644
--- a/config/variant.go
+++ b/config/variant.go
@@ -7,10 +7,10 @@ import (
// VariantConfig holds configuration fields for each defined build variant.
//
type VariantConfig struct {
- Includes []string `yaml:"includes" validate:"dive,variantref"` // other variants
- Copies string `yaml:"copies" validate:"omitempty,variantref"` // copy artifacts from variant
- Artifacts []ArtifactsConfig `yaml:"artifacts" validate:"dive"` // artifact configuration
- CommonConfig `yaml:",inline"`
+ Includes []string `json:"includes" validate:"dive,variantref"` // other variants
+ Copies string `json:"copies" validate:"omitempty,variantref"` // copy artifacts from variant
+ Artifacts []ArtifactsConfig `json:"artifacts" validate:"dive"` // artifact configuration
+ CommonConfig `json:",inline"`
}
// Merge takes another VariantConfig and overwrites this struct's fields.
diff --git a/config/variant_test.go b/config/variant_test.go
index b073654..9916185 100644
--- a/config/variant_test.go
+++ b/config/variant_test.go
@@ -11,7 +11,7 @@ import (
)
func TestVariantConfigYAML(t *testing.T) {
- cfg, err := config.ReadConfig([]byte(`---
+ cfg, err := config.ReadYAMLConfig([]byte(`---
version: v3
base: foo
variants:
@@ -202,7 +202,7 @@ func TestVariantConfigInstructions(t *testing.T) {
func TestVariantConfigValidation(t *testing.T) {
t.Run("includes", func(t *testing.T) {
t.Run("ok", func(t *testing.T) {
- _, err := config.ReadConfig([]byte(`---
+ _, err := config.ReadYAMLConfig([]byte(`---
version: v3
variants:
build: {}
@@ -212,7 +212,7 @@ func TestVariantConfigValidation(t *testing.T) {
})
t.Run("optional", func(t *testing.T) {
- _, err := config.ReadConfig([]byte(`---
+ _, err := config.ReadYAMLConfig([]byte(`---
version: v3
variants:
build: {}
@@ -222,7 +222,7 @@ func TestVariantConfigValidation(t *testing.T) {
})
t.Run("bad", func(t *testing.T) {
- _, err := config.ReadConfig([]byte(`---
+ _, err := config.ReadYAMLConfig([]byte(`---
version: v3
variants:
build: {}
@@ -242,7 +242,7 @@ func TestVariantConfigValidation(t *testing.T) {
t.Run("copies", func(t *testing.T) {
t.Run("ok", func(t *testing.T) {
- _, err := config.ReadConfig([]byte(`---
+ _, err := config.ReadYAMLConfig([]byte(`---
version: v3
variants:
build: {}
@@ -252,7 +252,7 @@ func TestVariantConfigValidation(t *testing.T) {
})
t.Run("optional", func(t *testing.T) {
- _, err := config.ReadConfig([]byte(`---
+ _, err := config.ReadYAMLConfig([]byte(`---
version: v3
variants:
build: {}
@@ -262,7 +262,7 @@ func TestVariantConfigValidation(t *testing.T) {
})
t.Run("bad", func(t *testing.T) {
- _, err := config.ReadConfig([]byte(`---
+ _, err := config.ReadYAMLConfig([]byte(`---
version: v3
variants:
build: {}
diff --git a/config/version.go b/config/version.go
index 0a41fca..b0e3589 100644
--- a/config/version.go
+++ b/config/version.go
@@ -8,5 +8,5 @@ const CurrentVersion string = "v3"
// config version independent from an entire Config struct.
//
type VersionConfig struct {
- Version string `yaml:"version" validate:"required,currentversion"`
+ Version string `json:"version" validate:"required,currentversion"`
}
diff --git a/config/version_test.go b/config/version_test.go
index 3b25d5e..bf2b0fc 100644
--- a/config/version_test.go
+++ b/config/version_test.go
@@ -9,7 +9,7 @@ import (
)
func TestVersionConfigYAML(t *testing.T) {
- cfg, err := config.ReadConfig([]byte(`---
+ cfg, err := config.ReadYAMLConfig([]byte(`---
version: v3
variants:
foo: {}`))
diff --git a/docker/compiler_test.go b/docker/compiler_test.go
index 6d7f4f2..0a12c69 100644
--- a/docker/compiler_test.go
+++ b/docker/compiler_test.go
@@ -12,7 +12,7 @@ import (
)
func TestSingleStageHasNoName(t *testing.T) {
- cfg, err := config.ReadConfig([]byte(`---
+ cfg, err := config.ReadYAMLConfig([]byte(`---
version: v3
base: foo/bar
variants:
@@ -27,7 +27,7 @@ func TestSingleStageHasNoName(t *testing.T) {
}
func TestMultiStageIncludesStageNames(t *testing.T) {
- cfg, err := config.ReadConfig([]byte(`---
+ cfg, err := config.ReadYAMLConfig([]byte(`---
version: v3
base: foo/bar
variants:
@@ -51,7 +51,7 @@ func TestMultiStageIncludesStageNames(t *testing.T) {
}
func TestMultipleArtifactsFromSameStage(t *testing.T) {
- cfg, err := config.ReadConfig([]byte(`---
+ cfg, err := config.ReadYAMLConfig([]byte(`---
version: v3
base: foo/bar
variants:
@@ -78,7 +78,7 @@ func TestMultipleArtifactsFromSameStage(t *testing.T) {
}
func TestMetaDataLabels(t *testing.T) {
- cfg, err := config.ReadConfig([]byte(`---
+ cfg, err := config.ReadYAMLConfig([]byte(`---
version: v3
base: foo/bar
variants:
diff --git a/vendor/github.com/davecgh/go-spew/.gitignore b/vendor/github.com/davecgh/go-spew/.gitignore
deleted file mode 100644
index 0026861..0000000
--- a/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/vendor/github.com/davecgh/go-spew/.travis.yml b/vendor/github.com/davecgh/go-spew/.travis.yml
deleted file mode 100644
index 984e073..0000000
--- a/vendor/github.com/davecgh/go-spew/.travis.yml
+++ /dev/null
@@ -1,14 +0,0 @@
-language: go
-go:
- - 1.5.4
- - 1.6.3
- - 1.7
-install:
- - go get -v golang.org/x/tools/cmd/cover
-script:
- - go test -v -tags=safe ./spew
- - go test -v -tags=testcgo ./spew -covermode=count -coverprofile=profile.cov
-after_success:
- - go get -v github.com/mattn/goveralls
- - export PATH=$PATH:$HOME/gopath/bin
- - goveralls -coverprofile=profile.cov -service=travis-ci
diff --git a/vendor/github.com/davecgh/go-spew/README.md b/vendor/github.com/davecgh/go-spew/README.md
deleted file mode 100644
index 2624304..0000000
--- a/vendor/github.com/davecgh/go-spew/README.md
+++ /dev/null
@@ -1,205 +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, "<!--\n" + html.EscapeString(spew.Sdump(w)) + "\n-->")
-}
-
-func main() {
- http.HandleFunc("/", handler)
- http.ListenAndServe(":8080", nil)
-}
-```
-
-## Sample Dump Output
-
-```
-(main.Foo) {
- unexportedField: (*main.Bar)(0xf84002e210)({
- flag: (main.Flag) flagTwo,
- data: (uintptr) <nil>
- }),
- 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 <*><shown>}
- %+v: <*>(0xf84003e260){ui8:1 c:<*>(0xf84003e260)<shown>}
- %#v: (*main.circular){ui8:(uint8)1 c:(*main.circular)<shown>}
- %#+v: (*main.circular)(0xf84003e260){ui8:(uint8)1 c:(*main.circular)(0xf84003e260)<shown>}
-```
-
-## 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/vendor/github.com/davecgh/go-spew/cov_report.sh b/vendor/github.com/davecgh/go-spew/cov_report.sh
deleted file mode 100644
index 9579497..0000000
--- a/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/vendor/github.com/davecgh/go-spew/spew/common_test.go b/vendor/github.com/davecgh/go-spew/spew/common_test.go
deleted file mode 100644
index 0f5ce47..0000000
--- a/vendor/github.com/davecgh/go-spew/spew/common_test.go
+++ /dev/null
@@ -1,298 +0,0 @@
-/*
- * Copyright (c) 2013-2016 Dave Collins <dave@davec.name>
- *
- * 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/vendor/github.com/davecgh/go-spew/spew/dump_test.go b/vendor/github.com/davecgh/go-spew/spew/dump_test.go
deleted file mode 100644
index 5aad9c7..0000000
--- a/vendor/github.com/davecgh/go-spew/spew/dump_test.go
+++ /dev/null
@@ -1,1042 +0,0 @@
-/*
- * Copyright (c) 2013-2016 Dave Collins <dave@davec.name>
- *
- * 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+")(<nil>)\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+")(<nil>)\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+")(<nil>)\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+")(<nil>)\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+")(<nil>)\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+")(<nil>)\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+")(<nil>)\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+")(<nil>)\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+")(<nil>)\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+")(<nil>)\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+")(<nil>)\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+")(<nil>)\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+")(<nil>)\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+")(<nil>)\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+")(<nil>)\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+")(<nil>)\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+")(<nil>)\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+")(<nil>)\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+")(<nil>)\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+")(<nil>)\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+")(<nil>)\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 + ") <nil>\n}"
- addDumpTest(v3, "("+v3t+") "+v3s+"\n")
- addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s+")\n")
- addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s+")\n")
- addDumpTest(nv3, "(*"+v3t+")(<nil>)\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+")(<nil>)\n")
-
- // Nil slice.
- v5 := []int(nil)
- nv5 := (*[]int)(nil)
- pv5 := &v5
- v5Addr := fmt.Sprintf("%p", pv5)
- pv5Addr := fmt.Sprintf("%p", &pv5)
- v5t := "[]int"
- v5s := "<nil>"
- addDumpTest(v5, "("+v5t+") "+v5s+"\n")
- addDumpTest(pv5, "(*"+v5t+")("+v5Addr+")("+v5s+")\n")
- addDumpTest(&pv5, "(**"+v5t+")("+pv5Addr+"->"+v5Addr+")("+v5s+")\n")
- addDumpTest(nv5, "(*"+v5t+")(<nil>)\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+")(<nil>)\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 := "<nil>"
- addDumpTest(v, "("+vt+") "+vs+"\n")
- addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n")
- addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n")
- addDumpTest(nv, "(*"+vt+")(<nil>)\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+")(<nil>)\n")
- addDumpTest(nilMap, "("+mt+") <nil>\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+")(<nil>)\n")
- addDumpTest(nilMap2, "("+m2t+") <nil>\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+")(<nil>)\n")
- addDumpTest(nilMap3, "("+m3t+") <nil>\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 + ") <nil>\n}"
- addDumpTest(m4, "("+m4t+") "+m4s+"\n")
- addDumpTest(pm4, "(*"+m4t+")("+m4Addr+")("+m4s+")\n")
- addDumpTest(&pm4, "(**"+m4t+")("+pm4Addr+"->"+m4Addr+")("+m4s+")\n")
- addDumpTest(nm4, "(*"+m4t+")(<nil>)\n")
- addDumpTest(nilMap4, "("+m4t+") <nil>\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+")(<nil>)\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+")(<nil>)\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+")(<nil>)\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+")(<nil>)\n")
-}
-
-func addUintptrDumpTests() {
- // Null pointer.
- v := uintptr(0)
- pv := &v
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "uintptr"
- vs := "<nil>"
- 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+")(<nil>)\n")
-}
-
-func addUnsafePointerDumpTests() {
- // Null pointer.
- v := unsafe.Pointer(uintptr(0))
- nv := (*unsafe.Pointer)(nil)
- pv := &v
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "unsafe.Pointer"
- vs := "<nil>"
- addDumpTest(v, "("+vt+") "+vs+"\n")
- addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n")
- addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n")
- addDumpTest(nv, "(*"+vt+")(<nil>)\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+")(<nil>)\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 := "<nil>"
- addDumpTest(v, "("+vt+") "+vs+"\n")
- addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n")
- addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n")
- addDumpTest(nv, "(*"+vt+")(<nil>)\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+")(<nil>)\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+")(<nil>)\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+")(<nil>)\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 + ")(<already shown>)\n })\n}"
- vs2 := "{\n c: (*" + vt + ")(" + vAddr + ")(<already shown>)\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 +
- ")(<already shown>)\n })\n })\n}"
- v2s2 := "{\n ps2: (*" + v2t2 + ")(" + ts2Addr + ")({\n ps1: (*" + v2t +
- ")(" + v2Addr + ")(<already shown>)\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 +
- ")(<already shown>)\n })\n })\n })\n}"
- v3s2 := "{\n ps2: (*" + v3t2 + ")(" + tic2Addr + ")({\n ps3: (*" + v3t3 +
- ")(" + tic3Addr + ")({\n ps1: (*" + v3t + ")(" + v3Addr +
- ")(<already shown>)\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+")(<nil>)\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+")(<nil>)\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/vendor/github.com/davecgh/go-spew/spew/dumpcgo_test.go b/vendor/github.com/davecgh/go-spew/spew/dumpcgo_test.go
deleted file mode 100644
index 6ab1808..0000000
--- a/vendor/github.com/davecgh/go-spew/spew/dumpcgo_test.go
+++ /dev/null
@@ -1,99 +0,0 @@
-// Copyright (c) 2013-2016 Dave Collins <dave@davec.name>
-//
-// 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+")(<nil>)\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"
- v5s := "(len=" + v5Len + " cap=" + v5Cap + ") " +
- "{\n 00000000 74 65 73 74 35 00 " +
- " |test5.|\n}"
- addDumpTest(v5, "("+v5t+") "+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"
- v6s := "(len=" + v6Len + " cap=" + v6Cap + ") " +
- "{\n 00000000 74 65 73 74 36 00 " +
- " |test6.|\n}"
- addDumpTest(v6, "("+v6t+") "+v6s+"\n")
-}
diff --git a/vendor/github.com/davecgh/go-spew/spew/dumpnocgo_test.go b/vendor/github.com/davecgh/go-spew/spew/dumpnocgo_test.go
deleted file mode 100644
index 52a0971..0000000
--- a/vendor/github.com/davecgh/go-spew/spew/dumpnocgo_test.go
+++ /dev/null
@@ -1,26 +0,0 @@
-// Copyright (c) 2013 Dave Collins <dave@davec.name>
-//
-// 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/vendor/github.com/davecgh/go-spew/spew/example_test.go b/vendor/github.com/davecgh/go-spew/spew/example_test.go
deleted file mode 100644
index c6ec8c6..0000000
--- a/vendor/github.com/davecgh/go-spew/spew/example_test.go
+++ /dev/null
@@ -1,226 +0,0 @@
-/*
- * Copyright (c) 2013-2016 Dave Collins <dave@davec.name>
- *
- * 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) <nil>
- // },
- // 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 <*><shown>}}
-}
-
-// 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) <nil>
- // },
- // ExportedField: (map[interface {}]interface {}) (len=1) {
- // (string) (len=3) "one": (bool) true
- // }
- // }
- // (spew_test.Foo) {
- // unexportedField: (spew_test.Bar) {
- // data: (uintptr) <nil>
- // },
- // 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/vendor/github.com/davecgh/go-spew/spew/format_test.go b/vendor/github.com/davecgh/go-spew/spew/format_test.go
deleted file mode 100644
index f9b93ab..0000000
--- a/vendor/github.com/davecgh/go-spew/spew/format_test.go
+++ /dev/null
@@ -1,1558 +0,0 @@
-/*
- * Copyright (c) 2013-2016 Dave Collins <dave@davec.name>
- *
- * 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, "<nil>")
- addFormatterTest("%+v", v, vs)
- addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs)
- addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%+v", nv, "<nil>")
- addFormatterTest("%#v", v, "("+vt+")"+vs)
- addFormatterTest("%#v", pv, "(*"+vt+")"+vs)
- addFormatterTest("%#v", &pv, "(**"+vt+")"+vs)
- addFormatterTest("%#v", nv, "(*"+vt+")"+"<nil>")
- addFormatterTest("%#+v", v, "("+vt+")"+vs)
- addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs)
- addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%#+v", nv, "(*"+vt+")"+"<nil>")
-
- // 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, "<nil>")
- addFormatterTest("%+v", v2, v2s)
- addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s)
- addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s)
- addFormatterTest("%+v", nv2, "<nil>")
- addFormatterTest("%#v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s)
- addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s)
- addFormatterTest("%#v", nv2, "(*"+v2t+")"+"<nil>")
- addFormatterTest("%#+v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s)
- addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s)
- addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"<nil>")
-
- // 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, "<nil>")
- addFormatterTest("%+v", v3, v3s)
- addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s)
- addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s)
- addFormatterTest("%+v", nv3, "<nil>")
- addFormatterTest("%#v", v3, "("+v3t+")"+v3s)
- addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s)
- addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s)
- addFormatterTest("%#v", nv3, "(*"+v3t+")"+"<nil>")
- addFormatterTest("%#+v", v3, "("+v3t+")"+v3s)
- addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s)
- addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s)
- addFormatterTest("%#v", nv3, "(*"+v3t+")"+"<nil>")
-
- // 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, "<nil>")
- addFormatterTest("%+v", v4, v4s)
- addFormatterTest("%+v", pv4, "<*>("+v4Addr+")"+v4s)
- addFormatterTest("%+v", &pv4, "<**>("+pv4Addr+"->"+v4Addr+")"+v4s)
- addFormatterTest("%+v", nv4, "<nil>")
- addFormatterTest("%#v", v4, "("+v4t+")"+v4s)
- addFormatterTest("%#v", pv4, "(*"+v4t+")"+v4s)
- addFormatterTest("%#v", &pv4, "(**"+v4t+")"+v4s)
- addFormatterTest("%#v", nv4, "(*"+v4t+")"+"<nil>")
- addFormatterTest("%#+v", v4, "("+v4t+")"+v4s)
- addFormatterTest("%#+v", pv4, "(*"+v4t+")("+v4Addr+")"+v4s)
- addFormatterTest("%#+v", &pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")"+v4s)
- addFormatterTest("%#+v", nv4, "(*"+v4t+")"+"<nil>")
-
- // 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, "<nil>")
- addFormatterTest("%+v", v5, v5s)
- addFormatterTest("%+v", pv5, "<*>("+v5Addr+")"+v5s)
- addFormatterTest("%+v", &pv5, "<**>("+pv5Addr+"->"+v5Addr+")"+v5s)
- addFormatterTest("%+v", nv5, "<nil>")
- addFormatterTest("%#v", v5, "("+v5t+")"+v5s)
- addFormatterTest("%#v", pv5, "(*"+v5t+")"+v5s)
- addFormatterTest("%#v", &pv5, "(**"+v5t+")"+v5s)
- addFormatterTest("%#v", nv5, "(*"+v5t+")"+"<nil>")
- addFormatterTest("%#+v", v5, "("+v5t+")"+v5s)
- addFormatterTest("%#+v", pv5, "(*"+v5t+")("+v5Addr+")"+v5s)
- addFormatterTest("%#+v", &pv5, "(**"+v5t+")("+pv5Addr+"->"+v5Addr+")"+v5s)
- addFormatterTest("%#+v", nv5, "(*"+v5t+")"+"<nil>")
-}
-
-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, "<nil>")
- addFormatterTest("%+v", v, vs)
- addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs)
- addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%+v", nv, "<nil>")
- addFormatterTest("%#v", v, "("+vt+")"+vs)
- addFormatterTest("%#v", pv, "(*"+vt+")"+vs)
- addFormatterTest("%#v", &pv, "(**"+vt+")"+vs)
- addFormatterTest("%#v", nv, "(*"+vt+")"+"<nil>")
- addFormatterTest("%#+v", v, "("+vt+")"+vs)
- addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs)
- addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%#+v", nv, "(*"+vt+")"+"<nil>")
-
- // 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, "<nil>")
- addFormatterTest("%+v", v2, v2s)
- addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s)
- addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s)
- addFormatterTest("%+v", nv2, "<nil>")
- addFormatterTest("%#v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s)
- addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s)
- addFormatterTest("%#v", nv2, "(*"+v2t+")"+"<nil>")
- addFormatterTest("%#+v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s)
- addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s)
- addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"<nil>")
-
- // 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, "<nil>")
- addFormatterTest("%+v", v3, v3s)
- addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s)
- addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s)
- addFormatterTest("%+v", nv3, "<nil>")
- addFormatterTest("%#v", v3, "("+v3t+")"+v3s)
- addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s)
- addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s)
- addFormatterTest("%#v", nv3, "(*"+v3t+")"+"<nil>")
- addFormatterTest("%#+v", v3, "("+v3t+")"+v3s)
- addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s)
- addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s)
- addFormatterTest("%#v", nv3, "(*"+v3t+")"+"<nil>")
-
- // 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, "<nil>")
- addFormatterTest("%+v", v4, v4s)
- addFormatterTest("%+v", pv4, "<*>("+v4Addr+")"+v4s)
- addFormatterTest("%+v", &pv4, "<**>("+pv4Addr+"->"+v4Addr+")"+v4s)
- addFormatterTest("%+v", nv4, "<nil>")
- addFormatterTest("%#v", v4, "("+v4t+")"+v4s)
- addFormatterTest("%#v", pv4, "(*"+v4t+")"+v4s)
- addFormatterTest("%#v", &pv4, "(**"+v4t+")"+v4s)
- addFormatterTest("%#v", nv4, "(*"+v4t+")"+"<nil>")
- addFormatterTest("%#+v", v4, "("+v4t+")"+v4s)
- addFormatterTest("%#+v", pv4, "(*"+v4t+")("+v4Addr+")"+v4s)
- addFormatterTest("%#+v", &pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")"+v4s)
- addFormatterTest("%#+v", nv4, "(*"+v4t+")"+"<nil>")
-
- // 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, "<nil>")
- addFormatterTest("%+v", v5, v5s)
- addFormatterTest("%+v", pv5, "<*>("+v5Addr+")"+v5s)
- addFormatterTest("%+v", &pv5, "<**>("+pv5Addr+"->"+v5Addr+")"+v5s)
- addFormatterTest("%+v", nv5, "<nil>")
- addFormatterTest("%#v", v5, "("+v5t+")"+v5s)
- addFormatterTest("%#v", pv5, "(*"+v5t+")"+v5s)
- addFormatterTest("%#v", &pv5, "(**"+v5t+")"+v5s)
- addFormatterTest("%#v", nv5, "(*"+v5t+")"+"<nil>")
- addFormatterTest("%#+v", v5, "("+v5t+")"+v5s)
- addFormatterTest("%#+v", pv5, "(*"+v5t+")("+v5Addr+")"+v5s)
- addFormatterTest("%#+v", &pv5, "(**"+v5t+")("+pv5Addr+"->"+v5Addr+")"+v5s)
- addFormatterTest("%#v", nv5, "(*"+v5t+")"+"<nil>")
-}
-
-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, "<nil>")
- addFormatterTest("%+v", v, vs)
- addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs)
- addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%+v", nv, "<nil>")
- addFormatterTest("%#v", v, "("+vt+")"+vs)
- addFormatterTest("%#v", pv, "(*"+vt+")"+vs)
- addFormatterTest("%#v", &pv, "(**"+vt+")"+vs)
- addFormatterTest("%#v", nv, "(*"+vt+")"+"<nil>")
- addFormatterTest("%#+v", v, "("+vt+")"+vs)
- addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs)
- addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%#+v", nv, "(*"+vt+")"+"<nil>")
-
- // 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, "<nil>")
- addFormatterTest("%+v", v, vs)
- addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs)
- addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%+v", nv, "<nil>")
- addFormatterTest("%#v", v, "("+vt+")"+vs)
- addFormatterTest("%#v", pv, "(*"+vt+")"+vs)
- addFormatterTest("%#v", &pv, "(**"+vt+")"+vs)
- addFormatterTest("%#v", nv, "(*"+vt+")"+"<nil>")
- addFormatterTest("%#+v", v, "("+vt+")"+vs)
- addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs)
- addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%#+v", nv, "(*"+vt+")"+"<nil>")
-
- // 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, "<nil>")
- addFormatterTest("%+v", v2, v2s)
- addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s)
- addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s)
- addFormatterTest("%+v", nv2, "<nil>")
- addFormatterTest("%#v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s)
- addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s)
- addFormatterTest("%#v", nv2, "(*"+v2t+")"+"<nil>")
- addFormatterTest("%#+v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s)
- addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s)
- addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"<nil>")
-}
-
-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, "<nil>")
- addFormatterTest("%+v", v, vs)
- addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs)
- addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%+v", nv, "<nil>")
- addFormatterTest("%#v", v, "("+vt+")"+vs)
- addFormatterTest("%#v", pv, "(*"+vt+")"+vs)
- addFormatterTest("%#v", &pv, "(**"+vt+")"+vs)
- addFormatterTest("%#v", nv, "(*"+vt+")"+"<nil>")
- addFormatterTest("%#+v", v, "("+vt+")"+vs)
- addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs)
- addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%#+v", nv, "(*"+vt+")"+"<nil>")
-
- // 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, "<nil>")
- addFormatterTest("%+v", v2, v2s)
- addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s)
- addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s)
- addFormatterTest("%+v", nv2, "<nil>")
- addFormatterTest("%#v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s)
- addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s)
- addFormatterTest("%#v", nv2, "(*"+v2t+")"+"<nil>")
- addFormatterTest("%#+v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s)
- addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s)
- addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"<nil>")
-}
-
-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, "<nil>")
- addFormatterTest("%+v", v, vs)
- addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs)
- addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%+v", nv, "<nil>")
- addFormatterTest("%#v", v, "("+vt+")"+vs)
- addFormatterTest("%#v", pv, "(*"+vt+")"+vs)
- addFormatterTest("%#v", &pv, "(**"+vt+")"+vs)
- addFormatterTest("%#v", nv, "(*"+vt+")"+"<nil>")
- addFormatterTest("%#+v", v, "("+vt+")"+vs)
- addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs)
- addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%#+v", nv, "(*"+vt+")"+"<nil>")
-
- // 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, "<nil>")
- addFormatterTest("%+v", v2, v2s)
- addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2sp)
- addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2sp)
- addFormatterTest("%+v", nv2, "<nil>")
- addFormatterTest("%#v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2sp)
- addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2sp)
- addFormatterTest("%#v", nv2, "(*"+v2t+")"+"<nil>")
- addFormatterTest("%#+v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2sp)
- addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2sp)
- addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"<nil>")
-
- // 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, "<nil>")
- addFormatterTest("%+v", v3, v3s)
- addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s)
- addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s)
- addFormatterTest("%+v", nv3, "<nil>")
- addFormatterTest("%#v", v3, "("+v3t+")"+v3s2)
- addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s2)
- addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s2)
- addFormatterTest("%#v", nv3, "(*"+v3t+")"+"<nil>")
- addFormatterTest("%#+v", v3, "("+v3t+")"+v3s2)
- addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s2)
- addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s2)
- addFormatterTest("%#+v", nv3, "(*"+v3t+")"+"<nil>")
-}
-
-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, "<nil>")
- addFormatterTest("%+v", v, vs)
- addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs)
- addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%+v", nv, "<nil>")
- addFormatterTest("%#v", v, "("+vt+")"+vs)
- addFormatterTest("%#v", pv, "(*"+vt+")"+vs)
- addFormatterTest("%#v", &pv, "(**"+vt+")"+vs)
- addFormatterTest("%#v", nv, "(*"+vt+")"+"<nil>")
- addFormatterTest("%#+v", v, "("+vt+")"+vs)
- addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs)
- addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%#+v", nv, "(*"+vt+")"+"<nil>")
-
- // 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, "<nil>")
- addFormatterTest("%+v", v2, v2s)
- addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s)
- addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s)
- addFormatterTest("%+v", nv2, "<nil>")
- addFormatterTest("%#v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s)
- addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s)
- addFormatterTest("%#v", nv2, "(*"+v2t+")"+"<nil>")
- addFormatterTest("%#+v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s)
- addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s)
- addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"<nil>")
-
- // 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 <nil>]"
- v3s2 := "[(" + v3t2 + ")one (" + v3t3 + ")2 (" + v3t4 + ")3 (" + v3t5 +
- ")<nil>]"
- addFormatterTest("%v", v3, v3s)
- addFormatterTest("%v", pv3, "<*>"+v3s)
- addFormatterTest("%v", &pv3, "<**>"+v3s)
- addFormatterTest("%+v", nv3, "<nil>")
- addFormatterTest("%+v", v3, v3s)
- addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s)
- addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s)
- addFormatterTest("%+v", nv3, "<nil>")
- addFormatterTest("%#v", v3, "("+v3t+")"+v3s2)
- addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s2)
- addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s2)
- addFormatterTest("%#v", nv3, "(*"+v3t+")"+"<nil>")
- addFormatterTest("%#+v", v3, "("+v3t+")"+v3s2)
- addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s2)
- addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s2)
- addFormatterTest("%#+v", nv3, "(*"+v3t+")"+"<nil>")
-
- // Nil slice.
- var v4 []int
- nv4 := (*[]int)(nil)
- pv4 := &v4
- v4Addr := fmt.Sprintf("%p", pv4)
- pv4Addr := fmt.Sprintf("%p", &pv4)
- v4t := "[]int"
- v4s := "<nil>"
- addFormatterTest("%v", v4, v4s)
- addFormatterTest("%v", pv4, "<*>"+v4s)
- addFormatterTest("%v", &pv4, "<**>"+v4s)
- addFormatterTest("%+v", nv4, "<nil>")
- addFormatterTest("%+v", v4, v4s)
- addFormatterTest("%+v", pv4, "<*>("+v4Addr+")"+v4s)
- addFormatterTest("%+v", &pv4, "<**>("+pv4Addr+"->"+v4Addr+")"+v4s)
- addFormatterTest("%+v", nv4, "<nil>")
- addFormatterTest("%#v", v4, "("+v4t+")"+v4s)
- addFormatterTest("%#v", pv4, "(*"+v4t+")"+v4s)
- addFormatterTest("%#v", &pv4, "(**"+v4t+")"+v4s)
- addFormatterTest("%#v", nv4, "(*"+v4t+")"+"<nil>")
- addFormatterTest("%#+v", v4, "("+v4t+")"+v4s)
- addFormatterTest("%#+v", pv4, "(*"+v4t+")("+v4Addr+")"+v4s)
- addFormatterTest("%#+v", &pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")"+v4s)
- addFormatterTest("%#+v", nv4, "(*"+v4t+")"+"<nil>")
-}
-
-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, "<nil>")
- addFormatterTest("%+v", v, vs)
- addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs)
- addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%+v", nv, "<nil>")
- addFormatterTest("%#v", v, "("+vt+")"+vs)
- addFormatterTest("%#v", pv, "(*"+vt+")"+vs)
- addFormatterTest("%#v", &pv, "(**"+vt+")"+vs)
- addFormatterTest("%#v", nv, "(*"+vt+")"+"<nil>")
- addFormatterTest("%#+v", v, "("+vt+")"+vs)
- addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs)
- addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%#+v", nv, "(*"+vt+")"+"<nil>")
-}
-
-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 := "<nil>"
- addFormatterTest("%v", v, vs)
- addFormatterTest("%v", pv, "<*>"+vs)
- addFormatterTest("%v", &pv, "<**>"+vs)
- addFormatterTest("%+v", nv, "<nil>")
- addFormatterTest("%+v", v, vs)
- addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs)
- addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%+v", nv, "<nil>")
- addFormatterTest("%#v", v, "("+vt+")"+vs)
- addFormatterTest("%#v", pv, "(*"+vt+")"+vs)
- addFormatterTest("%#v", &pv, "(**"+vt+")"+vs)
- addFormatterTest("%#v", nv, "(*"+vt+")"+"<nil>")
- addFormatterTest("%#+v", v, "("+vt+")"+vs)
- addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs)
- addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%#+v", nv, "(*"+vt+")"+"<nil>")
-
- // 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, "<nil>")
- addFormatterTest("%+v", nv, "<nil>")
- addFormatterTest("%+v", v, vs, vs2)
- addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs, "<*>("+vAddr+")"+vs2)
- addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs,
- "<**>("+pvAddr+"->"+vAddr+")"+vs2)
- addFormatterTest("%+v", nilMap, "<nil>")
- addFormatterTest("%+v", nv, "<nil>")
- 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+")"+"<nil>")
- addFormatterTest("%#v", nv, "(*"+vt+")"+"<nil>")
- 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+")"+"<nil>")
- addFormatterTest("%#+v", nv, "(*"+vt+")"+"<nil>")
-
- // 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, "<nil>")
- addFormatterTest("%+v", v2, v2s)
- addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s)
- addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s)
- addFormatterTest("%+v", nv2, "<nil>")
- addFormatterTest("%#v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s)
- addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s)
- addFormatterTest("%#v", nv2, "(*"+v2t+")"+"<nil>")
- addFormatterTest("%#+v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s)
- addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s)
- addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"<nil>")
-
- // 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, "<nil>")
- addFormatterTest("%+v", v3, v3s)
- addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s)
- addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s)
- addFormatterTest("%+v", nv3, "<nil>")
- addFormatterTest("%#v", v3, "("+v3t+")"+v3s2)
- addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s2)
- addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s2)
- addFormatterTest("%#v", nv3, "(*"+v3t+")"+"<nil>")
- addFormatterTest("%#+v", v3, "("+v3t+")"+v3s2)
- addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s2)
- addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s2)
- addFormatterTest("%#+v", nv3, "(*"+v3t+")"+"<nil>")
-
- // 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:<nil>]"
- v4s2 := "map[nil:(" + v4t1 + ")<nil>]"
- addFormatterTest("%v", v4, v4s)
- addFormatterTest("%v", pv4, "<*>"+v4s)
- addFormatterTest("%v", &pv4, "<**>"+v4s)
- addFormatterTest("%+v", nv4, "<nil>")
- addFormatterTest("%+v", v4, v4s)
- addFormatterTest("%+v", pv4, "<*>("+v4Addr+")"+v4s)
- addFormatterTest("%+v", &pv4, "<**>("+pv4Addr+"->"+v4Addr+")"+v4s)
- addFormatterTest("%+v", nv4, "<nil>")
- addFormatterTest("%#v", v4, "("+v4t+")"+v4s2)
- addFormatterTest("%#v", pv4, "(*"+v4t+")"+v4s2)
- addFormatterTest("%#v", &pv4, "(**"+v4t+")"+v4s2)
- addFormatterTest("%#v", nv4, "(*"+v4t+")"+"<nil>")
- addFormatterTest("%#+v", v4, "("+v4t+")"+v4s2)
- addFormatterTest("%#+v", pv4, "(*"+v4t+")("+v4Addr+")"+v4s2)
- addFormatterTest("%#+v", &pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")"+v4s2)
- addFormatterTest("%#+v", nv4, "(*"+v4t+")"+"<nil>")
-}
-
-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, "<nil>")
- addFormatterTest("%+v", v, vs2)
- addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs2)
- addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs2)
- addFormatterTest("%+v", nv, "<nil>")
- addFormatterTest("%#v", v, "("+vt+")"+vs3)
- addFormatterTest("%#v", pv, "(*"+vt+")"+vs3)
- addFormatterTest("%#v", &pv, "(**"+vt+")"+vs3)
- addFormatterTest("%#v", nv, "(*"+vt+")"+"<nil>")
- addFormatterTest("%#+v", v, "("+vt+")"+vs3)
- addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs3)
- addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs3)
- addFormatterTest("%#+v", nv, "(*"+vt+")"+"<nil>")
-
- // 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, "<nil>")
- addFormatterTest("%+v", v2, v2s2)
- addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s2)
- addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s2)
- addFormatterTest("%+v", nv2, "<nil>")
- addFormatterTest("%#v", v2, "("+v2t+")"+v2s3)
- addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s3)
- addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s3)
- addFormatterTest("%#v", nv2, "(*"+v2t+")"+"<nil>")
- addFormatterTest("%#+v", v2, "("+v2t+")"+v2s3)
- addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s3)
- addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s3)
- addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"<nil>")
-
- // 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, "<nil>")
- addFormatterTest("%+v", v3, v3s2)
- addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s2p)
- addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s2p)
- addFormatterTest("%+v", nv3, "<nil>")
- addFormatterTest("%#v", v3, "("+v3t+")"+v3s3)
- addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s3p)
- addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s3p)
- addFormatterTest("%#v", nv3, "(*"+v3t+")"+"<nil>")
- addFormatterTest("%#+v", v3, "("+v3t+")"+v3s3)
- addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s3p)
- addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s3p)
- addFormatterTest("%#+v", nv3, "(*"+v3t+")"+"<nil>")
-
- // 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, "<nil>")
- addFormatterTest("%+v", v4, v4s2)
- addFormatterTest("%+v", pv4, "<*>("+v4Addr+")"+v4s2)
- addFormatterTest("%+v", &pv4, "<**>("+pv4Addr+"->"+v4Addr+")"+v4s2)
- addFormatterTest("%+v", nv4, "<nil>")
- addFormatterTest("%#v", v4, "("+v4t+")"+v4s3)
- addFormatterTest("%#v", pv4, "(*"+v4t+")"+v4s3)
- addFormatterTest("%#v", &pv4, "(**"+v4t+")"+v4s3)
- addFormatterTest("%#v", nv4, "(*"+v4t+")"+"<nil>")
- addFormatterTest("%#+v", v4, "("+v4t+")"+v4s4)
- addFormatterTest("%#+v", pv4, "(*"+v4t+")("+v4Addr+")"+v4s4)
- addFormatterTest("%#+v", &pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")"+v4s4)
- addFormatterTest("%#+v", nv4, "(*"+v4t+")"+"<nil>")
-}
-
-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 := "<nil>"
- addFormatterTest("%v", v, vs)
- addFormatterTest("%v", pv, "<*>"+vs)
- addFormatterTest("%v", &pv, "<**>"+vs)
- addFormatterTest("%+v", nv, "<nil>")
- addFormatterTest("%+v", v, vs)
- addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs)
- addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%+v", nv, "<nil>")
- addFormatterTest("%#v", v, "("+vt+")"+vs)
- addFormatterTest("%#v", pv, "(*"+vt+")"+vs)
- addFormatterTest("%#v", &pv, "(**"+vt+")"+vs)
- addFormatterTest("%#v", nv, "(*"+vt+")"+"<nil>")
- addFormatterTest("%#+v", v, "("+vt+")"+vs)
- addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs)
- addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%#+v", nv, "(*"+vt+")"+"<nil>")
-
- // 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(uintptr(0))
- nv := (*unsafe.Pointer)(nil)
- pv := &v
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "unsafe.Pointer"
- vs := "<nil>"
- addFormatterTest("%v", v, vs)
- addFormatterTest("%v", pv, "<*>"+vs)
- addFormatterTest("%v", &pv, "<**>"+vs)
- addFormatterTest("%+v", nv, "<nil>")
- addFormatterTest("%+v", v, vs)
- addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs)
- addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%+v", nv, "<nil>")
- addFormatterTest("%#v", v, "("+vt+")"+vs)
- addFormatterTest("%#v", pv, "(*"+vt+")"+vs)
- addFormatterTest("%#v", &pv, "(**"+vt+")"+vs)
- addFormatterTest("%#v", nv, "(*"+vt+")"+"<nil>")
- addFormatterTest("%#+v", v, "("+vt+")"+vs)
- addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs)
- addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%#+v", nv, "(*"+vt+")"+"<nil>")
-
- // 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 := "<nil>"
- addFormatterTest("%v", v, vs)
- addFormatterTest("%v", pv, "<*>"+vs)
- addFormatterTest("%v", &pv, "<**>"+vs)
- addFormatterTest("%+v", nv, "<nil>")
- addFormatterTest("%+v", v, vs)
- addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs)
- addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%+v", nv, "<nil>")
- addFormatterTest("%#v", v, "("+vt+")"+vs)
- addFormatterTest("%#v", pv, "(*"+vt+")"+vs)
- addFormatterTest("%#v", &pv, "(**"+vt+")"+vs)
- addFormatterTest("%#v", nv, "(*"+vt+")"+"<nil>")
- addFormatterTest("%#+v", v, "("+vt+")"+vs)
- addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs)
- addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%#+v", nv, "(*"+vt+")"+"<nil>")
-
- // 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, "<nil>")
- addFormatterTest("%+v", v, vs)
- addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs)
- addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%+v", nv, "<nil>")
- addFormatterTest("%#v", v, "("+vt+")"+vs)
- addFormatterTest("%#v", pv, "(*"+vt+")"+vs)
- addFormatterTest("%#v", &pv, "(**"+vt+")"+vs)
- addFormatterTest("%#v", nv, "(*"+vt+")"+"<nil>")
- addFormatterTest("%#+v", v, "("+vt+")"+vs)
- addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs)
- addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%#+v", nv, "(*"+vt+")"+"<nil>")
-
- // 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, "<nil>")
- addFormatterTest("%+v", v2, v2s)
- addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s)
- addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s)
- addFormatterTest("%+v", nv2, "<nil>")
- addFormatterTest("%#v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s)
- addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s)
- addFormatterTest("%#v", nv2, "(*"+v2t+")"+"<nil>")
- addFormatterTest("%#+v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s)
- addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s)
- addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"<nil>")
-
- // 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, "<nil>")
- addFormatterTest("%+v", v3, v3s)
- addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s)
- addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s)
- addFormatterTest("%+v", nv3, "<nil>")
- addFormatterTest("%#v", v3, "("+v3t+")"+v3s)
- addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s)
- addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s)
- addFormatterTest("%#v", nv3, "(*"+v3t+")"+"<nil>")
- addFormatterTest("%#+v", v3, "("+v3t+")"+v3s)
- addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s)
- addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s)
- addFormatterTest("%#+v", nv3, "(*"+v3t+")"+"<nil>")
-}
-
-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 := "{<*>{<*><shown>}}"
- vs2 := "{<*><shown>}"
- vs3 := "{c:<*>(" + vAddr + "){c:<*>(" + vAddr + ")<shown>}}"
- vs4 := "{c:<*>(" + vAddr + ")<shown>}"
- vs5 := "{c:(*" + vt + "){c:(*" + vt + ")<shown>}}"
- vs6 := "{c:(*" + vt + ")<shown>}"
- vs7 := "{c:(*" + vt + ")(" + vAddr + "){c:(*" + vt + ")(" + vAddr +
- ")<shown>}}"
- vs8 := "{c:(*" + vt + ")(" + vAddr + ")<shown>}"
- 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 := "{<*>{<*>{<*><shown>}}}"
- v2s2 := "{<*>{<*><shown>}}"
- v2s3 := "{ps2:<*>(" + ts2Addr + "){ps1:<*>(" + v2Addr + "){ps2:<*>(" +
- ts2Addr + ")<shown>}}}"
- v2s4 := "{ps2:<*>(" + ts2Addr + "){ps1:<*>(" + v2Addr + ")<shown>}}"
- v2s5 := "{ps2:(*" + v2t2 + "){ps1:(*" + v2t + "){ps2:(*" + v2t2 +
- ")<shown>}}}"
- v2s6 := "{ps2:(*" + v2t2 + "){ps1:(*" + v2t + ")<shown>}}"
- v2s7 := "{ps2:(*" + v2t2 + ")(" + ts2Addr + "){ps1:(*" + v2t +
- ")(" + v2Addr + "){ps2:(*" + v2t2 + ")(" + ts2Addr +
- ")<shown>}}}"
- v2s8 := "{ps2:(*" + v2t2 + ")(" + ts2Addr + "){ps1:(*" + v2t +
- ")(" + v2Addr + ")<shown>}}"
- 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 := "{<*>{<*>{<*>{<*><shown>}}}}"
- v3s2 := "{<*>{<*>{<*><shown>}}}"
- v3s3 := "{ps2:<*>(" + tic2Addr + "){ps3:<*>(" + tic3Addr + "){ps1:<*>(" +
- v3Addr + "){ps2:<*>(" + tic2Addr + ")<shown>}}}}"
- v3s4 := "{ps2:<*>(" + tic2Addr + "){ps3:<*>(" + tic3Addr + "){ps1:<*>(" +
- v3Addr + ")<shown>}}}"
- v3s5 := "{ps2:(*" + v3t2 + "){ps3:(*" + v3t3 + "){ps1:(*" + v3t +
- "){ps2:(*" + v3t2 + ")<shown>}}}}"
- v3s6 := "{ps2:(*" + v3t2 + "){ps3:(*" + v3t3 + "){ps1:(*" + v3t +
- ")<shown>}}}"
- v3s7 := "{ps2:(*" + v3t2 + ")(" + tic2Addr + "){ps3:(*" + v3t3 + ")(" +
- tic3Addr + "){ps1:(*" + v3t + ")(" + v3Addr + "){ps2:(*" + v3t2 +
- ")(" + tic2Addr + ")<shown>}}}}"
- v3s8 := "{ps2:(*" + v3t2 + ")(" + tic2Addr + "){ps3:(*" + v3t3 + ")(" +
- tic3Addr + "){ps1:(*" + v3t + ")(" + v3Addr + ")<shown>}}}"
- 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, "<nil>")
- addFormatterTest("%+v", v, vs)
- addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs)
- addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%+v", nv, "<nil>")
- addFormatterTest("%#v", v, "("+vt+")"+vs)
- addFormatterTest("%#v", pv, "(*"+vt+")"+vs)
- addFormatterTest("%#v", &pv, "(**"+vt+")"+vs)
- addFormatterTest("%#v", nv, "(*"+vt+")"+"<nil>")
- addFormatterTest("%#+v", v, "("+vt+")"+vs)
- addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs)
- addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%#+v", nv, "(*"+vt+")"+"<nil>")
-}
-
-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, "<nil>")
- addFormatterTest("%+v", v, vs)
- addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs)
- addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%+v", nv, "<nil>")
- addFormatterTest("%#v", v, "("+vt+")"+vs)
- addFormatterTest("%#v", pv, "(*"+vt+")"+vs)
- addFormatterTest("%#v", &pv, "(**"+vt+")"+vs)
- addFormatterTest("%#v", nv, "(*"+vt+")"+"<nil>")
- addFormatterTest("%#+v", v, "("+vt+")"+vs)
- addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs)
- addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%#+v", nv, "(*"+vt+")"+"<nil>")
-}
-
-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{testStruct{1}: 1, testStruct{3}: 3, testStruct{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{testStructP{1}: 1, testStructP{3}: 3, testStructP{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/vendor/github.com/davecgh/go-spew/spew/internal_test.go b/vendor/github.com/davecgh/go-spew/spew/internal_test.go
deleted file mode 100644
index 20a9cfe..0000000
--- a/vendor/github.com/davecgh/go-spew/spew/internal_test.go
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- * Copyright (c) 2013-2016 Dave Collins <dave@davec.name>
- *
- * 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 {
- if f == int('+') {
- return true
- }
- return false
-}
-
-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 := "<invalid>"
- 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 = "<invalid>"
- 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/vendor/github.com/davecgh/go-spew/spew/internalunsafe_test.go b/vendor/github.com/davecgh/go-spew/spew/internalunsafe_test.go
deleted file mode 100644
index a0c612e..0000000
--- a/vendor/github.com/davecgh/go-spew/spew/internalunsafe_test.go
+++ /dev/null
@@ -1,102 +0,0 @@
-// Copyright (c) 2013-2016 Dave Collins <dave@davec.name>
-
-// 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
-
-/*
-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"
- "unsafe"
-)
-
-// 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) {
- rvf := (*uintptr)(unsafe.Pointer(uintptr(unsafe.Pointer(v)) + offsetFlag))
- *rvf = *rvf | ((1<<flagKindWidth - 1) << flagKindShift)
- if readOnly {
- *rvf |= flagRO
- } else {
- *rvf &= ^uintptr(flagRO)
- }
-}
-
-// 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) <int8 Value>"
- 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 = "<int8 Value>"
- if s != want {
- t.Errorf("TestAddedReflectValue #%d got: %s want: %s", i, s, want)
- }
-}
diff --git a/vendor/github.com/davecgh/go-spew/spew/spew_test.go b/vendor/github.com/davecgh/go-spew/spew/spew_test.go
deleted file mode 100644
index b70466c..0000000
--- a/vendor/github.com/davecgh/go-spew/spew/spew_test.go
+++ /dev/null
@@ -1,320 +0,0 @@
-/*
- * Copyright (c) 2013-2016 Dave Collins <dave@davec.name>
- *
- * 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, "{{<max>} [<max>] [<max>] map[<max>]}"},
- {scsMaxDepth, fCSFdump, "", dt, "(spew_test.depthTester) {\n" +
- " ic: (spew_test.indirCir1) {\n <max depth reached>\n },\n" +
- " arr: ([1]string) (len=1 cap=1) {\n <max depth reached>\n },\n" +
- " slice: ([]string) (len=1 cap=1) {\n <max depth reached>\n },\n" +
- " m: (map[string]int) (len=1) {\n <max depth reached>\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/vendor/github.com/davecgh/go-spew/test_coverage.txt b/vendor/github.com/davecgh/go-spew/test_coverage.txt
deleted file mode 100644
index 2cd087a..0000000
--- a/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/vendor/github.com/docker/distribution/.gitignore b/vendor/github.com/docker/distribution/.gitignore
deleted file mode 100644
index 1c3ae0a..0000000
--- a/vendor/github.com/docker/distribution/.gitignore
+++ /dev/null
@@ -1,37 +0,0 @@
-# Compiled Object files, Static and Dynamic libs (Shared Objects)
-*.o
-*.a
-*.so
-
-# Folders
-_obj
-_test
-
-# Architecture specific extensions/prefixes
-*.[568vq]
-[568vq].out
-
-*.cgo1.go
-*.cgo2.c
-_cgo_defun.c
-_cgo_gotypes.go
-_cgo_export.*
-
-_testmain.go
-
-*.exe
-*.test
-*.prof
-
-# never checkin from the bin file (for now)
-bin/*
-
-# Test key files
-*.pem
-
-# Cover profiles
-*.out
-
-# Editor/IDE specific files.
-*.sublime-project
-*.sublime-workspace
diff --git a/vendor/github.com/docker/distribution/.mailmap b/vendor/github.com/docker/distribution/.mailmap
deleted file mode 100644
index 2d68669..0000000
--- a/vendor/github.com/docker/distribution/.mailmap
+++ /dev/null
@@ -1,19 +0,0 @@
-Stephen J Day <stephen.day@docker.com> Stephen Day <stevvooe@users.noreply.github.com>
-Stephen J Day <stephen.day@docker.com> Stephen Day <stevvooe@gmail.com>
-Olivier Gambier <olivier@docker.com> Olivier Gambier <dmp42@users.noreply.github.com>
-Brian Bland <brian.bland@docker.com> Brian Bland <r4nd0m1n4t0r@gmail.com>
-Brian Bland <brian.bland@docker.com> Brian Bland <brian.t.bland@gmail.com>
-Josh Hawn <josh.hawn@docker.com> Josh Hawn <jlhawn@berkeley.edu>
-Richard Scothern <richard.scothern@docker.com> Richard <richard.scothern@gmail.com>
-Richard Scothern <richard.scothern@docker.com> Richard Scothern <richard.scothern@gmail.com>
-Andrew Meredith <andymeredith@gmail.com> Andrew Meredith <kendru@users.noreply.github.com>
-harche <p.harshal@gmail.com> harche <harche@users.noreply.github.com>
-Jessie Frazelle <jessie@docker.com> <jfrazelle@users.noreply.github.com>
-Sharif Nassar <sharif@mrwacky.com> Sharif Nassar <mrwacky42@users.noreply.github.com>
-Sven Dowideit <SvenDowideit@home.org.au> Sven Dowideit <SvenDowideit@users.noreply.github.com>
-Vincent Giersch <vincent.giersch@ovh.net> Vincent Giersch <vincent@giersch.fr>
-davidli <wenquan.li@hp.com> davidli <wenquan.li@hpe.com>
-Omer Cohen <git@omer.io> Omer Cohen <git@omerc.net>
-Eric Yang <windfarer@gmail.com> Eric Yang <Windfarer@users.noreply.github.com>
-Nikita Tarasov <nikita@mygento.ru> Nikita <luckyraul@users.noreply.github.com>
-Misty Stanley-Jones <misty@docker.com> Misty Stanley-Jones <misty@apache.org>
diff --git a/vendor/github.com/docker/distribution/BUILDING.md b/vendor/github.com/docker/distribution/BUILDING.md
deleted file mode 100644
index 2d5a101..0000000
--- a/vendor/github.com/docker/distribution/BUILDING.md
+++ /dev/null
@@ -1,119 +0,0 @@
-
-# Building the registry source
-
-## Use-case
-
-This is useful if you intend to actively work on the registry.
-
-### Alternatives
-
-Most people should use the [official Registry docker image](https://hub.docker.com/r/library/registry/).
-
-People looking for advanced operational use cases might consider rolling their own image with a custom Dockerfile inheriting `FROM registry:2`.
-
-OS X users who want to run natively can do so following [the instructions here](https://github.com/docker/docker.github.io/blob/master/registry/recipes/osx-setup-guide.md).
-
-### Gotchas
-
-You are expected to know your way around with go & git.
-
-If you are a casual user with no development experience, and no preliminary knowledge of go, building from source is probably not a good solution for you.
-
-## Build the development environment
-
-The first prerequisite of properly building distribution targets is to have a Go
-development environment setup. Please follow [How to Write Go Code](https://golang.org/doc/code.html)
-for proper setup. If done correctly, you should have a GOROOT and GOPATH set in the
-environment.
-
-If a Go development environment is setup, one can use `go get` to install the
-`registry` command from the current latest:
-
- go get github.com/docker/distribution/cmd/registry
-
-The above will install the source repository into the `GOPATH`.
-
-Now create the directory for the registry data (this might require you to set permissions properly)
-
- mkdir -p /var/lib/registry
-
-... or alternatively `export REGISTRY_STORAGE_FILESYSTEM_ROOTDIRECTORY=/somewhere` if you want to store data into another location.
-
-The `registry`
-binary can then be run with the following:
-
- $ $GOPATH/bin/registry --version
- $GOPATH/bin/registry github.com/docker/distribution v2.0.0-alpha.1+unknown
-
-> __NOTE:__ While you do not need to use `go get` to checkout the distribution
-> project, for these build instructions to work, the project must be checked
-> out in the correct location in the `GOPATH`. This should almost always be
-> `$GOPATH/src/github.com/docker/distribution`.
-
-The registry can be run with the default config using the following
-incantation:
-
- $ $GOPATH/bin/registry serve $GOPATH/src/github.com/docker/distribution/cmd/registry/config-example.yml
- INFO[0000] endpoint local-5003 disabled, skipping app.id=34bbec38-a91a-494a-9a3f-b72f9010081f version=v2.0.0-alpha.1+unknown
- INFO[0000] endpoint local-8083 disabled, skipping app.id=34bbec38-a91a-494a-9a3f-b72f9010081f version=v2.0.0-alpha.1+unknown
- INFO[0000] listening on :5000 app.id=34bbec38-a91a-494a-9a3f-b72f9010081f version=v2.0.0-alpha.1+unknown
- INFO[0000] debug server listening localhost:5001
-
-If it is working, one should see the above log messages.
-
-### Repeatable Builds
-
-For the full development experience, one should `cd` into
-`$GOPATH/src/github.com/docker/distribution`. From there, the regular `go`
-commands, such as `go test`, should work per package (please see
-[Developing](#developing) if they don't work).
-
-A `Makefile` has been provided as a convenience to support repeatable builds.
-Please install the following into `GOPATH` for it to work:
-
- go get github.com/tools/godep github.com/golang/lint/golint
-
-**TODO(stevvooe):** Add a `make setup` command to Makefile to run this. Have to think about how to interact with Godeps properly.
-
-Once these commands are available in the `GOPATH`, run `make` to get a full
-build:
-
- $ make
- + clean
- + fmt
- + vet
- + lint
- + build
- github.com/docker/docker/vendor/src/code.google.com/p/go/src/pkg/archive/tar
- github.com/Sirupsen/logrus
- github.com/docker/libtrust
- ...
- github.com/yvasiyarov/gorelic
- github.com/docker/distribution/registry/handlers
- github.com/docker/distribution/cmd/registry
- + test
- ...
- ok github.com/docker/distribution/digest 7.875s
- ok github.com/docker/distribution/manifest 0.028s
- ok github.com/docker/distribution/notifications 17.322s
- ? github.com/docker/distribution/registry [no test files]
- ok github.com/docker/distribution/registry/api/v2 0.101s
- ? github.com/docker/distribution/registry/auth [no test files]
- ok github.com/docker/distribution/registry/auth/silly 0.011s
- ...
- + /Users/sday/go/src/github.com/docker/distribution/bin/registry
- + /Users/sday/go/src/github.com/docker/distribution/bin/registry-api-descriptor-template
- + binaries
-
-The above provides a repeatable build using the contents of the vendored
-Godeps directory. This includes formatting, vetting, linting, building,
-testing and generating tagged binaries. We can verify this worked by running
-the registry binary generated in the "./bin" directory:
-
- $ ./bin/registry -version
- ./bin/registry github.com/docker/distribution v2.0.0-alpha.2-80-g16d8b2c.m
-
-### Optional build tags
-
-Optional [build tags](http://golang.org/pkg/go/build/) can be provided using
-the environment variable `DOCKER_BUILDTAGS`.
diff --git a/vendor/github.com/docker/distribution/CHANGELOG.md b/vendor/github.com/docker/distribution/CHANGELOG.md
deleted file mode 100644
index b1a5c68..0000000
--- a/vendor/github.com/docker/distribution/CHANGELOG.md
+++ /dev/null
@@ -1,114 +0,0 @@
-# Changelog
-
-## 2.6.1 (2017-04-05)
-
-#### Registry
-- Fix `Forwarded` header handling, revert use of `X-Forwarded-Port`
-- Use driver `Stat` for registry health check
-
-## 2.6.0 (2017-01-18)
-
-#### Storage
-- S3: fixed bug in delete due to read-after-write inconsistency
-- S3: allow EC2 IAM roles to be used when authorizing region endpoints
-- S3: add Object ACL Support
-- S3: fix delete method's notion of subpaths
-- S3: use multipart upload API in `Move` method for performance
-- S3: add v2 signature signing for legacy S3 clones
-- Swift: add simple heuristic to detect incomplete DLOs during read ops
-- Swift: support different user and tenant domains
-- Swift: bulk deletes in chunks
-- Aliyun OSS: fix delete method's notion of subpaths
-- Aliyun OSS: optimize data copy after upload finishes
-- Azure: close leaking response body
-- Fix storage drivers dropping non-EOF errors when listing repositories
-- Compare path properly when listing repositories in catalog
-- Add a foreign layer URL host whitelist
-- Improve catalog enumerate runtime
-
-#### Registry
-- Export `storage.CreateOptions` in top-level package
-- Enable notifications to endpoints that use self-signed certificates
-- Properly validate multi-URL foreign layers
-- Add control over validation of URLs in pushed manifests
-- Proxy mode: fix socket leak when pull is cancelled
-- Tag service: properly handle error responses on HEAD request
-- Support for custom authentication URL in proxying registry
-- Add configuration option to disable access logging
-- Add notification filtering by target media type
-- Manifest: `References()` returns all children
-- Honor `X-Forwarded-Port` and Forwarded headers
-- Reference: Preserve tag and digest in With* functions
-- Add policy configuration for enforcing repository classes
-
-#### Client
-- Changes the client Tags `All()` method to follow links
-- Allow registry clients to connect via HTTP2
-- Better handling of OAuth errors in client
-
-#### Spec
-- Manifest: clarify relationship between urls and foreign layers
-- Authorization: add support for repository classes
-
-#### Manifest
-- Override media type returned from `Stat()` for existing manifests
-- Add plugin mediatype to distribution manifest
-
-#### Docs
-- Document `TOOMANYREQUESTS` error code
-- Document required Let's Encrypt port
-- Improve documentation around implementation of OAuth2
-- Improve documentation for configuration
-
-#### Auth
-- Add support for registry type in scope
-- Add support for using v2 ping challenges for v1
-- Add leeway to JWT `nbf` and `exp` checking
-- htpasswd: dynamically parse htpasswd file
-- Fix missing auth headers with PATCH HTTP request when pushing to default port
-
-#### Dockerfile
-- Update to go1.7
-- Reorder Dockerfile steps for better layer caching
-
-#### Notes
-
-Documentation has moved to the documentation repository at
-`github.com/docker/docker.github.io/tree/master/registry`
-
-The registry is go 1.7 compliant, and passes newer, more restrictive `lint` and `vet` ing.
-
-
-## 2.5.0 (2016-06-14)
-
-#### Storage
-- Ensure uploads directory is cleaned after upload is committed
-- Add ability to cap concurrent operations in filesystem driver
-- S3: Add 'us-gov-west-1' to the valid region list
-- Swift: Handle ceph not returning Last-Modified header for HEAD requests
-- Add redirect middleware
-
-#### Registry
-- Add support for blobAccessController middleware
-- Add support for layers from foreign sources
-- Remove signature store
-- Add support for Let's Encrypt
-- Correct yaml key names in configuration
-
-#### Client
-- Add option to get content digest from manifest get
-
-#### Spec
-- Update the auth spec scope grammar to reflect the fact that hostnames are optionally supported
-- Clarify API documentation around catalog fetch behavior
-
-#### API
-- Support returning HTTP 429 (Too Many Requests)
-
-#### Documentation
-- Update auth documentation examples to show "expires in" as int
-
-#### Docker Image
-- Use Alpine Linux as base image
-
-
diff --git a/vendor/github.com/docker/distribution/CONTRIBUTING.md b/vendor/github.com/docker/distribution/CONTRIBUTING.md
deleted file mode 100644
index 7cc7aed..0000000
--- a/vendor/github.com/docker/distribution/CONTRIBUTING.md
+++ /dev/null
@@ -1,140 +0,0 @@
-# Contributing to the registry
-
-## Before reporting an issue...
-
-### If your problem is with...
-
- - automated builds
- - your account on the [Docker Hub](https://hub.docker.com/)
- - any other [Docker Hub](https://hub.docker.com/) issue
-
-Then please do not report your issue here - you should instead report it to [https://support.docker.com](https://support.docker.com)
-
-### If you...
-
- - need help setting up your registry
- - can't figure out something
- - are not sure what's going on or what your problem is
-
-Then please do not open an issue here yet - you should first try one of the following support forums:
-
- - irc: #docker-distribution on freenode
- - mailing-list: <distribution@dockerproject.org> or https://groups.google.com/a/dockerproject.org/forum/#!forum/distribution
-
-## Reporting an issue properly
-
-By following these simple rules you will get better and faster feedback on your issue.
-
- - search the bugtracker for an already reported issue
-
-### If you found an issue that describes your problem:
-
- - please read other user comments first, and confirm this is the same issue: a given error condition might be indicative of different problems - you may also find a workaround in the comments
- - please refrain from adding "same thing here" or "+1" comments
- - you don't need to comment on an issue to get notified of updates: just hit the "subscribe" button
- - comment if you have some new, technical and relevant information to add to the case
- - __DO NOT__ comment on closed issues or merged PRs. If you think you have a related problem, open up a new issue and reference the PR or issue.
-
-### If you have not found an existing issue that describes your problem:
-
- 1. create a new issue, with a succinct title that describes your issue:
- - bad title: "It doesn't work with my docker"
- - good title: "Private registry push fail: 400 error with E_INVALID_DIGEST"
- 2. copy the output of:
- - `docker version`
- - `docker info`
- - `docker exec <registry-container> registry -version`
- 3. copy the command line you used to launch your Registry
- 4. restart your docker daemon in debug mode (add `-D` to the daemon launch arguments)
- 5. reproduce your problem and get your docker daemon logs showing the error
- 6. if relevant, copy your registry logs that show the error
- 7. provide any relevant detail about your specific Registry configuration (e.g., storage backend used)
- 8. indicate if you are using an enterprise proxy, Nginx, or anything else between you and your Registry
-
-## Contributing a patch for a known bug, or a small correction
-
-You should follow the basic GitHub workflow:
-
- 1. fork
- 2. commit a change
- 3. make sure the tests pass
- 4. PR
-
-Additionally, you must [sign your commits](https://github.com/docker/docker/blob/master/CONTRIBUTING.md#sign-your-work). It's very simple:
-
- - configure your name with git: `git config user.name "Real Name" && git config user.email mail@example.com`
- - sign your commits using `-s`: `git commit -s -m "My commit"`
-
-Some simple rules to ensure quick merge:
-
- - clearly point to the issue(s) you want to fix in your PR comment (e.g., `closes #12345`)
- - prefer multiple (smaller) PRs addressing individual issues over a big one trying to address multiple issues at once
- - if you need to amend your PR following comments, please squash instead of adding more commits
-
-## Contributing new features
-
-You are heavily encouraged to first discuss what you want to do. You can do so on the irc channel, or by opening an issue that clearly describes the use case you want to fulfill, or the problem you are trying to solve.
-
-If this is a major new feature, you should then submit a proposal that describes your technical solution and reasoning.
-If you did discuss it first, this will likely be greenlighted very fast. It's advisable to address all feedback on this proposal before starting actual work.
-
-Then you should submit your implementation, clearly linking to the issue (and possible proposal).
-
-Your PR will be reviewed by the community, then ultimately by the project maintainers, before being merged.
-
-It's mandatory to:
-
- - interact respectfully with other community members and maintainers - more generally, you are expected to abide by the [Docker community rules](https://github.com/docker/docker/blob/master/CONTRIBUTING.md#docker-community-guidelines)
- - address maintainers' comments and modify your submission accordingly
- - write tests for any new code
-
-Complying to these simple rules will greatly accelerate the review process, and will ensure you have a pleasant experience in contributing code to the Registry.
-
-Have a look at a great, successful contribution: the [Swift driver PR](https://github.com/docker/distribution/pull/493)
-
-## Coding Style
-
-Unless explicitly stated, we follow all coding guidelines from the Go
-community. While some of these standards may seem arbitrary, they somehow seem
-to result in a solid, consistent codebase.
-
-It is possible that the code base does not currently comply with these
-guidelines. We are not looking for a massive PR that fixes this, since that
-goes against the spirit of the guidelines. All new contributions should make a
-best effort to clean up and make the code base better than they left it.
-Obviously, apply your best judgement. Remember, the goal here is to make the
-code base easier for humans to navigate and understand. Always keep that in
-mind when nudging others to comply.
-
-The rules:
-
-1. All code should be formatted with `gofmt -s`.
-2. All code should pass the default levels of
- [`golint`](https://github.com/golang/lint).
-3. All code should follow the guidelines covered in [Effective
- Go](http://golang.org/doc/effective_go.html) and [Go Code Review
- Comments](https://github.com/golang/go/wiki/CodeReviewComments).
-4. Comment the code. Tell us the why, the history and the context.
-5. Document _all_ declarations and methods, even private ones. Declare
- expectations, caveats and anything else that may be important. If a type
- gets exported, having the comments already there will ensure it's ready.
-6. Variable name length should be proportional to its context and no longer.
- `noCommaALongVariableNameLikeThisIsNotMoreClearWhenASimpleCommentWouldDo`.
- In practice, short methods will have short variable names and globals will
- have longer names.
-7. No underscores in package names. If you need a compound name, step back,
- and re-examine why you need a compound name. If you still think you need a
- compound name, lose the underscore.
-8. No utils or helpers packages. If a function is not general enough to
- warrant its own package, it has not been written generally enough to be a
- part of a util package. Just leave it unexported and well-documented.
-9. All tests should run with `go test` and outside tooling should not be
- required. No, we don't need another unit testing framework. Assertion
- packages are acceptable if they provide _real_ incremental value.
-10. Even though we call these "rules" above, they are actually just
- guidelines. Since you've read all the rules, you now know that.
-
-If you are having trouble getting into the mood of idiomatic Go, we recommend
-reading through [Effective Go](http://golang.org/doc/effective_go.html). The
-[Go Blog](http://blog.golang.org/) is also a great resource. Drinking the
-kool-aid is a lot easier than going thirsty.
diff --git a/vendor/github.com/docker/distribution/Dockerfile b/vendor/github.com/docker/distribution/Dockerfile
deleted file mode 100644
index 426954a..0000000
--- a/vendor/github.com/docker/distribution/Dockerfile
+++ /dev/null
@@ -1,18 +0,0 @@
-FROM golang:1.7-alpine
-
-ENV DISTRIBUTION_DIR /go/src/github.com/docker/distribution
-ENV DOCKER_BUILDTAGS include_oss include_gcs
-
-RUN set -ex \
- && apk add --no-cache make git
-
-WORKDIR $DISTRIBUTION_DIR
-COPY . $DISTRIBUTION_DIR
-COPY cmd/registry/config-dev.yml /etc/docker/registry/config.yml
-
-RUN make PREFIX=/go clean binaries
-
-VOLUME ["/var/lib/registry"]
-EXPOSE 5000
-ENTRYPOINT ["registry"]
-CMD ["serve", "/etc/docker/registry/config.yml"]
diff --git a/vendor/github.com/docker/distribution/MAINTAINERS b/vendor/github.com/docker/distribution/MAINTAINERS
deleted file mode 100644
index bda4001..0000000
--- a/vendor/github.com/docker/distribution/MAINTAINERS
+++ /dev/null
@@ -1,58 +0,0 @@
-# Distribution maintainers file
-#
-# This file describes who runs the docker/distribution project and how.
-# This is a living document - if you see something out of date or missing, speak up!
-#
-# It is structured to be consumable by both humans and programs.
-# To extract its contents programmatically, use any TOML-compliant parser.
-#
-# This file is compiled into the MAINTAINERS file in docker/opensource.
-#
-[Org]
- [Org."Core maintainers"]
- people = [
- "aaronlehmann",
- "dmcgowan",
- "dmp42",
- "richardscothern",
- "shykes",
- "stevvooe",
- ]
-
-[people]
-
-# A reference list of all people associated with the project.
-# All other sections should refer to people by their canonical key
-# in the people section.
-
- # ADD YOURSELF HERE IN ALPHABETICAL ORDER
-
- [people.aaronlehmann]
- Name = "Aaron Lehmann"
- Email = "aaron.lehmann@docker.com"
- GitHub = "aaronlehmann"
-
- [people.dmcgowan]
- Name = "Derek McGowan"
- Email = "derek@mcgstyle.net"
- GitHub = "dmcgowan"
-
- [people.dmp42]
- Name = "Olivier Gambier"
- Email = "olivier@docker.com"
- GitHub = "dmp42"
-
- [people.richardscothern]
- Name = "Richard Scothern"
- Email = "richard.scothern@gmail.com"
- GitHub = "richardscothern"
-
- [people.shykes]
- Name = "Solomon Hykes"
- Email = "solomon@docker.com"
- GitHub = "shykes"
-
- [people.stevvooe]
- Name = "Stephen Day"
- Email = "stephen.day@docker.com"
- GitHub = "stevvooe"
diff --git a/vendor/github.com/docker/distribution/Makefile b/vendor/github.com/docker/distribution/Makefile
deleted file mode 100644
index 47b8f1d..0000000
--- a/vendor/github.com/docker/distribution/Makefile
+++ /dev/null
@@ -1,109 +0,0 @@
-# Set an output prefix, which is the local directory if not specified
-PREFIX?=$(shell pwd)
-
-
-# Used to populate version variable in main package.
-VERSION=$(shell git describe --match 'v[0-9]*' --dirty='.m' --always)
-
-# Allow turning off function inlining and variable registerization
-ifeq (${DISABLE_OPTIMIZATION},true)
- GO_GCFLAGS=-gcflags "-N -l"
- VERSION:="$(VERSION)-noopt"
-endif
-
-GO_LDFLAGS=-ldflags "-X `go list ./version`.Version=$(VERSION)"
-
-.PHONY: all build binaries clean dep-restore dep-save dep-validate fmt lint test test-full vet
-.DEFAULT: all
-all: fmt vet lint build test binaries
-
-AUTHORS: .mailmap .git/HEAD
- git log --format='%aN <%aE>' | sort -fu > $@
-
-# This only needs to be generated by hand when cutting full releases.
-version/version.go:
- ./version/version.sh > $@
-
-# Required for go 1.5 to build
-GO15VENDOREXPERIMENT := 1
-
-# Go files
-GOFILES=$(shell find . -type f -name '*.go')
-
-# Package list
-PKGS=$(shell go list -tags "${DOCKER_BUILDTAGS}" ./... | grep -v ^github.com/docker/distribution/vendor/)
-
-# Resolving binary dependencies for specific targets
-GOLINT=$(shell which golint || echo '')
-GODEP=$(shell which godep || echo '')
-
-${PREFIX}/bin/registry: $(GOFILES)
- @echo "+ $@"
- @go build -tags "${DOCKER_BUILDTAGS}" -o $@ ${GO_LDFLAGS} ${GO_GCFLAGS} ./cmd/registry
-
-${PREFIX}/bin/digest: $(GOFILES)
- @echo "+ $@"
- @go build -tags "${DOCKER_BUILDTAGS}" -o $@ ${GO_LDFLAGS} ${GO_GCFLAGS} ./cmd/digest
-
-${PREFIX}/bin/registry-api-descriptor-template: $(GOFILES)
- @echo "+ $@"
- @go build -o $@ ${GO_LDFLAGS} ${GO_GCFLAGS} ./cmd/registry-api-descriptor-template
-
-docs/spec/api.md: docs/spec/api.md.tmpl ${PREFIX}/bin/registry-api-descriptor-template
- ./bin/registry-api-descriptor-template $< > $@
-
-vet:
- @echo "+ $@"
- @go vet -tags "${DOCKER_BUILDTAGS}" $(PKGS)
-
-fmt:
- @echo "+ $@"
- @test -z "$$(gofmt -s -l . 2>&1 | grep -v ^vendor/ | tee /dev/stderr)" || \
- (echo >&2 "+ please format Go code with 'gofmt -s'" && false)
-
-lint:
- @echo "+ $@"
- $(if $(GOLINT), , \
- $(error Please install golint: `go get -u github.com/golang/lint/golint`))
- @test -z "$$($(GOLINT) ./... 2>&1 | grep -v ^vendor/ | tee /dev/stderr)"
-
-build:
- @echo "+ $@"
- @go build -tags "${DOCKER_BUILDTAGS}" -v ${GO_LDFLAGS} $(PKGS)
-
-test:
- @echo "+ $@"
- @go test -test.short -tags "${DOCKER_BUILDTAGS}" $(PKGS)
-
-test-full:
- @echo "+ $@"
- @go test -tags "${DOCKER_BUILDTAGS}" $(PKGS)
-
-binaries: ${PREFIX}/bin/registry ${PREFIX}/bin/digest ${PREFIX}/bin/registry-api-descriptor-template
- @echo "+ $@"
-
-clean:
- @echo "+ $@"
- @rm -rf "${PREFIX}/bin/registry" "${PREFIX}/bin/digest" "${PREFIX}/bin/registry-api-descriptor-template"
-
-dep-save:
- @echo "+ $@"
- $(if $(GODEP), , \
- $(error Please install godep: go get github.com/tools/godep))
- @$(GODEP) save $(PKGS)
-
-dep-restore:
- @echo "+ $@"
- $(if $(GODEP), , \
- $(error Please install godep: go get github.com/tools/godep))
- @$(GODEP) restore -v
-
-dep-validate: dep-restore
- @echo "+ $@"
- @rm -Rf .vendor.bak
- @mv vendor .vendor.bak
- @rm -Rf Godeps
- @$(GODEP) save ./...
- @test -z "$$(diff -r vendor .vendor.bak 2>&1 | tee /dev/stderr)" || \
- (echo >&2 "+ borked dependencies! what you have in Godeps/Godeps.json does not match with what you have in vendor" && false)
- @rm -Rf .vendor.bak
diff --git a/vendor/github.com/docker/distribution/README.md b/vendor/github.com/docker/distribution/README.md
deleted file mode 100644
index a6e8db0..0000000
--- a/vendor/github.com/docker/distribution/README.md
+++ /dev/null
@@ -1,131 +0,0 @@
-# Distribution
-
-The Docker toolset to pack, ship, store, and deliver content.
-
-This repository's main product is the Docker Registry 2.0 implementation
-for storing and distributing Docker images. It supersedes the
-[docker/docker-registry](https://github.com/docker/docker-registry)
-project with a new API design, focused around security and performance.
-
-<img src="https://www.docker.com/sites/default/files/oyster-registry-3.png" width=200px/>
-
-[![Circle CI](https://circleci.com/gh/docker/distribution/tree/master.svg?style=svg)](https://circleci.com/gh/docker/distribution/tree/master)
-[![GoDoc](https://godoc.org/github.com/docker/distribution?status.svg)](https://godoc.org/github.com/docker/distribution)
-
-This repository contains the following components:
-
-|**Component** |Description |
-|--------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-| **registry** | An implementation of the [Docker Registry HTTP API V2](docs/spec/api.md) for use with docker 1.6+. |
-| **libraries** | A rich set of libraries for interacting with distribution components. Please see [godoc](https://godoc.org/github.com/docker/distribution) for details. **Note**: These libraries are **unstable**. |
-| **specifications** | _Distribution_ related specifications are available in [docs/spec](docs/spec) |
-| **documentation** | Docker's full documentation set is available at [docs.docker.com](https://docs.docker.com). This repository [contains the subset](docs/) related just to the registry. |
-
-### How does this integrate with Docker engine?
-
-This project should provide an implementation to a V2 API for use in the [Docker
-core project](https://github.com/docker/docker). The API should be embeddable
-and simplify the process of securely pulling and pushing content from `docker`
-daemons.
-
-### What are the long term goals of the Distribution project?
-
-The _Distribution_ project has the further long term goal of providing a
-secure tool chain for distributing content. The specifications, APIs and tools
-should be as useful with Docker as they are without.
-
-Our goal is to design a professional grade and extensible content distribution
-system that allow users to:
-
-* Enjoy an efficient, secured and reliable way to store, manage, package and
- exchange content
-* Hack/roll their own on top of healthy open-source components
-* Implement their own home made solution through good specs, and solid
- extensions mechanism.
-
-## More about Registry 2.0
-
-The new registry implementation provides the following benefits:
-
-- faster push and pull
-- new, more efficient implementation
-- simplified deployment
-- pluggable storage backend
-- webhook notifications
-
-For information on upcoming functionality, please see [ROADMAP.md](ROADMAP.md).
-
-### Who needs to deploy a registry?
-
-By default, Docker users pull images from Docker's public registry instance.
-[Installing Docker](https://docs.docker.com/engine/installation/) gives users this
-ability. Users can also push images to a repository on Docker's public registry,
-if they have a [Docker Hub](https://hub.docker.com/) account.
-
-For some users and even companies, this default behavior is sufficient. For
-others, it is not.
-
-For example, users with their own software products may want to maintain a
-registry for private, company images. Also, you may wish to deploy your own
-image repository for images used to test or in continuous integration. For these
-use cases and others, [deploying your own registry instance](https://github.com/docker/docker.github.io/blob/master/registry/deploying.md)
-may be the better choice.
-
-### Migration to Registry 2.0
-
-For those who have previously deployed their own registry based on the Registry
-1.0 implementation and wish to deploy a Registry 2.0 while retaining images,
-data migration is required. A tool to assist with migration efforts has been
-created. For more information see [docker/migrator]
-(https://github.com/docker/migrator).
-
-## Contribute
-
-Please see [CONTRIBUTING.md](CONTRIBUTING.md) for details on how to contribute
-issues, fixes, and patches to this project. If you are contributing code, see
-the instructions for [building a development environment](BUILDING.md).
-
-## Support
-
-If any issues are encountered while using the _Distribution_ project, several
-avenues are available for support:
-
-<table>
-<tr>
- <th align="left">
- IRC
- </th>
- <td>
- #docker-distribution on FreeNode
- </td>
-</tr>
-<tr>
- <th align="left">
- Issue Tracker
- </th>
- <td>
- github.com/docker/distribution/issues
- </td>
-</tr>
-<tr>
- <th align="left">
- Google Groups
- </th>
- <td>
- https://groups.google.com/a/dockerproject.org/forum/#!forum/distribution
- </td>
-</tr>
-<tr>
- <th align="left">
- Mailing List
- </th>
- <td>
- docker@dockerproject.org
- </td>
-</tr>
-</table>
-
-
-## License
-
-This project is distributed under [Apache License, Version 2.0](LICENSE).
diff --git a/vendor/github.com/docker/distribution/RELEASE-CHECKLIST.md b/vendor/github.com/docker/distribution/RELEASE-CHECKLIST.md
deleted file mode 100644
index 49235ce..0000000
--- a/vendor/github.com/docker/distribution/RELEASE-CHECKLIST.md
+++ /dev/null
@@ -1,36 +0,0 @@
-## Registry Release Checklist
-
-10. Compile release notes detailing features and since the last release. Update the `CHANGELOG.md` file.
-
-20. Update the version file: `https://github.com/docker/distribution/blob/master/version/version.go`
-
-30. Update the `MAINTAINERS` (if necessary), `AUTHORS` and `.mailmap` files.
-
- ```
-make AUTHORS
-```
-
-40. Create a signed tag.
-
- Distribution uses semantic versioning. Tags are of the format `vx.y.z[-rcn]`
-You will need PGP installed and a PGP key which has been added to your Github account. The comment for the tag should include the release notes.
-
-50. Push the signed tag
-
-60. Create a new [release](https://github.com/docker/distribution/releases). In the case of a release candidate, tick the `pre-release` checkbox.
-
-70. Update the registry binary in [distribution library image repo](https://github.com/docker/distribution-library-image) by running the update script and opening a pull request.
-
-80. Update the official image. Add the new version in the [official images repo](https://github.com/docker-library/official-images) by appending a new version to the `registry/registry` file with the git hash pointed to by the signed tag. Update the major version to point to the latest version and the minor version to point to new patch release if necessary.
-e.g. to release `2.3.1`
-
- `2.3.1 (new)`
-
- `2.3.0 -> 2.3.0` can be removed
-
- `2 -> 2.3.1`
-
- `2.3 -> 2.3.1`
-
-90. Build a new distribution/registry image on [Docker hub](https://hub.docker.com/u/distribution/dashboard) by adding a new automated build with the new tag and re-building the images.
-
diff --git a/vendor/github.com/docker/distribution/ROADMAP.md b/vendor/github.com/docker/distribution/ROADMAP.md
deleted file mode 100644
index 701127a..0000000
--- a/vendor/github.com/docker/distribution/ROADMAP.md
+++ /dev/null
@@ -1,267 +0,0 @@
-# Roadmap
-
-The Distribution Project consists of several components, some of which are
-still being defined. This document defines the high-level goals of the
-project, identifies the current components, and defines the release-
-relationship to the Docker Platform.
-
-* [Distribution Goals](#distribution-goals)
-* [Distribution Components](#distribution-components)
-* [Project Planning](#project-planning): release-relationship to the Docker Platform.
-
-This road map is a living document, providing an overview of the goals and
-considerations made in respect of the future of the project.
-
-## Distribution Goals
-
-- Replace the existing [docker registry](github.com/docker/docker-registry)
- implementation as the primary implementation.
-- Replace the existing push and pull code in the docker engine with the
- distribution package.
-- Define a strong data model for distributing docker images
-- Provide a flexible distribution tool kit for use in the docker platform
-- Unlock new distribution models
-
-## Distribution Components
-
-Components of the Distribution Project are managed via github [milestones](https://github.com/docker/distribution/milestones). Upcoming
-features and bugfixes for a component will be added to the relevant milestone. If a feature or
-bugfix is not part of a milestone, it is currently unscheduled for
-implementation.
-
-* [Registry](#registry)
-* [Distribution Package](#distribution-package)
-
-***
-
-### Registry
-
-The new Docker registry is the main portion of the distribution repository.
-Registry 2.0 is the first release of the next-generation registry. This was
-primarily focused on implementing the [new registry
-API](https://github.com/docker/distribution/blob/master/docs/spec/api.md),
-with a focus on security and performance.
-
-Following from the Distribution project goals above, we have a set of goals
-for registry v2 that we would like to follow in the design. New features
-should be compared against these goals.
-
-#### Data Storage and Distribution First
-
-The registry's first goal is to provide a reliable, consistent storage
-location for Docker images. The registry should only provide the minimal
-amount of indexing required to fetch image data and no more.
-
-This means we should be selective in new features and API additions, including
-those that may require expensive, ever growing indexes. Requests should be
-servable in "constant time".
-
-#### Content Addressability
-
-All data objects used in the registry API should be content addressable.
-Content identifiers should be secure and verifiable. This provides a secure,
-reliable base from which to build more advanced content distribution systems.
-
-#### Content Agnostic
-
-In the past, changes to the image format would require large changes in Docker
-and the Registry. By decoupling the distribution and image format, we can
-allow the formats to progress without having to coordinate between the two.
-This means that we should be focused on decoupling Docker from the registry
-just as much as decoupling the registry from Docker. Such an approach will
-allow us to unlock new distribution models that haven't been possible before.
-
-We can take this further by saying that the new registry should be content
-agnostic. The registry provides a model of names, tags, manifests and content
-addresses and that model can be used to work with content.
-
-#### Simplicity
-
-The new registry should be closer to a microservice component than its
-predecessor. This means it should have a narrower API and a low number of
-service dependencies. It should be easy to deploy.
-
-This means that other solutions should be explored before changing the API or
-adding extra dependencies. If functionality is required, can it be added as an
-extension or companion service.
-
-#### Extensibility
-
-The registry should provide extension points to add functionality. By keeping
-the scope narrow, but providing the ability to add functionality.
-
-Features like search, indexing, synchronization and registry explorers fall
-into this category. No such feature should be added unless we've found it
-impossible to do through an extension.
-
-#### Active Feature Discussions
-
-The following are feature discussions that are currently active.
-
-If you don't see your favorite, unimplemented feature, feel free to contact us
-via IRC or the mailing list and we can talk about adding it. The goal here is
-to make sure that new features go through a rigid design process before
-landing in the registry.
-
-##### Proxying to other Registries
-
-A _pull-through caching_ mode exists for the registry, but is restricted from
-within the docker client to only mirror the official Docker Hub. This functionality
-can be expanded when image provenance has been specified and implemented in the
-distribution project.
-
-##### Metadata storage
-
-Metadata for the registry is currently stored with the manifest and layer data on
-the storage backend. While this is a big win for simplicity and reliably maintaining
-state, it comes with the cost of consistency and high latency. The mutable registry
-metadata operations should be abstracted behind an API which will allow ACID compliant
-storage systems to handle metadata.
-
-##### Peer to Peer transfer
-
-Discussion has started here: https://docs.google.com/document/d/1rYDpSpJiQWmCQy8Cuiaa3NH-Co33oK_SC9HeXYo87QA/edit
-
-##### Indexing, Search and Discovery
-
-The original registry provided some implementation of search for use with
-private registries. Support has been elided from V2 since we'd like to both
-decouple search functionality from the registry. The makes the registry
-simpler to deploy, especially in use cases where search is not needed, and
-let's us decouple the image format from the registry.
-
-There are explorations into using the catalog API and notification system to
-build external indexes. The current line of thought is that we will define a
-common search API to index and query docker images. Such a system could be run
-as a companion to a registry or set of registries to power discovery.
-
-The main issue with search and discovery is that there are so many ways to
-accomplish it. There are two aspects to this project. The first is deciding on
-how it will be done, including an API definition that can work with changing
-data formats. The second is the process of integrating with `docker search`.
-We expect that someone attempts to address the problem with the existing tools
-and propose it as a standard search API or uses it to inform a standardization
-process. Once this has been explored, we integrate with the docker client.
-
-Please see the following for more detail:
-
-- https://github.com/docker/distribution/issues/206
-
-##### Deletes
-
-> __NOTE:__ Deletes are a much asked for feature. Before requesting this
-feature or participating in discussion, we ask that you read this section in
-full and understand the problems behind deletes.
-
-While, at first glance, implementing deleting seems simple, there are a number
-mitigating factors that make many solutions not ideal or even pathological in
-the context of a registry. The following paragraph discuss the background and
-approaches that could be applied to arrive at a solution.
-
-The goal of deletes in any system is to remove unused or unneeded data. Only
-data requested for deletion should be removed and no other data. Removing
-unintended data is worse than _not_ removing data that was requested for
-removal but ideally, both are supported. Generally, according to this rule, we
-err on holding data longer than needed, ensuring that it is only removed when
-we can be certain that it can be removed. With the current behavior, we opt to
-hold onto the data forever, ensuring that data cannot be incorrectly removed.
-
-To understand the problems with implementing deletes, one must understand the
-data model. All registry data is stored in a filesystem layout, implemented on
-a "storage driver", effectively a _virtual file system_ (VFS). The storage
-system must assume that this VFS layer will be eventually consistent and has
-poor read- after-write consistency, since this is the lower common denominator
-among the storage drivers. This is mitigated by writing values in reverse-
-dependent order, but makes wider transactional operations unsafe.
-
-Layered on the VFS model is a content-addressable _directed, acyclic graph_
-(DAG) made up of blobs. Manifests reference layers. Tags reference manifests.
-Since the same data can be referenced by multiple manifests, we only store
-data once, even if it is in different repositories. Thus, we have a set of
-blobs, referenced by tags and manifests. If we want to delete a blob we need
-to be certain that it is no longer referenced by another manifest or tag. When
-we delete a manifest, we also can try to delete the referenced blobs. Deciding
-whether or not a blob has an active reference is the crux of the problem.
-
-Conceptually, deleting a manifest and its resources is quite simple. Just find
-all the manifests, enumerate the referenced blobs and delete the blobs not in
-that set. An astute observer will recognize this as a garbage collection
-problem. As with garbage collection in programming languages, this is very
-simple when one always has a consistent view. When one adds parallelism and an
-inconsistent view of data, it becomes very challenging.
-
-A simple example can demonstrate this. Let's say we are deleting a manifest
-_A_ in one process. We scan the manifest and decide that all the blobs are
-ready for deletion. Concurrently, we have another process accepting a new
-manifest _B_ referencing one or more blobs from the manifest _A_. Manifest _B_
-is accepted and all the blobs are considered present, so the operation
-proceeds. The original process then deletes the referenced blobs, assuming
-they were unreferenced. The manifest _B_, which we thought had all of its data
-present, can no longer be served by the registry, since the dependent data has
-been deleted.
-
-Deleting data from the registry safely requires some way to coordinate this
-operation. The following approaches are being considered:
-
-- _Reference Counting_ - Maintain a count of references to each blob. This is
- challenging for a number of reasons: 1. maintaining a consistent consensus
- of reference counts across a set of Registries and 2. Building the initial
- list of reference counts for an existing registry. These challenges can be
- met with a consensus protocol like Paxos or Raft in the first case and a
- necessary but simple scan in the second..
-- _Lock the World GC_ - Halt all writes to the data store. Walk the data store
- and find all blob references. Delete all unreferenced blobs. This approach
- is very simple but requires disabling writes for a period of time while the
- service reads all data. This is slow and expensive but very accurate and
- effective.
-- _Generational GC_ - Do something similar to above but instead of blocking
- writes, writes are sent to another storage backend while reads are broadcast
- to the new and old backends. GC is then performed on the read-only portion.
- Because writes land in the new backend, the data in the read-only section
- can be safely deleted. The main drawbacks of this approach are complexity
- and coordination.
-- _Centralized Oracle_ - Using a centralized, transactional database, we can
- know exactly which data is referenced at any given time. This avoids
- coordination problem by managing this data in a single location. We trade
- off metadata scalability for simplicity and performance. This is a very good
- option for most registry deployments. This would create a bottleneck for
- registry metadata. However, metadata is generally not the main bottleneck
- when serving images.
-
-Please let us know if other solutions exist that we have yet to enumerate.
-Note that for any approach, implementation is a massive consideration. For
-example, a mark-sweep based solution may seem simple but the amount of work in
-coordination offset the extra work it might take to build a _Centralized
-Oracle_. We'll accept proposals for any solution but please coordinate with us
-before dropping code.
-
-At this time, we have traded off simplicity and ease of deployment for disk
-space. Simplicity and ease of deployment tend to reduce developer involvement,
-which is currently the most expensive resource in software engineering. Taking
-on any solution for deletes will greatly effect these factors, trading off
-very cheap disk space for a complex deployment and operational story.
-
-Please see the following issues for more detail:
-
-- https://github.com/docker/distribution/issues/422
-- https://github.com/docker/distribution/issues/461
-- https://github.com/docker/distribution/issues/462
-
-### Distribution Package
-
-At its core, the Distribution Project is a set of Go packages that make up
-Distribution Components. At this time, most of these packages make up the
-Registry implementation.
-
-The package itself is considered unstable. If you're using it, please take care to vendor the dependent version.
-
-For feature additions, please see the Registry section. In the future, we may break out a
-separate Roadmap for distribution-specific features that apply to more than
-just the registry.
-
-***
-
-### Project Planning
-
-An [Open-Source Planning Process](https://github.com/docker/distribution/wiki/Open-Source-Planning-Process) is used to define the Roadmap. [Project Pages](https://github.com/docker/distribution/wiki) define the goals for each Milestone and identify current progress.
-
diff --git a/vendor/github.com/docker/distribution/blobs.go b/vendor/github.com/docker/distribution/blobs.go
deleted file mode 100644
index 1f91ae2..0000000
--- a/vendor/github.com/docker/distribution/blobs.go
+++ /dev/null
@@ -1,257 +0,0 @@
-package distribution
-
-import (
- "errors"
- "fmt"
- "io"
- "net/http"
- "time"
-
- "github.com/docker/distribution/context"
- "github.com/docker/distribution/digest"
- "github.com/docker/distribution/reference"
-)
-
-var (
- // ErrBlobExists returned when blob already exists
- ErrBlobExists = errors.New("blob exists")
-
- // ErrBlobDigestUnsupported when blob digest is an unsupported version.
- ErrBlobDigestUnsupported = errors.New("unsupported blob digest")
-
- // ErrBlobUnknown when blob is not found.
- ErrBlobUnknown = errors.New("unknown blob")
-
- // ErrBlobUploadUnknown returned when upload is not found.
- ErrBlobUploadUnknown = errors.New("blob upload unknown")
-
- // ErrBlobInvalidLength returned when the blob has an expected length on
- // commit, meaning mismatched with the descriptor or an invalid value.
- ErrBlobInvalidLength = errors.New("blob invalid length")
-)
-
-// ErrBlobInvalidDigest returned when digest check fails.
-type ErrBlobInvalidDigest struct {
- Digest digest.Digest
- Reason error
-}
-
-func (err ErrBlobInvalidDigest) Error() string {
- return fmt.Sprintf("invalid digest for referenced layer: %v, %v",
- err.Digest, err.Reason)
-}
-
-// ErrBlobMounted returned when a blob is mounted from another repository
-// instead of initiating an upload session.
-type ErrBlobMounted struct {
- From reference.Canonical
- Descriptor Descriptor
-}
-
-func (err ErrBlobMounted) Error() string {
- return fmt.Sprintf("blob mounted from: %v to: %v",
- err.From, err.Descriptor)
-}
-
-// Descriptor describes targeted content. Used in conjunction with a blob
-// store, a descriptor can be used to fetch, store and target any kind of
-// blob. The struct also describes the wire protocol format. Fields should
-// only be added but never changed.
-type Descriptor struct {
- // MediaType describe the type of the content. All text based formats are
- // encoded as utf-8.
- MediaType string `json:"mediaType,omitempty"`
-
- // Size in bytes of content.
- Size int64 `json:"size,omitempty"`
-
- // Digest uniquely identifies the content. A byte stream can be verified
- // against against this digest.
- Digest digest.Digest `json:"digest,omitempty"`
-
- // URLs contains the source URLs of this content.
- URLs []string `json:"urls,omitempty"`
-
- // NOTE: Before adding a field here, please ensure that all
- // other options have been exhausted. Much of the type relationships
- // depend on the simplicity of this type.
-}
-
-// Descriptor returns the descriptor, to make it satisfy the Describable
-// interface. Note that implementations of Describable are generally objects
-// which can be described, not simply descriptors; this exception is in place
-// to make it more convenient to pass actual descriptors to functions that
-// expect Describable objects.
-func (d Descriptor) Descriptor() Descriptor {
- return d
-}
-
-// BlobStatter makes blob descriptors available by digest. The service may
-// provide a descriptor of a different digest if the provided digest is not
-// canonical.
-type BlobStatter interface {
- // Stat provides metadata about a blob identified by the digest. If the
- // blob is unknown to the describer, ErrBlobUnknown will be returned.
- Stat(ctx context.Context, dgst digest.Digest) (Descriptor, error)
-}
-
-// BlobDeleter enables deleting blobs from storage.
-type BlobDeleter interface {
- Delete(ctx context.Context, dgst digest.Digest) error
-}
-
-// BlobEnumerator enables iterating over blobs from storage
-type BlobEnumerator interface {
- Enumerate(ctx context.Context, ingester func(dgst digest.Digest) error) error
-}
-
-// BlobDescriptorService manages metadata about a blob by digest. Most
-// implementations will not expose such an interface explicitly. Such mappings
-// should be maintained by interacting with the BlobIngester. Hence, this is
-// left off of BlobService and BlobStore.
-type BlobDescriptorService interface {
- BlobStatter
-
- // SetDescriptor assigns the descriptor to the digest. The provided digest and
- // the digest in the descriptor must map to identical content but they may
- // differ on their algorithm. The descriptor must have the canonical
- // digest of the content and the digest algorithm must match the
- // annotators canonical algorithm.
- //
- // Such a facility can be used to map blobs between digest domains, with
- // the restriction that the algorithm of the descriptor must match the
- // canonical algorithm (ie sha256) of the annotator.
- SetDescriptor(ctx context.Context, dgst digest.Digest, desc Descriptor) error
-
- // Clear enables descriptors to be unlinked
- Clear(ctx context.Context, dgst digest.Digest) error
-}
-
-// BlobDescriptorServiceFactory creates middleware for BlobDescriptorService.
-type BlobDescriptorServiceFactory interface {
- BlobAccessController(svc BlobDescriptorService) BlobDescriptorService
-}
-
-// ReadSeekCloser is the primary reader type for blob data, combining
-// io.ReadSeeker with io.Closer.
-type ReadSeekCloser interface {
- io.ReadSeeker
- io.Closer
-}
-
-// BlobProvider describes operations for getting blob data.
-type BlobProvider interface {
- // Get returns the entire blob identified by digest along with the descriptor.
- Get(ctx context.Context, dgst digest.Digest) ([]byte, error)
-
- // Open provides a ReadSeekCloser to the blob identified by the provided
- // descriptor. If the blob is not known to the service, an error will be
- // returned.
- Open(ctx context.Context, dgst digest.Digest) (ReadSeekCloser, error)
-}
-
-// BlobServer can serve blobs via http.
-type BlobServer interface {
- // ServeBlob attempts to serve the blob, identifed by dgst, via http. The
- // service may decide to redirect the client elsewhere or serve the data
- // directly.
- //
- // This handler only issues successful responses, such as 2xx or 3xx,
- // meaning it serves data or issues a redirect. If the blob is not
- // available, an error will be returned and the caller may still issue a
- // response.
- //
- // The implementation may serve the same blob from a different digest
- // domain. The appropriate headers will be set for the blob, unless they
- // have already been set by the caller.
- ServeBlob(ctx context.Context, w http.ResponseWriter, r *http.Request, dgst digest.Digest) error
-}
-
-// BlobIngester ingests blob data.
-type BlobIngester interface {
- // Put inserts the content p into the blob service, returning a descriptor
- // or an error.
- Put(ctx context.Context, mediaType string, p []byte) (Descriptor, error)
-
- // Create allocates a new blob writer to add a blob to this service. The
- // returned handle can be written to and later resumed using an opaque
- // identifier. With this approach, one can Close and Resume a BlobWriter
- // multiple times until the BlobWriter is committed or cancelled.
- Create(ctx context.Context, options ...BlobCreateOption) (BlobWriter, error)
-
- // Resume attempts to resume a write to a blob, identified by an id.
- Resume(ctx context.Context, id string) (BlobWriter, error)
-}
-
-// BlobCreateOption is a general extensible function argument for blob creation
-// methods. A BlobIngester may choose to honor any or none of the given
-// BlobCreateOptions, which can be specific to the implementation of the
-// BlobIngester receiving them.
-// TODO (brianbland): unify this with ManifestServiceOption in the future
-type BlobCreateOption interface {
- Apply(interface{}) error
-}
-
-// CreateOptions is a collection of blob creation modifiers relevant to general
-// blob storage intended to be configured by the BlobCreateOption.Apply method.
-type CreateOptions struct {
- Mount struct {
- ShouldMount bool
- From reference.Canonical
- // Stat allows to pass precalculated descriptor to link and return.
- // Blob access check will be skipped if set.
- Stat *Descriptor
- }
-}
-
-// BlobWriter provides a handle for inserting data into a blob store.
-// Instances should be obtained from BlobWriteService.Writer and
-// BlobWriteService.Resume. If supported by the store, a writer can be
-// recovered with the id.
-type BlobWriter interface {
- io.WriteCloser
- io.ReaderFrom
-
- // Size returns the number of bytes written to this blob.
- Size() int64
-
- // ID returns the identifier for this writer. The ID can be used with the
- // Blob service to later resume the write.
- ID() string
-
- // StartedAt returns the time this blob write was started.
- StartedAt() time.Time
-
- // Commit completes the blob writer process. The content is verified
- // against the provided provisional descriptor, which may result in an
- // error. Depending on the implementation, written data may be validated
- // against the provisional descriptor fields. If MediaType is not present,
- // the implementation may reject the commit or assign "application/octet-
- // stream" to the blob. The returned descriptor may have a different
- // digest depending on the blob store, referred to as the canonical
- // descriptor.
- Commit(ctx context.Context, provisional Descriptor) (canonical Descriptor, err error)
-
- // Cancel ends the blob write without storing any data and frees any
- // associated resources. Any data written thus far will be lost. Cancel
- // implementations should allow multiple calls even after a commit that
- // result in a no-op. This allows use of Cancel in a defer statement,
- // increasing the assurance that it is correctly called.
- Cancel(ctx context.Context) error
-}
-
-// BlobService combines the operations to access, read and write blobs. This
-// can be used to describe remote blob services.
-type BlobService interface {
- BlobStatter
- BlobProvider
- BlobIngester
-}
-
-// BlobStore represent the entire suite of blob related operations. Such an
-// implementation can access, read, write, delete and serve blobs.
-type BlobStore interface {
- BlobService
- BlobServer
- BlobDeleter
-}
diff --git a/vendor/github.com/docker/distribution/circle.yml b/vendor/github.com/docker/distribution/circle.yml
deleted file mode 100644
index 61f8be0..0000000
--- a/vendor/github.com/docker/distribution/circle.yml
+++ /dev/null
@@ -1,93 +0,0 @@
-# Pony-up!
-machine:
- pre:
- # Install gvm
- - bash < <(curl -s -S -L https://raw.githubusercontent.com/moovweb/gvm/1.0.22/binscripts/gvm-installer)
- # Install codecov for coverage
- - pip install --user codecov
-
- post:
- # go
- - gvm install go1.7 --prefer-binary --name=stable
-
- environment:
- # Convenient shortcuts to "common" locations
- CHECKOUT: /home/ubuntu/$CIRCLE_PROJECT_REPONAME
- BASE_DIR: src/github.com/$CIRCLE_PROJECT_USERNAME/$CIRCLE_PROJECT_REPONAME
- # Trick circle brainflat "no absolute path" behavior
- BASE_STABLE: ../../../$HOME/.gvm/pkgsets/stable/global/$BASE_DIR
- DOCKER_BUILDTAGS: "include_oss include_gcs"
- # Workaround Circle parsing dumb bugs and/or YAML wonkyness
- CIRCLE_PAIN: "mode: set"
-
- hosts:
- # Not used yet
- fancy: 127.0.0.1
-
-dependencies:
- pre:
- # Copy the code to the gopath of all go versions
- - >
- gvm use stable &&
- mkdir -p "$(dirname $BASE_STABLE)" &&
- cp -R "$CHECKOUT" "$BASE_STABLE"
-
- override:
- # Install dependencies for every copied clone/go version
- - gvm use stable && go get github.com/tools/godep:
- pwd: $BASE_STABLE
-
- post:
- # For the stable go version, additionally install linting tools
- - >
- gvm use stable &&
- go get github.com/axw/gocov/gocov github.com/golang/lint/golint
-
-test:
- pre:
- # Output the go versions we are going to test
- # - gvm use old && go version
- - gvm use stable && go version
-
- # todo(richard): replace with a more robust vendoring solution. Removed due to a fundamental disagreement in godep philosophies.
- # Ensure validation of dependencies
- # - gvm use stable && if test -n "`git diff --stat=1000 master | grep -Ei \"vendor|godeps\"`"; then make dep-validate; fi:
- # pwd: $BASE_STABLE
-
- # First thing: build everything. This will catch compile errors, and it's
- # also necessary for go vet to work properly (see #807).
- - gvm use stable && godep go install $(go list ./... | grep -v "/vendor/"):
- pwd: $BASE_STABLE
-
- # FMT
- - gvm use stable && make fmt:
- pwd: $BASE_STABLE
-
- # VET
- - gvm use stable && make vet:
- pwd: $BASE_STABLE
-
- # LINT
- - gvm use stable && make lint:
- pwd: $BASE_STABLE
-
- override:
- # Test stable, and report
- - gvm use stable; export ROOT_PACKAGE=$(go list .); go list -tags "$DOCKER_BUILDTAGS" ./... | grep -v "/vendor/" | xargs -L 1 -I{} bash -c 'export PACKAGE={}; godep go test -tags "$DOCKER_BUILDTAGS" -test.short -coverprofile=$GOPATH/src/$PACKAGE/coverage.out -coverpkg=$(./coverpkg.sh $PACKAGE $ROOT_PACKAGE) $PACKAGE':
- timeout: 1000
- pwd: $BASE_STABLE
-
- # Test stable with race
- - gvm use stable; export ROOT_PACKAGE=$(go list .); go list -tags "$DOCKER_BUILDTAGS" ./... | grep -v "/vendor/" | grep -v "registry/handlers" | grep -v "registry/storage/driver" | xargs -L 1 -I{} bash -c 'export PACKAGE={}; godep go test -race -tags "$DOCKER_BUILDTAGS" -test.short $PACKAGE':
- timeout: 1000
- pwd: $BASE_STABLE
- post:
- # Report to codecov
- - bash <(curl -s https://codecov.io/bash):
- pwd: $BASE_STABLE
-
- ## Notes
- # Do we want these as well?
- # - go get code.google.com/p/go.tools/cmd/goimports
- # - test -z "$(goimports -l -w ./... | tee /dev/stderr)"
- # http://labix.org/gocheck
diff --git a/vendor/github.com/docker/distribution/coverpkg.sh b/vendor/github.com/docker/distribution/coverpkg.sh
deleted file mode 100755
index 25d419a..0000000
--- a/vendor/github.com/docker/distribution/coverpkg.sh
+++ /dev/null
@@ -1,7 +0,0 @@
-#!/usr/bin/env bash
-# Given a subpackage and the containing package, figures out which packages
-# need to be passed to `go test -coverpkg`: this includes all of the
-# subpackage's dependencies within the containing package, as well as the
-# subpackage itself.
-DEPENDENCIES="$(go list -f $'{{range $f := .Deps}}{{$f}}\n{{end}}' ${1} | grep ${2} | grep -v github.com/docker/distribution/vendor)"
-echo "${1} ${DEPENDENCIES}" | xargs echo -n | tr ' ' ','
diff --git a/vendor/github.com/docker/distribution/digest/digest_test.go b/vendor/github.com/docker/distribution/digest/digest_test.go
deleted file mode 100644
index afb4ebf..0000000
--- a/vendor/github.com/docker/distribution/digest/digest_test.go
+++ /dev/null
@@ -1,82 +0,0 @@
-package digest
-
-import (
- "testing"
-)
-
-func TestParseDigest(t *testing.T) {
- for _, testcase := range []struct {
- input string
- err error
- algorithm Algorithm
- hex string
- }{
- {
- input: "sha256:e58fcf7418d4390dec8e8fb69d88c06ec07039d651fedd3aa72af9972e7d046b",
- algorithm: "sha256",
- hex: "e58fcf7418d4390dec8e8fb69d88c06ec07039d651fedd3aa72af9972e7d046b",
- },
- {
- input: "sha384:d3fc7881460b7e22e3d172954463dddd7866d17597e7248453c48b3e9d26d9596bf9c4a9cf8072c9d5bad76e19af801d",
- algorithm: "sha384",
- hex: "d3fc7881460b7e22e3d172954463dddd7866d17597e7248453c48b3e9d26d9596bf9c4a9cf8072c9d5bad76e19af801d",
- },
- {
- // empty hex
- input: "sha256:",
- err: ErrDigestInvalidFormat,
- },
- {
- // just hex
- input: "d41d8cd98f00b204e9800998ecf8427e",
- err: ErrDigestInvalidFormat,
- },
- {
- // not hex
- input: "sha256:d41d8cd98f00b204e9800m98ecf8427e",
- err: ErrDigestInvalidFormat,
- },
- {
- // too short
- input: "sha256:abcdef0123456789",
- err: ErrDigestInvalidLength,
- },
- {
- // too short (from different algorithm)
- input: "sha512:abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789",
- err: ErrDigestInvalidLength,
- },
- {
- input: "foo:d41d8cd98f00b204e9800998ecf8427e",
- err: ErrDigestUnsupported,
- },
- } {
- digest, err := ParseDigest(testcase.input)
- if err != testcase.err {
- t.Fatalf("error differed from expected while parsing %q: %v != %v", testcase.input, err, testcase.err)
- }
-
- if testcase.err != nil {
- continue
- }
-
- if digest.Algorithm() != testcase.algorithm {
- t.Fatalf("incorrect algorithm for parsed digest: %q != %q", digest.Algorithm(), testcase.algorithm)
- }
-
- if digest.Hex() != testcase.hex {
- t.Fatalf("incorrect hex for parsed digest: %q != %q", digest.Hex(), testcase.hex)
- }
-
- // Parse string return value and check equality
- newParsed, err := ParseDigest(digest.String())
-
- if err != nil {
- t.Fatalf("unexpected error parsing input %q: %v", testcase.input, err)
- }
-
- if newParsed != digest {
- t.Fatalf("expected equal: %q != %q", newParsed, digest)
- }
- }
-}
diff --git a/vendor/github.com/docker/distribution/digest/digester_resumable_test.go b/vendor/github.com/docker/distribution/digest/digester_resumable_test.go
deleted file mode 100644
index 6ba21c8..0000000
--- a/vendor/github.com/docker/distribution/digest/digester_resumable_test.go
+++ /dev/null
@@ -1,21 +0,0 @@
-// +build !noresumabledigest
-
-package digest
-
-import (
- "testing"
-
- "github.com/stevvooe/resumable"
- _ "github.com/stevvooe/resumable/sha256"
-)
-
-// TestResumableDetection just ensures that the resumable capability of a hash
-// is exposed through the digester type, which is just a hash plus a Digest
-// method.
-func TestResumableDetection(t *testing.T) {
- d := Canonical.New()
-
- if _, ok := d.Hash().(resumable.Hash); !ok {
- t.Fatalf("expected digester to implement resumable.Hash: %#v, %v", d, d.Hash())
- }
-}
diff --git a/vendor/github.com/docker/distribution/digest/set_test.go b/vendor/github.com/docker/distribution/digest/set_test.go
deleted file mode 100644
index e9dab87..0000000
--- a/vendor/github.com/docker/distribution/digest/set_test.go
+++ /dev/null
@@ -1,368 +0,0 @@
-package digest
-
-import (
- "crypto/sha256"
- "encoding/binary"
- "math/rand"
- "testing"
-)
-
-func assertEqualDigests(t *testing.T, d1, d2 Digest) {
- if d1 != d2 {
- t.Fatalf("Digests do not match:\n\tActual: %s\n\tExpected: %s", d1, d2)
- }
-}
-
-func TestLookup(t *testing.T) {
- digests := []Digest{
- "sha256:1234511111111111111111111111111111111111111111111111111111111111",
- "sha256:1234111111111111111111111111111111111111111111111111111111111111",
- "sha256:1234611111111111111111111111111111111111111111111111111111111111",
- "sha256:5432111111111111111111111111111111111111111111111111111111111111",
- "sha256:6543111111111111111111111111111111111111111111111111111111111111",
- "sha256:6432111111111111111111111111111111111111111111111111111111111111",
- "sha256:6542111111111111111111111111111111111111111111111111111111111111",
- "sha256:6532111111111111111111111111111111111111111111111111111111111111",
- }
-
- dset := NewSet()
- for i := range digests {
- if err := dset.Add(digests[i]); err != nil {
- t.Fatal(err)
- }
- }
-
- dgst, err := dset.Lookup("54")
- if err != nil {
- t.Fatal(err)
- }
- assertEqualDigests(t, dgst, digests[3])
-
- dgst, err = dset.Lookup("1234")
- if err == nil {
- t.Fatal("Expected ambiguous error looking up: 1234")
- }
- if err != ErrDigestAmbiguous {
- t.Fatal(err)
- }
-
- dgst, err = dset.Lookup("9876")
- if err == nil {
- t.Fatal("Expected ambiguous error looking up: 9876")
- }
- if err != ErrDigestNotFound {
- t.Fatal(err)
- }
-
- dgst, err = dset.Lookup("sha256:1234")
- if err == nil {
- t.Fatal("Expected ambiguous error looking up: sha256:1234")
- }
- if err != ErrDigestAmbiguous {
- t.Fatal(err)
- }
-
- dgst, err = dset.Lookup("sha256:12345")
- if err != nil {
- t.Fatal(err)
- }
- assertEqualDigests(t, dgst, digests[0])
-
- dgst, err = dset.Lookup("sha256:12346")
- if err != nil {
- t.Fatal(err)
- }
- assertEqualDigests(t, dgst, digests[2])
-
- dgst, err = dset.Lookup("12346")
- if err != nil {
- t.Fatal(err)
- }
- assertEqualDigests(t, dgst, digests[2])
-
- dgst, err = dset.Lookup("12345")
- if err != nil {
- t.Fatal(err)
- }
- assertEqualDigests(t, dgst, digests[0])
-}
-
-func TestAddDuplication(t *testing.T) {
- digests := []Digest{
- "sha256:1234111111111111111111111111111111111111111111111111111111111111",
- "sha256:1234511111111111111111111111111111111111111111111111111111111111",
- "sha256:1234611111111111111111111111111111111111111111111111111111111111",
- "sha256:5432111111111111111111111111111111111111111111111111111111111111",
- "sha256:6543111111111111111111111111111111111111111111111111111111111111",
- "sha512:65431111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111",
- "sha512:65421111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111",
- "sha512:65321111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111",
- }
-
- dset := NewSet()
- for i := range digests {
- if err := dset.Add(digests[i]); err != nil {
- t.Fatal(err)
- }
- }
-
- if len(dset.entries) != 8 {
- t.Fatal("Invalid dset size")
- }
-
- if err := dset.Add(Digest("sha256:1234511111111111111111111111111111111111111111111111111111111111")); err != nil {
- t.Fatal(err)
- }
-
- if len(dset.entries) != 8 {
- t.Fatal("Duplicate digest insert allowed")
- }
-
- if err := dset.Add(Digest("sha384:123451111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111")); err != nil {
- t.Fatal(err)
- }
-
- if len(dset.entries) != 9 {
- t.Fatal("Insert with different algorithm not allowed")
- }
-}
-
-func TestRemove(t *testing.T) {
- digests, err := createDigests(10)
- if err != nil {
- t.Fatal(err)
- }
-
- dset := NewSet()
- for i := range digests {
- if err := dset.Add(digests[i]); err != nil {
- t.Fatal(err)
- }
- }
-
- dgst, err := dset.Lookup(digests[0].String())
- if err != nil {
- t.Fatal(err)
- }
- if dgst != digests[0] {
- t.Fatalf("Unexpected digest value:\n\tExpected: %s\n\tActual: %s", digests[0], dgst)
- }
-
- if err := dset.Remove(digests[0]); err != nil {
- t.Fatal(err)
- }
-
- if _, err := dset.Lookup(digests[0].String()); err != ErrDigestNotFound {
- t.Fatalf("Expected error %v when looking up removed digest, got %v", ErrDigestNotFound, err)
- }
-}
-
-func TestAll(t *testing.T) {
- digests, err := createDigests(100)
- if err != nil {
- t.Fatal(err)
- }
-
- dset := NewSet()
- for i := range digests {
- if err := dset.Add(digests[i]); err != nil {
- t.Fatal(err)
- }
- }
-
- all := map[Digest]struct{}{}
- for _, dgst := range dset.All() {
- all[dgst] = struct{}{}
- }
-
- if len(all) != len(digests) {
- t.Fatalf("Unexpected number of unique digests found:\n\tExpected: %d\n\tActual: %d", len(digests), len(all))
- }
-
- for i, dgst := range digests {
- if _, ok := all[dgst]; !ok {
- t.Fatalf("Missing element at position %d: %s", i, dgst)
- }
- }
-
-}
-
-func assertEqualShort(t *testing.T, actual, expected string) {
- if actual != expected {
- t.Fatalf("Unexpected short value:\n\tExpected: %s\n\tActual: %s", expected, actual)
- }
-}
-
-func TestShortCodeTable(t *testing.T) {
- digests := []Digest{
- "sha256:1234111111111111111111111111111111111111111111111111111111111111",
- "sha256:1234511111111111111111111111111111111111111111111111111111111111",
- "sha256:1234611111111111111111111111111111111111111111111111111111111111",
- "sha256:5432111111111111111111111111111111111111111111111111111111111111",
- "sha256:6543111111111111111111111111111111111111111111111111111111111111",
- "sha256:6432111111111111111111111111111111111111111111111111111111111111",
- "sha256:6542111111111111111111111111111111111111111111111111111111111111",
- "sha256:6532111111111111111111111111111111111111111111111111111111111111",
- }
-
- dset := NewSet()
- for i := range digests {
- if err := dset.Add(digests[i]); err != nil {
- t.Fatal(err)
- }
- }
-
- dump := ShortCodeTable(dset, 2)
-
- if len(dump) < len(digests) {
- t.Fatalf("Error unexpected size: %d, expecting %d", len(dump), len(digests))
- }
- assertEqualShort(t, dump[digests[0]], "12341")
- assertEqualShort(t, dump[digests[1]], "12345")
- assertEqualShort(t, dump[digests[2]], "12346")
- assertEqualShort(t, dump[digests[3]], "54")
- assertEqualShort(t, dump[digests[4]], "6543")
- assertEqualShort(t, dump[digests[5]], "64")
- assertEqualShort(t, dump[digests[6]], "6542")
- assertEqualShort(t, dump[digests[7]], "653")
-}
-
-func createDigests(count int) ([]Digest, error) {
- r := rand.New(rand.NewSource(25823))
- digests := make([]Digest, count)
- for i := range digests {
- h := sha256.New()
- if err := binary.Write(h, binary.BigEndian, r.Int63()); err != nil {
- return nil, err
- }
- digests[i] = NewDigest("sha256", h)
- }
- return digests, nil
-}
-
-func benchAddNTable(b *testing.B, n int) {
- digests, err := createDigests(n)
- if err != nil {
- b.Fatal(err)
- }
- b.ResetTimer()
- for i := 0; i < b.N; i++ {
- dset := &Set{entries: digestEntries(make([]*digestEntry, 0, n))}
- for j := range digests {
- if err = dset.Add(digests[j]); err != nil {
- b.Fatal(err)
- }
- }
- }
-}
-
-func benchLookupNTable(b *testing.B, n int, shortLen int) {
- digests, err := createDigests(n)
- if err != nil {
- b.Fatal(err)
- }
- dset := &Set{entries: digestEntries(make([]*digestEntry, 0, n))}
- for i := range digests {
- if err := dset.Add(digests[i]); err != nil {
- b.Fatal(err)
- }
- }
- shorts := make([]string, 0, n)
- for _, short := range ShortCodeTable(dset, shortLen) {
- shorts = append(shorts, short)
- }
-
- b.ResetTimer()
- for i := 0; i < b.N; i++ {
- if _, err = dset.Lookup(shorts[i%n]); err != nil {
- b.Fatal(err)
- }
- }
-}
-
-func benchRemoveNTable(b *testing.B, n int) {
- digests, err := createDigests(n)
- if err != nil {
- b.Fatal(err)
- }
- b.ResetTimer()
- for i := 0; i < b.N; i++ {
- dset := &Set{entries: digestEntries(make([]*digestEntry, 0, n))}
- b.StopTimer()
- for j := range digests {
- if err = dset.Add(digests[j]); err != nil {
- b.Fatal(err)
- }
- }
- b.StartTimer()
- for j := range digests {
- if err = dset.Remove(digests[j]); err != nil {
- b.Fatal(err)
- }
- }
- }
-}
-
-func benchShortCodeNTable(b *testing.B, n int, shortLen int) {
- digests, err := createDigests(n)
- if err != nil {
- b.Fatal(err)
- }
- dset := &Set{entries: digestEntries(make([]*digestEntry, 0, n))}
- for i := range digests {
- if err := dset.Add(digests[i]); err != nil {
- b.Fatal(err)
- }
- }
-
- b.ResetTimer()
- for i := 0; i < b.N; i++ {
- ShortCodeTable(dset, shortLen)
- }
-}
-
-func BenchmarkAdd10(b *testing.B) {
- benchAddNTable(b, 10)
-}
-
-func BenchmarkAdd100(b *testing.B) {
- benchAddNTable(b, 100)
-}
-
-func BenchmarkAdd1000(b *testing.B) {
- benchAddNTable(b, 1000)
-}
-
-func BenchmarkRemove10(b *testing.B) {
- benchRemoveNTable(b, 10)
-}
-
-func BenchmarkRemove100(b *testing.B) {
- benchRemoveNTable(b, 100)
-}
-
-func BenchmarkRemove1000(b *testing.B) {
- benchRemoveNTable(b, 1000)
-}
-
-func BenchmarkLookup10(b *testing.B) {
- benchLookupNTable(b, 10, 12)
-}
-
-func BenchmarkLookup100(b *testing.B) {
- benchLookupNTable(b, 100, 12)
-}
-
-func BenchmarkLookup1000(b *testing.B) {
- benchLookupNTable(b, 1000, 12)
-}
-
-func BenchmarkShortCode10(b *testing.B) {
- benchShortCodeNTable(b, 10, 12)
-}
-func BenchmarkShortCode100(b *testing.B) {
- benchShortCodeNTable(b, 100, 12)
-}
-func BenchmarkShortCode1000(b *testing.B) {
- benchShortCodeNTable(b, 1000, 12)
-}
diff --git a/vendor/github.com/docker/distribution/digest/verifiers_test.go b/vendor/github.com/docker/distribution/digest/verifiers_test.go
deleted file mode 100644
index c342d6e..0000000
--- a/vendor/github.com/docker/distribution/digest/verifiers_test.go
+++ /dev/null
@@ -1,49 +0,0 @@
-package digest
-
-import (
- "bytes"
- "crypto/rand"
- "io"
- "testing"
-)
-
-func TestDigestVerifier(t *testing.T) {
- p := make([]byte, 1<<20)
- rand.Read(p)
- digest := FromBytes(p)
-
- verifier, err := NewDigestVerifier(digest)
- if err != nil {
- t.Fatalf("unexpected error getting digest verifier: %s", err)
- }
-
- io.Copy(verifier, bytes.NewReader(p))
-
- if !verifier.Verified() {
- t.Fatalf("bytes not verified")
- }
-}
-
-// TestVerifierUnsupportedDigest ensures that unsupported digest validation is
-// flowing through verifier creation.
-func TestVerifierUnsupportedDigest(t *testing.T) {
- unsupported := Digest("bean:0123456789abcdef")
-
- _, err := NewDigestVerifier(unsupported)
- if err == nil {
- t.Fatalf("expected error when creating verifier")
- }
-
- if err != ErrDigestUnsupported {
- t.Fatalf("incorrect error for unsupported digest: %v", err)
- }
-}
-
-// TODO(stevvooe): Add benchmarks to measure bytes/second throughput for
-// DigestVerifier.
-//
-// The relevant benchmark for comparison can be run with the following
-// commands:
-//
-// go test -bench . crypto/sha1
-//
diff --git a/vendor/github.com/docker/distribution/doc.go b/vendor/github.com/docker/distribution/doc.go
deleted file mode 100644
index bdd8cb7..0000000
--- a/vendor/github.com/docker/distribution/doc.go
+++ /dev/null
@@ -1,7 +0,0 @@
-// Package distribution will define the interfaces for the components of
-// docker distribution. The goal is to allow users to reliably package, ship
-// and store content related to docker images.
-//
-// This is currently a work in progress. More details are available in the
-// README.md.
-package distribution
diff --git a/vendor/github.com/docker/distribution/errors.go b/vendor/github.com/docker/distribution/errors.go
deleted file mode 100644
index c20f281..0000000
--- a/vendor/github.com/docker/distribution/errors.go
+++ /dev/null
@@ -1,115 +0,0 @@
-package distribution
-
-import (
- "errors"
- "fmt"
- "strings"
-
- "github.com/docker/distribution/digest"
-)
-
-// ErrAccessDenied is returned when an access to a requested resource is
-// denied.
-var ErrAccessDenied = errors.New("access denied")
-
-// ErrManifestNotModified is returned when a conditional manifest GetByTag
-// returns nil due to the client indicating it has the latest version
-var ErrManifestNotModified = errors.New("manifest not modified")
-
-// ErrUnsupported is returned when an unimplemented or unsupported action is
-// performed
-var ErrUnsupported = errors.New("operation unsupported")
-
-// ErrTagUnknown is returned if the given tag is not known by the tag service
-type ErrTagUnknown struct {
- Tag string
-}
-
-func (err ErrTagUnknown) Error() string {
- return fmt.Sprintf("unknown tag=%s", err.Tag)
-}
-
-// ErrRepositoryUnknown is returned if the named repository is not known by
-// the registry.
-type ErrRepositoryUnknown struct {
- Name string
-}
-
-func (err ErrRepositoryUnknown) Error() string {
- return fmt.Sprintf("unknown repository name=%s", err.Name)
-}
-
-// ErrRepositoryNameInvalid should be used to denote an invalid repository
-// name. Reason may set, indicating the cause of invalidity.
-type ErrRepositoryNameInvalid struct {
- Name string
- Reason error
-}
-
-func (err ErrRepositoryNameInvalid) Error() string {
- return fmt.Sprintf("repository name %q invalid: %v", err.Name, err.Reason)
-}
-
-// ErrManifestUnknown is returned if the manifest is not known by the
-// registry.
-type ErrManifestUnknown struct {
- Name string
- Tag string
-}
-
-func (err ErrManifestUnknown) Error() string {
- return fmt.Sprintf("unknown manifest name=%s tag=%s", err.Name, err.Tag)
-}
-
-// ErrManifestUnknownRevision is returned when a manifest cannot be found by
-// revision within a repository.
-type ErrManifestUnknownRevision struct {
- Name string
- Revision digest.Digest
-}
-
-func (err ErrManifestUnknownRevision) Error() string {
- return fmt.Sprintf("unknown manifest name=%s revision=%s", err.Name, err.Revision)
-}
-
-// ErrManifestUnverified is returned when the registry is unable to verify
-// the manifest.
-type ErrManifestUnverified struct{}
-
-func (ErrManifestUnverified) Error() string {
- return fmt.Sprintf("unverified manifest")
-}
-
-// ErrManifestVerification provides a type to collect errors encountered
-// during manifest verification. Currently, it accepts errors of all types,
-// but it may be narrowed to those involving manifest verification.
-type ErrManifestVerification []error
-
-func (errs ErrManifestVerification) Error() string {
- var parts []string
- for _, err := range errs {
- parts = append(parts, err.Error())
- }
-
- return fmt.Sprintf("errors verifying manifest: %v", strings.Join(parts, ","))
-}
-
-// ErrManifestBlobUnknown returned when a referenced blob cannot be found.
-type ErrManifestBlobUnknown struct {
- Digest digest.Digest
-}
-
-func (err ErrManifestBlobUnknown) Error() string {
- return fmt.Sprintf("unknown blob %v on manifest", err.Digest)
-}
-
-// ErrManifestNameInvalid should be used to denote an invalid manifest
-// name. Reason may set, indicating the cause of invalidity.
-type ErrManifestNameInvalid struct {
- Name string
- Reason error
-}
-
-func (err ErrManifestNameInvalid) Error() string {
- return fmt.Sprintf("manifest name %q invalid: %v", err.Name, err.Reason)
-}
diff --git a/vendor/github.com/docker/distribution/manifests.go b/vendor/github.com/docker/distribution/manifests.go
deleted file mode 100644
index c4fb634..0000000
--- a/vendor/github.com/docker/distribution/manifests.go
+++ /dev/null
@@ -1,125 +0,0 @@
-package distribution
-
-import (
- "fmt"
- "mime"
-
- "github.com/docker/distribution/context"
- "github.com/docker/distribution/digest"
-)
-
-// Manifest represents a registry object specifying a set of
-// references and an optional target
-type Manifest interface {
- // References returns a list of objects which make up this manifest.
- // A reference is anything which can be represented by a
- // distribution.Descriptor. These can consist of layers, resources or other
- // manifests.
- //
- // While no particular order is required, implementations should return
- // them from highest to lowest priority. For example, one might want to
- // return the base layer before the top layer.
- References() []Descriptor
-
- // Payload provides the serialized format of the manifest, in addition to
- // the mediatype.
- Payload() (mediatype string, payload []byte, err error)
-}
-
-// ManifestBuilder creates a manifest allowing one to include dependencies.
-// Instances can be obtained from a version-specific manifest package. Manifest
-// specific data is passed into the function which creates the builder.
-type ManifestBuilder interface {
- // Build creates the manifest from his builder.
- Build(ctx context.Context) (Manifest, error)
-
- // References returns a list of objects which have been added to this
- // builder. The dependencies are returned in the order they were added,
- // which should be from base to head.
- References() []Descriptor
-
- // AppendReference includes the given object in the manifest after any
- // existing dependencies. If the add fails, such as when adding an
- // unsupported dependency, an error may be returned.
- //
- // The destination of the reference is dependent on the manifest type and
- // the dependency type.
- AppendReference(dependency Describable) error
-}
-
-// ManifestService describes operations on image manifests.
-type ManifestService interface {
- // Exists returns true if the manifest exists.
- Exists(ctx context.Context, dgst digest.Digest) (bool, error)
-
- // Get retrieves the manifest specified by the given digest
- Get(ctx context.Context, dgst digest.Digest, options ...ManifestServiceOption) (Manifest, error)
-
- // Put creates or updates the given manifest returning the manifest digest
- Put(ctx context.Context, manifest Manifest, options ...ManifestServiceOption) (digest.Digest, error)
-
- // Delete removes the manifest specified by the given digest. Deleting
- // a manifest that doesn't exist will return ErrManifestNotFound
- Delete(ctx context.Context, dgst digest.Digest) error
-}
-
-// ManifestEnumerator enables iterating over manifests
-type ManifestEnumerator interface {
- // Enumerate calls ingester for each manifest.
- Enumerate(ctx context.Context, ingester func(digest.Digest) error) error
-}
-
-// Describable is an interface for descriptors
-type Describable interface {
- Descriptor() Descriptor
-}
-
-// ManifestMediaTypes returns the supported media types for manifests.
-func ManifestMediaTypes() (mediaTypes []string) {
- for t := range mappings {
- if t != "" {
- mediaTypes = append(mediaTypes, t)
- }
- }
- return
-}
-
-// UnmarshalFunc implements manifest unmarshalling a given MediaType
-type UnmarshalFunc func([]byte) (Manifest, Descriptor, error)
-
-var mappings = make(map[string]UnmarshalFunc, 0)
-
-// UnmarshalManifest looks up manifest unmarshal functions based on
-// MediaType
-func UnmarshalManifest(ctHeader string, p []byte) (Manifest, Descriptor, error) {
- // Need to look up by the actual media type, not the raw contents of
- // the header. Strip semicolons and anything following them.
- var mediatype string
- if ctHeader != "" {
- var err error
- mediatype, _, err = mime.ParseMediaType(ctHeader)
- if err != nil {
- return nil, Descriptor{}, err
- }
- }
-
- unmarshalFunc, ok := mappings[mediatype]
- if !ok {
- unmarshalFunc, ok = mappings[""]
- if !ok {
- return nil, Descriptor{}, fmt.Errorf("unsupported manifest mediatype and no default available: %s", mediatype)
- }
- }
-
- return unmarshalFunc(p)
-}
-
-// RegisterManifestSchema registers an UnmarshalFunc for a given schema type. This
-// should be called from specific
-func RegisterManifestSchema(mediatype string, u UnmarshalFunc) error {
- if _, ok := mappings[mediatype]; ok {
- return fmt.Errorf("manifest mediatype registration would overwrite existing: %s", mediatype)
- }
- mappings[mediatype] = u
- return nil
-}
diff --git a/vendor/github.com/docker/distribution/reference/reference_test.go b/vendor/github.com/docker/distribution/reference/reference_test.go
deleted file mode 100644
index 405c47c..0000000
--- a/vendor/github.com/docker/distribution/reference/reference_test.go
+++ /dev/null
@@ -1,661 +0,0 @@
-package reference
-
-import (
- "encoding/json"
- "strconv"
- "strings"
- "testing"
-
- "github.com/docker/distribution/digest"
-)
-
-func TestReferenceParse(t *testing.T) {
- // referenceTestcases is a unified set of testcases for
- // testing the parsing of references
- referenceTestcases := []struct {
- // input is the repository name or name component testcase
- input string
- // err is the error expected from Parse, or nil
- err error
- // repository is the string representation for the reference
- repository string
- // hostname is the hostname expected in the reference
- hostname string
- // tag is the tag for the reference
- tag string
- // digest is the digest for the reference (enforces digest reference)
- digest string
- }{
- {
- input: "test_com",
- repository: "test_com",
- },
- {
- input: "test.com:tag",
- repository: "test.com",
- tag: "tag",
- },
- {
- input: "test.com:5000",
- repository: "test.com",
- tag: "5000",
- },
- {
- input: "test.com/repo:tag",
- hostname: "test.com",
- repository: "test.com/repo",
- tag: "tag",
- },
- {
- input: "test:5000/repo",
- hostname: "test:5000",
- repository: "test:5000/repo",
- },
- {
- input: "test:5000/repo:tag",
- hostname: "test:5000",
- repository: "test:5000/repo",
- tag: "tag",
- },
- {
- input: "test:5000/repo@sha256:ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
- hostname: "test:5000",
- repository: "test:5000/repo",
- digest: "sha256:ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
- },
- {
- input: "test:5000/repo:tag@sha256:ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
- hostname: "test:5000",
- repository: "test:5000/repo",
- tag: "tag",
- digest: "sha256:ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
- },
- {
- input: "test:5000/repo",
- hostname: "test:5000",
- repository: "test:5000/repo",
- },
- {
- input: "",
- err: ErrNameEmpty,
- },
- {
- input: ":justtag",
- err: ErrReferenceInvalidFormat,
- },
- {
- input: "@sha256:ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
- err: ErrReferenceInvalidFormat,
- },
- {
- input: "repo@sha256:ffffffffffffffffffffffffffffffffff",
- err: digest.ErrDigestInvalidLength,
- },
- {
- input: "validname@invaliddigest:ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
- err: digest.ErrDigestUnsupported,
- },
- {
- input: "Uppercase:tag",
- err: ErrNameContainsUppercase,
- },
- // FIXME "Uppercase" is incorrectly handled as a domain-name here, therefore passes.
- // See https://github.com/docker/distribution/pull/1778, and https://github.com/docker/docker/pull/20175
- //{
- // input: "Uppercase/lowercase:tag",
- // err: ErrNameContainsUppercase,
- //},
- {
- input: "test:5000/Uppercase/lowercase:tag",
- err: ErrNameContainsUppercase,
- },
- {
- input: "lowercase:Uppercase",
- repository: "lowercase",
- tag: "Uppercase",
- },
- {
- input: strings.Repeat("a/", 128) + "a:tag",
- err: ErrNameTooLong,
- },
- {
- input: strings.Repeat("a/", 127) + "a:tag-puts-this-over-max",
- hostname: "a",
- repository: strings.Repeat("a/", 127) + "a",
- tag: "tag-puts-this-over-max",
- },
- {
- input: "aa/asdf$$^/aa",
- err: ErrReferenceInvalidFormat,
- },
- {
- input: "sub-dom1.foo.com/bar/baz/quux",
- hostname: "sub-dom1.foo.com",
- repository: "sub-dom1.foo.com/bar/baz/quux",
- },
- {
- input: "sub-dom1.foo.com/bar/baz/quux:some-long-tag",
- hostname: "sub-dom1.foo.com",
- repository: "sub-dom1.foo.com/bar/baz/quux",
- tag: "some-long-tag",
- },
- {
- input: "b.gcr.io/test.example.com/my-app:test.example.com",
- hostname: "b.gcr.io",
- repository: "b.gcr.io/test.example.com/my-app",
- tag: "test.example.com",
- },
- {
- input: "xn--n3h.com/myimage:xn--n3h.com", // ☃.com in punycode
- hostname: "xn--n3h.com",
- repository: "xn--n3h.com/myimage",
- tag: "xn--n3h.com",
- },
- {
- input: "xn--7o8h.com/myimage:xn--7o8h.com@sha512:ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", // 🐳.com in punycode
- hostname: "xn--7o8h.com",
- repository: "xn--7o8h.com/myimage",
- tag: "xn--7o8h.com",
- digest: "sha512:ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
- },
- {
- input: "foo_bar.com:8080",
- repository: "foo_bar.com",
- tag: "8080",
- },
- {
- input: "foo/foo_bar.com:8080",
- hostname: "foo",
- repository: "foo/foo_bar.com",
- tag: "8080",
- },
- }
- for _, testcase := range referenceTestcases {
- failf := func(format string, v ...interface{}) {
- t.Logf(strconv.Quote(testcase.input)+": "+format, v...)
- t.Fail()
- }
-
- repo, err := Parse(testcase.input)
- if testcase.err != nil {
- if err == nil {
- failf("missing expected error: %v", testcase.err)
- } else if testcase.err != err {
- failf("mismatched error: got %v, expected %v", err, testcase.err)
- }
- continue
- } else if err != nil {
- failf("unexpected parse error: %v", err)
- continue
- }
- if repo.String() != testcase.input {
- failf("mismatched repo: got %q, expected %q", repo.String(), testcase.input)
- }
-
- if named, ok := repo.(Named); ok {
- if named.Name() != testcase.repository {
- failf("unexpected repository: got %q, expected %q", named.Name(), testcase.repository)
- }
- hostname, _ := SplitHostname(named)
- if hostname != testcase.hostname {
- failf("unexpected hostname: got %q, expected %q", hostname, testcase.hostname)
- }
- } else if testcase.repository != "" || testcase.hostname != "" {
- failf("expected named type, got %T", repo)
- }
-
- tagged, ok := repo.(Tagged)
- if testcase.tag != "" {
- if ok {
- if tagged.Tag() != testcase.tag {
- failf("unexpected tag: got %q, expected %q", tagged.Tag(), testcase.tag)
- }
- } else {
- failf("expected tagged type, got %T", repo)
- }
- } else if ok {
- failf("unexpected tagged type")
- }
-
- digested, ok := repo.(Digested)
- if testcase.digest != "" {
- if ok {
- if digested.Digest().String() != testcase.digest {
- failf("unexpected digest: got %q, expected %q", digested.Digest().String(), testcase.digest)
- }
- } else {
- failf("expected digested type, got %T", repo)
- }
- } else if ok {
- failf("unexpected digested type")
- }
-
- }
-}
-
-// TestWithNameFailure tests cases where WithName should fail. Cases where it
-// should succeed are covered by TestSplitHostname, below.
-func TestWithNameFailure(t *testing.T) {
- testcases := []struct {
- input string
- err error
- }{
- {
- input: "",
- err: ErrNameEmpty,
- },
- {
- input: ":justtag",
- err: ErrReferenceInvalidFormat,
- },
- {
- input: "@sha256:ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
- err: ErrReferenceInvalidFormat,
- },
- {
- input: "validname@invaliddigest:ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
- err: ErrReferenceInvalidFormat,
- },
- {
- input: strings.Repeat("a/", 128) + "a:tag",
- err: ErrNameTooLong,
- },
- {
- input: "aa/asdf$$^/aa",
- err: ErrReferenceInvalidFormat,
- },
- }
- for _, testcase := range testcases {
- failf := func(format string, v ...interface{}) {
- t.Logf(strconv.Quote(testcase.input)+": "+format, v...)
- t.Fail()
- }
-
- _, err := WithName(testcase.input)
- if err == nil {
- failf("no error parsing name. expected: %s", testcase.err)
- }
- }
-}
-
-func TestSplitHostname(t *testing.T) {
- testcases := []struct {
- input string
- hostname string
- name string
- }{
- {
- input: "test.com/foo",
- hostname: "test.com",
- name: "foo",
- },
- {
- input: "test_com/foo",
- hostname: "",
- name: "test_com/foo",
- },
- {
- input: "test:8080/foo",
- hostname: "test:8080",
- name: "foo",
- },
- {
- input: "test.com:8080/foo",
- hostname: "test.com:8080",
- name: "foo",
- },
- {
- input: "test-com:8080/foo",
- hostname: "test-com:8080",
- name: "foo",
- },
- {
- input: "xn--n3h.com:18080/foo",
- hostname: "xn--n3h.com:18080",
- name: "foo",
- },
- }
- for _, testcase := range testcases {
- failf := func(format string, v ...interface{}) {
- t.Logf(strconv.Quote(testcase.input)+": "+format, v...)
- t.Fail()
- }
-
- named, err := WithName(testcase.input)
- if err != nil {
- failf("error parsing name: %s", err)
- }
- hostname, name := SplitHostname(named)
- if hostname != testcase.hostname {
- failf("unexpected hostname: got %q, expected %q", hostname, testcase.hostname)
- }
- if name != testcase.name {
- failf("unexpected name: got %q, expected %q", name, testcase.name)
- }
- }
-}
-
-type serializationType struct {
- Description string
- Field Field
-}
-
-func TestSerialization(t *testing.T) {
- testcases := []struct {
- description string
- input string
- name string
- tag string
- digest string
- err error
- }{
- {
- description: "empty value",
- err: ErrNameEmpty,
- },
- {
- description: "just a name",
- input: "example.com:8000/named",
- name: "example.com:8000/named",
- },
- {
- description: "name with a tag",
- input: "example.com:8000/named:tagged",
- name: "example.com:8000/named",
- tag: "tagged",
- },
- {
- description: "name with digest",
- input: "other.com/named@sha256:1234567890098765432112345667890098765432112345667890098765432112",
- name: "other.com/named",
- digest: "sha256:1234567890098765432112345667890098765432112345667890098765432112",
- },
- }
- for _, testcase := range testcases {
- failf := func(format string, v ...interface{}) {
- t.Logf(strconv.Quote(testcase.input)+": "+format, v...)
- t.Fail()
- }
-
- m := map[string]string{
- "Description": testcase.description,
- "Field": testcase.input,
- }
- b, err := json.Marshal(m)
- if err != nil {
- failf("error marshalling: %v", err)
- }
- t := serializationType{}
-
- if err := json.Unmarshal(b, &t); err != nil {
- if testcase.err == nil {
- failf("error unmarshalling: %v", err)
- }
- if err != testcase.err {
- failf("wrong error, expected %v, got %v", testcase.err, err)
- }
-
- continue
- } else if testcase.err != nil {
- failf("expected error unmarshalling: %v", testcase.err)
- }
-
- if t.Description != testcase.description {
- failf("wrong description, expected %q, got %q", testcase.description, t.Description)
- }
-
- ref := t.Field.Reference()
-
- if named, ok := ref.(Named); ok {
- if named.Name() != testcase.name {
- failf("unexpected repository: got %q, expected %q", named.Name(), testcase.name)
- }
- } else if testcase.name != "" {
- failf("expected named type, got %T", ref)
- }
-
- tagged, ok := ref.(Tagged)
- if testcase.tag != "" {
- if ok {
- if tagged.Tag() != testcase.tag {
- failf("unexpected tag: got %q, expected %q", tagged.Tag(), testcase.tag)
- }
- } else {
- failf("expected tagged type, got %T", ref)
- }
- } else if ok {
- failf("unexpected tagged type")
- }
-
- digested, ok := ref.(Digested)
- if testcase.digest != "" {
- if ok {
- if digested.Digest().String() != testcase.digest {
- failf("unexpected digest: got %q, expected %q", digested.Digest().String(), testcase.digest)
- }
- } else {
- failf("expected digested type, got %T", ref)
- }
- } else if ok {
- failf("unexpected digested type")
- }
-
- t = serializationType{
- Description: testcase.description,
- Field: AsField(ref),
- }
-
- b2, err := json.Marshal(t)
- if err != nil {
- failf("error marshing serialization type: %v", err)
- }
-
- if string(b) != string(b2) {
- failf("unexpected serialized value: expected %q, got %q", string(b), string(b2))
- }
-
- // Ensure t.Field is not implementing "Reference" directly, getting
- // around the Reference type system
- var fieldInterface interface{} = t.Field
- if _, ok := fieldInterface.(Reference); ok {
- failf("field should not implement Reference interface")
- }
-
- }
-}
-
-func TestWithTag(t *testing.T) {
- testcases := []struct {
- name string
- digest digest.Digest
- tag string
- combined string
- }{
- {
- name: "test.com/foo",
- tag: "tag",
- combined: "test.com/foo:tag",
- },
- {
- name: "foo",
- tag: "tag2",
- combined: "foo:tag2",
- },
- {
- name: "test.com:8000/foo",
- tag: "tag4",
- combined: "test.com:8000/foo:tag4",
- },
- {
- name: "test.com:8000/foo",
- tag: "TAG5",
- combined: "test.com:8000/foo:TAG5",
- },
- {
- name: "test.com:8000/foo",
- digest: "sha256:1234567890098765432112345667890098765",
- tag: "TAG5",
- combined: "test.com:8000/foo:TAG5@sha256:1234567890098765432112345667890098765",
- },
- }
- for _, testcase := range testcases {
- failf := func(format string, v ...interface{}) {
- t.Logf(strconv.Quote(testcase.name)+": "+format, v...)
- t.Fail()
- }
-
- named, err := WithName(testcase.name)
- if err != nil {
- failf("error parsing name: %s", err)
- }
- if testcase.digest != "" {
- canonical, err := WithDigest(named, testcase.digest)
- if err != nil {
- failf("error adding digest")
- }
- named = canonical
- }
-
- tagged, err := WithTag(named, testcase.tag)
- if err != nil {
- failf("WithTag failed: %s", err)
- }
- if tagged.String() != testcase.combined {
- failf("unexpected: got %q, expected %q", tagged.String(), testcase.combined)
- }
- }
-}
-
-func TestWithDigest(t *testing.T) {
- testcases := []struct {
- name string
- digest digest.Digest
- tag string
- combined string
- }{
- {
- name: "test.com/foo",
- digest: "sha256:1234567890098765432112345667890098765",
- combined: "test.com/foo@sha256:1234567890098765432112345667890098765",
- },
- {
- name: "foo",
- digest: "sha256:1234567890098765432112345667890098765",
- combined: "foo@sha256:1234567890098765432112345667890098765",
- },
- {
- name: "test.com:8000/foo",
- digest: "sha256:1234567890098765432112345667890098765",
- combined: "test.com:8000/foo@sha256:1234567890098765432112345667890098765",
- },
- {
- name: "test.com:8000/foo",
- digest: "sha256:1234567890098765432112345667890098765",
- tag: "latest",
- combined: "test.com:8000/foo:latest@sha256:1234567890098765432112345667890098765",
- },
- }
- for _, testcase := range testcases {
- failf := func(format string, v ...interface{}) {
- t.Logf(strconv.Quote(testcase.name)+": "+format, v...)
- t.Fail()
- }
-
- named, err := WithName(testcase.name)
- if err != nil {
- failf("error parsing name: %s", err)
- }
- if testcase.tag != "" {
- tagged, err := WithTag(named, testcase.tag)
- if err != nil {
- failf("error adding tag")
- }
- named = tagged
- }
- digested, err := WithDigest(named, testcase.digest)
- if err != nil {
- failf("WithDigest failed: %s", err)
- }
- if digested.String() != testcase.combined {
- failf("unexpected: got %q, expected %q", digested.String(), testcase.combined)
- }
- }
-}
-
-func TestMatchError(t *testing.T) {
- named, err := Parse("foo")
- if err != nil {
- t.Fatal(err)
- }
- _, err = Match("[-x]", named)
- if err == nil {
- t.Fatalf("expected an error, got nothing")
- }
-}
-
-func TestMatch(t *testing.T) {
- matchCases := []struct {
- reference string
- pattern string
- expected bool
- }{
- {
- reference: "foo",
- pattern: "foo/**/ba[rz]",
- expected: false,
- },
- {
- reference: "foo/any/bat",
- pattern: "foo/**/ba[rz]",
- expected: false,
- },
- {
- reference: "foo/a/bar",
- pattern: "foo/**/ba[rz]",
- expected: true,
- },
- {
- reference: "foo/b/baz",
- pattern: "foo/**/ba[rz]",
- expected: true,
- },
- {
- reference: "foo/c/baz:tag",
- pattern: "foo/**/ba[rz]",
- expected: true,
- },
- {
- reference: "foo/c/baz:tag",
- pattern: "foo/*/baz:tag",
- expected: true,
- },
- {
- reference: "foo/c/baz:tag",
- pattern: "foo/c/baz:tag",
- expected: true,
- },
- {
- reference: "example.com/foo/c/baz:tag",
- pattern: "*/foo/c/baz",
- expected: true,
- },
- {
- reference: "example.com/foo/c/baz:tag",
- pattern: "example.com/foo/c/baz",
- expected: true,
- },
- }
- for _, c := range matchCases {
- named, err := Parse(c.reference)
- if err != nil {
- t.Fatal(err)
- }
- actual, err := Match(c.pattern, named)
- if err != nil {
- t.Fatal(err)
- }
- if actual != c.expected {
- t.Fatalf("expected %s match %s to be %v, was %v", c.reference, c.pattern, c.expected, actual)
- }
- }
-}
diff --git a/vendor/github.com/docker/distribution/reference/regexp_test.go b/vendor/github.com/docker/distribution/reference/regexp_test.go
deleted file mode 100644
index 2ec3937..0000000
--- a/vendor/github.com/docker/distribution/reference/regexp_test.go
+++ /dev/null
@@ -1,489 +0,0 @@
-package reference
-
-import (
- "regexp"
- "strings"
- "testing"
-)
-
-type regexpMatch struct {
- input string
- match bool
- subs []string
-}
-
-func checkRegexp(t *testing.T, r *regexp.Regexp, m regexpMatch) {
- matches := r.FindStringSubmatch(m.input)
- if m.match && matches != nil {
- if len(matches) != (r.NumSubexp()+1) || matches[0] != m.input {
- t.Fatalf("Bad match result %#v for %q", matches, m.input)
- }
- if len(matches) < (len(m.subs) + 1) {
- t.Errorf("Expected %d sub matches, only have %d for %q", len(m.subs), len(matches)-1, m.input)
- }
- for i := range m.subs {
- if m.subs[i] != matches[i+1] {
- t.Errorf("Unexpected submatch %d: %q, expected %q for %q", i+1, matches[i+1], m.subs[i], m.input)
- }
- }
- } else if m.match {
- t.Errorf("Expected match for %q", m.input)
- } else if matches != nil {
- t.Errorf("Unexpected match for %q", m.input)
- }
-}
-
-func TestHostRegexp(t *testing.T) {
- hostcases := []regexpMatch{
- {
- input: "test.com",
- match: true,
- },
- {
- input: "test.com:10304",
- match: true,
- },
- {
- input: "test.com:http",
- match: false,
- },
- {
- input: "localhost",
- match: true,
- },
- {
- input: "localhost:8080",
- match: true,
- },
- {
- input: "a",
- match: true,
- },
- {
- input: "a.b",
- match: true,
- },
- {
- input: "ab.cd.com",
- match: true,
- },
- {
- input: "a-b.com",
- match: true,
- },
- {
- input: "-ab.com",
- match: false,
- },
- {
- input: "ab-.com",
- match: false,
- },
- {
- input: "ab.c-om",
- match: true,
- },
- {
- input: "ab.-com",
- match: false,
- },
- {
- input: "ab.com-",
- match: false,
- },
- {
- input: "0101.com",
- match: true, // TODO(dmcgowan): valid if this should be allowed
- },
- {
- input: "001a.com",
- match: true,
- },
- {
- input: "b.gbc.io:443",
- match: true,
- },
- {
- input: "b.gbc.io",
- match: true,
- },
- {
- input: "xn--n3h.com", // ☃.com in punycode
- match: true,
- },
- {
- input: "Asdf.com", // uppercase character
- match: true,
- },
- }
- r := regexp.MustCompile(`^` + hostnameRegexp.String() + `$`)
- for i := range hostcases {
- checkRegexp(t, r, hostcases[i])
- }
-}
-
-func TestFullNameRegexp(t *testing.T) {
- if anchoredNameRegexp.NumSubexp() != 2 {
- t.Fatalf("anchored name regexp should have two submatches: %v, %v != 2",
- anchoredNameRegexp, anchoredNameRegexp.NumSubexp())
- }
-
- testcases := []regexpMatch{
- {
- input: "",
- match: false,
- },
- {
- input: "short",
- match: true,
- subs: []string{"", "short"},
- },
- {
- input: "simple/name",
- match: true,
- subs: []string{"simple", "name"},
- },
- {
- input: "library/ubuntu",
- match: true,
- subs: []string{"library", "ubuntu"},
- },
- {
- input: "docker/stevvooe/app",
- match: true,
- subs: []string{"docker", "stevvooe/app"},
- },
- {
- input: "aa/aa/aa/aa/aa/aa/aa/aa/aa/bb/bb/bb/bb/bb/bb",
- match: true,
- subs: []string{"aa", "aa/aa/aa/aa/aa/aa/aa/aa/bb/bb/bb/bb/bb/bb"},
- },
- {
- input: "aa/aa/bb/bb/bb",
- match: true,
- subs: []string{"aa", "aa/bb/bb/bb"},
- },
- {
- input: "a/a/a/a",
- match: true,
- subs: []string{"a", "a/a/a"},
- },
- {
- input: "a/a/a/a/",
- match: false,
- },
- {
- input: "a//a/a",
- match: false,
- },
- {
- input: "a",
- match: true,
- subs: []string{"", "a"},
- },
- {
- input: "a/aa",
- match: true,
- subs: []string{"a", "aa"},
- },
- {
- input: "a/aa/a",
- match: true,
- subs: []string{"a", "aa/a"},
- },
- {
- input: "foo.com",
- match: true,
- subs: []string{"", "foo.com"},
- },
- {
- input: "foo.com/",
- match: false,
- },
- {
- input: "foo.com:8080/bar",
- match: true,
- subs: []string{"foo.com:8080", "bar"},
- },
- {
- input: "foo.com:http/bar",
- match: false,
- },
- {
- input: "foo.com/bar",
- match: true,
- subs: []string{"foo.com", "bar"},
- },
- {
- input: "foo.com/bar/baz",
- match: true,
- subs: []string{"foo.com", "bar/baz"},
- },
- {
- input: "localhost:8080/bar",
- match: true,
- subs: []string{"localhost:8080", "bar"},
- },
- {
- input: "sub-dom1.foo.com/bar/baz/quux",
- match: true,
- subs: []string{"sub-dom1.foo.com", "bar/baz/quux"},
- },
- {
- input: "blog.foo.com/bar/baz",
- match: true,
- subs: []string{"blog.foo.com", "bar/baz"},
- },
- {
- input: "a^a",
- match: false,
- },
- {
- input: "aa/asdf$$^/aa",
- match: false,
- },
- {
- input: "asdf$$^/aa",
- match: false,
- },
- {
- input: "aa-a/a",
- match: true,
- subs: []string{"aa-a", "a"},
- },
- {
- input: strings.Repeat("a/", 128) + "a",
- match: true,
- subs: []string{"a", strings.Repeat("a/", 127) + "a"},
- },
- {
- input: "a-/a/a/a",
- match: false,
- },
- {
- input: "foo.com/a-/a/a",
- match: false,
- },
- {
- input: "-foo/bar",
- match: false,
- },
- {
- input: "foo/bar-",
- match: false,
- },
- {
- input: "foo-/bar",
- match: false,
- },
- {
- input: "foo/-bar",
- match: false,
- },
- {
- input: "_foo/bar",
- match: false,
- },
- {
- input: "foo_bar",
- match: true,
- subs: []string{"", "foo_bar"},
- },
- {
- input: "foo_bar.com",
- match: true,
- subs: []string{"", "foo_bar.com"},
- },
- {
- input: "foo_bar.com:8080",
- match: false,
- },
- {
- input: "foo_bar.com:8080/app",
- match: false,
- },
- {
- input: "foo.com/foo_bar",
- match: true,
- subs: []string{"foo.com", "foo_bar"},
- },
- {
- input: "____/____",
- match: false,
- },
- {
- input: "_docker/_docker",
- match: false,
- },
- {
- input: "docker_/docker_",
- match: false,
- },
- {
- input: "b.gcr.io/test.example.com/my-app",
- match: true,
- subs: []string{"b.gcr.io", "test.example.com/my-app"},
- },
- {
- input: "xn--n3h.com/myimage", // ☃.com in punycode
- match: true,
- subs: []string{"xn--n3h.com", "myimage"},
- },
- {
- input: "xn--7o8h.com/myimage", // 🐳.com in punycode
- match: true,
- subs: []string{"xn--7o8h.com", "myimage"},
- },
- {
- input: "example.com/xn--7o8h.com/myimage", // 🐳.com in punycode
- match: true,
- subs: []string{"example.com", "xn--7o8h.com/myimage"},
- },
- {
- input: "example.com/some_separator__underscore/myimage",
- match: true,
- subs: []string{"example.com", "some_separator__underscore/myimage"},
- },
- {
- input: "example.com/__underscore/myimage",
- match: false,
- },
- {
- input: "example.com/..dots/myimage",
- match: false,
- },
- {
- input: "example.com/.dots/myimage",
- match: false,
- },
- {
- input: "example.com/nodouble..dots/myimage",
- match: false,
- },
- {
- input: "example.com/nodouble..dots/myimage",
- match: false,
- },
- {
- input: "docker./docker",
- match: false,
- },
- {
- input: ".docker/docker",
- match: false,
- },
- {
- input: "docker-/docker",
- match: false,
- },
- {
- input: "-docker/docker",
- match: false,
- },
- {
- input: "do..cker/docker",
- match: false,
- },
- {
- input: "do__cker:8080/docker",
- match: false,
- },
- {
- input: "do__cker/docker",
- match: true,
- subs: []string{"", "do__cker/docker"},
- },
- {
- input: "b.gcr.io/test.example.com/my-app",
- match: true,
- subs: []string{"b.gcr.io", "test.example.com/my-app"},
- },
- {
- input: "registry.io/foo/project--id.module--name.ver---sion--name",
- match: true,
- subs: []string{"registry.io", "foo/project--id.module--name.ver---sion--name"},
- },
- {
- input: "Asdf.com/foo/bar", // uppercase character in hostname
- match: true,
- },
- {
- input: "Foo/FarB", // uppercase characters in remote name
- match: false,
- },
- }
- for i := range testcases {
- checkRegexp(t, anchoredNameRegexp, testcases[i])
- }
-}
-
-func TestReferenceRegexp(t *testing.T) {
- if ReferenceRegexp.NumSubexp() != 3 {
- t.Fatalf("anchored name regexp should have three submatches: %v, %v != 3",
- ReferenceRegexp, ReferenceRegexp.NumSubexp())
- }
-
- testcases := []regexpMatch{
- {
- input: "registry.com:8080/myapp:tag",
- match: true,
- subs: []string{"registry.com:8080/myapp", "tag", ""},
- },
- {
- input: "registry.com:8080/myapp@sha256:be178c0543eb17f5f3043021c9e5fcf30285e557a4fc309cce97ff9ca6182912",
- match: true,
- subs: []string{"registry.com:8080/myapp", "", "sha256:be178c0543eb17f5f3043021c9e5fcf30285e557a4fc309cce97ff9ca6182912"},
- },
- {
- input: "registry.com:8080/myapp:tag2@sha256:be178c0543eb17f5f3043021c9e5fcf30285e557a4fc309cce97ff9ca6182912",
- match: true,
- subs: []string{"registry.com:8080/myapp", "tag2", "sha256:be178c0543eb17f5f3043021c9e5fcf30285e557a4fc309cce97ff9ca6182912"},
- },
- {
- input: "registry.com:8080/myapp@sha256:badbadbadbad",
- match: false,
- },
- {
- input: "registry.com:8080/myapp:invalid~tag",
- match: false,
- },
- {
- input: "bad_hostname.com:8080/myapp:tag",
- match: false,
- },
- {
- input:// localhost treated as name, missing tag with 8080 as tag
- "localhost:8080@sha256:be178c0543eb17f5f3043021c9e5fcf30285e557a4fc309cce97ff9ca6182912",
- match: true,
- subs: []string{"localhost", "8080", "sha256:be178c0543eb17f5f3043021c9e5fcf30285e557a4fc309cce97ff9ca6182912"},
- },
- {
- input: "localhost:8080/name@sha256:be178c0543eb17f5f3043021c9e5fcf30285e557a4fc309cce97ff9ca6182912",
- match: true,
- subs: []string{"localhost:8080/name", "", "sha256:be178c0543eb17f5f3043021c9e5fcf30285e557a4fc309cce97ff9ca6182912"},
- },
- {
- input: "localhost:http/name@sha256:be178c0543eb17f5f3043021c9e5fcf30285e557a4fc309cce97ff9ca6182912",
- match: false,
- },
- {
- // localhost will be treated as an image name without a host
- input: "localhost@sha256:be178c0543eb17f5f3043021c9e5fcf30285e557a4fc309cce97ff9ca6182912",
- match: true,
- subs: []string{"localhost", "", "sha256:be178c0543eb17f5f3043021c9e5fcf30285e557a4fc309cce97ff9ca6182912"},
- },
- {
- input: "registry.com:8080/myapp@bad",
- match: false,
- },
- {
- input: "registry.com:8080/myapp@2bad",
- match: false, // TODO(dmcgowan): Support this as valid
- },
- }
-
- for i := range testcases {
- checkRegexp(t, ReferenceRegexp, testcases[i])
- }
-
-}
diff --git a/vendor/github.com/docker/distribution/registry.go b/vendor/github.com/docker/distribution/registry.go
deleted file mode 100644
index 1ede31e..0000000
--- a/vendor/github.com/docker/distribution/registry.go
+++ /dev/null
@@ -1,97 +0,0 @@
-package distribution
-
-import (
- "github.com/docker/distribution/context"
- "github.com/docker/distribution/reference"
-)
-
-// Scope defines the set of items that match a namespace.
-type Scope interface {
- // Contains returns true if the name belongs to the namespace.
- Contains(name string) bool
-}
-
-type fullScope struct{}
-
-func (f fullScope) Contains(string) bool {
- return true
-}
-
-// GlobalScope represents the full namespace scope which contains
-// all other scopes.
-var GlobalScope = Scope(fullScope{})
-
-// Namespace represents a collection of repositories, addressable by name.
-// Generally, a namespace is backed by a set of one or more services,
-// providing facilities such as registry access, trust, and indexing.
-type Namespace interface {
- // Scope describes the names that can be used with this Namespace. The
- // global namespace will have a scope that matches all names. The scope
- // effectively provides an identity for the namespace.
- Scope() Scope
-
- // Repository should return a reference to the named repository. The
- // registry may or may not have the repository but should always return a
- // reference.
- Repository(ctx context.Context, name reference.Named) (Repository, error)
-
- // Repositories fills 'repos' with a lexigraphically sorted catalog of repositories
- // up to the size of 'repos' and returns the value 'n' for the number of entries
- // which were filled. 'last' contains an offset in the catalog, and 'err' will be
- // set to io.EOF if there are no more entries to obtain.
- Repositories(ctx context.Context, repos []string, last string) (n int, err error)
-
- // Blobs returns a blob enumerator to access all blobs
- Blobs() BlobEnumerator
-
- // BlobStatter returns a BlobStatter to control
- BlobStatter() BlobStatter
-}
-
-// RepositoryEnumerator describes an operation to enumerate repositories
-type RepositoryEnumerator interface {
- Enumerate(ctx context.Context, ingester func(string) error) error
-}
-
-// ManifestServiceOption is a function argument for Manifest Service methods
-type ManifestServiceOption interface {
- Apply(ManifestService) error
-}
-
-// WithTag allows a tag to be passed into Put
-func WithTag(tag string) ManifestServiceOption {
- return WithTagOption{tag}
-}
-
-// WithTagOption holds a tag
-type WithTagOption struct{ Tag string }
-
-// Apply conforms to the ManifestServiceOption interface
-func (o WithTagOption) Apply(m ManifestService) error {
- // no implementation
- return nil
-}
-
-// Repository is a named collection of manifests and layers.
-type Repository interface {
- // Named returns the name of the repository.
- Named() reference.Named
-
- // Manifests returns a reference to this repository's manifest service.
- // with the supplied options applied.
- Manifests(ctx context.Context, options ...ManifestServiceOption) (ManifestService, error)
-
- // Blobs returns a reference to this repository's blob service.
- Blobs(ctx context.Context) BlobStore
-
- // TODO(stevvooe): The above BlobStore return can probably be relaxed to
- // be a BlobService for use with clients. This will allow such
- // implementations to avoid implementing ServeBlob.
-
- // Tags returns a reference to this repositories tag service
- Tags(ctx context.Context) TagService
-}
-
-// TODO(stevvooe): Must add close methods to all these. May want to change the
-// way instances are created to better reflect internal dependency
-// relationships.
diff --git a/vendor/github.com/docker/distribution/tags.go b/vendor/github.com/docker/distribution/tags.go
deleted file mode 100644
index 5030565..0000000
--- a/vendor/github.com/docker/distribution/tags.go
+++ /dev/null
@@ -1,27 +0,0 @@
-package distribution
-
-import (
- "github.com/docker/distribution/context"
-)
-
-// TagService provides access to information about tagged objects.
-type TagService interface {
- // Get retrieves the descriptor identified by the tag. Some
- // implementations may differentiate between "trusted" tags and
- // "untrusted" tags. If a tag is "untrusted", the mapping will be returned
- // as an ErrTagUntrusted error, with the target descriptor.
- Get(ctx context.Context, tag string) (Descriptor, error)
-
- // Tag associates the tag with the provided descriptor, updating the
- // current association, if needed.
- Tag(ctx context.Context, tag string, desc Descriptor) error
-
- // Untag removes the given tag association
- Untag(ctx context.Context, tag string) error
-
- // All returns the set of tags managed by this tag service
- All(ctx context.Context) ([]string, error)
-
- // Lookup returns the set of tags referencing the given digest.
- Lookup(ctx context.Context, digest Descriptor) ([]string, error)
-}
diff --git a/vendor/github.com/ghodss/yaml/LICENSE b/vendor/github.com/ghodss/yaml/LICENSE
new file mode 100644
index 0000000..7805d36
--- /dev/null
+++ b/vendor/github.com/ghodss/yaml/LICENSE
@@ -0,0 +1,50 @@
+The MIT License (MIT)
+
+Copyright (c) 2014 Sam Ghods
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+
+Copyright (c) 2012 The Go Authors. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+ * Redistributions of source code must retain the above copyright
+notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above
+copyright notice, this list of conditions and the following disclaimer
+in the documentation and/or other materials provided with the
+distribution.
+ * Neither the name of Google Inc. nor the names of its
+contributors may be used to endorse or promote products derived from
+this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/vendor/github.com/ghodss/yaml/fields.go b/vendor/github.com/ghodss/yaml/fields.go
new file mode 100644
index 0000000..5860074
--- /dev/null
+++ b/vendor/github.com/ghodss/yaml/fields.go
@@ -0,0 +1,501 @@
+// Copyright 2013 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+package yaml
+
+import (
+ "bytes"
+ "encoding"
+ "encoding/json"
+ "reflect"
+ "sort"
+ "strings"
+ "sync"
+ "unicode"
+ "unicode/utf8"
+)
+
+// indirect walks down v allocating pointers as needed,
+// until it gets to a non-pointer.
+// if it encounters an Unmarshaler, indirect stops and returns that.
+// if decodingNull is true, indirect stops at the last pointer so it can be set to nil.
+func indirect(v reflect.Value, decodingNull bool) (json.Unmarshaler, encoding.TextUnmarshaler, reflect.Value) {
+ // If v is a named type and is addressable,
+ // start with its address, so that if the type has pointer methods,
+ // we find them.
+ if v.Kind() != reflect.Ptr && v.Type().Name() != "" && v.CanAddr() {
+ v = v.Addr()
+ }
+ for {
+ // Load value from interface, but only if the result will be
+ // usefully addressable.
+ if v.Kind() == reflect.Interface && !v.IsNil() {
+ e := v.Elem()
+ if e.Kind() == reflect.Ptr && !e.IsNil() && (!decodingNull || e.Elem().Kind() == reflect.Ptr) {
+ v = e
+ continue
+ }
+ }
+
+ if v.Kind() != reflect.Ptr {
+ break
+ }
+
+ if v.Elem().Kind() != reflect.Ptr && decodingNull && v.CanSet() {
+ break
+ }
+ if v.IsNil() {
+ if v.CanSet() {
+ v.Set(reflect.New(v.Type().Elem()))
+ } else {
+ v = reflect.New(v.Type().Elem())
+ }
+ }
+ if v.Type().NumMethod() > 0 {
+ if u, ok := v.Interface().(json.Unmarshaler); ok {
+ return u, nil, reflect.Value{}
+ }
+ if u, ok := v.Interface().(encoding.TextUnmarshaler); ok {
+ return nil, u, reflect.Value{}
+ }
+ }
+ v = v.Elem()
+ }
+ return nil, nil, v
+}
+
+// A field represents a single field found in a struct.
+type field struct {
+ name string
+ nameBytes []byte // []byte(name)
+ equalFold func(s, t []byte) bool // bytes.EqualFold or equivalent
+
+ tag bool
+ index []int
+ typ reflect.Type
+ omitEmpty bool
+ quoted bool
+}
+
+func fillField(f field) field {
+ f.nameBytes = []byte(f.name)
+ f.equalFold = foldFunc(f.nameBytes)
+ return f
+}
+
+// byName sorts field by name, breaking ties with depth,
+// then breaking ties with "name came from json tag", then
+// breaking ties with index sequence.
+type byName []field
+
+func (x byName) Len() int { return len(x) }
+
+func (x byName) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
+
+func (x byName) Less(i, j int) bool {
+ if x[i].name != x[j].name {
+ return x[i].name < x[j].name
+ }
+ if len(x[i].index) != len(x[j].index) {
+ return len(x[i].index) < len(x[j].index)
+ }
+ if x[i].tag != x[j].tag {
+ return x[i].tag
+ }
+ return byIndex(x).Less(i, j)
+}
+
+// byIndex sorts field by index sequence.
+type byIndex []field
+
+func (x byIndex) Len() int { return len(x) }
+
+func (x byIndex) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
+
+func (x byIndex) Less(i, j int) bool {
+ for k, xik := range x[i].index {
+ if k >= len(x[j].index) {
+ return false
+ }
+ if xik != x[j].index[k] {
+ return xik < x[j].index[k]
+ }
+ }
+ return len(x[i].index) < len(x[j].index)
+}
+
+// typeFields returns a list of fields that JSON should recognize for the given type.
+// The algorithm is breadth-first search over the set of structs to include - the top struct
+// and then any reachable anonymous structs.
+func typeFields(t reflect.Type) []field {
+ // Anonymous fields to explore at the current level and the next.
+ current := []field{}
+ next := []field{{typ: t}}
+
+ // Count of queued names for current level and the next.
+ count := map[reflect.Type]int{}
+ nextCount := map[reflect.Type]int{}
+
+ // Types already visited at an earlier level.
+ visited := map[reflect.Type]bool{}
+
+ // Fields found.
+ var fields []field
+
+ for len(next) > 0 {
+ current, next = next, current[:0]
+ count, nextCount = nextCount, map[reflect.Type]int{}
+
+ for _, f := range current {
+ if visited[f.typ] {
+ continue
+ }
+ visited[f.typ] = true
+
+ // Scan f.typ for fields to include.
+ for i := 0; i < f.typ.NumField(); i++ {
+ sf := f.typ.Field(i)
+ if sf.PkgPath != "" { // unexported
+ continue
+ }
+ tag := sf.Tag.Get("json")
+ if tag == "-" {
+ continue
+ }
+ name, opts := parseTag(tag)
+ if !isValidTag(name) {
+ name = ""
+ }
+ index := make([]int, len(f.index)+1)
+ copy(index, f.index)
+ index[len(f.index)] = i
+
+ ft := sf.Type
+ if ft.Name() == "" && ft.Kind() == reflect.Ptr {
+ // Follow pointer.
+ ft = ft.Elem()
+ }
+
+ // Record found field and index sequence.
+ if name != "" || !sf.Anonymous || ft.Kind() != reflect.Struct {
+ tagged := name != ""
+ if name == "" {
+ name = sf.Name
+ }
+ fields = append(fields, fillField(field{
+ name: name,
+ tag: tagged,
+ index: index,
+ typ: ft,
+ omitEmpty: opts.Contains("omitempty"),
+ quoted: opts.Contains("string"),
+ }))
+ if count[f.typ] > 1 {
+ // If there were multiple instances, add a second,
+ // so that the annihilation code will see a duplicate.
+ // It only cares about the distinction between 1 or 2,
+ // so don't bother generating any more copies.
+ fields = append(fields, fields[len(fields)-1])
+ }
+ continue
+ }
+
+ // Record new anonymous struct to explore in next round.
+ nextCount[ft]++
+ if nextCount[ft] == 1 {
+ next = append(next, fillField(field{name: ft.Name(), index: index, typ: ft}))
+ }
+ }
+ }
+ }
+
+ sort.Sort(byName(fields))
+
+ // Delete all fields that are hidden by the Go rules for embedded fields,
+ // except that fields with JSON tags are promoted.
+
+ // The fields are sorted in primary order of name, secondary order
+ // of field index length. Loop over names; for each name, delete
+ // hidden fields by choosing the one dominant field that survives.
+ out := fields[:0]
+ for advance, i := 0, 0; i < len(fields); i += advance {
+ // One iteration per name.
+ // Find the sequence of fields with the name of this first field.
+ fi := fields[i]
+ name := fi.name
+ for advance = 1; i+advance < len(fields); advance++ {
+ fj := fields[i+advance]
+ if fj.name != name {
+ break
+ }
+ }
+ if advance == 1 { // Only one field with this name
+ out = append(out, fi)
+ continue
+ }
+ dominant, ok := dominantField(fields[i : i+advance])
+ if ok {
+ out = append(out, dominant)
+ }
+ }
+
+ fields = out
+ sort.Sort(byIndex(fields))
+
+ return fields
+}
+
+// dominantField looks through the fields, all of which are known to
+// have the same name, to find the single field that dominates the
+// others using Go's embedding rules, modified by the presence of
+// JSON tags. If there are multiple top-level fields, the boolean
+// will be false: This condition is an error in Go and we skip all
+// the fields.
+func dominantField(fields []field) (field, bool) {
+ // The fields are sorted in increasing index-length order. The winner
+ // must therefore be one with the shortest index length. Drop all
+ // longer entries, which is easy: just truncate the slice.
+ length := len(fields[0].index)
+ tagged := -1 // Index of first tagged field.
+ for i, f := range fields {
+ if len(f.index) > length {
+ fields = fields[:i]
+ break
+ }
+ if f.tag {
+ if tagged >= 0 {
+ // Multiple tagged fields at the same level: conflict.
+ // Return no field.
+ return field{}, false
+ }
+ tagged = i
+ }
+ }
+ if tagged >= 0 {
+ return fields[tagged], true
+ }
+ // All remaining fields have the same length. If there's more than one,
+ // we have a conflict (two fields named "X" at the same level) and we
+ // return no field.
+ if len(fields) > 1 {
+ return field{}, false
+ }
+ return fields[0], true
+}
+
+var fieldCache struct {
+ sync.RWMutex
+ m map[reflect.Type][]field
+}
+
+// cachedTypeFields is like typeFields but uses a cache to avoid repeated work.
+func cachedTypeFields(t reflect.Type) []field {
+ fieldCache.RLock()
+ f := fieldCache.m[t]
+ fieldCache.RUnlock()
+ if f != nil {
+ return f
+ }
+
+ // Compute fields without lock.
+ // Might duplicate effort but won't hold other computations back.
+ f = typeFields(t)
+ if f == nil {
+ f = []field{}
+ }
+
+ fieldCache.Lock()
+ if fieldCache.m == nil {
+ fieldCache.m = map[reflect.Type][]field{}
+ }
+ fieldCache.m[t] = f
+ fieldCache.Unlock()
+ return f
+}
+
+func isValidTag(s string) bool {
+ if s == "" {
+ return false
+ }
+ for _, c := range s {
+ switch {
+ case strings.ContainsRune("!#$%&()*+-./:<=>?@[]^_{|}~ ", c):
+ // Backslash and quote chars are reserved, but
+ // otherwise any punctuation chars are allowed
+ // in a tag name.
+ default:
+ if !unicode.IsLetter(c) && !unicode.IsDigit(c) {
+ return false
+ }
+ }
+ }
+ return true
+}
+
+const (
+ caseMask = ^byte(0x20) // Mask to ignore case in ASCII.
+ kelvin = '\u212a'
+ smallLongEss = '\u017f'
+)
+
+// foldFunc returns one of four different case folding equivalence
+// functions, from most general (and slow) to fastest:
+//
+// 1) bytes.EqualFold, if the key s contains any non-ASCII UTF-8
+// 2) equalFoldRight, if s contains special folding ASCII ('k', 'K', 's', 'S')
+// 3) asciiEqualFold, no special, but includes non-letters (including _)
+// 4) simpleLetterEqualFold, no specials, no non-letters.
+//
+// The letters S and K are special because they map to 3 runes, not just 2:
+// * S maps to s and to U+017F 'ſ' Latin small letter long s
+// * k maps to K and to U+212A 'K' Kelvin sign
+// See http://play.golang.org/p/tTxjOc0OGo
+//
+// The returned function is specialized for matching against s and
+// should only be given s. It's not curried for performance reasons.
+func foldFunc(s []byte) func(s, t []byte) bool {
+ nonLetter := false
+ special := false // special letter
+ for _, b := range s {
+ if b >= utf8.RuneSelf {
+ return bytes.EqualFold
+ }
+ upper := b & caseMask
+ if upper < 'A' || upper > 'Z' {
+ nonLetter = true
+ } else if upper == 'K' || upper == 'S' {
+ // See above for why these letters are special.
+ special = true
+ }
+ }
+ if special {
+ return equalFoldRight
+ }
+ if nonLetter {
+ return asciiEqualFold
+ }
+ return simpleLetterEqualFold
+}
+
+// equalFoldRight is a specialization of bytes.EqualFold when s is
+// known to be all ASCII (including punctuation), but contains an 's',
+// 'S', 'k', or 'K', requiring a Unicode fold on the bytes in t.
+// See comments on foldFunc.
+func equalFoldRight(s, t []byte) bool {
+ for _, sb := range s {
+ if len(t) == 0 {
+ return false
+ }
+ tb := t[0]
+ if tb < utf8.RuneSelf {
+ if sb != tb {
+ sbUpper := sb & caseMask
+ if 'A' <= sbUpper && sbUpper <= 'Z' {
+ if sbUpper != tb&caseMask {
+ return false
+ }
+ } else {
+ return false
+ }
+ }
+ t = t[1:]
+ continue
+ }
+ // sb is ASCII and t is not. t must be either kelvin
+ // sign or long s; sb must be s, S, k, or K.
+ tr, size := utf8.DecodeRune(t)
+ switch sb {
+ case 's', 'S':
+ if tr != smallLongEss {
+ return false
+ }
+ case 'k', 'K':
+ if tr != kelvin {
+ return false
+ }
+ default:
+ return false
+ }
+ t = t[size:]
+
+ }
+ if len(t) > 0 {
+ return false
+ }
+ return true
+}
+
+// asciiEqualFold is a specialization of bytes.EqualFold for use when
+// s is all ASCII (but may contain non-letters) and contains no
+// special-folding letters.
+// See comments on foldFunc.
+func asciiEqualFold(s, t []byte) bool {
+ if len(s) != len(t) {
+ return false
+ }
+ for i, sb := range s {
+ tb := t[i]
+ if sb == tb {
+ continue
+ }
+ if ('a' <= sb && sb <= 'z') || ('A' <= sb && sb <= 'Z') {
+ if sb&caseMask != tb&caseMask {
+ return false
+ }
+ } else {
+ return false
+ }
+ }
+ return true
+}
+
+// simpleLetterEqualFold is a specialization of bytes.EqualFold for
+// use when s is all ASCII letters (no underscores, etc) and also
+// doesn't contain 'k', 'K', 's', or 'S'.
+// See comments on foldFunc.
+func simpleLetterEqualFold(s, t []byte) bool {
+ if len(s) != len(t) {
+ return false
+ }
+ for i, b := range s {
+ if b&caseMask != t[i]&caseMask {
+ return false
+ }
+ }
+ return true
+}
+
+// tagOptions is the string following a comma in a struct field's "json"
+// tag, or the empty string. It does not include the leading comma.
+type tagOptions string
+
+// parseTag splits a struct field's json tag into its name and
+// comma-separated options.
+func parseTag(tag string) (string, tagOptions) {
+ if idx := strings.Index(tag, ","); idx != -1 {
+ return tag[:idx], tagOptions(tag[idx+1:])
+ }
+ return tag, tagOptions("")
+}
+
+// Contains reports whether a comma-separated list of options
+// contains a particular substr flag. substr must be surrounded by a
+// string boundary or commas.
+func (o tagOptions) Contains(optionName string) bool {
+ if len(o) == 0 {
+ return false
+ }
+ s := string(o)
+ for s != "" {
+ var next string
+ i := strings.Index(s, ",")
+ if i >= 0 {
+ s, next = s[:i], s[i+1:]
+ }
+ if s == optionName {
+ return true
+ }
+ s = next
+ }
+ return false
+}
diff --git a/vendor/github.com/ghodss/yaml/yaml.go b/vendor/github.com/ghodss/yaml/yaml.go
new file mode 100644
index 0000000..4fb4054
--- /dev/null
+++ b/vendor/github.com/ghodss/yaml/yaml.go
@@ -0,0 +1,277 @@
+package yaml
+
+import (
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "reflect"
+ "strconv"
+
+ "gopkg.in/yaml.v2"
+)
+
+// Marshals the object into JSON then converts JSON to YAML and returns the
+// YAML.
+func Marshal(o interface{}) ([]byte, error) {
+ j, err := json.Marshal(o)
+ if err != nil {
+ return nil, fmt.Errorf("error marshaling into JSON: %v", err)
+ }
+
+ y, err := JSONToYAML(j)
+ if err != nil {
+ return nil, fmt.Errorf("error converting JSON to YAML: %v", err)
+ }
+
+ return y, nil
+}
+
+// Converts YAML to JSON then uses JSON to unmarshal into an object.
+func Unmarshal(y []byte, o interface{}) error {
+ vo := reflect.ValueOf(o)
+ j, err := yamlToJSON(y, &vo)
+ if err != nil {
+ return fmt.Errorf("error converting YAML to JSON: %v", err)
+ }
+
+ err = json.Unmarshal(j, o)
+ if err != nil {
+ return fmt.Errorf("error unmarshaling JSON: %v", err)
+ }
+
+ return nil
+}
+
+// Convert JSON to YAML.
+func JSONToYAML(j []byte) ([]byte, error) {
+ // Convert the JSON to an object.
+ var jsonObj interface{}
+ // We are using yaml.Unmarshal here (instead of json.Unmarshal) because the
+ // Go JSON library doesn't try to pick the right number type (int, float,
+ // etc.) when unmarshalling to interface{}, it just picks float64
+ // universally. go-yaml does go through the effort of picking the right
+ // number type, so we can preserve number type throughout this process.
+ err := yaml.Unmarshal(j, &jsonObj)
+ if err != nil {
+ return nil, err
+ }
+
+ // Marshal this object into YAML.
+ return yaml.Marshal(jsonObj)
+}
+
+// Convert YAML to JSON. Since JSON is a subset of YAML, passing JSON through
+// this method should be a no-op.
+//
+// Things YAML can do that are not supported by JSON:
+// * In YAML you can have binary and null keys in your maps. These are invalid
+// in JSON. (int and float keys are converted to strings.)
+// * Binary data in YAML with the !!binary tag is not supported. If you want to
+// use binary data with this library, encode the data as base64 as usual but do
+// not use the !!binary tag in your YAML. This will ensure the original base64
+// encoded data makes it all the way through to the JSON.
+func YAMLToJSON(y []byte) ([]byte, error) {
+ return yamlToJSON(y, nil)
+}
+
+func yamlToJSON(y []byte, jsonTarget *reflect.Value) ([]byte, error) {
+ // Convert the YAML to an object.
+ var yamlObj interface{}
+ err := yaml.Unmarshal(y, &yamlObj)
+ if err != nil {
+ return nil, err
+ }
+
+ // YAML objects are not completely compatible with JSON objects (e.g. you
+ // can have non-string keys in YAML). So, convert the YAML-compatible object
+ // to a JSON-compatible object, failing with an error if irrecoverable
+ // incompatibilties happen along the way.
+ jsonObj, err := convertToJSONableObject(yamlObj, jsonTarget)
+ if err != nil {
+ return nil, err
+ }
+
+ // Convert this object to JSON and return the data.
+ return json.Marshal(jsonObj)
+}
+
+func convertToJSONableObject(yamlObj interface{}, jsonTarget *reflect.Value) (interface{}, error) {
+ var err error
+
+ // Resolve jsonTarget to a concrete value (i.e. not a pointer or an
+ // interface). We pass decodingNull as false because we're not actually
+ // decoding into the value, we're just checking if the ultimate target is a
+ // string.
+ if jsonTarget != nil {
+ ju, tu, pv := indirect(*jsonTarget, false)
+ // We have a JSON or Text Umarshaler at this level, so we can't be trying
+ // to decode into a string.
+ if ju != nil || tu != nil {
+ jsonTarget = nil
+ } else {
+ jsonTarget = &pv
+ }
+ }
+
+ // If yamlObj is a number or a boolean, check if jsonTarget is a string -
+ // if so, coerce. Else return normal.
+ // If yamlObj is a map or array, find the field that each key is
+ // unmarshaling to, and when you recurse pass the reflect.Value for that
+ // field back into this function.
+ switch typedYAMLObj := yamlObj.(type) {
+ case map[interface{}]interface{}:
+ // JSON does not support arbitrary keys in a map, so we must convert
+ // these keys to strings.
+ //
+ // From my reading of go-yaml v2 (specifically the resolve function),
+ // keys can only have the types string, int, int64, float64, binary
+ // (unsupported), or null (unsupported).
+ strMap := make(map[string]interface{})
+ for k, v := range typedYAMLObj {
+ // Resolve the key to a string first.
+ var keyString string
+ switch typedKey := k.(type) {
+ case string:
+ keyString = typedKey
+ case int:
+ keyString = strconv.Itoa(typedKey)
+ case int64:
+ // go-yaml will only return an int64 as a key if the system
+ // architecture is 32-bit and the key's value is between 32-bit
+ // and 64-bit. Otherwise the key type will simply be int.
+ keyString = strconv.FormatInt(typedKey, 10)
+ case float64:
+ // Stolen from go-yaml to use the same conversion to string as
+ // the go-yaml library uses to convert float to string when
+ // Marshaling.
+ s := strconv.FormatFloat(typedKey, 'g', -1, 32)
+ switch s {
+ case "+Inf":
+ s = ".inf"
+ case "-Inf":
+ s = "-.inf"
+ case "NaN":
+ s = ".nan"
+ }
+ keyString = s
+ case bool:
+ if typedKey {
+ keyString = "true"
+ } else {
+ keyString = "false"
+ }
+ default:
+ return nil, fmt.Errorf("Unsupported map key of type: %s, key: %+#v, value: %+#v",
+ reflect.TypeOf(k), k, v)
+ }
+
+ // jsonTarget should be a struct or a map. If it's a struct, find
+ // the field it's going to map to and pass its reflect.Value. If
+ // it's a map, find the element type of the map and pass the
+ // reflect.Value created from that type. If it's neither, just pass
+ // nil - JSON conversion will error for us if it's a real issue.
+ if jsonTarget != nil {
+ t := *jsonTarget
+ if t.Kind() == reflect.Struct {
+ keyBytes := []byte(keyString)
+ // Find the field that the JSON library would use.
+ var f *field
+ fields := cachedTypeFields(t.Type())
+ for i := range fields {
+ ff := &fields[i]
+ if bytes.Equal(ff.nameBytes, keyBytes) {
+ f = ff
+ break
+ }
+ // Do case-insensitive comparison.
+ if f == nil && ff.equalFold(ff.nameBytes, keyBytes) {
+ f = ff
+ }
+ }
+ if f != nil {
+ // Find the reflect.Value of the most preferential
+ // struct field.
+ jtf := t.Field(f.index[0])
+ strMap[keyString], err = convertToJSONableObject(v, &jtf)
+ if err != nil {
+ return nil, err
+ }
+ continue
+ }
+ } else if t.Kind() == reflect.Map {
+ // Create a zero value of the map's element type to use as
+ // the JSON target.
+ jtv := reflect.Zero(t.Type().Elem())
+ strMap[keyString], err = convertToJSONableObject(v, &jtv)
+ if err != nil {
+ return nil, err
+ }
+ continue
+ }
+ }
+ strMap[keyString], err = convertToJSONableObject(v, nil)
+ if err != nil {
+ return nil, err
+ }
+ }
+ return strMap, nil
+ case []interface{}:
+ // We need to recurse into arrays in case there are any
+ // map[interface{}]interface{}'s inside and to convert any
+ // numbers to strings.
+
+ // If jsonTarget is a slice (which it really should be), find the
+ // thing it's going to map to. If it's not a slice, just pass nil
+ // - JSON conversion will error for us if it's a real issue.
+ var jsonSliceElemValue *reflect.Value
+ if jsonTarget != nil {
+ t := *jsonTarget
+ if t.Kind() == reflect.Slice {
+ // By default slices point to nil, but we need a reflect.Value
+ // pointing to a value of the slice type, so we create one here.
+ ev := reflect.Indirect(reflect.New(t.Type().Elem()))
+ jsonSliceElemValue = &ev
+ }
+ }
+
+ // Make and use a new array.
+ arr := make([]interface{}, len(typedYAMLObj))
+ for i, v := range typedYAMLObj {
+ arr[i], err = convertToJSONableObject(v, jsonSliceElemValue)
+ if err != nil {
+ return nil, err
+ }
+ }
+ return arr, nil
+ default:
+ // If the target type is a string and the YAML type is a number,
+ // convert the YAML type to a string.
+ if jsonTarget != nil && (*jsonTarget).Kind() == reflect.String {
+ // Based on my reading of go-yaml, it may return int, int64,
+ // float64, or uint64.
+ var s string
+ switch typedVal := typedYAMLObj.(type) {
+ case int:
+ s = strconv.FormatInt(int64(typedVal), 10)
+ case int64:
+ s = strconv.FormatInt(typedVal, 10)
+ case float64:
+ s = strconv.FormatFloat(typedVal, 'g', -1, 32)
+ case uint64:
+ s = strconv.FormatUint(typedVal, 10)
+ case bool:
+ if typedVal {
+ s = "true"
+ } else {
+ s = "false"
+ }
+ }
+ if len(s) > 0 {
+ yamlObj = interface{}(s)
+ }
+ }
+ return yamlObj, nil
+ }
+
+ return nil, nil
+}
diff --git a/vendor/github.com/go-playground/locales/.gitignore b/vendor/github.com/go-playground/locales/.gitignore
deleted file mode 100644
index daf913b..0000000
--- a/vendor/github.com/go-playground/locales/.gitignore
+++ /dev/null
@@ -1,24 +0,0 @@
-# Compiled Object files, Static and Dynamic libs (Shared Objects)
-*.o
-*.a
-*.so
-
-# Folders
-_obj
-_test
-
-# Architecture specific extensions/prefixes
-*.[568vq]
-[568vq].out
-
-*.cgo1.go
-*.cgo2.c
-_cgo_defun.c
-_cgo_gotypes.go
-_cgo_export.*
-
-_testmain.go
-
-*.exe
-*.test
-*.prof
diff --git a/vendor/github.com/go-playground/locales/README.md b/vendor/github.com/go-playground/locales/README.md
deleted file mode 100644
index b462c93..0000000
--- a/vendor/github.com/go-playground/locales/README.md
+++ /dev/null
@@ -1,172 +0,0 @@
-## locales
-<img align="right" src="https://raw.githubusercontent.com/go-playground/locales/master/logo.png">![Project status](https://img.shields.io/badge/version-0.11.1-green.svg)
-[![Build Status](https://semaphoreci.com/api/v1/joeybloggs/locales/branches/master/badge.svg)](https://semaphoreci.com/joeybloggs/locales)
-[![Go Report Card](https://goreportcard.com/badge/github.com/go-playground/locales)](https://goreportcard.com/report/github.com/go-playground/locales)
-[![GoDoc](https://godoc.org/github.com/go-playground/locales?status.svg)](https://godoc.org/github.com/go-playground/locales)
-![License](https://img.shields.io/dub/l/vibe-d.svg)
-[![Gitter](https://badges.gitter.im/go-playground/locales.svg)](https://gitter.im/go-playground/locales?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)
-
-Locales is a set of locales generated from the [Unicode CLDR Project](http://cldr.unicode.org/) which can be used independently or within
-an i18n package; these were built for use with, but not exclusive to, [Universal Translator](https://github.com/go-playground/universal-translator).
-
-Features
---------
-- [x] Rules generated from the latest [CLDR](http://cldr.unicode.org/index/downloads) data, v31.0.1
-- [x] Contains Cardinal, Ordinal and Range Plural Rules
-- [x] Contains Month, Weekday and Timezone translations built in
-- [x] Contains Date & Time formatting functions
-- [x] Contains Number, Currency, Accounting and Percent formatting functions
-- [x] Supports the "Gregorian" calendar only ( my time isn't unlimited, had to draw the line somewhere )
-
-Full Tests
---------------------
-I could sure use your help adding tests for every locale, it is a huge undertaking and I just don't have the free time to do it all at the moment;
-any help would be **greatly appreciated!!!!** please see [issue](https://github.com/go-playground/locales/issues/1) for details.
-
-Installation
------------
-
-Use go get
-
-```shell
-go get github.com/go-playground/locales
-```
-
-NOTES
---------
-You'll notice most return types are []byte, this is because most of the time the results will be concatenated with a larger body
-of text and can avoid some allocations if already appending to a byte array, otherwise just cast as string.
-
-Usage
--------
-```go
-package main
-
-import (
- "fmt"
- "time"
-
- "github.com/go-playground/locales/currency"
- "github.com/go-playground/locales/en_CA"
-)
-
-func main() {
-
- loc, _ := time.LoadLocation("America/Toronto")
- datetime := time.Date(2016, 02, 03, 9, 0, 1, 0, loc)
-
- l := en_CA.New()
-
- // Dates
- fmt.Println(l.FmtDateFull(datetime))
- fmt.Println(l.FmtDateLong(datetime))
- fmt.Println(l.FmtDateMedium(datetime))
- fmt.Println(l.FmtDateShort(datetime))
-
- // Times
- fmt.Println(l.FmtTimeFull(datetime))
- fmt.Println(l.FmtTimeLong(datetime))
- fmt.Println(l.FmtTimeMedium(datetime))
- fmt.Println(l.FmtTimeShort(datetime))
-
- // Months Wide
- fmt.Println(l.MonthWide(time.January))
- fmt.Println(l.MonthWide(time.February))
- fmt.Println(l.MonthWide(time.March))
- // ...
-
- // Months Abbreviated
- fmt.Println(l.MonthAbbreviated(time.January))
- fmt.Println(l.MonthAbbreviated(time.February))
- fmt.Println(l.MonthAbbreviated(time.March))
- // ...
-
- // Months Narrow
- fmt.Println(l.MonthNarrow(time.January))
- fmt.Println(l.MonthNarrow(time.February))
- fmt.Println(l.MonthNarrow(time.March))
- // ...
-
- // Weekdays Wide
- fmt.Println(l.WeekdayWide(time.Sunday))
- fmt.Println(l.WeekdayWide(time.Monday))
- fmt.Println(l.WeekdayWide(time.Tuesday))
- // ...
-
- // Weekdays Abbreviated
- fmt.Println(l.WeekdayAbbreviated(time.Sunday))
- fmt.Println(l.WeekdayAbbreviated(time.Monday))
- fmt.Println(l.WeekdayAbbreviated(time.Tuesday))
- // ...
-
- // Weekdays Short
- fmt.Println(l.WeekdayShort(time.Sunday))
- fmt.Println(l.WeekdayShort(time.Monday))
- fmt.Println(l.WeekdayShort(time.Tuesday))
- // ...
-
- // Weekdays Narrow
- fmt.Println(l.WeekdayNarrow(time.Sunday))
- fmt.Println(l.WeekdayNarrow(time.Monday))
- fmt.Println(l.WeekdayNarrow(time.Tuesday))
- // ...
-
- var f64 float64
-
- f64 = -10356.4523
-
- // Number
- fmt.Println(l.FmtNumber(f64, 2))
-
- // Currency
- fmt.Println(l.FmtCurrency(f64, 2, currency.CAD))
- fmt.Println(l.FmtCurrency(f64, 2, currency.USD))
-
- // Accounting
- fmt.Println(l.FmtAccounting(f64, 2, currency.CAD))
- fmt.Println(l.FmtAccounting(f64, 2, currency.USD))
-
- f64 = 78.12
-
- // Percent
- fmt.Println(l.FmtPercent(f64, 0))
-
- // Plural Rules for locale, so you know what rules you must cover
- fmt.Println(l.PluralsCardinal())
- fmt.Println(l.PluralsOrdinal())
-
- // Cardinal Plural Rules
- fmt.Println(l.CardinalPluralRule(1, 0))
- fmt.Println(l.CardinalPluralRule(1.0, 0))
- fmt.Println(l.CardinalPluralRule(1.0, 1))
- fmt.Println(l.CardinalPluralRule(3, 0))
-
- // Ordinal Plural Rules
- fmt.Println(l.OrdinalPluralRule(21, 0)) // 21st
- fmt.Println(l.OrdinalPluralRule(22, 0)) // 22nd
- fmt.Println(l.OrdinalPluralRule(33, 0)) // 33rd
- fmt.Println(l.OrdinalPluralRule(34, 0)) // 34th
-
- // Range Plural Rules
- fmt.Println(l.RangePluralRule(1, 0, 1, 0)) // 1-1
- fmt.Println(l.RangePluralRule(1, 0, 2, 0)) // 1-2
- fmt.Println(l.RangePluralRule(5, 0, 8, 0)) // 5-8
-}
-```
-
-NOTES:
--------
-These rules were generated from the [Unicode CLDR Project](http://cldr.unicode.org/), if you encounter any issues
-I strongly encourage contributing to the CLDR project to get the locale information corrected and the next time
-these locales are regenerated the fix will come with.
-
-I do however realize that time constraints are often important and so there are two options:
-
-1. Create your own locale, copy, paste and modify, and ensure it complies with the `Translator` interface.
-2. Add an exception in the locale generation code directly and once regenerated, fix will be in place.
-
-Please to not make fixes inside the locale files, they WILL get overwritten when the locales are regenerated.
-
-License
-------
-Distributed under MIT License, please see license file in code for more details.
diff --git a/vendor/github.com/go-playground/locales/cu/cu.go b/vendor/github.com/go-playground/locales/cu/cu.go
deleted file mode 100644
index 0ec6b3a..0000000
--- a/vendor/github.com/go-playground/locales/cu/cu.go
+++ /dev/null
@@ -1,609 +0,0 @@
-package cu
-
-import (
- "math"
- "strconv"
- "time"
-
- "github.com/go-playground/locales"
- "github.com/go-playground/locales/currency"
-)
-
-type cu struct {
- locale string
- pluralsCardinal []locales.PluralRule
- pluralsOrdinal []locales.PluralRule
- pluralsRange []locales.PluralRule
- decimal string
- group string
- minus string
- percent string
- percentSuffix string
- perMille string
- timeSeparator string
- inifinity string
- currencies []string // idx = enum of currency code
- currencyPositiveSuffix string
- currencyNegativeSuffix string
- monthsAbbreviated []string
- monthsNarrow []string
- monthsWide []string
- daysAbbreviated []string
- daysNarrow []string
- daysShort []string
- daysWide []string
- periodsAbbreviated []string
- periodsNarrow []string
- periodsShort []string
- periodsWide []string
- erasAbbreviated []string
- erasNarrow []string
- erasWide []string
- timezones map[string]string
-}
-
-// New returns a new instance of translator for the 'cu' locale
-func New() locales.Translator {
- return &cu{
- locale: "cu",
- pluralsCardinal: nil,
- pluralsOrdinal: nil,
- pluralsRange: nil,
- decimal: ",",
- group: " ",
- minus: "-",
- percent: "%",
- timeSeparator: ":",
- inifinity: "∞",
- currencies: []string{"ADP", "AED", "AFA", "AFN", "ALK", "ALL", "AMD", "ANG", "AOA", "AOK", "AON", "AOR", "ARA", "ARL", "ARM", "ARP", "ARS", "ATS", "AUD", "AWG", "AZM", "AZN", "BAD", "BAM", "BAN", "BBD", "BDT", "BEC", "BEF", "BEL", "BGL", "BGM", "BGN", "BGO", "BHD", "BIF", "BMD", "BND", "BOB", "BOL", "BOP", "BOV", "BRB", "BRC", "BRE", "R$", "BRN", "BRR", "BRZ", "BSD", "BTN", "BUK", "BWP", "BYB", "BYN", "BYR", "BZD", "CAD", "CDF", "CHE", "CHF", "CHW", "CLE", "CLF", "CLP", "CNX", "CN¥", "COP", "COU", "CRC", "CSD", "CSK", "CUC", "CUP", "CVE", "CYP", "CZK", "DDM", "DEM", "DJF", "DKK", "DOP", "DZD", "ECS", "ECV", "EEK", "EGP", "ERN", "ESA", "ESB", "ESP", "ETB", "€", "FIM", "FJD", "FKP", "FRF", "£", "GEK", "GEL", "GHC", "GHS", "GIP", "GMD", "GNF", "GNS", "GQE", "GRD", "GTQ", "GWE", "GWP", "GYD", "HKD", "HNL", "HRD", "HRK", "HTG", "HUF", "IDR", "IEP", "ILP", "ILR", "ILS", "₹", "IQD", "IRR", "ISJ", "ISK", "ITL", "JMD", "JOD", "JP¥", "KES", "KGS", "KHR", "KMF", "KPW", "KRH", "KRO", "KRW", "KWD", "KYD", "₸", "LAK", "LBP", "LKR", "LRD", "LSL", "LTL", "LTT", "LUC", "LUF", "LUL", "LVL", "LVR", "LYD", "MAD", "MAF", "MCF", "MDC", "MDL", "MGA", "MGF", "MKD", "MKN", "MLF", "MMK", "MNT", "MOP", "MRO", "MTL", "MTP", "MUR", "MVP", "MVR", "MWK", "MXN", "MXP", "MXV", "MYR", "MZE", "MZM", "MZN", "NAD", "NGN", "NIC", "NIO", "NLG", "NOK", "NPR", "NZD", "OMR", "PAB", "PEI", "PEN", "PES", "PGK", "PHP", "PKR", "PLN", "PLZ", "PTE", "PYG", "QAR", "RHD", "ROL", "RON", "RSD", "₽", "RUR", "RWF", "SAR", "SBD", "SCR", "SDD", "SDG", "SDP", "SEK", "SGD", "SHP", "SIT", "SKK", "SLL", "SOS", "SRD", "SRG", "SSP", "STD", "SUR", "SVC", "SYP", "SZL", "THB", "TJR", "TJS", "TMM", "TMT", "TND", "TOP", "TPE", "TRL", "TRY", "TTD", "TWD", "TZS", "₴", "UAK", "UGS", "UGX", "$", "USN", "USS", "UYI", "UYP", "UYU", "UZS", "VEB", "VEF", "VND", "VNN", "VUV", "WST", "XAF", "XAG", "XAU", "XBA", "XBB", "XBC", "XBD", "XCD", "XDR", "XEU", "XFO", "XFU", "XOF", "XPD", "XPF", "XPT", "XRE", "XSU", "XTS", "XUA", "XXX", "YDD", "YER", "YUD", "YUM", "YUN", "YUR", "ZAL", "ZAR", "ZMK", "ZMW", "ZRN", "ZRZ", "ZWD", "ZWL", "ZWR"},
- percentSuffix: " ",
- currencyPositiveSuffix: " ",
- currencyNegativeSuffix: " ",
- monthsAbbreviated: []string{"", "і҆аⷩ҇", "феⷡ҇", "маⷬ҇", "а҆пⷬ҇", "маꙵ", "і҆ꙋⷩ҇", "і҆ꙋⷧ҇", "а҆́ѵⷢ҇", "сеⷫ҇", "ѻ҆кⷮ", "ноеⷨ", "деⷦ҇"},
- monthsNarrow: []string{"", "І҆", "Ф", "М", "А҆", "М", "І҆", "І҆", "А҆", "С", "Ѻ҆", "Н", "Д"},
- monthsWide: []string{"", "і҆аннꙋа́рїа", "феврꙋа́рїа", "ма́рта", "а҆прі́ллїа", "ма́їа", "і҆ꙋ́нїа", "і҆ꙋ́лїа", "а҆́ѵгꙋста", "септе́мврїа", "ѻ҆ктѡ́врїа", "ное́мврїа", "деке́мврїа"},
- daysAbbreviated: []string{"ндⷧ҇ѧ", "пнⷣе", "втоⷬ҇", "срⷣе", "чеⷦ҇", "пѧⷦ҇", "сꙋⷠ҇"},
- daysNarrow: []string{"Н", "П", "В", "С", "Ч", "П", "С"},
- daysShort: []string{"ндⷧ҇ѧ", "пнⷣе", "втоⷬ҇", "срⷣе", "чеⷦ҇", "пѧⷦ҇", "сꙋⷠ҇"},
- daysWide: []string{"недѣ́лѧ", "понедѣ́льникъ", "вто́рникъ", "среда̀", "четверто́къ", "пѧто́къ", "сꙋббѡ́та"},
- periodsAbbreviated: []string{"ДП", "ПП"},
- periodsNarrow: []string{"ДП", "ПП"},
- periodsWide: []string{"ДП", "ПП"},
- erasAbbreviated: []string{"", ""},
- erasNarrow: []string{"", ""},
- erasWide: []string{"пре́дъ р.\u00a0х.", "по р.\u00a0х."},
- timezones: map[string]string{"CLT": "CLT", "CLST": "CLST", "WEZ": "западноєѵрѡпе́йское зи́мнее вре́мѧ", "CHADT": "CHADT", "PST": "тихоѻкеа́нское зи́мнее вре́мѧ", "HADT": "HADT", "LHDT": "LHDT", "ADT": "а҆тланті́ческое лѣ́тнее вре́мѧ", "ACWDT": "ACWDT", "MYT": "MYT", "WIT": "WIT", "NZDT": "NZDT", "EAT": "EAT", "SRT": "SRT", "HNEG": "HNEG", "HAT": "HAT", "GMT": "сре́днее вре́мѧ по грі́нꙋичꙋ", "CDT": "среднеамерїка́нское лѣ́тнее вре́мѧ", "UYST": "UYST", "HAST": "HAST", "ARST": "ARST", "AST": "а҆тланті́ческое зи́мнее вре́мѧ", "AWST": "AWST", "MEZ": "среднеєѵрѡпе́йское зи́мнее вре́мѧ", "JDT": "JDT", "ECT": "ECT", "JST": "JST", "OESZ": "восточноєѵрѡпе́йское лѣ́тнее вре́мѧ", "COST": "COST", "HECU": "HECU", "HEPM": "HEPM", "HEEG": "HEEG", "HNT": "HNT", "AKST": "AKST", "AEDT": "AEDT", "COT": "COT", "EST": "восточноамерїка́нское зи́мнее вре́мѧ", "EDT": "восточноамерїка́нское лѣ́тнее вре́мѧ", "TMT": "TMT", "WARST": "WARST", "VET": "VET", "GFT": "GFT", "ACWST": "ACWST", "TMST": "TMST", "HEOG": "HEOG", "WAST": "WAST", "CAT": "CAT", "HEPMX": "HEPMX", "∅∅∅": "∅∅∅", "ART": "ART", "SGT": "SGT", "HNNOMX": "HNNOMX", "HKT": "HKT", "HNCU": "HNCU", "HNPM": "HNPM", "BT": "BT", "NZST": "NZST", "IST": "IST", "WESZ": "западноєѵрѡпе́йское лѣ́тнее вре́мѧ", "MESZ": "среднеєѵрѡпе́йское лѣ́тнее вре́мѧ", "ACDT": "ACDT", "AWDT": "AWDT", "SAST": "SAST", "AKDT": "AKDT", "HNPMX": "HNPMX", "WIB": "WIB", "CHAST": "CHAST", "MDT": "а҆мерїка́нское наго́рнее лѣ́тнее вре́мѧ", "WITA": "WITA", "OEZ": "восточноєѵрѡпе́йское зи́мнее вре́мѧ", "UYT": "UYT", "MST": "а҆мерїка́нское наго́рнее зи́мнее вре́мѧ", "AEST": "AEST", "PDT": "тихоѻкеа́нское лѣ́тнее вре́мѧ", "HKST": "HKST", "GYT": "GYT", "ACST": "ACST", "BOT": "BOT", "CST": "среднеамерїка́нское зи́мнее вре́мѧ", "LHST": "LHST", "WART": "WART", "HENOMX": "HENOMX", "HNOG": "HNOG", "WAT": "WAT", "ChST": "ChST"},
- }
-}
-
-// Locale returns the current translators string locale
-func (cu *cu) Locale() string {
- return cu.locale
-}
-
-// PluralsCardinal returns the list of cardinal plural rules associated with 'cu'
-func (cu *cu) PluralsCardinal() []locales.PluralRule {
- return cu.pluralsCardinal
-}
-
-// PluralsOrdinal returns the list of ordinal plural rules associated with 'cu'
-func (cu *cu) PluralsOrdinal() []locales.PluralRule {
- return cu.pluralsOrdinal
-}
-
-// PluralsRange returns the list of range plural rules associated with 'cu'
-func (cu *cu) PluralsRange() []locales.PluralRule {
- return cu.pluralsRange
-}
-
-// CardinalPluralRule returns the cardinal PluralRule given 'num' and digits/precision of 'v' for 'cu'
-func (cu *cu) CardinalPluralRule(num float64, v uint64) locales.PluralRule {
- return locales.PluralRuleUnknown
-}
-
-// OrdinalPluralRule returns the ordinal PluralRule given 'num' and digits/precision of 'v' for 'cu'
-func (cu *cu) OrdinalPluralRule(num float64, v uint64) locales.PluralRule {
- return locales.PluralRuleUnknown
-}
-
-// RangePluralRule returns the ordinal PluralRule given 'num1', 'num2' and digits/precision of 'v1' and 'v2' for 'cu'
-func (cu *cu) RangePluralRule(num1 float64, v1 uint64, num2 float64, v2 uint64) locales.PluralRule {
- return locales.PluralRuleUnknown
-}
-
-// MonthAbbreviated returns the locales abbreviated month given the 'month' provided
-func (cu *cu) MonthAbbreviated(month time.Month) string {
- return cu.monthsAbbreviated[month]
-}
-
-// MonthsAbbreviated returns the locales abbreviated months
-func (cu *cu) MonthsAbbreviated() []string {
- return cu.monthsAbbreviated[1:]
-}
-
-// MonthNarrow returns the locales narrow month given the 'month' provided
-func (cu *cu) MonthNarrow(month time.Month) string {
- return cu.monthsNarrow[month]
-}
-
-// MonthsNarrow returns the locales narrow months
-func (cu *cu) MonthsNarrow() []string {
- return cu.monthsNarrow[1:]
-}
-
-// MonthWide returns the locales wide month given the 'month' provided
-func (cu *cu) MonthWide(month time.Month) string {
- return cu.monthsWide[month]
-}
-
-// MonthsWide returns the locales wide months
-func (cu *cu) MonthsWide() []string {
- return cu.monthsWide[1:]
-}
-
-// WeekdayAbbreviated returns the locales abbreviated weekday given the 'weekday' provided
-func (cu *cu) WeekdayAbbreviated(weekday time.Weekday) string {
- return cu.daysAbbreviated[weekday]
-}
-
-// WeekdaysAbbreviated returns the locales abbreviated weekdays
-func (cu *cu) WeekdaysAbbreviated() []string {
- return cu.daysAbbreviated
-}
-
-// WeekdayNarrow returns the locales narrow weekday given the 'weekday' provided
-func (cu *cu) WeekdayNarrow(weekday time.Weekday) string {
- return cu.daysNarrow[weekday]
-}
-
-// WeekdaysNarrow returns the locales narrow weekdays
-func (cu *cu) WeekdaysNarrow() []string {
- return cu.daysNarrow
-}
-
-// WeekdayShort returns the locales short weekday given the 'weekday' provided
-func (cu *cu) WeekdayShort(weekday time.Weekday) string {
- return cu.daysShort[weekday]
-}
-
-// WeekdaysShort returns the locales short weekdays
-func (cu *cu) WeekdaysShort() []string {
- return cu.daysShort
-}
-
-// WeekdayWide returns the locales wide weekday given the 'weekday' provided
-func (cu *cu) WeekdayWide(weekday time.Weekday) string {
- return cu.daysWide[weekday]
-}
-
-// WeekdaysWide returns the locales wide weekdays
-func (cu *cu) WeekdaysWide() []string {
- return cu.daysWide
-}
-
-// Decimal returns the decimal point of number
-func (cu *cu) Decimal() string {
- return cu.decimal
-}
-
-// Group returns the group of number
-func (cu *cu) Group() string {
- return cu.group
-}
-
-// Group returns the minus sign of number
-func (cu *cu) Minus() string {
- return cu.minus
-}
-
-// FmtNumber returns 'num' with digits/precision of 'v' for 'cu' and handles both Whole and Real numbers based on 'v'
-func (cu *cu) FmtNumber(num float64, v uint64) string {
-
- s := strconv.FormatFloat(math.Abs(num), 'f', int(v), 64)
- l := len(s) + 2 + 2*len(s[:len(s)-int(v)-1])/3
- count := 0
- inWhole := v == 0
- b := make([]byte, 0, l)
-
- for i := len(s) - 1; i >= 0; i-- {
-
- if s[i] == '.' {
- b = append(b, cu.decimal[0])
- inWhole = true
- continue
- }
-
- if inWhole {
- if count == 3 {
- for j := len(cu.group) - 1; j >= 0; j-- {
- b = append(b, cu.group[j])
- }
- count = 1
- } else {
- count++
- }
- }
-
- b = append(b, s[i])
- }
-
- if num < 0 {
- b = append(b, cu.minus[0])
- }
-
- // reverse
- for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {
- b[i], b[j] = b[j], b[i]
- }
-
- return string(b)
-}
-
-// FmtPercent returns 'num' with digits/precision of 'v' for 'cu' and handles both Whole and Real numbers based on 'v'
-// NOTE: 'num' passed into FmtPercent is assumed to be in percent already
-func (cu *cu) FmtPercent(num float64, v uint64) string {
- s := strconv.FormatFloat(math.Abs(num), 'f', int(v), 64)
- l := len(s) + 5
- b := make([]byte, 0, l)
-
- for i := len(s) - 1; i >= 0; i-- {
-
- if s[i] == '.' {
- b = append(b, cu.decimal[0])
- continue
- }
-
- b = append(b, s[i])
- }
-
- if num < 0 {
- b = append(b, cu.minus[0])
- }
-
- // reverse
- for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {
- b[i], b[j] = b[j], b[i]
- }
-
- b = append(b, cu.percentSuffix...)
-
- b = append(b, cu.percent...)
-
- return string(b)
-}
-
-// FmtCurrency returns the currency representation of 'num' with digits/precision of 'v' for 'cu'
-func (cu *cu) FmtCurrency(num float64, v uint64, currency currency.Type) string {
-
- s := strconv.FormatFloat(math.Abs(num), 'f', int(v), 64)
- symbol := cu.currencies[currency]
- l := len(s) + len(symbol) + 4 + 2*len(s[:len(s)-int(v)-1])/3
- count := 0
- inWhole := v == 0
- b := make([]byte, 0, l)
-
- for i := len(s) - 1; i >= 0; i-- {
-
- if s[i] == '.' {
- b = append(b, cu.decimal[0])
- inWhole = true
- continue
- }
-
- if inWhole {
- if count == 3 {
- for j := len(cu.group) - 1; j >= 0; j-- {
- b = append(b, cu.group[j])
- }
- count = 1
- } else {
- count++
- }
- }
-
- b = append(b, s[i])
- }
-
- if num < 0 {
- b = append(b, cu.minus[0])
- }
-
- // reverse
- for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {
- b[i], b[j] = b[j], b[i]
- }
-
- if int(v) < 2 {
-
- if v == 0 {
- b = append(b, cu.decimal...)
- }
-
- for i := 0; i < 2-int(v); i++ {
- b = append(b, '0')
- }
- }
-
- b = append(b, cu.currencyPositiveSuffix...)
-
- b = append(b, symbol...)
-
- return string(b)
-}
-
-// FmtAccounting returns the currency representation of 'num' with digits/precision of 'v' for 'cu'
-// in accounting notation.
-func (cu *cu) FmtAccounting(num float64, v uint64, currency currency.Type) string {
-
- s := strconv.FormatFloat(math.Abs(num), 'f', int(v), 64)
- symbol := cu.currencies[currency]
- l := len(s) + len(symbol) + 4 + 2*len(s[:len(s)-int(v)-1])/3
- count := 0
- inWhole := v == 0
- b := make([]byte, 0, l)
-
- for i := len(s) - 1; i >= 0; i-- {
-
- if s[i] == '.' {
- b = append(b, cu.decimal[0])
- inWhole = true
- continue
- }
-
- if inWhole {
- if count == 3 {
- for j := len(cu.group) - 1; j >= 0; j-- {
- b = append(b, cu.group[j])
- }
- count = 1
- } else {
- count++
- }
- }
-
- b = append(b, s[i])
- }
-
- if num < 0 {
-
- b = append(b, cu.minus[0])
-
- }
-
- // reverse
- for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {
- b[i], b[j] = b[j], b[i]
- }
-
- if int(v) < 2 {
-
- if v == 0 {
- b = append(b, cu.decimal...)
- }
-
- for i := 0; i < 2-int(v); i++ {
- b = append(b, '0')
- }
- }
-
- if num < 0 {
- b = append(b, cu.currencyNegativeSuffix...)
- b = append(b, symbol...)
- } else {
-
- b = append(b, cu.currencyPositiveSuffix...)
- b = append(b, symbol...)
- }
-
- return string(b)
-}
-
-// FmtDateShort returns the short date representation of 't' for 'cu'
-func (cu *cu) FmtDateShort(t time.Time) string {
-
- b := make([]byte, 0, 32)
-
- if t.Year() > 0 {
- b = strconv.AppendInt(b, int64(t.Year()), 10)
- } else {
- b = strconv.AppendInt(b, int64(-t.Year()), 10)
- }
-
- b = append(b, []byte{0x2e}...)
-
- if t.Month() < 10 {
- b = append(b, '0')
- }
-
- b = strconv.AppendInt(b, int64(t.Month()), 10)
-
- b = append(b, []byte{0x2e}...)
-
- if t.Day() < 10 {
- b = append(b, '0')
- }
-
- b = strconv.AppendInt(b, int64(t.Day()), 10)
-
- return string(b)
-}
-
-// FmtDateMedium returns the medium date representation of 't' for 'cu'
-func (cu *cu) FmtDateMedium(t time.Time) string {
-
- b := make([]byte, 0, 32)
-
- if t.Year() > 0 {
- b = strconv.AppendInt(b, int64(t.Year()), 10)
- } else {
- b = strconv.AppendInt(b, int64(-t.Year()), 10)
- }
-
- b = append(b, []byte{0x20}...)
- b = append(b, cu.monthsAbbreviated[t.Month()]...)
- b = append(b, []byte{0x20}...)
- b = strconv.AppendInt(b, int64(t.Day()), 10)
-
- return string(b)
-}
-
-// FmtDateLong returns the long date representation of 't' for 'cu'
-func (cu *cu) FmtDateLong(t time.Time) string {
-
- b := make([]byte, 0, 32)
-
- if t.Year() > 0 {
- b = strconv.AppendInt(b, int64(t.Year()), 10)
- } else {
- b = strconv.AppendInt(b, int64(-t.Year()), 10)
- }
-
- b = append(b, []byte{0x20}...)
- b = append(b, cu.monthsWide[t.Month()]...)
- b = append(b, []byte{0x20}...)
- b = strconv.AppendInt(b, int64(t.Day()), 10)
-
- return string(b)
-}
-
-// FmtDateFull returns the full date representation of 't' for 'cu'
-func (cu *cu) FmtDateFull(t time.Time) string {
-
- b := make([]byte, 0, 32)
-
- b = append(b, cu.daysWide[t.Weekday()]...)
- b = append(b, []byte{0x2c, 0x20}...)
- b = strconv.AppendInt(b, int64(t.Day()), 10)
- b = append(b, []byte{0x20}...)
- b = append(b, cu.monthsWide[t.Month()]...)
- b = append(b, []byte{0x20, 0xd0, 0xbb}...)
- b = append(b, []byte{0x2e, 0x20}...)
-
- if t.Year() > 0 {
- b = strconv.AppendInt(b, int64(t.Year()), 10)
- } else {
- b = strconv.AppendInt(b, int64(-t.Year()), 10)
- }
-
- b = append(b, []byte{0x2e}...)
-
- return string(b)
-}
-
-// FmtTimeShort returns the short time representation of 't' for 'cu'
-func (cu *cu) FmtTimeShort(t time.Time) string {
-
- b := make([]byte, 0, 32)
-
- if t.Hour() < 10 {
- b = append(b, '0')
- }
-
- b = strconv.AppendInt(b, int64(t.Hour()), 10)
- b = append(b, cu.timeSeparator...)
-
- if t.Minute() < 10 {
- b = append(b, '0')
- }
-
- b = strconv.AppendInt(b, int64(t.Minute()), 10)
-
- return string(b)
-}
-
-// FmtTimeMedium returns the medium time representation of 't' for 'cu'
-func (cu *cu) FmtTimeMedium(t time.Time) string {
-
- b := make([]byte, 0, 32)
-
- if t.Hour() < 10 {
- b = append(b, '0')
- }
-
- b = strconv.AppendInt(b, int64(t.Hour()), 10)
- b = append(b, cu.timeSeparator...)
-
- if t.Minute() < 10 {
- b = append(b, '0')
- }
-
- b = strconv.AppendInt(b, int64(t.Minute()), 10)
- b = append(b, cu.timeSeparator...)
-
- if t.Second() < 10 {
- b = append(b, '0')
- }
-
- b = strconv.AppendInt(b, int64(t.Second()), 10)
-
- return string(b)
-}
-
-// FmtTimeLong returns the long time representation of 't' for 'cu'
-func (cu *cu) FmtTimeLong(t time.Time) string {
-
- b := make([]byte, 0, 32)
-
- if t.Hour() < 10 {
- b = append(b, '0')
- }
-
- b = strconv.AppendInt(b, int64(t.Hour()), 10)
- b = append(b, cu.timeSeparator...)
-
- if t.Minute() < 10 {
- b = append(b, '0')
- }
-
- b = strconv.AppendInt(b, int64(t.Minute()), 10)
- b = append(b, cu.timeSeparator...)
-
- if t.Second() < 10 {
- b = append(b, '0')
- }
-
- b = strconv.AppendInt(b, int64(t.Second()), 10)
- b = append(b, []byte{0x20}...)
-
- tz, _ := t.Zone()
- b = append(b, tz...)
-
- return string(b)
-}
-
-// FmtTimeFull returns the full time representation of 't' for 'cu'
-func (cu *cu) FmtTimeFull(t time.Time) string {
-
- b := make([]byte, 0, 32)
-
- if t.Hour() < 10 {
- b = append(b, '0')
- }
-
- b = strconv.AppendInt(b, int64(t.Hour()), 10)
- b = append(b, cu.timeSeparator...)
-
- if t.Minute() < 10 {
- b = append(b, '0')
- }
-
- b = strconv.AppendInt(b, int64(t.Minute()), 10)
- b = append(b, cu.timeSeparator...)
-
- if t.Second() < 10 {
- b = append(b, '0')
- }
-
- b = strconv.AppendInt(b, int64(t.Second()), 10)
- b = append(b, []byte{0x20}...)
-
- tz, _ := t.Zone()
-
- if btz, ok := cu.timezones[tz]; ok {
- b = append(b, btz...)
- } else {
- b = append(b, tz...)
- }
-
- return string(b)
-}
diff --git a/vendor/github.com/go-playground/locales/cu/cu_test.go b/vendor/github.com/go-playground/locales/cu/cu_test.go
deleted file mode 100644
index 91c734a..0000000
--- a/vendor/github.com/go-playground/locales/cu/cu_test.go
+++ /dev/null
@@ -1,1120 +0,0 @@
-package cu
-
-import (
- "testing"
- "time"
-
- "github.com/go-playground/locales"
- "github.com/go-playground/locales/currency"
-)
-
-func TestLocale(t *testing.T) {
-
- trans := New()
- expected := "cu"
-
- if trans.Locale() != expected {
- t.Errorf("Expected '%s' Got '%s'", expected, trans.Locale())
- }
-}
-
-func TestPluralsRange(t *testing.T) {
-
- trans := New()
-
- tests := []struct {
- expected locales.PluralRule
- }{
- // {
- // expected: locales.PluralRuleOther,
- // },
- }
-
- rules := trans.PluralsRange()
- // expected := 1
- // if len(rules) != expected {
- // t.Errorf("Expected '%d' Got '%d'", expected, len(rules))
- // }
-
- for _, tt := range tests {
-
- r := locales.PluralRuleUnknown
-
- for i := 0; i < len(rules); i++ {
- if rules[i] == tt.expected {
- r = rules[i]
- break
- }
- }
- if r == locales.PluralRuleUnknown {
- t.Errorf("Expected '%s' Got '%s'", tt.expected, r)
- }
- }
-}
-
-func TestPluralsOrdinal(t *testing.T) {
-
- trans := New()
-
- tests := []struct {
- expected locales.PluralRule
- }{
- // {
- // expected: locales.PluralRuleOne,
- // },
- // {
- // expected: locales.PluralRuleTwo,
- // },
- // {
- // expected: locales.PluralRuleFew,
- // },
- // {
- // expected: locales.PluralRuleOther,
- // },
- }
-
- rules := trans.PluralsOrdinal()
- // expected := 4
- // if len(rules) != expected {
- // t.Errorf("Expected '%d' Got '%d'", expected, len(rules))
- // }
-
- for _, tt := range tests {
-
- r := locales.PluralRuleUnknown
-
- for i := 0; i < len(rules); i++ {
- if rules[i] == tt.expected {
- r = rules[i]
- break
- }
- }
- if r == locales.PluralRuleUnknown {
- t.Errorf("Expected '%s' Got '%s'", tt.expected, r)
- }
- }
-}
-
-func TestPluralsCardinal(t *testing.T) {
-
- trans := New()
-
- tests := []struct {
- expected locales.PluralRule
- }{
- // {
- // expected: locales.PluralRuleOne,
- // },
- // {
- // expected: locales.PluralRuleOther,
- // },
- }
-
- rules := trans.PluralsCardinal()
- // expected := 2
- // if len(rules) != expected {
- // t.Errorf("Expected '%d' Got '%d'", expected, len(rules))
- // }
-
- for _, tt := range tests {
-
- r := locales.PluralRuleUnknown
-
- for i := 0; i < len(rules); i++ {
- if rules[i] == tt.expected {
- r = rules[i]
- break
- }
- }
- if r == locales.PluralRuleUnknown {
- t.Errorf("Expected '%s' Got '%s'", tt.expected, r)
- }
- }
-}
-
-func TestRangePlurals(t *testing.T) {
-
- trans := New()
-
- tests := []struct {
- num1 float64
- v1 uint64
- num2 float64
- v2 uint64
- expected locales.PluralRule
- }{
- // {
- // num1: 1,
- // v1: 1,
- // num2: 2,
- // v2: 2,
- // expected: locales.PluralRuleOther,
- // },
- }
-
- for _, tt := range tests {
- rule := trans.RangePluralRule(tt.num1, tt.v1, tt.num2, tt.v2)
- if rule != tt.expected {
- t.Errorf("Expected '%s' Got '%s'", tt.expected, rule)
- }
- }
-}
-
-func TestOrdinalPlurals(t *testing.T) {
-
- trans := New()
-
- tests := []struct {
- num float64
- v uint64
- expected locales.PluralRule
- }{
- // {
- // num: 1,
- // v: 0,
- // expected: locales.PluralRuleOne,
- // },
- // {
- // num: 2,
- // v: 0,
- // expected: locales.PluralRuleTwo,
- // },
- // {
- // num: 3,
- // v: 0,
- // expected: locales.PluralRuleFew,
- // },
- // {
- // num: 4,
- // v: 0,
- // expected: locales.PluralRuleOther,
- // },
- }
-
- for _, tt := range tests {
- rule := trans.OrdinalPluralRule(tt.num, tt.v)
- if rule != tt.expected {
- t.Errorf("Expected '%s' Got '%s'", tt.expected, rule)
- }
- }
-}
-
-func TestCardinalPlurals(t *testing.T) {
-
- trans := New()
-
- tests := []struct {
- num float64
- v uint64
- expected locales.PluralRule
- }{
- // {
- // num: 1,
- // v: 0,
- // expected: locales.PluralRuleOne,
- // },
- // {
- // num: 4,
- // v: 0,
- // expected: locales.PluralRuleOther,
- // },
- }
-
- for _, tt := range tests {
- rule := trans.CardinalPluralRule(tt.num, tt.v)
- if rule != tt.expected {
- t.Errorf("Expected '%s' Got '%s'", tt.expected, rule)
- }
- }
-}
-
-func TestDaysAbbreviated(t *testing.T) {
-
- trans := New()
- days := trans.WeekdaysAbbreviated()
-
- for i, day := range days {
- s := trans.WeekdayAbbreviated(time.Weekday(i))
- if s != day {
- t.Errorf("Expected '%s' Got '%s'", day, s)
- }
- }
-
- tests := []struct {
- idx int
- expected string
- }{
- // {
- // idx: 0,
- // expected: "Sun",
- // },
- // {
- // idx: 1,
- // expected: "Mon",
- // },
- // {
- // idx: 2,
- // expected: "Tue",
- // },
- // {
- // idx: 3,
- // expected: "Wed",
- // },
- // {
- // idx: 4,
- // expected: "Thu",
- // },
- // {
- // idx: 5,
- // expected: "Fri",
- // },
- // {
- // idx: 6,
- // expected: "Sat",
- // },
- }
-
- for _, tt := range tests {
- s := trans.WeekdayAbbreviated(time.Weekday(tt.idx))
- if s != tt.expected {
- t.Errorf("Expected '%s' Got '%s'", tt.expected, s)
- }
- }
-}
-
-func TestDaysNarrow(t *testing.T) {
-
- trans := New()
- days := trans.WeekdaysNarrow()
-
- for i, day := range days {
- s := trans.WeekdayNarrow(time.Weekday(i))
- if s != day {
- t.Errorf("Expected '%s' Got '%s'", string(day), s)
- }
- }
-
- tests := []struct {
- idx int
- expected string
- }{
- // {
- // idx: 0,
- // expected: "S",
- // },
- // {
- // idx: 1,
- // expected: "M",
- // },
- // {
- // idx: 2,
- // expected: "T",
- // },
- // {
- // idx: 3,
- // expected: "W",
- // },
- // {
- // idx: 4,
- // expected: "T",
- // },
- // {
- // idx: 5,
- // expected: "F",
- // },
- // {
- // idx: 6,
- // expected: "S",
- // },
- }
-
- for _, tt := range tests {
- s := trans.WeekdayNarrow(time.Weekday(tt.idx))
- if s != tt.expected {
- t.Errorf("Expected '%s' Got '%s'", tt.expected, s)
- }
- }
-}
-
-func TestDaysShort(t *testing.T) {
-
- trans := New()
- days := trans.WeekdaysShort()
-
- for i, day := range days {
- s := trans.WeekdayShort(time.Weekday(i))
- if s != day {
- t.Errorf("Expected '%s' Got '%s'", day, s)
- }
- }
-
- tests := []struct {
- idx int
- expected string
- }{
- // {
- // idx: 0,
- // expected: "Su",
- // },
- // {
- // idx: 1,
- // expected: "Mo",
- // },
- // {
- // idx: 2,
- // expected: "Tu",
- // },
- // {
- // idx: 3,
- // expected: "We",
- // },
- // {
- // idx: 4,
- // expected: "Th",
- // },
- // {
- // idx: 5,
- // expected: "Fr",
- // },
- // {
- // idx: 6,
- // expected: "Sa",
- // },
- }
-
- for _, tt := range tests {
- s := trans.WeekdayShort(time.Weekday(tt.idx))
- if s != tt.expected {
- t.Errorf("Expected '%s' Got '%s'", tt.expected, s)
- }
- }
-}
-
-func TestDaysWide(t *testing.T) {
-
- trans := New()
- days := trans.WeekdaysWide()
-
- for i, day := range days {
- s := trans.WeekdayWide(time.Weekday(i))
- if s != day {
- t.Errorf("Expected '%s' Got '%s'", day, s)
- }
- }
-
- tests := []struct {
- idx int
- expected string
- }{
- // {
- // idx: 0,
- // expected: "Sunday",
- // },
- // {
- // idx: 1,
- // expected: "Monday",
- // },
- // {
- // idx: 2,
- // expected: "Tuesday",
- // },
- // {
- // idx: 3,
- // expected: "Wednesday",
- // },
- // {
- // idx: 4,
- // expected: "Thursday",
- // },
- // {
- // idx: 5,
- // expected: "Friday",
- // },
- // {
- // idx: 6,
- // expected: "Saturday",
- // },
- }
-
- for _, tt := range tests {
- s := trans.WeekdayWide(time.Weekday(tt.idx))
- if s != tt.expected {
- t.Errorf("Expected '%s' Got '%s'", tt.expected, s)
- }
- }
-}
-
-func TestMonthsAbbreviated(t *testing.T) {
-
- trans := New()
- months := trans.MonthsAbbreviated()
-
- for i, month := range months {
- s := trans.MonthAbbreviated(time.Month(i + 1))
- if s != month {
- t.Errorf("Expected '%s' Got '%s'", month, s)
- }
- }
-
- tests := []struct {
- idx int
- expected string
- }{
- // {
- // idx: 1,
- // expected: "Jan",
- // },
- // {
- // idx: 2,
- // expected: "Feb",
- // },
- // {
- // idx: 3,
- // expected: "Mar",
- // },
- // {
- // idx: 4,
- // expected: "Apr",
- // },
- // {
- // idx: 5,
- // expected: "May",
- // },
- // {
- // idx: 6,
- // expected: "Jun",
- // },
- // {
- // idx: 7,
- // expected: "Jul",
- // },
- // {
- // idx: 8,
- // expected: "Aug",
- // },
- // {
- // idx: 9,
- // expected: "Sep",
- // },
- // {
- // idx: 10,
- // expected: "Oct",
- // },
- // {
- // idx: 11,
- // expected: "Nov",
- // },
- // {
- // idx: 12,
- // expected: "Dec",
- // },
- }
-
- for _, tt := range tests {
- s := trans.MonthAbbreviated(time.Month(tt.idx))
- if s != tt.expected {
- t.Errorf("Expected '%s' Got '%s'", tt.expected, s)
- }
- }
-}
-
-func TestMonthsNarrow(t *testing.T) {
-
- trans := New()
- months := trans.MonthsNarrow()
-
- for i, month := range months {
- s := trans.MonthNarrow(time.Month(i + 1))
- if s != month {
- t.Errorf("Expected '%s' Got '%s'", month, s)
- }
- }
-
- tests := []struct {
- idx int
- expected string
- }{
- // {
- // idx: 1,
- // expected: "J",
- // },
- // {
- // idx: 2,
- // expected: "F",
- // },
- // {
- // idx: 3,
- // expected: "M",
- // },
- // {
- // idx: 4,
- // expected: "A",
- // },
- // {
- // idx: 5,
- // expected: "M",
- // },
- // {
- // idx: 6,
- // expected: "J",
- // },
- // {
- // idx: 7,
- // expected: "J",
- // },
- // {
- // idx: 8,
- // expected: "A",
- // },
- // {
- // idx: 9,
- // expected: "S",
- // },
- // {
- // idx: 10,
- // expected: "O",
- // },
- // {
- // idx: 11,
- // expected: "N",
- // },
- // {
- // idx: 12,
- // expected: "D",
- // },
- }
-
- for _, tt := range tests {
- s := trans.MonthNarrow(time.Month(tt.idx))
- if s != tt.expected {
- t.Errorf("Expected '%s' Got '%s'", tt.expected, s)
- }
- }
-}
-
-func TestMonthsWide(t *testing.T) {
-
- trans := New()
- months := trans.MonthsWide()
-
- for i, month := range months {
- s := trans.MonthWide(time.Month(i + 1))
- if s != month {
- t.Errorf("Expected '%s' Got '%s'", month, s)
- }
- }
-
- tests := []struct {
- idx int
- expected string
- }{
- // {
- // idx: 1,
- // expected: "January",
- // },
- // {
- // idx: 2,
- // expected: "February",
- // },
- // {
- // idx: 3,
- // expected: "March",
- // },
- // {
- // idx: 4,
- // expected: "April",
- // },
- // {
- // idx: 5,
- // expected: "May",
- // },
- // {
- // idx: 6,
- // expected: "June",
- // },
- // {
- // idx: 7,
- // expected: "July",
- // },
- // {
- // idx: 8,
- // expected: "August",
- // },
- // {
- // idx: 9,
- // expected: "September",
- // },
- // {
- // idx: 10,
- // expected: "October",
- // },
- // {
- // idx: 11,
- // expected: "November",
- // },
- // {
- // idx: 12,
- // expected: "December",
- // },
- }
-
- for _, tt := range tests {
- s := string(trans.MonthWide(time.Month(tt.idx)))
- if s != tt.expected {
- t.Errorf("Expected '%s' Got '%s'", tt.expected, s)
- }
- }
-}
-
-func TestFmtTimeFull(t *testing.T) {
-
- // loc, err := time.LoadLocation("America/Toronto")
- // if err != nil {
- // t.Errorf("Expected '<nil>' Got '%s'", err)
- // }
-
- // fixed := time.FixedZone("OTHER", -4)
-
- tests := []struct {
- t time.Time
- expected string
- }{
- // {
- // t: time.Date(2016, 02, 03, 9, 5, 1, 0, loc),
- // expected: "9:05:01 am Eastern Standard Time",
- // },
- // {
- // t: time.Date(2016, 02, 03, 20, 5, 1, 0, fixed),
- // expected: "8:05:01 pm OTHER",
- // },
- }
-
- trans := New()
-
- for _, tt := range tests {
- s := trans.FmtTimeFull(tt.t)
- if s != tt.expected {
- t.Errorf("Expected '%s' Got '%s'", tt.expected, s)
- }
- }
-}
-
-func TestFmtTimeLong(t *testing.T) {
-
- // loc, err := time.LoadLocation("America/Toronto")
- // if err != nil {
- // t.Errorf("Expected '<nil>' Got '%s'", err)
- // }
-
- tests := []struct {
- t time.Time
- expected string
- }{
- // {
- // t: time.Date(2016, 02, 03, 9, 5, 1, 0, loc),
- // expected: "9:05:01 am EST",
- // },
- // {
- // t: time.Date(2016, 02, 03, 20, 5, 1, 0, loc),
- // expected: "8:05:01 pm EST",
- // },
- }
-
- trans := New()
-
- for _, tt := range tests {
- s := trans.FmtTimeLong(tt.t)
- if s != tt.expected {
- t.Errorf("Expected '%s' Got '%s'", tt.expected, s)
- }
- }
-}
-
-func TestFmtTimeMedium(t *testing.T) {
-
- tests := []struct {
- t time.Time
- expected string
- }{
- // {
- // t: time.Date(2016, 02, 03, 9, 5, 1, 0, time.UTC),
- // expected: "9:05:01 am",
- // },
- // {
- // t: time.Date(2016, 02, 03, 20, 5, 1, 0, time.UTC),
- // expected: "8:05:01 pm",
- // },
- }
-
- trans := New()
-
- for _, tt := range tests {
- s := trans.FmtTimeMedium(tt.t)
- if s != tt.expected {
- t.Errorf("Expected '%s' Got '%s'", tt.expected, s)
- }
- }
-}
-
-func TestFmtTimeShort(t *testing.T) {
-
- tests := []struct {
- t time.Time
- expected string
- }{
- // {
- // t: time.Date(2016, 02, 03, 9, 5, 1, 0, time.UTC),
- // expected: "9:05 am",
- // },
- // {
- // t: time.Date(2016, 02, 03, 20, 5, 1, 0, time.UTC),
- // expected: "8:05 pm",
- // },
- }
-
- trans := New()
-
- for _, tt := range tests {
- s := trans.FmtTimeShort(tt.t)
- if s != tt.expected {
- t.Errorf("Expected '%s' Got '%s'", tt.expected, s)
- }
- }
-}
-
-func TestFmtDateFull(t *testing.T) {
-
- tests := []struct {
- t time.Time
- expected string
- }{
- // {
- // t: time.Date(2016, 02, 03, 9, 0, 1, 0, time.UTC),
- // expected: "Wednesday, February 3, 2016",
- // },
- }
-
- trans := New()
-
- for _, tt := range tests {
- s := trans.FmtDateFull(tt.t)
- if s != tt.expected {
- t.Errorf("Expected '%s' Got '%s'", tt.expected, s)
- }
- }
-}
-
-func TestFmtDateLong(t *testing.T) {
-
- tests := []struct {
- t time.Time
- expected string
- }{
- // {
- // t: time.Date(2016, 02, 03, 9, 0, 1, 0, time.UTC),
- // expected: "February 3, 2016",
- // },
- }
-
- trans := New()
-
- for _, tt := range tests {
- s := trans.FmtDateLong(tt.t)
- if s != tt.expected {
- t.Errorf("Expected '%s' Got '%s'", tt.expected, s)
- }
- }
-}
-
-func TestFmtDateMedium(t *testing.T) {
-
- tests := []struct {
- t time.Time
- expected string
- }{
- // {
- // t: time.Date(2016, 02, 03, 9, 0, 1, 0, time.UTC),
- // expected: "Feb 3, 2016",
- // },
- }
-
- trans := New()
-
- for _, tt := range tests {
- s := trans.FmtDateMedium(tt.t)
- if s != tt.expected {
- t.Errorf("Expected '%s' Got '%s'", tt.expected, s)
- }
- }
-}
-
-func TestFmtDateShort(t *testing.T) {
-
- tests := []struct {
- t time.Time
- expected string
- }{
- // {
- // t: time.Date(2016, 02, 03, 9, 0, 1, 0, time.UTC),
- // expected: "2/3/16",
- // },
- // {
- // t: time.Date(-500, 02, 03, 9, 0, 1, 0, time.UTC),
- // expected: "2/3/500",
- // },
- }
-
- trans := New()
-
- for _, tt := range tests {
- s := trans.FmtDateShort(tt.t)
- if s != tt.expected {
- t.Errorf("Expected '%s' Got '%s'", tt.expected, s)
- }
- }
-}
-
-func TestFmtNumber(t *testing.T) {
-
- tests := []struct {
- num float64
- v uint64
- expected string
- }{
- // {
- // num: 1123456.5643,
- // v: 2,
- // expected: "1,123,456.56",
- // },
- // {
- // num: 1123456.5643,
- // v: 1,
- // expected: "1,123,456.6",
- // },
- // {
- // num: 221123456.5643,
- // v: 3,
- // expected: "221,123,456.564",
- // },
- // {
- // num: -221123456.5643,
- // v: 3,
- // expected: "-221,123,456.564",
- // },
- // {
- // num: -221123456.5643,
- // v: 3,
- // expected: "-221,123,456.564",
- // },
- // {
- // num: 0,
- // v: 2,
- // expected: "0.00",
- // },
- // {
- // num: -0,
- // v: 2,
- // expected: "0.00",
- // },
- // {
- // num: -0,
- // v: 2,
- // expected: "0.00",
- // },
- }
-
- trans := New()
-
- for _, tt := range tests {
- s := trans.FmtNumber(tt.num, tt.v)
- if s != tt.expected {
- t.Errorf("Expected '%s' Got '%s'", tt.expected, s)
- }
- }
-}
-
-func TestFmtCurrency(t *testing.T) {
-
- tests := []struct {
- num float64
- v uint64
- currency currency.Type
- expected string
- }{
- // {
- // num: 1123456.5643,
- // v: 2,
- // currency: currency.USD,
- // expected: "$1,123,456.56",
- // },
- // {
- // num: 1123456.5643,
- // v: 1,
- // currency: currency.USD,
- // expected: "$1,123,456.60",
- // },
- // {
- // num: 221123456.5643,
- // v: 3,
- // currency: currency.USD,
- // expected: "$221,123,456.564",
- // },
- // {
- // num: -221123456.5643,
- // v: 3,
- // currency: currency.USD,
- // expected: "-$221,123,456.564",
- // },
- // {
- // num: -221123456.5643,
- // v: 3,
- // currency: currency.CAD,
- // expected: "-CAD 221,123,456.564",
- // },
- // {
- // num: 0,
- // v: 2,
- // currency: currency.USD,
- // expected: "$0.00",
- // },
- // {
- // num: -0,
- // v: 2,
- // currency: currency.USD,
- // expected: "$0.00",
- // },
- // {
- // num: -0,
- // v: 2,
- // currency: currency.CAD,
- // expected: "CAD 0.00",
- // },
- // {
- // num: 1.23,
- // v: 0,
- // currency: currency.USD,
- // expected: "$1.00",
- // },
- }
-
- trans := New()
-
- for _, tt := range tests {
- s := trans.FmtCurrency(tt.num, tt.v, tt.currency)
- if s != tt.expected {
- t.Errorf("Expected '%s' Got '%s'", tt.expected, s)
- }
- }
-}
-
-func TestFmtAccounting(t *testing.T) {
-
- tests := []struct {
- num float64
- v uint64
- currency currency.Type
- expected string
- }{
- // {
- // num: 1123456.5643,
- // v: 2,
- // currency: currency.USD,
- // expected: "$1,123,456.56",
- // },
- // {
- // num: 1123456.5643,
- // v: 1,
- // currency: currency.USD,
- // expected: "$1,123,456.60",
- // },
- // {
- // num: 221123456.5643,
- // v: 3,
- // currency: currency.USD,
- // expected: "$221,123,456.564",
- // },
- // {
- // num: -221123456.5643,
- // v: 3,
- // currency: currency.USD,
- // expected: "($221,123,456.564)",
- // },
- // {
- // num: -221123456.5643,
- // v: 3,
- // currency: currency.CAD,
- // expected: "(CAD 221,123,456.564)",
- // },
- // {
- // num: -0,
- // v: 2,
- // currency: currency.USD,
- // expected: "$0.00",
- // },
- // {
- // num: -0,
- // v: 2,
- // currency: currency.CAD,
- // expected: "CAD 0.00",
- // },
- // {
- // num: 1.23,
- // v: 0,
- // currency: currency.USD,
- // expected: "$1.00",
- // },
- }
-
- trans := New()
-
- for _, tt := range tests {
- s := trans.FmtAccounting(tt.num, tt.v, tt.currency)
- if s != tt.expected {
- t.Errorf("Expected '%s' Got '%s'", tt.expected, s)
- }
- }
-}
-
-func TestFmtPercent(t *testing.T) {
-
- tests := []struct {
- num float64
- v uint64
- expected string
- }{
- // {
- // num: 15,
- // v: 0,
- // expected: "15%",
- // },
- // {
- // num: 15,
- // v: 2,
- // expected: "15.00%",
- // },
- // {
- // num: 434.45,
- // v: 0,
- // expected: "434%",
- // },
- // {
- // num: 34.4,
- // v: 2,
- // expected: "34.40%",
- // },
- // {
- // num: -34,
- // v: 0,
- // expected: "-34%",
- // },
- }
-
- trans := New()
-
- for _, tt := range tests {
- s := trans.FmtPercent(tt.num, tt.v)
- if s != tt.expected {
- t.Errorf("Expected '%s' Got '%s'", tt.expected, s)
- }
- }
-}
diff --git a/vendor/github.com/go-playground/locales/logo.png b/vendor/github.com/go-playground/locales/logo.png
deleted file mode 100644
index 3038276..0000000
--- a/vendor/github.com/go-playground/locales/logo.png
+++ /dev/null
Binary files differ
diff --git a/vendor/github.com/go-playground/universal-translator/.gitignore b/vendor/github.com/go-playground/universal-translator/.gitignore
deleted file mode 100644
index 2661785..0000000
--- a/vendor/github.com/go-playground/universal-translator/.gitignore
+++ /dev/null
@@ -1,24 +0,0 @@
-# Compiled Object files, Static and Dynamic libs (Shared Objects)
-*.o
-*.a
-*.so
-
-# Folders
-_obj
-_test
-
-# Architecture specific extensions/prefixes
-*.[568vq]
-[568vq].out
-
-*.cgo1.go
-*.cgo2.c
-_cgo_defun.c
-_cgo_gotypes.go
-_cgo_export.*
-
-_testmain.go
-
-*.exe
-*.test
-*.prof \ No newline at end of file
diff --git a/vendor/github.com/go-playground/universal-translator/README.md b/vendor/github.com/go-playground/universal-translator/README.md
deleted file mode 100644
index 24aef15..0000000
--- a/vendor/github.com/go-playground/universal-translator/README.md
+++ /dev/null
@@ -1,90 +0,0 @@
-## universal-translator
-<img align="right" src="https://raw.githubusercontent.com/go-playground/universal-translator/master/logo.png">
-![Project status](https://img.shields.io/badge/version-0.16.0-green.svg)
-[![Build Status](https://semaphoreci.com/api/v1/joeybloggs/universal-translator/branches/master/badge.svg)](https://semaphoreci.com/joeybloggs/universal-translator)
-[![Coverage Status](https://coveralls.io/repos/github/go-playground/universal-translator/badge.svg)](https://coveralls.io/github/go-playground/universal-translator)
-[![Go Report Card](https://goreportcard.com/badge/github.com/go-playground/universal-translator)](https://goreportcard.com/report/github.com/go-playground/universal-translator)
-[![GoDoc](https://godoc.org/github.com/go-playground/universal-translator?status.svg)](https://godoc.org/github.com/go-playground/universal-translator)
-![License](https://img.shields.io/dub/l/vibe-d.svg)
-[![Gitter](https://badges.gitter.im/go-playground/universal-translator.svg)](https://gitter.im/go-playground/universal-translator?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)
-
-Universal Translator is an i18n Translator for Go/Golang using CLDR data + pluralization rules
-
-Why another i18n library?
---------------------------
-Because none of the plural rules seem to be correct out there, including the previous implementation of this package,
-so I took it upon myself to create [locales](https://github.com/go-playground/locales) for everyone to use; this package
-is a thin wrapper around [locales](https://github.com/go-playground/locales) in order to store and translate text for
-use in your applications.
-
-Features
---------
-- [x] Rules generated from the [CLDR](http://cldr.unicode.org/index/downloads) data, v30.0.3
-- [x] Contains Cardinal, Ordinal and Range Plural Rules
-- [x] Contains Month, Weekday and Timezone translations built in
-- [x] Contains Date & Time formatting functions
-- [x] Contains Number, Currency, Accounting and Percent formatting functions
-- [x] Supports the "Gregorian" calendar only ( my time isn't unlimited, had to draw the line somewhere )
-- [x] Support loading translations from files
-- [x] Exporting translations to file(s), mainly for getting them professionally translated
-- [ ] Code Generation for translation files -> Go code.. i.e. after it has been professionally translated
-- [ ] Tests for all languages, I need help with this, please see [here](https://github.com/go-playground/locales/issues/1)
-
-Installation
------------
-
-Use go get
-
-```shell
-go get github.com/go-playground/universal-translator
-```
-
-Usage & Documentation
--------
-
-Please see https://godoc.org/github.com/go-playground/universal-translator for usage docs
-
-##### Examples:
-
-- [Basic](https://github.com/go-playground/universal-translator/tree/master/examples/basic)
-- [Full - no files](https://github.com/go-playground/universal-translator/tree/master/examples/full-no-files)
-- [Full - with files](https://github.com/go-playground/universal-translator/tree/master/examples/full-with-files)
-
-File formatting
---------------
-All types, Plain substitution, Cardinal, Ordinal and Range translations can all be contained withing the same file(s);
-they are only separated for easy viewing.
-
-##### Examples:
-
-- [Formats](https://github.com/go-playground/universal-translator/tree/master/examples/file-formats)
-
-##### Basic Makeup
-NOTE: not all fields are needed for all translation types, see [examples](https://github.com/go-playground/universal-translator/tree/master/examples/file-formats)
-```json
-{
- "locale": "en",
- "key": "days-left",
- "trans": "You have {0} day left.",
- "type": "Cardinal",
- "rule": "One",
- "override": false
-}
-```
-|Field|Description|
-|---|---|
-|locale|The locale for which the translation is for.|
-|key|The translation key that will be used to store and lookup each translation; normally it is a string or integer.|
-|trans|The actual translation text.|
-|type|The type of translation Cardinal, Ordinal, Range or "" for a plain substitution(not required to be defined if plain used)|
-|rule|The plural rule for which the translation is for eg. One, Two, Few, Many or Other.(not required to be defined if plain used)|
-|override|If you wish to override an existing translation that has already been registered, set this to 'true'. 99% of the time there is no need to define it.|
-
-Help With Tests
----------------
-To anyone interesting in helping or contributing, I sure could use some help creating tests for each language.
-Please see issue [here](https://github.com/go-playground/locales/issues/1) for details.
-
-License
-------
-Distributed under MIT License, please see license file in code for more details.
diff --git a/vendor/github.com/go-playground/universal-translator/benchmarks_test.go b/vendor/github.com/go-playground/universal-translator/benchmarks_test.go
deleted file mode 100644
index 3f5d0a4..0000000
--- a/vendor/github.com/go-playground/universal-translator/benchmarks_test.go
+++ /dev/null
@@ -1,110 +0,0 @@
-package ut
-
-import (
- "testing"
-
- "github.com/go-playground/locales/en"
-)
-
-func BenchmarkBasicTranslation(b *testing.B) {
-
- en := en.New()
- ut := New(en, en)
- loc, found := ut.FindTranslator("en")
- if !found {
- b.Fatalf("Expected '%t' Got '%t'", true, found)
- }
-
- translations := []struct {
- key interface{}
- trans string
- expected error
- override bool
- }{
- {
- key: "welcome",
- trans: "Welcome to the site",
- expected: nil,
- },
- {
- key: "welcome-user",
- trans: "Welcome to the site {0}",
- expected: nil,
- },
- {
- key: "welcome-user2",
- trans: "Welcome to the site {0}, your location is {1}",
- expected: nil,
- },
- }
-
- for _, tt := range translations {
- if err := loc.Add(tt.key, tt.trans, tt.override); err != nil {
- b.Fatalf("adding translation '%s' failed with key '%s'", tt.trans, tt.key)
- }
- }
-
- var err error
-
- b.ResetTimer()
-
- b.Run("", func(b *testing.B) {
- for i := 0; i < b.N; i++ {
- if _, err = loc.T("welcome"); err != nil {
- b.Error(err)
- }
- }
- })
-
- b.Run("Parallel", func(b *testing.B) {
-
- b.RunParallel(func(pb *testing.PB) {
-
- for pb.Next() {
- if _, err = loc.T("welcome"); err != nil {
- b.Error(err)
- }
- }
- })
- })
-
- b.Run("With1Param", func(b *testing.B) {
- for i := 0; i < b.N; i++ {
- if _, err = loc.T("welcome-user", "Joeybloggs"); err != nil {
- b.Error(err)
- }
- }
- })
-
- b.Run("ParallelWith1Param", func(b *testing.B) {
-
- b.RunParallel(func(pb *testing.PB) {
-
- for pb.Next() {
- if _, err = loc.T("welcome-user", "Joeybloggs"); err != nil {
- b.Error(err)
- }
- }
- })
- })
-
- b.Run("With2Param", func(b *testing.B) {
- for i := 0; i < b.N; i++ {
- if _, err = loc.T("welcome-user2", "Joeybloggs", "/dev/tty0"); err != nil {
- b.Error(err)
- }
- }
- })
-
- b.Run("ParallelWith2Param", func(b *testing.B) {
-
- b.RunParallel(func(pb *testing.PB) {
-
- for pb.Next() {
- if _, err = loc.T("welcome-user2", "Joeybloggs", "/dev/tty0"); err != nil {
- b.Error(err)
- }
- }
- })
- })
-}
diff --git a/vendor/github.com/go-playground/universal-translator/import_export_test.go b/vendor/github.com/go-playground/universal-translator/import_export_test.go
deleted file mode 100644
index e6a8505..0000000
--- a/vendor/github.com/go-playground/universal-translator/import_export_test.go
+++ /dev/null
@@ -1,789 +0,0 @@
-package ut
-
-import (
- "fmt"
- "path/filepath"
- "testing"
-
- "os"
-
- "github.com/go-playground/locales"
- "github.com/go-playground/locales/en"
- "github.com/go-playground/locales/nl"
-)
-
-// NOTES:
-// - Run "go test" to run tests
-// - Run "gocov test | gocov report" to report on test converage by file
-// - Run "gocov test | gocov annotate -" to report on all code and functions, those ,marked with "MISS" were never called
-//
-// or
-//
-// -- may be a good idea to change to output path to somewherelike /tmp
-// go test -coverprofile cover.out && go tool cover -html=cover.out -o cover.html
-//
-
-func TestExportImportBasic(t *testing.T) {
-
- e := en.New()
- uni := New(e, e)
- en, found := uni.GetTranslator("en") // or fallback if fails to find 'en'
- if !found {
- t.Fatalf("Expected '%t' Got '%t'", true, found)
- }
-
- translations := []struct {
- key interface{}
- trans string
- expected error
- expectedError bool
- override bool
- }{
- {
- key: "test_trans",
- trans: "Welcome {0}",
- expected: nil,
- },
- {
- key: -1,
- trans: "Welcome {0}",
- expected: nil,
- },
- {
- key: "test_trans2",
- trans: "{0} to the {1}.",
- expected: nil,
- },
- {
- key: "test_trans3",
- trans: "Welcome {0} to the {1}",
- expected: nil,
- },
- {
- key: "test_trans4",
- trans: "{0}{1}",
- expected: nil,
- },
- {
- key: "test_trans",
- trans: "{0}{1}",
- expected: &ErrConflictingTranslation{locale: en.Locale(), key: "test_trans", text: "{0}{1}"},
- expectedError: true,
- },
- {
- key: -1,
- trans: "{0}{1}",
- expected: &ErrConflictingTranslation{locale: en.Locale(), key: -1, text: "{0}{1}"},
- expectedError: true,
- },
- {
- key: "test_trans",
- trans: "Welcome {0} to the {1}.",
- expected: nil,
- override: true,
- },
- }
-
- for _, tt := range translations {
-
- err := en.Add(tt.key, tt.trans, tt.override)
- if err != tt.expected {
- if !tt.expectedError {
- t.Errorf("Expected '%s' Got '%s'", tt.expected, err)
- } else {
- if err.Error() != tt.expected.Error() {
- t.Errorf("Expected '%s' Got '%s'", tt.expected.Error(), err.Error())
- }
- }
- }
- }
-
- dirname := "testdata/translations"
- defer os.RemoveAll(dirname)
-
- err := uni.Export(FormatJSON, dirname)
- if err != nil {
- t.Fatalf("Expected '%v' Got '%s'", nil, err)
- }
-
- uni = New(e, e)
-
- err = uni.Import(FormatJSON, dirname)
- if err != nil {
- t.Fatalf("Expected '%v' Got '%s'", nil, err)
- }
-
- en, found = uni.GetTranslator("en") // or fallback if fails to find 'en'
- if !found {
- t.Fatalf("Expected '%t' Got '%t'", true, found)
- }
-
- tests := []struct {
- key interface{}
- params []string
- expected string
- expectedError bool
- }{
- {
- key: "test_trans",
- params: []string{"Joeybloggs", "The Test"},
- expected: "Welcome Joeybloggs to the The Test.",
- },
- {
- key: "test_trans2",
- params: []string{"Joeybloggs", "The Test"},
- expected: "Joeybloggs to the The Test.",
- },
- {
- key: "test_trans3",
- params: []string{"Joeybloggs", "The Test"},
- expected: "Welcome Joeybloggs to the The Test",
- },
- {
- key: "test_trans4",
- params: []string{"Joeybloggs", "The Test"},
- expected: "JoeybloggsThe Test",
- },
- // bad translation
- {
- key: "non-existant-key",
- params: []string{"Joeybloggs", "The Test"},
- expected: "",
- expectedError: true,
- },
- }
-
- for _, tt := range tests {
-
- s, err := en.T(tt.key, tt.params...)
- if s != tt.expected {
- if !tt.expectedError || (tt.expectedError && err != ErrUnknowTranslation) {
- t.Errorf("Expected '%s' Got '%s'", tt.expected, s)
- }
- }
- }
-}
-
-func TestExportImportCardinal(t *testing.T) {
-
- e := en.New()
- uni := New(e, e)
- en, found := uni.GetTranslator("en")
- if !found {
- t.Fatalf("Expected '%t' Got '%t'", true, found)
- }
-
- translations := []struct {
- key interface{}
- trans string
- rule locales.PluralRule
- expected error
- expectedError bool
- override bool
- }{
- // bad translation
- {
- key: "cardinal_test",
- trans: "You have a day left.",
- rule: locales.PluralRuleOne,
- expected: &ErrCardinalTranslation{text: fmt.Sprintf("error: parameter '%s' not found, may want to use 'Add' instead of 'AddCardinal'. locale: '%s' key: '%v' text: '%s'", paramZero, en.Locale(), "cardinal_test", "You have a day left.")},
- expectedError: true,
- },
- {
- key: "cardinal_test",
- trans: "You have {0} day",
- rule: locales.PluralRuleOne,
- expected: nil,
- },
- {
- key: "cardinal_test",
- trans: "You have {0} days left.",
- rule: locales.PluralRuleOther,
- expected: nil,
- },
- {
- key: "cardinal_test",
- trans: "You have {0} days left.",
- rule: locales.PluralRuleOther,
- expected: &ErrConflictingTranslation{locale: en.Locale(), key: "cardinal_test", rule: locales.PluralRuleOther, text: "You have {0} days left."},
- expectedError: true,
- },
- {
- key: "cardinal_test",
- trans: "You have {0} day left.",
- rule: locales.PluralRuleOne,
- expected: nil,
- override: true,
- },
- }
-
- for _, tt := range translations {
-
- err := en.AddCardinal(tt.key, tt.trans, tt.rule, tt.override)
- if err != tt.expected {
- if !tt.expectedError || err.Error() != tt.expected.Error() {
- t.Errorf("Expected '%s' Got '%s'", tt.expected, err)
- }
- }
- }
-
- dirname := "testdata/translations"
- defer os.RemoveAll(dirname)
-
- err := uni.Export(FormatJSON, dirname)
- if err != nil {
- t.Fatalf("Expected '%v' Got '%s'", nil, err)
- }
-
- uni = New(e, e)
-
- err = uni.Import(FormatJSON, dirname)
- if err != nil {
- t.Fatalf("Expected '%v' Got '%s'", nil, err)
- }
-
- en, found = uni.GetTranslator("en") // or fallback if fails to find 'en'
- if !found {
- t.Fatalf("Expected '%t' Got '%t'", true, found)
- }
-
- tests := []struct {
- key interface{}
- num float64
- digits uint64
- param string
- expected string
- expectedError bool
- }{
- {
- key: "cardinal_test",
- num: 1,
- digits: 0,
- param: string(en.FmtNumber(1, 0)),
- expected: "You have 1 day left.",
- },
- // bad translation key
- {
- key: "non-existant",
- num: 1,
- digits: 0,
- param: string(en.FmtNumber(1, 0)),
- expected: "",
- expectedError: true,
- },
- }
-
- for _, tt := range tests {
-
- s, err := en.C(tt.key, tt.num, tt.digits, tt.param)
- if err != nil {
- if !tt.expectedError && err != ErrUnknowTranslation {
- t.Errorf("Expected '<nil>' Got '%s'", err)
- }
- }
-
- if s != tt.expected {
- t.Errorf("Expected '%s' Got '%s'", tt.expected, s)
- }
- }
-}
-
-func TestExportImportOrdinal(t *testing.T) {
-
- e := en.New()
- uni := New(e, e)
- en, found := uni.GetTranslator("en")
- if !found {
- t.Fatalf("Expected '%t' Got '%t'", true, found)
- }
-
- translations := []struct {
- key interface{}
- trans string
- rule locales.PluralRule
- expected error
- expectedError bool
- override bool
- }{
- // bad translation
- {
- key: "day",
- trans: "st",
- rule: locales.PluralRuleOne,
- expected: &ErrOrdinalTranslation{text: fmt.Sprintf("error: parameter '%s' not found, may want to use 'Add' instead of 'AddOrdinal'. locale: '%s' key: '%v' text: '%s'", paramZero, en.Locale(), "day", "st")},
- expectedError: true,
- },
- {
- key: "day",
- trans: "{0}sfefewt",
- rule: locales.PluralRuleOne,
- expected: nil,
- },
- {
- key: "day",
- trans: "{0}nd",
- rule: locales.PluralRuleTwo,
- expected: nil,
- },
- {
- key: "day",
- trans: "{0}rd",
- rule: locales.PluralRuleFew,
- expected: nil,
- },
- {
- key: "day",
- trans: "{0}th",
- rule: locales.PluralRuleOther,
- expected: nil,
- },
- // bad translation
- {
- key: "day",
- trans: "{0}th",
- rule: locales.PluralRuleOther,
- expected: &ErrConflictingTranslation{locale: en.Locale(), key: "day", rule: locales.PluralRuleOther, text: "{0}th"},
- expectedError: true,
- },
- {
- key: "day",
- trans: "{0}st",
- rule: locales.PluralRuleOne,
- expected: nil,
- override: true,
- },
- }
-
- for _, tt := range translations {
-
- err := en.AddOrdinal(tt.key, tt.trans, tt.rule, tt.override)
- if err != tt.expected {
- if !tt.expectedError || err.Error() != tt.expected.Error() {
- t.Errorf("Expected '<nil>' Got '%s'", err)
- }
- }
- }
-
- dirname := "testdata/translations"
- defer os.RemoveAll(dirname)
-
- err := uni.Export(FormatJSON, dirname)
- if err != nil {
- t.Fatalf("Expected '%v' Got '%s'", nil, err)
- }
-
- uni = New(e, e)
-
- err = uni.Import(FormatJSON, dirname)
- if err != nil {
- t.Fatalf("Expected '%v' Got '%s'", nil, err)
- }
-
- en, found = uni.GetTranslator("en") // or fallback if fails to find 'en'
- if !found {
- t.Fatalf("Expected '%t' Got '%t'", true, found)
- }
-
- tests := []struct {
- key interface{}
- num float64
- digits uint64
- param string
- expected string
- expectedError bool
- }{
- {
- key: "day",
- num: 1,
- digits: 0,
- param: string(en.FmtNumber(1, 0)),
- expected: "1st",
- },
- {
- key: "day",
- num: 2,
- digits: 0,
- param: string(en.FmtNumber(2, 0)),
- expected: "2nd",
- },
- {
- key: "day",
- num: 3,
- digits: 0,
- param: string(en.FmtNumber(3, 0)),
- expected: "3rd",
- },
- {
- key: "day",
- num: 4,
- digits: 0,
- param: string(en.FmtNumber(4, 0)),
- expected: "4th",
- },
- {
- key: "day",
- num: 10258.43,
- digits: 0,
- param: string(en.FmtNumber(10258.43, 0)),
- expected: "10,258th",
- },
- // bad translation
- {
- key: "d-day",
- num: 10258.43,
- digits: 0,
- param: string(en.FmtNumber(10258.43, 0)),
- expected: "",
- expectedError: true,
- },
- }
-
- for _, tt := range tests {
-
- s, err := en.O(tt.key, tt.num, tt.digits, tt.param)
- if err != nil {
- if !tt.expectedError && err != ErrUnknowTranslation {
- t.Errorf("Expected '<nil>' Got '%s'", err)
- }
- }
-
- if s != tt.expected {
- t.Errorf("Expected '%s' Got '%s'", tt.expected, s)
- }
- }
-}
-
-func TestExportImportRange(t *testing.T) {
-
- n := nl.New()
- uni := New(n, n)
-
- // dutch
- nl, found := uni.GetTranslator("nl")
- if !found {
- t.Fatalf("Expected '%t' Got '%t'", true, found)
- }
-
- translations := []struct {
- key interface{}
- trans string
- rule locales.PluralRule
- expected error
- expectedError bool
- override bool
- }{
- // bad translation
- {
- key: "day",
- trans: "er -{1} dag vertrokken",
- rule: locales.PluralRuleOne,
- expected: &ErrRangeTranslation{text: fmt.Sprintf("error: parameter '%s' not found, are you sure you're adding a Range Translation? locale: '%s' key: '%s' text: '%s'", paramZero, nl.Locale(), "day", "er -{1} dag vertrokken")},
- expectedError: true,
- },
- // bad translation
- {
- key: "day",
- trans: "er {0}- dag vertrokken",
- rule: locales.PluralRuleOne,
- expected: &ErrRangeTranslation{text: fmt.Sprintf("error: parameter '%s' not found, a Range Translation requires two parameters. locale: '%s' key: '%s' text: '%s'", paramOne, nl.Locale(), "day", "er {0}- dag vertrokken")},
- expectedError: true,
- },
- {
- key: "day",
- trans: "er {0}-{1} dag",
- rule: locales.PluralRuleOne,
- expected: nil,
- },
- {
- key: "day",
- trans: "er zijn {0}-{1} dagen over",
- rule: locales.PluralRuleOther,
- expected: nil,
- },
- // bad translation
- {
- key: "day",
- trans: "er zijn {0}-{1} dagen over",
- rule: locales.PluralRuleOther,
- expected: &ErrConflictingTranslation{locale: nl.Locale(), key: "day", rule: locales.PluralRuleOther, text: "er zijn {0}-{1} dagen over"},
- expectedError: true,
- },
- {
- key: "day",
- trans: "er {0}-{1} dag vertrokken",
- rule: locales.PluralRuleOne,
- expected: nil,
- override: true,
- },
- }
-
- for _, tt := range translations {
-
- err := nl.AddRange(tt.key, tt.trans, tt.rule, tt.override)
- if err != tt.expected {
- if !tt.expectedError || err.Error() != tt.expected.Error() {
- t.Errorf("Expected '%#v' Got '%s'", tt.expected, err)
- }
- }
- }
-
- dirname := "testdata/translations"
- defer os.RemoveAll(dirname)
-
- err := uni.Export(FormatJSON, dirname)
- if err != nil {
- t.Fatalf("Expected '%v' Got '%s'", nil, err)
- }
-
- uni = New(n, n)
-
- err = uni.Import(FormatJSON, dirname)
- if err != nil {
- t.Fatalf("Expected '%v' Got '%s'", nil, err)
- }
-
- nl, found = uni.GetTranslator("nl") // or fallback if fails to find 'en'
- if !found {
- t.Fatalf("Expected '%t' Got '%t'", true, found)
- }
-
- tests := []struct {
- key interface{}
- num1 float64
- digits1 uint64
- num2 float64
- digits2 uint64
- param1 string
- param2 string
- expected string
- expectedError bool
- }{
- {
- key: "day",
- num1: 1,
- digits1: 0,
- num2: 2,
- digits2: 0,
- param1: string(nl.FmtNumber(1, 0)),
- param2: string(nl.FmtNumber(2, 0)),
- expected: "er zijn 1-2 dagen over",
- },
- {
- key: "day",
- num1: 0,
- digits1: 0,
- num2: 1,
- digits2: 0,
- param1: string(nl.FmtNumber(0, 0)),
- param2: string(nl.FmtNumber(1, 0)),
- expected: "er 0-1 dag vertrokken",
- },
- {
- key: "day",
- num1: 0,
- digits1: 0,
- num2: 2,
- digits2: 0,
- param1: string(nl.FmtNumber(0, 0)),
- param2: string(nl.FmtNumber(2, 0)),
- expected: "er zijn 0-2 dagen over",
- },
- // bad translations from here
- {
- key: "d-day",
- num1: 0,
- digits1: 0,
- num2: 2,
- digits2: 0,
- param1: string(nl.FmtNumber(0, 0)),
- param2: string(nl.FmtNumber(2, 0)),
- expected: "",
- expectedError: true,
- },
- }
-
- for _, tt := range tests {
-
- s, err := nl.R(tt.key, tt.num1, tt.digits1, tt.num2, tt.digits2, tt.param1, tt.param2)
- if err != nil {
- if !tt.expectedError && err != ErrUnknowTranslation {
- t.Errorf("Expected '<nil>' Got '%s'", err)
- }
- }
-
- if s != tt.expected {
- t.Errorf("Expected '%s' Got '%s'", tt.expected, s)
- }
- }
-}
-
-func TestImportRecursive(t *testing.T) {
-
- e := en.New()
- uni := New(e, e)
-
- dirname := "testdata/nested1"
- err := uni.Import(FormatJSON, dirname)
- if err != nil {
- t.Fatalf("Expected '%v' Got '%s'", nil, err)
- }
-
- en, found := uni.GetTranslator("en") // or fallback if fails to find 'en'
- if !found {
- t.Fatalf("Expected '%t' Got '%t'", true, found)
- }
-
- tests := []struct {
- key interface{}
- params []string
- expected string
- expectedError bool
- }{
- {
- key: "test_trans",
- params: []string{"Joeybloggs", "The Test"},
- expected: "Welcome Joeybloggs to the The Test.",
- },
- {
- key: "test_trans2",
- params: []string{"Joeybloggs", "The Test"},
- expected: "Joeybloggs to the The Test.",
- },
- {
- key: "test_trans3",
- params: []string{"Joeybloggs", "The Test"},
- expected: "Welcome Joeybloggs to the The Test",
- },
- {
- key: "test_trans4",
- params: []string{"Joeybloggs", "The Test"},
- expected: "JoeybloggsThe Test",
- },
- // bad translation
- {
- key: "non-existant-key",
- params: []string{"Joeybloggs", "The Test"},
- expected: "",
- expectedError: true,
- },
- }
-
- for _, tt := range tests {
-
- s, err := en.T(tt.key, tt.params...)
- if s != tt.expected {
- if !tt.expectedError || (tt.expectedError && err != ErrUnknowTranslation) {
- t.Errorf("Expected '%s' Got '%s'", tt.expected, s)
- }
- }
- }
-}
-
-func TestBadImport(t *testing.T) {
-
- // test non existant file
- e := en.New()
- uni := New(e, e)
-
- filename := "testdata/non-existant-file.json"
- expected := "stat testdata/non-existant-file.json: no such file or directory"
- err := uni.Import(FormatJSON, filename)
- if err == nil || err.Error() != expected {
- t.Fatalf("Expected '%s' Got '%s'", expected, err)
- }
-
- // test bad parameter basic translation
- filename = "testdata/bad-translation1.json"
- expected = "error: bad parameter syntax, missing parameter '{0}' in translation. locale: 'en' key: 'test_trans3' text: 'Welcome {lettersnotpermitted} to the {1}'"
- err = uni.Import(FormatJSON, filename)
- if err == nil || err.Error() != expected {
- t.Fatalf("Expected '%s' Got '%s'", expected, err)
- }
-
- // test missing bracket basic translation
- filename = "testdata/bad-translation2.json"
- expected = "error: missing bracket '{}', in translation. locale: 'en' key: 'test_trans3' text: 'Welcome {0 to the {1}'"
- err = uni.Import(FormatJSON, filename)
- if err == nil || err.Error() != expected {
- t.Fatalf("Expected '%s' Got '%s'", expected, err)
- }
-
- // test missing locale basic translation
- filename = "testdata/bad-translation3.json"
- expected = "error: locale 'nl' not registered."
- err = uni.Import(FormatJSON, filename)
- if err == nil || err.Error() != expected {
- t.Fatalf("Expected '%s' Got '%s'", expected, err)
- }
-
- // test bad plural definition
- filename = "testdata/bad-translation4.json"
- expected = "error: bad plural definition 'ut.translation{Locale:\"en\", Key:\"cardinal_test\", Translation:\"You have {0} day left.\", PluralType:\"NotAPluralType\", PluralRule:\"One\", OverrideExisting:false}'"
- err = uni.Import(FormatJSON, filename)
- if err == nil || err.Error() != expected {
- t.Fatalf("Expected '%s' Got '%s'", expected, err)
- }
-
- // test bad plural rule for locale
- filename = "testdata/bad-translation5.json"
- expected = "error: cardinal plural rule 'Many' does not exist for locale 'en' key: 'cardinal_test' text: 'You have {0} day left.'"
- err = uni.Import(FormatJSON, filename)
- if err == nil || err.Error() != expected {
- t.Fatalf("Expected '%s' Got '%s'", expected, err)
- }
-
- // test invalid JSON
- filename = "testdata/bad-translation6.json"
- expected = "invalid character ']' after object key:value pair"
- err = uni.Import(FormatJSON, filename)
- if err == nil || err.Error() != expected {
- t.Fatalf("Expected '%s' Got '%s'", expected, err)
- }
-
- // test bad io.Reader
- f, err := os.Open(filename)
- if err != nil {
- t.Fatalf("Expected '%v' Got '%s'", nil, err)
- }
- f.Close()
-
- expected = "read testdata/bad-translation6.json: bad file descriptor"
- err = uni.ImportByReader(FormatJSON, f)
- if err == nil || err.Error() != expected {
- t.Fatalf("Expected '%s' Got '%s'", expected, err)
- }
-}
-
-func TestBadExport(t *testing.T) {
-
- // test readonly directory
- e := en.New()
- uni := New(e, e)
-
- en, found := uni.GetTranslator("en") // or fallback if fails to find 'en'
- if !found {
- t.Fatalf("Expected '%t' Got '%t'", true, found)
- }
-
- dirname := "testdata/readonly"
- err := os.Mkdir(dirname, 0444)
- if err != nil {
- t.Fatalf("Expected '%v' Got '%s'", nil, err)
- }
- defer os.RemoveAll(dirname)
-
- en.Add("day", "this is a day", false)
-
- expected := "open testdata/readonly/en.json: permission denied"
- err = uni.Export(FormatJSON, dirname)
- if err == nil || err.Error() != expected {
- t.Fatalf("Expected '%s' Got '%s'", expected, err)
- }
-
- // test exporting into directory inside readonly directory
- expected = "stat testdata/readonly/inner: permission denied"
- err = uni.Export(FormatJSON, filepath.Join(dirname, "inner"))
- if err == nil || err.Error() != expected {
- t.Fatalf("Expected '%s' Got '%s'", expected, err)
- }
-}
diff --git a/vendor/github.com/go-playground/universal-translator/logo.png b/vendor/github.com/go-playground/universal-translator/logo.png
deleted file mode 100644
index a37aa8c..0000000
--- a/vendor/github.com/go-playground/universal-translator/logo.png
+++ /dev/null
Binary files differ
diff --git a/vendor/github.com/go-playground/universal-translator/translator_test.go b/vendor/github.com/go-playground/universal-translator/translator_test.go
deleted file mode 100644
index 837d2d3..0000000
--- a/vendor/github.com/go-playground/universal-translator/translator_test.go
+++ /dev/null
@@ -1,858 +0,0 @@
-package ut
-
-import (
- "fmt"
- "testing"
-
- "github.com/go-playground/locales"
- "github.com/go-playground/locales/en"
- "github.com/go-playground/locales/en_CA"
- "github.com/go-playground/locales/nl"
-)
-
-// NOTES:
-// - Run "go test" to run tests
-// - Run "gocov test | gocov report" to report on test converage by file
-// - Run "gocov test | gocov annotate -" to report on all code and functions, those ,marked with "MISS" were never called
-//
-// or
-//
-// -- may be a good idea to change to output path to somewherelike /tmp
-// go test -coverprofile cover.out && go tool cover -html=cover.out -o cover.html
-//
-
-func TestBasicTranslation(t *testing.T) {
-
- e := en.New()
- uni := New(e, e)
- en, found := uni.GetTranslator("en") // or fallback if fails to find 'en'
- if !found {
- t.Fatalf("Expected '%t' Got '%t'", true, found)
- }
-
- translations := []struct {
- key interface{}
- trans string
- expected error
- expectedError bool
- override bool
- }{
- {
- key: "test_trans",
- trans: "Welcome {0}",
- expected: nil,
- },
- {
- key: -1,
- trans: "Welcome {0}",
- expected: nil,
- },
- {
- key: "test_trans2",
- trans: "{0} to the {1}.",
- expected: nil,
- },
- {
- key: "test_trans3",
- trans: "Welcome {0} to the {1}",
- expected: nil,
- },
- {
- key: "test_trans4",
- trans: "{0}{1}",
- expected: nil,
- },
- {
- key: "test_trans",
- trans: "{0}{1}",
- expected: &ErrConflictingTranslation{locale: en.Locale(), key: "test_trans", text: "{0}{1}"},
- expectedError: true,
- },
- {
- key: -1,
- trans: "{0}{1}",
- expected: &ErrConflictingTranslation{locale: en.Locale(), key: -1, text: "{0}{1}"},
- expectedError: true,
- },
- {
- key: "test_trans",
- trans: "Welcome {0} to the {1}.",
- expected: nil,
- override: true,
- },
- }
-
- for _, tt := range translations {
-
- err := en.Add(tt.key, tt.trans, tt.override)
- if err != tt.expected {
- if !tt.expectedError {
- t.Errorf("Expected '%s' Got '%s'", tt.expected, err)
- } else {
- if err.Error() != tt.expected.Error() {
- t.Errorf("Expected '%s' Got '%s'", tt.expected.Error(), err.Error())
- }
- }
- }
- }
-
- tests := []struct {
- key interface{}
- params []string
- expected string
- expectedError bool
- }{
- {
- key: "test_trans",
- params: []string{"Joeybloggs", "The Test"},
- expected: "Welcome Joeybloggs to the The Test.",
- },
- {
- key: "test_trans2",
- params: []string{"Joeybloggs", "The Test"},
- expected: "Joeybloggs to the The Test.",
- },
- {
- key: "test_trans3",
- params: []string{"Joeybloggs", "The Test"},
- expected: "Welcome Joeybloggs to the The Test",
- },
- {
- key: "test_trans4",
- params: []string{"Joeybloggs", "The Test"},
- expected: "JoeybloggsThe Test",
- },
- // bad translation
- {
- key: "non-existant-key",
- params: []string{"Joeybloggs", "The Test"},
- expected: "",
- expectedError: true,
- },
- }
-
- for _, tt := range tests {
- s, err := en.T(tt.key, tt.params...)
- if s != tt.expected {
- if !tt.expectedError && err != ErrUnknowTranslation {
- t.Errorf("Expected '%s' Got '%s'", tt.expected, s)
- }
- }
- }
-}
-
-func TestCardinalTranslation(t *testing.T) {
-
- e := en.New()
- uni := New(e, e)
- en, found := uni.GetTranslator("en")
- if !found {
- t.Fatalf("Expected '%t' Got '%t'", true, found)
- }
-
- translations := []struct {
- key interface{}
- trans string
- rule locales.PluralRule
- expected error
- expectedError bool
- override bool
- }{
- // bad translation
- {
- key: "cardinal_test",
- trans: "You have a day left.",
- rule: locales.PluralRuleOne,
- expected: &ErrCardinalTranslation{text: fmt.Sprintf("error: parameter '%s' not found, may want to use 'Add' instead of 'AddCardinal'. locale: '%s' key: '%v' text: '%s'", paramZero, en.Locale(), "cardinal_test", "You have a day left.")},
- expectedError: true,
- },
- // bad translation
- {
- key: "cardinal_test",
- trans: "You have a day left few.",
- rule: locales.PluralRuleFew,
- expected: &ErrCardinalTranslation{text: fmt.Sprintf("error: cardinal plural rule '%s' does not exist for locale '%s' key: '%s' text: '%s'", locales.PluralRuleFew, en.Locale(), "cardinal_test", "You have a day left few.")},
- expectedError: true,
- },
- {
- key: "cardinal_test",
- trans: "You have {0} day",
- rule: locales.PluralRuleOne,
- expected: nil,
- },
- {
- key: "cardinal_test",
- trans: "You have {0} days left.",
- rule: locales.PluralRuleOther,
- expected: nil,
- },
- {
- key: "cardinal_test",
- trans: "You have {0} days left.",
- rule: locales.PluralRuleOther,
- expected: &ErrConflictingTranslation{locale: en.Locale(), key: "cardinal_test", rule: locales.PluralRuleOther, text: "You have {0} days left."},
- expectedError: true,
- },
- {
- key: "cardinal_test",
- trans: "You have {0} day left.",
- rule: locales.PluralRuleOne,
- expected: nil,
- override: true,
- },
- }
-
- for _, tt := range translations {
-
- err := en.AddCardinal(tt.key, tt.trans, tt.rule, tt.override)
- if err != tt.expected {
- if !tt.expectedError || err.Error() != tt.expected.Error() {
- t.Errorf("Expected '<nil>' Got '%s'", err)
- }
- }
- }
-
- tests := []struct {
- key interface{}
- num float64
- digits uint64
- param string
- expected string
- expectedError bool
- }{
- {
- key: "cardinal_test",
- num: 1,
- digits: 0,
- param: string(en.FmtNumber(1, 0)),
- expected: "You have 1 day left.",
- },
- // bad translation key
- {
- key: "non-existant",
- num: 1,
- digits: 0,
- param: string(en.FmtNumber(1, 0)),
- expected: "",
- expectedError: true,
- },
- }
-
- for _, tt := range tests {
-
- s, err := en.C(tt.key, tt.num, tt.digits, tt.param)
- if err != nil {
- if !tt.expectedError && err != ErrUnknowTranslation {
- t.Errorf("Expected '<nil>' Got '%s'", err)
- }
- }
-
- if s != tt.expected {
- t.Errorf("Expected '%s' Got '%s'", tt.expected, s)
- }
- }
-}
-
-func TestOrdinalTranslation(t *testing.T) {
-
- e := en.New()
- uni := New(e, e)
- en, found := uni.GetTranslator("en")
- if !found {
- t.Fatalf("Expected '%t' Got '%t'", true, found)
- }
-
- translations := []struct {
- key interface{}
- trans string
- rule locales.PluralRule
- expected error
- expectedError bool
- override bool
- }{
- // bad translation
- {
- key: "day",
- trans: "st",
- rule: locales.PluralRuleOne,
- expected: &ErrOrdinalTranslation{text: fmt.Sprintf("error: parameter '%s' not found, may want to use 'Add' instead of 'AddOrdinal'. locale: '%s' key: '%v' text: '%s'", paramZero, en.Locale(), "day", "st")},
- expectedError: true,
- },
- // bad translation
- {
- key: "day",
- trans: "st",
- rule: locales.PluralRuleMany,
- expected: &ErrOrdinalTranslation{text: fmt.Sprintf("error: ordinal plural rule '%s' does not exist for locale '%s' key: '%s' text: '%s'", locales.PluralRuleMany, en.Locale(), "day", "st")},
- expectedError: true,
- },
- {
- key: "day",
- trans: "{0}st",
- rule: locales.PluralRuleOne,
- expected: nil,
- },
- {
- key: "day",
- trans: "{0}nd",
- rule: locales.PluralRuleTwo,
- expected: nil,
- },
- {
- key: "day",
- trans: "{0}rd",
- rule: locales.PluralRuleFew,
- expected: nil,
- },
- {
- key: "day",
- trans: "{0}th",
- rule: locales.PluralRuleOther,
- expected: nil,
- },
- // bad translation
- {
- key: "day",
- trans: "{0}th",
- rule: locales.PluralRuleOther,
- expected: &ErrConflictingTranslation{locale: en.Locale(), key: "day", rule: locales.PluralRuleOther, text: "{0}th"},
- expectedError: true,
- },
- {
- key: "day",
- trans: "{0}st",
- rule: locales.PluralRuleOne,
- expected: nil,
- override: true,
- },
- }
-
- for _, tt := range translations {
-
- err := en.AddOrdinal(tt.key, tt.trans, tt.rule, tt.override)
- if err != tt.expected {
- if !tt.expectedError || err.Error() != tt.expected.Error() {
- t.Errorf("Expected '<nil>' Got '%s'", err)
- }
- }
- }
-
- tests := []struct {
- key interface{}
- num float64
- digits uint64
- param string
- expected string
- expectedError bool
- }{
- {
- key: "day",
- num: 1,
- digits: 0,
- param: string(en.FmtNumber(1, 0)),
- expected: "1st",
- },
- {
- key: "day",
- num: 2,
- digits: 0,
- param: string(en.FmtNumber(2, 0)),
- expected: "2nd",
- },
- {
- key: "day",
- num: 3,
- digits: 0,
- param: string(en.FmtNumber(3, 0)),
- expected: "3rd",
- },
- {
- key: "day",
- num: 4,
- digits: 0,
- param: string(en.FmtNumber(4, 0)),
- expected: "4th",
- },
- {
- key: "day",
- num: 10258.43,
- digits: 0,
- param: string(en.FmtNumber(10258.43, 0)),
- expected: "10,258th",
- },
- // bad translation
- {
- key: "d-day",
- num: 10258.43,
- digits: 0,
- param: string(en.FmtNumber(10258.43, 0)),
- expected: "",
- expectedError: true,
- },
- }
-
- for _, tt := range tests {
-
- s, err := en.O(tt.key, tt.num, tt.digits, tt.param)
- if err != nil {
- if !tt.expectedError && err != ErrUnknowTranslation {
- t.Errorf("Expected '<nil>' Got '%s'", err)
- }
- }
-
- if s != tt.expected {
- t.Errorf("Expected '%s' Got '%s'", tt.expected, s)
- }
- }
-}
-
-func TestRangeTranslation(t *testing.T) {
-
- n := nl.New()
- uni := New(n, n)
-
- // dutch
- nl, found := uni.GetTranslator("nl")
- if !found {
- t.Fatalf("Expected '%t' Got '%t'", true, found)
- }
-
- translations := []struct {
- key interface{}
- trans string
- rule locales.PluralRule
- expected error
- expectedError bool
- override bool
- }{
- // bad translation
- {
- key: "day",
- trans: "er -{1} dag vertrokken",
- rule: locales.PluralRuleOne,
- expected: &ErrRangeTranslation{text: fmt.Sprintf("error: parameter '%s' not found, are you sure you're adding a Range Translation? locale: '%s' key: '%s' text: '%s'", paramZero, nl.Locale(), "day", "er -{1} dag vertrokken")},
- expectedError: true,
- },
- // bad translation
- {
- key: "day",
- trans: "er {0}- dag vertrokken",
- rule: locales.PluralRuleMany,
- expected: &ErrRangeTranslation{text: fmt.Sprintf("error: range plural rule '%s' does not exist for locale '%s' key: '%s' text: '%s'", locales.PluralRuleMany, nl.Locale(), "day", "er {0}- dag vertrokken")},
- expectedError: true,
- },
- // bad translation
- {
- key: "day",
- trans: "er {0}- dag vertrokken",
- rule: locales.PluralRuleOne,
- expected: &ErrRangeTranslation{text: fmt.Sprintf("error: parameter '%s' not found, a Range Translation requires two parameters. locale: '%s' key: '%s' text: '%s'", paramOne, nl.Locale(), "day", "er {0}- dag vertrokken")},
- expectedError: true,
- },
- {
- key: "day",
- trans: "er {0}-{1} dag",
- rule: locales.PluralRuleOne,
- expected: nil,
- },
- {
- key: "day",
- trans: "er zijn {0}-{1} dagen over",
- rule: locales.PluralRuleOther,
- expected: nil,
- },
- // bad translation
- {
- key: "day",
- trans: "er zijn {0}-{1} dagen over",
- rule: locales.PluralRuleOther,
- expected: &ErrConflictingTranslation{locale: nl.Locale(), key: "day", rule: locales.PluralRuleOther, text: "er zijn {0}-{1} dagen over"},
- expectedError: true,
- },
- {
- key: "day",
- trans: "er {0}-{1} dag vertrokken",
- rule: locales.PluralRuleOne,
- expected: nil,
- override: true,
- },
- }
-
- for _, tt := range translations {
-
- err := nl.AddRange(tt.key, tt.trans, tt.rule, tt.override)
- if err != tt.expected {
- if !tt.expectedError || err.Error() != tt.expected.Error() {
- t.Errorf("Expected '%#v' Got '%s'", tt.expected, err)
- }
- }
- }
-
- tests := []struct {
- key interface{}
- num1 float64
- digits1 uint64
- num2 float64
- digits2 uint64
- param1 string
- param2 string
- expected string
- expectedError bool
- }{
- {
- key: "day",
- num1: 1,
- digits1: 0,
- num2: 2,
- digits2: 0,
- param1: string(nl.FmtNumber(1, 0)),
- param2: string(nl.FmtNumber(2, 0)),
- expected: "er zijn 1-2 dagen over",
- },
- {
- key: "day",
- num1: 0,
- digits1: 0,
- num2: 1,
- digits2: 0,
- param1: string(nl.FmtNumber(0, 0)),
- param2: string(nl.FmtNumber(1, 0)),
- expected: "er 0-1 dag vertrokken",
- },
- {
- key: "day",
- num1: 0,
- digits1: 0,
- num2: 2,
- digits2: 0,
- param1: string(nl.FmtNumber(0, 0)),
- param2: string(nl.FmtNumber(2, 0)),
- expected: "er zijn 0-2 dagen over",
- },
- // bad translations from here
- {
- key: "d-day",
- num1: 0,
- digits1: 0,
- num2: 2,
- digits2: 0,
- param1: string(nl.FmtNumber(0, 0)),
- param2: string(nl.FmtNumber(2, 0)),
- expected: "",
- expectedError: true,
- },
- }
-
- for _, tt := range tests {
-
- s, err := nl.R(tt.key, tt.num1, tt.digits1, tt.num2, tt.digits2, tt.param1, tt.param2)
- if err != nil {
- if !tt.expectedError && err != ErrUnknowTranslation {
- t.Errorf("Expected '<nil>' Got '%s'", err)
- }
- }
-
- if s != tt.expected {
- t.Errorf("Expected '%s' Got '%s'", tt.expected, s)
- }
- }
-}
-
-func TestFallbackTranslator(t *testing.T) {
-
- e := en.New()
- uni := New(e, e)
- en, found := uni.GetTranslator("en")
- if !found {
- t.Fatalf("Expected '%t' Got '%t'", true, found)
- }
-
- if en.Locale() != "en" {
- t.Errorf("Expected '%s' Got '%s'", "en", en.Locale())
- }
-
- fallback, _ := uni.GetTranslator("nl")
- if fallback.Locale() != "en" {
- t.Errorf("Expected '%s' Got '%s'", "en", fallback.Locale())
- }
-
- en, _ = uni.FindTranslator("nl", "en")
- if en.Locale() != "en" {
- t.Errorf("Expected '%s' Got '%s'", "en", en.Locale())
- }
-
- fallback, _ = uni.FindTranslator("nl")
- if fallback.Locale() != "en" {
- t.Errorf("Expected '%s' Got '%s'", "en", fallback.Locale())
- }
-}
-
-func TestAddTranslator(t *testing.T) {
-
- e := en.New()
- n := nl.New()
- uni := New(e, n)
-
- tests := []struct {
- trans locales.Translator
- expected error
- expectedError bool
- override bool
- }{
- {
- trans: en_CA.New(),
- expected: nil,
- override: false,
- },
- {
- trans: n,
- expected: &ErrExistingTranslator{locale: n.Locale()},
- expectedError: true,
- override: false,
- },
- {
- trans: e,
- expected: &ErrExistingTranslator{locale: e.Locale()},
- expectedError: true,
- override: false,
- },
- {
- trans: e,
- expected: nil,
- override: true,
- },
- }
-
- for _, tt := range tests {
-
- err := uni.AddTranslator(tt.trans, tt.override)
- if err != tt.expected {
- if !tt.expectedError || err.Error() != tt.expected.Error() {
- t.Errorf("Expected '%s' Got '%s'", tt.expected, err)
- }
- }
- }
-}
-
-func TestVerifyTranslations(t *testing.T) {
-
- n := nl.New()
- // dutch
- uni := New(n, n)
-
- loc, _ := uni.GetTranslator("nl")
- if loc.Locale() != "nl" {
- t.Errorf("Expected '%s' Got '%s'", "nl", loc.Locale())
- }
-
- // cardinal checks
-
- err := loc.AddCardinal("day", "je {0} dag hebben verlaten", locales.PluralRuleOne, false)
- if err != nil {
- t.Fatalf("Expected '<nil>' Got '%s'", err)
- }
-
- // fail cardinal rules
- expected := &ErrMissingPluralTranslation{locale: loc.Locale(), translationType: "plural", rule: locales.PluralRuleOther, key: "day"}
- err = loc.VerifyTranslations()
- if err == nil || err.Error() != expected.Error() {
- t.Errorf("Expected '%s' Got '%s'", expected, err)
- }
-
- // success cardinal
- err = loc.AddCardinal("day", "je {0} dagen hebben verlaten", locales.PluralRuleOther, false)
- if err != nil {
- t.Fatalf("Expected '<nil>' Got '%s'", err)
- }
-
- err = loc.VerifyTranslations()
- if err != nil {
- t.Fatalf("Expected '<nil>' Got '%s'", err)
- }
-
- // range checks
- err = loc.AddRange("day", "je {0}-{1} dagen hebben verlaten", locales.PluralRuleOther, false)
- if err != nil {
- t.Fatalf("Expected '<nil>' Got '%s'", err)
- }
-
- // fail range rules
- expected = &ErrMissingPluralTranslation{locale: loc.Locale(), translationType: "range", rule: locales.PluralRuleOne, key: "day"}
- err = loc.VerifyTranslations()
- if err == nil || err.Error() != expected.Error() {
- t.Errorf("Expected '%s' Got '%s'", expected, err)
- }
-
- // success range
- err = loc.AddRange("day", "je {0}-{1} dag hebben verlaten", locales.PluralRuleOne, false)
- if err != nil {
- t.Fatalf("Expected '<nil>' Got '%s'", err)
- }
-
- err = loc.VerifyTranslations()
- if err != nil {
- t.Fatalf("Expected '<nil>' Got '%s'", err)
- }
-
- // ok so 'nl' aka dutch, ony has one plural rule for ordinals, so going to switch to english from here which has 4
-
- err = uni.AddTranslator(en.New(), false)
- if err != nil {
- t.Fatalf("Expected '<nil>' Got '%s'", err)
- }
-
- loc, _ = uni.GetTranslator("en")
- if loc.Locale() != "en" {
- t.Errorf("Expected '%s' Got '%s'", "en", loc.Locale())
- }
-
- // ordinal checks
-
- err = loc.AddOrdinal("day", "{0}st", locales.PluralRuleOne, false)
- if err != nil {
- t.Fatalf("Expected '<nil>' Got '%s'", err)
- }
-
- err = loc.AddOrdinal("day", "{0}rd", locales.PluralRuleFew, false)
- if err != nil {
- t.Fatalf("Expected '<nil>' Got '%s'", err)
- }
-
- err = loc.AddOrdinal("day", "{0}th", locales.PluralRuleOther, false)
- if err != nil {
- t.Fatalf("Expected '<nil>' Got '%s'", err)
- }
-
- // fail ordinal rules
- expected = &ErrMissingPluralTranslation{locale: loc.Locale(), translationType: "ordinal", rule: locales.PluralRuleTwo, key: "day"}
- err = loc.VerifyTranslations()
- if err == nil || err.Error() != expected.Error() {
- t.Errorf("Expected '%s' Got '%s'", expected, err)
- }
-
- // success ordinal
-
- err = loc.AddOrdinal("day", "{0}nd", locales.PluralRuleTwo, false)
- if err != nil {
- t.Fatalf("Expected '<nil>' Got '%s'", err)
- }
-
- err = loc.VerifyTranslations()
- if err != nil {
- t.Fatalf("Expected '<nil>' Got '%s'", err)
- }
-}
-
-func TestVerifyTranslationsWithNonStringKeys(t *testing.T) {
-
- n := nl.New()
- // dutch
- uni := New(n, n)
-
- loc, _ := uni.GetTranslator("nl")
- if loc.Locale() != "nl" {
- t.Errorf("Expected '%s' Got '%s'", "nl", loc.Locale())
- }
-
- // cardinal checks
-
- err := loc.AddCardinal(-1, "je {0} dag hebben verlaten", locales.PluralRuleOne, false)
- if err != nil {
- t.Fatalf("Expected '<nil>' Got '%s'", err)
- }
-
- // fail cardinal rules
- expected := &ErrMissingPluralTranslation{locale: loc.Locale(), translationType: "plural", rule: locales.PluralRuleOther, key: -1}
- err = loc.VerifyTranslations()
- if err == nil || err.Error() != expected.Error() {
- t.Errorf("Expected '%s' Got '%s'", expected, err)
- }
-}
-
-func TestGetFallback(t *testing.T) {
-
- // dutch
- n := nl.New()
- e := en.New()
-
- uni := New(e, n)
-
- trans := uni.GetFallback()
-
- expected := "en"
-
- if trans.Locale() != expected {
- t.Errorf("Expected '%s' Got '%s'", expected, trans.Locale())
- }
-}
-
-func TestVerifyUTTranslations(t *testing.T) {
-
- e := en.New()
- uni := New(e, e)
- en, found := uni.GetTranslator("en")
- if !found {
- t.Fatalf("Expected '%t' Got '%t'", true, found)
- }
-
- translations := []struct {
- key interface{}
- trans string
- rule locales.PluralRule
- expected error
- expectedError bool
- override bool
- }{
- {
- key: "day",
- trans: "{0}st",
- rule: locales.PluralRuleOne,
- expected: nil,
- },
- {
- key: "day",
- trans: "{0}nd",
- rule: locales.PluralRuleTwo,
- expected: nil,
- },
- {
- key: "day",
- trans: "{0}rd",
- rule: locales.PluralRuleFew,
- expected: nil,
- },
- // intentionally leaving out plural other
- // {
- // key: "day",
- // trans: "{0}th",
- // rule: locales.PluralRuleOther,
- // expected: nil,
- // },
- }
-
- for _, tt := range translations {
-
- err := en.AddOrdinal(tt.key, tt.trans, tt.rule, tt.override)
- if err != tt.expected {
- if !tt.expectedError || err.Error() != tt.expected.Error() {
- t.Errorf("Expected '<nil>' Got '%s'", err)
- }
- }
- }
-
- expected := "error: missing 'ordinal' plural rule 'Other' for translation with key 'day' and locale 'en'"
- err := uni.VerifyTranslations()
- if err == nil || err.Error() != expected {
- t.Fatalf("Expected '%s' Got '%s'", expected, err)
- }
-
- err = en.AddOrdinal("day", "{0}th", locales.PluralRuleOther, false)
- if err != nil {
- t.Fatalf("Expected '%v' Got '%s'", nil, err)
- }
-
- err = uni.VerifyTranslations()
- if err != nil {
- t.Fatalf("Expected '%v' Got '%s'", nil, err)
- }
-}
diff --git a/vendor/github.com/pborman/getopt/CONTRIBUTING.md b/vendor/github.com/pborman/getopt/CONTRIBUTING.md
deleted file mode 100644
index 04fdf09..0000000
--- a/vendor/github.com/pborman/getopt/CONTRIBUTING.md
+++ /dev/null
@@ -1,10 +0,0 @@
-# How to contribute
-
-We definitely welcome patches and contribution to this project!
-
-### Legal requirements
-
-In order to protect both you and ourselves, you will need to sign the
-[Contributor License Agreement](https://cla.developers.google.com/clas).
-
-You may have already signed it for other Google projects.
diff --git a/vendor/github.com/pborman/getopt/README.md b/vendor/github.com/pborman/getopt/README.md
deleted file mode 100644
index 2e1cf72..0000000
--- a/vendor/github.com/pborman/getopt/README.md
+++ /dev/null
@@ -1,226 +0,0 @@
-# getopt
-
-Package getopt provides traditional getopt processing for implementing
-commands that use traditional command lines. The standard Go flag package
-cannot be used to write a program that parses flags the way ls or ssh does,
-for example. There are two versions, v1 and v2, both named getopt, that
-use the following import paths:
-
-```
- "github.com/pborman/getopt" // version 1
- "github.com/pborman/getopt/v2" // version 2
-```
-
-This README describes version 2 of the package, which has a simplified API.
-
-## Usage
-
-Getopt supports functionality found in both the standard BSD getopt as well
-as (one of the many versions of) the GNU getopt_long. Being a Go package,
-this package makes common usage easy, but still enables more controlled usage
-if needed.
-
-Typical usage:
-
-```
- Declare flags and have getopt return pointers to the values.
- helpFlag := getopt.Bool('?', "display help")
- cmdFlag := getopt.StringLong("command", 'c', "default", "the command)
-
- Declare flags against existing variables.
- var {
- fileName = "/the/default/path"
- timeout = time.Second * 5
- verbose bool
- }
- func init() {
- getopt.Flag(&verbose, 'v', "be verbose")
- getopt.FlagLong(&fileName, "path", 0, "the path")
- getopt.FlagLong(&timeout, "timeout", 't', "some timeout")
- }
-
- func main() {
- Parse the program arguments
- getopt.Parse()
- Get the remaining positional parameters
- args := getopt.Args()
- ...
-```
-
-If you don't want the program to exit on error, use getopt.Getopt:
-
-```
- err := getopt.Getopt(nil)
- if err != nil {
- code to handle error
- fmt.Fprintln(os.Stderr, err)
- }
-```
-
-## Flag Syntax
-
-Support is provided for both short (-f) and long (--flag) options. A single
-option may have both a short and a long name. Each option may be a flag or a
-value. A value takes an argument.
-
-Declaring no long names causes this package to process arguments like the
-traditional BSD getopt.
-
-Short flags may be combined into a single parameter. For example, "-a -b -c"
-may also be expressed "-abc". Long flags must stand on their own "--alpha
---beta"
-
-Values require an argument. For short options the argument may either be
-immediately following the short name or as the next argument. Only one short
-value may be combined with short flags in a single argument; the short value
-must be after all short flags. For example, if f is a flag and v is a value,
-then:
-
-```
- -vvalue (sets v to "value")
- -v value (sets v to "value")
- -fvvalue (sets f, and sets v to "value")
- -fv value (sets f, and sets v to "value")
- -vf value (set v to "f" and value is the first parameter)
-```
-
-For the long value option val:
-
-```
- --val value (sets val to "value")
- --val=value (sets val to "value")
- --valvalue (invalid option "valvalue")
-```
-
-Values with an optional value only set the value if the value is part of the
-same argument. In any event, the option count is increased and the option is
-marked as seen.
-
-```
- -v -f (sets v and f as being seen)
- -vvalue -f (sets v to "value" and sets f)
- --val -f (sets v and f as being seen)
- --val=value -f (sets v to "value" and sets f)
-```
-
-There is no convience function defined for making the value optional. The
-SetOptional method must be called on the actual Option.
-
-```
- v := String("val", 'v', "", "the optional v")
- Lookup("v").SetOptional()
-
- var s string
- FlagLong(&s, "val", 'v', "the optional v).SetOptional()
-```
-
-Parsing continues until the first non-option or "--" is encountered.
-
-The short name "-" can be used, but it either is specified as "-" or as part
-of a group of options, for example "-f-". If there are no long options
-specified then "--f" could also be used. If "-" is not declared as an option
-then the single "-" will also terminate the option processing but unlike
-"--", the "-" will be part of the remaining arguments.
-
-## Advanced Usage
-
-Normally the parsing is performed by calling the Parse function. If it is
-important to see the order of the options then the Getopt function should be
-used. The standard Parse function does the equivalent of:
-
-```
-func Parse() {
- if err := getopt.Getopt(os.Args, nil); err != nil {
- fmt.Fprintln(os.Stderr, err)
- s.usage()
- os.Exit(1)
- }
-}
-```
-
-When calling Getopt it is the responsibility of the caller to print any
-errors.
-
-Normally the default option set, CommandLine, is used. Other option sets may
-be created with New.
-
-After parsing, the sets Args will contain the non-option arguments. If an
-error is encountered then Args will begin with argument that caused the
-error.
-
-It is valid to call a set's Parse a second time to amend the current set of
-flags or values. As an example:
-
-```
- var a = getopt.Bool('a', "", "The a flag")
- var b = getopt.Bool('b', "", "The a flag")
- var cmd = ""
-
- var opts = getopt.CommandLine
-
- opts.Parse(os.Args)
- if opts.NArgs() > 0 {
- cmd = opts.Arg(0)
- opts.Parse(opts.Args())
- }
-```
-
-If called with set to { "prog", "-a", "cmd", "-b", "arg" } then both and and
-b would be set, cmd would be set to "cmd", and opts.Args() would return {
-"arg" }.
-
-Unless an option type explicitly prohibits it, an option may appear more than
-once in the arguments. The last value provided to the option is the value.
-
-## Builtin Types
-
-The Flag and FlagLong functions support most standard Go types. For the
-list, see the description of FlagLong below for a list of supported types.
-
-There are also helper routines to allow single line flag declarations. These
-types are: Bool, Counter, Duration, Enum, Int16, Int32, Int64, Int, List,
-Signed, String, Uint16, Uint32, Uint64, Uint, and Unsigned.
-
-Each comes in a short and long flavor, e.g., Bool and BoolLong and include
-functions to set the flags on the standard command line or for a specific Set
-of flags.
-
-Except for the Counter, Enum, Signed and Unsigned types, all of these types
-can be declared using Flag and FlagLong by passing in a pointer to the
-appropriate type.
-
-## Declaring New Flag Types
-
-A pointer to any type that implements the Value interface may be passed to
-Flag or FlagLong.
-
-## VALUEHELP
-
-All non-flag options are created with a "valuehelp" as the last parameter.
-Valuehelp should be 0, 1, or 2 strings. The first string, if provided, is
-the usage message for the option. If the second string, if provided, is the
-name to use for the value when displaying the usage. If not provided the
-term "value" is assumed.
-
-The usage message for the option created with
-
-```
- StringLong("option", 'o', "defval", "a string of letters")
-```
-
-is
-
-```
- -o, -option=value
-```
-while the usage message for the option created with
-
-```
- StringLong("option", 'o', "defval", "a string of letters", "string")
-```
-
-is
-
-```
- -o, -option=string
-```
diff --git a/vendor/github.com/pborman/getopt/bool.go b/vendor/github.com/pborman/getopt/bool.go
deleted file mode 100644
index 37ce019..0000000
--- a/vendor/github.com/pborman/getopt/bool.go
+++ /dev/null
@@ -1,74 +0,0 @@
-// Copyright 2013 Google Inc. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package getopt
-
-import (
- "fmt"
- "strings"
-)
-
-type boolValue bool
-
-func (b *boolValue) Set(value string, opt Option) error {
- switch strings.ToLower(value) {
- case "", "1", "true", "on", "t":
- *b = true
- case "0", "false", "off", "f":
- *b = false
- default:
- return fmt.Errorf("invalid value for bool %s: %q", opt.Name(), value)
- }
- return nil
-}
-
-func (b *boolValue) String() string {
- if *b {
- return "true"
- }
- return "false"
-}
-
-// Bool creates a flag option that is a bool. Bools normally do not take a
-// value however one can be assigned by using the long form of the option:
-//
-// --option=true
-// --o=false
-//
-// Its value is case insenstive and one of true, false, t, f, on, off, t and 0.
-func Bool(name rune, helpvalue ...string) *bool {
- return CommandLine.Bool(name, helpvalue...)
-}
-
-func (s *Set) Bool(name rune, helpvalue ...string) *bool {
- var p bool
- s.BoolVarLong(&p, "", name, helpvalue...)
- return &p
-}
-
-func BoolLong(name string, short rune, helpvalue ...string) *bool {
- return CommandLine.BoolLong(name, short, helpvalue...)
-}
-
-func (s *Set) BoolLong(name string, short rune, helpvalue ...string) *bool {
- var p bool
- s.BoolVarLong(&p, name, short, helpvalue...)
- return &p
-}
-
-func BoolVar(p *bool, name rune, helpvalue ...string) Option {
- return CommandLine.BoolVar(p, name, helpvalue...)
-}
-
-func (s *Set) BoolVar(p *bool, name rune, helpvalue ...string) Option {
- return s.BoolVarLong(p, "", name, helpvalue...)
-}
-
-func BoolVarLong(p *bool, name string, short rune, helpvalue ...string) Option {
- return CommandLine.BoolVarLong(p, name, short, helpvalue...)
-}
-
-func (s *Set) BoolVarLong(p *bool, name string, short rune, helpvalue ...string) Option {
- return s.VarLong((*boolValue)(p), name, short, helpvalue...).SetFlag()
-}
diff --git a/vendor/github.com/pborman/getopt/bool_test.go b/vendor/github.com/pborman/getopt/bool_test.go
deleted file mode 100644
index b112161..0000000
--- a/vendor/github.com/pborman/getopt/bool_test.go
+++ /dev/null
@@ -1,106 +0,0 @@
-// Copyright 2013 Google Inc. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package getopt
-
-import (
- "fmt"
- "strings"
- "testing"
-)
-
-var boolTests = []struct {
- where string
- in []string
- f bool
- fc int
- opt bool
- optc int
- err string
-}{
- {
- loc(),
- []string{},
- false, 0,
- false, 0,
- "",
- },
- {
- loc(),
- []string{"test", "-f", "--opt"},
- true, 1,
- true, 1,
- "",
- },
- {
- loc(),
- []string{"test", "--f", "--opt"},
- true, 1,
- true, 1,
- "",
- },
- {
- loc(),
- []string{"test", "-ff", "-f", "--opt", "--opt"},
- true, 3,
- true, 2,
- "",
- },
- {
- loc(),
- []string{"test", "--opt", "--opt=false"},
- false, 0,
- false, 2,
- "",
- },
- {
- loc(),
- []string{"test", "-f", "false"},
- true, 1,
- false, 0,
- "",
- },
- {
- loc(),
- []string{"test", "-f=false"},
- true, 1,
- false, 0,
- "test: unknown option: -=\n",
- },
- {
- loc(),
- []string{"test", "-f", "false"},
- true, 1,
- false, 0,
- "",
- },
-}
-
-func TestBool(t *testing.T) {
- for x, tt := range boolTests {
- reset()
- f := Bool('f')
- opt := BoolLong("opt", 0)
- if strings.Index(tt.where, ":-") > 0 {
- tt.where = fmt.Sprintf("#%d", x)
- }
-
- parse(tt.in)
- if s := checkError(tt.err); s != "" {
- t.Errorf("%s: %s", tt.where, s)
- }
- if got, want := *f, tt.f; got != want {
- t.Errorf("%s: got %v, want %v", tt.where, got, want)
- }
- if got, want := *opt, tt.opt; got != want {
- t.Errorf("%s: got %v, want %v", tt.where, got, want)
- }
- if got, want := GetCount('f'), tt.fc; got != want {
- t.Errorf("%s: got %v, want %v", tt.where, got, want)
- }
- if got, want := GetCount("opt"), tt.optc; got != want {
- t.Errorf("%s: got %v, want %v", tt.where, got, want)
- }
- }
-}
diff --git a/vendor/github.com/pborman/getopt/breakup_test.go b/vendor/github.com/pborman/getopt/breakup_test.go
deleted file mode 100644
index c0ac148..0000000
--- a/vendor/github.com/pborman/getopt/breakup_test.go
+++ /dev/null
@@ -1,34 +0,0 @@
-// Copyright 2013 Google Inc. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package getopt
-
-import (
- "testing"
-)
-
-var breakupTests = []struct {
- in string
- max int
- out []string
-}{
- {"", 8, []string{}},
- {"a fox", 8, []string{"a fox"}},
- {"a foxhound is sly", 2, []string{"a", "foxhound", "is", "sly"}},
- {"a foxhound is sly", 5, []string{"a", "foxhound", "is", "sly"}},
- {"a foxhound is sly", 6, []string{"a", "foxhound", "is sly"}},
- {"a foxhound is sly", 7, []string{"a", "foxhound", "is sly"}},
- {"a foxhound is sly", 8, []string{"a", "foxhound", "is sly"}},
- {"a foxhound is sly", 9, []string{"a", "foxhound", "is sly"}},
- {"a foxhound is sly", 10, []string{"a foxhound", "is sly"}},
-}
-
-func TestBreakup(t *testing.T) {
- for x, tt := range breakupTests {
- out := breakup(tt.in, tt.max)
- if badSlice(out, tt.out) {
- t.Errorf("#%d: got %v, want %v", x, out, tt.out)
- }
- }
-}
diff --git a/vendor/github.com/pborman/getopt/counter.go b/vendor/github.com/pborman/getopt/counter.go
deleted file mode 100644
index 8b11ec1..0000000
--- a/vendor/github.com/pborman/getopt/counter.go
+++ /dev/null
@@ -1,81 +0,0 @@
-// Copyright 2013 Google Inc. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package getopt
-
-import (
- "fmt"
- "strconv"
-)
-
-type counterValue int
-
-func (b *counterValue) Set(value string, opt Option) error {
- if value == "" {
- *b++
- } else {
- v, err := strconv.ParseInt(value, 0, strconv.IntSize)
- if err != nil {
- if e, ok := err.(*strconv.NumError); ok {
- switch e.Err {
- case strconv.ErrRange:
- err = fmt.Errorf("value out of range: %s", value)
- case strconv.ErrSyntax:
- err = fmt.Errorf("not a valid number: %s", value)
- }
- }
- return err
- }
- *b = counterValue(v)
- }
- return nil
-}
-
-func (b *counterValue) String() string {
- return strconv.Itoa(int(*b))
-}
-
-// Counter creates a counting flag stored as an int. Each time the option
-// is seen while parsing the value is incremented. The value of the counter
-// may be explicitly set by using the long form:
-//
-// --counter=5
-// --c=5
-//
-// Further instances of the option will increment from the set value.
-func Counter(name rune, helpvalue ...string) *int {
- return CommandLine.Counter(name, helpvalue...)
-}
-
-func (s *Set) Counter(name rune, helpvalue ...string) *int {
- var p int
- s.CounterVarLong(&p, "", name, helpvalue...)
- return &p
-}
-
-func CounterLong(name string, short rune, helpvalue ...string) *int {
- return CommandLine.CounterLong(name, short, helpvalue...)
-}
-
-func (s *Set) CounterLong(name string, short rune, helpvalue ...string) *int {
- var p int
- s.CounterVarLong(&p, name, short, helpvalue...)
- return &p
-}
-
-func CounterVar(p *int, name rune, helpvalue ...string) Option {
- return CommandLine.CounterVar(p, name, helpvalue...)
-}
-
-func (s *Set) CounterVar(p *int, name rune, helpvalue ...string) Option {
- return s.CounterVarLong(p, "", name, helpvalue...)
-}
-
-func CounterVarLong(p *int, name string, short rune, helpvalue ...string) Option {
- return CommandLine.CounterVarLong(p, name, short, helpvalue...)
-}
-
-func (s *Set) CounterVarLong(p *int, name string, short rune, helpvalue ...string) Option {
- return s.VarLong((*counterValue)(p), name, short, helpvalue...).SetFlag()
-}
diff --git a/vendor/github.com/pborman/getopt/counter_test.go b/vendor/github.com/pborman/getopt/counter_test.go
deleted file mode 100644
index 4b4e0cb..0000000
--- a/vendor/github.com/pborman/getopt/counter_test.go
+++ /dev/null
@@ -1,91 +0,0 @@
-// Copyright 2013 Google Inc. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package getopt
-
-import (
- "fmt"
- "strings"
- "testing"
-)
-
-var counterTests = []struct {
- where string
- in []string
- c int
- cnt int
- err string
-}{
- {
- loc(),
- []string{},
- 0,
- 0,
- "",
- },
- {
- loc(),
- []string{"test", "-c", "--cnt"},
- 1,
- 1,
- "",
- },
- {
- loc(),
- []string{"test", "-cc", "-c", "--cnt", "--cnt"},
- 3,
- 2,
- "",
- },
- {
- loc(),
- []string{"test", "--c=17", "--cnt=42"},
- 17,
- 42,
- "",
- },
- {
- loc(),
- []string{"test", "--cnt=false"},
- 0, 0,
- "test: not a valid number: false\n",
- },
-}
-
-func TestCounter(t *testing.T) {
- for x, tt := range counterTests {
- reset()
- c := Counter('c')
- cnt := CounterLong("cnt", 0)
- if strings.Index(tt.where, ":-") > 0 {
- tt.where = fmt.Sprintf("#%d", x)
- }
-
- parse(tt.in)
- if s := checkError(tt.err); s != "" {
- t.Errorf("%s: %s", tt.where, s)
- }
- if got, want := *c, tt.c; got != want {
- t.Errorf("%s: got %v, want %v", tt.where, got, want)
- }
- if got, want := *cnt, tt.cnt; got != want {
- t.Errorf("%s: got %v, want %v", tt.where, got, want)
- }
- }
-
- reset()
- c := 5
- opt := CounterVar(&c, 'c')
- parse([]string{"test", "-c"})
- if c != 6 {
- t.Errorf("got %d, want 6", c)
- }
- if opt.Count() != 1 {
- t.Errorf("got %d, want 1", c)
- }
- Reset()
- if c != 5 {
- t.Errorf("got %d, want 5", c)
- }
-}
diff --git a/vendor/github.com/pborman/getopt/duration.go b/vendor/github.com/pborman/getopt/duration.go
deleted file mode 100644
index 9061113..0000000
--- a/vendor/github.com/pborman/getopt/duration.go
+++ /dev/null
@@ -1,56 +0,0 @@
-// Copyright 2015 Google Inc. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package getopt
-
-import "time"
-
-type durationValue time.Duration
-
-func (d *durationValue) Set(value string, opt Option) error {
- v, err := time.ParseDuration(value)
- if err != nil {
- return err
- }
- *d = durationValue(v)
- return nil
-}
-
-func (d *durationValue) String() string {
- return time.Duration(*d).String()
-}
-
-// Duration creates an option that parses its value as a time.Duration.
-func Duration(name rune, value time.Duration, helpvalue ...string) *time.Duration {
- return CommandLine.Duration(name, value, helpvalue...)
-}
-
-func (s *Set) Duration(name rune, value time.Duration, helpvalue ...string) *time.Duration {
- return s.DurationLong("", name, value, helpvalue...)
-}
-
-func DurationLong(name string, short rune, value time.Duration, helpvalue ...string) *time.Duration {
- return CommandLine.DurationLong(name, short, value, helpvalue...)
-}
-
-func (s *Set) DurationLong(name string, short rune, value time.Duration, helpvalue ...string) *time.Duration {
- s.DurationVarLong(&value, name, short, helpvalue...)
- return &value
-}
-
-func DurationVar(p *time.Duration, name rune, helpvalue ...string) Option {
- return CommandLine.DurationVar(p, name, helpvalue...)
-}
-
-func (s *Set) DurationVar(p *time.Duration, name rune, helpvalue ...string) Option {
- return s.DurationVarLong(p, "", name, helpvalue...)
-}
-
-func DurationVarLong(p *time.Duration, name string, short rune, helpvalue ...string) Option {
- return CommandLine.DurationVarLong(p, name, short, helpvalue...)
-}
-
-func (s *Set) DurationVarLong(p *time.Duration, name string, short rune, helpvalue ...string) Option {
- return s.VarLong((*durationValue)(p), name, short, helpvalue...)
-}
diff --git a/vendor/github.com/pborman/getopt/duration_test.go b/vendor/github.com/pborman/getopt/duration_test.go
deleted file mode 100644
index fc4ded7..0000000
--- a/vendor/github.com/pborman/getopt/duration_test.go
+++ /dev/null
@@ -1,73 +0,0 @@
-// Copyright 2013 Google Inc. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package getopt
-
-import (
- "fmt"
- "strings"
- "testing"
- "time"
-)
-
-var durationTests = []struct {
- where string
- in []string
- d time.Duration
- dur time.Duration
- err string
-}{
- {
- loc(),
- []string{},
- 17, 42,
- "",
- },
- {
- loc(),
- []string{"test", "-d", "1s", "--duration", "2s"},
- time.Second, 2 * time.Second,
- "",
- },
- {
- loc(),
- []string{"test", "-d1s", "-d2s"},
- 2 * time.Second, 42,
- "",
- },
- {
- loc(),
- []string{"test", "-d1"},
- 17, 42,
- "test: time: missing unit in duration 1\n",
- },
- {
- loc(),
- []string{"test", "--duration", "foo"},
- 17, 42,
- "test: time: invalid duration foo\n",
- },
-}
-
-func TestDuration(t *testing.T) {
- for x, tt := range durationTests {
- reset()
- d := Duration('d', 17)
- opt := DurationLong("duration", 0, 42)
- if strings.Index(tt.where, ":-") > 0 {
- tt.where = fmt.Sprintf("#%d", x)
- }
-
- parse(tt.in)
- if s := checkError(tt.err); s != "" {
- t.Errorf("%s: %s", tt.where, s)
- }
- if got, want := *d, tt.d; got != want {
- t.Errorf("%s: got %v, want %v", tt.where, got, want)
- }
- if got, want := *opt, tt.dur; got != want {
- t.Errorf("%s: got %v, want %v", tt.where, got, want)
- }
- }
-}
diff --git a/vendor/github.com/pborman/getopt/enum.go b/vendor/github.com/pborman/getopt/enum.go
deleted file mode 100644
index ee4cf95..0000000
--- a/vendor/github.com/pborman/getopt/enum.go
+++ /dev/null
@@ -1,73 +0,0 @@
-// Copyright 2013 Google Inc. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package getopt
-
-import "errors"
-
-type enumValue string
-
-var enumValues = make(map[*enumValue]map[string]struct{})
-
-func (s *enumValue) Set(value string, opt Option) error {
- es, ok := enumValues[s]
- if !ok || es == nil {
- return errors.New("this option has no values")
- }
- if _, ok := es[value]; !ok {
- return errors.New("invalid value: " + value)
- }
- *s = enumValue(value)
- return nil
-}
-
-func (s *enumValue) String() string {
- return string(*s)
-}
-
-// Enum creates an option that can only be set to one of the enumerated strings
-// passed in values. Passing nil or an empty slice results in an option that
-// will always fail.
-func Enum(name rune, values []string, helpvalue ...string) *string {
- return CommandLine.Enum(name, values, helpvalue...)
-}
-
-func (s *Set) Enum(name rune, values []string, helpvalue ...string) *string {
- var p string
- s.EnumVarLong(&p, "", name, values, helpvalue...)
- return &p
-}
-
-func EnumLong(name string, short rune, values []string, helpvalue ...string) *string {
- return CommandLine.EnumLong(name, short, values, helpvalue...)
-}
-
-func (s *Set) EnumLong(name string, short rune, values []string, helpvalue ...string) *string {
- var p string
- s.EnumVarLong(&p, name, short, values, helpvalue...)
- return &p
-}
-
-// EnumVar creates an enum option that defaults to the starting value of *p.
-// If *p is not found in values then a reset of this option will fail.
-func EnumVar(p *string, name rune, values []string, helpvalue ...string) Option {
- return CommandLine.EnumVar(p, name, values, helpvalue...)
-}
-
-func (s *Set) EnumVar(p *string, name rune, values []string, helpvalue ...string) Option {
- return s.EnumVarLong(p, "", name, values, helpvalue...)
-}
-
-func EnumVarLong(p *string, name string, short rune, values []string, helpvalue ...string) Option {
- return CommandLine.EnumVarLong(p, name, short, values, helpvalue...)
-}
-
-func (s *Set) EnumVarLong(p *string, name string, short rune, values []string, helpvalue ...string) Option {
- m := make(map[string]struct{})
- for _, v := range values {
- m[v] = struct{}{}
- }
- enumValues[(*enumValue)(p)] = m
- return s.VarLong((*enumValue)(p), name, short, helpvalue...)
-}
diff --git a/vendor/github.com/pborman/getopt/enum_test.go b/vendor/github.com/pborman/getopt/enum_test.go
deleted file mode 100644
index 3c04ee8..0000000
--- a/vendor/github.com/pborman/getopt/enum_test.go
+++ /dev/null
@@ -1,66 +0,0 @@
-// Copyright 2013 Google Inc. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package getopt
-
-import (
- "fmt"
- "strings"
- "testing"
-)
-
-var enumTests = []struct {
- where string
- in []string
- values []string
- out string
- err string
-}{
- {
- loc(),
- nil,
- []string{},
- "",
- "",
- },
- {
- loc(),
- []string{"test", "-e", "val1"},
- []string{"val1", "val2"},
- "val1",
- "",
- },
- {
- loc(),
- []string{"test", "-e", "val1", "-e", "val2"},
- []string{"val1", "val2"},
- "val2",
- "",
- },
- {
- loc(),
- []string{"test", "-e", "val3"},
- []string{"val1", "val2"},
- "",
- "test: invalid value: val3\n",
- },
-}
-
-func TestEnum(t *testing.T) {
- for x, tt := range enumTests {
- if strings.Index(tt.where, ":-") > 0 {
- tt.where = fmt.Sprintf("#%d", x)
- }
-
- reset()
- e := Enum('e', tt.values)
- parse(tt.in)
- if s := checkError(tt.err); s != "" {
- t.Errorf("%s: %s", tt.where, s)
- }
- if *e != tt.out {
- t.Errorf("%s: got %v, want %v", tt.where, *e, tt.out)
- }
- }
-}
diff --git a/vendor/github.com/pborman/getopt/error.go b/vendor/github.com/pborman/getopt/error.go
deleted file mode 100644
index 3de8e86..0000000
--- a/vendor/github.com/pborman/getopt/error.go
+++ /dev/null
@@ -1,93 +0,0 @@
-// Copyright 2013 Google Inc. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package getopt
-
-import "fmt"
-
-// An Error is returned by Getopt when it encounters an error.
-type Error struct {
- ErrorCode // General reason of failure.
- Err error // The actual error.
- Parameter string // Parameter passed to option, if any
- Name string // Option that cause error, if any
-}
-
-// Error returns the error message, implementing the error interface.
-func (i *Error) Error() string { return i.Err.Error() }
-
-// An ErrorCode indicates what sort of error was encountered.
-type ErrorCode int
-
-const (
- NoError = ErrorCode(iota)
- UnknownOption // an invalid option was encountered
- MissingParameter // the options parameter is missing
- ExtraParameter // a value was set to a long flag
- Invalid // attempt to set an invalid value
-)
-
-func (e ErrorCode) String() string {
- switch e {
- case UnknownOption:
- return "unknow option"
- case MissingParameter:
- return "missing argument"
- case ExtraParameter:
- return "unxpected value"
- case Invalid:
- return "error setting value"
- }
- return "unknown error"
-}
-
-// unknownOption returns an Error indicating an unknown option was
-// encountered.
-func unknownOption(name interface{}) *Error {
- i := &Error{ErrorCode: UnknownOption}
- switch n := name.(type) {
- case rune:
- if n == '-' {
- i.Name = "-"
- } else {
- i.Name = "-" + string(n)
- }
- case string:
- i.Name = "--" + n
- }
- i.Err = fmt.Errorf("unknown option: %s", i.Name)
- return i
-}
-
-// missingArg returns an Error inidicating option o was not passed
-// a required paramter.
-func missingArg(o Option) *Error {
- return &Error{
- ErrorCode: MissingParameter,
- Name: o.Name(),
- Err: fmt.Errorf("missing parameter for %s", o.Name()),
- }
-}
-
-// extraArg returns an Error inidicating option o was passed the
-// unexpected paramter value.
-func extraArg(o Option, value string) *Error {
- return &Error{
- ErrorCode: ExtraParameter,
- Name: o.Name(),
- Parameter: value,
- Err: fmt.Errorf("unexpected parameter passed to %s: %q", o.Name(), value),
- }
-}
-
-// setError returns an Error inidicating option o and the specified
-// error while setting it to value.
-func setError(o Option, value string, err error) *Error {
- return &Error{
- ErrorCode: Invalid,
- Name: o.Name(),
- Parameter: value,
- Err: err,
- }
-}
diff --git a/vendor/github.com/pborman/getopt/getopt.go b/vendor/github.com/pborman/getopt/getopt.go
deleted file mode 100644
index e3279ab..0000000
--- a/vendor/github.com/pborman/getopt/getopt.go
+++ /dev/null
@@ -1,537 +0,0 @@
-// Copyright 2013 Google Inc. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// Package getopt (v1) provides traditional getopt processing for implementing
-// commands that use traditional command lines. The standard Go flag package
-// cannot be used to write a program that parses flags the way ls or ssh does,
-// for example.
-//
-// A new version of this package (v2) (whose package name is also getopt) is
-// available as:
-//
-// "github.com/pborman/getopt/v2"
-//
-// Getopt supports functionality found in both the standard BSD getopt as well
-// as (one of the many versions of) the GNU getopt_long. Being a Go package,
-// this package makes common usage easy, but still enables more controlled usage
-// if needed.
-//
-// Typical usage:
-//
-// // Declare the flags to be used
-// helpFlag := getopt.Bool('?', "display help")
-// cmdFlag := getopt.StringLong("command", 'c', "", "the command)
-//
-// func main() {
-// // Parse the program arguments
-// getopt.Parse()
-// // Get the remaining positional parameters
-// args := getopt.Args()
-//
-// If you don't want the program to exit on error, use getopt.Getopt:
-//
-// err := getopt.Getopt(nil)
-// if err != nil {
-// // code to handle error
-// fmt.Fprintln(os.Stderr, err)
-// }
-//
-// Support is provided for both short (-f) and long (--flag) options. A single
-// option may have both a short and a long name. Each option may be a flag or a
-// value. A value takes an argument.
-//
-// Declaring no long names causes this package to process arguments like the
-// traditional BSD getopt.
-//
-// Short flags may be combined into a single parameter. For example, "-a -b -c"
-// may also be expressed "-abc". Long flags must stand on their own "--alpha
-// --beta"
-//
-// Values require an argument. For short options the argument may either be
-// immediately following the short name or as the next argument. Only one short
-// value may be combined with short flags in a single argument; the short value
-// must be after all short flags. For example, if f is a flag and v is a value,
-// then:
-//
-// -vvalue (sets v to "value")
-// -v value (sets v to "value")
-// -fvvalue (sets f, and sets v to "value")
-// -fv value (sets f, and sets v to "value")
-// -vf value (set v to "f" and value is the first parameter)
-//
-// For the long value option val:
-//
-// --val value (sets val to "value")
-// --val=value (sets val to "value")
-// --valvalue (invalid option "valvalue")
-//
-// Values with an optional value only set the value if the value is part of the
-// same argument. In any event, the option count is increased and the option is
-// marked as seen.
-//
-// -v -f (sets v and f as being seen)
-// -vvalue -f (sets v to "value" and sets f)
-// --val -f (sets v and f as being seen)
-// --val=value -f (sets v to "value" and sets f)
-//
-// There is no convience function defined for making the value optional. The
-// SetOptional method must be called on the actual Option.
-//
-// v := String("val", 'v', "", "the optional v")
-// Lookup("v").SetOptional()
-//
-// var s string
-// StringVar(&s, "val", 'v', "the optional v).SetOptional()
-//
-// Parsing continues until the first non-option or "--" is encountered.
-//
-// The short name "-" can be used, but it either is specified as "-" or as part
-// of a group of options, for example "-f-". If there are no long options
-// specified then "--f" could also be used. If "-" is not declared as an option
-// then the single "-" will also terminate the option processing but unlike
-// "--", the "-" will be part of the remaining arguments.
-//
-// Normally the parsing is performed by calling the Parse function. If it is
-// important to see the order of the options then the Getopt function should be
-// used. The standard Parse function does the equivalent of:
-//
-// func Parse() {
-// if err := getopt.Getopt(os.Args, nil); err != nil {
-// fmt.Fprintln(os.Stderr, err)
-// s.usage()
-// os.Exit(1)
-// }
-//
-// When calling Getopt it is the responsibility of the caller to print any
-// errors.
-//
-// Normally the default option set, CommandLine, is used. Other option sets may
-// be created with New.
-//
-// After parsing, the sets Args will contain the non-option arguments. If an
-// error is encountered then Args will begin with argument that caused the
-// error.
-//
-// It is valid to call a set's Parse a second time to amend the current set of
-// flags or values. As an example:
-//
-// var a = getopt.Bool('a', "", "The a flag")
-// var b = getopt.Bool('b', "", "The a flag")
-// var cmd = ""
-//
-// var opts = getopt.CommandLine
-//
-// opts.Parse(os.Args)
-// if opts.NArgs() > 0 {
-// cmd = opts.Arg(0)
-// opts.Parse(opts.Args())
-// }
-//
-// If called with set to { "prog", "-a", "cmd", "-b", "arg" } then both and and
-// b would be set, cmd would be set to "cmd", and opts.Args() would return {
-// "arg" }.
-//
-// Unless an option type explicitly prohibits it, an option may appear more than
-// once in the arguments. The last value provided to the option is the value.
-//
-// SYNTAX
-//
-// For each option type there are an unfortunately large number of ways, 8, to
-// initialize the option. This number is derived from three attributes:
-//
-// 1) Short or Long name
-// 2) Normal vs Var
-// 3) Command Line vs Option Set
-//
-// The first two variations provide 4 signature:
-//
-// Option(name rune, [value type,] helpvalue... string)
-// OptionLong(name string, short rune, [value type,] helpvalue... string)
-// OptionVar(p *type, name rune, helpvalue... string)
-// OptionVarLong(p *type, name string, short rune, helpvalue... string)
-//
-// Foo can actually be expressed in terms of FooLong:
-//
-// func Foo(name rune, value type, helpvalue... string) *type {
-// return FooLong("", name, value, helpvalue...)
-// }
-//
-// Normally Foo is used, unless long options are needed. Setting short to 0
-// creates only a long option.
-//
-// The difference bentween Foo and FooVar is that you pass a pointer, p, to the
-// location of the value to FooVar. The default value is simply *p. The
-// initial value of *p is the defaut value of the option.
-//
-// Foo is actually a wrapper around FooVar:
-//
-// func Foo(name rune, value type, helpvalue... string) *type {
-// p := value
-// FooVar(&p, name, helpvalue... string)
-// return &p
-// }
-//
-//
-// The third variation provides a top-level function and a method on a Set:
-//
-// func Option(...)
-// func (s *Set) Option(...)
-//
-// The top-level function is simply:
-//
-// func Option(...) *type {
-// return CommandLine.Option(...) {
-// }
-//
-// To simplfy documentation, typically only the main top-level function is fully
-// documented. The others will have documentation when there is something
-// special about them.
-//
-// VALUEHELP
-//
-// All non-flag options are created with a "valuehelp" as the last parameter.
-// Valuehelp should be 0, 1, or 2 strings. The first string, if provided, is
-// the usage message for the option. If the second string, if provided, is the
-// name to use for the value when displaying the usage. If not provided the
-// term "value" is assumed.
-//
-// The usage message for the option created with
-//
-// StringLong("option", 'o', "defval", "a string of letters")
-//
-// is
-//
-// -o, -option=value
-//
-// StringLong("option", 'o', "defval", "a string of letters", "string")
-//
-// is
-//
-// -o, -option=string
-package getopt
-
-import (
- "fmt"
- "io"
- "os"
- "path"
- "sort"
- "strings"
-)
-
-// stderr allows tests to capture output to standard error.
-var stderr io.Writer = os.Stderr
-
-// exit allows tests to capture an os.Exit call
-var exit = os.Exit
-
-// DisplayWidth is used to determine where to split usage long lines.
-var DisplayWidth = 80
-
-// HelpColumn is the maximum column position that help strings start to display
-// at. If the option usage is too long then the help string will be displayed
-// on the next line. For example:
-//
-// -a this is the a flag
-// -u, --under=location
-// the u flag's usage is quite long
-var HelpColumn = 20
-
-// PrintUsage prints the usage of the program to w.
-func (s *Set) PrintUsage(w io.Writer) {
- sort.Sort(s.options)
- flags := ""
-
- // Build up the list of short flag names and also compute
- // how to display the option in the longer help listing.
- // We also keep track of the longest option usage string
- // that is no more than HelpColumn-3 bytes (at which point
- // we use two lines to display the help). The three
- // is for the leading space and the two spaces before the
- // help string.
- for _, opt := range s.options {
- if opt.name == "" {
- opt.name = "value"
- }
- if opt.uname == "" {
- opt.uname = opt.usageName()
- }
- if opt.flag && opt.short != 0 && opt.short != '-' {
- flags += string(opt.short)
- }
- }
-
- var opts []string
-
- // The short option - is special
- if s.shortOptions['-'] != nil {
- opts = append(opts, "-")
- }
-
- // If we have a bundle of flags, add them to the list
- if flags != "" {
- opts = append(opts, "-"+flags)
- }
-
- // Now append all the long options and options that require
- // values.
- for _, opt := range s.options {
- if opt.flag {
- if opt.short != 0 {
- continue
- }
- flags = "--" + opt.long
- } else if opt.short != 0 {
- flags = "-" + string(opt.short) + " " + opt.name
- } else {
- flags = "--" + string(opt.long) + " " + opt.name
- }
- opts = append(opts, flags)
- }
- flags = strings.Join(opts, "] [")
- if flags != "" {
- flags = " [" + flags + "]"
- }
- if s.parameters != "" {
- flags += " " + s.parameters
- }
- fmt.Fprintf(w, "Usage: %s%s\n", s.program, flags)
- s.PrintOptions(w)
-}
-
-// PrintOptions prints the list of options in s to w.
-func (s *Set) PrintOptions(w io.Writer) {
- sort.Sort(s.options)
- max := 4
- for _, opt := range s.options {
- if opt.name == "" {
- opt.name = "value"
- }
- if opt.uname == "" {
- opt.uname = opt.usageName()
- }
- if max < len(opt.uname) && len(opt.uname) <= HelpColumn-3 {
- max = len(opt.uname)
- }
- }
- // Now print one or more usage lines per option.
- for _, opt := range s.options {
- if opt.uname != "" {
- opt.help = strings.TrimSpace(opt.help)
- if len(opt.help) == 0 {
- fmt.Fprintf(w, " %s\n", opt.uname)
- continue
- }
- help := strings.Split(opt.help, "\n")
- // If they did not put in newlines then we will insert
- // them to keep the help messages from wrapping.
- if len(help) == 1 {
- help = breakup(help[0], DisplayWidth-HelpColumn)
- }
- if len(opt.uname) <= max {
- fmt.Fprintf(w, " %-*s %s\n", max, opt.uname, help[0])
- help = help[1:]
- } else {
- fmt.Fprintf(w, " %s\n", opt.uname)
- }
- for _, s := range help {
- fmt.Fprintf(w, " %-*s %s\n", max, " ", s)
- }
- }
- }
-}
-
-// breakup breaks s up into strings no longer than max bytes.
-func breakup(s string, max int) []string {
- var a []string
-
- for {
- // strip leading spaces
- for len(s) > 0 && s[0] == ' ' {
- s = s[1:]
- }
- // If the option is no longer than the max just return it
- if len(s) <= max {
- if len(s) != 0 {
- a = append(a, s)
- }
- return a
- }
- x := max
- for s[x] != ' ' {
- // the first word is too long?!
- if x == 0 {
- x = max
- for x < len(s) && s[x] != ' ' {
- x++
- }
- if x == len(s) {
- x--
- }
- break
- }
- x--
- }
- for s[x] == ' ' {
- x--
- }
- a = append(a, s[:x+1])
- s = s[x+1:]
- }
- panic("unreachable")
-}
-
-// Parse uses Getopt to parse args using the options set for s. The first
-// element of args is used to assign the program for s if it is not yet set. On
-// error, Parse displays the error message as well as a usage message on
-// standard error and then exits the program.
-func (s *Set) Parse(args []string) {
- if err := s.Getopt(args, nil); err != nil {
- fmt.Fprintln(stderr, err)
- s.usage()
- exit(1)
- }
-}
-
-// Parse uses Getopt to parse args using the options set for s. The first
-// element of args is used to assign the program for s if it is not yet set.
-// Getop calls fn, if not nil, for each option parsed.
-//
-// Getopt returns nil when all options have been processed (a non-option
-// argument was encountered, "--" was encountered, or fn returned false).
-//
-// On error getopt returns a refernce to an InvalidOption (which implements
-// the error interface).
-func (s *Set) Getopt(args []string, fn func(Option) bool) (err error) {
- s.State = InProgress
- defer func() {
- if s.State == InProgress {
- switch {
- case err != nil:
- s.State = Failure
- case len(s.args) == 0:
- s.State = EndOfArguments
- default:
- s.State = Unknown
- }
- }
- }()
- if fn == nil {
- fn = func(Option) bool { return true }
- }
- if len(args) == 0 {
- return nil
- }
-
- if s.program == "" {
- s.program = path.Base(args[0])
- }
- args = args[1:]
-Parsing:
- for len(args) > 0 {
- arg := args[0]
- s.args = args
- args = args[1:]
-
- // end of options?
- if arg == "" || arg[0] != '-' {
- s.State = EndOfOptions
- return nil
- }
-
- if arg == "-" {
- goto ShortParsing
- }
-
- // explicitly request end of options?
- if arg == "--" {
- s.args = args
- s.State = DashDash
- return nil
- }
-
- // Long option processing
- if len(s.longOptions) > 0 && arg[1] == '-' {
- e := strings.IndexRune(arg, '=')
- var value string
- if e > 0 {
- value = arg[e+1:]
- arg = arg[:e]
- }
- opt := s.longOptions[arg[2:]]
- // If we are processing long options then --f is -f
- // if f is not defined as a long option.
- // This lets you say --f=false
- if opt == nil && len(arg[2:]) == 1 {
- opt = s.shortOptions[rune(arg[2])]
- }
- if opt == nil {
- return unknownOption(arg[2:])
- }
- opt.isLong = true
- // If we require an option and did not have an =
- // then use the next argument as an option.
- if !opt.flag && e < 0 && !opt.optional {
- if len(args) == 0 {
- return missingArg(opt)
- }
- value = args[0]
- args = args[1:]
- }
- opt.count++
-
- if err := opt.value.Set(value, opt); err != nil {
- return setError(opt, value, err)
- }
-
- if !fn(opt) {
- s.State = Terminated
- return nil
- }
- continue Parsing
- }
-
- // Short option processing
- arg = arg[1:] // strip -
- ShortParsing:
- for i, c := range arg {
- opt := s.shortOptions[c]
- if opt == nil {
- // In traditional getopt, if - is not registered
- // as an option, a lone - is treated as
- // if there were a -- in front of it.
- if arg == "-" {
- s.State = Dash
- return nil
- }
- return unknownOption(c)
- }
- opt.isLong = false
- opt.count++
- var value string
- if !opt.flag {
- value = arg[1+i:]
- if value == "" && !opt.optional {
- if len(args) == 0 {
- return missingArg(opt)
- }
- value = args[0]
- args = args[1:]
- }
- }
- if err := opt.value.Set(value, opt); err != nil {
- return setError(opt, value, err)
- }
- if !fn(opt) {
- s.State = Terminated
- return nil
- }
- if !opt.flag {
- continue Parsing
- }
- }
- }
- s.args = []string{}
- return nil
-}
diff --git a/vendor/github.com/pborman/getopt/int.go b/vendor/github.com/pborman/getopt/int.go
deleted file mode 100644
index 3db5fd6..0000000
--- a/vendor/github.com/pborman/getopt/int.go
+++ /dev/null
@@ -1,67 +0,0 @@
-// Copyright 2013 Google Inc. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package getopt
-
-import (
- "fmt"
- "strconv"
-)
-
-type intValue int
-
-func (i *intValue) Set(value string, opt Option) error {
- v, err := strconv.ParseInt(value, 0, strconv.IntSize)
- if err != nil {
- if e, ok := err.(*strconv.NumError); ok {
- switch e.Err {
- case strconv.ErrRange:
- err = fmt.Errorf("value out of range: %s", value)
- case strconv.ErrSyntax:
- err = fmt.Errorf("not a valid number: %s", value)
- }
- }
- return err
- }
- *i = intValue(v)
- return nil
-}
-
-func (i *intValue) String() string {
- return strconv.FormatInt(int64(*i), 10)
-}
-
-// Int creates an option that parses its value as an integer.
-func Int(name rune, value int, helpvalue ...string) *int {
- return CommandLine.Int(name, value, helpvalue...)
-}
-
-func (s *Set) Int(name rune, value int, helpvalue ...string) *int {
- return s.IntLong("", name, value, helpvalue...)
-}
-
-func IntLong(name string, short rune, value int, helpvalue ...string) *int {
- return CommandLine.IntLong(name, short, value, helpvalue...)
-}
-
-func (s *Set) IntLong(name string, short rune, value int, helpvalue ...string) *int {
- s.IntVarLong(&value, name, short, helpvalue...)
- return &value
-}
-
-func IntVar(p *int, name rune, helpvalue ...string) Option {
- return CommandLine.IntVar(p, name, helpvalue...)
-}
-
-func (s *Set) IntVar(p *int, name rune, helpvalue ...string) Option {
- return s.IntVarLong(p, "", name, helpvalue...)
-}
-
-func IntVarLong(p *int, name string, short rune, helpvalue ...string) Option {
- return CommandLine.IntVarLong(p, name, short, helpvalue...)
-}
-
-func (s *Set) IntVarLong(p *int, name string, short rune, helpvalue ...string) Option {
- return s.VarLong((*intValue)(p), name, short, helpvalue...)
-}
diff --git a/vendor/github.com/pborman/getopt/int16.go b/vendor/github.com/pborman/getopt/int16.go
deleted file mode 100644
index 2ece51f..0000000
--- a/vendor/github.com/pborman/getopt/int16.go
+++ /dev/null
@@ -1,67 +0,0 @@
-// Copyright 2013 Google Inc. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package getopt
-
-import (
- "fmt"
- "strconv"
-)
-
-type int16Value int16
-
-func (i *int16Value) Set(value string, opt Option) error {
- v, err := strconv.ParseInt(value, 0, 16)
- if err != nil {
- if e, ok := err.(*strconv.NumError); ok {
- switch e.Err {
- case strconv.ErrRange:
- err = fmt.Errorf("value out of range: %s", value)
- case strconv.ErrSyntax:
- err = fmt.Errorf("not a valid number: %s", value)
- }
- }
- return err
- }
- *i = int16Value(v)
- return nil
-}
-
-func (i *int16Value) String() string {
- return strconv.FormatInt(int64(*i), 10)
-}
-
-// Int16 creates an option that parses its value as an int16.
-func Int16(name rune, value int16, helpvalue ...string) *int16 {
- return CommandLine.Int16(name, value, helpvalue...)
-}
-
-func (s *Set) Int16(name rune, value int16, helpvalue ...string) *int16 {
- return s.Int16Long("", name, value, helpvalue...)
-}
-
-func Int16Long(name string, short rune, value int16, helpvalue ...string) *int16 {
- return CommandLine.Int16Long(name, short, value, helpvalue...)
-}
-
-func (s *Set) Int16Long(name string, short rune, value int16, helpvalue ...string) *int16 {
- s.Int16VarLong(&value, name, short, helpvalue...)
- return &value
-}
-
-func Int16Var(p *int16, name rune, helpvalue ...string) Option {
- return CommandLine.Int16Var(p, name, helpvalue...)
-}
-
-func (s *Set) Int16Var(p *int16, name rune, helpvalue ...string) Option {
- return s.Int16VarLong(p, "", name, helpvalue...)
-}
-
-func Int16VarLong(p *int16, name string, short rune, helpvalue ...string) Option {
- return CommandLine.Int16VarLong(p, name, short, helpvalue...)
-}
-
-func (s *Set) Int16VarLong(p *int16, name string, short rune, helpvalue ...string) Option {
- return s.VarLong((*int16Value)(p), name, short, helpvalue...)
-}
diff --git a/vendor/github.com/pborman/getopt/int16_test.go b/vendor/github.com/pborman/getopt/int16_test.go
deleted file mode 100644
index 8b83c1e..0000000
--- a/vendor/github.com/pborman/getopt/int16_test.go
+++ /dev/null
@@ -1,84 +0,0 @@
-// Copyright 2013 Google Inc. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package getopt
-
-import (
- "fmt"
- "strings"
- "testing"
-)
-
-var int16Tests = []struct {
- where string
- in []string
- i int16
- int16 int16
- err string
-}{
- {
- loc(),
- []string{},
- 17, 42,
- "",
- },
- {
- loc(),
- []string{"test", "-i", "1", "--int16", "2"},
- 1, 2,
- "",
- },
- {
- loc(),
- []string{"test", "-i1", "--int16=2"},
- 1, 2,
- "",
- },
- {
- loc(),
- []string{"test", "-i1", "-i2"},
- 2, 42,
- "",
- },
- {
- loc(),
- []string{"test", "-i=1"},
- 17, 42,
- "test: not a valid number: =1\n",
- },
- {
- loc(),
- []string{"test", "-i0x20"},
- 0x20, 42,
- "",
- },
- {
- loc(),
- []string{"test", "-i010"},
- 8, 42,
- "",
- },
-}
-
-func TestInt16(t *testing.T) {
- for x, tt := range int16Tests {
- reset()
- i := Int16('i', 17)
- opt := Int16Long("int16", 0, 42)
- if strings.Index(tt.where, ":-") > 0 {
- tt.where = fmt.Sprintf("#%d", x)
- }
-
- parse(tt.in)
- if s := checkError(tt.err); s != "" {
- t.Errorf("%s: %s", tt.where, s)
- }
- if got, want := *i, tt.i; got != want {
- t.Errorf("%s: got %v, want %v", tt.where, got, want)
- }
- if got, want := *opt, tt.int16; got != want {
- t.Errorf("%s: got %v, want %v", tt.where, got, want)
- }
- }
-}
diff --git a/vendor/github.com/pborman/getopt/int32.go b/vendor/github.com/pborman/getopt/int32.go
deleted file mode 100644
index b8f3415..0000000
--- a/vendor/github.com/pborman/getopt/int32.go
+++ /dev/null
@@ -1,67 +0,0 @@
-// Copyright 2013 Google Inc. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package getopt
-
-import (
- "fmt"
- "strconv"
-)
-
-type int32Value int32
-
-func (i *int32Value) Set(value string, opt Option) error {
- v, err := strconv.ParseInt(value, 0, 32)
- if err != nil {
- if e, ok := err.(*strconv.NumError); ok {
- switch e.Err {
- case strconv.ErrRange:
- err = fmt.Errorf("value out of range: %s", value)
- case strconv.ErrSyntax:
- err = fmt.Errorf("not a valid number: %s", value)
- }
- }
- return err
- }
- *i = int32Value(v)
- return nil
-}
-
-func (i *int32Value) String() string {
- return strconv.FormatInt(int64(*i), 10)
-}
-
-// Int32 creates an option that parses its value as an int32.
-func Int32(name rune, value int32, helpvalue ...string) *int32 {
- return CommandLine.Int32(name, value, helpvalue...)
-}
-
-func (s *Set) Int32(name rune, value int32, helpvalue ...string) *int32 {
- return s.Int32Long("", name, value, helpvalue...)
-}
-
-func Int32Long(name string, short rune, value int32, helpvalue ...string) *int32 {
- return CommandLine.Int32Long(name, short, value, helpvalue...)
-}
-
-func (s *Set) Int32Long(name string, short rune, value int32, helpvalue ...string) *int32 {
- s.Int32VarLong(&value, name, short, helpvalue...)
- return &value
-}
-
-func Int32Var(p *int32, name rune, helpvalue ...string) Option {
- return CommandLine.Int32Var(p, name, helpvalue...)
-}
-
-func (s *Set) Int32Var(p *int32, name rune, helpvalue ...string) Option {
- return s.Int32VarLong(p, "", name, helpvalue...)
-}
-
-func Int32VarLong(p *int32, name string, short rune, helpvalue ...string) Option {
- return CommandLine.Int32VarLong(p, name, short, helpvalue...)
-}
-
-func (s *Set) Int32VarLong(p *int32, name string, short rune, helpvalue ...string) Option {
- return s.VarLong((*int32Value)(p), name, short, helpvalue...)
-}
diff --git a/vendor/github.com/pborman/getopt/int32_test.go b/vendor/github.com/pborman/getopt/int32_test.go
deleted file mode 100644
index 9da9aeb..0000000
--- a/vendor/github.com/pborman/getopt/int32_test.go
+++ /dev/null
@@ -1,84 +0,0 @@
-// Copyright 2013 Google Inc. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package getopt
-
-import (
- "fmt"
- "strings"
- "testing"
-)
-
-var int32Tests = []struct {
- where string
- in []string
- i int32
- int32 int32
- err string
-}{
- {
- loc(),
- []string{},
- 17, 42,
- "",
- },
- {
- loc(),
- []string{"test", "-i", "1", "--int32", "2"},
- 1, 2,
- "",
- },
- {
- loc(),
- []string{"test", "-i1", "--int32=2"},
- 1, 2,
- "",
- },
- {
- loc(),
- []string{"test", "-i1", "-i2"},
- 2, 42,
- "",
- },
- {
- loc(),
- []string{"test", "-i=1"},
- 17, 42,
- "test: not a valid number: =1\n",
- },
- {
- loc(),
- []string{"test", "-i0x20"},
- 0x20, 42,
- "",
- },
- {
- loc(),
- []string{"test", "-i010"},
- 8, 42,
- "",
- },
-}
-
-func TestInt32(t *testing.T) {
- for x, tt := range int32Tests {
- reset()
- i := Int32('i', 17)
- opt := Int32Long("int32", 0, 42)
- if strings.Index(tt.where, ":-") > 0 {
- tt.where = fmt.Sprintf("#%d", x)
- }
-
- parse(tt.in)
- if s := checkError(tt.err); s != "" {
- t.Errorf("%s: %s", tt.where, s)
- }
- if got, want := *i, tt.i; got != want {
- t.Errorf("%s: got %v, want %v", tt.where, got, want)
- }
- if got, want := *opt, tt.int32; got != want {
- t.Errorf("%s: got %v, want %v", tt.where, got, want)
- }
- }
-}
diff --git a/vendor/github.com/pborman/getopt/int64.go b/vendor/github.com/pborman/getopt/int64.go
deleted file mode 100644
index d29e6b4..0000000
--- a/vendor/github.com/pborman/getopt/int64.go
+++ /dev/null
@@ -1,67 +0,0 @@
-// Copyright 2013 Google Inc. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package getopt
-
-import (
- "fmt"
- "strconv"
-)
-
-type int64Value int64
-
-func (i *int64Value) Set(value string, opt Option) error {
- v, err := strconv.ParseInt(value, 0, 64)
- if err != nil {
- if e, ok := err.(*strconv.NumError); ok {
- switch e.Err {
- case strconv.ErrRange:
- err = fmt.Errorf("value out of range: %s", value)
- case strconv.ErrSyntax:
- err = fmt.Errorf("not a valid number: %s", value)
- }
- }
- return err
- }
- *i = int64Value(v)
- return nil
-}
-
-func (i *int64Value) String() string {
- return strconv.FormatInt(int64(*i), 10)
-}
-
-// Int64 creates an option that parses its value as an int64.
-func Int64(name rune, value int64, helpvalue ...string) *int64 {
- return CommandLine.Int64(name, value, helpvalue...)
-}
-
-func (s *Set) Int64(name rune, value int64, helpvalue ...string) *int64 {
- return s.Int64Long("", name, value, helpvalue...)
-}
-
-func Int64Long(name string, short rune, value int64, helpvalue ...string) *int64 {
- return CommandLine.Int64Long(name, short, value, helpvalue...)
-}
-
-func (s *Set) Int64Long(name string, short rune, value int64, helpvalue ...string) *int64 {
- s.Int64VarLong(&value, name, short, helpvalue...)
- return &value
-}
-
-func Int64Var(p *int64, name rune, helpvalue ...string) Option {
- return CommandLine.Int64Var(p, name, helpvalue...)
-}
-
-func (s *Set) Int64Var(p *int64, name rune, helpvalue ...string) Option {
- return s.Int64VarLong(p, "", name, helpvalue...)
-}
-
-func Int64VarLong(p *int64, name string, short rune, helpvalue ...string) Option {
- return CommandLine.Int64VarLong(p, name, short, helpvalue...)
-}
-
-func (s *Set) Int64VarLong(p *int64, name string, short rune, helpvalue ...string) Option {
- return s.VarLong((*int64Value)(p), name, short, helpvalue...)
-}
diff --git a/vendor/github.com/pborman/getopt/int64_test.go b/vendor/github.com/pborman/getopt/int64_test.go
deleted file mode 100644
index 7fa01b5..0000000
--- a/vendor/github.com/pborman/getopt/int64_test.go
+++ /dev/null
@@ -1,84 +0,0 @@
-// Copyright 2013 Google Inc. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package getopt
-
-import (
- "fmt"
- "strings"
- "testing"
-)
-
-var int64Tests = []struct {
- where string
- in []string
- i int64
- int64 int64
- err string
-}{
- {
- loc(),
- []string{},
- 17, 42,
- "",
- },
- {
- loc(),
- []string{"test", "-i", "1", "--int64", "2"},
- 1, 2,
- "",
- },
- {
- loc(),
- []string{"test", "-i1", "--int64=2"},
- 1, 2,
- "",
- },
- {
- loc(),
- []string{"test", "-i1", "-i2"},
- 2, 42,
- "",
- },
- {
- loc(),
- []string{"test", "-i=1"},
- 17, 42,
- "test: not a valid number: =1\n",
- },
- {
- loc(),
- []string{"test", "-i0x20"},
- 0x20, 42,
- "",
- },
- {
- loc(),
- []string{"test", "-i010"},
- 8, 42,
- "",
- },
-}
-
-func TestInt64(t *testing.T) {
- for x, tt := range int64Tests {
- reset()
- i := Int64('i', 17)
- opt := Int64Long("int64", 0, 42)
- if strings.Index(tt.where, ":-") > 0 {
- tt.where = fmt.Sprintf("#%d", x)
- }
-
- parse(tt.in)
- if s := checkError(tt.err); s != "" {
- t.Errorf("%s: %s", tt.where, s)
- }
- if got, want := *i, tt.i; got != want {
- t.Errorf("%s: got %v, want %v", tt.where, got, want)
- }
- if got, want := *opt, tt.int64; got != want {
- t.Errorf("%s: got %v, want %v", tt.where, got, want)
- }
- }
-}
diff --git a/vendor/github.com/pborman/getopt/int_test.go b/vendor/github.com/pborman/getopt/int_test.go
deleted file mode 100644
index f12af31..0000000
--- a/vendor/github.com/pborman/getopt/int_test.go
+++ /dev/null
@@ -1,84 +0,0 @@
-// Copyright 2013 Google Inc. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package getopt
-
-import (
- "fmt"
- "strings"
- "testing"
-)
-
-var intTests = []struct {
- where string
- in []string
- i int
- int int
- err string
-}{
- {
- loc(),
- []string{},
- 17, 42,
- "",
- },
- {
- loc(),
- []string{"test", "-i", "1", "--int", "2"},
- 1, 2,
- "",
- },
- {
- loc(),
- []string{"test", "-i1", "--int=2"},
- 1, 2,
- "",
- },
- {
- loc(),
- []string{"test", "-i1", "-i2"},
- 2, 42,
- "",
- },
- {
- loc(),
- []string{"test", "-i=1"},
- 17, 42,
- "test: not a valid number: =1\n",
- },
- {
- loc(),
- []string{"test", "-i0x20"},
- 0x20, 42,
- "",
- },
- {
- loc(),
- []string{"test", "-i010"},
- 8, 42,
- "",
- },
-}
-
-func TestInt(t *testing.T) {
- for x, tt := range intTests {
- reset()
- i := Int('i', 17)
- opt := IntLong("int", 0, 42)
- if strings.Index(tt.where, ":-") > 0 {
- tt.where = fmt.Sprintf("#%d", x)
- }
-
- parse(tt.in)
- if s := checkError(tt.err); s != "" {
- t.Errorf("%s: %s", tt.where, s)
- }
- if got, want := *i, tt.i; got != want {
- t.Errorf("%s: got %v, want %v", tt.where, got, want)
- }
- if got, want := *opt, tt.int; got != want {
- t.Errorf("%s: got %v, want %v", tt.where, got, want)
- }
- }
-}
diff --git a/vendor/github.com/pborman/getopt/list.go b/vendor/github.com/pborman/getopt/list.go
deleted file mode 100644
index b9d4267..0000000
--- a/vendor/github.com/pborman/getopt/list.go
+++ /dev/null
@@ -1,69 +0,0 @@
-// Copyright 2013 Google Inc. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package getopt
-
-import "strings"
-
-type listValue []string
-
-func (s *listValue) Set(value string, opt Option) error {
- a := strings.Split(value, ",")
- // If this is the first time we are seen then nil out the
- // default value.
- if opt.Count() <= 1 {
- *s = nil
- }
- *s = append(*s, a...)
- return nil
-}
-
-func (s *listValue) String() string {
- return strings.Join([]string(*s), ",")
-}
-
-// List creates an option that returns a slice of strings. The parameters
-// passed are converted from a comma seperated value list into a slice.
-// Subsequent occurrences append to the list.
-func List(name rune, helpvalue ...string) *[]string {
- return CommandLine.List(name, helpvalue...)
-}
-
-func (s *Set) List(name rune, helpvalue ...string) *[]string {
- p := []string{}
- s.ListVar(&p, name, helpvalue...)
- return &p
-}
-
-func ListLong(name string, short rune, helpvalue ...string) *[]string {
- return CommandLine.ListLong(name, short, helpvalue...)
-}
-
-func (s *Set) ListLong(name string, short rune, helpvalue ...string) *[]string {
- p := []string{}
- s.ListVarLong(&p, name, short, helpvalue...)
- return &p
-}
-
-// ListVar creats a list option and places the values in p. If p is pointing
-// to a list of values then those are considered the default values. The first
-// time name is seen in the options the list will be set to list specified by
-// the parameter to the option. Subsequent instances of the option will append
-// to the list.
-func ListVar(p *[]string, name rune, helpvalue ...string) Option {
- return CommandLine.ListVar(p, name, helpvalue...)
-}
-
-func (s *Set) ListVar(p *[]string, name rune, helpvalue ...string) Option {
- return s.ListVarLong(p, "", name, helpvalue...)
-}
-
-func ListVarLong(p *[]string, name string, short rune, helpvalue ...string) Option {
- return CommandLine.ListVarLong(p, name, short, helpvalue...)
-}
-
-func (s *Set) ListVarLong(p *[]string, name string, short rune, helpvalue ...string) Option {
- opt := s.VarLong((*listValue)(p), name, short, helpvalue...)
- return opt
-}
diff --git a/vendor/github.com/pborman/getopt/list_test.go b/vendor/github.com/pborman/getopt/list_test.go
deleted file mode 100644
index 71f9c32..0000000
--- a/vendor/github.com/pborman/getopt/list_test.go
+++ /dev/null
@@ -1,99 +0,0 @@
-// Copyright 2013 Google Inc. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package getopt
-
-import "testing"
-
-var listTests = []struct {
- where string
- in []string
- l, list []string
- err string
-}{
- {
- loc(),
- []string{},
- nil, nil,
- "",
- },
- {
- loc(),
- []string{"test", "-l", "one"},
- []string{"one"}, nil,
- "",
- },
- {
- loc(),
- []string{"test", "-lone", "-ltwo"},
- []string{"one", "two"}, nil,
- "",
- },
- {
- loc(),
- []string{"test", "--list", "one"},
- nil, []string{"one"},
- "",
- },
- {
- loc(),
- []string{"test", "--list=one", "--list=two"},
- nil, []string{"one", "two"},
- "",
- },
- {
- loc(),
- []string{"test", "--list=one,two"},
- nil, []string{"one", "two"},
- "",
- },
-}
-
-func TestList(t *testing.T) {
- for _, tt := range listTests {
- reset()
- l := List('l')
- list := ListLong("list", 0)
-
- parse(tt.in)
- if s := checkError(tt.err); s != "" {
- t.Errorf("%s: %s", tt.where, s)
- }
- if badSlice(*l, tt.l) {
- t.Errorf("%s: got s = %q, want %q", tt.where, *l, tt.l)
- }
- if badSlice(*list, tt.list) {
- t.Errorf("%s: got s = %q, want %q", tt.where, *list, tt.list)
- }
- }
-}
-
-func TestDefaultList(t *testing.T) {
- reset()
- list := []string{"d1", "d2", "d3"}
- ListVar(&list, 'l')
- parse([]string{"test"})
-
- want := []string{"d1", "d2", "d3"}
- if badSlice(list, want) {
- t.Errorf("got s = %q, want %q", list, want)
- }
-
- parse([]string{"test", "-l", "one"})
- want = []string{"one"}
- if badSlice(list, want) {
- t.Errorf("got s = %q, want %q", list, want)
- }
-
- parse([]string{"test", "-l", "two"})
- want = []string{"one", "two"}
- if badSlice(list, want) {
- t.Errorf("got s = %q, want %q", list, want)
- }
- Lookup('l').Reset()
- want = []string{"d1", "d2", "d3"}
- if badSlice(list, want) {
- t.Errorf("got s = %q, want %q", list, want)
- }
-}
diff --git a/vendor/github.com/pborman/getopt/option.go b/vendor/github.com/pborman/getopt/option.go
deleted file mode 100644
index 17dbe58..0000000
--- a/vendor/github.com/pborman/getopt/option.go
+++ /dev/null
@@ -1,193 +0,0 @@
-// Copyright 2013 Google Inc. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package getopt
-
-import (
- "fmt"
- "strings"
-)
-
-// An Option can be either a Flag or a Value
-type Option interface {
- // Name returns the name of the option. If the option has been seen
- // then the last way it was referenced (short or long) is returned
- // otherwise if there is a short name then this will be the short name
- // as a string, else it will be the long name.
- Name() string
-
- // IsFlag returns true if Option is a flag.
- IsFlag() bool
-
- // Seen returns true if the flag was seen.
- Seen() bool
-
- // Count returns the number of times the flag was seen.
- Count() int
-
- // String returns the last value the option was set to.
- String() string
-
- // Value returns the Value of the option.
- Value() Value
-
- // SetOptional makes the value optional. The option and value are
- // always a single argument. Either --option or --option=value. In
- // the former case the value of the option does not change but the Set()
- // will return true and the value returned by Count() is incremented.
- // The short form is either -o or -ovalue. SetOptional returns
- // the Option
- SetOptional() Option
-
- // SetFlag makes the value a flag. Flags are boolean values and
- // normally do not taken a value. They are set to true when seen.
- // If a value is passed in the long form then it must be on, case
- // insenstive, one of "true", "false", "t", "f", "on", "off", "1", "0".
- // SetFlag returns the Option
- SetFlag() Option
-
- // Reset resets the state of the option so it appears it has not
- // yet been seen, including resetting the value of the option
- // to its original default state.
- Reset()
-}
-
-type option struct {
- short rune // 0 means no short name
- long string // "" means no long name
- isLong bool // True if they used the long name
- flag bool // true if a boolean flag
- defval string // default value
- optional bool // true if we take an optional value
- help string // help message
- where string // file where the option was defined
- value Value // current value of option
- count int // number of times we have seen this option
- name string // name of the value (for usage)
- uname string // name of the option (for usage)
-}
-
-// usageName returns the name of the option for printing usage lines in one
-// of the following forms:
-//
-// -f
-// --flag
-// -f, --flag
-// -s value
-// --set=value
-// -s, --set=value
-func (o *option) usageName() string {
- // Don't print help messages if we have none and there is only one
- // way to specify the option.
- if o.help == "" && (o.short == 0 || o.long == "") {
- return ""
- }
- n := ""
-
- switch {
- case o.short != 0 && o.long == "":
- n = "-" + string(o.short)
- case o.short == 0 && o.long != "":
- n = " --" + o.long
- case o.short != 0 && o.long != "":
- n = "-" + string(o.short) + ", --" + o.long
- }
-
- switch {
- case o.flag:
- return n
- case o.optional:
- return n + "[=" + o.name + "]"
- case o.long != "":
- return n + "=" + o.name
- }
- return n + " " + o.name
-}
-
-// sortName returns the name to sort the option on.
-func (o *option) sortName() string {
- if o.short != 0 {
- return string(o.short) + o.long
- }
- return o.long[:1] + o.long
-}
-
-func (o *option) Seen() bool { return o.count > 0 }
-func (o *option) Count() int { return o.count }
-func (o *option) IsFlag() bool { return o.flag }
-func (o *option) String() string { return o.value.String() }
-func (o *option) SetOptional() Option { o.optional = true; return o }
-func (o *option) SetFlag() Option { o.flag = true; return o }
-
-func (o *option) Value() Value {
- if o == nil {
- return nil
- }
- return o.value
-}
-
-func (o *option) Name() string {
- if !o.isLong && o.short != 0 {
- return "-" + string(o.short)
- }
- return "--" + o.long
-}
-
-// Reset rests an option so that it appears it has not yet been seen.
-func (o *option) Reset() {
- o.isLong = false
- o.count = 0
- o.value.Set(o.defval, o)
-}
-
-type optionList []*option
-
-func (ol optionList) Len() int { return len(ol) }
-func (ol optionList) Swap(i, j int) { ol[i], ol[j] = ol[j], ol[i] }
-func (ol optionList) Less(i, j int) bool {
- // first check the short names (or the first letter of the long name)
- // If they are not equal (case insensitive) then we have our answer
- n1 := ol[i].sortName()
- n2 := ol[j].sortName()
- l1 := strings.ToLower(n1)
- l2 := strings.ToLower(n2)
- if l1 < l2 {
- return true
- }
- if l2 < l1 {
- return false
- }
- return n1 < n2
-}
-
-// AddOption add the option o to set CommandLine if o is not already in set
-// CommandLine.
-func AddOption(o Option) {
- CommandLine.AddOption(o)
-}
-
-// AddOption add the option o to set s if o is not already in set s.
-func (s *Set) AddOption(o Option) {
- opt := o.(*option)
- for _, eopt := range s.options {
- if opt == eopt {
- return
- }
- }
- if opt.short != 0 {
- if oo, ok := s.shortOptions[opt.short]; ok {
- fmt.Fprintf(stderr, "%s: -%c already declared at %s\n", opt.where, opt.short, oo.where)
- exit(1)
- }
- s.shortOptions[opt.short] = opt
- }
- if opt.long != "" {
- if oo, ok := s.longOptions[opt.long]; ok {
- fmt.Fprintf(stderr, "%s: --%s already declared at %s\n", opt.where, opt.long, oo.where)
- exit(1)
- }
- s.longOptions[opt.long] = opt
- }
- s.options = append(s.options, opt)
-}
diff --git a/vendor/github.com/pborman/getopt/set.go b/vendor/github.com/pborman/getopt/set.go
deleted file mode 100644
index 64d9ecf..0000000
--- a/vendor/github.com/pborman/getopt/set.go
+++ /dev/null
@@ -1,268 +0,0 @@
-// Copyright 2013 Google Inc. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package getopt
-
-import (
- "io"
- "os"
- "sort"
-)
-
-// A Termination says why Getopt returned.
-type State int
-
-const (
- InProgress = State(iota) // Getopt is still running
- Dash // Returned on "-"
- DashDash // Returned on "--"
- EndOfOptions // End of options reached
- EndOfArguments // No more arguments
- Terminated // Terminated by callback function
- Failure // Terminated due to error
- Unknown // Indicates internal error
-)
-
-type Set struct {
- State // State of getopt
-
- // args are the parameters remaining after parsing the optoins.
- args []string
-
- // program is the name of the program for usage and error messages.
- // If not set it will automatically be set to the base name of the
- // first argument passed to parse.
- program string
-
- // parameters is what is displayed on the usage line after displaying
- // the various options.
- parameters string
-
- usage func() // usage should print the programs usage and exit.
-
- shortOptions map[rune]*option
- longOptions map[string]*option
- options optionList
-}
-
-// New returns a newly created option set.
-func New() *Set {
- s := &Set{
- shortOptions: make(map[rune]*option),
- longOptions: make(map[string]*option),
- parameters: "[parameters ...]",
- }
-
- s.usage = func() {
- s.PrintUsage(stderr)
- }
- return s
-}
-
-// The default set of command-line options.
-var CommandLine = New()
-
-// PrintUsage calls PrintUsage in the default option set.
-func PrintUsage(w io.Writer) { CommandLine.PrintUsage(w) }
-
-// Usage calls the usage function in the default option set.
-func Usage() { CommandLine.usage() }
-
-// Parse calls Parse in the default option set with the command line arguments
-// found in os.Args.
-func Parse() { CommandLine.Parse(os.Args) }
-
-// Getops returns the result of calling Getop in the default option set with the
-// command line arguments found in os.Args. The fn function, which may be nil,
-// is passed to Getopt.
-func Getopt(fn func(Option) bool) error { return CommandLine.Getopt(os.Args, fn) }
-
-// Arg returns the n'th command-line argument. Arg(0) is the first remaining
-// argument after options have been processed.
-func Arg(n int) string {
- if n >= 0 && n < len(CommandLine.args) {
- return CommandLine.args[n]
- }
- return ""
-}
-
-// Arg returns the n'th argument. Arg(0) is the first remaining
-// argument after options have been processed.
-func (s *Set) Arg(n int) string {
- if n >= 0 && n < len(s.args) {
- return s.args[n]
- }
- return ""
-}
-
-// Args returns the non-option command line arguments.
-func Args() []string {
- return CommandLine.args
-}
-
-// Args returns the non-option arguments.
-func (s *Set) Args() []string {
- return s.args
-}
-
-// NArgs returns the number of non-option command line arguments.
-func NArgs() int {
- return len(CommandLine.args)
-}
-
-// NArgs returns the number of non-option arguments.
-func (s *Set) NArgs() int {
- return len(s.args)
-}
-
-// SetParameters sets the parameters string for printing the command line
-// usage. It defaults to "[parameters ...]"
-func SetParameters(parameters string) {
- CommandLine.parameters = parameters
-}
-
-// SetParameters sets the parameters string for printing the s's usage.
-// It defaults to "[parameters ...]"
-func (s *Set) SetParameters(parameters string) {
- s.parameters = parameters
-}
-
-// SetProgram sets the program name to program. Nomrally it is determined
-// from the zeroth command line argument (see os.Args).
-func SetProgram(program string) {
- CommandLine.program = program
-}
-
-// SetProgram sets s's program name to program. Nomrally it is determined
-// from the zeroth argument passed to Getopt or Parse.
-func (s *Set) SetProgram(program string) {
- s.program = program
-}
-
-// SetUsage sets the function used by Parse to display the commands usage
-// on error. It defaults to calling PrintUsage(os.Stderr).
-func SetUsage(usage func()) {
- CommandLine.usage = usage
-}
-
-// SetUsage sets the function used by Parse to display usage on error. It
-// defaults to calling f.PrintUsage(os.Stderr).
-func (s *Set) SetUsage(usage func()) {
- s.usage = usage
-}
-
-// Lookup returns the Option associated with name. Name should either be
-// a rune (the short name) or a string (the long name).
-func Lookup(name interface{}) Option {
- return CommandLine.Lookup(name)
-}
-
-// Lookup returns the Option associated with name in s. Name should either be
-// a rune (the short name) or a string (the long name).
-func (s *Set) Lookup(name interface{}) Option {
- switch v := name.(type) {
- case rune:
- return s.shortOptions[v]
- case int:
- return s.shortOptions[rune(v)]
- case string:
- return s.longOptions[v]
- }
- return nil
-}
-
-// IsSet returns true if the Option associated with name was seen while
-// parsing the command line arguments. Name should either be a rune (the
-// short name) or a string (the long name).
-func IsSet(name interface{}) bool {
- return CommandLine.IsSet(name)
-}
-
-// IsSet returns true if the Option associated with name was seen while
-// parsing s. Name should either be a rune (the short name) or a string (the
-// long name).
-func (s *Set) IsSet(name interface{}) bool {
- if opt := s.Lookup(name); opt != nil {
- return opt.Seen()
- }
- return false
-}
-
-// GetCount returns the number of times the Option associated with name has been
-// seen while parsing the command line arguments. Name should either be a rune
-// (the short name) or a string (the long name).
-func GetCount(name interface{}) int {
- return CommandLine.GetCount(name)
-}
-
-// GetCount returns the number of times the Option associated with name has been
-// seen while parsing s's arguments. Name should either be a rune (the short
-// name) or a string (the long name).
-func (s *Set) GetCount(name interface{}) int {
- if opt := s.Lookup(name); opt != nil {
- return opt.Count()
- }
- return 0
-}
-
-// GetValue returns the final value set to the command-line Option with name.
-// If the option has not been seen while parsing s then the default value is
-// returned. Name should either be a rune (the short name) or a string (the
-// long name).
-func GetValue(name interface{}) string {
- return CommandLine.GetValue(name)
-}
-
-// GetValue returns the final value set to the Option in s associated with name.
-// If the option has not been seen while parsing s then the default value is
-// returned. Name should either be a rune (the short name) or a string (the
-// long name).
-func (s *Set) GetValue(name interface{}) string {
- if opt := s.Lookup(name); opt != nil {
- return opt.String()
- }
- return ""
-}
-
-// Visit visits the command-line options in lexicographical order, calling fn
-// for each. It visits only those options that have been set.
-func Visit(fn func(Option)) { CommandLine.Visit(fn) }
-
-// Visit visits the options in s in lexicographical order, calling fn
-// for each. It visits only those options that have been set.
-func (s *Set) Visit(fn func(Option)) {
- sort.Sort(s.options)
- for _, opt := range s.options {
- if opt.count > 0 {
- fn(opt)
- }
- }
-}
-
-// VisitAll visits the options in s in lexicographical order, calling fn
-// for each. It visits all options, even those not set.
-func VisitAll(fn func(Option)) { CommandLine.VisitAll(fn) }
-
-// VisitAll visits the command-line flags in lexicographical order, calling fn
-// for each. It visits all flags, even those not set.
-func (s *Set) VisitAll(fn func(Option)) {
- sort.Sort(s.options)
- for _, opt := range s.options {
- fn(opt)
- }
-}
-
-// Reset resets all the command line options to the initial state so it
-// appears none of them have been seen.
-func Reset() {
- CommandLine.Reset()
-}
-
-// Reset resets all the options in s to the initial state so it
-// appears none of them have been seen.
-func (s *Set) Reset() {
- for _, opt := range s.options {
- opt.Reset()
- }
-}
diff --git a/vendor/github.com/pborman/getopt/signed.go b/vendor/github.com/pborman/getopt/signed.go
deleted file mode 100644
index a0e059c..0000000
--- a/vendor/github.com/pborman/getopt/signed.go
+++ /dev/null
@@ -1,110 +0,0 @@
-// Copyright 2013 Google Inc. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package getopt
-
-import (
- "fmt"
- "strconv"
-)
-
-type signed int64
-
-type SignedLimit struct {
- Base int // Base for conversion as per strconv.ParseInt
- Bits int // Number of bits as per strconv.ParseInt
- Min int64 // Minimum allowed value if both Min and Max are not 0
- Max int64 // Maximum allowed value if both Min and Max are not 0
-}
-
-var signedLimits = make(map[*signed]*SignedLimit)
-
-func (n *signed) Set(value string, opt Option) error {
- l := signedLimits[n]
- if l == nil {
- return fmt.Errorf("no limits defined for %s", opt.Name())
- }
- v, err := strconv.ParseInt(value, l.Base, l.Bits)
- if err != nil {
- if e, ok := err.(*strconv.NumError); ok {
- switch e.Err {
- case strconv.ErrRange:
- err = fmt.Errorf("value out of range: %s", value)
- case strconv.ErrSyntax:
- err = fmt.Errorf("not a valid number: %s", value)
- }
- }
- return err
- }
- if l.Min != 0 || l.Max != 0 {
- if v < l.Min {
- return fmt.Errorf("value out of range (<%v): %s", l.Min, value)
- }
- if v > l.Max {
- return fmt.Errorf("value out of range (>%v): %s", l.Max, value)
- }
- }
- *n = signed(v)
- return nil
-}
-
-func (n *signed) String() string {
- l := signedLimits[n]
- if l != nil && l.Base != 0 {
- return strconv.FormatInt(int64(*n), l.Base)
- }
- return strconv.FormatInt(int64(*n), 10)
-}
-
-// Signed creates an option that is stored in an int64 and is constrained
-// by the limits pointed to by l. The Max and Min values are only used if
-// at least one of the values are not 0. If Base is 0, the base is implied by
-// the string's prefix: base 16 for "0x", base 8 for "0", and base 10 otherwise.
-func Signed(name rune, value int64, l *SignedLimit, helpvalue ...string) *int64 {
- return CommandLine.Signed(name, value, l, helpvalue...)
-}
-
-func (s *Set) Signed(name rune, value int64, l *SignedLimit, helpvalue ...string) *int64 {
- return s.SignedLong("", name, value, l, helpvalue...)
-}
-
-func SignedLong(name string, short rune, value int64, l *SignedLimit, helpvalue ...string) *int64 {
- return CommandLine.SignedLong(name, short, value, l, helpvalue...)
-}
-
-func (s *Set) SignedLong(name string, short rune, value int64, l *SignedLimit, helpvalue ...string) *int64 {
- s.SignedVarLong(&value, name, short, l, helpvalue...)
- return &value
-}
-
-func SignedVar(p *int64, name rune, l *SignedLimit, helpvalue ...string) Option {
- return CommandLine.SignedVar(p, name, l, helpvalue...)
-}
-
-func (s *Set) SignedVar(p *int64, name rune, l *SignedLimit, helpvalue ...string) Option {
- return s.SignedVarLong(p, "", name, l, helpvalue...)
-}
-
-func SignedVarLong(p *int64, name string, short rune, l *SignedLimit, helpvalue ...string) Option {
- return CommandLine.SignedVarLong(p, name, short, l, helpvalue...)
-}
-
-func (s *Set) SignedVarLong(p *int64, name string, short rune, l *SignedLimit, helpvalue ...string) Option {
- opt := s.VarLong((*signed)(p), name, short, helpvalue...)
- if l.Base > 36 || l.Base == 1 || l.Base < 0 {
- fmt.Fprintf(stderr, "invalid base for %s: %d\n", opt.Name(), l.Base)
- exit(1)
- }
- if l.Bits < 0 || l.Bits > 64 {
- fmt.Fprintf(stderr, "invalid bit size for %s: %d\n", opt.Name(), l.Bits)
- exit(1)
- }
- if l.Min > l.Max {
- fmt.Fprintf(stderr, "min greater than max for %s\n", opt.Name())
- exit(1)
- }
- lim := *l
- signedLimits[(*signed)(p)] = &lim
- return opt
-}
diff --git a/vendor/github.com/pborman/getopt/signed_test.go b/vendor/github.com/pborman/getopt/signed_test.go
deleted file mode 100644
index 2d0635a..0000000
--- a/vendor/github.com/pborman/getopt/signed_test.go
+++ /dev/null
@@ -1,97 +0,0 @@
-// Copyright 2013 Google Inc. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package getopt
-
-import (
- "fmt"
- "strings"
- "testing"
-)
-
-var signedNumberTests = []struct {
- where string
- in []string
- l SignedLimit
- out int64
- err string
-}{
- {
- where: loc(),
- },
- {
- loc(),
- []string{"test", "-n", "1010"},
- SignedLimit{Base: 2, Bits: 5},
- 10,
- "",
- },
- {
- loc(),
- []string{"test", "-n", "1010"},
- SignedLimit{Base: 2, Bits: 4},
- 0,
- "test: value out of range: 1010\n",
- },
- {
- loc(),
- []string{"test", "-n", "-1000"},
- SignedLimit{Base: 2, Bits: 4},
- -8,
- "",
- },
- {
- loc(),
- []string{"test", "-n", "3"},
- SignedLimit{Min: 4, Max: 6},
- 0,
- "test: value out of range (<4): 3\n",
- },
- {
- loc(),
- []string{"test", "-n", "4"},
- SignedLimit{Min: 4, Max: 6},
- 4,
- "",
- },
- {
- loc(),
- []string{"test", "-n", "5"},
- SignedLimit{Min: 4, Max: 6},
- 5,
- "",
- },
- {
- loc(),
- []string{"test", "-n", "6"},
- SignedLimit{Min: 4, Max: 6},
- 6,
- "",
- },
- {
- loc(),
- []string{"test", "-n", "7"},
- SignedLimit{Min: 4, Max: 6},
- 0,
- "test: value out of range (>6): 7\n",
- },
-}
-
-func TestSigneds(t *testing.T) {
- for x, tt := range signedNumberTests {
- if strings.Index(tt.where, ":-") > 0 {
- tt.where = fmt.Sprintf("#%d", x)
- }
-
- reset()
- n := Signed('n', 0, &tt.l)
- parse(tt.in)
- if s := checkError(tt.err); s != "" {
- t.Errorf("%s: %s", tt.where, s)
- }
- if *n != tt.out {
- t.Errorf("%s: got %v, want %v", tt.where, *n, tt.out)
- }
- }
-}
diff --git a/vendor/github.com/pborman/getopt/string.go b/vendor/github.com/pborman/getopt/string.go
deleted file mode 100644
index 1121867..0000000
--- a/vendor/github.com/pborman/getopt/string.go
+++ /dev/null
@@ -1,53 +0,0 @@
-// Copyright 2013 Google Inc. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package getopt
-
-type stringValue string
-
-func (s *stringValue) Set(value string, opt Option) error {
- *s = stringValue(value)
- return nil
-}
-
-func (s *stringValue) String() string {
- return string(*s)
-}
-
-// String returns a value option that stores is value as a string. The
-// initial value of the string is passed in value.
-func String(name rune, value string, helpvalue ...string) *string {
- return CommandLine.String(name, value, helpvalue...)
-}
-
-func (s *Set) String(name rune, value string, helpvalue ...string) *string {
- p := value
- s.StringVarLong(&p, "", name, helpvalue...)
- return &p
-}
-
-func StringLong(name string, short rune, value string, helpvalue ...string) *string {
- return CommandLine.StringLong(name, short, value, helpvalue...)
-}
-
-func (s *Set) StringLong(name string, short rune, value string, helpvalue ...string) *string {
- s.StringVarLong(&value, name, short, helpvalue...)
- return &value
-}
-
-func StringVar(p *string, name rune, helpvalue ...string) Option {
- return CommandLine.StringVar(p, name, helpvalue...)
-}
-
-func (s *Set) StringVar(p *string, name rune, helpvalue ...string) Option {
- return s.VarLong((*stringValue)(p), "", name, helpvalue...)
-}
-
-func StringVarLong(p *string, name string, short rune, helpvalue ...string) Option {
- return CommandLine.StringVarLong(p, name, short, helpvalue...)
-}
-
-func (s *Set) StringVarLong(p *string, name string, short rune, helpvalue ...string) Option {
- return s.VarLong((*stringValue)(p), name, short, helpvalue...)
-}
diff --git a/vendor/github.com/pborman/getopt/string_test.go b/vendor/github.com/pborman/getopt/string_test.go
deleted file mode 100644
index c39a56c..0000000
--- a/vendor/github.com/pborman/getopt/string_test.go
+++ /dev/null
@@ -1,77 +0,0 @@
-// Copyright 2013 Google Inc. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package getopt
-
-import "testing"
-
-var stringTests = []struct {
- where string
- in []string
- sout string
- optout string
- err string
-}{
- {
- loc(),
- []string{},
- "one",
- "two",
- "",
- },
- {
- loc(),
- []string{"test", "-s"},
- "one",
- "two",
- "test: missing parameter for -s\n",
- },
- {
- loc(),
- []string{"test", "--opt"},
- "one",
- "two",
- "test: missing parameter for --opt\n",
- },
- {
- loc(),
- []string{"test", "-svalue", "--opt=option"},
- "value",
- "option",
- "",
- },
- {
- loc(),
- []string{"test", "-s", "value", "--opt", "option"},
- "value",
- "option",
- "",
- },
- {
- loc(),
- []string{"test", "-swrong", "--opt=wrong", "-s", "value", "--opt", "option"},
- "value",
- "option",
- "",
- },
-}
-
-func TestString(t *testing.T) {
- for _, tt := range stringTests {
- reset()
- s := String('s', "one")
- opt := StringLong("opt", 0, "two")
-
- parse(tt.in)
- if s := checkError(tt.err); s != "" {
- t.Errorf("%s: %s", tt.where, s)
- }
- if *s != tt.sout {
- t.Errorf("%s: got s = %q, want %q", tt.where, *s, tt.sout)
- }
- if *opt != tt.optout {
- t.Errorf("%s: got opt = %q, want %q", tt.where, *opt, tt.optout)
- }
- }
-}
diff --git a/vendor/github.com/pborman/getopt/uint.go b/vendor/github.com/pborman/getopt/uint.go
deleted file mode 100644
index bdb82b4..0000000
--- a/vendor/github.com/pborman/getopt/uint.go
+++ /dev/null
@@ -1,67 +0,0 @@
-// Copyright 2013 Google Inc. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package getopt
-
-import (
- "fmt"
- "strconv"
-)
-
-type uintValue uint
-
-func (i *uintValue) Set(value string, opt Option) error {
- v, err := strconv.ParseUint(value, 0, strconv.IntSize)
- if err != nil {
- if e, ok := err.(*strconv.NumError); ok {
- switch e.Err {
- case strconv.ErrRange:
- err = fmt.Errorf("value out of range: %s", value)
- case strconv.ErrSyntax:
- err = fmt.Errorf("not a valid number: %s", value)
- }
- }
- return err
- }
- *i = uintValue(v)
- return nil
-}
-
-func (i *uintValue) String() string {
- return strconv.FormatUint(uint64(*i), 10)
-}
-
-// Uint creates an option that parses its value as an unsigned integer.
-func Uint(name rune, value uint, helpvalue ...string) *uint {
- return CommandLine.Uint(name, value, helpvalue...)
-}
-
-func (s *Set) Uint(name rune, value uint, helpvalue ...string) *uint {
- return s.UintLong("", name, value, helpvalue...)
-}
-
-func UintLong(name string, short rune, value uint, helpvalue ...string) *uint {
- return CommandLine.UintLong(name, short, value, helpvalue...)
-}
-
-func (s *Set) UintLong(name string, short rune, value uint, helpvalue ...string) *uint {
- s.UintVarLong(&value, name, short, helpvalue...)
- return &value
-}
-
-func UintVar(p *uint, name rune, helpvalue ...string) Option {
- return CommandLine.UintVar(p, name, helpvalue...)
-}
-
-func (s *Set) UintVar(p *uint, name rune, helpvalue ...string) Option {
- return s.UintVarLong(p, "", name, helpvalue...)
-}
-
-func UintVarLong(p *uint, name string, short rune, helpvalue ...string) Option {
- return CommandLine.UintVarLong(p, name, short, helpvalue...)
-}
-
-func (s *Set) UintVarLong(p *uint, name string, short rune, helpvalue ...string) Option {
- return s.VarLong((*uintValue)(p), name, short, helpvalue...)
-}
diff --git a/vendor/github.com/pborman/getopt/uint16.go b/vendor/github.com/pborman/getopt/uint16.go
deleted file mode 100644
index 92013e0..0000000
--- a/vendor/github.com/pborman/getopt/uint16.go
+++ /dev/null
@@ -1,67 +0,0 @@
-// Copyright 2013 Google Inc. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package getopt
-
-import (
- "fmt"
- "strconv"
-)
-
-type uint16Value uint16
-
-func (i *uint16Value) Set(value string, opt Option) error {
- v, err := strconv.ParseUint(value, 0, 16)
- if err != nil {
- if e, ok := err.(*strconv.NumError); ok {
- switch e.Err {
- case strconv.ErrRange:
- err = fmt.Errorf("value out of range: %s", value)
- case strconv.ErrSyntax:
- err = fmt.Errorf("not a valid number: %s", value)
- }
- }
- return err
- }
- *i = uint16Value(v)
- return nil
-}
-
-func (i *uint16Value) String() string {
- return strconv.FormatUint(uint64(*i), 10)
-}
-
-// Uint16 creates an option that parses its value as an uint16.
-func Uint16(name rune, value uint16, helpvalue ...string) *uint16 {
- return CommandLine.Uint16(name, value, helpvalue...)
-}
-
-func (s *Set) Uint16(name rune, value uint16, helpvalue ...string) *uint16 {
- return s.Uint16Long("", name, value, helpvalue...)
-}
-
-func Uint16Long(name string, short rune, value uint16, helpvalue ...string) *uint16 {
- return CommandLine.Uint16Long(name, short, value, helpvalue...)
-}
-
-func (s *Set) Uint16Long(name string, short rune, value uint16, helpvalue ...string) *uint16 {
- s.Uint16VarLong(&value, name, short, helpvalue...)
- return &value
-}
-
-func Uint16Var(p *uint16, name rune, helpvalue ...string) Option {
- return CommandLine.Uint16Var(p, name, helpvalue...)
-}
-
-func (s *Set) Uint16Var(p *uint16, name rune, helpvalue ...string) Option {
- return s.Uint16VarLong(p, "", name, helpvalue...)
-}
-
-func Uint16VarLong(p *uint16, name string, short rune, helpvalue ...string) Option {
- return CommandLine.Uint16VarLong(p, name, short, helpvalue...)
-}
-
-func (s *Set) Uint16VarLong(p *uint16, name string, short rune, helpvalue ...string) Option {
- return s.VarLong((*uint16Value)(p), name, short, helpvalue...)
-}
diff --git a/vendor/github.com/pborman/getopt/uint16_test.go b/vendor/github.com/pborman/getopt/uint16_test.go
deleted file mode 100644
index 5363a0c..0000000
--- a/vendor/github.com/pborman/getopt/uint16_test.go
+++ /dev/null
@@ -1,84 +0,0 @@
-// Copyright 2013 Google Inc. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package getopt
-
-import (
- "fmt"
- "strings"
- "testing"
-)
-
-var uint16Tests = []struct {
- where string
- in []string
- i uint16
- uint16 uint16
- err string
-}{
- {
- loc(),
- []string{},
- 17, 42,
- "",
- },
- {
- loc(),
- []string{"test", "-i", "1", "--uint16", "2"},
- 1, 2,
- "",
- },
- {
- loc(),
- []string{"test", "-i1", "--uint16=2"},
- 1, 2,
- "",
- },
- {
- loc(),
- []string{"test", "-i1", "-i2"},
- 2, 42,
- "",
- },
- {
- loc(),
- []string{"test", "-i=1"},
- 17, 42,
- "test: not a valid number: =1\n",
- },
- {
- loc(),
- []string{"test", "-i0x20"},
- 0x20, 42,
- "",
- },
- {
- loc(),
- []string{"test", "-i010"},
- 8, 42,
- "",
- },
-}
-
-func TestUint16(t *testing.T) {
- for x, tt := range uint16Tests {
- reset()
- i := Uint16('i', 17)
- opt := Uint16Long("uint16", 0, 42)
- if strings.Index(tt.where, ":-") > 0 {
- tt.where = fmt.Sprintf("#%d", x)
- }
-
- parse(tt.in)
- if s := checkError(tt.err); s != "" {
- t.Errorf("%s: %s", tt.where, s)
- }
- if got, want := *i, tt.i; got != want {
- t.Errorf("%s: got %v, want %v", tt.where, got, want)
- }
- if got, want := *opt, tt.uint16; got != want {
- t.Errorf("%s: got %v, want %v", tt.where, got, want)
- }
- }
-}
diff --git a/vendor/github.com/pborman/getopt/uint32.go b/vendor/github.com/pborman/getopt/uint32.go
deleted file mode 100644
index abe911d..0000000
--- a/vendor/github.com/pborman/getopt/uint32.go
+++ /dev/null
@@ -1,67 +0,0 @@
-// Copyright 2013 Google Inc. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package getopt
-
-import (
- "fmt"
- "strconv"
-)
-
-type uint32Value uint32
-
-func (i *uint32Value) Set(value string, opt Option) error {
- v, err := strconv.ParseUint(value, 0, 32)
- if err != nil {
- if e, ok := err.(*strconv.NumError); ok {
- switch e.Err {
- case strconv.ErrRange:
- err = fmt.Errorf("value out of range: %s", value)
- case strconv.ErrSyntax:
- err = fmt.Errorf("not a valid number: %s", value)
- }
- }
- return err
- }
- *i = uint32Value(v)
- return nil
-}
-
-func (i *uint32Value) String() string {
- return strconv.FormatUint(uint64(*i), 10)
-}
-
-// Uint32 creates an option that parses its value as an uint32.
-func Uint32(name rune, value uint32, helpvalue ...string) *uint32 {
- return CommandLine.Uint32(name, value, helpvalue...)
-}
-
-func (s *Set) Uint32(name rune, value uint32, helpvalue ...string) *uint32 {
- return s.Uint32Long("", name, value, helpvalue...)
-}
-
-func Uint32Long(name string, short rune, value uint32, helpvalue ...string) *uint32 {
- return CommandLine.Uint32Long(name, short, value, helpvalue...)
-}
-
-func (s *Set) Uint32Long(name string, short rune, value uint32, helpvalue ...string) *uint32 {
- s.Uint32VarLong(&value, name, short, helpvalue...)
- return &value
-}
-
-func Uint32Var(p *uint32, name rune, helpvalue ...string) Option {
- return CommandLine.Uint32Var(p, name, helpvalue...)
-}
-
-func (s *Set) Uint32Var(p *uint32, name rune, helpvalue ...string) Option {
- return s.Uint32VarLong(p, "", name, helpvalue...)
-}
-
-func Uint32VarLong(p *uint32, name string, short rune, helpvalue ...string) Option {
- return CommandLine.Uint32VarLong(p, name, short, helpvalue...)
-}
-
-func (s *Set) Uint32VarLong(p *uint32, name string, short rune, helpvalue ...string) Option {
- return s.VarLong((*uint32Value)(p), name, short, helpvalue...)
-}
diff --git a/vendor/github.com/pborman/getopt/uint32_test.go b/vendor/github.com/pborman/getopt/uint32_test.go
deleted file mode 100644
index 80b4d11..0000000
--- a/vendor/github.com/pborman/getopt/uint32_test.go
+++ /dev/null
@@ -1,84 +0,0 @@
-// Copyright 2013 Google Inc. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package getopt
-
-import (
- "fmt"
- "strings"
- "testing"
-)
-
-var uint32Tests = []struct {
- where string
- in []string
- i uint32
- uint32 uint32
- err string
-}{
- {
- loc(),
- []string{},
- 17, 42,
- "",
- },
- {
- loc(),
- []string{"test", "-i", "1", "--uint32", "2"},
- 1, 2,
- "",
- },
- {
- loc(),
- []string{"test", "-i1", "--uint32=2"},
- 1, 2,
- "",
- },
- {
- loc(),
- []string{"test", "-i1", "-i2"},
- 2, 42,
- "",
- },
- {
- loc(),
- []string{"test", "-i=1"},
- 17, 42,
- "test: not a valid number: =1\n",
- },
- {
- loc(),
- []string{"test", "-i0x20"},
- 0x20, 42,
- "",
- },
- {
- loc(),
- []string{"test", "-i010"},
- 8, 42,
- "",
- },
-}
-
-func TestUint32(t *testing.T) {
- for x, tt := range uint32Tests {
- reset()
- i := Uint32('i', 17)
- opt := Uint32Long("uint32", 0, 42)
- if strings.Index(tt.where, ":-") > 0 {
- tt.where = fmt.Sprintf("#%d", x)
- }
-
- parse(tt.in)
- if s := checkError(tt.err); s != "" {
- t.Errorf("%s: %s", tt.where, s)
- }
- if got, want := *i, tt.i; got != want {
- t.Errorf("%s: got %v, want %v", tt.where, got, want)
- }
- if got, want := *opt, tt.uint32; got != want {
- t.Errorf("%s: got %v, want %v", tt.where, got, want)
- }
- }
-}
diff --git a/vendor/github.com/pborman/getopt/uint64.go b/vendor/github.com/pborman/getopt/uint64.go
deleted file mode 100644
index 788e97f..0000000
--- a/vendor/github.com/pborman/getopt/uint64.go
+++ /dev/null
@@ -1,67 +0,0 @@
-// Copyright 2013 Google Inc. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package getopt
-
-import (
- "fmt"
- "strconv"
-)
-
-type uint64Value uint64
-
-func (i *uint64Value) Set(value string, opt Option) error {
- v, err := strconv.ParseUint(value, 0, 64)
- if err != nil {
- if e, ok := err.(*strconv.NumError); ok {
- switch e.Err {
- case strconv.ErrRange:
- err = fmt.Errorf("value out of range: %s", value)
- case strconv.ErrSyntax:
- err = fmt.Errorf("not a valid number: %s", value)
- }
- }
- return err
- }
- *i = uint64Value(v)
- return nil
-}
-
-func (i *uint64Value) String() string {
- return strconv.FormatUint(uint64(*i), 10)
-}
-
-// Uint64 creates an option that parses its value as a uint64.
-func Uint64(name rune, value uint64, helpvalue ...string) *uint64 {
- return CommandLine.Uint64(name, value, helpvalue...)
-}
-
-func (s *Set) Uint64(name rune, value uint64, helpvalue ...string) *uint64 {
- return s.Uint64Long("", name, value, helpvalue...)
-}
-
-func Uint64Long(name string, short rune, value uint64, helpvalue ...string) *uint64 {
- return CommandLine.Uint64Long(name, short, value, helpvalue...)
-}
-
-func (s *Set) Uint64Long(name string, short rune, value uint64, helpvalue ...string) *uint64 {
- s.Uint64VarLong(&value, name, short, helpvalue...)
- return &value
-}
-
-func Uint64Var(p *uint64, name rune, helpvalue ...string) Option {
- return CommandLine.Uint64Var(p, name, helpvalue...)
-}
-
-func (s *Set) Uint64Var(p *uint64, name rune, helpvalue ...string) Option {
- return s.Uint64VarLong(p, "", name, helpvalue...)
-}
-
-func Uint64VarLong(p *uint64, name string, short rune, helpvalue ...string) Option {
- return CommandLine.Uint64VarLong(p, name, short, helpvalue...)
-}
-
-func (s *Set) Uint64VarLong(p *uint64, name string, short rune, helpvalue ...string) Option {
- return s.VarLong((*uint64Value)(p), name, short, helpvalue...)
-}
diff --git a/vendor/github.com/pborman/getopt/uint64_test.go b/vendor/github.com/pborman/getopt/uint64_test.go
deleted file mode 100644
index 962d369..0000000
--- a/vendor/github.com/pborman/getopt/uint64_test.go
+++ /dev/null
@@ -1,84 +0,0 @@
-// Copyright 2013 Google Inc. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package getopt
-
-import (
- "fmt"
- "strings"
- "testing"
-)
-
-var uint64Tests = []struct {
- where string
- in []string
- i uint64
- uint64 uint64
- err string
-}{
- {
- loc(),
- []string{},
- 17, 42,
- "",
- },
- {
- loc(),
- []string{"test", "-i", "1", "--uint64", "2"},
- 1, 2,
- "",
- },
- {
- loc(),
- []string{"test", "-i1", "--uint64=2"},
- 1, 2,
- "",
- },
- {
- loc(),
- []string{"test", "-i1", "-i2"},
- 2, 42,
- "",
- },
- {
- loc(),
- []string{"test", "-i=1"},
- 17, 42,
- "test: not a valid number: =1\n",
- },
- {
- loc(),
- []string{"test", "-i0x20"},
- 0x20, 42,
- "",
- },
- {
- loc(),
- []string{"test", "-i010"},
- 8, 42,
- "",
- },
-}
-
-func TestUint64(t *testing.T) {
- for x, tt := range uint64Tests {
- reset()
- i := Uint64('i', 17)
- opt := Uint64Long("uint64", 0, 42)
- if strings.Index(tt.where, ":-") > 0 {
- tt.where = fmt.Sprintf("#%d", x)
- }
-
- parse(tt.in)
- if s := checkError(tt.err); s != "" {
- t.Errorf("%s: %s", tt.where, s)
- }
- if got, want := *i, tt.i; got != want {
- t.Errorf("%s: got %v, want %v", tt.where, got, want)
- }
- if got, want := *opt, tt.uint64; got != want {
- t.Errorf("%s: got %v, want %v", tt.where, got, want)
- }
- }
-}
diff --git a/vendor/github.com/pborman/getopt/uint_test.go b/vendor/github.com/pborman/getopt/uint_test.go
deleted file mode 100644
index 48c38cb..0000000
--- a/vendor/github.com/pborman/getopt/uint_test.go
+++ /dev/null
@@ -1,84 +0,0 @@
-// Copyright 2013 Google Inc. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package getopt
-
-import (
- "fmt"
- "strings"
- "testing"
-)
-
-var uintTests = []struct {
- where string
- in []string
- i uint
- uint uint
- err string
-}{
- {
- loc(),
- []string{},
- 17, 42,
- "",
- },
- {
- loc(),
- []string{"test", "-i", "1", "--uint", "2"},
- 1, 2,
- "",
- },
- {
- loc(),
- []string{"test", "-i1", "--uint=2"},
- 1, 2,
- "",
- },
- {
- loc(),
- []string{"test", "-i1", "-i2"},
- 2, 42,
- "",
- },
- {
- loc(),
- []string{"test", "-i=1"},
- 17, 42,
- "test: not a valid number: =1\n",
- },
- {
- loc(),
- []string{"test", "-i0x20"},
- 0x20, 42,
- "",
- },
- {
- loc(),
- []string{"test", "-i010"},
- 8, 42,
- "",
- },
-}
-
-func TestUint(t *testing.T) {
- for x, tt := range uintTests {
- reset()
- i := Uint('i', 17)
- opt := UintLong("uint", 0, 42)
- if strings.Index(tt.where, ":-") > 0 {
- tt.where = fmt.Sprintf("#%d", x)
- }
-
- parse(tt.in)
- if s := checkError(tt.err); s != "" {
- t.Errorf("%s: %s", tt.where, s)
- }
- if got, want := *i, tt.i; got != want {
- t.Errorf("%s: got %v, want %v", tt.where, got, want)
- }
- if got, want := *opt, tt.uint; got != want {
- t.Errorf("%s: got %v, want %v", tt.where, got, want)
- }
- }
-}
diff --git a/vendor/github.com/pborman/getopt/unsigned.go b/vendor/github.com/pborman/getopt/unsigned.go
deleted file mode 100644
index 3ded0e7..0000000
--- a/vendor/github.com/pborman/getopt/unsigned.go
+++ /dev/null
@@ -1,111 +0,0 @@
-// Copyright 2013 Google Inc. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package getopt
-
-import (
- "fmt"
- "strconv"
-)
-
-type unsigned uint64
-
-type UnsignedLimit struct {
- Base int // Base for conversion as per strconv.ParseInt
- Bits int // Number of bits as per strconv.ParseInt
- Min uint64 // Minimum allowed value if both Min and Max are not 0
- Max uint64 // Maximum allowed value if both Min and Max are not 0
-}
-
-var unsignedLimits = make(map[*unsigned]*UnsignedLimit)
-
-func (n *unsigned) Set(value string, opt Option) error {
- l := unsignedLimits[n]
- if l == nil {
- return fmt.Errorf("no limits defined for %s", opt.Name())
- }
- v, err := strconv.ParseUint(value, l.Base, l.Bits)
- if err != nil {
- if e, ok := err.(*strconv.NumError); ok {
- switch e.Err {
- case strconv.ErrRange:
- err = fmt.Errorf("value out of range: %s", value)
- case strconv.ErrSyntax:
- err = fmt.Errorf("not a valid number: %s", value)
- }
- }
- return err
- }
- if l.Min != 0 || l.Max != 0 {
- if v < l.Min {
- return fmt.Errorf("value out of range (<%v): %s", l.Min, value)
- }
- if v > l.Max {
- return fmt.Errorf("value out of range (>%v): %s", l.Max, value)
- }
- }
- *n = unsigned(v)
- return nil
-}
-
-func (n *unsigned) String() string {
- l := unsignedLimits[n]
- if l != nil && l.Base != 0 {
- return strconv.FormatUint(uint64(*n), l.Base)
- }
- return strconv.FormatUint(uint64(*n), 10)
-}
-
-// Unsigned creates an option that is stored in a uint64 and is
-// constrained by the limits pointed to by l. The Max and Min values are only
-// used if at least one of the values are not 0. If Base is 0, the base is
-// implied by the string's prefix: base 16 for "0x", base 8 for "0", and base
-// 10 otherwise.
-func Unsigned(name rune, value uint64, l *UnsignedLimit, helpvalue ...string) *uint64 {
- return CommandLine.Unsigned(name, value, l, helpvalue...)
-}
-
-func (s *Set) Unsigned(name rune, value uint64, l *UnsignedLimit, helpvalue ...string) *uint64 {
- return s.UnsignedLong("", name, value, l, helpvalue...)
-}
-
-func UnsignedLong(name string, short rune, value uint64, l *UnsignedLimit, helpvalue ...string) *uint64 {
- return CommandLine.UnsignedLong(name, short, value, l, helpvalue...)
-}
-
-func (s *Set) UnsignedLong(name string, short rune, value uint64, l *UnsignedLimit, helpvalue ...string) *uint64 {
- s.UnsignedVarLong(&value, name, short, l, helpvalue...)
- return &value
-}
-
-func UnsignedVar(p *uint64, name rune, l *UnsignedLimit, helpvalue ...string) Option {
- return CommandLine.UnsignedVar(p, name, l, helpvalue...)
-}
-
-func (s *Set) UnsignedVar(p *uint64, name rune, l *UnsignedLimit, helpvalue ...string) Option {
- return s.UnsignedVarLong(p, "", name, l, helpvalue...)
-}
-
-func UnsignedVarLong(p *uint64, name string, short rune, l *UnsignedLimit, helpvalue ...string) Option {
- return CommandLine.UnsignedVarLong(p, name, short, l, helpvalue...)
-}
-
-func (s *Set) UnsignedVarLong(p *uint64, name string, short rune, l *UnsignedLimit, helpvalue ...string) Option {
- opt := s.VarLong((*unsigned)(p), name, short, helpvalue...)
- if l.Base > 36 || l.Base == 1 || l.Base < 0 {
- fmt.Fprintf(stderr, "invalid base for %s: %d\n", opt.Name(), l.Base)
- exit(1)
- }
- if l.Bits < 0 || l.Bits > 64 {
- fmt.Fprintf(stderr, "invalid bit size for %s: %d\n", opt.Name(), l.Bits)
- exit(1)
- }
- if l.Min > l.Max {
- fmt.Fprintf(stderr, "min greater than max for %s\n", opt.Name())
- exit(1)
- }
- lim := *l
- unsignedLimits[(*unsigned)(p)] = &lim
- return opt
-}
diff --git a/vendor/github.com/pborman/getopt/unsigned_test.go b/vendor/github.com/pborman/getopt/unsigned_test.go
deleted file mode 100644
index 0fd60d4..0000000
--- a/vendor/github.com/pborman/getopt/unsigned_test.go
+++ /dev/null
@@ -1,97 +0,0 @@
-// Copyright 2013 Google Inc. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package getopt
-
-import (
- "fmt"
- "strings"
- "testing"
-)
-
-var unsignedTests = []struct {
- where string
- in []string
- l UnsignedLimit
- out uint64
- err string
-}{
- {
- where: loc(),
- },
- {
- loc(),
- []string{"test", "-n", "1010"},
- UnsignedLimit{Base: 2, Bits: 5},
- 10,
- "",
- },
- {
- loc(),
- []string{"test", "-n", "1010"},
- UnsignedLimit{Base: 2, Bits: 4},
- 10,
- "",
- },
- {
- loc(),
- []string{"test", "-n", "1010"},
- UnsignedLimit{Base: 2, Bits: 3},
- 0,
- "test: value out of range: 1010\n",
- },
- {
- loc(),
- []string{"test", "-n", "3"},
- UnsignedLimit{Min: 4, Max: 6},
- 0,
- "test: value out of range (<4): 3\n",
- },
- {
- loc(),
- []string{"test", "-n", "4"},
- UnsignedLimit{Min: 4, Max: 6},
- 4,
- "",
- },
- {
- loc(),
- []string{"test", "-n", "5"},
- UnsignedLimit{Min: 4, Max: 6},
- 5,
- "",
- },
- {
- loc(),
- []string{"test", "-n", "6"},
- UnsignedLimit{Min: 4, Max: 6},
- 6,
- "",
- },
- {
- loc(),
- []string{"test", "-n", "7"},
- UnsignedLimit{Min: 4, Max: 6},
- 0,
- "test: value out of range (>6): 7\n",
- },
-}
-
-func TestUnsigneds(t *testing.T) {
- for x, tt := range unsignedTests {
- if strings.Index(tt.where, ":-") > 0 {
- tt.where = fmt.Sprintf("#%d", x)
- }
-
- reset()
- n := Unsigned('n', 0, &tt.l)
- parse(tt.in)
- if s := checkError(tt.err); s != "" {
- t.Errorf("%s: %s", tt.where, s)
- }
- if *n != tt.out {
- t.Errorf("%s: got %v, want %v", tt.where, *n, tt.out)
- }
- }
-}
diff --git a/vendor/github.com/pborman/getopt/util_test.go b/vendor/github.com/pborman/getopt/util_test.go
deleted file mode 100644
index 79a732a..0000000
--- a/vendor/github.com/pborman/getopt/util_test.go
+++ /dev/null
@@ -1,87 +0,0 @@
-// Copyright 2013 Google Inc. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package getopt
-
-import (
- "bytes"
- "fmt"
- "path"
- "reflect"
- "runtime"
- "strings"
-)
-
-var errorString string
-
-func reset() {
- CommandLine.shortOptions = make(map[rune]*option)
- CommandLine.longOptions = make(map[string]*option)
- CommandLine.options = nil
- CommandLine.args = nil
- CommandLine.program = ""
- errorString = ""
-}
-
-func parse(args []string) {
- err := CommandLine.Getopt(args, nil)
- if err != nil {
- b := &bytes.Buffer{}
-
- fmt.Fprintln(b, CommandLine.program+": "+err.Error())
- CommandLine.PrintUsage(b)
- errorString = b.String()
- }
-}
-
-func badSlice(a, b []string) bool {
- if len(a) != len(b) {
- return true
- }
- for x, v := range a {
- if b[x] != v {
- return true
- }
- }
- return false
-}
-
-func loc() string {
- _, file, line, _ := runtime.Caller(1)
- return fmt.Sprintf("%s:%d", path.Base(file), line)
-}
-
-func (o *option) Equal(opt *option) bool {
- if o.value != nil && opt.value == nil {
- return false
- }
- if o.value == nil && opt.value != nil {
- return false
- }
- if o.value != nil && o.value.String() != opt.value.String() {
- return false
- }
-
- oc := *o
- optc := *opt
- oc.value = nil
- optc.value = nil
- return reflect.DeepEqual(&oc, &optc)
-}
-
-func newStringValue(s string) *stringValue { return (*stringValue)(&s) }
-
-func checkError(err string) string {
- switch {
- case err == errorString:
- return ""
- case err == "":
- return fmt.Sprintf("unexpected error %q", errorString)
- case errorString == "":
- return fmt.Sprintf("did not get expected error %q", err)
- case !strings.HasPrefix(errorString, err):
- return fmt.Sprintf("got error %q, want %q", errorString, err)
- }
- return ""
-}
diff --git a/vendor/github.com/pborman/getopt/v2/bool_test.go b/vendor/github.com/pborman/getopt/v2/bool_test.go
deleted file mode 100644
index 0a90d96..0000000
--- a/vendor/github.com/pborman/getopt/v2/bool_test.go
+++ /dev/null
@@ -1,106 +0,0 @@
-// Copyright 2017 Google Inc. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package getopt
-
-import (
- "fmt"
- "strings"
- "testing"
-)
-
-var boolTests = []struct {
- where string
- in []string
- f bool
- fc int
- opt bool
- optc int
- err string
-}{
- {
- loc(),
- []string{},
- false, 0,
- false, 0,
- "",
- },
- {
- loc(),
- []string{"test", "-f", "--opt"},
- true, 1,
- true, 1,
- "",
- },
- {
- loc(),
- []string{"test", "--f", "--opt"},
- true, 1,
- true, 1,
- "",
- },
- {
- loc(),
- []string{"test", "-ff", "-f", "--opt", "--opt"},
- true, 3,
- true, 2,
- "",
- },
- {
- loc(),
- []string{"test", "--opt", "--opt=false"},
- false, 0,
- false, 2,
- "",
- },
- {
- loc(),
- []string{"test", "-f", "false"},
- true, 1,
- false, 0,
- "",
- },
- {
- loc(),
- []string{"test", "-f=false"},
- true, 1,
- false, 0,
- "test: unknown option: -=\n",
- },
- {
- loc(),
- []string{"test", "-f", "false"},
- true, 1,
- false, 0,
- "",
- },
-}
-
-func TestBool(t *testing.T) {
- for x, tt := range boolTests {
- reset()
- f := Bool('f')
- opt := BoolLong("opt", 0)
- if strings.Index(tt.where, ":-") > 0 {
- tt.where = fmt.Sprintf("#%d", x)
- }
-
- parse(tt.in)
- if s := checkError(tt.err); s != "" {
- t.Errorf("%s: %s", tt.where, s)
- }
- if got, want := *f, tt.f; got != want {
- t.Errorf("%s: got %v, want %v", tt.where, got, want)
- }
- if got, want := *opt, tt.opt; got != want {
- t.Errorf("%s: got %v, want %v", tt.where, got, want)
- }
- if got, want := GetCount('f'), tt.fc; got != want {
- t.Errorf("%s: got %v, want %v", tt.where, got, want)
- }
- if got, want := GetCount("opt"), tt.optc; got != want {
- t.Errorf("%s: got %v, want %v", tt.where, got, want)
- }
- }
-}
diff --git a/vendor/github.com/pborman/getopt/v2/breakup_test.go b/vendor/github.com/pborman/getopt/v2/breakup_test.go
deleted file mode 100644
index 5609e50..0000000
--- a/vendor/github.com/pborman/getopt/v2/breakup_test.go
+++ /dev/null
@@ -1,34 +0,0 @@
-// Copyright 2017 Google Inc. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package getopt
-
-import (
- "testing"
-)
-
-var breakupTests = []struct {
- in string
- max int
- out []string
-}{
- {"", 8, []string{}},
- {"a fox", 8, []string{"a fox"}},
- {"a foxhound is sly", 2, []string{"a", "foxhound", "is", "sly"}},
- {"a foxhound is sly", 5, []string{"a", "foxhound", "is", "sly"}},
- {"a foxhound is sly", 6, []string{"a", "foxhound", "is sly"}},
- {"a foxhound is sly", 7, []string{"a", "foxhound", "is sly"}},
- {"a foxhound is sly", 8, []string{"a", "foxhound", "is sly"}},
- {"a foxhound is sly", 9, []string{"a", "foxhound", "is sly"}},
- {"a foxhound is sly", 10, []string{"a foxhound", "is sly"}},
-}
-
-func TestBreakup(t *testing.T) {
- for x, tt := range breakupTests {
- out := breakup(tt.in, tt.max)
- if badSlice(out, tt.out) {
- t.Errorf("#%d: got %v, want %v", x, out, tt.out)
- }
- }
-}
diff --git a/vendor/github.com/pborman/getopt/v2/counter_test.go b/vendor/github.com/pborman/getopt/v2/counter_test.go
deleted file mode 100644
index b85a26d..0000000
--- a/vendor/github.com/pborman/getopt/v2/counter_test.go
+++ /dev/null
@@ -1,76 +0,0 @@
-// Copyright 2017 Google Inc. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package getopt
-
-import (
- "fmt"
- "strings"
- "testing"
-)
-
-var counterTests = []struct {
- where string
- in []string
- c int
- cnt int
- err string
-}{
- {
- loc(),
- []string{},
- 0,
- 0,
- "",
- },
- {
- loc(),
- []string{"test", "-c", "--cnt"},
- 1,
- 1,
- "",
- },
- {
- loc(),
- []string{"test", "-cc", "-c", "--cnt", "--cnt"},
- 3,
- 2,
- "",
- },
- {
- loc(),
- []string{"test", "--c=17", "--cnt=42"},
- 17,
- 42,
- "",
- },
- {
- loc(),
- []string{"test", "--cnt=false"},
- 0, 0,
- "test: not a valid number: false\n",
- },
-}
-
-func TestCounter(t *testing.T) {
- for x, tt := range counterTests {
- reset()
- c := Counter('c')
- cnt := CounterLong("cnt", 0)
- if strings.Index(tt.where, ":-") > 0 {
- tt.where = fmt.Sprintf("#%d", x)
- }
-
- parse(tt.in)
- if s := checkError(tt.err); s != "" {
- t.Errorf("%s: %s", tt.where, s)
- }
- if got, want := *c, tt.c; got != want {
- t.Errorf("%s: got %v, want %v", tt.where, got, want)
- }
- if got, want := *cnt, tt.cnt; got != want {
- t.Errorf("%s: got %v, want %v", tt.where, got, want)
- }
- }
-}
diff --git a/vendor/github.com/pborman/getopt/v2/duration_test.go b/vendor/github.com/pborman/getopt/v2/duration_test.go
deleted file mode 100644
index ffee177..0000000
--- a/vendor/github.com/pborman/getopt/v2/duration_test.go
+++ /dev/null
@@ -1,73 +0,0 @@
-// Copyright 2017 Google Inc. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package getopt
-
-import (
- "fmt"
- "strings"
- "testing"
- "time"
-)
-
-var durationTests = []struct {
- where string
- in []string
- d time.Duration
- dur time.Duration
- err string
-}{
- {
- loc(),
- []string{},
- 17, 42,
- "",
- },
- {
- loc(),
- []string{"test", "-d", "1s", "--duration", "2s"},
- time.Second, 2 * time.Second,
- "",
- },
- {
- loc(),
- []string{"test", "-d1s", "-d2s"},
- 2 * time.Second, 42,
- "",
- },
- {
- loc(),
- []string{"test", "-d1"},
- 17, 42,
- "test: time: missing unit in duration 1\n",
- },
- {
- loc(),
- []string{"test", "--duration", "foo"},
- 17, 42,
- "test: time: invalid duration foo\n",
- },
-}
-
-func TestDuration(t *testing.T) {
- for x, tt := range durationTests {
- reset()
- d := Duration('d', 17)
- opt := DurationLong("duration", 0, 42)
- if strings.Index(tt.where, ":-") > 0 {
- tt.where = fmt.Sprintf("#%d", x)
- }
-
- parse(tt.in)
- if s := checkError(tt.err); s != "" {
- t.Errorf("%s: %s", tt.where, s)
- }
- if got, want := *d, tt.d; got != want {
- t.Errorf("%s: got %v, want %v", tt.where, got, want)
- }
- if got, want := *opt, tt.dur; got != want {
- t.Errorf("%s: got %v, want %v", tt.where, got, want)
- }
- }
-}
diff --git a/vendor/github.com/pborman/getopt/v2/enum_test.go b/vendor/github.com/pborman/getopt/v2/enum_test.go
deleted file mode 100644
index c854015..0000000
--- a/vendor/github.com/pborman/getopt/v2/enum_test.go
+++ /dev/null
@@ -1,79 +0,0 @@
-// Copyright 2017 Google Inc. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package getopt
-
-import (
- "fmt"
- "strings"
- "testing"
-)
-
-var enumTests = []struct {
- where string
- in []string
- values []string
- def string
- out string
- err string
-}{
- {
- loc(),
- nil,
- []string{},
- "",
- "",
- "",
- },
- {
- loc(),
- []string{"test", "-e", "val1"},
- []string{"val1", "val2"},
- "",
- "val1",
- "",
- },
- {
- loc(),
- []string{"test", "-e", "val1", "-e", "val2"},
- []string{"val1", "val2"},
- "",
- "val2",
- "",
- },
- {
- loc(),
- []string{"test"},
- []string{"val1", "val2"},
- "val2",
- "val2",
- "",
- },
- {
- loc(),
- []string{"test", "-e", "val3"},
- []string{"val1", "val2"},
- "",
- "",
- "test: invalid value: val3\n",
- },
-}
-
-func TestEnum(t *testing.T) {
- for x, tt := range enumTests {
- if strings.Index(tt.where, ":-") > 0 {
- tt.where = fmt.Sprintf("#%d", x)
- }
-
- reset()
- e := Enum('e', tt.values, tt.def)
- parse(tt.in)
- if s := checkError(tt.err); s != "" {
- t.Errorf("%s: %s", tt.where, s)
- }
- if *e != tt.out {
- t.Errorf("%s: got %v, want %v", tt.where, *e, tt.out)
- }
- }
-}
diff --git a/vendor/github.com/pborman/getopt/v2/generic_test.go b/vendor/github.com/pborman/getopt/v2/generic_test.go
deleted file mode 100644
index 9a247ec..0000000
--- a/vendor/github.com/pborman/getopt/v2/generic_test.go
+++ /dev/null
@@ -1,319 +0,0 @@
-// Copyright 2017 Google Inc. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package getopt
-
-import (
- "bytes"
- "fmt"
- "os"
- "reflect"
- "runtime"
- "strings"
- "testing"
- "time"
-)
-
-func TestGeneric(t *testing.T) {
- const (
- shortTest = iota
- longTest
- bothTest
- )
- for _, tt := range []struct {
- where string
- kind int
- val interface{}
- str string
- def interface{}
- in []string
- err string
- }{
- // Do all four tests for string, the rest can mostly just use
- // shortTest (the 0 value).
- {
- where: loc(),
- kind: shortTest,
- val: "42",
- str: "42",
- in: []string{"test", "-s", "42"},
- },
- {
- where: loc(),
- kind: longTest,
- val: "42",
- str: "42",
- in: []string{"test", "--long", "42"},
- },
- {
- where: loc(),
- kind: bothTest,
- val: "42",
- str: "42",
- in: []string{"test", "--both", "42"},
- },
- {
- where: loc(),
- kind: bothTest,
- val: "42",
- str: "42",
- in: []string{"test", "-b", "42"},
- },
- {
- where: loc(),
- val: "42",
- def: "42",
- str: "42",
- in: []string{"test"},
- },
- {
- where: loc(),
- val: "42",
- def: "43",
- str: "42",
- in: []string{"test", "-s", "42"},
- },
-
- {
- where: loc(),
- val: true,
- str: "true",
- in: []string{"test", "-s"},
- },
- {
- where: loc(),
- val: true,
- def: true,
- str: "true",
- in: []string{"test"},
- },
- {
- where: loc(),
- kind: longTest,
- val: false,
- str: "false",
- in: []string{"test", "--long=false"},
- },
- {
- where: loc(),
- kind: longTest,
- val: false,
- def: true,
- str: "false",
- in: []string{"test", "--long=false"},
- },
-
- {
- where: loc(),
- val: int(42),
- str: "42",
- in: []string{"test", "-s", "42"},
- },
- {
- where: loc(),
- val: int8(42),
- str: "42",
- in: []string{"test", "-s", "42"},
- },
- {
- where: loc(),
- val: int16(42),
- str: "42",
- in: []string{"test", "-s", "42"},
- },
- {
- where: loc(),
- val: int32(42),
- str: "42",
- in: []string{"test", "-s", "42"},
- },
- {
- where: loc(),
- val: int64(42),
- str: "42",
- in: []string{"test", "-s", "42"},
- },
-
- {
- where: loc(),
- val: uint(42),
- str: "42",
- in: []string{"test", "-s", "42"},
- },
- {
- where: loc(),
- val: uint8(42),
- str: "42",
- in: []string{"test", "-s", "42"},
- },
- {
- where: loc(),
- val: uint16(42),
- str: "42",
- in: []string{"test", "-s", "42"},
- },
- {
- where: loc(),
- val: uint32(42),
- str: "42",
- in: []string{"test", "-s", "42"},
- },
- {
- where: loc(),
- val: uint64(42),
- str: "42",
- in: []string{"test", "-s", "42"},
- },
-
- {
- where: loc(),
- val: float32(4.2),
- str: "4.2",
- in: []string{"test", "-s", "4.2"},
- },
- {
- where: loc(),
- val: float64(4.2),
- str: "4.2",
- in: []string{"test", "-s", "4.2"},
- },
-
- {
- where: loc(),
- val: time.Duration(time.Second * 42),
- def: time.Second * 2,
- str: "42s",
- in: []string{"test", "-s", "42s"},
- },
- {
- where: loc(),
- val: time.Duration(time.Second * 42),
- def: time.Second * 2,
- str: "42s",
- in: []string{"test", "-s42s"},
- },
- {
- where: loc(),
- val: time.Duration(time.Second * 2),
- def: time.Second * 2,
- in: []string{"test", "-s42"},
- str: "2s",
- err: "test: time: missing unit in duration 42",
- },
-
- {
- where: loc(),
- val: []string{"42", "."},
- str: "42,.",
- def: []string{"one", "two", "three"},
- in: []string{"test", "-s42", "-s."},
- },
- {
- where: loc(),
- val: []string{"42", "."},
- str: "42,.",
- def: []string{"one", "two", "three"},
- in: []string{"test", "-s42,."},
- },
- {
- where: loc(),
- val: []string{"one", "two", "three"},
- def: []string{"one", "two", "three"},
- str: "one,two,three",
- in: []string{"test"},
- },
- } {
- reset()
- var opt Option
- val := reflect.New(reflect.TypeOf(tt.val)).Interface()
- if tt.def != nil {
- reflect.ValueOf(val).Elem().Set(reflect.ValueOf(tt.def))
- }
- switch tt.kind {
- case shortTest:
- opt = Flag(val, 's')
- case longTest:
- opt = FlagLong(val, "long", 0)
- case bothTest:
- opt = FlagLong(val, "both", 'b')
- }
- _ = opt
- parse(tt.in)
- if s := checkError(tt.err); s != "" {
- t.Errorf("%s: %s", tt.where, s)
- continue
- }
- got := reflect.ValueOf(val).Elem().Interface()
- want := reflect.ValueOf(tt.val).Interface()
- if !reflect.DeepEqual(got, want) {
- t.Errorf("%s: got %v, want %v", tt.where, got, want)
- }
- if str := opt.String(); str != tt.str {
- t.Errorf("%s: got string %q, want %q", tt.where, str, tt.str)
- }
- }
-}
-
-func TestGenericDup(t *testing.T) {
- defer func() {
- stderr = os.Stderr
- exit = os.Exit
- }()
-
- reset()
- var v1, v2 string
- type myPanic struct{}
- var errbuf bytes.Buffer
- stderr = &errbuf
- _, file, line, _ := runtime.Caller(0)
- Flag(&v1, 's')
- line++ // line is now the line number of the first call to Flag.
-
- exit = func(i int) { panic(myPanic{}) }
- defer func() {
- p := recover()
- if _, ok := p.(myPanic); ok {
- err := errbuf.String()
- if !strings.Contains(err, "-s already declared") || !strings.Contains(err, fmt.Sprintf("%s:%d", file, line)) {
- t.Errorf("unexpected error: %q\nshould contain \"-s already declared\" and \"%s:%d\"", err, file, line)
- }
- } else if p == nil {
- t.Errorf("Second call to Flag did not fail")
- } else {
- t.Errorf("panic %v", p)
- }
- }()
- Flag(&v2, 's')
-}
-
-func TestGenericDupNested(t *testing.T) {
- defer func() {
- stderr = os.Stderr
- exit = os.Exit
- }()
-
- reset()
- type myPanic struct{}
- var errbuf bytes.Buffer
- stderr = &errbuf
- _, file, line, _ := runtime.Caller(0)
- String('s', "default")
- line++ // line is now the line number of the first call to Flag.
-
- exit = func(i int) { panic(myPanic{}) }
- defer func() {
- p := recover()
- if _, ok := p.(myPanic); ok {
- err := errbuf.String()
- if !strings.Contains(err, "-s already declared") || !strings.Contains(err, fmt.Sprintf("%s:%d", file, line)) {
- t.Errorf("unexpected error: %q\nshould contain \"-s already declared\" and \"%s:%d\"", err, file, line)
- }
- } else if p == nil {
- t.Errorf("Second call to Flag did not fail")
- } else {
- t.Errorf("panic %v", p)
- }
- }()
- String('s', "default")
-}
diff --git a/vendor/github.com/pborman/getopt/v2/int_test.go b/vendor/github.com/pborman/getopt/v2/int_test.go
deleted file mode 100644
index 57175fd..0000000
--- a/vendor/github.com/pborman/getopt/v2/int_test.go
+++ /dev/null
@@ -1,595 +0,0 @@
-// Copyright 2017 Google Inc. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package getopt
-
-import (
- "fmt"
- "strings"
- "testing"
-)
-
-var intTests = []struct {
- where string
- in []string
- i int
- int int
- err string
-}{
- {
- loc(),
- []string{},
- 17, 42,
- "",
- },
- {
- loc(),
- []string{"test", "-i", "1", "--int", "2"},
- 1, 2,
- "",
- },
- {
- loc(),
- []string{"test", "-i1", "--int=2"},
- 1, 2,
- "",
- },
- {
- loc(),
- []string{"test", "-i1", "-i2"},
- 2, 42,
- "",
- },
- {
- loc(),
- []string{"test", "-i=1"},
- 17, 42,
- "test: not a valid number: =1\n",
- },
- {
- loc(),
- []string{"test", "-i0x20"},
- 0x20, 42,
- "",
- },
- {
- loc(),
- []string{"test", "-i010"},
- 8, 42,
- "",
- },
-}
-
-func TestInt(t *testing.T) {
- for x, tt := range intTests {
- reset()
- i := Int('i', 17)
- opt := IntLong("int", 0, 42)
- if strings.Index(tt.where, ":-") > 0 {
- tt.where = fmt.Sprintf("#%d", x)
- }
-
- parse(tt.in)
- if s := checkError(tt.err); s != "" {
- t.Errorf("%s: %s", tt.where, s)
- }
- if got, want := *i, tt.i; got != want {
- t.Errorf("%s: got %v, want %v", tt.where, got, want)
- }
- if got, want := *opt, tt.int; got != want {
- t.Errorf("%s: got %v, want %v", tt.where, got, want)
- }
- }
-}
-
-var int16Tests = []struct {
- where string
- in []string
- i int16
- int16 int16
- err string
-}{
- {
- loc(),
- []string{},
- 17, 42,
- "",
- },
- {
- loc(),
- []string{"test", "-i", "1", "--int16", "2"},
- 1, 2,
- "",
- },
- {
- loc(),
- []string{"test", "-i1", "--int16=2"},
- 1, 2,
- "",
- },
- {
- loc(),
- []string{"test", "-i1", "-i2"},
- 2, 42,
- "",
- },
- {
- loc(),
- []string{"test", "-i=1"},
- 17, 42,
- "test: not a valid number: =1\n",
- },
- {
- loc(),
- []string{"test", "-i0x20"},
- 0x20, 42,
- "",
- },
- {
- loc(),
- []string{"test", "-i010"},
- 8, 42,
- "",
- },
-}
-
-func TestInt16(t *testing.T) {
- for x, tt := range int16Tests {
- reset()
- i := Int16('i', 17)
- opt := Int16Long("int16", 0, 42)
- if strings.Index(tt.where, ":-") > 0 {
- tt.where = fmt.Sprintf("#%d", x)
- }
-
- parse(tt.in)
- if s := checkError(tt.err); s != "" {
- t.Errorf("%s: %s", tt.where, s)
- }
- if got, want := *i, tt.i; got != want {
- t.Errorf("%s: got %v, want %v", tt.where, got, want)
- }
- if got, want := *opt, tt.int16; got != want {
- t.Errorf("%s: got %v, want %v", tt.where, got, want)
- }
- }
-}
-
-var int32Tests = []struct {
- where string
- in []string
- i int32
- int32 int32
- err string
-}{
- {
- loc(),
- []string{},
- 17, 42,
- "",
- },
- {
- loc(),
- []string{"test", "-i", "1", "--int32", "2"},
- 1, 2,
- "",
- },
- {
- loc(),
- []string{"test", "-i1", "--int32=2"},
- 1, 2,
- "",
- },
- {
- loc(),
- []string{"test", "-i1", "-i2"},
- 2, 42,
- "",
- },
- {
- loc(),
- []string{"test", "-i=1"},
- 17, 42,
- "test: not a valid number: =1\n",
- },
- {
- loc(),
- []string{"test", "-i0x20"},
- 0x20, 42,
- "",
- },
- {
- loc(),
- []string{"test", "-i010"},
- 8, 42,
- "",
- },
-}
-
-func TestInt32(t *testing.T) {
- for x, tt := range int32Tests {
- reset()
- i := Int32('i', 17)
- opt := Int32Long("int32", 0, 42)
- if strings.Index(tt.where, ":-") > 0 {
- tt.where = fmt.Sprintf("#%d", x)
- }
-
- parse(tt.in)
- if s := checkError(tt.err); s != "" {
- t.Errorf("%s: %s", tt.where, s)
- }
- if got, want := *i, tt.i; got != want {
- t.Errorf("%s: got %v, want %v", tt.where, got, want)
- }
- if got, want := *opt, tt.int32; got != want {
- t.Errorf("%s: got %v, want %v", tt.where, got, want)
- }
- }
-}
-
-var int64Tests = []struct {
- where string
- in []string
- i int64
- int64 int64
- err string
-}{
- {
- loc(),
- []string{},
- 17, 42,
- "",
- },
- {
- loc(),
- []string{"test", "-i", "1", "--int64", "2"},
- 1, 2,
- "",
- },
- {
- loc(),
- []string{"test", "-i1", "--int64=2"},
- 1, 2,
- "",
- },
- {
- loc(),
- []string{"test", "-i1", "-i2"},
- 2, 42,
- "",
- },
- {
- loc(),
- []string{"test", "-i=1"},
- 17, 42,
- "test: not a valid number: =1\n",
- },
- {
- loc(),
- []string{"test", "-i0x20"},
- 0x20, 42,
- "",
- },
- {
- loc(),
- []string{"test", "-i010"},
- 8, 42,
- "",
- },
-}
-
-func TestInt64(t *testing.T) {
- for x, tt := range int64Tests {
- reset()
- i := Int64('i', 17)
- opt := Int64Long("int64", 0, 42)
- if strings.Index(tt.where, ":-") > 0 {
- tt.where = fmt.Sprintf("#%d", x)
- }
-
- parse(tt.in)
- if s := checkError(tt.err); s != "" {
- t.Errorf("%s: %s", tt.where, s)
- }
- if got, want := *i, tt.i; got != want {
- t.Errorf("%s: got %v, want %v", tt.where, got, want)
- }
- if got, want := *opt, tt.int64; got != want {
- t.Errorf("%s: got %v, want %v", tt.where, got, want)
- }
- }
-}
-
-var uintTests = []struct {
- where string
- in []string
- i uint
- uint uint
- err string
-}{
- {
- loc(),
- []string{},
- 17, 42,
- "",
- },
- {
- loc(),
- []string{"test", "-i", "1", "--uint", "2"},
- 1, 2,
- "",
- },
- {
- loc(),
- []string{"test", "-i1", "--uint=2"},
- 1, 2,
- "",
- },
- {
- loc(),
- []string{"test", "-i1", "-i2"},
- 2, 42,
- "",
- },
- {
- loc(),
- []string{"test", "-i=1"},
- 17, 42,
- "test: not a valid number: =1\n",
- },
- {
- loc(),
- []string{"test", "-i0x20"},
- 0x20, 42,
- "",
- },
- {
- loc(),
- []string{"test", "-i010"},
- 8, 42,
- "",
- },
-}
-
-func TestUint(t *testing.T) {
- for x, tt := range uintTests {
- reset()
- i := Uint('i', 17)
- opt := UintLong("uint", 0, 42)
- if strings.Index(tt.where, ":-") > 0 {
- tt.where = fmt.Sprintf("#%d", x)
- }
-
- parse(tt.in)
- if s := checkError(tt.err); s != "" {
- t.Errorf("%s: %s", tt.where, s)
- }
- if got, want := *i, tt.i; got != want {
- t.Errorf("%s: got %v, want %v", tt.where, got, want)
- }
- if got, want := *opt, tt.uint; got != want {
- t.Errorf("%s: got %v, want %v", tt.where, got, want)
- }
- }
-}
-
-var uint16Tests = []struct {
- where string
- in []string
- i uint16
- uint16 uint16
- err string
-}{
- {
- loc(),
- []string{},
- 17, 42,
- "",
- },
- {
- loc(),
- []string{"test", "-i", "1", "--uint16", "2"},
- 1, 2,
- "",
- },
- {
- loc(),
- []string{"test", "-i1", "--uint16=2"},
- 1, 2,
- "",
- },
- {
- loc(),
- []string{"test", "-i1", "-i2"},
- 2, 42,
- "",
- },
- {
- loc(),
- []string{"test", "-i=1"},
- 17, 42,
- "test: not a valid number: =1\n",
- },
- {
- loc(),
- []string{"test", "-i0x20"},
- 0x20, 42,
- "",
- },
- {
- loc(),
- []string{"test", "-i010"},
- 8, 42,
- "",
- },
-}
-
-func TestUint16(t *testing.T) {
- for x, tt := range uint16Tests {
- reset()
- i := Uint16('i', 17)
- opt := Uint16Long("uint16", 0, 42)
- if strings.Index(tt.where, ":-") > 0 {
- tt.where = fmt.Sprintf("#%d", x)
- }
-
- parse(tt.in)
- if s := checkError(tt.err); s != "" {
- t.Errorf("%s: %s", tt.where, s)
- }
- if got, want := *i, tt.i; got != want {
- t.Errorf("%s: got %v, want %v", tt.where, got, want)
- }
- if got, want := *opt, tt.uint16; got != want {
- t.Errorf("%s: got %v, want %v", tt.where, got, want)
- }
- }
-}
-
-var uint32Tests = []struct {
- where string
- in []string
- i uint32
- uint32 uint32
- err string
-}{
- {
- loc(),
- []string{},
- 17, 42,
- "",
- },
- {
- loc(),
- []string{"test", "-i", "1", "--uint32", "2"},
- 1, 2,
- "",
- },
- {
- loc(),
- []string{"test", "-i1", "--uint32=2"},
- 1, 2,
- "",
- },
- {
- loc(),
- []string{"test", "-i1", "-i2"},
- 2, 42,
- "",
- },
- {
- loc(),
- []string{"test", "-i=1"},
- 17, 42,
- "test: not a valid number: =1\n",
- },
- {
- loc(),
- []string{"test", "-i0x20"},
- 0x20, 42,
- "",
- },
- {
- loc(),
- []string{"test", "-i010"},
- 8, 42,
- "",
- },
-}
-
-func TestUint32(t *testing.T) {
- for x, tt := range uint32Tests {
- reset()
- i := Uint32('i', 17)
- opt := Uint32Long("uint32", 0, 42)
- if strings.Index(tt.where, ":-") > 0 {
- tt.where = fmt.Sprintf("#%d", x)
- }
-
- parse(tt.in)
- if s := checkError(tt.err); s != "" {
- t.Errorf("%s: %s", tt.where, s)
- }
- if got, want := *i, tt.i; got != want {
- t.Errorf("%s: got %v, want %v", tt.where, got, want)
- }
- if got, want := *opt, tt.uint32; got != want {
- t.Errorf("%s: got %v, want %v", tt.where, got, want)
- }
- }
-}
-
-var uint64Tests = []struct {
- where string
- in []string
- i uint64
- uint64 uint64
- err string
-}{
- {
- loc(),
- []string{},
- 17, 42,
- "",
- },
- {
- loc(),
- []string{"test", "-i", "1", "--uint64", "2"},
- 1, 2,
- "",
- },
- {
- loc(),
- []string{"test", "-i1", "--uint64=2"},
- 1, 2,
- "",
- },
- {
- loc(),
- []string{"test", "-i1", "-i2"},
- 2, 42,
- "",
- },
- {
- loc(),
- []string{"test", "-i=1"},
- 17, 42,
- "test: not a valid number: =1\n",
- },
- {
- loc(),
- []string{"test", "-i0x20"},
- 0x20, 42,
- "",
- },
- {
- loc(),
- []string{"test", "-i010"},
- 8, 42,
- "",
- },
-}
-
-func TestUint64(t *testing.T) {
- for x, tt := range uint64Tests {
- reset()
- i := Uint64('i', 17)
- opt := Uint64Long("uint64", 0, 42)
- if strings.Index(tt.where, ":-") > 0 {
- tt.where = fmt.Sprintf("#%d", x)
- }
-
- parse(tt.in)
- if s := checkError(tt.err); s != "" {
- t.Errorf("%s: %s", tt.where, s)
- }
- if got, want := *i, tt.i; got != want {
- t.Errorf("%s: got %v, want %v", tt.where, got, want)
- }
- if got, want := *opt, tt.uint64; got != want {
- t.Errorf("%s: got %v, want %v", tt.where, got, want)
- }
- }
-}
diff --git a/vendor/github.com/pborman/getopt/v2/list_test.go b/vendor/github.com/pborman/getopt/v2/list_test.go
deleted file mode 100644
index e8c8d18..0000000
--- a/vendor/github.com/pborman/getopt/v2/list_test.go
+++ /dev/null
@@ -1,99 +0,0 @@
-// Copyright 2017 Google Inc. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package getopt
-
-import "testing"
-
-var listTests = []struct {
- where string
- in []string
- l, list []string
- err string
-}{
- {
- loc(),
- []string{},
- nil, nil,
- "",
- },
- {
- loc(),
- []string{"test", "-l", "one"},
- []string{"one"}, nil,
- "",
- },
- {
- loc(),
- []string{"test", "-lone", "-ltwo"},
- []string{"one", "two"}, nil,
- "",
- },
- {
- loc(),
- []string{"test", "--list", "one"},
- nil, []string{"one"},
- "",
- },
- {
- loc(),
- []string{"test", "--list=one", "--list=two"},
- nil, []string{"one", "two"},
- "",
- },
- {
- loc(),
- []string{"test", "--list=one,two"},
- nil, []string{"one", "two"},
- "",
- },
-}
-
-func TestList(t *testing.T) {
- for _, tt := range listTests {
- reset()
- l := List('l')
- list := ListLong("list", 0)
-
- parse(tt.in)
- if s := checkError(tt.err); s != "" {
- t.Errorf("%s: %s", tt.where, s)
- }
- if badSlice(*l, tt.l) {
- t.Errorf("%s: got s = %q, want %q", tt.where, *l, tt.l)
- }
- if badSlice(*list, tt.list) {
- t.Errorf("%s: got s = %q, want %q", tt.where, *list, tt.list)
- }
- }
-}
-
-func TestDefaultList(t *testing.T) {
- reset()
- list := []string{"d1", "d2", "d3"}
- Flag(&list, 'l')
- parse([]string{"test"})
-
- want := []string{"d1", "d2", "d3"}
- if badSlice(list, want) {
- t.Errorf("got s = %q, want %q", list, want)
- }
-
- parse([]string{"test", "-l", "one"})
- want = []string{"one"}
- if badSlice(list, want) {
- t.Errorf("got s = %q, want %q", list, want)
- }
-
- parse([]string{"test", "-l", "two"})
- want = []string{"one", "two"}
- if badSlice(list, want) {
- t.Errorf("got s = %q, want %q", list, want)
- }
- Lookup('l').Reset()
- want = []string{"d1", "d2", "d3"}
- if badSlice(list, want) {
- t.Errorf("got s = %q, want %q", list, want)
- }
-}
diff --git a/vendor/github.com/pborman/getopt/v2/signed_test.go b/vendor/github.com/pborman/getopt/v2/signed_test.go
deleted file mode 100644
index 768a06d..0000000
--- a/vendor/github.com/pborman/getopt/v2/signed_test.go
+++ /dev/null
@@ -1,97 +0,0 @@
-// Copyright 2017 Google Inc. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package getopt
-
-import (
- "fmt"
- "strings"
- "testing"
-)
-
-var signedNumberTests = []struct {
- where string
- in []string
- l SignedLimit
- out int64
- err string
-}{
- {
- where: loc(),
- },
- {
- loc(),
- []string{"test", "-n", "1010"},
- SignedLimit{Base: 2, Bits: 5},
- 10,
- "",
- },
- {
- loc(),
- []string{"test", "-n", "1010"},
- SignedLimit{Base: 2, Bits: 4},
- 0,
- "test: value out of range: 1010\n",
- },
- {
- loc(),
- []string{"test", "-n", "-1000"},
- SignedLimit{Base: 2, Bits: 4},
- -8,
- "",
- },
- {
- loc(),
- []string{"test", "-n", "3"},
- SignedLimit{Min: 4, Max: 6},
- 0,
- "test: value out of range (<4): 3\n",
- },
- {
- loc(),
- []string{"test", "-n", "4"},
- SignedLimit{Min: 4, Max: 6},
- 4,
- "",
- },
- {
- loc(),
- []string{"test", "-n", "5"},
- SignedLimit{Min: 4, Max: 6},
- 5,
- "",
- },
- {
- loc(),
- []string{"test", "-n", "6"},
- SignedLimit{Min: 4, Max: 6},
- 6,
- "",
- },
- {
- loc(),
- []string{"test", "-n", "7"},
- SignedLimit{Min: 4, Max: 6},
- 0,
- "test: value out of range (>6): 7\n",
- },
-}
-
-func TestSigneds(t *testing.T) {
- for x, tt := range signedNumberTests {
- if strings.Index(tt.where, ":-") > 0 {
- tt.where = fmt.Sprintf("#%d", x)
- }
-
- reset()
- n := Signed('n', 0, &tt.l)
- parse(tt.in)
- if s := checkError(tt.err); s != "" {
- t.Errorf("%s: %s", tt.where, s)
- }
- if *n != tt.out {
- t.Errorf("%s: got %v, want %v", tt.where, *n, tt.out)
- }
- }
-}
diff --git a/vendor/github.com/pborman/getopt/v2/string_test.go b/vendor/github.com/pborman/getopt/v2/string_test.go
deleted file mode 100644
index 31abae8..0000000
--- a/vendor/github.com/pborman/getopt/v2/string_test.go
+++ /dev/null
@@ -1,77 +0,0 @@
-// Copyright 2017 Google Inc. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package getopt
-
-import "testing"
-
-var stringTests = []struct {
- where string
- in []string
- sout string
- optout string
- err string
-}{
- {
- loc(),
- []string{},
- "one",
- "two",
- "",
- },
- {
- loc(),
- []string{"test", "-s"},
- "one",
- "two",
- "test: missing parameter for -s\n",
- },
- {
- loc(),
- []string{"test", "--opt"},
- "one",
- "two",
- "test: missing parameter for --opt\n",
- },
- {
- loc(),
- []string{"test", "-svalue", "--opt=option"},
- "value",
- "option",
- "",
- },
- {
- loc(),
- []string{"test", "-s", "value", "--opt", "option"},
- "value",
- "option",
- "",
- },
- {
- loc(),
- []string{"test", "-swrong", "--opt=wrong", "-s", "value", "--opt", "option"},
- "value",
- "option",
- "",
- },
-}
-
-func TestString(t *testing.T) {
- for _, tt := range stringTests {
- reset()
- s := String('s', "one")
- opt := StringLong("opt", 0, "two")
-
- parse(tt.in)
- if s := checkError(tt.err); s != "" {
- t.Errorf("%s: %s", tt.where, s)
- }
- if *s != tt.sout {
- t.Errorf("%s: got s = %q, want %q", tt.where, *s, tt.sout)
- }
- if *opt != tt.optout {
- t.Errorf("%s: got opt = %q, want %q", tt.where, *opt, tt.optout)
- }
- }
-}
diff --git a/vendor/github.com/pborman/getopt/v2/unsigned_test.go b/vendor/github.com/pborman/getopt/v2/unsigned_test.go
deleted file mode 100644
index bf3d61a..0000000
--- a/vendor/github.com/pborman/getopt/v2/unsigned_test.go
+++ /dev/null
@@ -1,97 +0,0 @@
-// Copyright 2017 Google Inc. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package getopt
-
-import (
- "fmt"
- "strings"
- "testing"
-)
-
-var unsignedTests = []struct {
- where string
- in []string
- l UnsignedLimit
- out uint64
- err string
-}{
- {
- where: loc(),
- },
- {
- loc(),
- []string{"test", "-n", "1010"},
- UnsignedLimit{Base: 2, Bits: 5},
- 10,
- "",
- },
- {
- loc(),
- []string{"test", "-n", "1010"},
- UnsignedLimit{Base: 2, Bits: 4},
- 10,
- "",
- },
- {
- loc(),
- []string{"test", "-n", "1010"},
- UnsignedLimit{Base: 2, Bits: 3},
- 0,
- "test: value out of range: 1010\n",
- },
- {
- loc(),
- []string{"test", "-n", "3"},
- UnsignedLimit{Min: 4, Max: 6},
- 0,
- "test: value out of range (<4): 3\n",
- },
- {
- loc(),
- []string{"test", "-n", "4"},
- UnsignedLimit{Min: 4, Max: 6},
- 4,
- "",
- },
- {
- loc(),
- []string{"test", "-n", "5"},
- UnsignedLimit{Min: 4, Max: 6},
- 5,
- "",
- },
- {
- loc(),
- []string{"test", "-n", "6"},
- UnsignedLimit{Min: 4, Max: 6},
- 6,
- "",
- },
- {
- loc(),
- []string{"test", "-n", "7"},
- UnsignedLimit{Min: 4, Max: 6},
- 0,
- "test: value out of range (>6): 7\n",
- },
-}
-
-func TestUnsigneds(t *testing.T) {
- for x, tt := range unsignedTests {
- if strings.Index(tt.where, ":-") > 0 {
- tt.where = fmt.Sprintf("#%d", x)
- }
-
- reset()
- n := Unsigned('n', 0, &tt.l)
- parse(tt.in)
- if s := checkError(tt.err); s != "" {
- t.Errorf("%s: %s", tt.where, s)
- }
- if *n != tt.out {
- t.Errorf("%s: got %v, want %v", tt.where, *n, tt.out)
- }
- }
-}
diff --git a/vendor/github.com/pborman/getopt/v2/util_test.go b/vendor/github.com/pborman/getopt/v2/util_test.go
deleted file mode 100644
index d46e198..0000000
--- a/vendor/github.com/pborman/getopt/v2/util_test.go
+++ /dev/null
@@ -1,85 +0,0 @@
-// Copyright 2017 Google Inc. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package getopt
-
-import (
- "bytes"
- "fmt"
- "path"
- "reflect"
- "runtime"
- "strings"
-)
-
-var errorString string
-
-func reset() {
- CommandLine.shortOptions = make(map[rune]*option)
- CommandLine.longOptions = make(map[string]*option)
- CommandLine.options = nil
- CommandLine.args = nil
- CommandLine.program = ""
- errorString = ""
-}
-
-func parse(args []string) {
- err := CommandLine.Getopt(args, nil)
- if err != nil {
- b := &bytes.Buffer{}
-
- fmt.Fprintln(b, CommandLine.program+": "+err.Error())
- CommandLine.PrintUsage(b)
- errorString = b.String()
- }
-}
-
-func badSlice(a, b []string) bool {
- if len(a) != len(b) {
- return true
- }
- for x, v := range a {
- if b[x] != v {
- return true
- }
- }
- return false
-}
-
-func loc() string {
- _, file, line, _ := runtime.Caller(1)
- return fmt.Sprintf("%s:%d", path.Base(file), line)
-}
-
-func (o *option) Equal(opt *option) bool {
- if o.value != nil && opt.value == nil {
- return false
- }
- if o.value == nil && opt.value != nil {
- return false
- }
- if o.value != nil && o.value.String() != opt.value.String() {
- return false
- }
-
- oc := *o
- optc := *opt
- oc.value = nil
- optc.value = nil
- return reflect.DeepEqual(&oc, &optc)
-}
-
-func checkError(err string) string {
- switch {
- case err == errorString:
- return ""
- case err == "":
- return fmt.Sprintf("unexpected error %q", errorString)
- case errorString == "":
- return fmt.Sprintf("did not get expected error %q", err)
- case !strings.HasPrefix(errorString, err):
- return fmt.Sprintf("got error %q, want %q", errorString, err)
- }
- return ""
-}
diff --git a/vendor/github.com/pborman/getopt/var.go b/vendor/github.com/pborman/getopt/var.go
deleted file mode 100644
index fd816b9..0000000
--- a/vendor/github.com/pborman/getopt/var.go
+++ /dev/null
@@ -1,63 +0,0 @@
-// Copyright 2013 Google Inc. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package getopt
-
-import (
- "fmt"
- "runtime"
-)
-
-// Value is the interface to the dynamic value stored in a flag. (The default
-// value is represented as a string.) Set is passed the string to set the
-// value to as well as the Option that is being processed.
-type Value interface {
- Set(string, Option) error
- String() string
-}
-
-// Var creates an option of the specified name. The type and value of the option
-// are represented by the first argument, of type Value, which typically holds a
-// user-defined implementation of Value. All options are ultimately created
-// as a Var.
-func Var(p Value, name rune, helpvalue ...string) Option {
- return CommandLine.VarLong(p, "", name, helpvalue...)
-}
-
-func VarLong(p Value, name string, short rune, helpvalue ...string) Option {
- return CommandLine.VarLong(p, name, short, helpvalue...)
-}
-
-func (s *Set) Var(p Value, name rune, helpvalue ...string) Option {
- return s.VarLong(p, "", name, helpvalue...)
-}
-
-func (s *Set) VarLong(p Value, name string, short rune, helpvalue ...string) Option {
- opt := &option{
- short: short,
- long: name,
- value: p,
- defval: p.String(),
- }
-
- switch len(helpvalue) {
- case 2:
- opt.name = helpvalue[1]
- fallthrough
- case 1:
- opt.help = helpvalue[0]
- case 0:
- default:
- panic("Too many strings for String helpvalue")
- }
- if _, file, line, ok := runtime.Caller(1); ok {
- opt.where = fmt.Sprintf("%s:%d", file, line)
- }
- if opt.short == 0 && opt.long == "" {
- fmt.Fprintf(stderr, opt.where+": no short or long option given")
- exit(1)
- }
- s.AddOption(opt)
- return opt
-}
diff --git a/vendor/github.com/pmezard/go-difflib/.travis.yml b/vendor/github.com/pmezard/go-difflib/.travis.yml
deleted file mode 100644
index 90c9c6f..0000000
--- a/vendor/github.com/pmezard/go-difflib/.travis.yml
+++ /dev/null
@@ -1,5 +0,0 @@
-language: go
-go:
- - 1.5
- - tip
-
diff --git a/vendor/github.com/pmezard/go-difflib/README.md b/vendor/github.com/pmezard/go-difflib/README.md
deleted file mode 100644
index e87f307..0000000
--- a/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/vendor/github.com/pmezard/go-difflib/difflib/difflib_test.go b/vendor/github.com/pmezard/go-difflib/difflib/difflib_test.go
deleted file mode 100644
index d725119..0000000
--- a/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 <range> field shall be of the form:
- // %1d", <beginning line number> if the range contains exactly one line,
- // and:
- // "%1d,%1d", <beginning line number>, <number of lines> 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", <beginning line number>, <ending line number>
- // and the following format otherwise:
- // "*** %d ****\n", <ending line number>
- // 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", <beginning line number>, <ending line number>
- // and the following format otherwise:
- // "--- %d ----\n", <ending line number>
- 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/vendor/github.com/stretchr/testify/.gitignore b/vendor/github.com/stretchr/testify/.gitignore
deleted file mode 100644
index 5aacdb7..0000000
--- a/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/vendor/github.com/stretchr/testify/.travis.yml b/vendor/github.com/stretchr/testify/.travis.yml
deleted file mode 100644
index ffb9e0d..0000000
--- a/vendor/github.com/stretchr/testify/.travis.yml
+++ /dev/null
@@ -1,16 +0,0 @@
-language: go
-
-sudo: false
-
-go:
- - 1.1
- - 1.2
- - 1.3
- - 1.4
- - 1.5
- - 1.6
- - 1.7
- - tip
-
-script:
- - go test -v ./...
diff --git a/vendor/github.com/stretchr/testify/README.md b/vendor/github.com/stretchr/testify/README.md
deleted file mode 100644
index e57b181..0000000
--- a/vendor/github.com/stretchr/testify/README.md
+++ /dev/null
@@ -1,332 +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)
- * [HTTP response trapping](#http-package)
- * [Testing suite interfaces and functions](#suite-package)
-
-Get started:
-
- * Install testify with [one line of code](#installation), or [update it with another](#staying-up-to-date)
- * For an introduction to writing test code in Go, see http://golang.org/doc/code.html#Testing
- * Check out the API Documentation http://godoc.org/github.com/stretchr/testify
- * To make your testing life easier, check out our other project, [gorc](http://github.com/stretchr/gorc)
- * A little about [Test-Driven Development (TDD)](http://en.wikipedia.org/wiki/Test-driven_development)
-
-
-
-[`assert`](http://godoc.org/github.com/stretchr/testify/assert "API documentation") package
--------------------------------------------------------------------------------------------
-
-The `assert` package provides some helpful methods that allow you to write better test code in Go.
-
- * Prints friendly, easy to read failure descriptions
- * Allows for very readable code
- * Optionally annotate each assertion with a message
-
-See it in action:
-
-```go
-package yours
-
-import (
- "testing"
- "github.com/stretchr/testify/assert"
-)
-
-func TestSomething(t *testing.T) {
-
- // assert equality
- assert.Equal(t, 123, 123, "they should be equal")
-
- // assert inequality
- assert.NotEqual(t, 123, 456, "they should not be equal")
-
- // assert for nil (good for errors)
- assert.Nil(t, object)
-
- // assert for not nil (good when you expect something)
- if assert.NotNil(t, object) {
-
- // now we know that object isn't nil, we are safe to make
- // further assertions without causing any errors
- assert.Equal(t, "Something", object.Value)
-
- }
-
-}
-```
-
- * Every assert func takes the `testing.T` object as the first argument. This is how it writes the errors out through the normal `go test` capabilities.
- * Every assert func returns a bool indicating whether the assertion was successful or not, this is useful for if you want to go on making further assertions under certain conditions.
-
-if you assert many times, use the below:
-
-```go
-package yours
-
-import (
- "testing"
- "github.com/stretchr/testify/assert"
-)
-
-func TestSomething(t *testing.T) {
- assert := assert.New(t)
-
- // assert equality
- assert.Equal(123, 123, "they should be equal")
-
- // assert inequality
- assert.NotEqual(123, 456, "they should not be equal")
-
- // assert for nil (good for errors)
- assert.Nil(object)
-
- // assert for not nil (good when you expect something)
- if assert.NotNil(object) {
-
- // now we know that object isn't nil, we are safe to make
- // further assertions without causing any errors
- assert.Equal("Something", object.Value)
- }
-}
-```
-
-[`require`](http://godoc.org/github.com/stretchr/testify/require "API documentation") package
----------------------------------------------------------------------------------------------
-
-The `require` package provides same global functions as the `assert` package, but instead of returning a boolean result they terminate current test.
-
-See [t.FailNow](http://golang.org/pkg/testing/#T.FailNow) for details.
-
-
-[`http`](http://godoc.org/github.com/stretchr/testify/http "API documentation") package
----------------------------------------------------------------------------------------
-
-The `http` package contains test objects useful for testing code that relies on the `net/http` package. Check out the [(deprecated) API documentation for the `http` package](http://godoc.org/github.com/stretchr/testify/http).
-
-We recommend you use [httptest](http://golang.org/pkg/net/http/httptest) instead.
-
-[`mock`](http://godoc.org/github.com/stretchr/testify/mock "API documentation") package
-----------------------------------------------------------------------------------------
-
-The `mock` package provides a mechanism for easily writing mock objects that can be used in place of real objects when writing test code.
-
-An example test function that tests a piece of code that relies on an external object `testObj`, can setup expectations (testify) and assert that they indeed happened:
-
-```go
-package yours
-
-import (
- "testing"
- "github.com/stretchr/testify/mock"
-)
-
-/*
- Test objects
-*/
-
-// MyMockedObject is a mocked object that implements an interface
-// that describes an object that the code I am testing relies on.
-type MyMockedObject struct{
- mock.Mock
-}
-
-// DoSomething is a method on MyMockedObject that implements some interface
-// and just records the activity, and returns what the Mock object tells it to.
-//
-// In the real object, this method would do something useful, but since this
-// is a mocked object - we're just going to stub it out.
-//
-// NOTE: This method is not being tested here, code that uses this object is.
-func (m *MyMockedObject) DoSomething(number int) (bool, error) {
-
- args := m.Called(number)
- return args.Bool(0), args.Error(1)
-
-}
-
-/*
- Actual test functions
-*/
-
-// TestSomething is an example of how to use our test object to
-// make assertions about some target code we are testing.
-func TestSomething(t *testing.T) {
-
- // create an instance of our test object
- testObj := new(MyMockedObject)
-
- // setup expectations
- testObj.On("DoSomething", 123).Return(true, nil)
-
- // call the code we are testing
- targetFuncThatDoesSomethingWithObj(testObj)
-
- // assert that the expectations were met
- testObj.AssertExpectations(t)
-
-}
-```
-
-For more information on how to write mock code, check out the [API documentation for the `mock` package](http://godoc.org/github.com/stretchr/testify/mock).
-
-You can use the [mockery tool](http://github.com/vektra/mockery) to autogenerate the mock code against an interface as well, making using mocks much quicker.
-
-[`suite`](http://godoc.org/github.com/stretchr/testify/suite "API documentation") package
------------------------------------------------------------------------------------------
-
-The `suite` package provides functionality that you might be used to from more common object oriented languages. With it, you can build a testing suite as a struct, build setup/teardown methods and testing methods on your struct, and run them with 'go test' as per normal.
-
-An example suite is shown below:
-
-```go
-// Basic imports
-import (
- "testing"
- "github.com/stretchr/testify/assert"
- "github.com/stretchr/testify/suite"
-)
-
-// Define the suite, and absorb the built-in basic suite
-// functionality from testify - including a T() method which
-// returns the current testing context
-type ExampleTestSuite struct {
- suite.Suite
- VariableThatShouldStartAtFive int
-}
-
-// Make sure that VariableThatShouldStartAtFive is set to five
-// before each test
-func (suite *ExampleTestSuite) SetupTest() {
- suite.VariableThatShouldStartAtFive = 5
-}
-
-// All methods that begin with "Test" are run as tests within a
-// suite.
-func (suite *ExampleTestSuite) TestExample() {
- assert.Equal(suite.T(), 5, suite.VariableThatShouldStartAtFive)
-}
-
-// In order for 'go test' to run this suite, we need to create
-// a normal test function and pass our suite to suite.Run
-func TestExampleTestSuite(t *testing.T) {
- suite.Run(t, new(ExampleTestSuite))
-}
-```
-
-For a more complete example, using all of the functionality provided by the suite package, look at our [example testing suite](https://github.com/stretchr/testify/blob/master/suite/suite_test.go)
-
-For more information on writing suites, check out the [API documentation for the `suite` package](http://godoc.org/github.com/stretchr/testify/suite).
-
-`Suite` object has assertion methods:
-
-```go
-// Basic imports
-import (
- "testing"
- "github.com/stretchr/testify/suite"
-)
-
-// Define the suite, and absorb the built-in basic suite
-// functionality from testify - including assertion methods.
-type ExampleTestSuite struct {
- suite.Suite
- VariableThatShouldStartAtFive int
-}
-
-// Make sure that VariableThatShouldStartAtFive is set to five
-// before each test
-func (suite *ExampleTestSuite) SetupTest() {
- suite.VariableThatShouldStartAtFive = 5
-}
-
-// All methods that begin with "Test" are run as tests within a
-// suite.
-func (suite *ExampleTestSuite) TestExample() {
- suite.Equal(suite.VariableThatShouldStartAtFive, 5)
-}
-
-// In order for 'go test' to run this suite, we need to create
-// a normal test function and pass our suite to suite.Run
-func TestExampleTestSuite(t *testing.T) {
- suite.Run(t, new(ExampleTestSuite))
-}
-```
-
-------
-
-Installation
-============
-
-To install Testify, use `go get`:
-
- * Latest version: go get github.com/stretchr/testify
- * Specific version: go get gopkg.in/stretchr/testify.v1
-
-This will then make the following packages available to you:
-
- github.com/stretchr/testify/assert
- github.com/stretchr/testify/mock
- github.com/stretchr/testify/http
-
-Import the `testify/assert` package into your code using this template:
-
-```go
-package yours
-
-import (
- "testing"
- "github.com/stretchr/testify/assert"
-)
-
-func TestSomething(t *testing.T) {
-
- assert.True(t, true, "True is true!")
-
-}
-```
-
-------
-
-Staying up to date
-==================
-
-To update Testify to the latest version, use `go get -u github.com/stretchr/testify`.
-
-------
-
-Version History
-===============
-
- * 1.0 - New package versioning strategy adopted.
-
-------
-
-Contributing
-============
-
-Please feel free to submit issues, fork the repository and send pull requests!
-
-When submitting an issue, we ask that you please include a complete test function that demonstrates the issue. Extra credit for those using Testify to write the test code that demonstrates it.
-
-------
-
-Licence
-=======
-Copyright (c) 2012 - 2013 Mat Ryer and Tyler Bunnell
-
-Please consider promoting this project if you find it useful.
-
-Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/vendor/github.com/stretchr/testify/assert/assertion_forward.go.tmpl b/vendor/github.com/stretchr/testify/assert/assertion_forward.go.tmpl
deleted file mode 100644
index 99f9acf..0000000
--- a/vendor/github.com/stretchr/testify/assert/assertion_forward.go.tmpl
+++ /dev/null
@@ -1,4 +0,0 @@
-{{.CommentWithoutT "a"}}
-func (a *Assertions) {{.DocInfo.Name}}({{.Params}}) bool {
- return {{.DocInfo.Name}}(a.t, {{.ForwardedParams}})
-}
diff --git a/vendor/github.com/stretchr/testify/assert/assertions_test.go b/vendor/github.com/stretchr/testify/assert/assertions_test.go
deleted file mode 100644
index ac9b701..0000000
--- a/vendor/github.com/stretchr/testify/assert/assertions_test.go
+++ /dev/null
@@ -1,1210 +0,0 @@
-package assert
-
-import (
- "errors"
- "io"
- "math"
- "os"
- "reflect"
- "regexp"
- "testing"
- "time"
-)
-
-var (
- i interface{}
- zeros = []interface{}{
- false,
- byte(0),
- complex64(0),
- complex128(0),
- float32(0),
- float64(0),
- int(0),
- int8(0),
- int16(0),
- int32(0),
- int64(0),
- rune(0),
- uint(0),
- uint8(0),
- uint16(0),
- uint32(0),
- uint64(0),
- uintptr(0),
- "",
- [0]interface{}{},
- []interface{}(nil),
- struct{ x int }{},
- (*interface{})(nil),
- (func())(nil),
- nil,
- interface{}(nil),
- map[interface{}]interface{}(nil),
- (chan interface{})(nil),
- (<-chan interface{})(nil),
- (chan<- interface{})(nil),
- }
- nonZeros = []interface{}{
- true,
- byte(1),
- complex64(1),
- complex128(1),
- float32(1),
- float64(1),
- int(1),
- int8(1),
- int16(1),
- int32(1),
- int64(1),
- rune(1),
- uint(1),
- uint8(1),
- uint16(1),
- uint32(1),
- uint64(1),
- uintptr(1),
- "s",
- [1]interface{}{1},
- []interface{}{},
- struct{ x int }{1},
- (*interface{})(&i),
- (func())(func() {}),
- interface{}(1),
- map[interface{}]interface{}{},
- (chan interface{})(make(chan interface{})),
- (<-chan interface{})(make(chan interface{})),
- (chan<- interface{})(make(chan interface{})),
- }
-)
-
-// AssertionTesterInterface defines an interface to be used for testing assertion methods
-type AssertionTesterInterface interface {
- TestMethod()
-}
-
-// AssertionTesterConformingObject is an object that conforms to the AssertionTesterInterface interface
-type AssertionTesterConformingObject struct {
-}
-
-func (a *AssertionTesterConformingObject) TestMethod() {
-}
-
-// AssertionTesterNonConformingObject is an object that does not conform to the AssertionTesterInterface interface
-type AssertionTesterNonConformingObject struct {
-}
-
-func TestObjectsAreEqual(t *testing.T) {
-
- if !ObjectsAreEqual("Hello World", "Hello World") {
- t.Error("objectsAreEqual should return true")
- }
- if !ObjectsAreEqual(123, 123) {
- t.Error("objectsAreEqual should return true")
- }
- if !ObjectsAreEqual(123.5, 123.5) {
- t.Error("objectsAreEqual should return true")
- }
- if !ObjectsAreEqual([]byte("Hello World"), []byte("Hello World")) {
- t.Error("objectsAreEqual should return true")
- }
- if !ObjectsAreEqual(nil, nil) {
- t.Error("objectsAreEqual should return true")
- }
- if ObjectsAreEqual(map[int]int{5: 10}, map[int]int{10: 20}) {
- t.Error("objectsAreEqual should return false")
- }
- if ObjectsAreEqual('x', "x") {
- t.Error("objectsAreEqual should return false")
- }
- if ObjectsAreEqual("x", 'x') {
- t.Error("objectsAreEqual should return false")
- }
- if ObjectsAreEqual(0, 0.1) {
- t.Error("objectsAreEqual should return false")
- }
- if ObjectsAreEqual(0.1, 0) {
- t.Error("objectsAreEqual should return false")
- }
- if ObjectsAreEqual(uint32(10), int32(10)) {
- t.Error("objectsAreEqual should return false")
- }
- if !ObjectsAreEqualValues(uint32(10), int32(10)) {
- t.Error("ObjectsAreEqualValues should return true")
- }
- if ObjectsAreEqualValues(0, nil) {
- t.Fail()
- }
- if ObjectsAreEqualValues(nil, 0) {
- t.Fail()
- }
-
-}
-
-func TestImplements(t *testing.T) {
-
- mockT := new(testing.T)
-
- if !Implements(mockT, (*AssertionTesterInterface)(nil), new(AssertionTesterConformingObject)) {
- t.Error("Implements method should return true: AssertionTesterConformingObject implements AssertionTesterInterface")
- }
- if Implements(mockT, (*AssertionTesterInterface)(nil), new(AssertionTesterNonConformingObject)) {
- t.Error("Implements method should return false: AssertionTesterNonConformingObject does not implements AssertionTesterInterface")
- }
-
-}
-
-func TestIsType(t *testing.T) {
-
- mockT := new(testing.T)
-
- if !IsType(mockT, new(AssertionTesterConformingObject), new(AssertionTesterConformingObject)) {
- t.Error("IsType should return true: AssertionTesterConformingObject is the same type as AssertionTesterConformingObject")
- }
- if IsType(mockT, new(AssertionTesterConformingObject), new(AssertionTesterNonConformingObject)) {
- t.Error("IsType should return false: AssertionTesterConformingObject is not the same type as AssertionTesterNonConformingObject")
- }
-
-}
-
-func TestEqual(t *testing.T) {
-
- mockT := new(testing.T)
-
- if !Equal(mockT, "Hello World", "Hello World") {
- t.Error("Equal should return true")
- }
- if !Equal(mockT, 123, 123) {
- t.Error("Equal should return true")
- }
- if !Equal(mockT, 123.5, 123.5) {
- t.Error("Equal should return true")
- }
- if !Equal(mockT, []byte("Hello World"), []byte("Hello World")) {
- t.Error("Equal should return true")
- }
- if !Equal(mockT, nil, nil) {
- t.Error("Equal should return true")
- }
- if !Equal(mockT, int32(123), int32(123)) {
- t.Error("Equal should return true")
- }
- if !Equal(mockT, uint64(123), uint64(123)) {
- t.Error("Equal should return true")
- }
-
-}
-
-func 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")
-
- 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 true")
- }
-
- if NotEqual(mockT, "Hello World", "Hello World") {
- t.Error("NotEqual should return false")
- }
- if NotEqual(mockT, 123, 123) {
- t.Error("NotEqual should return false")
- }
- if NotEqual(mockT, 123.5, 123.5) {
- t.Error("NotEqual should return false")
- }
- if NotEqual(mockT, []byte("Hello World"), []byte("Hello World")) {
- t.Error("NotEqual should return false")
- }
- if NotEqual(mockT, new(AssertionTesterConformingObject), new(AssertionTesterConformingObject)) {
- t.Error("NotEqual should return false")
- }
-}
-
-type A struct {
- Name, Value string
-}
-
-func TestContains(t *testing.T) {
-
- mockT := new(testing.T)
- list := []string{"Foo", "Bar"}
- complexList := []*A{
- {"b", "c"},
- {"d", "e"},
- {"g", "h"},
- {"j", "k"},
- }
- simpleMap := map[interface{}]interface{}{"Foo": "Bar"}
-
- if !Contains(mockT, "Hello World", "Hello") {
- t.Error("Contains should return true: \"Hello World\" contains \"Hello\"")
- }
- if Contains(mockT, "Hello World", "Salut") {
- t.Error("Contains should return false: \"Hello World\" does not contain \"Salut\"")
- }
-
- if !Contains(mockT, list, "Bar") {
- t.Error("Contains should return true: \"[\"Foo\", \"Bar\"]\" contains \"Bar\"")
- }
- if Contains(mockT, list, "Salut") {
- t.Error("Contains should return false: \"[\"Foo\", \"Bar\"]\" does not contain \"Salut\"")
- }
- if !Contains(mockT, complexList, &A{"g", "h"}) {
- t.Error("Contains should return true: complexList contains {\"g\", \"h\"}")
- }
- if Contains(mockT, complexList, &A{"g", "e"}) {
- t.Error("Contains should return false: complexList contains {\"g\", \"e\"}")
- }
- if Contains(mockT, complexList, &A{"g", "e"}) {
- t.Error("Contains should return false: complexList contains {\"g\", \"e\"}")
- }
- if !Contains(mockT, simpleMap, "Foo") {
- t.Error("Contains should return true: \"{\"Foo\": \"Bar\"}\" contains \"Foo\"")
- }
- if Contains(mockT, simpleMap, "Bar") {
- t.Error("Contains should return false: \"{\"Foo\": \"Bar\"}\" does not contains \"Bar\"")
- }
-}
-
-func TestNotContains(t *testing.T) {
-
- mockT := new(testing.T)
- list := []string{"Foo", "Bar"}
- simpleMap := map[interface{}]interface{}{"Foo": "Bar"}
-
- if !NotContains(mockT, "Hello World", "Hello!") {
- t.Error("NotContains should return true: \"Hello World\" does not contain \"Hello!\"")
- }
- if NotContains(mockT, "Hello World", "Hello") {
- t.Error("NotContains should return false: \"Hello World\" contains \"Hello\"")
- }
-
- if !NotContains(mockT, list, "Foo!") {
- t.Error("NotContains should return true: \"[\"Foo\", \"Bar\"]\" does not contain \"Foo!\"")
- }
- if NotContains(mockT, list, "Foo") {
- t.Error("NotContains should return false: \"[\"Foo\", \"Bar\"]\" contains \"Foo\"")
- }
- if NotContains(mockT, simpleMap, "Foo") {
- t.Error("Contains should return true: \"{\"Foo\": \"Bar\"}\" contains \"Foo\"")
- }
- if !NotContains(mockT, simpleMap, "Bar") {
- t.Error("Contains should return false: \"{\"Foo\": \"Bar\"}\" does not contains \"Bar\"")
- }
-}
-
-func Test_includeElement(t *testing.T) {
-
- list1 := []string{"Foo", "Bar"}
- list2 := []int{1, 2}
- simpleMap := map[interface{}]interface{}{"Foo": "Bar"}
-
- ok, found := includeElement("Hello World", "World")
- True(t, ok)
- True(t, found)
-
- ok, found = includeElement(list1, "Foo")
- True(t, ok)
- True(t, found)
-
- ok, found = includeElement(list1, "Bar")
- True(t, ok)
- True(t, found)
-
- ok, found = includeElement(list2, 1)
- True(t, ok)
- True(t, found)
-
- ok, found = includeElement(list2, 2)
- True(t, ok)
- True(t, found)
-
- ok, found = includeElement(list1, "Foo!")
- True(t, ok)
- False(t, found)
-
- ok, found = includeElement(list2, 3)
- True(t, ok)
- False(t, found)
-
- ok, found = includeElement(list2, "1")
- True(t, ok)
- False(t, found)
-
- ok, found = includeElement(simpleMap, "Foo")
- True(t, ok)
- True(t, found)
-
- ok, found = includeElement(simpleMap, "Bar")
- True(t, ok)
- False(t, found)
-
- ok, found = includeElement(1433, "1")
- False(t, ok)
- False(t, found)
-}
-
-func TestCondition(t *testing.T) {
- mockT := new(testing.T)
-
- if !Condition(mockT, func() bool { return true }, "Truth") {
- t.Error("Condition should return true")
- }
-
- if Condition(mockT, func() bool { return false }, "Lie") {
- t.Error("Condition should return false")
- }
-
-}
-
-func TestDidPanic(t *testing.T) {
-
- if funcDidPanic, _ := didPanic(func() {
- panic("Panic!")
- }); !funcDidPanic {
- t.Error("didPanic should return true")
- }
-
- if funcDidPanic, _ := didPanic(func() {
- }); funcDidPanic {
- t.Error("didPanic should return false")
- }
-
-}
-
-func TestPanics(t *testing.T) {
-
- mockT := new(testing.T)
-
- if !Panics(mockT, func() {
- panic("Panic!")
- }) {
- t.Error("Panics should return true")
- }
-
- if Panics(mockT, func() {
- }) {
- t.Error("Panics should return false")
- }
-
-}
-
-func TestNotPanics(t *testing.T) {
-
- mockT := new(testing.T)
-
- if !NotPanics(mockT, func() {
- }) {
- t.Error("NotPanics should return true")
- }
-
- if NotPanics(mockT, func() {
- panic("Panic!")
- }) {
- t.Error("NotPanics should return false")
- }
-
-}
-
-func TestNoError(t *testing.T) {
-
- mockT := new(testing.T)
-
- // start with a nil error
- var err error
-
- True(t, NoError(mockT, err), "NoError should return True for nil arg")
-
- // now set an error
- err = errors.New("some error")
-
- False(t, NoError(mockT, err), "NoError with error should return False")
-
- // 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", 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")
-
- // 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", 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
-
- True(t, Empty(mockT, ""), "Empty string is empty")
- True(t, Empty(mockT, nil), "Nil is empty")
- True(t, Empty(mockT, []string{}), "Empty string array is empty")
- True(t, Empty(mockT, 0), "Zero int value is empty")
- True(t, Empty(mockT, false), "False value is empty")
- True(t, Empty(mockT, make(chan struct{})), "Channel without values is empty")
- True(t, Empty(mockT, s), "Nil string pointer is empty")
- True(t, Empty(mockT, f), "Nil os.File pointer is empty")
- True(t, Empty(mockT, tiP), "Nil time.Time pointer is empty")
- True(t, Empty(mockT, tiNP), "time.Time is empty")
-
- False(t, Empty(mockT, "something"), "Non Empty string is not empty")
- False(t, Empty(mockT, errors.New("something")), "Non nil object is not empty")
- False(t, Empty(mockT, []string{"something"}), "Non empty string array is not empty")
- False(t, Empty(mockT, 1), "Non-zero int value is not empty")
- False(t, Empty(mockT, true), "True value is not empty")
- False(t, Empty(mockT, chWithValue), "Channel with values is not empty")
-}
-
-func TestNotEmpty(t *testing.T) {
-
- mockT := new(testing.T)
- chWithValue := make(chan struct{}, 1)
- chWithValue <- struct{}{}
-
- False(t, NotEmpty(mockT, ""), "Empty string is empty")
- False(t, NotEmpty(mockT, nil), "Nil is empty")
- False(t, NotEmpty(mockT, []string{}), "Empty string array is empty")
- False(t, NotEmpty(mockT, 0), "Zero int value is empty")
- False(t, NotEmpty(mockT, false), "False value is empty")
- False(t, NotEmpty(mockT, make(chan struct{})), "Channel without values is empty")
-
- True(t, NotEmpty(mockT, "something"), "Non Empty string is not empty")
- True(t, NotEmpty(mockT, errors.New("something")), "Non nil object is not empty")
- True(t, NotEmpty(mockT, []string{"something"}), "Non empty string array is not empty")
- True(t, NotEmpty(mockT, 1), "Non-zero int value is not empty")
- True(t, NotEmpty(mockT, true), "True value is not empty")
- True(t, NotEmpty(mockT, chWithValue), "Channel with values is not empty")
-}
-
-func Test_getLen(t *testing.T) {
- falseCases := []interface{}{
- nil,
- 0,
- true,
- false,
- 'A',
- struct{}{},
- }
- for _, v := range falseCases {
- ok, l := getLen(v)
- False(t, ok, "Expected getLen fail to get length of %#v", v)
- Equal(t, 0, l, "getLen should return 0 for %#v", v)
- }
-
- ch := make(chan int, 5)
- ch <- 1
- ch <- 2
- ch <- 3
- trueCases := []struct {
- v interface{}
- l int
- }{
- {[]int{1, 2, 3}, 3},
- {[...]int{1, 2, 3}, 3},
- {"ABC", 3},
- {map[int]int{1: 2, 2: 4, 3: 6}, 3},
- {ch, 3},
-
- {[]int{}, 0},
- {map[int]int{}, 0},
- {make(chan int), 0},
-
- {[]int(nil), 0},
- {map[int]int(nil), 0},
- {(chan int)(nil), 0},
- }
-
- for _, c := range trueCases {
- ok, l := getLen(c.v)
- True(t, ok, "Expected getLen success to get length of %#v", c.v)
- Equal(t, c.l, l)
- }
-}
-
-func TestLen(t *testing.T) {
- mockT := new(testing.T)
-
- False(t, Len(mockT, nil, 0), "nil does not have length")
- False(t, Len(mockT, 0, 0), "int does not have length")
- False(t, Len(mockT, true, 0), "true does not have length")
- False(t, Len(mockT, false, 0), "false does not have length")
- False(t, Len(mockT, 'A', 0), "Rune does not have length")
- False(t, Len(mockT, struct{}{}, 0), "Struct does not have length")
-
- ch := make(chan int, 5)
- ch <- 1
- ch <- 2
- ch <- 3
-
- cases := []struct {
- v interface{}
- l int
- }{
- {[]int{1, 2, 3}, 3},
- {[...]int{1, 2, 3}, 3},
- {"ABC", 3},
- {map[int]int{1: 2, 2: 4, 3: 6}, 3},
- {ch, 3},
-
- {[]int{}, 0},
- {map[int]int{}, 0},
- {make(chan int), 0},
-
- {[]int(nil), 0},
- {map[int]int(nil), 0},
- {(chan int)(nil), 0},
- }
-
- for _, c := range cases {
- True(t, Len(mockT, c.v, c.l), "%#v have %d items", c.v, c.l)
- }
-
- cases = []struct {
- v interface{}
- l int
- }{
- {[]int{1, 2, 3}, 4},
- {[...]int{1, 2, 3}, 2},
- {"ABC", 2},
- {map[int]int{1: 2, 2: 4, 3: 6}, 4},
- {ch, 2},
-
- {[]int{}, 1},
- {map[int]int{}, 1},
- {make(chan int), 1},
-
- {[]int(nil), 1},
- {map[int]int(nil), 1},
- {(chan int)(nil), 1},
- }
-
- for _, c := range cases {
- False(t, Len(mockT, c.v, c.l), "%#v have %d items", c.v, c.l)
- }
-}
-
-func TestWithinDuration(t *testing.T) {
-
- mockT := new(testing.T)
- a := time.Now()
- b := a.Add(10 * time.Second)
-
- True(t, WithinDuration(mockT, a, b, 10*time.Second), "A 10s difference is within a 10s time difference")
- True(t, WithinDuration(mockT, b, a, 10*time.Second), "A 10s difference is within a 10s time difference")
-
- False(t, WithinDuration(mockT, a, b, 9*time.Second), "A 10s difference is not within a 9s time difference")
- False(t, WithinDuration(mockT, b, a, 9*time.Second), "A 10s difference is not within a 9s time difference")
-
- False(t, WithinDuration(mockT, a, b, -9*time.Second), "A 10s difference is not within a 9s time difference")
- False(t, WithinDuration(mockT, b, a, -9*time.Second), "A 10s difference is not within a 9s time difference")
-
- False(t, WithinDuration(mockT, a, b, -11*time.Second), "A 10s difference is not within a 9s time difference")
- False(t, WithinDuration(mockT, b, a, -11*time.Second), "A 10s difference is not within a 9s time difference")
-}
-
-func TestInDelta(t *testing.T) {
- mockT := new(testing.T)
-
- True(t, InDelta(mockT, 1.001, 1, 0.01), "|1.001 - 1| <= 0.01")
- True(t, InDelta(mockT, 1, 1.001, 0.01), "|1 - 1.001| <= 0.01")
- True(t, InDelta(mockT, 1, 2, 1), "|1 - 2| <= 1")
- False(t, InDelta(mockT, 1, 2, 0.5), "Expected |1 - 2| <= 0.5 to fail")
- False(t, InDelta(mockT, 2, 1, 0.5), "Expected |2 - 1| <= 0.5 to fail")
- False(t, InDelta(mockT, "", nil, 1), "Expected non numerals to fail")
- False(t, InDelta(mockT, 42, math.NaN(), 0.01), "Expected NaN for actual to fail")
- False(t, InDelta(mockT, math.NaN(), 42, 0.01), "Expected NaN for expected to fail")
-
- cases := []struct {
- a, b interface{}
- delta float64
- }{
- {uint8(2), uint8(1), 1},
- {uint16(2), uint16(1), 1},
- {uint32(2), uint32(1), 1},
- {uint64(2), uint64(1), 1},
-
- {int(2), int(1), 1},
- {int8(2), int8(1), 1},
- {int16(2), int16(1), 1},
- {int32(2), int32(1), 1},
- {int64(2), int64(1), 1},
-
- {float32(2), float32(1), 1},
- {float64(2), float64(1), 1},
- }
-
- for _, tc := range cases {
- True(t, InDelta(mockT, tc.a, tc.b, tc.delta), "Expected |%V - %V| <= %v", tc.a, tc.b, tc.delta)
- }
-}
-
-func TestInDeltaSlice(t *testing.T) {
- mockT := new(testing.T)
-
- True(t, InDeltaSlice(mockT,
- []float64{1.001, 0.999},
- []float64{1, 1},
- 0.1), "{1.001, 0.009} is element-wise close to {1, 1} in delta=0.1")
-
- True(t, InDeltaSlice(mockT,
- []float64{1, 2},
- []float64{0, 3},
- 1), "{1, 2} is element-wise close to {0, 3} in delta=1")
-
- False(t, InDeltaSlice(mockT,
- []float64{1, 2},
- []float64{0, 3},
- 0.1), "{1, 2} is not element-wise close to {0, 3} in delta=0.1")
-
- False(t, InDeltaSlice(mockT, "", nil, 1), "Expected non numeral slices to fail")
-}
-
-func TestInEpsilon(t *testing.T) {
- mockT := new(testing.T)
-
- cases := []struct {
- a, b interface{}
- epsilon float64
- }{
- {uint8(2), uint16(2), .001},
- {2.1, 2.2, 0.1},
- {2.2, 2.1, 0.1},
- {-2.1, -2.2, 0.1},
- {-2.2, -2.1, 0.1},
- {uint64(100), uint8(101), 0.01},
- {0.1, -0.1, 2},
- {0.1, 0, 2},
- }
-
- for _, tc := range cases {
- True(t, InEpsilon(t, tc.a, tc.b, tc.epsilon, "Expected %V and %V to have a relative difference of %v", tc.a, tc.b, tc.epsilon), "test: %q", tc)
- }
-
- cases = []struct {
- a, b interface{}
- epsilon float64
- }{
- {uint8(2), int16(-2), .001},
- {uint64(100), uint8(102), 0.01},
- {2.1, 2.2, 0.001},
- {2.2, 2.1, 0.001},
- {2.1, -2.2, 1},
- {2.1, "bla-bla", 0},
- {0.1, -0.1, 1.99},
- {0, 0.1, 2}, // expected must be different to zero
- }
-
- for _, tc := range cases {
- False(t, InEpsilon(mockT, tc.a, tc.b, tc.epsilon, "Expected %V and %V to have a relative difference of %v", tc.a, tc.b, tc.epsilon))
- }
-
-}
-
-func TestInEpsilonSlice(t *testing.T) {
- mockT := new(testing.T)
-
- True(t, InEpsilonSlice(mockT,
- []float64{2.2, 2.0},
- []float64{2.1, 2.1},
- 0.06), "{2.2, 2.0} is element-wise close to {2.1, 2.1} in espilon=0.06")
-
- False(t, InEpsilonSlice(mockT,
- []float64{2.2, 2.0},
- []float64{2.1, 2.1},
- 0.04), "{2.2, 2.0} is not element-wise close to {2.1, 2.1} in espilon=0.04")
-
- False(t, InEpsilonSlice(mockT, "", nil, 1), "Expected non numeral slices to fail")
-}
-
-func TestRegexp(t *testing.T) {
- mockT := new(testing.T)
-
- cases := []struct {
- rx, str string
- }{
- {"^start", "start of the line"},
- {"end$", "in the end"},
- {"[0-9]{3}[.-]?[0-9]{2}[.-]?[0-9]{2}", "My phone number is 650.12.34"},
- }
-
- for _, tc := range cases {
- True(t, Regexp(mockT, tc.rx, tc.str))
- True(t, Regexp(mockT, regexp.MustCompile(tc.rx), tc.str))
- False(t, NotRegexp(mockT, tc.rx, tc.str))
- False(t, NotRegexp(mockT, regexp.MustCompile(tc.rx), tc.str))
- }
-
- cases = []struct {
- rx, str string
- }{
- {"^asdfastart", "Not the start of the line"},
- {"end$", "in the end."},
- {"[0-9]{3}[.-]?[0-9]{2}[.-]?[0-9]{2}", "My phone number is 650.12a.34"},
- }
-
- for _, tc := range cases {
- False(t, Regexp(mockT, tc.rx, tc.str), "Expected \"%s\" to not match \"%s\"", tc.rx, tc.str)
- False(t, Regexp(mockT, regexp.MustCompile(tc.rx), tc.str))
- True(t, NotRegexp(mockT, tc.rx, tc.str))
- True(t, NotRegexp(mockT, regexp.MustCompile(tc.rx), tc.str))
- }
-}
-
-func testAutogeneratedFunction() {
- defer func() {
- if err := recover(); err == nil {
- panic("did not panic")
- }
- CallerInfo()
- }()
- t := struct {
- io.Closer
- }{}
- var c io.Closer
- c = t
- c.Close()
-}
-
-func TestCallerInfoWithAutogeneratedFunctions(t *testing.T) {
- NotPanics(t, func() {
- testAutogeneratedFunction()
- })
-}
-
-func TestZero(t *testing.T) {
- mockT := new(testing.T)
-
- for _, test := range zeros {
- True(t, Zero(mockT, test, "%#v is not the %v zero value", test, reflect.TypeOf(test)))
- }
-
- for _, test := range nonZeros {
- False(t, Zero(mockT, test, "%#v is not the %v zero value", test, reflect.TypeOf(test)))
- }
-}
-
-func TestNotZero(t *testing.T) {
- mockT := new(testing.T)
-
- for _, test := range zeros {
- False(t, NotZero(mockT, test, "%#v is not the %v zero value", test, reflect.TypeOf(test)))
- }
-
- for _, test := range nonZeros {
- True(t, NotZero(mockT, test, "%#v is not the %v zero value", test, reflect.TypeOf(test)))
- }
-}
-
-func TestJSONEq_EqualSONString(t *testing.T) {
- mockT := new(testing.T)
- True(t, JSONEq(mockT, `{"hello": "world", "foo": "bar"}`, `{"hello": "world", "foo": "bar"}`))
-}
-
-func TestJSONEq_EquivalentButNotEqual(t *testing.T) {
- mockT := new(testing.T)
- True(t, JSONEq(mockT, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`))
-}
-
-func TestJSONEq_HashOfArraysAndHashes(t *testing.T) {
- mockT := new(testing.T)
- True(t, JSONEq(mockT, "{\r\n\t\"numeric\": 1.5,\r\n\t\"array\": [{\"foo\": \"bar\"}, 1, \"string\", [\"nested\", \"array\", 5.5]],\r\n\t\"hash\": {\"nested\": \"hash\", \"nested_slice\": [\"this\", \"is\", \"nested\"]},\r\n\t\"string\": \"foo\"\r\n}",
- "{\r\n\t\"numeric\": 1.5,\r\n\t\"hash\": {\"nested\": \"hash\", \"nested_slice\": [\"this\", \"is\", \"nested\"]},\r\n\t\"string\": \"foo\",\r\n\t\"array\": [{\"foo\": \"bar\"}, 1, \"string\", [\"nested\", \"array\", 5.5]]\r\n}"))
-}
-
-func TestJSONEq_Array(t *testing.T) {
- mockT := new(testing.T)
- True(t, JSONEq(mockT, `["foo", {"hello": "world", "nested": "hash"}]`, `["foo", {"nested": "hash", "hello": "world"}]`))
-}
-
-func TestJSONEq_HashAndArrayNotEquivalent(t *testing.T) {
- mockT := new(testing.T)
- False(t, JSONEq(mockT, `["foo", {"hello": "world", "nested": "hash"}]`, `{"foo": "bar", {"nested": "hash", "hello": "world"}}`))
-}
-
-func TestJSONEq_HashesNotEquivalent(t *testing.T) {
- mockT := new(testing.T)
- False(t, JSONEq(mockT, `{"foo": "bar"}`, `{"foo": "bar", "hello": "world"}`))
-}
-
-func TestJSONEq_ActualIsNotJSON(t *testing.T) {
- mockT := new(testing.T)
- False(t, JSONEq(mockT, `{"foo": "bar"}`, "Not JSON"))
-}
-
-func TestJSONEq_ExpectedIsNotJSON(t *testing.T) {
- mockT := new(testing.T)
- False(t, JSONEq(mockT, "Not JSON", `{"foo": "bar", "hello": "world"}`))
-}
-
-func TestJSONEq_ExpectedAndActualNotJSON(t *testing.T) {
- mockT := new(testing.T)
- False(t, JSONEq(mockT, "Not JSON", "Not JSON"))
-}
-
-func TestJSONEq_ArraysOfDifferentOrder(t *testing.T) {
- mockT := new(testing.T)
- False(t, JSONEq(mockT, `["foo", {"hello": "world", "nested": "hash"}]`, `[{ "hello": "world", "nested": "hash"}, "foo"]`))
-}
-
-func TestDiff(t *testing.T) {
- expected := `
-
-Diff:
---- Expected
-+++ Actual
-@@ -1,3 +1,3 @@
- (struct { foo string }) {
-- foo: (string) (len=5) "hello"
-+ foo: (string) (len=3) "bar"
- }
-`
- actual := diff(
- struct{ foo string }{"hello"},
- struct{ foo string }{"bar"},
- )
- Equal(t, expected, actual)
-
- expected = `
-
-Diff:
---- Expected
-+++ Actual
-@@ -2,5 +2,5 @@
- (int) 1,
-- (int) 2,
- (int) 3,
-- (int) 4
-+ (int) 5,
-+ (int) 7
- }
-`
- actual = diff(
- []int{1, 2, 3, 4},
- []int{1, 3, 5, 7},
- )
- Equal(t, expected, actual)
-
- expected = `
-
-Diff:
---- Expected
-+++ Actual
-@@ -2,4 +2,4 @@
- (int) 1,
-- (int) 2,
-- (int) 3
-+ (int) 3,
-+ (int) 5
- }
-`
- actual = diff(
- []int{1, 2, 3, 4}[0:3],
- []int{1, 3, 5, 7}[0:3],
- )
- Equal(t, expected, actual)
-
- expected = `
-
-Diff:
---- Expected
-+++ Actual
-@@ -1,6 +1,6 @@
- (map[string]int) (len=4) {
-- (string) (len=4) "four": (int) 4,
-+ (string) (len=4) "five": (int) 5,
- (string) (len=3) "one": (int) 1,
-- (string) (len=5) "three": (int) 3,
-- (string) (len=3) "two": (int) 2
-+ (string) (len=5) "seven": (int) 7,
-+ (string) (len=5) "three": (int) 3
- }
-`
-
- actual = diff(
- map[string]int{"one": 1, "two": 2, "three": 3, "four": 4},
- map[string]int{"one": 1, "three": 3, "five": 5, "seven": 7},
- )
- Equal(t, expected, actual)
-}
-
-func TestDiffEmptyCases(t *testing.T) {
- Equal(t, "", diff(nil, nil))
- Equal(t, "", diff(struct{ foo string }{}, nil))
- Equal(t, "", diff(nil, struct{ foo string }{}))
- Equal(t, "", diff(1, 2))
- Equal(t, "", diff(1, 2))
- Equal(t, "", diff([]int{1}, []bool{true}))
-}
-
-// 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")
-}
diff --git a/vendor/github.com/stretchr/testify/assert/forward_assertions_test.go b/vendor/github.com/stretchr/testify/assert/forward_assertions_test.go
deleted file mode 100644
index 22e1df1..0000000
--- a/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/vendor/github.com/stretchr/testify/assert/http_assertions_test.go b/vendor/github.com/stretchr/testify/assert/http_assertions_test.go
deleted file mode 100644
index 684c2d5..0000000
--- a/vendor/github.com/stretchr/testify/assert/http_assertions_test.go
+++ /dev/null
@@ -1,86 +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 TestHTTPStatuses(t *testing.T) {
- assert := New(t)
- mockT := new(testing.T)
-
- assert.Equal(HTTPSuccess(mockT, httpOK, "GET", "/", nil), true)
- assert.Equal(HTTPSuccess(mockT, httpRedirect, "GET", "/", nil), false)
- assert.Equal(HTTPSuccess(mockT, httpError, "GET", "/", nil), false)
-
- assert.Equal(HTTPRedirect(mockT, httpOK, "GET", "/", nil), false)
- assert.Equal(HTTPRedirect(mockT, httpRedirect, "GET", "/", nil), true)
- assert.Equal(HTTPRedirect(mockT, httpError, "GET", "/", nil), false)
-
- assert.Equal(HTTPError(mockT, httpOK, "GET", "/", nil), false)
- assert.Equal(HTTPError(mockT, httpRedirect, "GET", "/", nil), false)
- assert.Equal(HTTPError(mockT, httpError, "GET", "/", nil), true)
-}
-
-func TestHTTPStatusesWrapper(t *testing.T) {
- assert := New(t)
- mockAssert := New(new(testing.T))
-
- assert.Equal(mockAssert.HTTPSuccess(httpOK, "GET", "/", nil), true)
- assert.Equal(mockAssert.HTTPSuccess(httpRedirect, "GET", "/", nil), false)
- assert.Equal(mockAssert.HTTPSuccess(httpError, "GET", "/", nil), false)
-
- assert.Equal(mockAssert.HTTPRedirect(httpOK, "GET", "/", nil), false)
- assert.Equal(mockAssert.HTTPRedirect(httpRedirect, "GET", "/", nil), true)
- assert.Equal(mockAssert.HTTPRedirect(httpError, "GET", "/", nil), false)
-
- assert.Equal(mockAssert.HTTPError(httpOK, "GET", "/", nil), false)
- assert.Equal(mockAssert.HTTPError(httpRedirect, "GET", "/", nil), false)
- assert.Equal(mockAssert.HTTPError(httpError, "GET", "/", nil), true)
-}
-
-func httpHelloName(w http.ResponseWriter, r *http.Request) {
- name := r.FormValue("name")
- w.Write([]byte(fmt.Sprintf("Hello, %s!", name)))
-}
-
-func TestHttpBody(t *testing.T) {
- assert := New(t)
- mockT := new(testing.T)
-
- assert.True(HTTPBodyContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "Hello, World!"))
- assert.True(HTTPBodyContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "World"))
- assert.False(HTTPBodyContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "world"))
-
- assert.False(HTTPBodyNotContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "Hello, World!"))
- assert.False(HTTPBodyNotContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "World"))
- assert.True(HTTPBodyNotContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "world"))
-}
-
-func TestHttpBodyWrappers(t *testing.T) {
- assert := New(t)
- mockAssert := New(new(testing.T))
-
- assert.True(mockAssert.HTTPBodyContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "Hello, World!"))
- assert.True(mockAssert.HTTPBodyContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "World"))
- assert.False(mockAssert.HTTPBodyContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "world"))
-
- assert.False(mockAssert.HTTPBodyNotContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "Hello, World!"))
- assert.False(mockAssert.HTTPBodyNotContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "World"))
- assert.True(mockAssert.HTTPBodyNotContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "world"))
-
-}
diff --git a/vendor/github.com/stretchr/testify/doc.go b/vendor/github.com/stretchr/testify/doc.go
deleted file mode 100644
index 377d5cc..0000000
--- a/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/vendor/github.com/stretchr/testify/package_test.go b/vendor/github.com/stretchr/testify/package_test.go
deleted file mode 100644
index 7ac5d6d..0000000
--- a/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/vendor/github.com/utahta/go-openuri/openuri_test.go b/vendor/github.com/utahta/go-openuri/openuri_test.go
deleted file mode 100644
index 7f653e6..0000000
--- a/vendor/github.com/utahta/go-openuri/openuri_test.go
+++ /dev/null
@@ -1,74 +0,0 @@
-package openuri
-
-import (
- "io/ioutil"
- "net/http"
- "strings"
- "testing"
-)
-
-type dummyRoundTripper struct{}
-
-func (d *dummyRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
- return &http.Response{Status: "dummy", Body: ioutil.NopCloser(strings.NewReader("body dummy"))}, nil
-}
-
-func TestNew(t *testing.T) {
- _, err := New()
- if err != nil {
- t.Error(err)
- }
-}
-
-func TestWithHTTPClient(t *testing.T) {
- c, err := New(WithHTTPClient(&http.Client{Transport: &dummyRoundTripper{}}))
- if err != nil {
- t.Error(err)
- }
-
- resp, _ := c.httpClient.Get("test")
- if resp.Status != "dummy" {
- t.Errorf("Expected status dummy, got %s", resp.Status)
- }
-}
-
-func TestOpen_File(t *testing.T) {
- o, err := Open("./openuri.go")
- if err != nil {
- t.Error(err)
- }
-
- b, err := ioutil.ReadAll(o)
- if err != nil {
- t.Error(err)
- }
-
- if !strings.HasPrefix(string(b), "package openuri") {
- t.Errorf("Expected open file, go %s", string(b))
- }
-}
-
-func TestOpen_URL(t *testing.T) {
- tests := []struct {
- url string
- }{
- {"http://example.com"},
- {"https://example.com"},
- }
-
- for _, test := range tests {
- o, err := Open(test.url, WithHTTPClient(&http.Client{Transport: &dummyRoundTripper{}}))
- if err != nil {
- t.Error(err)
- }
-
- b, err := ioutil.ReadAll(o)
- if err != nil {
- t.Error(err)
- }
-
- if !strings.HasPrefix(string(b), "body dummy") {
- t.Errorf("Expected open file, go %s", string(b))
- }
- }
-}
diff --git a/vendor/gopkg.in/go-playground/validator.v9/.gitignore b/vendor/gopkg.in/go-playground/validator.v9/.gitignore
deleted file mode 100644
index 792ca00..0000000
--- a/vendor/gopkg.in/go-playground/validator.v9/.gitignore
+++ /dev/null
@@ -1,29 +0,0 @@
-# Compiled Object files, Static and Dynamic libs (Shared Objects)
-*.o
-*.a
-*.so
-
-# Folders
-_obj
-_test
-
-# Architecture specific extensions/prefixes
-*.[568vq]
-[568vq].out
-
-*.cgo1.go
-*.cgo2.c
-_cgo_defun.c
-_cgo_gotypes.go
-_cgo_export.*
-
-_testmain.go
-
-*.exe
-*.test
-*.prof
-*.test
-*.out
-*.txt
-cover.html
-README.html \ No newline at end of file
diff --git a/vendor/gopkg.in/go-playground/validator.v9/README.md b/vendor/gopkg.in/go-playground/validator.v9/README.md
deleted file mode 100644
index d783749..0000000
--- a/vendor/gopkg.in/go-playground/validator.v9/README.md
+++ /dev/null
@@ -1,151 +0,0 @@
-Package validator
-================
-<img align="right" src="https://raw.githubusercontent.com/go-playground/validator/v9/logo.png">[![Join the chat at https://gitter.im/go-playground/validator](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/go-playground/validator?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
-![Project status](https://img.shields.io/badge/version-9.11.0-green.svg)
-[![Build Status](https://semaphoreci.com/api/v1/joeybloggs/validator/branches/v9/badge.svg)](https://semaphoreci.com/joeybloggs/validator)
-[![Coverage Status](https://coveralls.io/repos/go-playground/validator/badge.svg?branch=v9&service=github)](https://coveralls.io/github/go-playground/validator?branch=v9)
-[![Go Report Card](https://goreportcard.com/badge/github.com/go-playground/validator)](https://goreportcard.com/report/github.com/go-playground/validator)
-[![GoDoc](https://godoc.org/gopkg.in/go-playground/validator.v9?status.svg)](https://godoc.org/gopkg.in/go-playground/validator.v9)
-![License](https://img.shields.io/dub/l/vibe-d.svg)
-
-Package validator implements value validations for structs and individual fields based on tags.
-
-It has the following **unique** features:
-
-- Cross Field and Cross Struct validations by using validation tags or custom validators.
-- Slice, Array and Map diving, which allows any or all levels of a multidimensional field to be validated.
-- Ability to dive into both map keys and values for validation
-- Handles type interface by determining it's underlying type prior to validation.
-- Handles custom field types such as sql driver Valuer see [Valuer](https://golang.org/src/database/sql/driver/types.go?s=1210:1293#L29)
-- Alias validation tags, which allows for mapping of several validations to a single tag for easier defining of validations on structs
-- Extraction of custom defined Field Name e.g. can specify to extract the JSON name while validating and have it available in the resulting FieldError
-- Customizable i18n aware error messages.
-- Default validator for the [gin](https://github.com/gin-gonic/gin) web framework; upgrading from v8 to v9 in gin see [here](https://github.com/go-playground/validator/tree/v9/_examples/gin-upgrading-overriding)
-
-Installation
-------------
-
-Use go get.
-
- go get gopkg.in/go-playground/validator.v9
-
-Then import the validator package into your own code.
-
- import "gopkg.in/go-playground/validator.v9"
-
-Error Return Value
--------
-
-Validation functions return type error
-
-They return type error to avoid the issue discussed in the following, where err is always != nil:
-
-* http://stackoverflow.com/a/29138676/3158232
-* https://github.com/go-playground/validator/issues/134
-
-Validator only InvalidValidationError for bad validation input, nil or ValidationErrors as type error; so, in your code all you need to do is check if the error returned is not nil, and if it's not check if error is InvalidValidationError ( if necessary, most of the time it isn't ) type cast it to type ValidationErrors like so:
-
-```go
-err := validate.Struct(mystruct)
-validationErrors := err.(validator.ValidationErrors)
- ```
-
-Usage and documentation
-------
-
-Please see http://godoc.org/gopkg.in/go-playground/validator.v9 for detailed usage docs.
-
-##### Examples:
-
-- [Simple](https://github.com/go-playground/validator/blob/v9/_examples/simple/main.go)
-- [Custom Field Types](https://github.com/go-playground/validator/blob/v9/_examples/custom/main.go)
-- [Struct Level](https://github.com/go-playground/validator/blob/v9/_examples/struct-level/main.go)
-- [Translations & Custom Errors](https://github.com/go-playground/validator/blob/v9/_examples/translations/main.go)
-- [Gin upgrade and/or override validator](https://github.com/go-playground/validator/tree/v9/_examples/gin-upgrading-overriding)
-- [wash - an example application putting it all together](https://github.com/bluesuncorp/wash)
-
-Benchmarks
-------
-###### Run on MacBook Pro (15-inch, 2017) Go version go1.9.4 darwin/amd64
-```go
-goos: darwin
-goarch: amd64
-pkg: github.com/go-playground/validator
-BenchmarkFieldSuccess-8 20000000 86.4 ns/op 0 B/op 0 allocs/op
-BenchmarkFieldSuccessParallel-8 50000000 27.6 ns/op 0 B/op 0 allocs/op
-BenchmarkFieldFailure-8 5000000 297 ns/op 208 B/op 4 allocs/op
-BenchmarkFieldFailureParallel-8 20000000 107 ns/op 208 B/op 4 allocs/op
-BenchmarkFieldArrayDiveSuccess-8 2000000 618 ns/op 201 B/op 11 allocs/op
-BenchmarkFieldArrayDiveSuccessParallel-8 10000000 225 ns/op 201 B/op 11 allocs/op
-BenchmarkFieldArrayDiveFailure-8 2000000 863 ns/op 412 B/op 16 allocs/op
-BenchmarkFieldArrayDiveFailureParallel-8 5000000 322 ns/op 413 B/op 16 allocs/op
-BenchmarkFieldMapDiveSuccess-8 1000000 1336 ns/op 432 B/op 18 allocs/op
-BenchmarkFieldMapDiveSuccessParallel-8 3000000 474 ns/op 432 B/op 18 allocs/op
-BenchmarkFieldMapDiveFailure-8 1000000 1103 ns/op 512 B/op 16 allocs/op
-BenchmarkFieldMapDiveFailureParallel-8 5000000 412 ns/op 512 B/op 16 allocs/op
-BenchmarkFieldMapDiveWithKeysSuccess-8 1000000 1572 ns/op 480 B/op 21 allocs/op
-BenchmarkFieldMapDiveWithKeysSuccessParallel-8 3000000 615 ns/op 480 B/op 21 allocs/op
-BenchmarkFieldMapDiveWithKeysFailure-8 1000000 1438 ns/op 721 B/op 21 allocs/op
-BenchmarkFieldMapDiveWithKeysFailureParallel-8 3000000 543 ns/op 721 B/op 21 allocs/op
-BenchmarkFieldCustomTypeSuccess-8 10000000 230 ns/op 32 B/op 2 allocs/op
-BenchmarkFieldCustomTypeSuccessParallel-8 20000000 82.5 ns/op 32 B/op 2 allocs/op
-BenchmarkFieldCustomTypeFailure-8 5000000 284 ns/op 208 B/op 4 allocs/op
-BenchmarkFieldCustomTypeFailureParallel-8 20000000 118 ns/op 208 B/op 4 allocs/op
-BenchmarkFieldOrTagSuccess-8 2000000 824 ns/op 16 B/op 1 allocs/op
-BenchmarkFieldOrTagSuccessParallel-8 3000000 472 ns/op 16 B/op 1 allocs/op
-BenchmarkFieldOrTagFailure-8 3000000 487 ns/op 224 B/op 5 allocs/op
-BenchmarkFieldOrTagFailureParallel-8 5000000 405 ns/op 224 B/op 5 allocs/op
-BenchmarkStructLevelValidationSuccess-8 10000000 214 ns/op 32 B/op 2 allocs/op
-BenchmarkStructLevelValidationSuccessParallel-8 20000000 78.0 ns/op 32 B/op 2 allocs/op
-BenchmarkStructLevelValidationFailure-8 3000000 475 ns/op 304 B/op 8 allocs/op
-BenchmarkStructLevelValidationFailureParallel-8 10000000 200 ns/op 304 B/op 8 allocs/op
-BenchmarkStructSimpleCustomTypeSuccess-8 3000000 403 ns/op 32 B/op 2 allocs/op
-BenchmarkStructSimpleCustomTypeSuccessParallel-8 10000000 143 ns/op 32 B/op 2 allocs/op
-BenchmarkStructSimpleCustomTypeFailure-8 2000000 655 ns/op 424 B/op 9 allocs/op
-BenchmarkStructSimpleCustomTypeFailureParallel-8 5000000 286 ns/op 440 B/op 10 allocs/op
-BenchmarkStructFilteredSuccess-8 2000000 598 ns/op 288 B/op 9 allocs/op
-BenchmarkStructFilteredSuccessParallel-8 10000000 231 ns/op 288 B/op 9 allocs/op
-BenchmarkStructFilteredFailure-8 3000000 455 ns/op 256 B/op 7 allocs/op
-BenchmarkStructFilteredFailureParallel-8 10000000 197 ns/op 256 B/op 7 allocs/op
-BenchmarkStructPartialSuccess-8 3000000 552 ns/op 256 B/op 6 allocs/op
-BenchmarkStructPartialSuccessParallel-8 10000000 206 ns/op 256 B/op 6 allocs/op
-BenchmarkStructPartialFailure-8 2000000 750 ns/op 480 B/op 11 allocs/op
-BenchmarkStructPartialFailureParallel-8 5000000 317 ns/op 480 B/op 11 allocs/op
-BenchmarkStructExceptSuccess-8 2000000 853 ns/op 496 B/op 12 allocs/op
-BenchmarkStructExceptSuccessParallel-8 10000000 179 ns/op 240 B/op 5 allocs/op
-BenchmarkStructExceptFailure-8 2000000 698 ns/op 464 B/op 10 allocs/op
-BenchmarkStructExceptFailureParallel-8 5000000 276 ns/op 464 B/op 10 allocs/op
-BenchmarkStructSimpleCrossFieldSuccess-8 3000000 412 ns/op 72 B/op 3 allocs/op
-BenchmarkStructSimpleCrossFieldSuccessParallel-8 10000000 148 ns/op 72 B/op 3 allocs/op
-BenchmarkStructSimpleCrossFieldFailure-8 2000000 630 ns/op 304 B/op 8 allocs/op
-BenchmarkStructSimpleCrossFieldFailureParallel-8 10000000 244 ns/op 304 B/op 8 allocs/op
-BenchmarkStructSimpleCrossStructCrossFieldSuccess-8 2000000 610 ns/op 80 B/op 4 allocs/op
-BenchmarkStructSimpleCrossStructCrossFieldSuccessParallel-8 10000000 205 ns/op 80 B/op 4 allocs/op
-BenchmarkStructSimpleCrossStructCrossFieldFailure-8 2000000 861 ns/op 320 B/op 9 allocs/op
-BenchmarkStructSimpleCrossStructCrossFieldFailureParallel-8 5000000 315 ns/op 320 B/op 9 allocs/op
-BenchmarkStructSimpleSuccess-8 5000000 279 ns/op 0 B/op 0 allocs/op
-BenchmarkStructSimpleSuccessParallel-8 20000000 86.4 ns/op 0 B/op 0 allocs/op
-BenchmarkStructSimpleFailure-8 2000000 636 ns/op 424 B/op 9 allocs/op
-BenchmarkStructSimpleFailureParallel-8 10000000 264 ns/op 424 B/op 9 allocs/op
-BenchmarkStructComplexSuccess-8 1000000 1539 ns/op 128 B/op 8 allocs/op
-BenchmarkStructComplexSuccessParallel-8 3000000 557 ns/op 128 B/op 8 allocs/op
-BenchmarkStructComplexFailure-8 300000 4136 ns/op 3041 B/op 53 allocs/op
-BenchmarkStructComplexFailureParallel-8 1000000 1855 ns/op 3041 B/op 53 allocs/op
-```
-
-Complementary Software
-----------------------
-
-Here is a list of software that complements using this library either pre or post validation.
-
-* [form](https://github.com/go-playground/form) - Decodes url.Values into Go value(s) and Encodes Go value(s) into url.Values. Dual Array and Full map support.
-* [mold](https://github.com/go-playground/mold) - A general library to help modify or set data within data structures and other objects
-
-How to Contribute
-------
-
-Make a pull request...
-
-License
-------
-Distributed under MIT License, please see license file within the code for more details.
diff --git a/vendor/gopkg.in/go-playground/validator.v9/benchmarks_test.go b/vendor/gopkg.in/go-playground/validator.v9/benchmarks_test.go
deleted file mode 100644
index 5ac871f..0000000
--- a/vendor/gopkg.in/go-playground/validator.v9/benchmarks_test.go
+++ /dev/null
@@ -1,1210 +0,0 @@
-package validator
-
-import (
- "bytes"
- sql "database/sql/driver"
- "testing"
- "time"
-)
-
-func BenchmarkFieldSuccess(b *testing.B) {
-
- validate := New()
-
- s := "1"
-
- b.ResetTimer()
- for n := 0; n < b.N; n++ {
- validate.Var(&s, "len=1")
- }
-}
-
-func BenchmarkFieldSuccessParallel(b *testing.B) {
-
- validate := New()
-
- s := "1"
-
- b.ResetTimer()
- b.RunParallel(func(pb *testing.PB) {
- for pb.Next() {
- validate.Var(&s, "len=1")
- }
- })
-}
-
-func BenchmarkFieldFailure(b *testing.B) {
-
- validate := New()
-
- s := "12"
-
- b.ResetTimer()
- for n := 0; n < b.N; n++ {
- validate.Var(&s, "len=1")
- }
-}
-
-func BenchmarkFieldFailureParallel(b *testing.B) {
-
- validate := New()
-
- s := "12"
-
- b.ResetTimer()
- b.RunParallel(func(pb *testing.PB) {
- for pb.Next() {
- validate.Var(&s, "len=1")
- }
- })
-}
-
-func BenchmarkFieldArrayDiveSuccess(b *testing.B) {
-
- validate := New()
-
- m := []string{"val1", "val2", "val3"}
-
- b.ResetTimer()
-
- for n := 0; n < b.N; n++ {
- validate.Var(m, "required,dive,required")
- }
-}
-
-func BenchmarkFieldArrayDiveSuccessParallel(b *testing.B) {
-
- validate := New()
-
- m := []string{"val1", "val2", "val3"}
-
- b.ResetTimer()
- b.RunParallel(func(pb *testing.PB) {
- for pb.Next() {
- validate.Var(m, "required,dive,required")
- }
- })
-}
-
-func BenchmarkFieldArrayDiveFailure(b *testing.B) {
-
- validate := New()
-
- m := []string{"val1", "", "val3"}
-
- b.ResetTimer()
- for n := 0; n < b.N; n++ {
- validate.Var(m, "required,dive,required")
- }
-}
-
-func BenchmarkFieldArrayDiveFailureParallel(b *testing.B) {
-
- validate := New()
-
- m := []string{"val1", "", "val3"}
-
- b.ResetTimer()
- b.RunParallel(func(pb *testing.PB) {
- for pb.Next() {
- validate.Var(m, "required,dive,required")
- }
- })
-}
-
-func BenchmarkFieldMapDiveSuccess(b *testing.B) {
-
- validate := New()
-
- m := map[string]string{"val1": "val1", "val2": "val2", "val3": "val3"}
-
- b.ResetTimer()
-
- for n := 0; n < b.N; n++ {
- validate.Var(m, "required,dive,required")
- }
-}
-
-func BenchmarkFieldMapDiveSuccessParallel(b *testing.B) {
-
- validate := New()
-
- m := map[string]string{"val1": "val1", "val2": "val2", "val3": "val3"}
-
- b.ResetTimer()
- b.RunParallel(func(pb *testing.PB) {
- for pb.Next() {
- validate.Var(m, "required,dive,required")
- }
- })
-}
-
-func BenchmarkFieldMapDiveFailure(b *testing.B) {
-
- validate := New()
-
- m := map[string]string{"": "", "val3": "val3"}
-
- b.ResetTimer()
- for n := 0; n < b.N; n++ {
- validate.Var(m, "required,dive,required")
- }
-}
-
-func BenchmarkFieldMapDiveFailureParallel(b *testing.B) {
-
- validate := New()
-
- m := map[string]string{"": "", "val3": "val3"}
-
- b.ResetTimer()
- b.RunParallel(func(pb *testing.PB) {
- for pb.Next() {
- validate.Var(m, "required,dive,required")
- }
- })
-}
-
-func BenchmarkFieldMapDiveWithKeysSuccess(b *testing.B) {
-
- validate := New()
-
- m := map[string]string{"val1": "val1", "val2": "val2", "val3": "val3"}
-
- b.ResetTimer()
-
- for n := 0; n < b.N; n++ {
- validate.Var(m, "required,dive,keys,required,endkeys,required")
- }
-}
-
-func BenchmarkFieldMapDiveWithKeysSuccessParallel(b *testing.B) {
-
- validate := New()
-
- m := map[string]string{"val1": "val1", "val2": "val2", "val3": "val3"}
-
- b.ResetTimer()
- b.RunParallel(func(pb *testing.PB) {
- for pb.Next() {
- validate.Var(m, "required,dive,keys,required,endkeys,required")
- }
- })
-}
-
-func BenchmarkFieldMapDiveWithKeysFailure(b *testing.B) {
-
- validate := New()
-
- m := map[string]string{"": "", "val3": "val3"}
-
- b.ResetTimer()
- for n := 0; n < b.N; n++ {
- validate.Var(m, "required,dive,keys,required,endkeys,required")
- }
-}
-
-func BenchmarkFieldMapDiveWithKeysFailureParallel(b *testing.B) {
-
- validate := New()
-
- m := map[string]string{"": "", "val3": "val3"}
-
- b.ResetTimer()
- b.RunParallel(func(pb *testing.PB) {
- for pb.Next() {
- validate.Var(m, "required,dive,keys,required,endkeys,required")
- }
- })
-}
-
-func BenchmarkFieldCustomTypeSuccess(b *testing.B) {
-
- validate := New()
- validate.RegisterCustomTypeFunc(ValidateValuerType, (*sql.Valuer)(nil), valuer{})
-
- val := valuer{
- Name: "1",
- }
-
- b.ResetTimer()
- for n := 0; n < b.N; n++ {
- validate.Var(val, "len=1")
- }
-}
-
-func BenchmarkFieldCustomTypeSuccessParallel(b *testing.B) {
-
- validate := New()
- validate.RegisterCustomTypeFunc(ValidateValuerType, (*sql.Valuer)(nil), valuer{})
-
- val := valuer{
- Name: "1",
- }
-
- b.ResetTimer()
- b.RunParallel(func(pb *testing.PB) {
- for pb.Next() {
- validate.Var(val, "len=1")
- }
- })
-}
-
-func BenchmarkFieldCustomTypeFailure(b *testing.B) {
-
- validate := New()
- validate.RegisterCustomTypeFunc(ValidateValuerType, (*sql.Valuer)(nil), valuer{})
-
- val := valuer{}
-
- b.ResetTimer()
- for n := 0; n < b.N; n++ {
- validate.Var(val, "len=1")
- }
-}
-
-func BenchmarkFieldCustomTypeFailureParallel(b *testing.B) {
-
- validate := New()
- validate.RegisterCustomTypeFunc(ValidateValuerType, (*sql.Valuer)(nil), valuer{})
-
- val := valuer{}
-
- b.ResetTimer()
- b.RunParallel(func(pb *testing.PB) {
- for pb.Next() {
- validate.Var(val, "len=1")
- }
- })
-}
-
-func BenchmarkFieldOrTagSuccess(b *testing.B) {
-
- validate := New()
-
- s := "rgba(0,0,0,1)"
-
- b.ResetTimer()
- for n := 0; n < b.N; n++ {
- validate.Var(s, "rgb|rgba")
- }
-}
-
-func BenchmarkFieldOrTagSuccessParallel(b *testing.B) {
-
- validate := New()
-
- s := "rgba(0,0,0,1)"
-
- b.ResetTimer()
- b.RunParallel(func(pb *testing.PB) {
- for pb.Next() {
- validate.Var(s, "rgb|rgba")
- }
- })
-}
-
-func BenchmarkFieldOrTagFailure(b *testing.B) {
-
- validate := New()
-
- s := "#000"
-
- b.ResetTimer()
- for n := 0; n < b.N; n++ {
- validate.Var(s, "rgb|rgba")
- }
-}
-
-func BenchmarkFieldOrTagFailureParallel(b *testing.B) {
-
- validate := New()
-
- s := "#000"
-
- b.ResetTimer()
- b.RunParallel(func(pb *testing.PB) {
- for pb.Next() {
- validate.Var(s, "rgb|rgba")
- }
- })
-}
-
-func BenchmarkStructLevelValidationSuccess(b *testing.B) {
-
- validate := New()
- validate.RegisterStructValidation(StructValidationTestStructSuccess, TestStruct{})
-
- tst := TestStruct{
- String: "good value",
- }
-
- b.ResetTimer()
- for n := 0; n < b.N; n++ {
- validate.Struct(tst)
- }
-}
-
-func BenchmarkStructLevelValidationSuccessParallel(b *testing.B) {
-
- validate := New()
- validate.RegisterStructValidation(StructValidationTestStructSuccess, TestStruct{})
-
- tst := TestStruct{
- String: "good value",
- }
-
- b.ResetTimer()
- b.RunParallel(func(pb *testing.PB) {
- for pb.Next() {
- validate.Struct(tst)
- }
- })
-}
-
-func BenchmarkStructLevelValidationFailure(b *testing.B) {
-
- validate := New()
- validate.RegisterStructValidation(StructValidationTestStruct, TestStruct{})
-
- tst := TestStruct{
- String: "good value",
- }
-
- b.ResetTimer()
- for n := 0; n < b.N; n++ {
- validate.Struct(tst)
- }
-}
-
-func BenchmarkStructLevelValidationFailureParallel(b *testing.B) {
-
- validate := New()
- validate.RegisterStructValidation(StructValidationTestStruct, TestStruct{})
-
- tst := TestStruct{
- String: "good value",
- }
-
- b.ResetTimer()
- b.RunParallel(func(pb *testing.PB) {
- for pb.Next() {
- validate.Struct(tst)
- }
- })
-}
-
-func BenchmarkStructSimpleCustomTypeSuccess(b *testing.B) {
-
- validate := New()
- validate.RegisterCustomTypeFunc(ValidateValuerType, (*sql.Valuer)(nil), valuer{})
-
- val := valuer{
- Name: "1",
- }
-
- type Foo struct {
- Valuer valuer `validate:"len=1"`
- IntValue int `validate:"min=5,max=10"`
- }
-
- validFoo := &Foo{Valuer: val, IntValue: 7}
-
- b.ResetTimer()
- for n := 0; n < b.N; n++ {
- validate.Struct(validFoo)
- }
-}
-
-func BenchmarkStructSimpleCustomTypeSuccessParallel(b *testing.B) {
-
- validate := New()
- validate.RegisterCustomTypeFunc(ValidateValuerType, (*sql.Valuer)(nil), valuer{})
-
- val := valuer{
- Name: "1",
- }
-
- type Foo struct {
- Valuer valuer `validate:"len=1"`
- IntValue int `validate:"min=5,max=10"`
- }
-
- validFoo := &Foo{Valuer: val, IntValue: 7}
-
- b.ResetTimer()
- b.RunParallel(func(pb *testing.PB) {
- for pb.Next() {
- validate.Struct(validFoo)
- }
- })
-}
-
-func BenchmarkStructSimpleCustomTypeFailure(b *testing.B) {
-
- validate := New()
- validate.RegisterCustomTypeFunc(ValidateValuerType, (*sql.Valuer)(nil), valuer{})
-
- val := valuer{}
-
- type Foo struct {
- Valuer valuer `validate:"len=1"`
- IntValue int `validate:"min=5,max=10"`
- }
-
- validFoo := &Foo{Valuer: val, IntValue: 3}
-
- b.ResetTimer()
- for n := 0; n < b.N; n++ {
- validate.Struct(validFoo)
- }
-}
-
-func BenchmarkStructSimpleCustomTypeFailureParallel(b *testing.B) {
-
- validate := New()
- validate.RegisterCustomTypeFunc(ValidateValuerType, (*sql.Valuer)(nil), valuer{})
-
- val := valuer{}
-
- type Foo struct {
- Valuer valuer `validate:"len=1"`
- IntValue int `validate:"min=5,max=10"`
- }
-
- validFoo := &Foo{Valuer: val, IntValue: 3}
-
- b.ResetTimer()
- b.RunParallel(func(pb *testing.PB) {
- for pb.Next() {
- validate.Struct(validate.Struct(validFoo))
- }
- })
-}
-
-func BenchmarkStructFilteredSuccess(b *testing.B) {
-
- validate := New()
-
- type Test struct {
- Name string `validate:"required"`
- NickName string `validate:"required"`
- }
-
- test := &Test{
- Name: "Joey Bloggs",
- }
-
- byts := []byte("Name")
-
- fn := func(ns []byte) bool {
- return !bytes.HasSuffix(ns, byts)
- }
-
- b.ResetTimer()
- for n := 0; n < b.N; n++ {
- validate.StructFiltered(test, fn)
- }
-}
-
-func BenchmarkStructFilteredSuccessParallel(b *testing.B) {
-
- validate := New()
-
- type Test struct {
- Name string `validate:"required"`
- NickName string `validate:"required"`
- }
-
- test := &Test{
- Name: "Joey Bloggs",
- }
-
- byts := []byte("Name")
-
- fn := func(ns []byte) bool {
- return !bytes.HasSuffix(ns, byts)
- }
-
- b.ResetTimer()
- b.RunParallel(func(pb *testing.PB) {
- for pb.Next() {
- validate.StructFiltered(test, fn)
- }
- })
-}
-
-func BenchmarkStructFilteredFailure(b *testing.B) {
-
- validate := New()
-
- type Test struct {
- Name string `validate:"required"`
- NickName string `validate:"required"`
- }
-
- test := &Test{
- Name: "Joey Bloggs",
- }
-
- byts := []byte("NickName")
-
- fn := func(ns []byte) bool {
- return !bytes.HasSuffix(ns, byts)
- }
-
- b.ResetTimer()
- for n := 0; n < b.N; n++ {
- validate.StructFiltered(test, fn)
- }
-}
-
-func BenchmarkStructFilteredFailureParallel(b *testing.B) {
-
- validate := New()
-
- type Test struct {
- Name string `validate:"required"`
- NickName string `validate:"required"`
- }
-
- test := &Test{
- Name: "Joey Bloggs",
- }
-
- byts := []byte("NickName")
-
- fn := func(ns []byte) bool {
- return !bytes.HasSuffix(ns, byts)
- }
-
- b.ResetTimer()
- b.RunParallel(func(pb *testing.PB) {
- for pb.Next() {
- validate.StructFiltered(test, fn)
- }
- })
-}
-
-func BenchmarkStructPartialSuccess(b *testing.B) {
-
- validate := New()
-
- type Test struct {
- Name string `validate:"required"`
- NickName string `validate:"required"`
- }
-
- test := &Test{
- Name: "Joey Bloggs",
- }
-
- b.ResetTimer()
- for n := 0; n < b.N; n++ {
- validate.StructPartial(test, "Name")
- }
-}
-
-func BenchmarkStructPartialSuccessParallel(b *testing.B) {
-
- validate := New()
-
- type Test struct {
- Name string `validate:"required"`
- NickName string `validate:"required"`
- }
-
- test := &Test{
- Name: "Joey Bloggs",
- }
-
- b.ResetTimer()
- b.RunParallel(func(pb *testing.PB) {
- for pb.Next() {
- validate.StructPartial(test, "Name")
- }
- })
-}
-
-func BenchmarkStructPartialFailure(b *testing.B) {
-
- validate := New()
-
- type Test struct {
- Name string `validate:"required"`
- NickName string `validate:"required"`
- }
-
- test := &Test{
- Name: "Joey Bloggs",
- }
-
- b.ResetTimer()
- for n := 0; n < b.N; n++ {
- validate.StructPartial(test, "NickName")
- }
-}
-
-func BenchmarkStructPartialFailureParallel(b *testing.B) {
-
- validate := New()
-
- type Test struct {
- Name string `validate:"required"`
- NickName string `validate:"required"`
- }
-
- test := &Test{
- Name: "Joey Bloggs",
- }
-
- b.ResetTimer()
- b.RunParallel(func(pb *testing.PB) {
- for pb.Next() {
- validate.StructPartial(test, "NickName")
- }
- })
-}
-
-func BenchmarkStructExceptSuccess(b *testing.B) {
-
- validate := New()
-
- type Test struct {
- Name string `validate:"required"`
- NickName string `validate:"required"`
- }
-
- test := &Test{
- Name: "Joey Bloggs",
- }
-
- b.ResetTimer()
- for n := 0; n < b.N; n++ {
- validate.StructExcept(test, "Nickname")
- }
-}
-
-func BenchmarkStructExceptSuccessParallel(b *testing.B) {
-
- validate := New()
-
- type Test struct {
- Name string `validate:"required"`
- NickName string `validate:"required"`
- }
-
- test := &Test{
- Name: "Joey Bloggs",
- }
-
- b.ResetTimer()
- b.RunParallel(func(pb *testing.PB) {
- for pb.Next() {
- validate.StructExcept(test, "NickName")
- }
- })
-}
-
-func BenchmarkStructExceptFailure(b *testing.B) {
-
- validate := New()
-
- type Test struct {
- Name string `validate:"required"`
- NickName string `validate:"required"`
- }
-
- test := &Test{
- Name: "Joey Bloggs",
- }
-
- b.ResetTimer()
- for n := 0; n < b.N; n++ {
- validate.StructExcept(test, "Name")
- }
-}
-
-func BenchmarkStructExceptFailureParallel(b *testing.B) {
-
- validate := New()
-
- type Test struct {
- Name string `validate:"required"`
- NickName string `validate:"required"`
- }
-
- test := &Test{
- Name: "Joey Bloggs",
- }
-
- b.ResetTimer()
- b.RunParallel(func(pb *testing.PB) {
- for pb.Next() {
- validate.StructExcept(test, "Name")
- }
- })
-}
-
-func BenchmarkStructSimpleCrossFieldSuccess(b *testing.B) {
-
- validate := New()
-
- type Test struct {
- Start time.Time
- End time.Time `validate:"gtfield=Start"`
- }
-
- now := time.Now().UTC()
- then := now.Add(time.Hour * 5)
-
- test := &Test{
- Start: now,
- End: then,
- }
-
- b.ResetTimer()
- for n := 0; n < b.N; n++ {
- validate.Struct(test)
- }
-}
-
-func BenchmarkStructSimpleCrossFieldSuccessParallel(b *testing.B) {
-
- validate := New()
-
- type Test struct {
- Start time.Time
- End time.Time `validate:"gtfield=Start"`
- }
-
- now := time.Now().UTC()
- then := now.Add(time.Hour * 5)
-
- test := &Test{
- Start: now,
- End: then,
- }
-
- b.ResetTimer()
- b.RunParallel(func(pb *testing.PB) {
- for pb.Next() {
- validate.Struct(test)
- }
- })
-}
-
-func BenchmarkStructSimpleCrossFieldFailure(b *testing.B) {
-
- validate := New()
-
- type Test struct {
- Start time.Time
- End time.Time `validate:"gtfield=Start"`
- }
-
- now := time.Now().UTC()
- then := now.Add(time.Hour * -5)
-
- test := &Test{
- Start: now,
- End: then,
- }
-
- b.ResetTimer()
- for n := 0; n < b.N; n++ {
- validate.Struct(test)
- }
-}
-
-func BenchmarkStructSimpleCrossFieldFailureParallel(b *testing.B) {
-
- validate := New()
-
- type Test struct {
- Start time.Time
- End time.Time `validate:"gtfield=Start"`
- }
-
- now := time.Now().UTC()
- then := now.Add(time.Hour * -5)
-
- test := &Test{
- Start: now,
- End: then,
- }
- b.ResetTimer()
- b.RunParallel(func(pb *testing.PB) {
- for pb.Next() {
- validate.Struct(test)
- }
- })
-}
-
-func BenchmarkStructSimpleCrossStructCrossFieldSuccess(b *testing.B) {
-
- validate := New()
-
- type Inner struct {
- Start time.Time
- }
-
- type Outer struct {
- Inner *Inner
- CreatedAt time.Time `validate:"eqcsfield=Inner.Start"`
- }
-
- now := time.Now().UTC()
-
- inner := &Inner{
- Start: now,
- }
-
- outer := &Outer{
- Inner: inner,
- CreatedAt: now,
- }
-
- b.ResetTimer()
- for n := 0; n < b.N; n++ {
- validate.Struct(outer)
- }
-}
-
-func BenchmarkStructSimpleCrossStructCrossFieldSuccessParallel(b *testing.B) {
-
- validate := New()
-
- type Inner struct {
- Start time.Time
- }
-
- type Outer struct {
- Inner *Inner
- CreatedAt time.Time `validate:"eqcsfield=Inner.Start"`
- }
-
- now := time.Now().UTC()
-
- inner := &Inner{
- Start: now,
- }
-
- outer := &Outer{
- Inner: inner,
- CreatedAt: now,
- }
-
- b.ResetTimer()
- b.RunParallel(func(pb *testing.PB) {
- for pb.Next() {
- validate.Struct(outer)
- }
- })
-}
-
-func BenchmarkStructSimpleCrossStructCrossFieldFailure(b *testing.B) {
-
- validate := New()
-
- type Inner struct {
- Start time.Time
- }
-
- type Outer struct {
- Inner *Inner
- CreatedAt time.Time `validate:"eqcsfield=Inner.Start"`
- }
-
- now := time.Now().UTC()
- then := now.Add(time.Hour * 5)
-
- inner := &Inner{
- Start: then,
- }
-
- outer := &Outer{
- Inner: inner,
- CreatedAt: now,
- }
-
- b.ResetTimer()
- for n := 0; n < b.N; n++ {
- validate.Struct(outer)
- }
-}
-
-func BenchmarkStructSimpleCrossStructCrossFieldFailureParallel(b *testing.B) {
-
- validate := New()
-
- type Inner struct {
- Start time.Time
- }
-
- type Outer struct {
- Inner *Inner
- CreatedAt time.Time `validate:"eqcsfield=Inner.Start"`
- }
-
- now := time.Now().UTC()
- then := now.Add(time.Hour * 5)
-
- inner := &Inner{
- Start: then,
- }
-
- outer := &Outer{
- Inner: inner,
- CreatedAt: now,
- }
-
- b.ResetTimer()
- b.RunParallel(func(pb *testing.PB) {
- for pb.Next() {
- validate.Struct(outer)
- }
- })
-}
-
-func BenchmarkStructSimpleSuccess(b *testing.B) {
-
- validate := New()
-
- type Foo struct {
- StringValue string `validate:"min=5,max=10"`
- IntValue int `validate:"min=5,max=10"`
- }
-
- validFoo := &Foo{StringValue: "Foobar", IntValue: 7}
-
- b.ResetTimer()
- for n := 0; n < b.N; n++ {
- validate.Struct(validFoo)
- }
-}
-
-func BenchmarkStructSimpleSuccessParallel(b *testing.B) {
-
- validate := New()
-
- type Foo struct {
- StringValue string `validate:"min=5,max=10"`
- IntValue int `validate:"min=5,max=10"`
- }
-
- validFoo := &Foo{StringValue: "Foobar", IntValue: 7}
-
- b.ResetTimer()
- b.RunParallel(func(pb *testing.PB) {
- for pb.Next() {
- validate.Struct(validFoo)
- }
- })
-}
-
-func BenchmarkStructSimpleFailure(b *testing.B) {
-
- validate := New()
-
- type Foo struct {
- StringValue string `validate:"min=5,max=10"`
- IntValue int `validate:"min=5,max=10"`
- }
-
- invalidFoo := &Foo{StringValue: "Fo", IntValue: 3}
-
- b.ResetTimer()
- for n := 0; n < b.N; n++ {
- validate.Struct(invalidFoo)
- }
-}
-
-func BenchmarkStructSimpleFailureParallel(b *testing.B) {
-
- validate := New()
-
- type Foo struct {
- StringValue string `validate:"min=5,max=10"`
- IntValue int `validate:"min=5,max=10"`
- }
-
- invalidFoo := &Foo{StringValue: "Fo", IntValue: 3}
-
- b.ResetTimer()
- b.RunParallel(func(pb *testing.PB) {
- for pb.Next() {
- validate.Struct(invalidFoo)
- }
- })
-}
-
-func BenchmarkStructComplexSuccess(b *testing.B) {
-
- validate := New()
-
- tSuccess := &TestString{
- Required: "Required",
- Len: "length==10",
- Min: "min=1",
- Max: "1234567890",
- MinMax: "12345",
- Lt: "012345678",
- Lte: "0123456789",
- Gt: "01234567890",
- Gte: "0123456789",
- OmitEmpty: "",
- Sub: &SubTest{
- Test: "1",
- },
- SubIgnore: &SubTest{
- Test: "",
- },
- Anonymous: struct {
- A string `validate:"required"`
- }{
- A: "1",
- },
- Iface: &Impl{
- F: "123",
- },
- }
-
- b.ResetTimer()
- for n := 0; n < b.N; n++ {
- validate.Struct(tSuccess)
- }
-}
-
-func BenchmarkStructComplexSuccessParallel(b *testing.B) {
-
- validate := New()
-
- tSuccess := &TestString{
- Required: "Required",
- Len: "length==10",
- Min: "min=1",
- Max: "1234567890",
- MinMax: "12345",
- Lt: "012345678",
- Lte: "0123456789",
- Gt: "01234567890",
- Gte: "0123456789",
- OmitEmpty: "",
- Sub: &SubTest{
- Test: "1",
- },
- SubIgnore: &SubTest{
- Test: "",
- },
- Anonymous: struct {
- A string `validate:"required"`
- }{
- A: "1",
- },
- Iface: &Impl{
- F: "123",
- },
- }
-
- b.ResetTimer()
- b.RunParallel(func(pb *testing.PB) {
- for pb.Next() {
- validate.Struct(tSuccess)
- }
- })
-}
-
-func BenchmarkStructComplexFailure(b *testing.B) {
-
- validate := New()
-
- tFail := &TestString{
- Required: "",
- Len: "",
- Min: "",
- Max: "12345678901",
- MinMax: "",
- Lt: "0123456789",
- Lte: "01234567890",
- Gt: "1",
- Gte: "1",
- OmitEmpty: "12345678901",
- Sub: &SubTest{
- Test: "",
- },
- Anonymous: struct {
- A string `validate:"required"`
- }{
- A: "",
- },
- Iface: &Impl{
- F: "12",
- },
- }
-
- b.ResetTimer()
- for n := 0; n < b.N; n++ {
- validate.Struct(tFail)
- }
-}
-
-func BenchmarkStructComplexFailureParallel(b *testing.B) {
-
- validate := New()
-
- tFail := &TestString{
- Required: "",
- Len: "",
- Min: "",
- Max: "12345678901",
- MinMax: "",
- Lt: "0123456789",
- Lte: "01234567890",
- Gt: "1",
- Gte: "1",
- OmitEmpty: "12345678901",
- Sub: &SubTest{
- Test: "",
- },
- Anonymous: struct {
- A string `validate:"required"`
- }{
- A: "",
- },
- Iface: &Impl{
- F: "12",
- },
- }
-
- b.ResetTimer()
- b.RunParallel(func(pb *testing.PB) {
- for pb.Next() {
- validate.Struct(tFail)
- }
- })
-}
-
-type TestOneof struct {
- Color string `validate:"oneof=red green"`
-}
-
-func BenchmarkOneof(b *testing.B) {
- w := &TestOneof{Color: "green"}
- val := New()
- for i := 0; i < b.N; i++ {
- val.Struct(w)
- }
-}
-
-func BenchmarkOneofParallel(b *testing.B) {
- w := &TestOneof{Color: "green"}
- val := New()
-
- b.ResetTimer()
- b.RunParallel(func(pb *testing.PB) {
- for pb.Next() {
- val.Struct(w)
- }
- })
-}
diff --git a/vendor/gopkg.in/go-playground/validator.v9/examples_test.go b/vendor/gopkg.in/go-playground/validator.v9/examples_test.go
deleted file mode 100644
index 3f4df7e..0000000
--- a/vendor/gopkg.in/go-playground/validator.v9/examples_test.go
+++ /dev/null
@@ -1,83 +0,0 @@
-package validator_test
-
-// import (
-// "fmt"
-
-// "gopkg.in/go-playground/validator.v8"
-// )
-
-// func ExampleValidate_new() {
-// config := &validator.Config{TagName: "validate"}
-
-// validator.New(config)
-// }
-
-// func ExampleValidate_field() {
-// // This should be stored somewhere globally
-// var validate *validator.Validate
-
-// config := &validator.Config{TagName: "validate"}
-
-// validate = validator.New(config)
-
-// i := 0
-// errs := validate.Field(i, "gt=1,lte=10")
-// err := errs.(validator.ValidationErrors)[""]
-// fmt.Println(err.Field)
-// fmt.Println(err.Tag)
-// fmt.Println(err.Kind) // NOTE: Kind and Type can be different i.e. time Kind=struct and Type=time.Time
-// fmt.Println(err.Type)
-// fmt.Println(err.Param)
-// fmt.Println(err.Value)
-// //Output:
-// //
-// //gt
-// //int
-// //int
-// //1
-// //0
-// }
-
-// func ExampleValidate_struct() {
-// // This should be stored somewhere globally
-// var validate *validator.Validate
-
-// config := &validator.Config{TagName: "validate"}
-
-// validate = validator.New(config)
-
-// type ContactInformation struct {
-// Phone string `validate:"required"`
-// Street string `validate:"required"`
-// City string `validate:"required"`
-// }
-
-// type User struct {
-// Name string `validate:"required,excludesall=!@#$%^&*()_+-=:;?/0x2C"` // 0x2C = comma (,)
-// Age int8 `validate:"required,gt=0,lt=150"`
-// Email string `validate:"email"`
-// ContactInformation []*ContactInformation
-// }
-
-// contactInfo := &ContactInformation{
-// Street: "26 Here Blvd.",
-// City: "Paradeso",
-// }
-
-// user := &User{
-// Name: "Joey Bloggs",
-// Age: 31,
-// Email: "joeybloggs@gmail.com",
-// ContactInformation: []*ContactInformation{contactInfo},
-// }
-
-// errs := validate.Struct(user)
-// for _, v := range errs.(validator.ValidationErrors) {
-// fmt.Println(v.Field) // Phone
-// fmt.Println(v.Tag) // required
-// //... and so forth
-// //Output:
-// //Phone
-// //required
-// }
-// }
diff --git a/vendor/gopkg.in/go-playground/validator.v9/logo.png b/vendor/gopkg.in/go-playground/validator.v9/logo.png
deleted file mode 100644
index 355000f..0000000
--- a/vendor/gopkg.in/go-playground/validator.v9/logo.png
+++ /dev/null
Binary files differ
diff --git a/vendor/gopkg.in/go-playground/validator.v9/validator_test.go b/vendor/gopkg.in/go-playground/validator.v9/validator_test.go
deleted file mode 100644
index 9600d0f..0000000
--- a/vendor/gopkg.in/go-playground/validator.v9/validator_test.go
+++ /dev/null
@@ -1,7723 +0,0 @@
-package validator
-
-import (
- "bytes"
- "context"
- "database/sql"
- "database/sql/driver"
- "encoding/json"
- "fmt"
- "reflect"
- "strings"
- "testing"
- "time"
-
- "github.com/go-playground/locales/en"
- "github.com/go-playground/locales/fr"
- "github.com/go-playground/locales/nl"
- ut "github.com/go-playground/universal-translator"
- . "gopkg.in/go-playground/assert.v1"
-)
-
-// NOTES:
-// - Run "go test" to run tests
-// - Run "gocov test | gocov report" to report on test converage by file
-// - Run "gocov test | gocov annotate -" to report on all code and functions, those ,marked with "MISS" were never called
-//
-// or
-//
-// -- may be a good idea to change to output path to somewherelike /tmp
-// go test -coverprofile cover.out && go tool cover -html=cover.out -o cover.html
-//
-//
-// go test -cpuprofile cpu.out
-// ./validator.test -test.bench=. -test.cpuprofile=cpu.prof
-// go tool pprof validator.test cpu.prof
-//
-//
-// go test -memprofile mem.out
-
-type I interface {
- Foo() string
-}
-
-type Impl struct {
- F string `validate:"len=3"`
-}
-
-func (i *Impl) Foo() string {
- return i.F
-}
-
-type SubTest struct {
- Test string `validate:"required"`
-}
-
-type TestInterface struct {
- Iface I
-}
-
-type TestString struct {
- BlankTag string `validate:""`
- Required string `validate:"required"`
- Len string `validate:"len=10"`
- Min string `validate:"min=1"`
- Max string `validate:"max=10"`
- MinMax string `validate:"min=1,max=10"`
- Lt string `validate:"lt=10"`
- Lte string `validate:"lte=10"`
- Gt string `validate:"gt=10"`
- Gte string `validate:"gte=10"`
- OmitEmpty string `validate:"omitempty,min=1,max=10"`
- Sub *SubTest
- SubIgnore *SubTest `validate:"-"`
- Anonymous struct {
- A string `validate:"required"`
- }
- Iface I
-}
-
-type TestUint64 struct {
- Required uint64 `validate:"required"`
- Len uint64 `validate:"len=10"`
- Min uint64 `validate:"min=1"`
- Max uint64 `validate:"max=10"`
- MinMax uint64 `validate:"min=1,max=10"`
- OmitEmpty uint64 `validate:"omitempty,min=1,max=10"`
-}
-
-type TestFloat64 struct {
- Required float64 `validate:"required"`
- Len float64 `validate:"len=10"`
- Min float64 `validate:"min=1"`
- Max float64 `validate:"max=10"`
- MinMax float64 `validate:"min=1,max=10"`
- Lte float64 `validate:"lte=10"`
- OmitEmpty float64 `validate:"omitempty,min=1,max=10"`
-}
-
-type TestSlice struct {
- Required []int `validate:"required"`
- Len []int `validate:"len=10"`
- Min []int `validate:"min=1"`
- Max []int `validate:"max=10"`
- MinMax []int `validate:"min=1,max=10"`
- OmitEmpty []int `validate:"omitempty,min=1,max=10"`
-}
-
-func AssertError(t *testing.T, err error, nsKey, structNsKey, field, structField, expectedTag string) {
-
- errs := err.(ValidationErrors)
-
- found := false
- var fe FieldError
-
- for i := 0; i < len(errs); i++ {
- if errs[i].Namespace() == nsKey && errs[i].StructNamespace() == structNsKey {
- found = true
- fe = errs[i]
- break
- }
- }
-
- EqualSkip(t, 2, found, true)
- NotEqualSkip(t, 2, fe, nil)
- EqualSkip(t, 2, fe.Field(), field)
- EqualSkip(t, 2, fe.StructField(), structField)
- EqualSkip(t, 2, fe.Tag(), expectedTag)
-}
-
-func AssertDeepError(t *testing.T, err error, nsKey, structNsKey, field, structField, expectedTag, actualTag string) {
- errs := err.(ValidationErrors)
-
- found := false
- var fe FieldError
-
- for i := 0; i < len(errs); i++ {
- if errs[i].Namespace() == nsKey && errs[i].StructNamespace() == structNsKey && errs[i].Tag() == expectedTag && errs[i].ActualTag() == actualTag {
- found = true
- fe = errs[i]
- break
- }
- }
-
- EqualSkip(t, 2, found, true)
- NotEqualSkip(t, 2, fe, nil)
- EqualSkip(t, 2, fe.Field(), field)
- EqualSkip(t, 2, fe.StructField(), structField)
-}
-
-func getError(err error, nsKey, structNsKey string) FieldError {
-
- errs := err.(ValidationErrors)
-
- var fe FieldError
-
- for i := 0; i < len(errs); i++ {
- if errs[i].Namespace() == nsKey && errs[i].StructNamespace() == structNsKey {
- fe = errs[i]
- break
- }
- }
-
- return fe
-}
-
-type valuer struct {
- Name string
-}
-
-func (v valuer) Value() (driver.Value, error) {
-
- if v.Name == "errorme" {
- panic("SQL Driver Valuer error: some kind of error")
- // return nil, errors.New("some kind of error")
- }
-
- if len(v.Name) == 0 {
- return nil, nil
- }
-
- return v.Name, nil
-}
-
-type MadeUpCustomType struct {
- FirstName string
- LastName string
-}
-
-func ValidateCustomType(field reflect.Value) interface{} {
-
- if cust, ok := field.Interface().(MadeUpCustomType); ok {
-
- if len(cust.FirstName) == 0 || len(cust.LastName) == 0 {
- return ""
- }
-
- return cust.FirstName + " " + cust.LastName
- }
-
- return ""
-}
-
-func OverrideIntTypeForSomeReason(field reflect.Value) interface{} {
-
- if i, ok := field.Interface().(int); ok {
- if i == 1 {
- return "1"
- }
-
- if i == 2 {
- return "12"
- }
- }
-
- return ""
-}
-
-type CustomMadeUpStruct struct {
- MadeUp MadeUpCustomType `validate:"required"`
- OverriddenInt int `validate:"gt=1"`
-}
-
-func ValidateValuerType(field reflect.Value) interface{} {
-
- if valuer, ok := field.Interface().(driver.Valuer); ok {
-
- val, err := valuer.Value()
- if err != nil {
- // handle the error how you want
- return nil
- }
-
- return val
- }
-
- return nil
-}
-
-type TestPartial struct {
- NoTag string
- BlankTag string `validate:""`
- Required string `validate:"required"`
- SubSlice []*SubTest `validate:"required,dive"`
- Sub *SubTest
- SubIgnore *SubTest `validate:"-"`
- Anonymous struct {
- A string `validate:"required"`
- ASubSlice []*SubTest `validate:"required,dive"`
-
- SubAnonStruct []struct {
- Test string `validate:"required"`
- OtherTest string `validate:"required"`
- } `validate:"required,dive"`
- }
-}
-
-type TestStruct struct {
- String string `validate:"required" json:"StringVal"`
-}
-
-func StructValidationTestStructSuccess(sl StructLevel) {
-
- st := sl.Current().Interface().(TestStruct)
-
- if st.String != "good value" {
- sl.ReportError(st.String, "StringVal", "String", "badvalueteststruct", "good value")
- }
-}
-
-func StructValidationTestStruct(sl StructLevel) {
-
- st := sl.Current().Interface().(TestStruct)
-
- if st.String != "bad value" {
- sl.ReportError(st.String, "StringVal", "String", "badvalueteststruct", "bad value")
- }
-}
-
-func StructValidationNoTestStructCustomName(sl StructLevel) {
-
- st := sl.Current().Interface().(TestStruct)
-
- if st.String != "bad value" {
- sl.ReportError(st.String, "String", "", "badvalueteststruct", "bad value")
- }
-}
-
-func StructValidationTestStructInvalid(sl StructLevel) {
-
- st := sl.Current().Interface().(TestStruct)
-
- if st.String != "bad value" {
- sl.ReportError(nil, "StringVal", "String", "badvalueteststruct", "bad value")
- }
-}
-
-func StructValidationTestStructReturnValidationErrors(sl StructLevel) {
-
- s := sl.Current().Interface().(TestStructReturnValidationErrors)
-
- errs := sl.Validator().Struct(s.Inner1.Inner2)
- if errs == nil {
- return
- }
-
- sl.ReportValidationErrors("Inner1.", "Inner1.", errs.(ValidationErrors))
-}
-
-func StructValidationTestStructReturnValidationErrors2(sl StructLevel) {
-
- s := sl.Current().Interface().(TestStructReturnValidationErrors)
-
- errs := sl.Validator().Struct(s.Inner1.Inner2)
- if errs == nil {
- return
- }
-
- sl.ReportValidationErrors("Inner1JSON.", "Inner1.", errs.(ValidationErrors))
-}
-
-type TestStructReturnValidationErrorsInner2 struct {
- String string `validate:"required" json:"JSONString"`
-}
-
-type TestStructReturnValidationErrorsInner1 struct {
- Inner2 *TestStructReturnValidationErrorsInner2
-}
-
-type TestStructReturnValidationErrors struct {
- Inner1 *TestStructReturnValidationErrorsInner1 `json:"Inner1JSON"`
-}
-
-type StructLevelInvalidErr struct {
- Value string
-}
-
-func StructLevelInvalidError(sl StructLevel) {
-
- top := sl.Top().Interface().(StructLevelInvalidErr)
- s := sl.Current().Interface().(StructLevelInvalidErr)
-
- if top.Value == s.Value {
- sl.ReportError(nil, "Value", "Value", "required", "")
- }
-}
-
-func TestStructLevelInvalidError(t *testing.T) {
-
- validate := New()
- validate.RegisterStructValidation(StructLevelInvalidError, StructLevelInvalidErr{})
-
- var test StructLevelInvalidErr
-
- err := validate.Struct(test)
- NotEqual(t, err, nil)
-
- errs, ok := err.(ValidationErrors)
- Equal(t, ok, true)
-
- fe := errs[0]
- Equal(t, fe.Field(), "Value")
- Equal(t, fe.StructField(), "Value")
- Equal(t, fe.Namespace(), "StructLevelInvalidErr.Value")
- Equal(t, fe.StructNamespace(), "StructLevelInvalidErr.Value")
- Equal(t, fe.Tag(), "required")
- Equal(t, fe.ActualTag(), "required")
- Equal(t, fe.Kind(), reflect.Invalid)
- Equal(t, fe.Type(), reflect.TypeOf(nil))
-}
-
-func TestNameNamespace(t *testing.T) {
-
- type Inner2Namespace struct {
- String []string `validate:"dive,required" json:"JSONString"`
- }
-
- type Inner1Namespace struct {
- Inner2 *Inner2Namespace `json:"Inner2JSON"`
- }
-
- type Namespace struct {
- Inner1 *Inner1Namespace `json:"Inner1JSON"`
- }
-
- validate := New()
- validate.RegisterTagNameFunc(func(fld reflect.StructField) string {
- name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0]
-
- if name == "-" {
- return ""
- }
-
- return name
- })
-
- i2 := &Inner2Namespace{String: []string{"ok", "ok", "ok"}}
- i1 := &Inner1Namespace{Inner2: i2}
- ns := &Namespace{Inner1: i1}
-
- errs := validate.Struct(ns)
- Equal(t, errs, nil)
-
- i2.String[1] = ""
-
- errs = validate.Struct(ns)
- NotEqual(t, errs, nil)
-
- ve := errs.(ValidationErrors)
- Equal(t, len(ve), 1)
- AssertError(t, errs, "Namespace.Inner1JSON.Inner2JSON.JSONString[1]", "Namespace.Inner1.Inner2.String[1]", "JSONString[1]", "String[1]", "required")
-
- fe := getError(ve, "Namespace.Inner1JSON.Inner2JSON.JSONString[1]", "Namespace.Inner1.Inner2.String[1]")
- NotEqual(t, fe, nil)
- Equal(t, fe.Field(), "JSONString[1]")
- Equal(t, fe.StructField(), "String[1]")
- Equal(t, fe.Namespace(), "Namespace.Inner1JSON.Inner2JSON.JSONString[1]")
- Equal(t, fe.StructNamespace(), "Namespace.Inner1.Inner2.String[1]")
-}
-
-func TestAnonymous(t *testing.T) {
-
- validate := New()
- validate.RegisterTagNameFunc(func(fld reflect.StructField) string {
- name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0]
-
- if name == "-" {
- return ""
- }
-
- return name
- })
-
- type Test struct {
- Anonymous struct {
- A string `validate:"required" json:"EH"`
- }
- AnonymousB struct {
- B string `validate:"required" json:"BEE"`
- }
- anonymousC struct {
- c string `validate:"required"`
- }
- }
-
- tst := &Test{
- Anonymous: struct {
- A string `validate:"required" json:"EH"`
- }{
- A: "1",
- },
- AnonymousB: struct {
- B string `validate:"required" json:"BEE"`
- }{
- B: "",
- },
- anonymousC: struct {
- c string `validate:"required"`
- }{
- c: "",
- },
- }
-
- err := validate.Struct(tst)
- NotEqual(t, err, nil)
-
- errs := err.(ValidationErrors)
-
- Equal(t, len(errs), 1)
- AssertError(t, errs, "Test.AnonymousB.BEE", "Test.AnonymousB.B", "BEE", "B", "required")
-
- fe := getError(errs, "Test.AnonymousB.BEE", "Test.AnonymousB.B")
- NotEqual(t, fe, nil)
- Equal(t, fe.Field(), "BEE")
- Equal(t, fe.StructField(), "B")
-
- s := struct {
- c string `validate:"required"`
- }{
- c: "",
- }
-
- err = validate.Struct(s)
- Equal(t, err, nil)
-}
-
-func TestAnonymousSameStructDifferentTags(t *testing.T) {
-
- validate := New()
- validate.RegisterTagNameFunc(func(fld reflect.StructField) string {
- name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0]
-
- if name == "-" {
- return ""
- }
-
- return name
- })
-
- type Test struct {
- A interface{}
- }
-
- tst := &Test{
- A: struct {
- A string `validate:"required"`
- }{
- A: "",
- },
- }
-
- err := validate.Struct(tst)
- NotEqual(t, err, nil)
-
- errs := err.(ValidationErrors)
-
- Equal(t, len(errs), 1)
- AssertError(t, errs, "Test.A.A", "Test.A.A", "A", "A", "required")
-
- tst = &Test{
- A: struct {
- A string `validate:"omitempty,required"`
- }{
- A: "",
- },
- }
-
- err = validate.Struct(tst)
- Equal(t, err, nil)
-}
-
-func TestStructLevelReturnValidationErrors(t *testing.T) {
-
- validate := New()
- validate.RegisterStructValidation(StructValidationTestStructReturnValidationErrors, TestStructReturnValidationErrors{})
-
- inner2 := &TestStructReturnValidationErrorsInner2{
- String: "I'm HERE",
- }
-
- inner1 := &TestStructReturnValidationErrorsInner1{
- Inner2: inner2,
- }
-
- val := &TestStructReturnValidationErrors{
- Inner1: inner1,
- }
-
- errs := validate.Struct(val)
- Equal(t, errs, nil)
-
- inner2.String = ""
-
- errs = validate.Struct(val)
- NotEqual(t, errs, nil)
- Equal(t, len(errs.(ValidationErrors)), 2)
- AssertError(t, errs, "TestStructReturnValidationErrors.Inner1.Inner2.String", "TestStructReturnValidationErrors.Inner1.Inner2.String", "String", "String", "required")
- // this is an extra error reported from struct validation
- AssertError(t, errs, "TestStructReturnValidationErrors.Inner1.TestStructReturnValidationErrorsInner2.String", "TestStructReturnValidationErrors.Inner1.TestStructReturnValidationErrorsInner2.String", "String", "String", "required")
-}
-
-func TestStructLevelReturnValidationErrorsWithJSON(t *testing.T) {
-
- validate := New()
- validate.RegisterTagNameFunc(func(fld reflect.StructField) string {
- name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0]
-
- if name == "-" {
- return ""
- }
-
- return name
- })
- validate.RegisterStructValidation(StructValidationTestStructReturnValidationErrors2, TestStructReturnValidationErrors{})
-
- inner2 := &TestStructReturnValidationErrorsInner2{
- String: "I'm HERE",
- }
-
- inner1 := &TestStructReturnValidationErrorsInner1{
- Inner2: inner2,
- }
-
- val := &TestStructReturnValidationErrors{
- Inner1: inner1,
- }
-
- errs := validate.Struct(val)
- Equal(t, errs, nil)
-
- inner2.String = ""
-
- errs = validate.Struct(val)
- NotEqual(t, errs, nil)
- Equal(t, len(errs.(ValidationErrors)), 2)
- AssertError(t, errs, "TestStructReturnValidationErrors.Inner1JSON.Inner2.JSONString", "TestStructReturnValidationErrors.Inner1.Inner2.String", "JSONString", "String", "required")
- // this is an extra error reported from struct validation, it's a badly formatted one, but on purpose
- AssertError(t, errs, "TestStructReturnValidationErrors.Inner1JSON.TestStructReturnValidationErrorsInner2.JSONString", "TestStructReturnValidationErrors.Inner1.TestStructReturnValidationErrorsInner2.String", "JSONString", "String", "required")
-
- fe := getError(errs, "TestStructReturnValidationErrors.Inner1JSON.Inner2.JSONString", "TestStructReturnValidationErrors.Inner1.Inner2.String")
- NotEqual(t, fe, nil)
-
- // check for proper JSON namespace
- Equal(t, fe.Field(), "JSONString")
- Equal(t, fe.StructField(), "String")
- Equal(t, fe.Namespace(), "TestStructReturnValidationErrors.Inner1JSON.Inner2.JSONString")
- Equal(t, fe.StructNamespace(), "TestStructReturnValidationErrors.Inner1.Inner2.String")
-
- fe = getError(errs, "TestStructReturnValidationErrors.Inner1JSON.TestStructReturnValidationErrorsInner2.JSONString", "TestStructReturnValidationErrors.Inner1.TestStructReturnValidationErrorsInner2.String")
- NotEqual(t, fe, nil)
-
- // check for proper JSON namespace
- Equal(t, fe.Field(), "JSONString")
- Equal(t, fe.StructField(), "String")
- Equal(t, fe.Namespace(), "TestStructReturnValidationErrors.Inner1JSON.TestStructReturnValidationErrorsInner2.JSONString")
- Equal(t, fe.StructNamespace(), "TestStructReturnValidationErrors.Inner1.TestStructReturnValidationErrorsInner2.String")
-}
-
-func TestStructLevelValidations(t *testing.T) {
-
- v1 := New()
- v1.RegisterStructValidation(StructValidationTestStruct, TestStruct{})
-
- tst := &TestStruct{
- String: "good value",
- }
-
- errs := v1.Struct(tst)
- NotEqual(t, errs, nil)
- AssertError(t, errs, "TestStruct.StringVal", "TestStruct.String", "StringVal", "String", "badvalueteststruct")
-
- v2 := New()
- v2.RegisterStructValidation(StructValidationNoTestStructCustomName, TestStruct{})
-
- errs = v2.Struct(tst)
- NotEqual(t, errs, nil)
- AssertError(t, errs, "TestStruct.String", "TestStruct.String", "String", "String", "badvalueteststruct")
-
- v3 := New()
- v3.RegisterStructValidation(StructValidationTestStructInvalid, TestStruct{})
-
- errs = v3.Struct(tst)
- NotEqual(t, errs, nil)
- AssertError(t, errs, "TestStruct.StringVal", "TestStruct.String", "StringVal", "String", "badvalueteststruct")
-
- v4 := New()
- v4.RegisterStructValidation(StructValidationTestStructSuccess, TestStruct{})
-
- errs = v4.Struct(tst)
- Equal(t, errs, nil)
-}
-
-func TestAliasTags(t *testing.T) {
-
- validate := New()
- validate.RegisterAlias("iscoloralias", "hexcolor|rgb|rgba|hsl|hsla")
-
- s := "rgb(255,255,255)"
- errs := validate.Var(s, "iscoloralias")
- Equal(t, errs, nil)
-
- s = ""
- errs = validate.Var(s, "omitempty,iscoloralias")
- Equal(t, errs, nil)
-
- s = "rgb(255,255,0)"
- errs = validate.Var(s, "iscoloralias,len=5")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "len")
-
- type Test struct {
- Color string `validate:"iscoloralias"`
- }
-
- tst := &Test{
- Color: "#000",
- }
-
- errs = validate.Struct(tst)
- Equal(t, errs, nil)
-
- tst.Color = "cfvre"
- errs = validate.Struct(tst)
- NotEqual(t, errs, nil)
- AssertError(t, errs, "Test.Color", "Test.Color", "Color", "Color", "iscoloralias")
-
- fe := getError(errs, "Test.Color", "Test.Color")
- NotEqual(t, fe, nil)
- Equal(t, fe.ActualTag(), "hexcolor|rgb|rgba|hsl|hsla")
-
- validate.RegisterAlias("req", "required,dive,iscoloralias")
- arr := []string{"val1", "#fff", "#000"}
-
- errs = validate.Var(arr, "req")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "[0]", "[0]", "[0]", "[0]", "iscoloralias")
-
- PanicMatches(t, func() { validate.RegisterAlias("exists!", "gt=5,lt=10") }, "Alias 'exists!' either contains restricted characters or is the same as a restricted tag needed for normal operation")
-}
-
-func TestNilValidator(t *testing.T) {
-
- type TestStruct struct {
- Test string `validate:"required"`
- }
-
- ts := TestStruct{}
-
- var val *Validate
-
- fn := func(fl FieldLevel) bool {
-
- return fl.Parent().String() == fl.Field().String()
- }
-
- PanicMatches(t, func() { val.RegisterCustomTypeFunc(ValidateCustomType, MadeUpCustomType{}) }, "runtime error: invalid memory address or nil pointer dereference")
- PanicMatches(t, func() { val.RegisterValidation("something", fn) }, "runtime error: invalid memory address or nil pointer dereference")
- PanicMatches(t, func() { val.Var(ts.Test, "required") }, "runtime error: invalid memory address or nil pointer dereference")
- PanicMatches(t, func() { val.VarWithValue("test", ts.Test, "required") }, "runtime error: invalid memory address or nil pointer dereference")
- PanicMatches(t, func() { val.Struct(ts) }, "runtime error: invalid memory address or nil pointer dereference")
- PanicMatches(t, func() { val.StructExcept(ts, "Test") }, "runtime error: invalid memory address or nil pointer dereference")
- PanicMatches(t, func() { val.StructPartial(ts, "Test") }, "runtime error: invalid memory address or nil pointer dereference")
-}
-
-func TestStructPartial(t *testing.T) {
-
- p1 := []string{
- "NoTag",
- "Required",
- }
-
- p2 := []string{
- "SubSlice[0].Test",
- "Sub",
- "SubIgnore",
- "Anonymous.A",
- }
-
- p3 := []string{
- "SubTest.Test",
- }
-
- p4 := []string{
- "A",
- }
-
- tPartial := &TestPartial{
- NoTag: "NoTag",
- Required: "Required",
-
- SubSlice: []*SubTest{
- {
-
- Test: "Required",
- },
- {
-
- Test: "Required",
- },
- },
-
- Sub: &SubTest{
- Test: "1",
- },
- SubIgnore: &SubTest{
- Test: "",
- },
- Anonymous: struct {
- A string `validate:"required"`
- ASubSlice []*SubTest `validate:"required,dive"`
- SubAnonStruct []struct {
- Test string `validate:"required"`
- OtherTest string `validate:"required"`
- } `validate:"required,dive"`
- }{
- A: "1",
- ASubSlice: []*SubTest{
- {
- Test: "Required",
- },
- {
- Test: "Required",
- },
- },
-
- SubAnonStruct: []struct {
- Test string `validate:"required"`
- OtherTest string `validate:"required"`
- }{
- {"Required", "RequiredOther"},
- {"Required", "RequiredOther"},
- },
- },
- }
-
- validate := New()
-
- // the following should all return no errors as everything is valid in
- // the default state
- errs := validate.StructPartialCtx(context.Background(), tPartial, p1...)
- Equal(t, errs, nil)
-
- errs = validate.StructPartial(tPartial, p2...)
- Equal(t, errs, nil)
-
- // this isn't really a robust test, but is ment to illustrate the ANON CASE below
- errs = validate.StructPartial(tPartial.SubSlice[0], p3...)
- Equal(t, errs, nil)
-
- errs = validate.StructExceptCtx(context.Background(), tPartial, p1...)
- Equal(t, errs, nil)
-
- errs = validate.StructExcept(tPartial, p2...)
- Equal(t, errs, nil)
-
- // mod tParial for required feild and re-test making sure invalid fields are NOT required:
- tPartial.Required = ""
-
- errs = validate.StructExcept(tPartial, p1...)
- Equal(t, errs, nil)
-
- errs = validate.StructPartial(tPartial, p2...)
- Equal(t, errs, nil)
-
- // inversion and retesting Partial to generate failures:
- errs = validate.StructPartial(tPartial, p1...)
- NotEqual(t, errs, nil)
- AssertError(t, errs, "TestPartial.Required", "TestPartial.Required", "Required", "Required", "required")
-
- errs = validate.StructExcept(tPartial, p2...)
- AssertError(t, errs, "TestPartial.Required", "TestPartial.Required", "Required", "Required", "required")
-
- // reset Required field, and set nested struct
- tPartial.Required = "Required"
- tPartial.Anonymous.A = ""
-
- // will pass as unset feilds is not going to be tested
- errs = validate.StructPartial(tPartial, p1...)
- Equal(t, errs, nil)
-
- errs = validate.StructExcept(tPartial, p2...)
- Equal(t, errs, nil)
-
- // ANON CASE the response here is strange, it clearly does what it is being told to
- errs = validate.StructExcept(tPartial.Anonymous, p4...)
- Equal(t, errs, nil)
-
- // will fail as unset feild is tested
- errs = validate.StructPartial(tPartial, p2...)
- NotEqual(t, errs, nil)
- AssertError(t, errs, "TestPartial.Anonymous.A", "TestPartial.Anonymous.A", "A", "A", "required")
-
- errs = validate.StructExcept(tPartial, p1...)
- NotEqual(t, errs, nil)
- AssertError(t, errs, "TestPartial.Anonymous.A", "TestPartial.Anonymous.A", "A", "A", "required")
-
- // reset nested struct and unset struct in slice
- tPartial.Anonymous.A = "Required"
- tPartial.SubSlice[0].Test = ""
-
- // these will pass as unset item is NOT tested
- errs = validate.StructPartial(tPartial, p1...)
- Equal(t, errs, nil)
-
- errs = validate.StructExcept(tPartial, p2...)
- Equal(t, errs, nil)
-
- // these will fail as unset item IS tested
- errs = validate.StructExcept(tPartial, p1...)
- AssertError(t, errs, "TestPartial.SubSlice[0].Test", "TestPartial.SubSlice[0].Test", "Test", "Test", "required")
- Equal(t, len(errs.(ValidationErrors)), 1)
-
- errs = validate.StructPartial(tPartial, p2...)
- NotEqual(t, errs, nil)
- AssertError(t, errs, "TestPartial.SubSlice[0].Test", "TestPartial.SubSlice[0].Test", "Test", "Test", "required")
- Equal(t, len(errs.(ValidationErrors)), 1)
-
- // Unset second slice member concurrently to test dive behavior:
- tPartial.SubSlice[1].Test = ""
-
- errs = validate.StructPartial(tPartial, p1...)
- Equal(t, errs, nil)
-
- // NOTE: When specifying nested items, it is still the users responsibility
- // to specify the dive tag, the library does not override this.
- errs = validate.StructExcept(tPartial, p2...)
- NotEqual(t, errs, nil)
- AssertError(t, errs, "TestPartial.SubSlice[1].Test", "TestPartial.SubSlice[1].Test", "Test", "Test", "required")
-
- errs = validate.StructExcept(tPartial, p1...)
- Equal(t, len(errs.(ValidationErrors)), 2)
- AssertError(t, errs, "TestPartial.SubSlice[0].Test", "TestPartial.SubSlice[0].Test", "Test", "Test", "required")
- AssertError(t, errs, "TestPartial.SubSlice[1].Test", "TestPartial.SubSlice[1].Test", "Test", "Test", "required")
-
- errs = validate.StructPartial(tPartial, p2...)
- NotEqual(t, errs, nil)
- Equal(t, len(errs.(ValidationErrors)), 1)
- AssertError(t, errs, "TestPartial.SubSlice[0].Test", "TestPartial.SubSlice[0].Test", "Test", "Test", "required")
-
- // reset struct in slice, and unset struct in slice in unset posistion
- tPartial.SubSlice[0].Test = "Required"
-
- // these will pass as the unset item is NOT tested
- errs = validate.StructPartial(tPartial, p1...)
- Equal(t, errs, nil)
-
- errs = validate.StructPartial(tPartial, p2...)
- Equal(t, errs, nil)
-
- // testing for missing item by exception, yes it dives and fails
- errs = validate.StructExcept(tPartial, p1...)
- NotEqual(t, errs, nil)
- Equal(t, len(errs.(ValidationErrors)), 1)
- AssertError(t, errs, "TestPartial.SubSlice[1].Test", "TestPartial.SubSlice[1].Test", "Test", "Test", "required")
-
- errs = validate.StructExcept(tPartial, p2...)
- NotEqual(t, errs, nil)
- AssertError(t, errs, "TestPartial.SubSlice[1].Test", "TestPartial.SubSlice[1].Test", "Test", "Test", "required")
-
- tPartial.SubSlice[1].Test = "Required"
-
- tPartial.Anonymous.SubAnonStruct[0].Test = ""
- // these will pass as the unset item is NOT tested
- errs = validate.StructPartial(tPartial, p1...)
- Equal(t, errs, nil)
-
- errs = validate.StructPartial(tPartial, p2...)
- Equal(t, errs, nil)
-
- errs = validate.StructExcept(tPartial, p1...)
- NotEqual(t, errs, nil)
- AssertError(t, errs, "TestPartial.Anonymous.SubAnonStruct[0].Test", "TestPartial.Anonymous.SubAnonStruct[0].Test", "Test", "Test", "required")
-
- errs = validate.StructExcept(tPartial, p2...)
- NotEqual(t, errs, nil)
- AssertError(t, errs, "TestPartial.Anonymous.SubAnonStruct[0].Test", "TestPartial.Anonymous.SubAnonStruct[0].Test", "Test", "Test", "required")
-
-}
-
-func TestCrossStructLteFieldValidation(t *testing.T) {
-
- type Inner struct {
- CreatedAt *time.Time
- String string
- Int int
- Uint uint
- Float float64
- Array []string
- }
-
- type Test struct {
- Inner *Inner
- CreatedAt *time.Time `validate:"ltecsfield=Inner.CreatedAt"`
- String string `validate:"ltecsfield=Inner.String"`
- Int int `validate:"ltecsfield=Inner.Int"`
- Uint uint `validate:"ltecsfield=Inner.Uint"`
- Float float64 `validate:"ltecsfield=Inner.Float"`
- Array []string `validate:"ltecsfield=Inner.Array"`
- }
-
- now := time.Now().UTC()
- then := now.Add(time.Hour * 5)
-
- inner := &Inner{
- CreatedAt: &then,
- String: "abcd",
- Int: 13,
- Uint: 13,
- Float: 1.13,
- Array: []string{"val1", "val2"},
- }
-
- test := &Test{
- Inner: inner,
- CreatedAt: &now,
- String: "abc",
- Int: 12,
- Uint: 12,
- Float: 1.12,
- Array: []string{"val1"},
- }
-
- validate := New()
- errs := validate.Struct(test)
- Equal(t, errs, nil)
-
- test.CreatedAt = &then
- test.String = "abcd"
- test.Int = 13
- test.Uint = 13
- test.Float = 1.13
- test.Array = []string{"val1", "val2"}
-
- errs = validate.Struct(test)
- Equal(t, errs, nil)
-
- after := now.Add(time.Hour * 10)
-
- test.CreatedAt = &after
- test.String = "abce"
- test.Int = 14
- test.Uint = 14
- test.Float = 1.14
- test.Array = []string{"val1", "val2", "val3"}
-
- errs = validate.Struct(test)
- NotEqual(t, errs, nil)
- AssertError(t, errs, "Test.CreatedAt", "Test.CreatedAt", "CreatedAt", "CreatedAt", "ltecsfield")
- AssertError(t, errs, "Test.String", "Test.String", "String", "String", "ltecsfield")
- AssertError(t, errs, "Test.Int", "Test.Int", "Int", "Int", "ltecsfield")
- AssertError(t, errs, "Test.Uint", "Test.Uint", "Uint", "Uint", "ltecsfield")
- AssertError(t, errs, "Test.Float", "Test.Float", "Float", "Float", "ltecsfield")
- AssertError(t, errs, "Test.Array", "Test.Array", "Array", "Array", "ltecsfield")
-
- errs = validate.VarWithValueCtx(context.Background(), 1, "", "ltecsfield")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "ltecsfield")
-
- // this test is for the WARNING about unforseen validation issues.
- errs = validate.VarWithValue(test, now, "ltecsfield")
- NotEqual(t, errs, nil)
- Equal(t, len(errs.(ValidationErrors)), 6)
- AssertError(t, errs, "Test.CreatedAt", "Test.CreatedAt", "CreatedAt", "CreatedAt", "ltecsfield")
- AssertError(t, errs, "Test.String", "Test.String", "String", "String", "ltecsfield")
- AssertError(t, errs, "Test.Int", "Test.Int", "Int", "Int", "ltecsfield")
- AssertError(t, errs, "Test.Uint", "Test.Uint", "Uint", "Uint", "ltecsfield")
- AssertError(t, errs, "Test.Float", "Test.Float", "Float", "Float", "ltecsfield")
- AssertError(t, errs, "Test.Array", "Test.Array", "Array", "Array", "ltecsfield")
-
- type Other struct {
- Value string
- }
-
- type Test2 struct {
- Value Other
- Time time.Time `validate:"ltecsfield=Value"`
- }
-
- tst := Test2{
- Value: Other{Value: "StringVal"},
- Time: then,
- }
-
- errs = validate.Struct(tst)
- NotEqual(t, errs, nil)
- AssertError(t, errs, "Test2.Time", "Test2.Time", "Time", "Time", "ltecsfield")
-}
-
-func TestCrossStructLtFieldValidation(t *testing.T) {
-
- type Inner struct {
- CreatedAt *time.Time
- String string
- Int int
- Uint uint
- Float float64
- Array []string
- }
-
- type Test struct {
- Inner *Inner
- CreatedAt *time.Time `validate:"ltcsfield=Inner.CreatedAt"`
- String string `validate:"ltcsfield=Inner.String"`
- Int int `validate:"ltcsfield=Inner.Int"`
- Uint uint `validate:"ltcsfield=Inner.Uint"`
- Float float64 `validate:"ltcsfield=Inner.Float"`
- Array []string `validate:"ltcsfield=Inner.Array"`
- }
-
- now := time.Now().UTC()
- then := now.Add(time.Hour * 5)
-
- inner := &Inner{
- CreatedAt: &then,
- String: "abcd",
- Int: 13,
- Uint: 13,
- Float: 1.13,
- Array: []string{"val1", "val2"},
- }
-
- test := &Test{
- Inner: inner,
- CreatedAt: &now,
- String: "abc",
- Int: 12,
- Uint: 12,
- Float: 1.12,
- Array: []string{"val1"},
- }
-
- validate := New()
- errs := validate.Struct(test)
- Equal(t, errs, nil)
-
- test.CreatedAt = &then
- test.String = "abcd"
- test.Int = 13
- test.Uint = 13
- test.Float = 1.13
- test.Array = []string{"val1", "val2"}
-
- errs = validate.Struct(test)
- NotEqual(t, errs, nil)
- AssertError(t, errs, "Test.CreatedAt", "Test.CreatedAt", "CreatedAt", "CreatedAt", "ltcsfield")
- AssertError(t, errs, "Test.String", "Test.String", "String", "String", "ltcsfield")
- AssertError(t, errs, "Test.Int", "Test.Int", "Int", "Int", "ltcsfield")
- AssertError(t, errs, "Test.Uint", "Test.Uint", "Uint", "Uint", "ltcsfield")
- AssertError(t, errs, "Test.Float", "Test.Float", "Float", "Float", "ltcsfield")
- AssertError(t, errs, "Test.Array", "Test.Array", "Array", "Array", "ltcsfield")
-
- errs = validate.VarWithValue(1, "", "ltcsfield")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "ltcsfield")
-
- // this test is for the WARNING about unforseen validation issues.
- errs = validate.VarWithValue(test, now, "ltcsfield")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "Test.CreatedAt", "Test.CreatedAt", "CreatedAt", "CreatedAt", "ltcsfield")
- AssertError(t, errs, "Test.String", "Test.String", "String", "String", "ltcsfield")
- AssertError(t, errs, "Test.Int", "Test.Int", "Int", "Int", "ltcsfield")
- AssertError(t, errs, "Test.Uint", "Test.Uint", "Uint", "Uint", "ltcsfield")
- AssertError(t, errs, "Test.Float", "Test.Float", "Float", "Float", "ltcsfield")
- AssertError(t, errs, "Test.Array", "Test.Array", "Array", "Array", "ltcsfield")
-
- type Other struct {
- Value string
- }
-
- type Test2 struct {
- Value Other
- Time time.Time `validate:"ltcsfield=Value"`
- }
-
- tst := Test2{
- Value: Other{Value: "StringVal"},
- Time: then,
- }
-
- errs = validate.Struct(tst)
- NotEqual(t, errs, nil)
- AssertError(t, errs, "Test2.Time", "Test2.Time", "Time", "Time", "ltcsfield")
-}
-
-func TestCrossStructGteFieldValidation(t *testing.T) {
-
- type Inner struct {
- CreatedAt *time.Time
- String string
- Int int
- Uint uint
- Float float64
- Array []string
- }
-
- type Test struct {
- Inner *Inner
- CreatedAt *time.Time `validate:"gtecsfield=Inner.CreatedAt"`
- String string `validate:"gtecsfield=Inner.String"`
- Int int `validate:"gtecsfield=Inner.Int"`
- Uint uint `validate:"gtecsfield=Inner.Uint"`
- Float float64 `validate:"gtecsfield=Inner.Float"`
- Array []string `validate:"gtecsfield=Inner.Array"`
- }
-
- now := time.Now().UTC()
- then := now.Add(time.Hour * -5)
-
- inner := &Inner{
- CreatedAt: &then,
- String: "abcd",
- Int: 13,
- Uint: 13,
- Float: 1.13,
- Array: []string{"val1", "val2"},
- }
-
- test := &Test{
- Inner: inner,
- CreatedAt: &now,
- String: "abcde",
- Int: 14,
- Uint: 14,
- Float: 1.14,
- Array: []string{"val1", "val2", "val3"},
- }
-
- validate := New()
- errs := validate.Struct(test)
- Equal(t, errs, nil)
-
- test.CreatedAt = &then
- test.String = "abcd"
- test.Int = 13
- test.Uint = 13
- test.Float = 1.13
- test.Array = []string{"val1", "val2"}
-
- errs = validate.Struct(test)
- Equal(t, errs, nil)
-
- before := now.Add(time.Hour * -10)
-
- test.CreatedAt = &before
- test.String = "abc"
- test.Int = 12
- test.Uint = 12
- test.Float = 1.12
- test.Array = []string{"val1"}
-
- errs = validate.Struct(test)
- NotEqual(t, errs, nil)
- AssertError(t, errs, "Test.CreatedAt", "Test.CreatedAt", "CreatedAt", "CreatedAt", "gtecsfield")
- AssertError(t, errs, "Test.String", "Test.String", "String", "String", "gtecsfield")
- AssertError(t, errs, "Test.Int", "Test.Int", "Int", "Int", "gtecsfield")
- AssertError(t, errs, "Test.Uint", "Test.Uint", "Uint", "Uint", "gtecsfield")
- AssertError(t, errs, "Test.Float", "Test.Float", "Float", "Float", "gtecsfield")
- AssertError(t, errs, "Test.Array", "Test.Array", "Array", "Array", "gtecsfield")
-
- errs = validate.VarWithValue(1, "", "gtecsfield")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "gtecsfield")
-
- // this test is for the WARNING about unforseen validation issues.
- errs = validate.VarWithValue(test, now, "gtecsfield")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "Test.CreatedAt", "Test.CreatedAt", "CreatedAt", "CreatedAt", "gtecsfield")
- AssertError(t, errs, "Test.String", "Test.String", "String", "String", "gtecsfield")
- AssertError(t, errs, "Test.Int", "Test.Int", "Int", "Int", "gtecsfield")
- AssertError(t, errs, "Test.Uint", "Test.Uint", "Uint", "Uint", "gtecsfield")
- AssertError(t, errs, "Test.Float", "Test.Float", "Float", "Float", "gtecsfield")
- AssertError(t, errs, "Test.Array", "Test.Array", "Array", "Array", "gtecsfield")
-
- type Other struct {
- Value string
- }
-
- type Test2 struct {
- Value Other
- Time time.Time `validate:"gtecsfield=Value"`
- }
-
- tst := Test2{
- Value: Other{Value: "StringVal"},
- Time: then,
- }
-
- errs = validate.Struct(tst)
- NotEqual(t, errs, nil)
- AssertError(t, errs, "Test2.Time", "Test2.Time", "Time", "Time", "gtecsfield")
-}
-
-func TestCrossStructGtFieldValidation(t *testing.T) {
-
- type Inner struct {
- CreatedAt *time.Time
- String string
- Int int
- Uint uint
- Float float64
- Array []string
- }
-
- type Test struct {
- Inner *Inner
- CreatedAt *time.Time `validate:"gtcsfield=Inner.CreatedAt"`
- String string `validate:"gtcsfield=Inner.String"`
- Int int `validate:"gtcsfield=Inner.Int"`
- Uint uint `validate:"gtcsfield=Inner.Uint"`
- Float float64 `validate:"gtcsfield=Inner.Float"`
- Array []string `validate:"gtcsfield=Inner.Array"`
- }
-
- now := time.Now().UTC()
- then := now.Add(time.Hour * -5)
-
- inner := &Inner{
- CreatedAt: &then,
- String: "abcd",
- Int: 13,
- Uint: 13,
- Float: 1.13,
- Array: []string{"val1", "val2"},
- }
-
- test := &Test{
- Inner: inner,
- CreatedAt: &now,
- String: "abcde",
- Int: 14,
- Uint: 14,
- Float: 1.14,
- Array: []string{"val1", "val2", "val3"},
- }
-
- validate := New()
- errs := validate.Struct(test)
- Equal(t, errs, nil)
-
- test.CreatedAt = &then
- test.String = "abcd"
- test.Int = 13
- test.Uint = 13
- test.Float = 1.13
- test.Array = []string{"val1", "val2"}
-
- errs = validate.Struct(test)
- NotEqual(t, errs, nil)
- AssertError(t, errs, "Test.CreatedAt", "Test.CreatedAt", "CreatedAt", "CreatedAt", "gtcsfield")
- AssertError(t, errs, "Test.String", "Test.String", "String", "String", "gtcsfield")
- AssertError(t, errs, "Test.Int", "Test.Int", "Int", "Int", "gtcsfield")
- AssertError(t, errs, "Test.Uint", "Test.Uint", "Uint", "Uint", "gtcsfield")
- AssertError(t, errs, "Test.Float", "Test.Float", "Float", "Float", "gtcsfield")
- AssertError(t, errs, "Test.Array", "Test.Array", "Array", "Array", "gtcsfield")
-
- errs = validate.VarWithValue(1, "", "gtcsfield")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "gtcsfield")
-
- // this test is for the WARNING about unforseen validation issues.
- errs = validate.VarWithValue(test, now, "gtcsfield")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "Test.CreatedAt", "Test.CreatedAt", "CreatedAt", "CreatedAt", "gtcsfield")
- AssertError(t, errs, "Test.String", "Test.String", "String", "String", "gtcsfield")
- AssertError(t, errs, "Test.Int", "Test.Int", "Int", "Int", "gtcsfield")
- AssertError(t, errs, "Test.Uint", "Test.Uint", "Uint", "Uint", "gtcsfield")
- AssertError(t, errs, "Test.Float", "Test.Float", "Float", "Float", "gtcsfield")
- AssertError(t, errs, "Test.Array", "Test.Array", "Array", "Array", "gtcsfield")
-
- type Other struct {
- Value string
- }
-
- type Test2 struct {
- Value Other
- Time time.Time `validate:"gtcsfield=Value"`
- }
-
- tst := Test2{
- Value: Other{Value: "StringVal"},
- Time: then,
- }
-
- errs = validate.Struct(tst)
- NotEqual(t, errs, nil)
- AssertError(t, errs, "Test2.Time", "Test2.Time", "Time", "Time", "gtcsfield")
-}
-
-func TestCrossStructNeFieldValidation(t *testing.T) {
-
- type Inner struct {
- CreatedAt *time.Time
- }
-
- type Test struct {
- Inner *Inner
- CreatedAt *time.Time `validate:"necsfield=Inner.CreatedAt"`
- }
-
- now := time.Now().UTC()
- then := now.Add(time.Hour * 5)
-
- inner := &Inner{
- CreatedAt: &then,
- }
-
- test := &Test{
- Inner: inner,
- CreatedAt: &now,
- }
-
- validate := New()
- errs := validate.Struct(test)
- Equal(t, errs, nil)
-
- test.CreatedAt = &then
-
- errs = validate.Struct(test)
- NotEqual(t, errs, nil)
- AssertError(t, errs, "Test.CreatedAt", "Test.CreatedAt", "CreatedAt", "CreatedAt", "necsfield")
-
- var j uint64
- var k float64
- var j2 uint64
- var k2 float64
- s := "abcd"
- i := 1
- j = 1
- k = 1.543
- arr := []string{"test"}
-
- s2 := "abcd"
- i2 := 1
- j2 = 1
- k2 = 1.543
- arr2 := []string{"test"}
- arr3 := []string{"test", "test2"}
- now2 := now
-
- errs = validate.VarWithValue(s, s2, "necsfield")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "necsfield")
-
- errs = validate.VarWithValue(i2, i, "necsfield")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "necsfield")
-
- errs = validate.VarWithValue(j2, j, "necsfield")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "necsfield")
-
- errs = validate.VarWithValue(k2, k, "necsfield")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "necsfield")
-
- errs = validate.VarWithValue(arr2, arr, "necsfield")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "necsfield")
-
- errs = validate.VarWithValue(now2, now, "necsfield")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "necsfield")
-
- errs = validate.VarWithValue(arr3, arr, "necsfield")
- Equal(t, errs, nil)
-
- type SInner struct {
- Name string
- }
-
- type TStruct struct {
- Inner *SInner
- CreatedAt *time.Time `validate:"necsfield=Inner"`
- }
-
- sinner := &SInner{
- Name: "NAME",
- }
-
- test2 := &TStruct{
- Inner: sinner,
- CreatedAt: &now,
- }
-
- errs = validate.Struct(test2)
- Equal(t, errs, nil)
-
- test2.Inner = nil
- errs = validate.Struct(test2)
- Equal(t, errs, nil)
-
- errs = validate.VarWithValue(nil, 1, "necsfield")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "necsfield")
-}
-
-func TestCrossStructEqFieldValidation(t *testing.T) {
-
- type Inner struct {
- CreatedAt *time.Time
- }
-
- type Test struct {
- Inner *Inner
- CreatedAt *time.Time `validate:"eqcsfield=Inner.CreatedAt"`
- }
-
- now := time.Now().UTC()
-
- inner := &Inner{
- CreatedAt: &now,
- }
-
- test := &Test{
- Inner: inner,
- CreatedAt: &now,
- }
-
- validate := New()
- errs := validate.Struct(test)
- Equal(t, errs, nil)
-
- newTime := time.Now().UTC()
- test.CreatedAt = &newTime
-
- errs = validate.Struct(test)
- NotEqual(t, errs, nil)
- AssertError(t, errs, "Test.CreatedAt", "Test.CreatedAt", "CreatedAt", "CreatedAt", "eqcsfield")
-
- var j uint64
- var k float64
- s := "abcd"
- i := 1
- j = 1
- k = 1.543
- arr := []string{"test"}
-
- var j2 uint64
- var k2 float64
- s2 := "abcd"
- i2 := 1
- j2 = 1
- k2 = 1.543
- arr2 := []string{"test"}
- arr3 := []string{"test", "test2"}
- now2 := now
-
- errs = validate.VarWithValue(s, s2, "eqcsfield")
- Equal(t, errs, nil)
-
- errs = validate.VarWithValue(i2, i, "eqcsfield")
- Equal(t, errs, nil)
-
- errs = validate.VarWithValue(j2, j, "eqcsfield")
- Equal(t, errs, nil)
-
- errs = validate.VarWithValue(k2, k, "eqcsfield")
- Equal(t, errs, nil)
-
- errs = validate.VarWithValue(arr2, arr, "eqcsfield")
- Equal(t, errs, nil)
-
- errs = validate.VarWithValue(now2, now, "eqcsfield")
- Equal(t, errs, nil)
-
- errs = validate.VarWithValue(arr3, arr, "eqcsfield")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "eqcsfield")
-
- type SInner struct {
- Name string
- }
-
- type TStruct struct {
- Inner *SInner
- CreatedAt *time.Time `validate:"eqcsfield=Inner"`
- }
-
- sinner := &SInner{
- Name: "NAME",
- }
-
- test2 := &TStruct{
- Inner: sinner,
- CreatedAt: &now,
- }
-
- errs = validate.Struct(test2)
- NotEqual(t, errs, nil)
- AssertError(t, errs, "TStruct.CreatedAt", "TStruct.CreatedAt", "CreatedAt", "CreatedAt", "eqcsfield")
-
- test2.Inner = nil
- errs = validate.Struct(test2)
- NotEqual(t, errs, nil)
- AssertError(t, errs, "TStruct.CreatedAt", "TStruct.CreatedAt", "CreatedAt", "CreatedAt", "eqcsfield")
-
- errs = validate.VarWithValue(nil, 1, "eqcsfield")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "eqcsfield")
-}
-
-func TestCrossNamespaceFieldValidation(t *testing.T) {
-
- type SliceStruct struct {
- Name string
- }
-
- type Inner struct {
- CreatedAt *time.Time
- Slice []string
- SliceStructs []*SliceStruct
- SliceSlice [][]string
- SliceSliceStruct [][]*SliceStruct
- SliceMap []map[string]string
- Map map[string]string
- MapMap map[string]map[string]string
- MapStructs map[string]*SliceStruct
- MapMapStruct map[string]map[string]*SliceStruct
- MapSlice map[string][]string
- MapInt map[int]string
- MapInt8 map[int8]string
- MapInt16 map[int16]string
- MapInt32 map[int32]string
- MapInt64 map[int64]string
- MapUint map[uint]string
- MapUint8 map[uint8]string
- MapUint16 map[uint16]string
- MapUint32 map[uint32]string
- MapUint64 map[uint64]string
- MapFloat32 map[float32]string
- MapFloat64 map[float64]string
- MapBool map[bool]string
- }
-
- type Test struct {
- Inner *Inner
- CreatedAt *time.Time
- }
-
- now := time.Now()
-
- inner := &Inner{
- CreatedAt: &now,
- Slice: []string{"val1", "val2", "val3"},
- SliceStructs: []*SliceStruct{{Name: "name1"}, {Name: "name2"}, {Name: "name3"}},
- SliceSlice: [][]string{{"1", "2", "3"}, {"4", "5", "6"}, {"7", "8", "9"}},
- SliceSliceStruct: [][]*SliceStruct{{{Name: "name1"}, {Name: "name2"}, {Name: "name3"}}, {{Name: "name4"}, {Name: "name5"}, {Name: "name6"}}, {{Name: "name7"}, {Name: "name8"}, {Name: "name9"}}},
- SliceMap: []map[string]string{{"key1": "val1", "key2": "val2", "key3": "val3"}, {"key4": "val4", "key5": "val5", "key6": "val6"}},
- Map: map[string]string{"key1": "val1", "key2": "val2", "key3": "val3"},
- MapStructs: map[string]*SliceStruct{"key1": {Name: "name1"}, "key2": {Name: "name2"}, "key3": {Name: "name3"}},
- MapMap: map[string]map[string]string{"key1": {"key1-1": "val1"}, "key2": {"key2-1": "val2"}, "key3": {"key3-1": "val3"}},
- MapMapStruct: map[string]map[string]*SliceStruct{"key1": {"key1-1": {Name: "name1"}}, "key2": {"key2-1": {Name: "name2"}}, "key3": {"key3-1": {Name: "name3"}}},
- MapSlice: map[string][]string{"key1": {"1", "2", "3"}, "key2": {"4", "5", "6"}, "key3": {"7", "8", "9"}},
- MapInt: map[int]string{1: "val1", 2: "val2", 3: "val3"},
- MapInt8: map[int8]string{1: "val1", 2: "val2", 3: "val3"},
- MapInt16: map[int16]string{1: "val1", 2: "val2", 3: "val3"},
- MapInt32: map[int32]string{1: "val1", 2: "val2", 3: "val3"},
- MapInt64: map[int64]string{1: "val1", 2: "val2", 3: "val3"},
- MapUint: map[uint]string{1: "val1", 2: "val2", 3: "val3"},
- MapUint8: map[uint8]string{1: "val1", 2: "val2", 3: "val3"},
- MapUint16: map[uint16]string{1: "val1", 2: "val2", 3: "val3"},
- MapUint32: map[uint32]string{1: "val1", 2: "val2", 3: "val3"},
- MapUint64: map[uint64]string{1: "val1", 2: "val2", 3: "val3"},
- MapFloat32: map[float32]string{1.01: "val1", 2.02: "val2", 3.03: "val3"},
- MapFloat64: map[float64]string{1.01: "val1", 2.02: "val2", 3.03: "val3"},
- MapBool: map[bool]string{true: "val1", false: "val2"},
- }
-
- test := &Test{
- Inner: inner,
- CreatedAt: &now,
- }
-
- val := reflect.ValueOf(test)
-
- vd := New()
- v := &validate{
- v: vd,
- }
-
- current, kind, ok := v.getStructFieldOKInternal(val, "Inner.CreatedAt")
- Equal(t, ok, true)
- Equal(t, kind, reflect.Struct)
- tm, ok := current.Interface().(time.Time)
- Equal(t, ok, true)
- Equal(t, tm, now)
-
- current, kind, ok = v.getStructFieldOKInternal(val, "Inner.Slice[1]")
- Equal(t, ok, true)
- Equal(t, kind, reflect.String)
- Equal(t, current.String(), "val2")
-
- current, _, ok = v.getStructFieldOKInternal(val, "Inner.CrazyNonExistantField")
- Equal(t, ok, false)
-
- current, _, ok = v.getStructFieldOKInternal(val, "Inner.Slice[101]")
- Equal(t, ok, false)
-
- current, kind, ok = v.getStructFieldOKInternal(val, "Inner.Map[key3]")
- Equal(t, ok, true)
- Equal(t, kind, reflect.String)
- Equal(t, current.String(), "val3")
-
- current, kind, ok = v.getStructFieldOKInternal(val, "Inner.MapMap[key2][key2-1]")
- Equal(t, ok, true)
- Equal(t, kind, reflect.String)
- Equal(t, current.String(), "val2")
-
- current, kind, ok = v.getStructFieldOKInternal(val, "Inner.MapStructs[key2].Name")
- Equal(t, ok, true)
- Equal(t, kind, reflect.String)
- Equal(t, current.String(), "name2")
-
- current, kind, ok = v.getStructFieldOKInternal(val, "Inner.MapMapStruct[key3][key3-1].Name")
- Equal(t, ok, true)
- Equal(t, kind, reflect.String)
- Equal(t, current.String(), "name3")
-
- current, kind, ok = v.getStructFieldOKInternal(val, "Inner.SliceSlice[2][0]")
- Equal(t, ok, true)
- Equal(t, kind, reflect.String)
- Equal(t, current.String(), "7")
-
- current, kind, ok = v.getStructFieldOKInternal(val, "Inner.SliceSliceStruct[2][1].Name")
- Equal(t, ok, true)
- Equal(t, kind, reflect.String)
- Equal(t, current.String(), "name8")
-
- current, kind, ok = v.getStructFieldOKInternal(val, "Inner.SliceMap[1][key5]")
- Equal(t, ok, true)
- Equal(t, kind, reflect.String)
- Equal(t, current.String(), "val5")
-
- current, kind, ok = v.getStructFieldOKInternal(val, "Inner.MapSlice[key3][2]")
- Equal(t, ok, true)
- Equal(t, kind, reflect.String)
- Equal(t, current.String(), "9")
-
- current, kind, ok = v.getStructFieldOKInternal(val, "Inner.MapInt[2]")
- Equal(t, ok, true)
- Equal(t, kind, reflect.String)
- Equal(t, current.String(), "val2")
-
- current, kind, ok = v.getStructFieldOKInternal(val, "Inner.MapInt8[2]")
- Equal(t, ok, true)
- Equal(t, kind, reflect.String)
- Equal(t, current.String(), "val2")
-
- current, kind, ok = v.getStructFieldOKInternal(val, "Inner.MapInt16[2]")
- Equal(t, ok, true)
- Equal(t, kind, reflect.String)
- Equal(t, current.String(), "val2")
-
- current, kind, ok = v.getStructFieldOKInternal(val, "Inner.MapInt32[2]")
- Equal(t, ok, true)
- Equal(t, kind, reflect.String)
- Equal(t, current.String(), "val2")
-
- current, kind, ok = v.getStructFieldOKInternal(val, "Inner.MapInt64[2]")
- Equal(t, ok, true)
- Equal(t, kind, reflect.String)
- Equal(t, current.String(), "val2")
-
- current, kind, ok = v.getStructFieldOKInternal(val, "Inner.MapUint[2]")
- Equal(t, ok, true)
- Equal(t, kind, reflect.String)
- Equal(t, current.String(), "val2")
-
- current, kind, ok = v.getStructFieldOKInternal(val, "Inner.MapUint8[2]")
- Equal(t, ok, true)
- Equal(t, kind, reflect.String)
- Equal(t, current.String(), "val2")
-
- current, kind, ok = v.getStructFieldOKInternal(val, "Inner.MapUint16[2]")
- Equal(t, ok, true)
- Equal(t, kind, reflect.String)
- Equal(t, current.String(), "val2")
-
- current, kind, ok = v.getStructFieldOKInternal(val, "Inner.MapUint32[2]")
- Equal(t, ok, true)
- Equal(t, kind, reflect.String)
- Equal(t, current.String(), "val2")
-
- current, kind, ok = v.getStructFieldOKInternal(val, "Inner.MapUint64[2]")
- Equal(t, ok, true)
- Equal(t, kind, reflect.String)
- Equal(t, current.String(), "val2")
-
- current, kind, ok = v.getStructFieldOKInternal(val, "Inner.MapFloat32[3.03]")
- Equal(t, ok, true)
- Equal(t, kind, reflect.String)
- Equal(t, current.String(), "val3")
-
- current, kind, ok = v.getStructFieldOKInternal(val, "Inner.MapFloat64[2.02]")
- Equal(t, ok, true)
- Equal(t, kind, reflect.String)
- Equal(t, current.String(), "val2")
-
- current, kind, ok = v.getStructFieldOKInternal(val, "Inner.MapBool[true]")
- Equal(t, ok, true)
- Equal(t, kind, reflect.String)
- Equal(t, current.String(), "val1")
-
- inner = &Inner{
- CreatedAt: &now,
- Slice: []string{"val1", "val2", "val3"},
- SliceStructs: []*SliceStruct{{Name: "name1"}, {Name: "name2"}, nil},
- SliceSlice: [][]string{{"1", "2", "3"}, {"4", "5", "6"}, {"7", "8", "9"}},
- SliceSliceStruct: [][]*SliceStruct{{{Name: "name1"}, {Name: "name2"}, {Name: "name3"}}, {{Name: "name4"}, {Name: "name5"}, {Name: "name6"}}, {{Name: "name7"}, {Name: "name8"}, {Name: "name9"}}},
- SliceMap: []map[string]string{{"key1": "val1", "key2": "val2", "key3": "val3"}, {"key4": "val4", "key5": "val5", "key6": "val6"}},
- Map: map[string]string{"key1": "val1", "key2": "val2", "key3": "val3"},
- MapStructs: map[string]*SliceStruct{"key1": {Name: "name1"}, "key2": {Name: "name2"}, "key3": {Name: "name3"}},
- MapMap: map[string]map[string]string{"key1": {"key1-1": "val1"}, "key2": {"key2-1": "val2"}, "key3": {"key3-1": "val3"}},
- MapMapStruct: map[string]map[string]*SliceStruct{"key1": {"key1-1": {Name: "name1"}}, "key2": {"key2-1": {Name: "name2"}}, "key3": {"key3-1": {Name: "name3"}}},
- MapSlice: map[string][]string{"key1": {"1", "2", "3"}, "key2": {"4", "5", "6"}, "key3": {"7", "8", "9"}},
- }
-
- test = &Test{
- Inner: inner,
- CreatedAt: nil,
- }
-
- val = reflect.ValueOf(test)
-
- current, kind, ok = v.getStructFieldOKInternal(val, "Inner.SliceStructs[2]")
- Equal(t, ok, true)
- Equal(t, kind, reflect.Ptr)
- Equal(t, current.String(), "<*validator.SliceStruct Value>")
- Equal(t, current.IsNil(), true)
-
- current, kind, ok = v.getStructFieldOKInternal(val, "Inner.SliceStructs[2].Name")
- Equal(t, ok, false)
- Equal(t, kind, reflect.Ptr)
- Equal(t, current.String(), "<*validator.SliceStruct Value>")
- Equal(t, current.IsNil(), true)
-
- PanicMatches(t, func() { v.getStructFieldOKInternal(reflect.ValueOf(1), "crazyinput") }, "Invalid field namespace")
-}
-
-func TestExistsValidation(t *testing.T) {
-
- jsonText := "{ \"truthiness2\": true }"
-
- type Thing struct {
- Truthiness *bool `json:"truthiness" validate:"required"`
- }
-
- var ting Thing
-
- err := json.Unmarshal([]byte(jsonText), &ting)
- Equal(t, err, nil)
- NotEqual(t, ting, nil)
- Equal(t, ting.Truthiness, nil)
-
- validate := New()
- errs := validate.Struct(ting)
- NotEqual(t, errs, nil)
- AssertError(t, errs, "Thing.Truthiness", "Thing.Truthiness", "Truthiness", "Truthiness", "required")
-
- jsonText = "{ \"truthiness\": true }"
-
- err = json.Unmarshal([]byte(jsonText), &ting)
- Equal(t, err, nil)
- NotEqual(t, ting, nil)
- Equal(t, ting.Truthiness, true)
-
- errs = validate.Struct(ting)
- Equal(t, errs, nil)
-}
-
-func TestSQLValue2Validation(t *testing.T) {
-
- validate := New()
- validate.RegisterCustomTypeFunc(ValidateValuerType, valuer{}, (*driver.Valuer)(nil), sql.NullString{}, sql.NullInt64{}, sql.NullBool{}, sql.NullFloat64{})
- validate.RegisterCustomTypeFunc(ValidateCustomType, MadeUpCustomType{})
- validate.RegisterCustomTypeFunc(OverrideIntTypeForSomeReason, 1)
-
- val := valuer{
- Name: "",
- }
-
- errs := validate.Var(val, "required")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "required")
-
- val.Name = "Valid Name"
- errs = validate.VarCtx(context.Background(), val, "required")
- Equal(t, errs, nil)
-
- val.Name = "errorme"
-
- PanicMatches(t, func() { validate.Var(val, "required") }, "SQL Driver Valuer error: some kind of error")
-
- myVal := valuer{
- Name: "",
- }
-
- errs = validate.Var(myVal, "required")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "required")
-
- cust := MadeUpCustomType{
- FirstName: "Joey",
- LastName: "Bloggs",
- }
-
- c := CustomMadeUpStruct{MadeUp: cust, OverriddenInt: 2}
-
- errs = validate.Struct(c)
- Equal(t, errs, nil)
-
- c.MadeUp.FirstName = ""
- c.OverriddenInt = 1
-
- errs = validate.Struct(c)
- NotEqual(t, errs, nil)
- Equal(t, len(errs.(ValidationErrors)), 2)
- AssertError(t, errs, "CustomMadeUpStruct.MadeUp", "CustomMadeUpStruct.MadeUp", "MadeUp", "MadeUp", "required")
- AssertError(t, errs, "CustomMadeUpStruct.OverriddenInt", "CustomMadeUpStruct.OverriddenInt", "OverriddenInt", "OverriddenInt", "gt")
-}
-
-func TestSQLValueValidation(t *testing.T) {
-
- validate := New()
- validate.RegisterCustomTypeFunc(ValidateValuerType, (*driver.Valuer)(nil), valuer{})
- validate.RegisterCustomTypeFunc(ValidateCustomType, MadeUpCustomType{})
- validate.RegisterCustomTypeFunc(OverrideIntTypeForSomeReason, 1)
-
- val := valuer{
- Name: "",
- }
-
- errs := validate.Var(val, "required")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "required")
-
- val.Name = "Valid Name"
- errs = validate.Var(val, "required")
- Equal(t, errs, nil)
-
- val.Name = "errorme"
-
- PanicMatches(t, func() { errs = validate.Var(val, "required") }, "SQL Driver Valuer error: some kind of error")
-
- myVal := valuer{
- Name: "",
- }
-
- errs = validate.Var(myVal, "required")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "required")
-
- cust := MadeUpCustomType{
- FirstName: "Joey",
- LastName: "Bloggs",
- }
-
- c := CustomMadeUpStruct{MadeUp: cust, OverriddenInt: 2}
-
- errs = validate.Struct(c)
- Equal(t, errs, nil)
-
- c.MadeUp.FirstName = ""
- c.OverriddenInt = 1
-
- errs = validate.Struct(c)
- NotEqual(t, errs, nil)
- Equal(t, len(errs.(ValidationErrors)), 2)
- AssertError(t, errs, "CustomMadeUpStruct.MadeUp", "CustomMadeUpStruct.MadeUp", "MadeUp", "MadeUp", "required")
- AssertError(t, errs, "CustomMadeUpStruct.OverriddenInt", "CustomMadeUpStruct.OverriddenInt", "OverriddenInt", "OverriddenInt", "gt")
-}
-
-func TestMACValidation(t *testing.T) {
- tests := []struct {
- param string
- expected bool
- }{
- {"3D:F2:C9:A6:B3:4F", true},
- {"3D-F2-C9-A6-B3:4F", false},
- {"123", false},
- {"", false},
- {"abacaba", false},
- {"00:25:96:FF:FE:12:34:56", true},
- {"0025:96FF:FE12:3456", false},
- }
-
- validate := New()
-
- for i, test := range tests {
-
- errs := validate.Var(test.param, "mac")
-
- if test.expected {
- if !IsEqual(errs, nil) {
- t.Fatalf("Index: %d mac failed Error: %s", i, errs)
- }
- } else {
- if IsEqual(errs, nil) {
- t.Fatalf("Index: %d mac failed Error: %s", i, errs)
- } else {
- val := getError(errs, "", "")
- if val.Tag() != "mac" {
- t.Fatalf("Index: %d mac failed Error: %s", i, errs)
- }
- }
- }
- }
-}
-
-func TestIPValidation(t *testing.T) {
- tests := []struct {
- param string
- expected bool
- }{
- {"", false},
- {"10.0.0.1", true},
- {"172.16.0.1", true},
- {"192.168.0.1", true},
- {"192.168.255.254", true},
- {"192.168.255.256", false},
- {"172.16.255.254", true},
- {"172.16.256.255", false},
- {"2001:cdba:0000:0000:0000:0000:3257:9652", true},
- {"2001:cdba:0:0:0:0:3257:9652", true},
- {"2001:cdba::3257:9652", true},
- }
-
- validate := New()
-
- for i, test := range tests {
-
- errs := validate.Var(test.param, "ip")
-
- if test.expected {
- if !IsEqual(errs, nil) {
- t.Fatalf("Index: %d ip failed Error: %s", i, errs)
- }
- } else {
- if IsEqual(errs, nil) {
- t.Fatalf("Index: %d ip failed Error: %s", i, errs)
- } else {
- val := getError(errs, "", "")
- if val.Tag() != "ip" {
- t.Fatalf("Index: %d ip failed Error: %s", i, errs)
- }
- }
- }
- }
-}
-
-func TestIPv6Validation(t *testing.T) {
- tests := []struct {
- param string
- expected bool
- }{
- {"10.0.0.1", false},
- {"172.16.0.1", false},
- {"192.168.0.1", false},
- {"192.168.255.254", false},
- {"192.168.255.256", false},
- {"172.16.255.254", false},
- {"172.16.256.255", false},
- {"2001:cdba:0000:0000:0000:0000:3257:9652", true},
- {"2001:cdba:0:0:0:0:3257:9652", true},
- {"2001:cdba::3257:9652", true},
- }
-
- validate := New()
-
- for i, test := range tests {
-
- errs := validate.Var(test.param, "ipv6")
-
- if test.expected {
- if !IsEqual(errs, nil) {
- t.Fatalf("Index: %d ipv6 failed Error: %s", i, errs)
- }
- } else {
- if IsEqual(errs, nil) {
- t.Fatalf("Index: %d ipv6 failed Error: %s", i, errs)
- } else {
- val := getError(errs, "", "")
- if val.Tag() != "ipv6" {
- t.Fatalf("Index: %d ipv6 failed Error: %s", i, errs)
- }
- }
- }
- }
-}
-
-func TestIPv4Validation(t *testing.T) {
- tests := []struct {
- param string
- expected bool
- }{
- {"10.0.0.1", true},
- {"172.16.0.1", true},
- {"192.168.0.1", true},
- {"192.168.255.254", true},
- {"192.168.255.256", false},
- {"172.16.255.254", true},
- {"172.16.256.255", false},
- {"2001:cdba:0000:0000:0000:0000:3257:9652", false},
- {"2001:cdba:0:0:0:0:3257:9652", false},
- {"2001:cdba::3257:9652", false},
- }
-
- validate := New()
-
- for i, test := range tests {
-
- errs := validate.Var(test.param, "ipv4")
-
- if test.expected {
- if !IsEqual(errs, nil) {
- t.Fatalf("Index: %d ipv4 failed Error: %s", i, errs)
- }
- } else {
- if IsEqual(errs, nil) {
- t.Fatalf("Index: %d ipv4 failed Error: %s", i, errs)
- } else {
- val := getError(errs, "", "")
- if val.Tag() != "ipv4" {
- t.Fatalf("Index: %d ipv4 failed Error: %s", i, errs)
- }
- }
- }
- }
-}
-
-func TestCIDRValidation(t *testing.T) {
- tests := []struct {
- param string
- expected bool
- }{
- {"10.0.0.0/0", true},
- {"10.0.0.1/8", true},
- {"172.16.0.1/16", true},
- {"192.168.0.1/24", true},
- {"192.168.255.254/24", true},
- {"192.168.255.254/48", false},
- {"192.168.255.256/24", false},
- {"172.16.255.254/16", true},
- {"172.16.256.255/16", false},
- {"2001:cdba:0000:0000:0000:0000:3257:9652/64", true},
- {"2001:cdba:0000:0000:0000:0000:3257:9652/256", false},
- {"2001:cdba:0:0:0:0:3257:9652/32", true},
- {"2001:cdba::3257:9652/16", true},
- }
-
- validate := New()
-
- for i, test := range tests {
-
- errs := validate.Var(test.param, "cidr")
-
- if test.expected {
- if !IsEqual(errs, nil) {
- t.Fatalf("Index: %d cidr failed Error: %s", i, errs)
- }
- } else {
- if IsEqual(errs, nil) {
- t.Fatalf("Index: %d cidr failed Error: %s", i, errs)
- } else {
- val := getError(errs, "", "")
- if val.Tag() != "cidr" {
- t.Fatalf("Index: %d cidr failed Error: %s", i, errs)
- }
- }
- }
- }
-}
-
-func TestCIDRv6Validation(t *testing.T) {
- tests := []struct {
- param string
- expected bool
- }{
- {"10.0.0.0/0", false},
- {"10.0.0.1/8", false},
- {"172.16.0.1/16", false},
- {"192.168.0.1/24", false},
- {"192.168.255.254/24", false},
- {"192.168.255.254/48", false},
- {"192.168.255.256/24", false},
- {"172.16.255.254/16", false},
- {"172.16.256.255/16", false},
- {"2001:cdba:0000:0000:0000:0000:3257:9652/64", true},
- {"2001:cdba:0000:0000:0000:0000:3257:9652/256", false},
- {"2001:cdba:0:0:0:0:3257:9652/32", true},
- {"2001:cdba::3257:9652/16", true},
- }
-
- validate := New()
-
- for i, test := range tests {
-
- errs := validate.Var(test.param, "cidrv6")
-
- if test.expected {
- if !IsEqual(errs, nil) {
- t.Fatalf("Index: %d cidrv6 failed Error: %s", i, errs)
- }
- } else {
- if IsEqual(errs, nil) {
- t.Fatalf("Index: %d cidrv6 failed Error: %s", i, errs)
- } else {
- val := getError(errs, "", "")
- if val.Tag() != "cidrv6" {
- t.Fatalf("Index: %d cidrv6 failed Error: %s", i, errs)
- }
- }
- }
- }
-}
-
-func TestCIDRv4Validation(t *testing.T) {
- tests := []struct {
- param string
- expected bool
- }{
- {"10.0.0.0/0", true},
- {"10.0.0.1/8", true},
- {"172.16.0.1/16", true},
- {"192.168.0.1/24", true},
- {"192.168.255.254/24", true},
- {"192.168.255.254/48", false},
- {"192.168.255.256/24", false},
- {"172.16.255.254/16", true},
- {"172.16.256.255/16", false},
- {"2001:cdba:0000:0000:0000:0000:3257:9652/64", false},
- {"2001:cdba:0000:0000:0000:0000:3257:9652/256", false},
- {"2001:cdba:0:0:0:0:3257:9652/32", false},
- {"2001:cdba::3257:9652/16", false},
- }
-
- validate := New()
-
- for i, test := range tests {
-
- errs := validate.Var(test.param, "cidrv4")
-
- if test.expected {
- if !IsEqual(errs, nil) {
- t.Fatalf("Index: %d cidrv4 failed Error: %s", i, errs)
- }
- } else {
- if IsEqual(errs, nil) {
- t.Fatalf("Index: %d cidrv4 failed Error: %s", i, errs)
- } else {
- val := getError(errs, "", "")
- if val.Tag() != "cidrv4" {
- t.Fatalf("Index: %d cidrv4 failed Error: %s", i, errs)
- }
- }
- }
- }
-}
-
-func TestTCPAddrValidation(t *testing.T) {
- tests := []struct {
- param string
- expected bool
- }{
- {"", false},
- {":80", false},
- {"127.0.0.1:80", true},
- {"[::1]:80", true},
- {"256.0.0.0:1", false},
- {"[::1]", false},
- }
-
- validate := New()
-
- for i, test := range tests {
- errs := validate.Var(test.param, "tcp_addr")
- if test.expected {
- if !IsEqual(errs, nil) {
- t.Fatalf("Index: %d tcp_addr failed Error: %s", i, errs)
- }
- } else {
- if IsEqual(errs, nil) {
- t.Fatalf("Index: %d tcp_addr failed Error: %s", i, errs)
- } else {
- val := getError(errs, "", "")
- if val.Tag() != "tcp_addr" {
- t.Fatalf("Index: %d tcp_addr failed Error: %s", i, errs)
- }
- }
- }
- }
-}
-
-func TestTCP6AddrValidation(t *testing.T) {
- tests := []struct {
- param string
- expected bool
- }{
- {"", false},
- {":80", false},
- {"127.0.0.1:80", false},
- {"[::1]:80", true},
- {"256.0.0.0:1", false},
- {"[::1]", false},
- }
-
- validate := New()
-
- for i, test := range tests {
- errs := validate.Var(test.param, "tcp6_addr")
- if test.expected {
- if !IsEqual(errs, nil) {
- t.Fatalf("Index: %d tcp6_addr failed Error: %s", i, errs)
- }
- } else {
- if IsEqual(errs, nil) {
- t.Fatalf("Index: %d tcp6_addr failed Error: %s", i, errs)
- } else {
- val := getError(errs, "", "")
- if val.Tag() != "tcp6_addr" {
- t.Fatalf("Index: %d tcp6_addr failed Error: %s", i, errs)
- }
- }
- }
- }
-}
-
-func TestTCP4AddrValidation(t *testing.T) {
- tests := []struct {
- param string
- expected bool
- }{
- {"", false},
- {":80", false},
- {"127.0.0.1:80", true},
- {"[::1]:80", false}, // https://github.com/golang/go/issues/14037
- {"256.0.0.0:1", false},
- {"[::1]", false},
- }
-
- validate := New()
-
- for i, test := range tests {
- errs := validate.Var(test.param, "tcp4_addr")
- if test.expected {
- if !IsEqual(errs, nil) {
- t.Fatalf("Index: %d tcp4_addr failed Error: %s", i, errs)
- }
- } else {
- if IsEqual(errs, nil) {
- t.Log(test.param, IsEqual(errs, nil))
- t.Fatalf("Index: %d tcp4_addr failed Error: %s", i, errs)
- } else {
- val := getError(errs, "", "")
- if val.Tag() != "tcp4_addr" {
- t.Fatalf("Index: %d tcp4_addr failed Error: %s", i, errs)
- }
- }
- }
- }
-}
-
-func TestUDPAddrValidation(t *testing.T) {
- tests := []struct {
- param string
- expected bool
- }{
- {"", false},
- {":80", false},
- {"127.0.0.1:80", true},
- {"[::1]:80", true},
- {"256.0.0.0:1", false},
- {"[::1]", false},
- }
-
- validate := New()
-
- for i, test := range tests {
- errs := validate.Var(test.param, "udp_addr")
- if test.expected {
- if !IsEqual(errs, nil) {
- t.Fatalf("Index: %d udp_addr failed Error: %s", i, errs)
- }
- } else {
- if IsEqual(errs, nil) {
- t.Fatalf("Index: %d udp_addr failed Error: %s", i, errs)
- } else {
- val := getError(errs, "", "")
- if val.Tag() != "udp_addr" {
- t.Fatalf("Index: %d udp_addr failed Error: %s", i, errs)
- }
- }
- }
- }
-}
-
-func TestUDP6AddrValidation(t *testing.T) {
- tests := []struct {
- param string
- expected bool
- }{
- {"", false},
- {":80", false},
- {"127.0.0.1:80", false},
- {"[::1]:80", true},
- {"256.0.0.0:1", false},
- {"[::1]", false},
- }
-
- validate := New()
-
- for i, test := range tests {
- errs := validate.Var(test.param, "udp6_addr")
- if test.expected {
- if !IsEqual(errs, nil) {
- t.Fatalf("Index: %d udp6_addr failed Error: %s", i, errs)
- }
- } else {
- if IsEqual(errs, nil) {
- t.Fatalf("Index: %d udp6_addr failed Error: %s", i, errs)
- } else {
- val := getError(errs, "", "")
- if val.Tag() != "udp6_addr" {
- t.Fatalf("Index: %d udp6_addr failed Error: %s", i, errs)
- }
- }
- }
- }
-}
-
-func TestUDP4AddrValidation(t *testing.T) {
- tests := []struct {
- param string
- expected bool
- }{
- {"", false},
- {":80", false},
- {"127.0.0.1:80", true},
- {"[::1]:80", false}, // https://github.com/golang/go/issues/14037
- {"256.0.0.0:1", false},
- {"[::1]", false},
- }
-
- validate := New()
-
- for i, test := range tests {
- errs := validate.Var(test.param, "udp4_addr")
- if test.expected {
- if !IsEqual(errs, nil) {
- t.Fatalf("Index: %d udp4_addr failed Error: %s", i, errs)
- }
- } else {
- if IsEqual(errs, nil) {
- t.Log(test.param, IsEqual(errs, nil))
- t.Fatalf("Index: %d udp4_addr failed Error: %s", i, errs)
- } else {
- val := getError(errs, "", "")
- if val.Tag() != "udp4_addr" {
- t.Fatalf("Index: %d udp4_addr failed Error: %s", i, errs)
- }
- }
- }
- }
-}
-
-func TestIPAddrValidation(t *testing.T) {
- tests := []struct {
- param string
- expected bool
- }{
- {"", false},
- {"127.0.0.1", true},
- {"127.0.0.1:80", false},
- {"::1", true},
- {"256.0.0.0", false},
- {"localhost", false},
- }
-
- validate := New()
-
- for i, test := range tests {
- errs := validate.Var(test.param, "ip_addr")
- if test.expected {
- if !IsEqual(errs, nil) {
- t.Fatalf("Index: %d ip_addr failed Error: %s", i, errs)
- }
- } else {
- if IsEqual(errs, nil) {
- t.Fatalf("Index: %d ip_addr failed Error: %s", i, errs)
- } else {
- val := getError(errs, "", "")
- if val.Tag() != "ip_addr" {
- t.Fatalf("Index: %d ip_addr failed Error: %s", i, errs)
- }
- }
- }
- }
-}
-
-func TestIP6AddrValidation(t *testing.T) {
- tests := []struct {
- param string
- expected bool
- }{
- {"", false},
- {"127.0.0.1", false}, // https://github.com/golang/go/issues/14037
- {"127.0.0.1:80", false},
- {"::1", true},
- {"0:0:0:0:0:0:0:1", true},
- {"256.0.0.0", false},
- }
-
- validate := New()
-
- for i, test := range tests {
- errs := validate.Var(test.param, "ip6_addr")
- if test.expected {
- if !IsEqual(errs, nil) {
- t.Fatalf("Index: %d ip6_addr failed Error: %s", i, errs)
- }
- } else {
- if IsEqual(errs, nil) {
- t.Fatalf("Index: %d ip6_addr failed Error: %s", i, errs)
- } else {
- val := getError(errs, "", "")
- if val.Tag() != "ip6_addr" {
- t.Fatalf("Index: %d ip6_addr failed Error: %s", i, errs)
- }
- }
- }
- }
-}
-
-func TestIP4AddrValidation(t *testing.T) {
- tests := []struct {
- param string
- expected bool
- }{
- {"", false},
- {"127.0.0.1", true},
- {"127.0.0.1:80", false},
- {"::1", false}, // https://github.com/golang/go/issues/14037
- {"256.0.0.0", false},
- {"localhost", false},
- }
-
- validate := New()
-
- for i, test := range tests {
- errs := validate.Var(test.param, "ip4_addr")
- if test.expected {
- if !IsEqual(errs, nil) {
- t.Fatalf("Index: %d ip4_addr failed Error: %s", i, errs)
- }
- } else {
- if IsEqual(errs, nil) {
- t.Log(test.param, IsEqual(errs, nil))
- t.Fatalf("Index: %d ip4_addr failed Error: %s", i, errs)
- } else {
- val := getError(errs, "", "")
- if val.Tag() != "ip4_addr" {
- t.Fatalf("Index: %d ip4_addr failed Error: %s", i, errs)
- }
- }
- }
- }
-}
-
-func TestUnixAddrValidation(t *testing.T) {
- tests := []struct {
- param string
- expected bool
- }{
- {"", true},
- {"v.sock", true},
- }
-
- validate := New()
-
- for i, test := range tests {
- errs := validate.Var(test.param, "unix_addr")
- if test.expected {
- if !IsEqual(errs, nil) {
- t.Fatalf("Index: %d unix_addr failed Error: %s", i, errs)
- }
- } else {
- if IsEqual(errs, nil) {
- t.Log(test.param, IsEqual(errs, nil))
- t.Fatalf("Index: %d unix_addr failed Error: %s", i, errs)
- } else {
- val := getError(errs, "", "")
- if val.Tag() != "unix_addr" {
- t.Fatalf("Index: %d unix_addr failed Error: %s", i, errs)
- }
- }
- }
- }
-}
-
-func TestSliceMapArrayChanFuncPtrInterfaceRequiredValidation(t *testing.T) {
-
- validate := New()
-
- var m map[string]string
-
- errs := validate.Var(m, "required")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "required")
-
- m = map[string]string{}
- errs = validate.Var(m, "required")
- Equal(t, errs, nil)
-
- var arr [5]string
- errs = validate.Var(arr, "required")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "required")
-
- arr[0] = "ok"
- errs = validate.Var(arr, "required")
- Equal(t, errs, nil)
-
- var s []string
- errs = validate.Var(s, "required")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "required")
-
- s = []string{}
- errs = validate.Var(s, "required")
- Equal(t, errs, nil)
-
- var c chan string
- errs = validate.Var(c, "required")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "required")
-
- c = make(chan string)
- errs = validate.Var(c, "required")
- Equal(t, errs, nil)
-
- var tst *int
- errs = validate.Var(tst, "required")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "required")
-
- one := 1
- tst = &one
- errs = validate.Var(tst, "required")
- Equal(t, errs, nil)
-
- var iface interface{}
-
- errs = validate.Var(iface, "required")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "required")
-
- errs = validate.Var(iface, "omitempty,required")
- Equal(t, errs, nil)
-
- errs = validate.Var(iface, "")
- Equal(t, errs, nil)
-
- errs = validate.VarWithValue(nil, iface, "")
- Equal(t, errs, nil)
-
- var f func(string)
-
- errs = validate.Var(f, "required")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "required")
-
- f = func(name string) {}
-
- errs = validate.Var(f, "required")
- Equal(t, errs, nil)
-}
-
-func TestDatePtrValidationIssueValidation(t *testing.T) {
-
- type Test struct {
- LastViewed *time.Time
- Reminder *time.Time
- }
-
- test := &Test{}
-
- validate := New()
- errs := validate.Struct(test)
- Equal(t, errs, nil)
-}
-
-func TestCommaAndPipeObfuscationValidation(t *testing.T) {
- s := "My Name Is, |joeybloggs|"
-
- validate := New()
-
- errs := validate.Var(s, "excludesall=0x2C")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "excludesall")
-
- errs = validate.Var(s, "excludesall=0x7C")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "excludesall")
-}
-
-func TestBadKeyValidation(t *testing.T) {
- type Test struct {
- Name string `validate:"required, "`
- }
-
- tst := &Test{
- Name: "test",
- }
-
- validate := New()
-
- PanicMatches(t, func() { validate.Struct(tst) }, "Undefined validation function ' ' on field 'Name'")
-
- type Test2 struct {
- Name string `validate:"required,,len=2"`
- }
-
- tst2 := &Test2{
- Name: "test",
- }
-
- PanicMatches(t, func() { validate.Struct(tst2) }, "Invalid validation tag on field 'Name'")
-}
-
-func TestInterfaceErrValidation(t *testing.T) {
-
- var v2 interface{} = 1
- var v1 interface{} = v2
-
- validate := New()
- errs := validate.Var(v1, "len=1")
- Equal(t, errs, nil)
-
- errs = validate.Var(v2, "len=1")
- Equal(t, errs, nil)
-
- type ExternalCMD struct {
- Userid string `json:"userid"`
- Action uint32 `json:"action"`
- Data interface{} `json:"data,omitempty" validate:"required"`
- }
-
- s := &ExternalCMD{
- Userid: "123456",
- Action: 10000,
- // Data: 1,
- }
-
- errs = validate.Struct(s)
- NotEqual(t, errs, nil)
- Equal(t, len(errs.(ValidationErrors)), 1)
- AssertError(t, errs, "ExternalCMD.Data", "ExternalCMD.Data", "Data", "Data", "required")
-
- type ExternalCMD2 struct {
- Userid string `json:"userid"`
- Action uint32 `json:"action"`
- Data interface{} `json:"data,omitempty" validate:"len=1"`
- }
-
- s2 := &ExternalCMD2{
- Userid: "123456",
- Action: 10000,
- // Data: 1,
- }
-
- errs = validate.Struct(s2)
- NotEqual(t, errs, nil)
- Equal(t, len(errs.(ValidationErrors)), 1)
- AssertError(t, errs, "ExternalCMD2.Data", "ExternalCMD2.Data", "Data", "Data", "len")
-
- s3 := &ExternalCMD2{
- Userid: "123456",
- Action: 10000,
- Data: 2,
- }
-
- errs = validate.Struct(s3)
- NotEqual(t, errs, nil)
- Equal(t, len(errs.(ValidationErrors)), 1)
- AssertError(t, errs, "ExternalCMD2.Data", "ExternalCMD2.Data", "Data", "Data", "len")
-
- type Inner struct {
- Name string `validate:"required"`
- }
-
- inner := &Inner{
- Name: "",
- }
-
- s4 := &ExternalCMD{
- Userid: "123456",
- Action: 10000,
- Data: inner,
- }
-
- errs = validate.Struct(s4)
- NotEqual(t, errs, nil)
- Equal(t, len(errs.(ValidationErrors)), 1)
- AssertError(t, errs, "ExternalCMD.Data.Name", "ExternalCMD.Data.Name", "Name", "Name", "required")
-
- type TestMapStructPtr struct {
- Errs map[int]interface{} `validate:"gt=0,dive,len=2"`
- }
-
- mip := map[int]interface{}{0: &Inner{"ok"}, 3: nil, 4: &Inner{"ok"}}
-
- msp := &TestMapStructPtr{
- Errs: mip,
- }
-
- errs = validate.Struct(msp)
- NotEqual(t, errs, nil)
- Equal(t, len(errs.(ValidationErrors)), 1)
- AssertError(t, errs, "TestMapStructPtr.Errs[3]", "TestMapStructPtr.Errs[3]", "Errs[3]", "Errs[3]", "len")
-
- type TestMultiDimensionalStructs struct {
- Errs [][]interface{} `validate:"gt=0,dive,dive"`
- }
-
- var errStructArray [][]interface{}
-
- errStructArray = append(errStructArray, []interface{}{&Inner{"ok"}, &Inner{""}, &Inner{""}})
- errStructArray = append(errStructArray, []interface{}{&Inner{"ok"}, &Inner{""}, &Inner{""}})
-
- tms := &TestMultiDimensionalStructs{
- Errs: errStructArray,
- }
-
- errs = validate.Struct(tms)
- NotEqual(t, errs, nil)
- Equal(t, len(errs.(ValidationErrors)), 4)
- AssertError(t, errs, "TestMultiDimensionalStructs.Errs[0][1].Name", "TestMultiDimensionalStructs.Errs[0][1].Name", "Name", "Name", "required")
- AssertError(t, errs, "TestMultiDimensionalStructs.Errs[0][2].Name", "TestMultiDimensionalStructs.Errs[0][2].Name", "Name", "Name", "required")
- AssertError(t, errs, "TestMultiDimensionalStructs.Errs[1][1].Name", "TestMultiDimensionalStructs.Errs[1][1].Name", "Name", "Name", "required")
- AssertError(t, errs, "TestMultiDimensionalStructs.Errs[1][2].Name", "TestMultiDimensionalStructs.Errs[1][2].Name", "Name", "Name", "required")
-
- type TestMultiDimensionalStructsPtr2 struct {
- Errs [][]*Inner `validate:"gt=0,dive,dive,required"`
- }
-
- var errStructPtr2Array [][]*Inner
-
- errStructPtr2Array = append(errStructPtr2Array, []*Inner{{"ok"}, {""}, {""}})
- errStructPtr2Array = append(errStructPtr2Array, []*Inner{{"ok"}, {""}, {""}})
- errStructPtr2Array = append(errStructPtr2Array, []*Inner{{"ok"}, {""}, nil})
-
- tmsp2 := &TestMultiDimensionalStructsPtr2{
- Errs: errStructPtr2Array,
- }
-
- errs = validate.Struct(tmsp2)
- NotEqual(t, errs, nil)
- Equal(t, len(errs.(ValidationErrors)), 6)
- AssertError(t, errs, "TestMultiDimensionalStructsPtr2.Errs[0][1].Name", "TestMultiDimensionalStructsPtr2.Errs[0][1].Name", "Name", "Name", "required")
- AssertError(t, errs, "TestMultiDimensionalStructsPtr2.Errs[0][2].Name", "TestMultiDimensionalStructsPtr2.Errs[0][2].Name", "Name", "Name", "required")
- AssertError(t, errs, "TestMultiDimensionalStructsPtr2.Errs[1][1].Name", "TestMultiDimensionalStructsPtr2.Errs[1][1].Name", "Name", "Name", "required")
- AssertError(t, errs, "TestMultiDimensionalStructsPtr2.Errs[1][2].Name", "TestMultiDimensionalStructsPtr2.Errs[1][2].Name", "Name", "Name", "required")
- AssertError(t, errs, "TestMultiDimensionalStructsPtr2.Errs[2][1].Name", "TestMultiDimensionalStructsPtr2.Errs[2][1].Name", "Name", "Name", "required")
- AssertError(t, errs, "TestMultiDimensionalStructsPtr2.Errs[2][2]", "TestMultiDimensionalStructsPtr2.Errs[2][2]", "Errs[2][2]", "Errs[2][2]", "required")
-
- m := map[int]interface{}{0: "ok", 3: "", 4: "ok"}
-
- errs = validate.Var(m, "len=3,dive,len=2")
- NotEqual(t, errs, nil)
- Equal(t, len(errs.(ValidationErrors)), 1)
- AssertError(t, errs, "[3]", "[3]", "[3]", "[3]", "len")
-
- errs = validate.Var(m, "len=2,dive,required")
- NotEqual(t, errs, nil)
- Equal(t, len(errs.(ValidationErrors)), 1)
- AssertError(t, errs, "", "", "", "", "len")
-
- arr := []interface{}{"ok", "", "ok"}
-
- errs = validate.Var(arr, "len=3,dive,len=2")
- NotEqual(t, errs, nil)
- Equal(t, len(errs.(ValidationErrors)), 1)
- AssertError(t, errs, "[1]", "[1]", "[1]", "[1]", "len")
-
- errs = validate.Var(arr, "len=2,dive,required")
- NotEqual(t, errs, nil)
- Equal(t, len(errs.(ValidationErrors)), 1)
- AssertError(t, errs, "", "", "", "", "len")
-
- type MyStruct struct {
- A, B string
- C interface{}
- }
-
- var a MyStruct
-
- a.A = "value"
- a.C = "nu"
-
- errs = validate.Struct(a)
- Equal(t, errs, nil)
-}
-
-func TestMapDiveValidation(t *testing.T) {
-
- validate := New()
-
- n := map[int]interface{}{0: nil}
- errs := validate.Var(n, "omitempty,required")
- Equal(t, errs, nil)
-
- m := map[int]string{0: "ok", 3: "", 4: "ok"}
-
- errs = validate.Var(m, "len=3,dive,required")
- NotEqual(t, errs, nil)
- Equal(t, len(errs.(ValidationErrors)), 1)
- AssertError(t, errs, "[3]", "[3]", "[3]", "[3]", "required")
-
- errs = validate.Var(m, "len=2,dive,required")
- NotEqual(t, errs, nil)
- Equal(t, len(errs.(ValidationErrors)), 1)
- AssertError(t, errs, "", "", "", "", "len")
-
- type Inner struct {
- Name string `validate:"required"`
- }
-
- type TestMapStruct struct {
- Errs map[int]Inner `validate:"gt=0,dive"`
- }
-
- mi := map[int]Inner{0: {"ok"}, 3: {""}, 4: {"ok"}}
-
- ms := &TestMapStruct{
- Errs: mi,
- }
-
- errs = validate.Struct(ms)
- NotEqual(t, errs, nil)
- Equal(t, len(errs.(ValidationErrors)), 1)
- AssertError(t, errs, "TestMapStruct.Errs[3].Name", "TestMapStruct.Errs[3].Name", "Name", "Name", "required")
-
- // for full test coverage
- s := fmt.Sprint(errs.Error())
- NotEqual(t, s, "")
-
- type TestMapTimeStruct struct {
- Errs map[int]*time.Time `validate:"gt=0,dive,required"`
- }
-
- t1 := time.Now().UTC()
-
- mta := map[int]*time.Time{0: &t1, 3: nil, 4: nil}
-
- mt := &TestMapTimeStruct{
- Errs: mta,
- }
-
- errs = validate.Struct(mt)
- NotEqual(t, errs, nil)
- Equal(t, len(errs.(ValidationErrors)), 2)
- AssertError(t, errs, "TestMapTimeStruct.Errs[3]", "TestMapTimeStruct.Errs[3]", "Errs[3]", "Errs[3]", "required")
- AssertError(t, errs, "TestMapTimeStruct.Errs[4]", "TestMapTimeStruct.Errs[4]", "Errs[4]", "Errs[4]", "required")
-
- type TestMapStructPtr struct {
- Errs map[int]*Inner `validate:"gt=0,dive,required"`
- }
-
- mip := map[int]*Inner{0: {"ok"}, 3: nil, 4: {"ok"}}
-
- msp := &TestMapStructPtr{
- Errs: mip,
- }
-
- errs = validate.Struct(msp)
- NotEqual(t, errs, nil)
- Equal(t, len(errs.(ValidationErrors)), 1)
- AssertError(t, errs, "TestMapStructPtr.Errs[3]", "TestMapStructPtr.Errs[3]", "Errs[3]", "Errs[3]", "required")
-
- type TestMapStructPtr2 struct {
- Errs map[int]*Inner `validate:"gt=0,dive,omitempty,required"`
- }
-
- mip2 := map[int]*Inner{0: {"ok"}, 3: nil, 4: {"ok"}}
-
- msp2 := &TestMapStructPtr2{
- Errs: mip2,
- }
-
- errs = validate.Struct(msp2)
- Equal(t, errs, nil)
-
- v2 := New()
- v2.RegisterTagNameFunc(func(fld reflect.StructField) string {
- name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0]
-
- if name == "-" {
- return ""
- }
-
- return name
- })
-
- type MapDiveJSONTest struct {
- Map map[string]string `validate:"required,gte=1,dive,gte=1" json:"MyName"`
- }
-
- mdjt := &MapDiveJSONTest{
- Map: map[string]string{
- "Key1": "Value1",
- "Key2": "",
- },
- }
-
- err := v2.Struct(mdjt)
- NotEqual(t, err, nil)
-
- errs = err.(ValidationErrors)
- fe := getError(errs, "MapDiveJSONTest.MyName[Key2]", "MapDiveJSONTest.Map[Key2]")
- NotEqual(t, fe, nil)
- Equal(t, fe.Tag(), "gte")
- Equal(t, fe.ActualTag(), "gte")
- Equal(t, fe.Field(), "MyName[Key2]")
- Equal(t, fe.StructField(), "Map[Key2]")
-}
-
-func TestArrayDiveValidation(t *testing.T) {
-
- validate := New()
-
- arr := []string{"ok", "", "ok"}
-
- errs := validate.Var(arr, "len=3,dive,required")
- NotEqual(t, errs, nil)
- Equal(t, len(errs.(ValidationErrors)), 1)
- AssertError(t, errs, "[1]", "[1]", "[1]", "[1]", "required")
-
- errs = validate.Var(arr, "len=2,dive,required")
- NotEqual(t, errs, nil)
- Equal(t, len(errs.(ValidationErrors)), 1)
- AssertError(t, errs, "", "", "", "", "len")
-
- type BadDive struct {
- Name string `validate:"dive"`
- }
-
- bd := &BadDive{
- Name: "TEST",
- }
-
- PanicMatches(t, func() { validate.Struct(bd) }, "dive error! can't dive on a non slice or map")
-
- type Test struct {
- Errs []string `validate:"gt=0,dive,required"`
- }
-
- test := &Test{
- Errs: []string{"ok", "", "ok"},
- }
-
- errs = validate.Struct(test)
- NotEqual(t, errs, nil)
- Equal(t, len(errs.(ValidationErrors)), 1)
- AssertError(t, errs, "Test.Errs[1]", "Test.Errs[1]", "Errs[1]", "Errs[1]", "required")
-
- test = &Test{
- Errs: []string{"ok", "ok", ""},
- }
-
- errs = validate.Struct(test)
- NotEqual(t, errs, nil)
- Equal(t, len(errs.(ValidationErrors)), 1)
- AssertError(t, errs, "Test.Errs[2]", "Test.Errs[2]", "Errs[2]", "Errs[2]", "required")
-
- type TestMultiDimensional struct {
- Errs [][]string `validate:"gt=0,dive,dive,required"`
- }
-
- var errArray [][]string
-
- errArray = append(errArray, []string{"ok", "", ""})
- errArray = append(errArray, []string{"ok", "", ""})
-
- tm := &TestMultiDimensional{
- Errs: errArray,
- }
-
- errs = validate.Struct(tm)
- NotEqual(t, errs, nil)
- Equal(t, len(errs.(ValidationErrors)), 4)
- AssertError(t, errs, "TestMultiDimensional.Errs[0][1]", "TestMultiDimensional.Errs[0][1]", "Errs[0][1]", "Errs[0][1]", "required")
- AssertError(t, errs, "TestMultiDimensional.Errs[0][2]", "TestMultiDimensional.Errs[0][2]", "Errs[0][2]", "Errs[0][2]", "required")
- AssertError(t, errs, "TestMultiDimensional.Errs[1][1]", "TestMultiDimensional.Errs[1][1]", "Errs[1][1]", "Errs[1][1]", "required")
- AssertError(t, errs, "TestMultiDimensional.Errs[1][2]", "TestMultiDimensional.Errs[1][2]", "Errs[1][2]", "Errs[1][2]", "required")
-
- type Inner struct {
- Name string `validate:"required"`
- }
-
- type TestMultiDimensionalStructs struct {
- Errs [][]Inner `validate:"gt=0,dive,dive"`
- }
-
- var errStructArray [][]Inner
-
- errStructArray = append(errStructArray, []Inner{{"ok"}, {""}, {""}})
- errStructArray = append(errStructArray, []Inner{{"ok"}, {""}, {""}})
-
- tms := &TestMultiDimensionalStructs{
- Errs: errStructArray,
- }
-
- errs = validate.Struct(tms)
- NotEqual(t, errs, nil)
- Equal(t, len(errs.(ValidationErrors)), 4)
- AssertError(t, errs, "TestMultiDimensionalStructs.Errs[0][1].Name", "TestMultiDimensionalStructs.Errs[0][1].Name", "Name", "Name", "required")
- AssertError(t, errs, "TestMultiDimensionalStructs.Errs[0][2].Name", "TestMultiDimensionalStructs.Errs[0][2].Name", "Name", "Name", "required")
- AssertError(t, errs, "TestMultiDimensionalStructs.Errs[1][1].Name", "TestMultiDimensionalStructs.Errs[1][1].Name", "Name", "Name", "required")
- AssertError(t, errs, "TestMultiDimensionalStructs.Errs[1][2].Name", "TestMultiDimensionalStructs.Errs[1][2].Name", "Name", "Name", "required")
-
- type TestMultiDimensionalStructsPtr struct {
- Errs [][]*Inner `validate:"gt=0,dive,dive"`
- }
-
- var errStructPtrArray [][]*Inner
-
- errStructPtrArray = append(errStructPtrArray, []*Inner{{"ok"}, {""}, {""}})
- errStructPtrArray = append(errStructPtrArray, []*Inner{{"ok"}, {""}, {""}})
- errStructPtrArray = append(errStructPtrArray, []*Inner{{"ok"}, {""}, nil})
-
- tmsp := &TestMultiDimensionalStructsPtr{
- Errs: errStructPtrArray,
- }
-
- errs = validate.Struct(tmsp)
- NotEqual(t, errs, nil)
- Equal(t, len(errs.(ValidationErrors)), 5)
- AssertError(t, errs, "TestMultiDimensionalStructsPtr.Errs[0][1].Name", "TestMultiDimensionalStructsPtr.Errs[0][1].Name", "Name", "Name", "required")
- AssertError(t, errs, "TestMultiDimensionalStructsPtr.Errs[0][2].Name", "TestMultiDimensionalStructsPtr.Errs[0][2].Name", "Name", "Name", "required")
- AssertError(t, errs, "TestMultiDimensionalStructsPtr.Errs[1][1].Name", "TestMultiDimensionalStructsPtr.Errs[1][1].Name", "Name", "Name", "required")
- AssertError(t, errs, "TestMultiDimensionalStructsPtr.Errs[1][2].Name", "TestMultiDimensionalStructsPtr.Errs[1][2].Name", "Name", "Name", "required")
- AssertError(t, errs, "TestMultiDimensionalStructsPtr.Errs[2][1].Name", "TestMultiDimensionalStructsPtr.Errs[2][1].Name", "Name", "Name", "required")
-
- // for full test coverage
- s := fmt.Sprint(errs.Error())
- NotEqual(t, s, "")
-
- type TestMultiDimensionalStructsPtr2 struct {
- Errs [][]*Inner `validate:"gt=0,dive,dive,required"`
- }
-
- var errStructPtr2Array [][]*Inner
-
- errStructPtr2Array = append(errStructPtr2Array, []*Inner{{"ok"}, {""}, {""}})
- errStructPtr2Array = append(errStructPtr2Array, []*Inner{{"ok"}, {""}, {""}})
- errStructPtr2Array = append(errStructPtr2Array, []*Inner{{"ok"}, {""}, nil})
-
- tmsp2 := &TestMultiDimensionalStructsPtr2{
- Errs: errStructPtr2Array,
- }
-
- errs = validate.Struct(tmsp2)
- NotEqual(t, errs, nil)
- Equal(t, len(errs.(ValidationErrors)), 6)
- AssertError(t, errs, "TestMultiDimensionalStructsPtr2.Errs[0][1].Name", "TestMultiDimensionalStructsPtr2.Errs[0][1].Name", "Name", "Name", "required")
- AssertError(t, errs, "TestMultiDimensionalStructsPtr2.Errs[0][2].Name", "TestMultiDimensionalStructsPtr2.Errs[0][2].Name", "Name", "Name", "required")
- AssertError(t, errs, "TestMultiDimensionalStructsPtr2.Errs[1][1].Name", "TestMultiDimensionalStructsPtr2.Errs[1][1].Name", "Name", "Name", "required")
- AssertError(t, errs, "TestMultiDimensionalStructsPtr2.Errs[1][2].Name", "TestMultiDimensionalStructsPtr2.Errs[1][2].Name", "Name", "Name", "required")
- AssertError(t, errs, "TestMultiDimensionalStructsPtr2.Errs[2][1].Name", "TestMultiDimensionalStructsPtr2.Errs[2][1].Name", "Name", "Name", "required")
- AssertError(t, errs, "TestMultiDimensionalStructsPtr2.Errs[2][2]", "TestMultiDimensionalStructsPtr2.Errs[2][2]", "Errs[2][2]", "Errs[2][2]", "required")
-
- type TestMultiDimensionalStructsPtr3 struct {
- Errs [][]*Inner `validate:"gt=0,dive,dive,omitempty"`
- }
-
- var errStructPtr3Array [][]*Inner
-
- errStructPtr3Array = append(errStructPtr3Array, []*Inner{{"ok"}, {""}, {""}})
- errStructPtr3Array = append(errStructPtr3Array, []*Inner{{"ok"}, {""}, {""}})
- errStructPtr3Array = append(errStructPtr3Array, []*Inner{{"ok"}, {""}, nil})
-
- tmsp3 := &TestMultiDimensionalStructsPtr3{
- Errs: errStructPtr3Array,
- }
-
- errs = validate.Struct(tmsp3)
- NotEqual(t, errs, nil)
- Equal(t, len(errs.(ValidationErrors)), 5)
- AssertError(t, errs, "TestMultiDimensionalStructsPtr3.Errs[0][1].Name", "TestMultiDimensionalStructsPtr3.Errs[0][1].Name", "Name", "Name", "required")
- AssertError(t, errs, "TestMultiDimensionalStructsPtr3.Errs[0][2].Name", "TestMultiDimensionalStructsPtr3.Errs[0][2].Name", "Name", "Name", "required")
- AssertError(t, errs, "TestMultiDimensionalStructsPtr3.Errs[1][1].Name", "TestMultiDimensionalStructsPtr3.Errs[1][1].Name", "Name", "Name", "required")
- AssertError(t, errs, "TestMultiDimensionalStructsPtr3.Errs[1][2].Name", "TestMultiDimensionalStructsPtr3.Errs[1][2].Name", "Name", "Name", "required")
- AssertError(t, errs, "TestMultiDimensionalStructsPtr3.Errs[2][1].Name", "TestMultiDimensionalStructsPtr3.Errs[2][1].Name", "Name", "Name", "required")
-
- type TestMultiDimensionalTimeTime struct {
- Errs [][]*time.Time `validate:"gt=0,dive,dive,required"`
- }
-
- var errTimePtr3Array [][]*time.Time
-
- t1 := time.Now().UTC()
- t2 := time.Now().UTC()
- t3 := time.Now().UTC().Add(time.Hour * 24)
-
- errTimePtr3Array = append(errTimePtr3Array, []*time.Time{&t1, &t2, &t3})
- errTimePtr3Array = append(errTimePtr3Array, []*time.Time{&t1, &t2, nil})
- errTimePtr3Array = append(errTimePtr3Array, []*time.Time{&t1, nil, nil})
-
- tmtp3 := &TestMultiDimensionalTimeTime{
- Errs: errTimePtr3Array,
- }
-
- errs = validate.Struct(tmtp3)
- NotEqual(t, errs, nil)
- Equal(t, len(errs.(ValidationErrors)), 3)
- AssertError(t, errs, "TestMultiDimensionalTimeTime.Errs[1][2]", "TestMultiDimensionalTimeTime.Errs[1][2]", "Errs[1][2]", "Errs[1][2]", "required")
- AssertError(t, errs, "TestMultiDimensionalTimeTime.Errs[2][1]", "TestMultiDimensionalTimeTime.Errs[2][1]", "Errs[2][1]", "Errs[2][1]", "required")
- AssertError(t, errs, "TestMultiDimensionalTimeTime.Errs[2][2]", "TestMultiDimensionalTimeTime.Errs[2][2]", "Errs[2][2]", "Errs[2][2]", "required")
-
- type TestMultiDimensionalTimeTime2 struct {
- Errs [][]*time.Time `validate:"gt=0,dive,dive,required"`
- }
-
- var errTimeArray [][]*time.Time
-
- t1 = time.Now().UTC()
- t2 = time.Now().UTC()
- t3 = time.Now().UTC().Add(time.Hour * 24)
-
- errTimeArray = append(errTimeArray, []*time.Time{&t1, &t2, &t3})
- errTimeArray = append(errTimeArray, []*time.Time{&t1, &t2, nil})
- errTimeArray = append(errTimeArray, []*time.Time{&t1, nil, nil})
-
- tmtp := &TestMultiDimensionalTimeTime2{
- Errs: errTimeArray,
- }
-
- errs = validate.Struct(tmtp)
- NotEqual(t, errs, nil)
- Equal(t, len(errs.(ValidationErrors)), 3)
- AssertError(t, errs, "TestMultiDimensionalTimeTime2.Errs[1][2]", "TestMultiDimensionalTimeTime2.Errs[1][2]", "Errs[1][2]", "Errs[1][2]", "required")
- AssertError(t, errs, "TestMultiDimensionalTimeTime2.Errs[2][1]", "TestMultiDimensionalTimeTime2.Errs[2][1]", "Errs[2][1]", "Errs[2][1]", "required")
- AssertError(t, errs, "TestMultiDimensionalTimeTime2.Errs[2][2]", "TestMultiDimensionalTimeTime2.Errs[2][2]", "Errs[2][2]", "Errs[2][2]", "required")
-}
-
-func TestNilStructPointerValidation(t *testing.T) {
- type Inner struct {
- Data string
- }
-
- type Outer struct {
- Inner *Inner `validate:"omitempty"`
- }
-
- inner := &Inner{
- Data: "test",
- }
-
- outer := &Outer{
- Inner: inner,
- }
-
- validate := New()
- errs := validate.Struct(outer)
- Equal(t, errs, nil)
-
- outer = &Outer{
- Inner: nil,
- }
-
- errs = validate.Struct(outer)
- Equal(t, errs, nil)
-
- type Inner2 struct {
- Data string
- }
-
- type Outer2 struct {
- Inner2 *Inner2 `validate:"required"`
- }
-
- inner2 := &Inner2{
- Data: "test",
- }
-
- outer2 := &Outer2{
- Inner2: inner2,
- }
-
- errs = validate.Struct(outer2)
- Equal(t, errs, nil)
-
- outer2 = &Outer2{
- Inner2: nil,
- }
-
- errs = validate.Struct(outer2)
- NotEqual(t, errs, nil)
- AssertError(t, errs, "Outer2.Inner2", "Outer2.Inner2", "Inner2", "Inner2", "required")
-
- type Inner3 struct {
- Data string
- }
-
- type Outer3 struct {
- Inner3 *Inner3
- }
-
- inner3 := &Inner3{
- Data: "test",
- }
-
- outer3 := &Outer3{
- Inner3: inner3,
- }
-
- errs = validate.Struct(outer3)
- Equal(t, errs, nil)
-
- type Inner4 struct {
- Data string
- }
-
- type Outer4 struct {
- Inner4 *Inner4 `validate:"-"`
- }
-
- inner4 := &Inner4{
- Data: "test",
- }
-
- outer4 := &Outer4{
- Inner4: inner4,
- }
-
- errs = validate.Struct(outer4)
- Equal(t, errs, nil)
-}
-
-func TestSSNValidation(t *testing.T) {
- tests := []struct {
- param string
- expected bool
- }{
- {"", false},
- {"00-90-8787", false},
- {"66690-76", false},
- {"191 60 2869", true},
- {"191-60-2869", true},
- }
-
- validate := New()
-
- for i, test := range tests {
-
- errs := validate.Var(test.param, "ssn")
-
- if test.expected {
- if !IsEqual(errs, nil) {
- t.Fatalf("Index: %d SSN failed Error: %s", i, errs)
- }
- } else {
- if IsEqual(errs, nil) {
- t.Fatalf("Index: %d SSN failed Error: %s", i, errs)
- } else {
- val := getError(errs, "", "")
- if val.Tag() != "ssn" {
- t.Fatalf("Index: %d Latitude failed Error: %s", i, errs)
- }
- }
- }
- }
-}
-
-func TestLongitudeValidation(t *testing.T) {
- tests := []struct {
- param string
- expected bool
- }{
- {"", false},
- {"-180.000", true},
- {"180.1", false},
- {"+73.234", true},
- {"+382.3811", false},
- {"23.11111111", true},
- }
-
- validate := New()
-
- for i, test := range tests {
-
- errs := validate.Var(test.param, "longitude")
-
- if test.expected {
- if !IsEqual(errs, nil) {
- t.Fatalf("Index: %d Longitude failed Error: %s", i, errs)
- }
- } else {
- if IsEqual(errs, nil) {
- t.Fatalf("Index: %d Longitude failed Error: %s", i, errs)
- } else {
- val := getError(errs, "", "")
- if val.Tag() != "longitude" {
- t.Fatalf("Index: %d Latitude failed Error: %s", i, errs)
- }
- }
- }
- }
-}
-
-func TestLatitudeValidation(t *testing.T) {
- tests := []struct {
- param string
- expected bool
- }{
- {"", false},
- {"-90.000", true},
- {"+90", true},
- {"47.1231231", true},
- {"+99.9", false},
- {"108", false},
- }
-
- validate := New()
-
- for i, test := range tests {
-
- errs := validate.Var(test.param, "latitude")
-
- if test.expected {
- if !IsEqual(errs, nil) {
- t.Fatalf("Index: %d Latitude failed Error: %s", i, errs)
- }
- } else {
- if IsEqual(errs, nil) {
- t.Fatalf("Index: %d Latitude failed Error: %s", i, errs)
- } else {
- val := getError(errs, "", "")
- if val.Tag() != "latitude" {
- t.Fatalf("Index: %d Latitude failed Error: %s", i, errs)
- }
- }
- }
- }
-}
-
-func TestDataURIValidation(t *testing.T) {
- tests := []struct {
- param string
- expected bool
- }{
- {"data:image/png;base64,TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4=", true},
- {"data:text/plain;base64,Vml2YW11cyBmZXJtZW50dW0gc2VtcGVyIHBvcnRhLg==", true},
- {"image/gif;base64,U3VzcGVuZGlzc2UgbGVjdHVzIGxlbw==", false},
- {"data:image/gif;base64,MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuMPNS1Ufof9EW/M98FNw" +
- "UAKrwflsqVxaxQjBQnHQmiI7Vac40t8x7pIb8gLGV6wL7sBTJiPovJ0V7y7oc0Ye" +
- "rhKh0Rm4skP2z/jHwwZICgGzBvA0rH8xlhUiTvcwDCJ0kc+fh35hNt8srZQM4619" +
- "FTgB66Xmp4EtVyhpQV+t02g6NzK72oZI0vnAvqhpkxLeLiMCyrI416wHm5Tkukhx" +
- "QmcL2a6hNOyu0ixX/x2kSFXApEnVrJ+/IxGyfyw8kf4N2IZpW5nEP847lpfj0SZZ" +
- "Fwrd1mnfnDbYohX2zRptLy2ZUn06Qo9pkG5ntvFEPo9bfZeULtjYzIl6K8gJ2uGZ" + "HQIDAQAB", true},
- {"data:image/png;base64,12345", false},
- {"", false},
- {"data:text,:;base85,U3VzcGVuZGlzc2UgbGVjdHVzIGxlbw==", false},
- }
-
- validate := New()
-
- for i, test := range tests {
-
- errs := validate.Var(test.param, "datauri")
-
- if test.expected {
- if !IsEqual(errs, nil) {
- t.Fatalf("Index: %d DataURI failed Error: %s", i, errs)
- }
- } else {
- if IsEqual(errs, nil) {
- t.Fatalf("Index: %d DataURI failed Error: %s", i, errs)
- } else {
- val := getError(errs, "", "")
- if val.Tag() != "datauri" {
- t.Fatalf("Index: %d DataURI failed Error: %s", i, errs)
- }
- }
- }
- }
-}
-
-func TestMultibyteValidation(t *testing.T) {
- tests := []struct {
- param string
- expected bool
- }{
- {"", true},
- {"abc", false},
- {"123", false},
- {"<>@;.-=", false},
- {"ひらがな・カタカナ、.漢字", true},
- {"あいうえお foobar", true},
- {"test@example.com", true},
- {"test@example.com", true},
- {"1234abcDExyz", true},
- {"カタカナ", true},
- }
-
- validate := New()
-
- for i, test := range tests {
-
- errs := validate.Var(test.param, "multibyte")
-
- if test.expected {
- if !IsEqual(errs, nil) {
- t.Fatalf("Index: %d Multibyte failed Error: %s", i, errs)
- }
- } else {
- if IsEqual(errs, nil) {
- t.Fatalf("Index: %d Multibyte failed Error: %s", i, errs)
- } else {
- val := getError(errs, "", "")
- if val.Tag() != "multibyte" {
- t.Fatalf("Index: %d Multibyte failed Error: %s", i, errs)
- }
- }
- }
- }
-}
-
-func TestPrintableASCIIValidation(t *testing.T) {
- tests := []struct {
- param string
- expected bool
- }{
- {"", true},
- {"foobar", false},
- {"xyz098", false},
- {"123456", false},
- {"カタカナ", false},
- {"foobar", true},
- {"0987654321", true},
- {"test@example.com", true},
- {"1234abcDEF", true},
- {"newline\n", false},
- {"\x19test\x7F", false},
- }
-
- validate := New()
-
- for i, test := range tests {
-
- errs := validate.Var(test.param, "printascii")
-
- if test.expected {
- if !IsEqual(errs, nil) {
- t.Fatalf("Index: %d Printable ASCII failed Error: %s", i, errs)
- }
- } else {
- if IsEqual(errs, nil) {
- t.Fatalf("Index: %d Printable ASCII failed Error: %s", i, errs)
- } else {
- val := getError(errs, "", "")
- if val.Tag() != "printascii" {
- t.Fatalf("Index: %d Printable ASCII failed Error: %s", i, errs)
- }
- }
- }
- }
-}
-
-func TestASCIIValidation(t *testing.T) {
- tests := []struct {
- param string
- expected bool
- }{
- {"", true},
- {"foobar", false},
- {"xyz098", false},
- {"123456", false},
- {"カタカナ", false},
- {"foobar", true},
- {"0987654321", true},
- {"test@example.com", true},
- {"1234abcDEF", true},
- {"", true},
- }
-
- validate := New()
-
- for i, test := range tests {
-
- errs := validate.Var(test.param, "ascii")
-
- if test.expected {
- if !IsEqual(errs, nil) {
- t.Fatalf("Index: %d ASCII failed Error: %s", i, errs)
- }
- } else {
- if IsEqual(errs, nil) {
- t.Fatalf("Index: %d ASCII failed Error: %s", i, errs)
- } else {
- val := getError(errs, "", "")
- if val.Tag() != "ascii" {
- t.Fatalf("Index: %d ASCII failed Error: %s", i, errs)
- }
- }
- }
- }
-}
-
-func TestUUID5Validation(t *testing.T) {
- tests := []struct {
- param string
- expected bool
- }{
-
- {"", false},
- {"xxxa987fbc9-4bed-3078-cf07-9141ba07c9f3", false},
- {"9c858901-8a57-4791-81fe-4c455b099bc9", false},
- {"a987fbc9-4bed-3078-cf07-9141ba07c9f3", false},
- {"987fbc97-4bed-5078-af07-9141ba07c9f3", true},
- {"987fbc97-4bed-5078-9f07-9141ba07c9f3", true},
- }
-
- validate := New()
-
- for i, test := range tests {
-
- errs := validate.Var(test.param, "uuid5")
-
- if test.expected {
- if !IsEqual(errs, nil) {
- t.Fatalf("Index: %d UUID5 failed Error: %s", i, errs)
- }
- } else {
- if IsEqual(errs, nil) {
- t.Fatalf("Index: %d UUID5 failed Error: %s", i, errs)
- } else {
- val := getError(errs, "", "")
- if val.Tag() != "uuid5" {
- t.Fatalf("Index: %d UUID5 failed Error: %s", i, errs)
- }
- }
- }
- }
-}
-
-func TestUUID4Validation(t *testing.T) {
- tests := []struct {
- param string
- expected bool
- }{
- {"", false},
- {"xxxa987fbc9-4bed-3078-cf07-9141ba07c9f3", false},
- {"a987fbc9-4bed-5078-af07-9141ba07c9f3", false},
- {"934859", false},
- {"57b73598-8764-4ad0-a76a-679bb6640eb1", true},
- {"625e63f3-58f5-40b7-83a1-a72ad31acffb", true},
- }
-
- validate := New()
-
- for i, test := range tests {
-
- errs := validate.Var(test.param, "uuid4")
-
- if test.expected {
- if !IsEqual(errs, nil) {
- t.Fatalf("Index: %d UUID4 failed Error: %s", i, errs)
- }
- } else {
- if IsEqual(errs, nil) {
- t.Fatalf("Index: %d UUID4 failed Error: %s", i, errs)
- } else {
- val := getError(errs, "", "")
- if val.Tag() != "uuid4" {
- t.Fatalf("Index: %d UUID4 failed Error: %s", i, errs)
- }
- }
- }
- }
-}
-
-func TestUUID3Validation(t *testing.T) {
- tests := []struct {
- param string
- expected bool
- }{
- {"", false},
- {"412452646", false},
- {"xxxa987fbc9-4bed-3078-cf07-9141ba07c9f3", false},
- {"a987fbc9-4bed-4078-8f07-9141ba07c9f3", false},
- {"a987fbc9-4bed-3078-cf07-9141ba07c9f3", true},
- }
-
- validate := New()
-
- for i, test := range tests {
-
- errs := validate.Var(test.param, "uuid3")
-
- if test.expected {
- if !IsEqual(errs, nil) {
- t.Fatalf("Index: %d UUID3 failed Error: %s", i, errs)
- }
- } else {
- if IsEqual(errs, nil) {
- t.Fatalf("Index: %d UUID3 failed Error: %s", i, errs)
- } else {
- val := getError(errs, "", "")
- if val.Tag() != "uuid3" {
- t.Fatalf("Index: %d UUID3 failed Error: %s", i, errs)
- }
- }
- }
- }
-}
-
-func TestUUIDValidation(t *testing.T) {
- tests := []struct {
- param string
- expected bool
- }{
- {"", false},
- {"xxxa987fbc9-4bed-3078-cf07-9141ba07c9f3", false},
- {"a987fbc9-4bed-3078-cf07-9141ba07c9f3xxx", false},
- {"a987fbc94bed3078cf079141ba07c9f3", false},
- {"934859", false},
- {"987fbc9-4bed-3078-cf07a-9141ba07c9f3", false},
- {"aaaaaaaa-1111-1111-aaag-111111111111", false},
- {"a987fbc9-4bed-3078-cf07-9141ba07c9f3", true},
- }
-
- validate := New()
-
- for i, test := range tests {
-
- errs := validate.Var(test.param, "uuid")
-
- if test.expected {
- if !IsEqual(errs, nil) {
- t.Fatalf("Index: %d UUID failed Error: %s", i, errs)
- }
- } else {
- if IsEqual(errs, nil) {
- t.Fatalf("Index: %d UUID failed Error: %s", i, errs)
- } else {
- val := getError(errs, "", "")
- if val.Tag() != "uuid" {
- t.Fatalf("Index: %d UUID failed Error: %s", i, errs)
- }
- }
- }
- }
-}
-
-func TestISBNValidation(t *testing.T) {
- tests := []struct {
- param string
- expected bool
- }{
- {"", false},
- {"foo", false},
- {"3836221195", true},
- {"1-61729-085-8", true},
- {"3 423 21412 0", true},
- {"3 401 01319 X", true},
- {"9784873113685", true},
- {"978-4-87311-368-5", true},
- {"978 3401013190", true},
- {"978-3-8362-2119-1", true},
- }
-
- validate := New()
-
- for i, test := range tests {
-
- errs := validate.Var(test.param, "isbn")
-
- if test.expected {
- if !IsEqual(errs, nil) {
- t.Fatalf("Index: %d ISBN failed Error: %s", i, errs)
- }
- } else {
- if IsEqual(errs, nil) {
- t.Fatalf("Index: %d ISBN failed Error: %s", i, errs)
- } else {
- val := getError(errs, "", "")
- if val.Tag() != "isbn" {
- t.Fatalf("Index: %d ISBN failed Error: %s", i, errs)
- }
- }
- }
- }
-}
-
-func TestISBN13Validation(t *testing.T) {
- tests := []struct {
- param string
- expected bool
- }{
- {"", false},
- {"foo", false},
- {"3-8362-2119-5", false},
- {"01234567890ab", false},
- {"978 3 8362 2119 0", false},
- {"9784873113685", true},
- {"978-4-87311-368-5", true},
- {"978 3401013190", true},
- {"978-3-8362-2119-1", true},
- }
-
- validate := New()
-
- for i, test := range tests {
-
- errs := validate.Var(test.param, "isbn13")
-
- if test.expected {
- if !IsEqual(errs, nil) {
- t.Fatalf("Index: %d ISBN13 failed Error: %s", i, errs)
- }
- } else {
- if IsEqual(errs, nil) {
- t.Fatalf("Index: %d ISBN13 failed Error: %s", i, errs)
- } else {
- val := getError(errs, "", "")
- if val.Tag() != "isbn13" {
- t.Fatalf("Index: %d ISBN13 failed Error: %s", i, errs)
- }
- }
- }
- }
-}
-
-func TestISBN10Validation(t *testing.T) {
- tests := []struct {
- param string
- expected bool
- }{
- {"", false},
- {"foo", false},
- {"3423214121", false},
- {"978-3836221191", false},
- {"3-423-21412-1", false},
- {"3 423 21412 1", false},
- {"3836221195", true},
- {"1-61729-085-8", true},
- {"3 423 21412 0", true},
- {"3 401 01319 X", true},
- }
-
- validate := New()
-
- for i, test := range tests {
-
- errs := validate.Var(test.param, "isbn10")
-
- if test.expected {
- if !IsEqual(errs, nil) {
- t.Fatalf("Index: %d ISBN10 failed Error: %s", i, errs)
- }
- } else {
- if IsEqual(errs, nil) {
- t.Fatalf("Index: %d ISBN10 failed Error: %s", i, errs)
- } else {
- val := getError(errs, "", "")
- if val.Tag() != "isbn10" {
- t.Fatalf("Index: %d ISBN10 failed Error: %s", i, errs)
- }
- }
- }
- }
-}
-
-func TestExcludesRuneValidation(t *testing.T) {
-
- tests := []struct {
- Value string `validate:"excludesrune=☻"`
- Tag string
- ExpectedNil bool
- }{
- {Value: "a☺b☻c☹d", Tag: "excludesrune=☻", ExpectedNil: false},
- {Value: "abcd", Tag: "excludesrune=☻", ExpectedNil: true},
- }
-
- validate := New()
-
- for i, s := range tests {
- errs := validate.Var(s.Value, s.Tag)
-
- if (s.ExpectedNil && errs != nil) || (!s.ExpectedNil && errs == nil) {
- t.Fatalf("Index: %d failed Error: %s", i, errs)
- }
-
- errs = validate.Struct(s)
-
- if (s.ExpectedNil && errs != nil) || (!s.ExpectedNil && errs == nil) {
- t.Fatalf("Index: %d failed Error: %s", i, errs)
- }
- }
-}
-
-func TestExcludesAllValidation(t *testing.T) {
-
- tests := []struct {
- Value string `validate:"excludesall=@!{}[]"`
- Tag string
- ExpectedNil bool
- }{
- {Value: "abcd@!jfk", Tag: "excludesall=@!{}[]", ExpectedNil: false},
- {Value: "abcdefg", Tag: "excludesall=@!{}[]", ExpectedNil: true},
- }
-
- validate := New()
-
- for i, s := range tests {
- errs := validate.Var(s.Value, s.Tag)
-
- if (s.ExpectedNil && errs != nil) || (!s.ExpectedNil && errs == nil) {
- t.Fatalf("Index: %d failed Error: %s", i, errs)
- }
-
- errs = validate.Struct(s)
-
- if (s.ExpectedNil && errs != nil) || (!s.ExpectedNil && errs == nil) {
- t.Fatalf("Index: %d failed Error: %s", i, errs)
- }
- }
-
- username := "joeybloggs "
-
- errs := validate.Var(username, "excludesall=@ ")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "excludesall")
-
- excluded := ","
-
- errs = validate.Var(excluded, "excludesall=!@#$%^&*()_+.0x2C?")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "excludesall")
-
- excluded = "="
-
- errs = validate.Var(excluded, "excludesall=!@#$%^&*()_+.0x2C=?")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "excludesall")
-}
-
-func TestExcludesValidation(t *testing.T) {
-
- tests := []struct {
- Value string `validate:"excludes=@"`
- Tag string
- ExpectedNil bool
- }{
- {Value: "abcd@!jfk", Tag: "excludes=@", ExpectedNil: false},
- {Value: "abcdq!jfk", Tag: "excludes=@", ExpectedNil: true},
- }
-
- validate := New()
-
- for i, s := range tests {
- errs := validate.Var(s.Value, s.Tag)
-
- if (s.ExpectedNil && errs != nil) || (!s.ExpectedNil && errs == nil) {
- t.Fatalf("Index: %d failed Error: %s", i, errs)
- }
-
- errs = validate.Struct(s)
-
- if (s.ExpectedNil && errs != nil) || (!s.ExpectedNil && errs == nil) {
- t.Fatalf("Index: %d failed Error: %s", i, errs)
- }
- }
-}
-
-func TestContainsRuneValidation(t *testing.T) {
-
- tests := []struct {
- Value string `validate:"containsrune=☻"`
- Tag string
- ExpectedNil bool
- }{
- {Value: "a☺b☻c☹d", Tag: "containsrune=☻", ExpectedNil: true},
- {Value: "abcd", Tag: "containsrune=☻", ExpectedNil: false},
- }
-
- validate := New()
-
- for i, s := range tests {
- errs := validate.Var(s.Value, s.Tag)
-
- if (s.ExpectedNil && errs != nil) || (!s.ExpectedNil && errs == nil) {
- t.Fatalf("Index: %d failed Error: %s", i, errs)
- }
-
- errs = validate.Struct(s)
-
- if (s.ExpectedNil && errs != nil) || (!s.ExpectedNil && errs == nil) {
- t.Fatalf("Index: %d failed Error: %s", i, errs)
- }
- }
-}
-
-func TestContainsAnyValidation(t *testing.T) {
-
- tests := []struct {
- Value string `validate:"containsany=@!{}[]"`
- Tag string
- ExpectedNil bool
- }{
- {Value: "abcd@!jfk", Tag: "containsany=@!{}[]", ExpectedNil: true},
- {Value: "abcdefg", Tag: "containsany=@!{}[]", ExpectedNil: false},
- }
-
- validate := New()
-
- for i, s := range tests {
- errs := validate.Var(s.Value, s.Tag)
-
- if (s.ExpectedNil && errs != nil) || (!s.ExpectedNil && errs == nil) {
- t.Fatalf("Index: %d failed Error: %s", i, errs)
- }
-
- errs = validate.Struct(s)
-
- if (s.ExpectedNil && errs != nil) || (!s.ExpectedNil && errs == nil) {
- t.Fatalf("Index: %d failed Error: %s", i, errs)
- }
- }
-}
-
-func TestContainsValidation(t *testing.T) {
-
- tests := []struct {
- Value string `validate:"contains=@"`
- Tag string
- ExpectedNil bool
- }{
- {Value: "abcd@!jfk", Tag: "contains=@", ExpectedNil: true},
- {Value: "abcdq!jfk", Tag: "contains=@", ExpectedNil: false},
- }
-
- validate := New()
-
- for i, s := range tests {
- errs := validate.Var(s.Value, s.Tag)
-
- if (s.ExpectedNil && errs != nil) || (!s.ExpectedNil && errs == nil) {
- t.Fatalf("Index: %d failed Error: %s", i, errs)
- }
-
- errs = validate.Struct(s)
-
- if (s.ExpectedNil && errs != nil) || (!s.ExpectedNil && errs == nil) {
- t.Fatalf("Index: %d failed Error: %s", i, errs)
- }
- }
-}
-
-func TestIsNeFieldValidation(t *testing.T) {
-
- validate := New()
-
- var j uint64
- var k float64
- s := "abcd"
- i := 1
- j = 1
- k = 1.543
- arr := []string{"test"}
- now := time.Now().UTC()
-
- var j2 uint64
- var k2 float64
- s2 := "abcdef"
- i2 := 3
- j2 = 2
- k2 = 1.5434456
- arr2 := []string{"test", "test2"}
- arr3 := []string{"test"}
- now2 := now
-
- errs := validate.VarWithValue(s, s2, "nefield")
- Equal(t, errs, nil)
-
- errs = validate.VarWithValue(i2, i, "nefield")
- Equal(t, errs, nil)
-
- errs = validate.VarWithValue(j2, j, "nefield")
- Equal(t, errs, nil)
-
- errs = validate.VarWithValue(k2, k, "nefield")
- Equal(t, errs, nil)
-
- errs = validate.VarWithValue(arr2, arr, "nefield")
- Equal(t, errs, nil)
-
- errs = validate.VarWithValue(now2, now, "nefield")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "nefield")
-
- errs = validate.VarWithValue(arr3, arr, "nefield")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "nefield")
-
- type Test struct {
- Start *time.Time `validate:"nefield=End"`
- End *time.Time
- }
-
- sv := &Test{
- Start: &now,
- End: &now,
- }
-
- errs = validate.Struct(sv)
- NotEqual(t, errs, nil)
- AssertError(t, errs, "Test.Start", "Test.Start", "Start", "Start", "nefield")
-
- now3 := time.Now().UTC()
-
- sv = &Test{
- Start: &now,
- End: &now3,
- }
-
- errs = validate.Struct(sv)
- Equal(t, errs, nil)
-
- errs = validate.VarWithValue(nil, 1, "nefield")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "nefield")
-
- errs = validate.VarWithValue(sv, now, "nefield")
- Equal(t, errs, nil)
-
- type Test2 struct {
- Start *time.Time `validate:"nefield=NonExistantField"`
- End *time.Time
- }
-
- sv2 := &Test2{
- Start: &now,
- End: &now,
- }
-
- errs = validate.Struct(sv2)
- Equal(t, errs, nil)
-
- type Other struct {
- Value string
- }
-
- type Test3 struct {
- Value Other
- Time time.Time `validate:"nefield=Value"`
- }
-
- tst := Test3{
- Value: Other{Value: "StringVal"},
- Time: now,
- }
-
- errs = validate.Struct(tst)
- Equal(t, errs, nil)
-}
-
-func TestIsNeValidation(t *testing.T) {
-
- validate := New()
-
- var j uint64
- var k float64
- s := "abcdef"
- i := 3
- j = 2
- k = 1.5434
- arr := []string{"test"}
- now := time.Now().UTC()
-
- errs := validate.Var(s, "ne=abcd")
- Equal(t, errs, nil)
-
- errs = validate.Var(i, "ne=1")
- Equal(t, errs, nil)
-
- errs = validate.Var(j, "ne=1")
- Equal(t, errs, nil)
-
- errs = validate.Var(k, "ne=1.543")
- Equal(t, errs, nil)
-
- errs = validate.Var(arr, "ne=2")
- Equal(t, errs, nil)
-
- errs = validate.Var(arr, "ne=1")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "ne")
-
- PanicMatches(t, func() { validate.Var(now, "ne=now") }, "Bad field type time.Time")
-}
-
-func TestIsEqFieldValidation(t *testing.T) {
-
- validate := New()
-
- var j uint64
- var k float64
- s := "abcd"
- i := 1
- j = 1
- k = 1.543
- arr := []string{"test"}
- now := time.Now().UTC()
-
- var j2 uint64
- var k2 float64
- s2 := "abcd"
- i2 := 1
- j2 = 1
- k2 = 1.543
- arr2 := []string{"test"}
- arr3 := []string{"test", "test2"}
- now2 := now
-
- errs := validate.VarWithValue(s, s2, "eqfield")
- Equal(t, errs, nil)
-
- errs = validate.VarWithValue(i2, i, "eqfield")
- Equal(t, errs, nil)
-
- errs = validate.VarWithValue(j2, j, "eqfield")
- Equal(t, errs, nil)
-
- errs = validate.VarWithValue(k2, k, "eqfield")
- Equal(t, errs, nil)
-
- errs = validate.VarWithValue(arr2, arr, "eqfield")
- Equal(t, errs, nil)
-
- errs = validate.VarWithValue(now2, now, "eqfield")
- Equal(t, errs, nil)
-
- errs = validate.VarWithValue(arr3, arr, "eqfield")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "eqfield")
-
- type Test struct {
- Start *time.Time `validate:"eqfield=End"`
- End *time.Time
- }
-
- sv := &Test{
- Start: &now,
- End: &now,
- }
-
- errs = validate.Struct(sv)
- Equal(t, errs, nil)
-
- now3 := time.Now().UTC()
-
- sv = &Test{
- Start: &now,
- End: &now3,
- }
-
- errs = validate.Struct(sv)
- NotEqual(t, errs, nil)
- AssertError(t, errs, "Test.Start", "Test.Start", "Start", "Start", "eqfield")
-
- errs = validate.VarWithValue(nil, 1, "eqfield")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "eqfield")
-
- channel := make(chan string)
- errs = validate.VarWithValue(5, channel, "eqfield")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "eqfield")
-
- errs = validate.VarWithValue(5, now, "eqfield")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "eqfield")
-
- type Test2 struct {
- Start *time.Time `validate:"eqfield=NonExistantField"`
- End *time.Time
- }
-
- sv2 := &Test2{
- Start: &now,
- End: &now,
- }
-
- errs = validate.Struct(sv2)
- NotEqual(t, errs, nil)
- AssertError(t, errs, "Test2.Start", "Test2.Start", "Start", "Start", "eqfield")
-
- type Inner struct {
- Name string
- }
-
- type TStruct struct {
- Inner *Inner
- CreatedAt *time.Time `validate:"eqfield=Inner"`
- }
-
- inner := &Inner{
- Name: "NAME",
- }
-
- test := &TStruct{
- Inner: inner,
- CreatedAt: &now,
- }
-
- errs = validate.Struct(test)
- NotEqual(t, errs, nil)
- AssertError(t, errs, "TStruct.CreatedAt", "TStruct.CreatedAt", "CreatedAt", "CreatedAt", "eqfield")
-}
-
-func TestIsEqValidation(t *testing.T) {
-
- validate := New()
-
- var j uint64
- var k float64
- s := "abcd"
- i := 1
- j = 1
- k = 1.543
- arr := []string{"test"}
- now := time.Now().UTC()
-
- errs := validate.Var(s, "eq=abcd")
- Equal(t, errs, nil)
-
- errs = validate.Var(i, "eq=1")
- Equal(t, errs, nil)
-
- errs = validate.Var(j, "eq=1")
- Equal(t, errs, nil)
-
- errs = validate.Var(k, "eq=1.543")
- Equal(t, errs, nil)
-
- errs = validate.Var(arr, "eq=1")
- Equal(t, errs, nil)
-
- errs = validate.Var(arr, "eq=2")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "eq")
-
- PanicMatches(t, func() { validate.Var(now, "eq=now") }, "Bad field type time.Time")
-}
-
-func TestOneOfValidation(t *testing.T) {
- validate := New()
-
- passSpecs := []struct {
- f interface{}
- t string
- }{
- {f: "red", t: "oneof=red green"},
- {f: "green", t: "oneof=red green"},
- {f: 5, t: "oneof=5 6"},
- {f: 6, t: "oneof=5 6"},
- {f: int8(6), t: "oneof=5 6"},
- {f: int16(6), t: "oneof=5 6"},
- {f: int32(6), t: "oneof=5 6"},
- {f: int64(6), t: "oneof=5 6"},
- {f: uint(6), t: "oneof=5 6"},
- {f: uint8(6), t: "oneof=5 6"},
- {f: uint16(6), t: "oneof=5 6"},
- {f: uint32(6), t: "oneof=5 6"},
- {f: uint64(6), t: "oneof=5 6"},
- }
-
- for _, spec := range passSpecs {
- t.Logf("%#v", spec)
- errs := validate.Var(spec.f, spec.t)
- Equal(t, errs, nil)
- }
-
- failSpecs := []struct {
- f interface{}
- t string
- }{
- {f: "", t: "oneof=red green"},
- {f: "yellow", t: "oneof=red green"},
- {f: 5, t: "oneof=red green"},
- {f: 6, t: "oneof=red green"},
- {f: 6, t: "oneof=7"},
- {f: uint(6), t: "oneof=7"},
- {f: int8(5), t: "oneof=red green"},
- {f: int16(5), t: "oneof=red green"},
- {f: int32(5), t: "oneof=red green"},
- {f: int64(5), t: "oneof=red green"},
- {f: uint(5), t: "oneof=red green"},
- {f: uint8(5), t: "oneof=red green"},
- {f: uint16(5), t: "oneof=red green"},
- {f: uint32(5), t: "oneof=red green"},
- {f: uint64(5), t: "oneof=red green"},
- }
-
- for _, spec := range failSpecs {
- t.Logf("%#v", spec)
- errs := validate.Var(spec.f, spec.t)
- AssertError(t, errs, "", "", "", "", "oneof")
- }
-
- PanicMatches(t, func() {
- validate.Var(3.14, "oneof=red green")
- }, "Bad field type float64")
-}
-
-func TestBase64Validation(t *testing.T) {
-
- validate := New()
-
- s := "dW5pY29ybg=="
-
- errs := validate.Var(s, "base64")
- Equal(t, errs, nil)
-
- s = "dGhpIGlzIGEgdGVzdCBiYXNlNjQ="
- errs = validate.Var(s, "base64")
- Equal(t, errs, nil)
-
- s = ""
- errs = validate.Var(s, "base64")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "base64")
-
- s = "dW5pY29ybg== foo bar"
- errs = validate.Var(s, "base64")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "base64")
-}
-
-func TestNoStructLevelValidation(t *testing.T) {
-
- type Inner struct {
- Test string `validate:"len=5"`
- }
-
- type Outer struct {
- InnerStruct *Inner `validate:"required,nostructlevel"`
- }
-
- outer := &Outer{
- InnerStruct: nil,
- }
-
- validate := New()
-
- errs := validate.Struct(outer)
- NotEqual(t, errs, nil)
- AssertError(t, errs, "Outer.InnerStruct", "Outer.InnerStruct", "InnerStruct", "InnerStruct", "required")
-
- inner := &Inner{
- Test: "1234",
- }
-
- outer = &Outer{
- InnerStruct: inner,
- }
-
- errs = validate.Struct(outer)
- Equal(t, errs, nil)
-}
-
-func TestStructOnlyValidation(t *testing.T) {
-
- type Inner struct {
- Test string `validate:"len=5"`
- }
-
- type Outer struct {
- InnerStruct *Inner `validate:"required,structonly"`
- }
-
- outer := &Outer{
- InnerStruct: nil,
- }
-
- validate := New()
-
- errs := validate.Struct(outer)
- NotEqual(t, errs, nil)
- AssertError(t, errs, "Outer.InnerStruct", "Outer.InnerStruct", "InnerStruct", "InnerStruct", "required")
-
- inner := &Inner{
- Test: "1234",
- }
-
- outer = &Outer{
- InnerStruct: inner,
- }
-
- errs = validate.Struct(outer)
- Equal(t, errs, nil)
-
- // Address houses a users address information
- type Address struct {
- Street string `validate:"required"`
- City string `validate:"required"`
- Planet string `validate:"required"`
- Phone string `validate:"required"`
- }
-
- type User struct {
- FirstName string `json:"fname"`
- LastName string `json:"lname"`
- Age uint8 `validate:"gte=0,lte=130"`
- Email string `validate:"required,email"`
- FavouriteColor string `validate:"hexcolor|rgb|rgba"`
- Addresses []*Address `validate:"required"` // a person can have a home and cottage...
- Address Address `validate:"structonly"` // a person can have a home and cottage...
- }
-
- address := &Address{
- Street: "Eavesdown Docks",
- Planet: "Persphone",
- Phone: "none",
- City: "Unknown",
- }
-
- user := &User{
- FirstName: "",
- LastName: "",
- Age: 45,
- Email: "Badger.Smith@gmail.com",
- FavouriteColor: "#000",
- Addresses: []*Address{address},
- Address: Address{
- // Street: "Eavesdown Docks",
- Planet: "Persphone",
- Phone: "none",
- City: "Unknown",
- },
- }
-
- errs = validate.Struct(user)
- Equal(t, errs, nil)
-}
-
-func TestGtField(t *testing.T) {
-
- validate := New()
-
- type TimeTest struct {
- Start *time.Time `validate:"required,gt"`
- End *time.Time `validate:"required,gt,gtfield=Start"`
- }
-
- now := time.Now()
- start := now.Add(time.Hour * 24)
- end := start.Add(time.Hour * 24)
-
- timeTest := &TimeTest{
- Start: &start,
- End: &end,
- }
-
- errs := validate.Struct(timeTest)
- Equal(t, errs, nil)
-
- timeTest = &TimeTest{
- Start: &end,
- End: &start,
- }
-
- errs = validate.Struct(timeTest)
- NotEqual(t, errs, nil)
- AssertError(t, errs, "TimeTest.End", "TimeTest.End", "End", "End", "gtfield")
-
- errs = validate.VarWithValue(&end, &start, "gtfield")
- Equal(t, errs, nil)
-
- errs = validate.VarWithValue(&start, &end, "gtfield")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "gtfield")
-
- errs = validate.VarWithValue(&end, &start, "gtfield")
- Equal(t, errs, nil)
-
- errs = validate.VarWithValue(&timeTest, &end, "gtfield")
- NotEqual(t, errs, nil)
-
- errs = validate.VarWithValue("test bigger", "test", "gtfield")
- Equal(t, errs, nil)
-
- type IntTest struct {
- Val1 int `validate:"required"`
- Val2 int `validate:"required,gtfield=Val1"`
- }
-
- intTest := &IntTest{
- Val1: 1,
- Val2: 5,
- }
-
- errs = validate.Struct(intTest)
- Equal(t, errs, nil)
-
- intTest = &IntTest{
- Val1: 5,
- Val2: 1,
- }
-
- errs = validate.Struct(intTest)
- NotEqual(t, errs, nil)
- AssertError(t, errs, "IntTest.Val2", "IntTest.Val2", "Val2", "Val2", "gtfield")
-
- errs = validate.VarWithValue(int(5), int(1), "gtfield")
- Equal(t, errs, nil)
-
- errs = validate.VarWithValue(int(1), int(5), "gtfield")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "gtfield")
-
- type UIntTest struct {
- Val1 uint `validate:"required"`
- Val2 uint `validate:"required,gtfield=Val1"`
- }
-
- uIntTest := &UIntTest{
- Val1: 1,
- Val2: 5,
- }
-
- errs = validate.Struct(uIntTest)
- Equal(t, errs, nil)
-
- uIntTest = &UIntTest{
- Val1: 5,
- Val2: 1,
- }
-
- errs = validate.Struct(uIntTest)
- NotEqual(t, errs, nil)
- AssertError(t, errs, "UIntTest.Val2", "UIntTest.Val2", "Val2", "Val2", "gtfield")
-
- errs = validate.VarWithValue(uint(5), uint(1), "gtfield")
- Equal(t, errs, nil)
-
- errs = validate.VarWithValue(uint(1), uint(5), "gtfield")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "gtfield")
-
- type FloatTest struct {
- Val1 float64 `validate:"required"`
- Val2 float64 `validate:"required,gtfield=Val1"`
- }
-
- floatTest := &FloatTest{
- Val1: 1,
- Val2: 5,
- }
-
- errs = validate.Struct(floatTest)
- Equal(t, errs, nil)
-
- floatTest = &FloatTest{
- Val1: 5,
- Val2: 1,
- }
-
- errs = validate.Struct(floatTest)
- NotEqual(t, errs, nil)
- AssertError(t, errs, "FloatTest.Val2", "FloatTest.Val2", "Val2", "Val2", "gtfield")
-
- errs = validate.VarWithValue(float32(5), float32(1), "gtfield")
- Equal(t, errs, nil)
-
- errs = validate.VarWithValue(float32(1), float32(5), "gtfield")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "gtfield")
-
- errs = validate.VarWithValue(nil, 1, "gtfield")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "gtfield")
-
- errs = validate.VarWithValue(5, "T", "gtfield")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "gtfield")
-
- errs = validate.VarWithValue(5, start, "gtfield")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "gtfield")
-
- type TimeTest2 struct {
- Start *time.Time `validate:"required"`
- End *time.Time `validate:"required,gtfield=NonExistantField"`
- }
-
- timeTest2 := &TimeTest2{
- Start: &start,
- End: &end,
- }
-
- errs = validate.Struct(timeTest2)
- NotEqual(t, errs, nil)
- AssertError(t, errs, "TimeTest2.End", "TimeTest2.End", "End", "End", "gtfield")
-
- type Other struct {
- Value string
- }
-
- type Test struct {
- Value Other
- Time time.Time `validate:"gtfield=Value"`
- }
-
- tst := Test{
- Value: Other{Value: "StringVal"},
- Time: end,
- }
-
- errs = validate.Struct(tst)
- NotEqual(t, errs, nil)
- AssertError(t, errs, "Test.Time", "Test.Time", "Time", "Time", "gtfield")
-}
-
-func TestLtField(t *testing.T) {
-
- validate := New()
-
- type TimeTest struct {
- Start *time.Time `validate:"required,lt,ltfield=End"`
- End *time.Time `validate:"required,lt"`
- }
-
- now := time.Now()
- start := now.Add(time.Hour * 24 * -1 * 2)
- end := start.Add(time.Hour * 24)
-
- timeTest := &TimeTest{
- Start: &start,
- End: &end,
- }
-
- errs := validate.Struct(timeTest)
- Equal(t, errs, nil)
-
- timeTest = &TimeTest{
- Start: &end,
- End: &start,
- }
-
- errs = validate.Struct(timeTest)
- NotEqual(t, errs, nil)
- AssertError(t, errs, "TimeTest.Start", "TimeTest.Start", "Start", "Start", "ltfield")
-
- errs = validate.VarWithValue(&start, &end, "ltfield")
- Equal(t, errs, nil)
-
- errs = validate.VarWithValue(&end, &start, "ltfield")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "ltfield")
-
- errs = validate.VarWithValue(&end, timeTest, "ltfield")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "ltfield")
-
- errs = validate.VarWithValue("tes", "test", "ltfield")
- Equal(t, errs, nil)
-
- type IntTest struct {
- Val1 int `validate:"required"`
- Val2 int `validate:"required,ltfield=Val1"`
- }
-
- intTest := &IntTest{
- Val1: 5,
- Val2: 1,
- }
-
- errs = validate.Struct(intTest)
- Equal(t, errs, nil)
-
- intTest = &IntTest{
- Val1: 1,
- Val2: 5,
- }
-
- errs = validate.Struct(intTest)
- NotEqual(t, errs, nil)
- AssertError(t, errs, "IntTest.Val2", "IntTest.Val2", "Val2", "Val2", "ltfield")
-
- errs = validate.VarWithValue(int(1), int(5), "ltfield")
- Equal(t, errs, nil)
-
- errs = validate.VarWithValue(int(5), int(1), "ltfield")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "ltfield")
-
- type UIntTest struct {
- Val1 uint `validate:"required"`
- Val2 uint `validate:"required,ltfield=Val1"`
- }
-
- uIntTest := &UIntTest{
- Val1: 5,
- Val2: 1,
- }
-
- errs = validate.Struct(uIntTest)
- Equal(t, errs, nil)
-
- uIntTest = &UIntTest{
- Val1: 1,
- Val2: 5,
- }
-
- errs = validate.Struct(uIntTest)
- NotEqual(t, errs, nil)
- AssertError(t, errs, "UIntTest.Val2", "UIntTest.Val2", "Val2", "Val2", "ltfield")
-
- errs = validate.VarWithValue(uint(1), uint(5), "ltfield")
- Equal(t, errs, nil)
-
- errs = validate.VarWithValue(uint(5), uint(1), "ltfield")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "ltfield")
-
- type FloatTest struct {
- Val1 float64 `validate:"required"`
- Val2 float64 `validate:"required,ltfield=Val1"`
- }
-
- floatTest := &FloatTest{
- Val1: 5,
- Val2: 1,
- }
-
- errs = validate.Struct(floatTest)
- Equal(t, errs, nil)
-
- floatTest = &FloatTest{
- Val1: 1,
- Val2: 5,
- }
-
- errs = validate.Struct(floatTest)
- NotEqual(t, errs, nil)
- AssertError(t, errs, "FloatTest.Val2", "FloatTest.Val2", "Val2", "Val2", "ltfield")
-
- errs = validate.VarWithValue(float32(1), float32(5), "ltfield")
- Equal(t, errs, nil)
-
- errs = validate.VarWithValue(float32(5), float32(1), "ltfield")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "ltfield")
-
- errs = validate.VarWithValue(nil, 5, "ltfield")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "ltfield")
-
- errs = validate.VarWithValue(1, "T", "ltfield")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "ltfield")
-
- errs = validate.VarWithValue(1, end, "ltfield")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "ltfield")
-
- type TimeTest2 struct {
- Start *time.Time `validate:"required"`
- End *time.Time `validate:"required,ltfield=NonExistantField"`
- }
-
- timeTest2 := &TimeTest2{
- Start: &end,
- End: &start,
- }
-
- errs = validate.Struct(timeTest2)
- NotEqual(t, errs, nil)
- AssertError(t, errs, "TimeTest2.End", "TimeTest2.End", "End", "End", "ltfield")
-}
-
-func TestLteField(t *testing.T) {
-
- validate := New()
-
- type TimeTest struct {
- Start *time.Time `validate:"required,lte,ltefield=End"`
- End *time.Time `validate:"required,lte"`
- }
-
- now := time.Now()
- start := now.Add(time.Hour * 24 * -1 * 2)
- end := start.Add(time.Hour * 24)
-
- timeTest := &TimeTest{
- Start: &start,
- End: &end,
- }
-
- errs := validate.Struct(timeTest)
- Equal(t, errs, nil)
-
- timeTest = &TimeTest{
- Start: &end,
- End: &start,
- }
-
- errs = validate.Struct(timeTest)
- NotEqual(t, errs, nil)
- AssertError(t, errs, "TimeTest.Start", "TimeTest.Start", "Start", "Start", "ltefield")
-
- errs = validate.VarWithValue(&start, &end, "ltefield")
- Equal(t, errs, nil)
-
- errs = validate.VarWithValue(&end, &start, "ltefield")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "ltefield")
-
- errs = validate.VarWithValue(&end, timeTest, "ltefield")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "ltefield")
-
- errs = validate.VarWithValue("tes", "test", "ltefield")
- Equal(t, errs, nil)
-
- errs = validate.VarWithValue("test", "test", "ltefield")
- Equal(t, errs, nil)
-
- type IntTest struct {
- Val1 int `validate:"required"`
- Val2 int `validate:"required,ltefield=Val1"`
- }
-
- intTest := &IntTest{
- Val1: 5,
- Val2: 1,
- }
-
- errs = validate.Struct(intTest)
- Equal(t, errs, nil)
-
- intTest = &IntTest{
- Val1: 1,
- Val2: 5,
- }
-
- errs = validate.Struct(intTest)
- NotEqual(t, errs, nil)
- AssertError(t, errs, "IntTest.Val2", "IntTest.Val2", "Val2", "Val2", "ltefield")
-
- errs = validate.VarWithValue(int(1), int(5), "ltefield")
- Equal(t, errs, nil)
-
- errs = validate.VarWithValue(int(5), int(1), "ltefield")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "ltefield")
-
- type UIntTest struct {
- Val1 uint `validate:"required"`
- Val2 uint `validate:"required,ltefield=Val1"`
- }
-
- uIntTest := &UIntTest{
- Val1: 5,
- Val2: 1,
- }
-
- errs = validate.Struct(uIntTest)
- Equal(t, errs, nil)
-
- uIntTest = &UIntTest{
- Val1: 1,
- Val2: 5,
- }
-
- errs = validate.Struct(uIntTest)
- NotEqual(t, errs, nil)
- AssertError(t, errs, "UIntTest.Val2", "UIntTest.Val2", "Val2", "Val2", "ltefield")
-
- errs = validate.VarWithValue(uint(1), uint(5), "ltefield")
- Equal(t, errs, nil)
-
- errs = validate.VarWithValue(uint(5), uint(1), "ltefield")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "ltefield")
-
- type FloatTest struct {
- Val1 float64 `validate:"required"`
- Val2 float64 `validate:"required,ltefield=Val1"`
- }
-
- floatTest := &FloatTest{
- Val1: 5,
- Val2: 1,
- }
-
- errs = validate.Struct(floatTest)
- Equal(t, errs, nil)
-
- floatTest = &FloatTest{
- Val1: 1,
- Val2: 5,
- }
-
- errs = validate.Struct(floatTest)
- NotEqual(t, errs, nil)
- AssertError(t, errs, "FloatTest.Val2", "FloatTest.Val2", "Val2", "Val2", "ltefield")
-
- errs = validate.VarWithValue(float32(1), float32(5), "ltefield")
- Equal(t, errs, nil)
-
- errs = validate.VarWithValue(float32(5), float32(1), "ltefield")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "ltefield")
-
- errs = validate.VarWithValue(nil, 5, "ltefield")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "ltefield")
-
- errs = validate.VarWithValue(1, "T", "ltefield")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "ltefield")
-
- errs = validate.VarWithValue(1, end, "ltefield")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "ltefield")
-
- type TimeTest2 struct {
- Start *time.Time `validate:"required"`
- End *time.Time `validate:"required,ltefield=NonExistantField"`
- }
-
- timeTest2 := &TimeTest2{
- Start: &end,
- End: &start,
- }
-
- errs = validate.Struct(timeTest2)
- NotEqual(t, errs, nil)
- AssertError(t, errs, "TimeTest2.End", "TimeTest2.End", "End", "End", "ltefield")
-}
-
-func TestGteField(t *testing.T) {
-
- validate := New()
-
- type TimeTest struct {
- Start *time.Time `validate:"required,gte"`
- End *time.Time `validate:"required,gte,gtefield=Start"`
- }
-
- now := time.Now()
- start := now.Add(time.Hour * 24)
- end := start.Add(time.Hour * 24)
-
- timeTest := &TimeTest{
- Start: &start,
- End: &end,
- }
-
- errs := validate.Struct(timeTest)
- Equal(t, errs, nil)
-
- timeTest = &TimeTest{
- Start: &end,
- End: &start,
- }
-
- errs = validate.Struct(timeTest)
- NotEqual(t, errs, nil)
- AssertError(t, errs, "TimeTest.End", "TimeTest.End", "End", "End", "gtefield")
-
- errs = validate.VarWithValue(&end, &start, "gtefield")
- Equal(t, errs, nil)
-
- errs = validate.VarWithValue(&start, &end, "gtefield")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "gtefield")
-
- errs = validate.VarWithValue(&start, timeTest, "gtefield")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "gtefield")
-
- errs = validate.VarWithValue("test", "test", "gtefield")
- Equal(t, errs, nil)
-
- errs = validate.VarWithValue("test bigger", "test", "gtefield")
- Equal(t, errs, nil)
-
- type IntTest struct {
- Val1 int `validate:"required"`
- Val2 int `validate:"required,gtefield=Val1"`
- }
-
- intTest := &IntTest{
- Val1: 1,
- Val2: 5,
- }
-
- errs = validate.Struct(intTest)
- Equal(t, errs, nil)
-
- intTest = &IntTest{
- Val1: 5,
- Val2: 1,
- }
-
- errs = validate.Struct(intTest)
- NotEqual(t, errs, nil)
- AssertError(t, errs, "IntTest.Val2", "IntTest.Val2", "Val2", "Val2", "gtefield")
-
- errs = validate.VarWithValue(int(5), int(1), "gtefield")
- Equal(t, errs, nil)
-
- errs = validate.VarWithValue(int(1), int(5), "gtefield")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "gtefield")
-
- type UIntTest struct {
- Val1 uint `validate:"required"`
- Val2 uint `validate:"required,gtefield=Val1"`
- }
-
- uIntTest := &UIntTest{
- Val1: 1,
- Val2: 5,
- }
-
- errs = validate.Struct(uIntTest)
- Equal(t, errs, nil)
-
- uIntTest = &UIntTest{
- Val1: 5,
- Val2: 1,
- }
-
- errs = validate.Struct(uIntTest)
- NotEqual(t, errs, nil)
- AssertError(t, errs, "UIntTest.Val2", "UIntTest.Val2", "Val2", "Val2", "gtefield")
-
- errs = validate.VarWithValue(uint(5), uint(1), "gtefield")
- Equal(t, errs, nil)
-
- errs = validate.VarWithValue(uint(1), uint(5), "gtefield")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "gtefield")
-
- type FloatTest struct {
- Val1 float64 `validate:"required"`
- Val2 float64 `validate:"required,gtefield=Val1"`
- }
-
- floatTest := &FloatTest{
- Val1: 1,
- Val2: 5,
- }
-
- errs = validate.Struct(floatTest)
- Equal(t, errs, nil)
-
- floatTest = &FloatTest{
- Val1: 5,
- Val2: 1,
- }
-
- errs = validate.Struct(floatTest)
- NotEqual(t, errs, nil)
- AssertError(t, errs, "FloatTest.Val2", "FloatTest.Val2", "Val2", "Val2", "gtefield")
-
- errs = validate.VarWithValue(float32(5), float32(1), "gtefield")
- Equal(t, errs, nil)
-
- errs = validate.VarWithValue(float32(1), float32(5), "gtefield")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "gtefield")
-
- errs = validate.VarWithValue(nil, 1, "gtefield")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "gtefield")
-
- errs = validate.VarWithValue(5, "T", "gtefield")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "gtefield")
-
- errs = validate.VarWithValue(5, start, "gtefield")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "gtefield")
-
- type TimeTest2 struct {
- Start *time.Time `validate:"required"`
- End *time.Time `validate:"required,gtefield=NonExistantField"`
- }
-
- timeTest2 := &TimeTest2{
- Start: &start,
- End: &end,
- }
-
- errs = validate.Struct(timeTest2)
- NotEqual(t, errs, nil)
- AssertError(t, errs, "TimeTest2.End", "TimeTest2.End", "End", "End", "gtefield")
-}
-
-func TestValidateByTagAndValue(t *testing.T) {
-
- validate := New()
-
- val := "test"
- field := "test"
- errs := validate.VarWithValue(val, field, "required")
- Equal(t, errs, nil)
-
- fn := func(fl FieldLevel) bool {
-
- return fl.Parent().String() == fl.Field().String()
- }
-
- validate.RegisterValidation("isequaltestfunc", fn)
-
- errs = validate.VarWithValue(val, field, "isequaltestfunc")
- Equal(t, errs, nil)
-
- val = "unequal"
-
- errs = validate.VarWithValue(val, field, "isequaltestfunc")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "isequaltestfunc")
-}
-
-func TestAddFunctions(t *testing.T) {
-
- fn := func(fl FieldLevel) bool {
-
- return true
- }
-
- fnCtx := func(ctx context.Context, fl FieldLevel) bool {
- return true
- }
-
- validate := New()
-
- errs := validate.RegisterValidation("new", fn)
- Equal(t, errs, nil)
-
- errs = validate.RegisterValidation("", fn)
- NotEqual(t, errs, nil)
-
- validate.RegisterValidation("new", nil)
- NotEqual(t, errs, nil)
-
- errs = validate.RegisterValidation("new", fn)
- Equal(t, errs, nil)
-
- errs = validate.RegisterValidationCtx("new", fnCtx)
- Equal(t, errs, nil)
-
- PanicMatches(t, func() { validate.RegisterValidation("dive", fn) }, "Tag 'dive' either contains restricted characters or is the same as a restricted tag needed for normal operation")
-}
-
-func TestChangeTag(t *testing.T) {
-
- validate := New()
- validate.SetTagName("val")
-
- type Test struct {
- Name string `val:"len=4"`
- }
- s := &Test{
- Name: "TEST",
- }
-
- errs := validate.Struct(s)
- Equal(t, errs, nil)
-
- s.Name = ""
-
- errs = validate.Struct(s)
- NotEqual(t, errs, nil)
- AssertError(t, errs, "Test.Name", "Test.Name", "Name", "Name", "len")
-}
-
-func TestUnexposedStruct(t *testing.T) {
-
- validate := New()
-
- type Test struct {
- Name string
- unexposed struct {
- A string `validate:"required"`
- }
- }
-
- s := &Test{
- Name: "TEST",
- }
-
- errs := validate.Struct(s)
- Equal(t, errs, nil)
-}
-
-func TestBadParams(t *testing.T) {
-
- validate := New()
-
- i := 1
- errs := validate.Var(i, "-")
- Equal(t, errs, nil)
-
- PanicMatches(t, func() { validate.Var(i, "len=a") }, "strconv.ParseInt: parsing \"a\": invalid syntax")
- PanicMatches(t, func() { validate.Var(i, "len=a") }, "strconv.ParseInt: parsing \"a\": invalid syntax")
-
- var ui uint = 1
- PanicMatches(t, func() { validate.Var(ui, "len=a") }, "strconv.ParseUint: parsing \"a\": invalid syntax")
-
- f := 1.23
- PanicMatches(t, func() { validate.Var(f, "len=a") }, "strconv.ParseFloat: parsing \"a\": invalid syntax")
-}
-
-func TestLength(t *testing.T) {
-
- validate := New()
-
- i := true
- PanicMatches(t, func() { validate.Var(i, "len") }, "Bad field type bool")
-}
-
-func TestIsGt(t *testing.T) {
-
- validate := New()
-
- myMap := map[string]string{}
- errs := validate.Var(myMap, "gt=0")
- NotEqual(t, errs, nil)
-
- f := 1.23
- errs = validate.Var(f, "gt=5")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "gt")
-
- var ui uint = 5
- errs = validate.Var(ui, "gt=10")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "gt")
-
- i := true
- PanicMatches(t, func() { validate.Var(i, "gt") }, "Bad field type bool")
-
- tm := time.Now().UTC()
- tm = tm.Add(time.Hour * 24)
-
- errs = validate.Var(tm, "gt")
- Equal(t, errs, nil)
-
- t2 := time.Now().UTC().Add(-time.Hour)
-
- errs = validate.Var(t2, "gt")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "gt")
-
- type Test struct {
- Now *time.Time `validate:"gt"`
- }
- s := &Test{
- Now: &tm,
- }
-
- errs = validate.Struct(s)
- Equal(t, errs, nil)
-
- s = &Test{
- Now: &t2,
- }
-
- errs = validate.Struct(s)
- NotEqual(t, errs, nil)
- AssertError(t, errs, "Test.Now", "Test.Now", "Now", "Now", "gt")
-}
-
-func TestIsGte(t *testing.T) {
-
- validate := New()
-
- i := true
- PanicMatches(t, func() { validate.Var(i, "gte") }, "Bad field type bool")
-
- t1 := time.Now().UTC()
- t1 = t1.Add(time.Hour * 24)
-
- errs := validate.Var(t1, "gte")
- Equal(t, errs, nil)
-
- t2 := time.Now().UTC().Add(-time.Hour)
-
- errs = validate.Var(t2, "gte")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "gte")
-
- type Test struct {
- Now *time.Time `validate:"gte"`
- }
- s := &Test{
- Now: &t1,
- }
-
- errs = validate.Struct(s)
- Equal(t, errs, nil)
-
- s = &Test{
- Now: &t2,
- }
-
- errs = validate.Struct(s)
- NotEqual(t, errs, nil)
- AssertError(t, errs, "Test.Now", "Test.Now", "Now", "Now", "gte")
-}
-
-func TestIsLt(t *testing.T) {
-
- validate := New()
-
- myMap := map[string]string{}
- errs := validate.Var(myMap, "lt=0")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "lt")
-
- f := 1.23
- errs = validate.Var(f, "lt=0")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "lt")
-
- var ui uint = 5
- errs = validate.Var(ui, "lt=0")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "lt")
-
- i := true
- PanicMatches(t, func() { validate.Var(i, "lt") }, "Bad field type bool")
-
- t1 := time.Now().UTC().Add(-time.Hour)
-
- errs = validate.Var(t1, "lt")
- Equal(t, errs, nil)
-
- t2 := time.Now().UTC()
- t2 = t2.Add(time.Hour * 24)
-
- errs = validate.Var(t2, "lt")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "lt")
-
- type Test struct {
- Now *time.Time `validate:"lt"`
- }
-
- s := &Test{
- Now: &t1,
- }
-
- errs = validate.Struct(s)
- Equal(t, errs, nil)
-
- s = &Test{
- Now: &t2,
- }
-
- errs = validate.Struct(s)
- NotEqual(t, errs, nil)
- AssertError(t, errs, "Test.Now", "Test.Now", "Now", "Now", "lt")
-}
-
-func TestIsLte(t *testing.T) {
-
- validate := New()
-
- i := true
- PanicMatches(t, func() { validate.Var(i, "lte") }, "Bad field type bool")
-
- t1 := time.Now().UTC().Add(-time.Hour)
-
- errs := validate.Var(t1, "lte")
- Equal(t, errs, nil)
-
- t2 := time.Now().UTC()
- t2 = t2.Add(time.Hour * 24)
-
- errs = validate.Var(t2, "lte")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "lte")
-
- type Test struct {
- Now *time.Time `validate:"lte"`
- }
-
- s := &Test{
- Now: &t1,
- }
-
- errs = validate.Struct(s)
- Equal(t, errs, nil)
-
- s = &Test{
- Now: &t2,
- }
-
- errs = validate.Struct(s)
- NotEqual(t, errs, nil)
-}
-
-func TestUrl(t *testing.T) {
-
- var tests = []struct {
- param string
- expected bool
- }{
- {"http://foo.bar#com", true},
- {"http://foobar.com", true},
- {"https://foobar.com", true},
- {"foobar.com", false},
- {"http://foobar.coffee/", true},
- {"http://foobar.中文网/", true},
- {"http://foobar.org/", true},
- {"http://foobar.org:8080/", true},
- {"ftp://foobar.ru/", true},
- {"http://user:pass@www.foobar.com/", true},
- {"http://127.0.0.1/", true},
- {"http://duckduckgo.com/?q=%2F", true},
- {"http://localhost:3000/", true},
- {"http://foobar.com/?foo=bar#baz=qux", true},
- {"http://foobar.com?foo=bar", true},
- {"http://www.xn--froschgrn-x9a.net/", true},
- {"", false},
- {"xyz://foobar.com", true},
- {"invalid.", false},
- {".com", false},
- {"rtmp://foobar.com", true},
- {"http://www.foo_bar.com/", true},
- {"http://localhost:3000/", true},
- {"http://foobar.com/#baz", true},
- {"http://foobar.com#baz=qux", true},
- {"http://foobar.com/t$-_.+!*\\'(),", true},
- {"http://www.foobar.com/~foobar", true},
- {"http://www.-foobar.com/", true},
- {"http://www.foo---bar.com/", true},
- {"mailto:someone@example.com", true},
- {"irc://irc.server.org/channel", true},
- {"irc://#channel@network", true},
- {"/abs/test/dir", false},
- {"./rel/test/dir", false},
- }
-
- validate := New()
-
- for i, test := range tests {
-
- errs := validate.Var(test.param, "url")
-
- if test.expected {
- if !IsEqual(errs, nil) {
- t.Fatalf("Index: %d URL failed Error: %s", i, errs)
- }
- } else {
- if IsEqual(errs, nil) {
- t.Fatalf("Index: %d URL failed Error: %s", i, errs)
- } else {
- val := getError(errs, "", "")
- if val.Tag() != "url" {
- t.Fatalf("Index: %d URL failed Error: %s", i, errs)
- }
- }
- }
- }
-
- i := 1
- PanicMatches(t, func() { validate.Var(i, "url") }, "Bad field type int")
-}
-
-func TestUri(t *testing.T) {
-
- var tests = []struct {
- param string
- expected bool
- }{
- {"http://foo.bar#com", true},
- {"http://foobar.com", true},
- {"https://foobar.com", true},
- {"foobar.com", false},
- {"http://foobar.coffee/", true},
- {"http://foobar.中文网/", true},
- {"http://foobar.org/", true},
- {"http://foobar.org:8080/", true},
- {"ftp://foobar.ru/", true},
- {"http://user:pass@www.foobar.com/", true},
- {"http://127.0.0.1/", true},
- {"http://duckduckgo.com/?q=%2F", true},
- {"http://localhost:3000/", true},
- {"http://foobar.com/?foo=bar#baz=qux", true},
- {"http://foobar.com?foo=bar", true},
- {"http://www.xn--froschgrn-x9a.net/", true},
- {"", false},
- {"xyz://foobar.com", true},
- {"invalid.", false},
- {".com", false},
- {"rtmp://foobar.com", true},
- {"http://www.foo_bar.com/", true},
- {"http://localhost:3000/", true},
- {"http://foobar.com#baz=qux", true},
- {"http://foobar.com/t$-_.+!*\\'(),", true},
- {"http://www.foobar.com/~foobar", true},
- {"http://www.-foobar.com/", true},
- {"http://www.foo---bar.com/", true},
- {"mailto:someone@example.com", true},
- {"irc://irc.server.org/channel", true},
- {"irc://#channel@network", true},
- {"/abs/test/dir", true},
- {"./rel/test/dir", false},
- }
-
- validate := New()
-
- for i, test := range tests {
-
- errs := validate.Var(test.param, "uri")
-
- if test.expected {
- if !IsEqual(errs, nil) {
- t.Fatalf("Index: %d URI failed Error: %s", i, errs)
- }
- } else {
- if IsEqual(errs, nil) {
- t.Fatalf("Index: %d URI failed Error: %s", i, errs)
- } else {
- val := getError(errs, "", "")
- if val.Tag() != "uri" {
- t.Fatalf("Index: %d URI failed Error: %s", i, errs)
- }
- }
- }
- }
-
- i := 1
- PanicMatches(t, func() { validate.Var(i, "uri") }, "Bad field type int")
-}
-
-func TestOrTag(t *testing.T) {
-
- validate := New()
-
- s := "rgba(0,31,255,0.5)"
- errs := validate.Var(s, "rgb|rgba")
- Equal(t, errs, nil)
-
- s = "rgba(0,31,255,0.5)"
- errs = validate.Var(s, "rgb|rgba|len=18")
- Equal(t, errs, nil)
-
- s = "this ain't right"
- errs = validate.Var(s, "rgb|rgba")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "rgb|rgba")
-
- s = "this ain't right"
- errs = validate.Var(s, "rgb|rgba|len=10")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "rgb|rgba|len=10")
-
- s = "this is right"
- errs = validate.Var(s, "rgb|rgba|len=13")
- Equal(t, errs, nil)
-
- s = ""
- errs = validate.Var(s, "omitempty,rgb|rgba")
- Equal(t, errs, nil)
-
- s = "green"
- errs = validate.Var(s, "eq=|eq=blue,rgb|rgba") //should fail on first validation block
- NotEqual(t, errs, nil)
- ve := errs.(ValidationErrors)
- Equal(t, len(ve), 1)
- Equal(t, ve[0].Tag(), "eq=|eq=blue")
-
- s = "this is right, but a blank or isn't"
-
- PanicMatches(t, func() { validate.Var(s, "rgb||len=13") }, "Invalid validation tag on field ''")
- PanicMatches(t, func() { validate.Var(s, "rgb|rgbaa|len=13") }, "Undefined validation function 'rgbaa' on field ''")
-
- v2 := New()
- v2.RegisterTagNameFunc(func(fld reflect.StructField) string {
-
- name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0]
-
- if name == "-" {
- return ""
- }
-
- return name
- })
-
- type Colors struct {
- Fav string `validate:"rgb|rgba" json:"fc"`
- }
-
- c := Colors{Fav: "this ain't right"}
-
- err := v2.Struct(c)
- NotEqual(t, err, nil)
-
- errs = err.(ValidationErrors)
- fe := getError(errs, "Colors.fc", "Colors.Fav")
- NotEqual(t, fe, nil)
-}
-
-func TestHsla(t *testing.T) {
-
- validate := New()
-
- s := "hsla(360,100%,100%,1)"
- errs := validate.Var(s, "hsla")
- Equal(t, errs, nil)
-
- s = "hsla(360,100%,100%,0.5)"
- errs = validate.Var(s, "hsla")
- Equal(t, errs, nil)
-
- s = "hsla(0,0%,0%, 0)"
- errs = validate.Var(s, "hsla")
- Equal(t, errs, nil)
-
- s = "hsl(361,100%,50%,1)"
- errs = validate.Var(s, "hsla")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "hsla")
-
- s = "hsl(361,100%,50%)"
- errs = validate.Var(s, "hsla")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "hsla")
-
- s = "hsla(361,100%,50%)"
- errs = validate.Var(s, "hsla")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "hsla")
-
- s = "hsla(360,101%,50%)"
- errs = validate.Var(s, "hsla")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "hsla")
-
- s = "hsla(360,100%,101%)"
- errs = validate.Var(s, "hsla")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "hsla")
-
- i := 1
- validate.Var(i, "hsla")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "hsla")
-}
-
-func TestHsl(t *testing.T) {
-
- validate := New()
-
- s := "hsl(360,100%,50%)"
- errs := validate.Var(s, "hsl")
- Equal(t, errs, nil)
-
- s = "hsl(0,0%,0%)"
- errs = validate.Var(s, "hsl")
- Equal(t, errs, nil)
-
- s = "hsl(361,100%,50%)"
- errs = validate.Var(s, "hsl")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "hsl")
-
- s = "hsl(361,101%,50%)"
- errs = validate.Var(s, "hsl")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "hsl")
-
- s = "hsl(361,100%,101%)"
- errs = validate.Var(s, "hsl")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "hsl")
-
- s = "hsl(-10,100%,100%)"
- errs = validate.Var(s, "hsl")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "hsl")
-
- i := 1
- errs = validate.Var(i, "hsl")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "hsl")
-}
-
-func TestRgba(t *testing.T) {
-
- validate := New()
-
- s := "rgba(0,31,255,0.5)"
- errs := validate.Var(s, "rgba")
- Equal(t, errs, nil)
-
- s = "rgba(0,31,255,0.12)"
- errs = validate.Var(s, "rgba")
- Equal(t, errs, nil)
-
- s = "rgba(12%,55%,100%,0.12)"
- errs = validate.Var(s, "rgba")
- Equal(t, errs, nil)
-
- s = "rgba( 0, 31, 255, 0.5)"
- errs = validate.Var(s, "rgba")
- Equal(t, errs, nil)
-
- s = "rgba(12%,55,100%,0.12)"
- errs = validate.Var(s, "rgba")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "rgba")
-
- s = "rgb(0, 31, 255)"
- errs = validate.Var(s, "rgba")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "rgba")
-
- s = "rgb(1,349,275,0.5)"
- errs = validate.Var(s, "rgba")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "rgba")
-
- s = "rgb(01,31,255,0.5)"
- errs = validate.Var(s, "rgba")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "rgba")
-
- i := 1
- errs = validate.Var(i, "rgba")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "rgba")
-}
-
-func TestRgb(t *testing.T) {
-
- validate := New()
-
- s := "rgb(0,31,255)"
- errs := validate.Var(s, "rgb")
- Equal(t, errs, nil)
-
- s = "rgb(0, 31, 255)"
- errs = validate.Var(s, "rgb")
- Equal(t, errs, nil)
-
- s = "rgb(10%, 50%, 100%)"
- errs = validate.Var(s, "rgb")
- Equal(t, errs, nil)
-
- s = "rgb(10%, 50%, 55)"
- errs = validate.Var(s, "rgb")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "rgb")
-
- s = "rgb(1,349,275)"
- errs = validate.Var(s, "rgb")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "rgb")
-
- s = "rgb(01,31,255)"
- errs = validate.Var(s, "rgb")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "rgb")
-
- s = "rgba(0,31,255)"
- errs = validate.Var(s, "rgb")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "rgb")
-
- i := 1
- errs = validate.Var(i, "rgb")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "rgb")
-}
-
-func TestEmail(t *testing.T) {
-
- validate := New()
-
- s := "test@mail.com"
- errs := validate.Var(s, "email")
- Equal(t, errs, nil)
-
- s = "Dörte@Sörensen.example.com"
- errs = validate.Var(s, "email")
- Equal(t, errs, nil)
-
- s = "θσερ@εχαμπλε.ψομ"
- errs = validate.Var(s, "email")
- Equal(t, errs, nil)
-
- s = "юзер@екзампл.ком"
- errs = validate.Var(s, "email")
- Equal(t, errs, nil)
-
- s = "उपयोगकर्ता@उदाहरण.कॉम"
- errs = validate.Var(s, "email")
- Equal(t, errs, nil)
-
- s = "用户@例子.广告"
- errs = validate.Var(s, "email")
- Equal(t, errs, nil)
-
- s = ""
- errs = validate.Var(s, "email")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "email")
-
- s = "test@email"
- errs = validate.Var(s, "email")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "email")
-
- s = "test@email."
- errs = validate.Var(s, "email")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "email")
-
- s = "@email.com"
- errs = validate.Var(s, "email")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "email")
-
- i := true
- errs = validate.Var(i, "email")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "email")
-}
-
-func TestHexColor(t *testing.T) {
-
- validate := New()
-
- s := "#fff"
- errs := validate.Var(s, "hexcolor")
- Equal(t, errs, nil)
-
- s = "#c2c2c2"
- errs = validate.Var(s, "hexcolor")
- Equal(t, errs, nil)
-
- s = "fff"
- errs = validate.Var(s, "hexcolor")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "hexcolor")
-
- s = "fffFF"
- errs = validate.Var(s, "hexcolor")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "hexcolor")
-
- i := true
- errs = validate.Var(i, "hexcolor")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "hexcolor")
-}
-
-func TestHexadecimal(t *testing.T) {
-
- validate := New()
-
- s := "ff0044"
- errs := validate.Var(s, "hexadecimal")
- Equal(t, errs, nil)
-
- s = "abcdefg"
- errs = validate.Var(s, "hexadecimal")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "hexadecimal")
-
- i := true
- errs = validate.Var(i, "hexadecimal")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "hexadecimal")
-}
-
-func TestNumber(t *testing.T) {
-
- validate := New()
-
- s := "1"
- errs := validate.Var(s, "number")
- Equal(t, errs, nil)
-
- s = "+1"
- errs = validate.Var(s, "number")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "number")
-
- s = "-1"
- errs = validate.Var(s, "number")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "number")
-
- s = "1.12"
- errs = validate.Var(s, "number")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "number")
-
- s = "+1.12"
- errs = validate.Var(s, "number")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "number")
-
- s = "-1.12"
- errs = validate.Var(s, "number")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "number")
-
- s = "1."
- errs = validate.Var(s, "number")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "number")
-
- s = "1.o"
- errs = validate.Var(s, "number")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "number")
-
- i := 1
- errs = validate.Var(i, "number")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "number")
-}
-
-func TestNumeric(t *testing.T) {
-
- validate := New()
-
- s := "1"
- errs := validate.Var(s, "numeric")
- Equal(t, errs, nil)
-
- s = "+1"
- errs = validate.Var(s, "numeric")
- Equal(t, errs, nil)
-
- s = "-1"
- errs = validate.Var(s, "numeric")
- Equal(t, errs, nil)
-
- s = "1.12"
- errs = validate.Var(s, "numeric")
- Equal(t, errs, nil)
-
- s = "+1.12"
- errs = validate.Var(s, "numeric")
- Equal(t, errs, nil)
-
- s = "-1.12"
- errs = validate.Var(s, "numeric")
- Equal(t, errs, nil)
-
- s = "1."
- errs = validate.Var(s, "numeric")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "numeric")
-
- s = "1.o"
- errs = validate.Var(s, "numeric")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "numeric")
-
- i := 1
- errs = validate.Var(i, "numeric")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "numeric")
-}
-
-func TestAlphaNumeric(t *testing.T) {
-
- validate := New()
-
- s := "abcd123"
- errs := validate.Var(s, "alphanum")
- Equal(t, errs, nil)
-
- s = "abc!23"
- errs = validate.Var(s, "alphanum")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "alphanum")
-
- errs = validate.Var(1, "alphanum")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "alphanum")
-}
-
-func TestAlpha(t *testing.T) {
-
- validate := New()
-
- s := "abcd"
- errs := validate.Var(s, "alpha")
- Equal(t, errs, nil)
-
- s = "abc®"
- errs = validate.Var(s, "alpha")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "alpha")
-
- s = "abc÷"
- errs = validate.Var(s, "alpha")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "alpha")
-
- s = "abc1"
- errs = validate.Var(s, "alpha")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "alpha")
-
- s = "this is a test string"
- errs = validate.Var(s, "alpha")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "alpha")
-
- errs = validate.Var(1, "alpha")
- NotEqual(t, errs, nil)
- AssertError(t, errs, "", "", "", "", "alpha")
-
-}
-
-func TestStructStringValidation(t *testing.T) {
-
- validate := New()
-
- tSuccess := &TestString{
- Required: "Required",
- Len: "length==10",
- Min: "min=1",
- Max: "1234567890",
- MinMax: "12345",
- Lt: "012345678",
- Lte: "0123456789",
- Gt: "01234567890",
- Gte: "0123456789",
- OmitEmpty: "",
- Sub: &SubTest{
- Test: "1",
- },
- SubIgnore: &SubTest{
- Test: "",
- },
- Anonymous: struct {
- A string `validate:"required"`
- }{
- A: "1",
- },
- Iface: &Impl{
- F: "123",
- },
- }
-
- errs := validate.Struct(tSuccess)
- Equal(t, errs, nil)
-
- tFail := &TestString{
- Required: "",
- Len: "",
- Min: "",
- Max: "12345678901",
- MinMax: "",
- Lt: "0123456789",
- Lte: "01234567890",
- Gt: "1",
- Gte: "1",
- OmitEmpty: "12345678901",
- Sub: &SubTest{
- Test: "",
- },
- Anonymous: struct {
- A string `validate:"required"`
- }{
- A: "",
- },
- Iface: &Impl{
- F: "12",
- },
- }
-
- errs = validate.Struct(tFail)
-
- // Assert Top Level
- NotEqual(t, errs, nil)
- Equal(t, len(errs.(ValidationErrors)), 13)
-
- // Assert Fields
- AssertError(t, errs, "TestString.Required", "TestString.Required", "Required", "Required", "required")
- AssertError(t, errs, "TestString.Len", "TestString.Len", "Len", "Len", "len")
- AssertError(t, errs, "TestString.Min", "TestString.Min", "Min", "Min", "min")
- AssertError(t, errs, "TestString.Max", "TestString.Max", "Max", "Max", "max")
- AssertError(t, errs, "TestString.MinMax", "TestString.MinMax", "MinMax", "MinMax", "min")
- AssertError(t, errs, "TestString.Lt", "TestString.Lt", "Lt", "Lt", "lt")
- AssertError(t, errs, "TestString.Lte", "TestString.Lte", "Lte", "Lte", "lte")
- AssertError(t, errs, "TestString.Gt", "TestString.Gt", "Gt", "Gt", "gt")
- AssertError(t, errs, "TestString.Gte", "TestString.Gte", "Gte", "Gte", "gte")
- AssertError(t, errs, "TestString.OmitEmpty", "TestString.OmitEmpty", "OmitEmpty", "OmitEmpty", "max")
-
- // Nested Struct Field Errs
- AssertError(t, errs, "TestString.Anonymous.A", "TestString.Anonymous.A", "A", "A", "required")
- AssertError(t, errs, "TestString.Sub.Test", "TestString.Sub.Test", "Test", "Test", "required")
- AssertError(t, errs, "TestString.Iface.F", "TestString.Iface.F", "F", "F", "len")
-}
-
-func TestStructInt32Validation(t *testing.T) {
-
- type TestInt32 struct {
- Required int `validate:"required"`
- Len int `validate:"len=10"`
- Min int `validate:"min=1"`
- Max int `validate:"max=10"`
- MinMax int `validate:"min=1,max=10"`
- Lt int `validate:"lt=10"`
- Lte int `validate:"lte=10"`
- Gt int `validate:"gt=10"`
- Gte int `validate:"gte=10"`
- OmitEmpty int `validate:"omitempty,min=1,max=10"`
- }
-
- tSuccess := &TestInt32{
- Required: 1,
- Len: 10,
- Min: 1,
- Max: 10,
- MinMax: 5,
- Lt: 9,
- Lte: 10,
- Gt: 11,
- Gte: 10,
- OmitEmpty: 0,
- }
-
- validate := New()
- errs := validate.Struct(tSuccess)
- Equal(t, errs, nil)
-
- tFail := &TestInt32{
- Required: 0,
- Len: 11,
- Min: -1,
- Max: 11,
- MinMax: -1,
- Lt: 10,
- Lte: 11,
- Gt: 10,
- Gte: 9,
- OmitEmpty: 11,
- }
-
- errs = validate.Struct(tFail)
-
- // Assert Top Level
- NotEqual(t, errs, nil)
- Equal(t, len(errs.(ValidationErrors)), 10)
-
- // Assert Fields
- AssertError(t, errs, "TestInt32.Required", "TestInt32.Required", "Required", "Required", "required")
- AssertError(t, errs, "TestInt32.Len", "TestInt32.Len", "Len", "Len", "len")
- AssertError(t, errs, "TestInt32.Min", "TestInt32.Min", "Min", "Min", "min")
- AssertError(t, errs, "TestInt32.Max", "TestInt32.Max", "Max", "Max", "max")
- AssertError(t, errs, "TestInt32.MinMax", "TestInt32.MinMax", "MinMax", "MinMax", "min")
- AssertError(t, errs, "TestInt32.Lt", "TestInt32.Lt", "Lt", "Lt", "lt")
- AssertError(t, errs, "TestInt32.Lte", "TestInt32.Lte", "Lte", "Lte", "lte")
- AssertError(t, errs, "TestInt32.Gt", "TestInt32.Gt", "Gt", "Gt", "gt")
- AssertError(t, errs, "TestInt32.Gte", "TestInt32.Gte", "Gte", "Gte", "gte")
- AssertError(t, errs, "TestInt32.OmitEmpty", "TestInt32.OmitEmpty", "OmitEmpty", "OmitEmpty", "max")
-}
-
-func TestStructUint64Validation(t *testing.T) {
-
- validate := New()
-
- tSuccess := &TestUint64{
- Required: 1,
- Len: 10,
- Min: 1,
- Max: 10,
- MinMax: 5,
- OmitEmpty: 0,
- }
-
- errs := validate.Struct(tSuccess)
- Equal(t, errs, nil)
-
- tFail := &TestUint64{
- Required: 0,
- Len: 11,
- Min: 0,
- Max: 11,
- MinMax: 0,
- OmitEmpty: 11,
- }
-
- errs = validate.Struct(tFail)
-
- // Assert Top Level
- NotEqual(t, errs, nil)
- Equal(t, len(errs.(ValidationErrors)), 6)
-
- // Assert Fields
- AssertError(t, errs, "TestUint64.Required", "TestUint64.Required", "Required", "Required", "required")
- AssertError(t, errs, "TestUint64.Len", "TestUint64.Len", "Len", "Len", "len")
- AssertError(t, errs, "TestUint64.Min", "TestUint64.Min", "Min", "Min", "min")
- AssertError(t, errs, "TestUint64.Max", "TestUint64.Max", "Max", "Max", "max")
- AssertError(t, errs, "TestUint64.MinMax", "TestUint64.MinMax", "MinMax", "MinMax", "min")
- AssertError(t, errs, "TestUint64.OmitEmpty", "TestUint64.OmitEmpty", "OmitEmpty", "OmitEmpty", "max")
-}
-
-func TestStructFloat64Validation(t *testing.T) {
-
- validate := New()
-
- tSuccess := &TestFloat64{
- Required: 1,
- Len: 10,
- Min: 1,
- Max: 10,
- MinMax: 5,
- OmitEmpty: 0,
- }
-
- errs := validate.Struct(tSuccess)
- Equal(t, errs, nil)
-
- tFail := &TestFloat64{
- Required: 0,
- Len: 11,
- Min: 0,
- Max: 11,
- MinMax: 0,
- OmitEmpty: 11,
- }
-
- errs = validate.Struct(tFail)
-
- // Assert Top Level
- NotEqual(t, errs, nil)
- Equal(t, len(errs.(ValidationErrors)), 6)
-
- // Assert Fields
- AssertError(t, errs, "TestFloat64.Required", "TestFloat64.Required", "Required", "Required", "required")
- AssertError(t, errs, "TestFloat64.Len", "TestFloat64.Len", "Len", "Len", "len")
- AssertError(t, errs, "TestFloat64.Min", "TestFloat64.Min", "Min", "Min", "min")
- AssertError(t, errs, "TestFloat64.Max", "TestFloat64.Max", "Max", "Max", "max")
- AssertError(t, errs, "TestFloat64.MinMax", "TestFloat64.MinMax", "MinMax", "MinMax", "min")
- AssertError(t, errs, "TestFloat64.OmitEmpty", "TestFloat64.OmitEmpty", "OmitEmpty", "OmitEmpty", "max")
-}
-
-func TestStructSliceValidation(t *testing.T) {
-
- validate := New()
-
- tSuccess := &TestSlice{
- Required: []int{1},
- Len: []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 0},
- Min: []int{1, 2},
- Max: []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 0},
- MinMax: []int{1, 2, 3, 4, 5},
- OmitEmpty: nil,
- }
-
- errs := validate.Struct(tSuccess)
- Equal(t, errs, nil)
-
- tFail := &TestSlice{
- Required: nil,
- Len: []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1},
- Min: []int{},
- Max: []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1},
- MinMax: []int{},
- OmitEmpty: []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1},
- }
-
- errs = validate.Struct(tFail)
- NotEqual(t, errs, nil)
- Equal(t, len(errs.(ValidationErrors)), 6)
-
- // Assert Field Errors
- AssertError(t, errs, "TestSlice.Required", "TestSlice.Required", "Required", "Required", "required")
- AssertError(t, errs, "TestSlice.Len", "TestSlice.Len", "Len", "Len", "len")
- AssertError(t, errs, "TestSlice.Min", "TestSlice.Min", "Min", "Min", "min")
- AssertError(t, errs, "TestSlice.Max", "TestSlice.Max", "Max", "Max", "max")
- AssertError(t, errs, "TestSlice.MinMax", "TestSlice.MinMax", "MinMax", "MinMax", "min")
- AssertError(t, errs, "TestSlice.OmitEmpty", "TestSlice.OmitEmpty", "OmitEmpty", "OmitEmpty", "max")
-
- fe := getError(errs, "TestSlice.Len", "TestSlice.Len")
- NotEqual(t, fe, nil)
- Equal(t, fe.Field(), "Len")
- Equal(t, fe.StructField(), "Len")
- Equal(t, fe.Namespace(), "TestSlice.Len")
- Equal(t, fe.StructNamespace(), "TestSlice.Len")
- Equal(t, fe.Tag(), "len")
- Equal(t, fe.ActualTag(), "len")
- Equal(t, fe.Param(), "10")
- Equal(t, fe.Kind(), reflect.Slice)
- Equal(t, fe.Type(), reflect.TypeOf([]int{}))
-
- _, ok := fe.Value().([]int)
- Equal(t, ok, true)
-
-}
-
-func TestInvalidStruct(t *testing.T) {
-
- validate := New()
-
- s := &SubTest{
- Test: "1",
- }
-
- err := validate.Struct(s.Test)
- NotEqual(t, err, nil)
- Equal(t, err.Error(), "validator: (nil string)")
-
- err = validate.Struct(nil)
- NotEqual(t, err, nil)
- Equal(t, err.Error(), "validator: (nil)")
-
- err = validate.StructPartial(nil, "SubTest.Test")
- NotEqual(t, err, nil)
- Equal(t, err.Error(), "validator: (nil)")
-
- err = validate.StructExcept(nil, "SubTest.Test")
- NotEqual(t, err, nil)
- Equal(t, err.Error(), "validator: (nil)")
-}
-
-func TestInvalidValidatorFunction(t *testing.T) {
-
- validate := New()
-
- s := &SubTest{
- Test: "1",
- }
-
- PanicMatches(t, func() { validate.Var(s.Test, "zzxxBadFunction") }, "Undefined validation function 'zzxxBadFunction' on field ''")
-}
-
-func TestCustomFieldName(t *testing.T) {
-
- validate := New()
- validate.RegisterTagNameFunc(func(fld reflect.StructField) string {
- name := strings.SplitN(fld.Tag.Get("schema"), ",", 2)[0]
-
- if name == "-" {
- return ""
- }
-
- return name
- })
-
- type A struct {
- B string `schema:"b" validate:"required"`
- C string `schema:"c" validate:"required"`
- D []bool `schema:"d" validate:"required"`
- E string `schema:"-" validate:"required"`
- }
-
- a := &A{}
-
- err := validate.Struct(a)
- NotEqual(t, err, nil)
-
- errs := err.(ValidationErrors)
- Equal(t, len(errs), 4)
- Equal(t, getError(errs, "A.b", "A.B").Field(), "b")
- Equal(t, getError(errs, "A.c", "A.C").Field(), "c")
- Equal(t, getError(errs, "A.d", "A.D").Field(), "d")
- Equal(t, getError(errs, "A.E", "A.E").Field(), "E")
-
- v2 := New()
- err = v2.Struct(a)
- NotEqual(t, err, nil)
-
- errs = err.(ValidationErrors)
- Equal(t, len(errs), 4)
- Equal(t, getError(errs, "A.B", "A.B").Field(), "B")
- Equal(t, getError(errs, "A.C", "A.C").Field(), "C")
- Equal(t, getError(errs, "A.D", "A.D").Field(), "D")
- Equal(t, getError(errs, "A.E", "A.E").Field(), "E")
-}
-
-func TestMutipleRecursiveExtractStructCache(t *testing.T) {
-
- validate := New()
-
- type Recursive struct {
- Field *string `validate:"required,len=5,ne=string"`
- }
-
- var test Recursive
-
- current := reflect.ValueOf(test)
- name := "Recursive"
- proceed := make(chan struct{})
-
- sc := validate.extractStructCache(current, name)
- ptr := fmt.Sprintf("%p", sc)
-
- for i := 0; i < 100; i++ {
-
- go func() {
- <-proceed
- sc := validate.extractStructCache(current, name)
- Equal(t, ptr, fmt.Sprintf("%p", sc))
- }()
- }
-
- close(proceed)
-}
-
-// Thanks @robbrockbank, see https://github.com/go-playground/validator/issues/249
-func TestPointerAndOmitEmpty(t *testing.T) {
-
- validate := New()
-
- type Test struct {
- MyInt *int `validate:"omitempty,gte=2,lte=255"`
- }
-
- val1 := 0
- val2 := 256
-
- t1 := Test{MyInt: &val1} // This should fail validation on gte because value is 0
- t2 := Test{MyInt: &val2} // This should fail validate on lte because value is 256
- t3 := Test{MyInt: nil} // This should succeed validation because pointer is nil
-
- errs := validate.Struct(t1)
- NotEqual(t, errs, nil)
- AssertError(t, errs, "Test.MyInt", "Test.MyInt", "MyInt", "MyInt", "gte")
-
- errs = validate.Struct(t2)
- NotEqual(t, errs, nil)
- AssertError(t, errs, "Test.MyInt", "Test.MyInt", "MyInt", "MyInt", "lte")
-
- errs = validate.Struct(t3)
- Equal(t, errs, nil)
-
- type TestIface struct {
- MyInt interface{} `validate:"omitempty,gte=2,lte=255"`
- }
-
- ti1 := TestIface{MyInt: &val1} // This should fail validation on gte because value is 0
- ti2 := TestIface{MyInt: &val2} // This should fail validate on lte because value is 256
- ti3 := TestIface{MyInt: nil} // This should succeed validation because pointer is nil
-
- errs = validate.Struct(ti1)
- NotEqual(t, errs, nil)
- AssertError(t, errs, "TestIface.MyInt", "TestIface.MyInt", "MyInt", "MyInt", "gte")
-
- errs = validate.Struct(ti2)
- NotEqual(t, errs, nil)
- AssertError(t, errs, "TestIface.MyInt", "TestIface.MyInt", "MyInt", "MyInt", "lte")
-
- errs = validate.Struct(ti3)
- Equal(t, errs, nil)
-}
-
-func TestRequired(t *testing.T) {
-
- validate := New()
- validate.RegisterTagNameFunc(func(fld reflect.StructField) string {
- name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0]
-
- if name == "-" {
- return ""
- }
-
- return name
- })
-
- type Test struct {
- Value interface{} `validate:"required"`
- }
-
- var test Test
-
- err := validate.Struct(test)
- NotEqual(t, err, nil)
- AssertError(t, err.(ValidationErrors), "Test.Value", "Test.Value", "Value", "Value", "required")
-}
-
-func TestTranslations(t *testing.T) {
- en := en.New()
- uni := ut.New(en, en, fr.New())
-
- trans, _ := uni.GetTranslator("en")
- fr, _ := uni.GetTranslator("fr")
-
- validate := New()
- err := validate.RegisterTranslation("required", trans,
- func(ut ut.Translator) (err error) {
-
- // using this stype because multiple translation may have to be added for the full translation
- if err = ut.Add("required", "{0} is a required field", false); err != nil {
- return
- }
-
- return
-
- }, func(ut ut.Translator, fe FieldError) string {
-
- t, err := ut.T(fe.Tag(), fe.Field())
- if err != nil {
- fmt.Printf("warning: error translating FieldError: %#v", fe.(*fieldError))
- return fe.(*fieldError).Error()
- }
-
- return t
- })
- Equal(t, err, nil)
-
- err = validate.RegisterTranslation("required", fr,
- func(ut ut.Translator) (err error) {
-
- // using this stype because multiple translation may have to be added for the full translation
- if err = ut.Add("required", "{0} est un champ obligatoire", false); err != nil {
- return
- }
-
- return
-
- }, func(ut ut.Translator, fe FieldError) string {
-
- t, err := ut.T(fe.Tag(), fe.Field())
- if err != nil {
- fmt.Printf("warning: error translating FieldError: %#v", fe.(*fieldError))
- return fe.(*fieldError).Error()
- }
-
- return t
- })
-
- Equal(t, err, nil)
-
- type Test struct {
- Value interface{} `validate:"required"`
- }
-
- var test Test
-
- err = validate.Struct(test)
- NotEqual(t, err, nil)
-
- errs := err.(ValidationErrors)
- Equal(t, len(errs), 1)
-
- fe := errs[0]
- Equal(t, fe.Tag(), "required")
- Equal(t, fe.Namespace(), "Test.Value")
- Equal(t, fe.Translate(trans), fmt.Sprintf("%s is a required field", fe.Field()))
- Equal(t, fe.Translate(fr), fmt.Sprintf("%s est un champ obligatoire", fe.Field()))
-
- nl := nl.New()
- uni2 := ut.New(nl, nl)
- trans2, _ := uni2.GetTranslator("nl")
- Equal(t, fe.Translate(trans2), "Key: 'Test.Value' Error:Field validation for 'Value' failed on the 'required' tag")
-
- terrs := errs.Translate(trans)
- Equal(t, len(terrs), 1)
-
- v, ok := terrs["Test.Value"]
- Equal(t, ok, true)
- Equal(t, v, fmt.Sprintf("%s is a required field", fe.Field()))
-
- terrs = errs.Translate(fr)
- Equal(t, len(terrs), 1)
-
- v, ok = terrs["Test.Value"]
- Equal(t, ok, true)
- Equal(t, v, fmt.Sprintf("%s est un champ obligatoire", fe.Field()))
-
- type Test2 struct {
- Value string `validate:"gt=1"`
- }
-
- var t2 Test2
-
- err = validate.Struct(t2)
- NotEqual(t, err, nil)
-
- errs = err.(ValidationErrors)
- Equal(t, len(errs), 1)
-
- fe = errs[0]
- Equal(t, fe.Tag(), "gt")
- Equal(t, fe.Namespace(), "Test2.Value")
- Equal(t, fe.Translate(trans), "Key: 'Test2.Value' Error:Field validation for 'Value' failed on the 'gt' tag")
-}
-
-func TestTranslationErrors(t *testing.T) {
-
- en := en.New()
- uni := ut.New(en, en, fr.New())
-
- trans, _ := uni.GetTranslator("en")
- trans.Add("required", "{0} is a required field", false) // using translator outside of validator also
-
- validate := New()
- err := validate.RegisterTranslation("required", trans,
- func(ut ut.Translator) (err error) {
-
- // using this stype because multiple translation may have to be added for the full translation
- if err = ut.Add("required", "{0} is a required field", false); err != nil {
- return
- }
-
- return
-
- }, func(ut ut.Translator, fe FieldError) string {
-
- t, err := ut.T(fe.Tag(), fe.Field())
- if err != nil {
- fmt.Printf("warning: error translating FieldError: %#v", fe.(*fieldError))
- return fe.(*fieldError).Error()
- }
-
- return t
- })
-
- NotEqual(t, err, nil)
- Equal(t, err.Error(), "error: conflicting key 'required' rule 'Unknown' with text '{0} is a required field' for locale 'en', value being ignored")
-}
-
-func TestStructFiltered(t *testing.T) {
-
- p1 := func(ns []byte) bool {
- if bytes.HasSuffix(ns, []byte("NoTag")) || bytes.HasSuffix(ns, []byte("Required")) {
- return false
- }
-
- return true
- }
-
- p2 := func(ns []byte) bool {
- if bytes.HasSuffix(ns, []byte("SubSlice[0].Test")) ||
- bytes.HasSuffix(ns, []byte("SubSlice[0]")) ||
- bytes.HasSuffix(ns, []byte("SubSlice")) ||
- bytes.HasSuffix(ns, []byte("Sub")) ||
- bytes.HasSuffix(ns, []byte("SubIgnore")) ||
- bytes.HasSuffix(ns, []byte("Anonymous")) ||
- bytes.HasSuffix(ns, []byte("Anonymous.A")) {
- return false
- }
-
- return true
- }
-
- p3 := func(ns []byte) bool {
- return !bytes.HasSuffix(ns, []byte("SubTest.Test"))
- }
-
- // p4 := []string{
- // "A",
- // }
-
- tPartial := &TestPartial{
- NoTag: "NoTag",
- Required: "Required",
-
- SubSlice: []*SubTest{
- {
-
- Test: "Required",
- },
- {
-
- Test: "Required",
- },
- },
-
- Sub: &SubTest{
- Test: "1",
- },
- SubIgnore: &SubTest{
- Test: "",
- },
- Anonymous: struct {
- A string `validate:"required"`
- ASubSlice []*SubTest `validate:"required,dive"`
- SubAnonStruct []struct {
- Test string `validate:"required"`
- OtherTest string `validate:"required"`
- } `validate:"required,dive"`
- }{
- A: "1",
- ASubSlice: []*SubTest{
- {
- Test: "Required",
- },
- {
- Test: "Required",
- },
- },
-
- SubAnonStruct: []struct {
- Test string `validate:"required"`
- OtherTest string `validate:"required"`
- }{
- {"Required", "RequiredOther"},
- {"Required", "RequiredOther"},
- },
- },
- }
-
- validate := New()
-
- // the following should all return no errors as everything is valid in
- // the default state
- errs := validate.StructFilteredCtx(context.Background(), tPartial, p1)
- Equal(t, errs, nil)
-
- errs = validate.StructFiltered(tPartial, p2)
- Equal(t, errs, nil)
-
- // this isn't really a robust test, but is ment to illustrate the ANON CASE below
- errs = validate.StructFiltered(tPartial.SubSlice[0], p3)
- Equal(t, errs, nil)
-
- // mod tParial for required feild and re-test making sure invalid fields are NOT required:
- tPartial.Required = ""
-
- // inversion and retesting Partial to generate failures:
- errs = validate.StructFiltered(tPartial, p1)
- NotEqual(t, errs, nil)
- AssertError(t, errs, "TestPartial.Required", "TestPartial.Required", "Required", "Required", "required")
-
- // reset Required field, and set nested struct
- tPartial.Required = "Required"
- tPartial.Anonymous.A = ""
-
- // will pass as unset feilds is not going to be tested
- errs = validate.StructFiltered(tPartial, p1)
- Equal(t, errs, nil)
-
- // will fail as unset feild is tested
- errs = validate.StructFiltered(tPartial, p2)
- NotEqual(t, errs, nil)
- AssertError(t, errs, "TestPartial.Anonymous.A", "TestPartial.Anonymous.A", "A", "A", "required")
-
- // reset nested struct and unset struct in slice
- tPartial.Anonymous.A = "Required"
- tPartial.SubSlice[0].Test = ""
-
- // these will pass as unset item is NOT tested
- errs = validate.StructFiltered(tPartial, p1)
- Equal(t, errs, nil)
-
- errs = validate.StructFiltered(tPartial, p2)
- NotEqual(t, errs, nil)
- AssertError(t, errs, "TestPartial.SubSlice[0].Test", "TestPartial.SubSlice[0].Test", "Test", "Test", "required")
- Equal(t, len(errs.(ValidationErrors)), 1)
-
- // Unset second slice member concurrently to test dive behavior:
- tPartial.SubSlice[1].Test = ""
-
- errs = validate.StructFiltered(tPartial, p1)
- Equal(t, errs, nil)
-
- errs = validate.StructFiltered(tPartial, p2)
- NotEqual(t, errs, nil)
- Equal(t, len(errs.(ValidationErrors)), 1)
- AssertError(t, errs, "TestPartial.SubSlice[0].Test", "TestPartial.SubSlice[0].Test", "Test", "Test", "required")
-
- // reset struct in slice, and unset struct in slice in unset posistion
- tPartial.SubSlice[0].Test = "Required"
-
- // these will pass as the unset item is NOT tested
- errs = validate.StructFiltered(tPartial, p1)
- Equal(t, errs, nil)
-
- errs = validate.StructFiltered(tPartial, p2)
- Equal(t, errs, nil)
-
- tPartial.SubSlice[1].Test = "Required"
- tPartial.Anonymous.SubAnonStruct[0].Test = ""
-
- // these will pass as the unset item is NOT tested
- errs = validate.StructFiltered(tPartial, p1)
- Equal(t, errs, nil)
-
- errs = validate.StructFiltered(tPartial, p2)
- Equal(t, errs, nil)
-
- dt := time.Now()
- err := validate.StructFiltered(&dt, func(ns []byte) bool { return true })
- NotEqual(t, err, nil)
- Equal(t, err.Error(), "validator: (nil *time.Time)")
-}
-
-func TestRequiredPtr(t *testing.T) {
-
- type Test struct {
- Bool *bool `validate:"required"`
- }
-
- validate := New()
-
- f := false
-
- test := Test{
- Bool: &f,
- }
-
- err := validate.Struct(test)
- Equal(t, err, nil)
-
- tr := true
-
- test.Bool = &tr
-
- err = validate.Struct(test)
- Equal(t, err, nil)
-
- test.Bool = nil
-
- err = validate.Struct(test)
- NotEqual(t, err, nil)
-
- errs, ok := err.(ValidationErrors)
- Equal(t, ok, true)
- Equal(t, len(errs), 1)
- AssertError(t, errs, "Test.Bool", "Test.Bool", "Bool", "Bool", "required")
-
- type Test2 struct {
- Bool bool `validate:"required"`
- }
-
- var test2 Test2
-
- err = validate.Struct(test2)
- NotEqual(t, err, nil)
-
- errs, ok = err.(ValidationErrors)
- Equal(t, ok, true)
- Equal(t, len(errs), 1)
- AssertError(t, errs, "Test2.Bool", "Test2.Bool", "Bool", "Bool", "required")
-
- test2.Bool = true
-
- err = validate.Struct(test2)
- Equal(t, err, nil)
-
- type Test3 struct {
- Arr []string `validate:"required"`
- }
-
- var test3 Test3
-
- err = validate.Struct(test3)
- NotEqual(t, err, nil)
-
- errs, ok = err.(ValidationErrors)
- Equal(t, ok, true)
- Equal(t, len(errs), 1)
- AssertError(t, errs, "Test3.Arr", "Test3.Arr", "Arr", "Arr", "required")
-
- test3.Arr = make([]string, 0)
-
- err = validate.Struct(test3)
- Equal(t, err, nil)
-
- type Test4 struct {
- Arr *[]string `validate:"required"` // I know I know pointer to array, just making sure validation works as expected...
- }
-
- var test4 Test4
-
- err = validate.Struct(test4)
- NotEqual(t, err, nil)
-
- errs, ok = err.(ValidationErrors)
- Equal(t, ok, true)
- Equal(t, len(errs), 1)
- AssertError(t, errs, "Test4.Arr", "Test4.Arr", "Arr", "Arr", "required")
-
- arr := make([]string, 0)
- test4.Arr = &arr
-
- err = validate.Struct(test4)
- Equal(t, err, nil)
-}
-
-func TestAlphaUnicodeValidation(t *testing.T) {
- tests := []struct {
- param string
- expected bool
- }{
- {"", false},
- {"abc", true},
- {"this is a test string", false},
- {"这是一个测试字符串", true},
- {"123", false},
- {"<>@;.-=", false},
- {"ひらがな・カタカナ、.漢字", false},
- {"あいうえおfoobar", true},
- {"test@example.com", false},
- {"1234abcDE", false},
- {"カタカナ", true},
- }
-
- validate := New()
-
- for i, test := range tests {
-
- errs := validate.Var(test.param, "alphaunicode")
-
- if test.expected {
- if !IsEqual(errs, nil) {
- t.Fatalf("Index: %d Alpha Unicode failed Error: %s", i, errs)
- }
- } else {
- if IsEqual(errs, nil) {
- t.Fatalf("Index: %d Alpha Unicode failed Error: %s", i, errs)
- } else {
- val := getError(errs, "", "")
- if val.Tag() != "alphaunicode" {
- t.Fatalf("Index: %d Alpha Unicode failed Error: %s", i, errs)
- }
- }
- }
- }
-}
-
-func TestAlphanumericUnicodeValidation(t *testing.T) {
-
- tests := []struct {
- param string
- expected bool
- }{
- {"", false},
- {"abc", true},
- {"this is a test string", false},
- {"这是一个测试字符串", true},
- {"\u0031\u0032\u0033", true}, // unicode 5
- {"123", true},
- {"<>@;.-=", false},
- {"ひらがな・カタカナ、.漢字", false},
- {"あいうえおfoobar", true},
- {"test@example.com", false},
- {"1234abcDE", true},
- {"カタカナ", true},
- }
-
- validate := New()
-
- for i, test := range tests {
-
- errs := validate.Var(test.param, "alphanumunicode")
-
- if test.expected {
- if !IsEqual(errs, nil) {
- t.Fatalf("Index: %d Alphanum Unicode failed Error: %s", i, errs)
- }
- } else {
- if IsEqual(errs, nil) {
- t.Fatalf("Index: %d Alphanum Unicode failed Error: %s", i, errs)
- } else {
- val := getError(errs, "", "")
- if val.Tag() != "alphanumunicode" {
- t.Fatalf("Index: %d Alphanum Unicode failed Error: %s", i, errs)
- }
- }
- }
- }
-}
-
-func TestArrayStructNamespace(t *testing.T) {
-
- validate := New()
- validate.RegisterTagNameFunc(func(fld reflect.StructField) string {
- name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0]
-
- if name == "-" {
- return ""
- }
-
- return name
- })
-
- type child struct {
- Name string `json:"name" validate:"required"`
- }
- var input struct {
- Children []child `json:"children" validate:"required,gt=0,dive"`
- }
- input.Children = []child{{"ok"}, {""}}
-
- errs := validate.Struct(input)
- NotEqual(t, errs, nil)
-
- ve := errs.(ValidationErrors)
- Equal(t, len(ve), 1)
- AssertError(t, errs, "children[1].name", "Children[1].Name", "name", "Name", "required")
-}
-
-func TestMapStructNamespace(t *testing.T) {
-
- validate := New()
- validate.RegisterTagNameFunc(func(fld reflect.StructField) string {
- name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0]
-
- if name == "-" {
- return ""
- }
-
- return name
- })
-
- type child struct {
- Name string `json:"name" validate:"required"`
- }
- var input struct {
- Children map[int]child `json:"children" validate:"required,gt=0,dive"`
- }
- input.Children = map[int]child{
- 0: {Name: "ok"},
- 1: {Name: ""},
- }
-
- errs := validate.Struct(input)
- NotEqual(t, errs, nil)
-
- ve := errs.(ValidationErrors)
- Equal(t, len(ve), 1)
- AssertError(t, errs, "children[1].name", "Children[1].Name", "name", "Name", "required")
-}
-
-func TestFieldLevelName(t *testing.T) {
- type Test struct {
- String string `validate:"custom1" json:"json1"`
- Array []string `validate:"dive,custom2" json:"json2"`
- Map map[string]string `validate:"dive,custom3" json:"json3"`
- Array2 []string `validate:"custom4" json:"json4"`
- Map2 map[string]string `validate:"custom5" json:"json5"`
- }
-
- var res1, res2, res3, res4, res5, alt1, alt2, alt3, alt4, alt5 string
- validate := New()
- validate.RegisterTagNameFunc(func(fld reflect.StructField) string {
- name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0]
-
- if name == "-" {
- return ""
- }
-
- return name
- })
- validate.RegisterValidation("custom1", func(fl FieldLevel) bool {
- res1 = fl.FieldName()
- alt1 = fl.StructFieldName()
- return true
- })
- validate.RegisterValidation("custom2", func(fl FieldLevel) bool {
- res2 = fl.FieldName()
- alt2 = fl.StructFieldName()
- return true
- })
- validate.RegisterValidation("custom3", func(fl FieldLevel) bool {
- res3 = fl.FieldName()
- alt3 = fl.StructFieldName()
- return true
- })
- validate.RegisterValidation("custom4", func(fl FieldLevel) bool {
- res4 = fl.FieldName()
- alt4 = fl.StructFieldName()
- return true
- })
- validate.RegisterValidation("custom5", func(fl FieldLevel) bool {
- res5 = fl.FieldName()
- alt5 = fl.StructFieldName()
- return true
- })
-
- test := Test{
- String: "test",
- Array: []string{"1"},
- Map: map[string]string{"test": "test"},
- }
-
- errs := validate.Struct(test)
- Equal(t, errs, nil)
- Equal(t, res1, "json1")
- Equal(t, alt1, "String")
- Equal(t, res2, "json2[0]")
- Equal(t, alt2, "Array[0]")
- Equal(t, res3, "json3[test]")
- Equal(t, alt3, "Map[test]")
- Equal(t, res4, "json4")
- Equal(t, alt4, "Array2")
- Equal(t, res5, "json5")
- Equal(t, alt5, "Map2")
-}
-
-func TestValidateStructRegisterCtx(t *testing.T) {
-
- var ctxVal string
-
- fnCtx := func(ctx context.Context, fl FieldLevel) bool {
- ctxVal = ctx.Value(&ctxVal).(string)
- return true
- }
-
- var ctxSlVal string
- slFn := func(ctx context.Context, sl StructLevel) {
- ctxSlVal = ctx.Value(&ctxSlVal).(string)
- }
-
- type Test struct {
- Field string `validate:"val"`
- }
-
- var tst Test
-
- validate := New()
- validate.RegisterValidationCtx("val", fnCtx)
- validate.RegisterStructValidationCtx(slFn, Test{})
-
- ctx := context.WithValue(context.Background(), &ctxVal, "testval")
- ctx = context.WithValue(ctx, &ctxSlVal, "slVal")
- errs := validate.StructCtx(ctx, tst)
- Equal(t, errs, nil)
- Equal(t, ctxVal, "testval")
- Equal(t, ctxSlVal, "slVal")
-}
-
-func TestHostnameRFC952Validation(t *testing.T) {
- tests := []struct {
- param string
- expected bool
- }{
- {"test.example.com", true},
- {"example.com", true},
- {"example24.com", true},
- {"test.example24.com", true},
- {"test24.example24.com", true},
- {"example", true},
- {"1.foo.com", false},
- {"test.example.com.", false},
- {"example.com.", false},
- {"example24.com.", false},
- {"test.example24.com.", false},
- {"test24.example24.com.", false},
- {"example.", false},
- {"192.168.0.1", false},
- {"email@example.com", false},
- {"2001:cdba:0000:0000:0000:0000:3257:9652", false},
- {"2001:cdba:0:0:0:0:3257:9652", false},
- {"2001:cdba::3257:9652", false},
- }
-
- validate := New()
-
- for i, test := range tests {
-
- errs := validate.Var(test.param, "hostname")
-
- if test.expected {
- if !IsEqual(errs, nil) {
- t.Fatalf("Index: %d hostname failed Error: %v", i, errs)
- }
- } else {
- if IsEqual(errs, nil) {
- t.Fatalf("Index: %d hostname failed Error: %v", i, errs)
- } else {
- val := getError(errs, "", "")
- if val.Tag() != "hostname" {
- t.Fatalf("Index: %d hostname failed Error: %v", i, errs)
- }
- }
- }
- }
-}
-
-func TestHostnameRFC1123Validation(t *testing.T) {
- tests := []struct {
- param string
- expected bool
- }{
- {"test.example.com", true},
- {"example.com", true},
- {"example24.com", true},
- {"test.example24.com", true},
- {"test24.example24.com", true},
- {"example", true},
- {"1.foo.com", true},
- {"test.example.com.", false},
- {"example.com.", false},
- {"example24.com.", false},
- {"test.example24.com.", false},
- {"test24.example24.com.", false},
- {"example.", false},
- {"192.168.0.1", true},
- {"email@example.com", false},
- {"2001:cdba:0000:0000:0000:0000:3257:9652", false},
- {"2001:cdba:0:0:0:0:3257:9652", false},
- {"2001:cdba::3257:9652", false},
- }
-
- validate := New()
-
- for i, test := range tests {
-
- errs := validate.Var(test.param, "hostname_rfc1123")
-
- if test.expected {
- if !IsEqual(errs, nil) {
- t.Fatalf("Index: %d hostname failed Error: %v", i, errs)
- }
- } else {
- if IsEqual(errs, nil) {
- t.Fatalf("Index: %d hostname failed Error: %v", i, errs)
- } else {
- val := getError(errs, "", "")
- if val.Tag() != "hostname_rfc1123" {
- t.Fatalf("Index: %d hostname failed Error: %v", i, errs)
- }
- }
- }
- }
-}
-
-func TestHostnameRFC1123AliasValidation(t *testing.T) {
- tests := []struct {
- param string
- expected bool
- }{
- {"test.example.com", true},
- {"example.com", true},
- {"example24.com", true},
- {"test.example24.com", true},
- {"test24.example24.com", true},
- {"example", true},
- {"1.foo.com", true},
- {"test.example.com.", false},
- {"example.com.", false},
- {"example24.com.", false},
- {"test.example24.com.", false},
- {"test24.example24.com.", false},
- {"example.", false},
- {"192.168.0.1", true},
- {"email@example.com", false},
- {"2001:cdba:0000:0000:0000:0000:3257:9652", false},
- {"2001:cdba:0:0:0:0:3257:9652", false},
- {"2001:cdba::3257:9652", false},
- }
-
- validate := New()
- validate.RegisterAlias("hostname", "hostname_rfc1123")
-
- for i, test := range tests {
-
- errs := validate.Var(test.param, "hostname")
-
- if test.expected {
- if !IsEqual(errs, nil) {
- t.Fatalf("Index: %d hostname failed Error: %v", i, errs)
- }
- } else {
- if IsEqual(errs, nil) {
- t.Fatalf("Index: %d hostname failed Error: %v", i, errs)
- } else {
- val := getError(errs, "", "")
- if val.Tag() != "hostname" {
- t.Fatalf("Index: %d hostname failed Error: %v", i, errs)
- }
- }
- }
- }
-}
-
-func TestFQDNValidation(t *testing.T) {
- tests := []struct {
- param string
- expected bool
- }{
- {"test.example.com", true},
- {"example.com", true},
- {"example24.com", true},
- {"test.example24.com", true},
- {"test24.example24.com", true},
- {"test.example.com.", true},
- {"example.com.", true},
- {"example24.com.", true},
- {"test.example24.com.", true},
- {"test24.example24.com.", true},
- {"test24.example24.com..", false},
- {"example", false},
- {"192.168.0.1", false},
- {"email@example.com", false},
- {"2001:cdba:0000:0000:0000:0000:3257:9652", false},
- {"2001:cdba:0:0:0:0:3257:9652", false},
- {"2001:cdba::3257:9652", false},
- {"", false},
- }
-
- validate := New()
-
- for i, test := range tests {
-
- errs := validate.Var(test.param, "fqdn")
-
- if test.expected {
- if !IsEqual(errs, nil) {
- t.Fatalf("Index: %d fqdn failed Error: %v", i, errs)
- }
- } else {
- if IsEqual(errs, nil) {
- t.Fatalf("Index: %d fqdn failed Error: %v", i, errs)
- } else {
- val := getError(errs, "", "")
- if val.Tag() != "fqdn" {
- t.Fatalf("Index: %d fqdn failed Error: %v", i, errs)
- }
- }
- }
- }
-}
-
-func TestIsDefault(t *testing.T) {
-
- validate := New()
-
- type Inner struct {
- String string `validate:"isdefault"`
- }
- type Test struct {
- String string `validate:"isdefault"`
- Inner *Inner `validate:"isdefault"`
- }
-
- var tt Test
-
- errs := validate.Struct(tt)
- Equal(t, errs, nil)
-
- tt.Inner = &Inner{String: ""}
- errs = validate.Struct(tt)
- NotEqual(t, errs, nil)
-
- fe := errs.(ValidationErrors)[0]
- Equal(t, fe.Field(), "Inner")
- Equal(t, fe.Namespace(), "Test.Inner")
- Equal(t, fe.Tag(), "isdefault")
-
- validate.RegisterTagNameFunc(func(fld reflect.StructField) string {
- name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0]
-
- if name == "-" {
- return ""
- }
-
- return name
- })
-
- type Inner2 struct {
- String string `validate:"isdefault"`
- }
-
- type Test2 struct {
- Inner Inner2 `validate:"isdefault" json:"inner"`
- }
-
- var t2 Test2
- errs = validate.Struct(t2)
- Equal(t, errs, nil)
-
- t2.Inner.String = "Changed"
- errs = validate.Struct(t2)
- NotEqual(t, errs, nil)
-
- fe = errs.(ValidationErrors)[0]
- Equal(t, fe.Field(), "inner")
- Equal(t, fe.Namespace(), "Test2.inner")
- Equal(t, fe.Tag(), "isdefault")
-}
-
-func TestUniqueValidation(t *testing.T) {
- tests := []struct {
- param interface{}
- expected bool
- }{
- {[]string{"a", "b"}, true},
- {[]int{1, 2}, true},
- {[]float64{1, 2}, true},
- {[]interface{}{"a", "b"}, true},
- {[]interface{}{"a", 1}, true},
- {[]float64{1, 1}, false},
- {[]int{1, 1}, false},
- {[]string{"a", "a"}, false},
- {[]interface{}{"a", "a"}, false},
- {[]interface{}{"a", 1, "b", 1}, false},
- }
-
- validate := New()
-
- for i, test := range tests {
-
- errs := validate.Var(test.param, "unique")
-
- if test.expected {
- if !IsEqual(errs, nil) {
- t.Fatalf("Index: %d unique failed Error: %v", i, errs)
- }
- } else {
- if IsEqual(errs, nil) {
- t.Fatalf("Index: %d unique failed Error: %v", i, errs)
- } else {
- val := getError(errs, "", "")
- if val.Tag() != "unique" {
- t.Fatalf("Index: %d unique failed Error: %v", i, errs)
- }
- }
- }
- }
- PanicMatches(t, func() { validate.Var(1.0, "unique") }, "Bad field type float64")
-}
-
-func TestKeys(t *testing.T) {
-
- type Test struct {
- Test1 map[string]string `validate:"gt=0,dive,keys,eq=testkey,endkeys,eq=testval" json:"test1"`
- Test2 map[int]int `validate:"gt=0,dive,keys,eq=3,endkeys,eq=4" json:"test2"`
- Test3 map[int]int `validate:"gt=0,dive,keys,eq=3,endkeys" json:"test3"`
- }
-
- var tst Test
-
- validate := New()
- err := validate.Struct(tst)
- NotEqual(t, err, nil)
- Equal(t, len(err.(ValidationErrors)), 3)
- AssertError(t, err.(ValidationErrors), "Test.Test1", "Test.Test1", "Test1", "Test1", "gt")
- AssertError(t, err.(ValidationErrors), "Test.Test2", "Test.Test2", "Test2", "Test2", "gt")
- AssertError(t, err.(ValidationErrors), "Test.Test3", "Test.Test3", "Test3", "Test3", "gt")
-
- tst.Test1 = map[string]string{
- "testkey": "testval",
- }
-
- tst.Test2 = map[int]int{
- 3: 4,
- }
-
- tst.Test3 = map[int]int{
- 3: 4,
- }
-
- err = validate.Struct(tst)
- Equal(t, err, nil)
-
- tst.Test1["badtestkey"] = "badtestvalue"
- tst.Test2[10] = 11
-
- err = validate.Struct(tst)
- NotEqual(t, err, nil)
-
- errs := err.(ValidationErrors)
-
- Equal(t, len(errs), 4)
-
- AssertDeepError(t, errs, "Test.Test1[badtestkey]", "Test.Test1[badtestkey]", "Test1[badtestkey]", "Test1[badtestkey]", "eq", "eq")
- AssertDeepError(t, errs, "Test.Test1[badtestkey]", "Test.Test1[badtestkey]", "Test1[badtestkey]", "Test1[badtestkey]", "eq", "eq")
- AssertDeepError(t, errs, "Test.Test2[10]", "Test.Test2[10]", "Test2[10]", "Test2[10]", "eq", "eq")
- AssertDeepError(t, errs, "Test.Test2[10]", "Test.Test2[10]", "Test2[10]", "Test2[10]", "eq", "eq")
-
- type Test2 struct {
- NestedKeys map[[1]string]string `validate:"gt=0,dive,keys,dive,eq=innertestkey,endkeys,eq=outertestval"`
- }
-
- var tst2 Test2
-
- err = validate.Struct(tst2)
- NotEqual(t, err, nil)
- Equal(t, len(err.(ValidationErrors)), 1)
- AssertError(t, err.(ValidationErrors), "Test2.NestedKeys", "Test2.NestedKeys", "NestedKeys", "NestedKeys", "gt")
-
- tst2.NestedKeys = map[[1]string]string{
- [1]string{"innertestkey"}: "outertestval",
- }
-
- err = validate.Struct(tst2)
- Equal(t, err, nil)
-
- tst2.NestedKeys[[1]string{"badtestkey"}] = "badtestvalue"
-
- err = validate.Struct(tst2)
- NotEqual(t, err, nil)
-
- errs = err.(ValidationErrors)
-
- Equal(t, len(errs), 2)
- AssertDeepError(t, errs, "Test2.NestedKeys[[badtestkey]][0]", "Test2.NestedKeys[[badtestkey]][0]", "NestedKeys[[badtestkey]][0]", "NestedKeys[[badtestkey]][0]", "eq", "eq")
- AssertDeepError(t, errs, "Test2.NestedKeys[[badtestkey]]", "Test2.NestedKeys[[badtestkey]]", "NestedKeys[[badtestkey]]", "NestedKeys[[badtestkey]]", "eq", "eq")
-
- // test bad tag definitions
-
- PanicMatches(t, func() { validate.Var(map[string]string{"key": "val"}, "endkeys,dive,eq=val") }, "'endkeys' tag encountered without a corresponding 'keys' tag")
- PanicMatches(t, func() { validate.Var(1, "keys,eq=1,endkeys") }, "'keys' tag must be immediately preceeded by the 'dive' tag")
-
- // test custom tag name
- validate = New()
- validate.RegisterTagNameFunc(func(fld reflect.StructField) string {
- name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0]
-
- if name == "-" {
- return ""
- }
- return name
- })
-
- err = validate.Struct(tst)
- NotEqual(t, err, nil)
-
- errs = err.(ValidationErrors)
-
- Equal(t, len(errs), 4)
-
- AssertDeepError(t, errs, "Test.test1[badtestkey]", "Test.Test1[badtestkey]", "test1[badtestkey]", "Test1[badtestkey]", "eq", "eq")
- AssertDeepError(t, errs, "Test.test1[badtestkey]", "Test.Test1[badtestkey]", "test1[badtestkey]", "Test1[badtestkey]", "eq", "eq")
- AssertDeepError(t, errs, "Test.test2[10]", "Test.Test2[10]", "test2[10]", "Test2[10]", "eq", "eq")
- AssertDeepError(t, errs, "Test.test2[10]", "Test.Test2[10]", "test2[10]", "Test2[10]", "eq", "eq")
-}
-
-// Thanks @adrian-sgn specific test for your specific scenario
-func TestKeysCustomValidation(t *testing.T) {
-
- type LangCode string
- type Label map[LangCode]string
-
- type TestMapStructPtr struct {
- Label Label `validate:"dive,keys,lang_code,endkeys,required"`
- }
-
- validate := New()
- validate.RegisterValidation("lang_code", func(fl FieldLevel) bool {
- validLangCodes := map[LangCode]struct{}{
- "en": {},
- "es": {},
- "pt": {},
- }
-
- _, ok := validLangCodes[fl.Field().Interface().(LangCode)]
- return ok
- })
-
- label := Label{
- "en": "Good morning!",
- "pt": "",
- "es": "¡Buenos días!",
- "xx": "Bad key",
- "xxx": "",
- }
-
- err := validate.Struct(TestMapStructPtr{label})
- NotEqual(t, err, nil)
-
- errs := err.(ValidationErrors)
- Equal(t, len(errs), 4)
-
- AssertDeepError(t, errs, "TestMapStructPtr.Label[xx]", "TestMapStructPtr.Label[xx]", "Label[xx]", "Label[xx]", "lang_code", "lang_code")
- AssertDeepError(t, errs, "TestMapStructPtr.Label[pt]", "TestMapStructPtr.Label[pt]", "Label[pt]", "Label[pt]", "required", "required")
- AssertDeepError(t, errs, "TestMapStructPtr.Label[xxx]", "TestMapStructPtr.Label[xxx]", "Label[xxx]", "Label[xxx]", "lang_code", "lang_code")
- AssertDeepError(t, errs, "TestMapStructPtr.Label[xxx]", "TestMapStructPtr.Label[xxx]", "Label[xxx]", "Label[xxx]", "required", "required")
-
- // find specific error
-
- var e FieldError
- for _, e = range errs {
- if e.Namespace() == "TestMapStructPtr.Label[xxx]" {
- break
- }
- }
-
- Equal(t, e.Param(), "")
- Equal(t, e.Value().(LangCode), LangCode("xxx"))
-
- for _, e = range errs {
- if e.Namespace() == "TestMapStructPtr.Label[xxx]" && e.Tag() == "required" {
- break
- }
- }
-
- Equal(t, e.Param(), "")
- Equal(t, e.Value().(string), "")
-}
-
-func TestKeyOrs(t *testing.T) {
-
- type Test struct {
- Test1 map[string]string `validate:"gt=0,dive,keys,eq=testkey|eq=testkeyok,endkeys,eq=testval" json:"test1"`
- }
-
- var tst Test
-
- validate := New()
- err := validate.Struct(tst)
- NotEqual(t, err, nil)
- Equal(t, len(err.(ValidationErrors)), 1)
- AssertError(t, err.(ValidationErrors), "Test.Test1", "Test.Test1", "Test1", "Test1", "gt")
-
- tst.Test1 = map[string]string{
- "testkey": "testval",
- }
-
- err = validate.Struct(tst)
- Equal(t, err, nil)
-
- tst.Test1["badtestkey"] = "badtestval"
-
- err = validate.Struct(tst)
- NotEqual(t, err, nil)
-
- errs := err.(ValidationErrors)
-
- Equal(t, len(errs), 2)
-
- AssertDeepError(t, errs, "Test.Test1[badtestkey]", "Test.Test1[badtestkey]", "Test1[badtestkey]", "Test1[badtestkey]", "eq=testkey|eq=testkeyok", "eq=testkey|eq=testkeyok")
- AssertDeepError(t, errs, "Test.Test1[badtestkey]", "Test.Test1[badtestkey]", "Test1[badtestkey]", "Test1[badtestkey]", "eq", "eq")
-
- validate.RegisterAlias("okkey", "eq=testkey|eq=testkeyok")
-
- type Test2 struct {
- Test1 map[string]string `validate:"gt=0,dive,keys,okkey,endkeys,eq=testval" json:"test1"`
- }
-
- var tst2 Test2
-
- err = validate.Struct(tst2)
- NotEqual(t, err, nil)
- Equal(t, len(err.(ValidationErrors)), 1)
- AssertError(t, err.(ValidationErrors), "Test2.Test1", "Test2.Test1", "Test1", "Test1", "gt")
-
- tst2.Test1 = map[string]string{
- "testkey": "testval",
- }
-
- err = validate.Struct(tst2)
- Equal(t, err, nil)
-
- tst2.Test1["badtestkey"] = "badtestval"
-
- err = validate.Struct(tst2)
- NotEqual(t, err, nil)
-
- errs = err.(ValidationErrors)
-
- Equal(t, len(errs), 2)
-
- AssertDeepError(t, errs, "Test2.Test1[badtestkey]", "Test2.Test1[badtestkey]", "Test1[badtestkey]", "Test1[badtestkey]", "okkey", "eq=testkey|eq=testkeyok")
- AssertDeepError(t, errs, "Test2.Test1[badtestkey]", "Test2.Test1[badtestkey]", "Test1[badtestkey]", "Test1[badtestkey]", "eq", "eq")
-}
diff --git a/vendor/gopkg.in/yaml.v2/.travis.yml b/vendor/gopkg.in/yaml.v2/.travis.yml
deleted file mode 100644
index 004172a..0000000
--- a/vendor/gopkg.in/yaml.v2/.travis.yml
+++ /dev/null
@@ -1,9 +0,0 @@
-language: go
-
-go:
- - 1.4
- - 1.5
- - 1.6
- - tip
-
-go_import_path: gopkg.in/yaml.v2
diff --git a/vendor/gopkg.in/yaml.v2/README.md b/vendor/gopkg.in/yaml.v2/README.md
deleted file mode 100644
index 7a512d6..0000000
--- a/vendor/gopkg.in/yaml.v2/README.md
+++ /dev/null
@@ -1,133 +0,0 @@
-# YAML support for the Go language
-
-Introduction
-------------
-
-The yaml package enables Go programs to comfortably encode and decode YAML
-values. It was developed within [Canonical](https://www.canonical.com) as
-part of the [juju](https://juju.ubuntu.com) project, and is based on a
-pure Go port of the well-known [libyaml](http://pyyaml.org/wiki/LibYAML)
-C library to parse and generate YAML data quickly and reliably.
-
-Compatibility
--------------
-
-The yaml package supports most of YAML 1.1 and 1.2, including support for
-anchors, tags, map merging, etc. Multi-document unmarshalling is not yet
-implemented, and base-60 floats from YAML 1.1 are purposefully not
-supported since they're a poor design and are gone in YAML 1.2.
-
-Installation and usage
-----------------------
-
-The import path for the package is *gopkg.in/yaml.v2*.
-
-To install it, run:
-
- go get gopkg.in/yaml.v2
-
-API documentation
------------------
-
-If opened in a browser, the import path itself leads to the API documentation:
-
- * [https://gopkg.in/yaml.v2](https://gopkg.in/yaml.v2)
-
-API stability
--------------
-
-The package API for yaml v2 will remain stable as described in [gopkg.in](https://gopkg.in).
-
-
-License
--------
-
-The yaml package is licensed under the Apache License 2.0. Please see the LICENSE file for details.
-
-
-Example
--------
-
-Some more examples can be found in the "examples" folder.
-
-```Go
-package main
-
-import (
- "fmt"
- "log"
-
- "gopkg.in/yaml.v2"
-)
-
-var data = `
-a: Easy!
-b:
- c: 2
- d: [3, 4]
-`
-
-type T struct {
- A string
- B struct {
- RenamedC int `yaml:"c"`
- D []int `yaml:",flow"`
- }
-}
-
-func main() {
- t := T{}
-
- err := yaml.Unmarshal([]byte(data), &t)
- if err != nil {
- log.Fatalf("error: %v", err)
- }
- fmt.Printf("--- t:\n%v\n\n", t)
-
- d, err := yaml.Marshal(&t)
- if err != nil {
- log.Fatalf("error: %v", err)
- }
- fmt.Printf("--- t dump:\n%s\n\n", string(d))
-
- m := make(map[interface{}]interface{})
-
- err = yaml.Unmarshal([]byte(data), &m)
- if err != nil {
- log.Fatalf("error: %v", err)
- }
- fmt.Printf("--- m:\n%v\n\n", m)
-
- d, err = yaml.Marshal(&m)
- if err != nil {
- log.Fatalf("error: %v", err)
- }
- fmt.Printf("--- m dump:\n%s\n\n", string(d))
-}
-```
-
-This example will generate the following output:
-
-```
---- t:
-{Easy! {2 [3 4]}}
-
---- t dump:
-a: Easy!
-b:
- c: 2
- d: [3, 4]
-
-
---- m:
-map[a:Easy! b:map[c:2 d:[3 4]]]
-
---- m dump:
-a: Easy!
-b:
- c: 2
- d:
- - 3
- - 4
-```
-
diff --git a/vendor/gopkg.in/yaml.v2/decode_test.go b/vendor/gopkg.in/yaml.v2/decode_test.go
deleted file mode 100644
index 713b1ee..0000000
--- a/vendor/gopkg.in/yaml.v2/decode_test.go
+++ /dev/null
@@ -1,1017 +0,0 @@
-package yaml_test
-
-import (
- "errors"
- . "gopkg.in/check.v1"
- "gopkg.in/yaml.v2"
- "math"
- "net"
- "reflect"
- "strings"
- "time"
-)
-
-var unmarshalIntTest = 123
-
-var unmarshalTests = []struct {
- data string
- value interface{}
-}{
- {
- "",
- &struct{}{},
- }, {
- "{}", &struct{}{},
- }, {
- "v: hi",
- map[string]string{"v": "hi"},
- }, {
- "v: hi", map[string]interface{}{"v": "hi"},
- }, {
- "v: true",
- map[string]string{"v": "true"},
- }, {
- "v: true",
- map[string]interface{}{"v": true},
- }, {
- "v: 10",
- map[string]interface{}{"v": 10},
- }, {
- "v: 0b10",
- map[string]interface{}{"v": 2},
- }, {
- "v: 0xA",
- map[string]interface{}{"v": 10},
- }, {
- "v: 4294967296",
- map[string]int64{"v": 4294967296},
- }, {
- "v: 0.1",
- map[string]interface{}{"v": 0.1},
- }, {
- "v: .1",
- map[string]interface{}{"v": 0.1},
- }, {
- "v: .Inf",
- map[string]interface{}{"v": math.Inf(+1)},
- }, {
- "v: -.Inf",
- map[string]interface{}{"v": math.Inf(-1)},
- }, {
- "v: -10",
- map[string]interface{}{"v": -10},
- }, {
- "v: -.1",
- map[string]interface{}{"v": -0.1},
- },
-
- // Simple values.
- {
- "123",
- &unmarshalIntTest,
- },
-
- // Floats from spec
- {
- "canonical: 6.8523e+5",
- map[string]interface{}{"canonical": 6.8523e+5},
- }, {
- "expo: 685.230_15e+03",
- map[string]interface{}{"expo": 685.23015e+03},
- }, {
- "fixed: 685_230.15",
- map[string]interface{}{"fixed": 685230.15},
- }, {
- "neginf: -.inf",
- map[string]interface{}{"neginf": math.Inf(-1)},
- }, {
- "fixed: 685_230.15",
- map[string]float64{"fixed": 685230.15},
- },
- //{"sexa: 190:20:30.15", map[string]interface{}{"sexa": 0}}, // Unsupported
- //{"notanum: .NaN", map[string]interface{}{"notanum": math.NaN()}}, // Equality of NaN fails.
-
- // Bools from spec
- {
- "canonical: y",
- map[string]interface{}{"canonical": true},
- }, {
- "answer: NO",
- map[string]interface{}{"answer": false},
- }, {
- "logical: True",
- map[string]interface{}{"logical": true},
- }, {
- "option: on",
- map[string]interface{}{"option": true},
- }, {
- "option: on",
- map[string]bool{"option": true},
- },
- // Ints from spec
- {
- "canonical: 685230",
- map[string]interface{}{"canonical": 685230},
- }, {
- "decimal: +685_230",
- map[string]interface{}{"decimal": 685230},
- }, {
- "octal: 02472256",
- map[string]interface{}{"octal": 685230},
- }, {
- "hexa: 0x_0A_74_AE",
- map[string]interface{}{"hexa": 685230},
- }, {
- "bin: 0b1010_0111_0100_1010_1110",
- map[string]interface{}{"bin": 685230},
- }, {
- "bin: -0b101010",
- map[string]interface{}{"bin": -42},
- }, {
- "decimal: +685_230",
- map[string]int{"decimal": 685230},
- },
-
- //{"sexa: 190:20:30", map[string]interface{}{"sexa": 0}}, // Unsupported
-
- // Nulls from spec
- {
- "empty:",
- map[string]interface{}{"empty": nil},
- }, {
- "canonical: ~",
- map[string]interface{}{"canonical": nil},
- }, {
- "english: null",
- map[string]interface{}{"english": nil},
- }, {
- "~: null key",
- map[interface{}]string{nil: "null key"},
- }, {
- "empty:",
- map[string]*bool{"empty": nil},
- },
-
- // Flow sequence
- {
- "seq: [A,B]",
- map[string]interface{}{"seq": []interface{}{"A", "B"}},
- }, {
- "seq: [A,B,C,]",
- map[string][]string{"seq": []string{"A", "B", "C"}},
- }, {
- "seq: [A,1,C]",
- map[string][]string{"seq": []string{"A", "1", "C"}},
- }, {
- "seq: [A,1,C]",
- map[string][]int{"seq": []int{1}},
- }, {
- "seq: [A,1,C]",
- map[string]interface{}{"seq": []interface{}{"A", 1, "C"}},
- },
- // Block sequence
- {
- "seq:\n - A\n - B",
- map[string]interface{}{"seq": []interface{}{"A", "B"}},
- }, {
- "seq:\n - A\n - B\n - C",
- map[string][]string{"seq": []string{"A", "B", "C"}},
- }, {
- "seq:\n - A\n - 1\n - C",
- map[string][]string{"seq": []string{"A", "1", "C"}},
- }, {
- "seq:\n - A\n - 1\n - C",
- map[string][]int{"seq": []int{1}},
- }, {
- "seq:\n - A\n - 1\n - C",
- map[string]interface{}{"seq": []interface{}{"A", 1, "C"}},
- },
-
- // Literal block scalar
- {
- "scalar: | # Comment\n\n literal\n\n \ttext\n\n",
- map[string]string{"scalar": "\nliteral\n\n\ttext\n"},
- },
-
- // Folded block scalar
- {
- "scalar: > # Comment\n\n folded\n line\n \n next\n line\n * one\n * two\n\n last\n line\n\n",
- map[string]string{"scalar": "\nfolded line\nnext line\n * one\n * two\n\nlast line\n"},
- },
-
- // Map inside interface with no type hints.
- {
- "a: {b: c}",
- map[interface{}]interface{}{"a": map[interface{}]interface{}{"b": "c"}},
- },
-
- // Structs and type conversions.
- {
- "hello: world",
- &struct{ Hello string }{"world"},
- }, {
- "a: {b: c}",
- &struct{ A struct{ B string } }{struct{ B string }{"c"}},
- }, {
- "a: {b: c}",
- &struct{ A *struct{ B string } }{&struct{ B string }{"c"}},
- }, {
- "a: {b: c}",
- &struct{ A map[string]string }{map[string]string{"b": "c"}},
- }, {
- "a: {b: c}",
- &struct{ A *map[string]string }{&map[string]string{"b": "c"}},
- }, {
- "a:",
- &struct{ A map[string]string }{},
- }, {
- "a: 1",
- &struct{ A int }{1},
- }, {
- "a: 1",
- &struct{ A float64 }{1},
- }, {
- "a: 1.0",
- &struct{ A int }{1},
- }, {
- "a: 1.0",
- &struct{ A uint }{1},
- }, {
- "a: [1, 2]",
- &struct{ A []int }{[]int{1, 2}},
- }, {
- "a: 1",
- &struct{ B int }{0},
- }, {
- "a: 1",
- &struct {
- B int "a"
- }{1},
- }, {
- "a: y",
- &struct{ A bool }{true},
- },
-
- // Some cross type conversions
- {
- "v: 42",
- map[string]uint{"v": 42},
- }, {
- "v: -42",
- map[string]uint{},
- }, {
- "v: 4294967296",
- map[string]uint64{"v": 4294967296},
- }, {
- "v: -4294967296",
- map[string]uint64{},
- },
-
- // int
- {
- "int_max: 2147483647",
- map[string]int{"int_max": math.MaxInt32},
- },
- {
- "int_min: -2147483648",
- map[string]int{"int_min": math.MinInt32},
- },
- {
- "int_overflow: 9223372036854775808", // math.MaxInt64 + 1
- map[string]int{},
- },
-
- // int64
- {
- "int64_max: 9223372036854775807",
- map[string]int64{"int64_max": math.MaxInt64},
- },
- {
- "int64_max_base2: 0b111111111111111111111111111111111111111111111111111111111111111",
- map[string]int64{"int64_max_base2": math.MaxInt64},
- },
- {
- "int64_min: -9223372036854775808",
- map[string]int64{"int64_min": math.MinInt64},
- },
- {
- "int64_neg_base2: -0b111111111111111111111111111111111111111111111111111111111111111",
- map[string]int64{"int64_neg_base2": -math.MaxInt64},
- },
- {
- "int64_overflow: 9223372036854775808", // math.MaxInt64 + 1
- map[string]int64{},
- },
-
- // uint
- {
- "uint_min: 0",
- map[string]uint{"uint_min": 0},
- },
- {
- "uint_max: 4294967295",
- map[string]uint{"uint_max": math.MaxUint32},
- },
- {
- "uint_underflow: -1",
- map[string]uint{},
- },
-
- // uint64
- {
- "uint64_min: 0",
- map[string]uint{"uint64_min": 0},
- },
- {
- "uint64_max: 18446744073709551615",
- map[string]uint64{"uint64_max": math.MaxUint64},
- },
- {
- "uint64_max_base2: 0b1111111111111111111111111111111111111111111111111111111111111111",
- map[string]uint64{"uint64_max_base2": math.MaxUint64},
- },
- {
- "uint64_maxint64: 9223372036854775807",
- map[string]uint64{"uint64_maxint64": math.MaxInt64},
- },
- {
- "uint64_underflow: -1",
- map[string]uint64{},
- },
-
- // float32
- {
- "float32_max: 3.40282346638528859811704183484516925440e+38",
- map[string]float32{"float32_max": math.MaxFloat32},
- },
- {
- "float32_nonzero: 1.401298464324817070923729583289916131280e-45",
- map[string]float32{"float32_nonzero": math.SmallestNonzeroFloat32},
- },
- {
- "float32_maxuint64: 18446744073709551615",
- map[string]float32{"float32_maxuint64": float32(math.MaxUint64)},
- },
- {
- "float32_maxuint64+1: 18446744073709551616",
- map[string]float32{"float32_maxuint64+1": float32(math.MaxUint64 + 1)},
- },
-
- // float64
- {
- "float64_max: 1.797693134862315708145274237317043567981e+308",
- map[string]float64{"float64_max": math.MaxFloat64},
- },
- {
- "float64_nonzero: 4.940656458412465441765687928682213723651e-324",
- map[string]float64{"float64_nonzero": math.SmallestNonzeroFloat64},
- },
- {
- "float64_maxuint64: 18446744073709551615",
- map[string]float64{"float64_maxuint64": float64(math.MaxUint64)},
- },
- {
- "float64_maxuint64+1: 18446744073709551616",
- map[string]float64{"float64_maxuint64+1": float64(math.MaxUint64 + 1)},
- },
-
- // Overflow cases.
- {
- "v: 4294967297",
- map[string]int32{},
- }, {
- "v: 128",
- map[string]int8{},
- },
-
- // Quoted values.
- {
- "'1': '\"2\"'",
- map[interface{}]interface{}{"1": "\"2\""},
- }, {
- "v:\n- A\n- 'B\n\n C'\n",
- map[string][]string{"v": []string{"A", "B\nC"}},
- },
-
- // Explicit tags.
- {
- "v: !!float '1.1'",
- map[string]interface{}{"v": 1.1},
- }, {
- "v: !!null ''",
- map[string]interface{}{"v": nil},
- }, {
- "%TAG !y! tag:yaml.org,2002:\n---\nv: !y!int '1'",
- map[string]interface{}{"v": 1},
- },
-
- // Non-specific tag (Issue #75)
- {
- "v: ! test",
- map[string]interface{}{"v": "test"},
- },
-
- // Anchors and aliases.
- {
- "a: &x 1\nb: &y 2\nc: *x\nd: *y\n",
- &struct{ A, B, C, D int }{1, 2, 1, 2},
- }, {
- "a: &a {c: 1}\nb: *a",
- &struct {
- A, B struct {
- C int
- }
- }{struct{ C int }{1}, struct{ C int }{1}},
- }, {
- "a: &a [1, 2]\nb: *a",
- &struct{ B []int }{[]int{1, 2}},
- }, {
- "b: *a\na: &a {c: 1}",
- &struct {
- A, B struct {
- C int
- }
- }{struct{ C int }{1}, struct{ C int }{1}},
- },
-
- // Bug #1133337
- {
- "foo: ''",
- map[string]*string{"foo": new(string)},
- }, {
- "foo: null",
- map[string]string{"foo": ""},
- }, {
- "foo: null",
- map[string]interface{}{"foo": nil},
- },
-
- // Ignored field
- {
- "a: 1\nb: 2\n",
- &struct {
- A int
- B int "-"
- }{1, 0},
- },
-
- // Bug #1191981
- {
- "" +
- "%YAML 1.1\n" +
- "--- !!str\n" +
- `"Generic line break (no glyph)\n\` + "\n" +
- ` Generic line break (glyphed)\n\` + "\n" +
- ` Line separator\u2028\` + "\n" +
- ` Paragraph separator\u2029"` + "\n",
- "" +
- "Generic line break (no glyph)\n" +
- "Generic line break (glyphed)\n" +
- "Line separator\u2028Paragraph separator\u2029",
- },
-
- // Struct inlining
- {
- "a: 1\nb: 2\nc: 3\n",
- &struct {
- A int
- C inlineB `yaml:",inline"`
- }{1, inlineB{2, inlineC{3}}},
- },
-
- // Map inlining
- {
- "a: 1\nb: 2\nc: 3\n",
- &struct {
- A int
- C map[string]int `yaml:",inline"`
- }{1, map[string]int{"b": 2, "c": 3}},
- },
-
- // bug 1243827
- {
- "a: -b_c",
- map[string]interface{}{"a": "-b_c"},
- },
- {
- "a: +b_c",
- map[string]interface{}{"a": "+b_c"},
- },
- {
- "a: 50cent_of_dollar",
- map[string]interface{}{"a": "50cent_of_dollar"},
- },
-
- // Duration
- {
- "a: 3s",
- map[string]time.Duration{"a": 3 * time.Second},
- },
-
- // Issue #24.
- {
- "a: <foo>",
- map[string]string{"a": "<foo>"},
- },
-
- // Base 60 floats are obsolete and unsupported.
- {
- "a: 1:1\n",
- map[string]string{"a": "1:1"},
- },
-
- // Binary data.
- {
- "a: !!binary gIGC\n",
- map[string]string{"a": "\x80\x81\x82"},
- }, {
- "a: !!binary |\n " + strings.Repeat("kJCQ", 17) + "kJ\n CQ\n",
- map[string]string{"a": strings.Repeat("\x90", 54)},
- }, {
- "a: !!binary |\n " + strings.Repeat("A", 70) + "\n ==\n",
- map[string]string{"a": strings.Repeat("\x00", 52)},
- },
-
- // Ordered maps.
- {
- "{b: 2, a: 1, d: 4, c: 3, sub: {e: 5}}",
- &yaml.MapSlice{{"b", 2}, {"a", 1}, {"d", 4}, {"c", 3}, {"sub", yaml.MapSlice{{"e", 5}}}},
- },
-
- // Issue #39.
- {
- "a:\n b:\n c: d\n",
- map[string]struct{ B interface{} }{"a": {map[interface{}]interface{}{"c": "d"}}},
- },
-
- // Custom map type.
- {
- "a: {b: c}",
- M{"a": M{"b": "c"}},
- },
-
- // Support encoding.TextUnmarshaler.
- {
- "a: 1.2.3.4\n",
- map[string]net.IP{"a": net.IPv4(1, 2, 3, 4)},
- },
- {
- "a: 2015-02-24T18:19:39Z\n",
- map[string]time.Time{"a": time.Unix(1424801979, 0).In(time.UTC)},
- },
-
- // Encode empty lists as zero-length slices.
- {
- "a: []",
- &struct{ A []int }{[]int{}},
- },
-
- // UTF-16-LE
- {
- "\xff\xfe\xf1\x00o\x00\xf1\x00o\x00:\x00 \x00v\x00e\x00r\x00y\x00 \x00y\x00e\x00s\x00\n\x00",
- M{"ñoño": "very yes"},
- },
- // UTF-16-LE with surrogate.
- {
- "\xff\xfe\xf1\x00o\x00\xf1\x00o\x00:\x00 \x00v\x00e\x00r\x00y\x00 \x00y\x00e\x00s\x00 \x00=\xd8\xd4\xdf\n\x00",
- M{"ñoño": "very yes 🟔"},
- },
-
- // UTF-16-BE
- {
- "\xfe\xff\x00\xf1\x00o\x00\xf1\x00o\x00:\x00 \x00v\x00e\x00r\x00y\x00 \x00y\x00e\x00s\x00\n",
- M{"ñoño": "very yes"},
- },
- // UTF-16-BE with surrogate.
- {
- "\xfe\xff\x00\xf1\x00o\x00\xf1\x00o\x00:\x00 \x00v\x00e\x00r\x00y\x00 \x00y\x00e\x00s\x00 \xd8=\xdf\xd4\x00\n",
- M{"ñoño": "very yes 🟔"},
- },
-
- // YAML Float regex shouldn't match this
- {
- "a: 123456e1\n",
- M{"a": "123456e1"},
- }, {
- "a: 123456E1\n",
- M{"a": "123456E1"},
- },
-}
-
-type M map[interface{}]interface{}
-
-type inlineB struct {
- B int
- inlineC `yaml:",inline"`
-}
-
-type inlineC struct {
- C int
-}
-
-func (s *S) TestUnmarshal(c *C) {
- for i, item := range unmarshalTests {
- c.Logf("test %d: %q", i, item.data)
- t := reflect.ValueOf(item.value).Type()
- var value interface{}
- switch t.Kind() {
- case reflect.Map:
- value = reflect.MakeMap(t).Interface()
- case reflect.String:
- value = reflect.New(t).Interface()
- case reflect.Ptr:
- value = reflect.New(t.Elem()).Interface()
- default:
- c.Fatalf("missing case for %s", t)
- }
- err := yaml.Unmarshal([]byte(item.data), value)
- if _, ok := err.(*yaml.TypeError); !ok {
- c.Assert(err, IsNil)
- }
- if t.Kind() == reflect.String {
- c.Assert(*value.(*string), Equals, item.value)
- } else {
- c.Assert(value, DeepEquals, item.value)
- }
- }
-}
-
-func (s *S) TestUnmarshalNaN(c *C) {
- value := map[string]interface{}{}
- err := yaml.Unmarshal([]byte("notanum: .NaN"), &value)
- c.Assert(err, IsNil)
- c.Assert(math.IsNaN(value["notanum"].(float64)), Equals, true)
-}
-
-var unmarshalErrorTests = []struct {
- data, error string
-}{
- {"v: !!float 'error'", "yaml: cannot decode !!str `error` as a !!float"},
- {"v: [A,", "yaml: line 1: did not find expected node content"},
- {"v:\n- [A,", "yaml: line 2: did not find expected node content"},
- {"a: *b\n", "yaml: unknown anchor 'b' referenced"},
- {"a: &a\n b: *a\n", "yaml: anchor 'a' value contains itself"},
- {"value: -", "yaml: block sequence entries are not allowed in this context"},
- {"a: !!binary ==", "yaml: !!binary value contains invalid base64 data"},
- {"{[.]}", `yaml: invalid map key: \[\]interface \{\}\{"\."\}`},
- {"{{.}}", `yaml: invalid map key: map\[interface\ \{\}\]interface \{\}\{".":interface \{\}\(nil\)\}`},
- {"%TAG !%79! tag:yaml.org,2002:\n---\nv: !%79!int '1'", "yaml: did not find expected whitespace"},
-}
-
-func (s *S) TestUnmarshalErrors(c *C) {
- for _, item := range unmarshalErrorTests {
- var value interface{}
- err := yaml.Unmarshal([]byte(item.data), &value)
- c.Assert(err, ErrorMatches, item.error, Commentf("Partial unmarshal: %#v", value))
- }
-}
-
-var unmarshalerTests = []struct {
- data, tag string
- value interface{}
-}{
- {"_: {hi: there}", "!!map", map[interface{}]interface{}{"hi": "there"}},
- {"_: [1,A]", "!!seq", []interface{}{1, "A"}},
- {"_: 10", "!!int", 10},
- {"_: null", "!!null", nil},
- {`_: BAR!`, "!!str", "BAR!"},
- {`_: "BAR!"`, "!!str", "BAR!"},
- {"_: !!foo 'BAR!'", "!!foo", "BAR!"},
- {`_: ""`, "!!str", ""},
-}
-
-var unmarshalerResult = map[int]error{}
-
-type unmarshalerType struct {
- value interface{}
-}
-
-func (o *unmarshalerType) UnmarshalYAML(unmarshal func(v interface{}) error) error {
- if err := unmarshal(&o.value); err != nil {
- return err
- }
- if i, ok := o.value.(int); ok {
- if result, ok := unmarshalerResult[i]; ok {
- return result
- }
- }
- return nil
-}
-
-type unmarshalerPointer struct {
- Field *unmarshalerType "_"
-}
-
-type unmarshalerValue struct {
- Field unmarshalerType "_"
-}
-
-func (s *S) TestUnmarshalerPointerField(c *C) {
- for _, item := range unmarshalerTests {
- obj := &unmarshalerPointer{}
- err := yaml.Unmarshal([]byte(item.data), obj)
- c.Assert(err, IsNil)
- if item.value == nil {
- c.Assert(obj.Field, IsNil)
- } else {
- c.Assert(obj.Field, NotNil, Commentf("Pointer not initialized (%#v)", item.value))
- c.Assert(obj.Field.value, DeepEquals, item.value)
- }
- }
-}
-
-func (s *S) TestUnmarshalerValueField(c *C) {
- for _, item := range unmarshalerTests {
- obj := &unmarshalerValue{}
- err := yaml.Unmarshal([]byte(item.data), obj)
- c.Assert(err, IsNil)
- c.Assert(obj.Field, NotNil, Commentf("Pointer not initialized (%#v)", item.value))
- c.Assert(obj.Field.value, DeepEquals, item.value)
- }
-}
-
-func (s *S) TestUnmarshalerWholeDocument(c *C) {
- obj := &unmarshalerType{}
- err := yaml.Unmarshal([]byte(unmarshalerTests[0].data), obj)
- c.Assert(err, IsNil)
- value, ok := obj.value.(map[interface{}]interface{})
- c.Assert(ok, Equals, true, Commentf("value: %#v", obj.value))
- c.Assert(value["_"], DeepEquals, unmarshalerTests[0].value)
-}
-
-func (s *S) TestUnmarshalerTypeError(c *C) {
- unmarshalerResult[2] = &yaml.TypeError{[]string{"foo"}}
- unmarshalerResult[4] = &yaml.TypeError{[]string{"bar"}}
- defer func() {
- delete(unmarshalerResult, 2)
- delete(unmarshalerResult, 4)
- }()
-
- type T struct {
- Before int
- After int
- M map[string]*unmarshalerType
- }
- var v T
- data := `{before: A, m: {abc: 1, def: 2, ghi: 3, jkl: 4}, after: B}`
- err := yaml.Unmarshal([]byte(data), &v)
- c.Assert(err, ErrorMatches, ""+
- "yaml: unmarshal errors:\n"+
- " line 1: cannot unmarshal !!str `A` into int\n"+
- " foo\n"+
- " bar\n"+
- " line 1: cannot unmarshal !!str `B` into int")
- c.Assert(v.M["abc"], NotNil)
- c.Assert(v.M["def"], IsNil)
- c.Assert(v.M["ghi"], NotNil)
- c.Assert(v.M["jkl"], IsNil)
-
- c.Assert(v.M["abc"].value, Equals, 1)
- c.Assert(v.M["ghi"].value, Equals, 3)
-}
-
-type proxyTypeError struct{}
-
-func (v *proxyTypeError) UnmarshalYAML(unmarshal func(interface{}) error) error {
- var s string
- var a int32
- var b int64
- if err := unmarshal(&s); err != nil {
- panic(err)
- }
- if s == "a" {
- if err := unmarshal(&b); err == nil {
- panic("should have failed")
- }
- return unmarshal(&a)
- }
- if err := unmarshal(&a); err == nil {
- panic("should have failed")
- }
- return unmarshal(&b)
-}
-
-func (s *S) TestUnmarshalerTypeErrorProxying(c *C) {
- type T struct {
- Before int
- After int
- M map[string]*proxyTypeError
- }
- var v T
- data := `{before: A, m: {abc: a, def: b}, after: B}`
- err := yaml.Unmarshal([]byte(data), &v)
- c.Assert(err, ErrorMatches, ""+
- "yaml: unmarshal errors:\n"+
- " line 1: cannot unmarshal !!str `A` into int\n"+
- " line 1: cannot unmarshal !!str `a` into int32\n"+
- " line 1: cannot unmarshal !!str `b` into int64\n"+
- " line 1: cannot unmarshal !!str `B` into int")
-}
-
-type failingUnmarshaler struct{}
-
-var failingErr = errors.New("failingErr")
-
-func (ft *failingUnmarshaler) UnmarshalYAML(unmarshal func(interface{}) error) error {
- return failingErr
-}
-
-func (s *S) TestUnmarshalerError(c *C) {
- err := yaml.Unmarshal([]byte("a: b"), &failingUnmarshaler{})
- c.Assert(err, Equals, failingErr)
-}
-
-type sliceUnmarshaler []int
-
-func (su *sliceUnmarshaler) UnmarshalYAML(unmarshal func(interface{}) error) error {
- var slice []int
- err := unmarshal(&slice)
- if err == nil {
- *su = slice
- return nil
- }
-
- var intVal int
- err = unmarshal(&intVal)
- if err == nil {
- *su = []int{intVal}
- return nil
- }
-
- return err
-}
-
-func (s *S) TestUnmarshalerRetry(c *C) {
- var su sliceUnmarshaler
- err := yaml.Unmarshal([]byte("[1, 2, 3]"), &su)
- c.Assert(err, IsNil)
- c.Assert(su, DeepEquals, sliceUnmarshaler([]int{1, 2, 3}))
-
- err = yaml.Unmarshal([]byte("1"), &su)
- c.Assert(err, IsNil)
- c.Assert(su, DeepEquals, sliceUnmarshaler([]int{1}))
-}
-
-// From http://yaml.org/type/merge.html
-var mergeTests = `
-anchors:
- list:
- - &CENTER { "x": 1, "y": 2 }
- - &LEFT { "x": 0, "y": 2 }
- - &BIG { "r": 10 }
- - &SMALL { "r": 1 }
-
-# All the following maps are equal:
-
-plain:
- # Explicit keys
- "x": 1
- "y": 2
- "r": 10
- label: center/big
-
-mergeOne:
- # Merge one map
- << : *CENTER
- "r": 10
- label: center/big
-
-mergeMultiple:
- # Merge multiple maps
- << : [ *CENTER, *BIG ]
- label: center/big
-
-override:
- # Override
- << : [ *BIG, *LEFT, *SMALL ]
- "x": 1
- label: center/big
-
-shortTag:
- # Explicit short merge tag
- !!merge "<<" : [ *CENTER, *BIG ]
- label: center/big
-
-longTag:
- # Explicit merge long tag
- !<tag:yaml.org,2002:merge> "<<" : [ *CENTER, *BIG ]
- label: center/big
-
-inlineMap:
- # Inlined map
- << : {"x": 1, "y": 2, "r": 10}
- label: center/big
-
-inlineSequenceMap:
- # Inlined map in sequence
- << : [ *CENTER, {"r": 10} ]
- label: center/big
-`
-
-func (s *S) TestMerge(c *C) {
- var want = map[interface{}]interface{}{
- "x": 1,
- "y": 2,
- "r": 10,
- "label": "center/big",
- }
-
- var m map[interface{}]interface{}
- err := yaml.Unmarshal([]byte(mergeTests), &m)
- c.Assert(err, IsNil)
- for name, test := range m {
- if name == "anchors" {
- continue
- }
- c.Assert(test, DeepEquals, want, Commentf("test %q failed", name))
- }
-}
-
-func (s *S) TestMergeStruct(c *C) {
- type Data struct {
- X, Y, R int
- Label string
- }
- want := Data{1, 2, 10, "center/big"}
-
- var m map[string]Data
- err := yaml.Unmarshal([]byte(mergeTests), &m)
- c.Assert(err, IsNil)
- for name, test := range m {
- if name == "anchors" {
- continue
- }
- c.Assert(test, Equals, want, Commentf("test %q failed", name))
- }
-}
-
-var unmarshalNullTests = []func() interface{}{
- func() interface{} { var v interface{}; v = "v"; return &v },
- func() interface{} { var s = "s"; return &s },
- func() interface{} { var s = "s"; sptr := &s; return &sptr },
- func() interface{} { var i = 1; return &i },
- func() interface{} { var i = 1; iptr := &i; return &iptr },
- func() interface{} { m := map[string]int{"s": 1}; return &m },
- func() interface{} { m := map[string]int{"s": 1}; return m },
-}
-
-func (s *S) TestUnmarshalNull(c *C) {
- for _, test := range unmarshalNullTests {
- item := test()
- zero := reflect.Zero(reflect.TypeOf(item).Elem()).Interface()
- err := yaml.Unmarshal([]byte("null"), item)
- c.Assert(err, IsNil)
- if reflect.TypeOf(item).Kind() == reflect.Map {
- c.Assert(reflect.ValueOf(item).Interface(), DeepEquals, reflect.MakeMap(reflect.TypeOf(item)).Interface())
- } else {
- c.Assert(reflect.ValueOf(item).Elem().Interface(), DeepEquals, zero)
- }
- }
-}
-
-func (s *S) TestUnmarshalSliceOnPreset(c *C) {
- // Issue #48.
- v := struct{ A []int }{[]int{1}}
- yaml.Unmarshal([]byte("a: [2]"), &v)
- c.Assert(v.A, DeepEquals, []int{2})
-}
-
-func (s *S) TestUnmarshalStrict(c *C) {
- v := struct{ A, B int }{}
-
- err := yaml.UnmarshalStrict([]byte("a: 1\nb: 2"), &v)
- c.Check(err, IsNil)
- err = yaml.Unmarshal([]byte("a: 1\nb: 2\nc: 3"), &v)
- c.Check(err, IsNil)
- err = yaml.UnmarshalStrict([]byte("a: 1\nb: 2\nc: 3"), &v)
- c.Check(err, ErrorMatches, "yaml: unmarshal errors:\n line 1: field c not found in struct struct { A int; B int }")
-}
-
-//var data []byte
-//func init() {
-// var err error
-// data, err = ioutil.ReadFile("/tmp/file.yaml")
-// if err != nil {
-// panic(err)
-// }
-//}
-//
-//func (s *S) BenchmarkUnmarshal(c *C) {
-// var err error
-// for i := 0; i < c.N; i++ {
-// var v map[string]interface{}
-// err = yaml.Unmarshal(data, &v)
-// }
-// if err != nil {
-// panic(err)
-// }
-//}
-//
-//func (s *S) BenchmarkMarshal(c *C) {
-// var v map[string]interface{}
-// yaml.Unmarshal(data, &v)
-// c.ResetTimer()
-// for i := 0; i < c.N; i++ {
-// yaml.Marshal(&v)
-// }
-//}
diff --git a/vendor/gopkg.in/yaml.v2/encode_test.go b/vendor/gopkg.in/yaml.v2/encode_test.go
deleted file mode 100644
index 84099bd..0000000
--- a/vendor/gopkg.in/yaml.v2/encode_test.go
+++ /dev/null
@@ -1,501 +0,0 @@
-package yaml_test
-
-import (
- "fmt"
- "math"
- "strconv"
- "strings"
- "time"
-
- . "gopkg.in/check.v1"
- "gopkg.in/yaml.v2"
- "net"
- "os"
-)
-
-var marshalIntTest = 123
-
-var marshalTests = []struct {
- value interface{}
- data string
-}{
- {
- nil,
- "null\n",
- }, {
- &struct{}{},
- "{}\n",
- }, {
- map[string]string{"v": "hi"},
- "v: hi\n",
- }, {
- map[string]interface{}{"v": "hi"},
- "v: hi\n",
- }, {
- map[string]string{"v": "true"},
- "v: \"true\"\n",
- }, {
- map[string]string{"v": "false"},
- "v: \"false\"\n",
- }, {
- map[string]interface{}{"v": true},
- "v: true\n",
- }, {
- map[string]interface{}{"v": false},
- "v: false\n",
- }, {
- map[string]interface{}{"v": 10},
- "v: 10\n",
- }, {
- map[string]interface{}{"v": -10},
- "v: -10\n",
- }, {
- map[string]uint{"v": 42},
- "v: 42\n",
- }, {
- map[string]interface{}{"v": int64(4294967296)},
- "v: 4294967296\n",
- }, {
- map[string]int64{"v": int64(4294967296)},
- "v: 4294967296\n",
- }, {
- map[string]uint64{"v": 4294967296},
- "v: 4294967296\n",
- }, {
- map[string]interface{}{"v": "10"},
- "v: \"10\"\n",
- }, {
- map[string]interface{}{"v": 0.1},
- "v: 0.1\n",
- }, {
- map[string]interface{}{"v": float64(0.1)},
- "v: 0.1\n",
- }, {
- map[string]interface{}{"v": -0.1},
- "v: -0.1\n",
- }, {
- map[string]interface{}{"v": math.Inf(+1)},
- "v: .inf\n",
- }, {
- map[string]interface{}{"v": math.Inf(-1)},
- "v: -.inf\n",
- }, {
- map[string]interface{}{"v": math.NaN()},
- "v: .nan\n",
- }, {
- map[string]interface{}{"v": nil},
- "v: null\n",
- }, {
- map[string]interface{}{"v": ""},
- "v: \"\"\n",
- }, {
- map[string][]string{"v": []string{"A", "B"}},
- "v:\n- A\n- B\n",
- }, {
- map[string][]string{"v": []string{"A", "B\nC"}},
- "v:\n- A\n- |-\n B\n C\n",
- }, {
- map[string][]interface{}{"v": []interface{}{"A", 1, map[string][]int{"B": []int{2, 3}}}},
- "v:\n- A\n- 1\n- B:\n - 2\n - 3\n",
- }, {
- map[string]interface{}{"a": map[interface{}]interface{}{"b": "c"}},
- "a:\n b: c\n",
- }, {
- map[string]interface{}{"a": "-"},
- "a: '-'\n",
- },
-
- // Simple values.
- {
- &marshalIntTest,
- "123\n",
- },
-
- // Structures
- {
- &struct{ Hello string }{"world"},
- "hello: world\n",
- }, {
- &struct {
- A struct {
- B string
- }
- }{struct{ B string }{"c"}},
- "a:\n b: c\n",
- }, {
- &struct {
- A *struct {
- B string
- }
- }{&struct{ B string }{"c"}},
- "a:\n b: c\n",
- }, {
- &struct {
- A *struct {
- B string
- }
- }{},
- "a: null\n",
- }, {
- &struct{ A int }{1},
- "a: 1\n",
- }, {
- &struct{ A []int }{[]int{1, 2}},
- "a:\n- 1\n- 2\n",
- }, {
- &struct {
- B int "a"
- }{1},
- "a: 1\n",
- }, {
- &struct{ A bool }{true},
- "a: true\n",
- },
-
- // Conditional flag
- {
- &struct {
- A int "a,omitempty"
- B int "b,omitempty"
- }{1, 0},
- "a: 1\n",
- }, {
- &struct {
- A int "a,omitempty"
- B int "b,omitempty"
- }{0, 0},
- "{}\n",
- }, {
- &struct {
- A *struct{ X, y int } "a,omitempty,flow"
- }{&struct{ X, y int }{1, 2}},
- "a: {x: 1}\n",
- }, {
- &struct {
- A *struct{ X, y int } "a,omitempty,flow"
- }{nil},
- "{}\n",
- }, {
- &struct {
- A *struct{ X, y int } "a,omitempty,flow"
- }{&struct{ X, y int }{}},
- "a: {x: 0}\n",
- }, {
- &struct {
- A struct{ X, y int } "a,omitempty,flow"
- }{struct{ X, y int }{1, 2}},
- "a: {x: 1}\n",
- }, {
- &struct {
- A struct{ X, y int } "a,omitempty,flow"
- }{struct{ X, y int }{0, 1}},
- "{}\n",
- }, {
- &struct {
- A float64 "a,omitempty"
- B float64 "b,omitempty"
- }{1, 0},
- "a: 1\n",
- },
-
- // Flow flag
- {
- &struct {
- A []int "a,flow"
- }{[]int{1, 2}},
- "a: [1, 2]\n",
- }, {
- &struct {
- A map[string]string "a,flow"
- }{map[string]string{"b": "c", "d": "e"}},
- "a: {b: c, d: e}\n",
- }, {
- &struct {
- A struct {
- B, D string
- } "a,flow"
- }{struct{ B, D string }{"c", "e"}},
- "a: {b: c, d: e}\n",
- },
-
- // Unexported field
- {
- &struct {
- u int
- A int
- }{0, 1},
- "a: 1\n",
- },
-
- // Ignored field
- {
- &struct {
- A int
- B int "-"
- }{1, 2},
- "a: 1\n",
- },
-
- // Struct inlining
- {
- &struct {
- A int
- C inlineB `yaml:",inline"`
- }{1, inlineB{2, inlineC{3}}},
- "a: 1\nb: 2\nc: 3\n",
- },
-
- // Map inlining
- {
- &struct {
- A int
- C map[string]int `yaml:",inline"`
- }{1, map[string]int{"b": 2, "c": 3}},
- "a: 1\nb: 2\nc: 3\n",
- },
-
- // Duration
- {
- map[string]time.Duration{"a": 3 * time.Second},
- "a: 3s\n",
- },
-
- // Issue #24: bug in map merging logic.
- {
- map[string]string{"a": "<foo>"},
- "a: <foo>\n",
- },
-
- // Issue #34: marshal unsupported base 60 floats quoted for compatibility
- // with old YAML 1.1 parsers.
- {
- map[string]string{"a": "1:1"},
- "a: \"1:1\"\n",
- },
-
- // Binary data.
- {
- map[string]string{"a": "\x00"},
- "a: \"\\0\"\n",
- }, {
- map[string]string{"a": "\x80\x81\x82"},
- "a: !!binary gIGC\n",
- }, {
- map[string]string{"a": strings.Repeat("\x90", 54)},
- "a: !!binary |\n " + strings.Repeat("kJCQ", 17) + "kJ\n CQ\n",
- },
-
- // Ordered maps.
- {
- &yaml.MapSlice{{"b", 2}, {"a", 1}, {"d", 4}, {"c", 3}, {"sub", yaml.MapSlice{{"e", 5}}}},
- "b: 2\na: 1\nd: 4\nc: 3\nsub:\n e: 5\n",
- },
-
- // Encode unicode as utf-8 rather than in escaped form.
- {
- map[string]string{"a": "你好"},
- "a: 你好\n",
- },
-
- // Support encoding.TextMarshaler.
- {
- map[string]net.IP{"a": net.IPv4(1, 2, 3, 4)},
- "a: 1.2.3.4\n",
- },
- {
- map[string]time.Time{"a": time.Unix(1424801979, 0)},
- "a: 2015-02-24T18:19:39Z\n",
- },
-
- // Ensure strings containing ": " are quoted (reported as PR #43, but not reproducible).
- {
- map[string]string{"a": "b: c"},
- "a: 'b: c'\n",
- },
-
- // Containing hash mark ('#') in string should be quoted
- {
- map[string]string{"a": "Hello #comment"},
- "a: 'Hello #comment'\n",
- },
- {
- map[string]string{"a": "你好 #comment"},
- "a: '你好 #comment'\n",
- },
-}
-
-func (s *S) TestMarshal(c *C) {
- defer os.Setenv("TZ", os.Getenv("TZ"))
- os.Setenv("TZ", "UTC")
- for _, item := range marshalTests {
- data, err := yaml.Marshal(item.value)
- c.Assert(err, IsNil)
- c.Assert(string(data), Equals, item.data)
- }
-}
-
-var marshalErrorTests = []struct {
- value interface{}
- error string
- panic string
-}{{
- value: &struct {
- B int
- inlineB ",inline"
- }{1, inlineB{2, inlineC{3}}},
- panic: `Duplicated key 'b' in struct struct \{ B int; .*`,
-}, {
- value: &struct {
- A int
- B map[string]int ",inline"
- }{1, map[string]int{"a": 2}},
- panic: `Can't have key "a" in inlined map; conflicts with struct field`,
-}}
-
-func (s *S) TestMarshalErrors(c *C) {
- for _, item := range marshalErrorTests {
- if item.panic != "" {
- c.Assert(func() { yaml.Marshal(item.value) }, PanicMatches, item.panic)
- } else {
- _, err := yaml.Marshal(item.value)
- c.Assert(err, ErrorMatches, item.error)
- }
- }
-}
-
-func (s *S) TestMarshalTypeCache(c *C) {
- var data []byte
- var err error
- func() {
- type T struct{ A int }
- data, err = yaml.Marshal(&T{})
- c.Assert(err, IsNil)
- }()
- func() {
- type T struct{ B int }
- data, err = yaml.Marshal(&T{})
- c.Assert(err, IsNil)
- }()
- c.Assert(string(data), Equals, "b: 0\n")
-}
-
-var marshalerTests = []struct {
- data string
- value interface{}
-}{
- {"_:\n hi: there\n", map[interface{}]interface{}{"hi": "there"}},
- {"_:\n- 1\n- A\n", []interface{}{1, "A"}},
- {"_: 10\n", 10},
- {"_: null\n", nil},
- {"_: BAR!\n", "BAR!"},
-}
-
-type marshalerType struct {
- value interface{}
-}
-
-func (o marshalerType) MarshalText() ([]byte, error) {
- panic("MarshalText called on type with MarshalYAML")
-}
-
-func (o marshalerType) MarshalYAML() (interface{}, error) {
- return o.value, nil
-}
-
-type marshalerValue struct {
- Field marshalerType "_"
-}
-
-func (s *S) TestMarshaler(c *C) {
- for _, item := range marshalerTests {
- obj := &marshalerValue{}
- obj.Field.value = item.value
- data, err := yaml.Marshal(obj)
- c.Assert(err, IsNil)
- c.Assert(string(data), Equals, string(item.data))
- }
-}
-
-func (s *S) TestMarshalerWholeDocument(c *C) {
- obj := &marshalerType{}
- obj.value = map[string]string{"hello": "world!"}
- data, err := yaml.Marshal(obj)
- c.Assert(err, IsNil)
- c.Assert(string(data), Equals, "hello: world!\n")
-}
-
-type failingMarshaler struct{}
-
-func (ft *failingMarshaler) MarshalYAML() (interface{}, error) {
- return nil, failingErr
-}
-
-func (s *S) TestMarshalerError(c *C) {
- _, err := yaml.Marshal(&failingMarshaler{})
- c.Assert(err, Equals, failingErr)
-}
-
-func (s *S) TestSortedOutput(c *C) {
- order := []interface{}{
- false,
- true,
- 1,
- uint(1),
- 1.0,
- 1.1,
- 1.2,
- 2,
- uint(2),
- 2.0,
- 2.1,
- "",
- ".1",
- ".2",
- ".a",
- "1",
- "2",
- "a!10",
- "a/2",
- "a/10",
- "a~10",
- "ab/1",
- "b/1",
- "b/01",
- "b/2",
- "b/02",
- "b/3",
- "b/03",
- "b1",
- "b01",
- "b3",
- "c2.10",
- "c10.2",
- "d1",
- "d12",
- "d12a",
- }
- m := make(map[interface{}]int)
- for _, k := range order {
- m[k] = 1
- }
- data, err := yaml.Marshal(m)
- c.Assert(err, IsNil)
- out := "\n" + string(data)
- last := 0
- for i, k := range order {
- repr := fmt.Sprint(k)
- if s, ok := k.(string); ok {
- if _, err = strconv.ParseFloat(repr, 32); s == "" || err == nil {
- repr = `"` + repr + `"`
- }
- }
- index := strings.Index(out, "\n"+repr+":")
- if index == -1 {
- c.Fatalf("%#v is not in the output: %#v", k, out)
- }
- if index < last {
- c.Fatalf("%#v was generated before %#v: %q", k, order[i-1], out)
- }
- last = index
- }
-}
diff --git a/vendor/gopkg.in/yaml.v2/example_embedded_test.go b/vendor/gopkg.in/yaml.v2/example_embedded_test.go
deleted file mode 100644
index c8b241d..0000000
--- a/vendor/gopkg.in/yaml.v2/example_embedded_test.go
+++ /dev/null
@@ -1,41 +0,0 @@
-package yaml_test
-
-import (
- "fmt"
- "log"
-
- "gopkg.in/yaml.v2"
-)
-
-// An example showing how to unmarshal embedded
-// structs from YAML.
-
-type StructA struct {
- A string `yaml:"a"`
-}
-
-type StructB struct {
- // Embedded structs are not treated as embedded in YAML by default. To do that,
- // add the ",inline" annotation below
- StructA `yaml:",inline"`
- B string `yaml:"b"`
-}
-
-var data = `
-a: a string from struct A
-b: a string from struct B
-`
-
-func ExampleUnmarshal_embedded() {
- var b StructB
-
- err := yaml.Unmarshal([]byte(data), &b)
- if err != nil {
- log.Fatal("cannot unmarshal data: %v", err)
- }
- fmt.Println(b.A)
- fmt.Println(b.B)
- // Output:
- // a string from struct A
- // a string from struct B
-}
diff --git a/vendor/gopkg.in/yaml.v2/suite_test.go b/vendor/gopkg.in/yaml.v2/suite_test.go
deleted file mode 100644
index c5cf1ed..0000000
--- a/vendor/gopkg.in/yaml.v2/suite_test.go
+++ /dev/null
@@ -1,12 +0,0 @@
-package yaml_test
-
-import (
- . "gopkg.in/check.v1"
- "testing"
-)
-
-func Test(t *testing.T) { TestingT(t) }
-
-type S struct{}
-
-var _ = Suite(&S{})