From 981fde99e25796ef6abc96672f6895c0b170d224 Mon Sep 17 00:00:00 2001 From: elij Date: Sat, 17 Feb 2018 15:40:21 -0800 Subject: [PATCH] stop using GB, convert to dep/gox/GOPATH model GB seems semi-abandoned, and currently doesn't cross compile with either go-1.9.4 or go-1.10 ([bug][1]). Possibly due to the new cgo flag whitelisting (see: [go issue: 23739][2])? Instead: * require devs to put into GOPATH, as this seems unfortunately to be the convention the go community arrived at :( * use dep for vendoring * use gox for easy cross compilation [1]: https://github.com/constabulary/gb/issues/733 [2]: https://github.com/golang/go/issues/23739 --- .circleci/config.yml | 3 +- .gitignore | 6 +- .travis.yml | 6 +- CHANGELOG.md | 1 + DEPS.md | 3 - Gopkg.lock | 39 + Gopkg.toml | 33 + Makefile | 81 +- README.md | 29 +- {src/go-camo/camo => camo}/encoding/url.go | 0 .../camo => camo}/encoding/url_test.go | 0 .../example_proxymetrics_test.go | 4 +- {src/go-camo/camo => camo}/misc.go | 0 {src/go-camo/camo => camo}/proxy.go | 2 +- {src/go-camo/camo => camo}/proxy_test.go | 4 +- {src/go-camo/camo => camo}/vars.go | 0 src/go-camo/main.go => main.go | 8 +- ...sion_info_generated.go => main_vers_gen.go | 3 - {src/go-camo/router => router}/httpdate.go | 0 .../router => router}/httpdate_test.go | 0 {src/go-camo/router => router}/router.go | 0 {src/go-camo/stats => stats}/stats.go | 0 {src/go-camo/stats => stats}/stats_test.go | 0 {src/go-camo/url-tool => url-tool}/main.go | 2 +- vendor/github.com/cactus/mlog/.gitignore | 4 + vendor/github.com/cactus/mlog/.travis.yml | 7 + .../github.com/cactus/mlog/CHANGELOG.md | 1 - .../github.com/cactus/mlog/LICENSE.md | 0 .../github.com/cactus/mlog/README.md | 25 +- .../github.com/cactus/mlog/default_logger.go | 17 - .../{src => }/github.com/cactus/mlog/doc.go | 0 .../github.com/cactus/mlog/flagset.go | 24 +- .../github.com/cactus/mlog/flagset_test.go | 0 .../cactus/mlog/formatwriter_json.go | 101 +- .../mlog/formatwriter_json_bench_test.go | 9 - .../cactus/mlog/formatwriter_plain.go | 59 +- .../mlog/formatwriter_plain_bench_test.go | 9 - .../cactus/mlog/formatwriter_structured.go | 60 +- .../formatwriter_structured_bench_test.go | 9 - .../github.com/cactus/mlog/logger.go | 27 +- .../cactus/mlog/logger_bench_test.go | 0 .../github.com/cactus/mlog/logger_test.go | 66 +- .../github.com/cactus/mlog/logmap.go | 4 +- .../github.com/cactus/mlog/logmap_test.go | 1 + .../github.com/cactus/mlog/slicebuffer.go | 42 +- .../test_logger_msgs.debug1.golden | 0 .../test_logger_msgs.debug2.golden | 0 .../test_logger_msgs.infof1.golden | 0 .../test_logger_msgs.infof2.golden | 0 .../test_logger_msgs.infof3.golden | 0 .../test_logger_msgs.infom1.golden | 0 .../test_logger_msgs.infom2.golden | 0 .../test_logger_msgs.infom3.golden | 0 .../test_logger_msgs.infom4.golden | 0 .../{src => }/github.com/cactus/mlog/time.go | 27 +- vendor/github.com/cactus/mlog/time_test.go | 45 + vendor/github.com/davecgh/go-spew/.gitignore | 22 + vendor/github.com/davecgh/go-spew/.travis.yml | 14 + vendor/github.com/davecgh/go-spew/LICENSE | 15 + vendor/github.com/davecgh/go-spew/README.md | 205 +++ .../github.com/davecgh/go-spew/cov_report.sh | 22 + .../github.com/davecgh/go-spew/spew/bypass.go | 6 +- .../davecgh/go-spew/spew/bypasssafe.go | 0 .../github.com/davecgh/go-spew/spew/common.go | 2 +- .../davecgh/go-spew/spew/common_test.go | 0 .../github.com/davecgh/go-spew/spew/config.go | 0 .../github.com/davecgh/go-spew/spew/doc.go | 0 .../github.com/davecgh/go-spew/spew/dump.go | 10 +- .../davecgh/go-spew/spew/dump_test.go | 0 .../davecgh/go-spew/spew/dumpcgo_test.go | 6 +- .../davecgh/go-spew/spew/dumpnocgo_test.go | 0 .../davecgh/go-spew/spew/example_test.go | 0 .../github.com/davecgh/go-spew/spew/format.go | 4 +- .../davecgh/go-spew/spew/format_test.go | 4 +- .../davecgh/go-spew/spew/internal_test.go | 5 +- .../go-spew/spew/internalunsafe_test.go | 0 .../github.com/davecgh/go-spew/spew/spew.go | 0 .../davecgh/go-spew/spew/spew_test.go | 0 .../davecgh/go-spew/spew/testdata/dumpcgo.go | 0 .../davecgh/go-spew/test_coverage.txt | 61 + .../github.com/jessevdk/go-flags/.travis.yml | 38 + .../github.com/jessevdk/go-flags/LICENSE | 0 .../github.com/jessevdk/go-flags/README.md | 1 + .../github.com/jessevdk/go-flags/arg.go | 0 .../github.com/jessevdk/go-flags/arg_test.go | 0 .../jessevdk/go-flags/assert_test.go | 0 .../jessevdk/go-flags/check_crosscompile.sh | 0 .../github.com/jessevdk/go-flags/closest.go | 0 .../github.com/jessevdk/go-flags/command.go | 14 +- .../jessevdk/go-flags/command_test.go | 0 .../jessevdk/go-flags/completion.go | 0 .../jessevdk/go-flags/completion_test.go | 0 .../github.com/jessevdk/go-flags/convert.go | 0 .../jessevdk/go-flags/convert_test.go | 0 .../github.com/jessevdk/go-flags/error.go | 0 .../jessevdk/go-flags/example_test.go | 0 .../jessevdk/go-flags/examples/add.go | 0 .../go-flags/examples/bash-completion | 0 .../jessevdk/go-flags/examples/main.go | 0 .../jessevdk/go-flags/examples/rm.go | 0 .../github.com/jessevdk/go-flags/flags.go | 0 .../github.com/jessevdk/go-flags/group.go | 15 +- .../jessevdk/go-flags/group_test.go | 0 .../github.com/jessevdk/go-flags/help.go | 0 .../github.com/jessevdk/go-flags/help_test.go | 0 .../github.com/jessevdk/go-flags/ini.go | 0 .../github.com/jessevdk/go-flags/ini_test.go | 0 .../github.com/jessevdk/go-flags/long_test.go | 0 .../github.com/jessevdk/go-flags/man.go | 0 .../jessevdk/go-flags/marshal_test.go | 0 .../github.com/jessevdk/go-flags/multitag.go | 0 .../github.com/jessevdk/go-flags/option.go | 0 .../jessevdk/go-flags/options_test.go | 0 .../jessevdk/go-flags/optstyle_other.go | 0 .../jessevdk/go-flags/optstyle_windows.go | 0 .../github.com/jessevdk/go-flags/parser.go | 0 .../jessevdk/go-flags/parser_test.go | 0 .../jessevdk/go-flags/pointer_test.go | 0 .../jessevdk/go-flags/short_test.go | 0 .../github.com/jessevdk/go-flags/tag_test.go | 0 .../github.com/jessevdk/go-flags/termsize.go | 2 +- .../jessevdk/go-flags/termsize_linux.go} | 0 .../jessevdk/go-flags/termsize_nosysioctl.go | 2 +- .../jessevdk/go-flags/termsize_other.go} | 0 .../jessevdk/go-flags/termsize_unix.go} | 0 .../jessevdk/go-flags/unknown_test.go | 0 .../github.com/pmezard/go-difflib/.travis.yml | 5 + vendor/github.com/pmezard/go-difflib/LICENSE | 27 + .../github.com/pmezard/go-difflib/README.md | 50 + .../pmezard/go-difflib/difflib/difflib.go | 0 .../go-difflib/difflib/difflib_test.go | 0 vendor/github.com/stretchr/testify/.gitignore | 24 + .../stretchr/testify/.travis.gofmt.sh | 7 + .../stretchr/testify/.travis.gogenerate.sh | 13 + .../stretchr/testify/.travis.govet.sh | 10 + .../github.com/stretchr/testify/.travis.yml | 15 + vendor/github.com/stretchr/testify/Gopkg.lock | 27 + vendor/github.com/stretchr/testify/Gopkg.toml | 16 + vendor/github.com/stretchr/testify/LICENSE | 22 + vendor/github.com/stretchr/testify/README.md | 301 ++++ .../stretchr/testify/_codegen/main.go | 316 ++++ .../testify/assert/assertion_format.go | 2 +- .../testify/assert/assertion_format.go.tmpl | 0 .../testify/assert/assertion_forward.go | 4 +- .../testify/assert/assertion_forward.go.tmpl | 0 .../stretchr/testify/assert/assertions.go | 4 +- .../testify/assert/assertions_test.go | 0 .../github.com/stretchr/testify/assert/doc.go | 0 .../stretchr/testify/assert/errors.go | 0 .../testify/assert/forward_assertions.go | 0 .../testify/assert/forward_assertions_test.go | 0 .../testify/assert/http_assertions.go | 0 .../testify/assert/http_assertions_test.go | 0 vendor/github.com/stretchr/testify/doc.go | 22 + .../github.com/stretchr/testify/http/doc.go | 2 + .../testify/http/test_response_writer.go | 49 + .../testify/http/test_round_tripper.go | 17 + .../github.com/stretchr/testify/mock/doc.go | 44 + .../github.com/stretchr/testify/mock/mock.go | 815 ++++++++++ .../stretchr/testify/mock/mock_test.go | 1352 +++++++++++++++++ .../stretchr/testify/package_test.go | 12 + .../stretchr/testify/require/doc.go | 28 + .../testify/require/forward_requirements.go | 16 + .../require/forward_requirements_test.go | 385 +++++ .../stretchr/testify/require/require.go | 867 +++++++++++ .../stretchr/testify/require/require.go.tmpl | 6 + .../testify/require/require_forward.go | 687 +++++++++ .../testify/require/require_forward.go.tmpl | 4 + .../stretchr/testify/require/requirements.go | 9 + .../testify/require/requirements_test.go | 369 +++++ .../github.com/stretchr/testify/suite/doc.go | 65 + .../stretchr/testify/suite/interfaces.go | 46 + .../stretchr/testify/suite/suite.go | 136 ++ .../stretchr/testify/suite/suite_test.go | 294 ++++ vendor/manifest | 44 - .../cactus/mlog/formatwriter_json_test.go | 42 - .../cactus/mlog/formatwriter_plain_test.go | 34 - .../mlog/formatwriter_structured_test.go | 34 - .../test_logger_msgs.panic.golden | 1 - .../test_logger_msgs.panicf.golden | 1 - .../test_logger_msgs.panicm.golden | 1 - .../src/github.com/cactus/mlog/time_test.go | 82 - vendor/src/github.com/cactus/tai64/LICENSE.md | 19 - vendor/src/github.com/cactus/tai64/README.md | 60 - vendor/src/github.com/cactus/tai64/offsets.go | 45 - vendor/src/github.com/cactus/tai64/time.go | 120 -- .../src/github.com/cactus/tai64/time_test.go | 87 -- .../github.com/cactus/tai64/tools/generate.go | 144 -- 188 files changed, 6820 insertions(+), 1171 deletions(-) create mode 100644 Gopkg.lock create mode 100644 Gopkg.toml rename {src/go-camo/camo => camo}/encoding/url.go (100%) rename {src/go-camo/camo => camo}/encoding/url_test.go (100%) rename {src/go-camo/camo => camo}/example_proxymetrics_test.go (85%) rename {src/go-camo/camo => camo}/misc.go (100%) rename {src/go-camo/camo => camo}/proxy.go (99%) rename {src/go-camo/camo => camo}/proxy_test.go (99%) rename {src/go-camo/camo => camo}/vars.go (100%) rename src/go-camo/main.go => main.go (96%) rename src/go-camo/version_info_generated.go => main_vers_gen.go (75%) rename {src/go-camo/router => router}/httpdate.go (100%) rename {src/go-camo/router => router}/httpdate_test.go (100%) rename {src/go-camo/router => router}/router.go (100%) rename {src/go-camo/stats => stats}/stats.go (100%) rename {src/go-camo/stats => stats}/stats_test.go (100%) rename {src/go-camo/url-tool => url-tool}/main.go (98%) create mode 100644 vendor/github.com/cactus/mlog/.gitignore create mode 100644 vendor/github.com/cactus/mlog/.travis.yml rename vendor/{src => }/github.com/cactus/mlog/CHANGELOG.md (77%) rename vendor/{src => }/github.com/cactus/mlog/LICENSE.md (100%) rename vendor/{src => }/github.com/cactus/mlog/README.md (69%) rename vendor/{src => }/github.com/cactus/mlog/default_logger.go (84%) rename vendor/{src => }/github.com/cactus/mlog/doc.go (100%) rename vendor/{src => }/github.com/cactus/mlog/flagset.go (79%) rename vendor/{src => }/github.com/cactus/mlog/flagset_test.go (100%) rename vendor/{src => }/github.com/cactus/mlog/formatwriter_json.go (61%) rename vendor/{src => }/github.com/cactus/mlog/formatwriter_json_bench_test.go (89%) rename vendor/{src => }/github.com/cactus/mlog/formatwriter_plain.go (59%) rename vendor/{src => }/github.com/cactus/mlog/formatwriter_plain_bench_test.go (90%) rename vendor/{src => }/github.com/cactus/mlog/formatwriter_structured.go (61%) rename vendor/{src => }/github.com/cactus/mlog/formatwriter_structured_bench_test.go (90%) rename vendor/{src => }/github.com/cactus/mlog/logger.go (85%) rename vendor/{src => }/github.com/cactus/mlog/logger_bench_test.go (100%) rename vendor/{src => }/github.com/cactus/mlog/logger_test.go (70%) rename vendor/{src => }/github.com/cactus/mlog/logmap.go (96%) rename vendor/{src => }/github.com/cactus/mlog/logmap_test.go (94%) rename vendor/{src => }/github.com/cactus/mlog/slicebuffer.go (68%) rename vendor/{src => }/github.com/cactus/mlog/test-fixtures/test_logger_msgs.debug1.golden (100%) rename vendor/{src => }/github.com/cactus/mlog/test-fixtures/test_logger_msgs.debug2.golden (100%) rename vendor/{src => }/github.com/cactus/mlog/test-fixtures/test_logger_msgs.infof1.golden (100%) rename vendor/{src => }/github.com/cactus/mlog/test-fixtures/test_logger_msgs.infof2.golden (100%) rename vendor/{src => }/github.com/cactus/mlog/test-fixtures/test_logger_msgs.infof3.golden (100%) rename vendor/{src => }/github.com/cactus/mlog/test-fixtures/test_logger_msgs.infom1.golden (100%) rename vendor/{src => }/github.com/cactus/mlog/test-fixtures/test_logger_msgs.infom2.golden (100%) rename vendor/{src => }/github.com/cactus/mlog/test-fixtures/test_logger_msgs.infom3.golden (100%) rename vendor/{src => }/github.com/cactus/mlog/test-fixtures/test_logger_msgs.infom4.golden (100%) rename vendor/{src => }/github.com/cactus/mlog/time.go (59%) create mode 100644 vendor/github.com/cactus/mlog/time_test.go create mode 100644 vendor/github.com/davecgh/go-spew/.gitignore create mode 100644 vendor/github.com/davecgh/go-spew/.travis.yml create mode 100644 vendor/github.com/davecgh/go-spew/LICENSE create mode 100644 vendor/github.com/davecgh/go-spew/README.md create mode 100644 vendor/github.com/davecgh/go-spew/cov_report.sh rename vendor/{src => }/github.com/davecgh/go-spew/spew/bypass.go (98%) rename vendor/{src => }/github.com/davecgh/go-spew/spew/bypasssafe.go (100%) rename vendor/{src => }/github.com/davecgh/go-spew/spew/common.go (99%) rename vendor/{src => }/github.com/davecgh/go-spew/spew/common_test.go (100%) rename vendor/{src => }/github.com/davecgh/go-spew/spew/config.go (100%) rename vendor/{src => }/github.com/davecgh/go-spew/spew/doc.go (100%) rename vendor/{src => }/github.com/davecgh/go-spew/spew/dump.go (98%) rename vendor/{src => }/github.com/davecgh/go-spew/spew/dump_test.go (100%) rename vendor/{src => }/github.com/davecgh/go-spew/spew/dumpcgo_test.go (94%) rename vendor/{src => }/github.com/davecgh/go-spew/spew/dumpnocgo_test.go (100%) rename vendor/{src => }/github.com/davecgh/go-spew/spew/example_test.go (100%) rename vendor/{src => }/github.com/davecgh/go-spew/spew/format.go (99%) rename vendor/{src => }/github.com/davecgh/go-spew/spew/format_test.go (99%) rename vendor/{src => }/github.com/davecgh/go-spew/spew/internal_test.go (98%) rename vendor/{src => }/github.com/davecgh/go-spew/spew/internalunsafe_test.go (100%) rename vendor/{src => }/github.com/davecgh/go-spew/spew/spew.go (100%) rename vendor/{src => }/github.com/davecgh/go-spew/spew/spew_test.go (100%) rename vendor/{src => }/github.com/davecgh/go-spew/spew/testdata/dumpcgo.go (100%) create mode 100644 vendor/github.com/davecgh/go-spew/test_coverage.txt create mode 100644 vendor/github.com/jessevdk/go-flags/.travis.yml rename vendor/{src => }/github.com/jessevdk/go-flags/LICENSE (100%) rename vendor/{src => }/github.com/jessevdk/go-flags/README.md (99%) rename vendor/{src => }/github.com/jessevdk/go-flags/arg.go (100%) rename vendor/{src => }/github.com/jessevdk/go-flags/arg_test.go (100%) rename vendor/{src => }/github.com/jessevdk/go-flags/assert_test.go (100%) rename vendor/{src => }/github.com/jessevdk/go-flags/check_crosscompile.sh (100%) mode change 100644 => 100755 rename vendor/{src => }/github.com/jessevdk/go-flags/closest.go (100%) rename vendor/{src => }/github.com/jessevdk/go-flags/command.go (97%) rename vendor/{src => }/github.com/jessevdk/go-flags/command_test.go (100%) rename vendor/{src => }/github.com/jessevdk/go-flags/completion.go (100%) rename vendor/{src => }/github.com/jessevdk/go-flags/completion_test.go (100%) rename vendor/{src => }/github.com/jessevdk/go-flags/convert.go (100%) rename vendor/{src => }/github.com/jessevdk/go-flags/convert_test.go (100%) rename vendor/{src => }/github.com/jessevdk/go-flags/error.go (100%) rename vendor/{src => }/github.com/jessevdk/go-flags/example_test.go (100%) rename vendor/{src => }/github.com/jessevdk/go-flags/examples/add.go (100%) rename vendor/{src => }/github.com/jessevdk/go-flags/examples/bash-completion (100%) rename vendor/{src => }/github.com/jessevdk/go-flags/examples/main.go (100%) rename vendor/{src => }/github.com/jessevdk/go-flags/examples/rm.go (100%) rename vendor/{src => }/github.com/jessevdk/go-flags/flags.go (100%) rename vendor/{src => }/github.com/jessevdk/go-flags/group.go (97%) rename vendor/{src => }/github.com/jessevdk/go-flags/group_test.go (100%) rename vendor/{src => }/github.com/jessevdk/go-flags/help.go (100%) rename vendor/{src => }/github.com/jessevdk/go-flags/help_test.go (100%) rename vendor/{src => }/github.com/jessevdk/go-flags/ini.go (100%) rename vendor/{src => }/github.com/jessevdk/go-flags/ini_test.go (100%) rename vendor/{src => }/github.com/jessevdk/go-flags/long_test.go (100%) rename vendor/{src => }/github.com/jessevdk/go-flags/man.go (100%) rename vendor/{src => }/github.com/jessevdk/go-flags/marshal_test.go (100%) rename vendor/{src => }/github.com/jessevdk/go-flags/multitag.go (100%) rename vendor/{src => }/github.com/jessevdk/go-flags/option.go (100%) rename vendor/{src => }/github.com/jessevdk/go-flags/options_test.go (100%) rename vendor/{src => }/github.com/jessevdk/go-flags/optstyle_other.go (100%) rename vendor/{src => }/github.com/jessevdk/go-flags/optstyle_windows.go (100%) rename vendor/{src => }/github.com/jessevdk/go-flags/parser.go (100%) rename vendor/{src => }/github.com/jessevdk/go-flags/parser_test.go (100%) rename vendor/{src => }/github.com/jessevdk/go-flags/pointer_test.go (100%) rename vendor/{src => }/github.com/jessevdk/go-flags/short_test.go (100%) rename vendor/{src => }/github.com/jessevdk/go-flags/tag_test.go (100%) rename vendor/{src => }/github.com/jessevdk/go-flags/termsize.go (88%) rename vendor/{src/github.com/jessevdk/go-flags/tiocgwinsz_linux.go => github.com/jessevdk/go-flags/termsize_linux.go} (100%) rename vendor/{src => }/github.com/jessevdk/go-flags/termsize_nosysioctl.go (59%) rename vendor/{src/github.com/jessevdk/go-flags/tiocgwinsz_other.go => github.com/jessevdk/go-flags/termsize_other.go} (100%) rename vendor/{src/github.com/jessevdk/go-flags/tiocgwinsz_bsdish.go => github.com/jessevdk/go-flags/termsize_unix.go} (100%) rename vendor/{src => }/github.com/jessevdk/go-flags/unknown_test.go (100%) create mode 100644 vendor/github.com/pmezard/go-difflib/.travis.yml create mode 100644 vendor/github.com/pmezard/go-difflib/LICENSE create mode 100644 vendor/github.com/pmezard/go-difflib/README.md rename vendor/{src => }/github.com/pmezard/go-difflib/difflib/difflib.go (100%) rename vendor/{src => }/github.com/pmezard/go-difflib/difflib/difflib_test.go (100%) create mode 100644 vendor/github.com/stretchr/testify/.gitignore create mode 100755 vendor/github.com/stretchr/testify/.travis.gofmt.sh create mode 100755 vendor/github.com/stretchr/testify/.travis.gogenerate.sh create mode 100755 vendor/github.com/stretchr/testify/.travis.govet.sh create mode 100644 vendor/github.com/stretchr/testify/.travis.yml create mode 100644 vendor/github.com/stretchr/testify/Gopkg.lock create mode 100644 vendor/github.com/stretchr/testify/Gopkg.toml create mode 100644 vendor/github.com/stretchr/testify/LICENSE create mode 100644 vendor/github.com/stretchr/testify/README.md create mode 100644 vendor/github.com/stretchr/testify/_codegen/main.go rename vendor/{src => }/github.com/stretchr/testify/assert/assertion_format.go (99%) rename vendor/{src => }/github.com/stretchr/testify/assert/assertion_format.go.tmpl (100%) rename vendor/{src => }/github.com/stretchr/testify/assert/assertion_forward.go (99%) rename vendor/{src => }/github.com/stretchr/testify/assert/assertion_forward.go.tmpl (100%) rename vendor/{src => }/github.com/stretchr/testify/assert/assertions.go (99%) rename vendor/{src => }/github.com/stretchr/testify/assert/assertions_test.go (100%) rename vendor/{src => }/github.com/stretchr/testify/assert/doc.go (100%) rename vendor/{src => }/github.com/stretchr/testify/assert/errors.go (100%) rename vendor/{src => }/github.com/stretchr/testify/assert/forward_assertions.go (100%) rename vendor/{src => }/github.com/stretchr/testify/assert/forward_assertions_test.go (100%) rename vendor/{src => }/github.com/stretchr/testify/assert/http_assertions.go (100%) rename vendor/{src => }/github.com/stretchr/testify/assert/http_assertions_test.go (100%) create mode 100644 vendor/github.com/stretchr/testify/doc.go create mode 100644 vendor/github.com/stretchr/testify/http/doc.go create mode 100644 vendor/github.com/stretchr/testify/http/test_response_writer.go create mode 100644 vendor/github.com/stretchr/testify/http/test_round_tripper.go create mode 100644 vendor/github.com/stretchr/testify/mock/doc.go create mode 100644 vendor/github.com/stretchr/testify/mock/mock.go create mode 100644 vendor/github.com/stretchr/testify/mock/mock_test.go create mode 100644 vendor/github.com/stretchr/testify/package_test.go create mode 100644 vendor/github.com/stretchr/testify/require/doc.go create mode 100644 vendor/github.com/stretchr/testify/require/forward_requirements.go create mode 100644 vendor/github.com/stretchr/testify/require/forward_requirements_test.go create mode 100644 vendor/github.com/stretchr/testify/require/require.go create mode 100644 vendor/github.com/stretchr/testify/require/require.go.tmpl create mode 100644 vendor/github.com/stretchr/testify/require/require_forward.go create mode 100644 vendor/github.com/stretchr/testify/require/require_forward.go.tmpl create mode 100644 vendor/github.com/stretchr/testify/require/requirements.go create mode 100644 vendor/github.com/stretchr/testify/require/requirements_test.go create mode 100644 vendor/github.com/stretchr/testify/suite/doc.go create mode 100644 vendor/github.com/stretchr/testify/suite/interfaces.go create mode 100644 vendor/github.com/stretchr/testify/suite/suite.go create mode 100644 vendor/github.com/stretchr/testify/suite/suite_test.go delete mode 100644 vendor/manifest delete mode 100644 vendor/src/github.com/cactus/mlog/formatwriter_json_test.go delete mode 100644 vendor/src/github.com/cactus/mlog/formatwriter_plain_test.go delete mode 100644 vendor/src/github.com/cactus/mlog/formatwriter_structured_test.go delete mode 100644 vendor/src/github.com/cactus/mlog/test-fixtures/test_logger_msgs.panic.golden delete mode 100644 vendor/src/github.com/cactus/mlog/test-fixtures/test_logger_msgs.panicf.golden delete mode 100644 vendor/src/github.com/cactus/mlog/test-fixtures/test_logger_msgs.panicm.golden delete mode 100644 vendor/src/github.com/cactus/mlog/time_test.go delete mode 100644 vendor/src/github.com/cactus/tai64/LICENSE.md delete mode 100644 vendor/src/github.com/cactus/tai64/README.md delete mode 100644 vendor/src/github.com/cactus/tai64/offsets.go delete mode 100644 vendor/src/github.com/cactus/tai64/time.go delete mode 100644 vendor/src/github.com/cactus/tai64/time_test.go delete mode 100644 vendor/src/github.com/cactus/tai64/tools/generate.go diff --git a/.circleci/config.yml b/.circleci/config.yml index 04b18bf..89fcc13 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -1,8 +1,9 @@ version: 2 jobs: build: + working_directory: /go/src/github.com/cactus/go-camo docker: - image: circleci/golang:1 steps: - checkout - - run: make build-setup test + - run: make test diff --git a/.gitignore b/.gitignore index 79252f3..f084c39 100644 --- a/.gitignore +++ b/.gitignore @@ -1,8 +1,6 @@ +/build /config.json -/bin -/pkg -/tar -/man/*.[1-9] +/diagrams /prox.exe /server.pem /server.key diff --git a/.travis.yml b/.travis.yml index 787be34..5357ee8 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,6 +1,6 @@ language: go -script: make build-setup test +script: make test sudo: false go: - - 1.8 - - 1.9 + - "1.9.x" + - "1.10" diff --git a/CHANGELOG.md b/CHANGELOG.md index fa663fd..ac02caa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ Changelog ========= ## HEAD +* change repo layout and build pipeline to dep/gox/GOPATH style ## 1.0.17 2018-01-25 * update dependency versions to current diff --git a/DEPS.md b/DEPS.md index 8336070..b269188 100644 --- a/DEPS.md +++ b/DEPS.md @@ -6,11 +6,8 @@ Portions of this software utilize third party libraries: * Runtime dependencies: ├── https://github.com/cactus/mlog (MIT License) - ├── https://github.com/cactus/tai64 (MIT License) └── https://github.com/jessevdk/go-flags (BSD License) * Test only dependencies: └── https://github.com/stretchr/testify/assert (MIT License) - ├── https://github.com/davecgh/go-spew (ISC License) - └── https://github.com/pmezard/go-difflib (BSD License) ~~~ diff --git a/Gopkg.lock b/Gopkg.lock new file mode 100644 index 0000000..7527a38 --- /dev/null +++ b/Gopkg.lock @@ -0,0 +1,39 @@ +# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. + + +[[projects]] + name = "github.com/cactus/mlog" + packages = ["."] + revision = "fc2dce550187f3b7c4b871a2528b6e2aebe2580b" + version = "v1.0.0" + +[[projects]] + name = "github.com/davecgh/go-spew" + packages = ["spew"] + revision = "346938d642f2ec3594ed81d874461961cd0faa76" + version = "v1.1.0" + +[[projects]] + name = "github.com/jessevdk/go-flags" + packages = ["."] + revision = "96dc06278ce32a0e9d957d590bb987c81ee66407" + version = "v1.3.0" + +[[projects]] + name = "github.com/pmezard/go-difflib" + packages = ["difflib"] + revision = "792786c7400a136282c1664665ae0a8db921c6c2" + version = "v1.0.0" + +[[projects]] + name = "github.com/stretchr/testify" + packages = ["assert"] + revision = "12b6f73e6084dad08a7c6e575284b177ecafbc71" + version = "v1.2.1" + +[solve-meta] + analyzer-name = "dep" + analyzer-version = 1 + inputs-digest = "c4bbd1c91c001d7740ac8c43bdf3cd4a920b5bdec6e00070034889fae4385085" + solver-name = "gps-cdcl" + solver-version = 1 diff --git a/Gopkg.toml b/Gopkg.toml new file mode 100644 index 0000000..231bfc6 --- /dev/null +++ b/Gopkg.toml @@ -0,0 +1,33 @@ +# Gopkg.toml example +# +# Refer to https://github.com/golang/dep/blob/master/docs/Gopkg.toml.md +# for detailed Gopkg.toml documentation. +# +# required = ["github.com/user/thing/cmd/thing"] +# ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"] +# +# [[constraint]] +# name = "github.com/user/project" +# version = "1.0.0" +# +# [[constraint]] +# name = "github.com/user/project2" +# branch = "dev" +# source = "github.com/myfork/project2" +# +# [[override]] +# name = "github.com/x/y" +# version = "2.4.0" + + +[[constraint]] + name = "github.com/cactus/mlog" + version = "1.0.0" + +[[constraint]] + name = "github.com/jessevdk/go-flags" + version = "1.3.0" + +[[constraint]] + name = "github.com/stretchr/testify" + version = "1.2.1" diff --git a/Makefile b/Makefile index 86d3600..ead6475 100644 --- a/Makefile +++ b/Makefile @@ -1,17 +1,28 @@ - -BUILDDIR := ${CURDIR} +# environment +BUILDDIR := ${CURDIR}/build TARBUILDDIR := ${BUILDDIR}/tar ARCH := $(shell go env GOHOSTARCH) OS := $(shell go env GOHOSTOS) GOVER := $(shell go version | awk '{print $$3}' | tr -d '.') + +# app specific info APP_NAME := go-camo APP_VER := $(shell git describe --always --dirty --tags|sed 's/^v//') VERSION_VAR := main.ServerVersion + +# flags and build configuration GOTEST_FLAGS := -cpu=1,2 GOBUILD_DEPFLAGS := -tags netgo GOBUILD_LDFLAGS ?= -s -w GOBUILD_FLAGS := ${GOBUILD_DEPFLAGS} -ldflags "${GOBUILD_LDFLAGS} -X ${VERSION_VAR}=${APP_VER}" -GB := gb + +# cross compile defs +CC_BUILD_ARCHES = darwin/amd64 freebsd/amd64 linux/amd64 +CC_OUTPUT_TPL := ${BUILDDIR}/bin/{{.Dir}}.{{.OS}}-{{.Arch}} + +# error messages +GOX_ERR_MSG = 'gox' command not found. +GOX_INSTALL_MSG = try 'go get github.com/mitchellh/gox' define HELP_OUTPUT Available targets: @@ -20,7 +31,6 @@ Available targets: all build binaries and man pages test run tests cover run tests with cover output - build-setup fetch dependencies build build all binaries man build all man pages tar build release tarball @@ -34,31 +44,31 @@ help: @echo "$$HELP_OUTPUT" clean: - @rm -rf "${BUILDDIR}/bin" - @rm -rf "${BUILDDIR}/pkg" - @rm -rf "${BUILDDIR}/tar" - @rm -rf "${BUILDDIR}/man/"*.[1-9] - -build-setup: - @go get github.com/constabulary/gb/... + @rm -rf "${BUILDDIR}" build: + @[ -d "${BUILDDIR}/bin" ] || mkdir -p "${BUILDDIR}/bin" @echo "Building..." - @${GB} build ${GOBUILD_FLAGS} ... + @echo "...go-camo..." + @env CGO_ENABLED=0 go build ${GOBUILD_FLAGS} -o "${BUILDDIR}/bin/go-camo" . + @echo "...url-tool..." + @env CGO_ENABLED=0 go build ${GOBUILD_FLAGS} -o "${BUILDDIR}/bin/url-tool" ./url-tool + @echo "done!" test: @echo "Running tests..." - @${GB} test ${GOTEST_FLAGS} ... + @go test ${GOTEST_FLAGS} ./... generate: @echo "Running generate..." - @${GB} generate + @go generate cover: @echo "Running tests with coverage..." - @${GB} test -cover ${GOTEST_FLAGS} ... + @go test -cover ${GOTEST_FLAGS} ./... ${BUILDDIR}/man/%: man/%.mdoc + @[ -d "${BUILDDIR}/man" ] || mkdir -p "${BUILDDIR}/man" @cat $< | sed -E "s#.Os (.*) VERSION#.Os \1 ${APP_VER}#" > $@ man: $(patsubst man/%.mdoc,${BUILDDIR}/man/%,$(wildcard man/*.1.mdoc)) @@ -67,28 +77,41 @@ tar: all @echo "Building tar..." @mkdir -p ${TARBUILDDIR}/${APP_NAME}-${APP_VER}/bin @mkdir -p ${TARBUILDDIR}/${APP_NAME}-${APP_VER}/man - @cp ${BUILDDIR}/bin/${APP_NAME}-netgo ${TARBUILDDIR}/${APP_NAME}-${APP_VER}/bin/${APP_NAME} - @cp ${BUILDDIR}/bin/url-tool-netgo ${TARBUILDDIR}/${APP_NAME}-${APP_VER}/bin/url-tool + @cp ${BUILDDIR}/bin/${APP_NAME} ${TARBUILDDIR}/${APP_NAME}-${APP_VER}/bin/${APP_NAME} + @cp ${BUILDDIR}/bin/url-tool ${TARBUILDDIR}/${APP_NAME}-${APP_VER}/bin/url-tool @cp ${BUILDDIR}/man/*.[1-9] ${TARBUILDDIR}/${APP_NAME}-${APP_VER}/man/ @tar -C ${TARBUILDDIR} -czf ${TARBUILDDIR}/${APP_NAME}-${APP_VER}.${GOVER}.${OS}-${ARCH}.tar.gz ${APP_NAME}-${APP_VER} + @rm -rf "${TARBUILDDIR}/${APP_NAME}-${APP_VER}" cross-tar: man - @echo "Making tar for ${APP_NAME}:darwin.amd64" - @env GOOS=darwin GOARCH=amd64 ${GB} build ${GOBUILD_FLAGS} ... - @env GOOS=freebsd GOARCH=amd64 ${GB} build ${GOBUILD_FLAGS} ... - @env GOOS=linux GOARCH=amd64 ${GB} build ${GOBUILD_FLAGS} ... - - @(for x in darwin-amd64 freebsd-amd64 linux-amd64; do \ - echo "Making tar for ${APP_NAME}.$${x}"; \ + $(if $(shell type -p gox),,$(error ${GOX_ERR_MSG} ${GOX_INSTALL_MSG})) + + @echo "Building (cross-compile: ${CC_BUILD_ARCHES})..." + @echo "...go-camo..." + @env gox -output="${CC_OUTPUT_TPL}" -osarch="${CC_BUILD_ARCHES}" \ + ${GOBUILD_FLAGS} . + @echo + + @echo "...url-tool..." + @env gox -output="${CC_OUTPUT_TPL}" -osarch="${CC_BUILD_ARCHES}" \ + ${GOBUILD_FLAGS} ./url-tool + @echo + + @echo "...creating tar files..." + @(for x in $(subst /,-,${CC_BUILD_ARCHES}); do \ + echo "making tar for ${APP_NAME}.$${x}"; \ XDIR="${GOVER}.$${x}"; \ - mkdir -p ${TARBUILDDIR}/$${XDIR}/${APP_NAME}-${APP_VER}/bin/; \ - mkdir -p ${TARBUILDDIR}/$${XDIR}/${APP_NAME}-${APP_VER}/man/; \ - cp bin/${APP_NAME}-$${x}-netgo ${TARBUILDDIR}/$${XDIR}/${APP_NAME}-${APP_VER}/bin/${APP_NAME}; \ - cp bin/url-tool-$${x}-netgo ${TARBUILDDIR}/$${XDIR}/${APP_NAME}-${APP_VER}/bin/url-tool; \ - cp ${BUILDDIR}/man/*.[1-9] ${TARBUILDDIR}/$${XDIR}/${APP_NAME}-${APP_VER}/man/; \ + ODIR="${TARBUILDDIR}/$${XDIR}/${APP_NAME}-${APP_VER}"; \ + mkdir -p $${ODIR}/{bin,man}/; \ + cp ${BUILDDIR}/bin/${APP_NAME}.$${x} $${ODIR}/bin/${APP_NAME}; \ + cp ${BUILDDIR}/bin/url-tool.$${x} $${ODIR}/bin/url-tool; \ + cp ${BUILDDIR}/man/*.[1-9] $${ODIR}/man/; \ tar -C ${TARBUILDDIR}/$${XDIR} -czf ${TARBUILDDIR}/${APP_NAME}-${APP_VER}.$${XDIR}.tar.gz ${APP_NAME}-${APP_VER}; \ + rm -rf "${TARBUILDDIR}/$${XDIR}/"; \ done) + @echo "done!" + release-sign: @echo "signing release tarballs" @(cd tar; shasum -a 256 go-camo-*.tar.gz > SHA256; \ diff --git a/README.md b/README.md index fd183af..297c401 100644 --- a/README.md +++ b/README.md @@ -118,12 +118,27 @@ Extract, and copy files to desired locations. Building requires: -* git * make -* go (version 1.8 recommended) +* git +* go (latest version recommended. At least version >= 1.9) + +Additionally required, if cross compiling: + +* [gox](https://github.com/mitchellh/gox) Building: +First, make sure you check out the repository into the proper location +in your GOPATH. This can be done manually, or with `go get`. + +``` +$ export GOPATH=/tmp/go +$ go get -d github.com/cactus/go-camo +$ cd $GOPATH/src/github.com/cactus/go-camo +``` + +Once that is done, you are ready to build! + ```text # show make targets $ make @@ -133,15 +148,11 @@ Available targets: all build binaries and man pages test run tests cover run tests with cover output - build-setup fetch dependencies build build all man build all man pages tar build release tarball cross-tar cross compile and build release tarballs -# fetch vendor dependencies -$ make build-setup - # build all binaries and man pages # strips debug symbols by default $ make all @@ -150,12 +161,6 @@ $ make all $ make all GOBUILD_LDFLAGS="" ``` -By default, Go-Camo builds with `-tags netgo`. However, for Go versions -older than 1.5, this may not result in Go-Camo using the netgo resolver unless -your Go stdlib is also compiled with `-tags netgo`. For this reason, it is -required to build with at least go-1.5. Building with the latest Go version is -recommended. - ## Running ```text diff --git a/src/go-camo/camo/encoding/url.go b/camo/encoding/url.go similarity index 100% rename from src/go-camo/camo/encoding/url.go rename to camo/encoding/url.go diff --git a/src/go-camo/camo/encoding/url_test.go b/camo/encoding/url_test.go similarity index 100% rename from src/go-camo/camo/encoding/url_test.go rename to camo/encoding/url_test.go diff --git a/src/go-camo/camo/example_proxymetrics_test.go b/camo/example_proxymetrics_test.go similarity index 85% rename from src/go-camo/camo/example_proxymetrics_test.go rename to camo/example_proxymetrics_test.go index 17f022a..a892a14 100644 --- a/src/go-camo/camo/example_proxymetrics_test.go +++ b/camo/example_proxymetrics_test.go @@ -8,8 +8,8 @@ import ( "fmt" "os" - "go-camo/camo" - "go-camo/stats" + "github.com/cactus/go-camo/camo" + "github.com/cactus/go-camo/stats" ) func ExampleProxyMetrics() { diff --git a/src/go-camo/camo/misc.go b/camo/misc.go similarity index 100% rename from src/go-camo/camo/misc.go rename to camo/misc.go diff --git a/src/go-camo/camo/proxy.go b/camo/proxy.go similarity index 99% rename from src/go-camo/camo/proxy.go rename to camo/proxy.go index 490fa6e..7a6012f 100644 --- a/src/go-camo/camo/proxy.go +++ b/camo/proxy.go @@ -16,7 +16,7 @@ import ( "strings" "time" - "go-camo/camo/encoding" + "github.com/cactus/go-camo/camo/encoding" "github.com/cactus/mlog" ) diff --git a/src/go-camo/camo/proxy_test.go b/camo/proxy_test.go similarity index 99% rename from src/go-camo/camo/proxy_test.go rename to camo/proxy_test.go index ab2656f..2322ba6 100644 --- a/src/go-camo/camo/proxy_test.go +++ b/camo/proxy_test.go @@ -11,8 +11,8 @@ import ( "testing" "time" - "go-camo/camo/encoding" - "go-camo/router" + "github.com/cactus/go-camo/camo/encoding" + "github.com/cactus/go-camo/router" "github.com/stretchr/testify/assert" ) diff --git a/src/go-camo/camo/vars.go b/camo/vars.go similarity index 100% rename from src/go-camo/camo/vars.go rename to camo/vars.go diff --git a/src/go-camo/main.go b/main.go similarity index 96% rename from src/go-camo/main.go rename to main.go index 7dc3b7b..2748fdb 100644 --- a/src/go-camo/main.go +++ b/main.go @@ -5,7 +5,7 @@ // go-camo daemon (go-camod) package main -//go:generate go run ../../tools/genversion.go -pkg $GOPACKAGE -input ../../DEPS.md -output version_info_generated.go +//go:generate go run tools/genversion.go -pkg $GOPACKAGE -input DEPS.md -output main_vers_gen.go import ( "fmt" @@ -17,9 +17,9 @@ import ( "strings" "time" - "go-camo/camo" - "go-camo/router" - "go-camo/stats" + "github.com/cactus/go-camo/camo" + "github.com/cactus/go-camo/router" + "github.com/cactus/go-camo/stats" "github.com/cactus/mlog" flags "github.com/jessevdk/go-flags" diff --git a/src/go-camo/version_info_generated.go b/main_vers_gen.go similarity index 75% rename from src/go-camo/version_info_generated.go rename to main_vers_gen.go index adedb30..041ab92 100644 --- a/src/go-camo/version_info_generated.go +++ b/main_vers_gen.go @@ -14,11 +14,8 @@ Portions of this software utilize third party libraries: * Runtime dependencies: ├── https://github.com/cactus/mlog (MIT License) - ├── https://github.com/cactus/tai64 (MIT License) └── https://github.com/jessevdk/go-flags (BSD License) * Test only dependencies: └── https://github.com/stretchr/testify/assert (MIT License) - ├── https://github.com/davecgh/go-spew (ISC License) - └── https://github.com/pmezard/go-difflib (BSD License) ` \ No newline at end of file diff --git a/src/go-camo/router/httpdate.go b/router/httpdate.go similarity index 100% rename from src/go-camo/router/httpdate.go rename to router/httpdate.go diff --git a/src/go-camo/router/httpdate_test.go b/router/httpdate_test.go similarity index 100% rename from src/go-camo/router/httpdate_test.go rename to router/httpdate_test.go diff --git a/src/go-camo/router/router.go b/router/router.go similarity index 100% rename from src/go-camo/router/router.go rename to router/router.go diff --git a/src/go-camo/stats/stats.go b/stats/stats.go similarity index 100% rename from src/go-camo/stats/stats.go rename to stats/stats.go diff --git a/src/go-camo/stats/stats_test.go b/stats/stats_test.go similarity index 100% rename from src/go-camo/stats/stats_test.go rename to stats/stats_test.go diff --git a/src/go-camo/url-tool/main.go b/url-tool/main.go similarity index 98% rename from src/go-camo/url-tool/main.go rename to url-tool/main.go index 54f51ff..62cbbf6 100644 --- a/src/go-camo/url-tool/main.go +++ b/url-tool/main.go @@ -12,7 +12,7 @@ import ( "os" "strings" - "go-camo/camo/encoding" + "github.com/cactus/go-camo/camo/encoding" flags "github.com/jessevdk/go-flags" ) diff --git a/vendor/github.com/cactus/mlog/.gitignore b/vendor/github.com/cactus/mlog/.gitignore new file mode 100644 index 0000000..9e13edb --- /dev/null +++ b/vendor/github.com/cactus/mlog/.gitignore @@ -0,0 +1,4 @@ +/bin +/pkg +/vendor/src +*.py[co] diff --git a/vendor/github.com/cactus/mlog/.travis.yml b/vendor/github.com/cactus/mlog/.travis.yml new file mode 100644 index 0000000..a1a6cb1 --- /dev/null +++ b/vendor/github.com/cactus/mlog/.travis.yml @@ -0,0 +1,7 @@ +language: go +sudo: false +script: go test -v -cpu=1,2 ./... +go: + - 1.4 + - 1.5 + - 1.6 diff --git a/vendor/src/github.com/cactus/mlog/CHANGELOG.md b/vendor/github.com/cactus/mlog/CHANGELOG.md similarity index 77% rename from vendor/src/github.com/cactus/mlog/CHANGELOG.md rename to vendor/github.com/cactus/mlog/CHANGELOG.md index 03a9f3f..725d2ff 100644 --- a/vendor/src/github.com/cactus/mlog/CHANGELOG.md +++ b/vendor/github.com/cactus/mlog/CHANGELOG.md @@ -2,7 +2,6 @@ Changelog ========= ## HEAD -* add panic methods ## 1.0.0 2016-05-08 * initial version tag diff --git a/vendor/src/github.com/cactus/mlog/LICENSE.md b/vendor/github.com/cactus/mlog/LICENSE.md similarity index 100% rename from vendor/src/github.com/cactus/mlog/LICENSE.md rename to vendor/github.com/cactus/mlog/LICENSE.md diff --git a/vendor/src/github.com/cactus/mlog/README.md b/vendor/github.com/cactus/mlog/README.md similarity index 69% rename from vendor/src/github.com/cactus/mlog/README.md rename to vendor/github.com/cactus/mlog/README.md index 910fb7a..3d3907b 100644 --- a/vendor/src/github.com/cactus/mlog/README.md +++ b/vendor/github.com/cactus/mlog/README.md @@ -3,7 +3,6 @@ mlog [![Build Status](https://travis-ci.org/cactus/mlog.png?branch=master)](https://travis-ci.org/cactus/mlog) [![GoDoc](https://godoc.org/github.com/cactus/mlog?status.png)](https://godoc.org/github.com/cactus/mlog) -[![Go Report Card](https://goreportcard.com/badge/cactus/mlog)](https://goreportcard.com/report/cactus/mlog) ## About @@ -13,8 +12,8 @@ mlog only has 3 logging levels: Debug, Info, and Fatal. ### Why only 3 levels? -Dave Cheney [wrote a great post][1], that made me rethink my own approach to -logging, and prompted me to start writing mlog. +Dave Cheney [wrote a great post][1], that made me think more about logging, and +prompted me to start writing mlog. ### How does it work? @@ -61,7 +60,7 @@ func main() { }, ) - mlog.Infom("this is also a log with more data", thing) + mlog.Info("this is a log with more data", thing) mlog.Debug("this won't print") @@ -95,15 +94,15 @@ func main() { Output: ``` -time="2016-04-29T19:59:11.474362716-07:00" level="I" msg="this is a log" -time="2016-04-29T19:59:11.474506079-07:00" level="I" msg="this is a log with more data" interesting="data" something="42" -time="2016-04-29T19:59:11.474523514-07:00" level="I" msg="this is also a log with more data" this-works?="as long as it is a mlog.Map" what‽="yup" -time="2016-04-29T19:59:11.474535676-07:00" msg="now this will print!" -time="2016-04-29T19:59:11.474542467-07:00" msg="can it print?" how_fancy="[118 101 114 121 33]" this_too="if fmt.Print can print it!" -time="2016-04-29T19:59:11.474551625-07:00" msg="a printf style debug log: here!" -time="2016-04-29T19:59:11.474578991-07:00" msg="a printf style info log: here!" -{"time": "2016-04-29T19:59:11.474583762-07:00", "msg": "something" "extra": {"one": "two", "three": "3"}} -{"time": "2016-04-29T19:59:11.474604928-07:00", "msg": "time for a nap" "extra": {"cleanup": "false"}} +time="2016-04-29T19:59:11-07:00" level="I" msg="this is a log" +time="2016-04-29T19:59:11-07:00" level="I" msg="this is a log with more data" interesting="data" something="42" +time="2016-04-29T19:59:11-07:00" level="I" msg="this is a log with more datawhat‽="yup" this-works?="as long as it is a mlog.Map"" +time="2016-04-29T19:59:11-07:00" msg="now this will print!" +time="2016-04-29T19:59:11-07:00" msg="can it print?" this_too="if fmt.Print can print it!" how_fancy="[118 101 114 121 33]" +time="2016-04-29T19:59:11-07:00" msg="a printf style debug log: here!" +time="2016-04-29T19:59:11-07:00" msg="a printf style info log: here!" +{"time": "2016-04-29T19:59:11-07:00", "msg": "something" "extra": {"one": "two", "three": "3"}} +{"time": "2016-04-29T19:59:11-07:00", "msg": "time for a nap" "extra": {"cleanup": "false"}} exit status 1 ``` diff --git a/vendor/src/github.com/cactus/mlog/default_logger.go b/vendor/github.com/cactus/mlog/default_logger.go similarity index 84% rename from vendor/src/github.com/cactus/mlog/default_logger.go rename to vendor/github.com/cactus/mlog/default_logger.go index 9dad10a..1f86d29 100644 --- a/vendor/src/github.com/cactus/mlog/default_logger.go +++ b/vendor/github.com/cactus/mlog/default_logger.go @@ -47,11 +47,6 @@ func Fatalm(message string, v Map) { os.Exit(1) } -// Panicm logs to the default Logger. See Logger.Panicm -func Panicm(message string, v Map) { - DefaultLogger.Panicm(message, v) -} - // Debugf logs to the default Logger. See Logger.Debugf func Debugf(format string, v ...interface{}) { if DefaultLogger.HasDebug() { @@ -75,12 +70,6 @@ func Fatalf(format string, v ...interface{}) { os.Exit(1) } -// Panicf is equivalent to Printf() followed by a call to panic(). -// See Logger.Panicf -func Panicf(format string, v ...interface{}) { - DefaultLogger.Panicf(format, v...) -} - // Debug logs to the default Logger. See Logger.Debug func Debug(v ...interface{}) { if DefaultLogger.HasDebug() { @@ -103,9 +92,3 @@ func Fatal(v ...interface{}) { DefaultLogger.Emit(1, fmt.Sprint(v...), nil) os.Exit(1) } - -// Panic is equivalent to Print() followed by a call to panic(). -// See Logger.Panic -func Panic(v ...interface{}) { - DefaultLogger.Panic(v...) -} diff --git a/vendor/src/github.com/cactus/mlog/doc.go b/vendor/github.com/cactus/mlog/doc.go similarity index 100% rename from vendor/src/github.com/cactus/mlog/doc.go rename to vendor/github.com/cactus/mlog/doc.go diff --git a/vendor/src/github.com/cactus/mlog/flagset.go b/vendor/github.com/cactus/mlog/flagset.go similarity index 79% rename from vendor/src/github.com/cactus/mlog/flagset.go rename to vendor/github.com/cactus/mlog/flagset.go index 9c51b2b..941fe5f 100644 --- a/vendor/src/github.com/cactus/mlog/flagset.go +++ b/vendor/github.com/cactus/mlog/flagset.go @@ -14,9 +14,12 @@ const ( // Ltimestamp specifies to log the date+time stamp Ltimestamp FlagSet = 1 << iota - // Ltai64n specifies to use tia64n timestamps - // overrides Ltimestamp. - Ltai64n + // Lmicroseconds specifies to use microsecond timestamp granularity in + // Ltimestamp. + Lmicroseconds + // Lnanoseconds specifies to use nanosecond timestamp granularity in + // Ltimestamp. overrides Lmicroseconds. + Lnanoseconds // Llevel specifies to log message level. Llevel // Llongfile specifies to log file path and line number: /a/b/c/d.go:23 @@ -33,13 +36,14 @@ const ( ) var flagNames = map[FlagSet]string{ - Ltimestamp: "Ltimestamp", - Ltai64n: "Ltai64n", - Llevel: "Llevel", - Llongfile: "Llongfile", - Lshortfile: "Lshortfile", - Lsort: "Lsort", - Ldebug: "Ldebug", + Ltimestamp: "Ltimestamp", + Lmicroseconds: "Lmicroseconds", + Lnanoseconds: "Lnanoseconds", + Llevel: "Llevel", + Llongfile: "Llongfile", + Lshortfile: "Lshortfile", + Lsort: "Lsort", + Ldebug: "Ldebug", } // FlagSet defines the output formatting flags (bitfield) type, which define diff --git a/vendor/src/github.com/cactus/mlog/flagset_test.go b/vendor/github.com/cactus/mlog/flagset_test.go similarity index 100% rename from vendor/src/github.com/cactus/mlog/flagset_test.go rename to vendor/github.com/cactus/mlog/flagset_test.go diff --git a/vendor/src/github.com/cactus/mlog/formatwriter_json.go b/vendor/github.com/cactus/mlog/formatwriter_json.go similarity index 61% rename from vendor/src/github.com/cactus/mlog/formatwriter_json.go rename to vendor/github.com/cactus/mlog/formatwriter_json.go index b06d5c5..91b4e2a 100644 --- a/vendor/src/github.com/cactus/mlog/formatwriter_json.go +++ b/vendor/github.com/cactus/mlog/formatwriter_json.go @@ -1,14 +1,12 @@ package mlog import ( + "encoding/json" "fmt" "runtime" "time" - "unicode/utf8" ) -const hex = "0123456789abcdef" - // FormatWriterJSON writes a json structured log line. // Example: // {"time": "2016-04-29T20:49:12Z", "level": "I", "msg": "this is a log"} @@ -23,14 +21,10 @@ func (j *FormatWriterJSON) Emit(logger *Logger, level int, message string, extra sb.WriteByte('{') // if time is being logged, handle time as soon as possible - if flags&(Ltimestamp|Ltai64n) != 0 { + if flags&Ltimestamp != 0 { t := time.Now() sb.WriteString(`"time": "`) - if flags&Ltai64n != 0 { - writeTimeTAI64N(sb, &t, flags) - } else { - writeTime(sb, &t, flags) - } + writeTime(sb, &t, flags) sb.WriteString(`", `) } @@ -72,13 +66,20 @@ func (j *FormatWriterJSON) Emit(logger *Logger, level int, message string, extra sb.WriteString(`", `) } - sb.WriteString(`"msg": "`) - encodeStringJSON(sb, message) - sb.WriteByte('"') + sb.WriteString(`"msg": `) + // as a kindness, strip any newlines off the end of the string + for i := len(message) - 1; i > 0; i-- { + if message[i] == '\n' { + message = message[:i] + } else { + break + } + } + encodeString(sb, message) if extra != nil && len(extra) > 0 { - sb.WriteString(`, "extra": {`) - encodeLogMapJSON(sb, extra) + sb.WriteString(` "extra": {`) + jsonEncodeLogMap(sb, extra) sb.WriteByte('}') } @@ -87,7 +88,7 @@ func (j *FormatWriterJSON) Emit(logger *Logger, level int, message string, extra sb.WriteTo(logger) } -func encodeLogMapJSON(w byteSliceWriter, m Map) { +func jsonEncodeLogMap(w sliceWriter, m Map) { first := true for k, v := range m { if first { @@ -96,24 +97,45 @@ func encodeLogMapJSON(w byteSliceWriter, m Map) { w.WriteString(`, `) } - w.WriteByte('"') - encodeStringJSON(w, k) - w.WriteString(`": "`) - encodeStringJSON(w, fmt.Sprint(v)) - w.WriteByte('"') + encodeString(w, k) + w.WriteString(`: `) + encodeString(w, fmt.Sprint(v)) } } +var hex = "0123456789abcdef" + +func encodeString(e sliceWriter, s string) { + sb := bufPool.Get() + defer bufPool.Put(sb) + encoder := json.NewEncoder(sb) + encoder.Encode(s) + b := sb.Bytes() + for i := len(b) - 1; i > 0; i-- { + if b[i] == '\n' { + b = b[:i] + } else { + break + } + } + + e.Write(b) +} + +/* // modified from Go stdlib: encoding/json/encode.go:787-862 (approx) -func encodeStringJSON(e byteSliceWriter, s string) { +func encodeString(e sliceWriter, s string) { + e.WriteByte('"') + start := 0 for i := 0; i < len(s); { if b := s[i]; b < utf8.RuneSelf { - i++ - if 0x20 <= b && b != '\\' && b != '"' { - e.WriteByte(b) + if 0x20 <= b && b != '\\' && b != '"' && b != '<' && b != '>' && b != '&' { + i++ continue } - + if start < i { + e.WriteString(s[start:i]) + } switch b { case '\\', '"': e.WriteByte('\\') @@ -128,35 +150,50 @@ func encodeStringJSON(e byteSliceWriter, s string) { e.WriteByte('\\') e.WriteByte('t') default: - // This encodes bytes < 0x20 except for escapes above + // This encodes bytes < 0x20 except for \n and \r, + // as well as <, > and &. The latter are escaped because they + // can lead to security holes when user-controlled strings + // are rendered into JSON and served to some browsers. e.WriteString(`\u00`) e.WriteByte(hex[b>>4]) e.WriteByte(hex[b&0xF]) } + i++ + start = i continue } - c, size := utf8.DecodeRuneInString(s[i:]) if c == utf8.RuneError && size == 1 { + if start < i { + e.WriteString(s[start:i]) + } e.WriteString(`\ufffd`) - i++ + i += size + start = i continue } - // U+2028 is LINE SEPARATOR. // U+2029 is PARAGRAPH SEPARATOR. // They are both technically valid characters in JSON strings, // but don't work in JSONP, which has to be evaluated as JavaScript, // and can lead to security holes there. It is valid JSON to - // escape them, so do so unconditionally. - // See http://timelessrepo.com/json-isnt-a-javascript-subset + // escape them, so we do so unconditionally. + // See http://timelessrepo.com/json-isnt-a-javascript-subset for discussion. if c == '\u2028' || c == '\u2029' { + if start < i { + e.WriteString(s[start:i]) + } e.WriteString(`\u202`) e.WriteByte(hex[c&0xF]) i += size + start = i continue } - e.WriteString(s[i : i+size]) i += size } + if start < len(s) { + e.WriteString(s[start:]) + } + e.WriteByte('"') } +*/ diff --git a/vendor/src/github.com/cactus/mlog/formatwriter_json_bench_test.go b/vendor/github.com/cactus/mlog/formatwriter_json_bench_test.go similarity index 89% rename from vendor/src/github.com/cactus/mlog/formatwriter_json_bench_test.go rename to vendor/github.com/cactus/mlog/formatwriter_json_bench_test.go index f064af9..ac630ed 100644 --- a/vendor/src/github.com/cactus/mlog/formatwriter_json_bench_test.go +++ b/vendor/github.com/cactus/mlog/formatwriter_json_bench_test.go @@ -36,15 +36,6 @@ func BenchmarkFormatWriterJSONTime(b *testing.B) { } } -func BenchmarkFormatWriterJSONTimeTAI64N(b *testing.B) { - logger := New(ioutil.Discard, Ltai64n) - logWriter := &FormatWriterJSON{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - logWriter.Emit(logger, 0, "this is a test", nil) - } -} - func BenchmarkFormatWriterJSONShortfile(b *testing.B) { logger := New(ioutil.Discard, Lshortfile) logWriter := &FormatWriterJSON{} diff --git a/vendor/src/github.com/cactus/mlog/formatwriter_plain.go b/vendor/github.com/cactus/mlog/formatwriter_plain.go similarity index 59% rename from vendor/src/github.com/cactus/mlog/formatwriter_plain.go rename to vendor/github.com/cactus/mlog/formatwriter_plain.go index 12f66ca..3704263 100644 --- a/vendor/src/github.com/cactus/mlog/formatwriter_plain.go +++ b/vendor/github.com/cactus/mlog/formatwriter_plain.go @@ -3,7 +3,6 @@ package mlog import ( "runtime" "time" - "unicode/utf8" ) // FormatWriterPlain a plain text structured log line. @@ -19,13 +18,9 @@ func (l *FormatWriterPlain) Emit(logger *Logger, level int, message string, extr flags := logger.Flags() // if time is being logged, handle time as soon as possible - if flags&(Ltimestamp|Ltai64n) != 0 { + if flags&Ltimestamp != 0 { t := time.Now() - if flags&Ltai64n != 0 { - writeTimeTAI64N(sb, &t, flags) - } else { - writeTime(sb, &t, flags) - } + writeTime(sb, &t, flags) sb.WriteByte(' ') } @@ -36,7 +31,7 @@ func (l *FormatWriterPlain) Emit(logger *Logger, level int, message string, extr case 1: sb.WriteString(`FATAL `) default: - sb.WriteString(`INFO `) + sb.WriteString(`INFO `) } } @@ -64,7 +59,15 @@ func (l *FormatWriterPlain) Emit(logger *Logger, level int, message string, extr sb.WriteByte(' ') } - encodeStringPlain(sb, message) + // as a kindness, strip any newlines off the end of the string + for i := len(message) - 1; i > 0; i-- { + if message[i] == '\n' { + message = message[:i] + } else { + break + } + } + sb.WriteString(message) if extra != nil && len(extra) > 0 { sb.WriteByte(' ') @@ -78,41 +81,3 @@ func (l *FormatWriterPlain) Emit(logger *Logger, level int, message string, extr sb.WriteByte('\n') sb.WriteTo(logger) } - -// modified from Go stdlib: encoding/json/encode.go:787-862 (approx) -func encodeStringPlain(e byteSliceWriter, s string) { - for i := 0; i < len(s); { - if b := s[i]; b < utf8.RuneSelf { - i++ - if 0x20 <= b { - e.WriteByte(b) - continue - } - - switch b { - case '\n': - e.WriteByte('\\') - e.WriteByte('n') - case '\r': - e.WriteByte('\\') - e.WriteByte('r') - case '\t': - e.WriteByte('\\') - e.WriteByte('t') - default: - e.WriteByte(b) - } - continue - } - - c, size := utf8.DecodeRuneInString(s[i:]) - if c == utf8.RuneError && size == 1 { - e.WriteString(`\ufffd`) - i++ - continue - } - - e.WriteString(s[i : i+size]) - i += size - } -} diff --git a/vendor/src/github.com/cactus/mlog/formatwriter_plain_bench_test.go b/vendor/github.com/cactus/mlog/formatwriter_plain_bench_test.go similarity index 90% rename from vendor/src/github.com/cactus/mlog/formatwriter_plain_bench_test.go rename to vendor/github.com/cactus/mlog/formatwriter_plain_bench_test.go index 8aa3e35..3589d4f 100644 --- a/vendor/src/github.com/cactus/mlog/formatwriter_plain_bench_test.go +++ b/vendor/github.com/cactus/mlog/formatwriter_plain_bench_test.go @@ -36,15 +36,6 @@ func BenchmarkFormatWriterPlainTime(b *testing.B) { } } -func BenchmarkFormatWriterPlainTimeTAI64N(b *testing.B) { - logger := New(ioutil.Discard, Ltai64n) - logWriter := &FormatWriterPlain{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - logWriter.Emit(logger, 0, "this is a test", nil) - } -} - func BenchmarkFormatWriterPlainShortfile(b *testing.B) { logger := New(ioutil.Discard, Lshortfile) logWriter := &FormatWriterPlain{} diff --git a/vendor/src/github.com/cactus/mlog/formatwriter_structured.go b/vendor/github.com/cactus/mlog/formatwriter_structured.go similarity index 61% rename from vendor/src/github.com/cactus/mlog/formatwriter_structured.go rename to vendor/github.com/cactus/mlog/formatwriter_structured.go index 3682b88..a51da1e 100644 --- a/vendor/src/github.com/cactus/mlog/formatwriter_structured.go +++ b/vendor/github.com/cactus/mlog/formatwriter_structured.go @@ -3,7 +3,6 @@ package mlog import ( "runtime" "time" - "unicode/utf8" ) // FormatWriterStructured writes a plain text structured log line. @@ -19,14 +18,10 @@ func (l *FormatWriterStructured) Emit(logger *Logger, level int, message string, flags := logger.Flags() // if time is being logged, handle time as soon as possible - if flags&(Ltimestamp|Ltai64n) != 0 { + if flags&Ltimestamp != 0 { t := time.Now() sb.WriteString(`time="`) - if flags&Ltai64n != 0 { - writeTimeTAI64N(sb, &t, flags) - } else { - writeTime(sb, &t, flags) - } + writeTime(sb, &t, flags) sb.WriteString(`" `) } @@ -69,7 +64,15 @@ func (l *FormatWriterStructured) Emit(logger *Logger, level int, message string, } sb.WriteString(`msg="`) - encodeStringStructured(sb, message) + // as a kindness, strip any newlines off the end of the string + for i := len(message) - 1; i > 0; i-- { + if message[i] == '\n' { + message = message[:i] + } else { + break + } + } + sb.WriteString(message) sb.WriteByte('"') if extra != nil && len(extra) > 0 { @@ -84,44 +87,3 @@ func (l *FormatWriterStructured) Emit(logger *Logger, level int, message string, sb.WriteByte('\n') sb.WriteTo(logger) } - -// modified from Go stdlib: encoding/json/encode.go:787-862 (approx) -func encodeStringStructured(e byteSliceWriter, s string) { - for i := 0; i < len(s); { - if b := s[i]; b < utf8.RuneSelf { - i++ - if 0x20 <= b && b != '"' { - e.WriteByte(b) - continue - } - - switch b { - case '"': - e.WriteByte('\\') - e.WriteByte(b) - case '\n': - e.WriteByte('\\') - e.WriteByte('n') - case '\r': - e.WriteByte('\\') - e.WriteByte('r') - case '\t': - e.WriteByte('\\') - e.WriteByte('t') - default: - e.WriteByte(b) - } - continue - } - - c, size := utf8.DecodeRuneInString(s[i:]) - if c == utf8.RuneError && size == 1 { - e.WriteString(`\ufffd`) - i++ - continue - } - - e.WriteString(s[i : i+size]) - i += size - } -} diff --git a/vendor/src/github.com/cactus/mlog/formatwriter_structured_bench_test.go b/vendor/github.com/cactus/mlog/formatwriter_structured_bench_test.go similarity index 90% rename from vendor/src/github.com/cactus/mlog/formatwriter_structured_bench_test.go rename to vendor/github.com/cactus/mlog/formatwriter_structured_bench_test.go index 8f54b03..0718e56 100644 --- a/vendor/src/github.com/cactus/mlog/formatwriter_structured_bench_test.go +++ b/vendor/github.com/cactus/mlog/formatwriter_structured_bench_test.go @@ -36,15 +36,6 @@ func BenchmarkFormatWriterStructuredTime(b *testing.B) { } } -func BenchmarkFormatWriterStructuredTimeTAI64N(b *testing.B) { - logger := New(ioutil.Discard, Ltai64n) - logWriter := &FormatWriterStructured{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - logWriter.Emit(logger, 0, "this is a test", nil) - } -} - func BenchmarkFormatWriterStructuredShortfile(b *testing.B) { logger := New(ioutil.Discard, Lshortfile) logWriter := &FormatWriterStructured{} diff --git a/vendor/src/github.com/cactus/mlog/logger.go b/vendor/github.com/cactus/mlog/logger.go similarity index 85% rename from vendor/src/github.com/cactus/mlog/logger.go rename to vendor/github.com/cactus/mlog/logger.go index e5fe549..a3fdc96 100644 --- a/vendor/src/github.com/cactus/mlog/logger.go +++ b/vendor/github.com/cactus/mlog/logger.go @@ -45,7 +45,7 @@ func (l *Logger) SetEmitter(e Emitter) { l.e = e } -// Flags returns the current FlagSet +// Flags retuns the current FlagSet func (l *Logger) Flags() FlagSet { return FlagSet(atomic.LoadUint64(&l.flags)) } @@ -87,13 +87,6 @@ func (l *Logger) Fatalm(message string, v Map) { os.Exit(1) } -// Panicm logs message and any Map elements at level="fatal", then calls -// panic(). -func (l *Logger) Panicm(message string, v Map) { - l.Emit(1, message, v) - panic(message) -} - // Debugf formats and conditionally logs message at level="debug". // If the Logger does not have the Ldebug flag, nothing is logged. func (l *Logger) Debugf(format string, v ...interface{}) { @@ -119,14 +112,6 @@ func (l *Logger) Fatalf(format string, v ...interface{}) { os.Exit(1) } -// Panicf formats and logs message at level="fatal", then calls -// panic(). -func (l *Logger) Panicf(format string, v ...interface{}) { - s := fmt.Sprintf(format, v...) - l.Emit(1, s, nil) - panic(s) -} - // Debug conditionally logs message at level="debug". // If the Logger does not have the Ldebug flag, nothing is logged. func (l *Logger) Debug(v ...interface{}) { @@ -152,20 +137,12 @@ func (l *Logger) Fatal(v ...interface{}) { os.Exit(1) } -// Panic logs message at level="fatal", then calls -// panic(). -func (l *Logger) Panic(v ...interface{}) { - s := fmt.Sprint(v...) - l.Emit(1, s, nil) - panic(s) -} - // New creates a new Logger. func New(out io.Writer, flags FlagSet) *Logger { return NewFormatLogger(out, flags, &FormatWriterStructured{}) } -// NewFormatLogger creates a new Logger, using the specified Emitter. +// New creates a new Logger, using the specified Emitter. func NewFormatLogger(out io.Writer, flags FlagSet, e Emitter) *Logger { return &Logger{ out: out, diff --git a/vendor/src/github.com/cactus/mlog/logger_bench_test.go b/vendor/github.com/cactus/mlog/logger_bench_test.go similarity index 100% rename from vendor/src/github.com/cactus/mlog/logger_bench_test.go rename to vendor/github.com/cactus/mlog/logger_bench_test.go diff --git a/vendor/src/github.com/cactus/mlog/logger_test.go b/vendor/github.com/cactus/mlog/logger_test.go similarity index 70% rename from vendor/src/github.com/cactus/mlog/logger_test.go rename to vendor/github.com/cactus/mlog/logger_test.go index 488b9dd..21aca2b 100644 --- a/vendor/src/github.com/cactus/mlog/logger_test.go +++ b/vendor/github.com/cactus/mlog/logger_test.go @@ -18,15 +18,6 @@ import ( var update = flag.Bool("update", false, "update golden files") -func assertPanic(t *testing.T, f func()) { - defer func() { - if r := recover(); r == nil { - t.Errorf("The code did not panic") - } - }() - f() -} - func TestLoggerMsgs(t *testing.T) { var infoTests = map[string]struct { flags FlagSet @@ -103,7 +94,7 @@ func TestLoggerTimestamp(t *testing.T) { buf := &bytes.Buffer{} // test nanoseconds - logger := New(buf, Lstd) + logger := New(buf, Lstd|Lnanoseconds) tnow := time.Now() logger.Info("test this") ts := bytes.Split(buf.Bytes()[6:], []byte{'"'})[0] @@ -114,7 +105,7 @@ func TestLoggerTimestamp(t *testing.T) { buf.Truncate(0) // test microeconds - logger.SetFlags(Lstd) + logger.SetFlags(Lstd | Lmicroseconds) tnow = time.Now() logger.Info("test this") ts = bytes.Split(buf.Bytes()[6:], []byte{'"'})[0] @@ -133,56 +124,3 @@ func TestLoggerTimestamp(t *testing.T) { assert.Nil(t, err, "Failed to parse time from log") assert.WithinDuration(t, tnow, tlog, 2*time.Second, "Time not even close") } - -func TestPanics(t *testing.T) { - var infoTests = map[string]struct { - flags FlagSet - method string - message string - extra interface{} - }{ - "panic": {Llevel | Lsort, "panic", "test", nil}, - "panicf": {Llevel | Lsort, "panicf", "test: %d", 5}, - "panicm": {Llevel | Lsort, "panicm", "test", Map{"x": "y"}}, - } - - buf := &bytes.Buffer{} - logger := New(ioutil.Discard, Llevel|Lsort) - logger.out = buf - - for name, tt := range infoTests { - buf.Truncate(0) - logger.flags = uint64(tt.flags) - - switch tt.method { - case "panicm": - m, ok := tt.extra.(Map) - if !ok && tt.extra != nil { - t.Errorf("%s: failed type assertion", name) - continue - } - assertPanic(t, func() { - logger.Panicm(tt.message, m) - }) - case "panicf": - assertPanic(t, func() { - logger.Panicf(tt.message, tt.extra) - }) - case "panic": - assertPanic(t, func() { - logger.Panic(tt.message) - }) - default: - t.Errorf("%s: not sure what to do", name) - continue - } - - actual := buf.Bytes() - golden := filepath.Join("test-fixtures", fmt.Sprintf("test_logger_msgs.%s.golden", name)) - if *update { - ioutil.WriteFile(golden, actual, 0644) - } - expected, _ := ioutil.ReadFile(golden) - assert.Equal(t, string(expected), string(actual), "%s: did not match expectation", name) - } -} diff --git a/vendor/src/github.com/cactus/mlog/logmap.go b/vendor/github.com/cactus/mlog/logmap.go similarity index 96% rename from vendor/src/github.com/cactus/mlog/logmap.go rename to vendor/github.com/cactus/mlog/logmap.go index 76329b3..7fbafeb 100644 --- a/vendor/src/github.com/cactus/mlog/logmap.go +++ b/vendor/github.com/cactus/mlog/logmap.go @@ -24,7 +24,7 @@ func (m Map) Keys() []string { // unsortedWriteBuf writes an unsorted string representation of // the Map's key value pairs to w. -func (m Map) unsortedWriteBuf(w byteSliceWriter) { +func (m Map) unsortedWriteBuf(w sliceWriter) { // scratch buffer for intermediate writes buf := bufPool.Get() defer bufPool.Put(buf) @@ -77,7 +77,7 @@ func (m Map) unsortedWriteBuf(w byteSliceWriter) { // sortedWriteBuf writes a sorted string representation of // the Map's key value pairs to w. -func (m Map) sortedWriteBuf(w byteSliceWriter) { +func (m Map) sortedWriteBuf(w sliceWriter) { // scratch buffer for intermediate writes buf := bufPool.Get() defer bufPool.Put(buf) diff --git a/vendor/src/github.com/cactus/mlog/logmap_test.go b/vendor/github.com/cactus/mlog/logmap_test.go similarity index 94% rename from vendor/src/github.com/cactus/mlog/logmap_test.go rename to vendor/github.com/cactus/mlog/logmap_test.go index c9a49f4..a4b0af9 100644 --- a/vendor/src/github.com/cactus/mlog/logmap_test.go +++ b/vendor/github.com/cactus/mlog/logmap_test.go @@ -12,6 +12,7 @@ func (d *discardSliceWriter) WriteString(s string) (int, error) { return len(s), func (d *discardSliceWriter) Write(b []byte) (int, error) { return len(b), nil } func (d *discardSliceWriter) WriteByte(c byte) error { return nil } func (d *discardSliceWriter) Truncate(i int) {} +func (d *discardSliceWriter) AppendIntWidth(i, j int) {} func BenchmarkLogMapUnsortedWriteBuf(b *testing.B) { buf := &discardSliceWriter{} diff --git a/vendor/src/github.com/cactus/mlog/slicebuffer.go b/vendor/github.com/cactus/mlog/slicebuffer.go similarity index 68% rename from vendor/src/github.com/cactus/mlog/slicebuffer.go rename to vendor/github.com/cactus/mlog/slicebuffer.go index be187b9..cddc5ba 100644 --- a/vendor/src/github.com/cactus/mlog/slicebuffer.go +++ b/vendor/github.com/cactus/mlog/slicebuffer.go @@ -28,17 +28,12 @@ func (sp *sliceBufferPool) Put(c *sliceBuffer) { sp.Pool.Put(c) } -type byteSliceWriter interface { +type sliceWriter interface { Write([]byte) (int, error) WriteByte(byte) error WriteString(string) (int, error) - Truncate(int) -} - -type intSliceWriter interface { - byteSliceWriter AppendIntWidth(int, int) - AppendIntWidthHex(int64, int) + Truncate(int) } type sliceBuffer struct { @@ -69,34 +64,6 @@ func (sb *sliceBuffer) AppendIntWidth(i int, wid int) { } } -const hexdigits = "0123456789abcdefghijklmnopqrstuvwxyz" - -func (sb *sliceBuffer) AppendIntWidthHex(i int64, wid int) { - u := uint64(i) - - digits := 0 - b := uint64(16) - m := uintptr(b) - 1 - for u >= b { - sb.data = append(sb.data, hexdigits[uintptr(u)&m]) - u >>= 4 - digits++ - } - sb.data = append(sb.data, hexdigits[uintptr(u)]) - digits++ - - for j := wid - digits; j > 0; j-- { - sb.data = append(sb.data, '0') - digits++ - } - - // reverse to proper order - sblen := len(sb.data) - for i, j := sblen-digits, sblen-1; i < j; i, j = i+1, j-1 { - sb.data[i], sb.data[j] = sb.data[j], sb.data[i] - } -} - func (sb *sliceBuffer) Write(b []byte) (int, error) { sb.data = append(sb.data, b...) return len(b), nil @@ -112,9 +79,8 @@ func (sb *sliceBuffer) WriteString(s string) (int, error) { return len(s), nil } -func (sb *sliceBuffer) WriteTo(w io.Writer) (int64, error) { - n, err := w.Write(sb.data) - return int64(n), err +func (sb *sliceBuffer) WriteTo(w io.Writer) (int, error) { + return w.Write(sb.data) } func (sb *sliceBuffer) Bytes() []byte { diff --git a/vendor/src/github.com/cactus/mlog/test-fixtures/test_logger_msgs.debug1.golden b/vendor/github.com/cactus/mlog/test-fixtures/test_logger_msgs.debug1.golden similarity index 100% rename from vendor/src/github.com/cactus/mlog/test-fixtures/test_logger_msgs.debug1.golden rename to vendor/github.com/cactus/mlog/test-fixtures/test_logger_msgs.debug1.golden diff --git a/vendor/src/github.com/cactus/mlog/test-fixtures/test_logger_msgs.debug2.golden b/vendor/github.com/cactus/mlog/test-fixtures/test_logger_msgs.debug2.golden similarity index 100% rename from vendor/src/github.com/cactus/mlog/test-fixtures/test_logger_msgs.debug2.golden rename to vendor/github.com/cactus/mlog/test-fixtures/test_logger_msgs.debug2.golden diff --git a/vendor/src/github.com/cactus/mlog/test-fixtures/test_logger_msgs.infof1.golden b/vendor/github.com/cactus/mlog/test-fixtures/test_logger_msgs.infof1.golden similarity index 100% rename from vendor/src/github.com/cactus/mlog/test-fixtures/test_logger_msgs.infof1.golden rename to vendor/github.com/cactus/mlog/test-fixtures/test_logger_msgs.infof1.golden diff --git a/vendor/src/github.com/cactus/mlog/test-fixtures/test_logger_msgs.infof2.golden b/vendor/github.com/cactus/mlog/test-fixtures/test_logger_msgs.infof2.golden similarity index 100% rename from vendor/src/github.com/cactus/mlog/test-fixtures/test_logger_msgs.infof2.golden rename to vendor/github.com/cactus/mlog/test-fixtures/test_logger_msgs.infof2.golden diff --git a/vendor/src/github.com/cactus/mlog/test-fixtures/test_logger_msgs.infof3.golden b/vendor/github.com/cactus/mlog/test-fixtures/test_logger_msgs.infof3.golden similarity index 100% rename from vendor/src/github.com/cactus/mlog/test-fixtures/test_logger_msgs.infof3.golden rename to vendor/github.com/cactus/mlog/test-fixtures/test_logger_msgs.infof3.golden diff --git a/vendor/src/github.com/cactus/mlog/test-fixtures/test_logger_msgs.infom1.golden b/vendor/github.com/cactus/mlog/test-fixtures/test_logger_msgs.infom1.golden similarity index 100% rename from vendor/src/github.com/cactus/mlog/test-fixtures/test_logger_msgs.infom1.golden rename to vendor/github.com/cactus/mlog/test-fixtures/test_logger_msgs.infom1.golden diff --git a/vendor/src/github.com/cactus/mlog/test-fixtures/test_logger_msgs.infom2.golden b/vendor/github.com/cactus/mlog/test-fixtures/test_logger_msgs.infom2.golden similarity index 100% rename from vendor/src/github.com/cactus/mlog/test-fixtures/test_logger_msgs.infom2.golden rename to vendor/github.com/cactus/mlog/test-fixtures/test_logger_msgs.infom2.golden diff --git a/vendor/src/github.com/cactus/mlog/test-fixtures/test_logger_msgs.infom3.golden b/vendor/github.com/cactus/mlog/test-fixtures/test_logger_msgs.infom3.golden similarity index 100% rename from vendor/src/github.com/cactus/mlog/test-fixtures/test_logger_msgs.infom3.golden rename to vendor/github.com/cactus/mlog/test-fixtures/test_logger_msgs.infom3.golden diff --git a/vendor/src/github.com/cactus/mlog/test-fixtures/test_logger_msgs.infom4.golden b/vendor/github.com/cactus/mlog/test-fixtures/test_logger_msgs.infom4.golden similarity index 100% rename from vendor/src/github.com/cactus/mlog/test-fixtures/test_logger_msgs.infom4.golden rename to vendor/github.com/cactus/mlog/test-fixtures/test_logger_msgs.infom4.golden diff --git a/vendor/src/github.com/cactus/mlog/time.go b/vendor/github.com/cactus/mlog/time.go similarity index 59% rename from vendor/src/github.com/cactus/mlog/time.go rename to vendor/github.com/cactus/mlog/time.go index db936c2..c044dd5 100644 --- a/vendor/src/github.com/cactus/mlog/time.go +++ b/vendor/github.com/cactus/mlog/time.go @@ -1,12 +1,8 @@ package mlog -import ( - "time" +import "time" - "github.com/cactus/tai64" -) - -func writeTime(sb intSliceWriter, t *time.Time, flags FlagSet) { +func writeTime(sb sliceWriter, t *time.Time, flags FlagSet) { year, month, day := t.Date() sb.AppendIntWidth(year, 4) sb.WriteByte('-') @@ -23,8 +19,14 @@ func writeTime(sb intSliceWriter, t *time.Time, flags FlagSet) { sb.WriteByte(':') sb.AppendIntWidth(sec, 2) - sb.WriteByte('.') - sb.AppendIntWidth(t.Nanosecond(), 9) + switch { + case flags&Lnanoseconds != 0: + sb.WriteByte('.') + sb.AppendIntWidth(t.Nanosecond(), 9) + case flags&Lmicroseconds != 0: + sb.WriteByte('.') + sb.AppendIntWidth(t.Nanosecond()/1e3, 6) + } _, offset := t.Zone() if offset == 0 { @@ -41,12 +43,3 @@ func writeTime(sb intSliceWriter, t *time.Time, flags FlagSet) { sb.AppendIntWidth(offset%3600, 2) } } - -func writeTimeTAI64N(sb intSliceWriter, t *time.Time, flags FlagSet) { - tu := t.UTC() - tux := tu.Unix() - offset := tai64.GetOffsetUnix(tux) - sb.WriteString("@4") - sb.AppendIntWidthHex(tux+offset, 15) - sb.AppendIntWidthHex(int64(tu.Nanosecond()), 8) -} diff --git a/vendor/github.com/cactus/mlog/time_test.go b/vendor/github.com/cactus/mlog/time_test.go new file mode 100644 index 0000000..567a825 --- /dev/null +++ b/vendor/github.com/cactus/mlog/time_test.go @@ -0,0 +1,45 @@ +package mlog + +import ( + "testing" + "time" + + "github.com/stretchr/testify/assert" +) + +func TestTime(t *testing.T) { + loc := time.FixedZone("PDT", -25200) + cases := []struct { + F FlagSet + T time.Time + R string + }{ + { + Lnanoseconds, + time.Date(2016, time.November, 1, 2, 3, 4, 5, loc), + `2016-11-01T02:03:04.000000005-07:00`, + }, + { + Lnanoseconds, + time.Date(2016, time.January, 11, 12, 13, 14, 15, time.UTC), + `2016-01-11T12:13:14.000000015Z`, + }, + { + Lmicroseconds, + time.Date(2016, time.November, 1, 2, 3, 4, 5000, loc), + `2016-11-01T02:03:04.000005-07:00`, + }, + { + Lmicroseconds, + time.Date(2016, time.January, 11, 12, 13, 14, 15000, time.UTC), + `2016-01-11T12:13:14.000015Z`, + }, + } + + b := &sliceBuffer{make([]byte, 0, 1024)} + for _, tc := range cases { + b.Truncate(0) + writeTime(b, &(tc.T), tc.F) + assert.Equal(t, tc.R, b.String(), "time written incorrectly") + } +} diff --git a/vendor/github.com/davecgh/go-spew/.gitignore b/vendor/github.com/davecgh/go-spew/.gitignore new file mode 100644 index 0000000..0026861 --- /dev/null +++ b/vendor/github.com/davecgh/go-spew/.gitignore @@ -0,0 +1,22 @@ +# 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 new file mode 100644 index 0000000..984e073 --- /dev/null +++ b/vendor/github.com/davecgh/go-spew/.travis.yml @@ -0,0 +1,14 @@ +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/LICENSE b/vendor/github.com/davecgh/go-spew/LICENSE new file mode 100644 index 0000000..c836416 --- /dev/null +++ b/vendor/github.com/davecgh/go-spew/LICENSE @@ -0,0 +1,15 @@ +ISC License + +Copyright (c) 2012-2016 Dave Collins + +Permission to use, copy, modify, and distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/vendor/github.com/davecgh/go-spew/README.md b/vendor/github.com/davecgh/go-spew/README.md new file mode 100644 index 0000000..2624304 --- /dev/null +++ b/vendor/github.com/davecgh/go-spew/README.md @@ -0,0 +1,205 @@ +go-spew +======= + +[![Build Status](https://img.shields.io/travis/davecgh/go-spew.svg)] +(https://travis-ci.org/davecgh/go-spew) [![ISC License] +(http://img.shields.io/badge/license-ISC-blue.svg)](http://copyfree.org) [![Coverage Status] +(https://img.shields.io/coveralls/davecgh/go-spew.svg)] +(https://coveralls.io/r/davecgh/go-spew?branch=master) + + +Go-spew implements a deep pretty printer for Go data structures to aid in +debugging. A comprehensive suite of tests with 100% test coverage is provided +to ensure proper functionality. See `test_coverage.txt` for the gocov coverage +report. Go-spew is licensed under the liberal ISC license, so it may be used in +open source or commercial projects. + +If you're interested in reading about how this package came to life and some +of the challenges involved in providing a deep pretty printer, there is a blog +post about it +[here](https://web.archive.org/web/20160304013555/https://blog.cyphertite.com/go-spew-a-journey-into-dumping-go-data-structures/). + +## Documentation + +[![GoDoc](https://img.shields.io/badge/godoc-reference-blue.svg)] +(http://godoc.org/github.com/davecgh/go-spew/spew) + +Full `go doc` style documentation for the project can be viewed online without +installing this package by using the excellent GoDoc site here: +http://godoc.org/github.com/davecgh/go-spew/spew + +You can also view the documentation locally once the package is installed with +the `godoc` tool by running `godoc -http=":6060"` and pointing your browser to +http://localhost:6060/pkg/github.com/davecgh/go-spew/spew + +## Installation + +```bash +$ go get -u github.com/davecgh/go-spew/spew +``` + +## Quick Start + +Add this import line to the file you're working in: + +```Go +import "github.com/davecgh/go-spew/spew" +``` + +To dump a variable with full newlines, indentation, type, and pointer +information use Dump, Fdump, or Sdump: + +```Go +spew.Dump(myVar1, myVar2, ...) +spew.Fdump(someWriter, myVar1, myVar2, ...) +str := spew.Sdump(myVar1, myVar2, ...) +``` + +Alternatively, if you would prefer to use format strings with a compacted inline +printing style, use the convenience wrappers Printf, Fprintf, etc with %v (most +compact), %+v (adds pointer addresses), %#v (adds types), or %#+v (adds types +and pointer addresses): + +```Go +spew.Printf("myVar1: %v -- myVar2: %+v", myVar1, myVar2) +spew.Printf("myVar3: %#v -- myVar4: %#+v", myVar3, myVar4) +spew.Fprintf(someWriter, "myVar1: %v -- myVar2: %+v", myVar1, myVar2) +spew.Fprintf(someWriter, "myVar3: %#v -- myVar4: %#+v", myVar3, myVar4) +``` + +## Debugging a Web Application Example + +Here is an example of how you can use `spew.Sdump()` to help debug a web application. Please be sure to wrap your output using the `html.EscapeString()` function for safety reasons. You should also only use this debugging technique in a development environment, never in production. + +```Go +package main + +import ( + "fmt" + "html" + "net/http" + + "github.com/davecgh/go-spew/spew" +) + +func handler(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/html") + fmt.Fprintf(w, "Hi there, %s!", r.URL.Path[1:]) + fmt.Fprintf(w, "") +} + +func main() { + http.HandleFunc("/", handler) + http.ListenAndServe(":8080", nil) +} +``` + +## Sample Dump Output + +``` +(main.Foo) { + unexportedField: (*main.Bar)(0xf84002e210)({ + flag: (main.Flag) flagTwo, + data: (uintptr) + }), + ExportedField: (map[interface {}]interface {}) { + (string) "one": (bool) true + } +} +([]uint8) { + 00000000 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 |............... | + 00000010 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30 |!"#$%&'()*+,-./0| + 00000020 31 32 |12| +} +``` + +## Sample Formatter Output + +Double pointer to a uint8: +``` + %v: <**>5 + %+v: <**>(0xf8400420d0->0xf8400420c8)5 + %#v: (**uint8)5 + %#+v: (**uint8)(0xf8400420d0->0xf8400420c8)5 +``` + +Pointer to circular struct with a uint8 field and a pointer to itself: +``` + %v: <*>{1 <*>} + %+v: <*>(0xf84003e260){ui8:1 c:<*>(0xf84003e260)} + %#v: (*main.circular){ui8:(uint8)1 c:(*main.circular)} + %#+v: (*main.circular)(0xf84003e260){ui8:(uint8)1 c:(*main.circular)(0xf84003e260)} +``` + +## Configuration Options + +Configuration of spew is handled by fields in the ConfigState type. For +convenience, all of the top-level functions use a global state available via the +spew.Config global. + +It is also possible to create a ConfigState instance that provides methods +equivalent to the top-level functions. This allows concurrent configuration +options. See the ConfigState documentation for more details. + +``` +* Indent + String to use for each indentation level for Dump functions. + It is a single space by default. A popular alternative is "\t". + +* MaxDepth + Maximum number of levels to descend into nested data structures. + There is no limit by default. + +* DisableMethods + Disables invocation of error and Stringer interface methods. + Method invocation is enabled by default. + +* DisablePointerMethods + Disables invocation of error and Stringer interface methods on types + which only accept pointer receivers from non-pointer variables. This option + relies on access to the unsafe package, so it will not have any effect when + running in environments without access to the unsafe package such as Google + App Engine or with the "safe" build tag specified. + Pointer method invocation is enabled by default. + +* DisablePointerAddresses + DisablePointerAddresses specifies whether to disable the printing of + pointer addresses. This is useful when diffing data structures in tests. + +* DisableCapacities + DisableCapacities specifies whether to disable the printing of capacities + for arrays, slices, maps and channels. This is useful when diffing data + structures in tests. + +* ContinueOnMethod + Enables recursion into types after invoking error and Stringer interface + methods. Recursion after method invocation is disabled by default. + +* SortKeys + Specifies map keys should be sorted before being printed. Use + this to have a more deterministic, diffable output. Note that + only native types (bool, int, uint, floats, uintptr and string) + and types which implement error or Stringer interfaces are supported, + with other types sorted according to the reflect.Value.String() output + which guarantees display stability. Natural map order is used by + default. + +* SpewKeys + SpewKeys specifies that, as a last resort attempt, map keys should be + spewed to strings and sorted by those strings. This is only considered + if SortKeys is true. + +``` + +## Unsafe Package Dependency + +This package relies on the unsafe package to perform some of the more advanced +features, however it also supports a "limited" mode which allows it to work in +environments where the unsafe package is not available. By default, it will +operate in this mode on Google App Engine and when compiled with GopherJS. The +"safe" build tag may also be specified to force the package to build without +using the unsafe package. + +## License + +Go-spew is licensed under the [copyfree](http://copyfree.org) ISC License. diff --git a/vendor/github.com/davecgh/go-spew/cov_report.sh b/vendor/github.com/davecgh/go-spew/cov_report.sh new file mode 100644 index 0000000..9579497 --- /dev/null +++ b/vendor/github.com/davecgh/go-spew/cov_report.sh @@ -0,0 +1,22 @@ +#!/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/src/github.com/davecgh/go-spew/spew/bypass.go b/vendor/github.com/davecgh/go-spew/spew/bypass.go similarity index 98% rename from vendor/src/github.com/davecgh/go-spew/spew/bypass.go rename to vendor/github.com/davecgh/go-spew/spew/bypass.go index 7f166c3..8a4a658 100644 --- a/vendor/src/github.com/davecgh/go-spew/spew/bypass.go +++ b/vendor/github.com/davecgh/go-spew/spew/bypass.go @@ -41,9 +41,9 @@ var ( // after commit 82f48826c6c7 which changed the format again to mirror // the original format. Code in the init function updates these offsets // as necessary. - offsetPtr = ptrSize + offsetPtr = uintptr(ptrSize) offsetScalar = uintptr(0) - offsetFlag = ptrSize * 2 + offsetFlag = uintptr(ptrSize * 2) // flagKindWidth and flagKindShift indicate various bits that the // reflect package uses internally to track kind information. @@ -58,7 +58,7 @@ var ( // changed their positions. Code in the init function updates these // flags as necessary. flagKindWidth = uintptr(5) - flagKindShift = flagKindWidth - 1 + flagKindShift = uintptr(flagKindWidth - 1) flagRO = uintptr(1 << 0) flagIndir = uintptr(1 << 1) ) diff --git a/vendor/src/github.com/davecgh/go-spew/spew/bypasssafe.go b/vendor/github.com/davecgh/go-spew/spew/bypasssafe.go similarity index 100% rename from vendor/src/github.com/davecgh/go-spew/spew/bypasssafe.go rename to vendor/github.com/davecgh/go-spew/spew/bypasssafe.go diff --git a/vendor/src/github.com/davecgh/go-spew/spew/common.go b/vendor/github.com/davecgh/go-spew/spew/common.go similarity index 99% rename from vendor/src/github.com/davecgh/go-spew/spew/common.go rename to vendor/github.com/davecgh/go-spew/spew/common.go index 1be8ce9..7c519ff 100644 --- a/vendor/src/github.com/davecgh/go-spew/spew/common.go +++ b/vendor/github.com/davecgh/go-spew/spew/common.go @@ -180,7 +180,7 @@ func printComplex(w io.Writer, c complex128, floatPrecision int) { w.Write(closeParenBytes) } -// printHexPtr outputs a uintptr formatted as hexadecimal with a leading '0x' +// printHexPtr outputs a uintptr formatted as hexidecimal with a leading '0x' // prefix to Writer w. func printHexPtr(w io.Writer, p uintptr) { // Null pointer. diff --git a/vendor/src/github.com/davecgh/go-spew/spew/common_test.go b/vendor/github.com/davecgh/go-spew/spew/common_test.go similarity index 100% rename from vendor/src/github.com/davecgh/go-spew/spew/common_test.go rename to vendor/github.com/davecgh/go-spew/spew/common_test.go diff --git a/vendor/src/github.com/davecgh/go-spew/spew/config.go b/vendor/github.com/davecgh/go-spew/spew/config.go similarity index 100% rename from vendor/src/github.com/davecgh/go-spew/spew/config.go rename to vendor/github.com/davecgh/go-spew/spew/config.go diff --git a/vendor/src/github.com/davecgh/go-spew/spew/doc.go b/vendor/github.com/davecgh/go-spew/spew/doc.go similarity index 100% rename from vendor/src/github.com/davecgh/go-spew/spew/doc.go rename to vendor/github.com/davecgh/go-spew/spew/doc.go diff --git a/vendor/src/github.com/davecgh/go-spew/spew/dump.go b/vendor/github.com/davecgh/go-spew/spew/dump.go similarity index 98% rename from vendor/src/github.com/davecgh/go-spew/spew/dump.go rename to vendor/github.com/davecgh/go-spew/spew/dump.go index f78d89f..df1d582 100644 --- a/vendor/src/github.com/davecgh/go-spew/spew/dump.go +++ b/vendor/github.com/davecgh/go-spew/spew/dump.go @@ -35,16 +35,16 @@ var ( // cCharRE is a regular expression that matches a cgo char. // It is used to detect character arrays to hexdump them. - cCharRE = regexp.MustCompile(`^.*\._Ctype_char$`) + cCharRE = regexp.MustCompile("^.*\\._Ctype_char$") // cUnsignedCharRE is a regular expression that matches a cgo unsigned // char. It is used to detect unsigned character arrays to hexdump // them. - cUnsignedCharRE = regexp.MustCompile(`^.*\._Ctype_unsignedchar$`) + cUnsignedCharRE = regexp.MustCompile("^.*\\._Ctype_unsignedchar$") // cUint8tCharRE is a regular expression that matches a cgo uint8_t. // It is used to detect uint8_t arrays to hexdump them. - cUint8tCharRE = regexp.MustCompile(`^.*\._Ctype_uint8_t$`) + cUint8tCharRE = regexp.MustCompile("^.*\\._Ctype_uint8_t$") ) // dumpState contains information about the state of a dump operation. @@ -143,10 +143,10 @@ func (d *dumpState) dumpPtr(v reflect.Value) { // Display dereferenced value. d.w.Write(openParenBytes) switch { - case nilFound: + case nilFound == true: d.w.Write(nilAngleBytes) - case cycleFound: + case cycleFound == true: d.w.Write(circularBytes) default: diff --git a/vendor/src/github.com/davecgh/go-spew/spew/dump_test.go b/vendor/github.com/davecgh/go-spew/spew/dump_test.go similarity index 100% rename from vendor/src/github.com/davecgh/go-spew/spew/dump_test.go rename to vendor/github.com/davecgh/go-spew/spew/dump_test.go diff --git a/vendor/src/github.com/davecgh/go-spew/spew/dumpcgo_test.go b/vendor/github.com/davecgh/go-spew/spew/dumpcgo_test.go similarity index 94% rename from vendor/src/github.com/davecgh/go-spew/spew/dumpcgo_test.go rename to vendor/github.com/davecgh/go-spew/spew/dumpcgo_test.go index 108baa5..6ab1808 100644 --- a/vendor/src/github.com/davecgh/go-spew/spew/dumpcgo_test.go +++ b/vendor/github.com/davecgh/go-spew/spew/dumpcgo_test.go @@ -82,20 +82,18 @@ func addCgoDumpTests() { v5Len := fmt.Sprintf("%d", v5l) v5Cap := fmt.Sprintf("%d", v5c) v5t := "[6]testdata._Ctype_uint8_t" - v5t2 := "[6]testdata._Ctype_uchar" v5s := "(len=" + v5Len + " cap=" + v5Cap + ") " + "{\n 00000000 74 65 73 74 35 00 " + " |test5.|\n}" - addDumpTest(v5, "("+v5t+") "+v5s+"\n", "("+v5t2+") "+v5s+"\n") + 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" - v6t2 := "[6]testdata._Ctype_uchar" v6s := "(len=" + v6Len + " cap=" + v6Cap + ") " + "{\n 00000000 74 65 73 74 36 00 " + " |test6.|\n}" - addDumpTest(v6, "("+v6t+") "+v6s+"\n", "("+v6t2+") "+v6s+"\n") + addDumpTest(v6, "("+v6t+") "+v6s+"\n") } diff --git a/vendor/src/github.com/davecgh/go-spew/spew/dumpnocgo_test.go b/vendor/github.com/davecgh/go-spew/spew/dumpnocgo_test.go similarity index 100% rename from vendor/src/github.com/davecgh/go-spew/spew/dumpnocgo_test.go rename to vendor/github.com/davecgh/go-spew/spew/dumpnocgo_test.go diff --git a/vendor/src/github.com/davecgh/go-spew/spew/example_test.go b/vendor/github.com/davecgh/go-spew/spew/example_test.go similarity index 100% rename from vendor/src/github.com/davecgh/go-spew/spew/example_test.go rename to vendor/github.com/davecgh/go-spew/spew/example_test.go diff --git a/vendor/src/github.com/davecgh/go-spew/spew/format.go b/vendor/github.com/davecgh/go-spew/spew/format.go similarity index 99% rename from vendor/src/github.com/davecgh/go-spew/spew/format.go rename to vendor/github.com/davecgh/go-spew/spew/format.go index b04edb7..c49875b 100644 --- a/vendor/src/github.com/davecgh/go-spew/spew/format.go +++ b/vendor/github.com/davecgh/go-spew/spew/format.go @@ -182,10 +182,10 @@ func (f *formatState) formatPtr(v reflect.Value) { // Display dereferenced value. switch { - case nilFound: + case nilFound == true: f.fs.Write(nilAngleBytes) - case cycleFound: + case cycleFound == true: f.fs.Write(circularShortBytes) default: diff --git a/vendor/src/github.com/davecgh/go-spew/spew/format_test.go b/vendor/github.com/davecgh/go-spew/spew/format_test.go similarity index 99% rename from vendor/src/github.com/davecgh/go-spew/spew/format_test.go rename to vendor/github.com/davecgh/go-spew/spew/format_test.go index 0719eb9..f9b93ab 100644 --- a/vendor/src/github.com/davecgh/go-spew/spew/format_test.go +++ b/vendor/github.com/davecgh/go-spew/spew/format_test.go @@ -1536,14 +1536,14 @@ func TestPrintSortedKeys(t *testing.T) { t.Errorf("Sorted keys mismatch 3:\n %v %v", s, expected) } - s = cfg.Sprint(map[testStruct]int{{1}: 1, {3}: 3, {2}: 2}) + 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{{1}: 1, {3}: 3, {2}: 2}) + 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) diff --git a/vendor/src/github.com/davecgh/go-spew/spew/internal_test.go b/vendor/github.com/davecgh/go-spew/spew/internal_test.go similarity index 98% rename from vendor/src/github.com/davecgh/go-spew/spew/internal_test.go rename to vendor/github.com/davecgh/go-spew/spew/internal_test.go index e312b4f..20a9cfe 100644 --- a/vendor/src/github.com/davecgh/go-spew/spew/internal_test.go +++ b/vendor/github.com/davecgh/go-spew/spew/internal_test.go @@ -36,7 +36,10 @@ type dummyFmtState struct { } func (dfs *dummyFmtState) Flag(f int) bool { - return f == int('+') + if f == int('+') { + return true + } + return false } func (dfs *dummyFmtState) Precision() (int, bool) { diff --git a/vendor/src/github.com/davecgh/go-spew/spew/internalunsafe_test.go b/vendor/github.com/davecgh/go-spew/spew/internalunsafe_test.go similarity index 100% rename from vendor/src/github.com/davecgh/go-spew/spew/internalunsafe_test.go rename to vendor/github.com/davecgh/go-spew/spew/internalunsafe_test.go diff --git a/vendor/src/github.com/davecgh/go-spew/spew/spew.go b/vendor/github.com/davecgh/go-spew/spew/spew.go similarity index 100% rename from vendor/src/github.com/davecgh/go-spew/spew/spew.go rename to vendor/github.com/davecgh/go-spew/spew/spew.go diff --git a/vendor/src/github.com/davecgh/go-spew/spew/spew_test.go b/vendor/github.com/davecgh/go-spew/spew/spew_test.go similarity index 100% rename from vendor/src/github.com/davecgh/go-spew/spew/spew_test.go rename to vendor/github.com/davecgh/go-spew/spew/spew_test.go diff --git a/vendor/src/github.com/davecgh/go-spew/spew/testdata/dumpcgo.go b/vendor/github.com/davecgh/go-spew/spew/testdata/dumpcgo.go similarity index 100% rename from vendor/src/github.com/davecgh/go-spew/spew/testdata/dumpcgo.go rename to vendor/github.com/davecgh/go-spew/spew/testdata/dumpcgo.go diff --git a/vendor/github.com/davecgh/go-spew/test_coverage.txt b/vendor/github.com/davecgh/go-spew/test_coverage.txt new file mode 100644 index 0000000..2cd087a --- /dev/null +++ b/vendor/github.com/davecgh/go-spew/test_coverage.txt @@ -0,0 +1,61 @@ + +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/jessevdk/go-flags/.travis.yml b/vendor/github.com/jessevdk/go-flags/.travis.yml new file mode 100644 index 0000000..e7c4be0 --- /dev/null +++ b/vendor/github.com/jessevdk/go-flags/.travis.yml @@ -0,0 +1,38 @@ +language: go + +go: + - 1.6.x + - 1.7.x + +install: + # go-flags + - go get -d -v ./... + - go build -v ./... + + # linting + - go get github.com/golang/lint + - go install github.com/golang/lint/golint + + # code coverage + - go get golang.org/x/tools/cmd/cover + - go get github.com/onsi/ginkgo/ginkgo + - go get github.com/modocache/gover + - if [ "$TRAVIS_SECURE_ENV_VARS" = "true" ]; then go get github.com/mattn/goveralls; fi + +script: + # go-flags + - $(exit $(gofmt -l . | wc -l)) + - go test -v ./... + + # linting + - go tool vet -all=true -v=true . || true + - $(go env GOPATH | awk 'BEGIN{FS=":"} {print $1}')/bin/golint ./... + + # code coverage + - $(go env GOPATH | awk 'BEGIN{FS=":"} {print $1}')/bin/ginkgo -r -cover + - $(go env GOPATH | awk 'BEGIN{FS=":"} {print $1}')/bin/gover + - if [ "$TRAVIS_SECURE_ENV_VARS" = "true" ]; then $(go env GOPATH | awk 'BEGIN{FS=":"} {print $1}')/bin/goveralls -coverprofile=gover.coverprofile -service=travis-ci -repotoken $COVERALLS_TOKEN; fi + +env: + # coveralls.io + secure: "RCYbiB4P0RjQRIoUx/vG/AjP3mmYCbzOmr86DCww1Z88yNcy3hYr3Cq8rpPtYU5v0g7wTpu4adaKIcqRE9xknYGbqj3YWZiCoBP1/n4Z+9sHW3Dsd9D/GRGeHUus0laJUGARjWoCTvoEtOgTdGQDoX7mH+pUUY0FBltNYUdOiiU=" diff --git a/vendor/src/github.com/jessevdk/go-flags/LICENSE b/vendor/github.com/jessevdk/go-flags/LICENSE similarity index 100% rename from vendor/src/github.com/jessevdk/go-flags/LICENSE rename to vendor/github.com/jessevdk/go-flags/LICENSE diff --git a/vendor/src/github.com/jessevdk/go-flags/README.md b/vendor/github.com/jessevdk/go-flags/README.md similarity index 99% rename from vendor/src/github.com/jessevdk/go-flags/README.md rename to vendor/github.com/jessevdk/go-flags/README.md index 3b02394..9378b76 100644 --- a/vendor/src/github.com/jessevdk/go-flags/README.md +++ b/vendor/github.com/jessevdk/go-flags/README.md @@ -110,6 +110,7 @@ args, err := flags.ParseArgs(&opts, args) if err != nil { panic(err) + os.Exit(1) } fmt.Printf("Verbosity: %v\n", opts.Verbose) diff --git a/vendor/src/github.com/jessevdk/go-flags/arg.go b/vendor/github.com/jessevdk/go-flags/arg.go similarity index 100% rename from vendor/src/github.com/jessevdk/go-flags/arg.go rename to vendor/github.com/jessevdk/go-flags/arg.go diff --git a/vendor/src/github.com/jessevdk/go-flags/arg_test.go b/vendor/github.com/jessevdk/go-flags/arg_test.go similarity index 100% rename from vendor/src/github.com/jessevdk/go-flags/arg_test.go rename to vendor/github.com/jessevdk/go-flags/arg_test.go diff --git a/vendor/src/github.com/jessevdk/go-flags/assert_test.go b/vendor/github.com/jessevdk/go-flags/assert_test.go similarity index 100% rename from vendor/src/github.com/jessevdk/go-flags/assert_test.go rename to vendor/github.com/jessevdk/go-flags/assert_test.go diff --git a/vendor/src/github.com/jessevdk/go-flags/check_crosscompile.sh b/vendor/github.com/jessevdk/go-flags/check_crosscompile.sh old mode 100644 new mode 100755 similarity index 100% rename from vendor/src/github.com/jessevdk/go-flags/check_crosscompile.sh rename to vendor/github.com/jessevdk/go-flags/check_crosscompile.sh diff --git a/vendor/src/github.com/jessevdk/go-flags/closest.go b/vendor/github.com/jessevdk/go-flags/closest.go similarity index 100% rename from vendor/src/github.com/jessevdk/go-flags/closest.go rename to vendor/github.com/jessevdk/go-flags/closest.go diff --git a/vendor/src/github.com/jessevdk/go-flags/command.go b/vendor/github.com/jessevdk/go-flags/command.go similarity index 97% rename from vendor/src/github.com/jessevdk/go-flags/command.go rename to vendor/github.com/jessevdk/go-flags/command.go index 486bacb..2662843 100644 --- a/vendor/src/github.com/jessevdk/go-flags/command.go +++ b/vendor/github.com/jessevdk/go-flags/command.go @@ -5,6 +5,7 @@ import ( "sort" "strconv" "strings" + "unsafe" ) // Command represents an application command. Commands can be added to the @@ -228,17 +229,7 @@ func (c *Command) scanSubcommandHandler(parentg *Group) scanHandler { subcommand := mtag.Get("command") if len(subcommand) != 0 { - var ptrval reflect.Value - - if realval.Kind() == reflect.Ptr { - ptrval = realval - - if ptrval.IsNil() { - ptrval.Set(reflect.New(ptrval.Type().Elem())) - } - } else { - ptrval = realval.Addr() - } + ptrval := reflect.NewAt(realval.Type(), unsafe.Pointer(realval.UnsafeAddr())) shortDescription := mtag.Get("description") longDescription := mtag.Get("long-description") @@ -246,7 +237,6 @@ func (c *Command) scanSubcommandHandler(parentg *Group) scanHandler { aliases := mtag.GetMany("alias") subc, err := c.AddCommand(subcommand, shortDescription, longDescription, ptrval.Interface()) - if err != nil { return true, err } diff --git a/vendor/src/github.com/jessevdk/go-flags/command_test.go b/vendor/github.com/jessevdk/go-flags/command_test.go similarity index 100% rename from vendor/src/github.com/jessevdk/go-flags/command_test.go rename to vendor/github.com/jessevdk/go-flags/command_test.go diff --git a/vendor/src/github.com/jessevdk/go-flags/completion.go b/vendor/github.com/jessevdk/go-flags/completion.go similarity index 100% rename from vendor/src/github.com/jessevdk/go-flags/completion.go rename to vendor/github.com/jessevdk/go-flags/completion.go diff --git a/vendor/src/github.com/jessevdk/go-flags/completion_test.go b/vendor/github.com/jessevdk/go-flags/completion_test.go similarity index 100% rename from vendor/src/github.com/jessevdk/go-flags/completion_test.go rename to vendor/github.com/jessevdk/go-flags/completion_test.go diff --git a/vendor/src/github.com/jessevdk/go-flags/convert.go b/vendor/github.com/jessevdk/go-flags/convert.go similarity index 100% rename from vendor/src/github.com/jessevdk/go-flags/convert.go rename to vendor/github.com/jessevdk/go-flags/convert.go diff --git a/vendor/src/github.com/jessevdk/go-flags/convert_test.go b/vendor/github.com/jessevdk/go-flags/convert_test.go similarity index 100% rename from vendor/src/github.com/jessevdk/go-flags/convert_test.go rename to vendor/github.com/jessevdk/go-flags/convert_test.go diff --git a/vendor/src/github.com/jessevdk/go-flags/error.go b/vendor/github.com/jessevdk/go-flags/error.go similarity index 100% rename from vendor/src/github.com/jessevdk/go-flags/error.go rename to vendor/github.com/jessevdk/go-flags/error.go diff --git a/vendor/src/github.com/jessevdk/go-flags/example_test.go b/vendor/github.com/jessevdk/go-flags/example_test.go similarity index 100% rename from vendor/src/github.com/jessevdk/go-flags/example_test.go rename to vendor/github.com/jessevdk/go-flags/example_test.go diff --git a/vendor/src/github.com/jessevdk/go-flags/examples/add.go b/vendor/github.com/jessevdk/go-flags/examples/add.go similarity index 100% rename from vendor/src/github.com/jessevdk/go-flags/examples/add.go rename to vendor/github.com/jessevdk/go-flags/examples/add.go diff --git a/vendor/src/github.com/jessevdk/go-flags/examples/bash-completion b/vendor/github.com/jessevdk/go-flags/examples/bash-completion similarity index 100% rename from vendor/src/github.com/jessevdk/go-flags/examples/bash-completion rename to vendor/github.com/jessevdk/go-flags/examples/bash-completion diff --git a/vendor/src/github.com/jessevdk/go-flags/examples/main.go b/vendor/github.com/jessevdk/go-flags/examples/main.go similarity index 100% rename from vendor/src/github.com/jessevdk/go-flags/examples/main.go rename to vendor/github.com/jessevdk/go-flags/examples/main.go diff --git a/vendor/src/github.com/jessevdk/go-flags/examples/rm.go b/vendor/github.com/jessevdk/go-flags/examples/rm.go similarity index 100% rename from vendor/src/github.com/jessevdk/go-flags/examples/rm.go rename to vendor/github.com/jessevdk/go-flags/examples/rm.go diff --git a/vendor/src/github.com/jessevdk/go-flags/flags.go b/vendor/github.com/jessevdk/go-flags/flags.go similarity index 100% rename from vendor/src/github.com/jessevdk/go-flags/flags.go rename to vendor/github.com/jessevdk/go-flags/flags.go diff --git a/vendor/src/github.com/jessevdk/go-flags/group.go b/vendor/github.com/jessevdk/go-flags/group.go similarity index 97% rename from vendor/src/github.com/jessevdk/go-flags/group.go rename to vendor/github.com/jessevdk/go-flags/group.go index 9e057ab..6133a71 100644 --- a/vendor/src/github.com/jessevdk/go-flags/group.go +++ b/vendor/github.com/jessevdk/go-flags/group.go @@ -9,6 +9,7 @@ import ( "reflect" "strings" "unicode/utf8" + "unsafe" ) // ErrNotPointerToStruct indicates that a provided data container is not @@ -337,22 +338,10 @@ func (g *Group) scanSubGroupHandler(realval reflect.Value, sfield *reflect.Struc subgroup := mtag.Get("group") if len(subgroup) != 0 { - var ptrval reflect.Value - - if realval.Kind() == reflect.Ptr { - ptrval = realval - - if ptrval.IsNil() { - ptrval.Set(reflect.New(ptrval.Type())) - } - } else { - ptrval = realval.Addr() - } - + ptrval := reflect.NewAt(realval.Type(), unsafe.Pointer(realval.UnsafeAddr())) description := mtag.Get("description") group, err := g.AddGroup(subgroup, description, ptrval.Interface()) - if err != nil { return true, err } diff --git a/vendor/src/github.com/jessevdk/go-flags/group_test.go b/vendor/github.com/jessevdk/go-flags/group_test.go similarity index 100% rename from vendor/src/github.com/jessevdk/go-flags/group_test.go rename to vendor/github.com/jessevdk/go-flags/group_test.go diff --git a/vendor/src/github.com/jessevdk/go-flags/help.go b/vendor/github.com/jessevdk/go-flags/help.go similarity index 100% rename from vendor/src/github.com/jessevdk/go-flags/help.go rename to vendor/github.com/jessevdk/go-flags/help.go diff --git a/vendor/src/github.com/jessevdk/go-flags/help_test.go b/vendor/github.com/jessevdk/go-flags/help_test.go similarity index 100% rename from vendor/src/github.com/jessevdk/go-flags/help_test.go rename to vendor/github.com/jessevdk/go-flags/help_test.go diff --git a/vendor/src/github.com/jessevdk/go-flags/ini.go b/vendor/github.com/jessevdk/go-flags/ini.go similarity index 100% rename from vendor/src/github.com/jessevdk/go-flags/ini.go rename to vendor/github.com/jessevdk/go-flags/ini.go diff --git a/vendor/src/github.com/jessevdk/go-flags/ini_test.go b/vendor/github.com/jessevdk/go-flags/ini_test.go similarity index 100% rename from vendor/src/github.com/jessevdk/go-flags/ini_test.go rename to vendor/github.com/jessevdk/go-flags/ini_test.go diff --git a/vendor/src/github.com/jessevdk/go-flags/long_test.go b/vendor/github.com/jessevdk/go-flags/long_test.go similarity index 100% rename from vendor/src/github.com/jessevdk/go-flags/long_test.go rename to vendor/github.com/jessevdk/go-flags/long_test.go diff --git a/vendor/src/github.com/jessevdk/go-flags/man.go b/vendor/github.com/jessevdk/go-flags/man.go similarity index 100% rename from vendor/src/github.com/jessevdk/go-flags/man.go rename to vendor/github.com/jessevdk/go-flags/man.go diff --git a/vendor/src/github.com/jessevdk/go-flags/marshal_test.go b/vendor/github.com/jessevdk/go-flags/marshal_test.go similarity index 100% rename from vendor/src/github.com/jessevdk/go-flags/marshal_test.go rename to vendor/github.com/jessevdk/go-flags/marshal_test.go diff --git a/vendor/src/github.com/jessevdk/go-flags/multitag.go b/vendor/github.com/jessevdk/go-flags/multitag.go similarity index 100% rename from vendor/src/github.com/jessevdk/go-flags/multitag.go rename to vendor/github.com/jessevdk/go-flags/multitag.go diff --git a/vendor/src/github.com/jessevdk/go-flags/option.go b/vendor/github.com/jessevdk/go-flags/option.go similarity index 100% rename from vendor/src/github.com/jessevdk/go-flags/option.go rename to vendor/github.com/jessevdk/go-flags/option.go diff --git a/vendor/src/github.com/jessevdk/go-flags/options_test.go b/vendor/github.com/jessevdk/go-flags/options_test.go similarity index 100% rename from vendor/src/github.com/jessevdk/go-flags/options_test.go rename to vendor/github.com/jessevdk/go-flags/options_test.go diff --git a/vendor/src/github.com/jessevdk/go-flags/optstyle_other.go b/vendor/github.com/jessevdk/go-flags/optstyle_other.go similarity index 100% rename from vendor/src/github.com/jessevdk/go-flags/optstyle_other.go rename to vendor/github.com/jessevdk/go-flags/optstyle_other.go diff --git a/vendor/src/github.com/jessevdk/go-flags/optstyle_windows.go b/vendor/github.com/jessevdk/go-flags/optstyle_windows.go similarity index 100% rename from vendor/src/github.com/jessevdk/go-flags/optstyle_windows.go rename to vendor/github.com/jessevdk/go-flags/optstyle_windows.go diff --git a/vendor/src/github.com/jessevdk/go-flags/parser.go b/vendor/github.com/jessevdk/go-flags/parser.go similarity index 100% rename from vendor/src/github.com/jessevdk/go-flags/parser.go rename to vendor/github.com/jessevdk/go-flags/parser.go diff --git a/vendor/src/github.com/jessevdk/go-flags/parser_test.go b/vendor/github.com/jessevdk/go-flags/parser_test.go similarity index 100% rename from vendor/src/github.com/jessevdk/go-flags/parser_test.go rename to vendor/github.com/jessevdk/go-flags/parser_test.go diff --git a/vendor/src/github.com/jessevdk/go-flags/pointer_test.go b/vendor/github.com/jessevdk/go-flags/pointer_test.go similarity index 100% rename from vendor/src/github.com/jessevdk/go-flags/pointer_test.go rename to vendor/github.com/jessevdk/go-flags/pointer_test.go diff --git a/vendor/src/github.com/jessevdk/go-flags/short_test.go b/vendor/github.com/jessevdk/go-flags/short_test.go similarity index 100% rename from vendor/src/github.com/jessevdk/go-flags/short_test.go rename to vendor/github.com/jessevdk/go-flags/short_test.go diff --git a/vendor/src/github.com/jessevdk/go-flags/tag_test.go b/vendor/github.com/jessevdk/go-flags/tag_test.go similarity index 100% rename from vendor/src/github.com/jessevdk/go-flags/tag_test.go rename to vendor/github.com/jessevdk/go-flags/tag_test.go diff --git a/vendor/src/github.com/jessevdk/go-flags/termsize.go b/vendor/github.com/jessevdk/go-flags/termsize.go similarity index 88% rename from vendor/src/github.com/jessevdk/go-flags/termsize.go rename to vendor/github.com/jessevdk/go-flags/termsize.go index 1ca6a85..df97e7e 100644 --- a/vendor/src/github.com/jessevdk/go-flags/termsize.go +++ b/vendor/github.com/jessevdk/go-flags/termsize.go @@ -1,4 +1,4 @@ -// +build !windows,!plan9,!solaris,!appengine +// +build !windows,!plan9,!solaris package flags diff --git a/vendor/src/github.com/jessevdk/go-flags/tiocgwinsz_linux.go b/vendor/github.com/jessevdk/go-flags/termsize_linux.go similarity index 100% rename from vendor/src/github.com/jessevdk/go-flags/tiocgwinsz_linux.go rename to vendor/github.com/jessevdk/go-flags/termsize_linux.go diff --git a/vendor/src/github.com/jessevdk/go-flags/termsize_nosysioctl.go b/vendor/github.com/jessevdk/go-flags/termsize_nosysioctl.go similarity index 59% rename from vendor/src/github.com/jessevdk/go-flags/termsize_nosysioctl.go rename to vendor/github.com/jessevdk/go-flags/termsize_nosysioctl.go index 3d5385b..2a9bbe0 100644 --- a/vendor/src/github.com/jessevdk/go-flags/termsize_nosysioctl.go +++ b/vendor/github.com/jessevdk/go-flags/termsize_nosysioctl.go @@ -1,4 +1,4 @@ -// +build windows plan9 solaris appengine +// +build windows plan9 solaris package flags diff --git a/vendor/src/github.com/jessevdk/go-flags/tiocgwinsz_other.go b/vendor/github.com/jessevdk/go-flags/termsize_other.go similarity index 100% rename from vendor/src/github.com/jessevdk/go-flags/tiocgwinsz_other.go rename to vendor/github.com/jessevdk/go-flags/termsize_other.go diff --git a/vendor/src/github.com/jessevdk/go-flags/tiocgwinsz_bsdish.go b/vendor/github.com/jessevdk/go-flags/termsize_unix.go similarity index 100% rename from vendor/src/github.com/jessevdk/go-flags/tiocgwinsz_bsdish.go rename to vendor/github.com/jessevdk/go-flags/termsize_unix.go diff --git a/vendor/src/github.com/jessevdk/go-flags/unknown_test.go b/vendor/github.com/jessevdk/go-flags/unknown_test.go similarity index 100% rename from vendor/src/github.com/jessevdk/go-flags/unknown_test.go rename to vendor/github.com/jessevdk/go-flags/unknown_test.go diff --git a/vendor/github.com/pmezard/go-difflib/.travis.yml b/vendor/github.com/pmezard/go-difflib/.travis.yml new file mode 100644 index 0000000..90c9c6f --- /dev/null +++ b/vendor/github.com/pmezard/go-difflib/.travis.yml @@ -0,0 +1,5 @@ +language: go +go: + - 1.5 + - tip + diff --git a/vendor/github.com/pmezard/go-difflib/LICENSE b/vendor/github.com/pmezard/go-difflib/LICENSE new file mode 100644 index 0000000..c67dad6 --- /dev/null +++ b/vendor/github.com/pmezard/go-difflib/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) 2013, Patrick Mezard +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + Redistributions in binary form must reproduce the above copyright +notice, this list of conditions and the following disclaimer in the +documentation and/or other materials provided with the distribution. + The names of its contributors may not be used to endorse or promote +products derived from this software without specific prior written +permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS +IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER 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/pmezard/go-difflib/README.md b/vendor/github.com/pmezard/go-difflib/README.md new file mode 100644 index 0000000..e87f307 --- /dev/null +++ b/vendor/github.com/pmezard/go-difflib/README.md @@ -0,0 +1,50 @@ +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/src/github.com/pmezard/go-difflib/difflib/difflib.go b/vendor/github.com/pmezard/go-difflib/difflib/difflib.go similarity index 100% rename from vendor/src/github.com/pmezard/go-difflib/difflib/difflib.go rename to vendor/github.com/pmezard/go-difflib/difflib/difflib.go diff --git a/vendor/src/github.com/pmezard/go-difflib/difflib/difflib_test.go b/vendor/github.com/pmezard/go-difflib/difflib/difflib_test.go similarity index 100% rename from vendor/src/github.com/pmezard/go-difflib/difflib/difflib_test.go rename to vendor/github.com/pmezard/go-difflib/difflib/difflib_test.go diff --git a/vendor/github.com/stretchr/testify/.gitignore b/vendor/github.com/stretchr/testify/.gitignore new file mode 100644 index 0000000..5aacdb7 --- /dev/null +++ b/vendor/github.com/stretchr/testify/.gitignore @@ -0,0 +1,24 @@ +# 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.gofmt.sh b/vendor/github.com/stretchr/testify/.travis.gofmt.sh new file mode 100755 index 0000000..bfffdca --- /dev/null +++ b/vendor/github.com/stretchr/testify/.travis.gofmt.sh @@ -0,0 +1,7 @@ +#!/bin/bash + +if [ -n "$(gofmt -l .)" ]; then + echo "Go code is not formatted:" + gofmt -d . + exit 1 +fi diff --git a/vendor/github.com/stretchr/testify/.travis.gogenerate.sh b/vendor/github.com/stretchr/testify/.travis.gogenerate.sh new file mode 100755 index 0000000..161b449 --- /dev/null +++ b/vendor/github.com/stretchr/testify/.travis.gogenerate.sh @@ -0,0 +1,13 @@ +#!/bin/bash + +if [[ "$TRAVIS_GO_VERSION" =~ ^1\.[45](\..*)?$ ]]; then + exit 0 +fi + +go get github.com/ernesto-jimenez/gogen/imports +go generate ./... +if [ -n "$(git diff)" ]; then + echo "Go generate had not been run" + git diff + exit 1 +fi diff --git a/vendor/github.com/stretchr/testify/.travis.govet.sh b/vendor/github.com/stretchr/testify/.travis.govet.sh new file mode 100755 index 0000000..f8fbba7 --- /dev/null +++ b/vendor/github.com/stretchr/testify/.travis.govet.sh @@ -0,0 +1,10 @@ +#!/bin/bash + +cd "$(dirname $0)" +DIRS=". assert require mock _codegen" +set -e +for subdir in $DIRS; do + pushd $subdir + go vet + popd +done diff --git a/vendor/github.com/stretchr/testify/.travis.yml b/vendor/github.com/stretchr/testify/.travis.yml new file mode 100644 index 0000000..6e51e63 --- /dev/null +++ b/vendor/github.com/stretchr/testify/.travis.yml @@ -0,0 +1,15 @@ +language: go + +sudo: false + +go: + - 1.7 + - 1.8 + - 1.9 + - tip + +script: + - ./.travis.gogenerate.sh + - ./.travis.gofmt.sh + - ./.travis.govet.sh + - go test -v -race $(go list ./... | grep -v vendor) diff --git a/vendor/github.com/stretchr/testify/Gopkg.lock b/vendor/github.com/stretchr/testify/Gopkg.lock new file mode 100644 index 0000000..294cda0 --- /dev/null +++ b/vendor/github.com/stretchr/testify/Gopkg.lock @@ -0,0 +1,27 @@ +# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. + + +[[projects]] + name = "github.com/davecgh/go-spew" + packages = ["spew"] + revision = "346938d642f2ec3594ed81d874461961cd0faa76" + version = "v1.1.0" + +[[projects]] + name = "github.com/pmezard/go-difflib" + packages = ["difflib"] + revision = "792786c7400a136282c1664665ae0a8db921c6c2" + version = "v1.0.0" + +[[projects]] + name = "github.com/stretchr/objx" + packages = ["."] + revision = "facf9a85c22f48d2f52f2380e4efce1768749a89" + version = "v0.1" + +[solve-meta] + analyzer-name = "dep" + analyzer-version = 1 + inputs-digest = "448ddae4702c6aded2555faafd390c537789bb1c483f70b0431e6634f73f2090" + solver-name = "gps-cdcl" + solver-version = 1 diff --git a/vendor/github.com/stretchr/testify/Gopkg.toml b/vendor/github.com/stretchr/testify/Gopkg.toml new file mode 100644 index 0000000..a16374c --- /dev/null +++ b/vendor/github.com/stretchr/testify/Gopkg.toml @@ -0,0 +1,16 @@ +[prune] + unused-packages = true + non-go = true + go-tests = true + +[[constraint]] + name = "github.com/davecgh/go-spew" + version = "~1.1.0" + +[[constraint]] + name = "github.com/pmezard/go-difflib" + version = "~1.0.0" + +[[constraint]] + name = "github.com/stretchr/objx" + version = "~0.1.0" diff --git a/vendor/github.com/stretchr/testify/LICENSE b/vendor/github.com/stretchr/testify/LICENSE new file mode 100644 index 0000000..473b670 --- /dev/null +++ b/vendor/github.com/stretchr/testify/LICENSE @@ -0,0 +1,22 @@ +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/README.md b/vendor/github.com/stretchr/testify/README.md new file mode 100644 index 0000000..d3b942b --- /dev/null +++ b/vendor/github.com/stretchr/testify/README.md @@ -0,0 +1,301 @@ +Testify - Thou Shalt Write Tests +================================ + +[![Build Status](https://travis-ci.org/stretchr/testify.svg)](https://travis-ci.org/stretchr/testify) [![Go Report Card](https://goreportcard.com/badge/github.com/stretchr/testify)](https://goreportcard.com/report/github.com/stretchr/testify) [![GoDoc](https://godoc.org/github.com/stretchr/testify?status.svg)](https://godoc.org/github.com/stretchr/testify) + +Go code (golang) set of packages that provide many tools for testifying that your code will behave as you intend. + +Features include: + + * [Easy assertions](#assert-package) + * [Mocking](#mock-package) + * [Testing suite interfaces and functions](#suite-package) + +Get started: + + * Install testify with [one line of code](#installation), or [update it with another](#staying-up-to-date) + * For an introduction to writing test code in Go, see http://golang.org/doc/code.html#Testing + * Check out the API Documentation http://godoc.org/github.com/stretchr/testify + * To make your testing life easier, check out our other project, [gorc](http://github.com/stretchr/gorc) + * A little about [Test-Driven Development (TDD)](http://en.wikipedia.org/wiki/Test-driven_development) + + + +[`assert`](http://godoc.org/github.com/stretchr/testify/assert "API documentation") package +------------------------------------------------------------------------------------------- + +The `assert` package provides some helpful methods that allow you to write better test code in Go. + + * Prints friendly, easy to read failure descriptions + * Allows for very readable code + * Optionally annotate each assertion with a message + +See it in action: + +```go +package yours + +import ( + "testing" + "github.com/stretchr/testify/assert" +) + +func TestSomething(t *testing.T) { + + // assert equality + assert.Equal(t, 123, 123, "they should be equal") + + // assert inequality + assert.NotEqual(t, 123, 456, "they should not be equal") + + // assert for nil (good for errors) + assert.Nil(t, object) + + // assert for not nil (good when you expect something) + if assert.NotNil(t, object) { + + // now we know that object isn't nil, we are safe to make + // further assertions without causing any errors + assert.Equal(t, "Something", object.Value) + + } + +} +``` + + * Every assert func takes the `testing.T` object as the first argument. This is how it writes the errors out through the normal `go test` capabilities. + * Every assert func returns a bool indicating whether the assertion was successful or not, this is useful for if you want to go on making further assertions under certain conditions. + +if you assert many times, use the below: + +```go +package yours + +import ( + "testing" + "github.com/stretchr/testify/assert" +) + +func TestSomething(t *testing.T) { + assert := assert.New(t) + + // assert equality + assert.Equal(123, 123, "they should be equal") + + // assert inequality + assert.NotEqual(123, 456, "they should not be equal") + + // assert for nil (good for errors) + assert.Nil(object) + + // assert for not nil (good when you expect something) + if assert.NotNil(object) { + + // now we know that object isn't nil, we are safe to make + // further assertions without causing any errors + assert.Equal("Something", object.Value) + } +} +``` + +[`require`](http://godoc.org/github.com/stretchr/testify/require "API documentation") package +--------------------------------------------------------------------------------------------- + +The `require` package provides same global functions as the `assert` package, but instead of returning a boolean result they terminate current test. + +See [t.FailNow](http://golang.org/pkg/testing/#T.FailNow) for details. + +[`mock`](http://godoc.org/github.com/stretchr/testify/mock "API documentation") package +---------------------------------------------------------------------------------------- + +The `mock` package provides a mechanism for easily writing mock objects that can be used in place of real objects when writing test code. + +An example test function that tests a piece of code that relies on an external object `testObj`, can setup expectations (testify) and assert that they indeed happened: + +```go +package yours + +import ( + "testing" + "github.com/stretchr/testify/mock" +) + +/* + Test objects +*/ + +// MyMockedObject is a mocked object that implements an interface +// that describes an object that the code I am testing relies on. +type MyMockedObject struct{ + mock.Mock +} + +// DoSomething is a method on MyMockedObject that implements some interface +// and just records the activity, and returns what the Mock object tells it to. +// +// In the real object, this method would do something useful, but since this +// is a mocked object - we're just going to stub it out. +// +// NOTE: This method is not being tested here, code that uses this object is. +func (m *MyMockedObject) DoSomething(number int) (bool, error) { + + args := m.Called(number) + return args.Bool(0), args.Error(1) + +} + +/* + Actual test functions +*/ + +// TestSomething is an example of how to use our test object to +// make assertions about some target code we are testing. +func TestSomething(t *testing.T) { + + // create an instance of our test object + testObj := new(MyMockedObject) + + // setup expectations + testObj.On("DoSomething", 123).Return(true, nil) + + // call the code we are testing + targetFuncThatDoesSomethingWithObj(testObj) + + // assert that the expectations were met + testObj.AssertExpectations(t) + +} +``` + +For more information on how to write mock code, check out the [API documentation for the `mock` package](http://godoc.org/github.com/stretchr/testify/mock). + +You can use the [mockery tool](http://github.com/vektra/mockery) to autogenerate the mock code against an interface as well, making using mocks much quicker. + +[`suite`](http://godoc.org/github.com/stretchr/testify/suite "API documentation") package +----------------------------------------------------------------------------------------- + +The `suite` package provides functionality that you might be used to from more common object oriented languages. With it, you can build a testing suite as a struct, build setup/teardown methods and testing methods on your struct, and run them with 'go test' as per normal. + +An example suite is shown below: + +```go +// Basic imports +import ( + "testing" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/suite" +) + +// Define the suite, and absorb the built-in basic suite +// functionality from testify - including a T() method which +// returns the current testing context +type ExampleTestSuite struct { + suite.Suite + VariableThatShouldStartAtFive int +} + +// Make sure that VariableThatShouldStartAtFive is set to five +// before each test +func (suite *ExampleTestSuite) SetupTest() { + suite.VariableThatShouldStartAtFive = 5 +} + +// All methods that begin with "Test" are run as tests within a +// suite. +func (suite *ExampleTestSuite) TestExample() { + assert.Equal(suite.T(), 5, suite.VariableThatShouldStartAtFive) +} + +// In order for 'go test' to run this suite, we need to create +// a normal test function and pass our suite to suite.Run +func TestExampleTestSuite(t *testing.T) { + suite.Run(t, new(ExampleTestSuite)) +} +``` + +For a more complete example, using all of the functionality provided by the suite package, look at our [example testing suite](https://github.com/stretchr/testify/blob/master/suite/suite_test.go) + +For more information on writing suites, check out the [API documentation for the `suite` package](http://godoc.org/github.com/stretchr/testify/suite). + +`Suite` object has assertion methods: + +```go +// Basic imports +import ( + "testing" + "github.com/stretchr/testify/suite" +) + +// Define the suite, and absorb the built-in basic suite +// functionality from testify - including assertion methods. +type ExampleTestSuite struct { + suite.Suite + VariableThatShouldStartAtFive int +} + +// Make sure that VariableThatShouldStartAtFive is set to five +// before each test +func (suite *ExampleTestSuite) SetupTest() { + suite.VariableThatShouldStartAtFive = 5 +} + +// All methods that begin with "Test" are run as tests within a +// suite. +func (suite *ExampleTestSuite) TestExample() { + suite.Equal(suite.VariableThatShouldStartAtFive, 5) +} + +// In order for 'go test' to run this suite, we need to create +// a normal test function and pass our suite to suite.Run +func TestExampleTestSuite(t *testing.T) { + suite.Run(t, new(ExampleTestSuite)) +} +``` + +------ + +Installation +============ + +To install Testify, use `go get`: + + go get github.com/stretchr/testify + +This will then make the following packages available to you: + + github.com/stretchr/testify/assert + github.com/stretchr/testify/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`. + +------ + +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. diff --git a/vendor/github.com/stretchr/testify/_codegen/main.go b/vendor/github.com/stretchr/testify/_codegen/main.go new file mode 100644 index 0000000..2e5e812 --- /dev/null +++ b/vendor/github.com/stretchr/testify/_codegen/main.go @@ -0,0 +1,316 @@ +// This program reads all assertion functions from the assert package and +// automatically generates the corresponding requires and forwarded assertions + +package main + +import ( + "bytes" + "flag" + "fmt" + "go/ast" + "go/build" + "go/doc" + "go/format" + "go/importer" + "go/parser" + "go/token" + "go/types" + "io" + "io/ioutil" + "log" + "os" + "path" + "regexp" + "strings" + "text/template" + + "github.com/ernesto-jimenez/gogen/imports" +) + +var ( + pkg = flag.String("assert-path", "github.com/stretchr/testify/assert", "Path to the assert package") + includeF = flag.Bool("include-format-funcs", false, "include format functions such as Errorf and Equalf") + outputPkg = flag.String("output-package", "", "package for the resulting code") + tmplFile = flag.String("template", "", "What file to load the function template from") + out = flag.String("out", "", "What file to write the source code to") +) + +func main() { + flag.Parse() + + scope, docs, err := parsePackageSource(*pkg) + if err != nil { + log.Fatal(err) + } + + importer, funcs, err := analyzeCode(scope, docs) + if err != nil { + log.Fatal(err) + } + + if err := generateCode(importer, funcs); err != nil { + log.Fatal(err) + } +} + +func generateCode(importer imports.Importer, funcs []testFunc) error { + buff := bytes.NewBuffer(nil) + + tmplHead, tmplFunc, err := parseTemplates() + if err != nil { + return err + } + + // Generate header + if err := tmplHead.Execute(buff, struct { + Name string + Imports map[string]string + }{ + *outputPkg, + importer.Imports(), + }); err != nil { + return err + } + + // Generate funcs + for _, fn := range funcs { + buff.Write([]byte("\n\n")) + if err := tmplFunc.Execute(buff, &fn); err != nil { + return err + } + } + + code, err := format.Source(buff.Bytes()) + if err != nil { + return err + } + + // Write file + output, err := outputFile() + if err != nil { + return err + } + defer output.Close() + _, err = io.Copy(output, bytes.NewReader(code)) + return err +} + +func parseTemplates() (*template.Template, *template.Template, error) { + tmplHead, err := template.New("header").Parse(headerTemplate) + if err != nil { + return nil, nil, err + } + if *tmplFile != "" { + f, err := ioutil.ReadFile(*tmplFile) + if err != nil { + return nil, nil, err + } + funcTemplate = string(f) + } + tmpl, err := template.New("function").Parse(funcTemplate) + if err != nil { + return nil, nil, err + } + return tmplHead, tmpl, nil +} + +func outputFile() (*os.File, error) { + filename := *out + if filename == "-" || (filename == "" && *tmplFile == "") { + return os.Stdout, nil + } + if filename == "" { + filename = strings.TrimSuffix(strings.TrimSuffix(*tmplFile, ".tmpl"), ".go") + ".go" + } + return os.Create(filename) +} + +// analyzeCode takes the types scope and the docs and returns the import +// information and information about all the assertion functions. +func analyzeCode(scope *types.Scope, docs *doc.Package) (imports.Importer, []testFunc, error) { + testingT := scope.Lookup("TestingT").Type().Underlying().(*types.Interface) + + importer := imports.New(*outputPkg) + var funcs []testFunc + // Go through all the top level functions + for _, fdocs := range docs.Funcs { + // Find the function + obj := scope.Lookup(fdocs.Name) + + fn, ok := obj.(*types.Func) + if !ok { + continue + } + // Check function signature has at least two arguments + sig := fn.Type().(*types.Signature) + if sig.Params().Len() < 2 { + continue + } + // Check first argument is of type testingT + first, ok := sig.Params().At(0).Type().(*types.Named) + if !ok { + continue + } + firstType, ok := first.Underlying().(*types.Interface) + if !ok { + continue + } + if !types.Implements(firstType, testingT) { + continue + } + + // Skip functions ending with f + if strings.HasSuffix(fdocs.Name, "f") && !*includeF { + continue + } + + funcs = append(funcs, testFunc{*outputPkg, fdocs, fn}) + importer.AddImportsFrom(sig.Params()) + } + return importer, funcs, nil +} + +// parsePackageSource returns the types scope and the package documentation from the package +func parsePackageSource(pkg string) (*types.Scope, *doc.Package, error) { + pd, err := build.Import(pkg, ".", 0) + if err != nil { + return nil, nil, err + } + + fset := token.NewFileSet() + files := make(map[string]*ast.File) + fileList := make([]*ast.File, len(pd.GoFiles)) + for i, fname := range pd.GoFiles { + src, err := ioutil.ReadFile(path.Join(pd.SrcRoot, pd.ImportPath, fname)) + if err != nil { + return nil, nil, err + } + f, err := parser.ParseFile(fset, fname, src, parser.ParseComments|parser.AllErrors) + if err != nil { + return nil, nil, err + } + files[fname] = f + fileList[i] = f + } + + cfg := types.Config{ + Importer: importer.Default(), + } + info := types.Info{ + Defs: make(map[*ast.Ident]types.Object), + } + tp, err := cfg.Check(pkg, fset, fileList, &info) + if err != nil { + return nil, nil, err + } + + scope := tp.Scope() + + ap, _ := ast.NewPackage(fset, files, nil, nil) + docs := doc.New(ap, pkg, 0) + + return scope, docs, nil +} + +type testFunc struct { + CurrentPkg string + DocInfo *doc.Func + TypeInfo *types.Func +} + +func (f *testFunc) Qualifier(p *types.Package) string { + if p == nil || p.Name() == f.CurrentPkg { + return "" + } + return p.Name() +} + +func (f *testFunc) Params() string { + sig := f.TypeInfo.Type().(*types.Signature) + params := sig.Params() + p := "" + comma := "" + to := params.Len() + var i int + + if sig.Variadic() { + to-- + } + for i = 1; i < to; i++ { + param := params.At(i) + p += fmt.Sprintf("%s%s %s", comma, param.Name(), types.TypeString(param.Type(), f.Qualifier)) + comma = ", " + } + if sig.Variadic() { + param := params.At(params.Len() - 1) + p += fmt.Sprintf("%s%s ...%s", comma, param.Name(), types.TypeString(param.Type().(*types.Slice).Elem(), f.Qualifier)) + } + return p +} + +func (f *testFunc) ForwardedParams() string { + sig := f.TypeInfo.Type().(*types.Signature) + params := sig.Params() + p := "" + comma := "" + to := params.Len() + var i int + + if sig.Variadic() { + to-- + } + for i = 1; i < to; i++ { + param := params.At(i) + p += fmt.Sprintf("%s%s", comma, param.Name()) + comma = ", " + } + if sig.Variadic() { + param := params.At(params.Len() - 1) + p += fmt.Sprintf("%s%s...", comma, param.Name()) + } + return p +} + +func (f *testFunc) ParamsFormat() string { + return strings.Replace(f.Params(), "msgAndArgs", "msg string, args", 1) +} + +func (f *testFunc) ForwardedParamsFormat() string { + return strings.Replace(f.ForwardedParams(), "msgAndArgs", "append([]interface{}{msg}, args...)", 1) +} + +func (f *testFunc) Comment() string { + return "// " + strings.Replace(strings.TrimSpace(f.DocInfo.Doc), "\n", "\n// ", -1) +} + +func (f *testFunc) CommentFormat() string { + search := fmt.Sprintf("%s", f.DocInfo.Name) + replace := fmt.Sprintf("%sf", f.DocInfo.Name) + comment := strings.Replace(f.Comment(), search, replace, -1) + exp := regexp.MustCompile(replace + `\(((\(\)|[^)])+)\)`) + return exp.ReplaceAllString(comment, replace+`($1, "error message %s", "formatted")`) +} + +func (f *testFunc) CommentWithoutT(receiver string) string { + search := fmt.Sprintf("assert.%s(t, ", f.DocInfo.Name) + replace := fmt.Sprintf("%s.%s(", receiver, f.DocInfo.Name) + return strings.Replace(f.Comment(), search, replace, -1) +} + +var headerTemplate = `/* +* CODE GENERATED AUTOMATICALLY WITH github.com/stretchr/testify/_codegen +* THIS FILE MUST NOT BE EDITED BY HAND +*/ + +package {{.Name}} + +import ( +{{range $path, $name := .Imports}} + {{$name}} "{{$path}}"{{end}} +) +` + +var funcTemplate = `{{.Comment}} +func (fwd *AssertionsForwarder) {{.DocInfo.Name}}({{.Params}}) bool { + return assert.{{.DocInfo.Name}}({{.ForwardedParams}}) +}` diff --git a/vendor/src/github.com/stretchr/testify/assert/assertion_format.go b/vendor/github.com/stretchr/testify/assert/assertion_format.go similarity index 99% rename from vendor/src/github.com/stretchr/testify/assert/assertion_format.go rename to vendor/github.com/stretchr/testify/assert/assertion_format.go index e35541a..ae06a54 100644 --- a/vendor/src/github.com/stretchr/testify/assert/assertion_format.go +++ b/vendor/github.com/stretchr/testify/assert/assertion_format.go @@ -35,7 +35,7 @@ func DirExistsf(t TestingT, path string, msg string, args ...interface{}) bool { // listB(array, slice...) ignoring the order of the elements. If there are duplicate elements, // the number of appearances of each of them in both lists should match. // -// assert.ElementsMatchf(t, [1, 3, 2, 3], [1, 3, 3, 2], "error message %s", "formatted")) +// assert.ElementsMatchf(t, [1, 3, 2, 3], [1, 3, 3, 2], "error message %s", "formatted") func ElementsMatchf(t TestingT, listA interface{}, listB interface{}, msg string, args ...interface{}) bool { return ElementsMatch(t, listA, listB, append([]interface{}{msg}, args...)...) } diff --git a/vendor/src/github.com/stretchr/testify/assert/assertion_format.go.tmpl b/vendor/github.com/stretchr/testify/assert/assertion_format.go.tmpl similarity index 100% rename from vendor/src/github.com/stretchr/testify/assert/assertion_format.go.tmpl rename to vendor/github.com/stretchr/testify/assert/assertion_format.go.tmpl diff --git a/vendor/src/github.com/stretchr/testify/assert/assertion_forward.go b/vendor/github.com/stretchr/testify/assert/assertion_forward.go similarity index 99% rename from vendor/src/github.com/stretchr/testify/assert/assertion_forward.go rename to vendor/github.com/stretchr/testify/assert/assertion_forward.go index 04748be..ffa5428 100644 --- a/vendor/src/github.com/stretchr/testify/assert/assertion_forward.go +++ b/vendor/github.com/stretchr/testify/assert/assertion_forward.go @@ -55,7 +55,7 @@ func (a *Assertions) DirExistsf(path string, msg string, args ...interface{}) bo // listB(array, slice...) ignoring the order of the elements. If there are duplicate elements, // the number of appearances of each of them in both lists should match. // -// a.ElementsMatch([1, 3, 2, 3], [1, 3, 3, 2])) +// a.ElementsMatch([1, 3, 2, 3], [1, 3, 3, 2]) func (a *Assertions) ElementsMatch(listA interface{}, listB interface{}, msgAndArgs ...interface{}) bool { return ElementsMatch(a.t, listA, listB, msgAndArgs...) } @@ -64,7 +64,7 @@ func (a *Assertions) ElementsMatch(listA interface{}, listB interface{}, msgAndA // listB(array, slice...) ignoring the order of the elements. If there are duplicate elements, // the number of appearances of each of them in both lists should match. // -// a.ElementsMatchf([1, 3, 2, 3], [1, 3, 3, 2], "error message %s", "formatted")) +// a.ElementsMatchf([1, 3, 2, 3], [1, 3, 3, 2], "error message %s", "formatted") func (a *Assertions) ElementsMatchf(listA interface{}, listB interface{}, msg string, args ...interface{}) bool { return ElementsMatchf(a.t, listA, listB, msg, args...) } diff --git a/vendor/src/github.com/stretchr/testify/assert/assertion_forward.go.tmpl b/vendor/github.com/stretchr/testify/assert/assertion_forward.go.tmpl similarity index 100% rename from vendor/src/github.com/stretchr/testify/assert/assertion_forward.go.tmpl rename to vendor/github.com/stretchr/testify/assert/assertion_forward.go.tmpl diff --git a/vendor/src/github.com/stretchr/testify/assert/assertions.go b/vendor/github.com/stretchr/testify/assert/assertions.go similarity index 99% rename from vendor/src/github.com/stretchr/testify/assert/assertions.go rename to vendor/github.com/stretchr/testify/assert/assertions.go index 2015555..47bda77 100644 --- a/vendor/src/github.com/stretchr/testify/assert/assertions.go +++ b/vendor/github.com/stretchr/testify/assert/assertions.go @@ -711,7 +711,7 @@ func NotSubset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) // listB(array, slice...) ignoring the order of the elements. If there are duplicate elements, // the number of appearances of each of them in both lists should match. // -// assert.ElementsMatch(t, [1, 3, 2, 3], [1, 3, 3, 2])) +// assert.ElementsMatch(t, [1, 3, 2, 3], [1, 3, 3, 2]) func ElementsMatch(t TestingT, listA, listB interface{}, msgAndArgs ...interface{}) (ok bool) { if isEmpty(listA) && isEmpty(listB) { return true @@ -947,7 +947,7 @@ func InDeltaMapValues(t TestingT, expected, actual interface{}, delta float64, m actualMap := reflect.ValueOf(actual) if expectedMap.Len() != actualMap.Len() { - return Fail(t, "Arguments must have the same numbe of keys", msgAndArgs...) + return Fail(t, "Arguments must have the same number of keys", msgAndArgs...) } for _, k := range expectedMap.MapKeys() { diff --git a/vendor/src/github.com/stretchr/testify/assert/assertions_test.go b/vendor/github.com/stretchr/testify/assert/assertions_test.go similarity index 100% rename from vendor/src/github.com/stretchr/testify/assert/assertions_test.go rename to vendor/github.com/stretchr/testify/assert/assertions_test.go diff --git a/vendor/src/github.com/stretchr/testify/assert/doc.go b/vendor/github.com/stretchr/testify/assert/doc.go similarity index 100% rename from vendor/src/github.com/stretchr/testify/assert/doc.go rename to vendor/github.com/stretchr/testify/assert/doc.go diff --git a/vendor/src/github.com/stretchr/testify/assert/errors.go b/vendor/github.com/stretchr/testify/assert/errors.go similarity index 100% rename from vendor/src/github.com/stretchr/testify/assert/errors.go rename to vendor/github.com/stretchr/testify/assert/errors.go diff --git a/vendor/src/github.com/stretchr/testify/assert/forward_assertions.go b/vendor/github.com/stretchr/testify/assert/forward_assertions.go similarity index 100% rename from vendor/src/github.com/stretchr/testify/assert/forward_assertions.go rename to vendor/github.com/stretchr/testify/assert/forward_assertions.go diff --git a/vendor/src/github.com/stretchr/testify/assert/forward_assertions_test.go b/vendor/github.com/stretchr/testify/assert/forward_assertions_test.go similarity index 100% rename from vendor/src/github.com/stretchr/testify/assert/forward_assertions_test.go rename to vendor/github.com/stretchr/testify/assert/forward_assertions_test.go diff --git a/vendor/src/github.com/stretchr/testify/assert/http_assertions.go b/vendor/github.com/stretchr/testify/assert/http_assertions.go similarity index 100% rename from vendor/src/github.com/stretchr/testify/assert/http_assertions.go rename to vendor/github.com/stretchr/testify/assert/http_assertions.go diff --git a/vendor/src/github.com/stretchr/testify/assert/http_assertions_test.go b/vendor/github.com/stretchr/testify/assert/http_assertions_test.go similarity index 100% rename from vendor/src/github.com/stretchr/testify/assert/http_assertions_test.go rename to vendor/github.com/stretchr/testify/assert/http_assertions_test.go diff --git a/vendor/github.com/stretchr/testify/doc.go b/vendor/github.com/stretchr/testify/doc.go new file mode 100644 index 0000000..377d5cc --- /dev/null +++ b/vendor/github.com/stretchr/testify/doc.go @@ -0,0 +1,22 @@ +// 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/http/doc.go b/vendor/github.com/stretchr/testify/http/doc.go new file mode 100644 index 0000000..695167c --- /dev/null +++ b/vendor/github.com/stretchr/testify/http/doc.go @@ -0,0 +1,2 @@ +// Package http DEPRECATED USE net/http/httptest +package http diff --git a/vendor/github.com/stretchr/testify/http/test_response_writer.go b/vendor/github.com/stretchr/testify/http/test_response_writer.go new file mode 100644 index 0000000..5c3f813 --- /dev/null +++ b/vendor/github.com/stretchr/testify/http/test_response_writer.go @@ -0,0 +1,49 @@ +package http + +import ( + "net/http" +) + +// TestResponseWriter DEPRECATED: We recommend you use http://golang.org/pkg/net/http/httptest instead. +type TestResponseWriter struct { + + // StatusCode is the last int written by the call to WriteHeader(int) + StatusCode int + + // Output is a string containing the written bytes using the Write([]byte) func. + Output string + + // header is the internal storage of the http.Header object + header http.Header +} + +// Header DEPRECATED: We recommend you use http://golang.org/pkg/net/http/httptest instead. +func (rw *TestResponseWriter) Header() http.Header { + + if rw.header == nil { + rw.header = make(http.Header) + } + + return rw.header +} + +// Write DEPRECATED: We recommend you use http://golang.org/pkg/net/http/httptest instead. +func (rw *TestResponseWriter) Write(bytes []byte) (int, error) { + + // assume 200 success if no header has been set + if rw.StatusCode == 0 { + rw.WriteHeader(200) + } + + // add these bytes to the output string + rw.Output = rw.Output + string(bytes) + + // return normal values + return 0, nil + +} + +// WriteHeader DEPRECATED: We recommend you use http://golang.org/pkg/net/http/httptest instead. +func (rw *TestResponseWriter) WriteHeader(i int) { + rw.StatusCode = i +} diff --git a/vendor/github.com/stretchr/testify/http/test_round_tripper.go b/vendor/github.com/stretchr/testify/http/test_round_tripper.go new file mode 100644 index 0000000..b1e32f1 --- /dev/null +++ b/vendor/github.com/stretchr/testify/http/test_round_tripper.go @@ -0,0 +1,17 @@ +package http + +import ( + "github.com/stretchr/testify/mock" + "net/http" +) + +// TestRoundTripper DEPRECATED USE net/http/httptest +type TestRoundTripper struct { + mock.Mock +} + +// RoundTrip DEPRECATED USE net/http/httptest +func (t *TestRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { + args := t.Called(req) + return args.Get(0).(*http.Response), args.Error(1) +} diff --git a/vendor/github.com/stretchr/testify/mock/doc.go b/vendor/github.com/stretchr/testify/mock/doc.go new file mode 100644 index 0000000..7324128 --- /dev/null +++ b/vendor/github.com/stretchr/testify/mock/doc.go @@ -0,0 +1,44 @@ +// Package mock provides a system by which it is possible to mock your objects +// and verify calls are happening as expected. +// +// Example Usage +// +// The mock package provides an object, Mock, that tracks activity on another object. It is usually +// embedded into a test object as shown below: +// +// type MyTestObject struct { +// // add a Mock object instance +// mock.Mock +// +// // other fields go here as normal +// } +// +// When implementing the methods of an interface, you wire your functions up +// to call the Mock.Called(args...) method, and return the appropriate values. +// +// For example, to mock a method that saves the name and age of a person and returns +// the year of their birth or an error, you might write this: +// +// func (o *MyTestObject) SavePersonDetails(firstname, lastname string, age int) (int, error) { +// args := o.Called(firstname, lastname, age) +// return args.Int(0), args.Error(1) +// } +// +// The Int, Error and Bool methods are examples of strongly typed getters that take the argument +// index position. Given this argument list: +// +// (12, true, "Something") +// +// You could read them out strongly typed like this: +// +// args.Int(0) +// args.Bool(1) +// args.String(2) +// +// For objects of your own type, use the generic Arguments.Get(index) method and make a type assertion: +// +// return args.Get(0).(*MyObject), args.Get(1).(*AnotherObjectOfMine) +// +// This may cause a panic if the object you are getting is nil (the type assertion will fail), in those +// cases you should check for nil first. +package mock diff --git a/vendor/github.com/stretchr/testify/mock/mock.go b/vendor/github.com/stretchr/testify/mock/mock.go new file mode 100644 index 0000000..1e232b5 --- /dev/null +++ b/vendor/github.com/stretchr/testify/mock/mock.go @@ -0,0 +1,815 @@ +package mock + +import ( + "errors" + "fmt" + "reflect" + "regexp" + "runtime" + "strings" + "sync" + "time" + + "github.com/davecgh/go-spew/spew" + "github.com/pmezard/go-difflib/difflib" + "github.com/stretchr/objx" + "github.com/stretchr/testify/assert" +) + +// TestingT is an interface wrapper around *testing.T +type TestingT interface { + Logf(format string, args ...interface{}) + Errorf(format string, args ...interface{}) + FailNow() +} + +/* + Call +*/ + +// Call represents a method call and is used for setting expectations, +// as well as recording activity. +type Call struct { + Parent *Mock + + // The name of the method that was or will be called. + Method string + + // Holds the arguments of the method. + Arguments Arguments + + // Holds the arguments that should be returned when + // this method is called. + ReturnArguments Arguments + + // The number of times to return the return arguments when setting + // expectations. 0 means to always return the value. + Repeatability int + + // Amount of times this call has been called + totalCalls int + + // Call to this method can be optional + optional bool + + // Holds a channel that will be used to block the Return until it either + // receives a message or is closed. nil means it returns immediately. + WaitFor <-chan time.Time + + waitTime time.Duration + + // Holds a handler used to manipulate arguments content that are passed by + // reference. It's useful when mocking methods such as unmarshalers or + // decoders. + RunFn func(Arguments) +} + +func newCall(parent *Mock, methodName string, methodArguments ...interface{}) *Call { + return &Call{ + Parent: parent, + Method: methodName, + Arguments: methodArguments, + ReturnArguments: make([]interface{}, 0), + Repeatability: 0, + WaitFor: nil, + RunFn: nil, + } +} + +func (c *Call) lock() { + c.Parent.mutex.Lock() +} + +func (c *Call) unlock() { + c.Parent.mutex.Unlock() +} + +// Return specifies the return arguments for the expectation. +// +// Mock.On("DoSomething").Return(errors.New("failed")) +func (c *Call) Return(returnArguments ...interface{}) *Call { + c.lock() + defer c.unlock() + + c.ReturnArguments = returnArguments + + return c +} + +// Once indicates that that the mock should only return the value once. +// +// Mock.On("MyMethod", arg1, arg2).Return(returnArg1, returnArg2).Once() +func (c *Call) Once() *Call { + return c.Times(1) +} + +// Twice indicates that that the mock should only return the value twice. +// +// Mock.On("MyMethod", arg1, arg2).Return(returnArg1, returnArg2).Twice() +func (c *Call) Twice() *Call { + return c.Times(2) +} + +// Times indicates that that the mock should only return the indicated number +// of times. +// +// Mock.On("MyMethod", arg1, arg2).Return(returnArg1, returnArg2).Times(5) +func (c *Call) Times(i int) *Call { + c.lock() + defer c.unlock() + c.Repeatability = i + return c +} + +// WaitUntil sets the channel that will block the mock's return until its closed +// or a message is received. +// +// Mock.On("MyMethod", arg1, arg2).WaitUntil(time.After(time.Second)) +func (c *Call) WaitUntil(w <-chan time.Time) *Call { + c.lock() + defer c.unlock() + c.WaitFor = w + return c +} + +// After sets how long to block until the call returns +// +// Mock.On("MyMethod", arg1, arg2).After(time.Second) +func (c *Call) After(d time.Duration) *Call { + c.lock() + defer c.unlock() + c.waitTime = d + return c +} + +// Run sets a handler to be called before returning. It can be used when +// mocking a method such as unmarshalers that takes a pointer to a struct and +// sets properties in such struct +// +// Mock.On("Unmarshal", AnythingOfType("*map[string]interface{}").Return().Run(func(args Arguments) { +// arg := args.Get(0).(*map[string]interface{}) +// arg["foo"] = "bar" +// }) +func (c *Call) Run(fn func(args Arguments)) *Call { + c.lock() + defer c.unlock() + c.RunFn = fn + return c +} + +// Maybe allows the method call to be optional. Not calling an optional method +// will not cause an error while asserting expectations +func (c *Call) Maybe() *Call { + c.lock() + defer c.unlock() + c.optional = true + return c +} + +// On chains a new expectation description onto the mocked interface. This +// allows syntax like. +// +// Mock. +// On("MyMethod", 1).Return(nil). +// On("MyOtherMethod", 'a', 'b', 'c').Return(errors.New("Some Error")) +func (c *Call) On(methodName string, arguments ...interface{}) *Call { + return c.Parent.On(methodName, arguments...) +} + +// Mock is the workhorse used to track activity on another object. +// For an example of its usage, refer to the "Example Usage" section at the top +// of this document. +type Mock struct { + // Represents the calls that are expected of + // an object. + ExpectedCalls []*Call + + // Holds the calls that were made to this mocked object. + Calls []Call + + // TestData holds any data that might be useful for testing. Testify ignores + // this data completely allowing you to do whatever you like with it. + testData objx.Map + + mutex sync.Mutex +} + +// TestData holds any data that might be useful for testing. Testify ignores +// this data completely allowing you to do whatever you like with it. +func (m *Mock) TestData() objx.Map { + + if m.testData == nil { + m.testData = make(objx.Map) + } + + return m.testData +} + +/* + Setting expectations +*/ + +// On starts a description of an expectation of the specified method +// being called. +// +// Mock.On("MyMethod", arg1, arg2) +func (m *Mock) On(methodName string, arguments ...interface{}) *Call { + for _, arg := range arguments { + if v := reflect.ValueOf(arg); v.Kind() == reflect.Func { + panic(fmt.Sprintf("cannot use Func in expectations. Use mock.AnythingOfType(\"%T\")", arg)) + } + } + + m.mutex.Lock() + defer m.mutex.Unlock() + c := newCall(m, methodName, arguments...) + m.ExpectedCalls = append(m.ExpectedCalls, c) + return c +} + +// /* +// Recording and responding to activity +// */ + +func (m *Mock) findExpectedCall(method string, arguments ...interface{}) (int, *Call) { + for i, call := range m.ExpectedCalls { + if call.Method == method && call.Repeatability > -1 { + + _, diffCount := call.Arguments.Diff(arguments) + if diffCount == 0 { + return i, call + } + + } + } + return -1, nil +} + +func (m *Mock) findClosestCall(method string, arguments ...interface{}) (bool, *Call) { + diffCount := 0 + var closestCall *Call + + for _, call := range m.expectedCalls() { + if call.Method == method { + + _, tempDiffCount := call.Arguments.Diff(arguments) + if tempDiffCount < diffCount || diffCount == 0 { + diffCount = tempDiffCount + closestCall = call + } + + } + } + + if closestCall == nil { + return false, nil + } + + return true, closestCall +} + +func callString(method string, arguments Arguments, includeArgumentValues bool) string { + + var argValsString string + if includeArgumentValues { + var argVals []string + for argIndex, arg := range arguments { + argVals = append(argVals, fmt.Sprintf("%d: %#v", argIndex, arg)) + } + argValsString = fmt.Sprintf("\n\t\t%s", strings.Join(argVals, "\n\t\t")) + } + + return fmt.Sprintf("%s(%s)%s", method, arguments.String(), argValsString) +} + +// Called tells the mock object that a method has been called, and gets an array +// of arguments to return. Panics if the call is unexpected (i.e. not preceded by +// appropriate .On .Return() calls) +// If Call.WaitFor is set, blocks until the channel is closed or receives a message. +func (m *Mock) Called(arguments ...interface{}) Arguments { + // get the calling function's name + pc, _, _, ok := runtime.Caller(1) + if !ok { + panic("Couldn't get the caller information") + } + functionPath := runtime.FuncForPC(pc).Name() + //Next four lines are required to use GCCGO function naming conventions. + //For Ex: github_com_docker_libkv_store_mock.WatchTree.pN39_github_com_docker_libkv_store_mock.Mock + //uses interface information unlike golang github.com/docker/libkv/store/mock.(*Mock).WatchTree + //With GCCGO we need to remove interface information starting from pN
. + re := regexp.MustCompile("\\.pN\\d+_") + if re.MatchString(functionPath) { + functionPath = re.Split(functionPath, -1)[0] + } + parts := strings.Split(functionPath, ".") + functionName := parts[len(parts)-1] + return m.MethodCalled(functionName, arguments...) +} + +// MethodCalled tells the mock object that the given method has been called, and gets +// an array of arguments to return. Panics if the call is unexpected (i.e. not preceded +// by appropriate .On .Return() calls) +// If Call.WaitFor is set, blocks until the channel is closed or receives a message. +func (m *Mock) MethodCalled(methodName string, arguments ...interface{}) Arguments { + m.mutex.Lock() + found, call := m.findExpectedCall(methodName, arguments...) + + if found < 0 { + // we have to fail here - because we don't know what to do + // as the return arguments. This is because: + // + // a) this is a totally unexpected call to this method, + // b) the arguments are not what was expected, or + // c) the developer has forgotten to add an accompanying On...Return pair. + + closestFound, closestCall := m.findClosestCall(methodName, arguments...) + m.mutex.Unlock() + + if closestFound { + panic(fmt.Sprintf("\n\nmock: Unexpected Method Call\n-----------------------------\n\n%s\n\nThe closest call I have is: \n\n%s\n\n%s\n", callString(methodName, arguments, true), callString(methodName, closestCall.Arguments, true), diffArguments(closestCall.Arguments, arguments))) + } else { + panic(fmt.Sprintf("\nassert: mock: I don't know what to return because the method call was unexpected.\n\tEither do Mock.On(\"%s\").Return(...) first, or remove the %s() call.\n\tThis method was unexpected:\n\t\t%s\n\tat: %s", methodName, methodName, callString(methodName, arguments, true), assert.CallerInfo())) + } + } + + if call.Repeatability == 1 { + call.Repeatability = -1 + } else if call.Repeatability > 1 { + call.Repeatability-- + } + call.totalCalls++ + + // add the call + m.Calls = append(m.Calls, *newCall(m, methodName, arguments...)) + m.mutex.Unlock() + + // block if specified + if call.WaitFor != nil { + <-call.WaitFor + } else { + time.Sleep(call.waitTime) + } + + m.mutex.Lock() + runFn := call.RunFn + m.mutex.Unlock() + + if runFn != nil { + runFn(arguments) + } + + m.mutex.Lock() + returnArgs := call.ReturnArguments + m.mutex.Unlock() + + return returnArgs +} + +/* + Assertions +*/ + +type assertExpectationser interface { + AssertExpectations(TestingT) bool +} + +// AssertExpectationsForObjects asserts that everything specified with On and Return +// of the specified objects was in fact called as expected. +// +// Calls may have occurred in any order. +func AssertExpectationsForObjects(t TestingT, testObjects ...interface{}) bool { + for _, obj := range testObjects { + if m, ok := obj.(Mock); ok { + t.Logf("Deprecated mock.AssertExpectationsForObjects(myMock.Mock) use mock.AssertExpectationsForObjects(myMock)") + obj = &m + } + m := obj.(assertExpectationser) + if !m.AssertExpectations(t) { + return false + } + } + return true +} + +// AssertExpectations asserts that everything specified with On and Return was +// in fact called as expected. Calls may have occurred in any order. +func (m *Mock) AssertExpectations(t TestingT) bool { + m.mutex.Lock() + defer m.mutex.Unlock() + var somethingMissing bool + var failedExpectations int + + // iterate through each expectation + expectedCalls := m.expectedCalls() + for _, expectedCall := range expectedCalls { + if !expectedCall.optional && !m.methodWasCalled(expectedCall.Method, expectedCall.Arguments) && expectedCall.totalCalls == 0 { + somethingMissing = true + failedExpectations++ + t.Logf("FAIL:\t%s(%s)", expectedCall.Method, expectedCall.Arguments.String()) + } else { + if expectedCall.Repeatability > 0 { + somethingMissing = true + failedExpectations++ + t.Logf("FAIL:\t%s(%s)", expectedCall.Method, expectedCall.Arguments.String()) + } else { + t.Logf("PASS:\t%s(%s)", expectedCall.Method, expectedCall.Arguments.String()) + } + } + } + + if somethingMissing { + t.Errorf("FAIL: %d out of %d expectation(s) were met.\n\tThe code you are testing needs to make %d more call(s).\n\tat: %s", len(expectedCalls)-failedExpectations, len(expectedCalls), failedExpectations, assert.CallerInfo()) + } + + return !somethingMissing +} + +// AssertNumberOfCalls asserts that the method was called expectedCalls times. +func (m *Mock) AssertNumberOfCalls(t TestingT, methodName string, expectedCalls int) bool { + m.mutex.Lock() + defer m.mutex.Unlock() + var actualCalls int + for _, call := range m.calls() { + if call.Method == methodName { + actualCalls++ + } + } + return assert.Equal(t, expectedCalls, actualCalls, fmt.Sprintf("Expected number of calls (%d) does not match the actual number of calls (%d).", expectedCalls, actualCalls)) +} + +// AssertCalled asserts that the method was called. +// It can produce a false result when an argument is a pointer type and the underlying value changed after calling the mocked method. +func (m *Mock) AssertCalled(t TestingT, methodName string, arguments ...interface{}) bool { + m.mutex.Lock() + defer m.mutex.Unlock() + if !assert.True(t, m.methodWasCalled(methodName, arguments), fmt.Sprintf("The \"%s\" method should have been called with %d argument(s), but was not.", methodName, len(arguments))) { + t.Logf("%v", m.expectedCalls()) + return false + } + return true +} + +// AssertNotCalled asserts that the method was not called. +// It can produce a false result when an argument is a pointer type and the underlying value changed after calling the mocked method. +func (m *Mock) AssertNotCalled(t TestingT, methodName string, arguments ...interface{}) bool { + m.mutex.Lock() + defer m.mutex.Unlock() + if !assert.False(t, m.methodWasCalled(methodName, arguments), fmt.Sprintf("The \"%s\" method was called with %d argument(s), but should NOT have been.", methodName, len(arguments))) { + t.Logf("%v", m.expectedCalls()) + return false + } + return true +} + +func (m *Mock) methodWasCalled(methodName string, expected []interface{}) bool { + for _, call := range m.calls() { + if call.Method == methodName { + + _, differences := Arguments(expected).Diff(call.Arguments) + + if differences == 0 { + // found the expected call + return true + } + + } + } + // we didn't find the expected call + return false +} + +func (m *Mock) expectedCalls() []*Call { + return append([]*Call{}, m.ExpectedCalls...) +} + +func (m *Mock) calls() []Call { + return append([]Call{}, m.Calls...) +} + +/* + Arguments +*/ + +// Arguments holds an array of method arguments or return values. +type Arguments []interface{} + +const ( + // Anything is used in Diff and Assert when the argument being tested + // shouldn't be taken into consideration. + Anything string = "mock.Anything" +) + +// AnythingOfTypeArgument is a string that contains the type of an argument +// for use when type checking. Used in Diff and Assert. +type AnythingOfTypeArgument string + +// AnythingOfType returns an AnythingOfTypeArgument object containing the +// name of the type to check for. Used in Diff and Assert. +// +// For example: +// Assert(t, AnythingOfType("string"), AnythingOfType("int")) +func AnythingOfType(t string) AnythingOfTypeArgument { + return AnythingOfTypeArgument(t) +} + +// argumentMatcher performs custom argument matching, returning whether or +// not the argument is matched by the expectation fixture function. +type argumentMatcher struct { + // fn is a function which accepts one argument, and returns a bool. + fn reflect.Value +} + +func (f argumentMatcher) Matches(argument interface{}) bool { + expectType := f.fn.Type().In(0) + expectTypeNilSupported := false + switch expectType.Kind() { + case reflect.Interface, reflect.Chan, reflect.Func, reflect.Map, reflect.Slice, reflect.Ptr: + expectTypeNilSupported = true + } + + argType := reflect.TypeOf(argument) + var arg reflect.Value + if argType == nil { + arg = reflect.New(expectType).Elem() + } else { + arg = reflect.ValueOf(argument) + } + + if argType == nil && !expectTypeNilSupported { + panic(errors.New("attempting to call matcher with nil for non-nil expected type")) + } + if argType == nil || argType.AssignableTo(expectType) { + result := f.fn.Call([]reflect.Value{arg}) + return result[0].Bool() + } + return false +} + +func (f argumentMatcher) String() string { + return fmt.Sprintf("func(%s) bool", f.fn.Type().In(0).Name()) +} + +// MatchedBy can be used to match a mock call based on only certain properties +// from a complex struct or some calculation. It takes a function that will be +// evaluated with the called argument and will return true when there's a match +// and false otherwise. +// +// Example: +// m.On("Do", MatchedBy(func(req *http.Request) bool { return req.Host == "example.com" })) +// +// |fn|, must be a function accepting a single argument (of the expected type) +// which returns a bool. If |fn| doesn't match the required signature, +// MatchedBy() panics. +func MatchedBy(fn interface{}) argumentMatcher { + fnType := reflect.TypeOf(fn) + + if fnType.Kind() != reflect.Func { + panic(fmt.Sprintf("assert: arguments: %s is not a func", fn)) + } + if fnType.NumIn() != 1 { + panic(fmt.Sprintf("assert: arguments: %s does not take exactly one argument", fn)) + } + if fnType.NumOut() != 1 || fnType.Out(0).Kind() != reflect.Bool { + panic(fmt.Sprintf("assert: arguments: %s does not return a bool", fn)) + } + + return argumentMatcher{fn: reflect.ValueOf(fn)} +} + +// Get Returns the argument at the specified index. +func (args Arguments) Get(index int) interface{} { + if index+1 > len(args) { + panic(fmt.Sprintf("assert: arguments: Cannot call Get(%d) because there are %d argument(s).", index, len(args))) + } + return args[index] +} + +// Is gets whether the objects match the arguments specified. +func (args Arguments) Is(objects ...interface{}) bool { + for i, obj := range args { + if obj != objects[i] { + return false + } + } + return true +} + +// Diff gets a string describing the differences between the arguments +// and the specified objects. +// +// Returns the diff string and number of differences found. +func (args Arguments) Diff(objects []interface{}) (string, int) { + + var output = "\n" + var differences int + + var maxArgCount = len(args) + if len(objects) > maxArgCount { + maxArgCount = len(objects) + } + + for i := 0; i < maxArgCount; i++ { + var actual, expected interface{} + + if len(objects) <= i { + actual = "(Missing)" + } else { + actual = objects[i] + } + + if len(args) <= i { + expected = "(Missing)" + } else { + expected = args[i] + } + + if matcher, ok := expected.(argumentMatcher); ok { + if matcher.Matches(actual) { + output = fmt.Sprintf("%s\t%d: PASS: %s matched by %s\n", output, i, actual, matcher) + } else { + differences++ + output = fmt.Sprintf("%s\t%d: PASS: %s not matched by %s\n", output, i, actual, matcher) + } + } else if reflect.TypeOf(expected) == reflect.TypeOf((*AnythingOfTypeArgument)(nil)).Elem() { + + // type checking + if reflect.TypeOf(actual).Name() != string(expected.(AnythingOfTypeArgument)) && reflect.TypeOf(actual).String() != string(expected.(AnythingOfTypeArgument)) { + // not match + differences++ + output = fmt.Sprintf("%s\t%d: FAIL: type %s != type %s - %s\n", output, i, expected, reflect.TypeOf(actual).Name(), actual) + } + + } else { + + // normal checking + + if assert.ObjectsAreEqual(expected, Anything) || assert.ObjectsAreEqual(actual, Anything) || assert.ObjectsAreEqual(actual, expected) { + // match + output = fmt.Sprintf("%s\t%d: PASS: %s == %s\n", output, i, actual, expected) + } else { + // not match + differences++ + output = fmt.Sprintf("%s\t%d: FAIL: %s != %s\n", output, i, actual, expected) + } + } + + } + + if differences == 0 { + return "No differences.", differences + } + + return output, differences + +} + +// Assert compares the arguments with the specified objects and fails if +// they do not exactly match. +func (args Arguments) Assert(t TestingT, objects ...interface{}) bool { + + // get the differences + diff, diffCount := args.Diff(objects) + + if diffCount == 0 { + return true + } + + // there are differences... report them... + t.Logf(diff) + t.Errorf("%sArguments do not match.", assert.CallerInfo()) + + return false + +} + +// String gets the argument at the specified index. Panics if there is no argument, or +// if the argument is of the wrong type. +// +// If no index is provided, String() returns a complete string representation +// of the arguments. +func (args Arguments) String(indexOrNil ...int) string { + + if len(indexOrNil) == 0 { + // normal String() method - return a string representation of the args + var argsStr []string + for _, arg := range args { + argsStr = append(argsStr, fmt.Sprintf("%s", reflect.TypeOf(arg))) + } + return strings.Join(argsStr, ",") + } else if len(indexOrNil) == 1 { + // Index has been specified - get the argument at that index + var index = indexOrNil[0] + var s string + var ok bool + if s, ok = args.Get(index).(string); !ok { + panic(fmt.Sprintf("assert: arguments: String(%d) failed because object wasn't correct type: %s", index, args.Get(index))) + } + return s + } + + panic(fmt.Sprintf("assert: arguments: Wrong number of arguments passed to String. Must be 0 or 1, not %d", len(indexOrNil))) + +} + +// Int gets the argument at the specified index. Panics if there is no argument, or +// if the argument is of the wrong type. +func (args Arguments) Int(index int) int { + var s int + var ok bool + if s, ok = args.Get(index).(int); !ok { + panic(fmt.Sprintf("assert: arguments: Int(%d) failed because object wasn't correct type: %v", index, args.Get(index))) + } + return s +} + +// Error gets the argument at the specified index. Panics if there is no argument, or +// if the argument is of the wrong type. +func (args Arguments) Error(index int) error { + obj := args.Get(index) + var s error + var ok bool + if obj == nil { + return nil + } + if s, ok = obj.(error); !ok { + panic(fmt.Sprintf("assert: arguments: Error(%d) failed because object wasn't correct type: %v", index, args.Get(index))) + } + return s +} + +// Bool gets the argument at the specified index. Panics if there is no argument, or +// if the argument is of the wrong type. +func (args Arguments) Bool(index int) bool { + var s bool + var ok bool + if s, ok = args.Get(index).(bool); !ok { + panic(fmt.Sprintf("assert: arguments: Bool(%d) failed because object wasn't correct type: %v", index, args.Get(index))) + } + return s +} + +func typeAndKind(v interface{}) (reflect.Type, reflect.Kind) { + t := reflect.TypeOf(v) + k := t.Kind() + + if k == reflect.Ptr { + t = t.Elem() + k = t.Kind() + } + return t, k +} + +func diffArguments(expected Arguments, actual Arguments) string { + if len(expected) != len(actual) { + return fmt.Sprintf("Provided %v arguments, mocked for %v arguments", len(expected), len(actual)) + } + + for x := range expected { + if diffString := diff(expected[x], actual[x]); diffString != "" { + return fmt.Sprintf("Difference found in argument %v:\n\n%s", x, diffString) + } + } + + return "" +} + +// diff returns a diff of both values as long as both are of the same type and +// are a struct, map, slice or array. Otherwise it returns an empty string. +func diff(expected interface{}, actual interface{}) string { + if expected == nil || actual == nil { + return "" + } + + et, ek := typeAndKind(expected) + at, _ := typeAndKind(actual) + + if et != at { + return "" + } + + if ek != reflect.Struct && ek != reflect.Map && ek != reflect.Slice && ek != reflect.Array { + return "" + } + + e := spewConfig.Sdump(expected) + a := spewConfig.Sdump(actual) + + diff, _ := difflib.GetUnifiedDiffString(difflib.UnifiedDiff{ + A: difflib.SplitLines(e), + B: difflib.SplitLines(a), + FromFile: "Expected", + FromDate: "", + ToFile: "Actual", + ToDate: "", + Context: 1, + }) + + return diff +} + +var spewConfig = spew.ConfigState{ + Indent: " ", + DisablePointerAddresses: true, + DisableCapacities: true, + SortKeys: true, +} diff --git a/vendor/github.com/stretchr/testify/mock/mock_test.go b/vendor/github.com/stretchr/testify/mock/mock_test.go new file mode 100644 index 0000000..cb245ba --- /dev/null +++ b/vendor/github.com/stretchr/testify/mock/mock_test.go @@ -0,0 +1,1352 @@ +package mock + +import ( + "errors" + "fmt" + "sync" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +/* + Test objects +*/ + +// ExampleInterface represents an example interface. +type ExampleInterface interface { + TheExampleMethod(a, b, c int) (int, error) +} + +// TestExampleImplementation is a test implementation of ExampleInterface +type TestExampleImplementation struct { + Mock +} + +func (i *TestExampleImplementation) TheExampleMethod(a, b, c int) (int, error) { + args := i.Called(a, b, c) + return args.Int(0), errors.New("Whoops") +} + +func (i *TestExampleImplementation) TheExampleMethod2(yesorno bool) { + i.Called(yesorno) +} + +type ExampleType struct { + ran bool +} + +func (i *TestExampleImplementation) TheExampleMethod3(et *ExampleType) error { + args := i.Called(et) + return args.Error(0) +} + +func (i *TestExampleImplementation) TheExampleMethod4(v ExampleInterface) error { + args := i.Called(v) + return args.Error(0) +} + +func (i *TestExampleImplementation) TheExampleMethod5(ch chan struct{}) error { + args := i.Called(ch) + return args.Error(0) +} + +func (i *TestExampleImplementation) TheExampleMethod6(m map[string]bool) error { + args := i.Called(m) + return args.Error(0) +} + +func (i *TestExampleImplementation) TheExampleMethod7(slice []bool) error { + args := i.Called(slice) + return args.Error(0) +} + +func (i *TestExampleImplementation) TheExampleMethodFunc(fn func(string) error) error { + args := i.Called(fn) + return args.Error(0) +} + +func (i *TestExampleImplementation) TheExampleMethodVariadic(a ...int) error { + args := i.Called(a) + return args.Error(0) +} + +func (i *TestExampleImplementation) TheExampleMethodVariadicInterface(a ...interface{}) error { + args := i.Called(a) + return args.Error(0) +} + +func (i *TestExampleImplementation) TheExampleMethodMixedVariadic(a int, b ...int) error { + args := i.Called(a, b) + return args.Error(0) +} + +type ExampleFuncType func(string) error + +func (i *TestExampleImplementation) TheExampleMethodFuncType(fn ExampleFuncType) error { + args := i.Called(fn) + return args.Error(0) +} + +/* + Mock +*/ + +func Test_Mock_TestData(t *testing.T) { + + var mockedService = new(TestExampleImplementation) + + if assert.NotNil(t, mockedService.TestData()) { + + mockedService.TestData().Set("something", 123) + assert.Equal(t, 123, mockedService.TestData().Get("something").Data()) + } +} + +func Test_Mock_On(t *testing.T) { + + // make a test impl object + var mockedService = new(TestExampleImplementation) + + c := mockedService.On("TheExampleMethod") + assert.Equal(t, []*Call{c}, mockedService.ExpectedCalls) + assert.Equal(t, "TheExampleMethod", c.Method) +} + +func Test_Mock_Chained_On(t *testing.T) { + // make a test impl object + var mockedService = new(TestExampleImplementation) + + mockedService. + On("TheExampleMethod", 1, 2, 3). + Return(0). + On("TheExampleMethod3", AnythingOfType("*mock.ExampleType")). + Return(nil) + + expectedCalls := []*Call{ + &Call{ + Parent: &mockedService.Mock, + Method: "TheExampleMethod", + Arguments: []interface{}{1, 2, 3}, + ReturnArguments: []interface{}{0}, + }, + &Call{ + Parent: &mockedService.Mock, + Method: "TheExampleMethod3", + Arguments: []interface{}{AnythingOfType("*mock.ExampleType")}, + ReturnArguments: []interface{}{nil}, + }, + } + assert.Equal(t, expectedCalls, mockedService.ExpectedCalls) +} + +func Test_Mock_On_WithArgs(t *testing.T) { + + // make a test impl object + var mockedService = new(TestExampleImplementation) + + c := mockedService.On("TheExampleMethod", 1, 2, 3, 4) + + assert.Equal(t, []*Call{c}, mockedService.ExpectedCalls) + assert.Equal(t, "TheExampleMethod", c.Method) + assert.Equal(t, Arguments{1, 2, 3, 4}, c.Arguments) +} + +func Test_Mock_On_WithFuncArg(t *testing.T) { + + // make a test impl object + var mockedService = new(TestExampleImplementation) + + c := mockedService. + On("TheExampleMethodFunc", AnythingOfType("func(string) error")). + Return(nil) + + assert.Equal(t, []*Call{c}, mockedService.ExpectedCalls) + assert.Equal(t, "TheExampleMethodFunc", c.Method) + assert.Equal(t, 1, len(c.Arguments)) + assert.Equal(t, AnythingOfType("func(string) error"), c.Arguments[0]) + + fn := func(string) error { return nil } + + assert.NotPanics(t, func() { + mockedService.TheExampleMethodFunc(fn) + }) +} + +func Test_Mock_On_WithIntArgMatcher(t *testing.T) { + var mockedService TestExampleImplementation + + mockedService.On("TheExampleMethod", + MatchedBy(func(a int) bool { + return a == 1 + }), MatchedBy(func(b int) bool { + return b == 2 + }), MatchedBy(func(c int) bool { + return c == 3 + })).Return(0, nil) + + assert.Panics(t, func() { + mockedService.TheExampleMethod(1, 2, 4) + }) + assert.Panics(t, func() { + mockedService.TheExampleMethod(2, 2, 3) + }) + assert.NotPanics(t, func() { + mockedService.TheExampleMethod(1, 2, 3) + }) +} + +func Test_Mock_On_WithPtrArgMatcher(t *testing.T) { + var mockedService TestExampleImplementation + + mockedService.On("TheExampleMethod3", + MatchedBy(func(a *ExampleType) bool { return a != nil && a.ran == true }), + ).Return(nil) + + mockedService.On("TheExampleMethod3", + MatchedBy(func(a *ExampleType) bool { return a != nil && a.ran == false }), + ).Return(errors.New("error")) + + mockedService.On("TheExampleMethod3", + MatchedBy(func(a *ExampleType) bool { return a == nil }), + ).Return(errors.New("error2")) + + assert.Equal(t, mockedService.TheExampleMethod3(&ExampleType{true}), nil) + assert.EqualError(t, mockedService.TheExampleMethod3(&ExampleType{false}), "error") + assert.EqualError(t, mockedService.TheExampleMethod3(nil), "error2") +} + +func Test_Mock_On_WithFuncArgMatcher(t *testing.T) { + var mockedService TestExampleImplementation + + fixture1, fixture2 := errors.New("fixture1"), errors.New("fixture2") + + mockedService.On("TheExampleMethodFunc", + MatchedBy(func(a func(string) error) bool { return a != nil && a("string") == fixture1 }), + ).Return(errors.New("fixture1")) + + mockedService.On("TheExampleMethodFunc", + MatchedBy(func(a func(string) error) bool { return a != nil && a("string") == fixture2 }), + ).Return(errors.New("fixture2")) + + mockedService.On("TheExampleMethodFunc", + MatchedBy(func(a func(string) error) bool { return a == nil }), + ).Return(errors.New("fixture3")) + + assert.EqualError(t, mockedService.TheExampleMethodFunc( + func(string) error { return fixture1 }), "fixture1") + assert.EqualError(t, mockedService.TheExampleMethodFunc( + func(string) error { return fixture2 }), "fixture2") + assert.EqualError(t, mockedService.TheExampleMethodFunc(nil), "fixture3") +} + +func Test_Mock_On_WithInterfaceArgMatcher(t *testing.T) { + var mockedService TestExampleImplementation + + mockedService.On("TheExampleMethod4", + MatchedBy(func(a ExampleInterface) bool { return a == nil }), + ).Return(errors.New("fixture1")) + + assert.EqualError(t, mockedService.TheExampleMethod4(nil), "fixture1") +} + +func Test_Mock_On_WithChannelArgMatcher(t *testing.T) { + var mockedService TestExampleImplementation + + mockedService.On("TheExampleMethod5", + MatchedBy(func(ch chan struct{}) bool { return ch == nil }), + ).Return(errors.New("fixture1")) + + assert.EqualError(t, mockedService.TheExampleMethod5(nil), "fixture1") +} + +func Test_Mock_On_WithMapArgMatcher(t *testing.T) { + var mockedService TestExampleImplementation + + mockedService.On("TheExampleMethod6", + MatchedBy(func(m map[string]bool) bool { return m == nil }), + ).Return(errors.New("fixture1")) + + assert.EqualError(t, mockedService.TheExampleMethod6(nil), "fixture1") +} + +func Test_Mock_On_WithSliceArgMatcher(t *testing.T) { + var mockedService TestExampleImplementation + + mockedService.On("TheExampleMethod7", + MatchedBy(func(slice []bool) bool { return slice == nil }), + ).Return(errors.New("fixture1")) + + assert.EqualError(t, mockedService.TheExampleMethod7(nil), "fixture1") +} + +func Test_Mock_On_WithVariadicFunc(t *testing.T) { + + // make a test impl object + var mockedService = new(TestExampleImplementation) + + c := mockedService. + On("TheExampleMethodVariadic", []int{1, 2, 3}). + Return(nil) + + assert.Equal(t, []*Call{c}, mockedService.ExpectedCalls) + assert.Equal(t, 1, len(c.Arguments)) + assert.Equal(t, []int{1, 2, 3}, c.Arguments[0]) + + assert.NotPanics(t, func() { + mockedService.TheExampleMethodVariadic(1, 2, 3) + }) + assert.Panics(t, func() { + mockedService.TheExampleMethodVariadic(1, 2) + }) + +} + +func Test_Mock_On_WithMixedVariadicFunc(t *testing.T) { + + // make a test impl object + var mockedService = new(TestExampleImplementation) + + c := mockedService. + On("TheExampleMethodMixedVariadic", 1, []int{2, 3, 4}). + Return(nil) + + assert.Equal(t, []*Call{c}, mockedService.ExpectedCalls) + assert.Equal(t, 2, len(c.Arguments)) + assert.Equal(t, 1, c.Arguments[0]) + assert.Equal(t, []int{2, 3, 4}, c.Arguments[1]) + + assert.NotPanics(t, func() { + mockedService.TheExampleMethodMixedVariadic(1, 2, 3, 4) + }) + assert.Panics(t, func() { + mockedService.TheExampleMethodMixedVariadic(1, 2, 3, 5) + }) + +} + +func Test_Mock_On_WithVariadicFuncWithInterface(t *testing.T) { + + // make a test impl object + var mockedService = new(TestExampleImplementation) + + c := mockedService.On("TheExampleMethodVariadicInterface", []interface{}{1, 2, 3}). + Return(nil) + + assert.Equal(t, []*Call{c}, mockedService.ExpectedCalls) + assert.Equal(t, 1, len(c.Arguments)) + assert.Equal(t, []interface{}{1, 2, 3}, c.Arguments[0]) + + assert.NotPanics(t, func() { + mockedService.TheExampleMethodVariadicInterface(1, 2, 3) + }) + assert.Panics(t, func() { + mockedService.TheExampleMethodVariadicInterface(1, 2) + }) + +} + +func Test_Mock_On_WithVariadicFuncWithEmptyInterfaceArray(t *testing.T) { + + // make a test impl object + var mockedService = new(TestExampleImplementation) + + var expected []interface{} + c := mockedService. + On("TheExampleMethodVariadicInterface", expected). + Return(nil) + + assert.Equal(t, []*Call{c}, mockedService.ExpectedCalls) + assert.Equal(t, 1, len(c.Arguments)) + assert.Equal(t, expected, c.Arguments[0]) + + assert.NotPanics(t, func() { + mockedService.TheExampleMethodVariadicInterface() + }) + assert.Panics(t, func() { + mockedService.TheExampleMethodVariadicInterface(1, 2) + }) + +} + +func Test_Mock_On_WithFuncPanics(t *testing.T) { + // make a test impl object + var mockedService = new(TestExampleImplementation) + + assert.Panics(t, func() { + mockedService.On("TheExampleMethodFunc", func(string) error { return nil }) + }) +} + +func Test_Mock_On_WithFuncTypeArg(t *testing.T) { + + // make a test impl object + var mockedService = new(TestExampleImplementation) + + c := mockedService. + On("TheExampleMethodFuncType", AnythingOfType("mock.ExampleFuncType")). + Return(nil) + + assert.Equal(t, []*Call{c}, mockedService.ExpectedCalls) + assert.Equal(t, 1, len(c.Arguments)) + assert.Equal(t, AnythingOfType("mock.ExampleFuncType"), c.Arguments[0]) + + fn := func(string) error { return nil } + assert.NotPanics(t, func() { + mockedService.TheExampleMethodFuncType(fn) + }) +} + +func Test_Mock_Return(t *testing.T) { + + // make a test impl object + var mockedService = new(TestExampleImplementation) + + c := mockedService. + On("TheExampleMethod", "A", "B", true). + Return(1, "two", true) + + require.Equal(t, []*Call{c}, mockedService.ExpectedCalls) + + call := mockedService.ExpectedCalls[0] + + assert.Equal(t, "TheExampleMethod", call.Method) + assert.Equal(t, "A", call.Arguments[0]) + assert.Equal(t, "B", call.Arguments[1]) + assert.Equal(t, true, call.Arguments[2]) + assert.Equal(t, 1, call.ReturnArguments[0]) + assert.Equal(t, "two", call.ReturnArguments[1]) + assert.Equal(t, true, call.ReturnArguments[2]) + assert.Equal(t, 0, call.Repeatability) + assert.Nil(t, call.WaitFor) +} + +func Test_Mock_Return_WaitUntil(t *testing.T) { + + // make a test impl object + var mockedService = new(TestExampleImplementation) + ch := time.After(time.Second) + + c := mockedService.Mock. + On("TheExampleMethod", "A", "B", true). + WaitUntil(ch). + Return(1, "two", true) + + // assert that the call was created + require.Equal(t, []*Call{c}, mockedService.ExpectedCalls) + + call := mockedService.ExpectedCalls[0] + + assert.Equal(t, "TheExampleMethod", call.Method) + assert.Equal(t, "A", call.Arguments[0]) + assert.Equal(t, "B", call.Arguments[1]) + assert.Equal(t, true, call.Arguments[2]) + assert.Equal(t, 1, call.ReturnArguments[0]) + assert.Equal(t, "two", call.ReturnArguments[1]) + assert.Equal(t, true, call.ReturnArguments[2]) + assert.Equal(t, 0, call.Repeatability) + assert.Equal(t, ch, call.WaitFor) +} + +func Test_Mock_Return_After(t *testing.T) { + + // make a test impl object + var mockedService = new(TestExampleImplementation) + + c := mockedService.Mock. + On("TheExampleMethod", "A", "B", true). + Return(1, "two", true). + After(time.Second) + + require.Equal(t, []*Call{c}, mockedService.ExpectedCalls) + + call := mockedService.Mock.ExpectedCalls[0] + + assert.Equal(t, "TheExampleMethod", call.Method) + assert.Equal(t, "A", call.Arguments[0]) + assert.Equal(t, "B", call.Arguments[1]) + assert.Equal(t, true, call.Arguments[2]) + assert.Equal(t, 1, call.ReturnArguments[0]) + assert.Equal(t, "two", call.ReturnArguments[1]) + assert.Equal(t, true, call.ReturnArguments[2]) + assert.Equal(t, 0, call.Repeatability) + assert.NotEqual(t, nil, call.WaitFor) + +} + +func Test_Mock_Return_Run(t *testing.T) { + + // make a test impl object + var mockedService = new(TestExampleImplementation) + + fn := func(args Arguments) { + arg := args.Get(0).(*ExampleType) + arg.ran = true + } + + c := mockedService.Mock. + On("TheExampleMethod3", AnythingOfType("*mock.ExampleType")). + Return(nil). + Run(fn) + + require.Equal(t, []*Call{c}, mockedService.ExpectedCalls) + + call := mockedService.Mock.ExpectedCalls[0] + + assert.Equal(t, "TheExampleMethod3", call.Method) + assert.Equal(t, AnythingOfType("*mock.ExampleType"), call.Arguments[0]) + assert.Equal(t, nil, call.ReturnArguments[0]) + assert.Equal(t, 0, call.Repeatability) + assert.NotEqual(t, nil, call.WaitFor) + assert.NotNil(t, call.Run) + + et := ExampleType{} + assert.Equal(t, false, et.ran) + mockedService.TheExampleMethod3(&et) + assert.Equal(t, true, et.ran) +} + +func Test_Mock_Return_Run_Out_Of_Order(t *testing.T) { + // make a test impl object + var mockedService = new(TestExampleImplementation) + f := func(args Arguments) { + arg := args.Get(0).(*ExampleType) + arg.ran = true + } + + c := mockedService.Mock. + On("TheExampleMethod3", AnythingOfType("*mock.ExampleType")). + Run(f). + Return(nil) + + require.Equal(t, []*Call{c}, mockedService.ExpectedCalls) + + call := mockedService.Mock.ExpectedCalls[0] + + assert.Equal(t, "TheExampleMethod3", call.Method) + assert.Equal(t, AnythingOfType("*mock.ExampleType"), call.Arguments[0]) + assert.Equal(t, nil, call.ReturnArguments[0]) + assert.Equal(t, 0, call.Repeatability) + assert.NotEqual(t, nil, call.WaitFor) + assert.NotNil(t, call.Run) +} + +func Test_Mock_Return_Once(t *testing.T) { + + // make a test impl object + var mockedService = new(TestExampleImplementation) + + c := mockedService.On("TheExampleMethod", "A", "B", true). + Return(1, "two", true). + Once() + + require.Equal(t, []*Call{c}, mockedService.ExpectedCalls) + + call := mockedService.ExpectedCalls[0] + + assert.Equal(t, "TheExampleMethod", call.Method) + assert.Equal(t, "A", call.Arguments[0]) + assert.Equal(t, "B", call.Arguments[1]) + assert.Equal(t, true, call.Arguments[2]) + assert.Equal(t, 1, call.ReturnArguments[0]) + assert.Equal(t, "two", call.ReturnArguments[1]) + assert.Equal(t, true, call.ReturnArguments[2]) + assert.Equal(t, 1, call.Repeatability) + assert.Nil(t, call.WaitFor) +} + +func Test_Mock_Return_Twice(t *testing.T) { + + // make a test impl object + var mockedService = new(TestExampleImplementation) + + c := mockedService. + On("TheExampleMethod", "A", "B", true). + Return(1, "two", true). + Twice() + + require.Equal(t, []*Call{c}, mockedService.ExpectedCalls) + + call := mockedService.ExpectedCalls[0] + + assert.Equal(t, "TheExampleMethod", call.Method) + assert.Equal(t, "A", call.Arguments[0]) + assert.Equal(t, "B", call.Arguments[1]) + assert.Equal(t, true, call.Arguments[2]) + assert.Equal(t, 1, call.ReturnArguments[0]) + assert.Equal(t, "two", call.ReturnArguments[1]) + assert.Equal(t, true, call.ReturnArguments[2]) + assert.Equal(t, 2, call.Repeatability) + assert.Nil(t, call.WaitFor) +} + +func Test_Mock_Return_Times(t *testing.T) { + + // make a test impl object + var mockedService = new(TestExampleImplementation) + + c := mockedService. + On("TheExampleMethod", "A", "B", true). + Return(1, "two", true). + Times(5) + + require.Equal(t, []*Call{c}, mockedService.ExpectedCalls) + + call := mockedService.ExpectedCalls[0] + + assert.Equal(t, "TheExampleMethod", call.Method) + assert.Equal(t, "A", call.Arguments[0]) + assert.Equal(t, "B", call.Arguments[1]) + assert.Equal(t, true, call.Arguments[2]) + assert.Equal(t, 1, call.ReturnArguments[0]) + assert.Equal(t, "two", call.ReturnArguments[1]) + assert.Equal(t, true, call.ReturnArguments[2]) + assert.Equal(t, 5, call.Repeatability) + assert.Nil(t, call.WaitFor) +} + +func Test_Mock_Return_Nothing(t *testing.T) { + + // make a test impl object + var mockedService = new(TestExampleImplementation) + + c := mockedService. + On("TheExampleMethod", "A", "B", true). + Return() + + require.Equal(t, []*Call{c}, mockedService.ExpectedCalls) + + call := mockedService.ExpectedCalls[0] + + assert.Equal(t, "TheExampleMethod", call.Method) + assert.Equal(t, "A", call.Arguments[0]) + assert.Equal(t, "B", call.Arguments[1]) + assert.Equal(t, true, call.Arguments[2]) + assert.Equal(t, 0, len(call.ReturnArguments)) +} + +func Test_Mock_findExpectedCall(t *testing.T) { + + m := new(Mock) + m.On("One", 1).Return("one") + m.On("Two", 2).Return("two") + m.On("Two", 3).Return("three") + + f, c := m.findExpectedCall("Two", 3) + + if assert.Equal(t, 2, f) { + if assert.NotNil(t, c) { + assert.Equal(t, "Two", c.Method) + assert.Equal(t, 3, c.Arguments[0]) + assert.Equal(t, "three", c.ReturnArguments[0]) + } + } + +} + +func Test_Mock_findExpectedCall_For_Unknown_Method(t *testing.T) { + + m := new(Mock) + m.On("One", 1).Return("one") + m.On("Two", 2).Return("two") + m.On("Two", 3).Return("three") + + f, _ := m.findExpectedCall("Two") + + assert.Equal(t, -1, f) + +} + +func Test_Mock_findExpectedCall_Respects_Repeatability(t *testing.T) { + + m := new(Mock) + m.On("One", 1).Return("one") + m.On("Two", 2).Return("two").Once() + m.On("Two", 3).Return("three").Twice() + m.On("Two", 3).Return("three").Times(8) + + f, c := m.findExpectedCall("Two", 3) + + if assert.Equal(t, 2, f) { + if assert.NotNil(t, c) { + assert.Equal(t, "Two", c.Method) + assert.Equal(t, 3, c.Arguments[0]) + assert.Equal(t, "three", c.ReturnArguments[0]) + } + } + +} + +func Test_callString(t *testing.T) { + + assert.Equal(t, `Method(int,bool,string)`, callString("Method", []interface{}{1, true, "something"}, false)) + +} + +func Test_Mock_Called(t *testing.T) { + + var mockedService = new(TestExampleImplementation) + + mockedService.On("Test_Mock_Called", 1, 2, 3).Return(5, "6", true) + + returnArguments := mockedService.Called(1, 2, 3) + + if assert.Equal(t, 1, len(mockedService.Calls)) { + assert.Equal(t, "Test_Mock_Called", mockedService.Calls[0].Method) + assert.Equal(t, 1, mockedService.Calls[0].Arguments[0]) + assert.Equal(t, 2, mockedService.Calls[0].Arguments[1]) + assert.Equal(t, 3, mockedService.Calls[0].Arguments[2]) + } + + if assert.Equal(t, 3, len(returnArguments)) { + assert.Equal(t, 5, returnArguments[0]) + assert.Equal(t, "6", returnArguments[1]) + assert.Equal(t, true, returnArguments[2]) + } + +} + +func asyncCall(m *Mock, ch chan Arguments) { + ch <- m.Called(1, 2, 3) +} + +func Test_Mock_Called_blocks(t *testing.T) { + + var mockedService = new(TestExampleImplementation) + + mockedService.Mock.On("asyncCall", 1, 2, 3).Return(5, "6", true).After(2 * time.Millisecond) + + ch := make(chan Arguments) + + go asyncCall(&mockedService.Mock, ch) + + select { + case <-ch: + t.Fatal("should have waited") + case <-time.After(1 * time.Millisecond): + } + + returnArguments := <-ch + + if assert.Equal(t, 1, len(mockedService.Mock.Calls)) { + assert.Equal(t, "asyncCall", mockedService.Mock.Calls[0].Method) + assert.Equal(t, 1, mockedService.Mock.Calls[0].Arguments[0]) + assert.Equal(t, 2, mockedService.Mock.Calls[0].Arguments[1]) + assert.Equal(t, 3, mockedService.Mock.Calls[0].Arguments[2]) + } + + if assert.Equal(t, 3, len(returnArguments)) { + assert.Equal(t, 5, returnArguments[0]) + assert.Equal(t, "6", returnArguments[1]) + assert.Equal(t, true, returnArguments[2]) + } + +} + +func Test_Mock_Called_For_Bounded_Repeatability(t *testing.T) { + + var mockedService = new(TestExampleImplementation) + + mockedService. + On("Test_Mock_Called_For_Bounded_Repeatability", 1, 2, 3). + Return(5, "6", true). + Once() + mockedService. + On("Test_Mock_Called_For_Bounded_Repeatability", 1, 2, 3). + Return(-1, "hi", false) + + returnArguments1 := mockedService.Called(1, 2, 3) + returnArguments2 := mockedService.Called(1, 2, 3) + + if assert.Equal(t, 2, len(mockedService.Calls)) { + assert.Equal(t, "Test_Mock_Called_For_Bounded_Repeatability", mockedService.Calls[0].Method) + assert.Equal(t, 1, mockedService.Calls[0].Arguments[0]) + assert.Equal(t, 2, mockedService.Calls[0].Arguments[1]) + assert.Equal(t, 3, mockedService.Calls[0].Arguments[2]) + + assert.Equal(t, "Test_Mock_Called_For_Bounded_Repeatability", mockedService.Calls[1].Method) + assert.Equal(t, 1, mockedService.Calls[1].Arguments[0]) + assert.Equal(t, 2, mockedService.Calls[1].Arguments[1]) + assert.Equal(t, 3, mockedService.Calls[1].Arguments[2]) + } + + if assert.Equal(t, 3, len(returnArguments1)) { + assert.Equal(t, 5, returnArguments1[0]) + assert.Equal(t, "6", returnArguments1[1]) + assert.Equal(t, true, returnArguments1[2]) + } + + if assert.Equal(t, 3, len(returnArguments2)) { + assert.Equal(t, -1, returnArguments2[0]) + assert.Equal(t, "hi", returnArguments2[1]) + assert.Equal(t, false, returnArguments2[2]) + } + +} + +func Test_Mock_Called_For_SetTime_Expectation(t *testing.T) { + + var mockedService = new(TestExampleImplementation) + + mockedService.On("TheExampleMethod", 1, 2, 3).Return(5, "6", true).Times(4) + + mockedService.TheExampleMethod(1, 2, 3) + mockedService.TheExampleMethod(1, 2, 3) + mockedService.TheExampleMethod(1, 2, 3) + mockedService.TheExampleMethod(1, 2, 3) + assert.Panics(t, func() { + mockedService.TheExampleMethod(1, 2, 3) + }) + +} + +func Test_Mock_Called_Unexpected(t *testing.T) { + + var mockedService = new(TestExampleImplementation) + + // make sure it panics if no expectation was made + assert.Panics(t, func() { + mockedService.Called(1, 2, 3) + }, "Calling unexpected method should panic") + +} + +func Test_AssertExpectationsForObjects_Helper(t *testing.T) { + + var mockedService1 = new(TestExampleImplementation) + var mockedService2 = new(TestExampleImplementation) + var mockedService3 = new(TestExampleImplementation) + + mockedService1.On("Test_AssertExpectationsForObjects_Helper", 1).Return() + mockedService2.On("Test_AssertExpectationsForObjects_Helper", 2).Return() + mockedService3.On("Test_AssertExpectationsForObjects_Helper", 3).Return() + + mockedService1.Called(1) + mockedService2.Called(2) + mockedService3.Called(3) + + assert.True(t, AssertExpectationsForObjects(t, &mockedService1.Mock, &mockedService2.Mock, &mockedService3.Mock)) + assert.True(t, AssertExpectationsForObjects(t, mockedService1, mockedService2, mockedService3)) + +} + +func Test_AssertExpectationsForObjects_Helper_Failed(t *testing.T) { + + var mockedService1 = new(TestExampleImplementation) + var mockedService2 = new(TestExampleImplementation) + var mockedService3 = new(TestExampleImplementation) + + mockedService1.On("Test_AssertExpectationsForObjects_Helper_Failed", 1).Return() + mockedService2.On("Test_AssertExpectationsForObjects_Helper_Failed", 2).Return() + mockedService3.On("Test_AssertExpectationsForObjects_Helper_Failed", 3).Return() + + mockedService1.Called(1) + mockedService3.Called(3) + + tt := new(testing.T) + assert.False(t, AssertExpectationsForObjects(tt, &mockedService1.Mock, &mockedService2.Mock, &mockedService3.Mock)) + assert.False(t, AssertExpectationsForObjects(tt, mockedService1, mockedService2, mockedService3)) + +} + +func Test_Mock_AssertExpectations(t *testing.T) { + + var mockedService = new(TestExampleImplementation) + + mockedService.On("Test_Mock_AssertExpectations", 1, 2, 3).Return(5, 6, 7) + + tt := new(testing.T) + assert.False(t, mockedService.AssertExpectations(tt)) + + // make the call now + mockedService.Called(1, 2, 3) + + // now assert expectations + assert.True(t, mockedService.AssertExpectations(tt)) + +} + +func Test_Mock_AssertExpectations_Placeholder_NoArgs(t *testing.T) { + + var mockedService = new(TestExampleImplementation) + + mockedService.On("Test_Mock_AssertExpectations_Placeholder_NoArgs").Return(5, 6, 7).Once() + mockedService.On("Test_Mock_AssertExpectations_Placeholder_NoArgs").Return(7, 6, 5) + + tt := new(testing.T) + assert.False(t, mockedService.AssertExpectations(tt)) + + // make the call now + mockedService.Called() + + // now assert expectations + assert.True(t, mockedService.AssertExpectations(tt)) + +} + +func Test_Mock_AssertExpectations_Placeholder(t *testing.T) { + + var mockedService = new(TestExampleImplementation) + + mockedService.On("Test_Mock_AssertExpectations_Placeholder", 1, 2, 3).Return(5, 6, 7).Once() + mockedService.On("Test_Mock_AssertExpectations_Placeholder", 3, 2, 1).Return(7, 6, 5) + + tt := new(testing.T) + assert.False(t, mockedService.AssertExpectations(tt)) + + // make the call now + mockedService.Called(1, 2, 3) + + // now assert expectations + assert.False(t, mockedService.AssertExpectations(tt)) + + // make call to the second expectation + mockedService.Called(3, 2, 1) + + // now assert expectations again + assert.True(t, mockedService.AssertExpectations(tt)) +} + +func Test_Mock_AssertExpectations_With_Pointers(t *testing.T) { + + var mockedService = new(TestExampleImplementation) + + mockedService.On("Test_Mock_AssertExpectations_With_Pointers", &struct{ Foo int }{1}).Return(1) + mockedService.On("Test_Mock_AssertExpectations_With_Pointers", &struct{ Foo int }{2}).Return(2) + + tt := new(testing.T) + assert.False(t, mockedService.AssertExpectations(tt)) + + s := struct{ Foo int }{1} + // make the calls now + mockedService.Called(&s) + s.Foo = 2 + mockedService.Called(&s) + + // now assert expectations + assert.True(t, mockedService.AssertExpectations(tt)) + +} + +func Test_Mock_AssertExpectationsCustomType(t *testing.T) { + + var mockedService = new(TestExampleImplementation) + + mockedService.On("TheExampleMethod3", AnythingOfType("*mock.ExampleType")).Return(nil).Once() + + tt := new(testing.T) + assert.False(t, mockedService.AssertExpectations(tt)) + + // make the call now + mockedService.TheExampleMethod3(&ExampleType{}) + + // now assert expectations + assert.True(t, mockedService.AssertExpectations(tt)) + +} + +func Test_Mock_AssertExpectations_With_Repeatability(t *testing.T) { + + var mockedService = new(TestExampleImplementation) + + mockedService.On("Test_Mock_AssertExpectations_With_Repeatability", 1, 2, 3).Return(5, 6, 7).Twice() + + tt := new(testing.T) + assert.False(t, mockedService.AssertExpectations(tt)) + + // make the call now + mockedService.Called(1, 2, 3) + + assert.False(t, mockedService.AssertExpectations(tt)) + + mockedService.Called(1, 2, 3) + + // now assert expectations + assert.True(t, mockedService.AssertExpectations(tt)) + +} + +func Test_Mock_TwoCallsWithDifferentArguments(t *testing.T) { + + var mockedService = new(TestExampleImplementation) + + mockedService.On("Test_Mock_TwoCallsWithDifferentArguments", 1, 2, 3).Return(5, 6, 7) + mockedService.On("Test_Mock_TwoCallsWithDifferentArguments", 4, 5, 6).Return(5, 6, 7) + + args1 := mockedService.Called(1, 2, 3) + assert.Equal(t, 5, args1.Int(0)) + assert.Equal(t, 6, args1.Int(1)) + assert.Equal(t, 7, args1.Int(2)) + + args2 := mockedService.Called(4, 5, 6) + assert.Equal(t, 5, args2.Int(0)) + assert.Equal(t, 6, args2.Int(1)) + assert.Equal(t, 7, args2.Int(2)) + +} + +func Test_Mock_AssertNumberOfCalls(t *testing.T) { + + var mockedService = new(TestExampleImplementation) + + mockedService.On("Test_Mock_AssertNumberOfCalls", 1, 2, 3).Return(5, 6, 7) + + mockedService.Called(1, 2, 3) + assert.True(t, mockedService.AssertNumberOfCalls(t, "Test_Mock_AssertNumberOfCalls", 1)) + + mockedService.Called(1, 2, 3) + assert.True(t, mockedService.AssertNumberOfCalls(t, "Test_Mock_AssertNumberOfCalls", 2)) + +} + +func Test_Mock_AssertCalled(t *testing.T) { + + var mockedService = new(TestExampleImplementation) + + mockedService.On("Test_Mock_AssertCalled", 1, 2, 3).Return(5, 6, 7) + + mockedService.Called(1, 2, 3) + + assert.True(t, mockedService.AssertCalled(t, "Test_Mock_AssertCalled", 1, 2, 3)) + +} + +func Test_Mock_AssertCalled_WithAnythingOfTypeArgument(t *testing.T) { + + var mockedService = new(TestExampleImplementation) + + mockedService. + On("Test_Mock_AssertCalled_WithAnythingOfTypeArgument", Anything, Anything, Anything). + Return() + + mockedService.Called(1, "two", []uint8("three")) + + assert.True(t, mockedService.AssertCalled(t, "Test_Mock_AssertCalled_WithAnythingOfTypeArgument", AnythingOfType("int"), AnythingOfType("string"), AnythingOfType("[]uint8"))) + +} + +func Test_Mock_AssertCalled_WithArguments(t *testing.T) { + + var mockedService = new(TestExampleImplementation) + + mockedService.On("Test_Mock_AssertCalled_WithArguments", 1, 2, 3).Return(5, 6, 7) + + mockedService.Called(1, 2, 3) + + tt := new(testing.T) + assert.True(t, mockedService.AssertCalled(tt, "Test_Mock_AssertCalled_WithArguments", 1, 2, 3)) + assert.False(t, mockedService.AssertCalled(tt, "Test_Mock_AssertCalled_WithArguments", 2, 3, 4)) + +} + +func Test_Mock_AssertCalled_WithArguments_With_Repeatability(t *testing.T) { + + var mockedService = new(TestExampleImplementation) + + mockedService.On("Test_Mock_AssertCalled_WithArguments_With_Repeatability", 1, 2, 3).Return(5, 6, 7).Once() + mockedService.On("Test_Mock_AssertCalled_WithArguments_With_Repeatability", 2, 3, 4).Return(5, 6, 7).Once() + + mockedService.Called(1, 2, 3) + mockedService.Called(2, 3, 4) + + tt := new(testing.T) + assert.True(t, mockedService.AssertCalled(tt, "Test_Mock_AssertCalled_WithArguments_With_Repeatability", 1, 2, 3)) + assert.True(t, mockedService.AssertCalled(tt, "Test_Mock_AssertCalled_WithArguments_With_Repeatability", 2, 3, 4)) + assert.False(t, mockedService.AssertCalled(tt, "Test_Mock_AssertCalled_WithArguments_With_Repeatability", 3, 4, 5)) + +} + +func Test_Mock_AssertNotCalled(t *testing.T) { + + var mockedService = new(TestExampleImplementation) + + mockedService.On("Test_Mock_AssertNotCalled", 1, 2, 3).Return(5, 6, 7) + + mockedService.Called(1, 2, 3) + + assert.True(t, mockedService.AssertNotCalled(t, "Test_Mock_NotCalled")) + +} + +func Test_Mock_AssertOptional(t *testing.T) { + // Optional called + var ms1 = new(TestExampleImplementation) + ms1.On("TheExampleMethod", 1, 2, 3).Maybe().Return(4, nil) + ms1.TheExampleMethod(1, 2, 3) + + tt1 := new(testing.T) + assert.Equal(t, true, ms1.AssertExpectations(tt1)) + + // Optional not called + var ms2 = new(TestExampleImplementation) + ms2.On("TheExampleMethod", 1, 2, 3).Maybe().Return(4, nil) + + tt2 := new(testing.T) + assert.Equal(t, true, ms2.AssertExpectations(tt2)) + + // Non-optional called + var ms3 = new(TestExampleImplementation) + ms3.On("TheExampleMethod", 1, 2, 3).Return(4, nil) + ms3.TheExampleMethod(1, 2, 3) + + tt3 := new(testing.T) + assert.Equal(t, true, ms3.AssertExpectations(tt3)) +} + +/* + Arguments helper methods +*/ +func Test_Arguments_Get(t *testing.T) { + + var args = Arguments([]interface{}{"string", 123, true}) + + assert.Equal(t, "string", args.Get(0).(string)) + assert.Equal(t, 123, args.Get(1).(int)) + assert.Equal(t, true, args.Get(2).(bool)) + +} + +func Test_Arguments_Is(t *testing.T) { + + var args = Arguments([]interface{}{"string", 123, true}) + + assert.True(t, args.Is("string", 123, true)) + assert.False(t, args.Is("wrong", 456, false)) + +} + +func Test_Arguments_Diff(t *testing.T) { + + var args = Arguments([]interface{}{"Hello World", 123, true}) + var diff string + var count int + diff, count = args.Diff([]interface{}{"Hello World", 456, "false"}) + + assert.Equal(t, 2, count) + assert.Contains(t, diff, `%!s(int=456) != %!s(int=123)`) + assert.Contains(t, diff, `false != %!s(bool=true)`) + +} + +func Test_Arguments_Diff_DifferentNumberOfArgs(t *testing.T) { + + var args = Arguments([]interface{}{"string", 123, true}) + var diff string + var count int + diff, count = args.Diff([]interface{}{"string", 456, "false", "extra"}) + + assert.Equal(t, 3, count) + assert.Contains(t, diff, `extra != (Missing)`) + +} + +func Test_Arguments_Diff_WithAnythingArgument(t *testing.T) { + + var args = Arguments([]interface{}{"string", 123, true}) + var count int + _, count = args.Diff([]interface{}{"string", Anything, true}) + + assert.Equal(t, 0, count) + +} + +func Test_Arguments_Diff_WithAnythingArgument_InActualToo(t *testing.T) { + + var args = Arguments([]interface{}{"string", Anything, true}) + var count int + _, count = args.Diff([]interface{}{"string", 123, true}) + + assert.Equal(t, 0, count) + +} + +func Test_Arguments_Diff_WithAnythingOfTypeArgument(t *testing.T) { + + var args = Arguments([]interface{}{"string", AnythingOfType("int"), true}) + var count int + _, count = args.Diff([]interface{}{"string", 123, true}) + + assert.Equal(t, 0, count) + +} + +func Test_Arguments_Diff_WithAnythingOfTypeArgument_Failing(t *testing.T) { + + var args = Arguments([]interface{}{"string", AnythingOfType("string"), true}) + var count int + var diff string + diff, count = args.Diff([]interface{}{"string", 123, true}) + + assert.Equal(t, 1, count) + assert.Contains(t, diff, `string != type int - %!s(int=123)`) + +} + +func Test_Arguments_Diff_WithArgMatcher(t *testing.T) { + matchFn := func(a int) bool { + return a == 123 + } + var args = Arguments([]interface{}{"string", MatchedBy(matchFn), true}) + + diff, count := args.Diff([]interface{}{"string", 124, true}) + assert.Equal(t, 1, count) + assert.Contains(t, diff, `%!s(int=124) not matched by func(int) bool`) + + diff, count = args.Diff([]interface{}{"string", false, true}) + assert.Equal(t, 1, count) + assert.Contains(t, diff, `%!s(bool=false) not matched by func(int) bool`) + + diff, count = args.Diff([]interface{}{"string", 123, false}) + assert.Contains(t, diff, `%!s(int=123) matched by func(int) bool`) + + diff, count = args.Diff([]interface{}{"string", 123, true}) + assert.Equal(t, 0, count) + assert.Contains(t, diff, `No differences.`) +} + +func Test_Arguments_Assert(t *testing.T) { + + var args = Arguments([]interface{}{"string", 123, true}) + + assert.True(t, args.Assert(t, "string", 123, true)) + +} + +func Test_Arguments_String_Representation(t *testing.T) { + + var args = Arguments([]interface{}{"string", 123, true}) + assert.Equal(t, `string,int,bool`, args.String()) + +} + +func Test_Arguments_String(t *testing.T) { + + var args = Arguments([]interface{}{"string", 123, true}) + assert.Equal(t, "string", args.String(0)) + +} + +func Test_Arguments_Error(t *testing.T) { + + var err = errors.New("An Error") + var args = Arguments([]interface{}{"string", 123, true, err}) + assert.Equal(t, err, args.Error(3)) + +} + +func Test_Arguments_Error_Nil(t *testing.T) { + + var args = Arguments([]interface{}{"string", 123, true, nil}) + assert.Equal(t, nil, args.Error(3)) + +} + +func Test_Arguments_Int(t *testing.T) { + + var args = Arguments([]interface{}{"string", 123, true}) + assert.Equal(t, 123, args.Int(1)) + +} + +func Test_Arguments_Bool(t *testing.T) { + + var args = Arguments([]interface{}{"string", 123, true}) + assert.Equal(t, true, args.Bool(2)) + +} + +func Test_WaitUntil_Parallel(t *testing.T) { + + // make a test impl object + var mockedService *TestExampleImplementation = new(TestExampleImplementation) + + ch1 := make(chan time.Time) + ch2 := make(chan time.Time) + + mockedService.Mock.On("TheExampleMethod2", true).Return().WaitUntil(ch2).Run(func(args Arguments) { + ch1 <- time.Now() + }) + + mockedService.Mock.On("TheExampleMethod2", false).Return().WaitUntil(ch1) + + // Lock both goroutines on the .WaitUntil method + go func() { + mockedService.TheExampleMethod2(false) + }() + go func() { + mockedService.TheExampleMethod2(true) + }() + + // Allow the first call to execute, so the second one executes afterwards + ch2 <- time.Now() +} + +func Test_MockMethodCalled(t *testing.T) { + m := new(Mock) + m.On("foo", "hello").Return("world") + + retArgs := m.MethodCalled("foo", "hello") + require.True(t, len(retArgs) == 1) + require.Equal(t, "world", retArgs[0]) + m.AssertExpectations(t) +} + +// Test to validate fix for racy concurrent call access in MethodCalled() +func Test_MockReturnAndCalledConcurrent(t *testing.T) { + iterations := 1000 + m := &Mock{} + call := m.On("ConcurrencyTestMethod") + + wg := sync.WaitGroup{} + wg.Add(2) + + go func() { + for i := 0; i < iterations; i++ { + call.Return(10) + } + wg.Done() + }() + go func() { + for i := 0; i < iterations; i++ { + ConcurrencyTestMethod(m) + } + wg.Done() + }() + wg.Wait() +} + +type timer struct{ Mock } + +func (s *timer) GetTime(i int) string { + return s.Called(i).Get(0).(string) +} + +func TestAfterTotalWaitTimeWhileExecution(t *testing.T) { + waitDuration := 1 + total, waitMs := 5, time.Millisecond*time.Duration(waitDuration) + aTimer := new(timer) + for i := 0; i < total; i++ { + aTimer.On("GetTime", i).After(waitMs).Return(fmt.Sprintf("Time%d", i)).Once() + } + time.Sleep(waitMs) + start := time.Now() + var results []string + + for i := 0; i < total; i++ { + results = append(results, aTimer.GetTime(i)) + } + + end := time.Now() + elapsedTime := end.Sub(start) + assert.True(t, elapsedTime > waitMs, fmt.Sprintf("Total elapsed time:%v should be atleast greater than %v", elapsedTime, waitMs)) + assert.Equal(t, total, len(results)) + for i, _ := range results { + assert.Equal(t, fmt.Sprintf("Time%d", i), results[i], "Return value of method should be same") + } +} + +func ConcurrencyTestMethod(m *Mock) { + m.Called() +} diff --git a/vendor/github.com/stretchr/testify/package_test.go b/vendor/github.com/stretchr/testify/package_test.go new file mode 100644 index 0000000..7ac5d6d --- /dev/null +++ b/vendor/github.com/stretchr/testify/package_test.go @@ -0,0 +1,12 @@ +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/stretchr/testify/require/doc.go b/vendor/github.com/stretchr/testify/require/doc.go new file mode 100644 index 0000000..169de39 --- /dev/null +++ b/vendor/github.com/stretchr/testify/require/doc.go @@ -0,0 +1,28 @@ +// Package require implements the same assertions as the `assert` package but +// stops test execution when a test fails. +// +// Example Usage +// +// The following is a complete example using require in a standard test function: +// import ( +// "testing" +// "github.com/stretchr/testify/require" +// ) +// +// func TestSomething(t *testing.T) { +// +// var a string = "Hello" +// var b string = "Hello" +// +// require.Equal(t, a, b, "The two words should be the same.") +// +// } +// +// Assertions +// +// The `require` package have same global functions as in the `assert` package, +// but instead of returning a boolean result they call `t.FailNow()`. +// +// Every assertion function also takes an optional string message as the final argument, +// allowing custom error messages to be appended to the message the assertion method outputs. +package require diff --git a/vendor/github.com/stretchr/testify/require/forward_requirements.go b/vendor/github.com/stretchr/testify/require/forward_requirements.go new file mode 100644 index 0000000..ac71d40 --- /dev/null +++ b/vendor/github.com/stretchr/testify/require/forward_requirements.go @@ -0,0 +1,16 @@ +package require + +// Assertions provides assertion methods around the +// TestingT interface. +type Assertions struct { + t TestingT +} + +// New makes a new Assertions object for the specified TestingT. +func New(t TestingT) *Assertions { + return &Assertions{ + t: t, + } +} + +//go:generate go run ../_codegen/main.go -output-package=require -template=require_forward.go.tmpl -include-format-funcs diff --git a/vendor/github.com/stretchr/testify/require/forward_requirements_test.go b/vendor/github.com/stretchr/testify/require/forward_requirements_test.go new file mode 100644 index 0000000..b120ae3 --- /dev/null +++ b/vendor/github.com/stretchr/testify/require/forward_requirements_test.go @@ -0,0 +1,385 @@ +package require + +import ( + "errors" + "testing" + "time" +) + +func TestImplementsWrapper(t *testing.T) { + require := New(t) + + require.Implements((*AssertionTesterInterface)(nil), new(AssertionTesterConformingObject)) + + mockT := new(MockT) + mockRequire := New(mockT) + mockRequire.Implements((*AssertionTesterInterface)(nil), new(AssertionTesterNonConformingObject)) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestIsTypeWrapper(t *testing.T) { + require := New(t) + require.IsType(new(AssertionTesterConformingObject), new(AssertionTesterConformingObject)) + + mockT := new(MockT) + mockRequire := New(mockT) + mockRequire.IsType(new(AssertionTesterConformingObject), new(AssertionTesterNonConformingObject)) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestEqualWrapper(t *testing.T) { + require := New(t) + require.Equal(1, 1) + + mockT := new(MockT) + mockRequire := New(mockT) + mockRequire.Equal(1, 2) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestNotEqualWrapper(t *testing.T) { + require := New(t) + require.NotEqual(1, 2) + + mockT := new(MockT) + mockRequire := New(mockT) + mockRequire.NotEqual(2, 2) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestExactlyWrapper(t *testing.T) { + require := New(t) + + a := float32(1) + b := float32(1) + c := float64(1) + + require.Exactly(a, b) + + mockT := new(MockT) + mockRequire := New(mockT) + mockRequire.Exactly(a, c) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestNotNilWrapper(t *testing.T) { + require := New(t) + require.NotNil(t, new(AssertionTesterConformingObject)) + + mockT := new(MockT) + mockRequire := New(mockT) + mockRequire.NotNil(nil) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestNilWrapper(t *testing.T) { + require := New(t) + require.Nil(nil) + + mockT := new(MockT) + mockRequire := New(mockT) + mockRequire.Nil(new(AssertionTesterConformingObject)) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestTrueWrapper(t *testing.T) { + require := New(t) + require.True(true) + + mockT := new(MockT) + mockRequire := New(mockT) + mockRequire.True(false) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestFalseWrapper(t *testing.T) { + require := New(t) + require.False(false) + + mockT := new(MockT) + mockRequire := New(mockT) + mockRequire.False(true) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestContainsWrapper(t *testing.T) { + require := New(t) + require.Contains("Hello World", "Hello") + + mockT := new(MockT) + mockRequire := New(mockT) + mockRequire.Contains("Hello World", "Salut") + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestNotContainsWrapper(t *testing.T) { + require := New(t) + require.NotContains("Hello World", "Hello!") + + mockT := new(MockT) + mockRequire := New(mockT) + mockRequire.NotContains("Hello World", "Hello") + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestPanicsWrapper(t *testing.T) { + require := New(t) + require.Panics(func() { + panic("Panic!") + }) + + mockT := new(MockT) + mockRequire := New(mockT) + mockRequire.Panics(func() {}) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestNotPanicsWrapper(t *testing.T) { + require := New(t) + require.NotPanics(func() {}) + + mockT := new(MockT) + mockRequire := New(mockT) + mockRequire.NotPanics(func() { + panic("Panic!") + }) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestNoErrorWrapper(t *testing.T) { + require := New(t) + require.NoError(nil) + + mockT := new(MockT) + mockRequire := New(mockT) + mockRequire.NoError(errors.New("some error")) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestErrorWrapper(t *testing.T) { + require := New(t) + require.Error(errors.New("some error")) + + mockT := new(MockT) + mockRequire := New(mockT) + mockRequire.Error(nil) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestEqualErrorWrapper(t *testing.T) { + require := New(t) + require.EqualError(errors.New("some error"), "some error") + + mockT := new(MockT) + mockRequire := New(mockT) + mockRequire.EqualError(errors.New("some error"), "Not some error") + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestEmptyWrapper(t *testing.T) { + require := New(t) + require.Empty("") + + mockT := new(MockT) + mockRequire := New(mockT) + mockRequire.Empty("x") + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestNotEmptyWrapper(t *testing.T) { + require := New(t) + require.NotEmpty("x") + + mockT := new(MockT) + mockRequire := New(mockT) + mockRequire.NotEmpty("") + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestWithinDurationWrapper(t *testing.T) { + require := New(t) + a := time.Now() + b := a.Add(10 * time.Second) + + require.WithinDuration(a, b, 15*time.Second) + + mockT := new(MockT) + mockRequire := New(mockT) + mockRequire.WithinDuration(a, b, 5*time.Second) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestInDeltaWrapper(t *testing.T) { + require := New(t) + require.InDelta(1.001, 1, 0.01) + + mockT := new(MockT) + mockRequire := New(mockT) + mockRequire.InDelta(1, 2, 0.5) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestZeroWrapper(t *testing.T) { + require := New(t) + require.Zero(0) + + mockT := new(MockT) + mockRequire := New(mockT) + mockRequire.Zero(1) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestNotZeroWrapper(t *testing.T) { + require := New(t) + require.NotZero(1) + + mockT := new(MockT) + mockRequire := New(mockT) + mockRequire.NotZero(0) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestJSONEqWrapper_EqualSONString(t *testing.T) { + mockT := new(MockT) + mockRequire := New(mockT) + + mockRequire.JSONEq(`{"hello": "world", "foo": "bar"}`, `{"hello": "world", "foo": "bar"}`) + if mockT.Failed { + t.Error("Check should pass") + } +} + +func TestJSONEqWrapper_EquivalentButNotEqual(t *testing.T) { + mockT := new(MockT) + mockRequire := New(mockT) + + mockRequire.JSONEq(`{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) + if mockT.Failed { + t.Error("Check should pass") + } +} + +func TestJSONEqWrapper_HashOfArraysAndHashes(t *testing.T) { + mockT := new(MockT) + mockRequire := New(mockT) + + mockRequire.JSONEq("{\r\n\t\"numeric\": 1.5,\r\n\t\"array\": [{\"foo\": \"bar\"}, 1, \"string\", [\"nested\", \"array\", 5.5]],\r\n\t\"hash\": {\"nested\": \"hash\", \"nested_slice\": [\"this\", \"is\", \"nested\"]},\r\n\t\"string\": \"foo\"\r\n}", + "{\r\n\t\"numeric\": 1.5,\r\n\t\"hash\": {\"nested\": \"hash\", \"nested_slice\": [\"this\", \"is\", \"nested\"]},\r\n\t\"string\": \"foo\",\r\n\t\"array\": [{\"foo\": \"bar\"}, 1, \"string\", [\"nested\", \"array\", 5.5]]\r\n}") + if mockT.Failed { + t.Error("Check should pass") + } +} + +func TestJSONEqWrapper_Array(t *testing.T) { + mockT := new(MockT) + mockRequire := New(mockT) + + mockRequire.JSONEq(`["foo", {"hello": "world", "nested": "hash"}]`, `["foo", {"nested": "hash", "hello": "world"}]`) + if mockT.Failed { + t.Error("Check should pass") + } +} + +func TestJSONEqWrapper_HashAndArrayNotEquivalent(t *testing.T) { + mockT := new(MockT) + mockRequire := New(mockT) + + mockRequire.JSONEq(`["foo", {"hello": "world", "nested": "hash"}]`, `{"foo": "bar", {"nested": "hash", "hello": "world"}}`) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestJSONEqWrapper_HashesNotEquivalent(t *testing.T) { + mockT := new(MockT) + mockRequire := New(mockT) + + mockRequire.JSONEq(`{"foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestJSONEqWrapper_ActualIsNotJSON(t *testing.T) { + mockT := new(MockT) + mockRequire := New(mockT) + + mockRequire.JSONEq(`{"foo": "bar"}`, "Not JSON") + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestJSONEqWrapper_ExpectedIsNotJSON(t *testing.T) { + mockT := new(MockT) + mockRequire := New(mockT) + + mockRequire.JSONEq("Not JSON", `{"foo": "bar", "hello": "world"}`) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestJSONEqWrapper_ExpectedAndActualNotJSON(t *testing.T) { + mockT := new(MockT) + mockRequire := New(mockT) + + mockRequire.JSONEq("Not JSON", "Not JSON") + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestJSONEqWrapper_ArraysOfDifferentOrder(t *testing.T) { + mockT := new(MockT) + mockRequire := New(mockT) + + mockRequire.JSONEq(`["foo", {"hello": "world", "nested": "hash"}]`, `[{ "hello": "world", "nested": "hash"}, "foo"]`) + if !mockT.Failed { + t.Error("Check should fail") + } +} diff --git a/vendor/github.com/stretchr/testify/require/require.go b/vendor/github.com/stretchr/testify/require/require.go new file mode 100644 index 0000000..ac3c308 --- /dev/null +++ b/vendor/github.com/stretchr/testify/require/require.go @@ -0,0 +1,867 @@ +/* +* CODE GENERATED AUTOMATICALLY WITH github.com/stretchr/testify/_codegen +* THIS FILE MUST NOT BE EDITED BY HAND + */ + +package require + +import ( + assert "github.com/stretchr/testify/assert" + http "net/http" + url "net/url" + time "time" +) + +// Condition uses a Comparison to assert a complex condition. +func Condition(t TestingT, comp assert.Comparison, msgAndArgs ...interface{}) { + if !assert.Condition(t, comp, msgAndArgs...) { + t.FailNow() + } +} + +// Conditionf uses a Comparison to assert a complex condition. +func Conditionf(t TestingT, comp assert.Comparison, msg string, args ...interface{}) { + if !assert.Conditionf(t, comp, msg, args...) { + t.FailNow() + } +} + +// Contains asserts that the specified string, list(array, slice...) or map contains the +// specified substring or element. +// +// assert.Contains(t, "Hello World", "World") +// assert.Contains(t, ["Hello", "World"], "World") +// assert.Contains(t, {"Hello": "World"}, "Hello") +func Contains(t TestingT, s interface{}, contains interface{}, msgAndArgs ...interface{}) { + if !assert.Contains(t, s, contains, msgAndArgs...) { + t.FailNow() + } +} + +// Containsf asserts that the specified string, list(array, slice...) or map contains the +// specified substring or element. +// +// assert.Containsf(t, "Hello World", "World", "error message %s", "formatted") +// assert.Containsf(t, ["Hello", "World"], "World", "error message %s", "formatted") +// assert.Containsf(t, {"Hello": "World"}, "Hello", "error message %s", "formatted") +func Containsf(t TestingT, s interface{}, contains interface{}, msg string, args ...interface{}) { + if !assert.Containsf(t, s, contains, msg, args...) { + t.FailNow() + } +} + +// DirExists checks whether a directory exists in the given path. It also fails if the path is a file rather a directory or there is an error checking whether it exists. +func DirExists(t TestingT, path string, msgAndArgs ...interface{}) { + if !assert.DirExists(t, path, msgAndArgs...) { + t.FailNow() + } +} + +// DirExistsf checks whether a directory exists in the given path. It also fails if the path is a file rather a directory or there is an error checking whether it exists. +func DirExistsf(t TestingT, path string, msg string, args ...interface{}) { + if !assert.DirExistsf(t, path, msg, args...) { + t.FailNow() + } +} + +// ElementsMatch asserts that the specified listA(array, slice...) is equal to specified +// listB(array, slice...) ignoring the order of the elements. If there are duplicate elements, +// the number of appearances of each of them in both lists should match. +// +// assert.ElementsMatch(t, [1, 3, 2, 3], [1, 3, 3, 2]) +func ElementsMatch(t TestingT, listA interface{}, listB interface{}, msgAndArgs ...interface{}) { + if !assert.ElementsMatch(t, listA, listB, msgAndArgs...) { + t.FailNow() + } +} + +// ElementsMatchf asserts that the specified listA(array, slice...) is equal to specified +// listB(array, slice...) ignoring the order of the elements. If there are duplicate elements, +// the number of appearances of each of them in both lists should match. +// +// assert.ElementsMatchf(t, [1, 3, 2, 3], [1, 3, 3, 2], "error message %s", "formatted") +func ElementsMatchf(t TestingT, listA interface{}, listB interface{}, msg string, args ...interface{}) { + if !assert.ElementsMatchf(t, listA, listB, msg, args...) { + t.FailNow() + } +} + +// Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either +// a slice or a channel with len == 0. +// +// assert.Empty(t, obj) +func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) { + if !assert.Empty(t, object, msgAndArgs...) { + t.FailNow() + } +} + +// Emptyf asserts that the specified object is empty. I.e. nil, "", false, 0 or either +// a slice or a channel with len == 0. +// +// assert.Emptyf(t, obj, "error message %s", "formatted") +func Emptyf(t TestingT, object interface{}, msg string, args ...interface{}) { + if !assert.Emptyf(t, object, msg, args...) { + t.FailNow() + } +} + +// Equal asserts that two objects are equal. +// +// assert.Equal(t, 123, 123) +// +// Pointer variable equality is determined based on the equality of the +// referenced values (as opposed to the memory addresses). Function equality +// cannot be determined and will always fail. +func Equal(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) { + if !assert.Equal(t, expected, actual, msgAndArgs...) { + t.FailNow() + } +} + +// EqualError asserts that a function returned an error (i.e. not `nil`) +// and that it is equal to the provided error. +// +// actualObj, err := SomeFunction() +// assert.EqualError(t, err, expectedErrorString) +func EqualError(t TestingT, theError error, errString string, msgAndArgs ...interface{}) { + if !assert.EqualError(t, theError, errString, msgAndArgs...) { + t.FailNow() + } +} + +// EqualErrorf asserts that a function returned an error (i.e. not `nil`) +// and that it is equal to the provided error. +// +// actualObj, err := SomeFunction() +// assert.EqualErrorf(t, err, expectedErrorString, "error message %s", "formatted") +func EqualErrorf(t TestingT, theError error, errString string, msg string, args ...interface{}) { + if !assert.EqualErrorf(t, theError, errString, msg, args...) { + t.FailNow() + } +} + +// EqualValues asserts that two objects are equal or convertable to the same types +// and equal. +// +// assert.EqualValues(t, uint32(123), int32(123)) +func EqualValues(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) { + if !assert.EqualValues(t, expected, actual, msgAndArgs...) { + t.FailNow() + } +} + +// EqualValuesf asserts that two objects are equal or convertable to the same types +// and equal. +// +// assert.EqualValuesf(t, uint32(123, "error message %s", "formatted"), int32(123)) +func EqualValuesf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) { + if !assert.EqualValuesf(t, expected, actual, msg, args...) { + t.FailNow() + } +} + +// Equalf asserts that two objects are equal. +// +// assert.Equalf(t, 123, 123, "error message %s", "formatted") +// +// Pointer variable equality is determined based on the equality of the +// referenced values (as opposed to the memory addresses). Function equality +// cannot be determined and will always fail. +func Equalf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) { + if !assert.Equalf(t, expected, actual, msg, args...) { + t.FailNow() + } +} + +// Error asserts that a function returned an error (i.e. not `nil`). +// +// actualObj, err := SomeFunction() +// if assert.Error(t, err) { +// assert.Equal(t, expectedError, err) +// } +func Error(t TestingT, err error, msgAndArgs ...interface{}) { + if !assert.Error(t, err, msgAndArgs...) { + t.FailNow() + } +} + +// Errorf asserts that a function returned an error (i.e. not `nil`). +// +// actualObj, err := SomeFunction() +// if assert.Errorf(t, err, "error message %s", "formatted") { +// assert.Equal(t, expectedErrorf, err) +// } +func Errorf(t TestingT, err error, msg string, args ...interface{}) { + if !assert.Errorf(t, err, msg, args...) { + t.FailNow() + } +} + +// Exactly asserts that two objects are equal in value and type. +// +// assert.Exactly(t, int32(123), int64(123)) +func Exactly(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) { + if !assert.Exactly(t, expected, actual, msgAndArgs...) { + t.FailNow() + } +} + +// Exactlyf asserts that two objects are equal in value and type. +// +// assert.Exactlyf(t, int32(123, "error message %s", "formatted"), int64(123)) +func Exactlyf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) { + if !assert.Exactlyf(t, expected, actual, msg, args...) { + t.FailNow() + } +} + +// Fail reports a failure through +func Fail(t TestingT, failureMessage string, msgAndArgs ...interface{}) { + if !assert.Fail(t, failureMessage, msgAndArgs...) { + t.FailNow() + } +} + +// FailNow fails test +func FailNow(t TestingT, failureMessage string, msgAndArgs ...interface{}) { + if !assert.FailNow(t, failureMessage, msgAndArgs...) { + t.FailNow() + } +} + +// FailNowf fails test +func FailNowf(t TestingT, failureMessage string, msg string, args ...interface{}) { + if !assert.FailNowf(t, failureMessage, msg, args...) { + t.FailNow() + } +} + +// Failf reports a failure through +func Failf(t TestingT, failureMessage string, msg string, args ...interface{}) { + if !assert.Failf(t, failureMessage, msg, args...) { + t.FailNow() + } +} + +// False asserts that the specified value is false. +// +// assert.False(t, myBool) +func False(t TestingT, value bool, msgAndArgs ...interface{}) { + if !assert.False(t, value, msgAndArgs...) { + t.FailNow() + } +} + +// Falsef asserts that the specified value is false. +// +// assert.Falsef(t, myBool, "error message %s", "formatted") +func Falsef(t TestingT, value bool, msg string, args ...interface{}) { + if !assert.Falsef(t, value, msg, args...) { + t.FailNow() + } +} + +// FileExists checks whether a file exists in the given path. It also fails if the path points to a directory or there is an error when trying to check the file. +func FileExists(t TestingT, path string, msgAndArgs ...interface{}) { + if !assert.FileExists(t, path, msgAndArgs...) { + t.FailNow() + } +} + +// FileExistsf checks whether a file exists in the given path. It also fails if the path points to a directory or there is an error when trying to check the file. +func FileExistsf(t TestingT, path string, msg string, args ...interface{}) { + if !assert.FileExistsf(t, path, msg, args...) { + t.FailNow() + } +} + +// HTTPBodyContains asserts that a specified handler returns a +// body that contains a string. +// +// assert.HTTPBodyContains(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky") +// +// Returns whether the assertion was successful (true) or not (false). +func HTTPBodyContains(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) { + if !assert.HTTPBodyContains(t, handler, method, url, values, str, msgAndArgs...) { + t.FailNow() + } +} + +// HTTPBodyContainsf asserts that a specified handler returns a +// body that contains a string. +// +// assert.HTTPBodyContainsf(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func HTTPBodyContainsf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) { + if !assert.HTTPBodyContainsf(t, handler, method, url, values, str, msg, args...) { + t.FailNow() + } +} + +// HTTPBodyNotContains asserts that a specified handler returns a +// body that does not contain a string. +// +// assert.HTTPBodyNotContains(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky") +// +// Returns whether the assertion was successful (true) or not (false). +func HTTPBodyNotContains(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) { + if !assert.HTTPBodyNotContains(t, handler, method, url, values, str, msgAndArgs...) { + t.FailNow() + } +} + +// HTTPBodyNotContainsf asserts that a specified handler returns a +// body that does not contain a string. +// +// assert.HTTPBodyNotContainsf(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func HTTPBodyNotContainsf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) { + if !assert.HTTPBodyNotContainsf(t, handler, method, url, values, str, msg, args...) { + t.FailNow() + } +} + +// HTTPError asserts that a specified handler returns an error status code. +// +// assert.HTTPError(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} +// +// Returns whether the assertion was successful (true) or not (false). +func HTTPError(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) { + if !assert.HTTPError(t, handler, method, url, values, msgAndArgs...) { + t.FailNow() + } +} + +// HTTPErrorf asserts that a specified handler returns an error status code. +// +// assert.HTTPErrorf(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} +// +// Returns whether the assertion was successful (true, "error message %s", "formatted") or not (false). +func HTTPErrorf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) { + if !assert.HTTPErrorf(t, handler, method, url, values, msg, args...) { + t.FailNow() + } +} + +// HTTPRedirect asserts that a specified handler returns a redirect status code. +// +// assert.HTTPRedirect(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} +// +// Returns whether the assertion was successful (true) or not (false). +func HTTPRedirect(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) { + if !assert.HTTPRedirect(t, handler, method, url, values, msgAndArgs...) { + t.FailNow() + } +} + +// HTTPRedirectf asserts that a specified handler returns a redirect status code. +// +// assert.HTTPRedirectf(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} +// +// Returns whether the assertion was successful (true, "error message %s", "formatted") or not (false). +func HTTPRedirectf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) { + if !assert.HTTPRedirectf(t, handler, method, url, values, msg, args...) { + t.FailNow() + } +} + +// HTTPSuccess asserts that a specified handler returns a success status code. +// +// assert.HTTPSuccess(t, myHandler, "POST", "http://www.google.com", nil) +// +// Returns whether the assertion was successful (true) or not (false). +func HTTPSuccess(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) { + if !assert.HTTPSuccess(t, handler, method, url, values, msgAndArgs...) { + t.FailNow() + } +} + +// HTTPSuccessf asserts that a specified handler returns a success status code. +// +// assert.HTTPSuccessf(t, myHandler, "POST", "http://www.google.com", nil, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func HTTPSuccessf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) { + if !assert.HTTPSuccessf(t, handler, method, url, values, msg, args...) { + t.FailNow() + } +} + +// Implements asserts that an object is implemented by the specified interface. +// +// assert.Implements(t, (*MyInterface)(nil), new(MyObject)) +func Implements(t TestingT, interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) { + if !assert.Implements(t, interfaceObject, object, msgAndArgs...) { + t.FailNow() + } +} + +// Implementsf asserts that an object is implemented by the specified interface. +// +// assert.Implementsf(t, (*MyInterface, "error message %s", "formatted")(nil), new(MyObject)) +func Implementsf(t TestingT, interfaceObject interface{}, object interface{}, msg string, args ...interface{}) { + if !assert.Implementsf(t, interfaceObject, object, msg, args...) { + t.FailNow() + } +} + +// InDelta asserts that the two numerals are within delta of each other. +// +// assert.InDelta(t, math.Pi, (22 / 7.0), 0.01) +func InDelta(t TestingT, expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) { + if !assert.InDelta(t, expected, actual, delta, msgAndArgs...) { + t.FailNow() + } +} + +// InDeltaMapValues is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys. +func InDeltaMapValues(t TestingT, expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) { + if !assert.InDeltaMapValues(t, expected, actual, delta, msgAndArgs...) { + t.FailNow() + } +} + +// InDeltaMapValuesf is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys. +func InDeltaMapValuesf(t TestingT, expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) { + if !assert.InDeltaMapValuesf(t, expected, actual, delta, msg, args...) { + t.FailNow() + } +} + +// InDeltaSlice is the same as InDelta, except it compares two slices. +func InDeltaSlice(t TestingT, expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) { + if !assert.InDeltaSlice(t, expected, actual, delta, msgAndArgs...) { + t.FailNow() + } +} + +// InDeltaSlicef is the same as InDelta, except it compares two slices. +func InDeltaSlicef(t TestingT, expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) { + if !assert.InDeltaSlicef(t, expected, actual, delta, msg, args...) { + t.FailNow() + } +} + +// InDeltaf asserts that the two numerals are within delta of each other. +// +// assert.InDeltaf(t, math.Pi, (22 / 7.0, "error message %s", "formatted"), 0.01) +func InDeltaf(t TestingT, expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) { + if !assert.InDeltaf(t, expected, actual, delta, msg, args...) { + t.FailNow() + } +} + +// InEpsilon asserts that expected and actual have a relative error less than epsilon +func InEpsilon(t TestingT, expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) { + if !assert.InEpsilon(t, expected, actual, epsilon, msgAndArgs...) { + t.FailNow() + } +} + +// InEpsilonSlice is the same as InEpsilon, except it compares each value from two slices. +func InEpsilonSlice(t TestingT, expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) { + if !assert.InEpsilonSlice(t, expected, actual, epsilon, msgAndArgs...) { + t.FailNow() + } +} + +// InEpsilonSlicef is the same as InEpsilon, except it compares each value from two slices. +func InEpsilonSlicef(t TestingT, expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) { + if !assert.InEpsilonSlicef(t, expected, actual, epsilon, msg, args...) { + t.FailNow() + } +} + +// InEpsilonf asserts that expected and actual have a relative error less than epsilon +func InEpsilonf(t TestingT, expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) { + if !assert.InEpsilonf(t, expected, actual, epsilon, msg, args...) { + t.FailNow() + } +} + +// IsType asserts that the specified objects are of the same type. +func IsType(t TestingT, expectedType interface{}, object interface{}, msgAndArgs ...interface{}) { + if !assert.IsType(t, expectedType, object, msgAndArgs...) { + t.FailNow() + } +} + +// IsTypef asserts that the specified objects are of the same type. +func IsTypef(t TestingT, expectedType interface{}, object interface{}, msg string, args ...interface{}) { + if !assert.IsTypef(t, expectedType, object, msg, args...) { + t.FailNow() + } +} + +// JSONEq asserts that two JSON strings are equivalent. +// +// assert.JSONEq(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) +func JSONEq(t TestingT, expected string, actual string, msgAndArgs ...interface{}) { + if !assert.JSONEq(t, expected, actual, msgAndArgs...) { + t.FailNow() + } +} + +// JSONEqf asserts that two JSON strings are equivalent. +// +// assert.JSONEqf(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`, "error message %s", "formatted") +func JSONEqf(t TestingT, expected string, actual string, msg string, args ...interface{}) { + if !assert.JSONEqf(t, expected, actual, msg, args...) { + t.FailNow() + } +} + +// Len asserts that the specified object has specific length. +// Len also fails if the object has a type that len() not accept. +// +// assert.Len(t, mySlice, 3) +func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{}) { + if !assert.Len(t, object, length, msgAndArgs...) { + t.FailNow() + } +} + +// Lenf asserts that the specified object has specific length. +// Lenf also fails if the object has a type that len() not accept. +// +// assert.Lenf(t, mySlice, 3, "error message %s", "formatted") +func Lenf(t TestingT, object interface{}, length int, msg string, args ...interface{}) { + if !assert.Lenf(t, object, length, msg, args...) { + t.FailNow() + } +} + +// Nil asserts that the specified object is nil. +// +// assert.Nil(t, err) +func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) { + if !assert.Nil(t, object, msgAndArgs...) { + t.FailNow() + } +} + +// Nilf asserts that the specified object is nil. +// +// assert.Nilf(t, err, "error message %s", "formatted") +func Nilf(t TestingT, object interface{}, msg string, args ...interface{}) { + if !assert.Nilf(t, object, msg, args...) { + t.FailNow() + } +} + +// NoError asserts that a function returned no error (i.e. `nil`). +// +// actualObj, err := SomeFunction() +// if assert.NoError(t, err) { +// assert.Equal(t, expectedObj, actualObj) +// } +func NoError(t TestingT, err error, msgAndArgs ...interface{}) { + if !assert.NoError(t, err, msgAndArgs...) { + t.FailNow() + } +} + +// NoErrorf asserts that a function returned no error (i.e. `nil`). +// +// actualObj, err := SomeFunction() +// if assert.NoErrorf(t, err, "error message %s", "formatted") { +// assert.Equal(t, expectedObj, actualObj) +// } +func NoErrorf(t TestingT, err error, msg string, args ...interface{}) { + if !assert.NoErrorf(t, err, msg, args...) { + t.FailNow() + } +} + +// NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the +// specified substring or element. +// +// assert.NotContains(t, "Hello World", "Earth") +// assert.NotContains(t, ["Hello", "World"], "Earth") +// assert.NotContains(t, {"Hello": "World"}, "Earth") +func NotContains(t TestingT, s interface{}, contains interface{}, msgAndArgs ...interface{}) { + if !assert.NotContains(t, s, contains, msgAndArgs...) { + t.FailNow() + } +} + +// NotContainsf asserts that the specified string, list(array, slice...) or map does NOT contain the +// specified substring or element. +// +// assert.NotContainsf(t, "Hello World", "Earth", "error message %s", "formatted") +// assert.NotContainsf(t, ["Hello", "World"], "Earth", "error message %s", "formatted") +// assert.NotContainsf(t, {"Hello": "World"}, "Earth", "error message %s", "formatted") +func NotContainsf(t TestingT, s interface{}, contains interface{}, msg string, args ...interface{}) { + if !assert.NotContainsf(t, s, contains, msg, args...) { + t.FailNow() + } +} + +// NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either +// a slice or a channel with len == 0. +// +// if assert.NotEmpty(t, obj) { +// assert.Equal(t, "two", obj[1]) +// } +func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) { + if !assert.NotEmpty(t, object, msgAndArgs...) { + t.FailNow() + } +} + +// NotEmptyf asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either +// a slice or a channel with len == 0. +// +// if assert.NotEmptyf(t, obj, "error message %s", "formatted") { +// assert.Equal(t, "two", obj[1]) +// } +func NotEmptyf(t TestingT, object interface{}, msg string, args ...interface{}) { + if !assert.NotEmptyf(t, object, msg, args...) { + t.FailNow() + } +} + +// NotEqual asserts that the specified values are NOT equal. +// +// assert.NotEqual(t, obj1, obj2) +// +// Pointer variable equality is determined based on the equality of the +// referenced values (as opposed to the memory addresses). +func NotEqual(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) { + if !assert.NotEqual(t, expected, actual, msgAndArgs...) { + t.FailNow() + } +} + +// NotEqualf asserts that the specified values are NOT equal. +// +// assert.NotEqualf(t, obj1, obj2, "error message %s", "formatted") +// +// Pointer variable equality is determined based on the equality of the +// referenced values (as opposed to the memory addresses). +func NotEqualf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) { + if !assert.NotEqualf(t, expected, actual, msg, args...) { + t.FailNow() + } +} + +// NotNil asserts that the specified object is not nil. +// +// assert.NotNil(t, err) +func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) { + if !assert.NotNil(t, object, msgAndArgs...) { + t.FailNow() + } +} + +// NotNilf asserts that the specified object is not nil. +// +// assert.NotNilf(t, err, "error message %s", "formatted") +func NotNilf(t TestingT, object interface{}, msg string, args ...interface{}) { + if !assert.NotNilf(t, object, msg, args...) { + t.FailNow() + } +} + +// NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic. +// +// assert.NotPanics(t, func(){ RemainCalm() }) +func NotPanics(t TestingT, f assert.PanicTestFunc, msgAndArgs ...interface{}) { + if !assert.NotPanics(t, f, msgAndArgs...) { + t.FailNow() + } +} + +// NotPanicsf asserts that the code inside the specified PanicTestFunc does NOT panic. +// +// assert.NotPanicsf(t, func(){ RemainCalm() }, "error message %s", "formatted") +func NotPanicsf(t TestingT, f assert.PanicTestFunc, msg string, args ...interface{}) { + if !assert.NotPanicsf(t, f, msg, args...) { + t.FailNow() + } +} + +// NotRegexp asserts that a specified regexp does not match a string. +// +// assert.NotRegexp(t, regexp.MustCompile("starts"), "it's starting") +// assert.NotRegexp(t, "^start", "it's not starting") +func NotRegexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) { + if !assert.NotRegexp(t, rx, str, msgAndArgs...) { + t.FailNow() + } +} + +// NotRegexpf asserts that a specified regexp does not match a string. +// +// assert.NotRegexpf(t, regexp.MustCompile("starts", "error message %s", "formatted"), "it's starting") +// assert.NotRegexpf(t, "^start", "it's not starting", "error message %s", "formatted") +func NotRegexpf(t TestingT, rx interface{}, str interface{}, msg string, args ...interface{}) { + if !assert.NotRegexpf(t, rx, str, msg, args...) { + t.FailNow() + } +} + +// NotSubset asserts that the specified list(array, slice...) contains not all +// elements given in the specified subset(array, slice...). +// +// assert.NotSubset(t, [1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]") +func NotSubset(t TestingT, list interface{}, subset interface{}, msgAndArgs ...interface{}) { + if !assert.NotSubset(t, list, subset, msgAndArgs...) { + t.FailNow() + } +} + +// NotSubsetf asserts that the specified list(array, slice...) contains not all +// elements given in the specified subset(array, slice...). +// +// assert.NotSubsetf(t, [1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]", "error message %s", "formatted") +func NotSubsetf(t TestingT, list interface{}, subset interface{}, msg string, args ...interface{}) { + if !assert.NotSubsetf(t, list, subset, msg, args...) { + t.FailNow() + } +} + +// NotZero asserts that i is not the zero value for its type. +func NotZero(t TestingT, i interface{}, msgAndArgs ...interface{}) { + if !assert.NotZero(t, i, msgAndArgs...) { + t.FailNow() + } +} + +// NotZerof asserts that i is not the zero value for its type. +func NotZerof(t TestingT, i interface{}, msg string, args ...interface{}) { + if !assert.NotZerof(t, i, msg, args...) { + t.FailNow() + } +} + +// Panics asserts that the code inside the specified PanicTestFunc panics. +// +// assert.Panics(t, func(){ GoCrazy() }) +func Panics(t TestingT, f assert.PanicTestFunc, msgAndArgs ...interface{}) { + if !assert.Panics(t, f, msgAndArgs...) { + t.FailNow() + } +} + +// PanicsWithValue asserts that the code inside the specified PanicTestFunc panics, and that +// the recovered panic value equals the expected panic value. +// +// assert.PanicsWithValue(t, "crazy error", func(){ GoCrazy() }) +func PanicsWithValue(t TestingT, expected interface{}, f assert.PanicTestFunc, msgAndArgs ...interface{}) { + if !assert.PanicsWithValue(t, expected, f, msgAndArgs...) { + t.FailNow() + } +} + +// PanicsWithValuef asserts that the code inside the specified PanicTestFunc panics, and that +// the recovered panic value equals the expected panic value. +// +// assert.PanicsWithValuef(t, "crazy error", func(){ GoCrazy() }, "error message %s", "formatted") +func PanicsWithValuef(t TestingT, expected interface{}, f assert.PanicTestFunc, msg string, args ...interface{}) { + if !assert.PanicsWithValuef(t, expected, f, msg, args...) { + t.FailNow() + } +} + +// Panicsf asserts that the code inside the specified PanicTestFunc panics. +// +// assert.Panicsf(t, func(){ GoCrazy() }, "error message %s", "formatted") +func Panicsf(t TestingT, f assert.PanicTestFunc, msg string, args ...interface{}) { + if !assert.Panicsf(t, f, msg, args...) { + t.FailNow() + } +} + +// Regexp asserts that a specified regexp matches a string. +// +// assert.Regexp(t, regexp.MustCompile("start"), "it's starting") +// assert.Regexp(t, "start...$", "it's not starting") +func Regexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) { + if !assert.Regexp(t, rx, str, msgAndArgs...) { + t.FailNow() + } +} + +// Regexpf asserts that a specified regexp matches a string. +// +// assert.Regexpf(t, regexp.MustCompile("start", "error message %s", "formatted"), "it's starting") +// assert.Regexpf(t, "start...$", "it's not starting", "error message %s", "formatted") +func Regexpf(t TestingT, rx interface{}, str interface{}, msg string, args ...interface{}) { + if !assert.Regexpf(t, rx, str, msg, args...) { + t.FailNow() + } +} + +// Subset asserts that the specified list(array, slice...) contains all +// elements given in the specified subset(array, slice...). +// +// assert.Subset(t, [1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]") +func Subset(t TestingT, list interface{}, subset interface{}, msgAndArgs ...interface{}) { + if !assert.Subset(t, list, subset, msgAndArgs...) { + t.FailNow() + } +} + +// Subsetf asserts that the specified list(array, slice...) contains all +// elements given in the specified subset(array, slice...). +// +// assert.Subsetf(t, [1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]", "error message %s", "formatted") +func Subsetf(t TestingT, list interface{}, subset interface{}, msg string, args ...interface{}) { + if !assert.Subsetf(t, list, subset, msg, args...) { + t.FailNow() + } +} + +// True asserts that the specified value is true. +// +// assert.True(t, myBool) +func True(t TestingT, value bool, msgAndArgs ...interface{}) { + if !assert.True(t, value, msgAndArgs...) { + t.FailNow() + } +} + +// Truef asserts that the specified value is true. +// +// assert.Truef(t, myBool, "error message %s", "formatted") +func Truef(t TestingT, value bool, msg string, args ...interface{}) { + if !assert.Truef(t, value, msg, args...) { + t.FailNow() + } +} + +// WithinDuration asserts that the two times are within duration delta of each other. +// +// assert.WithinDuration(t, time.Now(), time.Now(), 10*time.Second) +func WithinDuration(t TestingT, expected time.Time, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) { + if !assert.WithinDuration(t, expected, actual, delta, msgAndArgs...) { + t.FailNow() + } +} + +// WithinDurationf asserts that the two times are within duration delta of each other. +// +// assert.WithinDurationf(t, time.Now(), time.Now(), 10*time.Second, "error message %s", "formatted") +func WithinDurationf(t TestingT, expected time.Time, actual time.Time, delta time.Duration, msg string, args ...interface{}) { + if !assert.WithinDurationf(t, expected, actual, delta, msg, args...) { + t.FailNow() + } +} + +// Zero asserts that i is the zero value for its type. +func Zero(t TestingT, i interface{}, msgAndArgs ...interface{}) { + if !assert.Zero(t, i, msgAndArgs...) { + t.FailNow() + } +} + +// Zerof asserts that i is the zero value for its type. +func Zerof(t TestingT, i interface{}, msg string, args ...interface{}) { + if !assert.Zerof(t, i, msg, args...) { + t.FailNow() + } +} diff --git a/vendor/github.com/stretchr/testify/require/require.go.tmpl b/vendor/github.com/stretchr/testify/require/require.go.tmpl new file mode 100644 index 0000000..d2c38f6 --- /dev/null +++ b/vendor/github.com/stretchr/testify/require/require.go.tmpl @@ -0,0 +1,6 @@ +{{.Comment}} +func {{.DocInfo.Name}}(t TestingT, {{.Params}}) { + if !assert.{{.DocInfo.Name}}(t, {{.ForwardedParams}}) { + t.FailNow() + } +} diff --git a/vendor/github.com/stretchr/testify/require/require_forward.go b/vendor/github.com/stretchr/testify/require/require_forward.go new file mode 100644 index 0000000..299ceb9 --- /dev/null +++ b/vendor/github.com/stretchr/testify/require/require_forward.go @@ -0,0 +1,687 @@ +/* +* CODE GENERATED AUTOMATICALLY WITH github.com/stretchr/testify/_codegen +* THIS FILE MUST NOT BE EDITED BY HAND + */ + +package require + +import ( + assert "github.com/stretchr/testify/assert" + http "net/http" + url "net/url" + time "time" +) + +// Condition uses a Comparison to assert a complex condition. +func (a *Assertions) Condition(comp assert.Comparison, msgAndArgs ...interface{}) { + Condition(a.t, comp, msgAndArgs...) +} + +// Conditionf uses a Comparison to assert a complex condition. +func (a *Assertions) Conditionf(comp assert.Comparison, msg string, args ...interface{}) { + Conditionf(a.t, comp, msg, args...) +} + +// Contains asserts that the specified string, list(array, slice...) or map contains the +// specified substring or element. +// +// a.Contains("Hello World", "World") +// a.Contains(["Hello", "World"], "World") +// a.Contains({"Hello": "World"}, "Hello") +func (a *Assertions) Contains(s interface{}, contains interface{}, msgAndArgs ...interface{}) { + Contains(a.t, s, contains, msgAndArgs...) +} + +// Containsf asserts that the specified string, list(array, slice...) or map contains the +// specified substring or element. +// +// a.Containsf("Hello World", "World", "error message %s", "formatted") +// a.Containsf(["Hello", "World"], "World", "error message %s", "formatted") +// a.Containsf({"Hello": "World"}, "Hello", "error message %s", "formatted") +func (a *Assertions) Containsf(s interface{}, contains interface{}, msg string, args ...interface{}) { + Containsf(a.t, s, contains, msg, args...) +} + +// DirExists checks whether a directory exists in the given path. It also fails if the path is a file rather a directory or there is an error checking whether it exists. +func (a *Assertions) DirExists(path string, msgAndArgs ...interface{}) { + DirExists(a.t, path, msgAndArgs...) +} + +// DirExistsf checks whether a directory exists in the given path. It also fails if the path is a file rather a directory or there is an error checking whether it exists. +func (a *Assertions) DirExistsf(path string, msg string, args ...interface{}) { + DirExistsf(a.t, path, msg, args...) +} + +// ElementsMatch asserts that the specified listA(array, slice...) is equal to specified +// listB(array, slice...) ignoring the order of the elements. If there are duplicate elements, +// the number of appearances of each of them in both lists should match. +// +// a.ElementsMatch([1, 3, 2, 3], [1, 3, 3, 2]) +func (a *Assertions) ElementsMatch(listA interface{}, listB interface{}, msgAndArgs ...interface{}) { + ElementsMatch(a.t, listA, listB, msgAndArgs...) +} + +// ElementsMatchf asserts that the specified listA(array, slice...) is equal to specified +// listB(array, slice...) ignoring the order of the elements. If there are duplicate elements, +// the number of appearances of each of them in both lists should match. +// +// a.ElementsMatchf([1, 3, 2, 3], [1, 3, 3, 2], "error message %s", "formatted") +func (a *Assertions) ElementsMatchf(listA interface{}, listB interface{}, msg string, args ...interface{}) { + ElementsMatchf(a.t, listA, listB, msg, args...) +} + +// Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either +// a slice or a channel with len == 0. +// +// a.Empty(obj) +func (a *Assertions) Empty(object interface{}, msgAndArgs ...interface{}) { + Empty(a.t, object, msgAndArgs...) +} + +// Emptyf asserts that the specified object is empty. I.e. nil, "", false, 0 or either +// a slice or a channel with len == 0. +// +// a.Emptyf(obj, "error message %s", "formatted") +func (a *Assertions) Emptyf(object interface{}, msg string, args ...interface{}) { + Emptyf(a.t, object, msg, args...) +} + +// Equal asserts that two objects are equal. +// +// a.Equal(123, 123) +// +// Pointer variable equality is determined based on the equality of the +// referenced values (as opposed to the memory addresses). Function equality +// cannot be determined and will always fail. +func (a *Assertions) Equal(expected interface{}, actual interface{}, msgAndArgs ...interface{}) { + Equal(a.t, expected, actual, msgAndArgs...) +} + +// EqualError asserts that a function returned an error (i.e. not `nil`) +// and that it is equal to the provided error. +// +// actualObj, err := SomeFunction() +// a.EqualError(err, expectedErrorString) +func (a *Assertions) EqualError(theError error, errString string, msgAndArgs ...interface{}) { + EqualError(a.t, theError, errString, msgAndArgs...) +} + +// EqualErrorf asserts that a function returned an error (i.e. not `nil`) +// and that it is equal to the provided error. +// +// actualObj, err := SomeFunction() +// a.EqualErrorf(err, expectedErrorString, "error message %s", "formatted") +func (a *Assertions) EqualErrorf(theError error, errString string, msg string, args ...interface{}) { + EqualErrorf(a.t, theError, errString, msg, args...) +} + +// EqualValues asserts that two objects are equal or convertable to the same types +// and equal. +// +// a.EqualValues(uint32(123), int32(123)) +func (a *Assertions) EqualValues(expected interface{}, actual interface{}, msgAndArgs ...interface{}) { + EqualValues(a.t, expected, actual, msgAndArgs...) +} + +// EqualValuesf asserts that two objects are equal or convertable to the same types +// and equal. +// +// a.EqualValuesf(uint32(123, "error message %s", "formatted"), int32(123)) +func (a *Assertions) EqualValuesf(expected interface{}, actual interface{}, msg string, args ...interface{}) { + EqualValuesf(a.t, expected, actual, msg, args...) +} + +// Equalf asserts that two objects are equal. +// +// a.Equalf(123, 123, "error message %s", "formatted") +// +// Pointer variable equality is determined based on the equality of the +// referenced values (as opposed to the memory addresses). Function equality +// cannot be determined and will always fail. +func (a *Assertions) Equalf(expected interface{}, actual interface{}, msg string, args ...interface{}) { + Equalf(a.t, expected, actual, msg, args...) +} + +// Error asserts that a function returned an error (i.e. not `nil`). +// +// actualObj, err := SomeFunction() +// if a.Error(err) { +// assert.Equal(t, expectedError, err) +// } +func (a *Assertions) Error(err error, msgAndArgs ...interface{}) { + Error(a.t, err, msgAndArgs...) +} + +// Errorf asserts that a function returned an error (i.e. not `nil`). +// +// actualObj, err := SomeFunction() +// if a.Errorf(err, "error message %s", "formatted") { +// assert.Equal(t, expectedErrorf, err) +// } +func (a *Assertions) Errorf(err error, msg string, args ...interface{}) { + Errorf(a.t, err, msg, args...) +} + +// Exactly asserts that two objects are equal in value and type. +// +// a.Exactly(int32(123), int64(123)) +func (a *Assertions) Exactly(expected interface{}, actual interface{}, msgAndArgs ...interface{}) { + Exactly(a.t, expected, actual, msgAndArgs...) +} + +// Exactlyf asserts that two objects are equal in value and type. +// +// a.Exactlyf(int32(123, "error message %s", "formatted"), int64(123)) +func (a *Assertions) Exactlyf(expected interface{}, actual interface{}, msg string, args ...interface{}) { + Exactlyf(a.t, expected, actual, msg, args...) +} + +// Fail reports a failure through +func (a *Assertions) Fail(failureMessage string, msgAndArgs ...interface{}) { + Fail(a.t, failureMessage, msgAndArgs...) +} + +// FailNow fails test +func (a *Assertions) FailNow(failureMessage string, msgAndArgs ...interface{}) { + FailNow(a.t, failureMessage, msgAndArgs...) +} + +// FailNowf fails test +func (a *Assertions) FailNowf(failureMessage string, msg string, args ...interface{}) { + FailNowf(a.t, failureMessage, msg, args...) +} + +// Failf reports a failure through +func (a *Assertions) Failf(failureMessage string, msg string, args ...interface{}) { + Failf(a.t, failureMessage, msg, args...) +} + +// False asserts that the specified value is false. +// +// a.False(myBool) +func (a *Assertions) False(value bool, msgAndArgs ...interface{}) { + False(a.t, value, msgAndArgs...) +} + +// Falsef asserts that the specified value is false. +// +// a.Falsef(myBool, "error message %s", "formatted") +func (a *Assertions) Falsef(value bool, msg string, args ...interface{}) { + Falsef(a.t, value, msg, args...) +} + +// FileExists checks whether a file exists in the given path. It also fails if the path points to a directory or there is an error when trying to check the file. +func (a *Assertions) FileExists(path string, msgAndArgs ...interface{}) { + FileExists(a.t, path, msgAndArgs...) +} + +// FileExistsf checks whether a file exists in the given path. It also fails if the path points to a directory or there is an error when trying to check the file. +func (a *Assertions) FileExistsf(path string, msg string, args ...interface{}) { + FileExistsf(a.t, path, msg, args...) +} + +// HTTPBodyContains asserts that a specified handler returns a +// body that contains a string. +// +// a.HTTPBodyContains(myHandler, "www.google.com", nil, "I'm Feeling Lucky") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) HTTPBodyContains(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) { + HTTPBodyContains(a.t, handler, method, url, values, str, msgAndArgs...) +} + +// HTTPBodyContainsf asserts that a specified handler returns a +// body that contains a string. +// +// a.HTTPBodyContainsf(myHandler, "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) HTTPBodyContainsf(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) { + HTTPBodyContainsf(a.t, handler, method, url, values, str, msg, args...) +} + +// HTTPBodyNotContains asserts that a specified handler returns a +// body that does not contain a string. +// +// a.HTTPBodyNotContains(myHandler, "www.google.com", nil, "I'm Feeling Lucky") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) HTTPBodyNotContains(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) { + HTTPBodyNotContains(a.t, handler, method, url, values, str, msgAndArgs...) +} + +// HTTPBodyNotContainsf asserts that a specified handler returns a +// body that does not contain a string. +// +// a.HTTPBodyNotContainsf(myHandler, "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) HTTPBodyNotContainsf(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) { + HTTPBodyNotContainsf(a.t, handler, method, url, values, str, msg, args...) +} + +// HTTPError asserts that a specified handler returns an error status code. +// +// a.HTTPError(myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) HTTPError(handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) { + HTTPError(a.t, handler, method, url, values, msgAndArgs...) +} + +// HTTPErrorf asserts that a specified handler returns an error status code. +// +// a.HTTPErrorf(myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} +// +// Returns whether the assertion was successful (true, "error message %s", "formatted") or not (false). +func (a *Assertions) HTTPErrorf(handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) { + HTTPErrorf(a.t, handler, method, url, values, msg, args...) +} + +// HTTPRedirect asserts that a specified handler returns a redirect status code. +// +// a.HTTPRedirect(myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) HTTPRedirect(handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) { + HTTPRedirect(a.t, handler, method, url, values, msgAndArgs...) +} + +// HTTPRedirectf asserts that a specified handler returns a redirect status code. +// +// a.HTTPRedirectf(myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} +// +// Returns whether the assertion was successful (true, "error message %s", "formatted") or not (false). +func (a *Assertions) HTTPRedirectf(handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) { + HTTPRedirectf(a.t, handler, method, url, values, msg, args...) +} + +// HTTPSuccess asserts that a specified handler returns a success status code. +// +// a.HTTPSuccess(myHandler, "POST", "http://www.google.com", nil) +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) HTTPSuccess(handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) { + HTTPSuccess(a.t, handler, method, url, values, msgAndArgs...) +} + +// HTTPSuccessf asserts that a specified handler returns a success status code. +// +// a.HTTPSuccessf(myHandler, "POST", "http://www.google.com", nil, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) HTTPSuccessf(handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) { + HTTPSuccessf(a.t, handler, method, url, values, msg, args...) +} + +// Implements asserts that an object is implemented by the specified interface. +// +// a.Implements((*MyInterface)(nil), new(MyObject)) +func (a *Assertions) Implements(interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) { + Implements(a.t, interfaceObject, object, msgAndArgs...) +} + +// Implementsf asserts that an object is implemented by the specified interface. +// +// a.Implementsf((*MyInterface, "error message %s", "formatted")(nil), new(MyObject)) +func (a *Assertions) Implementsf(interfaceObject interface{}, object interface{}, msg string, args ...interface{}) { + Implementsf(a.t, interfaceObject, object, msg, args...) +} + +// InDelta asserts that the two numerals are within delta of each other. +// +// a.InDelta(math.Pi, (22 / 7.0), 0.01) +func (a *Assertions) InDelta(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) { + InDelta(a.t, expected, actual, delta, msgAndArgs...) +} + +// InDeltaMapValues is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys. +func (a *Assertions) InDeltaMapValues(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) { + InDeltaMapValues(a.t, expected, actual, delta, msgAndArgs...) +} + +// InDeltaMapValuesf is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys. +func (a *Assertions) InDeltaMapValuesf(expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) { + InDeltaMapValuesf(a.t, expected, actual, delta, msg, args...) +} + +// InDeltaSlice is the same as InDelta, except it compares two slices. +func (a *Assertions) InDeltaSlice(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) { + InDeltaSlice(a.t, expected, actual, delta, msgAndArgs...) +} + +// InDeltaSlicef is the same as InDelta, except it compares two slices. +func (a *Assertions) InDeltaSlicef(expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) { + InDeltaSlicef(a.t, expected, actual, delta, msg, args...) +} + +// InDeltaf asserts that the two numerals are within delta of each other. +// +// a.InDeltaf(math.Pi, (22 / 7.0, "error message %s", "formatted"), 0.01) +func (a *Assertions) InDeltaf(expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) { + InDeltaf(a.t, expected, actual, delta, msg, args...) +} + +// InEpsilon asserts that expected and actual have a relative error less than epsilon +func (a *Assertions) InEpsilon(expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) { + InEpsilon(a.t, expected, actual, epsilon, msgAndArgs...) +} + +// InEpsilonSlice is the same as InEpsilon, except it compares each value from two slices. +func (a *Assertions) InEpsilonSlice(expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) { + InEpsilonSlice(a.t, expected, actual, epsilon, msgAndArgs...) +} + +// InEpsilonSlicef is the same as InEpsilon, except it compares each value from two slices. +func (a *Assertions) InEpsilonSlicef(expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) { + InEpsilonSlicef(a.t, expected, actual, epsilon, msg, args...) +} + +// InEpsilonf asserts that expected and actual have a relative error less than epsilon +func (a *Assertions) InEpsilonf(expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) { + InEpsilonf(a.t, expected, actual, epsilon, msg, args...) +} + +// IsType asserts that the specified objects are of the same type. +func (a *Assertions) IsType(expectedType interface{}, object interface{}, msgAndArgs ...interface{}) { + IsType(a.t, expectedType, object, msgAndArgs...) +} + +// IsTypef asserts that the specified objects are of the same type. +func (a *Assertions) IsTypef(expectedType interface{}, object interface{}, msg string, args ...interface{}) { + IsTypef(a.t, expectedType, object, msg, args...) +} + +// JSONEq asserts that two JSON strings are equivalent. +// +// a.JSONEq(`{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) +func (a *Assertions) JSONEq(expected string, actual string, msgAndArgs ...interface{}) { + JSONEq(a.t, expected, actual, msgAndArgs...) +} + +// JSONEqf asserts that two JSON strings are equivalent. +// +// a.JSONEqf(`{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`, "error message %s", "formatted") +func (a *Assertions) JSONEqf(expected string, actual string, msg string, args ...interface{}) { + JSONEqf(a.t, expected, actual, msg, args...) +} + +// Len asserts that the specified object has specific length. +// Len also fails if the object has a type that len() not accept. +// +// a.Len(mySlice, 3) +func (a *Assertions) Len(object interface{}, length int, msgAndArgs ...interface{}) { + Len(a.t, object, length, msgAndArgs...) +} + +// Lenf asserts that the specified object has specific length. +// Lenf also fails if the object has a type that len() not accept. +// +// a.Lenf(mySlice, 3, "error message %s", "formatted") +func (a *Assertions) Lenf(object interface{}, length int, msg string, args ...interface{}) { + Lenf(a.t, object, length, msg, args...) +} + +// Nil asserts that the specified object is nil. +// +// a.Nil(err) +func (a *Assertions) Nil(object interface{}, msgAndArgs ...interface{}) { + Nil(a.t, object, msgAndArgs...) +} + +// Nilf asserts that the specified object is nil. +// +// a.Nilf(err, "error message %s", "formatted") +func (a *Assertions) Nilf(object interface{}, msg string, args ...interface{}) { + Nilf(a.t, object, msg, args...) +} + +// NoError asserts that a function returned no error (i.e. `nil`). +// +// actualObj, err := SomeFunction() +// if a.NoError(err) { +// assert.Equal(t, expectedObj, actualObj) +// } +func (a *Assertions) NoError(err error, msgAndArgs ...interface{}) { + NoError(a.t, err, msgAndArgs...) +} + +// NoErrorf asserts that a function returned no error (i.e. `nil`). +// +// actualObj, err := SomeFunction() +// if a.NoErrorf(err, "error message %s", "formatted") { +// assert.Equal(t, expectedObj, actualObj) +// } +func (a *Assertions) NoErrorf(err error, msg string, args ...interface{}) { + NoErrorf(a.t, err, msg, args...) +} + +// NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the +// specified substring or element. +// +// a.NotContains("Hello World", "Earth") +// a.NotContains(["Hello", "World"], "Earth") +// a.NotContains({"Hello": "World"}, "Earth") +func (a *Assertions) NotContains(s interface{}, contains interface{}, msgAndArgs ...interface{}) { + NotContains(a.t, s, contains, msgAndArgs...) +} + +// NotContainsf asserts that the specified string, list(array, slice...) or map does NOT contain the +// specified substring or element. +// +// a.NotContainsf("Hello World", "Earth", "error message %s", "formatted") +// a.NotContainsf(["Hello", "World"], "Earth", "error message %s", "formatted") +// a.NotContainsf({"Hello": "World"}, "Earth", "error message %s", "formatted") +func (a *Assertions) NotContainsf(s interface{}, contains interface{}, msg string, args ...interface{}) { + NotContainsf(a.t, s, contains, msg, args...) +} + +// NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either +// a slice or a channel with len == 0. +// +// if a.NotEmpty(obj) { +// assert.Equal(t, "two", obj[1]) +// } +func (a *Assertions) NotEmpty(object interface{}, msgAndArgs ...interface{}) { + NotEmpty(a.t, object, msgAndArgs...) +} + +// NotEmptyf asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either +// a slice or a channel with len == 0. +// +// if a.NotEmptyf(obj, "error message %s", "formatted") { +// assert.Equal(t, "two", obj[1]) +// } +func (a *Assertions) NotEmptyf(object interface{}, msg string, args ...interface{}) { + NotEmptyf(a.t, object, msg, args...) +} + +// NotEqual asserts that the specified values are NOT equal. +// +// a.NotEqual(obj1, obj2) +// +// Pointer variable equality is determined based on the equality of the +// referenced values (as opposed to the memory addresses). +func (a *Assertions) NotEqual(expected interface{}, actual interface{}, msgAndArgs ...interface{}) { + NotEqual(a.t, expected, actual, msgAndArgs...) +} + +// NotEqualf asserts that the specified values are NOT equal. +// +// a.NotEqualf(obj1, obj2, "error message %s", "formatted") +// +// Pointer variable equality is determined based on the equality of the +// referenced values (as opposed to the memory addresses). +func (a *Assertions) NotEqualf(expected interface{}, actual interface{}, msg string, args ...interface{}) { + NotEqualf(a.t, expected, actual, msg, args...) +} + +// NotNil asserts that the specified object is not nil. +// +// a.NotNil(err) +func (a *Assertions) NotNil(object interface{}, msgAndArgs ...interface{}) { + NotNil(a.t, object, msgAndArgs...) +} + +// NotNilf asserts that the specified object is not nil. +// +// a.NotNilf(err, "error message %s", "formatted") +func (a *Assertions) NotNilf(object interface{}, msg string, args ...interface{}) { + NotNilf(a.t, object, msg, args...) +} + +// NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic. +// +// a.NotPanics(func(){ RemainCalm() }) +func (a *Assertions) NotPanics(f assert.PanicTestFunc, msgAndArgs ...interface{}) { + NotPanics(a.t, f, msgAndArgs...) +} + +// NotPanicsf asserts that the code inside the specified PanicTestFunc does NOT panic. +// +// a.NotPanicsf(func(){ RemainCalm() }, "error message %s", "formatted") +func (a *Assertions) NotPanicsf(f assert.PanicTestFunc, msg string, args ...interface{}) { + NotPanicsf(a.t, f, msg, args...) +} + +// NotRegexp asserts that a specified regexp does not match a string. +// +// a.NotRegexp(regexp.MustCompile("starts"), "it's starting") +// a.NotRegexp("^start", "it's not starting") +func (a *Assertions) NotRegexp(rx interface{}, str interface{}, msgAndArgs ...interface{}) { + NotRegexp(a.t, rx, str, msgAndArgs...) +} + +// NotRegexpf asserts that a specified regexp does not match a string. +// +// a.NotRegexpf(regexp.MustCompile("starts", "error message %s", "formatted"), "it's starting") +// a.NotRegexpf("^start", "it's not starting", "error message %s", "formatted") +func (a *Assertions) NotRegexpf(rx interface{}, str interface{}, msg string, args ...interface{}) { + NotRegexpf(a.t, rx, str, msg, args...) +} + +// NotSubset asserts that the specified list(array, slice...) contains not all +// elements given in the specified subset(array, slice...). +// +// a.NotSubset([1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]") +func (a *Assertions) NotSubset(list interface{}, subset interface{}, msgAndArgs ...interface{}) { + NotSubset(a.t, list, subset, msgAndArgs...) +} + +// NotSubsetf asserts that the specified list(array, slice...) contains not all +// elements given in the specified subset(array, slice...). +// +// a.NotSubsetf([1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]", "error message %s", "formatted") +func (a *Assertions) NotSubsetf(list interface{}, subset interface{}, msg string, args ...interface{}) { + NotSubsetf(a.t, list, subset, msg, args...) +} + +// NotZero asserts that i is not the zero value for its type. +func (a *Assertions) NotZero(i interface{}, msgAndArgs ...interface{}) { + NotZero(a.t, i, msgAndArgs...) +} + +// NotZerof asserts that i is not the zero value for its type. +func (a *Assertions) NotZerof(i interface{}, msg string, args ...interface{}) { + NotZerof(a.t, i, msg, args...) +} + +// Panics asserts that the code inside the specified PanicTestFunc panics. +// +// a.Panics(func(){ GoCrazy() }) +func (a *Assertions) Panics(f assert.PanicTestFunc, msgAndArgs ...interface{}) { + Panics(a.t, f, msgAndArgs...) +} + +// PanicsWithValue asserts that the code inside the specified PanicTestFunc panics, and that +// the recovered panic value equals the expected panic value. +// +// a.PanicsWithValue("crazy error", func(){ GoCrazy() }) +func (a *Assertions) PanicsWithValue(expected interface{}, f assert.PanicTestFunc, msgAndArgs ...interface{}) { + PanicsWithValue(a.t, expected, f, msgAndArgs...) +} + +// PanicsWithValuef asserts that the code inside the specified PanicTestFunc panics, and that +// the recovered panic value equals the expected panic value. +// +// a.PanicsWithValuef("crazy error", func(){ GoCrazy() }, "error message %s", "formatted") +func (a *Assertions) PanicsWithValuef(expected interface{}, f assert.PanicTestFunc, msg string, args ...interface{}) { + PanicsWithValuef(a.t, expected, f, msg, args...) +} + +// Panicsf asserts that the code inside the specified PanicTestFunc panics. +// +// a.Panicsf(func(){ GoCrazy() }, "error message %s", "formatted") +func (a *Assertions) Panicsf(f assert.PanicTestFunc, msg string, args ...interface{}) { + Panicsf(a.t, f, msg, args...) +} + +// Regexp asserts that a specified regexp matches a string. +// +// a.Regexp(regexp.MustCompile("start"), "it's starting") +// a.Regexp("start...$", "it's not starting") +func (a *Assertions) Regexp(rx interface{}, str interface{}, msgAndArgs ...interface{}) { + Regexp(a.t, rx, str, msgAndArgs...) +} + +// Regexpf asserts that a specified regexp matches a string. +// +// a.Regexpf(regexp.MustCompile("start", "error message %s", "formatted"), "it's starting") +// a.Regexpf("start...$", "it's not starting", "error message %s", "formatted") +func (a *Assertions) Regexpf(rx interface{}, str interface{}, msg string, args ...interface{}) { + Regexpf(a.t, rx, str, msg, args...) +} + +// Subset asserts that the specified list(array, slice...) contains all +// elements given in the specified subset(array, slice...). +// +// a.Subset([1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]") +func (a *Assertions) Subset(list interface{}, subset interface{}, msgAndArgs ...interface{}) { + Subset(a.t, list, subset, msgAndArgs...) +} + +// Subsetf asserts that the specified list(array, slice...) contains all +// elements given in the specified subset(array, slice...). +// +// a.Subsetf([1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]", "error message %s", "formatted") +func (a *Assertions) Subsetf(list interface{}, subset interface{}, msg string, args ...interface{}) { + Subsetf(a.t, list, subset, msg, args...) +} + +// True asserts that the specified value is true. +// +// a.True(myBool) +func (a *Assertions) True(value bool, msgAndArgs ...interface{}) { + True(a.t, value, msgAndArgs...) +} + +// Truef asserts that the specified value is true. +// +// a.Truef(myBool, "error message %s", "formatted") +func (a *Assertions) Truef(value bool, msg string, args ...interface{}) { + Truef(a.t, value, msg, args...) +} + +// WithinDuration asserts that the two times are within duration delta of each other. +// +// a.WithinDuration(time.Now(), time.Now(), 10*time.Second) +func (a *Assertions) WithinDuration(expected time.Time, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) { + WithinDuration(a.t, expected, actual, delta, msgAndArgs...) +} + +// WithinDurationf asserts that the two times are within duration delta of each other. +// +// a.WithinDurationf(time.Now(), time.Now(), 10*time.Second, "error message %s", "formatted") +func (a *Assertions) WithinDurationf(expected time.Time, actual time.Time, delta time.Duration, msg string, args ...interface{}) { + WithinDurationf(a.t, expected, actual, delta, msg, args...) +} + +// Zero asserts that i is the zero value for its type. +func (a *Assertions) Zero(i interface{}, msgAndArgs ...interface{}) { + Zero(a.t, i, msgAndArgs...) +} + +// Zerof asserts that i is the zero value for its type. +func (a *Assertions) Zerof(i interface{}, msg string, args ...interface{}) { + Zerof(a.t, i, msg, args...) +} diff --git a/vendor/github.com/stretchr/testify/require/require_forward.go.tmpl b/vendor/github.com/stretchr/testify/require/require_forward.go.tmpl new file mode 100644 index 0000000..b93569e --- /dev/null +++ b/vendor/github.com/stretchr/testify/require/require_forward.go.tmpl @@ -0,0 +1,4 @@ +{{.CommentWithoutT "a"}} +func (a *Assertions) {{.DocInfo.Name}}({{.Params}}) { + {{.DocInfo.Name}}(a.t, {{.ForwardedParams}}) +} diff --git a/vendor/github.com/stretchr/testify/require/requirements.go b/vendor/github.com/stretchr/testify/require/requirements.go new file mode 100644 index 0000000..e404f01 --- /dev/null +++ b/vendor/github.com/stretchr/testify/require/requirements.go @@ -0,0 +1,9 @@ +package require + +// TestingT is an interface wrapper around *testing.T +type TestingT interface { + Errorf(format string, args ...interface{}) + FailNow() +} + +//go:generate go run ../_codegen/main.go -output-package=require -template=require.go.tmpl -include-format-funcs diff --git a/vendor/github.com/stretchr/testify/require/requirements_test.go b/vendor/github.com/stretchr/testify/require/requirements_test.go new file mode 100644 index 0000000..d2ccc99 --- /dev/null +++ b/vendor/github.com/stretchr/testify/require/requirements_test.go @@ -0,0 +1,369 @@ +package require + +import ( + "errors" + "testing" + "time" +) + +// AssertionTesterInterface defines an interface to be used for testing assertion methods +type AssertionTesterInterface interface { + TestMethod() +} + +// AssertionTesterConformingObject is an object that conforms to the AssertionTesterInterface interface +type AssertionTesterConformingObject struct { +} + +func (a *AssertionTesterConformingObject) TestMethod() { +} + +// AssertionTesterNonConformingObject is an object that does not conform to the AssertionTesterInterface interface +type AssertionTesterNonConformingObject struct { +} + +type MockT struct { + Failed bool +} + +func (t *MockT) FailNow() { + t.Failed = true +} + +func (t *MockT) Errorf(format string, args ...interface{}) { + _, _ = format, args +} + +func TestImplements(t *testing.T) { + + Implements(t, (*AssertionTesterInterface)(nil), new(AssertionTesterConformingObject)) + + mockT := new(MockT) + Implements(mockT, (*AssertionTesterInterface)(nil), new(AssertionTesterNonConformingObject)) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestIsType(t *testing.T) { + + IsType(t, new(AssertionTesterConformingObject), new(AssertionTesterConformingObject)) + + mockT := new(MockT) + IsType(mockT, new(AssertionTesterConformingObject), new(AssertionTesterNonConformingObject)) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestEqual(t *testing.T) { + + Equal(t, 1, 1) + + mockT := new(MockT) + Equal(mockT, 1, 2) + if !mockT.Failed { + t.Error("Check should fail") + } + +} + +func TestNotEqual(t *testing.T) { + + NotEqual(t, 1, 2) + mockT := new(MockT) + NotEqual(mockT, 2, 2) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestExactly(t *testing.T) { + + a := float32(1) + b := float32(1) + c := float64(1) + + Exactly(t, a, b) + + mockT := new(MockT) + Exactly(mockT, a, c) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestNotNil(t *testing.T) { + + NotNil(t, new(AssertionTesterConformingObject)) + + mockT := new(MockT) + NotNil(mockT, nil) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestNil(t *testing.T) { + + Nil(t, nil) + + mockT := new(MockT) + Nil(mockT, new(AssertionTesterConformingObject)) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestTrue(t *testing.T) { + + True(t, true) + + mockT := new(MockT) + True(mockT, false) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestFalse(t *testing.T) { + + False(t, false) + + mockT := new(MockT) + False(mockT, true) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestContains(t *testing.T) { + + Contains(t, "Hello World", "Hello") + + mockT := new(MockT) + Contains(mockT, "Hello World", "Salut") + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestNotContains(t *testing.T) { + + NotContains(t, "Hello World", "Hello!") + + mockT := new(MockT) + NotContains(mockT, "Hello World", "Hello") + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestPanics(t *testing.T) { + + Panics(t, func() { + panic("Panic!") + }) + + mockT := new(MockT) + Panics(mockT, func() {}) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestNotPanics(t *testing.T) { + + NotPanics(t, func() {}) + + mockT := new(MockT) + NotPanics(mockT, func() { + panic("Panic!") + }) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestNoError(t *testing.T) { + + NoError(t, nil) + + mockT := new(MockT) + NoError(mockT, errors.New("some error")) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestError(t *testing.T) { + + Error(t, errors.New("some error")) + + mockT := new(MockT) + Error(mockT, nil) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestEqualError(t *testing.T) { + + EqualError(t, errors.New("some error"), "some error") + + mockT := new(MockT) + EqualError(mockT, errors.New("some error"), "Not some error") + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestEmpty(t *testing.T) { + + Empty(t, "") + + mockT := new(MockT) + Empty(mockT, "x") + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestNotEmpty(t *testing.T) { + + NotEmpty(t, "x") + + mockT := new(MockT) + NotEmpty(mockT, "") + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestWithinDuration(t *testing.T) { + + a := time.Now() + b := a.Add(10 * time.Second) + + WithinDuration(t, a, b, 15*time.Second) + + mockT := new(MockT) + WithinDuration(mockT, a, b, 5*time.Second) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestInDelta(t *testing.T) { + + InDelta(t, 1.001, 1, 0.01) + + mockT := new(MockT) + InDelta(mockT, 1, 2, 0.5) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestZero(t *testing.T) { + + Zero(t, "") + + mockT := new(MockT) + Zero(mockT, "x") + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestNotZero(t *testing.T) { + + NotZero(t, "x") + + mockT := new(MockT) + NotZero(mockT, "") + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestJSONEq_EqualSONString(t *testing.T) { + mockT := new(MockT) + JSONEq(mockT, `{"hello": "world", "foo": "bar"}`, `{"hello": "world", "foo": "bar"}`) + if mockT.Failed { + t.Error("Check should pass") + } +} + +func TestJSONEq_EquivalentButNotEqual(t *testing.T) { + mockT := new(MockT) + JSONEq(mockT, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) + if mockT.Failed { + t.Error("Check should pass") + } +} + +func TestJSONEq_HashOfArraysAndHashes(t *testing.T) { + mockT := new(MockT) + JSONEq(mockT, "{\r\n\t\"numeric\": 1.5,\r\n\t\"array\": [{\"foo\": \"bar\"}, 1, \"string\", [\"nested\", \"array\", 5.5]],\r\n\t\"hash\": {\"nested\": \"hash\", \"nested_slice\": [\"this\", \"is\", \"nested\"]},\r\n\t\"string\": \"foo\"\r\n}", + "{\r\n\t\"numeric\": 1.5,\r\n\t\"hash\": {\"nested\": \"hash\", \"nested_slice\": [\"this\", \"is\", \"nested\"]},\r\n\t\"string\": \"foo\",\r\n\t\"array\": [{\"foo\": \"bar\"}, 1, \"string\", [\"nested\", \"array\", 5.5]]\r\n}") + if mockT.Failed { + t.Error("Check should pass") + } +} + +func TestJSONEq_Array(t *testing.T) { + mockT := new(MockT) + JSONEq(mockT, `["foo", {"hello": "world", "nested": "hash"}]`, `["foo", {"nested": "hash", "hello": "world"}]`) + if mockT.Failed { + t.Error("Check should pass") + } +} + +func TestJSONEq_HashAndArrayNotEquivalent(t *testing.T) { + mockT := new(MockT) + JSONEq(mockT, `["foo", {"hello": "world", "nested": "hash"}]`, `{"foo": "bar", {"nested": "hash", "hello": "world"}}`) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestJSONEq_HashesNotEquivalent(t *testing.T) { + mockT := new(MockT) + JSONEq(mockT, `{"foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestJSONEq_ActualIsNotJSON(t *testing.T) { + mockT := new(MockT) + JSONEq(mockT, `{"foo": "bar"}`, "Not JSON") + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestJSONEq_ExpectedIsNotJSON(t *testing.T) { + mockT := new(MockT) + JSONEq(mockT, "Not JSON", `{"foo": "bar", "hello": "world"}`) + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestJSONEq_ExpectedAndActualNotJSON(t *testing.T) { + mockT := new(MockT) + JSONEq(mockT, "Not JSON", "Not JSON") + if !mockT.Failed { + t.Error("Check should fail") + } +} + +func TestJSONEq_ArraysOfDifferentOrder(t *testing.T) { + mockT := new(MockT) + JSONEq(mockT, `["foo", {"hello": "world", "nested": "hash"}]`, `[{ "hello": "world", "nested": "hash"}, "foo"]`) + if !mockT.Failed { + t.Error("Check should fail") + } +} diff --git a/vendor/github.com/stretchr/testify/suite/doc.go b/vendor/github.com/stretchr/testify/suite/doc.go new file mode 100644 index 0000000..f91a245 --- /dev/null +++ b/vendor/github.com/stretchr/testify/suite/doc.go @@ -0,0 +1,65 @@ +// Package suite contains logic for creating testing suite structs +// and running the methods on those structs as tests. The most useful +// piece of this package is that you can create setup/teardown methods +// on your testing suites, which will run before/after the whole suite +// or individual tests (depending on which interface(s) you +// implement). +// +// A testing suite is usually built by first extending the built-in +// suite functionality from suite.Suite in testify. Alternatively, +// you could reproduce that logic on your own if you wanted (you +// just need to implement the TestingSuite interface from +// suite/interfaces.go). +// +// After that, you can implement any of the interfaces in +// suite/interfaces.go to add setup/teardown functionality to your +// suite, and add any methods that start with "Test" to add tests. +// Methods that do not match any suite interfaces and do not begin +// with "Test" will not be run by testify, and can safely be used as +// helper methods. +// +// Once you've built your testing suite, you need to run the suite +// (using suite.Run from testify) inside any function that matches the +// identity that "go test" is already looking for (i.e. +// func(*testing.T)). +// +// Regular expression to select test suites specified command-line +// argument "-run". Regular expression to select the methods +// of test suites specified command-line argument "-m". +// Suite object has assertion methods. +// +// A crude example: +// // Basic imports +// import ( +// "testing" +// "github.com/stretchr/testify/assert" +// "github.com/stretchr/testify/suite" +// ) +// +// // Define the suite, and absorb the built-in basic suite +// // functionality from testify - including a T() method which +// // returns the current testing context +// type ExampleTestSuite struct { +// suite.Suite +// VariableThatShouldStartAtFive int +// } +// +// // Make sure that VariableThatShouldStartAtFive is set to five +// // before each test +// func (suite *ExampleTestSuite) SetupTest() { +// suite.VariableThatShouldStartAtFive = 5 +// } +// +// // All methods that begin with "Test" are run as tests within a +// // suite. +// func (suite *ExampleTestSuite) TestExample() { +// assert.Equal(suite.T(), 5, suite.VariableThatShouldStartAtFive) +// suite.Equal(5, suite.VariableThatShouldStartAtFive) +// } +// +// // In order for 'go test' to run this suite, we need to create +// // a normal test function and pass our suite to suite.Run +// func TestExampleTestSuite(t *testing.T) { +// suite.Run(t, new(ExampleTestSuite)) +// } +package suite diff --git a/vendor/github.com/stretchr/testify/suite/interfaces.go b/vendor/github.com/stretchr/testify/suite/interfaces.go new file mode 100644 index 0000000..b37cb04 --- /dev/null +++ b/vendor/github.com/stretchr/testify/suite/interfaces.go @@ -0,0 +1,46 @@ +package suite + +import "testing" + +// TestingSuite can store and return the current *testing.T context +// generated by 'go test'. +type TestingSuite interface { + T() *testing.T + SetT(*testing.T) +} + +// SetupAllSuite has a SetupSuite method, which will run before the +// tests in the suite are run. +type SetupAllSuite interface { + SetupSuite() +} + +// SetupTestSuite has a SetupTest method, which will run before each +// test in the suite. +type SetupTestSuite interface { + SetupTest() +} + +// TearDownAllSuite has a TearDownSuite method, which will run after +// all the tests in the suite have been run. +type TearDownAllSuite interface { + TearDownSuite() +} + +// TearDownTestSuite has a TearDownTest method, which will run after +// each test in the suite. +type TearDownTestSuite interface { + TearDownTest() +} + +// BeforeTest has a function to be executed right before the test +// starts and receives the suite and test names as input +type BeforeTest interface { + BeforeTest(suiteName, testName string) +} + +// AfterTest has a function to be executed right after the test +// finishes and receives the suite and test names as input +type AfterTest interface { + AfterTest(suiteName, testName string) +} diff --git a/vendor/github.com/stretchr/testify/suite/suite.go b/vendor/github.com/stretchr/testify/suite/suite.go new file mode 100644 index 0000000..e20afbc --- /dev/null +++ b/vendor/github.com/stretchr/testify/suite/suite.go @@ -0,0 +1,136 @@ +package suite + +import ( + "flag" + "fmt" + "os" + "reflect" + "regexp" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +var allTestsFilter = func(_, _ string) (bool, error) { return true, nil } +var matchMethod = flag.String("testify.m", "", "regular expression to select tests of the testify suite to run") + +// Suite is a basic testing suite with methods for storing and +// retrieving the current *testing.T context. +type Suite struct { + *assert.Assertions + require *require.Assertions + t *testing.T +} + +// T retrieves the current *testing.T context. +func (suite *Suite) T() *testing.T { + return suite.t +} + +// SetT sets the current *testing.T context. +func (suite *Suite) SetT(t *testing.T) { + suite.t = t + suite.Assertions = assert.New(t) + suite.require = require.New(t) +} + +// Require returns a require context for suite. +func (suite *Suite) Require() *require.Assertions { + if suite.require == nil { + suite.require = require.New(suite.T()) + } + return suite.require +} + +// Assert returns an assert context for suite. Normally, you can call +// `suite.NoError(expected, actual)`, but for situations where the embedded +// methods are overridden (for example, you might want to override +// assert.Assertions with require.Assertions), this method is provided so you +// can call `suite.Assert().NoError()`. +func (suite *Suite) Assert() *assert.Assertions { + if suite.Assertions == nil { + suite.Assertions = assert.New(suite.T()) + } + return suite.Assertions +} + +// Run takes a testing suite and runs all of the tests attached +// to it. +func Run(t *testing.T, suite TestingSuite) { + suite.SetT(t) + + if setupAllSuite, ok := suite.(SetupAllSuite); ok { + setupAllSuite.SetupSuite() + } + defer func() { + if tearDownAllSuite, ok := suite.(TearDownAllSuite); ok { + tearDownAllSuite.TearDownSuite() + } + }() + + methodFinder := reflect.TypeOf(suite) + tests := []testing.InternalTest{} + for index := 0; index < methodFinder.NumMethod(); index++ { + method := methodFinder.Method(index) + ok, err := methodFilter(method.Name) + if err != nil { + fmt.Fprintf(os.Stderr, "testify: invalid regexp for -m: %s\n", err) + os.Exit(1) + } + if ok { + test := testing.InternalTest{ + Name: method.Name, + F: func(t *testing.T) { + parentT := suite.T() + suite.SetT(t) + if setupTestSuite, ok := suite.(SetupTestSuite); ok { + setupTestSuite.SetupTest() + } + if beforeTestSuite, ok := suite.(BeforeTest); ok { + beforeTestSuite.BeforeTest(methodFinder.Elem().Name(), method.Name) + } + defer func() { + if afterTestSuite, ok := suite.(AfterTest); ok { + afterTestSuite.AfterTest(methodFinder.Elem().Name(), method.Name) + } + if tearDownTestSuite, ok := suite.(TearDownTestSuite); ok { + tearDownTestSuite.TearDownTest() + } + suite.SetT(parentT) + }() + method.Func.Call([]reflect.Value{reflect.ValueOf(suite)}) + }, + } + tests = append(tests, test) + } + } + runTests(t, tests) +} + +func runTests(t testing.TB, tests []testing.InternalTest) { + r, ok := t.(runner) + if !ok { // backwards compatibility with Go 1.6 and below + if !testing.RunTests(allTestsFilter, tests) { + t.Fail() + } + return + } + + for _, test := range tests { + r.Run(test.Name, test.F) + } +} + +// Filtering method according to set regular expression +// specified command-line argument -m +func methodFilter(name string) (bool, error) { + if ok, _ := regexp.MatchString("^Test", name); !ok { + return false, nil + } + return regexp.MatchString(*matchMethod, name) +} + +type runner interface { + Run(name string, f func(t *testing.T)) bool +} diff --git a/vendor/github.com/stretchr/testify/suite/suite_test.go b/vendor/github.com/stretchr/testify/suite/suite_test.go new file mode 100644 index 0000000..b75fa4a --- /dev/null +++ b/vendor/github.com/stretchr/testify/suite/suite_test.go @@ -0,0 +1,294 @@ +package suite + +import ( + "errors" + "io/ioutil" + "os" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// SuiteRequireTwice is intended to test the usage of suite.Require in two +// different tests +type SuiteRequireTwice struct{ Suite } + +// TestSuiteRequireTwice checks for regressions of issue #149 where +// suite.requirements was not initialised in suite.SetT() +// A regression would result on these tests panicking rather than failing. +func TestSuiteRequireTwice(t *testing.T) { + ok := testing.RunTests( + allTestsFilter, + []testing.InternalTest{{ + Name: "TestSuiteRequireTwice", + F: func(t *testing.T) { + suite := new(SuiteRequireTwice) + Run(t, suite) + }, + }}, + ) + assert.Equal(t, false, ok) +} + +func (s *SuiteRequireTwice) TestRequireOne() { + r := s.Require() + r.Equal(1, 2) +} + +func (s *SuiteRequireTwice) TestRequireTwo() { + r := s.Require() + r.Equal(1, 2) +} + +// This suite is intended to store values to make sure that only +// testing-suite-related methods are run. It's also a fully +// functional example of a testing suite, using setup/teardown methods +// and a helper method that is ignored by testify. To make this look +// more like a real world example, all tests in the suite perform some +// type of assertion. +type SuiteTester struct { + // Include our basic suite logic. + Suite + + // Keep counts of how many times each method is run. + SetupSuiteRunCount int + TearDownSuiteRunCount int + SetupTestRunCount int + TearDownTestRunCount int + TestOneRunCount int + TestTwoRunCount int + NonTestMethodRunCount int + + SuiteNameBefore []string + TestNameBefore []string + + SuiteNameAfter []string + TestNameAfter []string + + TimeBefore []time.Time + TimeAfter []time.Time +} + +type SuiteSkipTester struct { + // Include our basic suite logic. + Suite + + // Keep counts of how many times each method is run. + SetupSuiteRunCount int + TearDownSuiteRunCount int +} + +// The SetupSuite method will be run by testify once, at the very +// start of the testing suite, before any tests are run. +func (suite *SuiteTester) SetupSuite() { + suite.SetupSuiteRunCount++ +} + +func (suite *SuiteTester) BeforeTest(suiteName, testName string) { + suite.SuiteNameBefore = append(suite.SuiteNameBefore, suiteName) + suite.TestNameBefore = append(suite.TestNameBefore, testName) + suite.TimeBefore = append(suite.TimeBefore, time.Now()) +} + +func (suite *SuiteTester) AfterTest(suiteName, testName string) { + suite.SuiteNameAfter = append(suite.SuiteNameAfter, suiteName) + suite.TestNameAfter = append(suite.TestNameAfter, testName) + suite.TimeAfter = append(suite.TimeAfter, time.Now()) +} + +func (suite *SuiteSkipTester) SetupSuite() { + suite.SetupSuiteRunCount++ + suite.T().Skip() +} + +// The TearDownSuite method will be run by testify once, at the very +// end of the testing suite, after all tests have been run. +func (suite *SuiteTester) TearDownSuite() { + suite.TearDownSuiteRunCount++ +} + +func (suite *SuiteSkipTester) TearDownSuite() { + suite.TearDownSuiteRunCount++ +} + +// The SetupTest method will be run before every test in the suite. +func (suite *SuiteTester) SetupTest() { + suite.SetupTestRunCount++ +} + +// The TearDownTest method will be run after every test in the suite. +func (suite *SuiteTester) TearDownTest() { + suite.TearDownTestRunCount++ +} + +// Every method in a testing suite that begins with "Test" will be run +// as a test. TestOne is an example of a test. For the purposes of +// this example, we've included assertions in the tests, since most +// tests will issue assertions. +func (suite *SuiteTester) TestOne() { + beforeCount := suite.TestOneRunCount + suite.TestOneRunCount++ + assert.Equal(suite.T(), suite.TestOneRunCount, beforeCount+1) + suite.Equal(suite.TestOneRunCount, beforeCount+1) +} + +// TestTwo is another example of a test. +func (suite *SuiteTester) TestTwo() { + beforeCount := suite.TestTwoRunCount + suite.TestTwoRunCount++ + assert.NotEqual(suite.T(), suite.TestTwoRunCount, beforeCount) + suite.NotEqual(suite.TestTwoRunCount, beforeCount) +} + +func (suite *SuiteTester) TestSkip() { + suite.T().Skip() +} + +// NonTestMethod does not begin with "Test", so it will not be run by +// testify as a test in the suite. This is useful for creating helper +// methods for your tests. +func (suite *SuiteTester) NonTestMethod() { + suite.NonTestMethodRunCount++ +} + +// TestRunSuite will be run by the 'go test' command, so within it, we +// can run our suite using the Run(*testing.T, TestingSuite) function. +func TestRunSuite(t *testing.T) { + suiteTester := new(SuiteTester) + Run(t, suiteTester) + + // Normally, the test would end here. The following are simply + // some assertions to ensure that the Run function is working as + // intended - they are not part of the example. + + // The suite was only run once, so the SetupSuite and TearDownSuite + // methods should have each been run only once. + assert.Equal(t, suiteTester.SetupSuiteRunCount, 1) + assert.Equal(t, suiteTester.TearDownSuiteRunCount, 1) + + assert.Equal(t, len(suiteTester.SuiteNameAfter), 3) + assert.Equal(t, len(suiteTester.SuiteNameBefore), 3) + assert.Equal(t, len(suiteTester.TestNameAfter), 3) + assert.Equal(t, len(suiteTester.TestNameBefore), 3) + + assert.Contains(t, suiteTester.TestNameAfter, "TestOne") + assert.Contains(t, suiteTester.TestNameAfter, "TestTwo") + assert.Contains(t, suiteTester.TestNameAfter, "TestSkip") + + assert.Contains(t, suiteTester.TestNameBefore, "TestOne") + assert.Contains(t, suiteTester.TestNameBefore, "TestTwo") + assert.Contains(t, suiteTester.TestNameBefore, "TestSkip") + + for _, suiteName := range suiteTester.SuiteNameAfter { + assert.Equal(t, "SuiteTester", suiteName) + } + + for _, suiteName := range suiteTester.SuiteNameBefore { + assert.Equal(t, "SuiteTester", suiteName) + } + + for _, when := range suiteTester.TimeAfter { + assert.False(t, when.IsZero()) + } + + for _, when := range suiteTester.TimeBefore { + assert.False(t, when.IsZero()) + } + + // There are three test methods (TestOne, TestTwo, and TestSkip), so + // the SetupTest and TearDownTest methods (which should be run once for + // each test) should have been run three times. + assert.Equal(t, suiteTester.SetupTestRunCount, 3) + assert.Equal(t, suiteTester.TearDownTestRunCount, 3) + + // Each test should have been run once. + assert.Equal(t, suiteTester.TestOneRunCount, 1) + assert.Equal(t, suiteTester.TestTwoRunCount, 1) + + // Methods that don't match the test method identifier shouldn't + // have been run at all. + assert.Equal(t, suiteTester.NonTestMethodRunCount, 0) + + suiteSkipTester := new(SuiteSkipTester) + Run(t, suiteSkipTester) + + // The suite was only run once, so the SetupSuite and TearDownSuite + // methods should have each been run only once, even though SetupSuite + // called Skip() + assert.Equal(t, suiteSkipTester.SetupSuiteRunCount, 1) + assert.Equal(t, suiteSkipTester.TearDownSuiteRunCount, 1) + +} + +func TestSuiteGetters(t *testing.T) { + suite := new(SuiteTester) + suite.SetT(t) + assert.NotNil(t, suite.Assert()) + assert.Equal(t, suite.Assertions, suite.Assert()) + assert.NotNil(t, suite.Require()) + assert.Equal(t, suite.require, suite.Require()) +} + +type SuiteLoggingTester struct { + Suite +} + +func (s *SuiteLoggingTester) TestLoggingPass() { + s.T().Log("TESTLOGPASS") +} + +func (s *SuiteLoggingTester) TestLoggingFail() { + s.T().Log("TESTLOGFAIL") + assert.NotNil(s.T(), nil) // expected to fail +} + +type StdoutCapture struct { + oldStdout *os.File + readPipe *os.File +} + +func (sc *StdoutCapture) StartCapture() { + sc.oldStdout = os.Stdout + sc.readPipe, os.Stdout, _ = os.Pipe() +} + +func (sc *StdoutCapture) StopCapture() (string, error) { + if sc.oldStdout == nil || sc.readPipe == nil { + return "", errors.New("StartCapture not called before StopCapture") + } + os.Stdout.Close() + os.Stdout = sc.oldStdout + bytes, err := ioutil.ReadAll(sc.readPipe) + if err != nil { + return "", err + } + return string(bytes), nil +} + +func TestSuiteLogging(t *testing.T) { + suiteLoggingTester := new(SuiteLoggingTester) + capture := StdoutCapture{} + internalTest := testing.InternalTest{ + Name: "SomeTest", + F: func(subT *testing.T) { + Run(subT, suiteLoggingTester) + }, + } + capture.StartCapture() + testing.RunTests(allTestsFilter, []testing.InternalTest{internalTest}) + output, err := capture.StopCapture() + require.NoError(t, err, "Got an error trying to capture stdout and stderr!") + require.NotEmpty(t, output, "output content must not be empty") + + // Failed tests' output is always printed + assert.Contains(t, output, "TESTLOGFAIL") + + if testing.Verbose() { + // In verbose mode, output from successful tests is also printed + assert.Contains(t, output, "TESTLOGPASS") + } else { + assert.NotContains(t, output, "TESTLOGPASS") + } +} diff --git a/vendor/manifest b/vendor/manifest deleted file mode 100644 index ec89d07..0000000 --- a/vendor/manifest +++ /dev/null @@ -1,44 +0,0 @@ -{ - "version": 0, - "dependencies": [ - { - "importpath": "github.com/cactus/mlog", - "repository": "https://github.com/cactus/mlog", - "revision": "aa86a0f73a6e8d6736f68093bef0996b7d2c58b4", - "branch": "master" - }, - { - "importpath": "github.com/cactus/tai64", - "repository": "https://github.com/cactus/tai64", - "revision": "3445910b21a47018240be2c4333bcf982d786310", - "branch": "master" - }, - { - "importpath": "github.com/davecgh/go-spew/spew", - "repository": "https://github.com/davecgh/go-spew", - "revision": "ecdeabc65495df2dec95d7c4a4c3e021903035e5", - "branch": "master", - "path": "/spew" - }, - { - "importpath": "github.com/jessevdk/go-flags", - "repository": "https://github.com/jessevdk/go-flags", - "revision": "f88afde2fa19a30cf50ba4b05b3d13bc6bae3079", - "branch": "master" - }, - { - "importpath": "github.com/pmezard/go-difflib/difflib", - "repository": "https://github.com/pmezard/go-difflib", - "revision": "792786c7400a136282c1664665ae0a8db921c6c2", - "branch": "master", - "path": "/difflib" - }, - { - "importpath": "github.com/stretchr/testify/assert", - "repository": "https://github.com/stretchr/testify", - "revision": "87b1dfb5b2fa649f52695dd9eae19abe404a4308", - "branch": "master", - "path": "/assert" - } - ] -} diff --git a/vendor/src/github.com/cactus/mlog/formatwriter_json_test.go b/vendor/src/github.com/cactus/mlog/formatwriter_json_test.go deleted file mode 100644 index 022b72f..0000000 --- a/vendor/src/github.com/cactus/mlog/formatwriter_json_test.go +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) 2012-2016 Eli Janssen -// Use of this source code is governed by an MIT-style -// license that can be found in the LICENSE file. - -package mlog - -import ( - "bytes" - "encoding/json" - "testing" - - "github.com/stretchr/testify/assert" -) - -func testEncodeString(e byteSliceWriter, s string) { - encoder := json.NewEncoder(e) - encoder.Encode(s) -} - -func TestFormatWriterJSONEncodeString(t *testing.T) { - var jsonStringTests = map[string]string{ - "generic": `test`, - "quote": `"this"`, - "r&n": "te\r\nst", - "tab": "\t what", - "weird chars": "\u2028 \u2029", - "other weird chars": `"\u003c\u0026\u003e"`, - "invalid utf8": "\xff\xff\xffhello", - } - - b := &bytes.Buffer{} - for name, s := range jsonStringTests { - e, err := json.Marshal(s) - assert.Nil(t, err, "%s: json marshal failed", name) - - b.Truncate(0) - b.WriteByte('"') - encodeStringJSON(b, s) - b.WriteByte('"') - assert.Equal(t, string(e), b.String(), "%s: did not match expectation", name) - } -} diff --git a/vendor/src/github.com/cactus/mlog/formatwriter_plain_test.go b/vendor/src/github.com/cactus/mlog/formatwriter_plain_test.go deleted file mode 100644 index 1c247f8..0000000 --- a/vendor/src/github.com/cactus/mlog/formatwriter_plain_test.go +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (c) 2012-2016 Eli Janssen -// Use of this source code is governed by an MIT-style -// license that can be found in the LICENSE file. - -package mlog - -import ( - "bytes" - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestFormatWriterPlainEncodeString(t *testing.T) { - var stringTests = map[string]struct { - input string - output string - }{ - "generic": {`test`, `test`}, - "quote": {`"this"`, `"this"`}, - "r&n": {"te\r\nst", `te\r\nst`}, - "tab": {"\t what", `\t what`}, - "weird chars": {"\u2028 \u2029", "\u2028 \u2029"}, - "other weird chars": {`"\u003c\u0026\u003e"`, `"\u003c\u0026\u003e"`}, - "invalid utf8": {"\xff\xff\xffhello", `\ufffd\ufffd\ufffdhello`}, - } - - b := &bytes.Buffer{} - for name, tt := range stringTests { - b.Truncate(0) - encodeStringPlain(b, tt.input) - assert.Equal(t, []byte(tt.output), b.Bytes(), "%s: did not match expectation", name) - } -} diff --git a/vendor/src/github.com/cactus/mlog/formatwriter_structured_test.go b/vendor/src/github.com/cactus/mlog/formatwriter_structured_test.go deleted file mode 100644 index 3e5b832..0000000 --- a/vendor/src/github.com/cactus/mlog/formatwriter_structured_test.go +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (c) 2012-2016 Eli Janssen -// Use of this source code is governed by an MIT-style -// license that can be found in the LICENSE file. - -package mlog - -import ( - "bytes" - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestFormatWriterStructuredEncodeString(t *testing.T) { - var stringTests = map[string]struct { - input string - output string - }{ - "generic": {`test`, `test`}, - "quote": {`"this"`, `\"this\"`}, - "r&n": {"te\r\nst", `te\r\nst`}, - "tab": {"\t what", `\t what`}, - "weird chars": {"\u2028 \u2029", "\u2028 \u2029"}, - "other weird chars": {`"\u003c\u0026\u003e"`, `\"\u003c\u0026\u003e\"`}, - "invalid utf8": {"\xff\xff\xffhello", `\ufffd\ufffd\ufffdhello`}, - } - - b := &bytes.Buffer{} - for name, tt := range stringTests { - b.Truncate(0) - encodeStringStructured(b, tt.input) - assert.Equal(t, []byte(tt.output), b.Bytes(), "%s: did not match expectation", name) - } -} diff --git a/vendor/src/github.com/cactus/mlog/test-fixtures/test_logger_msgs.panic.golden b/vendor/src/github.com/cactus/mlog/test-fixtures/test_logger_msgs.panic.golden deleted file mode 100644 index fbfbac9..0000000 --- a/vendor/src/github.com/cactus/mlog/test-fixtures/test_logger_msgs.panic.golden +++ /dev/null @@ -1 +0,0 @@ -level="F" msg="test" diff --git a/vendor/src/github.com/cactus/mlog/test-fixtures/test_logger_msgs.panicf.golden b/vendor/src/github.com/cactus/mlog/test-fixtures/test_logger_msgs.panicf.golden deleted file mode 100644 index 4f3d27e..0000000 --- a/vendor/src/github.com/cactus/mlog/test-fixtures/test_logger_msgs.panicf.golden +++ /dev/null @@ -1 +0,0 @@ -level="F" msg="test: 5" diff --git a/vendor/src/github.com/cactus/mlog/test-fixtures/test_logger_msgs.panicm.golden b/vendor/src/github.com/cactus/mlog/test-fixtures/test_logger_msgs.panicm.golden deleted file mode 100644 index efdb590..0000000 --- a/vendor/src/github.com/cactus/mlog/test-fixtures/test_logger_msgs.panicm.golden +++ /dev/null @@ -1 +0,0 @@ -level="F" msg="test" x="y" diff --git a/vendor/src/github.com/cactus/mlog/time_test.go b/vendor/src/github.com/cactus/mlog/time_test.go deleted file mode 100644 index a606143..0000000 --- a/vendor/src/github.com/cactus/mlog/time_test.go +++ /dev/null @@ -1,82 +0,0 @@ -package mlog - -import ( - "testing" - "time" - - "github.com/stretchr/testify/assert" -) - -func TestTime(t *testing.T) { - loc := time.FixedZone("PDT", -25200) - cases := []struct { - F FlagSet - T time.Time - R string - }{ - { - Ltimestamp, - time.Date(2016, time.November, 1, 2, 3, 4, 5, loc), - `2016-11-01T02:03:04.000000005-07:00`, - }, - { - Ltimestamp, - time.Date(2016, time.January, 11, 12, 13, 14, 15, time.UTC), - `2016-01-11T12:13:14.000000015Z`, - }, - { - Ltimestamp, - time.Date(2016, time.November, 1, 2, 3, 4, 5000, loc), - `2016-11-01T02:03:04.000005000-07:00`, - }, - { - Ltimestamp, - time.Date(2016, time.January, 11, 12, 13, 14, 15000, time.UTC), - `2016-01-11T12:13:14.000015000Z`, - }, - } - - b := &sliceBuffer{make([]byte, 0, 1024)} - for _, tc := range cases { - b.Truncate(0) - writeTime(b, &(tc.T), tc.F) - assert.Equal(t, tc.R, b.String(), "time written incorrectly") - } -} - -func TestTimeTAI64N(t *testing.T) { - loc := time.FixedZone("PDT", -25200) - cases := []struct { - F FlagSet - T time.Time - R string - }{ - { - Ltai64n, - time.Date(1980, time.November, 1, 2, 3, 4, 5, loc), - `@4000000014613edb00000005`, - }, - { - Ltai64n, - time.Date(1980, time.January, 11, 12, 13, 14, 15, time.UTC), - `@4000000012dc80ed0000000f`, - }, - { - Ltai64n, - time.Date(2016, time.November, 1, 2, 3, 4, 5000, loc), - `@4000000058185a6c00001388`, - }, - { - Ltai64n, - time.Date(2016, time.January, 11, 12, 13, 14, 15000, time.UTC), - `@4000000056939c7e00003a98`, - }, - } - - b := &sliceBuffer{make([]byte, 0, 1024)} - for _, tc := range cases { - b.Truncate(0) - writeTimeTAI64N(b, &(tc.T), tc.F) - assert.Equal(t, tc.R, b.String(), "time written incorrectly") - } -} diff --git a/vendor/src/github.com/cactus/tai64/LICENSE.md b/vendor/src/github.com/cactus/tai64/LICENSE.md deleted file mode 100644 index 56bee4f..0000000 --- a/vendor/src/github.com/cactus/tai64/LICENSE.md +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2012-2016 Eli Janssen - -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/src/github.com/cactus/tai64/README.md b/vendor/src/github.com/cactus/tai64/README.md deleted file mode 100644 index 512a0ec..0000000 --- a/vendor/src/github.com/cactus/tai64/README.md +++ /dev/null @@ -1,60 +0,0 @@ -tai64 -===== - -[![Build Status](https://travis-ci.org/cactus/tai64.svg?branch=master)](https://travis-ci.org/cactus/tai64) -[![GoDoc](https://godoc.org/github.com/cactus/tai64?status.png)](https://godoc.org/github.com/cactus/tai64) -[![Go Report Card](https://goreportcard.com/badge/github.com/cactus/tai64)](https://goreportcard.com/report/github.com/cactus/tai64) - -## About - -Formats and parses [TAI64 and TAI64N][1] timestamps. - -## Usage - -``` go -package main - -import ( - "fmt" - "os" - "time" - - "github.com/cactus/tai64" -) - -func main() { - t := time.Now() - fmt.Println(t) - - s := tai64.FormatNano(t) - fmt.Println(s) - - p, err := tai64.Parse(s) - if err != nil { - fmt.Println("Failed to decode time") - os.Exit(1) - } - - // tai64 times are in UTC - fmt.Println(p) - - // time.Equal properly compares times with different locations. - if t.Equal(p) { - fmt.Println("equal") - } else { - fmt.Println("not equal") - } -} -``` - -Output: - -``` -2016-05-25 13:44:01.281160355 -0700 PDT -@4000000057460eb510c22aa3 -2016-05-25 20:44:01.281160355 +0000 UTC -equal -``` - - -[1]: http://www.tai64.com diff --git a/vendor/src/github.com/cactus/tai64/offsets.go b/vendor/src/github.com/cactus/tai64/offsets.go deleted file mode 100644 index 1461533..0000000 --- a/vendor/src/github.com/cactus/tai64/offsets.go +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright (c) 2012-2016 Eli Janssen -// Use of this source code is governed by an MIT-style -// license that can be found in the LICENSE file. - -// THIS FILE IS AUTOGENERATED. DO NOT EDIT! - -package tai64 - -// http://maia.usno.navy.mil/ser7/tai-utc.dat -// http://www.stjarnhimlen.se/comp/time.html -var tia64nDifferences = []struct { - utime int64 - offset int64 -}{ - {63072000, 10}, // 1972-01-01T00:00:00Z - {78796800, 11}, // 1972-07-01T00:00:00Z - {94694400, 12}, // 1973-01-01T00:00:00Z - {126230400, 13}, // 1974-01-01T00:00:00Z - {157766400, 14}, // 1975-01-01T00:00:00Z - {189302400, 15}, // 1976-01-01T00:00:00Z - {220924800, 16}, // 1977-01-01T00:00:00Z - {252460800, 17}, // 1978-01-01T00:00:00Z - {283996800, 18}, // 1979-01-01T00:00:00Z - {315532800, 19}, // 1980-01-01T00:00:00Z - {362793600, 20}, // 1981-07-01T00:00:00Z - {394329600, 21}, // 1982-07-01T00:00:00Z - {425865600, 22}, // 1983-07-01T00:00:00Z - {489024000, 23}, // 1985-07-01T00:00:00Z - {567993600, 24}, // 1988-01-01T00:00:00Z - {631152000, 25}, // 1990-01-01T00:00:00Z - {662688000, 26}, // 1991-01-01T00:00:00Z - {709948800, 27}, // 1992-07-01T00:00:00Z - {741484800, 28}, // 1993-07-01T00:00:00Z - {773020800, 29}, // 1994-07-01T00:00:00Z - {820454400, 30}, // 1996-01-01T00:00:00Z - {867715200, 31}, // 1997-07-01T00:00:00Z - {915148800, 32}, // 1999-01-01T00:00:00Z - {1136073600, 33}, // 2006-01-01T00:00:00Z - {1230768000, 34}, // 2009-01-01T00:00:00Z - {1341100800, 35}, // 2012-07-01T00:00:00Z - {1435708800, 36}, // 2015-07-01T00:00:00Z - {1483228800, 37}, // 2017-01-01T00:00:00Z -} - -var tia64nSize = len(tia64nDifferences) diff --git a/vendor/src/github.com/cactus/tai64/time.go b/vendor/src/github.com/cactus/tai64/time.go deleted file mode 100644 index 33bd60a..0000000 --- a/vendor/src/github.com/cactus/tai64/time.go +++ /dev/null @@ -1,120 +0,0 @@ -// Copyright (c) 2012-2016 Eli Janssen -// Use of this source code is governed by an MIT-style -// license that can be found in the LICENSE file. - -package tai64 - -//go:generate go run ./tools/generate.go -pkg $GOPACKAGE -output offsets.go - -import ( - "fmt" - "strconv" - "time" -) - -const tai64Epoch = 2 << 61 - -// GetOffsetUnix returns the TAI64 offset for a UTC unix timestamp -// returns int64 offset -func GetOffsetUnix(utime int64) int64 { - // default offset is 10 - offset := int64(10) - for i := tia64nSize - 1; i >= 0; i-- { - if utime < tia64nDifferences[i].utime { - continue - } else { - offset = tia64nDifferences[i].offset - break - } - } - return offset -} - -// GetOffsetTime returns the TAI64 offset for a time.Time in UTC -// returns int64 offset -func GetOffsetTime(t time.Time) int64 { - return GetOffsetUnix(t.UTC().Unix()) -} - -func getInvOffsetUnix(utime int64) int64 { - // default offset is 10 - offset := int64(10) - for i := tia64nSize - 1; i >= 0; i-- { - t := tia64nDifferences[i] - if utime < (t.utime + t.offset) { - continue - } else { - offset = t.offset - break - } - } - return offset -} - -// FormatNano formats a time.Time as a TAI64N timestamp -// returns a string TAI64N timestamps -func FormatNano(t time.Time) string { - t = t.UTC() - u := t.Unix() - - if u < 0 { - return fmt.Sprintf("@%016x%08x", (2<<61)+u+10, t.Nanosecond()) - } - return fmt.Sprintf("@4%015x%08x", u+GetOffsetUnix(u), t.Nanosecond()) -} - -// Format formats a time.Time as a TAI64 timestamp -// returns a string TAI64 timestamps -func Format(t time.Time) string { - u := t.UTC().Unix() - - if u < 0 { - return fmt.Sprintf("@%016x", (2<<61)+u+10) - } - return fmt.Sprintf("@4%015x", u+GetOffsetUnix(u)) -} - -// Parse parses a TAI64 or TAI64N timestamp -// returns a time.Time and an error. -func Parse(s string) (time.Time, error) { - var seconds, nanoseconds int64 - if s[0] == '@' { - s = s[1:] - } - - if len(s) < 16 { - return time.Time{}, fmt.Errorf("invalid tai64 time string") - } - - i, err := strconv.ParseInt(s[0:16], 16, 64) - if err != nil { - return time.Time{}, err - } - seconds = i - s = s[16:] - - // Check for TAI64N or TAI64NA format - slen := len(s) - if slen == 8 || slen == 16 { - // time.Time is not attoseconds granular, so - // just pull off the TAI64N section. - i, err := strconv.ParseInt(s[:8], 16, 64) - if err != nil { - return time.Time{}, err - } - nanoseconds = i - } - - if seconds >= tai64Epoch { - // fiddle with add/remove time - unix := seconds - tai64Epoch - offset := getInvOffsetUnix(unix) - unix = unix - offset - t := time.Unix(unix, nanoseconds).UTC() - return t, nil - } - - unix := -(tai64Epoch - seconds + 10) - t := time.Unix(unix, nanoseconds).UTC() - return t, nil -} diff --git a/vendor/src/github.com/cactus/tai64/time_test.go b/vendor/src/github.com/cactus/tai64/time_test.go deleted file mode 100644 index 36f6a13..0000000 --- a/vendor/src/github.com/cactus/tai64/time_test.go +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright (c) 2012-2016 Eli Janssen -// Use of this source code is governed by an MIT-style -// license that can be found in the LICENSE file. - -package tai64 - -import ( - "testing" - "time" - - "github.com/stretchr/testify/assert" -) - -var tests = map[string]struct { - t string - o string -}{ - "a while ago": {"1920-01-01T00:00:00Z", "@3fffffffa1f2cd8a00000000"}, - "before tai swap": {"1969-12-31T23:59:49Z", "@3fffffffffffffff00000000"}, - "at tai swap": {"1969-12-31T23:59:50Z", "@400000000000000000000000"}, - "after tai swap": {"1969-12-31T23:59:51Z", "@400000000000000100000000"}, - "before unix epoch": {"1969-12-31T23:59:59Z", "@400000000000000900000000"}, - "at unix epoch": {"1970-01-01T00:00:00Z", "@400000000000000a00000000"}, - "after unix epoch": {"1970-01-01T00:00:01Z", "@400000000000000b00000000"}, - "before tai-utc epoch": {"1970-01-01T00:00:09Z", "@400000000000001300000000"}, - "at tai-utc epoch": {"1970-01-01T00:00:10Z", "@400000000000001400000000"}, - "after tai-utc epoch": {"1970-01-01T00:00:11Z", "@400000000000001500000000"}, - "a more current date": {"2016-12-31T23:59:59Z", "@40000000586846a300000000"}, - "nanoseconds": {"2015-06-30T23:59:59.908626131Z", "@4000000055932da2362888d3"}, -} - -func TestRoundTripNano(t *testing.T) { - for name, tt := range tests { - tm, err := time.Parse(time.RFC3339Nano, tt.t) - assert.Nil(t, err, "%s: test failed parsing time.Time", name) - o := FormatNano(tm) - p, err := Parse(o) - assert.Nil(t, err, "%s: test failed parsing", name) - assert.Equal(t, tm, p, "%s: test failed date compare: %s", name) - } -} - -func TestRoundTrip(t *testing.T) { - for name, tt := range tests { - tm, err := time.Parse(time.RFC3339Nano, tt.t) - assert.Nil(t, err, "%s: test failed parsing time.Time", name) - o := Format(tm) - p, err := Parse(o[:17]) - assert.Nil(t, err, "%s: test failed parsing", name) - assert.Equal(t, tm.Truncate(time.Second), p, "%s: test failed date compare: %s", name) - } -} - -func TestFormat(t *testing.T) { - for name, tt := range tests { - tm, err := time.Parse(time.RFC3339Nano, tt.t) - assert.Nil(t, err, "%s: test failed parsing time.Time", name) - o := FormatNano(tm) - assert.Equal(t, tt.o, o, "%s: test failed date compare", name) - } -} - -func TestParse(t *testing.T) { - for name, tt := range tests { - tm, err := time.Parse(time.RFC3339Nano, tt.t) - assert.Nil(t, err, "%s: test failed parsing time.Time", name) - p, err := Parse(tt.o) - assert.Nil(t, err, "%s: test failed parsing", name) - assert.Equal(t, tm, p, "%s: test failed date compare", name) - } -} - -func BenchmarkFormat(b *testing.B) { - t := time.Date(2016, 12, 31, 23, 59, 59, 00, time.UTC) - b.ResetTimer() - for i := 0; i < b.N; i++ { - Format(t) - } -} - -func BenchmarkParse(b *testing.B) { - s := "@40000000586846a300000000" - b.ResetTimer() - for i := 0; i < b.N; i++ { - Parse(s) - } -} diff --git a/vendor/src/github.com/cactus/tai64/tools/generate.go b/vendor/src/github.com/cactus/tai64/tools/generate.go deleted file mode 100644 index 6c2309b..0000000 --- a/vendor/src/github.com/cactus/tai64/tools/generate.go +++ /dev/null @@ -1,144 +0,0 @@ -// Copyright (c) 2012-2016 Eli Janssen -// Use of this source code is governed by an MIT-style -// license that can be found in the LICENSE file. - -package main - -import ( - "bufio" - "flag" - "fmt" - "html/template" - "log" - "net/http" - "os" - "path" - "strconv" - "strings" - "time" -) - -const tplText = ` -// Copyright (c) 2012-2016 Eli Janssen -// Use of this source code is governed by an MIT-style -// license that can be found in the LICENSE file. - -// THIS FILE IS AUTOGENERATED. DO NOT EDIT! - -package {{.Pkg}} - -// http://maia.usno.navy.mil/ser7/tai-utc.dat -// http://www.stjarnhimlen.se/comp/time.html -var tia64nDifferences = []struct { - utime int64 - offset int64 -}{ - {{- range .Entries}} - {{"{"}}{{.Ts}}, {{.Drift}}{{"}"}}, // {{.TsD}} - {{- end}} -} - -var tia64nSize = len(tia64nDifferences) -` - -type srcFile struct { - Pkg string - Entries []entry -} - -type entry struct { - Ts int64 - TsD string - Drift int64 -} - -func main() { - var output, input, pkg string - flag.StringVar(&output, "output", "", "output file") - flag.StringVar(&input, "input", "", "input file") - flag.StringVar(&pkg, "pkg", "", "package name") - flag.Parse() - - if output == "" { - log.Fatal("Output option is required") - } - - if pkg == "" { - log.Fatal("Package option is required") - } - - var br *bufio.Reader - if input == "" { - input = "http://maia.usno.navy.mil/ser7/tai-utc.dat" - resp, err := http.Get(input) - if err != nil { - os.Exit(1) - } - defer resp.Body.Close() - br = bufio.NewReader(resp.Body) - } else { - f, err := os.Open(input) - if err != nil { - log.Fatalf("Cant open file: %s", err) - } - defer f.Close() - br = bufio.NewReader(f) - } - - fmt.Printf("Generating %s based on %s\n", path.Base(output), path.Base(input)) - - t, err := template.New("fileTemplate").Parse(strings.TrimLeft(tplText, "\n")) - if err != nil { - log.Fatal(err) - } - - entries := make([]entry, 0) - - for { - line, err := br.ReadString('\n') - if err != nil { - break - } - - line = strings.TrimSpace(line) - if line == "" { - continue - } - - parts := strings.Fields(line) - t, err := time.Parse("2006 Jan 2", strings.Title(strings.Join(parts[0:3], " "))) - if err != nil { - fmt.Println(err) - continue - } - - if t.Before(time.Date(1972, 1, 1, 0, 0, 0, 0, time.UTC)) { - continue - } - - s, err := strconv.ParseFloat(parts[6], 32) - if err != nil { - fmt.Println(err) - continue - } - // just truncate the float to int - e := entry{t.Unix(), t.Format(time.RFC3339), int64(s)} - entries = append(entries, e) - } - - w, err := os.Create(output) - if err != nil { - log.Fatal(err) - } - defer w.Close() - - writer := bufio.NewWriter(w) - defer writer.Flush() - - srcfile := &srcFile{pkg, entries} - err = t.Execute(writer, srcfile) - if err != nil { - log.Fatal(err) - } - -}