From 4eb82d588378b853fe16b00ae3099cca60b7a6ec Mon Sep 17 00:00:00 2001 From: Thomas Jackson Date: Tue, 14 Aug 2018 16:58:34 -0700 Subject: [PATCH] Upgrade prom dep to 2.3 --- Gopkg.lock | 46 +- Gopkg.toml | 8 +- proxyquerier/querier.go | 3 +- proxystorage/proxy.go | 2 +- servergroup/servergroup.go | 5 +- vendor/cloud.google.com/go/.travis.yml | 16 - vendor/cloud.google.com/go/CONTRIBUTING.md | 144 - vendor/cloud.google.com/go/MIGRATION.md | 54 - vendor/cloud.google.com/go/README.md | 514 - vendor/cloud.google.com/go/appveyor.yml | 32 - .../cloud.google.com/go/authexample_test.go | 49 - vendor/cloud.google.com/go/cloud.go | 20 - .../go/compute/metadata/metadata_test.go | 48 - vendor/cloud.google.com/go/key.json.enc | Bin 2432 -> 0 bytes vendor/cloud.google.com/go/license_test.go | 70 - vendor/cloud.google.com/go/old-news.md | 486 - vendor/cloud.google.com/go/run-tests.sh | 88 - .../Azure/azure-sdk-for-go/.gitignore | 32 - .../Azure/azure-sdk-for-go/.travis.yml | 33 - .../Azure/azure-sdk-for-go/CHANGELOG.md | 280 - .../Azure/azure-sdk-for-go/README.md | 102 - .../Azure/azure-sdk-for-go/arm/README.md | 272 - .../Azure/azure-sdk-for-go/glide.lock | 53 - .../Azure/azure-sdk-for-go/glide.yaml | 12 - .../github.com/Azure/go-autorest/.gitignore | 29 - .../github.com/Azure/go-autorest/.travis.yml | 18 - .../github.com/Azure/go-autorest/CHANGELOG.md | 139 - vendor/github.com/Azure/go-autorest/README.md | 131 - .../go-autorest/autorest/autorest_test.go | 126 - .../go-autorest/autorest/azure/async_test.go | 1115 - .../go-autorest/autorest/azure/azure_test.go | 431 - .../autorest/azure/devicetoken_test.go | 301 - .../autorest/azure/environments_test.go | 232 - .../autorest/azure/persist_test.go | 152 - .../go-autorest/autorest/azure/token_test.go | 509 - .../Azure/go-autorest/autorest/client_test.go | 315 - .../go-autorest/autorest/date/date_test.go | 223 - .../go-autorest/autorest/date/time_test.go | 263 - .../autorest/date/timerfc1123_test.go | 212 - .../Azure/go-autorest/autorest/error_test.go | 188 - .../go-autorest/autorest/preparer_test.go | 718 - .../go-autorest/autorest/responder_test.go | 535 - .../Azure/go-autorest/autorest/sender_test.go | 732 - .../go-autorest/autorest/to/convert_test.go | 220 - .../go-autorest/autorest/utility_test.go | 368 - .../autorest/validation/validation_test.go | 2417 -- .../go-autorest/autorest/version_test.go | 13 - .../github.com/Azure/go-autorest/glide.lock | 40 - .../github.com/Azure/go-autorest/glide.yaml | 26 - .../github.com/PuerkitoBio/purell/.gitignore | 5 - .../github.com/PuerkitoBio/purell/.travis.yml | 7 - .../github.com/PuerkitoBio/purell/README.md | 187 - .../PuerkitoBio/purell/bench_test.go | 57 - .../PuerkitoBio/purell/example_test.go | 35 - .../PuerkitoBio/purell/purell_test.go | 768 - .../PuerkitoBio/purell/urlnorm_test.go | 53 - .../github.com/PuerkitoBio/urlesc/.travis.yml | 15 - .../github.com/PuerkitoBio/urlesc/README.md | 16 - .../PuerkitoBio/urlesc/urlesc_test.go | 641 - .../github.com/alecthomas/template/README.md | 25 - .../alecthomas/template/example_test.go | 72 - .../alecthomas/template/examplefiles_test.go | 183 - .../alecthomas/template/examplefunc_test.go | 55 - .../alecthomas/template/exec_test.go | 1044 - .../alecthomas/template/multi_test.go | 293 - .../alecthomas/template/parse/lex_test.go | 468 - .../alecthomas/template/parse/parse_test.go | 426 - vendor/github.com/alecthomas/units/README.md | 11 - .../github.com/alecthomas/units/bytes_test.go | 49 - vendor/github.com/aws/aws-sdk-go/.gitignore | 11 - .../github.com/aws/aws-sdk-go/.godoc_config | 14 - vendor/github.com/aws/aws-sdk-go/.travis.yml | 25 - vendor/github.com/aws/aws-sdk-go/CHANGELOG.md | 2022 -- .../aws/aws-sdk-go/CHANGELOG_PENDING.md | 5 - .../github.com/aws/aws-sdk-go/CONTRIBUTING.md | 127 - vendor/github.com/aws/aws-sdk-go/Gopkg.lock | 20 - vendor/github.com/aws/aws-sdk-go/Gopkg.toml | 48 - vendor/github.com/aws/aws-sdk-go/Makefile | 187 - vendor/github.com/aws/aws-sdk-go/README.md | 449 - .../aws/aws-sdk-go/aws/awsutil/copy_test.go | 353 - .../aws/aws-sdk-go/aws/awsutil/equal_test.go | 30 - .../aws-sdk-go/aws/awsutil/path_value_test.go | 182 - .../aws/aws-sdk-go/aws/client/client_test.go | 78 - .../aws/aws-sdk-go/aws/client/logger_test.go | 57 - .../aws/aws-sdk-go/aws/config_test.go | 86 - .../aws/aws-sdk-go/aws/context_test.go | 37 - .../aws/aws-sdk-go/aws/convert_types_test.go | 641 - .../aws/corehandlers/handlers_1_8_test.go | 64 - .../aws/corehandlers/handlers_test.go | 398 - .../aws/corehandlers/param_validator_test.go | 286 - .../aws/credentials/chain_provider_test.go | 154 - .../aws/credentials/credentials_test.go | 73 - .../ec2rolecreds/ec2_role_provider_test.go | 159 - .../endpointcreds/provider_test.go | 111 - .../aws/credentials/env_provider_test.go | 70 - .../aws-sdk-go/aws/credentials/example.ini | 12 - .../shared_credentials_provider_test.go | 136 - .../aws/credentials/static_provider_test.go | 34 - .../stscreds/assume_role_provider_test.go | 150 - .../aws-sdk-go/aws/defaults/defaults_test.go | 88 - .../aws-sdk-go/aws/ec2metadata/api_test.go | 289 - .../aws/ec2metadata/service_test.go | 78 - .../aws-sdk-go/aws/endpoints/decode_test.go | 117 - .../aws/endpoints/endpoints_test.go | 335 - .../aws-sdk-go/aws/endpoints/example_test.go | 66 - .../aws-sdk-go/aws/endpoints/v3model_test.go | 354 - .../connection_reset_error_other_test.go | 9 - .../request/connection_reset_error_test.go | 11 - .../aws-sdk-go/aws/request/handlers_test.go | 266 - .../aws/request/http_request_copy_test.go | 34 - .../aws/request/http_request_retry_test.go | 37 - .../aws/request/offset_reader_test.go | 139 - .../aws/request/request_1_5_test.go | 11 - .../aws/request/request_1_6_test.go | 51 - .../aws/request/request_1_7_test.go | 24 - .../aws/request/request_1_8_test.go | 85 - .../aws/request/request_context_test.go | 46 - .../aws/request/request_internal_test.go | 27 - .../aws/request/request_pagination_test.go | 604 - .../aws/request/request_resetbody_test.go | 58 - .../aws-sdk-go/aws/request/request_test.go | 844 - .../aws-sdk-go/aws/request/retryer_test.go | 62 - .../timeout_read_closer_benchmark_test.go | 76 - .../aws/request/timeout_read_closer_test.go | 118 - .../aws/aws-sdk-go/aws/request/waiter_test.go | 654 - .../aws/session/custom_ca_bundle_test.go | 243 - .../aws-sdk-go/aws/session/env_config_test.go | 279 - .../aws-sdk-go/aws/session/session_test.go | 428 - .../aws/session/shared_config_test.go | 274 - .../aws/signer/v4/functional_1_5_test.go | 86 - .../aws/signer/v4/functional_test.go | 166 - .../aws/signer/v4/header_rules_test.go | 77 - .../aws/aws-sdk-go/aws/signer/v4/v4_test.go | 644 - .../aws/aws-sdk-go/aws/types_test.go | 92 - .../github.com/aws/aws-sdk-go/buildspec.yml | 21 - vendor/github.com/aws/aws-sdk-go/doc.go | 405 - .../shared_config_other_test.go | 40 - .../shared_config_windows_test.go | 40 - .../aws/aws-sdk-go/private/README.md | 4 - .../protocol/ec2query/build_bench_test.go | 85 - .../private/protocol/ec2query/build_test.go | 1760 - .../protocol/ec2query/unmarshal_test.go | 1678 - .../private/protocol/idempotency_test.go | 106 - .../private/protocol/protocol_test.go | 203 - .../private/protocol/query/build_test.go | 3657 --- .../private/protocol/query/unmarshal_test.go | 2800 -- .../private/protocol/rest/build_test.go | 63 - .../private/protocol/rest/rest_test.go | 63 - .../private/protocol/unmarshal_test.go | 40 - .../protocol/xml/xmlutil/unmarshal_test.go | 142 - .../xml/xmlutil/xml_to_struct_test.go | 66 - .../service/ec2/customizations_test.go | 48 - .../aws-sdk-go/service/ec2/examples_test.go | 4201 --- .../aws/aws-sdk-go/service/generate.go | 5 - .../service/sts/customizations_test.go | 45 - .../aws-sdk-go/service/sts/examples_test.go | 282 - vendor/github.com/beorn7/perks/.gitignore | 2 - vendor/github.com/beorn7/perks/README.md | 31 - .../beorn7/perks/quantile/bench_test.go | 63 - .../beorn7/perks/quantile/example_test.go | 121 - .../beorn7/perks/quantile/exampledata.txt | 2388 -- .../beorn7/perks/quantile/stream_test.go | 215 - vendor/github.com/cespare/xxhash/README.md | 42 - .../cespare/xxhash/xxhash_amd64_test.go | 41 - .../github.com/cespare/xxhash/xxhash_test.go | 154 - vendor/github.com/cockroachdb/cmux/.gitignore | 24 - .../github.com/cockroachdb/cmux/.travis.yml | 29 - vendor/github.com/cockroachdb/cmux/README.md | 72 - .../github.com/cockroachdb/cmux/bench_test.go | 137 - .../github.com/cockroachdb/cmux/cmux_test.go | 485 - .../cmux/example_recursive_test.go | 123 - .../cockroachdb/cmux/example_test.go | 133 - .../cockroachdb/cmux/example_tls_test.go | 89 - .../cockroachdb/cmux/patricia_test.go | 56 - .../cockroachdb/cockroach/.codacy.yml | 4 - .../cockroachdb/cockroach/.editorconfig | 10 - .../cockroachdb/cockroach/.gitattributes | 7 - .../cockroachdb/cockroach/.gitignore | 26 - .../cockroachdb/cockroach/.gitmodules | 3 - .../cockroachdb/cockroach/.go-version | 1 - .../github.com/cockroachdb/cockroach/.mailmap | 50 - .../cockroachdb/cockroach/CONTRIBUTING.md | 177 - .../github.com/cockroachdb/cockroach/Makefile | 329 - .../cockroachdb/cockroach/README.md | 189 - .../github.com/cockroachdb/cockroach/STYLE.md | 80 - .../cockroachdb/cockroach/glide.lock | 555 - .../cockroachdb/cockroach/glide.yaml | 62 - .../github.com/cockroachdb/cockroach/main.go | 29 - .../cockroachdb/cockroach/pkg/Makefile | 20 - .../pkg/ccl/utilccl/license_check.go | 39 + .../cockroach/pkg/util/duration.go | 30 - .../cockroach/pkg/util/duration_test.go | 43 - .../cockroachdb/cockroach/pkg/util/nocopy.go | 27 - .../cockroach/pkg/util/pluralize.go | 25 - .../pkg/util/protoutil/clone_test.go | 89 - .../cockroachdb/cockroach/pkg/util/reflect.go | 55 - .../cockroachdb/cockroach/pkg/util/retry.go | 41 - .../cockroach/pkg/util/roundup2.go | 30 - .../cockroach/pkg/util/smalltrace.go | 43 - .../cockroach/pkg/util/smalltrace_test.go | 37 - .../pkg/util/syncutil/mutex_sync_test.go | 51 - .../cockroach/pkg/util/testaddr_default.go | 24 - .../cockroach/pkg/util/testaddr_random.go | 36 - .../cockroachdb/cockroach/pkg/util/topk.go | 109 - .../cockroach/pkg/util/topk_test.go | 125 - .../cockroach/pkg/util/unresolved_addr.go | 98 - .../cockroach/pkg/util/unresolved_addr.pb.go | 353 - .../cockroach/pkg/util/unresolved_addr.proto | 29 - .../pkg/util/unresolved_addr_test.go | 40 - .../cockroachdb/cockroach/scripts/authors.sh | 15 + vendor/github.com/davecgh/go-spew/.gitignore | 22 - vendor/github.com/davecgh/go-spew/.travis.yml | 14 - vendor/github.com/davecgh/go-spew/README.md | 205 - .../github.com/davecgh/go-spew/cov_report.sh | 22 - .../davecgh/go-spew/spew/common_test.go | 298 - .../davecgh/go-spew/spew/dump_test.go | 1042 - .../davecgh/go-spew/spew/dumpcgo_test.go | 99 - .../davecgh/go-spew/spew/dumpnocgo_test.go | 26 - .../davecgh/go-spew/spew/example_test.go | 226 - .../davecgh/go-spew/spew/format_test.go | 1558 - .../davecgh/go-spew/spew/internal_test.go | 87 - .../go-spew/spew/internalunsafe_test.go | 102 - .../davecgh/go-spew/spew/spew_test.go | 320 - .../davecgh/go-spew/test_coverage.txt | 61 - vendor/github.com/dgrijalva/jwt-go/.gitignore | 4 - .../github.com/dgrijalva/jwt-go/.travis.yml | 8 - .../dgrijalva/jwt-go/MIGRATION_GUIDE.md | 96 - vendor/github.com/dgrijalva/jwt-go/README.md | 85 - .../dgrijalva/jwt-go/VERSION_HISTORY.md | 105 - .../github.com/dgrijalva/jwt-go/ecdsa_test.go | 100 - .../dgrijalva/jwt-go/example_test.go | 114 - .../dgrijalva/jwt-go/hmac_example_test.go | 64 - .../github.com/dgrijalva/jwt-go/hmac_test.go | 91 - .../dgrijalva/jwt-go/http_example_test.go | 216 - .../github.com/dgrijalva/jwt-go/none_test.go | 72 - .../dgrijalva/jwt-go/parser_test.go | 252 - .../dgrijalva/jwt-go/rsa_pss_test.go | 96 - .../github.com/dgrijalva/jwt-go/rsa_test.go | 176 - .../github.com/docker/distribution/.gitignore | 37 - .../github.com/docker/distribution/.mailmap | 19 - .../docker/distribution/BUILDING.md | 119 - .../docker/distribution/CHANGELOG.md | 114 - .../docker/distribution/CONTRIBUTING.md | 140 - .../github.com/docker/distribution/Dockerfile | 18 - .../docker/distribution/MAINTAINERS | 58 - .../github.com/docker/distribution/Makefile | 109 - .../github.com/docker/distribution/README.md | 131 - .../docker/distribution/RELEASE-CHECKLIST.md | 36 - .../github.com/docker/distribution/ROADMAP.md | 267 - .../github.com/docker/distribution/blobs.go | 257 - .../github.com/docker/distribution/circle.yml | 93 - .../docker/distribution/coverpkg.sh | 7 - .../docker/distribution/digest/digest_test.go | 82 - .../digest/digester_resumable_test.go | 21 - .../docker/distribution/digest/set_test.go | 368 - .../distribution/digest/verifiers_test.go | 49 - vendor/github.com/docker/distribution/doc.go | 7 - .../github.com/docker/distribution/errors.go | 115 - .../docker/distribution/manifests.go | 125 - .../distribution/reference/reference_test.go | 661 - .../distribution/reference/regexp_test.go | 489 - .../docker/distribution/registry.go | 97 - vendor/github.com/docker/distribution/tags.go | 27 - .../github.com/emicklei/go-restful/.gitignore | 70 - .../github.com/emicklei/go-restful/CHANGES.md | 159 - .../github.com/emicklei/go-restful/README.md | 74 - vendor/github.com/emicklei/go-restful/Srcfile | 1 - .../emicklei/go-restful/bench_curly_test.go | 51 - .../emicklei/go-restful/bench_test.go | 43 - .../emicklei/go-restful/bench_test.sh | 10 - .../emicklei/go-restful/compress_test.go | 127 - .../emicklei/go-restful/container_test.go | 61 - .../emicklei/go-restful/cors_filter_test.go | 125 - .../emicklei/go-restful/coverage.sh | 2 - .../emicklei/go-restful/curly_test.go | 231 - .../emicklei/go-restful/doc_examples_test.go | 41 - .../go-restful/entity_accessors_test.go | 69 - .../emicklei/go-restful/filter_test.go | 141 - .../github.com/emicklei/go-restful/install.sh | 9 - .../emicklei/go-restful/jsr311_test.go | 212 - .../go-restful/options_filter_test.go | 34 - .../go-restful/path_expression_test.go | 37 - .../emicklei/go-restful/request_test.go | 204 - .../emicklei/go-restful/response_test.go | 204 - .../emicklei/go-restful/route_builder_test.go | 58 - .../emicklei/go-restful/route_test.go | 127 - .../emicklei/go-restful/swagger/CHANGES.md | 43 - .../emicklei/go-restful/swagger/README.md | 76 - .../go-restful/swagger/model_builder_test.go | 1142 - .../go-restful/swagger/model_list_test.go | 48 - .../swagger/model_property_ext_test.go | 60 - .../swagger/model_property_list_test.go | 47 - .../swagger/ordered_route_map_test.go | 29 - .../swagger/postbuild_model_test.go | 42 - .../go-restful/swagger/swagger_test.go | 284 - .../emicklei/go-restful/swagger/utils_test.go | 78 - .../emicklei/go-restful/tracer_test.go | 18 - .../emicklei/go-restful/web_service_test.go | 254 - vendor/github.com/ghodss/yaml/.gitignore | 20 - vendor/github.com/ghodss/yaml/.travis.yml | 7 - vendor/github.com/ghodss/yaml/README.md | 121 - vendor/github.com/ghodss/yaml/yaml_test.go | 287 - vendor/github.com/go-ini/ini/.gitignore | 6 - vendor/github.com/go-ini/ini/.travis.yml | 13 - vendor/github.com/go-ini/ini/Makefile | 12 - vendor/github.com/go-ini/ini/README.md | 763 - vendor/github.com/go-ini/ini/README_ZH.md | 750 - vendor/github.com/go-ini/ini/ini_test.go | 502 - vendor/github.com/go-ini/ini/key_test.go | 573 - vendor/github.com/go-ini/ini/parser_test.go | 42 - vendor/github.com/go-ini/ini/section_test.go | 75 - vendor/github.com/go-ini/ini/struct_test.go | 369 - vendor/github.com/go-kit/kit/.gitignore | 45 - vendor/github.com/go-kit/kit/.travis.yml | 17 - vendor/github.com/go-kit/kit/CONTRIBUTING.md | 18 - vendor/github.com/go-kit/kit/README.md | 119 - vendor/github.com/go-kit/kit/circle.yml | 27 - vendor/github.com/go-kit/kit/coveralls.bash | 31 - .../go-kit/kit/docker-compose-integration.yml | 22 - vendor/github.com/go-kit/kit/lint | 26 - vendor/github.com/go-kit/kit/log/README.md | 147 - .../go-kit/kit/log/benchmark_test.go | 21 - .../go-kit/kit/log/concurrency_test.go | 40 - .../github.com/go-kit/kit/log/example_test.go | 137 - .../go-kit/kit/log/json_logger_test.go | 162 - .../go-kit/kit/log/level/benchmark_test.go | 72 - .../go-kit/kit/log/level/example_test.go | 25 - .../go-kit/kit/log/level/level_test.go | 235 - vendor/github.com/go-kit/kit/log/log_test.go | 191 - .../go-kit/kit/log/logfmt_logger_test.go | 57 - .../go-kit/kit/log/nop_logger_test.go | 26 - .../github.com/go-kit/kit/log/stdlib_test.go | 205 - vendor/github.com/go-kit/kit/log/sync_test.go | 83 - vendor/github.com/go-kit/kit/log/term/LICENSE | 21 + .../github.com/go-kit/kit/log/value_test.go | 150 - vendor/github.com/go-kit/kit/update_deps.bash | 28 - vendor/github.com/go-logfmt/logfmt/.gitignore | 4 - .../github.com/go-logfmt/logfmt/.travis.yml | 15 - vendor/github.com/go-logfmt/logfmt/README.md | 33 - .../go-logfmt/logfmt/decode-bench_test.go | 75 - .../go-logfmt/logfmt/decode_test.go | 184 - .../go-logfmt/logfmt/encode_internal_test.go | 233 - .../go-logfmt/logfmt/encode_test.go | 206 - .../go-logfmt/logfmt/example_test.go | 60 - .../go-openapi/jsonpointer/.editorconfig | 26 - .../go-openapi/jsonpointer/.gitignore | 1 - .../go-openapi/jsonpointer/.travis.yml | 13 - .../go-openapi/jsonpointer/CODE_OF_CONDUCT.md | 74 - .../go-openapi/jsonpointer/README.md | 15 - .../go-openapi/jsonpointer/pointer_test.go | 573 - .../go-openapi/jsonreference/.gitignore | 1 - .../go-openapi/jsonreference/.travis.yml | 14 - .../jsonreference/CODE_OF_CONDUCT.md | 74 - .../go-openapi/jsonreference/README.md | 15 - .../jsonreference/reference_test.go | 420 - .../github.com/go-openapi/spec/.editorconfig | 26 - vendor/github.com/go-openapi/spec/.gitignore | 2 - vendor/github.com/go-openapi/spec/.travis.yml | 16 - .../go-openapi/spec/CODE_OF_CONDUCT.md | 74 - vendor/github.com/go-openapi/spec/README.md | 5 - .../github.com/go-openapi/spec/auth_test.go | 128 - .../go-openapi/spec/contact_info_test.go | 37 - .../go-openapi/spec/expander_test.go | 1162 - .../go-openapi/spec/external_docs_test.go | 29 - .../github.com/go-openapi/spec/header_test.go | 90 - .../github.com/go-openapi/spec/info_test.go | 65 - .../github.com/go-openapi/spec/items_test.go | 81 - .../go-openapi/spec/license_test.go | 28 - .../go-openapi/spec/operation_test.go | 85 - .../go-openapi/spec/parameters_test.go | 156 - .../go-openapi/spec/path_item_test.go | 81 - .../github.com/go-openapi/spec/paths_test.go | 43 - .../go-openapi/spec/properties_test.go | 58 - .../go-openapi/spec/response_test.go | 53 - .../github.com/go-openapi/spec/schema_test.go | 205 - .../go-openapi/spec/structs_test.go | 110 - .../go-openapi/spec/swagger_test.go | 365 - .../go-openapi/spec/xml_object_test.go | 65 - .../github.com/go-openapi/swag/.editorconfig | 26 - vendor/github.com/go-openapi/swag/.gitignore | 1 - vendor/github.com/go-openapi/swag/.travis.yml | 14 - .../go-openapi/swag/CODE_OF_CONDUCT.md | 74 - vendor/github.com/go-openapi/swag/README.md | 12 - .../go-openapi/swag/convert_test.go | 215 - .../go-openapi/swag/convert_types_test.go | 579 - .../github.com/go-openapi/swag/json_test.go | 163 - .../go-openapi/swag/loading_test.go | 47 - vendor/github.com/go-openapi/swag/net_test.go | 30 - .../github.com/go-openapi/swag/path_test.go | 118 - .../github.com/go-openapi/swag/util_test.go | 277 - .../github.com/go-openapi/swag/yaml_test.go | 444 - vendor/github.com/go-stack/stack/.travis.yml | 13 - vendor/github.com/go-stack/stack/README.md | 38 - .../github.com/go-stack/stack/format_test.go | 21 - .../go-stack/stack/stack-go19_test.go | 67 - .../github.com/go-stack/stack/stack_test.go | 582 - vendor/github.com/gogo/protobuf/.gitignore | 3 - vendor/github.com/gogo/protobuf/.mailmap | 8 - vendor/github.com/gogo/protobuf/.travis.yml | 20 - vendor/github.com/gogo/protobuf/Makefile | 161 - vendor/github.com/gogo/protobuf/README | 257 - vendor/github.com/gogo/protobuf/Readme.md | 122 - vendor/github.com/gogo/protobuf/bench.md | 190 - .../github.com/gogo/protobuf/custom_types.md | 68 - vendor/github.com/gogo/protobuf/extensions.md | 162 - .../gogo/protobuf/gogoproto/Makefile | 37 - .../github.com/gogo/protobuf/gogoproto/doc.go | 169 - .../gogo/protobuf/gogoproto/gogo.pb.go | 803 - .../gogo/protobuf/gogoproto/gogo.pb.golden | 45 - .../gogo/protobuf/gogoproto/gogo.proto | 132 - .../gogo/protobuf/gogoproto/helper.go | 357 - .../gogo/protobuf/install-protobuf.sh | 32 - .../gogo/protobuf/jsonpb/jsonpb_test.go | 783 - .../github.com/gogo/protobuf/proto/Makefile | 43 - .../gogo/protobuf/proto/all_test.go | 2278 -- .../gogo/protobuf/proto/any_test.go | 300 - .../gogo/protobuf/proto/clone_test.go | 300 - .../gogo/protobuf/proto/decode_test.go | 262 - .../gogo/protobuf/proto/encode_test.go | 84 - .../gogo/protobuf/proto/equal_test.go | 224 - .../gogo/protobuf/proto/extensions_test.go | 538 - .../gogo/protobuf/proto/map_test.go | 46 - .../gogo/protobuf/proto/message_set_test.go | 66 - .../gogo/protobuf/proto/proto3_test.go | 135 - .../gogo/protobuf/proto/size2_test.go | 63 - .../gogo/protobuf/proto/size_test.go | 164 - .../gogo/protobuf/proto/text_parser_test.go | 673 - .../gogo/protobuf/proto/text_test.go | 474 - .../gogo/protobuf/protoc-gen-gogo/Makefile | 33 - .../protoc-gen-gogo/descriptor/Makefile | 36 - .../protoc-gen-gogo/descriptor/descriptor.go | 118 - .../descriptor/descriptor.pb.go | 2223 -- .../descriptor/descriptor_gostring.gen.go | 749 - .../descriptor/descriptor_test.go | 31 - .../protoc-gen-gogo/descriptor/helper.go | 390 - .../gogo/protobuf/protoc-gen-gogo/doc.go | 51 - .../gogo/protobuf/protoc-gen-gogo/main.go | 57 - .../github.com/gogo/protobuf/types/Makefile | 39 - .../gogo/protobuf/types/any_test.go | 112 - .../gogo/protobuf/types/duration_test.go | 120 - .../gogo/protobuf/types/timestamp_test.go | 152 - vendor/github.com/golang/glog/README | 44 - vendor/github.com/golang/glog/glog_test.go | 415 - vendor/github.com/golang/protobuf/.gitignore | 16 - vendor/github.com/golang/protobuf/.travis.yml | 18 - .../github.com/golang/protobuf/Make.protobuf | 40 - vendor/github.com/golang/protobuf/Makefile | 55 - vendor/github.com/golang/protobuf/README.md | 243 - .../golang/protobuf/jsonpb/jsonpb_test.go | 896 - .../github.com/golang/protobuf/proto/Makefile | 43 - .../golang/protobuf/proto/all_test.go | 2278 -- .../golang/protobuf/proto/any_test.go | 300 - .../golang/protobuf/proto/clone_test.go | 300 - .../golang/protobuf/proto/decode_test.go | 258 - .../golang/protobuf/proto/encode_test.go | 85 - .../golang/protobuf/proto/equal_test.go | 224 - .../golang/protobuf/proto/extensions_test.go | 536 - .../golang/protobuf/proto/map_test.go | 46 - .../golang/protobuf/proto/message_set_test.go | 66 - .../golang/protobuf/proto/proto3_test.go | 135 - .../golang/protobuf/proto/size2_test.go | 63 - .../golang/protobuf/proto/size_test.go | 164 - .../golang/protobuf/proto/text_parser_test.go | 673 - .../golang/protobuf/proto/text_test.go | 474 - .../golang/protobuf/protoc-gen-go/Makefile | 33 - .../protoc-gen-go/descriptor/Makefile | 37 - .../protoc-gen-go/descriptor/descriptor.proto | 849 - .../golang/protobuf/protoc-gen-go/doc.go | 51 - .../protobuf/protoc-gen-go/link_grpc.go | 34 - .../golang/protobuf/protoc-gen-go/main.go | 98 - .../golang/protobuf/ptypes/any/any.proto | 149 - .../golang/protobuf/ptypes/any_test.go | 113 - .../protobuf/ptypes/duration/duration.proto | 117 - .../golang/protobuf/ptypes/duration_test.go | 121 - .../golang/protobuf/ptypes/regen.sh | 43 - .../protobuf/ptypes/struct/struct.proto | 96 - .../protobuf/ptypes/timestamp/timestamp.proto | 133 - .../golang/protobuf/ptypes/timestamp_test.go | 153 - vendor/github.com/golang/snappy/.gitignore | 16 - vendor/github.com/golang/snappy/README | 107 - .../github.com/golang/snappy/golden_test.go | 1965 -- .../github.com/golang/snappy/snappy_test.go | 1353 - vendor/github.com/google/gofuzz/.travis.yml | 13 - .../github.com/google/gofuzz/CONTRIBUTING.md | 67 - vendor/github.com/google/gofuzz/README.md | 71 - .../github.com/google/gofuzz/example_test.go | 225 - vendor/github.com/google/gofuzz/fuzz_test.go | 472 - .../gophercloud/gophercloud/.gitignore | 1 - .../gophercloud/gophercloud/.travis.yml | 21 - .../github.com/gophercloud/gophercloud/FAQ.md | 148 - .../gophercloud/gophercloud/MIGRATING.md | 32 - .../gophercloud/gophercloud/README.md | 143 - .../gophercloud/gophercloud/STYLEGUIDE.md | 74 - .../compute/v2/extensions/delegate.go | 23 - .../openstack/compute/v2/extensions/doc.go | 3 - .../grpc-ecosystem/grpc-gateway/.gitignore | 2 - .../grpc-ecosystem/grpc-gateway/.travis.yml | 38 - .../grpc-ecosystem/grpc-gateway/CHANGELOG.md | 215 - .../grpc-gateway/CONTRIBUTING.md | 20 - .../grpc-ecosystem/grpc-gateway/Makefile | 154 - .../grpc-ecosystem/grpc-gateway/README.md | 245 - .../grpc-gateway/runtime/context_test.go | 172 - .../grpc-gateway/runtime/errors_test.go | 57 - .../grpc-gateway/runtime/handler_test.go | 204 - .../runtime/internal/stream_chunk.proto | 12 - .../grpc-gateway/runtime/marshal_json_test.go | 245 - .../runtime/marshal_jsonpb_test.go | 618 - .../runtime/marshal_proto_test.go | 91 - .../runtime/marshaler_registry_test.go | 107 - .../grpc-gateway/runtime/mux_test.go | 213 - .../grpc-gateway/runtime/pattern_test.go | 590 - .../grpc-gateway/runtime/query_test.go | 715 - .../third_party/googleapis/LICENSE} | 7 +- .../grpc-gateway/utilities/trie_test.go | 372 - vendor/github.com/hashicorp/consul/.gitignore | 22 - .../github.com/hashicorp/consul/.travis.yml | 13 - .../github.com/hashicorp/consul/CHANGELOG.md | 1069 - .../github.com/hashicorp/consul/GNUmakefile | 108 - .../hashicorp/consul/ISSUE_TEMPLATE.md | 35 - vendor/github.com/hashicorp/consul/README.md | 70 - .../github.com/hashicorp/consul/api/README.md | 43 - .../hashicorp/consul/api/acl_test.go | 164 - .../hashicorp/consul/api/agent_test.go | 836 - .../hashicorp/consul/api/api_test.go | 537 - .../hashicorp/consul/api/catalog_test.go | 476 - .../hashicorp/consul/api/coordinate_test.go | 44 - .../hashicorp/consul/api/event_test.go | 50 - .../hashicorp/consul/api/health_test.go | 354 - .../hashicorp/consul/api/kv_test.go | 574 - .../hashicorp/consul/api/lock_test.go | 560 - .../consul/api/operator_autopilot_test.go | 104 - .../consul/api/operator_keyring_test.go | 73 - .../consul/api/operator_raft_test.go | 38 - .../consul/api/prepared_query_test.go | 133 - .../hashicorp/consul/api/semaphore_test.go | 518 - .../hashicorp/consul/api/session_test.go | 392 - .../hashicorp/consul/api/snapshot_test.go | 134 - .../hashicorp/consul/api/status_test.go | 37 - vendor/github.com/hashicorp/consul/main.go | 57 - .../github.com/hashicorp/consul/main_test.go | 1 - .../hashicorp/consul/website/LICENSE.md | 10 + .../hashicorp/go-cleanhttp/README.md | 30 - .../hashicorp/go-cleanhttp/handlers_test.go | 72 - .../hashicorp/go-rootcerts/.travis.yml | 12 - .../hashicorp/go-rootcerts/Makefile | 8 - .../hashicorp/go-rootcerts/README.md | 43 - .../go-rootcerts/rootcerts_darwin_test.go | 17 - .../hashicorp/go-rootcerts/rootcerts_test.go | 52 - .../capath-with-symlinks/securetrust.pem | 1 + .../capath-with-symlinks/thawte.pem | 1 + vendor/github.com/hashicorp/serf/.gitignore | 32 - vendor/github.com/hashicorp/serf/.travis.yml | 15 - vendor/github.com/hashicorp/serf/CHANGELOG.md | 398 - vendor/github.com/hashicorp/serf/GNUmakefile | 64 - vendor/github.com/hashicorp/serf/README.md | 121 - .../hashicorp/serf/coordinate/client_test.go | 109 - .../serf/coordinate/coordinate_test.go | 260 - .../serf/coordinate/performance_test.go | 182 - .../hashicorp/serf/coordinate/util_test.go | 27 - .../hashicorp/serf/ops-misc/debian/copyright | 2 + .../hashicorp/serf/website/source/LICENSE | 10 + .../github.com/jessevdk/go-flags/.travis.yml | 38 - vendor/github.com/jessevdk/go-flags/README.md | 135 - .../github.com/jessevdk/go-flags/arg_test.go | 163 - .../jessevdk/go-flags/assert_test.go | 177 - .../jessevdk/go-flags/check_crosscompile.sh | 16 - .../jessevdk/go-flags/command_test.go | 582 - .../jessevdk/go-flags/completion_test.go | 315 - .../jessevdk/go-flags/convert_test.go | 159 - .../jessevdk/go-flags/example_test.go | 110 - .../jessevdk/go-flags/group_test.go | 255 - .../github.com/jessevdk/go-flags/help_test.go | 538 - .../github.com/jessevdk/go-flags/ini_test.go | 1053 - .../github.com/jessevdk/go-flags/long_test.go | 85 - .../jessevdk/go-flags/marshal_test.go | 119 - .../jessevdk/go-flags/options_test.go | 45 - .../jessevdk/go-flags/parser_test.go | 612 - .../jessevdk/go-flags/pointer_test.go | 164 - .../jessevdk/go-flags/short_test.go | 234 - .../github.com/jessevdk/go-flags/tag_test.go | 38 - .../jessevdk/go-flags/unknown_test.go | 66 - .../jmespath/go-jmespath/.gitignore | 4 - .../jmespath/go-jmespath/.travis.yml | 9 - .../github.com/jmespath/go-jmespath/Makefile | 44 - .../github.com/jmespath/go-jmespath/README.md | 7 - .../jmespath/go-jmespath/api_test.go | 32 - .../jmespath/go-jmespath/compliance_test.go | 123 - .../jmespath/go-jmespath/interpreter_test.go | 221 - .../jmespath/go-jmespath/lexer_test.go | 161 - .../jmespath/go-jmespath/parser_test.go | 136 - .../jmespath/go-jmespath/util_test.go | 73 - vendor/github.com/json-iterator/go/LICENSE | 21 + vendor/github.com/json-iterator/go/adapter.go | 150 + vendor/github.com/json-iterator/go/any.go | 321 + .../github.com/json-iterator/go/any_array.go | 278 + .../github.com/json-iterator/go/any_bool.go | 137 + .../github.com/json-iterator/go/any_float.go | 83 + .../github.com/json-iterator/go/any_int32.go | 74 + .../github.com/json-iterator/go/any_int64.go | 74 + .../json-iterator/go/any_invalid.go | 82 + vendor/github.com/json-iterator/go/any_nil.go | 69 + .../github.com/json-iterator/go/any_number.go | 123 + .../github.com/json-iterator/go/any_object.go | 374 + vendor/github.com/json-iterator/go/any_str.go | 166 + .../github.com/json-iterator/go/any_uint32.go | 74 + .../github.com/json-iterator/go/any_uint64.go | 74 + vendor/github.com/json-iterator/go/config.go | 375 + vendor/github.com/json-iterator/go/iter.go | 322 + .../github.com/json-iterator/go/iter_array.go | 58 + .../github.com/json-iterator/go/iter_float.go | 347 + .../github.com/json-iterator/go/iter_int.go | 345 + .../json-iterator/go/iter_object.go | 251 + .../github.com/json-iterator/go/iter_skip.go | 129 + .../json-iterator/go/iter_skip_sloppy.go | 144 + .../json-iterator/go/iter_skip_strict.go | 89 + .../github.com/json-iterator/go/iter_str.go | 215 + .../github.com/json-iterator/go/jsoniter.go | 18 + vendor/github.com/json-iterator/go/pool.go | 42 + vendor/github.com/json-iterator/go/reflect.go | 332 + .../json-iterator/go/reflect_array.go | 104 + .../json-iterator/go/reflect_dynamic.go | 70 + .../json-iterator/go/reflect_extension.go | 483 + .../json-iterator/go/reflect_json_number.go | 112 + .../go/reflect_json_raw_message.go | 60 + .../json-iterator/go/reflect_map.go | 326 + .../json-iterator/go/reflect_marshaler.go | 218 + .../json-iterator/go/reflect_native.go | 451 + .../json-iterator/go/reflect_optional.go | 133 + .../json-iterator/go/reflect_slice.go | 99 + .../go/reflect_struct_decoder.go | 1048 + .../go/reflect_struct_encoder.go | 210 + vendor/github.com/json-iterator/go/stream.go | 211 + .../json-iterator/go/stream_float.go | 94 + .../github.com/json-iterator/go/stream_int.go | 190 + .../github.com/json-iterator/go/stream_str.go | 372 + vendor/github.com/juju/ratelimit/README.md | 117 - .../juju/ratelimit/ratelimit_test.go | 389 - .../julienschmidt/httprouter/.travis.yml | 8 - .../julienschmidt/httprouter/README.md | 323 - .../julienschmidt/httprouter/path_test.go | 92 - .../julienschmidt/httprouter/router_test.go | 378 - .../julienschmidt/httprouter/tree_test.go | 611 - vendor/github.com/kr/logfmt/.gitignore | 3 - vendor/github.com/kr/logfmt/Readme | 12 - vendor/github.com/kr/logfmt/bench_test.go | 59 - vendor/github.com/kr/logfmt/decode_test.go | 110 - vendor/github.com/kr/logfmt/example_test.go | 59 - vendor/github.com/kr/logfmt/scanner_test.go | 67 - vendor/github.com/mailru/easyjson/.gitignore | 4 - vendor/github.com/mailru/easyjson/.travis.yml | 9 - vendor/github.com/mailru/easyjson/Makefile | 55 - vendor/github.com/mailru/easyjson/README.md | 331 - .../mailru/easyjson/buffer/pool_test.go | 107 - .../mailru/easyjson/jlexer/lexer_test.go | 251 - .../golang_protobuf_extensions/.travis.yml | 2 - .../golang_protobuf_extensions/README.md | 20 - .../pbutil/all_test.go | 177 - .../pbutil/decode_test.go | 99 - .../pbutil/encode_test.go | 67 - .../pbutil/fixtures_test.go | 103 - vendor/github.com/miekg/dns/.gitignore | 4 - vendor/github.com/miekg/dns/.travis.yml | 14 - vendor/github.com/miekg/dns/README.md | 162 - vendor/github.com/miekg/dns/client_test.go | 680 - .../github.com/miekg/dns/clientconfig_test.go | 87 - vendor/github.com/miekg/dns/dns_bench_test.go | 230 - vendor/github.com/miekg/dns/dns_test.go | 453 - vendor/github.com/miekg/dns/dnssec_test.go | 733 - vendor/github.com/miekg/dns/dyn_test.go | 3 - vendor/github.com/miekg/dns/edns_test.go | 68 - vendor/github.com/miekg/dns/example_test.go | 146 - vendor/github.com/miekg/dns/fuzz_test.go | 25 - .../internal/socket/controlmessage_test.go | 103 - vendor/github.com/miekg/dns/issue_test.go | 68 - vendor/github.com/miekg/dns/labels_test.go | 203 - vendor/github.com/miekg/dns/msg_test.go | 124 - vendor/github.com/miekg/dns/nsecx_test.go | 133 - vendor/github.com/miekg/dns/parse_test.go | 1508 - vendor/github.com/miekg/dns/privaterr_test.go | 171 - vendor/github.com/miekg/dns/remote_test.go | 19 - vendor/github.com/miekg/dns/sanitize_test.go | 84 - vendor/github.com/miekg/dns/scan_test.go | 48 - vendor/github.com/miekg/dns/server_test.go | 729 - vendor/github.com/miekg/dns/sig0_test.go | 89 - vendor/github.com/miekg/dns/tsig_test.go | 52 - vendor/github.com/miekg/dns/types_test.go | 74 - vendor/github.com/miekg/dns/udp_linux_test.go | 68 - vendor/github.com/miekg/dns/update_test.go | 145 - vendor/github.com/miekg/dns/xfr_test.go | 184 - .../github.com/mitchellh/go-homedir/README.md | 14 - .../mitchellh/go-homedir/homedir_test.go | 112 - .../github.com/modern-go/concurrent/LICENSE | 201 + .../modern-go/concurrent/executor.go | 14 + .../modern-go/concurrent/go_above_19.go | 15 + .../modern-go/concurrent/go_below_19.go | 33 + vendor/github.com/modern-go/concurrent/log.go | 13 + .../concurrent/unbounded_executor.go | 119 + vendor/github.com/modern-go/reflect2/LICENSE | 201 + .../modern-go/reflect2/go_above_17.go | 8 + .../modern-go/reflect2/go_above_19.go | 14 + .../modern-go/reflect2/go_below_17.go | 9 + .../modern-go/reflect2/go_below_19.go | 14 + .../github.com/modern-go/reflect2/reflect2.go | 298 + .../reflect2/reflect2_amd64.s} | 0 .../modern-go/reflect2/reflect2_kind.go | 30 + .../modern-go/reflect2/relfect2_386.s | 0 .../modern-go/reflect2/relfect2_amd64p32.s | 0 .../modern-go/reflect2/relfect2_arm.s | 0 .../modern-go/reflect2/relfect2_arm64.s | 0 .../modern-go/reflect2/relfect2_mips64x.s | 0 .../modern-go/reflect2/relfect2_mipsx.s | 0 .../modern-go/reflect2/relfect2_ppc64x.s | 0 .../modern-go/reflect2/relfect2_s390x.s | 0 .../modern-go/reflect2/safe_field.go | 58 + .../github.com/modern-go/reflect2/safe_map.go | 101 + .../modern-go/reflect2/safe_slice.go | 92 + .../modern-go/reflect2/safe_struct.go | 29 + .../modern-go/reflect2/safe_type.go | 78 + .../github.com/modern-go/reflect2/type_map.go | 103 + .../modern-go/reflect2/unsafe_array.go | 65 + .../modern-go/reflect2/unsafe_eface.go | 59 + .../modern-go/reflect2/unsafe_field.go | 74 + .../modern-go/reflect2/unsafe_iface.go | 64 + .../modern-go/reflect2/unsafe_link.go | 70 + .../modern-go/reflect2/unsafe_map.go | 138 + .../modern-go/reflect2/unsafe_ptr.go | 46 + .../modern-go/reflect2/unsafe_slice.go | 177 + .../modern-go/reflect2/unsafe_struct.go | 59 + .../modern-go/reflect2/unsafe_type.go | 85 + .../mwitkow/go-conntrack/.gitignore | 163 - .../mwitkow/go-conntrack/.travis.yml | 13 - .../github.com/mwitkow/go-conntrack/README.md | 88 - .../mwitkow/go-conntrack/dialer_test.go | 189 - .../mwitkow/go-conntrack/listener_test.go | 100 - .../mwitkow/go-conntrack/promhelper_test.go | 56 - .../mwitkow/go-conntrack/tracehelper_test.go | 23 - .../github.com/nightlyone/lockfile/.gitignore | 27 - .../nightlyone/lockfile/.gitmodules | 3 - .../nightlyone/lockfile/.travis.yml | 14 - .../github.com/nightlyone/lockfile/README.md | 52 - .../nightlyone/lockfile/appveyor.yml | 12 - .../nightlyone/lockfile/lockfile_test.go | 308 - vendor/github.com/oklog/ulid/.gitignore | 29 - vendor/github.com/oklog/ulid/.travis.yml | 17 - vendor/github.com/oklog/ulid/CHANGELOG.md | 12 - vendor/github.com/oklog/ulid/CONTRIBUTING.md | 17 - vendor/github.com/oklog/ulid/README.md | 144 - vendor/github.com/oklog/ulid/ulid_test.go | 535 - .../opentracing-contrib/go-stdlib/.travis.yml | 11 - .../opentracing-contrib/go-stdlib/README.md | 18 - .../go-stdlib/nethttp/client_test.go | 101 - .../go-stdlib/nethttp/server_test.go | 109 - .../opentracing/opentracing-go/.gitignore | 13 - .../opentracing/opentracing-go/.travis.yml | 14 - .../opentracing/opentracing-go/CHANGELOG.md | 14 - .../opentracing/opentracing-go/Makefile | 32 - .../opentracing/opentracing-go/README.md | 147 - .../opentracing-go/ext/tags_test.go | 148 - .../opentracing-go/gocontext_test.go | 81 - .../opentracing-go/log/field_test.go | 39 - .../opentracing-go/options_test.go | 31 - .../opentracing-go/propagation_test.go | 93 - .../opentracing-go/testtracer_test.go | 138 - vendor/github.com/petermattis/goid/.gitignore | 4 - .../github.com/petermattis/goid/.travis.yml | 11 - vendor/github.com/petermattis/goid/README.md | 5 - .../github.com/petermattis/goid/goid_test.go | 50 - vendor/github.com/pkg/errors/.gitignore | 24 - vendor/github.com/pkg/errors/.travis.yml | 11 - vendor/github.com/pkg/errors/README.md | 52 - vendor/github.com/pkg/errors/appveyor.yml | 32 - vendor/github.com/pkg/errors/bench_test.go | 59 - vendor/github.com/pkg/errors/errors_test.go | 226 - vendor/github.com/pkg/errors/example_test.go | 205 - vendor/github.com/pkg/errors/format_test.go | 535 - vendor/github.com/pkg/errors/stack_test.go | 292 - .../prometheus/client_golang/.gitignore | 26 - .../prometheus/client_golang/.travis.yml | 9 - .../prometheus/client_golang/AUTHORS.md | 18 - .../prometheus/client_golang/CHANGELOG.md | 109 - .../prometheus/client_golang/CONTRIBUTING.md | 18 - .../prometheus/client_golang/README.md | 45 - .../prometheus/client_golang/VERSION | 1 - .../client_golang/prometheus/.gitignore | 1 - .../client_golang/prometheus/README.md | 1 - .../prometheus/benchmark_test.go | 183 - .../client_golang/prometheus/collector.go | 39 +- .../client_golang/prometheus/counter.go | 191 +- .../client_golang/prometheus/counter_test.go | 58 - .../client_golang/prometheus/desc.go | 39 +- .../client_golang/prometheus/doc.go | 94 +- .../prometheus/example_clustermanager_test.go | 118 - .../client_golang/prometheus/examples_test.go | 751 - .../prometheus/expvar_collector_test.go | 97 - .../client_golang/prometheus/gauge.go | 204 +- .../client_golang/prometheus/gauge_test.go | 182 - .../client_golang/prometheus/go_collector.go | 61 +- .../prometheus/go_collector_test.go | 123 - .../client_golang/prometheus/histogram.go | 147 +- .../prometheus/histogram_test.go | 326 - .../client_golang/prometheus/http.go | 130 +- .../client_golang/prometheus/http_test.go | 121 - .../client_golang/prometheus/labels.go | 57 + .../client_golang/prometheus/metric.go | 34 +- .../client_golang/prometheus/metric_test.go | 35 - .../client_golang/prometheus/observer.go | 52 + .../prometheus/process_collector.go | 127 +- .../prometheus/process_collector_test.go | 58 - .../prometheus/promhttp/delegator.go | 199 + .../prometheus/promhttp/delegator_1_8.go | 181 + .../prometheus/promhttp/delegator_pre_1_8.go} | 38 +- .../client_golang/prometheus/promhttp/http.go | 311 + .../prometheus/promhttp/instrument_client.go | 97 + .../promhttp/instrument_client_1_8.go | 144 + .../prometheus/promhttp/instrument_server.go | 447 + .../client_golang/prometheus/registry.go | 581 +- .../client_golang/prometheus/registry_test.go | 545 - .../client_golang/prometheus/summary.go | 185 +- .../client_golang/prometheus/summary_test.go | 347 - .../client_golang/prometheus/timer.go | 51 + .../client_golang/prometheus/untyped.go | 102 +- .../client_golang/prometheus/value.go | 82 +- .../client_golang/prometheus/vec.go | 494 +- .../client_golang/prometheus/vec_test.go | 312 - .../prometheus/client_model/.gitignore | 1 - .../prometheus/client_model/CONTRIBUTING.md | 18 - .../prometheus/client_model/MAINTAINERS.md | 1 - .../prometheus/client_model/Makefile | 61 - .../prometheus/client_model/README.md | 26 - .../prometheus/client_model/metrics.proto | 81 - .../prometheus/client_model/pom.xml | 130 - .../prometheus/client_model/ruby/LICENSE | 201 + .../prometheus/client_model/setup.py | 23 - .../github.com/prometheus/common/.travis.yml | 6 - .../prometheus/common/CONTRIBUTING.md | 18 - .../prometheus/common/MAINTAINERS.md | 1 - vendor/github.com/prometheus/common/README.md | 12 - .../prometheus/common/config/config.go | 19 +- .../prometheus/common/config/http_config.go | 166 +- .../common/config/http_config_test.go | 157 - .../common/config/tls_config_test.go | 92 - .../prometheus/common/expfmt/bench_test.go | 167 - .../prometheus/common/expfmt/decode_test.go | 435 - .../common/expfmt/text_create_test.go | 443 - .../prometheus/common/expfmt/text_parse.go | 2 +- .../common/expfmt/text_parse_test.go | 593 - .../bitbucket.org/ww/goautoneg/README.txt | 67 - .../ww/goautoneg/autoneg_test.go | 33 - .../prometheus/common/log/log_test.go | 39 - .../common/log/syslog_formatter_test.go | 52 - .../prometheus/common/model/alert_test.go | 118 - .../prometheus/common/model/labels_test.go | 140 - .../prometheus/common/model/metric_test.go | 132 - .../prometheus/common/model/signature_test.go | 314 - .../prometheus/common/model/silence_test.go | 228 - .../prometheus/common/model/time_test.go | 221 - .../common/model/value_bench_test.go | 131 - .../prometheus/common/model/value_test.go | 502 - .../prometheus/common/route/route_test.go | 76 - .../github.com/prometheus/procfs/.travis.yml | 5 - .../prometheus/procfs/CONTRIBUTING.md | 18 - .../prometheus/procfs/MAINTAINERS.md | 1 - vendor/github.com/prometheus/procfs/Makefile | 18 - vendor/github.com/prometheus/procfs/README.md | 11 - .../prometheus/procfs/buddyinfo_test.go | 64 - .../prometheus/procfs/fixtures/26231/exe | 1 + .../prometheus/procfs/fixtures/26231/fd/0 | 1 + .../prometheus/procfs/fixtures/26231/fd/1 | 1 + .../prometheus/procfs/fixtures/26231/fd/10 | 1 + .../prometheus/procfs/fixtures/26231/fd/2 | 1 + .../prometheus/procfs/fixtures/26231/fd/3 | 1 + .../prometheus/procfs/fixtures/26232/fd/0 | 1 + .../prometheus/procfs/fixtures/26232/fd/1 | 1 + .../prometheus/procfs/fixtures/26232/fd/2 | 1 + .../prometheus/procfs/fixtures/26232/fd/3 | 1 + .../prometheus/procfs/fixtures/26232/fd/4 | 1 + .../prometheus/procfs/fixtures/self | 1 + .../github.com/prometheus/procfs/fs_test.go | 26 - .../github.com/prometheus/procfs/ipvs_test.go | 237 - .../prometheus/procfs/mdstat_test.go | 31 - .../prometheus/procfs/mountstats_test.go | 273 - .../prometheus/procfs/proc_io_test.go | 33 - .../prometheus/procfs/proc_limits_test.go | 31 - .../prometheus/procfs/proc_stat_test.go | 110 - .../github.com/prometheus/procfs/proc_test.go | 160 - .../github.com/prometheus/procfs/stat_test.go | 61 - vendor/github.com/prometheus/procfs/ttar | 264 - .../github.com/prometheus/procfs/xfrm_test.go | 66 - .../prometheus/procfs/xfs/parse_test.go | 442 - .../prometheus/prometheus/.dockerignore | 5 - .../prometheus/prometheus/.gitignore | 23 - .../prometheus/prometheus/.promu.yml | 49 - .../prometheus/prometheus/.travis.yml | 12 - .../prometheus/prometheus/CHANGELOG.md | 1083 - .../prometheus/prometheus/CONTRIBUTING.md | 51 - .../prometheus/prometheus/Dockerfile | 22 - .../prometheus/prometheus/MAINTAINERS.md | 6 - .../github.com/prometheus/prometheus/Makefile | 106 - .../prometheus/prometheus/README.md | 105 - .../github.com/prometheus/prometheus/VERSION | 1 - .../prometheus/prometheus/circle.yml | 63 - .../prometheus/prometheus/code-of-conduct.md | 3 - .../prometheus/prometheus/config/config.go | 95 +- .../prometheus/config/config_test.go | 751 - .../prometheus/config/config_windows_test.go | 26 - .../prometheus/prometheus/discovery/README.md | 219 - .../prometheus/discovery/azure/azure.go | 7 +- .../prometheus/discovery/config/config.go | 10 +- .../prometheus/discovery/consul/consul.go | 426 +- .../discovery/consul/consul_test.go | 46 - .../prometheus/discovery/dns/dns.go | 19 +- .../prometheus/discovery/ec2/ec2.go | 52 +- .../prometheus/discovery/file/file.go | 17 +- .../prometheus/discovery/file/file_test.go | 172 - .../prometheus/discovery/gce/gce.go | 20 +- .../discovery/kubernetes/endpoints.go | 153 +- .../discovery/kubernetes/endpoints_test.go | 370 - .../discovery/kubernetes/ingress.go | 139 +- .../discovery/kubernetes/ingress_test.go | 136 - .../discovery/kubernetes/kubernetes.go | 200 +- .../prometheus/discovery/kubernetes/node.go | 125 +- .../discovery/kubernetes/node_test.go | 355 - .../prometheus/discovery/kubernetes/pod.go | 153 +- .../discovery/kubernetes/pod_test.go | 395 - .../discovery/kubernetes/service.go | 122 +- .../discovery/kubernetes/service_test.go | 253 - .../prometheus/discovery/manager.go | 18 +- .../prometheus/discovery/manager_test.go | 818 - .../prometheus/discovery/marathon/marathon.go | 136 +- .../discovery/marathon/marathon_test.go | 548 - .../discovery/openstack/hypervisor_test.go | 82 - .../discovery/openstack/instance_test.go | 85 - .../discovery/openstack/openstack.go | 6 +- .../discovery/targetgroup/targetgroup.go | 8 +- .../discovery/targetgroup/targetgroup_test.go | 48 - .../prometheus/discovery/triton/triton.go | 8 +- .../discovery/triton/triton_test.go | 183 - .../discovery/zookeeper/zookeeper.go | 20 +- .../prometheus/notifier/notifier.go | 8 +- .../prometheus/notifier/notifier_test.go | 574 - .../prometheus/pkg/labels/matcher_test.go | 89 - .../prometheus/pkg/relabel/relabel_test.go | 423 - .../prometheus/pkg/rulefmt/rulefmt.go | 36 +- .../prometheus/pkg/rulefmt/rulefmt_test.go | 81 - .../prometheus/prometheus/pkg/textparse/lex.l | 129 - .../prometheus/pkg/textparse/lex.l.go | 471 +- .../prometheus/pkg/textparse/parse.go | 387 +- .../prometheus/pkg/textparse/parse_test.go | 403 - .../pkg/textparse/testdata.nometa.txt | 410 - .../prometheus/pkg/textparse/testdata.txt | 528 - .../prometheus/prometheus/prompb/remote.pb.go | 114 +- .../prometheus/prometheus/prompb/remote.proto | 43 - .../prometheus/prometheus/prompb/rpc.pb.go | 43 +- .../prometheus/prometheus/prompb/rpc.pb.gw.go | 8 +- .../prometheus/prometheus/prompb/rpc.proto | 76 - .../prometheus/prometheus/prompb/types.pb.go | 314 +- .../prometheus/prometheus/prompb/types.proto | 51 - .../prometheus/prometheus/promql/ast.go | 40 +- .../prometheus/promql/bench_test.go | 47 - .../prometheus/prometheus/promql/engine.go | 994 +- .../prometheus/promql/engine_test.go | 325 - .../prometheus/prometheus/promql/functions.go | 724 +- .../prometheus/promql/functions_test.go | 119 - .../prometheus/prometheus/promql/lex.go | 32 +- .../prometheus/prometheus/promql/lex_test.go | 488 - .../prometheus/prometheus/promql/parse.go | 28 +- .../prometheus/promql/parse_test.go | 1858 -- .../prometheus/promql/printer_test.go | 163 - .../prometheus/promql/promql_test.go | 37 - .../prometheus/prometheus/promql/quantile.go | 4 +- .../prometheus/prometheus/promql/test.go | 106 +- .../prometheus/prometheus/promql/test_test.go | 40 - .../prometheus/prometheus/promql/value.go | 49 +- .../prometheus/relabel/relabel_test.go | 422 - .../prometheus/prometheus/rules/alerting.go | 2 +- .../prometheus/rules/alerting_test.go | 39 - .../prometheus/prometheus/rules/manager.go | 44 +- .../prometheus/rules/manager_test.go | 323 - .../prometheus/rules/recording_test.go | 84 - .../prometheus/scrape/helpers_test.go | 70 - .../prometheus/prometheus/scrape/manager.go | 1 - .../prometheus/scrape/manager_test.go | 275 - .../prometheus/prometheus/scrape/scrape.go | 204 +- .../prometheus/scrape/scrape_test.go | 1224 - .../prometheus/prometheus/scrape/target.go | 49 +- .../prometheus/scrape/target_test.go | 373 - .../prometheus/prometheus/storage/buffer.go | 26 +- .../prometheus/storage/buffer_test.go | 257 - .../prometheus/prometheus/storage/fanout.go | 16 +- .../prometheus/storage/fanout_test.go | 271 - .../prometheus/storage/interface.go | 3 + .../prometheus/storage/remote/client.go | 6 +- .../prometheus/storage/remote/client_test.go | 83 - .../prometheus/storage/remote/codec.go | 37 +- .../prometheus/storage/remote/codec_test.go | 147 - .../storage/remote/queue_manager.go | 64 +- .../storage/remote/queue_manager_test.go | 301 - .../prometheus/storage/remote/read.go | 4 +- .../prometheus/storage/remote/read_test.go | 327 - .../prometheus/storage/remote/storage.go | 11 +- .../prometheus/storage/tsdb/tsdb.go | 2 +- .../prometheus/template/template_test.go | 289 - .../prometheus/util/httputil/client.go | 187 - .../prometheus/util/httputil/client_test.go | 468 - .../prometheus/util/stats/query_stats.go | 6 - .../prometheus/util/stats/stats_test.go | 61 - .../prometheus/util/strutil/quote_test.go | 125 - .../prometheus/util/strutil/strconv_test.go | 49 - .../prometheus/prometheus/util/yaml/yaml.go | 31 - .../prometheus/prometheus/web/api/v1/api.go | 300 +- .../prometheus/web/api/v1/api_easyjson.go | 7 +- .../prometheus/web/api/v1/api_test.go | 855 - .../prometheus/prometheus/web/api/v2/api.go | 2 +- .../prometheus/web/federate_test.go | 241 - .../prometheus/prometheus/web/ui/README.md | 12 - .../prometheus/prometheus/web/ui/bindata.go | 106 +- .../prometheus/prometheus/web/web.go | 177 +- .../prometheus/prometheus/web/web_test.go | 343 - vendor/github.com/prometheus/tsdb/.gitignore | 1 - vendor/github.com/prometheus/tsdb/.travis.yml | 13 - vendor/github.com/prometheus/tsdb/README.md | 7 - .../github.com/prometheus/tsdb/block_test.go | 74 - .../prometheus/tsdb/chunkenc/chunk_test.go | 201 - .../prometheus/tsdb/compact_test.go | 403 - vendor/github.com/prometheus/tsdb/db_test.go | 978 - .../github.com/prometheus/tsdb/head_test.go | 771 - .../prometheus/tsdb/index/index_test.go | 382 - .../prometheus/tsdb/index/postings_test.go | 556 - .../prometheus/tsdb/labels/labels_test.go | 198 - .../prometheus/tsdb/querier_test.go | 1479 - .../github.com/prometheus/tsdb/repair_test.go | 122 - .../prometheus/tsdb/tombstones_test.go | 123 - vendor/github.com/prometheus/tsdb/wal_test.go | 433 - .../github.com/samuel/go-zookeeper/.gitignore | 1 - .../samuel/go-zookeeper/.travis.yml | 27 - .../github.com/samuel/go-zookeeper/README.md | 11 - .../samuel/go-zookeeper/zk/cluster_test.go | 314 - .../samuel/go-zookeeper/zk/constants_test.go | 24 - .../go-zookeeper/zk/dnshostprovider_test.go | 224 - .../samuel/go-zookeeper/zk/flw_test.go | 330 - .../samuel/go-zookeeper/zk/lock_test.go | 94 - .../samuel/go-zookeeper/zk/structs_test.go | 83 - .../samuel/go-zookeeper/zk/throttle_test.go | 136 - .../samuel/go-zookeeper/zk/util_test.go | 53 - .../samuel/go-zookeeper/zk/zk_test.go | 939 - .../sasha-s/go-deadlock/.travis.yml | 10 - .../github.com/sasha-s/go-deadlock/Readme.md | 117 - .../sasha-s/go-deadlock/deadlock_test.go | 189 - vendor/github.com/sirupsen/logrus/.gitignore | 1 - vendor/github.com/sirupsen/logrus/.travis.yml | 15 - .../github.com/sirupsen/logrus/CHANGELOG.md | 123 - vendor/github.com/sirupsen/logrus/README.md | 513 - .../sirupsen/logrus/alt_exit_test.go | 83 - .../github.com/sirupsen/logrus/appveyor.yml | 14 - .../github.com/sirupsen/logrus/entry_test.go | 115 - .../sirupsen/logrus/example_basic_test.go | 69 - .../sirupsen/logrus/example_hook_test.go | 35 - .../sirupsen/logrus/formatter_bench_test.go | 101 - .../github.com/sirupsen/logrus/hook_test.go | 144 - .../sirupsen/logrus/json_formatter_test.go | 254 - .../sirupsen/logrus/logger_bench_test.go | 61 - .../github.com/sirupsen/logrus/logrus_test.go | 386 - .../sirupsen/logrus/text_formatter_test.go | 179 - vendor/github.com/spf13/pflag/.gitignore | 2 - vendor/github.com/spf13/pflag/.travis.yml | 21 - vendor/github.com/spf13/pflag/README.md | 296 - .../github.com/spf13/pflag/bool_slice_test.go | 215 - vendor/github.com/spf13/pflag/bool_test.go | 179 - vendor/github.com/spf13/pflag/count_test.go | 52 - vendor/github.com/spf13/pflag/example_test.go | 36 - vendor/github.com/spf13/pflag/export_test.go | 29 - vendor/github.com/spf13/pflag/flag_test.go | 1085 - .../github.com/spf13/pflag/golangflag_test.go | 39 - .../github.com/spf13/pflag/int_slice_test.go | 165 - .../github.com/spf13/pflag/ip_slice_test.go | 222 - vendor/github.com/spf13/pflag/ip_test.go | 63 - vendor/github.com/spf13/pflag/ipnet_test.go | 70 - .../spf13/pflag/string_array_test.go | 233 - .../spf13/pflag/string_slice_test.go | 253 - .../github.com/spf13/pflag/uint_slice_test.go | 161 - vendor/github.com/ugorji/go/README.md | 20 - vendor/github.com/ugorji/go/codec/README.md | 148 - .../github.com/ugorji/go/codec/cbor_test.go | 205 - .../github.com/ugorji/go/codec/codec_test.go | 1185 - .../ugorji/go/codec/codecgen_test.go | 24 - .../ugorji/go/codec/fast-path.go.tmpl | 511 - .../ugorji/go/codec/gen-dec-array.go.tmpl | 101 - .../ugorji/go/codec/gen-dec-map.go.tmpl | 58 - .../ugorji/go/codec/gen-helper.go.tmpl | 364 - .../github.com/ugorji/go/codec/helper_test.go | 242 - vendor/github.com/ugorji/go/codec/prebuild.sh | 199 - vendor/github.com/ugorji/go/codec/py_test.go | 30 - .../ugorji/go/codec/test-cbor-goldens.json | 639 - vendor/github.com/ugorji/go/codec/test.py | 120 - vendor/github.com/ugorji/go/codec/tests.sh | 74 - .../github.com/ugorji/go/codec/values_test.go | 203 - vendor/github.com/ugorji/go/msgpack.org.md | 47 - vendor/golang.org/x/crypto/.gitattributes | 10 - vendor/golang.org/x/crypto/.gitignore | 2 - vendor/golang.org/x/crypto/CONTRIBUTING.md | 31 - vendor/golang.org/x/crypto/README.md | 21 - vendor/golang.org/x/crypto/codereview.cfg | 1 - .../golang.org/x/crypto/ssh/benchmark_test.go | 122 - vendor/golang.org/x/crypto/ssh/buffer.go | 97 - vendor/golang.org/x/crypto/ssh/buffer_test.go | 87 - vendor/golang.org/x/crypto/ssh/certs.go | 519 - vendor/golang.org/x/crypto/ssh/certs_test.go | 222 - vendor/golang.org/x/crypto/ssh/channel.go | 633 - vendor/golang.org/x/crypto/ssh/cipher.go | 629 - vendor/golang.org/x/crypto/ssh/cipher_test.go | 129 - vendor/golang.org/x/crypto/ssh/client.go | 257 - vendor/golang.org/x/crypto/ssh/client_auth.go | 486 - .../x/crypto/ssh/client_auth_test.go | 628 - vendor/golang.org/x/crypto/ssh/client_test.go | 81 - vendor/golang.org/x/crypto/ssh/common.go | 373 - vendor/golang.org/x/crypto/ssh/connection.go | 143 - vendor/golang.org/x/crypto/ssh/doc.go | 21 - .../golang.org/x/crypto/ssh/example_test.go | 320 - vendor/golang.org/x/crypto/ssh/handshake.go | 640 - .../golang.org/x/crypto/ssh/handshake_test.go | 559 - vendor/golang.org/x/crypto/ssh/kex.go | 540 - vendor/golang.org/x/crypto/ssh/kex_test.go | 50 - vendor/golang.org/x/crypto/ssh/keys.go | 1031 - vendor/golang.org/x/crypto/ssh/keys_test.go | 500 - vendor/golang.org/x/crypto/ssh/mac.go | 61 - .../golang.org/x/crypto/ssh/mempipe_test.go | 110 - vendor/golang.org/x/crypto/ssh/messages.go | 758 - .../golang.org/x/crypto/ssh/messages_test.go | 288 - vendor/golang.org/x/crypto/ssh/mux.go | 330 - vendor/golang.org/x/crypto/ssh/mux_test.go | 505 - vendor/golang.org/x/crypto/ssh/server.go | 563 - vendor/golang.org/x/crypto/ssh/session.go | 647 - .../golang.org/x/crypto/ssh/session_test.go | 774 - vendor/golang.org/x/crypto/ssh/streamlocal.go | 115 - vendor/golang.org/x/crypto/ssh/tcpip.go | 465 - vendor/golang.org/x/crypto/ssh/tcpip_test.go | 20 - .../x/crypto/ssh/terminal/terminal_test.go | 350 - .../golang.org/x/crypto/ssh/testdata_test.go | 63 - vendor/golang.org/x/crypto/ssh/transport.go | 375 - .../golang.org/x/crypto/ssh/transport_test.go | 109 - vendor/golang.org/x/net/.gitattributes | 10 - vendor/golang.org/x/net/.gitignore | 2 - vendor/golang.org/x/net/CONTRIBUTING.md | 31 - vendor/golang.org/x/net/README.md | 16 - vendor/golang.org/x/net/codereview.cfg | 1 - .../golang.org/x/net/context/context_test.go | 583 - .../x/net/context/ctxhttp/ctxhttp_17_test.go | 29 - .../net/context/ctxhttp/ctxhttp_pre17_test.go | 79 - .../x/net/context/ctxhttp/ctxhttp_test.go | 105 - .../x/net/context/withtimeout_test.go | 31 - vendor/golang.org/x/net/http2/.gitignore | 2 - vendor/golang.org/x/net/http2/Dockerfile | 51 - vendor/golang.org/x/net/http2/Makefile | 3 - vendor/golang.org/x/net/http2/README | 20 - vendor/golang.org/x/net/http2/ciphers_test.go | 309 - .../golang.org/x/net/http2/databuffer_test.go | 157 - vendor/golang.org/x/net/http2/errors_test.go | 24 - vendor/golang.org/x/net/http2/flow_test.go | 53 - vendor/golang.org/x/net/http2/frame_test.go | 1191 - vendor/golang.org/x/net/http2/go18_test.go | 79 - vendor/golang.org/x/net/http2/go19_test.go | 60 - vendor/golang.org/x/net/http2/gotrack_test.go | 33 - .../x/net/http2/hpack/encode_test.go | 386 - .../x/net/http2/hpack/hpack_test.go | 722 - .../x/net/http2/hpack/tables_test.go | 214 - vendor/golang.org/x/net/http2/http2_test.go | 199 - vendor/golang.org/x/net/http2/pipe_test.go | 130 - .../x/net/http2/server_push_test.go | 521 - vendor/golang.org/x/net/http2/server_test.go | 3721 --- .../golang.org/x/net/http2/transport_test.go | 3686 --- .../x/net/http2/writesched_priority_test.go | 541 - .../x/net/http2/writesched_random_test.go | 44 - .../golang.org/x/net/http2/writesched_test.go | 125 - vendor/golang.org/x/net/http2/z_spec_test.go | 356 - vendor/golang.org/x/net/idna/example_test.go | 70 - vendor/golang.org/x/net/idna/idna_test.go | 108 - vendor/golang.org/x/net/idna/punycode_test.go | 198 - .../internal/timeseries/timeseries_test.go | 170 - .../x/net/lex/httplex/httplex_test.go | 119 - .../golang.org/x/net/netutil/listen_test.go | 101 - .../golang.org/x/net/trace/histogram_test.go | 325 - vendor/golang.org/x/net/trace/trace_test.go | 178 - vendor/golang.org/x/oauth2/.travis.yml | 13 - vendor/golang.org/x/oauth2/CONTRIBUTING.md | 31 - vendor/golang.org/x/oauth2/README.md | 77 - vendor/golang.org/x/oauth2/example_test.go | 89 - .../x/oauth2/google/example_test.go | 150 - .../golang.org/x/oauth2/google/google_test.go | 116 - vendor/golang.org/x/oauth2/google/jwt_test.go | 91 - vendor/golang.org/x/oauth2/google/sdk_test.go | 46 - .../x/oauth2/internal/oauth2_test.go | 61 - .../x/oauth2/internal/token_test.go | 104 - .../x/oauth2/internal/transport_test.go | 38 - vendor/golang.org/x/oauth2/jws/jws_test.go | 46 - .../golang.org/x/oauth2/jwt/example_test.go | 33 - vendor/golang.org/x/oauth2/jwt/jwt_test.go | 190 - vendor/golang.org/x/oauth2/oauth2_test.go | 490 - vendor/golang.org/x/oauth2/token_test.go | 72 - vendor/golang.org/x/oauth2/transport_test.go | 108 - vendor/golang.org/x/sync/CONTRIBUTING.md | 26 - vendor/golang.org/x/sync/README.md | 18 - vendor/golang.org/x/sync/codereview.cfg | 1 - .../errgroup/errgroup_example_md5all_test.go | 101 - .../x/sync/errgroup/errgroup_test.go | 176 - vendor/golang.org/x/sys/.gitattributes | 10 - vendor/golang.org/x/sys/.gitignore | 2 - vendor/golang.org/x/sys/CONTRIBUTING.md | 31 - vendor/golang.org/x/sys/README.md | 18 - vendor/golang.org/x/sys/codereview.cfg | 1 - vendor/golang.org/x/sys/unix/.gitignore | 1 - vendor/golang.org/x/sys/unix/README.md | 173 - vendor/golang.org/x/sys/unix/creds_test.go | 136 - .../golang.org/x/sys/unix/dev_darwin_test.go | 49 - .../x/sys/unix/dev_dragonfly_test.go | 48 - .../golang.org/x/sys/unix/dev_linux_test.go | 51 - .../golang.org/x/sys/unix/dev_netbsd_test.go | 50 - .../golang.org/x/sys/unix/dev_openbsd_test.go | 52 - .../golang.org/x/sys/unix/dev_solaris_test.go | 49 - vendor/golang.org/x/sys/unix/export_test.go | 9 - vendor/golang.org/x/sys/unix/mkall.sh | 194 - vendor/golang.org/x/sys/unix/mkerrors.sh | 566 - vendor/golang.org/x/sys/unix/mksyscall.pl | 328 - .../x/sys/unix/mksyscall_solaris.pl | 289 - .../golang.org/x/sys/unix/mksysctl_openbsd.pl | 264 - .../golang.org/x/sys/unix/mksysnum_darwin.pl | 39 - .../x/sys/unix/mksysnum_dragonfly.pl | 50 - .../golang.org/x/sys/unix/mksysnum_freebsd.pl | 50 - .../golang.org/x/sys/unix/mksysnum_netbsd.pl | 58 - .../golang.org/x/sys/unix/mksysnum_openbsd.pl | 50 - .../golang.org/x/sys/unix/mmap_unix_test.go | 35 - vendor/golang.org/x/sys/unix/openbsd_test.go | 113 - .../golang.org/x/sys/unix/syscall_bsd_test.go | 62 - .../x/sys/unix/syscall_freebsd_test.go | 297 - .../x/sys/unix/syscall_linux_test.go | 234 - .../x/sys/unix/syscall_solaris_test.go | 34 - vendor/golang.org/x/sys/unix/syscall_test.go | 50 - .../x/sys/unix/syscall_unix_test.go | 345 - .../x/sys/windows/registry/export_test.go | 11 - .../x/sys/windows/registry/registry_test.go | 756 - vendor/golang.org/x/sys/windows/svc/event.go | 48 - .../x/sys/windows/svc/eventlog/log_test.go | 51 - vendor/golang.org/x/sys/windows/svc/go12.c | 24 - vendor/golang.org/x/sys/windows/svc/go12.go | 11 - vendor/golang.org/x/sys/windows/svc/go13.go | 31 - .../golang.org/x/sys/windows/svc/security.go | 62 - .../golang.org/x/sys/windows/svc/service.go | 363 - .../golang.org/x/sys/windows/svc/svc_test.go | 118 - vendor/golang.org/x/sys/windows/svc/sys_386.s | 68 - .../golang.org/x/sys/windows/svc/sys_amd64.s | 42 - .../golang.org/x/sys/windows/syscall_test.go | 33 - .../x/sys/windows/syscall_windows_test.go | 107 - vendor/golang.org/x/text/.gitattributes | 10 - vendor/golang.org/x/text/.gitignore | 6 - vendor/golang.org/x/text/CONTRIBUTING.md | 31 - vendor/golang.org/x/text/README.md | 91 - vendor/golang.org/x/text/codereview.cfg | 1 - .../x/text/collate/build/builder_test.go | 290 - .../x/text/collate/build/colelem_test.go | 215 - .../x/text/collate/build/contract_test.go | 266 - .../x/text/collate/build/order_test.go | 229 - .../x/text/collate/build/trie_test.go | 107 - .../golang.org/x/text/collate/collate_test.go | 482 - .../golang.org/x/text/collate/export_test.go | 51 - .../golang.org/x/text/collate/option_test.go | 209 - vendor/golang.org/x/text/collate/reg_test.go | 230 - vendor/golang.org/x/text/collate/sort_test.go | 55 - .../golang.org/x/text/collate/table_test.go | 291 - vendor/golang.org/x/text/doc.go | 13 - vendor/golang.org/x/text/gen.go | 318 - .../x/text/internal/colltab/collate_test.go | 121 - .../x/text/internal/colltab/collelem_test.go | 183 - .../x/text/internal/colltab/colltab_test.go | 64 - .../x/text/internal/colltab/contract_test.go | 131 - .../x/text/internal/colltab/iter_test.go | 63 - .../x/text/internal/colltab/numeric_test.go | 159 - .../x/text/internal/colltab/trie_test.go | 106 - .../x/text/internal/colltab/weighter_test.go | 42 - vendor/golang.org/x/text/internal/gen.go | 52 - vendor/golang.org/x/text/internal/gen_test.go | 38 - vendor/golang.org/x/text/internal/internal.go | 51 - .../x/text/internal/internal_test.go | 38 - vendor/golang.org/x/text/internal/match.go | 67 - .../golang.org/x/text/internal/match_test.go | 56 - vendor/golang.org/x/text/internal/tables.go | 117 - .../x/text/internal/tag/tag_test.go | 67 - .../x/text/internal/triegen/data_test.go | 875 - .../internal/triegen/example_compact_test.go | 71 - .../x/text/internal/triegen/example_test.go | 148 - .../x/text/internal/triegen/gen_test.go | 68 - .../x/text/internal/ucd/example_test.go | 81 - .../x/text/internal/ucd/ucd_test.go | 105 - vendor/golang.org/x/text/language/Makefile | 16 - .../x/text/language/coverage_test.go | 154 - .../x/text/language/examples_test.go | 413 - .../x/text/language/httpexample_test.go | 48 - .../x/text/language/language_test.go | 878 - .../golang.org/x/text/language/lookup_test.go | 457 - .../golang.org/x/text/language/match_test.go | 505 - .../golang.org/x/text/language/parse_test.go | 517 - .../x/text/secure/bidirule/bench_test.go | 54 - .../x/text/secure/bidirule/bidirule_test.go | 851 - vendor/golang.org/x/text/secure/doc.go | 6 - .../x/text/transform/examples_test.go | 37 - .../x/text/transform/transform_test.go | 1317 - .../x/text/unicode/bidi/core_test.go | 224 - .../x/text/unicode/bidi/ranges_test.go | 53 - .../x/text/unicode/bidi/tables_test.go | 82 - .../x/text/unicode/cldr/cldr_test.go | 27 - .../x/text/unicode/cldr/collate_test.go | 275 - .../x/text/unicode/cldr/data_test.go | 186 - .../x/text/unicode/cldr/examples_test.go | 21 - .../x/text/unicode/cldr/resolve_test.go | 368 - .../x/text/unicode/cldr/slice_test.go | 175 - vendor/golang.org/x/text/unicode/doc.go | 8 - .../x/text/unicode/norm/composition_test.go | 130 - .../x/text/unicode/norm/example_iter_test.go | 82 - .../x/text/unicode/norm/example_test.go | 27 - .../x/text/unicode/norm/forminfo_test.go | 54 - .../x/text/unicode/norm/iter_test.go | 98 - .../x/text/unicode/norm/norm_test.go | 14 - .../x/text/unicode/norm/normalize_test.go | 1287 - .../x/text/unicode/norm/readwriter_test.go | 56 - .../x/text/unicode/norm/transform_test.go | 101 - .../x/text/unicode/norm/ucd_test.go | 275 - .../x/text/unicode/rangetable/merge_test.go | 184 - .../unicode/rangetable/rangetable_test.go | 55 - vendor/golang.org/x/text/width/common_test.go | 92 - .../golang.org/x/text/width/example_test.go | 52 - vendor/golang.org/x/text/width/runes_test.go | 461 - vendor/golang.org/x/text/width/tables_test.go | 59 - .../golang.org/x/text/width/transform_test.go | 701 - vendor/golang.org/x/time/CONTRIBUTING.md | 31 - vendor/golang.org/x/time/README.md | 17 - vendor/golang.org/x/time/rate/rate_test.go | 449 - vendor/google.golang.org/api/.gitignore | 12 - vendor/google.golang.org/api/.hgtags | 1 - vendor/google.golang.org/api/.travis.yml | 17 - vendor/google.golang.org/api/CONTRIBUTING.md | 484 - .../google.golang.org/api/GettingStarted.md | 130 - vendor/google.golang.org/api/NOTES | 13 - vendor/google.golang.org/api/README.md | 108 - vendor/google.golang.org/api/TODO | 2 - vendor/google.golang.org/api/api-list.json | 2909 -- .../api/compute/v1/compute-api.json | 27209 ---------------- .../api/gensupport/backoff_test.go | 46 - .../api/gensupport/buffer_test.go | 296 - .../api/gensupport/header_test.go | 28 - .../api/gensupport/json_test.go | 516 - .../api/gensupport/jsonfloat_test.go | 53 - .../api/gensupport/media_test.go | 338 - .../api/gensupport/resumable_test.go | 281 - .../api/gensupport/retry_test.go | 176 - .../api/gensupport/send_test.go | 20 - .../api/gensupport/util_test.go | 57 - .../api/googleapi/googleapi_test.go | 291 - .../uritemplates/uritemplates_test.go | 280 - .../api/googleapi/types_test.go | 68 - vendor/google.golang.org/api/key.json.enc | Bin 2432 -> 0 bytes .../google.golang.org/appengine/.travis.yml | 18 - vendor/google.golang.org/appengine/README.md | 73 - .../appengine/appengine_test.go | 49 - .../appengine/internal/api_race_test.go | 9 - .../appengine/internal/api_test.go | 467 - .../appengine/internal/app_id_test.go | 34 - .../app_identity/app_identity_service.proto | 64 - .../appengine/internal/base/api_base.proto | 33 - .../internal/datastore/datastore_v3.proto | 541 - .../appengine/internal/internal_vm_test.go | 60 - .../appengine/internal/log/log_service.proto | 150 - .../internal/modules/modules_service.proto | 80 - .../appengine/internal/net_test.go | 58 - .../appengine/internal/regen.sh | 40 - .../internal/remote_api/remote_api.proto | 44 - .../internal/urlfetch/urlfetch_service.proto | 64 - .../appengine/namespace_test.go | 39 - vendor/google.golang.org/genproto/.travis.yml | 12 - .../genproto/CONTRIBUTING.md | 27 - vendor/google.golang.org/genproto/README.md | 28 - .../googleapis/api/authorization_config.pb.go | 80 - .../googleapis/api/experimental.pb.go | 56 - vendor/google.golang.org/genproto/regen.go | 123 - vendor/google.golang.org/genproto/regen.sh | 77 - vendor/google.golang.org/grpc/.travis.yml | 24 - vendor/google.golang.org/grpc/CONTRIBUTING.md | 32 - vendor/google.golang.org/grpc/Makefile | 45 - vendor/google.golang.org/grpc/README.md | 45 - vendor/google.golang.org/grpc/backoff_test.go | 29 - .../balancer/roundrobin/roundrobin_test.go | 477 - .../grpc/balancer_switching_test.go | 443 - .../google.golang.org/grpc/balancer_test.go | 804 - vendor/google.golang.org/grpc/call_test.go | 292 - .../google.golang.org/grpc/clientconn_test.go | 646 - vendor/google.golang.org/grpc/codec_test.go | 32 - vendor/google.golang.org/grpc/codegen.sh | 17 - .../grpc/codes/codes_test.go | 64 - .../grpc/credentials/credentials_test.go | 206 - .../encoding/proto/proto_benchmark_test.go | 100 - .../grpc/encoding/proto/proto_test.go | 129 - .../grpclb/grpc_lb_v1/messages/messages.proto | 155 - .../grpc/grpclb/grpclb_test.go | 975 - .../grpc/grpclog/loggerv2_test.go | 62 - .../grpc/metadata/metadata_test.go | 167 - .../grpc/naming/dns_resolver_test.go | 315 - .../grpc/naming/go17_test.go | 42 - .../grpc/naming/go18_test.go | 41 - .../grpc/picker_wrapper_test.go | 160 - .../google.golang.org/grpc/pickfirst_test.go | 360 - vendor/google.golang.org/grpc/proxy_test.go | 182 - .../grpc/resolver/dns/dns_resolver_test.go | 894 - .../grpc/resolver/dns/go17_test.go | 50 - .../grpc/resolver/dns/go18_test.go | 49 - .../grpc/resolver_conn_wrapper_test.go | 113 - .../google.golang.org/grpc/rpc_util_test.go | 286 - vendor/google.golang.org/grpc/server_test.go | 136 - .../grpc/service_config_test.go | 386 - .../grpc/stats/stats_test.go | 1257 - .../grpc/status/status_test.go | 331 - .../grpc/transport/handler_server_test.go | 482 - .../grpc/transport/http_util_test.go | 176 - .../grpc/transport/transport_test.go | 2269 -- vendor/google.golang.org/grpc/vet.sh | 84 - .../alecthomas/kingpin.v2/.travis.yml | 4 - .../gopkg.in/alecthomas/kingpin.v2/README.md | 674 - .../alecthomas/kingpin.v2/app_test.go | 404 - .../alecthomas/kingpin.v2/args_test.go | 84 - .../alecthomas/kingpin.v2/cmd_test.go | 374 - .../alecthomas/kingpin.v2/completions_test.go | 78 - .../alecthomas/kingpin.v2/examples_test.go | 46 - .../alecthomas/kingpin.v2/flags_test.go | 368 - .../alecthomas/kingpin.v2/parser_test.go | 122 - .../alecthomas/kingpin.v2/parsers_test.go | 98 - .../alecthomas/kingpin.v2/usage_test.go | 65 - .../alecthomas/kingpin.v2/values.json | 25 - .../alecthomas/kingpin.v2/values_test.go | 98 - vendor/gopkg.in/fsnotify.v1/.editorconfig | 5 - vendor/gopkg.in/fsnotify.v1/.gitignore | 6 - vendor/gopkg.in/fsnotify.v1/.travis.yml | 30 - vendor/gopkg.in/fsnotify.v1/CHANGELOG.md | 317 - vendor/gopkg.in/fsnotify.v1/CONTRIBUTING.md | 77 - vendor/gopkg.in/fsnotify.v1/README.md | 79 - vendor/gopkg.in/fsnotify.v1/example_test.go | 42 - vendor/gopkg.in/fsnotify.v1/fsnotify_test.go | 70 - .../fsnotify.v1/inotify_poller_test.go | 229 - vendor/gopkg.in/fsnotify.v1/inotify_test.go | 449 - .../fsnotify.v1/integration_darwin_test.go | 147 - .../gopkg.in/fsnotify.v1/integration_test.go | 1237 - .../{ => fsnotify}/fsnotify.v1/AUTHORS | 0 .../{ => fsnotify}/fsnotify.v1/LICENSE | 0 .../{ => fsnotify}/fsnotify.v1/fen.go | 0 .../{ => fsnotify}/fsnotify.v1/fsnotify.go | 0 .../{ => fsnotify}/fsnotify.v1/inotify.go | 0 .../fsnotify.v1/inotify_poller.go | 0 .../{ => fsnotify}/fsnotify.v1/kqueue.go | 0 .../fsnotify.v1/open_mode_bsd.go | 0 .../fsnotify.v1/open_mode_darwin.go | 0 .../{ => fsnotify}/fsnotify.v1/windows.go | 0 vendor/gopkg.in/inf.v0/benchmark_test.go | 210 - vendor/gopkg.in/inf.v0/dec_go1_2_test.go | 33 - vendor/gopkg.in/inf.v0/dec_internal_test.go | 40 - vendor/gopkg.in/inf.v0/dec_test.go | 379 - vendor/gopkg.in/inf.v0/example_test.go | 62 - .../gopkg.in/inf.v0/rounder_example_test.go | 72 - vendor/gopkg.in/inf.v0/rounder_test.go | 109 - vendor/gopkg.in/yaml.v2/.travis.yml | 9 - vendor/gopkg.in/yaml.v2/README.md | 133 - vendor/gopkg.in/yaml.v2/decode_test.go | 1017 - vendor/gopkg.in/yaml.v2/encode_test.go | 501 - .../gopkg.in/yaml.v2/example_embedded_test.go | 41 - vendor/gopkg.in/yaml.v2/suite_test.go | 12 - vendor/k8s.io/apimachinery/README.md | 29 - vendor/k8s.io/apimachinery/kubernetes-sha | 1 - vendor/k8s.io/apimachinery/pkg/OWNERS | 6 - .../k8s.io/apimachinery/pkg/api/errors/OWNERS | 27 - .../pkg/api/errors/errors_test.go | 196 - .../k8s.io/apimachinery/pkg/api/meta/OWNERS | 26 - .../pkg/api/meta/multirestmapper_test.go | 359 - .../pkg/api/meta/priority_test.go | 346 - .../pkg/api/meta/restmapper_test.go | 751 - .../apimachinery/pkg/api/resource/OWNERS | 17 - .../pkg/api/resource/amount_test.go | 111 - .../pkg/api/resource/generated.proto | 94 - .../pkg/api/resource/math_test.go | 211 - .../pkg/api/resource/quantity_example_test.go | 59 - .../pkg/api/resource/quantity_test.go | 1330 - .../pkg/api/resource/scale_int_test.go | 85 - .../apimachinery/announced/announced_test.go | 66 - .../registered/registered_test.go | 148 - .../pkg/apimachinery/types_test.go | 43 - .../apimachinery/pkg/apis/meta/v1/OWNERS | 33 - .../pkg/apis/meta/v1/duration_test.go | 153 - .../pkg/apis/meta/v1/generated.proto | 689 - .../pkg/apis/meta/v1/group_version_test.go | 78 - .../pkg/apis/meta/v1/helpers_test.go | 154 - .../pkg/apis/meta/v1/labels_test.go | 120 - .../pkg/apis/meta/v1/time_test.go | 173 - .../pkg/apis/meta/v1/types_test.go | 134 - .../meta/v1/unstructured/unstructured_test.go | 36 - .../k8s.io/apimachinery/pkg/conversion/OWNERS | 10 - .../pkg/conversion/converter_test.go | 826 - .../pkg/conversion/deep_copy_test.go | 161 - .../conversion/queryparams/convert_test.go | 212 - .../apimachinery/pkg/fields/fields_test.go | 57 - .../apimachinery/pkg/fields/selector_test.go | 327 - .../apimachinery/pkg/labels/labels_test.go | 231 - .../apimachinery/pkg/labels/selector_test.go | 575 - vendor/k8s.io/apimachinery/pkg/runtime/OWNERS | 19 - .../pkg/runtime/conversion_test.go | 135 - .../apimachinery/pkg/runtime/embedded_test.go | 290 - .../pkg/runtime/extension_test.go | 39 - .../apimachinery/pkg/runtime/generated.proto | 128 - .../pkg/runtime/schema/generated.proto | 28 - .../pkg/runtime/schema/group_version_test.go | 136 - .../apimachinery/pkg/runtime/scheme_test.go | 998 - .../pkg/runtime/serializer/codec_test.go | 426 - .../pkg/runtime/serializer/json/json_test.go | 264 - .../pkg/runtime/serializer/json/meta_test.go | 45 - .../serializer/streaming/streaming_test.go | 84 - .../serializer/versioning/versioning_test.go | 399 - .../pkg/runtime/swagger_doc_generator_test.go | 43 - .../apimachinery/pkg/util/diff/diff_test.go | 88 - .../pkg/util/errors/errors_test.go | 326 - .../pkg/util/framer/framer_test.go | 176 - .../pkg/util/intstr/generated.proto | 43 - .../pkg/util/intstr/intstr_test.go | 176 - .../apimachinery/pkg/util/json/json_test.go | 317 - .../apimachinery/pkg/util/net/http_test.go | 246 - .../pkg/util/net/interface_test.go | 300 - .../pkg/util/net/port_range_test.go | 69 - .../pkg/util/net/port_split_test.go | 121 - .../apimachinery/pkg/util/net/util_test.go | 68 - .../apimachinery/pkg/util/rand/rand_test.go | 101 - .../pkg/util/runtime/runtime_test.go | 71 - .../apimachinery/pkg/util/sets/set_test.go | 270 - .../pkg/util/validation/field/errors_test.go | 167 - .../pkg/util/validation/field/path_test.go | 123 - .../pkg/util/validation/validation_test.go | 436 - .../apimachinery/pkg/util/wait/wait_test.go | 501 - .../pkg/util/yaml/decoder_test.go | 349 - .../apimachinery/pkg/watch/filter_test.go | 84 - .../k8s.io/apimachinery/pkg/watch/mux_test.go | 168 - .../pkg/watch/streamwatcher_test.go | 68 - .../apimachinery/pkg/watch/watch_test.go | 135 - .../forked/golang/reflect/deep_equal_test.go | 137 - vendor/k8s.io/client-go/.travis.yml | 8 - vendor/k8s.io/client-go/CHANGELOG.md | 31 - vendor/k8s.io/client-go/INSTALL.md | 157 - vendor/k8s.io/client-go/OWNERS | 44 - vendor/k8s.io/client-go/README.md | 144 - .../discovery/discovery_client_test.go | 740 - .../discovery/helper_blackbox_test.go | 231 - .../client-go/discovery/restmapper_test.go | 349 - .../extensions/v1beta1/thirdpartyresource.go | 68 + vendor/k8s.io/client-go/kubernetes-sha | 1 - .../v1beta1/fake/fake_thirdpartyresource.go | 110 + .../extensions/v1beta1/thirdpartyresource.go | 68 + vendor/k8s.io/client-go/pkg/api/OWNERS | 44 - .../k8s.io/client-go/pkg/api/install/OWNERS | 11 - vendor/k8s.io/client-go/pkg/api/v1/OWNERS | 41 - .../client-go/pkg/api/v1/generated.proto | 3922 --- vendor/k8s.io/client-go/pkg/apis/apps/OWNERS | 21 - .../pkg/apis/apps/v1beta1/generated.proto | 342 - .../client-go/pkg/apis/authentication/OWNERS | 9 - .../apis/authentication/v1/generated.proto | 100 - .../authentication/v1beta1/generated.proto | 101 - .../client-go/pkg/apis/authorization/OWNERS | 17 - .../pkg/apis/authorization/v1/generated.proto | 185 - .../authorization/v1beta1/generated.proto | 185 - .../client-go/pkg/apis/autoscaling/OWNERS | 20 - .../pkg/apis/autoscaling/v1/generated.proto | 298 - .../apis/autoscaling/v2alpha1/generated.proto | 275 - vendor/k8s.io/client-go/pkg/apis/batch/OWNERS | 19 - .../pkg/apis/batch/v1/generated.proto | 168 - .../pkg/apis/batch/v2alpha1/generated.proto | 135 - .../client-go/pkg/apis/certificates/OWNERS | 14 - .../apis/certificates/v1beta1/generated.proto | 124 - .../client-go/pkg/apis/extensions/OWNERS | 41 - .../apis/extensions/v1beta1/generated.proto | 1005 - .../k8s.io/client-go/pkg/apis/policy/OWNERS | 14 - .../pkg/apis/policy/v1beta1/generated.proto | 109 - vendor/k8s.io/client-go/pkg/apis/rbac/OWNERS | 17 - .../pkg/apis/rbac/v1alpha1/generated.proto | 202 - .../pkg/apis/rbac/v1beta1/generated.proto | 200 - .../apis/settings/v1alpha1/generated.proto | 76 - .../k8s.io/client-go/pkg/apis/storage/OWNERS | 3 - .../pkg/apis/storage/v1/generated.proto | 63 - .../pkg/apis/storage/v1beta1/generated.proto | 64 - .../client-go/pkg/version/.gitattributes | 1 - vendor/k8s.io/client-go/rest/OWNERS | 24 - vendor/k8s.io/client-go/rest/client_test.go | 342 - vendor/k8s.io/client-go/rest/config_test.go | 272 - vendor/k8s.io/client-go/rest/plugin_test.go | 311 - vendor/k8s.io/client-go/rest/request_test.go | 1733 - .../k8s.io/client-go/rest/url_utils_test.go | 61 - .../k8s.io/client-go/rest/urlbackoff_test.go | 79 - .../client-go/rest/watch/decoder_test.go | 117 - .../client-go/rest/watch/encoder_test.go | 82 - vendor/k8s.io/client-go/tools/cache/OWNERS | 41 - .../client-go/tools/cache/controller_test.go | 405 - .../client-go/tools/cache/delta_fifo_test.go | 533 - .../tools/cache/expiration_cache_test.go | 189 - .../k8s.io/client-go/tools/cache/fifo_test.go | 280 - .../client-go/tools/cache/index_test.go | 137 - .../tools/cache/mutation_detector_test.go | 81 - .../tools/cache/processor_listener_test.go | 48 - .../client-go/tools/cache/reflector_test.go | 389 - .../tools/cache/shared_informer_test.go | 253 - .../client-go/tools/cache/store_test.go | 156 - .../tools/cache/undelta_store_test.go | 131 - .../tools/clientcmd/api/helpers_test.go | 301 - .../tools/clientcmd/api/types_test.go | 135 - .../client-go/tools/clientcmd/auth_loaders.go | 106 - .../tools/clientcmd/client_config.go | 537 - .../tools/clientcmd/client_config_test.go | 506 - .../client-go/tools/clientcmd/config.go | 472 - .../k8s.io/client-go/tools/clientcmd/doc.go | 37 - .../client-go/tools/clientcmd/helpers.go | 35 - .../client-go/tools/clientcmd/loader.go | 609 - .../client-go/tools/clientcmd/loader_test.go | 579 - .../tools/clientcmd/merged_client_builder.go | 169 - .../clientcmd/merged_client_builder_test.go | 328 - .../client-go/tools/clientcmd/overrides.go | 214 - .../client-go/tools/clientcmd/validation.go | 270 - .../tools/clientcmd/validation_test.go | 432 - vendor/k8s.io/client-go/tools/metrics/OWNERS | 7 - vendor/k8s.io/client-go/transport/OWNERS | 7 - .../k8s.io/client-go/transport/cache_test.go | 114 - .../transport/round_trippers_test.go | 218 - .../client-go/transport/transport_test.go | 204 - vendor/k8s.io/client-go/util/cert/csr_test.go | 75 - .../k8s.io/client-go/util/clock/clock_test.go | 184 - .../util/flowcontrol/backoff_test.go | 195 - .../util/flowcontrol/throttle_test.go | 177 - .../client-go/util/integer/integer_test.go | 244 - .../util/workqueue/default_rate_limiters.go | 211 + .../util/workqueue/delaying_queue.go | 246 + .../util/workqueue/doc.go} | 32 +- .../client-go/util/workqueue/metrics.go | 195 + .../client-go/util/workqueue/parallelizer.go | 52 + .../k8s.io/client-go/util/workqueue/queue.go | 172 + .../util/workqueue/rate_limitting_queue.go | 69 + .../client-go/util/workqueue/timed_queue.go | 52 + 1641 files changed, 19776 insertions(+), 331864 deletions(-) delete mode 100644 vendor/cloud.google.com/go/.travis.yml delete mode 100644 vendor/cloud.google.com/go/CONTRIBUTING.md delete mode 100644 vendor/cloud.google.com/go/MIGRATION.md delete mode 100644 vendor/cloud.google.com/go/README.md delete mode 100644 vendor/cloud.google.com/go/appveyor.yml delete mode 100644 vendor/cloud.google.com/go/authexample_test.go delete mode 100644 vendor/cloud.google.com/go/cloud.go delete mode 100644 vendor/cloud.google.com/go/compute/metadata/metadata_test.go delete mode 100644 vendor/cloud.google.com/go/key.json.enc delete mode 100644 vendor/cloud.google.com/go/license_test.go delete mode 100644 vendor/cloud.google.com/go/old-news.md delete mode 100755 vendor/cloud.google.com/go/run-tests.sh delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/.gitignore delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/.travis.yml delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/CHANGELOG.md delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/README.md delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/arm/README.md delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/glide.lock delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/glide.yaml delete mode 100644 vendor/github.com/Azure/go-autorest/.gitignore delete mode 100644 vendor/github.com/Azure/go-autorest/.travis.yml delete mode 100644 vendor/github.com/Azure/go-autorest/CHANGELOG.md delete mode 100644 vendor/github.com/Azure/go-autorest/README.md delete mode 100644 vendor/github.com/Azure/go-autorest/autorest/autorest_test.go delete mode 100644 vendor/github.com/Azure/go-autorest/autorest/azure/async_test.go delete mode 100644 vendor/github.com/Azure/go-autorest/autorest/azure/azure_test.go delete mode 100644 vendor/github.com/Azure/go-autorest/autorest/azure/devicetoken_test.go delete mode 100644 vendor/github.com/Azure/go-autorest/autorest/azure/environments_test.go delete mode 100644 vendor/github.com/Azure/go-autorest/autorest/azure/persist_test.go delete mode 100644 vendor/github.com/Azure/go-autorest/autorest/azure/token_test.go delete mode 100644 vendor/github.com/Azure/go-autorest/autorest/client_test.go delete mode 100644 vendor/github.com/Azure/go-autorest/autorest/date/date_test.go delete mode 100644 vendor/github.com/Azure/go-autorest/autorest/date/time_test.go delete mode 100644 vendor/github.com/Azure/go-autorest/autorest/date/timerfc1123_test.go delete mode 100644 vendor/github.com/Azure/go-autorest/autorest/error_test.go delete mode 100644 vendor/github.com/Azure/go-autorest/autorest/preparer_test.go delete mode 100644 vendor/github.com/Azure/go-autorest/autorest/responder_test.go delete mode 100644 vendor/github.com/Azure/go-autorest/autorest/sender_test.go delete mode 100644 vendor/github.com/Azure/go-autorest/autorest/to/convert_test.go delete mode 100644 vendor/github.com/Azure/go-autorest/autorest/utility_test.go delete mode 100644 vendor/github.com/Azure/go-autorest/autorest/validation/validation_test.go delete mode 100644 vendor/github.com/Azure/go-autorest/autorest/version_test.go delete mode 100644 vendor/github.com/Azure/go-autorest/glide.lock delete mode 100644 vendor/github.com/Azure/go-autorest/glide.yaml delete mode 100644 vendor/github.com/PuerkitoBio/purell/.gitignore delete mode 100644 vendor/github.com/PuerkitoBio/purell/.travis.yml delete mode 100644 vendor/github.com/PuerkitoBio/purell/README.md delete mode 100644 vendor/github.com/PuerkitoBio/purell/bench_test.go delete mode 100644 vendor/github.com/PuerkitoBio/purell/example_test.go delete mode 100644 vendor/github.com/PuerkitoBio/purell/purell_test.go delete mode 100644 vendor/github.com/PuerkitoBio/purell/urlnorm_test.go delete mode 100644 vendor/github.com/PuerkitoBio/urlesc/.travis.yml delete mode 100644 vendor/github.com/PuerkitoBio/urlesc/README.md delete mode 100644 vendor/github.com/PuerkitoBio/urlesc/urlesc_test.go delete mode 100644 vendor/github.com/alecthomas/template/README.md delete mode 100644 vendor/github.com/alecthomas/template/example_test.go delete mode 100644 vendor/github.com/alecthomas/template/examplefiles_test.go delete mode 100644 vendor/github.com/alecthomas/template/examplefunc_test.go delete mode 100644 vendor/github.com/alecthomas/template/exec_test.go delete mode 100644 vendor/github.com/alecthomas/template/multi_test.go delete mode 100644 vendor/github.com/alecthomas/template/parse/lex_test.go delete mode 100644 vendor/github.com/alecthomas/template/parse/parse_test.go delete mode 100644 vendor/github.com/alecthomas/units/README.md delete mode 100644 vendor/github.com/alecthomas/units/bytes_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/.gitignore delete mode 100644 vendor/github.com/aws/aws-sdk-go/.godoc_config delete mode 100644 vendor/github.com/aws/aws-sdk-go/.travis.yml delete mode 100644 vendor/github.com/aws/aws-sdk-go/CHANGELOG.md delete mode 100644 vendor/github.com/aws/aws-sdk-go/CHANGELOG_PENDING.md delete mode 100644 vendor/github.com/aws/aws-sdk-go/CONTRIBUTING.md delete mode 100644 vendor/github.com/aws/aws-sdk-go/Gopkg.lock delete mode 100644 vendor/github.com/aws/aws-sdk-go/Gopkg.toml delete mode 100644 vendor/github.com/aws/aws-sdk-go/Makefile delete mode 100644 vendor/github.com/aws/aws-sdk-go/README.md delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/awsutil/copy_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/awsutil/equal_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/awsutil/path_value_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/client/client_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/client/logger_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/config_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/context_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/convert_types_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/corehandlers/handlers_1_8_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/corehandlers/handlers_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/corehandlers/param_validator_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/credentials/chain_provider_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/credentials/credentials_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds/ec2_role_provider_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/credentials/endpointcreds/provider_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/credentials/env_provider_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/credentials/example.ini delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/credentials/shared_credentials_provider_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/credentials/static_provider_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/credentials/stscreds/assume_role_provider_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/defaults/defaults_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/api_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/service_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/endpoints/decode_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/endpoints/endpoints_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/endpoints/example_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/endpoints/v3model_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/request/connection_reset_error_other_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/request/connection_reset_error_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/request/handlers_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/request/http_request_copy_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/request/http_request_retry_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/request/offset_reader_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/request/request_1_5_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/request/request_1_6_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/request/request_1_7_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/request/request_1_8_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/request/request_context_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/request/request_internal_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/request/request_pagination_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/request/request_resetbody_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/request/request_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/request/retryer_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/request/timeout_read_closer_benchmark_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/request/timeout_read_closer_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/request/waiter_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/session/custom_ca_bundle_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/session/env_config_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/session/session_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/session/shared_config_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/signer/v4/functional_1_5_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/signer/v4/functional_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/signer/v4/header_rules_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/signer/v4/v4_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/types_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/buildspec.yml delete mode 100644 vendor/github.com/aws/aws-sdk-go/doc.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/internal/shareddefaults/shared_config_other_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/internal/shareddefaults/shared_config_windows_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/private/README.md delete mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/ec2query/build_bench_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/ec2query/build_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/ec2query/unmarshal_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/idempotency_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/protocol_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/query/build_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/query/unmarshal_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/rest/build_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/rest/rest_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/unmarshal_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/unmarshal_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/xml_to_struct_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/service/ec2/customizations_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/service/ec2/examples_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/service/generate.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/service/sts/customizations_test.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/service/sts/examples_test.go delete mode 100644 vendor/github.com/beorn7/perks/.gitignore delete mode 100644 vendor/github.com/beorn7/perks/README.md delete mode 100644 vendor/github.com/beorn7/perks/quantile/bench_test.go delete mode 100644 vendor/github.com/beorn7/perks/quantile/example_test.go delete mode 100644 vendor/github.com/beorn7/perks/quantile/exampledata.txt delete mode 100644 vendor/github.com/beorn7/perks/quantile/stream_test.go delete mode 100644 vendor/github.com/cespare/xxhash/README.md delete mode 100644 vendor/github.com/cespare/xxhash/xxhash_amd64_test.go delete mode 100644 vendor/github.com/cespare/xxhash/xxhash_test.go delete mode 100644 vendor/github.com/cockroachdb/cmux/.gitignore delete mode 100644 vendor/github.com/cockroachdb/cmux/.travis.yml delete mode 100644 vendor/github.com/cockroachdb/cmux/README.md delete mode 100644 vendor/github.com/cockroachdb/cmux/bench_test.go delete mode 100644 vendor/github.com/cockroachdb/cmux/cmux_test.go delete mode 100644 vendor/github.com/cockroachdb/cmux/example_recursive_test.go delete mode 100644 vendor/github.com/cockroachdb/cmux/example_test.go delete mode 100644 vendor/github.com/cockroachdb/cmux/example_tls_test.go delete mode 100644 vendor/github.com/cockroachdb/cmux/patricia_test.go delete mode 100644 vendor/github.com/cockroachdb/cockroach/.codacy.yml delete mode 100644 vendor/github.com/cockroachdb/cockroach/.editorconfig delete mode 100644 vendor/github.com/cockroachdb/cockroach/.gitattributes delete mode 100644 vendor/github.com/cockroachdb/cockroach/.gitignore delete mode 100644 vendor/github.com/cockroachdb/cockroach/.gitmodules delete mode 100644 vendor/github.com/cockroachdb/cockroach/.go-version delete mode 100644 vendor/github.com/cockroachdb/cockroach/.mailmap delete mode 100644 vendor/github.com/cockroachdb/cockroach/CONTRIBUTING.md delete mode 100644 vendor/github.com/cockroachdb/cockroach/Makefile delete mode 100644 vendor/github.com/cockroachdb/cockroach/README.md delete mode 100644 vendor/github.com/cockroachdb/cockroach/STYLE.md delete mode 100644 vendor/github.com/cockroachdb/cockroach/glide.lock delete mode 100644 vendor/github.com/cockroachdb/cockroach/glide.yaml delete mode 100644 vendor/github.com/cockroachdb/cockroach/main.go delete mode 100644 vendor/github.com/cockroachdb/cockroach/pkg/Makefile create mode 100644 vendor/github.com/cockroachdb/cockroach/pkg/ccl/utilccl/license_check.go delete mode 100644 vendor/github.com/cockroachdb/cockroach/pkg/util/duration.go delete mode 100644 vendor/github.com/cockroachdb/cockroach/pkg/util/duration_test.go delete mode 100644 vendor/github.com/cockroachdb/cockroach/pkg/util/nocopy.go delete mode 100644 vendor/github.com/cockroachdb/cockroach/pkg/util/pluralize.go delete mode 100644 vendor/github.com/cockroachdb/cockroach/pkg/util/protoutil/clone_test.go delete mode 100644 vendor/github.com/cockroachdb/cockroach/pkg/util/reflect.go delete mode 100644 vendor/github.com/cockroachdb/cockroach/pkg/util/retry.go delete mode 100644 vendor/github.com/cockroachdb/cockroach/pkg/util/roundup2.go delete mode 100644 vendor/github.com/cockroachdb/cockroach/pkg/util/smalltrace.go delete mode 100644 vendor/github.com/cockroachdb/cockroach/pkg/util/smalltrace_test.go delete mode 100644 vendor/github.com/cockroachdb/cockroach/pkg/util/syncutil/mutex_sync_test.go delete mode 100644 vendor/github.com/cockroachdb/cockroach/pkg/util/testaddr_default.go delete mode 100644 vendor/github.com/cockroachdb/cockroach/pkg/util/testaddr_random.go delete mode 100644 vendor/github.com/cockroachdb/cockroach/pkg/util/topk.go delete mode 100644 vendor/github.com/cockroachdb/cockroach/pkg/util/topk_test.go delete mode 100644 vendor/github.com/cockroachdb/cockroach/pkg/util/unresolved_addr.go delete mode 100644 vendor/github.com/cockroachdb/cockroach/pkg/util/unresolved_addr.pb.go delete mode 100644 vendor/github.com/cockroachdb/cockroach/pkg/util/unresolved_addr.proto delete mode 100644 vendor/github.com/cockroachdb/cockroach/pkg/util/unresolved_addr_test.go create mode 100755 vendor/github.com/cockroachdb/cockroach/scripts/authors.sh delete mode 100644 vendor/github.com/davecgh/go-spew/.gitignore delete mode 100644 vendor/github.com/davecgh/go-spew/.travis.yml delete mode 100644 vendor/github.com/davecgh/go-spew/README.md delete mode 100644 vendor/github.com/davecgh/go-spew/cov_report.sh delete mode 100644 vendor/github.com/davecgh/go-spew/spew/common_test.go delete mode 100644 vendor/github.com/davecgh/go-spew/spew/dump_test.go delete mode 100644 vendor/github.com/davecgh/go-spew/spew/dumpcgo_test.go delete mode 100644 vendor/github.com/davecgh/go-spew/spew/dumpnocgo_test.go delete mode 100644 vendor/github.com/davecgh/go-spew/spew/example_test.go delete mode 100644 vendor/github.com/davecgh/go-spew/spew/format_test.go delete mode 100644 vendor/github.com/davecgh/go-spew/spew/internal_test.go delete mode 100644 vendor/github.com/davecgh/go-spew/spew/internalunsafe_test.go delete mode 100644 vendor/github.com/davecgh/go-spew/spew/spew_test.go delete mode 100644 vendor/github.com/davecgh/go-spew/test_coverage.txt delete mode 100644 vendor/github.com/dgrijalva/jwt-go/.gitignore delete mode 100644 vendor/github.com/dgrijalva/jwt-go/.travis.yml delete mode 100644 vendor/github.com/dgrijalva/jwt-go/MIGRATION_GUIDE.md delete mode 100644 vendor/github.com/dgrijalva/jwt-go/README.md delete mode 100644 vendor/github.com/dgrijalva/jwt-go/VERSION_HISTORY.md delete mode 100644 vendor/github.com/dgrijalva/jwt-go/ecdsa_test.go delete mode 100644 vendor/github.com/dgrijalva/jwt-go/example_test.go delete mode 100644 vendor/github.com/dgrijalva/jwt-go/hmac_example_test.go delete mode 100644 vendor/github.com/dgrijalva/jwt-go/hmac_test.go delete mode 100644 vendor/github.com/dgrijalva/jwt-go/http_example_test.go delete mode 100644 vendor/github.com/dgrijalva/jwt-go/none_test.go delete mode 100644 vendor/github.com/dgrijalva/jwt-go/parser_test.go delete mode 100644 vendor/github.com/dgrijalva/jwt-go/rsa_pss_test.go delete mode 100644 vendor/github.com/dgrijalva/jwt-go/rsa_test.go delete mode 100644 vendor/github.com/docker/distribution/.gitignore delete mode 100644 vendor/github.com/docker/distribution/.mailmap delete mode 100644 vendor/github.com/docker/distribution/BUILDING.md delete mode 100644 vendor/github.com/docker/distribution/CHANGELOG.md delete mode 100644 vendor/github.com/docker/distribution/CONTRIBUTING.md delete mode 100644 vendor/github.com/docker/distribution/Dockerfile delete mode 100644 vendor/github.com/docker/distribution/MAINTAINERS delete mode 100644 vendor/github.com/docker/distribution/Makefile delete mode 100644 vendor/github.com/docker/distribution/README.md delete mode 100644 vendor/github.com/docker/distribution/RELEASE-CHECKLIST.md delete mode 100644 vendor/github.com/docker/distribution/ROADMAP.md delete mode 100644 vendor/github.com/docker/distribution/blobs.go delete mode 100644 vendor/github.com/docker/distribution/circle.yml delete mode 100755 vendor/github.com/docker/distribution/coverpkg.sh delete mode 100644 vendor/github.com/docker/distribution/digest/digest_test.go delete mode 100644 vendor/github.com/docker/distribution/digest/digester_resumable_test.go delete mode 100644 vendor/github.com/docker/distribution/digest/set_test.go delete mode 100644 vendor/github.com/docker/distribution/digest/verifiers_test.go delete mode 100644 vendor/github.com/docker/distribution/doc.go delete mode 100644 vendor/github.com/docker/distribution/errors.go delete mode 100644 vendor/github.com/docker/distribution/manifests.go delete mode 100644 vendor/github.com/docker/distribution/reference/reference_test.go delete mode 100644 vendor/github.com/docker/distribution/reference/regexp_test.go delete mode 100644 vendor/github.com/docker/distribution/registry.go delete mode 100644 vendor/github.com/docker/distribution/tags.go delete mode 100644 vendor/github.com/emicklei/go-restful/.gitignore delete mode 100644 vendor/github.com/emicklei/go-restful/CHANGES.md delete mode 100644 vendor/github.com/emicklei/go-restful/README.md delete mode 100644 vendor/github.com/emicklei/go-restful/Srcfile delete mode 100644 vendor/github.com/emicklei/go-restful/bench_curly_test.go delete mode 100644 vendor/github.com/emicklei/go-restful/bench_test.go delete mode 100644 vendor/github.com/emicklei/go-restful/bench_test.sh delete mode 100644 vendor/github.com/emicklei/go-restful/compress_test.go delete mode 100644 vendor/github.com/emicklei/go-restful/container_test.go delete mode 100644 vendor/github.com/emicklei/go-restful/cors_filter_test.go delete mode 100644 vendor/github.com/emicklei/go-restful/coverage.sh delete mode 100644 vendor/github.com/emicklei/go-restful/curly_test.go delete mode 100644 vendor/github.com/emicklei/go-restful/doc_examples_test.go delete mode 100644 vendor/github.com/emicklei/go-restful/entity_accessors_test.go delete mode 100644 vendor/github.com/emicklei/go-restful/filter_test.go delete mode 100644 vendor/github.com/emicklei/go-restful/install.sh delete mode 100644 vendor/github.com/emicklei/go-restful/jsr311_test.go delete mode 100644 vendor/github.com/emicklei/go-restful/options_filter_test.go delete mode 100644 vendor/github.com/emicklei/go-restful/path_expression_test.go delete mode 100644 vendor/github.com/emicklei/go-restful/request_test.go delete mode 100644 vendor/github.com/emicklei/go-restful/response_test.go delete mode 100644 vendor/github.com/emicklei/go-restful/route_builder_test.go delete mode 100644 vendor/github.com/emicklei/go-restful/route_test.go delete mode 100644 vendor/github.com/emicklei/go-restful/swagger/CHANGES.md delete mode 100644 vendor/github.com/emicklei/go-restful/swagger/README.md delete mode 100644 vendor/github.com/emicklei/go-restful/swagger/model_builder_test.go delete mode 100644 vendor/github.com/emicklei/go-restful/swagger/model_list_test.go delete mode 100644 vendor/github.com/emicklei/go-restful/swagger/model_property_ext_test.go delete mode 100644 vendor/github.com/emicklei/go-restful/swagger/model_property_list_test.go delete mode 100644 vendor/github.com/emicklei/go-restful/swagger/ordered_route_map_test.go delete mode 100644 vendor/github.com/emicklei/go-restful/swagger/postbuild_model_test.go delete mode 100644 vendor/github.com/emicklei/go-restful/swagger/swagger_test.go delete mode 100644 vendor/github.com/emicklei/go-restful/swagger/utils_test.go delete mode 100644 vendor/github.com/emicklei/go-restful/tracer_test.go delete mode 100644 vendor/github.com/emicklei/go-restful/web_service_test.go delete mode 100644 vendor/github.com/ghodss/yaml/.gitignore delete mode 100644 vendor/github.com/ghodss/yaml/.travis.yml delete mode 100644 vendor/github.com/ghodss/yaml/README.md delete mode 100644 vendor/github.com/ghodss/yaml/yaml_test.go delete mode 100644 vendor/github.com/go-ini/ini/.gitignore delete mode 100644 vendor/github.com/go-ini/ini/.travis.yml delete mode 100644 vendor/github.com/go-ini/ini/Makefile delete mode 100644 vendor/github.com/go-ini/ini/README.md delete mode 100644 vendor/github.com/go-ini/ini/README_ZH.md delete mode 100644 vendor/github.com/go-ini/ini/ini_test.go delete mode 100644 vendor/github.com/go-ini/ini/key_test.go delete mode 100644 vendor/github.com/go-ini/ini/parser_test.go delete mode 100644 vendor/github.com/go-ini/ini/section_test.go delete mode 100644 vendor/github.com/go-ini/ini/struct_test.go delete mode 100644 vendor/github.com/go-kit/kit/.gitignore delete mode 100644 vendor/github.com/go-kit/kit/.travis.yml delete mode 100644 vendor/github.com/go-kit/kit/CONTRIBUTING.md delete mode 100644 vendor/github.com/go-kit/kit/README.md delete mode 100644 vendor/github.com/go-kit/kit/circle.yml delete mode 100755 vendor/github.com/go-kit/kit/coveralls.bash delete mode 100644 vendor/github.com/go-kit/kit/docker-compose-integration.yml delete mode 100755 vendor/github.com/go-kit/kit/lint delete mode 100644 vendor/github.com/go-kit/kit/log/README.md delete mode 100644 vendor/github.com/go-kit/kit/log/benchmark_test.go delete mode 100644 vendor/github.com/go-kit/kit/log/concurrency_test.go delete mode 100644 vendor/github.com/go-kit/kit/log/example_test.go delete mode 100644 vendor/github.com/go-kit/kit/log/json_logger_test.go delete mode 100644 vendor/github.com/go-kit/kit/log/level/benchmark_test.go delete mode 100644 vendor/github.com/go-kit/kit/log/level/example_test.go delete mode 100644 vendor/github.com/go-kit/kit/log/level/level_test.go delete mode 100644 vendor/github.com/go-kit/kit/log/log_test.go delete mode 100644 vendor/github.com/go-kit/kit/log/logfmt_logger_test.go delete mode 100644 vendor/github.com/go-kit/kit/log/nop_logger_test.go delete mode 100644 vendor/github.com/go-kit/kit/log/stdlib_test.go delete mode 100644 vendor/github.com/go-kit/kit/log/sync_test.go create mode 100644 vendor/github.com/go-kit/kit/log/term/LICENSE delete mode 100644 vendor/github.com/go-kit/kit/log/value_test.go delete mode 100755 vendor/github.com/go-kit/kit/update_deps.bash delete mode 100644 vendor/github.com/go-logfmt/logfmt/.gitignore delete mode 100644 vendor/github.com/go-logfmt/logfmt/.travis.yml delete mode 100644 vendor/github.com/go-logfmt/logfmt/README.md delete mode 100644 vendor/github.com/go-logfmt/logfmt/decode-bench_test.go delete mode 100644 vendor/github.com/go-logfmt/logfmt/decode_test.go delete mode 100644 vendor/github.com/go-logfmt/logfmt/encode_internal_test.go delete mode 100644 vendor/github.com/go-logfmt/logfmt/encode_test.go delete mode 100644 vendor/github.com/go-logfmt/logfmt/example_test.go delete mode 100644 vendor/github.com/go-openapi/jsonpointer/.editorconfig delete mode 100644 vendor/github.com/go-openapi/jsonpointer/.gitignore delete mode 100644 vendor/github.com/go-openapi/jsonpointer/.travis.yml delete mode 100644 vendor/github.com/go-openapi/jsonpointer/CODE_OF_CONDUCT.md delete mode 100644 vendor/github.com/go-openapi/jsonpointer/README.md delete mode 100644 vendor/github.com/go-openapi/jsonpointer/pointer_test.go delete mode 100644 vendor/github.com/go-openapi/jsonreference/.gitignore delete mode 100644 vendor/github.com/go-openapi/jsonreference/.travis.yml delete mode 100644 vendor/github.com/go-openapi/jsonreference/CODE_OF_CONDUCT.md delete mode 100644 vendor/github.com/go-openapi/jsonreference/README.md delete mode 100644 vendor/github.com/go-openapi/jsonreference/reference_test.go delete mode 100644 vendor/github.com/go-openapi/spec/.editorconfig delete mode 100644 vendor/github.com/go-openapi/spec/.gitignore delete mode 100644 vendor/github.com/go-openapi/spec/.travis.yml delete mode 100644 vendor/github.com/go-openapi/spec/CODE_OF_CONDUCT.md delete mode 100644 vendor/github.com/go-openapi/spec/README.md delete mode 100644 vendor/github.com/go-openapi/spec/auth_test.go delete mode 100644 vendor/github.com/go-openapi/spec/contact_info_test.go delete mode 100644 vendor/github.com/go-openapi/spec/expander_test.go delete mode 100644 vendor/github.com/go-openapi/spec/external_docs_test.go delete mode 100644 vendor/github.com/go-openapi/spec/header_test.go delete mode 100644 vendor/github.com/go-openapi/spec/info_test.go delete mode 100644 vendor/github.com/go-openapi/spec/items_test.go delete mode 100644 vendor/github.com/go-openapi/spec/license_test.go delete mode 100644 vendor/github.com/go-openapi/spec/operation_test.go delete mode 100644 vendor/github.com/go-openapi/spec/parameters_test.go delete mode 100644 vendor/github.com/go-openapi/spec/path_item_test.go delete mode 100644 vendor/github.com/go-openapi/spec/paths_test.go delete mode 100644 vendor/github.com/go-openapi/spec/properties_test.go delete mode 100644 vendor/github.com/go-openapi/spec/response_test.go delete mode 100644 vendor/github.com/go-openapi/spec/schema_test.go delete mode 100644 vendor/github.com/go-openapi/spec/structs_test.go delete mode 100644 vendor/github.com/go-openapi/spec/swagger_test.go delete mode 100644 vendor/github.com/go-openapi/spec/xml_object_test.go delete mode 100644 vendor/github.com/go-openapi/swag/.editorconfig delete mode 100644 vendor/github.com/go-openapi/swag/.gitignore delete mode 100644 vendor/github.com/go-openapi/swag/.travis.yml delete mode 100644 vendor/github.com/go-openapi/swag/CODE_OF_CONDUCT.md delete mode 100644 vendor/github.com/go-openapi/swag/README.md delete mode 100644 vendor/github.com/go-openapi/swag/convert_test.go delete mode 100644 vendor/github.com/go-openapi/swag/convert_types_test.go delete mode 100644 vendor/github.com/go-openapi/swag/json_test.go delete mode 100644 vendor/github.com/go-openapi/swag/loading_test.go delete mode 100644 vendor/github.com/go-openapi/swag/net_test.go delete mode 100644 vendor/github.com/go-openapi/swag/path_test.go delete mode 100644 vendor/github.com/go-openapi/swag/util_test.go delete mode 100644 vendor/github.com/go-openapi/swag/yaml_test.go delete mode 100644 vendor/github.com/go-stack/stack/.travis.yml delete mode 100644 vendor/github.com/go-stack/stack/README.md delete mode 100644 vendor/github.com/go-stack/stack/format_test.go delete mode 100644 vendor/github.com/go-stack/stack/stack-go19_test.go delete mode 100644 vendor/github.com/go-stack/stack/stack_test.go delete mode 100644 vendor/github.com/gogo/protobuf/.gitignore delete mode 100644 vendor/github.com/gogo/protobuf/.mailmap delete mode 100644 vendor/github.com/gogo/protobuf/.travis.yml delete mode 100644 vendor/github.com/gogo/protobuf/Makefile delete mode 100644 vendor/github.com/gogo/protobuf/README delete mode 100644 vendor/github.com/gogo/protobuf/Readme.md delete mode 100644 vendor/github.com/gogo/protobuf/bench.md delete mode 100644 vendor/github.com/gogo/protobuf/custom_types.md delete mode 100644 vendor/github.com/gogo/protobuf/extensions.md delete mode 100644 vendor/github.com/gogo/protobuf/gogoproto/Makefile delete mode 100644 vendor/github.com/gogo/protobuf/gogoproto/doc.go delete mode 100644 vendor/github.com/gogo/protobuf/gogoproto/gogo.pb.go delete mode 100644 vendor/github.com/gogo/protobuf/gogoproto/gogo.pb.golden delete mode 100644 vendor/github.com/gogo/protobuf/gogoproto/gogo.proto delete mode 100644 vendor/github.com/gogo/protobuf/gogoproto/helper.go delete mode 100755 vendor/github.com/gogo/protobuf/install-protobuf.sh delete mode 100644 vendor/github.com/gogo/protobuf/jsonpb/jsonpb_test.go delete mode 100644 vendor/github.com/gogo/protobuf/proto/Makefile delete mode 100644 vendor/github.com/gogo/protobuf/proto/all_test.go delete mode 100644 vendor/github.com/gogo/protobuf/proto/any_test.go delete mode 100644 vendor/github.com/gogo/protobuf/proto/clone_test.go delete mode 100644 vendor/github.com/gogo/protobuf/proto/decode_test.go delete mode 100644 vendor/github.com/gogo/protobuf/proto/encode_test.go delete mode 100644 vendor/github.com/gogo/protobuf/proto/equal_test.go delete mode 100644 vendor/github.com/gogo/protobuf/proto/extensions_test.go delete mode 100644 vendor/github.com/gogo/protobuf/proto/map_test.go delete mode 100644 vendor/github.com/gogo/protobuf/proto/message_set_test.go delete mode 100644 vendor/github.com/gogo/protobuf/proto/proto3_test.go delete mode 100644 vendor/github.com/gogo/protobuf/proto/size2_test.go delete mode 100644 vendor/github.com/gogo/protobuf/proto/size_test.go delete mode 100644 vendor/github.com/gogo/protobuf/proto/text_parser_test.go delete mode 100644 vendor/github.com/gogo/protobuf/proto/text_test.go delete mode 100644 vendor/github.com/gogo/protobuf/protoc-gen-gogo/Makefile delete mode 100644 vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/Makefile delete mode 100644 vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/descriptor.go delete mode 100644 vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/descriptor.pb.go delete mode 100644 vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/descriptor_gostring.gen.go delete mode 100644 vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/descriptor_test.go delete mode 100644 vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/helper.go delete mode 100644 vendor/github.com/gogo/protobuf/protoc-gen-gogo/doc.go delete mode 100644 vendor/github.com/gogo/protobuf/protoc-gen-gogo/main.go delete mode 100644 vendor/github.com/gogo/protobuf/types/Makefile delete mode 100644 vendor/github.com/gogo/protobuf/types/any_test.go delete mode 100644 vendor/github.com/gogo/protobuf/types/duration_test.go delete mode 100644 vendor/github.com/gogo/protobuf/types/timestamp_test.go delete mode 100644 vendor/github.com/golang/glog/README delete mode 100644 vendor/github.com/golang/glog/glog_test.go delete mode 100644 vendor/github.com/golang/protobuf/.gitignore delete mode 100644 vendor/github.com/golang/protobuf/.travis.yml delete mode 100644 vendor/github.com/golang/protobuf/Make.protobuf delete mode 100644 vendor/github.com/golang/protobuf/Makefile delete mode 100644 vendor/github.com/golang/protobuf/README.md delete mode 100644 vendor/github.com/golang/protobuf/jsonpb/jsonpb_test.go delete mode 100644 vendor/github.com/golang/protobuf/proto/Makefile delete mode 100644 vendor/github.com/golang/protobuf/proto/all_test.go delete mode 100644 vendor/github.com/golang/protobuf/proto/any_test.go delete mode 100644 vendor/github.com/golang/protobuf/proto/clone_test.go delete mode 100644 vendor/github.com/golang/protobuf/proto/decode_test.go delete mode 100644 vendor/github.com/golang/protobuf/proto/encode_test.go delete mode 100644 vendor/github.com/golang/protobuf/proto/equal_test.go delete mode 100644 vendor/github.com/golang/protobuf/proto/extensions_test.go delete mode 100644 vendor/github.com/golang/protobuf/proto/map_test.go delete mode 100644 vendor/github.com/golang/protobuf/proto/message_set_test.go delete mode 100644 vendor/github.com/golang/protobuf/proto/proto3_test.go delete mode 100644 vendor/github.com/golang/protobuf/proto/size2_test.go delete mode 100644 vendor/github.com/golang/protobuf/proto/size_test.go delete mode 100644 vendor/github.com/golang/protobuf/proto/text_parser_test.go delete mode 100644 vendor/github.com/golang/protobuf/proto/text_test.go delete mode 100644 vendor/github.com/golang/protobuf/protoc-gen-go/Makefile delete mode 100644 vendor/github.com/golang/protobuf/protoc-gen-go/descriptor/Makefile delete mode 100644 vendor/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.proto delete mode 100644 vendor/github.com/golang/protobuf/protoc-gen-go/doc.go delete mode 100644 vendor/github.com/golang/protobuf/protoc-gen-go/link_grpc.go delete mode 100644 vendor/github.com/golang/protobuf/protoc-gen-go/main.go delete mode 100644 vendor/github.com/golang/protobuf/ptypes/any/any.proto delete mode 100644 vendor/github.com/golang/protobuf/ptypes/any_test.go delete mode 100644 vendor/github.com/golang/protobuf/ptypes/duration/duration.proto delete mode 100644 vendor/github.com/golang/protobuf/ptypes/duration_test.go delete mode 100755 vendor/github.com/golang/protobuf/ptypes/regen.sh delete mode 100644 vendor/github.com/golang/protobuf/ptypes/struct/struct.proto delete mode 100644 vendor/github.com/golang/protobuf/ptypes/timestamp/timestamp.proto delete mode 100644 vendor/github.com/golang/protobuf/ptypes/timestamp_test.go delete mode 100644 vendor/github.com/golang/snappy/.gitignore delete mode 100644 vendor/github.com/golang/snappy/README delete mode 100644 vendor/github.com/golang/snappy/golden_test.go delete mode 100644 vendor/github.com/golang/snappy/snappy_test.go delete mode 100644 vendor/github.com/google/gofuzz/.travis.yml delete mode 100644 vendor/github.com/google/gofuzz/CONTRIBUTING.md delete mode 100644 vendor/github.com/google/gofuzz/README.md delete mode 100644 vendor/github.com/google/gofuzz/example_test.go delete mode 100644 vendor/github.com/google/gofuzz/fuzz_test.go delete mode 100644 vendor/github.com/gophercloud/gophercloud/.gitignore delete mode 100644 vendor/github.com/gophercloud/gophercloud/.travis.yml delete mode 100644 vendor/github.com/gophercloud/gophercloud/FAQ.md delete mode 100644 vendor/github.com/gophercloud/gophercloud/MIGRATING.md delete mode 100644 vendor/github.com/gophercloud/gophercloud/README.md delete mode 100644 vendor/github.com/gophercloud/gophercloud/STYLEGUIDE.md delete mode 100644 vendor/github.com/gophercloud/gophercloud/openstack/compute/v2/extensions/delegate.go delete mode 100644 vendor/github.com/gophercloud/gophercloud/openstack/compute/v2/extensions/doc.go delete mode 100644 vendor/github.com/grpc-ecosystem/grpc-gateway/.gitignore delete mode 100644 vendor/github.com/grpc-ecosystem/grpc-gateway/.travis.yml delete mode 100644 vendor/github.com/grpc-ecosystem/grpc-gateway/CHANGELOG.md delete mode 100644 vendor/github.com/grpc-ecosystem/grpc-gateway/CONTRIBUTING.md delete mode 100644 vendor/github.com/grpc-ecosystem/grpc-gateway/Makefile delete mode 100644 vendor/github.com/grpc-ecosystem/grpc-gateway/README.md delete mode 100644 vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/context_test.go delete mode 100644 vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/errors_test.go delete mode 100644 vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/handler_test.go delete mode 100644 vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/internal/stream_chunk.proto delete mode 100644 vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/marshal_json_test.go delete mode 100644 vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/marshal_jsonpb_test.go delete mode 100644 vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/marshal_proto_test.go delete mode 100644 vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/marshaler_registry_test.go delete mode 100644 vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/mux_test.go delete mode 100644 vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/pattern_test.go delete mode 100644 vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/query_test.go rename vendor/github.com/{cockroachdb/cockroach/APL.txt => grpc-ecosystem/grpc-gateway/third_party/googleapis/LICENSE} (99%) delete mode 100644 vendor/github.com/grpc-ecosystem/grpc-gateway/utilities/trie_test.go delete mode 100644 vendor/github.com/hashicorp/consul/.gitignore delete mode 100644 vendor/github.com/hashicorp/consul/.travis.yml delete mode 100644 vendor/github.com/hashicorp/consul/CHANGELOG.md delete mode 100644 vendor/github.com/hashicorp/consul/GNUmakefile delete mode 100644 vendor/github.com/hashicorp/consul/ISSUE_TEMPLATE.md delete mode 100644 vendor/github.com/hashicorp/consul/README.md delete mode 100644 vendor/github.com/hashicorp/consul/api/README.md delete mode 100644 vendor/github.com/hashicorp/consul/api/acl_test.go delete mode 100644 vendor/github.com/hashicorp/consul/api/agent_test.go delete mode 100644 vendor/github.com/hashicorp/consul/api/api_test.go delete mode 100644 vendor/github.com/hashicorp/consul/api/catalog_test.go delete mode 100644 vendor/github.com/hashicorp/consul/api/coordinate_test.go delete mode 100644 vendor/github.com/hashicorp/consul/api/event_test.go delete mode 100644 vendor/github.com/hashicorp/consul/api/health_test.go delete mode 100644 vendor/github.com/hashicorp/consul/api/kv_test.go delete mode 100644 vendor/github.com/hashicorp/consul/api/lock_test.go delete mode 100644 vendor/github.com/hashicorp/consul/api/operator_autopilot_test.go delete mode 100644 vendor/github.com/hashicorp/consul/api/operator_keyring_test.go delete mode 100644 vendor/github.com/hashicorp/consul/api/operator_raft_test.go delete mode 100644 vendor/github.com/hashicorp/consul/api/prepared_query_test.go delete mode 100644 vendor/github.com/hashicorp/consul/api/semaphore_test.go delete mode 100644 vendor/github.com/hashicorp/consul/api/session_test.go delete mode 100644 vendor/github.com/hashicorp/consul/api/snapshot_test.go delete mode 100644 vendor/github.com/hashicorp/consul/api/status_test.go delete mode 100644 vendor/github.com/hashicorp/consul/main.go delete mode 100644 vendor/github.com/hashicorp/consul/main_test.go create mode 100644 vendor/github.com/hashicorp/consul/website/LICENSE.md delete mode 100644 vendor/github.com/hashicorp/go-cleanhttp/README.md delete mode 100644 vendor/github.com/hashicorp/go-cleanhttp/handlers_test.go delete mode 100644 vendor/github.com/hashicorp/go-rootcerts/.travis.yml delete mode 100644 vendor/github.com/hashicorp/go-rootcerts/Makefile delete mode 100644 vendor/github.com/hashicorp/go-rootcerts/README.md delete mode 100644 vendor/github.com/hashicorp/go-rootcerts/rootcerts_darwin_test.go delete mode 100644 vendor/github.com/hashicorp/go-rootcerts/rootcerts_test.go create mode 120000 vendor/github.com/hashicorp/go-rootcerts/test-fixtures/capath-with-symlinks/securetrust.pem create mode 120000 vendor/github.com/hashicorp/go-rootcerts/test-fixtures/capath-with-symlinks/thawte.pem delete mode 100644 vendor/github.com/hashicorp/serf/.gitignore delete mode 100644 vendor/github.com/hashicorp/serf/.travis.yml delete mode 100644 vendor/github.com/hashicorp/serf/CHANGELOG.md delete mode 100644 vendor/github.com/hashicorp/serf/GNUmakefile delete mode 100644 vendor/github.com/hashicorp/serf/README.md delete mode 100644 vendor/github.com/hashicorp/serf/coordinate/client_test.go delete mode 100644 vendor/github.com/hashicorp/serf/coordinate/coordinate_test.go delete mode 100644 vendor/github.com/hashicorp/serf/coordinate/performance_test.go delete mode 100644 vendor/github.com/hashicorp/serf/coordinate/util_test.go create mode 100644 vendor/github.com/hashicorp/serf/ops-misc/debian/copyright create mode 100644 vendor/github.com/hashicorp/serf/website/source/LICENSE delete mode 100644 vendor/github.com/jessevdk/go-flags/.travis.yml delete mode 100644 vendor/github.com/jessevdk/go-flags/README.md delete mode 100644 vendor/github.com/jessevdk/go-flags/arg_test.go delete mode 100644 vendor/github.com/jessevdk/go-flags/assert_test.go delete mode 100755 vendor/github.com/jessevdk/go-flags/check_crosscompile.sh delete mode 100644 vendor/github.com/jessevdk/go-flags/command_test.go delete mode 100644 vendor/github.com/jessevdk/go-flags/completion_test.go delete mode 100644 vendor/github.com/jessevdk/go-flags/convert_test.go delete mode 100644 vendor/github.com/jessevdk/go-flags/example_test.go delete mode 100644 vendor/github.com/jessevdk/go-flags/group_test.go delete mode 100644 vendor/github.com/jessevdk/go-flags/help_test.go delete mode 100644 vendor/github.com/jessevdk/go-flags/ini_test.go delete mode 100644 vendor/github.com/jessevdk/go-flags/long_test.go delete mode 100644 vendor/github.com/jessevdk/go-flags/marshal_test.go delete mode 100644 vendor/github.com/jessevdk/go-flags/options_test.go delete mode 100644 vendor/github.com/jessevdk/go-flags/parser_test.go delete mode 100644 vendor/github.com/jessevdk/go-flags/pointer_test.go delete mode 100644 vendor/github.com/jessevdk/go-flags/short_test.go delete mode 100644 vendor/github.com/jessevdk/go-flags/tag_test.go delete mode 100644 vendor/github.com/jessevdk/go-flags/unknown_test.go delete mode 100644 vendor/github.com/jmespath/go-jmespath/.gitignore delete mode 100644 vendor/github.com/jmespath/go-jmespath/.travis.yml delete mode 100644 vendor/github.com/jmespath/go-jmespath/Makefile delete mode 100644 vendor/github.com/jmespath/go-jmespath/README.md delete mode 100644 vendor/github.com/jmespath/go-jmespath/api_test.go delete mode 100644 vendor/github.com/jmespath/go-jmespath/compliance_test.go delete mode 100644 vendor/github.com/jmespath/go-jmespath/interpreter_test.go delete mode 100644 vendor/github.com/jmespath/go-jmespath/lexer_test.go delete mode 100644 vendor/github.com/jmespath/go-jmespath/parser_test.go delete mode 100644 vendor/github.com/jmespath/go-jmespath/util_test.go create mode 100644 vendor/github.com/json-iterator/go/LICENSE create mode 100644 vendor/github.com/json-iterator/go/adapter.go create mode 100644 vendor/github.com/json-iterator/go/any.go create mode 100644 vendor/github.com/json-iterator/go/any_array.go create mode 100644 vendor/github.com/json-iterator/go/any_bool.go create mode 100644 vendor/github.com/json-iterator/go/any_float.go create mode 100644 vendor/github.com/json-iterator/go/any_int32.go create mode 100644 vendor/github.com/json-iterator/go/any_int64.go create mode 100644 vendor/github.com/json-iterator/go/any_invalid.go create mode 100644 vendor/github.com/json-iterator/go/any_nil.go create mode 100644 vendor/github.com/json-iterator/go/any_number.go create mode 100644 vendor/github.com/json-iterator/go/any_object.go create mode 100644 vendor/github.com/json-iterator/go/any_str.go create mode 100644 vendor/github.com/json-iterator/go/any_uint32.go create mode 100644 vendor/github.com/json-iterator/go/any_uint64.go create mode 100644 vendor/github.com/json-iterator/go/config.go create mode 100644 vendor/github.com/json-iterator/go/iter.go create mode 100644 vendor/github.com/json-iterator/go/iter_array.go create mode 100644 vendor/github.com/json-iterator/go/iter_float.go create mode 100644 vendor/github.com/json-iterator/go/iter_int.go create mode 100644 vendor/github.com/json-iterator/go/iter_object.go create mode 100644 vendor/github.com/json-iterator/go/iter_skip.go create mode 100644 vendor/github.com/json-iterator/go/iter_skip_sloppy.go create mode 100644 vendor/github.com/json-iterator/go/iter_skip_strict.go create mode 100644 vendor/github.com/json-iterator/go/iter_str.go create mode 100644 vendor/github.com/json-iterator/go/jsoniter.go create mode 100644 vendor/github.com/json-iterator/go/pool.go create mode 100644 vendor/github.com/json-iterator/go/reflect.go create mode 100644 vendor/github.com/json-iterator/go/reflect_array.go create mode 100644 vendor/github.com/json-iterator/go/reflect_dynamic.go create mode 100644 vendor/github.com/json-iterator/go/reflect_extension.go create mode 100644 vendor/github.com/json-iterator/go/reflect_json_number.go create mode 100644 vendor/github.com/json-iterator/go/reflect_json_raw_message.go create mode 100644 vendor/github.com/json-iterator/go/reflect_map.go create mode 100644 vendor/github.com/json-iterator/go/reflect_marshaler.go create mode 100644 vendor/github.com/json-iterator/go/reflect_native.go create mode 100644 vendor/github.com/json-iterator/go/reflect_optional.go create mode 100644 vendor/github.com/json-iterator/go/reflect_slice.go create mode 100644 vendor/github.com/json-iterator/go/reflect_struct_decoder.go create mode 100644 vendor/github.com/json-iterator/go/reflect_struct_encoder.go create mode 100644 vendor/github.com/json-iterator/go/stream.go create mode 100644 vendor/github.com/json-iterator/go/stream_float.go create mode 100644 vendor/github.com/json-iterator/go/stream_int.go create mode 100644 vendor/github.com/json-iterator/go/stream_str.go delete mode 100644 vendor/github.com/juju/ratelimit/README.md delete mode 100644 vendor/github.com/juju/ratelimit/ratelimit_test.go delete mode 100644 vendor/github.com/julienschmidt/httprouter/.travis.yml delete mode 100644 vendor/github.com/julienschmidt/httprouter/README.md delete mode 100644 vendor/github.com/julienschmidt/httprouter/path_test.go delete mode 100644 vendor/github.com/julienschmidt/httprouter/router_test.go delete mode 100644 vendor/github.com/julienschmidt/httprouter/tree_test.go delete mode 100644 vendor/github.com/kr/logfmt/.gitignore delete mode 100644 vendor/github.com/kr/logfmt/Readme delete mode 100644 vendor/github.com/kr/logfmt/bench_test.go delete mode 100644 vendor/github.com/kr/logfmt/decode_test.go delete mode 100644 vendor/github.com/kr/logfmt/example_test.go delete mode 100644 vendor/github.com/kr/logfmt/scanner_test.go delete mode 100644 vendor/github.com/mailru/easyjson/.gitignore delete mode 100644 vendor/github.com/mailru/easyjson/.travis.yml delete mode 100644 vendor/github.com/mailru/easyjson/Makefile delete mode 100644 vendor/github.com/mailru/easyjson/README.md delete mode 100644 vendor/github.com/mailru/easyjson/buffer/pool_test.go delete mode 100644 vendor/github.com/mailru/easyjson/jlexer/lexer_test.go delete mode 100644 vendor/github.com/matttproud/golang_protobuf_extensions/.travis.yml delete mode 100644 vendor/github.com/matttproud/golang_protobuf_extensions/README.md delete mode 100644 vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/all_test.go delete mode 100644 vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/decode_test.go delete mode 100644 vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/encode_test.go delete mode 100644 vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/fixtures_test.go delete mode 100644 vendor/github.com/miekg/dns/.gitignore delete mode 100644 vendor/github.com/miekg/dns/.travis.yml delete mode 100644 vendor/github.com/miekg/dns/README.md delete mode 100644 vendor/github.com/miekg/dns/client_test.go delete mode 100644 vendor/github.com/miekg/dns/clientconfig_test.go delete mode 100644 vendor/github.com/miekg/dns/dns_bench_test.go delete mode 100644 vendor/github.com/miekg/dns/dns_test.go delete mode 100644 vendor/github.com/miekg/dns/dnssec_test.go delete mode 100644 vendor/github.com/miekg/dns/dyn_test.go delete mode 100644 vendor/github.com/miekg/dns/edns_test.go delete mode 100644 vendor/github.com/miekg/dns/example_test.go delete mode 100644 vendor/github.com/miekg/dns/fuzz_test.go delete mode 100644 vendor/github.com/miekg/dns/internal/socket/controlmessage_test.go delete mode 100644 vendor/github.com/miekg/dns/issue_test.go delete mode 100644 vendor/github.com/miekg/dns/labels_test.go delete mode 100644 vendor/github.com/miekg/dns/msg_test.go delete mode 100644 vendor/github.com/miekg/dns/nsecx_test.go delete mode 100644 vendor/github.com/miekg/dns/parse_test.go delete mode 100644 vendor/github.com/miekg/dns/privaterr_test.go delete mode 100644 vendor/github.com/miekg/dns/remote_test.go delete mode 100644 vendor/github.com/miekg/dns/sanitize_test.go delete mode 100644 vendor/github.com/miekg/dns/scan_test.go delete mode 100644 vendor/github.com/miekg/dns/server_test.go delete mode 100644 vendor/github.com/miekg/dns/sig0_test.go delete mode 100644 vendor/github.com/miekg/dns/tsig_test.go delete mode 100644 vendor/github.com/miekg/dns/types_test.go delete mode 100644 vendor/github.com/miekg/dns/udp_linux_test.go delete mode 100644 vendor/github.com/miekg/dns/update_test.go delete mode 100644 vendor/github.com/miekg/dns/xfr_test.go delete mode 100644 vendor/github.com/mitchellh/go-homedir/README.md delete mode 100644 vendor/github.com/mitchellh/go-homedir/homedir_test.go create mode 100644 vendor/github.com/modern-go/concurrent/LICENSE create mode 100644 vendor/github.com/modern-go/concurrent/executor.go create mode 100644 vendor/github.com/modern-go/concurrent/go_above_19.go create mode 100644 vendor/github.com/modern-go/concurrent/go_below_19.go create mode 100644 vendor/github.com/modern-go/concurrent/log.go create mode 100644 vendor/github.com/modern-go/concurrent/unbounded_executor.go create mode 100644 vendor/github.com/modern-go/reflect2/LICENSE create mode 100644 vendor/github.com/modern-go/reflect2/go_above_17.go create mode 100644 vendor/github.com/modern-go/reflect2/go_above_19.go create mode 100644 vendor/github.com/modern-go/reflect2/go_below_17.go create mode 100644 vendor/github.com/modern-go/reflect2/go_below_19.go create mode 100644 vendor/github.com/modern-go/reflect2/reflect2.go rename vendor/github.com/{gophercloud/gophercloud/CHANGELOG.md => modern-go/reflect2/reflect2_amd64.s} (100%) create mode 100644 vendor/github.com/modern-go/reflect2/reflect2_kind.go create mode 100644 vendor/github.com/modern-go/reflect2/relfect2_386.s create mode 100644 vendor/github.com/modern-go/reflect2/relfect2_amd64p32.s create mode 100644 vendor/github.com/modern-go/reflect2/relfect2_arm.s create mode 100644 vendor/github.com/modern-go/reflect2/relfect2_arm64.s create mode 100644 vendor/github.com/modern-go/reflect2/relfect2_mips64x.s create mode 100644 vendor/github.com/modern-go/reflect2/relfect2_mipsx.s create mode 100644 vendor/github.com/modern-go/reflect2/relfect2_ppc64x.s create mode 100644 vendor/github.com/modern-go/reflect2/relfect2_s390x.s create mode 100644 vendor/github.com/modern-go/reflect2/safe_field.go create mode 100644 vendor/github.com/modern-go/reflect2/safe_map.go create mode 100644 vendor/github.com/modern-go/reflect2/safe_slice.go create mode 100644 vendor/github.com/modern-go/reflect2/safe_struct.go create mode 100644 vendor/github.com/modern-go/reflect2/safe_type.go create mode 100644 vendor/github.com/modern-go/reflect2/type_map.go create mode 100644 vendor/github.com/modern-go/reflect2/unsafe_array.go create mode 100644 vendor/github.com/modern-go/reflect2/unsafe_eface.go create mode 100644 vendor/github.com/modern-go/reflect2/unsafe_field.go create mode 100644 vendor/github.com/modern-go/reflect2/unsafe_iface.go create mode 100644 vendor/github.com/modern-go/reflect2/unsafe_link.go create mode 100644 vendor/github.com/modern-go/reflect2/unsafe_map.go create mode 100644 vendor/github.com/modern-go/reflect2/unsafe_ptr.go create mode 100644 vendor/github.com/modern-go/reflect2/unsafe_slice.go create mode 100644 vendor/github.com/modern-go/reflect2/unsafe_struct.go create mode 100644 vendor/github.com/modern-go/reflect2/unsafe_type.go delete mode 100644 vendor/github.com/mwitkow/go-conntrack/.gitignore delete mode 100644 vendor/github.com/mwitkow/go-conntrack/.travis.yml delete mode 100644 vendor/github.com/mwitkow/go-conntrack/README.md delete mode 100644 vendor/github.com/mwitkow/go-conntrack/dialer_test.go delete mode 100644 vendor/github.com/mwitkow/go-conntrack/listener_test.go delete mode 100644 vendor/github.com/mwitkow/go-conntrack/promhelper_test.go delete mode 100644 vendor/github.com/mwitkow/go-conntrack/tracehelper_test.go delete mode 100644 vendor/github.com/nightlyone/lockfile/.gitignore delete mode 100644 vendor/github.com/nightlyone/lockfile/.gitmodules delete mode 100644 vendor/github.com/nightlyone/lockfile/.travis.yml delete mode 100644 vendor/github.com/nightlyone/lockfile/README.md delete mode 100644 vendor/github.com/nightlyone/lockfile/appveyor.yml delete mode 100644 vendor/github.com/nightlyone/lockfile/lockfile_test.go delete mode 100644 vendor/github.com/oklog/ulid/.gitignore delete mode 100644 vendor/github.com/oklog/ulid/.travis.yml delete mode 100644 vendor/github.com/oklog/ulid/CHANGELOG.md delete mode 100644 vendor/github.com/oklog/ulid/CONTRIBUTING.md delete mode 100644 vendor/github.com/oklog/ulid/README.md delete mode 100644 vendor/github.com/oklog/ulid/ulid_test.go delete mode 100644 vendor/github.com/opentracing-contrib/go-stdlib/.travis.yml delete mode 100644 vendor/github.com/opentracing-contrib/go-stdlib/README.md delete mode 100644 vendor/github.com/opentracing-contrib/go-stdlib/nethttp/client_test.go delete mode 100644 vendor/github.com/opentracing-contrib/go-stdlib/nethttp/server_test.go delete mode 100644 vendor/github.com/opentracing/opentracing-go/.gitignore delete mode 100644 vendor/github.com/opentracing/opentracing-go/.travis.yml delete mode 100644 vendor/github.com/opentracing/opentracing-go/CHANGELOG.md delete mode 100644 vendor/github.com/opentracing/opentracing-go/Makefile delete mode 100644 vendor/github.com/opentracing/opentracing-go/README.md delete mode 100644 vendor/github.com/opentracing/opentracing-go/ext/tags_test.go delete mode 100644 vendor/github.com/opentracing/opentracing-go/gocontext_test.go delete mode 100644 vendor/github.com/opentracing/opentracing-go/log/field_test.go delete mode 100644 vendor/github.com/opentracing/opentracing-go/options_test.go delete mode 100644 vendor/github.com/opentracing/opentracing-go/propagation_test.go delete mode 100644 vendor/github.com/opentracing/opentracing-go/testtracer_test.go delete mode 100644 vendor/github.com/petermattis/goid/.gitignore delete mode 100644 vendor/github.com/petermattis/goid/.travis.yml delete mode 100644 vendor/github.com/petermattis/goid/README.md delete mode 100644 vendor/github.com/petermattis/goid/goid_test.go delete mode 100644 vendor/github.com/pkg/errors/.gitignore delete mode 100644 vendor/github.com/pkg/errors/.travis.yml delete mode 100644 vendor/github.com/pkg/errors/README.md delete mode 100644 vendor/github.com/pkg/errors/appveyor.yml delete mode 100644 vendor/github.com/pkg/errors/bench_test.go delete mode 100644 vendor/github.com/pkg/errors/errors_test.go delete mode 100644 vendor/github.com/pkg/errors/example_test.go delete mode 100644 vendor/github.com/pkg/errors/format_test.go delete mode 100644 vendor/github.com/pkg/errors/stack_test.go delete mode 100644 vendor/github.com/prometheus/client_golang/.gitignore delete mode 100644 vendor/github.com/prometheus/client_golang/.travis.yml delete mode 100644 vendor/github.com/prometheus/client_golang/AUTHORS.md delete mode 100644 vendor/github.com/prometheus/client_golang/CHANGELOG.md delete mode 100644 vendor/github.com/prometheus/client_golang/CONTRIBUTING.md delete mode 100644 vendor/github.com/prometheus/client_golang/README.md delete mode 100644 vendor/github.com/prometheus/client_golang/VERSION delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/.gitignore delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/README.md delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/benchmark_test.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/counter_test.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/example_clustermanager_test.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/examples_test.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/expvar_collector_test.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/gauge_test.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/go_collector_test.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/histogram_test.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/http_test.go create mode 100644 vendor/github.com/prometheus/client_golang/prometheus/labels.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/metric_test.go create mode 100644 vendor/github.com/prometheus/client_golang/prometheus/observer.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/process_collector_test.go create mode 100644 vendor/github.com/prometheus/client_golang/prometheus/promhttp/delegator.go create mode 100644 vendor/github.com/prometheus/client_golang/prometheus/promhttp/delegator_1_8.go rename vendor/github.com/prometheus/{prometheus/config/config_default_test.go => client_golang/prometheus/promhttp/delegator_pre_1_8.go} (52%) create mode 100644 vendor/github.com/prometheus/client_golang/prometheus/promhttp/http.go create mode 100644 vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_client.go create mode 100644 vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_client_1_8.go create mode 100644 vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_server.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/registry_test.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/summary_test.go create mode 100644 vendor/github.com/prometheus/client_golang/prometheus/timer.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/vec_test.go delete mode 100644 vendor/github.com/prometheus/client_model/.gitignore delete mode 100644 vendor/github.com/prometheus/client_model/CONTRIBUTING.md delete mode 100644 vendor/github.com/prometheus/client_model/MAINTAINERS.md delete mode 100644 vendor/github.com/prometheus/client_model/Makefile delete mode 100644 vendor/github.com/prometheus/client_model/README.md delete mode 100644 vendor/github.com/prometheus/client_model/metrics.proto delete mode 100644 vendor/github.com/prometheus/client_model/pom.xml create mode 100644 vendor/github.com/prometheus/client_model/ruby/LICENSE delete mode 100644 vendor/github.com/prometheus/client_model/setup.py delete mode 100644 vendor/github.com/prometheus/common/.travis.yml delete mode 100644 vendor/github.com/prometheus/common/CONTRIBUTING.md delete mode 100644 vendor/github.com/prometheus/common/MAINTAINERS.md delete mode 100644 vendor/github.com/prometheus/common/README.md delete mode 100644 vendor/github.com/prometheus/common/config/http_config_test.go delete mode 100644 vendor/github.com/prometheus/common/config/tls_config_test.go delete mode 100644 vendor/github.com/prometheus/common/expfmt/bench_test.go delete mode 100644 vendor/github.com/prometheus/common/expfmt/decode_test.go delete mode 100644 vendor/github.com/prometheus/common/expfmt/text_create_test.go delete mode 100644 vendor/github.com/prometheus/common/expfmt/text_parse_test.go delete mode 100644 vendor/github.com/prometheus/common/internal/bitbucket.org/ww/goautoneg/README.txt delete mode 100644 vendor/github.com/prometheus/common/internal/bitbucket.org/ww/goautoneg/autoneg_test.go delete mode 100644 vendor/github.com/prometheus/common/log/log_test.go delete mode 100644 vendor/github.com/prometheus/common/log/syslog_formatter_test.go delete mode 100644 vendor/github.com/prometheus/common/model/alert_test.go delete mode 100644 vendor/github.com/prometheus/common/model/labels_test.go delete mode 100644 vendor/github.com/prometheus/common/model/metric_test.go delete mode 100644 vendor/github.com/prometheus/common/model/signature_test.go delete mode 100644 vendor/github.com/prometheus/common/model/silence_test.go delete mode 100644 vendor/github.com/prometheus/common/model/time_test.go delete mode 100644 vendor/github.com/prometheus/common/model/value_bench_test.go delete mode 100644 vendor/github.com/prometheus/common/model/value_test.go delete mode 100644 vendor/github.com/prometheus/common/route/route_test.go delete mode 100644 vendor/github.com/prometheus/procfs/.travis.yml delete mode 100644 vendor/github.com/prometheus/procfs/CONTRIBUTING.md delete mode 100644 vendor/github.com/prometheus/procfs/MAINTAINERS.md delete mode 100644 vendor/github.com/prometheus/procfs/Makefile delete mode 100644 vendor/github.com/prometheus/procfs/README.md delete mode 100644 vendor/github.com/prometheus/procfs/buddyinfo_test.go create mode 120000 vendor/github.com/prometheus/procfs/fixtures/26231/exe create mode 120000 vendor/github.com/prometheus/procfs/fixtures/26231/fd/0 create mode 120000 vendor/github.com/prometheus/procfs/fixtures/26231/fd/1 create mode 120000 vendor/github.com/prometheus/procfs/fixtures/26231/fd/10 create mode 120000 vendor/github.com/prometheus/procfs/fixtures/26231/fd/2 create mode 120000 vendor/github.com/prometheus/procfs/fixtures/26231/fd/3 create mode 120000 vendor/github.com/prometheus/procfs/fixtures/26232/fd/0 create mode 120000 vendor/github.com/prometheus/procfs/fixtures/26232/fd/1 create mode 120000 vendor/github.com/prometheus/procfs/fixtures/26232/fd/2 create mode 120000 vendor/github.com/prometheus/procfs/fixtures/26232/fd/3 create mode 120000 vendor/github.com/prometheus/procfs/fixtures/26232/fd/4 create mode 120000 vendor/github.com/prometheus/procfs/fixtures/self delete mode 100644 vendor/github.com/prometheus/procfs/fs_test.go delete mode 100644 vendor/github.com/prometheus/procfs/ipvs_test.go delete mode 100644 vendor/github.com/prometheus/procfs/mdstat_test.go delete mode 100644 vendor/github.com/prometheus/procfs/mountstats_test.go delete mode 100644 vendor/github.com/prometheus/procfs/proc_io_test.go delete mode 100644 vendor/github.com/prometheus/procfs/proc_limits_test.go delete mode 100644 vendor/github.com/prometheus/procfs/proc_stat_test.go delete mode 100644 vendor/github.com/prometheus/procfs/proc_test.go delete mode 100644 vendor/github.com/prometheus/procfs/stat_test.go delete mode 100755 vendor/github.com/prometheus/procfs/ttar delete mode 100644 vendor/github.com/prometheus/procfs/xfrm_test.go delete mode 100644 vendor/github.com/prometheus/procfs/xfs/parse_test.go delete mode 100644 vendor/github.com/prometheus/prometheus/.dockerignore delete mode 100644 vendor/github.com/prometheus/prometheus/.gitignore delete mode 100644 vendor/github.com/prometheus/prometheus/.promu.yml delete mode 100644 vendor/github.com/prometheus/prometheus/.travis.yml delete mode 100644 vendor/github.com/prometheus/prometheus/CHANGELOG.md delete mode 100644 vendor/github.com/prometheus/prometheus/CONTRIBUTING.md delete mode 100644 vendor/github.com/prometheus/prometheus/Dockerfile delete mode 100644 vendor/github.com/prometheus/prometheus/MAINTAINERS.md delete mode 100644 vendor/github.com/prometheus/prometheus/Makefile delete mode 100644 vendor/github.com/prometheus/prometheus/README.md delete mode 100644 vendor/github.com/prometheus/prometheus/VERSION delete mode 100644 vendor/github.com/prometheus/prometheus/circle.yml delete mode 100644 vendor/github.com/prometheus/prometheus/code-of-conduct.md delete mode 100644 vendor/github.com/prometheus/prometheus/config/config_test.go delete mode 100644 vendor/github.com/prometheus/prometheus/config/config_windows_test.go delete mode 100644 vendor/github.com/prometheus/prometheus/discovery/README.md delete mode 100644 vendor/github.com/prometheus/prometheus/discovery/consul/consul_test.go delete mode 100644 vendor/github.com/prometheus/prometheus/discovery/file/file_test.go delete mode 100644 vendor/github.com/prometheus/prometheus/discovery/kubernetes/endpoints_test.go delete mode 100644 vendor/github.com/prometheus/prometheus/discovery/kubernetes/ingress_test.go delete mode 100644 vendor/github.com/prometheus/prometheus/discovery/kubernetes/node_test.go delete mode 100644 vendor/github.com/prometheus/prometheus/discovery/kubernetes/pod_test.go delete mode 100644 vendor/github.com/prometheus/prometheus/discovery/kubernetes/service_test.go delete mode 100644 vendor/github.com/prometheus/prometheus/discovery/manager_test.go delete mode 100644 vendor/github.com/prometheus/prometheus/discovery/marathon/marathon_test.go delete mode 100644 vendor/github.com/prometheus/prometheus/discovery/openstack/hypervisor_test.go delete mode 100644 vendor/github.com/prometheus/prometheus/discovery/openstack/instance_test.go delete mode 100644 vendor/github.com/prometheus/prometheus/discovery/targetgroup/targetgroup_test.go delete mode 100644 vendor/github.com/prometheus/prometheus/discovery/triton/triton_test.go delete mode 100644 vendor/github.com/prometheus/prometheus/notifier/notifier_test.go delete mode 100644 vendor/github.com/prometheus/prometheus/pkg/labels/matcher_test.go delete mode 100644 vendor/github.com/prometheus/prometheus/pkg/relabel/relabel_test.go delete mode 100644 vendor/github.com/prometheus/prometheus/pkg/rulefmt/rulefmt_test.go delete mode 100644 vendor/github.com/prometheus/prometheus/pkg/textparse/lex.l delete mode 100644 vendor/github.com/prometheus/prometheus/pkg/textparse/parse_test.go delete mode 100644 vendor/github.com/prometheus/prometheus/pkg/textparse/testdata.nometa.txt delete mode 100644 vendor/github.com/prometheus/prometheus/pkg/textparse/testdata.txt delete mode 100644 vendor/github.com/prometheus/prometheus/prompb/remote.proto delete mode 100644 vendor/github.com/prometheus/prometheus/prompb/rpc.proto delete mode 100644 vendor/github.com/prometheus/prometheus/prompb/types.proto delete mode 100644 vendor/github.com/prometheus/prometheus/promql/bench_test.go delete mode 100644 vendor/github.com/prometheus/prometheus/promql/engine_test.go delete mode 100644 vendor/github.com/prometheus/prometheus/promql/functions_test.go delete mode 100644 vendor/github.com/prometheus/prometheus/promql/lex_test.go delete mode 100644 vendor/github.com/prometheus/prometheus/promql/parse_test.go delete mode 100644 vendor/github.com/prometheus/prometheus/promql/printer_test.go delete mode 100644 vendor/github.com/prometheus/prometheus/promql/promql_test.go delete mode 100644 vendor/github.com/prometheus/prometheus/promql/test_test.go delete mode 100644 vendor/github.com/prometheus/prometheus/relabel/relabel_test.go delete mode 100644 vendor/github.com/prometheus/prometheus/rules/alerting_test.go delete mode 100644 vendor/github.com/prometheus/prometheus/rules/manager_test.go delete mode 100644 vendor/github.com/prometheus/prometheus/rules/recording_test.go delete mode 100644 vendor/github.com/prometheus/prometheus/scrape/helpers_test.go delete mode 100644 vendor/github.com/prometheus/prometheus/scrape/manager_test.go delete mode 100644 vendor/github.com/prometheus/prometheus/scrape/scrape_test.go delete mode 100644 vendor/github.com/prometheus/prometheus/scrape/target_test.go delete mode 100644 vendor/github.com/prometheus/prometheus/storage/buffer_test.go delete mode 100644 vendor/github.com/prometheus/prometheus/storage/fanout_test.go delete mode 100644 vendor/github.com/prometheus/prometheus/storage/remote/client_test.go delete mode 100644 vendor/github.com/prometheus/prometheus/storage/remote/codec_test.go delete mode 100644 vendor/github.com/prometheus/prometheus/storage/remote/queue_manager_test.go delete mode 100644 vendor/github.com/prometheus/prometheus/storage/remote/read_test.go delete mode 100644 vendor/github.com/prometheus/prometheus/template/template_test.go delete mode 100644 vendor/github.com/prometheus/prometheus/util/httputil/client.go delete mode 100644 vendor/github.com/prometheus/prometheus/util/httputil/client_test.go delete mode 100644 vendor/github.com/prometheus/prometheus/util/stats/stats_test.go delete mode 100644 vendor/github.com/prometheus/prometheus/util/strutil/quote_test.go delete mode 100644 vendor/github.com/prometheus/prometheus/util/strutil/strconv_test.go delete mode 100644 vendor/github.com/prometheus/prometheus/util/yaml/yaml.go delete mode 100644 vendor/github.com/prometheus/prometheus/web/api/v1/api_test.go delete mode 100644 vendor/github.com/prometheus/prometheus/web/federate_test.go delete mode 100644 vendor/github.com/prometheus/prometheus/web/ui/README.md delete mode 100644 vendor/github.com/prometheus/prometheus/web/web_test.go delete mode 100644 vendor/github.com/prometheus/tsdb/.gitignore delete mode 100644 vendor/github.com/prometheus/tsdb/.travis.yml delete mode 100644 vendor/github.com/prometheus/tsdb/README.md delete mode 100644 vendor/github.com/prometheus/tsdb/block_test.go delete mode 100644 vendor/github.com/prometheus/tsdb/chunkenc/chunk_test.go delete mode 100644 vendor/github.com/prometheus/tsdb/compact_test.go delete mode 100644 vendor/github.com/prometheus/tsdb/db_test.go delete mode 100644 vendor/github.com/prometheus/tsdb/head_test.go delete mode 100644 vendor/github.com/prometheus/tsdb/index/index_test.go delete mode 100644 vendor/github.com/prometheus/tsdb/index/postings_test.go delete mode 100644 vendor/github.com/prometheus/tsdb/labels/labels_test.go delete mode 100644 vendor/github.com/prometheus/tsdb/querier_test.go delete mode 100644 vendor/github.com/prometheus/tsdb/repair_test.go delete mode 100644 vendor/github.com/prometheus/tsdb/tombstones_test.go delete mode 100644 vendor/github.com/prometheus/tsdb/wal_test.go delete mode 100644 vendor/github.com/samuel/go-zookeeper/.gitignore delete mode 100644 vendor/github.com/samuel/go-zookeeper/.travis.yml delete mode 100644 vendor/github.com/samuel/go-zookeeper/README.md delete mode 100644 vendor/github.com/samuel/go-zookeeper/zk/cluster_test.go delete mode 100644 vendor/github.com/samuel/go-zookeeper/zk/constants_test.go delete mode 100644 vendor/github.com/samuel/go-zookeeper/zk/dnshostprovider_test.go delete mode 100644 vendor/github.com/samuel/go-zookeeper/zk/flw_test.go delete mode 100644 vendor/github.com/samuel/go-zookeeper/zk/lock_test.go delete mode 100644 vendor/github.com/samuel/go-zookeeper/zk/structs_test.go delete mode 100644 vendor/github.com/samuel/go-zookeeper/zk/throttle_test.go delete mode 100644 vendor/github.com/samuel/go-zookeeper/zk/util_test.go delete mode 100644 vendor/github.com/samuel/go-zookeeper/zk/zk_test.go delete mode 100644 vendor/github.com/sasha-s/go-deadlock/.travis.yml delete mode 100644 vendor/github.com/sasha-s/go-deadlock/Readme.md delete mode 100644 vendor/github.com/sasha-s/go-deadlock/deadlock_test.go delete mode 100644 vendor/github.com/sirupsen/logrus/.gitignore delete mode 100644 vendor/github.com/sirupsen/logrus/.travis.yml delete mode 100644 vendor/github.com/sirupsen/logrus/CHANGELOG.md delete mode 100644 vendor/github.com/sirupsen/logrus/README.md delete mode 100644 vendor/github.com/sirupsen/logrus/alt_exit_test.go delete mode 100644 vendor/github.com/sirupsen/logrus/appveyor.yml delete mode 100644 vendor/github.com/sirupsen/logrus/entry_test.go delete mode 100644 vendor/github.com/sirupsen/logrus/example_basic_test.go delete mode 100644 vendor/github.com/sirupsen/logrus/example_hook_test.go delete mode 100644 vendor/github.com/sirupsen/logrus/formatter_bench_test.go delete mode 100644 vendor/github.com/sirupsen/logrus/hook_test.go delete mode 100644 vendor/github.com/sirupsen/logrus/json_formatter_test.go delete mode 100644 vendor/github.com/sirupsen/logrus/logger_bench_test.go delete mode 100644 vendor/github.com/sirupsen/logrus/logrus_test.go delete mode 100644 vendor/github.com/sirupsen/logrus/text_formatter_test.go delete mode 100644 vendor/github.com/spf13/pflag/.gitignore delete mode 100644 vendor/github.com/spf13/pflag/.travis.yml delete mode 100644 vendor/github.com/spf13/pflag/README.md delete mode 100644 vendor/github.com/spf13/pflag/bool_slice_test.go delete mode 100644 vendor/github.com/spf13/pflag/bool_test.go delete mode 100644 vendor/github.com/spf13/pflag/count_test.go delete mode 100644 vendor/github.com/spf13/pflag/example_test.go delete mode 100644 vendor/github.com/spf13/pflag/export_test.go delete mode 100644 vendor/github.com/spf13/pflag/flag_test.go delete mode 100644 vendor/github.com/spf13/pflag/golangflag_test.go delete mode 100644 vendor/github.com/spf13/pflag/int_slice_test.go delete mode 100644 vendor/github.com/spf13/pflag/ip_slice_test.go delete mode 100644 vendor/github.com/spf13/pflag/ip_test.go delete mode 100644 vendor/github.com/spf13/pflag/ipnet_test.go delete mode 100644 vendor/github.com/spf13/pflag/string_array_test.go delete mode 100644 vendor/github.com/spf13/pflag/string_slice_test.go delete mode 100644 vendor/github.com/spf13/pflag/uint_slice_test.go delete mode 100644 vendor/github.com/ugorji/go/README.md delete mode 100644 vendor/github.com/ugorji/go/codec/README.md delete mode 100644 vendor/github.com/ugorji/go/codec/cbor_test.go delete mode 100644 vendor/github.com/ugorji/go/codec/codec_test.go delete mode 100644 vendor/github.com/ugorji/go/codec/codecgen_test.go delete mode 100644 vendor/github.com/ugorji/go/codec/fast-path.go.tmpl delete mode 100644 vendor/github.com/ugorji/go/codec/gen-dec-array.go.tmpl delete mode 100644 vendor/github.com/ugorji/go/codec/gen-dec-map.go.tmpl delete mode 100644 vendor/github.com/ugorji/go/codec/gen-helper.go.tmpl delete mode 100644 vendor/github.com/ugorji/go/codec/helper_test.go delete mode 100755 vendor/github.com/ugorji/go/codec/prebuild.sh delete mode 100644 vendor/github.com/ugorji/go/codec/py_test.go delete mode 100644 vendor/github.com/ugorji/go/codec/test-cbor-goldens.json delete mode 100755 vendor/github.com/ugorji/go/codec/test.py delete mode 100755 vendor/github.com/ugorji/go/codec/tests.sh delete mode 100644 vendor/github.com/ugorji/go/codec/values_test.go delete mode 100644 vendor/github.com/ugorji/go/msgpack.org.md delete mode 100644 vendor/golang.org/x/crypto/.gitattributes delete mode 100644 vendor/golang.org/x/crypto/.gitignore delete mode 100644 vendor/golang.org/x/crypto/CONTRIBUTING.md delete mode 100644 vendor/golang.org/x/crypto/README.md delete mode 100644 vendor/golang.org/x/crypto/codereview.cfg delete mode 100644 vendor/golang.org/x/crypto/ssh/benchmark_test.go delete mode 100644 vendor/golang.org/x/crypto/ssh/buffer.go delete mode 100644 vendor/golang.org/x/crypto/ssh/buffer_test.go delete mode 100644 vendor/golang.org/x/crypto/ssh/certs.go delete mode 100644 vendor/golang.org/x/crypto/ssh/certs_test.go delete mode 100644 vendor/golang.org/x/crypto/ssh/channel.go delete mode 100644 vendor/golang.org/x/crypto/ssh/cipher.go delete mode 100644 vendor/golang.org/x/crypto/ssh/cipher_test.go delete mode 100644 vendor/golang.org/x/crypto/ssh/client.go delete mode 100644 vendor/golang.org/x/crypto/ssh/client_auth.go delete mode 100644 vendor/golang.org/x/crypto/ssh/client_auth_test.go delete mode 100644 vendor/golang.org/x/crypto/ssh/client_test.go delete mode 100644 vendor/golang.org/x/crypto/ssh/common.go delete mode 100644 vendor/golang.org/x/crypto/ssh/connection.go delete mode 100644 vendor/golang.org/x/crypto/ssh/doc.go delete mode 100644 vendor/golang.org/x/crypto/ssh/example_test.go delete mode 100644 vendor/golang.org/x/crypto/ssh/handshake.go delete mode 100644 vendor/golang.org/x/crypto/ssh/handshake_test.go delete mode 100644 vendor/golang.org/x/crypto/ssh/kex.go delete mode 100644 vendor/golang.org/x/crypto/ssh/kex_test.go delete mode 100644 vendor/golang.org/x/crypto/ssh/keys.go delete mode 100644 vendor/golang.org/x/crypto/ssh/keys_test.go delete mode 100644 vendor/golang.org/x/crypto/ssh/mac.go delete mode 100644 vendor/golang.org/x/crypto/ssh/mempipe_test.go delete mode 100644 vendor/golang.org/x/crypto/ssh/messages.go delete mode 100644 vendor/golang.org/x/crypto/ssh/messages_test.go delete mode 100644 vendor/golang.org/x/crypto/ssh/mux.go delete mode 100644 vendor/golang.org/x/crypto/ssh/mux_test.go delete mode 100644 vendor/golang.org/x/crypto/ssh/server.go delete mode 100644 vendor/golang.org/x/crypto/ssh/session.go delete mode 100644 vendor/golang.org/x/crypto/ssh/session_test.go delete mode 100644 vendor/golang.org/x/crypto/ssh/streamlocal.go delete mode 100644 vendor/golang.org/x/crypto/ssh/tcpip.go delete mode 100644 vendor/golang.org/x/crypto/ssh/tcpip_test.go delete mode 100644 vendor/golang.org/x/crypto/ssh/terminal/terminal_test.go delete mode 100644 vendor/golang.org/x/crypto/ssh/testdata_test.go delete mode 100644 vendor/golang.org/x/crypto/ssh/transport.go delete mode 100644 vendor/golang.org/x/crypto/ssh/transport_test.go delete mode 100644 vendor/golang.org/x/net/.gitattributes delete mode 100644 vendor/golang.org/x/net/.gitignore delete mode 100644 vendor/golang.org/x/net/CONTRIBUTING.md delete mode 100644 vendor/golang.org/x/net/README.md delete mode 100644 vendor/golang.org/x/net/codereview.cfg delete mode 100644 vendor/golang.org/x/net/context/context_test.go delete mode 100644 vendor/golang.org/x/net/context/ctxhttp/ctxhttp_17_test.go delete mode 100644 vendor/golang.org/x/net/context/ctxhttp/ctxhttp_pre17_test.go delete mode 100644 vendor/golang.org/x/net/context/ctxhttp/ctxhttp_test.go delete mode 100644 vendor/golang.org/x/net/context/withtimeout_test.go delete mode 100644 vendor/golang.org/x/net/http2/.gitignore delete mode 100644 vendor/golang.org/x/net/http2/Dockerfile delete mode 100644 vendor/golang.org/x/net/http2/Makefile delete mode 100644 vendor/golang.org/x/net/http2/README delete mode 100644 vendor/golang.org/x/net/http2/ciphers_test.go delete mode 100644 vendor/golang.org/x/net/http2/databuffer_test.go delete mode 100644 vendor/golang.org/x/net/http2/errors_test.go delete mode 100644 vendor/golang.org/x/net/http2/flow_test.go delete mode 100644 vendor/golang.org/x/net/http2/frame_test.go delete mode 100644 vendor/golang.org/x/net/http2/go18_test.go delete mode 100644 vendor/golang.org/x/net/http2/go19_test.go delete mode 100644 vendor/golang.org/x/net/http2/gotrack_test.go delete mode 100644 vendor/golang.org/x/net/http2/hpack/encode_test.go delete mode 100644 vendor/golang.org/x/net/http2/hpack/hpack_test.go delete mode 100644 vendor/golang.org/x/net/http2/hpack/tables_test.go delete mode 100644 vendor/golang.org/x/net/http2/http2_test.go delete mode 100644 vendor/golang.org/x/net/http2/pipe_test.go delete mode 100644 vendor/golang.org/x/net/http2/server_push_test.go delete mode 100644 vendor/golang.org/x/net/http2/server_test.go delete mode 100644 vendor/golang.org/x/net/http2/transport_test.go delete mode 100644 vendor/golang.org/x/net/http2/writesched_priority_test.go delete mode 100644 vendor/golang.org/x/net/http2/writesched_random_test.go delete mode 100644 vendor/golang.org/x/net/http2/writesched_test.go delete mode 100644 vendor/golang.org/x/net/http2/z_spec_test.go delete mode 100644 vendor/golang.org/x/net/idna/example_test.go delete mode 100644 vendor/golang.org/x/net/idna/idna_test.go delete mode 100644 vendor/golang.org/x/net/idna/punycode_test.go delete mode 100644 vendor/golang.org/x/net/internal/timeseries/timeseries_test.go delete mode 100644 vendor/golang.org/x/net/lex/httplex/httplex_test.go delete mode 100644 vendor/golang.org/x/net/netutil/listen_test.go delete mode 100644 vendor/golang.org/x/net/trace/histogram_test.go delete mode 100644 vendor/golang.org/x/net/trace/trace_test.go delete mode 100644 vendor/golang.org/x/oauth2/.travis.yml delete mode 100644 vendor/golang.org/x/oauth2/CONTRIBUTING.md delete mode 100644 vendor/golang.org/x/oauth2/README.md delete mode 100644 vendor/golang.org/x/oauth2/example_test.go delete mode 100644 vendor/golang.org/x/oauth2/google/example_test.go delete mode 100644 vendor/golang.org/x/oauth2/google/google_test.go delete mode 100644 vendor/golang.org/x/oauth2/google/jwt_test.go delete mode 100644 vendor/golang.org/x/oauth2/google/sdk_test.go delete mode 100644 vendor/golang.org/x/oauth2/internal/oauth2_test.go delete mode 100644 vendor/golang.org/x/oauth2/internal/token_test.go delete mode 100644 vendor/golang.org/x/oauth2/internal/transport_test.go delete mode 100644 vendor/golang.org/x/oauth2/jws/jws_test.go delete mode 100644 vendor/golang.org/x/oauth2/jwt/example_test.go delete mode 100644 vendor/golang.org/x/oauth2/jwt/jwt_test.go delete mode 100644 vendor/golang.org/x/oauth2/oauth2_test.go delete mode 100644 vendor/golang.org/x/oauth2/token_test.go delete mode 100644 vendor/golang.org/x/oauth2/transport_test.go delete mode 100644 vendor/golang.org/x/sync/CONTRIBUTING.md delete mode 100644 vendor/golang.org/x/sync/README.md delete mode 100644 vendor/golang.org/x/sync/codereview.cfg delete mode 100644 vendor/golang.org/x/sync/errgroup/errgroup_example_md5all_test.go delete mode 100644 vendor/golang.org/x/sync/errgroup/errgroup_test.go delete mode 100644 vendor/golang.org/x/sys/.gitattributes delete mode 100644 vendor/golang.org/x/sys/.gitignore delete mode 100644 vendor/golang.org/x/sys/CONTRIBUTING.md delete mode 100644 vendor/golang.org/x/sys/README.md delete mode 100644 vendor/golang.org/x/sys/codereview.cfg delete mode 100644 vendor/golang.org/x/sys/unix/.gitignore delete mode 100644 vendor/golang.org/x/sys/unix/README.md delete mode 100644 vendor/golang.org/x/sys/unix/creds_test.go delete mode 100644 vendor/golang.org/x/sys/unix/dev_darwin_test.go delete mode 100644 vendor/golang.org/x/sys/unix/dev_dragonfly_test.go delete mode 100644 vendor/golang.org/x/sys/unix/dev_linux_test.go delete mode 100644 vendor/golang.org/x/sys/unix/dev_netbsd_test.go delete mode 100644 vendor/golang.org/x/sys/unix/dev_openbsd_test.go delete mode 100644 vendor/golang.org/x/sys/unix/dev_solaris_test.go delete mode 100644 vendor/golang.org/x/sys/unix/export_test.go delete mode 100755 vendor/golang.org/x/sys/unix/mkall.sh delete mode 100755 vendor/golang.org/x/sys/unix/mkerrors.sh delete mode 100755 vendor/golang.org/x/sys/unix/mksyscall.pl delete mode 100755 vendor/golang.org/x/sys/unix/mksyscall_solaris.pl delete mode 100755 vendor/golang.org/x/sys/unix/mksysctl_openbsd.pl delete mode 100755 vendor/golang.org/x/sys/unix/mksysnum_darwin.pl delete mode 100755 vendor/golang.org/x/sys/unix/mksysnum_dragonfly.pl delete mode 100755 vendor/golang.org/x/sys/unix/mksysnum_freebsd.pl delete mode 100755 vendor/golang.org/x/sys/unix/mksysnum_netbsd.pl delete mode 100755 vendor/golang.org/x/sys/unix/mksysnum_openbsd.pl delete mode 100644 vendor/golang.org/x/sys/unix/mmap_unix_test.go delete mode 100644 vendor/golang.org/x/sys/unix/openbsd_test.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_bsd_test.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_freebsd_test.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_test.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_solaris_test.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_test.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_unix_test.go delete mode 100644 vendor/golang.org/x/sys/windows/registry/export_test.go delete mode 100644 vendor/golang.org/x/sys/windows/registry/registry_test.go delete mode 100644 vendor/golang.org/x/sys/windows/svc/event.go delete mode 100644 vendor/golang.org/x/sys/windows/svc/eventlog/log_test.go delete mode 100644 vendor/golang.org/x/sys/windows/svc/go12.c delete mode 100644 vendor/golang.org/x/sys/windows/svc/go12.go delete mode 100644 vendor/golang.org/x/sys/windows/svc/go13.go delete mode 100644 vendor/golang.org/x/sys/windows/svc/security.go delete mode 100644 vendor/golang.org/x/sys/windows/svc/service.go delete mode 100644 vendor/golang.org/x/sys/windows/svc/svc_test.go delete mode 100644 vendor/golang.org/x/sys/windows/svc/sys_386.s delete mode 100644 vendor/golang.org/x/sys/windows/svc/sys_amd64.s delete mode 100644 vendor/golang.org/x/sys/windows/syscall_test.go delete mode 100644 vendor/golang.org/x/sys/windows/syscall_windows_test.go delete mode 100644 vendor/golang.org/x/text/.gitattributes delete mode 100644 vendor/golang.org/x/text/.gitignore delete mode 100644 vendor/golang.org/x/text/CONTRIBUTING.md delete mode 100644 vendor/golang.org/x/text/README.md delete mode 100644 vendor/golang.org/x/text/codereview.cfg delete mode 100644 vendor/golang.org/x/text/collate/build/builder_test.go delete mode 100644 vendor/golang.org/x/text/collate/build/colelem_test.go delete mode 100644 vendor/golang.org/x/text/collate/build/contract_test.go delete mode 100644 vendor/golang.org/x/text/collate/build/order_test.go delete mode 100644 vendor/golang.org/x/text/collate/build/trie_test.go delete mode 100644 vendor/golang.org/x/text/collate/collate_test.go delete mode 100644 vendor/golang.org/x/text/collate/export_test.go delete mode 100644 vendor/golang.org/x/text/collate/option_test.go delete mode 100644 vendor/golang.org/x/text/collate/reg_test.go delete mode 100644 vendor/golang.org/x/text/collate/sort_test.go delete mode 100644 vendor/golang.org/x/text/collate/table_test.go delete mode 100644 vendor/golang.org/x/text/doc.go delete mode 100644 vendor/golang.org/x/text/gen.go delete mode 100644 vendor/golang.org/x/text/internal/colltab/collate_test.go delete mode 100644 vendor/golang.org/x/text/internal/colltab/collelem_test.go delete mode 100644 vendor/golang.org/x/text/internal/colltab/colltab_test.go delete mode 100644 vendor/golang.org/x/text/internal/colltab/contract_test.go delete mode 100644 vendor/golang.org/x/text/internal/colltab/iter_test.go delete mode 100644 vendor/golang.org/x/text/internal/colltab/numeric_test.go delete mode 100644 vendor/golang.org/x/text/internal/colltab/trie_test.go delete mode 100644 vendor/golang.org/x/text/internal/colltab/weighter_test.go delete mode 100644 vendor/golang.org/x/text/internal/gen.go delete mode 100644 vendor/golang.org/x/text/internal/gen_test.go delete mode 100644 vendor/golang.org/x/text/internal/internal.go delete mode 100644 vendor/golang.org/x/text/internal/internal_test.go delete mode 100644 vendor/golang.org/x/text/internal/match.go delete mode 100644 vendor/golang.org/x/text/internal/match_test.go delete mode 100644 vendor/golang.org/x/text/internal/tables.go delete mode 100644 vendor/golang.org/x/text/internal/tag/tag_test.go delete mode 100644 vendor/golang.org/x/text/internal/triegen/data_test.go delete mode 100644 vendor/golang.org/x/text/internal/triegen/example_compact_test.go delete mode 100644 vendor/golang.org/x/text/internal/triegen/example_test.go delete mode 100644 vendor/golang.org/x/text/internal/triegen/gen_test.go delete mode 100644 vendor/golang.org/x/text/internal/ucd/example_test.go delete mode 100644 vendor/golang.org/x/text/internal/ucd/ucd_test.go delete mode 100644 vendor/golang.org/x/text/language/Makefile delete mode 100644 vendor/golang.org/x/text/language/coverage_test.go delete mode 100644 vendor/golang.org/x/text/language/examples_test.go delete mode 100644 vendor/golang.org/x/text/language/httpexample_test.go delete mode 100644 vendor/golang.org/x/text/language/language_test.go delete mode 100644 vendor/golang.org/x/text/language/lookup_test.go delete mode 100644 vendor/golang.org/x/text/language/match_test.go delete mode 100644 vendor/golang.org/x/text/language/parse_test.go delete mode 100644 vendor/golang.org/x/text/secure/bidirule/bench_test.go delete mode 100644 vendor/golang.org/x/text/secure/bidirule/bidirule_test.go delete mode 100644 vendor/golang.org/x/text/secure/doc.go delete mode 100644 vendor/golang.org/x/text/transform/examples_test.go delete mode 100644 vendor/golang.org/x/text/transform/transform_test.go delete mode 100644 vendor/golang.org/x/text/unicode/bidi/core_test.go delete mode 100644 vendor/golang.org/x/text/unicode/bidi/ranges_test.go delete mode 100644 vendor/golang.org/x/text/unicode/bidi/tables_test.go delete mode 100644 vendor/golang.org/x/text/unicode/cldr/cldr_test.go delete mode 100644 vendor/golang.org/x/text/unicode/cldr/collate_test.go delete mode 100644 vendor/golang.org/x/text/unicode/cldr/data_test.go delete mode 100644 vendor/golang.org/x/text/unicode/cldr/examples_test.go delete mode 100644 vendor/golang.org/x/text/unicode/cldr/resolve_test.go delete mode 100644 vendor/golang.org/x/text/unicode/cldr/slice_test.go delete mode 100644 vendor/golang.org/x/text/unicode/doc.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/composition_test.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/example_iter_test.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/example_test.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/forminfo_test.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/iter_test.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/norm_test.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/normalize_test.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/readwriter_test.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/transform_test.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/ucd_test.go delete mode 100644 vendor/golang.org/x/text/unicode/rangetable/merge_test.go delete mode 100644 vendor/golang.org/x/text/unicode/rangetable/rangetable_test.go delete mode 100644 vendor/golang.org/x/text/width/common_test.go delete mode 100644 vendor/golang.org/x/text/width/example_test.go delete mode 100644 vendor/golang.org/x/text/width/runes_test.go delete mode 100644 vendor/golang.org/x/text/width/tables_test.go delete mode 100644 vendor/golang.org/x/text/width/transform_test.go delete mode 100644 vendor/golang.org/x/time/CONTRIBUTING.md delete mode 100644 vendor/golang.org/x/time/README.md delete mode 100644 vendor/golang.org/x/time/rate/rate_test.go delete mode 100644 vendor/google.golang.org/api/.gitignore delete mode 100644 vendor/google.golang.org/api/.hgtags delete mode 100644 vendor/google.golang.org/api/.travis.yml delete mode 100644 vendor/google.golang.org/api/CONTRIBUTING.md delete mode 100644 vendor/google.golang.org/api/GettingStarted.md delete mode 100644 vendor/google.golang.org/api/NOTES delete mode 100644 vendor/google.golang.org/api/README.md delete mode 100644 vendor/google.golang.org/api/TODO delete mode 100644 vendor/google.golang.org/api/api-list.json delete mode 100644 vendor/google.golang.org/api/compute/v1/compute-api.json delete mode 100644 vendor/google.golang.org/api/gensupport/backoff_test.go delete mode 100644 vendor/google.golang.org/api/gensupport/buffer_test.go delete mode 100644 vendor/google.golang.org/api/gensupport/header_test.go delete mode 100644 vendor/google.golang.org/api/gensupport/json_test.go delete mode 100644 vendor/google.golang.org/api/gensupport/jsonfloat_test.go delete mode 100644 vendor/google.golang.org/api/gensupport/media_test.go delete mode 100644 vendor/google.golang.org/api/gensupport/resumable_test.go delete mode 100644 vendor/google.golang.org/api/gensupport/retry_test.go delete mode 100644 vendor/google.golang.org/api/gensupport/send_test.go delete mode 100644 vendor/google.golang.org/api/gensupport/util_test.go delete mode 100644 vendor/google.golang.org/api/googleapi/googleapi_test.go delete mode 100644 vendor/google.golang.org/api/googleapi/internal/uritemplates/uritemplates_test.go delete mode 100644 vendor/google.golang.org/api/googleapi/types_test.go delete mode 100644 vendor/google.golang.org/api/key.json.enc delete mode 100644 vendor/google.golang.org/appengine/.travis.yml delete mode 100644 vendor/google.golang.org/appengine/README.md delete mode 100644 vendor/google.golang.org/appengine/appengine_test.go delete mode 100644 vendor/google.golang.org/appengine/internal/api_race_test.go delete mode 100644 vendor/google.golang.org/appengine/internal/api_test.go delete mode 100644 vendor/google.golang.org/appengine/internal/app_id_test.go delete mode 100644 vendor/google.golang.org/appengine/internal/app_identity/app_identity_service.proto delete mode 100644 vendor/google.golang.org/appengine/internal/base/api_base.proto delete mode 100755 vendor/google.golang.org/appengine/internal/datastore/datastore_v3.proto delete mode 100644 vendor/google.golang.org/appengine/internal/internal_vm_test.go delete mode 100644 vendor/google.golang.org/appengine/internal/log/log_service.proto delete mode 100644 vendor/google.golang.org/appengine/internal/modules/modules_service.proto delete mode 100644 vendor/google.golang.org/appengine/internal/net_test.go delete mode 100755 vendor/google.golang.org/appengine/internal/regen.sh delete mode 100644 vendor/google.golang.org/appengine/internal/remote_api/remote_api.proto delete mode 100644 vendor/google.golang.org/appengine/internal/urlfetch/urlfetch_service.proto delete mode 100644 vendor/google.golang.org/appengine/namespace_test.go delete mode 100644 vendor/google.golang.org/genproto/.travis.yml delete mode 100644 vendor/google.golang.org/genproto/CONTRIBUTING.md delete mode 100644 vendor/google.golang.org/genproto/README.md delete mode 100644 vendor/google.golang.org/genproto/googleapis/api/authorization_config.pb.go delete mode 100644 vendor/google.golang.org/genproto/googleapis/api/experimental.pb.go delete mode 100644 vendor/google.golang.org/genproto/regen.go delete mode 100755 vendor/google.golang.org/genproto/regen.sh delete mode 100644 vendor/google.golang.org/grpc/.travis.yml delete mode 100644 vendor/google.golang.org/grpc/CONTRIBUTING.md delete mode 100644 vendor/google.golang.org/grpc/Makefile delete mode 100644 vendor/google.golang.org/grpc/README.md delete mode 100644 vendor/google.golang.org/grpc/backoff_test.go delete mode 100644 vendor/google.golang.org/grpc/balancer/roundrobin/roundrobin_test.go delete mode 100644 vendor/google.golang.org/grpc/balancer_switching_test.go delete mode 100644 vendor/google.golang.org/grpc/balancer_test.go delete mode 100644 vendor/google.golang.org/grpc/call_test.go delete mode 100644 vendor/google.golang.org/grpc/clientconn_test.go delete mode 100644 vendor/google.golang.org/grpc/codec_test.go delete mode 100755 vendor/google.golang.org/grpc/codegen.sh delete mode 100644 vendor/google.golang.org/grpc/codes/codes_test.go delete mode 100644 vendor/google.golang.org/grpc/credentials/credentials_test.go delete mode 100644 vendor/google.golang.org/grpc/encoding/proto/proto_benchmark_test.go delete mode 100644 vendor/google.golang.org/grpc/encoding/proto/proto_test.go delete mode 100644 vendor/google.golang.org/grpc/grpclb/grpc_lb_v1/messages/messages.proto delete mode 100644 vendor/google.golang.org/grpc/grpclb/grpclb_test.go delete mode 100644 vendor/google.golang.org/grpc/grpclog/loggerv2_test.go delete mode 100644 vendor/google.golang.org/grpc/metadata/metadata_test.go delete mode 100644 vendor/google.golang.org/grpc/naming/dns_resolver_test.go delete mode 100644 vendor/google.golang.org/grpc/naming/go17_test.go delete mode 100644 vendor/google.golang.org/grpc/naming/go18_test.go delete mode 100644 vendor/google.golang.org/grpc/picker_wrapper_test.go delete mode 100644 vendor/google.golang.org/grpc/pickfirst_test.go delete mode 100644 vendor/google.golang.org/grpc/proxy_test.go delete mode 100644 vendor/google.golang.org/grpc/resolver/dns/dns_resolver_test.go delete mode 100644 vendor/google.golang.org/grpc/resolver/dns/go17_test.go delete mode 100644 vendor/google.golang.org/grpc/resolver/dns/go18_test.go delete mode 100644 vendor/google.golang.org/grpc/resolver_conn_wrapper_test.go delete mode 100644 vendor/google.golang.org/grpc/rpc_util_test.go delete mode 100644 vendor/google.golang.org/grpc/server_test.go delete mode 100644 vendor/google.golang.org/grpc/service_config_test.go delete mode 100644 vendor/google.golang.org/grpc/stats/stats_test.go delete mode 100644 vendor/google.golang.org/grpc/status/status_test.go delete mode 100644 vendor/google.golang.org/grpc/transport/handler_server_test.go delete mode 100644 vendor/google.golang.org/grpc/transport/http_util_test.go delete mode 100644 vendor/google.golang.org/grpc/transport/transport_test.go delete mode 100755 vendor/google.golang.org/grpc/vet.sh delete mode 100644 vendor/gopkg.in/alecthomas/kingpin.v2/.travis.yml delete mode 100644 vendor/gopkg.in/alecthomas/kingpin.v2/README.md delete mode 100644 vendor/gopkg.in/alecthomas/kingpin.v2/app_test.go delete mode 100644 vendor/gopkg.in/alecthomas/kingpin.v2/args_test.go delete mode 100644 vendor/gopkg.in/alecthomas/kingpin.v2/cmd_test.go delete mode 100644 vendor/gopkg.in/alecthomas/kingpin.v2/completions_test.go delete mode 100644 vendor/gopkg.in/alecthomas/kingpin.v2/examples_test.go delete mode 100644 vendor/gopkg.in/alecthomas/kingpin.v2/flags_test.go delete mode 100644 vendor/gopkg.in/alecthomas/kingpin.v2/parser_test.go delete mode 100644 vendor/gopkg.in/alecthomas/kingpin.v2/parsers_test.go delete mode 100644 vendor/gopkg.in/alecthomas/kingpin.v2/usage_test.go delete mode 100644 vendor/gopkg.in/alecthomas/kingpin.v2/values.json delete mode 100644 vendor/gopkg.in/alecthomas/kingpin.v2/values_test.go delete mode 100644 vendor/gopkg.in/fsnotify.v1/.editorconfig delete mode 100644 vendor/gopkg.in/fsnotify.v1/.gitignore delete mode 100644 vendor/gopkg.in/fsnotify.v1/.travis.yml delete mode 100644 vendor/gopkg.in/fsnotify.v1/CHANGELOG.md delete mode 100644 vendor/gopkg.in/fsnotify.v1/CONTRIBUTING.md delete mode 100644 vendor/gopkg.in/fsnotify.v1/README.md delete mode 100644 vendor/gopkg.in/fsnotify.v1/example_test.go delete mode 100644 vendor/gopkg.in/fsnotify.v1/fsnotify_test.go delete mode 100644 vendor/gopkg.in/fsnotify.v1/inotify_poller_test.go delete mode 100644 vendor/gopkg.in/fsnotify.v1/inotify_test.go delete mode 100644 vendor/gopkg.in/fsnotify.v1/integration_darwin_test.go delete mode 100644 vendor/gopkg.in/fsnotify.v1/integration_test.go rename vendor/gopkg.in/{ => fsnotify}/fsnotify.v1/AUTHORS (100%) rename vendor/gopkg.in/{ => fsnotify}/fsnotify.v1/LICENSE (100%) rename vendor/gopkg.in/{ => fsnotify}/fsnotify.v1/fen.go (100%) rename vendor/gopkg.in/{ => fsnotify}/fsnotify.v1/fsnotify.go (100%) rename vendor/gopkg.in/{ => fsnotify}/fsnotify.v1/inotify.go (100%) rename vendor/gopkg.in/{ => fsnotify}/fsnotify.v1/inotify_poller.go (100%) rename vendor/gopkg.in/{ => fsnotify}/fsnotify.v1/kqueue.go (100%) rename vendor/gopkg.in/{ => fsnotify}/fsnotify.v1/open_mode_bsd.go (100%) rename vendor/gopkg.in/{ => fsnotify}/fsnotify.v1/open_mode_darwin.go (100%) rename vendor/gopkg.in/{ => fsnotify}/fsnotify.v1/windows.go (100%) delete mode 100644 vendor/gopkg.in/inf.v0/benchmark_test.go delete mode 100644 vendor/gopkg.in/inf.v0/dec_go1_2_test.go delete mode 100644 vendor/gopkg.in/inf.v0/dec_internal_test.go delete mode 100644 vendor/gopkg.in/inf.v0/dec_test.go delete mode 100644 vendor/gopkg.in/inf.v0/example_test.go delete mode 100644 vendor/gopkg.in/inf.v0/rounder_example_test.go delete mode 100644 vendor/gopkg.in/inf.v0/rounder_test.go delete mode 100644 vendor/gopkg.in/yaml.v2/.travis.yml delete mode 100644 vendor/gopkg.in/yaml.v2/README.md delete mode 100644 vendor/gopkg.in/yaml.v2/decode_test.go delete mode 100644 vendor/gopkg.in/yaml.v2/encode_test.go delete mode 100644 vendor/gopkg.in/yaml.v2/example_embedded_test.go delete mode 100644 vendor/gopkg.in/yaml.v2/suite_test.go delete mode 100644 vendor/k8s.io/apimachinery/README.md delete mode 100644 vendor/k8s.io/apimachinery/kubernetes-sha delete mode 100644 vendor/k8s.io/apimachinery/pkg/OWNERS delete mode 100755 vendor/k8s.io/apimachinery/pkg/api/errors/OWNERS delete mode 100644 vendor/k8s.io/apimachinery/pkg/api/errors/errors_test.go delete mode 100755 vendor/k8s.io/apimachinery/pkg/api/meta/OWNERS delete mode 100644 vendor/k8s.io/apimachinery/pkg/api/meta/multirestmapper_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/api/meta/priority_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/api/meta/restmapper_test.go delete mode 100755 vendor/k8s.io/apimachinery/pkg/api/resource/OWNERS delete mode 100644 vendor/k8s.io/apimachinery/pkg/api/resource/amount_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/api/resource/generated.proto delete mode 100644 vendor/k8s.io/apimachinery/pkg/api/resource/math_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/api/resource/quantity_example_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/api/resource/quantity_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/api/resource/scale_int_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/apimachinery/announced/announced_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/apimachinery/registered/registered_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/apimachinery/types_test.go delete mode 100755 vendor/k8s.io/apimachinery/pkg/apis/meta/v1/OWNERS delete mode 100644 vendor/k8s.io/apimachinery/pkg/apis/meta/v1/duration_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/apis/meta/v1/generated.proto delete mode 100644 vendor/k8s.io/apimachinery/pkg/apis/meta/v1/group_version_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/apis/meta/v1/helpers_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/apis/meta/v1/labels_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/apis/meta/v1/time_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/apis/meta/v1/types_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/conversion/OWNERS delete mode 100644 vendor/k8s.io/apimachinery/pkg/conversion/converter_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/conversion/deep_copy_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/conversion/queryparams/convert_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/fields/fields_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/fields/selector_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/labels/labels_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/labels/selector_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/runtime/OWNERS delete mode 100644 vendor/k8s.io/apimachinery/pkg/runtime/conversion_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/runtime/embedded_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/runtime/extension_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/runtime/generated.proto delete mode 100644 vendor/k8s.io/apimachinery/pkg/runtime/schema/generated.proto delete mode 100644 vendor/k8s.io/apimachinery/pkg/runtime/schema/group_version_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/runtime/scheme_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/runtime/serializer/codec_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/runtime/serializer/json/json_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/runtime/serializer/json/meta_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/runtime/serializer/streaming/streaming_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/runtime/serializer/versioning/versioning_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/runtime/swagger_doc_generator_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/diff/diff_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/errors/errors_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/framer/framer_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/intstr/generated.proto delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/intstr/intstr_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/json/json_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/net/http_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/net/interface_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/net/port_range_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/net/port_split_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/net/util_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/rand/rand_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/runtime/runtime_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/sets/set_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/validation/field/errors_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/validation/field/path_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/validation/validation_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/wait/wait_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/yaml/decoder_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/watch/filter_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/watch/mux_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/watch/streamwatcher_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/watch/watch_test.go delete mode 100644 vendor/k8s.io/apimachinery/third_party/forked/golang/reflect/deep_equal_test.go delete mode 100644 vendor/k8s.io/client-go/.travis.yml delete mode 100644 vendor/k8s.io/client-go/CHANGELOG.md delete mode 100644 vendor/k8s.io/client-go/INSTALL.md delete mode 100644 vendor/k8s.io/client-go/OWNERS delete mode 100644 vendor/k8s.io/client-go/README.md delete mode 100644 vendor/k8s.io/client-go/discovery/discovery_client_test.go delete mode 100644 vendor/k8s.io/client-go/discovery/helper_blackbox_test.go delete mode 100644 vendor/k8s.io/client-go/discovery/restmapper_test.go create mode 100644 vendor/k8s.io/client-go/informers/extensions/v1beta1/thirdpartyresource.go delete mode 100644 vendor/k8s.io/client-go/kubernetes-sha create mode 100644 vendor/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/fake/fake_thirdpartyresource.go create mode 100644 vendor/k8s.io/client-go/listers/extensions/v1beta1/thirdpartyresource.go delete mode 100644 vendor/k8s.io/client-go/pkg/api/OWNERS delete mode 100755 vendor/k8s.io/client-go/pkg/api/install/OWNERS delete mode 100755 vendor/k8s.io/client-go/pkg/api/v1/OWNERS delete mode 100644 vendor/k8s.io/client-go/pkg/api/v1/generated.proto delete mode 100755 vendor/k8s.io/client-go/pkg/apis/apps/OWNERS delete mode 100644 vendor/k8s.io/client-go/pkg/apis/apps/v1beta1/generated.proto delete mode 100755 vendor/k8s.io/client-go/pkg/apis/authentication/OWNERS delete mode 100644 vendor/k8s.io/client-go/pkg/apis/authentication/v1/generated.proto delete mode 100644 vendor/k8s.io/client-go/pkg/apis/authentication/v1beta1/generated.proto delete mode 100755 vendor/k8s.io/client-go/pkg/apis/authorization/OWNERS delete mode 100644 vendor/k8s.io/client-go/pkg/apis/authorization/v1/generated.proto delete mode 100644 vendor/k8s.io/client-go/pkg/apis/authorization/v1beta1/generated.proto delete mode 100755 vendor/k8s.io/client-go/pkg/apis/autoscaling/OWNERS delete mode 100644 vendor/k8s.io/client-go/pkg/apis/autoscaling/v1/generated.proto delete mode 100644 vendor/k8s.io/client-go/pkg/apis/autoscaling/v2alpha1/generated.proto delete mode 100755 vendor/k8s.io/client-go/pkg/apis/batch/OWNERS delete mode 100644 vendor/k8s.io/client-go/pkg/apis/batch/v1/generated.proto delete mode 100644 vendor/k8s.io/client-go/pkg/apis/batch/v2alpha1/generated.proto delete mode 100755 vendor/k8s.io/client-go/pkg/apis/certificates/OWNERS delete mode 100644 vendor/k8s.io/client-go/pkg/apis/certificates/v1beta1/generated.proto delete mode 100755 vendor/k8s.io/client-go/pkg/apis/extensions/OWNERS delete mode 100644 vendor/k8s.io/client-go/pkg/apis/extensions/v1beta1/generated.proto delete mode 100755 vendor/k8s.io/client-go/pkg/apis/policy/OWNERS delete mode 100644 vendor/k8s.io/client-go/pkg/apis/policy/v1beta1/generated.proto delete mode 100755 vendor/k8s.io/client-go/pkg/apis/rbac/OWNERS delete mode 100644 vendor/k8s.io/client-go/pkg/apis/rbac/v1alpha1/generated.proto delete mode 100644 vendor/k8s.io/client-go/pkg/apis/rbac/v1beta1/generated.proto delete mode 100644 vendor/k8s.io/client-go/pkg/apis/settings/v1alpha1/generated.proto delete mode 100755 vendor/k8s.io/client-go/pkg/apis/storage/OWNERS delete mode 100644 vendor/k8s.io/client-go/pkg/apis/storage/v1/generated.proto delete mode 100644 vendor/k8s.io/client-go/pkg/apis/storage/v1beta1/generated.proto delete mode 100644 vendor/k8s.io/client-go/pkg/version/.gitattributes delete mode 100755 vendor/k8s.io/client-go/rest/OWNERS delete mode 100644 vendor/k8s.io/client-go/rest/client_test.go delete mode 100644 vendor/k8s.io/client-go/rest/config_test.go delete mode 100644 vendor/k8s.io/client-go/rest/plugin_test.go delete mode 100755 vendor/k8s.io/client-go/rest/request_test.go delete mode 100644 vendor/k8s.io/client-go/rest/url_utils_test.go delete mode 100644 vendor/k8s.io/client-go/rest/urlbackoff_test.go delete mode 100644 vendor/k8s.io/client-go/rest/watch/decoder_test.go delete mode 100644 vendor/k8s.io/client-go/rest/watch/encoder_test.go delete mode 100755 vendor/k8s.io/client-go/tools/cache/OWNERS delete mode 100644 vendor/k8s.io/client-go/tools/cache/controller_test.go delete mode 100644 vendor/k8s.io/client-go/tools/cache/delta_fifo_test.go delete mode 100644 vendor/k8s.io/client-go/tools/cache/expiration_cache_test.go delete mode 100644 vendor/k8s.io/client-go/tools/cache/fifo_test.go delete mode 100644 vendor/k8s.io/client-go/tools/cache/index_test.go delete mode 100644 vendor/k8s.io/client-go/tools/cache/mutation_detector_test.go delete mode 100644 vendor/k8s.io/client-go/tools/cache/processor_listener_test.go delete mode 100644 vendor/k8s.io/client-go/tools/cache/reflector_test.go delete mode 100644 vendor/k8s.io/client-go/tools/cache/shared_informer_test.go delete mode 100644 vendor/k8s.io/client-go/tools/cache/store_test.go delete mode 100644 vendor/k8s.io/client-go/tools/cache/undelta_store_test.go delete mode 100644 vendor/k8s.io/client-go/tools/clientcmd/api/helpers_test.go delete mode 100644 vendor/k8s.io/client-go/tools/clientcmd/api/types_test.go delete mode 100644 vendor/k8s.io/client-go/tools/clientcmd/auth_loaders.go delete mode 100644 vendor/k8s.io/client-go/tools/clientcmd/client_config.go delete mode 100644 vendor/k8s.io/client-go/tools/clientcmd/client_config_test.go delete mode 100644 vendor/k8s.io/client-go/tools/clientcmd/config.go delete mode 100644 vendor/k8s.io/client-go/tools/clientcmd/doc.go delete mode 100644 vendor/k8s.io/client-go/tools/clientcmd/helpers.go delete mode 100644 vendor/k8s.io/client-go/tools/clientcmd/loader.go delete mode 100644 vendor/k8s.io/client-go/tools/clientcmd/loader_test.go delete mode 100644 vendor/k8s.io/client-go/tools/clientcmd/merged_client_builder.go delete mode 100644 vendor/k8s.io/client-go/tools/clientcmd/merged_client_builder_test.go delete mode 100644 vendor/k8s.io/client-go/tools/clientcmd/overrides.go delete mode 100644 vendor/k8s.io/client-go/tools/clientcmd/validation.go delete mode 100644 vendor/k8s.io/client-go/tools/clientcmd/validation_test.go delete mode 100755 vendor/k8s.io/client-go/tools/metrics/OWNERS delete mode 100755 vendor/k8s.io/client-go/transport/OWNERS delete mode 100644 vendor/k8s.io/client-go/transport/cache_test.go delete mode 100644 vendor/k8s.io/client-go/transport/round_trippers_test.go delete mode 100644 vendor/k8s.io/client-go/transport/transport_test.go delete mode 100644 vendor/k8s.io/client-go/util/cert/csr_test.go delete mode 100644 vendor/k8s.io/client-go/util/clock/clock_test.go delete mode 100644 vendor/k8s.io/client-go/util/flowcontrol/backoff_test.go delete mode 100644 vendor/k8s.io/client-go/util/flowcontrol/throttle_test.go delete mode 100644 vendor/k8s.io/client-go/util/integer/integer_test.go create mode 100644 vendor/k8s.io/client-go/util/workqueue/default_rate_limiters.go create mode 100644 vendor/k8s.io/client-go/util/workqueue/delaying_queue.go rename vendor/k8s.io/{apimachinery/pkg/conversion/helper_test.go => client-go/util/workqueue/doc.go} (51%) create mode 100644 vendor/k8s.io/client-go/util/workqueue/metrics.go create mode 100644 vendor/k8s.io/client-go/util/workqueue/parallelizer.go create mode 100644 vendor/k8s.io/client-go/util/workqueue/queue.go create mode 100644 vendor/k8s.io/client-go/util/workqueue/rate_limitting_queue.go create mode 100644 vendor/k8s.io/client-go/util/workqueue/timed_queue.go diff --git a/Gopkg.lock b/Gopkg.lock index 05b3ad688..a3eeb5921 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -205,10 +205,8 @@ [[projects]] name = "github.com/gogo/protobuf" packages = [ - "gogoproto", "jsonpb", "proto", - "protoc-gen-gogo/descriptor", "sortkeys", "types" ] @@ -312,6 +310,12 @@ packages = ["."] revision = "0b12d6b5" +[[projects]] + name = "github.com/json-iterator/go" + packages = ["."] + revision = "1624edc4454b8682399def8740d46db5e4362ba4" + version = "1.1.5" + [[projects]] branch = "master" name = "github.com/juju/ratelimit" @@ -362,6 +366,18 @@ packages = ["."] revision = "b8bc1bf767474819792c23f32d8286a45736f1c6" +[[projects]] + name = "github.com/modern-go/concurrent" + packages = ["."] + revision = "bacd9c7ef1dd9b15be4a9909b8ac7a4e313eec94" + version = "1.0.3" + +[[projects]] + name = "github.com/modern-go/reflect2" + packages = ["."] + revision = "4b7aa43c6742a2c18fdef89dd197aaae7dac7ccd" + version = "1.0.1" + [[projects]] branch = "master" name = "github.com/mwitkow/go-conntrack" @@ -409,10 +425,13 @@ version = "v0.8.0" [[projects]] + branch = "master" name = "github.com/prometheus/client_golang" - packages = ["prometheus"] - revision = "c5b7fccd204277076155f10851dad72b76a49317" - version = "v0.8.0" + packages = [ + "prometheus", + "prometheus/promhttp" + ] + revision = "5b23715facdef1452016bae512489c3cdf82458c" [[projects]] branch = "master" @@ -421,7 +440,7 @@ revision = "6f3806018612930941127f2a7c6c453ba2c527d2" [[projects]] - branch = "tjackson_fork_22" + branch = "tjackson_fork_23" name = "github.com/prometheus/common" packages = [ "config", @@ -433,7 +452,7 @@ "route", "version" ] - revision = "ced8cc405cc4476542fb62641ebe80f07fb5c31d" + revision = "b6328fa22d05e30e511feed43277a9165c159ddb" source = "github.com/jacksontj/common" [[projects]] @@ -446,7 +465,7 @@ revision = "e645f4e5aaa8506fc71d6edbc5c4ff02c04c46f2" [[projects]] - branch = "release-2.2_fork_promxy" + branch = "release-2.3_fork_promxy" name = "github.com/prometheus/prometheus" packages = [ "config", @@ -486,13 +505,12 @@ "util/strutil", "util/testutil", "util/treecache", - "util/yaml", "web", "web/api/v1", "web/api/v2", "web/ui" ] - revision = "9afbbc0c5df386ab546cb8522fa3dc132eb2650b" + revision = "3e594b7652fc5fa1265b75cd429995bf5949f363" source = "github.com/jacksontj/prometheus" [[projects]] @@ -690,10 +708,9 @@ version = "v2.2.5" [[projects]] - name = "gopkg.in/fsnotify.v1" + name = "gopkg.in/fsnotify/fsnotify.v1" packages = ["."] revision = "c2828203cd70a50dcccfb2761f8b1f8ceef9a8e9" - source = "github.com/fsnotify/fsnotify" version = "v1.4.7" [[projects]] @@ -831,7 +848,8 @@ "util/cert", "util/clock", "util/flowcontrol", - "util/integer" + "util/integer", + "util/workqueue" ] revision = "21300e3e11c918b8e6a70fb7293b310683d6c046" version = "v3.0.0" @@ -839,6 +857,6 @@ [solve-meta] analyzer-name = "dep" analyzer-version = 1 - inputs-digest = "6d309226eb6f92c04c79779c8e3b3ec609cf4b263d3bbe9e454abcb8864fe4ad" + inputs-digest = "d9a759a37e1301cb3968d3700610da155eafd5698d7a757effaa43854d18f31e" solver-name = "gps-cdcl" solver-version = 1 diff --git a/Gopkg.toml b/Gopkg.toml index 7cde8ec8c..483e2986b 100644 --- a/Gopkg.toml +++ b/Gopkg.toml @@ -12,12 +12,12 @@ version = "1.1.0" [[constraint]] - branch = "tjackson_fork_22" + branch = "tjackson_fork_23" name = "github.com/prometheus/common" source = "github.com/jacksontj/common" [[constraint]] - branch = "release-2.2_fork_promxy" + branch = "release-2.3_fork_promxy" name = "github.com/prometheus/prometheus" source = "github.com/jacksontj/prometheus" @@ -29,6 +29,10 @@ branch = "v2" name = "gopkg.in/yaml.v2" +[[constraint]] + branch = "master" + name = "github.com/prometheus/client_golang" + # Force some transitive stuffs [[override]] name = "github.com/hashicorp/consul" diff --git a/proxyquerier/querier.go b/proxyquerier/querier.go index 47dc1c40d..4eeb96df7 100644 --- a/proxyquerier/querier.go +++ b/proxyquerier/querier.go @@ -9,6 +9,7 @@ import ( "github.com/jacksontj/promxy/servergroup" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/prometheus/pkg/labels" + "github.com/prometheus/prometheus/pkg/timestamp" "github.com/prometheus/prometheus/storage" "github.com/sirupsen/logrus" ) @@ -44,7 +45,7 @@ func (h *ProxyQuerier) Select(selectParams *storage.SelectParams, matchers ...*l }).Debug("Select") }() - result, err := h.ServerGroups.GetValue(h.Ctx, h.Start, h.End, matchers) + result, err := h.ServerGroups.GetValue(h.Ctx, timestamp.Time(selectParams.Start), timestamp.Time(selectParams.End), matchers) if err != nil { return nil, err } diff --git a/proxystorage/proxy.go b/proxystorage/proxy.go index 23e1b2633..5e2d7fbf2 100644 --- a/proxystorage/proxy.go +++ b/proxystorage/proxy.go @@ -161,7 +161,7 @@ func (p *ProxyStorage) NodeReplacer(ctx context.Context, s *promql.EvalStmt, nod visitor := &OffsetFinder{} if _, err := promql.Walk(ctx, visitor, s, node, nil, nil); err != nil { - return nil, err + return nil, nil } // If we couldn't find an offset, then something is wrong-- lets skip // Also if there was an error, skip diff --git a/servergroup/servergroup.go b/servergroup/servergroup.go index 51127f5fb..0f4fce913 100644 --- a/servergroup/servergroup.go +++ b/servergroup/servergroup.go @@ -21,7 +21,6 @@ import ( "github.com/prometheus/prometheus/promql" "github.com/prometheus/prometheus/relabel" "github.com/prometheus/prometheus/storage/remote" - httputil "github.com/prometheus/prometheus/util/httputil" sd_config "github.com/prometheus/prometheus/discovery/config" ) @@ -118,7 +117,7 @@ func (s *ServerGroup) ApplyConfig(cfg *Config) error { // stage the client swap as well // TODO: better name - client, err := httputil.NewClientFromConfig(cfg.HTTPConfig, "somename") + client, err := config_util.NewClientFromConfig(cfg.HTTPConfig, "somename") if err != nil { return fmt.Errorf("Unable to load client from config: %s", err) } @@ -226,7 +225,7 @@ func (s *ServerGroup) RemoteRead(ctx context.Context, start, end time.Time, matc } start := time.Now() - query, err := remote.ToQuery(int64(timestamp.FromTime(start)), int64(timestamp.FromTime(end)), matchers) + query, err := remote.ToQuery(int64(timestamp.FromTime(start)), int64(timestamp.FromTime(end)), matchers, nil) if err != nil { retChan <- err return diff --git a/vendor/cloud.google.com/go/.travis.yml b/vendor/cloud.google.com/go/.travis.yml deleted file mode 100644 index 8c769d71f..000000000 --- a/vendor/cloud.google.com/go/.travis.yml +++ /dev/null @@ -1,16 +0,0 @@ -sudo: false -language: go -go: -- 1.6 -- 1.7 -- 1.8 -install: -- go get -v cloud.google.com/go/... -script: -- openssl aes-256-cbc -K $encrypted_a8b3f4fc85f4_key -iv $encrypted_a8b3f4fc85f4_iv -in key.json.enc -out key.json -d -- GCLOUD_TESTS_GOLANG_PROJECT_ID="dulcet-port-762" GCLOUD_TESTS_GOLANG_KEY="$(pwd)/key.json" - ./run-tests.sh $TRAVIS_COMMIT -env: - matrix: - # The GCLOUD_TESTS_API_KEY environment variable. - secure: VdldogUOoubQ60LhuHJ+g/aJoBiujkSkWEWl79Zb8cvQorcQbxISS+JsOOp4QkUOU4WwaHAm8/3pIH1QMWOR6O78DaLmDKi5Q4RpkVdCpUXy+OAfQaZIcBsispMrjxLXnqFjo9ELnrArfjoeCTzaX0QTCfwQwVmigC8rR30JBKI= diff --git a/vendor/cloud.google.com/go/CONTRIBUTING.md b/vendor/cloud.google.com/go/CONTRIBUTING.md deleted file mode 100644 index f99b50d0e..000000000 --- a/vendor/cloud.google.com/go/CONTRIBUTING.md +++ /dev/null @@ -1,144 +0,0 @@ -# Contributing - -1. Sign one of the contributor license agreements below. -1. `go get golang.org/x/review/git-codereview` to install the code reviewing tool. - 1. You will need to ensure that your `GOBIN` directory (by default - `$GOPATH/bin`) is in your `PATH` so that git can find the command. - 1. If you would like, you may want to set up aliases for git-codereview, - such that `git codereview change` becomes `git change`. See the - [godoc](https://godoc.org/golang.org/x/review/git-codereview) for details. - 1. Should you run into issues with the git-codereview tool, please note - that all error messages will assume that you have set up these - aliases. -1. Get the cloud package by running `go get -d cloud.google.com/go`. - 1. If you have already checked out the source, make sure that the remote git - origin is https://code.googlesource.com/gocloud: - - git remote set-url origin https://code.googlesource.com/gocloud -1. Make sure your auth is configured correctly by visiting - https://code.googlesource.com, clicking "Generate Password", and following - the directions. -1. Make changes and create a change by running `git codereview change `, -provide a commit message, and use `git codereview mail` to create a Gerrit CL. -1. Keep amending to the change with `git codereview change` and mail as your receive -feedback. Each new mailed amendment will create a new patch set for your change in Gerrit. - -## Integration Tests - -In addition to the unit tests, you may run the integration test suite. - -To run the integrations tests, creating and configuration of a project in the -Google Developers Console is required. - -After creating a project, you must [create a service account](https://developers.google.com/identity/protocols/OAuth2ServiceAccount#creatinganaccount). -Ensure the project-level **Owner** [IAM role](console.cloud.google.com/iam-admin/iam/project) -(or **Editor** and **Logs Configuration Writer** roles) are added to the -service account. - -Once you create a project, set the following environment variables to be able to -run the against the actual APIs. - -- **GCLOUD_TESTS_GOLANG_PROJECT_ID**: Developers Console project's ID (e.g. bamboo-shift-455) -- **GCLOUD_TESTS_GOLANG_KEY**: The path to the JSON key file. -- **GCLOUD_TESTS_API_KEY**: Your API key. - -Firestore requires a different project and key: - -- **GCLOUD_TESTS_GOLANG_FIRESTORE_PROJECT_ID**: Developers Console project's ID - supporting Firestore -- **GCLOUD_TESTS_GOLANG_FIRESTORE_KEY**: The path to the JSON key file. - -Install the [gcloud command-line tool][gcloudcli] to your machine and use it -to create some resources used in integration tests. - -From the project's root directory: - -``` sh -# Set the default project in your env. -$ gcloud config set project $GCLOUD_TESTS_GOLANG_PROJECT_ID - -# Authenticate the gcloud tool with your account. -$ gcloud auth login - -# Create the indexes used in the datastore integration tests. -$ gcloud preview datastore create-indexes datastore/testdata/index.yaml - -# Create a Google Cloud storage bucket with the same name as your test project, -# and with the Stackdriver Logging service account as owner, for the sink -# integration tests in logging. -$ gsutil mb gs://$GCLOUD_TESTS_GOLANG_PROJECT_ID -$ gsutil acl ch -g cloud-logs@google.com:O gs://$GCLOUD_TESTS_GOLANG_PROJECT_ID - -# Create a Spanner instance for the spanner integration tests. -$ gcloud beta spanner instances create go-integration-test --config regional-us-central1 --nodes 1 --description 'Instance for go client test' -# NOTE: Spanner instances are priced by the node-hour, so you may want to delete -# the instance after testing with 'gcloud beta spanner instances delete'. -``` - -Once you've set the environment variables, you can run the integration tests by -running: - -``` sh -$ go test -v cloud.google.com/go/... -``` - -## Contributor License Agreements - -Before we can accept your pull requests you'll need to sign a Contributor -License Agreement (CLA): - -- **If you are an individual writing original source code** and **you own the -- intellectual property**, then you'll need to sign an [individual CLA][indvcla]. -- **If you work for a company that wants to allow you to contribute your work**, -then you'll need to sign a [corporate CLA][corpcla]. - -You can sign these electronically (just scroll to the bottom). After that, -we'll be able to accept your pull requests. - -## Contributor Code of Conduct - -As contributors and maintainers of this project, -and in the interest of fostering an open and welcoming community, -we pledge to respect all people who contribute through reporting issues, -posting feature requests, updating documentation, -submitting pull requests or patches, and other activities. - -We are committed to making participation in this project -a harassment-free experience for everyone, -regardless of level of experience, gender, gender identity and expression, -sexual orientation, disability, personal appearance, -body size, race, ethnicity, age, religion, or nationality. - -Examples of unacceptable behavior by participants include: - -* The use of sexualized language or imagery -* Personal attacks -* Trolling or insulting/derogatory comments -* Public or private harassment -* Publishing other's private information, -such as physical or electronic -addresses, without explicit permission -* Other unethical or unprofessional conduct. - -Project maintainers have the right and responsibility to remove, edit, or reject -comments, commits, code, wiki edits, issues, and other contributions -that are not aligned to this Code of Conduct. -By adopting this Code of Conduct, -project maintainers commit themselves to fairly and consistently -applying these principles to every aspect of managing this project. -Project maintainers who do not follow or enforce the Code of Conduct -may be permanently removed from the project team. - -This code of conduct applies both within project spaces and in public spaces -when an individual is representing the project or its community. - -Instances of abusive, harassing, or otherwise unacceptable behavior -may be reported by opening an issue -or contacting one or more of the project maintainers. - -This Code of Conduct is adapted from the [Contributor Covenant](http://contributor-covenant.org), version 1.2.0, -available at [http://contributor-covenant.org/version/1/2/0/](http://contributor-covenant.org/version/1/2/0/) - -[gcloudcli]: https://developers.google.com/cloud/sdk/gcloud/ -[indvcla]: https://developers.google.com/open-source/cla/individual -[corpcla]: https://developers.google.com/open-source/cla/corporate diff --git a/vendor/cloud.google.com/go/MIGRATION.md b/vendor/cloud.google.com/go/MIGRATION.md deleted file mode 100644 index 791210de1..000000000 --- a/vendor/cloud.google.com/go/MIGRATION.md +++ /dev/null @@ -1,54 +0,0 @@ -# Code Changes - -## v0.10.0 - -- pubsub: Replace - - ``` - sub.ModifyPushConfig(ctx, pubsub.PushConfig{Endpoint: "https://example.com/push"}) - ``` - - with - - ``` - sub.Update(ctx, pubsub.SubscriptionConfigToUpdate{ - PushConfig: &pubsub.PushConfig{Endpoint: "https://example.com/push"}, - }) - ``` - -- trace: traceGRPCServerInterceptor will be provided from *trace.Client. -Given an initialized `*trace.Client` named `tc`, instead of - - ``` - s := grpc.NewServer(grpc.UnaryInterceptor(trace.GRPCServerInterceptor(tc))) - ``` - - write - - ``` - s := grpc.NewServer(grpc.UnaryInterceptor(tc.GRPCServerInterceptor())) - ``` - -- trace trace.GRPCClientInterceptor will also provided from *trace.Client. -Instead of - - ``` - conn, err := grpc.Dial(srv.Addr, grpc.WithUnaryInterceptor(trace.GRPCClientInterceptor())) - ``` - - write - - ``` - conn, err := grpc.Dial(srv.Addr, grpc.WithUnaryInterceptor(tc.GRPCClientInterceptor())) - ``` - -- trace: We removed the deprecated `trace.EnableGRPCTracing`. Use the gRPC -interceptor as a dial option as shown below when initializing Cloud package -clients: - - ``` - c, err := pubsub.NewClient(ctx, "project-id", option.WithGRPCDialOption(grpc.WithUnaryInterceptor(tc.GRPCClientInterceptor()))) - if err != nil { - ... - } - ``` diff --git a/vendor/cloud.google.com/go/README.md b/vendor/cloud.google.com/go/README.md deleted file mode 100644 index 1e0e241d6..000000000 --- a/vendor/cloud.google.com/go/README.md +++ /dev/null @@ -1,514 +0,0 @@ -# Google Cloud Client Libraries for Go - -[![GoDoc](https://godoc.org/cloud.google.com/go?status.svg)](https://godoc.org/cloud.google.com/go) - -Go packages for [Google Cloud Platform](https://cloud.google.com) services. - -``` go -import "cloud.google.com/go" -``` - -To install the packages on your system, - -``` -$ go get -u cloud.google.com/go/... -``` - -**NOTE:** Some of these packages are under development, and may occasionally -make backwards-incompatible changes. - -**NOTE:** Github repo is a mirror of [https://code.googlesource.com/gocloud](https://code.googlesource.com/gocloud). - - * [News](#news) - * [Supported APIs](#supported-apis) - * [Go Versions Supported](#go-versions-supported) - * [Authorization](#authorization) - * [Cloud Datastore](#cloud-datastore-) - * [Cloud Storage](#cloud-storage-) - * [Cloud Pub/Sub](#cloud-pub-sub-) - * [Cloud BigQuery](#cloud-bigquery-) - * [Stackdriver Logging](#stackdriver-logging-) - * [Cloud Spanner](#cloud-spanner-) - - -## News - -*v0.15.0* - -_October 3, 2017_ - -- firestore: beta release. See the - [announcement](https://firebase.googleblog.com/2017/10/introducing-cloud-firestore.html). - -- errorreporting: The existing package has been redesigned. - -- errors: This package has been removed. Use errorreporting. - - -_September 28, 2017_ - -*v0.14.0* - -- bigquery BREAKING CHANGES: - - Standard SQL is the default for queries and views. - - `Table.Create` takes `TableMetadata` as a second argument, instead of - options. - - `Dataset.Create` takes `DatasetMetadata` as a second argument. - - `DatasetMetadata` field `ID` renamed to `FullID` - - `TableMetadata` field `ID` renamed to `FullID` - -- Other bigquery changes: - - The client will append a random suffix to a provided job ID if you set - `AddJobIDSuffix` to true in a job config. - - Listing jobs is supported. - - Better retry logic. - -- vision, language, speech: clients are now stable - -- monitoring: client is now beta - -- profiler: - - Rename InstanceName to Instance, ZoneName to Zone - - Auto-detect service name and version on AppEngine. - -_September 8, 2017_ - -*v0.13.0* - -- bigquery: UseLegacySQL options for CreateTable and QueryConfig. Use these - options to continue using Legacy SQL after the client switches its default - to Standard SQL. - -- bigquery: Support for updating dataset labels. - -- bigquery: Set DatasetIterator.ProjectID to list datasets in a project other - than the client's. DatasetsInProject is no longer needed and is deprecated. - -- bigtable: Fail ListInstances when any zones fail. - -- spanner: support decoding of slices of basic types (e.g. []string, []int64, - etc.) - -- logging/logadmin: UpdateSink no longer creates a sink if it is missing - (actually a change to the underlying service, not the client) - -- profiler: Service and ServiceVersion replace Target in Config. - -_August 22, 2017_ - -*v0.12.0* - -- pubsub: Subscription.Receive now uses streaming pull. - -- pubsub: add Client.TopicInProject to access topics in a different project - than the client. - -- errors: renamed errorreporting. The errors package will be removed shortly. - -- datastore: improved retry behavior. - -- bigquery: support updates to dataset metadata, with etags. - -- bigquery: add etag support to Table.Update (BREAKING: etag argument added). - -- bigquery: generate all job IDs on the client. - -- storage: support bucket lifecycle configurations. - - -[Older news](https://github.com/GoogleCloudPlatform/google-cloud-go/blob/master/old-news.md) - -## Supported APIs - -Google API | Status | Package ----------------------------------|--------------|----------------------------------------------------------- -[Datastore][cloud-datastore] | stable | [`cloud.google.com/go/datastore`][cloud-datastore-ref] -[Firestore][cloud-firestore] | beta | [`cloud.google.com/go/firestore`][cloud-firestore-ref] -[Storage][cloud-storage] | stable | [`cloud.google.com/go/storage`][cloud-storage-ref] -[Bigtable][cloud-bigtable] | beta | [`cloud.google.com/go/bigtable`][cloud-bigtable-ref] -[BigQuery][cloud-bigquery] | beta | [`cloud.google.com/go/bigquery`][cloud-bigquery-ref] -[Logging][cloud-logging] | stable | [`cloud.google.com/go/logging`][cloud-logging-ref] -[Monitoring][cloud-monitoring] | beta | [`cloud.google.com/go/monitoring/apiv3`][cloud-monitoring-ref] -[Pub/Sub][cloud-pubsub] | beta | [`cloud.google.com/go/pubsub`][cloud-pubsub-ref] -[Vision][cloud-vision] | stable | [`cloud.google.com/go/vision/apiv1`][cloud-vision-ref] -[Language][cloud-language] | stable | [`cloud.google.com/go/language/apiv1`][cloud-language-ref] -[Speech][cloud-speech] | stable | [`cloud.google.com/go/speech/apiv1`][cloud-speech-ref] -[Spanner][cloud-spanner] | beta | [`cloud.google.com/go/spanner`][cloud-spanner-ref] -[Translation][cloud-translation] | stable | [`cloud.google.com/go/translate`][cloud-translation-ref] -[Trace][cloud-trace] | alpha | [`cloud.google.com/go/trace`][cloud-trace-ref] -[Video Intelligence][cloud-video]| beta | [`cloud.google.com/go/videointelligence/apiv1beta1`][cloud-video-ref] -[ErrorReporting][cloud-errors] | alpha | [`cloud.google.com/go/errorreporting`][cloud-errors-ref] - - -> **Alpha status**: the API is still being actively developed. As a -> result, it might change in backward-incompatible ways and is not recommended -> for production use. -> -> **Beta status**: the API is largely complete, but still has outstanding -> features and bugs to be addressed. There may be minor backwards-incompatible -> changes where necessary. -> -> **Stable status**: the API is mature and ready for production use. We will -> continue addressing bugs and feature requests. - -Documentation and examples are available at -https://godoc.org/cloud.google.com/go - -Visit or join the -[google-api-go-announce group](https://groups.google.com/forum/#!forum/google-api-go-announce) -for updates on these packages. - -## Go Versions Supported - -We support the two most recent major versions of Go. If Google App Engine uses -an older version, we support that as well. You can see which versions are -currently supported by looking at the lines following `go:` in -[`.travis.yml`](.travis.yml). - -## Authorization - -By default, each API will use [Google Application Default Credentials][default-creds] -for authorization credentials used in calling the API endpoints. This will allow your -application to run in many environments without requiring explicit configuration. - -[snip]:# (auth) -```go -client, err := storage.NewClient(ctx) -``` - -To authorize using a -[JSON key file](https://cloud.google.com/iam/docs/managing-service-account-keys), -pass -[`option.WithServiceAccountFile`](https://godoc.org/google.golang.org/api/option#WithServiceAccountFile) -to the `NewClient` function of the desired package. For example: - -[snip]:# (auth-JSON) -```go -client, err := storage.NewClient(ctx, option.WithServiceAccountFile("path/to/keyfile.json")) -``` - -You can exert more control over authorization by using the -[`golang.org/x/oauth2`](https://godoc.org/golang.org/x/oauth2) package to -create an `oauth2.TokenSource`. Then pass -[`option.WithTokenSource`](https://godoc.org/google.golang.org/api/option#WithTokenSource) -to the `NewClient` function: -[snip]:# (auth-ts) -```go -tokenSource := ... -client, err := storage.NewClient(ctx, option.WithTokenSource(tokenSource)) -``` - -## Cloud Datastore [![GoDoc](https://godoc.org/cloud.google.com/go/datastore?status.svg)](https://godoc.org/cloud.google.com/go/datastore) - -- [About Cloud Datastore][cloud-datastore] -- [Activating the API for your project][cloud-datastore-activation] -- [API documentation][cloud-datastore-docs] -- [Go client documentation](https://godoc.org/cloud.google.com/go/datastore) -- [Complete sample program](https://github.com/GoogleCloudPlatform/golang-samples/tree/master/datastore/tasks) - -### Example Usage - -First create a `datastore.Client` to use throughout your application: - -[snip]:# (datastore-1) -```go -client, err := datastore.NewClient(ctx, "my-project-id") -if err != nil { - log.Fatal(err) -} -``` - -Then use that client to interact with the API: - -[snip]:# (datastore-2) -```go -type Post struct { - Title string - Body string `datastore:",noindex"` - PublishedAt time.Time -} -keys := []*datastore.Key{ - datastore.NameKey("Post", "post1", nil), - datastore.NameKey("Post", "post2", nil), -} -posts := []*Post{ - {Title: "Post 1", Body: "...", PublishedAt: time.Now()}, - {Title: "Post 2", Body: "...", PublishedAt: time.Now()}, -} -if _, err := client.PutMulti(ctx, keys, posts); err != nil { - log.Fatal(err) -} -``` - -## Cloud Storage [![GoDoc](https://godoc.org/cloud.google.com/go/storage?status.svg)](https://godoc.org/cloud.google.com/go/storage) - -- [About Cloud Storage][cloud-storage] -- [API documentation][cloud-storage-docs] -- [Go client documentation](https://godoc.org/cloud.google.com/go/storage) -- [Complete sample programs](https://github.com/GoogleCloudPlatform/golang-samples/tree/master/storage) - -### Example Usage - -First create a `storage.Client` to use throughout your application: - -[snip]:# (storage-1) -```go -client, err := storage.NewClient(ctx) -if err != nil { - log.Fatal(err) -} -``` - -[snip]:# (storage-2) -```go -// Read the object1 from bucket. -rc, err := client.Bucket("bucket").Object("object1").NewReader(ctx) -if err != nil { - log.Fatal(err) -} -defer rc.Close() -body, err := ioutil.ReadAll(rc) -if err != nil { - log.Fatal(err) -} -``` - -## Cloud Pub/Sub [![GoDoc](https://godoc.org/cloud.google.com/go/pubsub?status.svg)](https://godoc.org/cloud.google.com/go/pubsub) - -- [About Cloud Pubsub][cloud-pubsub] -- [API documentation][cloud-pubsub-docs] -- [Go client documentation](https://godoc.org/cloud.google.com/go/pubsub) -- [Complete sample programs](https://github.com/GoogleCloudPlatform/golang-samples/tree/master/pubsub) - -### Example Usage - -First create a `pubsub.Client` to use throughout your application: - -[snip]:# (pubsub-1) -```go -client, err := pubsub.NewClient(ctx, "project-id") -if err != nil { - log.Fatal(err) -} -``` - -Then use the client to publish and subscribe: - -[snip]:# (pubsub-2) -```go -// Publish "hello world" on topic1. -topic := client.Topic("topic1") -res := topic.Publish(ctx, &pubsub.Message{ - Data: []byte("hello world"), -}) -// The publish happens asynchronously. -// Later, you can get the result from res: -... -msgID, err := res.Get(ctx) -if err != nil { - log.Fatal(err) -} - -// Use a callback to receive messages via subscription1. -sub := client.Subscription("subscription1") -err = sub.Receive(ctx, func(ctx context.Context, m *pubsub.Message) { - fmt.Println(m.Data) - m.Ack() // Acknowledge that we've consumed the message. -}) -if err != nil { - log.Println(err) -} -``` - -## Cloud BigQuery [![GoDoc](https://godoc.org/cloud.google.com/go/bigquery?status.svg)](https://godoc.org/cloud.google.com/go/bigquery) - -- [About Cloud BigQuery][cloud-bigquery] -- [API documentation][cloud-bigquery-docs] -- [Go client documentation][cloud-bigquery-ref] -- [Complete sample programs](https://github.com/GoogleCloudPlatform/golang-samples/tree/master/bigquery) - -### Example Usage - -First create a `bigquery.Client` to use throughout your application: -[snip]:# (bq-1) -```go -c, err := bigquery.NewClient(ctx, "my-project-ID") -if err != nil { - // TODO: Handle error. -} -``` - -Then use that client to interact with the API: -[snip]:# (bq-2) -```go -// Construct a query. -q := c.Query(` - SELECT year, SUM(number) - FROM [bigquery-public-data:usa_names.usa_1910_2013] - WHERE name = "William" - GROUP BY year - ORDER BY year -`) -// Execute the query. -it, err := q.Read(ctx) -if err != nil { - // TODO: Handle error. -} -// Iterate through the results. -for { - var values []bigquery.Value - err := it.Next(&values) - if err == iterator.Done { - break - } - if err != nil { - // TODO: Handle error. - } - fmt.Println(values) -} -``` - - -## Stackdriver Logging [![GoDoc](https://godoc.org/cloud.google.com/go/logging?status.svg)](https://godoc.org/cloud.google.com/go/logging) - -- [About Stackdriver Logging][cloud-logging] -- [API documentation][cloud-logging-docs] -- [Go client documentation][cloud-logging-ref] -- [Complete sample programs](https://github.com/GoogleCloudPlatform/golang-samples/tree/master/logging) - -### Example Usage - -First create a `logging.Client` to use throughout your application: -[snip]:# (logging-1) -```go -ctx := context.Background() -client, err := logging.NewClient(ctx, "my-project") -if err != nil { - // TODO: Handle error. -} -``` - -Usually, you'll want to add log entries to a buffer to be periodically flushed -(automatically and asynchronously) to the Stackdriver Logging service. -[snip]:# (logging-2) -```go -logger := client.Logger("my-log") -logger.Log(logging.Entry{Payload: "something happened!"}) -``` - -Close your client before your program exits, to flush any buffered log entries. -[snip]:# (logging-3) -```go -err = client.Close() -if err != nil { - // TODO: Handle error. -} -``` - -## Cloud Spanner [![GoDoc](https://godoc.org/cloud.google.com/go/spanner?status.svg)](https://godoc.org/cloud.google.com/go/spanner) - -- [About Cloud Spanner][cloud-spanner] -- [API documentation][cloud-spanner-docs] -- [Go client documentation](https://godoc.org/cloud.google.com/go/spanner) - -### Example Usage - -First create a `spanner.Client` to use throughout your application: - -[snip]:# (spanner-1) -```go -client, err := spanner.NewClient(ctx, "projects/P/instances/I/databases/D") -if err != nil { - log.Fatal(err) -} -``` - -[snip]:# (spanner-2) -```go -// Simple Reads And Writes -_, err = client.Apply(ctx, []*spanner.Mutation{ - spanner.Insert("Users", - []string{"name", "email"}, - []interface{}{"alice", "a@example.com"})}) -if err != nil { - log.Fatal(err) -} -row, err := client.Single().ReadRow(ctx, "Users", - spanner.Key{"alice"}, []string{"email"}) -if err != nil { - log.Fatal(err) -} -``` - - -## Contributing - -Contributions are welcome. Please, see the -[CONTRIBUTING](https://github.com/GoogleCloudPlatform/google-cloud-go/blob/master/CONTRIBUTING.md) -document for details. We're using Gerrit for our code reviews. Please don't open pull -requests against this repo, new pull requests will be automatically closed. - -Please note that this project is released with a Contributor Code of Conduct. -By participating in this project you agree to abide by its terms. -See [Contributor Code of Conduct](https://github.com/GoogleCloudPlatform/google-cloud-go/blob/master/CONTRIBUTING.md#contributor-code-of-conduct) -for more information. - -[cloud-datastore]: https://cloud.google.com/datastore/ -[cloud-datastore-ref]: https://godoc.org/cloud.google.com/go/datastore -[cloud-datastore-docs]: https://cloud.google.com/datastore/docs -[cloud-datastore-activation]: https://cloud.google.com/datastore/docs/activate - -[cloud-firestore]: https://cloud.google.com/firestore/ -[cloud-firestore-ref]: https://godoc.org/cloud.google.com/go/firestore -[cloud-firestore-docs]: https://cloud.google.com/firestore/docs -[cloud-firestore-activation]: https://cloud.google.com/firestore/docs/activate - -[cloud-pubsub]: https://cloud.google.com/pubsub/ -[cloud-pubsub-ref]: https://godoc.org/cloud.google.com/go/pubsub -[cloud-pubsub-docs]: https://cloud.google.com/pubsub/docs - -[cloud-storage]: https://cloud.google.com/storage/ -[cloud-storage-ref]: https://godoc.org/cloud.google.com/go/storage -[cloud-storage-docs]: https://cloud.google.com/storage/docs -[cloud-storage-create-bucket]: https://cloud.google.com/storage/docs/cloud-console#_creatingbuckets - -[cloud-bigtable]: https://cloud.google.com/bigtable/ -[cloud-bigtable-ref]: https://godoc.org/cloud.google.com/go/bigtable - -[cloud-bigquery]: https://cloud.google.com/bigquery/ -[cloud-bigquery-docs]: https://cloud.google.com/bigquery/docs -[cloud-bigquery-ref]: https://godoc.org/cloud.google.com/go/bigquery - -[cloud-logging]: https://cloud.google.com/logging/ -[cloud-logging-docs]: https://cloud.google.com/logging/docs -[cloud-logging-ref]: https://godoc.org/cloud.google.com/go/logging - -[cloud-monitoring]: https://cloud.google.com/monitoring/ -[cloud-monitoring-ref]: https://godoc.org/cloud.google.com/go/monitoring/apiv3 - -[cloud-vision]: https://cloud.google.com/vision -[cloud-vision-ref]: https://godoc.org/cloud.google.com/go/vision/apiv1 - -[cloud-language]: https://cloud.google.com/natural-language -[cloud-language-ref]: https://godoc.org/cloud.google.com/go/language/apiv1 - -[cloud-speech]: https://cloud.google.com/speech -[cloud-speech-ref]: https://godoc.org/cloud.google.com/go/speech/apiv1 - -[cloud-spanner]: https://cloud.google.com/spanner/ -[cloud-spanner-ref]: https://godoc.org/cloud.google.com/go/spanner -[cloud-spanner-docs]: https://cloud.google.com/spanner/docs - -[cloud-translation]: https://cloud.google.com/translation -[cloud-translation-ref]: https://godoc.org/cloud.google.com/go/translation - -[cloud-trace]: https://cloud.google.com/trace/ -[cloud-trace-ref]: https://godoc.org/cloud.google.com/go/trace - -[cloud-video]: https://cloud.google.com/video-intelligence/ -[cloud-video-ref]: https://godoc.org/cloud.google.com/go/videointelligence/apiv1beta1 - -[cloud-errors]: https://cloud.google.com/error-reporting/ -[cloud-errors-ref]: https://godoc.org/cloud.google.com/go/errorreporting - -[default-creds]: https://developers.google.com/identity/protocols/application-default-credentials diff --git a/vendor/cloud.google.com/go/appveyor.yml b/vendor/cloud.google.com/go/appveyor.yml deleted file mode 100644 index e66cd00af..000000000 --- a/vendor/cloud.google.com/go/appveyor.yml +++ /dev/null @@ -1,32 +0,0 @@ -# This file configures AppVeyor (http://www.appveyor.com), -# a Windows-based CI service similar to Travis. - -# Identifier for this run -version: "{build}" - -# Clone the repo into this path, which conforms to the standard -# Go workspace structure. -clone_folder: c:\gopath\src\cloud.google.com\go - -environment: - GOPATH: c:\gopath - GCLOUD_TESTS_GOLANG_PROJECT_ID: dulcet-port-762 - GCLOUD_TESTS_GOLANG_KEY: c:\gopath\src\cloud.google.com\go\key.json - KEYFILE_CONTENTS: - secure: IvRbDAhM2PIQqzVkjzJ4FjizUvoQ+c3vG/qhJQG+HlZ/L5KEkqLu+x6WjLrExrNMyGku4znB2jmbTrUW3Ob4sGG+R5vvqeQ3YMHCVIkw5CxY+/bUDkW5RZWsVbuCnNa/vKsWmCP+/sZW6ICe29yKJ2ZOb6QaauI4s9R6j+cqBbU9pumMGYFRb0Rw3uUU7DKmVFCy+NjTENZIlDP9rmjANgAzigowJJEb2Tg9sLlQKmQeKiBSRN8lKc5Nq60a+fIzHGKvql4eIitDDDpOpyHv15/Xr1BzFw2yDoiR4X1lng0u7q0X9RgX4VIYa6gT16NXBEmQgbuX8gh7SfPMp9RhiZD9sVUaV+yogEabYpyPnmUURo0hXwkctKaBkQlEmKvjHwF5dvbg8+yqGhwtjAgFNimXG3INrwQsfQsZskkQWanutbJf9xy50GyWWFZZdi0uT4oXP/b5P7aklPXKXsvrJKBh7RjEaqBrhi86IJwOjBspvoR4l2WmcQyxb2xzQS1pjbBJFQfYJJ8+JgsstTL8PBO9d4ybJC0li1Om1qnWxkaewvPxxuoHJ9LpRKof19yRYWBmhTXb2tTASKG/zslvl4fgG4DmQBS93WC7dsiGOhAraGw2eCTgd0lYZOhk1FjWl9TS80aktXxzH/7nTvem5ohm+eDl6O0wnTL4KXjQVNSQ1PyLn4lGRJ5MNGzBTRFWIr2API2rca4Fysyfh/UdmazPGlNbY9JPGqb9+F04QzLfqm+Zz/cHy59E7lOSMBlUI4KD6d6ZNNKNRH+/g9i+fSiyiXKugTfda8KBnWGyPwprxuWGYaiQUGUYOwJY5R6x5c4mjImAB310V+Wo33UbWFJiwxEDsiCNqW1meVkBzt2er26vh4qbgCUIQ3iM3gFPfHgy+QxkmIhic7Q1HYacQElt8AAP41M7cCKWCuZidegP37MBB//mjjiNt047ZSQEvB4tqsX/OvfbByVef+cbtVw9T0yjHvmCdPW1XrhyrCCgclu6oYYdbmc5D7BBDRbjjMWGv6YvceAbfGf6ukdB5PuV+TGEN/FoQ1QTRA6Aqf+3fLMg4mS4oyTfw5xyYNbv3qoyLPrp+BnxI53WB9p0hfMg4n9FD6NntBxjDq+Q3Lk/bjC/Y4MaRWdzbMzF9a0lgGfcw9DURlK5p7uGJC9vg34feNoQprxVEZRQ01cHLeob6eGkYm4HxSRx8JY39Mh+9wzJo+k/aIvFleNC3e35NOrkXr6wb5e42n2DwBdPqdNolTLtLFRglAL1LTpp27UjvjieWJAKfoDTR5CKl01sZqt0wPdLLcvsMj6CiPFmccUIOYeZMe86kLBD61Qa5F1EwkgO3Om2qSjW96FzL4skRc+BmU5RrHlAFSldR1wpUgtkUMv9vH5Cy+UJdcvpZ8KbmhZ2PsjF7ddJ1ve9RAw3cP325AyIMwZ77Ef1mgTM0NJze6eSW1qKlEsgt1FADPyeUu1NQTA2H2dueMPGlArWTSUgyWR9AdfpqouT7eg0JWI5w+yUZZC+/rPglYbt84oLmYpwuli0z8FyEQRPIc3EtkfWIv/yYgDr2TZ0N2KvGfpi/MAUWgxI1gleC2uKgEOEtuJthd3XZjF2NoE7IBqjQOINybcJOjyeB5vRLDY1FLuxYzdg1y1etkV4XQig/vje - -install: - # Info for debugging. - - echo %PATH% - - go version - - go env - - go get -v -d -t ./... - - -# Provide a build script, or AppVeyor will call msbuild. -build_script: - - go install -v ./... - - echo %KEYFILE_CONTENTS% > %GCLOUD_TESTS_GOLANG_KEY% - -test_script: - - go test -v ./... diff --git a/vendor/cloud.google.com/go/authexample_test.go b/vendor/cloud.google.com/go/authexample_test.go deleted file mode 100644 index fe75467f9..000000000 --- a/vendor/cloud.google.com/go/authexample_test.go +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright 2016 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package cloud_test - -import ( - "cloud.google.com/go/datastore" - "golang.org/x/net/context" - "google.golang.org/api/option" -) - -func Example_applicationDefaultCredentials() { - // Google Application Default Credentials is the recommended way to authorize - // and authenticate clients. - // - // See the following link on how to create and obtain Application Default Credentials: - // https://developers.google.com/identity/protocols/application-default-credentials. - client, err := datastore.NewClient(context.Background(), "project-id") - if err != nil { - // TODO: handle error. - } - _ = client // Use the client. -} - -func Example_serviceAccountFile() { - // Use a JSON key file associated with a Google service account to - // authenticate and authorize. Service Account keys can be created and - // downloaded from https://console.developers.google.com/permissions/serviceaccounts. - // - // Note: This example uses the datastore client, but the same steps apply to - // the other client libraries underneath this package. - client, err := datastore.NewClient(context.Background(), - "project-id", option.WithServiceAccountFile("/path/to/service-account-key.json")) - if err != nil { - // TODO: handle error. - } - _ = client // Use the client. -} diff --git a/vendor/cloud.google.com/go/cloud.go b/vendor/cloud.google.com/go/cloud.go deleted file mode 100644 index 6ba428dc6..000000000 --- a/vendor/cloud.google.com/go/cloud.go +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Package cloud is the root of the packages used to access Google Cloud -// Services. See https://godoc.org/cloud.google.com/go for a full list -// of sub-packages. -// -// This package documents how to authorize and authenticate the sub packages. -package cloud // import "cloud.google.com/go" diff --git a/vendor/cloud.google.com/go/compute/metadata/metadata_test.go b/vendor/cloud.google.com/go/compute/metadata/metadata_test.go deleted file mode 100644 index 9ac592691..000000000 --- a/vendor/cloud.google.com/go/compute/metadata/metadata_test.go +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright 2016 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package metadata - -import ( - "os" - "sync" - "testing" -) - -func TestOnGCE_Stress(t *testing.T) { - if testing.Short() { - t.Skip("skipping in -short mode") - } - var last bool - for i := 0; i < 100; i++ { - onGCEOnce = sync.Once{} - - now := OnGCE() - if i > 0 && now != last { - t.Errorf("%d. changed from %v to %v", i, last, now) - } - last = now - } - t.Logf("OnGCE() = %v", last) -} - -func TestOnGCE_Force(t *testing.T) { - onGCEOnce = sync.Once{} - old := os.Getenv(metadataHostEnv) - defer os.Setenv(metadataHostEnv, old) - os.Setenv(metadataHostEnv, "127.0.0.1") - if !OnGCE() { - t.Error("OnGCE() = false; want true") - } -} diff --git a/vendor/cloud.google.com/go/key.json.enc b/vendor/cloud.google.com/go/key.json.enc deleted file mode 100644 index a8978a9015b90ec780d8a0d55273622e373b94dc..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 2432 zcmV-`34it-l&USX|M+{?-NqC3UwZP!9~cXufwcE;XsEQd>f+7?1R~ctV-!a7+I=7;AIX@R11L(kGXg4P*{S}4tQJMhHrGw*6GOwCE4y6eW$MCwt`LeioePo!slde= zh?{$Gq}3vGyQ$6svV5~iS3zKx!LR|2ec5CkLQizAqGEzt-fk_`+s5&e@WHf6rjd{k zhZO$-U_iXQxa1K=VZZ-qw|dg6hYi>SY@ery+&t@>k9`JGb`K^UJyz>+p(cxCxbDos zJ2^shF~*(w_9xPrHE7`&`Vc`{nHO{>FlRq#&`?Xbt51Jx_(uGAk5{;=sU!4|0(Y4Re6ygl)AYVZi-z$$+Nh;_&D!#ei6?@}SrR<-mX{pxlznb#yqF%3k zdzWnItjjb4Qklw=>U!IZAg3}6!-k0Auptx{p0(uuSPQwhk+p6DlH&^wD^<%%-AMTP zJ_fGnefVaGd^|I}f^o-ZaHl@%765s$(qopGyWX-&6!L4Z6WZj5j8|ZQKGM^$|NgHE zMOsn)CWY9sXB3ZoyZtPiE@Pk6cCku-Y7Z&M8?V9Zy!eJ>%GvHVhX-|BcPas=0FWYm z0v{;q{Es$vc1MCTlaXq>HY-XY*6v9$hRb3>GESvV7S?fLBP@risR&+jIc;v$Utcy& z9)Zkg_*F4evBya$R5O8uC0Vlq6?%vsIo!hXa8pa=aXcF2iGugq@|NU7#$z9Y_}?#4 z+Q|7g@046Hy@Vif%9qLPth@k*UN5U2xCCW4A97>f;wCq8_ReQayY^b-&;PFZEUa@? zzK+Nl>yl+*dG4J0s)uzQZ^{e-XiO==L(OMzKRvxr7gaP%fw3b_)T5aszA8*|eqZF6 zmE%(=t8R`_M=ELV^D7L^SAeve9u~`c=*~$0#9HK)J>J)*LIh5G)aC)mrLiZMedEELl(V76RL!E1^<6RJ=fZ2c#@L3G{z$0ZY%c0 zb%Lvg)z{fZc7S2jww$GYi3_lBy#s235Gs~bhASijhN*QMVvisFnQL`NlR$EWfP8$9 zMum#U9W{YC=2*WhK6GU_2;JbGGeYYzEeSGcBieLH;+{5o8C7*}hmlBxPW;NS zQ;hR_=67B;gIdb^27UN=wx|TsDQ%e+V(Df5K~+PtJd|y&8@f{q^qnxCn-XM2-{eCC zRKS9WrrM;F*CQT-HAoQUA-konS8x(SAF(bi{2XR?0=*}?HtczIOsB zV?Vi-NgEw_h_J`$sWTg840|hJxfz@&QMy$?4+t3_3GIvxIlA44zRJFQkR(NW`d(u# z(HZ~e#@X4g_bO*@91#dvMBpT)lttOQ7)IyYy{V*BfqrKDZr#~0wJuuVmn7OaSb{qs zs`>+nc3)>CLC~z%pBrsPFn!TTMiffrJ|#rDtB>2e9G{r~s(JnHm&nfL%Rt;2V4W|U zYD(Q<$o3L!U$C7Qo+>Ts5`*i5-dj?cZRGDcI6U&Si|<#` zr~<>bOl?t!;WwUW&ueqUoGCC&u_NJ;v;SnojnXiT-hjetj^_N_5Z|(Ze_U9vVw|vCU=o$6v(?S1CcZYkR z$@aRKnohGv8Q$_bC^;rsNdz2e6#jd|J0MX8zR%F2D=pKh&KA-04}9zzzH+=V4Gr++ zqa7%vm3)y>bRFDP5>AL%P+X5T^HM^|Rjqz5REcDKm0IQnC|{;~dP&uTTz~>K-PF8y!Hmg6Zkl$cw03|2pm+;-a;bAfli+ z&-iUS`7V!Y6g#(wva_F9+^k}xOv-2#Ni1}cK2>3+b{}O8o=vo@QQ7fU);-F`2`^ez zJTxA8Xr2u0oz`_J5wM^0v|XKf*3}By`(=0}%GoLvZX7@e^j}`+FJW~p4_`+7-`op< zZ;lk$vMIGij23O*6{bCy?Y~>7a+!dlTe!jT^(E9!00f6f?`s?8l&}q84bx=#^lALC zkhgzwsjay`v*QNB+qP_e4Eb14DWlb;AqG7O!n#D@W0x z6qF%kXj}47Hu{&drkfWUIZKF{_fn9h&MHd~0Exj*MXAo_)*ZO#-`470~ zidlpg0N%7mJC2w)fEJ!PxKdkY2vS~t!UR8f1?`rbbcbGM#KHAp{Vncervc0a&c{=o zctu%Rrz}V&?1-IMs#pxCQyEOUGf0=Hs<;z6I3Lwjt(+Q_@rBPg%G=olwJ$-U z0r{)fb+>}CEI-aLrO0s3&BH^9eI8+2~I4z9-ZE@mM;^ zdQ__V12IU*3Dqs1CxbHG>alvUuot9QbwOwG=Cz$i<;MDk;anv>y_pKoLQ@M0v0rh0 yqfml!vBS0FfZA^RTvj0s;vvF6)Hy|dAPY2Pg4{1K_(ia8pTApJ#MvjcIq}{n62c4s diff --git a/vendor/cloud.google.com/go/license_test.go b/vendor/cloud.google.com/go/license_test.go deleted file mode 100644 index 4b87878a0..000000000 --- a/vendor/cloud.google.com/go/license_test.go +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright 2016 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package cloud - -import ( - "bytes" - "io/ioutil" - "os" - "path/filepath" - "strings" - "testing" -) - -var sentinels = []string{ - "Copyright", - "Google Inc", - `Licensed under the Apache License, Version 2.0 (the "License");`, -} - -func TestLicense(t *testing.T) { - err := filepath.Walk(".", func(path string, fi os.FileInfo, err error) error { - if err != nil { - return err - } - - if ext := filepath.Ext(path); ext != ".go" && ext != ".proto" { - return nil - } - if strings.HasSuffix(path, ".pb.go") { - // .pb.go files are generated from the proto files. - // .proto files must have license headers. - return nil - } - if path == "bigtable/cmd/cbt/cbtdoc.go" { - // Automatically generated. - return nil - } - - src, err := ioutil.ReadFile(path) - if err != nil { - return nil - } - src = src[:140] // Ensure all of the sentinel values are at the top of the file. - - // Find license - for _, sentinel := range sentinels { - if !bytes.Contains(src, []byte(sentinel)) { - t.Errorf("%v: license header not present. want %q", path, sentinel) - return nil - } - } - - return nil - }) - if err != nil { - t.Fatal(err) - } -} diff --git a/vendor/cloud.google.com/go/old-news.md b/vendor/cloud.google.com/go/old-news.md deleted file mode 100644 index 896980d96..000000000 --- a/vendor/cloud.google.com/go/old-news.md +++ /dev/null @@ -1,486 +0,0 @@ -_July 31, 2017_ - -*v0.11.0* - -- Clients for spanner, pubsub and video are now in beta. - -- New client for DLP. - -- spanner: performance and testing improvements. - -- storage: requester-pays buckets are supported. - -- storage, profiler, bigtable, bigquery: bug fixes and other minor improvements. - -- pubsub: bug fixes and other minor improvements - -_June 17, 2017_ - - -*v0.10.0* - -- pubsub: Subscription.ModifyPushConfig replaced with Subscription.Update. - -- pubsub: Subscription.Receive now runs concurrently for higher throughput. - -- vision: cloud.google.com/go/vision is deprecated. Use -cloud.google.com/go/vision/apiv1 instead. - -- translation: now stable. - -- trace: several changes to the surface. See the link below. - -[Code changes required from v0.9.0.](https://github.com/GoogleCloudPlatform/google-cloud-go/blob/master/MIGRATION.md) - - -_March 17, 2017_ - -Breaking Pubsub changes. -* Publish is now asynchronous -([announcement](https://groups.google.com/d/topic/google-api-go-announce/aaqRDIQ3rvU/discussion)). -* Subscription.Pull replaced by Subscription.Receive, which takes a callback ([announcement](https://groups.google.com/d/topic/google-api-go-announce/8pt6oetAdKc/discussion)). -* Message.Done replaced with Message.Ack and Message.Nack. - -_February 14, 2017_ - -Release of a client library for Spanner. See -the -[blog post](https://cloudplatform.googleblog.com/2017/02/introducing-Cloud-Spanner-a-global-database-service-for-mission-critical-applications.html). - -Note that although the Spanner service is beta, the Go client library is alpha. - -_December 12, 2016_ - -Beta release of BigQuery, DataStore, Logging and Storage. See the -[blog post](https://cloudplatform.googleblog.com/2016/12/announcing-new-google-cloud-client.html). - -Also, BigQuery now supports structs. Read a row directly into a struct with -`RowIterator.Next`, and upload a row directly from a struct with `Uploader.Put`. -You can also use field tags. See the [package documentation][cloud-bigquery-ref] -for details. - -_December 5, 2016_ - -More changes to BigQuery: - -* The `ValueList` type was removed. It is no longer necessary. Instead of - ```go - var v ValueList - ... it.Next(&v) .. - ``` - use - - ```go - var v []Value - ... it.Next(&v) ... - ``` - -* Previously, repeatedly calling `RowIterator.Next` on the same `[]Value` or - `ValueList` would append to the slice. Now each call resets the size to zero first. - -* Schema inference will infer the SQL type BYTES for a struct field of - type []byte. Previously it inferred STRING. - -* The types `uint`, `uint64` and `uintptr` are no longer supported in schema - inference. BigQuery's integer type is INT64, and those types may hold values - that are not correctly represented in a 64-bit signed integer. - -* The SQL types DATE, TIME and DATETIME are now supported. They correspond to - the `Date`, `Time` and `DateTime` types in the new `cloud.google.com/go/civil` - package. - -_November 17, 2016_ - -Change to BigQuery: values from INTEGER columns will now be returned as int64, -not int. This will avoid errors arising from large values on 32-bit systems. - -_November 8, 2016_ - -New datastore feature: datastore now encodes your nested Go structs as Entity values, -instead of a flattened list of the embedded struct's fields. -This means that you may now have twice-nested slices, eg. -```go -type State struct { - Cities []struct{ - Populations []int - } -} -``` - -See [the announcement](https://groups.google.com/forum/#!topic/google-api-go-announce/79jtrdeuJAg) for -more details. - -_November 8, 2016_ - -Breaking changes to datastore: contexts no longer hold namespaces; instead you -must set a key's namespace explicitly. Also, key functions have been changed -and renamed. - -* The WithNamespace function has been removed. To specify a namespace in a Query, use the Query.Namespace method: - ```go - q := datastore.NewQuery("Kind").Namespace("ns") - ``` - -* All the fields of Key are exported. That means you can construct any Key with a struct literal: - ```go - k := &Key{Kind: "Kind", ID: 37, Namespace: "ns"} - ``` - -* As a result of the above, the Key methods Kind, ID, d.Name, Parent, SetParent and Namespace have been removed. - -* `NewIncompleteKey` has been removed, replaced by `IncompleteKey`. Replace - ```go - NewIncompleteKey(ctx, kind, parent) - ``` - with - ```go - IncompleteKey(kind, parent) - ``` - and if you do use namespaces, make sure you set the namespace on the returned key. - -* `NewKey` has been removed, replaced by `NameKey` and `IDKey`. Replace - ```go - NewKey(ctx, kind, name, 0, parent) - NewKey(ctx, kind, "", id, parent) - ``` - with - ```go - NameKey(kind, name, parent) - IDKey(kind, id, parent) - ``` - and if you do use namespaces, make sure you set the namespace on the returned key. - -* The `Done` variable has been removed. Replace `datastore.Done` with `iterator.Done`, from the package `google.golang.org/api/iterator`. - -* The `Client.Close` method will have a return type of error. It will return the result of closing the underlying gRPC connection. - -See [the announcement](https://groups.google.com/forum/#!topic/google-api-go-announce/hqXtM_4Ix-0) for -more details. - -_October 27, 2016_ - -Breaking change to bigquery: `NewGCSReference` is now a function, -not a method on `Client`. - -New bigquery feature: `Table.LoaderFrom` now accepts a `ReaderSource`, enabling -loading data into a table from a file or any `io.Reader`. - -_October 21, 2016_ - -Breaking change to pubsub: removed `pubsub.Done`. - -Use `iterator.Done` instead, where `iterator` is the package -`google.golang.org/api/iterator`. - -_October 19, 2016_ - -Breaking changes to cloud.google.com/go/bigquery: - -* Client.Table and Client.OpenTable have been removed. - Replace - ```go - client.OpenTable("project", "dataset", "table") - ``` - with - ```go - client.DatasetInProject("project", "dataset").Table("table") - ``` - -* Client.CreateTable has been removed. - Replace - ```go - client.CreateTable(ctx, "project", "dataset", "table") - ``` - with - ```go - client.DatasetInProject("project", "dataset").Table("table").Create(ctx) - ``` - -* Dataset.ListTables have been replaced with Dataset.Tables. - Replace - ```go - tables, err := ds.ListTables(ctx) - ``` - with - ```go - it := ds.Tables(ctx) - for { - table, err := it.Next() - if err == iterator.Done { - break - } - if err != nil { - // TODO: Handle error. - } - // TODO: use table. - } - ``` - -* Client.Read has been replaced with Job.Read, Table.Read and Query.Read. - Replace - ```go - it, err := client.Read(ctx, job) - ``` - with - ```go - it, err := job.Read(ctx) - ``` - and similarly for reading from tables or queries. - -* The iterator returned from the Read methods is now named RowIterator. Its - behavior is closer to the other iterators in these libraries. It no longer - supports the Schema method; see the next item. - Replace - ```go - for it.Next(ctx) { - var vals ValueList - if err := it.Get(&vals); err != nil { - // TODO: Handle error. - } - // TODO: use vals. - } - if err := it.Err(); err != nil { - // TODO: Handle error. - } - ``` - with - ``` - for { - var vals ValueList - err := it.Next(&vals) - if err == iterator.Done { - break - } - if err != nil { - // TODO: Handle error. - } - // TODO: use vals. - } - ``` - Instead of the `RecordsPerRequest(n)` option, write - ```go - it.PageInfo().MaxSize = n - ``` - Instead of the `StartIndex(i)` option, write - ```go - it.StartIndex = i - ``` - -* ValueLoader.Load now takes a Schema in addition to a slice of Values. - Replace - ```go - func (vl *myValueLoader) Load(v []bigquery.Value) - ``` - with - ```go - func (vl *myValueLoader) Load(v []bigquery.Value, s bigquery.Schema) - ``` - - -* Table.Patch is replace by Table.Update. - Replace - ```go - p := table.Patch() - p.Description("new description") - metadata, err := p.Apply(ctx) - ``` - with - ```go - metadata, err := table.Update(ctx, bigquery.TableMetadataToUpdate{ - Description: "new description", - }) - ``` - -* Client.Copy is replaced by separate methods for each of its four functions. - All options have been replaced by struct fields. - - * To load data from Google Cloud Storage into a table, use Table.LoaderFrom. - - Replace - ```go - client.Copy(ctx, table, gcsRef) - ``` - with - ```go - table.LoaderFrom(gcsRef).Run(ctx) - ``` - Instead of passing options to Copy, set fields on the Loader: - ```go - loader := table.LoaderFrom(gcsRef) - loader.WriteDisposition = bigquery.WriteTruncate - ``` - - * To extract data from a table into Google Cloud Storage, use - Table.ExtractorTo. Set fields on the returned Extractor instead of - passing options. - - Replace - ```go - client.Copy(ctx, gcsRef, table) - ``` - with - ```go - table.ExtractorTo(gcsRef).Run(ctx) - ``` - - * To copy data into a table from one or more other tables, use - Table.CopierFrom. Set fields on the returned Copier instead of passing options. - - Replace - ```go - client.Copy(ctx, dstTable, srcTable) - ``` - with - ```go - dst.Table.CopierFrom(srcTable).Run(ctx) - ``` - - * To start a query job, create a Query and call its Run method. Set fields - on the query instead of passing options. - - Replace - ```go - client.Copy(ctx, table, query) - ``` - with - ```go - query.Run(ctx) - ``` - -* Table.NewUploader has been renamed to Table.Uploader. Instead of options, - configure an Uploader by setting its fields. - Replace - ```go - u := table.NewUploader(bigquery.UploadIgnoreUnknownValues()) - ``` - with - ```go - u := table.NewUploader(bigquery.UploadIgnoreUnknownValues()) - u.IgnoreUnknownValues = true - ``` - -_October 10, 2016_ - -Breaking changes to cloud.google.com/go/storage: - -* AdminClient replaced by methods on Client. - Replace - ```go - adminClient.CreateBucket(ctx, bucketName, attrs) - ``` - with - ```go - client.Bucket(bucketName).Create(ctx, projectID, attrs) - ``` - -* BucketHandle.List replaced by BucketHandle.Objects. - Replace - ```go - for query != nil { - objs, err := bucket.List(d.ctx, query) - if err != nil { ... } - query = objs.Next - for _, obj := range objs.Results { - fmt.Println(obj) - } - } - ``` - with - ```go - iter := bucket.Objects(d.ctx, query) - for { - obj, err := iter.Next() - if err == iterator.Done { - break - } - if err != nil { ... } - fmt.Println(obj) - } - ``` - (The `iterator` package is at `google.golang.org/api/iterator`.) - - Replace `Query.Cursor` with `ObjectIterator.PageInfo().Token`. - - Replace `Query.MaxResults` with `ObjectIterator.PageInfo().MaxSize`. - - -* ObjectHandle.CopyTo replaced by ObjectHandle.CopierFrom. - Replace - ```go - attrs, err := src.CopyTo(ctx, dst, nil) - ``` - with - ```go - attrs, err := dst.CopierFrom(src).Run(ctx) - ``` - - Replace - ```go - attrs, err := src.CopyTo(ctx, dst, &storage.ObjectAttrs{ContextType: "text/html"}) - ``` - with - ```go - c := dst.CopierFrom(src) - c.ContextType = "text/html" - attrs, err := c.Run(ctx) - ``` - -* ObjectHandle.ComposeFrom replaced by ObjectHandle.ComposerFrom. - Replace - ```go - attrs, err := dst.ComposeFrom(ctx, []*storage.ObjectHandle{src1, src2}, nil) - ``` - with - ```go - attrs, err := dst.ComposerFrom(src1, src2).Run(ctx) - ``` - -* ObjectHandle.Update's ObjectAttrs argument replaced by ObjectAttrsToUpdate. - Replace - ```go - attrs, err := obj.Update(ctx, &storage.ObjectAttrs{ContextType: "text/html"}) - ``` - with - ```go - attrs, err := obj.Update(ctx, storage.ObjectAttrsToUpdate{ContextType: "text/html"}) - ``` - -* ObjectHandle.WithConditions replaced by ObjectHandle.If. - Replace - ```go - obj.WithConditions(storage.Generation(gen), storage.IfMetaGenerationMatch(mgen)) - ``` - with - ```go - obj.Generation(gen).If(storage.Conditions{MetagenerationMatch: mgen}) - ``` - - Replace - ```go - obj.WithConditions(storage.IfGenerationMatch(0)) - ``` - with - ```go - obj.If(storage.Conditions{DoesNotExist: true}) - ``` - -* `storage.Done` replaced by `iterator.Done` (from package `google.golang.org/api/iterator`). - -_October 6, 2016_ - -Package preview/logging deleted. Use logging instead. - -_September 27, 2016_ - -Logging client replaced with preview version (see below). - -_September 8, 2016_ - -* New clients for some of Google's Machine Learning APIs: Vision, Speech, and -Natural Language. - -* Preview version of a new [Stackdriver Logging][cloud-logging] client in -[`cloud.google.com/go/preview/logging`](https://godoc.org/cloud.google.com/go/preview/logging). -This client uses gRPC as its transport layer, and supports log reading, sinks -and metrics. It will replace the current client at `cloud.google.com/go/logging` shortly. - diff --git a/vendor/cloud.google.com/go/run-tests.sh b/vendor/cloud.google.com/go/run-tests.sh deleted file mode 100755 index f47ff50a5..000000000 --- a/vendor/cloud.google.com/go/run-tests.sh +++ /dev/null @@ -1,88 +0,0 @@ -#!/bin/bash - -# Selectively run tests for this repo, based on what has changed -# in a commit. Runs short tests for the whole repo, and full tests -# for changed directories. - -set -e - -prefix=cloud.google.com/go - -dryrun=false -if [[ $1 == "-n" ]]; then - dryrun=true - shift -fi - -if [[ $1 == "" ]]; then - echo >&2 "usage: $0 [-n] COMMIT" - exit 1 -fi - -# Files or directories that cause all tests to run if modified. -declare -A run_all -run_all=([.travis.yml]=1 [run-tests.sh]=1) - -function run { - if $dryrun; then - echo $* - else - (set -x; $*) - fi -} - - -# Find all the packages that have changed in this commit. -declare -A changed_packages - -for f in $(git diff-tree --no-commit-id --name-only -r $1); do - if [[ ${run_all[$f]} == 1 ]]; then - # This change requires a full test. Do it and exit. - run go test -race -v $prefix/... - exit - fi - # Map, e.g., "spanner/client.go" to "$prefix/spanner". - d=$(dirname $f) - if [[ $d == "." ]]; then - pkg=$prefix - else - pkg=$prefix/$d - fi - changed_packages[$pkg]=1 -done - -echo "changed packages: ${!changed_packages[*]}" - - -# Reports whether its argument, a package name, depends (recursively) -# on a changed package. -function depends_on_changed_package { - # According to go list, a package does not depend on itself, so - # we test that separately. - if [[ ${changed_packages[$1]} == 1 ]]; then - return 0 - fi - for dep in $(go list -f '{{range .Deps}}{{.}} {{end}}' $1); do - if [[ ${changed_packages[$dep]} == 1 ]]; then - return 0 - fi - done - return 1 -} - -# Collect the packages into two separate lists. (It is faster go test a list of -# packages than to individually go test each one.) - -shorts= -fulls= -for pkg in $(go list $prefix/...); do # for each package in the repo - if depends_on_changed_package $pkg; then # if it depends on a changed package - fulls="$fulls $pkg" # run the full test - else # otherwise - shorts="$shorts $pkg" # run the short test - fi -done -run go test -race -v -short $shorts -if [[ $fulls != "" ]]; then - run go test -race -v $fulls -fi diff --git a/vendor/github.com/Azure/azure-sdk-for-go/.gitignore b/vendor/github.com/Azure/azure-sdk-for-go/.gitignore deleted file mode 100644 index 2da4dc358..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/.gitignore +++ /dev/null @@ -1,32 +0,0 @@ -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe -*.test -*.prof - -# Editor swap files -*.swp -*~ -.DS_Store - -# ignore vendor/ -vendor/ diff --git a/vendor/github.com/Azure/azure-sdk-for-go/.travis.yml b/vendor/github.com/Azure/azure-sdk-for-go/.travis.yml deleted file mode 100644 index 6a134afeb..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/.travis.yml +++ /dev/null @@ -1,33 +0,0 @@ -sudo: false - -language: go - -go: 1.7 - -install: - - go get -u github.com/golang/lint/golint - - go get -u github.com/Masterminds/glide - - go get -u golang.org/x/net/context - - go get -u github.com/HewlettPackard/gas - - go get -u gopkg.in/godo.v2/cmd/godo - - export GO15VENDOREXPERIMENT=1 - - glide install - -script: - - gas -skip=management/examples/*.go -skip=*vendor* -skip=Gododir/* ./... | tee gas-scan.txt - - test -z "$(grep 'Severity:\s*HIGH' gas-scan.txt)" - - test -z "$(gofmt -s -l $(find ./arm/* -type d -print) | tee /dev/stderr)" - - test -z "$(gofmt -s -l -w management | tee /dev/stderr)" - - test -z "$(gofmt -s -l -w storage | tee /dev/stderr)" - - test -z "$(gofmt -s -l -w Gododir | tee /dev/stderr)" - - test -z "$(go build $(find ./* -type d -print | grep -v '^./vendor$') | tee /dev/stderr)" - - test -z "$(go vet $(find ./arm/* -type d -print) | tee /dev/stderr)" - - test -z "$(golint ./arm/... | tee /dev/stderr)" - - go test -v ./storage/... -check.v - - test -z "$(golint ./storage/... | tee /dev/stderr)" - - go vet ./storage/... - - go test -v ./management/... - - test -z "$(golint ./management/... | grep -v 'should have comment' | grep -v 'stutters' | tee /dev/stderr)" - - go vet ./management/... - - test -z "$(golint ./Gododir/... | tee /dev/stderr)" - - go vet ./Gododir/... diff --git a/vendor/github.com/Azure/azure-sdk-for-go/CHANGELOG.md b/vendor/github.com/Azure/azure-sdk-for-go/CHANGELOG.md deleted file mode 100644 index 13a0ca4b3..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/CHANGELOG.md +++ /dev/null @@ -1,280 +0,0 @@ -# CHANGELOG - ------ - -## `v6.0.0-beta` - -| api | version | note | -|:-------------------------------|:-------------------|:-----------------------------------| -| arm/authorization | no change | code refactoring | -| arm/batch | no change | code refactoring | -| arm/compute | no change | code refactoring | -| arm/containerservice | 2016-03-30 | return | -| arm/datalake-analytics/account | 2015-10-01-preview | new | -| arm/datalake-store/filesystem | no change | moved to datalake-store/filesystem | -| arm/eventhub | no change | code refactoring | -| arm/intune | no change | code refactoring | -| arm/iothub | no change | code refactoring | -| arm/keyvault | no change | code refactoring | -| arm/mediaservices | no change | code refactoring | -| arm/network | no change | code refactoring | -| arm/notificationhubs | no change | code refactoring | -| arm/redis | no change | code refactoring | -| arm/resources/resources | no change | code refactoring | -| arm/resources/links | 2016-09-01 | new | -| arm/resources/locks | 2016-09-01 | updated | -| arm/resources/policy | no change | code refactoring | -| arm/resources/resources | 2016-09-01 | updated | -| arm/servermanagement | 2016-07-01-preview | updated | -| arm/web | no change | code refactoring | - -- storage: Added blob lease functionality and tests - -## `v5.0.0-beta` - -| api | version | note | -|:------------------------------|:--------------------|:-----------------| -| arm/network | 2016-09-01 | updated | -| arm/servermanagement | 2015-07-01-preview | new | -| arm/eventhub | 2015-08-01 | new | -| arm/containerservice | -- | removed | -| arm/resources/subscriptions | no change | code refactoring | -| arm/resources/features | no change | code refactoring | -| arm/resources/resources | no change | code refactoring | -| arm/datalake-store/accounts | no change | code refactoring | -| arm/datalake-store/filesystem | no change | code refactoring | -| arm/notificationhubs | no change | code refactoring | -| arm/redis | no change | code refactoring | - -- storage: Add more file storage share operations. -- azure-rest-api-specs/commit/b8cdc2c50a0872fc0039f20c2b6b33aa0c2af4bf -- Uses go-autorest v7.2.1 - -## `v4.0.0-beta` - -- arm/logic: breaking change in package logic. -- arm: parameter validation code added in all arm packages. -- Uses go-autorest v7.2.0. - - -## `v3.2.0-beta` - -| api | version | note | -|:----------------------------|:--------------------|:----------| -| arm/mediaservices | 2015-10-01 | new | -| arm/keyvault | 2015-06-01 | new | -| arm/iothub | 2016-02-03 | new | -| arm/datalake-store | 2015-12-01 | new | -| arm/network | 2016-06-01 | updated | -| arm/resources/resources | 2016-07-01 | updated | -| arm/resources/policy | 2016-04-01 | updated | -| arm/servicebus | 2015-08-01 | updated | - -- arm: uses go-autorest version v7.1.0. -- storage: fix for operating on blobs names containing special characters. -- storage: add SetBlobProperties(), update BlobProperties response fields. -- storage: make storage client work correctly with read-only secondary account. -- storage: add Azure Storage Emulator support. - - -## `v3.1.0-beta` - -- Added a new arm/compute/containerservice (2016-03-30) package -- Reintroduced NewxxClientWithBaseURI method. -- Uses go-autorest version - v7.0.7. - - -## `v3.0.0-beta` - -This release brings the Go SDK ARM packages up-to-date with Azure ARM Swagger files for most -services. Since the underlying [Swagger files](https://github.com/Azure/azure-rest-api-specs) -continue to change substantially, the ARM packages are still in *beta* status. - -The ARM packages now align with the following API versions (*highlighted* packages are new or -updated in this release): - -| api | version | note | -|:----------------------------|:--------------------|:----------| -| arm/authorization | 2015-07-01 | no change | -| arm/intune | 2015-01-14-preview | no change | -| arm/notificationhubs | 2014-09-01 | no change | -| arm/resources/features | 2015-12-01 | no change | -| arm/resources/subscriptions | 2015-11-01 | no change | -| arm/web | 2015-08-01 | no change | -| arm/cdn | 2016-04-02 | updated | -| arm/compute | 2016-03-30 | updated | -| arm/dns | 2016-04-01 | updated | -| arm/logic | 2015-08-01-preview | updated | -| arm/network | 2016-03-30 | updated | -| arm/redis | 2016-04-01 | updated | -| arm/resources/resources | 2016-02-01 | updated | -| arm/resources/policy | 2015-10-01-preview | updated | -| arm/resources/locks | 2015-01-01 | updated (resources/authorization earlier)| -| arm/scheduler | 2016-03-01 | updated | -| arm/storage | 2016-01-01 | updated | -| arm/search | 2015-02-28 | updated | -| arm/batch | 2015-12-01 | new | -| arm/cognitiveservices | 2016-02-01-preview | new | -| arm/devtestlabs | 2016-05-15 | new | -| arm/machinelearning | 2016-05-01-preview | new | -| arm/powerbiembedded | 2016-01-29 | new | -| arm/mobileengagement | 2014-12-01 | new | -| arm/servicebus | 2014-09-01 | new | -| arm/sql | 2015-05-01 | new | -| arm/trafficmanager | 2015-11-01 | new | - - -Below are some design changes. -- Removed Api version from method arguments. -- Removed New...ClientWithBaseURI() method in all clients. BaseURI value is set in client.go. -- Uses go-autorest version v7.0.6. - - -## `v2.2.0-beta` - -- Uses go-autorest version v7.0.5. -- Update version of pacakges "jwt-go" and "crypto" in glide.lock. - - -## `v2.1.1-beta` - -- arm: Better error messages for long running operation failures (Uses go-autorest version v7.0.4). - - -## `v2.1.0-beta` - -- arm: Uses go-autorest v7.0.3 (polling related updates). -- arm: Cancel channel argument added in long-running calls. -- storage: Allow caller to provide headers for DeleteBlob methods. -- storage: Enables connection sharing with http keepalive. -- storage: Add BlobPrefixes and Delimiter to BlobListResponse - - -## `v2.0.0-beta` - -- Uses go-autorest v6.0.0 (Polling and Asynchronous requests related changes). - - -## `v0.5.0-beta` - -Updated following packages to new API versions: -- arm/resources/features 2015-12-01 -- arm/resources/resources 2015-11-01 -- arm/resources/subscriptions 2015-11-01 - - -### Changes - - - SDK now uses go-autorest v3.0.0. - - - -## `v0.4.0-beta` - -This release brings the Go SDK ARM packages up-to-date with Azure ARM Swagger files for most -services. Since the underlying [Swagger files](https://github.com/Azure/azure-rest-api-specs) -continue to change substantially, the ARM packages are still in *beta* status. - -The ARM packages now align with the following API versions (*highlighted* packages are new or -updated in this release): - -- *arm/authorization 2015-07-01* -- *arm/cdn 2015-06-01* -- arm/compute 2015-06-15 -- arm/dns 2015-05-04-preview -- *arm/intune 2015-01-14-preview* -- arm/logic 2015-02-01-preview -- *arm/network 2015-06-15* -- *arm/notificationhubs 2014-09-01* -- arm/redis 2015-08-01 -- *arm/resources/authorization 2015-01-01* -- *arm/resources/features 2014-08-01-preview* -- *arm/resources/resources 2014-04-01-preview* -- *arm/resources/subscriptions 2014-04-01-preview* -- *arm/scheduler 2016-01-01* -- arm/storage 2015-06-15 -- arm/web 2015-08-01 - -### Changes - -- Moved the arm/authorization, arm/features, arm/resources, and arm/subscriptions packages under a new, resources, package (to reflect the corresponding Swagger structure) -- Added a new arm/authoriation (2015-07-01) package -- Added a new arm/cdn (2015-06-01) package -- Added a new arm/intune (2015-01-14-preview) package -- Udated arm/network (2015-06-01) -- Added a new arm/notificationhubs (2014-09-01) package -- Updated arm/scheduler (2016-01-01) package - - ------ - -## `v0.3.0-beta` - -- Corrected unintentional struct field renaming and client renaming in v0.2.0-beta - ------ - -## `v0.2.0-beta` - -- Added support for DNS, Redis, and Web site services -- Updated Storage service to API version 2015-06-15 -- Updated Network to include routing table support -- Address https://github.com/Azure/azure-sdk-for-go/issues/232 -- Address https://github.com/Azure/azure-sdk-for-go/issues/231 -- Address https://github.com/Azure/azure-sdk-for-go/issues/230 -- Address https://github.com/Azure/azure-sdk-for-go/issues/224 -- Address https://github.com/Azure/azure-sdk-for-go/issues/184 -- Address https://github.com/Azure/azure-sdk-for-go/issues/183 - ------- - -## `v0.1.1-beta` - -- Improves the UserAgent string to disambiguate arm packages from others in the SDK -- Improves setting the http.Response into generated results (reduces likelihood of a nil reference) -- Adds gofmt, golint, and govet to Travis CI for the arm packages - -##### Fixed Issues - -- https://github.com/Azure/azure-sdk-for-go/issues/196 -- https://github.com/Azure/azure-sdk-for-go/issues/213 - ------- - -## v0.1.0-beta - -This release addresses the issues raised against the alpha release and adds more features. Most -notably, to address the challenges of encoding JSON -(see the [comments](https://github.com/Azure/go-autorest#handling-empty-values) in the -[go-autorest](https://github.com/Azure/go-autorest) package) by using pointers for *all* structure -fields (with the exception of enumerations). The -[go-autorest/autorest/to](https://github.com/Azure/go-autorest/tree/master/autorest/to) package -provides helpers to convert to / from pointers. The examples demonstrate their usage. - -Additionally, the packages now align with Go coding standards and pass both `golint` and `govet`. -Accomplishing this required renaming various fields and parameters (such as changing Url to URL). - -##### Changes - -- Changed request / response structures to use pointer fields. -- Changed methods to return `error` instead of `autorest.Error`. -- Re-divided methods to ease asynchronous requests. -- Added paged results support. -- Added a UserAgent string. -- Added changes necessary to pass golint and govet. -- Updated README.md with details on asynchronous requests and paging. -- Saved package dependencies through Godep (for the entire SDK). - -##### Fixed Issues: - -- https://github.com/Azure/azure-sdk-for-go/issues/205 -- https://github.com/Azure/azure-sdk-for-go/issues/206 -- https://github.com/Azure/azure-sdk-for-go/issues/211 -- https://github.com/Azure/azure-sdk-for-go/issues/212 - ------ - -## v0.1.0-alpha - -This release introduces the Azure Resource Manager packages generated from the corresponding -[Swagger API](http://swagger.io) [definitions](https://github.com/Azure/azure-rest-api-specs). \ No newline at end of file diff --git a/vendor/github.com/Azure/azure-sdk-for-go/README.md b/vendor/github.com/Azure/azure-sdk-for-go/README.md deleted file mode 100644 index 6a1aaf4ac..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/README.md +++ /dev/null @@ -1,102 +0,0 @@ -# Microsoft Azure SDK for Go - -This project provides various Go packages to perform operations -on Microsoft Azure REST APIs. - -[![GoDoc](https://godoc.org/github.com/Azure/azure-sdk-for-go?status.svg)](https://godoc.org/github.com/Azure/azure-sdk-for-go) [![Build Status](https://travis-ci.org/Azure/azure-sdk-for-go.svg?branch=master)](https://travis-ci.org/Azure/azure-sdk-for-go) - -> **NOTE:** This repository is under heavy ongoing development and -is likely to break over time. We currently do not have any releases -yet. If you are planning to use the repository, please consider vendoring -the packages in your project and update them when a stable tag is out. - -# Packages - -## Azure Resource Manager (ARM) - -[About ARM](/arm/README.md) - -- [authorization](/arm/authorization) -- [batch](/arm/batch) -- [cdn](/arm/cdn) -- [cognitiveservices](/arm/cognitiveservices) -- [compute](/arm/compute) -- [containerservice](/arm/containerservice) -- [datalake-store](/arm/datalake-store) -- [devtestlabs](/arm/devtestlabs) -- [dns](/arm/dns) -- [intune](/arm/intune) -- [iothub](/arm/iothub) -- [keyvault](/arm/keyvault) -- [logic](/arm/logic) -- [machinelearning](/arm/machinelearning) -- [mediaservices](/arm/mediaservices) -- [mobileengagement](/arm/mobileengagement) -- [network](/arm/network) -- [notificationhubs](/arm/notificationhubs) -- [powerbiembedded](/arm/powerbiembedded) -- [redis](/arm/redis) -- [resources](/arm/resources) -- [scheduler](/arm/scheduler) -- [search](/arm/search) -- [servicebus](/arm/servicebus) -- [sql](/arm/sql) -- [storage](/arm/storage) -- [trafficmanager](/arm/trafficmanager) -- [web](/arm/web) - -## Azure Service Management (ASM), aka classic deployment - -[About ASM](/management/README.md) - -- [affinitygroup](/management/affinitygroup) -- [hostedservice](/management/hostedservice) -- [location](/management/location) -- [networksecuritygroup](/management/networksecuritygroup) -- [osimage](/management/osimage) -- [sql](/management/sql) -- [storageservice](/management/storageservice) -- [virtualmachine](/management/virtualmachine) -- [virtualmachinedisk](/management/virtualmachinedisk) -- [virtualmachineimage](/management/virtualmachineimage) -- [virtualnetwork](/management/virtualnetwork) -- [vmutils](/management/vmutils) - -## Azure Storage SDK for Go - -[About Storage](/storage/README.md) - -- [storage](/storage) - -# Installation - -- [Install Go 1.7](https://golang.org/dl/). - -- Go get the SDK: - -``` -$ go get -d github.com/Azure/azure-sdk-for-go -``` - -> **IMPORTANT:** We highly suggest vendoring Azure SDK for Go as a dependency. For vendoring dependencies, Azure SDK for Go uses [glide](https://github.com/Masterminds/glide). If you haven't already, install glide. Navigate to your project directory and install the dependencies. - -``` -$ cd your/project -$ glide create -$ glide install -``` - -# Documentation - -Read the Godoc of the repository at [Godoc.org](http://godoc.org/github.com/Azure/azure-sdk-for-go/). - -# Contribute - -If you would like to become an active contributor to this project please follow the instructions provided in [Microsoft Azure Projects Contribution Guidelines](http://azure.github.io/guidelines/). - -# License - -This project is published under [Apache 2.0 License](LICENSE). - ------ -This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/README.md b/vendor/github.com/Azure/azure-sdk-for-go/arm/README.md deleted file mode 100644 index 4ddee085d..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/README.md +++ /dev/null @@ -1,272 +0,0 @@ -# Introducing the Azure Resource Manager packages for Go - -The `github.com/Azure/azure-sdk-for-go/arm` packages are used to perform operations using the Azure Resource Manager (ARM). Read more about [Azure Resource Manager vs. classic deployment](https://azure.microsoft.com/documentation/articles/resource-manager-deployment-model/). Packages for Azure Service Manager or classic deployment are in the [management](https://github.com/Azure/azure-sdk-for-go/tree/master/management) folder. - - -## How Did We Get Here? - -Azure is growing rapidly, regularly adding new services and features. While rapid growth -is good for users, it is hard on SDKs. Each new service and each new feature requires someone to -learn the details and add the needed code to the SDK. As a result, the -[Azure SDK for Go](https://github.com/Azure/azure-sdk-for-go) -has lagged behind Azure. It is missing -entire services and has not kept current with features. There is simply too much change to maintain -a hand-written SDK. - -For this reason, the -[Azure SDK for Go](https://github.com/Azure/azure-sdk-for-go), -with the release of the Azure Resource Manager (ARM) -packages, is transitioning to a generated-code model. Other Azure SDKs, notably the -[Azure SDK for .NET](https://github.com/Azure/azure-sdk-for-net), have successfully adopted a -generated-code strategy. Recently, Microsoft published the -[Autorest](https://github.com/Azure/autorest) tool used to create these SDKs and we have been adding support for Go. The ARM packages are -the first set generated using this new toolchain. - -There are a couple of items to note. First, since both the tooling and the underlying support -packages are new, the code is not yet "production ready". Treat these packages as of -***beta*** quality. -That's not to say we don't believe in the code, but we want to see what others think and how well -they work in a variety of environments before settling down into an official, first release. If you -find problems or have suggestions, please submit a pull request to document what you find. However, -since the code is generated, we'll use your pull request to guide changes we make to the underlying -generator versus merging the pull request itself. - -The second item of note is that, to keep the generated code clean and reliable, it depends on -another new package [go-autorest](https://github.com/Azure/go-autorest). -Though part of the SDK, we separated the code to better control versioning and maintain agility. -Since -[go-autorest](https://github.com/Azure/go-autorest) -is hand-crafted, we will take pull requests in the same manner as for our other repositories. - -We intend to rapidly improve these packages until they are "production ready". -So, try them out and give us your thoughts. - -## What Have We Done? - -Creating new frameworks is hard and often leads to "cliffs": The code is easy to use until some -special case or tweak arises and then, well, then you're stuck. Often times small differences in -requirements can lead to forking the code and investing a lot of time. Cliffs occur even more -frequently in generated code. We wanted to avoid them and believe the new model does. Our initial -goals were: - -* Easy-to-use out of the box. It should be "clone and go" for straight-forward use. -* Easy composition to handle the majority of complex cases. -* Easy to integrate with existing frameworks, fit nicely with channels, supporting fan-out / -fan-in set ups. - -These are best shown in a series of examples, all of which are included in the -[examples](/arm/examples) sub-folder. - -## First a Sidenote: Authentication and the Azure Resource Manager - -Before using the Azure Resource Manager packages, you need to understand how it authenticates and -authorizes requests. -Azure Resource Manager requests can be authorized through [OAuth2](http://oauth.net). While OAuth2 provides many advantages over -certificates, programmatic use, such as for scripts on headless servers, requires understanding and -creating one or more *Service Principals.* -There are several good blog posts, such as -[Automating Azure on your CI server using a Service Principal](http://blog.davidebbo.com/2014/12/azure-service-principal.html) -and -[Microsoft Azure REST API + OAuth 2.0](https://ahmetalpbalkan.com/blog/azure-rest-api-with-oauth2/), -that describe what this means. -For details on creating and authorizing Service Principals, see the MSDN articles -[Azure API Management REST API Authentication](https://msdn.microsoft.com/library/azure/5b13010a-d202-4af5-aabf-7ebc26800b3d) -and -[Create a new Azure Service Principal using the Azure portal](https://azure.microsoft.com/documentation/articles/resource-group-create-service-principal-portal/). -Dushyant Gill, a Senior Program Manager for Azure Active Directory, has written an extensive blog -post, -[Developer's Guide to Auth with Azure Resource Manager API](http://www.dushyantgill.com/blog/2015/05/23/developers-guide-to-auth-with-azure-resource-manager-api/), -that is also quite helpful. - -### Complete source code - -Get code for a full example of [authenticating to Azure via certificate or device authorization](https://github.com/Azure/go-autorest/tree/master/autorest/azure/example). - -## A Simple Example: Checking availability of name within Azure Storage - -Each ARM provider, such as -[Azure Storage](http://azure.microsoft.com/documentation/services/storage/) -or -[Azure Compute](https://azure.microsoft.com/documentation/services/virtual-machines/), -has its own package. Start by importing -the packages for the providers you need. Next, most packages divide their APIs across multiple -clients to avoid name collision and improve usability. For example, the -[Azure Storage](http://azure.microsoft.com/documentation/services/storage/) -package has -two clients: -[storage.AccountsClient](https://godoc.org/github.com/Azure/azure-sdk-for-go/arm/storage#AccountsClient) -and -[storage.UsageOperationsClient](https://godoc.org/github.com/Azure/azure-sdk-for-go/arm/storage#UsageOperationsClient). -To check if a name is available, use the -[storage.AccountsClient](https://godoc.org/github.com/Azure/azure-sdk-for-go/arm/storage#AccountsClient). - -Each ARM client composes with [autorest.Client](https://godoc.org/github.com/Azure/go-autorest/autorest#Client). -[autorest.Client](https://godoc.org/github.com/Azure/go-autorest/autorest#Client) -enables altering the behavior of the API calls by leveraging the decorator pattern of -[go-autorest](https://github.com/Azure/go-autorest). For example, in the code above, the -[azure.ServicePrincipalToken](https://godoc.org/github.com/Azure/go-autorest/autorest/azure#ServicePrincipalToken) -includes a -[WithAuthorization](https://godoc.org/github.com/Azure/go-autorest/autorest#Client.WithAuthorization) -[autorest.PrepareDecorator](https://godoc.org/github.com/Azure/go-autorest/autorest#PrepareDecorator) -that applies the OAuth2 authorization token to the request. It will, as needed, refresh the token -using the supplied credentials. - -Providing a decorated -[autorest.Sender](https://godoc.org/github.com/Azure/go-autorest/autorest#Sender) or populating -the [autorest.Client](https://godoc.org/github.com/Azure/go-autorest/autorest#Client) -with a custom -[autorest.PrepareDecorator](https://godoc.org/github.com/Azure/go-autorest/autorest#PrepareDecorator) -or -[autorest.RespondDecorator](https://godoc.org/github.com/Azure/go-autorest/autorest#RespondDecorator) -enables more control. See the included example file -[check.go](/arm/examples/check/check.go) -for more details. Through these you can modify the outgoing request, inspect the incoming response, -or even go so far as to provide a -[circuit breaker](https://msdn.microsoft.com/library/dn589784.aspx) -to protect your service from unexpected latencies. - -Lastly, all Azure ARM API calls return an instance of -[autorest.DetailedError](https://godoc.org/github.com/Azure/go-autorest/autorest#DetailedError). -Not only DetailedError gives anonymous access to the original -[error](http://golang.org/ref/spec#Errors), -but provides the package type (e.g., -[storage.AccountsClient](https://godoc.org/github.com/Azure/azure-sdk-for-go/arm/storage#AccountsClient)), -the failing method (e.g., -[CheckNameAvailability](https://godoc.org/github.com/Azure/azure-sdk-for-go/arm/storage#AccountsClient.CheckNameAvailability)), -and a detailed error message. - -### Complete source code - -Complete source code for this example can be found in [check.go](/arm/examples/check/check.go). - -1. Create a [service principal](https://azure.microsoft.com/documentation/articles/resource-group-authenticate-service-principal-cli/). You will need the Tenant ID, Client ID and Client Secret for [authentication](#first-a-sidenote-authentication-and-the-azure-resource-manager), so keep them as soon as you get them. -2. Get your Azure Subscription ID using either of the methods mentioned below: - - Get it through the [portal](portal.azure.com) in the subscriptions section. - - Get it using the [Azure CLI](https://azure.microsoft.com/documentation/articles/xplat-cli-install/) with command `azure account show`. - - Get it using [Azure Powershell](https://azure.microsoft.com/documentation/articles/powershell-install-configure/) whit cmdlet `Get-AzureRmSubscription`. -3. Set environment variables `AZURE_TENANT_ID = `, `AZURE_CLIENT_ID = `, `AZURE_CLIENT_SECRET = ` and `AZURE_SUBSCRIPTION_ID = `. -4. Run the sample with commands: - -``` -$ cd arm/examples/check -$ go run check.go -``` - -## Something a Bit More Complex: Creating a new Azure Storage account - -Redundancy, both local and across regions, and service load affect service responsiveness. Some -API calls will return before having completed the request. An Azure ARM API call indicates the -request is incomplete (versus the request failed for some reason) by returning HTTP status code -'202 Accepted.' The -[autorest.Client](https://godoc.org/github.com/Azure/go-autorest/autorest#Client) -composed into -all of the Azure ARM clients, provides support for basic request polling. The default is to -poll until a specified duration has passed (with polling frequency determined by the -HTTP [Retry-After](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.37) -header in the response). By changing the -[autorest.Client](https://godoc.org/github.com/Azure/go-autorest/autorest#Client) -settings, you can poll for a fixed number of attempts or elect to not poll at all. - -Whether you elect to poll or not, all Azure ARM client responses compose with an instance of -[autorest.Response](https://godoc.org/github.com/Azure/go-autorest/autorest#Response). -At present, -[autorest.Response](https://godoc.org/github.com/Azure/go-autorest/autorest#Response) -only composes over the standard -[http.Response](https://golang.org/pkg/net/http/#Response) -object (that may change as we implement more features). When your code receives an error from an -Azure ARM API call, you may find it useful to inspect the HTTP status code contained in the returned -[autorest.Response](https://godoc.org/github.com/Azure/go-autorest/autorest#Response). -If, for example, it is an HTTP 202, then you can use the -[GetPollingLocation](https://godoc.org/github.com/Azure/go-autorest/autorest#Response.GetPollingLocation) -response method to extract the URL at which to continue polling. Similarly, the -[GetPollingDelay](https://godoc.org/github.com/Azure/go-autorest/autorest#Response.GetPollingDelay) -response method returns, as a -[time.Duration](http://golang.org/pkg/time/#Duration), -the service suggested minimum polling delay. - -Creating a new Azure storage account is a straight-forward way to see these concepts. - -[autorest.Client](https://godoc.org/github.com/Azure/go-autorest/autorest#Client) -portion of the -[storage.AccountsClient](https://godoc.org/github.com/Azure/azure-sdk-for-go/arm/storage#AccountsClient) -to poll for a fixed number of attempts versus polling for a set duration (which is the default). -If an error occurs creating the storage account, the code inspects the HTTP status code and -prints the URL the -[Azure Storage](http://azure.microsoft.com/documentation/services/storage/) -service returned for polling. - -### Complete source for the example -More details, including deleting the created account, are in the example code file [create.go](/arm/examples/create/create.go) - -1. Create a [service principal](https://azure.microsoft.com/documentation/articles/resource-group-authenticate-service-principal-cli/). You will need the Tenant ID, Client ID and Client Secret for [authentication](#first-a-sidenote-authentication-and-the-azure-resource-manager), so keep them as soon as you get them. -2. Get your Azure Subscription ID using either of the methods mentioned below: - - Get it through the [portal](portal.azure.com) in the subscriptions section. - - Get it using the [Azure CLI](https://azure.microsoft.com/documentation/articles/xplat-cli-install/) with command `azure account show`. - - Get it using [Azure Powershell](https://azure.microsoft.com/documentation/articles/powershell-install-configure/) whit cmdlet `Get-AzureRmSubscription`. -3. Set environment variables `AZURE_TENANT_ID = `, `AZURE_CLIENT_ID = `, `AZURE_CLIENT_SECRET = ` and `AZURE_SUBSCRIPTION_ID = `. -4. Create a resource group and add its name in the first line of the main function. -5. Run the example with commands: - -``` -$ cd arm/examples/create -$ go run create.go -``` - - -## Making Asynchronous Requests - -One of Go's many strong points is how natural it makes sending and managing asynchronous requests -by means of goroutines. We wanted the ARM packages to fit naturally in the variety of asynchronous -patterns used in Go code, but also be straight-forward for simple use cases. We accomplished both -by adopting a pattern for all APIs. Each package API includes (at least) four methods -(more if the API returns a paged result set). For example, for an API call named `Foo` the package -defines: - -- `FooPreparer`: This method accepts the arguments for the API and returns a prepared -`http.Request`. -- `FooSender`: This method sends the prepared `http.Request`. It handles the possible status codes -and will, unless the disabled in the [autorest.Client](https://godoc.org/github.com/Azure/go-autorest/autorest#Client), handling polling. -- `FooResponder`: This method accepts and handles the `http.Response` returned by the sender -and unmarshals the JSON, if any, into the result. -- `Foo`: This method accepts the arguments for the API and returns the result. It is a wrapper -around the `FooPreparer`, `FooSender`, and `FooResponder`. - -By using the preparer, sender, and responder methods, package users can spread request and -response handling across goroutines as needed. Further, adding a cancel channel to the -`http.Response` (most easily through a -[PrepareDecorator](https://godoc.org/github.com/Azure/go-autorest/autorest#PrepareDecorator)), -enables canceling sent requests (see the documentation on -[http.Request](https://golang.org/pkg/net/http/#Request)) for details. - -## Paged Result Sets - -Some API calls return partial results. Typically, when they do, the result structure will include -a `Value` array and a `NextLink` URL. The `NextLink` URL is used to retrieve the next page or -block of results. - -The packages add two methods to make working with and retrieving paged results natural. First, -on paged result structures, the packages include a preparer method that returns an `http.Request` -for the next set of results. For a result set returned in a structure named `FooResults`, the -package will include a method named `FooResultsPreparer`. If the `NextLink` is `nil` or empty, the -method returns `nil`. - -The corresponding API (which typically includes "List" in the name) has a method to ease retrieving -the next result set given a result set. For example, for an API named `FooList`, the package will -include `FooListNextResults` that accepts the results of the last call and returns the next set. - -## Summing Up - -The new Azure Resource Manager packages for the Azure SDK for Go are a big step toward keeping the -SDK current with Azure's rapid growth. -As mentioned, we intend to rapidly stabilize these packages for production use. -We'll also add more examples, including some highlighting the -[Azure Resource Manager Templates](https://msdn.microsoft.com/library/azure/dn790568.aspx) -and the other providers. - -So, give the packages a try, explore the various ARM providers, and let us know what you think. - -We look forward to hearing from you! - -## License - -See the Azure SDK for Go LICENSE file. diff --git a/vendor/github.com/Azure/azure-sdk-for-go/glide.lock b/vendor/github.com/Azure/azure-sdk-for-go/glide.lock deleted file mode 100644 index 31f3207ee..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/glide.lock +++ /dev/null @@ -1,53 +0,0 @@ -hash: 7407050cee9bb9ce89e23ef26bce4051cce63d558338a4937f027a18b789e3a1 -updated: 2016-10-25T11:34:48.4987356-07:00 -imports: -- name: github.com/Azure/go-autorest - version: 0781901f19f1e7db3034d97ec57af753db0bf808 - subpackages: - - autorest - - autorest/azure - - autorest/date - - autorest/to - - autorest/validation -- name: github.com/dgrijalva/jwt-go - version: 24c63f56522a87ec5339cc3567883f1039378fdb -- name: github.com/howeyc/gopass - version: f5387c492211eb133053880d23dfae62aa14123d -- name: github.com/mattn/go-colorable - version: 6c903ff4aa50920ca86087a280590b36b3152b9c -- name: github.com/mattn/go-isatty - version: 66b8e73f3f5cda9f96b69efd03dd3d7fc4a5cdb8 -- name: github.com/mgutz/ansi - version: c286dcecd19ff979eeb73ea444e479b903f2cfcb -- name: github.com/mgutz/minimist - version: 39eb8cf573ca29344bd7d7e6ba4d7febdebd37a9 -- name: github.com/mgutz/str - version: 968bf66e3da857419e4f6e71b2d5c9ae95682dc4 -- name: github.com/mgutz/to - version: 2a0bcba0661696e339461f5efb2273f4459dd1b9 -- name: github.com/MichaelTJones/walk - version: 3af09438b0ab0e8f296410bfa646a7e635ea1fc0 -- name: github.com/nozzle/throttler - version: d9b45f19996c645d38c9266d1f5cf1990e930119 -- name: github.com/satori/uuid - version: b061729afc07e77a8aa4fad0a2fd840958f1942a -- name: golang.org/x/crypto - version: 84e98f45760e87786b7f24603b8166a6fa09811d - subpackages: - - pkcs12 - - pkcs12/internal/rc2 - - ssh/terminal -- name: golang.org/x/sys - version: c200b10b5d5e122be351b67af224adc6128af5bf - subpackages: - - unix -- name: gopkg.in/check.v1 - version: 4f90aeace3a26ad7021961c297b22c42160c7b25 -- name: gopkg.in/godo.v2 - version: b5fd2f0bef1ebe832e628cfad18ab1cc707f65a1 - subpackages: - - glob - - util - - watcher - - watcher/fswatch -testImports: [] diff --git a/vendor/github.com/Azure/azure-sdk-for-go/glide.yaml b/vendor/github.com/Azure/azure-sdk-for-go/glide.yaml deleted file mode 100644 index 90f54fd10..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/glide.yaml +++ /dev/null @@ -1,12 +0,0 @@ -package: github.com/Azure/azure-sdk-for-go -import: -- package: github.com/Azure/go-autorest - subpackages: - - /autorest - - autorest/azure - - autorest/date - - autorest/to -- package: golang.org/x/crypto - subpackages: - - /pkcs12 -- package: gopkg.in/check.v1 \ No newline at end of file diff --git a/vendor/github.com/Azure/go-autorest/.gitignore b/vendor/github.com/Azure/go-autorest/.gitignore deleted file mode 100644 index 325986efa..000000000 --- a/vendor/github.com/Azure/go-autorest/.gitignore +++ /dev/null @@ -1,29 +0,0 @@ -# The standard Go .gitignore file follows. (Sourced from: github.com/github/gitignore/master/Go.gitignore) -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe -*.test -*.prof - -# go-autorest specific -vendor/ -autorest/azure/example/example diff --git a/vendor/github.com/Azure/go-autorest/.travis.yml b/vendor/github.com/Azure/go-autorest/.travis.yml deleted file mode 100644 index 7b32dd0da..000000000 --- a/vendor/github.com/Azure/go-autorest/.travis.yml +++ /dev/null @@ -1,18 +0,0 @@ -sudo: false - -language: go - -go: 1.7 - -install: - - go get -u github.com/golang/lint/golint - - go get -u github.com/Masterminds/glide - - go get -u github.com/stretchr/testify - - glide install - -script: - - test -z "$(gofmt -s -l -w ./autorest/. | tee /dev/stderr)" - - test -z "$(golint ./autorest/... | tee /dev/stderr)" - - go vet ./autorest/... - - go build -v ./autorest/... - - go test -v ./autorest/... diff --git a/vendor/github.com/Azure/go-autorest/CHANGELOG.md b/vendor/github.com/Azure/go-autorest/CHANGELOG.md deleted file mode 100644 index 32990bcc7..000000000 --- a/vendor/github.com/Azure/go-autorest/CHANGELOG.md +++ /dev/null @@ -1,139 +0,0 @@ -# CHANGELOG - -## v7.2.2 -- autorest/azure: added ASM and ARM VM DNS suffixes. - -## v7.2.1 -- fixed parsing of UTC times that are not RFC3339 conformant. - -## v7.2.0 -- autorest/validation: Reformat validation error for better error message. - -## v7.1.0 -- preparer: Added support for multipart formdata - WithMultiPartFormdata() -- preparer: Added support for sending file in request body - WithFile -- client: Added RetryDuration parameter. -- autorest/validation: new package for validation code for Azure Go SDK. - -## v7.0.7 -- Add trailing / to endpoint -- azure: add EnvironmentFromName - -## v7.0.6 -- Add retry logic for 408, 500, 502, 503 and 504 status codes. -- Change url path and query encoding logic. -- Fix DelayForBackoff for proper exponential delay. -- Add CookieJar in Client. - -## v7.0.5 -- Add check to start polling only when status is in [200,201,202]. -- Refactoring for unchecked errors. -- azure/persist changes. -- Fix 'file in use' issue in renewing token in deviceflow. -- Store header RetryAfter for subsequent requests in polling. -- Add attribute details in service error. - -## v7.0.4 -- Better error messages for long running operation failures - -## v7.0.3 -- Corrected DoPollForAsynchronous to properly handle the initial response - -## v7.0.2 -- Corrected DoPollForAsynchronous to continue using the polling method first discovered - -## v7.0.1 -- Fixed empty JSON input error in ByUnmarshallingJSON -- Fixed polling support for GET calls -- Changed format name from TimeRfc1123 to TimeRFC1123 - -## v7.0.0 -- Added ByCopying responder with supporting TeeReadCloser -- Rewrote Azure asynchronous handling -- Reverted to only unmarshalling JSON -- Corrected handling of RFC3339 time strings and added support for Rfc1123 time format - -The `json.Decoder` does not catch bad data as thoroughly as `json.Unmarshal`. Since -`encoding/json` successfully deserializes all core types, and extended types normally provide -their custom JSON serialization handlers, the code has been reverted back to using -`json.Unmarshal`. The original change to use `json.Decode` was made to reduce duplicate -code; there is no loss of function, and there is a gain in accuracy, by reverting. - -Additionally, Azure services indicate requests to be polled by multiple means. The existing code -only checked for one of those (that is, the presence of the `Azure-AsyncOperation` header). -The new code correctly covers all cases and aligns with the other Azure SDKs. - -## v6.1.0 -- Introduced `date.ByUnmarshallingJSONDate` and `date.ByUnmarshallingJSONTime` to enable JSON encoded values. - -## v6.0.0 -- Completely reworked the handling of polled and asynchronous requests -- Removed unnecessary routines -- Reworked `mocks.Sender` to replay a series of `http.Response` objects -- Added `PrepareDecorators` for primitive types (e.g., bool, int32) - -Handling polled and asynchronous requests is no longer part of `Client#Send`. Instead new -`SendDecorators` implement different styles of polled behavior. See`autorest.DoPollForStatusCodes` -and `azure.DoPollForAsynchronous` for examples. - -## v5.0.0 -- Added new RespondDecorators unmarshalling primitive types -- Corrected application of inspection and authorization PrependDecorators - -## v4.0.0 -- Added support for Azure long-running operations. -- Added cancelation support to all decorators and functions that may delay. -- Breaking: `DelayForBackoff` now accepts a channel, which may be nil. - -## v3.1.0 -- Add support for OAuth Device Flow authorization. -- Add support for ServicePrincipalTokens that are backed by an existing token, rather than other secret material. -- Add helpers for persisting and restoring Tokens. -- Increased code coverage in the github.com/Azure/autorest/azure package - -## v3.0.0 -- Breaking: `NewErrorWithError` no longer takes `statusCode int`. -- Breaking: `NewErrorWithStatusCode` is replaced with `NewErrorWithResponse`. -- Breaking: `Client#Send()` no longer takes `codes ...int` argument. -- Add: XML unmarshaling support with `ByUnmarshallingXML()` -- Stopped vending dependencies locally and switched to [Glide](https://github.com/Masterminds/glide). - Applications using this library should either use Glide or vendor dependencies locally some other way. -- Add: `azure.WithErrorUnlessStatusCode()` decorator to handle Azure errors. -- Fix: use `net/http.DefaultClient` as base client. -- Fix: Missing inspection for polling responses added. -- Add: CopyAndDecode helpers. -- Improved `./autorest/to` with `[]string` helpers. -- Removed golint suppressions in .travis.yml. - -## v2.1.0 - -- Added `StatusCode` to `Error` for more easily obtaining the HTTP Reponse StatusCode (if any) - -## v2.0.0 - -- Changed `to.StringMapPtr` method signature to return a pointer -- Changed `ServicePrincipalCertificateSecret` and `NewServicePrincipalTokenFromCertificate` to support generic certificate and private keys - -## v1.0.0 - -- Added Logging inspectors to trace http.Request / Response -- Added support for User-Agent header -- Changed WithHeader PrepareDecorator to use set vs. add -- Added JSON to error when unmarshalling fails -- Added Client#Send method -- Corrected case of "Azure" in package paths -- Added "to" helpers, Azure helpers, and improved ease-of-use -- Corrected golint issues - -## v1.0.1 - -- Added CHANGELOG.md - -## v1.1.0 - -- Added mechanism to retrieve a ServicePrincipalToken using a certificate-signed JWT -- Added an example of creating a certificate-based ServicePrincipal and retrieving an OAuth token using the certificate - -## v1.1.1 - -- Introduce godeps and vendor dependencies introduced in v1.1.1 diff --git a/vendor/github.com/Azure/go-autorest/README.md b/vendor/github.com/Azure/go-autorest/README.md deleted file mode 100644 index 5be4d5d2d..000000000 --- a/vendor/github.com/Azure/go-autorest/README.md +++ /dev/null @@ -1,131 +0,0 @@ -# go-autorest - -[![GoDoc](https://godoc.org/github.com/Azure/go-autorest/autorest?status.png)](https://godoc.org/github.com/Azure/go-autorest/autorest) [![Build Status](https://travis-ci.org/Azure/go-autorest.svg?branch=master)](https://travis-ci.org/Azure/go-autorest) [![Go Report Card](https://goreportcard.com/badge/Azure/go-autorest)](https://goreportcard.com/report/Azure/go-autorest) - -## Usage -Package autorest implements an HTTP request pipeline suitable for use across multiple go-routines -and provides the shared routines relied on by AutoRest (see https://github.com/Azure/autorest/) -generated Go code. - -The package breaks sending and responding to HTTP requests into three phases: Preparing, Sending, -and Responding. A typical pattern is: - -```go - req, err := Prepare(&http.Request{}, - token.WithAuthorization()) - - resp, err := Send(req, - WithLogging(logger), - DoErrorIfStatusCode(http.StatusInternalServerError), - DoCloseIfError(), - DoRetryForAttempts(5, time.Second)) - - err = Respond(resp, - ByClosing()) -``` - -Each phase relies on decorators to modify and / or manage processing. Decorators may first modify -and then pass the data along, pass the data first and then modify the result, or wrap themselves -around passing the data (such as a logger might do). Decorators run in the order provided. For -example, the following: - -```go - req, err := Prepare(&http.Request{}, - WithBaseURL("https://microsoft.com/"), - WithPath("a"), - WithPath("b"), - WithPath("c")) -``` - -will set the URL to: - -``` - https://microsoft.com/a/b/c -``` - -Preparers and Responders may be shared and re-used (assuming the underlying decorators support -sharing and re-use). Performant use is obtained by creating one or more Preparers and Responders -shared among multiple go-routines, and a single Sender shared among multiple sending go-routines, -all bound together by means of input / output channels. - -Decorators hold their passed state within a closure (such as the path components in the example -above). Be careful to share Preparers and Responders only in a context where such held state -applies. For example, it may not make sense to share a Preparer that applies a query string from a -fixed set of values. Similarly, sharing a Responder that reads the response body into a passed -struct (e.g., `ByUnmarshallingJson`) is likely incorrect. - -Errors raised by autorest objects and methods will conform to the `autorest.Error` interface. - -See the included examples for more detail. For details on the suggested use of this package by -generated clients, see the Client described below. - -## Helpers - -### Handling Swagger Dates - -The Swagger specification (https://swagger.io) that drives AutoRest -(https://github.com/Azure/autorest/) precisely defines two date forms: date and date-time. The -github.com/Azure/go-autorest/autorest/date package provides time.Time derivations to ensure correct -parsing and formatting. - -### Handling Empty Values - -In JSON, missing values have different semantics than empty values. This is especially true for -services using the HTTP PATCH verb. The JSON submitted with a PATCH request generally contains -only those values to modify. Missing values are to be left unchanged. Developers, then, require a -means to both specify an empty value and to leave the value out of the submitted JSON. - -The Go JSON package (`encoding/json`) supports the `omitempty` tag. When specified, it omits -empty values from the rendered JSON. Since Go defines default values for all base types (such as "" -for string and 0 for int) and provides no means to mark a value as actually empty, the JSON package -treats default values as meaning empty, omitting them from the rendered JSON. This means that, using -the Go base types encoded through the default JSON package, it is not possible to create JSON to -clear a value at the server. - -The workaround within the Go community is to use pointers to base types in lieu of base types within -structures that map to JSON. For example, instead of a value of type `string`, the workaround uses -`*string`. While this enables distinguishing empty values from those to be unchanged, creating -pointers to a base type (notably constant, in-line values) requires additional variables. This, for -example, - -```go - s := struct { - S *string - }{ S: &"foo" } -``` -fails, while, this - -```go - v := "foo" - s := struct { - S *string - }{ S: &v } -``` -succeeds. - -To ease using pointers, the subpackage `to` contains helpers that convert to and from pointers for -Go base types which have Swagger analogs. It also provides a helper that converts between -`map[string]string` and `map[string]*string`, enabling the JSON to specify that the value -associated with a key should be cleared. With the helpers, the previous example becomes - -```go - s := struct { - S *string - }{ S: to.StringPtr("foo") } -``` - -## Install - -```bash -go get github.com/Azure/go-autorest/autorest -go get github.com/Azure/go-autorest/autorest/azure -go get github.com/Azure/go-autorest/autorest/date -go get github.com/Azure/go-autorest/autorest/to -``` - -## License - -See LICENSE file. - ------ -This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. diff --git a/vendor/github.com/Azure/go-autorest/autorest/autorest_test.go b/vendor/github.com/Azure/go-autorest/autorest/autorest_test.go deleted file mode 100644 index 58f650114..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/autorest_test.go +++ /dev/null @@ -1,126 +0,0 @@ -package autorest - -import ( - "net/http" - "testing" - - "github.com/Azure/go-autorest/autorest/mocks" -) - -func TestResponseHasStatusCode(t *testing.T) { - codes := []int{http.StatusOK, http.StatusAccepted} - resp := &http.Response{StatusCode: http.StatusAccepted} - if !ResponseHasStatusCode(resp, codes...) { - t.Fatalf("autorest: ResponseHasStatusCode failed to find %v in %v", resp.StatusCode, codes) - } -} - -func TestResponseHasStatusCodeNotPresent(t *testing.T) { - codes := []int{http.StatusOK, http.StatusAccepted} - resp := &http.Response{StatusCode: http.StatusInternalServerError} - if ResponseHasStatusCode(resp, codes...) { - t.Fatalf("autorest: ResponseHasStatusCode unexpectedly found %v in %v", resp.StatusCode, codes) - } -} - -func TestNewPollingRequestDoesNotReturnARequestWhenLocationHeaderIsMissing(t *testing.T) { - resp := mocks.NewResponseWithStatus("500 InternalServerError", http.StatusInternalServerError) - - req, _ := NewPollingRequest(resp, nil) - if req != nil { - t.Fatal("autorest: NewPollingRequest returned an http.Request when the Location header was missing") - } -} - -func TestNewPollingRequestReturnsAnErrorWhenPrepareFails(t *testing.T) { - resp := mocks.NewResponseWithStatus("202 Accepted", http.StatusAccepted) - mocks.SetAcceptedHeaders(resp) - resp.Header.Set(http.CanonicalHeaderKey(HeaderLocation), mocks.TestBadURL) - - _, err := NewPollingRequest(resp, nil) - if err == nil { - t.Fatal("autorest: NewPollingRequest failed to return an error when Prepare fails") - } -} - -func TestNewPollingRequestDoesNotReturnARequestWhenPrepareFails(t *testing.T) { - resp := mocks.NewResponseWithStatus("202 Accepted", http.StatusAccepted) - mocks.SetAcceptedHeaders(resp) - resp.Header.Set(http.CanonicalHeaderKey(HeaderLocation), mocks.TestBadURL) - - req, _ := NewPollingRequest(resp, nil) - if req != nil { - t.Fatal("autorest: NewPollingRequest returned an http.Request when Prepare failed") - } -} - -func TestNewPollingRequestReturnsAGetRequest(t *testing.T) { - resp := mocks.NewResponseWithStatus("202 Accepted", http.StatusAccepted) - mocks.SetAcceptedHeaders(resp) - - req, _ := NewPollingRequest(resp, nil) - if req.Method != "GET" { - t.Fatalf("autorest: NewPollingRequest did not create an HTTP GET request -- actual method %v", req.Method) - } -} - -func TestNewPollingRequestProvidesTheURL(t *testing.T) { - resp := mocks.NewResponseWithStatus("202 Accepted", http.StatusAccepted) - mocks.SetAcceptedHeaders(resp) - - req, _ := NewPollingRequest(resp, nil) - if req.URL.String() != mocks.TestURL { - t.Fatalf("autorest: NewPollingRequest did not create an HTTP with the expected URL -- received %v, expected %v", req.URL, mocks.TestURL) - } -} - -func TestGetLocation(t *testing.T) { - resp := mocks.NewResponseWithStatus("202 Accepted", http.StatusAccepted) - mocks.SetAcceptedHeaders(resp) - - l := GetLocation(resp) - if len(l) == 0 { - t.Fatalf("autorest: GetLocation failed to return Location header -- expected %v, received %v", mocks.TestURL, l) - } -} - -func TestGetLocationReturnsEmptyStringForMissingLocation(t *testing.T) { - resp := mocks.NewResponseWithStatus("202 Accepted", http.StatusAccepted) - - l := GetLocation(resp) - if len(l) != 0 { - t.Fatalf("autorest: GetLocation return a value without a Location header -- received %v", l) - } -} - -func TestGetRetryAfter(t *testing.T) { - resp := mocks.NewResponseWithStatus("202 Accepted", http.StatusAccepted) - mocks.SetAcceptedHeaders(resp) - - d := GetRetryAfter(resp, DefaultPollingDelay) - if d != mocks.TestDelay { - t.Fatalf("autorest: GetRetryAfter failed to returned the expected delay -- expected %v, received %v", mocks.TestDelay, d) - } -} - -func TestGetRetryAfterReturnsDefaultDelayIfRetryHeaderIsMissing(t *testing.T) { - resp := mocks.NewResponseWithStatus("202 Accepted", http.StatusAccepted) - - d := GetRetryAfter(resp, DefaultPollingDelay) - if d != DefaultPollingDelay { - t.Fatalf("autorest: GetRetryAfter failed to returned the default delay for a missing Retry-After header -- expected %v, received %v", - DefaultPollingDelay, d) - } -} - -func TestGetRetryAfterReturnsDefaultDelayIfRetryHeaderIsMalformed(t *testing.T) { - resp := mocks.NewResponseWithStatus("202 Accepted", http.StatusAccepted) - mocks.SetAcceptedHeaders(resp) - resp.Header.Set(http.CanonicalHeaderKey(HeaderRetryAfter), "a very bad non-integer value") - - d := GetRetryAfter(resp, DefaultPollingDelay) - if d != DefaultPollingDelay { - t.Fatalf("autorest: GetRetryAfter failed to returned the default delay for a malformed Retry-After header -- expected %v, received %v", - DefaultPollingDelay, d) - } -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/async_test.go b/vendor/github.com/Azure/go-autorest/autorest/azure/async_test.go deleted file mode 100644 index 0a06b0b15..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/azure/async_test.go +++ /dev/null @@ -1,1115 +0,0 @@ -package azure - -import ( - "fmt" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/mocks" - "io/ioutil" - "net/http" - "reflect" - "strings" - "sync" - "testing" - "time" -) - -func TestGetAsyncOperation_ReturnsAzureAsyncOperationHeader(t *testing.T) { - r := newAsynchronousResponse() - - if getAsyncOperation(r) != mocks.TestAzureAsyncURL { - t.Fatalf("azure: getAsyncOperation failed to extract the Azure-AsyncOperation header -- expected %v, received %v", mocks.TestURL, getAsyncOperation(r)) - } -} - -func TestGetAsyncOperation_ReturnsEmptyStringIfHeaderIsAbsent(t *testing.T) { - r := mocks.NewResponse() - - if len(getAsyncOperation(r)) != 0 { - t.Fatalf("azure: getAsyncOperation failed to return empty string when the Azure-AsyncOperation header is absent -- received %v", getAsyncOperation(r)) - } -} - -func TestHasSucceeded_ReturnsTrueForSuccess(t *testing.T) { - if !hasSucceeded(operationSucceeded) { - t.Fatal("azure: hasSucceeded failed to return true for success") - } -} - -func TestHasSucceeded_ReturnsFalseOtherwise(t *testing.T) { - if hasSucceeded("not a success string") { - t.Fatal("azure: hasSucceeded returned true for a non-success") - } -} - -func TestHasTerminated_ReturnsTrueForValidTerminationStates(t *testing.T) { - for _, state := range []string{operationSucceeded, operationCanceled, operationFailed} { - if !hasTerminated(state) { - t.Fatalf("azure: hasTerminated failed to return true for the '%s' state", state) - } - } -} - -func TestHasTerminated_ReturnsFalseForUnknownStates(t *testing.T) { - if hasTerminated("not a known state") { - t.Fatal("azure: hasTerminated returned true for an unknown state") - } -} - -func TestOperationError_ErrorReturnsAString(t *testing.T) { - s := (ServiceError{Code: "server code", Message: "server error"}).Error() - if s == "" { - t.Fatalf("azure: operationError#Error failed to return an error") - } - if !strings.Contains(s, "server code") || !strings.Contains(s, "server error") { - t.Fatalf("azure: operationError#Error returned a malformed error -- error='%v'", s) - } -} - -func TestOperationResource_StateReturnsState(t *testing.T) { - if (operationResource{Status: "state"}).state() != "state" { - t.Fatalf("azure: operationResource#state failed to return the correct state") - } -} - -func TestOperationResource_HasSucceededReturnsFalseIfNotSuccess(t *testing.T) { - if (operationResource{Status: "not a success string"}).hasSucceeded() { - t.Fatalf("azure: operationResource#hasSucceeded failed to return false for a canceled operation") - } -} - -func TestOperationResource_HasSucceededReturnsTrueIfSuccessful(t *testing.T) { - if !(operationResource{Status: operationSucceeded}).hasSucceeded() { - t.Fatalf("azure: operationResource#hasSucceeded failed to return true for a successful operation") - } -} - -func TestOperationResource_HasTerminatedReturnsTrueForKnownStates(t *testing.T) { - for _, state := range []string{operationSucceeded, operationCanceled, operationFailed} { - if !(operationResource{Status: state}).hasTerminated() { - t.Fatalf("azure: operationResource#hasTerminated failed to return true for the '%s' state", state) - } - } -} - -func TestOperationResource_HasTerminatedReturnsFalseForUnknownStates(t *testing.T) { - if (operationResource{Status: "not a known state"}).hasTerminated() { - t.Fatalf("azure: operationResource#hasTerminated returned true for a non-terminal operation") - } -} - -func TestProvisioningStatus_StateReturnsState(t *testing.T) { - if (provisioningStatus{Properties: provisioningProperties{"state"}}).state() != "state" { - t.Fatalf("azure: provisioningStatus#state failed to return the correct state") - } -} - -func TestProvisioningStatus_HasSucceededReturnsFalseIfNotSuccess(t *testing.T) { - if (provisioningStatus{Properties: provisioningProperties{"not a success string"}}).hasSucceeded() { - t.Fatalf("azure: provisioningStatus#hasSucceeded failed to return false for a canceled operation") - } -} - -func TestProvisioningStatus_HasSucceededReturnsTrueIfSuccessful(t *testing.T) { - if !(provisioningStatus{Properties: provisioningProperties{operationSucceeded}}).hasSucceeded() { - t.Fatalf("azure: provisioningStatus#hasSucceeded failed to return true for a successful operation") - } -} - -func TestProvisioningStatus_HasTerminatedReturnsTrueForKnownStates(t *testing.T) { - for _, state := range []string{operationSucceeded, operationCanceled, operationFailed} { - if !(provisioningStatus{Properties: provisioningProperties{state}}).hasTerminated() { - t.Fatalf("azure: provisioningStatus#hasTerminated failed to return true for the '%s' state", state) - } - } -} - -func TestProvisioningStatus_HasTerminatedReturnsFalseForUnknownStates(t *testing.T) { - if (provisioningStatus{Properties: provisioningProperties{"not a known state"}}).hasTerminated() { - t.Fatalf("azure: provisioningStatus#hasTerminated returned true for a non-terminal operation") - } -} - -func TestPollingState_HasSucceededReturnsFalseIfNotSuccess(t *testing.T) { - if (pollingState{state: "not a success string"}).hasSucceeded() { - t.Fatalf("azure: pollingState#hasSucceeded failed to return false for a canceled operation") - } -} - -func TestPollingState_HasSucceededReturnsTrueIfSuccessful(t *testing.T) { - if !(pollingState{state: operationSucceeded}).hasSucceeded() { - t.Fatalf("azure: pollingState#hasSucceeded failed to return true for a successful operation") - } -} - -func TestPollingState_HasTerminatedReturnsTrueForKnownStates(t *testing.T) { - for _, state := range []string{operationSucceeded, operationCanceled, operationFailed} { - if !(pollingState{state: state}).hasTerminated() { - t.Fatalf("azure: pollingState#hasTerminated failed to return true for the '%s' state", state) - } - } -} - -func TestPollingState_HasTerminatedReturnsFalseForUnknownStates(t *testing.T) { - if (pollingState{state: "not a known state"}).hasTerminated() { - t.Fatalf("azure: pollingState#hasTerminated returned true for a non-terminal operation") - } -} - -func TestUpdatePollingState_ReturnsAnErrorIfOneOccurs(t *testing.T) { - resp := mocks.NewResponseWithContent(operationResourceIllegal) - err := updatePollingState(resp, &pollingState{}) - if err == nil { - t.Fatalf("azure: updatePollingState failed to return an error after a JSON parsing error") - } -} - -func TestUpdatePollingState_ReturnsTerminatedForKnownProvisioningStates(t *testing.T) { - for _, state := range []string{operationSucceeded, operationCanceled, operationFailed} { - resp := mocks.NewResponseWithContent(fmt.Sprintf(pollingStateFormat, state)) - resp.StatusCode = 42 - ps := &pollingState{responseFormat: usesProvisioningStatus} - updatePollingState(resp, ps) - if !ps.hasTerminated() { - t.Fatalf("azure: updatePollingState failed to return a terminating pollingState for the '%s' state", state) - } - } -} - -func TestUpdatePollingState_ReturnsSuccessForSuccessfulProvisioningState(t *testing.T) { - resp := mocks.NewResponseWithContent(fmt.Sprintf(pollingStateFormat, operationSucceeded)) - resp.StatusCode = 42 - ps := &pollingState{responseFormat: usesProvisioningStatus} - updatePollingState(resp, ps) - if !ps.hasSucceeded() { - t.Fatalf("azure: updatePollingState failed to return a successful pollingState for the '%s' state", operationSucceeded) - } -} - -func TestUpdatePollingState_ReturnsInProgressForAllOtherProvisioningStates(t *testing.T) { - s := "not a recognized state" - resp := mocks.NewResponseWithContent(fmt.Sprintf(pollingStateFormat, s)) - resp.StatusCode = 42 - ps := &pollingState{responseFormat: usesProvisioningStatus} - updatePollingState(resp, ps) - if ps.hasTerminated() { - t.Fatalf("azure: updatePollingState returned terminated for unknown state '%s'", s) - } -} - -func TestUpdatePollingState_ReturnsSuccessWhenProvisioningStateFieldIsAbsentForSuccessStatusCodes(t *testing.T) { - for _, sc := range []int{http.StatusOK, http.StatusCreated, http.StatusNoContent} { - resp := mocks.NewResponseWithContent(pollingStateEmpty) - resp.StatusCode = sc - ps := &pollingState{responseFormat: usesProvisioningStatus} - updatePollingState(resp, ps) - if !ps.hasSucceeded() { - t.Fatalf("azure: updatePollingState failed to return success when the provisionState field is absent for Status Code %d", sc) - } - } -} - -func TestUpdatePollingState_ReturnsInProgressWhenProvisioningStateFieldIsAbsentForAccepted(t *testing.T) { - resp := mocks.NewResponseWithContent(pollingStateEmpty) - resp.StatusCode = http.StatusAccepted - ps := &pollingState{responseFormat: usesProvisioningStatus} - updatePollingState(resp, ps) - if ps.hasTerminated() { - t.Fatalf("azure: updatePollingState returned terminated when the provisionState field is absent for Status Code Accepted") - } -} - -func TestUpdatePollingState_ReturnsFailedWhenProvisioningStateFieldIsAbsentForUnknownStatusCodes(t *testing.T) { - resp := mocks.NewResponseWithContent(pollingStateEmpty) - resp.StatusCode = 42 - ps := &pollingState{responseFormat: usesProvisioningStatus} - updatePollingState(resp, ps) - if !ps.hasTerminated() || ps.hasSucceeded() { - t.Fatalf("azure: updatePollingState did not return failed when the provisionState field is absent for an unknown Status Code") - } -} - -func TestUpdatePollingState_ReturnsTerminatedForKnownOperationResourceStates(t *testing.T) { - for _, state := range []string{operationSucceeded, operationCanceled, operationFailed} { - resp := mocks.NewResponseWithContent(fmt.Sprintf(operationResourceFormat, state)) - resp.StatusCode = 42 - ps := &pollingState{responseFormat: usesOperationResponse} - updatePollingState(resp, ps) - if !ps.hasTerminated() { - t.Fatalf("azure: updatePollingState failed to return a terminating pollingState for the '%s' state", state) - } - } -} - -func TestUpdatePollingState_ReturnsSuccessForSuccessfulOperationResourceState(t *testing.T) { - resp := mocks.NewResponseWithContent(fmt.Sprintf(operationResourceFormat, operationSucceeded)) - resp.StatusCode = 42 - ps := &pollingState{responseFormat: usesOperationResponse} - updatePollingState(resp, ps) - if !ps.hasSucceeded() { - t.Fatalf("azure: updatePollingState failed to return a successful pollingState for the '%s' state", operationSucceeded) - } -} - -func TestUpdatePollingState_ReturnsInProgressForAllOtherOperationResourceStates(t *testing.T) { - s := "not a recognized state" - resp := mocks.NewResponseWithContent(fmt.Sprintf(operationResourceFormat, s)) - resp.StatusCode = 42 - ps := &pollingState{responseFormat: usesOperationResponse} - updatePollingState(resp, ps) - if ps.hasTerminated() { - t.Fatalf("azure: updatePollingState returned terminated for unknown state '%s'", s) - } -} - -func TestUpdatePollingState_CopiesTheResponseBody(t *testing.T) { - s := fmt.Sprintf(pollingStateFormat, operationSucceeded) - resp := mocks.NewResponseWithContent(s) - resp.StatusCode = 42 - ps := &pollingState{responseFormat: usesOperationResponse} - updatePollingState(resp, ps) - b, err := ioutil.ReadAll(resp.Body) - if err != nil { - t.Fatalf("azure: updatePollingState failed to replace the http.Response Body -- Error='%v'", err) - } - if string(b) != s { - t.Fatalf("azure: updatePollingState failed to copy the http.Response Body -- Expected='%s' Received='%s'", s, string(b)) - } -} - -func TestUpdatePollingState_ClosesTheOriginalResponseBody(t *testing.T) { - resp := mocks.NewResponse() - b := resp.Body.(*mocks.Body) - ps := &pollingState{responseFormat: usesProvisioningStatus} - updatePollingState(resp, ps) - if b.IsOpen() { - t.Fatal("azure: updatePollingState failed to close the original http.Response Body") - } -} - -func TestUpdatePollingState_FailsWhenResponseLacksRequest(t *testing.T) { - resp := newAsynchronousResponse() - resp.Request = nil - - ps := pollingState{} - err := updatePollingState(resp, &ps) - if err == nil { - t.Fatal("azure: updatePollingState failed to return an error when the http.Response lacked the original http.Request") - } -} - -func TestUpdatePollingState_SetsTheResponseFormatWhenUsingTheAzureAsyncOperationHeader(t *testing.T) { - ps := pollingState{} - updatePollingState(newAsynchronousResponse(), &ps) - - if ps.responseFormat != usesOperationResponse { - t.Fatal("azure: updatePollingState failed to set the correct response format when using the Azure-AsyncOperation header") - } -} - -func TestUpdatePollingState_SetsTheResponseFormatWhenUsingTheAzureAsyncOperationHeaderIsMissing(t *testing.T) { - resp := newAsynchronousResponse() - resp.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation)) - - ps := pollingState{} - updatePollingState(resp, &ps) - - if ps.responseFormat != usesProvisioningStatus { - t.Fatal("azure: updatePollingState failed to set the correct response format when the Azure-AsyncOperation header is absent") - } -} - -func TestUpdatePollingState_DoesNotChangeAnExistingReponseFormat(t *testing.T) { - resp := newAsynchronousResponse() - resp.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation)) - - ps := pollingState{responseFormat: usesOperationResponse} - updatePollingState(resp, &ps) - - if ps.responseFormat != usesOperationResponse { - t.Fatal("azure: updatePollingState failed to leave an existing response format setting") - } -} - -func TestUpdatePollingState_PrefersTheAzureAsyncOperationHeader(t *testing.T) { - resp := newAsynchronousResponse() - - ps := pollingState{} - updatePollingState(resp, &ps) - - if ps.uri != mocks.TestAzureAsyncURL { - t.Fatal("azure: updatePollingState failed to prefer the Azure-AsyncOperation header") - } -} - -func TestUpdatePollingState_PrefersLocationWhenTheAzureAsyncOperationHeaderMissing(t *testing.T) { - resp := newAsynchronousResponse() - resp.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation)) - - ps := pollingState{} - updatePollingState(resp, &ps) - - if ps.uri != mocks.TestLocationURL { - t.Fatal("azure: updatePollingState failed to prefer the Location header when the Azure-AsyncOperation header is missing") - } -} - -func TestUpdatePollingState_UsesTheObjectLocationIfAsyncHeadersAreMissing(t *testing.T) { - resp := newAsynchronousResponse() - resp.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation)) - resp.Header.Del(http.CanonicalHeaderKey(autorest.HeaderLocation)) - resp.Request.Method = methodPatch - - ps := pollingState{} - updatePollingState(resp, &ps) - - if ps.uri != mocks.TestURL { - t.Fatal("azure: updatePollingState failed to use the Object URL when the asynchronous headers are missing") - } -} - -func TestUpdatePollingState_RecognizesLowerCaseHTTPVerbs(t *testing.T) { - for _, m := range []string{"patch", "put", "get"} { - resp := newAsynchronousResponse() - resp.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation)) - resp.Header.Del(http.CanonicalHeaderKey(autorest.HeaderLocation)) - resp.Request.Method = m - - ps := pollingState{} - updatePollingState(resp, &ps) - - if ps.uri != mocks.TestURL { - t.Fatalf("azure: updatePollingState failed to recognize the lower-case HTTP verb '%s'", m) - } - } -} - -func TestUpdatePollingState_ReturnsAnErrorIfAsyncHeadersAreMissingForANewOrDeletedObject(t *testing.T) { - resp := newAsynchronousResponse() - resp.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation)) - resp.Header.Del(http.CanonicalHeaderKey(autorest.HeaderLocation)) - - for _, m := range []string{methodDelete, methodPost} { - resp.Request.Method = m - err := updatePollingState(resp, &pollingState{}) - if err == nil { - t.Fatalf("azure: updatePollingState failed to return an error even though it could not determine the polling URL for Method '%s'", m) - } - } -} - -func TestNewPollingRequest_FailsWhenResponseLacksRequest(t *testing.T) { - resp := newAsynchronousResponse() - resp.Request = nil - - _, err := newPollingRequest(resp, pollingState{}) - if err == nil { - t.Fatal("azure: newPollingRequest failed to return an error when the http.Response lacked the original http.Request") - } -} - -func TestNewPollingRequest_ReturnsAnErrorWhenPrepareFails(t *testing.T) { - _, err := newPollingRequest(newAsynchronousResponse(), pollingState{responseFormat: usesOperationResponse, uri: mocks.TestBadURL}) - if err == nil { - t.Fatal("azure: newPollingRequest failed to return an error when Prepare fails") - } -} - -func TestNewPollingRequest_DoesNotReturnARequestWhenPrepareFails(t *testing.T) { - req, _ := newPollingRequest(newAsynchronousResponse(), pollingState{responseFormat: usesOperationResponse, uri: mocks.TestBadURL}) - if req != nil { - t.Fatal("azure: newPollingRequest returned an http.Request when Prepare failed") - } -} - -func TestNewPollingRequest_ReturnsAGetRequest(t *testing.T) { - req, _ := newPollingRequest(newAsynchronousResponse(), pollingState{responseFormat: usesOperationResponse, uri: mocks.TestAzureAsyncURL}) - if req.Method != "GET" { - t.Fatalf("azure: newPollingRequest did not create an HTTP GET request -- actual method %v", req.Method) - } -} - -func TestDoPollForAsynchronous_IgnoresUnspecifiedStatusCodes(t *testing.T) { - client := mocks.NewSender() - - r, _ := autorest.SendWithSender(client, mocks.NewRequest(), - DoPollForAsynchronous(time.Duration(0))) - - if client.Attempts() != 1 { - t.Fatalf("azure: DoPollForAsynchronous polled for unspecified status code") - } - - autorest.Respond(r, - autorest.ByClosing()) -} - -func TestDoPollForAsynchronous_PollsForSpecifiedStatusCodes(t *testing.T) { - client := mocks.NewSender() - client.AppendResponse(newAsynchronousResponse()) - - r, _ := autorest.SendWithSender(client, mocks.NewRequest(), - DoPollForAsynchronous(time.Millisecond)) - - if client.Attempts() != 2 { - t.Fatalf("azure: DoPollForAsynchronous failed to poll for specified status code") - } - - autorest.Respond(r, - autorest.ByClosing()) -} - -func TestDoPollForAsynchronous_CanBeCanceled(t *testing.T) { - cancel := make(chan struct{}) - delay := 5 * time.Second - - r1 := newAsynchronousResponse() - - client := mocks.NewSender() - client.AppendResponse(r1) - client.AppendAndRepeatResponse(newOperationResourceResponse("Busy"), -1) - - var wg sync.WaitGroup - wg.Add(1) - start := time.Now() - go func() { - req := mocks.NewRequest() - req.Cancel = cancel - - wg.Done() - - r, _ := autorest.SendWithSender(client, req, - DoPollForAsynchronous(10*time.Second)) - autorest.Respond(r, - autorest.ByClosing()) - }() - wg.Wait() - close(cancel) - time.Sleep(5 * time.Millisecond) - if time.Since(start) >= delay { - t.Fatalf("azure: DoPollForAsynchronous failed to cancel") - } -} - -func TestDoPollForAsynchronous_ClosesAllNonreturnedResponseBodiesWhenPolling(t *testing.T) { - r1 := newAsynchronousResponse() - b1 := r1.Body.(*mocks.Body) - r2 := newOperationResourceResponse("busy") - b2 := r2.Body.(*mocks.Body) - r3 := newOperationResourceResponse(operationSucceeded) - b3 := r3.Body.(*mocks.Body) - - client := mocks.NewSender() - client.AppendResponse(r1) - client.AppendAndRepeatResponse(r2, 2) - client.AppendResponse(r3) - - r, _ := autorest.SendWithSender(client, mocks.NewRequest(), - DoPollForAsynchronous(time.Millisecond)) - - if b1.IsOpen() || b2.IsOpen() || b3.IsOpen() { - t.Fatalf("azure: DoPollForAsynchronous did not close unreturned response bodies") - } - - autorest.Respond(r, - autorest.ByClosing()) -} - -func TestDoPollForAsynchronous_LeavesLastResponseBodyOpen(t *testing.T) { - r1 := newAsynchronousResponse() - r2 := newOperationResourceResponse("busy") - r3 := newOperationResourceResponse(operationSucceeded) - - client := mocks.NewSender() - client.AppendResponse(r1) - client.AppendAndRepeatResponse(r2, 2) - client.AppendResponse(r3) - - r, _ := autorest.SendWithSender(client, mocks.NewRequest(), - DoPollForAsynchronous(time.Millisecond)) - - b, err := ioutil.ReadAll(r.Body) - if len(b) <= 0 || err != nil { - t.Fatalf("azure: DoPollForAsynchronous did not leave open the body of the last response - Error='%v'", err) - } - - autorest.Respond(r, - autorest.ByClosing()) -} - -func TestDoPollForAsynchronous_DoesNotPollIfOriginalRequestReturnedAnError(t *testing.T) { - r1 := newAsynchronousResponse() - r2 := newOperationResourceResponse("busy") - - client := mocks.NewSender() - client.AppendResponse(r1) - client.AppendResponse(r2) - client.SetError(fmt.Errorf("Faux Error")) - - r, _ := autorest.SendWithSender(client, mocks.NewRequest(), - DoPollForAsynchronous(time.Millisecond)) - - if client.Attempts() != 1 { - t.Fatalf("azure: DoPollForAsynchronous tried to poll after receiving an error") - } - - autorest.Respond(r, - autorest.ByClosing()) -} - -func TestDoPollForAsynchronous_DoesNotPollIfCreatingOperationRequestFails(t *testing.T) { - r1 := newAsynchronousResponse() - mocks.SetResponseHeader(r1, http.CanonicalHeaderKey(headerAsyncOperation), mocks.TestBadURL) - r2 := newOperationResourceResponse("busy") - - client := mocks.NewSender() - client.AppendResponse(r1) - client.AppendAndRepeatResponse(r2, 2) - - r, _ := autorest.SendWithSender(client, mocks.NewRequest(), - DoPollForAsynchronous(time.Millisecond)) - - if client.Attempts() > 1 { - t.Fatalf("azure: DoPollForAsynchronous polled with an invalidly formed operation request") - } - - autorest.Respond(r, - autorest.ByClosing()) -} - -func TestDoPollForAsynchronous_StopsPollingAfterAnError(t *testing.T) { - r1 := newAsynchronousResponse() - r2 := newOperationResourceResponse("busy") - - client := mocks.NewSender() - client.AppendResponse(r1) - client.AppendAndRepeatResponse(r2, 2) - client.SetError(fmt.Errorf("Faux Error")) - client.SetEmitErrorAfter(2) - - r, _ := autorest.SendWithSender(client, mocks.NewRequest(), - DoPollForAsynchronous(time.Millisecond)) - - if client.Attempts() > 3 { - t.Fatalf("azure: DoPollForAsynchronous failed to stop polling after receiving an error") - } - - autorest.Respond(r, - autorest.ByClosing()) -} - -func TestDoPollForAsynchronous_ReturnsPollingError(t *testing.T) { - client := mocks.NewSender() - client.AppendAndRepeatResponse(newAsynchronousResponse(), 5) - client.SetError(fmt.Errorf("Faux Error")) - client.SetEmitErrorAfter(1) - - r, err := autorest.SendWithSender(client, mocks.NewRequest(), - DoPollForAsynchronous(time.Millisecond)) - - if err == nil { - t.Fatalf("azure: DoPollForAsynchronous failed to return error from polling") - } - - autorest.Respond(r, - autorest.ByClosing()) -} - -func TestDoPollForAsynchronous_PollsForStatusAccepted(t *testing.T) { - r1 := newAsynchronousResponse() - r1.Status = "202 Accepted" - r1.StatusCode = http.StatusAccepted - r2 := newOperationResourceResponse("busy") - r3 := newOperationResourceResponse(operationCanceled) - - client := mocks.NewSender() - client.AppendResponse(r1) - client.AppendAndRepeatResponse(r2, 2) - client.AppendAndRepeatResponse(r3, 1) - - r, _ := autorest.SendWithSender(client, mocks.NewRequest(), - DoPollForAsynchronous(time.Millisecond)) - - if client.Attempts() < 4 { - t.Fatalf("azure: DoPollForAsynchronous stopped polling before receiving a terminated OperationResource") - } - - autorest.Respond(r, - autorest.ByClosing()) -} - -func TestDoPollForAsynchronous_PollsForStatusCreated(t *testing.T) { - r1 := newAsynchronousResponse() - r1.Status = "201 Created" - r1.StatusCode = http.StatusCreated - r2 := newOperationResourceResponse("busy") - r3 := newOperationResourceResponse(operationCanceled) - - client := mocks.NewSender() - client.AppendResponse(r1) - client.AppendAndRepeatResponse(r2, 2) - client.AppendAndRepeatResponse(r3, 1) - - r, _ := autorest.SendWithSender(client, mocks.NewRequest(), - DoPollForAsynchronous(time.Millisecond)) - - if client.Attempts() < 4 { - t.Fatalf("azure: DoPollForAsynchronous stopped polling before receiving a terminated OperationResource") - } - - autorest.Respond(r, - autorest.ByClosing()) -} - -func TestDoPollForAsynchronous_PollsUntilProvisioningStatusTerminates(t *testing.T) { - r1 := newAsynchronousResponse() - r1.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation)) - r2 := newProvisioningStatusResponse("busy") - r2.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation)) - r3 := newProvisioningStatusResponse(operationCanceled) - r3.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation)) - - client := mocks.NewSender() - client.AppendResponse(r1) - client.AppendAndRepeatResponse(r2, 2) - client.AppendAndRepeatResponse(r3, 1) - - r, _ := autorest.SendWithSender(client, mocks.NewRequest(), - DoPollForAsynchronous(time.Millisecond)) - - if client.Attempts() < 4 { - t.Fatalf("azure: DoPollForAsynchronous stopped polling before receiving a terminated OperationResource") - } - - autorest.Respond(r, - autorest.ByClosing()) -} - -func TestDoPollForAsynchronous_PollsUntilProvisioningStatusSucceeds(t *testing.T) { - r1 := newAsynchronousResponse() - r1.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation)) - r2 := newProvisioningStatusResponse("busy") - r2.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation)) - r3 := newProvisioningStatusResponse(operationSucceeded) - r3.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation)) - - client := mocks.NewSender() - client.AppendResponse(r1) - client.AppendAndRepeatResponse(r2, 2) - client.AppendAndRepeatResponse(r3, 1) - - r, _ := autorest.SendWithSender(client, mocks.NewRequest(), - DoPollForAsynchronous(time.Millisecond)) - - if client.Attempts() < 4 { - t.Fatalf("azure: DoPollForAsynchronous stopped polling before receiving a terminated OperationResource") - } - - autorest.Respond(r, - autorest.ByClosing()) -} - -func TestDoPollForAsynchronous_PollsUntilOperationResourceHasTerminated(t *testing.T) { - r1 := newAsynchronousResponse() - r2 := newOperationResourceResponse("busy") - r3 := newOperationResourceResponse(operationCanceled) - - client := mocks.NewSender() - client.AppendResponse(r1) - client.AppendAndRepeatResponse(r2, 2) - client.AppendAndRepeatResponse(r3, 1) - - r, _ := autorest.SendWithSender(client, mocks.NewRequest(), - DoPollForAsynchronous(time.Millisecond)) - - if client.Attempts() < 4 { - t.Fatalf("azure: DoPollForAsynchronous stopped polling before receiving a terminated OperationResource") - } - - autorest.Respond(r, - autorest.ByClosing()) -} - -func TestDoPollForAsynchronous_PollsUntilOperationResourceHasSucceeded(t *testing.T) { - r1 := newAsynchronousResponse() - r2 := newOperationResourceResponse("busy") - r3 := newOperationResourceResponse(operationSucceeded) - - client := mocks.NewSender() - client.AppendResponse(r1) - client.AppendAndRepeatResponse(r2, 2) - client.AppendAndRepeatResponse(r3, 1) - - r, _ := autorest.SendWithSender(client, mocks.NewRequest(), - DoPollForAsynchronous(time.Millisecond)) - - if client.Attempts() < 4 { - t.Fatalf("azure: DoPollForAsynchronous stopped polling before receiving a terminated OperationResource") - } - - autorest.Respond(r, - autorest.ByClosing()) -} - -func TestDoPollForAsynchronous_StopsPollingWhenOperationResourceHasTerminated(t *testing.T) { - r1 := newAsynchronousResponse() - r2 := newOperationResourceResponse("busy") - r3 := newOperationResourceResponse(operationCanceled) - - client := mocks.NewSender() - client.AppendResponse(r1) - client.AppendAndRepeatResponse(r2, 2) - client.AppendAndRepeatResponse(r3, 2) - - r, _ := autorest.SendWithSender(client, mocks.NewRequest(), - DoPollForAsynchronous(time.Millisecond)) - - if client.Attempts() > 4 { - t.Fatalf("azure: DoPollForAsynchronous failed to stop after receiving a terminated OperationResource") - } - - autorest.Respond(r, - autorest.ByClosing()) -} - -func TestDoPollForAsynchronous_ReturnsAnErrorForCanceledOperations(t *testing.T) { - r1 := newAsynchronousResponse() - r2 := newOperationResourceResponse("busy") - r3 := newOperationResourceErrorResponse(operationCanceled) - - client := mocks.NewSender() - client.AppendResponse(r1) - client.AppendAndRepeatResponse(r2, 2) - client.AppendAndRepeatResponse(r3, 1) - - r, err := autorest.SendWithSender(client, mocks.NewRequest(), - DoPollForAsynchronous(time.Millisecond)) - - if err == nil || !strings.Contains(fmt.Sprintf("%v", err), "Canceled") { - t.Fatalf("azure: DoPollForAsynchronous failed to return an appropriate error for a canceled OperationResource") - } - - autorest.Respond(r, - autorest.ByClosing()) -} - -func TestDoPollForAsynchronous_ReturnsAnErrorForFailedOperations(t *testing.T) { - r1 := newAsynchronousResponse() - r2 := newOperationResourceResponse("busy") - r3 := newOperationResourceErrorResponse(operationFailed) - - client := mocks.NewSender() - client.AppendResponse(r1) - client.AppendAndRepeatResponse(r2, 2) - client.AppendAndRepeatResponse(r3, 1) - - r, err := autorest.SendWithSender(client, mocks.NewRequest(), - DoPollForAsynchronous(time.Millisecond)) - - if err == nil || !strings.Contains(fmt.Sprintf("%v", err), "Failed") { - t.Fatalf("azure: DoPollForAsynchronous failed to return an appropriate error for a canceled OperationResource") - } - - autorest.Respond(r, - autorest.ByClosing()) -} - -func TestDoPollForAsynchronous_WithNilURI(t *testing.T) { - r1 := newAsynchronousResponse() - r1.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation)) - r1.Header.Del(http.CanonicalHeaderKey(autorest.HeaderLocation)) - - r2 := newOperationResourceResponse("busy") - r2.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation)) - r2.Header.Del(http.CanonicalHeaderKey(autorest.HeaderLocation)) - - client := mocks.NewSender() - client.AppendResponse(r1) - client.AppendResponse(r2) - - req, _ := http.NewRequest("POST", "https://microsoft.com/a/b/c/", mocks.NewBody("")) - r, err := autorest.SendWithSender(client, req, - DoPollForAsynchronous(time.Millisecond)) - - if err == nil { - t.Fatalf("azure: DoPollForAsynchronous failed to return error for nil URI. got: nil; want: Azure Polling Error - Unable to obtain polling URI for POST") - } - - autorest.Respond(r, - autorest.ByClosing()) -} - -func TestDoPollForAsynchronous_ReturnsAnUnknownErrorForFailedOperations(t *testing.T) { - // Return unknown error if error not present in last response - r1 := newAsynchronousResponse() - r1.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation)) - r2 := newProvisioningStatusResponse("busy") - r2.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation)) - r3 := newProvisioningStatusResponse(operationFailed) - r3.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation)) - - client := mocks.NewSender() - client.AppendResponse(r1) - client.AppendAndRepeatResponse(r2, 2) - client.AppendAndRepeatResponse(r3, 1) - - r, err := autorest.SendWithSender(client, mocks.NewRequest(), - DoPollForAsynchronous(time.Millisecond)) - - expected := makeLongRunningOperationErrorString("Unknown", "None") - if err.Error() != expected { - t.Fatalf("azure: DoPollForAsynchronous failed to return an appropriate error message for an unknown error. \n expected=%q \n got=%q", - expected, err.Error()) - } - - autorest.Respond(r, - autorest.ByClosing()) -} - -func TestDoPollForAsynchronous_ReturnsErrorForLastErrorResponse(t *testing.T) { - // Return error code and message if error present in last response - r1 := newAsynchronousResponse() - r1.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation)) - r2 := newProvisioningStatusResponse("busy") - r2.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation)) - r3 := newAsynchronousResponseWithError() - r3.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation)) - - client := mocks.NewSender() - client.AppendResponse(r1) - client.AppendAndRepeatResponse(r2, 2) - client.AppendAndRepeatResponse(r3, 1) - - r, err := autorest.SendWithSender(client, mocks.NewRequest(), - DoPollForAsynchronous(time.Millisecond)) - - expected := makeLongRunningOperationErrorString("InvalidParameter", "tom-service-DISCOVERY-server-base-v1.core.local' is not a valid captured VHD blob name prefix.") - if err.Error() != expected { - t.Fatalf("azure: DoPollForAsynchronous failed to return an appropriate error message for an unknown error. \n expected=%q \n got=%q", - expected, err.Error()) - } - - autorest.Respond(r, - autorest.ByClosing()) -} - -func TestDoPollForAsynchronous_ReturnsOperationResourceErrorForFailedOperations(t *testing.T) { - // Return Operation resource response with error code and message in last operation resource response - r1 := newAsynchronousResponse() - r2 := newOperationResourceResponse("busy") - r3 := newOperationResourceErrorResponse(operationFailed) - - client := mocks.NewSender() - client.AppendResponse(r1) - client.AppendAndRepeatResponse(r2, 2) - client.AppendAndRepeatResponse(r3, 1) - - r, err := autorest.SendWithSender(client, mocks.NewRequest(), - DoPollForAsynchronous(time.Millisecond)) - - expected := makeLongRunningOperationErrorString("BadArgument", "The provided database 'foo' has an invalid username.") - if err.Error() != expected { - t.Fatalf("azure: DoPollForAsynchronous failed to return an appropriate error message for a failed Operations. \n expected=%q \n got=%q", - expected, err.Error()) - } - - autorest.Respond(r, - autorest.ByClosing()) -} - -func TestDoPollForAsynchronous_ReturnsErrorForFirstPutRequest(t *testing.T) { - // Return 400 bad response with error code and message in first put - r1 := newAsynchronousResponseWithError() - client := mocks.NewSender() - client.AppendResponse(r1) - - res, err := autorest.SendWithSender(client, mocks.NewRequest(), - DoPollForAsynchronous(time.Millisecond)) - if err != nil { - t.Fatalf("azure: DoPollForAsynchronous failed to return an appropriate error message for a failed Operations. \n expected=%q \n got=%q", - errorResponse, err.Error()) - } - - err = autorest.Respond(res, - WithErrorUnlessStatusCode(http.StatusAccepted, http.StatusCreated, http.StatusOK), - autorest.ByClosing()) - - reqError, ok := err.(*RequestError) - if !ok { - t.Fatalf("azure: returned error is not azure.RequestError: %T", err) - } - - expected := &RequestError{ - ServiceError: &ServiceError{ - Code: "InvalidParameter", - Message: "tom-service-DISCOVERY-server-base-v1.core.local' is not a valid captured VHD blob name prefix.", - }, - DetailedError: autorest.DetailedError{ - StatusCode: 400, - }, - } - if !reflect.DeepEqual(reqError, expected) { - t.Fatalf("azure: wrong error. expected=%q\ngot=%q", expected, reqError) - } - - defer res.Body.Close() - b, err := ioutil.ReadAll(res.Body) - if err != nil { - t.Fatal(err) - } - if string(b) != errorResponse { - t.Fatalf("azure: Response body is wrong. got=%q expected=%q", string(b), errorResponse) - } - -} - -func TestDoPollForAsynchronous_ReturnsNoErrorForSuccessfulOperations(t *testing.T) { - r1 := newAsynchronousResponse() - r2 := newOperationResourceResponse("busy") - r3 := newOperationResourceErrorResponse(operationSucceeded) - - client := mocks.NewSender() - client.AppendResponse(r1) - client.AppendAndRepeatResponse(r2, 2) - client.AppendAndRepeatResponse(r3, 1) - - r, err := autorest.SendWithSender(client, mocks.NewRequest(), - DoPollForAsynchronous(time.Millisecond)) - - if err != nil { - t.Fatalf("azure: DoPollForAsynchronous returned an error for a successful OperationResource") - } - - autorest.Respond(r, - autorest.ByClosing()) -} - -func TestDoPollForAsynchronous_StopsPollingIfItReceivesAnInvalidOperationResource(t *testing.T) { - r1 := newAsynchronousResponse() - r2 := newOperationResourceResponse("busy") - r3 := newOperationResourceResponse("busy") - r3.Body = mocks.NewBody(operationResourceIllegal) - r4 := newOperationResourceResponse(operationSucceeded) - - client := mocks.NewSender() - client.AppendResponse(r1) - client.AppendAndRepeatResponse(r2, 2) - client.AppendAndRepeatResponse(r3, 1) - client.AppendAndRepeatResponse(r4, 1) - - r, err := autorest.SendWithSender(client, mocks.NewRequest(), - DoPollForAsynchronous(time.Millisecond)) - - if client.Attempts() > 4 { - t.Fatalf("azure: DoPollForAsynchronous failed to stop polling after receiving an invalid OperationResource") - } - if err == nil { - t.Fatalf("azure: DoPollForAsynchronous failed to return an error after receving an invalid OperationResource") - } - - autorest.Respond(r, - autorest.ByClosing()) -} - -const ( - operationResourceIllegal = ` - This is not JSON and should fail...badly. - ` - pollingStateFormat = ` - { - "unused" : { - "somefield" : 42 - }, - "properties" : { - "provisioningState": "%s" - } - } - ` - - errorResponse = ` - { - "error" : { - "code" : "InvalidParameter", - "message" : "tom-service-DISCOVERY-server-base-v1.core.local' is not a valid captured VHD blob name prefix." - } - } - ` - - pollingStateEmpty = ` - { - "unused" : { - "somefield" : 42 - }, - "properties" : { - } - } - ` - - operationResourceFormat = ` - { - "id": "/subscriptions/id/locations/westus/operationsStatus/sameguid", - "name": "sameguid", - "status" : "%s", - "startTime" : "2006-01-02T15:04:05Z", - "endTime" : "2006-01-02T16:04:05Z", - "percentComplete" : 50.00, - - "properties" : {} - } - ` - - operationResourceErrorFormat = ` - { - "id": "/subscriptions/id/locations/westus/operationsStatus/sameguid", - "name": "sameguid", - "status" : "%s", - "startTime" : "2006-01-02T15:04:05Z", - "endTime" : "2006-01-02T16:04:05Z", - "percentComplete" : 50.00, - - "properties" : {}, - "error" : { - "code" : "BadArgument", - "message" : "The provided database 'foo' has an invalid username." - } - } - ` -) - -func newAsynchronousResponse() *http.Response { - r := mocks.NewResponseWithStatus("201 Created", http.StatusCreated) - r.Body = mocks.NewBody(fmt.Sprintf(pollingStateFormat, operationInProgress)) - mocks.SetResponseHeader(r, http.CanonicalHeaderKey(headerAsyncOperation), mocks.TestAzureAsyncURL) - mocks.SetResponseHeader(r, http.CanonicalHeaderKey(autorest.HeaderLocation), mocks.TestLocationURL) - mocks.SetRetryHeader(r, retryDelay) - r.Request = mocks.NewRequestForURL(mocks.TestURL) - return r -} - -func newAsynchronousResponseWithError() *http.Response { - r := mocks.NewResponseWithStatus("400 Bad Request", http.StatusBadRequest) - mocks.SetRetryHeader(r, retryDelay) - r.Request = mocks.NewRequestForURL(mocks.TestURL) - r.Body = mocks.NewBody(errorResponse) - return r -} - -func newOperationResourceResponse(status string) *http.Response { - r := newAsynchronousResponse() - r.Body = mocks.NewBody(fmt.Sprintf(operationResourceFormat, status)) - return r -} - -func newOperationResourceErrorResponse(status string) *http.Response { - r := newAsynchronousResponse() - r.Body = mocks.NewBody(fmt.Sprintf(operationResourceErrorFormat, status)) - return r -} - -func newProvisioningStatusResponse(status string) *http.Response { - r := newAsynchronousResponse() - r.Body = mocks.NewBody(fmt.Sprintf(pollingStateFormat, status)) - return r -} - -func makeLongRunningOperationErrorString(code string, message string) string { - return fmt.Sprintf("Long running operation terminated with status 'Failed': Code=%q Message=%q", code, message) -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/azure_test.go b/vendor/github.com/Azure/go-autorest/autorest/azure/azure_test.go deleted file mode 100644 index ff014b518..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/azure/azure_test.go +++ /dev/null @@ -1,431 +0,0 @@ -package azure - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "reflect" - "strconv" - "testing" - "time" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/mocks" -) - -const ( - headerAuthorization = "Authorization" - longDelay = 5 * time.Second - retryDelay = 10 * time.Millisecond - testLogPrefix = "azure:" -) - -// Use a Client Inspector to set the request identifier. -func ExampleWithClientID() { - uuid := "71FDB9F4-5E49-4C12-B266-DE7B4FD999A6" - req, _ := autorest.Prepare(&http.Request{}, - autorest.AsGet(), - autorest.WithBaseURL("https://microsoft.com/a/b/c/")) - - c := autorest.Client{Sender: mocks.NewSender()} - c.RequestInspector = WithReturningClientID(uuid) - - autorest.SendWithSender(c, req) - fmt.Printf("Inspector added the %s header with the value %s\n", - HeaderClientID, req.Header.Get(HeaderClientID)) - fmt.Printf("Inspector added the %s header with the value %s\n", - HeaderReturnClientID, req.Header.Get(HeaderReturnClientID)) - // Output: - // Inspector added the x-ms-client-request-id header with the value 71FDB9F4-5E49-4C12-B266-DE7B4FD999A6 - // Inspector added the x-ms-return-client-request-id header with the value true -} - -func TestWithReturningClientIDReturnsError(t *testing.T) { - var errIn error - uuid := "71FDB9F4-5E49-4C12-B266-DE7B4FD999A6" - _, errOut := autorest.Prepare(&http.Request{}, - withErrorPrepareDecorator(&errIn), - WithReturningClientID(uuid)) - - if errOut == nil || errIn != errOut { - t.Fatalf("azure: WithReturningClientID failed to exit early when receiving an error -- expected (%v), received (%v)", - errIn, errOut) - } -} - -func TestWithClientID(t *testing.T) { - uuid := "71FDB9F4-5E49-4C12-B266-DE7B4FD999A6" - req, _ := autorest.Prepare(&http.Request{}, - WithClientID(uuid)) - - if req.Header.Get(HeaderClientID) != uuid { - t.Fatalf("azure: WithClientID failed to set %s -- expected %s, received %s", - HeaderClientID, uuid, req.Header.Get(HeaderClientID)) - } -} - -func TestWithReturnClientID(t *testing.T) { - b := false - req, _ := autorest.Prepare(&http.Request{}, - WithReturnClientID(b)) - - if req.Header.Get(HeaderReturnClientID) != strconv.FormatBool(b) { - t.Fatalf("azure: WithReturnClientID failed to set %s -- expected %s, received %s", - HeaderClientID, strconv.FormatBool(b), req.Header.Get(HeaderClientID)) - } -} - -func TestExtractClientID(t *testing.T) { - uuid := "71FDB9F4-5E49-4C12-B266-DE7B4FD999A6" - resp := mocks.NewResponse() - mocks.SetResponseHeader(resp, HeaderClientID, uuid) - - if ExtractClientID(resp) != uuid { - t.Fatalf("azure: ExtractClientID failed to extract the %s -- expected %s, received %s", - HeaderClientID, uuid, ExtractClientID(resp)) - } -} - -func TestExtractRequestID(t *testing.T) { - uuid := "71FDB9F4-5E49-4C12-B266-DE7B4FD999A6" - resp := mocks.NewResponse() - mocks.SetResponseHeader(resp, HeaderRequestID, uuid) - - if ExtractRequestID(resp) != uuid { - t.Fatalf("azure: ExtractRequestID failed to extract the %s -- expected %s, received %s", - HeaderRequestID, uuid, ExtractRequestID(resp)) - } -} - -func TestIsAzureError_ReturnsTrueForAzureError(t *testing.T) { - if !IsAzureError(&RequestError{}) { - t.Fatalf("azure: IsAzureError failed to return true for an Azure Service error") - } -} - -func TestIsAzureError_ReturnsFalseForNonAzureError(t *testing.T) { - if IsAzureError(fmt.Errorf("An Error")) { - t.Fatalf("azure: IsAzureError return true for an non-Azure Service error") - } -} - -func TestNewErrorWithError_UsesReponseStatusCode(t *testing.T) { - e := NewErrorWithError(fmt.Errorf("Error"), "packageType", "method", mocks.NewResponseWithStatus("Forbidden", http.StatusForbidden), "message") - if e.StatusCode != http.StatusForbidden { - t.Fatalf("azure: NewErrorWithError failed to use the Status Code of the passed Response -- expected %v, received %v", http.StatusForbidden, e.StatusCode) - } -} - -func TestNewErrorWithError_ReturnsUnwrappedError(t *testing.T) { - e1 := RequestError{} - e1.ServiceError = &ServiceError{Code: "42", Message: "A Message"} - e1.StatusCode = 200 - e1.RequestID = "A RequestID" - e2 := NewErrorWithError(&e1, "packageType", "method", nil, "message") - - if !reflect.DeepEqual(e1, e2) { - t.Fatalf("azure: NewErrorWithError wrapped an RequestError -- expected %T, received %T", e1, e2) - } -} - -func TestNewErrorWithError_WrapsAnError(t *testing.T) { - e1 := fmt.Errorf("Inner Error") - var e2 interface{} = NewErrorWithError(e1, "packageType", "method", nil, "message") - - if _, ok := e2.(RequestError); !ok { - t.Fatalf("azure: NewErrorWithError failed to wrap a standard error -- received %T", e2) - } -} - -func TestWithErrorUnlessStatusCode_NotAnAzureError(t *testing.T) { - body := ` - - IIS Error page - - Some non-JSON error page - ` - r := mocks.NewResponseWithContent(body) - r.Request = mocks.NewRequest() - r.StatusCode = http.StatusBadRequest - r.Status = http.StatusText(r.StatusCode) - - err := autorest.Respond(r, - WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - ok, _ := err.(*RequestError) - if ok != nil { - t.Fatalf("azure: azure.RequestError returned from malformed response: %v", err) - } - - // the error body should still be there - defer r.Body.Close() - b, err := ioutil.ReadAll(r.Body) - if err != nil { - t.Fatal(err) - } - if string(b) != body { - t.Fatalf("response body is wrong. got=%q exptected=%q", string(b), body) - } -} - -func TestWithErrorUnlessStatusCode_FoundAzureErrorWithoutDetails(t *testing.T) { - j := `{ - "error": { - "code": "InternalError", - "message": "Azure is having trouble right now." - } - }` - uuid := "71FDB9F4-5E49-4C12-B266-DE7B4FD999A6" - r := mocks.NewResponseWithContent(j) - mocks.SetResponseHeader(r, HeaderRequestID, uuid) - r.Request = mocks.NewRequest() - r.StatusCode = http.StatusInternalServerError - r.Status = http.StatusText(r.StatusCode) - - err := autorest.Respond(r, - WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - - if err == nil { - t.Fatalf("azure: returned nil error for proper error response") - } - azErr, ok := err.(*RequestError) - if !ok { - t.Fatalf("azure: returned error is not azure.RequestError: %T", err) - } - - expected := "autorest/azure: Service returned an error. Status=500 Code=\"InternalError\" Message=\"Azure is having trouble right now.\"" - if !reflect.DeepEqual(expected, azErr.Error()) { - t.Fatalf("azure: service error is not unmarshaled properly.\nexpected=%v\ngot=%v", expected, azErr.Error()) - } - - if expected := http.StatusInternalServerError; azErr.StatusCode != expected { - t.Fatalf("azure: got wrong StatusCode=%d Expected=%d", azErr.StatusCode, expected) - } - if expected := uuid; azErr.RequestID != expected { - t.Fatalf("azure: wrong request ID in error. expected=%q; got=%q", expected, azErr.RequestID) - } - - _ = azErr.Error() - - // the error body should still be there - defer r.Body.Close() - b, err := ioutil.ReadAll(r.Body) - if err != nil { - t.Fatal(err) - } - if string(b) != j { - t.Fatalf("response body is wrong. got=%q expected=%q", string(b), j) - } - -} - -func TestWithErrorUnlessStatusCode_FoundAzureErrorWithDetails(t *testing.T) { - j := `{ - "error": { - "code": "InternalError", - "message": "Azure is having trouble right now.", - "details": [{"code": "conflict1", "message":"error message1"}, - {"code": "conflict2", "message":"error message2"}] - } - }` - uuid := "71FDB9F4-5E49-4C12-B266-DE7B4FD999A6" - r := mocks.NewResponseWithContent(j) - mocks.SetResponseHeader(r, HeaderRequestID, uuid) - r.Request = mocks.NewRequest() - r.StatusCode = http.StatusInternalServerError - r.Status = http.StatusText(r.StatusCode) - - err := autorest.Respond(r, - WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - - if err == nil { - t.Fatalf("azure: returned nil error for proper error response") - } - azErr, ok := err.(*RequestError) - if !ok { - t.Fatalf("azure: returned error is not azure.RequestError: %T", err) - } - - if expected := "InternalError"; azErr.ServiceError.Code != expected { - t.Fatalf("azure: wrong error code. expected=%q; got=%q", expected, azErr.ServiceError.Code) - } - if azErr.ServiceError.Message == "" { - t.Fatalf("azure: error message is not unmarshaled properly") - } - b, _ := json.Marshal(*azErr.ServiceError.Details) - if string(b) != `[{"code":"conflict1","message":"error message1"},{"code":"conflict2","message":"error message2"}]` { - t.Fatalf("azure: error details is not unmarshaled properly") - } - - if expected := http.StatusInternalServerError; azErr.StatusCode != expected { - t.Fatalf("azure: got wrong StatusCode=%v Expected=%d", azErr.StatusCode, expected) - } - if expected := uuid; azErr.RequestID != expected { - t.Fatalf("azure: wrong request ID in error. expected=%q; got=%q", expected, azErr.RequestID) - } - - _ = azErr.Error() - - // the error body should still be there - defer r.Body.Close() - b, err = ioutil.ReadAll(r.Body) - if err != nil { - t.Fatal(err) - } - if string(b) != j { - t.Fatalf("response body is wrong. got=%q expected=%q", string(b), j) - } - -} - -func TestWithErrorUnlessStatusCode_NoAzureError(t *testing.T) { - j := `{ - "Status":"NotFound" - }` - uuid := "71FDB9F4-5E49-4C12-B266-DE7B4FD999A6" - r := mocks.NewResponseWithContent(j) - mocks.SetResponseHeader(r, HeaderRequestID, uuid) - r.Request = mocks.NewRequest() - r.StatusCode = http.StatusInternalServerError - r.Status = http.StatusText(r.StatusCode) - - err := autorest.Respond(r, - WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - if err == nil { - t.Fatalf("azure: returned nil error for proper error response") - } - azErr, ok := err.(*RequestError) - if !ok { - t.Fatalf("azure: returned error is not azure.RequestError: %T", err) - } - - expected := &ServiceError{ - Code: "Unknown", - Message: "Unknown service error", - } - - if !reflect.DeepEqual(expected, azErr.ServiceError) { - t.Fatalf("azure: service error is not unmarshaled properly. expected=%q\ngot=%q", expected, azErr.ServiceError) - } - - if expected := http.StatusInternalServerError; azErr.StatusCode != expected { - t.Fatalf("azure: got wrong StatusCode=%v Expected=%d", azErr.StatusCode, expected) - } - if expected := uuid; azErr.RequestID != expected { - t.Fatalf("azure: wrong request ID in error. expected=%q; got=%q", expected, azErr.RequestID) - } - - _ = azErr.Error() - - // the error body should still be there - defer r.Body.Close() - b, err := ioutil.ReadAll(r.Body) - if err != nil { - t.Fatal(err) - } - if string(b) != j { - t.Fatalf("response body is wrong. got=%q expected=%q", string(b), j) - } - -} - -func TestRequestErrorString_WithError(t *testing.T) { - j := `{ - "error": { - "code": "InternalError", - "message": "Conflict", - "details": [{"code": "conflict1", "message":"error message1"}] - } - }` - uuid := "71FDB9F4-5E49-4C12-B266-DE7B4FD999A6" - r := mocks.NewResponseWithContent(j) - mocks.SetResponseHeader(r, HeaderRequestID, uuid) - r.Request = mocks.NewRequest() - r.StatusCode = http.StatusInternalServerError - r.Status = http.StatusText(r.StatusCode) - - err := autorest.Respond(r, - WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - - if err == nil { - t.Fatalf("azure: returned nil error for proper error response") - } - azErr, _ := err.(*RequestError) - expected := "autorest/azure: Service returned an error. Status=500 Code=\"InternalError\" Message=\"Conflict\" Details=[{\"code\":\"conflict1\",\"message\":\"error message1\"}]" - if expected != azErr.Error() { - t.Fatalf("azure: send wrong RequestError.\nexpected=%v\ngot=%v", expected, azErr.Error()) - } -} - -func withErrorPrepareDecorator(e *error) autorest.PrepareDecorator { - return func(p autorest.Preparer) autorest.Preparer { - return autorest.PreparerFunc(func(r *http.Request) (*http.Request, error) { - *e = fmt.Errorf("azure: Faux Prepare Error") - return r, *e - }) - } -} - -func withAsyncResponseDecorator(n int) autorest.SendDecorator { - i := 0 - return func(s autorest.Sender) autorest.Sender { - return autorest.SenderFunc(func(r *http.Request) (*http.Response, error) { - resp, err := s.Do(r) - if err == nil { - if i < n { - resp.StatusCode = http.StatusCreated - resp.Header = http.Header{} - resp.Header.Add(http.CanonicalHeaderKey(headerAsyncOperation), mocks.TestURL) - i++ - } else { - resp.StatusCode = http.StatusOK - resp.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation)) - } - } - return resp, err - }) - } -} - -type mockAuthorizer struct{} - -func (ma mockAuthorizer) WithAuthorization() autorest.PrepareDecorator { - return autorest.WithHeader(headerAuthorization, mocks.TestAuthorizationHeader) -} - -type mockFailingAuthorizer struct{} - -func (mfa mockFailingAuthorizer) WithAuthorization() autorest.PrepareDecorator { - return func(p autorest.Preparer) autorest.Preparer { - return autorest.PreparerFunc(func(r *http.Request) (*http.Request, error) { - return r, fmt.Errorf("ERROR: mockFailingAuthorizer returned expected error") - }) - } -} - -type mockInspector struct { - wasInvoked bool -} - -func (mi *mockInspector) WithInspection() autorest.PrepareDecorator { - return func(p autorest.Preparer) autorest.Preparer { - return autorest.PreparerFunc(func(r *http.Request) (*http.Request, error) { - mi.wasInvoked = true - return p.Prepare(r) - }) - } -} - -func (mi *mockInspector) ByInspecting() autorest.RespondDecorator { - return func(r autorest.Responder) autorest.Responder { - return autorest.ResponderFunc(func(resp *http.Response) error { - mi.wasInvoked = true - return r.Respond(resp) - }) - } -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/devicetoken_test.go b/vendor/github.com/Azure/go-autorest/autorest/azure/devicetoken_test.go deleted file mode 100644 index ab8a78893..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/azure/devicetoken_test.go +++ /dev/null @@ -1,301 +0,0 @@ -package azure - -import ( - "encoding/json" - "fmt" - "net/http" - "strings" - "testing" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/mocks" -) - -const ( - TestResource = "SomeResource" - TestClientID = "SomeClientID" - TestTenantID = "SomeTenantID" -) - -var ( - testOAuthConfig, _ = PublicCloud.OAuthConfigForTenant(TestTenantID) - TestOAuthConfig = *testOAuthConfig -) - -const MockDeviceCodeResponse = ` -{ - "device_code": "10000-40-1234567890", - "user_code": "ABCDEF", - "verification_url": "http://aka.ms/deviceauth", - "expires_in": "900", - "interval": "0" -} -` - -const MockDeviceTokenResponse = `{ - "access_token": "accessToken", - "refresh_token": "refreshToken", - "expires_in": "1000", - "expires_on": "2000", - "not_before": "3000", - "resource": "resource", - "token_type": "type" -} -` - -func TestDeviceCodeIncludesResource(t *testing.T) { - sender := mocks.NewSender() - sender.AppendResponse(mocks.NewResponseWithContent(MockDeviceCodeResponse)) - client := &autorest.Client{Sender: sender} - - code, err := InitiateDeviceAuth(client, TestOAuthConfig, TestClientID, TestResource) - if err != nil { - t.Fatalf("azure: unexpected error initiating device auth") - } - - if code.Resource != TestResource { - t.Fatalf("azure: InitiateDeviceAuth failed to stash the resource in the DeviceCode struct") - } -} - -func TestDeviceCodeReturnsErrorIfSendingFails(t *testing.T) { - sender := mocks.NewSender() - sender.SetError(fmt.Errorf("this is an error")) - client := &autorest.Client{Sender: sender} - - _, err := InitiateDeviceAuth(client, TestOAuthConfig, TestClientID, TestResource) - if err == nil || !strings.Contains(err.Error(), errCodeSendingFails) { - t.Fatalf("azure: failed to get correct error expected(%s) actual(%s)", errCodeSendingFails, err.Error()) - } -} - -func TestDeviceCodeReturnsErrorIfBadRequest(t *testing.T) { - sender := mocks.NewSender() - body := mocks.NewBody("doesn't matter") - sender.AppendResponse(mocks.NewResponseWithBodyAndStatus(body, 400, "Bad Request")) - client := &autorest.Client{Sender: sender} - - _, err := InitiateDeviceAuth(client, TestOAuthConfig, TestClientID, TestResource) - if err == nil || !strings.Contains(err.Error(), errCodeHandlingFails) { - t.Fatalf("azure: failed to get correct error expected(%s) actual(%s)", errCodeHandlingFails, err.Error()) - } - - if body.IsOpen() { - t.Fatalf("response body was left open!") - } -} - -func TestDeviceCodeReturnsErrorIfCannotDeserializeDeviceCode(t *testing.T) { - gibberishJSON := strings.Replace(MockDeviceCodeResponse, "expires_in", "\":, :gibberish", -1) - sender := mocks.NewSender() - body := mocks.NewBody(gibberishJSON) - sender.AppendResponse(mocks.NewResponseWithBodyAndStatus(body, 200, "OK")) - client := &autorest.Client{Sender: sender} - - _, err := InitiateDeviceAuth(client, TestOAuthConfig, TestClientID, TestResource) - if err == nil || !strings.Contains(err.Error(), errCodeHandlingFails) { - t.Fatalf("azure: failed to get correct error expected(%s) actual(%s)", errCodeHandlingFails, err.Error()) - } - - if body.IsOpen() { - t.Fatalf("response body was left open!") - } -} - -func deviceCode() *DeviceCode { - var deviceCode DeviceCode - json.Unmarshal([]byte(MockDeviceCodeResponse), &deviceCode) - deviceCode.Resource = TestResource - deviceCode.ClientID = TestClientID - return &deviceCode -} - -func TestDeviceTokenReturns(t *testing.T) { - sender := mocks.NewSender() - body := mocks.NewBody(MockDeviceTokenResponse) - sender.AppendResponse(mocks.NewResponseWithBodyAndStatus(body, 200, "OK")) - client := &autorest.Client{Sender: sender} - - _, err := WaitForUserCompletion(client, deviceCode()) - if err != nil { - t.Fatalf("azure: got error unexpectedly") - } - - if body.IsOpen() { - t.Fatalf("response body was left open!") - } -} - -func TestDeviceTokenReturnsErrorIfSendingFails(t *testing.T) { - sender := mocks.NewSender() - sender.SetError(fmt.Errorf("this is an error")) - client := &autorest.Client{Sender: sender} - - _, err := WaitForUserCompletion(client, deviceCode()) - if err == nil || !strings.Contains(err.Error(), errTokenSendingFails) { - t.Fatalf("azure: failed to get correct error expected(%s) actual(%s)", errTokenSendingFails, err.Error()) - } -} - -func TestDeviceTokenReturnsErrorIfServerError(t *testing.T) { - sender := mocks.NewSender() - body := mocks.NewBody("") - sender.AppendResponse(mocks.NewResponseWithBodyAndStatus(body, 500, "Internal Server Error")) - client := &autorest.Client{Sender: sender} - - _, err := WaitForUserCompletion(client, deviceCode()) - if err == nil || !strings.Contains(err.Error(), errTokenHandlingFails) { - t.Fatalf("azure: failed to get correct error expected(%s) actual(%s)", errTokenHandlingFails, err.Error()) - } - - if body.IsOpen() { - t.Fatalf("response body was left open!") - } -} - -func TestDeviceTokenReturnsErrorIfCannotDeserializeDeviceToken(t *testing.T) { - gibberishJSON := strings.Replace(MockDeviceTokenResponse, "expires_in", ";:\"gibberish", -1) - sender := mocks.NewSender() - body := mocks.NewBody(gibberishJSON) - sender.AppendResponse(mocks.NewResponseWithBodyAndStatus(body, 200, "OK")) - client := &autorest.Client{Sender: sender} - - _, err := WaitForUserCompletion(client, deviceCode()) - if err == nil || !strings.Contains(err.Error(), errTokenHandlingFails) { - t.Fatalf("azure: failed to get correct error expected(%s) actual(%s)", errTokenHandlingFails, err.Error()) - } - - if body.IsOpen() { - t.Fatalf("response body was left open!") - } -} - -func errorDeviceTokenResponse(message string) string { - return `{ "error": "` + message + `" }` -} - -func TestDeviceTokenReturnsErrorIfAuthorizationPending(t *testing.T) { - sender := mocks.NewSender() - body := mocks.NewBody(errorDeviceTokenResponse("authorization_pending")) - sender.AppendResponse(mocks.NewResponseWithBodyAndStatus(body, 400, "Bad Request")) - client := &autorest.Client{Sender: sender} - - _, err := CheckForUserCompletion(client, deviceCode()) - if err != ErrDeviceAuthorizationPending { - t.Fatalf("!!!") - } - - if body.IsOpen() { - t.Fatalf("response body was left open!") - } -} - -func TestDeviceTokenReturnsErrorIfSlowDown(t *testing.T) { - sender := mocks.NewSender() - body := mocks.NewBody(errorDeviceTokenResponse("slow_down")) - sender.AppendResponse(mocks.NewResponseWithBodyAndStatus(body, 400, "Bad Request")) - client := &autorest.Client{Sender: sender} - - _, err := CheckForUserCompletion(client, deviceCode()) - if err != ErrDeviceSlowDown { - t.Fatalf("!!!") - } - - if body.IsOpen() { - t.Fatalf("response body was left open!") - } -} - -type deviceTokenSender struct { - errorString string - attempts int -} - -func newDeviceTokenSender(deviceErrorString string) *deviceTokenSender { - return &deviceTokenSender{errorString: deviceErrorString, attempts: 0} -} - -func (s *deviceTokenSender) Do(req *http.Request) (*http.Response, error) { - var resp *http.Response - if s.attempts < 1 { - s.attempts++ - resp = mocks.NewResponseWithContent(errorDeviceTokenResponse(s.errorString)) - } else { - resp = mocks.NewResponseWithContent(MockDeviceTokenResponse) - } - return resp, nil -} - -// since the above only exercise CheckForUserCompletion, we repeat the test here, -// but with the intent of showing that WaitForUserCompletion loops properly. -func TestDeviceTokenSucceedsWithIntermediateAuthPending(t *testing.T) { - sender := newDeviceTokenSender("authorization_pending") - client := &autorest.Client{Sender: sender} - - _, err := WaitForUserCompletion(client, deviceCode()) - if err != nil { - t.Fatalf("unexpected error occurred") - } -} - -// same as above but with SlowDown now -func TestDeviceTokenSucceedsWithIntermediateSlowDown(t *testing.T) { - sender := newDeviceTokenSender("slow_down") - client := &autorest.Client{Sender: sender} - - _, err := WaitForUserCompletion(client, deviceCode()) - if err != nil { - t.Fatalf("unexpected error occurred") - } -} - -func TestDeviceTokenReturnsErrorIfAccessDenied(t *testing.T) { - sender := mocks.NewSender() - body := mocks.NewBody(errorDeviceTokenResponse("access_denied")) - sender.AppendResponse(mocks.NewResponseWithBodyAndStatus(body, 400, "Bad Request")) - client := &autorest.Client{Sender: sender} - - _, err := WaitForUserCompletion(client, deviceCode()) - if err != ErrDeviceAccessDenied { - t.Fatalf("azure: got wrong error expected(%s) actual(%s)", ErrDeviceAccessDenied.Error(), err.Error()) - } - - if body.IsOpen() { - t.Fatalf("response body was left open!") - } -} - -func TestDeviceTokenReturnsErrorIfCodeExpired(t *testing.T) { - sender := mocks.NewSender() - body := mocks.NewBody(errorDeviceTokenResponse("code_expired")) - sender.AppendResponse(mocks.NewResponseWithBodyAndStatus(body, 400, "Bad Request")) - client := &autorest.Client{Sender: sender} - - _, err := WaitForUserCompletion(client, deviceCode()) - if err != ErrDeviceCodeExpired { - t.Fatalf("azure: got wrong error expected(%s) actual(%s)", ErrDeviceCodeExpired.Error(), err.Error()) - } - - if body.IsOpen() { - t.Fatalf("response body was left open!") - } -} - -func TestDeviceTokenReturnsErrorForUnknownError(t *testing.T) { - sender := mocks.NewSender() - body := mocks.NewBody(errorDeviceTokenResponse("unknown_error")) - sender.AppendResponse(mocks.NewResponseWithBodyAndStatus(body, 400, "Bad Request")) - client := &autorest.Client{Sender: sender} - - _, err := WaitForUserCompletion(client, deviceCode()) - if err == nil { - t.Fatalf("failed to get error") - } - if err != ErrDeviceGeneric { - t.Fatalf("azure: got wrong error expected(%s) actual(%s)", ErrDeviceGeneric.Error(), err.Error()) - } - - if body.IsOpen() { - t.Fatalf("response body was left open!") - } -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/environments_test.go b/vendor/github.com/Azure/go-autorest/autorest/azure/environments_test.go deleted file mode 100644 index 73d494295..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/azure/environments_test.go +++ /dev/null @@ -1,232 +0,0 @@ -// test -package azure - -import ( - "encoding/json" - "testing" -) - -func TestOAuthConfigForTenant(t *testing.T) { - az := PublicCloud - - config, err := az.OAuthConfigForTenant("tenant-id-test") - if err != nil { - t.Fatalf("autorest/azure: Unexpected error while retrieving oauth configuration for tenant: %v.", err) - } - - expected := "https://login.microsoftonline.com/tenant-id-test/oauth2/authorize?api-version=1.0" - if config.AuthorizeEndpoint.String() != expected { - t.Fatalf("autorest/azure: Incorrect authorize url for Tenant from Environment. expected(%s). actual(%v).", expected, config.AuthorizeEndpoint) - } - - expected = "https://login.microsoftonline.com/tenant-id-test/oauth2/token?api-version=1.0" - if config.TokenEndpoint.String() != expected { - t.Fatalf("autorest/azure: Incorrect authorize url for Tenant from Environment. expected(%s). actual(%v).", expected, config.TokenEndpoint) - } - - expected = "https://login.microsoftonline.com/tenant-id-test/oauth2/devicecode?api-version=1.0" - if config.DeviceCodeEndpoint.String() != expected { - t.Fatalf("autorest/azure: Incorrect devicecode url for Tenant from Environment. expected(%s). actual(%v).", expected, config.DeviceCodeEndpoint) - } -} - -func TestEnvironmentFromName(t *testing.T) { - name := "azurechinacloud" - if env, _ := EnvironmentFromName(name); env != ChinaCloud { - t.Errorf("Expected to get ChinaCloud for %q", name) - } - - name = "AzureChinaCloud" - if env, _ := EnvironmentFromName(name); env != ChinaCloud { - t.Errorf("Expected to get ChinaCloud for %q", name) - } - - name = "azuregermancloud" - if env, _ := EnvironmentFromName(name); env != GermanCloud { - t.Errorf("Expected to get GermanCloud for %q", name) - } - - name = "AzureGermanCloud" - if env, _ := EnvironmentFromName(name); env != GermanCloud { - t.Errorf("Expected to get GermanCloud for %q", name) - } - - name = "azurepubliccloud" - if env, _ := EnvironmentFromName(name); env != PublicCloud { - t.Errorf("Expected to get PublicCloud for %q", name) - } - - name = "AzurePublicCloud" - if env, _ := EnvironmentFromName(name); env != PublicCloud { - t.Errorf("Expected to get PublicCloud for %q", name) - } - - name = "azureusgovernmentcloud" - if env, _ := EnvironmentFromName(name); env != USGovernmentCloud { - t.Errorf("Expected to get USGovernmentCloud for %q", name) - } - - name = "AzureUSGovernmentCloud" - if env, _ := EnvironmentFromName(name); env != USGovernmentCloud { - t.Errorf("Expected to get USGovernmentCloud for %q", name) - } - - name = "thisisnotarealcloudenv" - if _, err := EnvironmentFromName(name); err == nil { - t.Errorf("Expected to get an error for %q", name) - } -} - -func TestDeserializeEnvironment(t *testing.T) { - env := `{ - "name": "--name--", - "ActiveDirectoryEndpoint": "--active-directory-endpoint--", - "galleryEndpoint": "--gallery-endpoint--", - "graphEndpoint": "--graph-endpoint--", - "keyVaultDNSSuffix": "--key-vault-dns-suffix--", - "keyVaultEndpoint": "--key-vault-endpoint--", - "managementPortalURL": "--management-portal-url--", - "publishSettingsURL": "--publish-settings-url--", - "resourceManagerEndpoint": "--resource-manager-endpoint--", - "serviceBusEndpointSuffix": "--service-bus-endpoint-suffix--", - "serviceManagementEndpoint": "--service-management-endpoint--", - "sqlDatabaseDNSSuffix": "--sql-database-dns-suffix--", - "storageEndpointSuffix": "--storage-endpoint-suffix--", - "trafficManagerDNSSuffix": "--traffic-manager-dns-suffix--", - "serviceManagementVMDNSSuffix": "--asm-vm-dns-suffix--", - "resourceManagerVMDNSSuffix": "--arm-vm-dns-suffix--" - }` - - testSubject := Environment{} - err := json.Unmarshal([]byte(env), &testSubject) - if err != nil { - t.Fatalf("failed to unmarshal: %s", err) - } - - if "--name--" != testSubject.Name { - t.Errorf("Expected Name to be \"--name--\", but got %q", testSubject.Name) - } - if "--management-portal-url--" != testSubject.ManagementPortalURL { - t.Errorf("Expected ManagementPortalURL to be \"--management-portal-url--\", but got %q", testSubject.ManagementPortalURL) - } - if "--publish-settings-url--" != testSubject.PublishSettingsURL { - t.Errorf("Expected PublishSettingsURL to be \"--publish-settings-url--\", but got %q", testSubject.PublishSettingsURL) - } - if "--service-management-endpoint--" != testSubject.ServiceManagementEndpoint { - t.Errorf("Expected ServiceManagementEndpoint to be \"--service-management-endpoint--\", but got %q", testSubject.ServiceManagementEndpoint) - } - if "--resource-manager-endpoint--" != testSubject.ResourceManagerEndpoint { - t.Errorf("Expected ResourceManagerEndpoint to be \"--resource-manager-endpoint--\", but got %q", testSubject.ResourceManagerEndpoint) - } - if "--active-directory-endpoint--" != testSubject.ActiveDirectoryEndpoint { - t.Errorf("Expected ActiveDirectoryEndpoint to be \"--active-directory-endpoint--\", but got %q", testSubject.ActiveDirectoryEndpoint) - } - if "--gallery-endpoint--" != testSubject.GalleryEndpoint { - t.Errorf("Expected GalleryEndpoint to be \"--gallery-endpoint--\", but got %q", testSubject.GalleryEndpoint) - } - if "--key-vault-endpoint--" != testSubject.KeyVaultEndpoint { - t.Errorf("Expected KeyVaultEndpoint to be \"--key-vault-endpoint--\", but got %q", testSubject.KeyVaultEndpoint) - } - if "--graph-endpoint--" != testSubject.GraphEndpoint { - t.Errorf("Expected GraphEndpoint to be \"--graph-endpoint--\", but got %q", testSubject.GraphEndpoint) - } - if "--storage-endpoint-suffix--" != testSubject.StorageEndpointSuffix { - t.Errorf("Expected StorageEndpointSuffix to be \"--storage-endpoint-suffix--\", but got %q", testSubject.StorageEndpointSuffix) - } - if "--sql-database-dns-suffix--" != testSubject.SQLDatabaseDNSSuffix { - t.Errorf("Expected sql-database-dns-suffix to be \"--sql-database-dns-suffix--\", but got %q", testSubject.SQLDatabaseDNSSuffix) - } - if "--key-vault-dns-suffix--" != testSubject.KeyVaultDNSSuffix { - t.Errorf("Expected StorageEndpointSuffix to be \"--key-vault-dns-suffix--\", but got %q", testSubject.KeyVaultDNSSuffix) - } - if "--service-bus-endpoint-suffix--" != testSubject.ServiceBusEndpointSuffix { - t.Errorf("Expected StorageEndpointSuffix to be \"--service-bus-endpoint-suffix--\", but got %q", testSubject.ServiceBusEndpointSuffix) - } - if "--asm-vm-dns-suffix--" != testSubject.ServiceManagementVMDNSSuffix { - t.Errorf("Expected ServiceManagementVMDNSSuffix to be \"--asm-vm-dns-suffix--\", but got %q", testSubject.ServiceManagementVMDNSSuffix) - } - if "--arm-vm-dns-suffix--" != testSubject.ResourceManagerVMDNSSuffix { - t.Errorf("Expected ResourceManagerVMDNSSuffix to be \"--arm-vm-dns-suffix--\", but got %q", testSubject.ResourceManagerVMDNSSuffix) - } -} - -func TestRoundTripSerialization(t *testing.T) { - env := Environment{ - Name: "--unit-test--", - ManagementPortalURL: "--management-portal-url", - PublishSettingsURL: "--publish-settings-url--", - ServiceManagementEndpoint: "--service-management-endpoint--", - ResourceManagerEndpoint: "--resource-management-endpoint--", - ActiveDirectoryEndpoint: "--active-directory-endpoint--", - GalleryEndpoint: "--gallery-endpoint--", - KeyVaultEndpoint: "--key-vault--endpoint--", - GraphEndpoint: "--graph-endpoint--", - StorageEndpointSuffix: "--storage-endpoint-suffix--", - SQLDatabaseDNSSuffix: "--sql-database-dns-suffix--", - TrafficManagerDNSSuffix: "--traffic-manager-dns-suffix--", - KeyVaultDNSSuffix: "--key-vault-dns-suffix--", - ServiceBusEndpointSuffix: "--service-bus-endpoint-suffix--", - ServiceManagementVMDNSSuffix: "--asm-vm-dns-suffix--", - ResourceManagerVMDNSSuffix: "--arm-vm-dns-suffix--", - } - - bytes, err := json.Marshal(env) - if err != nil { - t.Fatalf("failed to marshal: %s", err) - } - - testSubject := Environment{} - err = json.Unmarshal(bytes, &testSubject) - if err != nil { - t.Fatalf("failed to unmarshal: %s", err) - } - - if env.Name != testSubject.Name { - t.Errorf("Expected Name to be %q, but got %q", env.Name, testSubject.Name) - } - if env.ManagementPortalURL != testSubject.ManagementPortalURL { - t.Errorf("Expected ManagementPortalURL to be %q, but got %q", env.ManagementPortalURL, testSubject.ManagementPortalURL) - } - if env.PublishSettingsURL != testSubject.PublishSettingsURL { - t.Errorf("Expected PublishSettingsURL to be %q, but got %q", env.PublishSettingsURL, testSubject.PublishSettingsURL) - } - if env.ServiceManagementEndpoint != testSubject.ServiceManagementEndpoint { - t.Errorf("Expected ServiceManagementEndpoint to be %q, but got %q", env.ServiceManagementEndpoint, testSubject.ServiceManagementEndpoint) - } - if env.ResourceManagerEndpoint != testSubject.ResourceManagerEndpoint { - t.Errorf("Expected ResourceManagerEndpoint to be %q, but got %q", env.ResourceManagerEndpoint, testSubject.ResourceManagerEndpoint) - } - if env.ActiveDirectoryEndpoint != testSubject.ActiveDirectoryEndpoint { - t.Errorf("Expected ActiveDirectoryEndpoint to be %q, but got %q", env.ActiveDirectoryEndpoint, testSubject.ActiveDirectoryEndpoint) - } - if env.GalleryEndpoint != testSubject.GalleryEndpoint { - t.Errorf("Expected GalleryEndpoint to be %q, but got %q", env.GalleryEndpoint, testSubject.GalleryEndpoint) - } - if env.KeyVaultEndpoint != testSubject.KeyVaultEndpoint { - t.Errorf("Expected KeyVaultEndpoint to be %q, but got %q", env.KeyVaultEndpoint, testSubject.KeyVaultEndpoint) - } - if env.GraphEndpoint != testSubject.GraphEndpoint { - t.Errorf("Expected GraphEndpoint to be %q, but got %q", env.GraphEndpoint, testSubject.GraphEndpoint) - } - if env.StorageEndpointSuffix != testSubject.StorageEndpointSuffix { - t.Errorf("Expected StorageEndpointSuffix to be %q, but got %q", env.StorageEndpointSuffix, testSubject.StorageEndpointSuffix) - } - if env.SQLDatabaseDNSSuffix != testSubject.SQLDatabaseDNSSuffix { - t.Errorf("Expected SQLDatabaseDNSSuffix to be %q, but got %q", env.SQLDatabaseDNSSuffix, testSubject.SQLDatabaseDNSSuffix) - } - if env.TrafficManagerDNSSuffix != testSubject.TrafficManagerDNSSuffix { - t.Errorf("Expected TrafficManagerDNSSuffix to be %q, but got %q", env.TrafficManagerDNSSuffix, testSubject.TrafficManagerDNSSuffix) - } - if env.KeyVaultDNSSuffix != testSubject.KeyVaultDNSSuffix { - t.Errorf("Expected KeyVaultDNSSuffix to be %q, but got %q", env.KeyVaultDNSSuffix, testSubject.KeyVaultDNSSuffix) - } - if env.ServiceBusEndpointSuffix != testSubject.ServiceBusEndpointSuffix { - t.Errorf("Expected ServiceBusEndpointSuffix to be %q, but got %q", env.ServiceBusEndpointSuffix, testSubject.ServiceBusEndpointSuffix) - } - if env.ServiceManagementVMDNSSuffix != testSubject.ServiceManagementVMDNSSuffix { - t.Errorf("Expected ServiceManagementVMDNSSuffix to be %q, but got %q", env.ServiceManagementVMDNSSuffix, testSubject.ServiceManagementVMDNSSuffix) - } - if env.ResourceManagerVMDNSSuffix != testSubject.ResourceManagerVMDNSSuffix { - t.Errorf("Expected ResourceManagerVMDNSSuffix to be %q, but got %q", env.ResourceManagerVMDNSSuffix, testSubject.ResourceManagerVMDNSSuffix) - } -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/persist_test.go b/vendor/github.com/Azure/go-autorest/autorest/azure/persist_test.go deleted file mode 100644 index d0b10b755..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/azure/persist_test.go +++ /dev/null @@ -1,152 +0,0 @@ -package azure - -import ( - "encoding/json" - "io/ioutil" - "os" - "reflect" - "runtime" - "strings" - "testing" -) - -const MockTokenJSON string = `{ - "access_token": "accessToken", - "refresh_token": "refreshToken", - "expires_in": "1000", - "expires_on": "2000", - "not_before": "3000", - "resource": "resource", - "token_type": "type" -}` - -var TestToken = Token{ - AccessToken: "accessToken", - RefreshToken: "refreshToken", - ExpiresIn: "1000", - ExpiresOn: "2000", - NotBefore: "3000", - Resource: "resource", - Type: "type", -} - -func writeTestTokenFile(t *testing.T, suffix string, contents string) *os.File { - f, err := ioutil.TempFile(os.TempDir(), suffix) - if err != nil { - t.Fatalf("azure: unexpected error when creating temp file: %v", err) - } - defer f.Close() - - _, err = f.Write([]byte(contents)) - if err != nil { - t.Fatalf("azure: unexpected error when writing temp test file: %v", err) - } - - return f -} - -func TestLoadToken(t *testing.T) { - f := writeTestTokenFile(t, "testloadtoken", MockTokenJSON) - defer os.Remove(f.Name()) - - expectedToken := TestToken - actualToken, err := LoadToken(f.Name()) - if err != nil { - t.Fatalf("azure: unexpected error loading token from file: %v", err) - } - - if *actualToken != expectedToken { - t.Fatalf("azure: failed to decode properly expected(%v) actual(%v)", expectedToken, *actualToken) - } - - // test that LoadToken closes the file properly - err = SaveToken(f.Name(), 0600, *actualToken) - if err != nil { - t.Fatalf("azure: could not save token after LoadToken: %v", err) - } -} - -func TestLoadTokenFailsBadPath(t *testing.T) { - _, err := LoadToken("/tmp/this_file_should_never_exist_really") - expectedSubstring := "failed to open file" - if err == nil || !strings.Contains(err.Error(), expectedSubstring) { - t.Fatalf("azure: failed to get correct error expected(%s) actual(%s)", expectedSubstring, err.Error()) - } -} - -func TestLoadTokenFailsBadJson(t *testing.T) { - gibberishJSON := strings.Replace(MockTokenJSON, "expires_on", ";:\"gibberish", -1) - f := writeTestTokenFile(t, "testloadtokenfailsbadjson", gibberishJSON) - defer os.Remove(f.Name()) - - _, err := LoadToken(f.Name()) - expectedSubstring := "failed to decode contents of file" - if err == nil || !strings.Contains(err.Error(), expectedSubstring) { - t.Fatalf("azure: failed to get correct error expected(%s) actual(%s)", expectedSubstring, err.Error()) - } -} - -func token() *Token { - var token Token - json.Unmarshal([]byte(MockTokenJSON), &token) - return &token -} - -func TestSaveToken(t *testing.T) { - f, err := ioutil.TempFile("", "testloadtoken") - if err != nil { - t.Fatalf("azure: unexpected error when creating temp file: %v", err) - } - defer os.Remove(f.Name()) - f.Close() - - mode := os.ModePerm & 0642 - err = SaveToken(f.Name(), mode, *token()) - if err != nil { - t.Fatalf("azure: unexpected error saving token to file: %v", err) - } - fi, err := os.Stat(f.Name()) // open a new stat as held ones are not fresh - if err != nil { - t.Fatalf("azure: stat failed: %v", err) - } - if runtime.GOOS != "windows" { // permissions don't work on Windows - if perm := fi.Mode().Perm(); perm != mode { - t.Fatalf("azure: wrong file perm. got:%s; expected:%s file :%s", perm, mode, f.Name()) - } - } - - var actualToken Token - var expectedToken Token - - json.Unmarshal([]byte(MockTokenJSON), expectedToken) - - contents, err := ioutil.ReadFile(f.Name()) - if err != nil { - t.Fatal("!!") - } - json.Unmarshal(contents, actualToken) - - if !reflect.DeepEqual(actualToken, expectedToken) { - t.Fatal("azure: token was not serialized correctly") - } -} - -func TestSaveTokenFailsNoPermission(t *testing.T) { - pathWhereWeShouldntHavePermission := "/usr/thiswontwork/atall" - if runtime.GOOS == "windows" { - pathWhereWeShouldntHavePermission = "c:\\windows\\system32\\mytokendir\\mytoken" - } - err := SaveToken(pathWhereWeShouldntHavePermission, 0644, *token()) - expectedSubstring := "failed to create directory" - if err == nil || !strings.Contains(err.Error(), expectedSubstring) { - t.Fatalf("azure: failed to get correct error expected(%s) actual(%v)", expectedSubstring, err) - } -} - -func TestSaveTokenFailsCantCreate(t *testing.T) { - err := SaveToken("/thiswontwork", 0644, *token()) - expectedSubstring := "failed to create the temp file to write the token" - if err == nil || !strings.Contains(err.Error(), expectedSubstring) { - t.Fatalf("azure: failed to get correct error expected(%s) actual(%v)", expectedSubstring, err) - } -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/token_test.go b/vendor/github.com/Azure/go-autorest/autorest/azure/token_test.go deleted file mode 100644 index 86aac61b1..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/azure/token_test.go +++ /dev/null @@ -1,509 +0,0 @@ -package azure - -import ( - "crypto/rand" - "crypto/rsa" - "crypto/x509" - "crypto/x509/pkix" - "fmt" - "io/ioutil" - "math/big" - "net/http" - "net/url" - "reflect" - "strconv" - "strings" - "testing" - "time" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/mocks" -) - -const ( - defaultFormData = "client_id=id&client_secret=secret&grant_type=client_credentials&resource=resource" - defaultManualFormData = "client_id=id&grant_type=refresh_token&refresh_token=refreshtoken&resource=resource" -) - -func TestTokenExpires(t *testing.T) { - tt := time.Now().Add(5 * time.Second) - tk := newTokenExpiresAt(tt) - - if tk.Expires().Equal(tt) { - t.Fatalf("azure: Token#Expires miscalculated expiration time -- received %v, expected %v", tk.Expires(), tt) - } -} - -func TestTokenIsExpired(t *testing.T) { - tk := newTokenExpiresAt(time.Now().Add(-5 * time.Second)) - - if !tk.IsExpired() { - t.Fatalf("azure: Token#IsExpired failed to mark a stale token as expired -- now %v, token expires at %v", - time.Now().UTC(), tk.Expires()) - } -} - -func TestTokenIsExpiredUninitialized(t *testing.T) { - tk := &Token{} - - if !tk.IsExpired() { - t.Fatalf("azure: An uninitialized Token failed to mark itself as expired (expiration time %v)", tk.Expires()) - } -} - -func TestTokenIsNoExpired(t *testing.T) { - tk := newTokenExpiresAt(time.Now().Add(1000 * time.Second)) - - if tk.IsExpired() { - t.Fatalf("azure: Token marked a fresh token as expired -- now %v, token expires at %v", time.Now().UTC(), tk.Expires()) - } -} - -func TestTokenWillExpireIn(t *testing.T) { - d := 5 * time.Second - tk := newTokenExpiresIn(d) - - if !tk.WillExpireIn(d) { - t.Fatal("azure: Token#WillExpireIn mismeasured expiration time") - } -} - -func TestTokenWithAuthorization(t *testing.T) { - tk := newToken() - - req, err := autorest.Prepare(&http.Request{}, tk.WithAuthorization()) - if err != nil { - t.Fatalf("azure: Token#WithAuthorization returned an error (%v)", err) - } else if req.Header.Get(http.CanonicalHeaderKey("Authorization")) != fmt.Sprintf("Bearer %s", tk.AccessToken) { - t.Fatal("azure: Token#WithAuthorization failed to set Authorization header") - } -} - -func TestServicePrincipalTokenSetAutoRefresh(t *testing.T) { - spt := newServicePrincipalToken() - - if !spt.autoRefresh { - t.Fatal("azure: ServicePrincipalToken did not default to automatic token refreshing") - } - - spt.SetAutoRefresh(false) - if spt.autoRefresh { - t.Fatal("azure: ServicePrincipalToken#SetAutoRefresh did not disable automatic token refreshing") - } -} - -func TestServicePrincipalTokenSetRefreshWithin(t *testing.T) { - spt := newServicePrincipalToken() - - if spt.refreshWithin != defaultRefresh { - t.Fatal("azure: ServicePrincipalToken did not correctly set the default refresh interval") - } - - spt.SetRefreshWithin(2 * defaultRefresh) - if spt.refreshWithin != 2*defaultRefresh { - t.Fatal("azure: ServicePrincipalToken#SetRefreshWithin did not set the refresh interval") - } -} - -func TestServicePrincipalTokenSetSender(t *testing.T) { - spt := newServicePrincipalToken() - - var s autorest.Sender - s = mocks.NewSender() - spt.SetSender(s) - if !reflect.DeepEqual(s, spt.sender) { - t.Fatal("azure: ServicePrincipalToken#SetSender did not set the sender") - } -} - -func TestServicePrincipalTokenRefreshUsesPOST(t *testing.T) { - spt := newServicePrincipalToken() - - body := mocks.NewBody("") - resp := mocks.NewResponseWithBodyAndStatus(body, 200, "OK") - - c := mocks.NewSender() - s := autorest.DecorateSender(c, - (func() autorest.SendDecorator { - return func(s autorest.Sender) autorest.Sender { - return autorest.SenderFunc(func(r *http.Request) (*http.Response, error) { - if r.Method != "POST" { - t.Fatalf("azure: ServicePrincipalToken#Refresh did not correctly set HTTP method -- expected %v, received %v", "POST", r.Method) - } - return resp, nil - }) - } - })()) - spt.SetSender(s) - spt.Refresh() - - if body.IsOpen() { - t.Fatalf("the response was not closed!") - } -} - -func TestServicePrincipalTokenRefreshSetsMimeType(t *testing.T) { - spt := newServicePrincipalToken() - - c := mocks.NewSender() - s := autorest.DecorateSender(c, - (func() autorest.SendDecorator { - return func(s autorest.Sender) autorest.Sender { - return autorest.SenderFunc(func(r *http.Request) (*http.Response, error) { - if r.Header.Get(http.CanonicalHeaderKey("Content-Type")) != "application/x-www-form-urlencoded" { - t.Fatalf("azure: ServicePrincipalToken#Refresh did not correctly set Content-Type -- expected %v, received %v", - "application/x-form-urlencoded", - r.Header.Get(http.CanonicalHeaderKey("Content-Type"))) - } - return mocks.NewResponse(), nil - }) - } - })()) - spt.SetSender(s) - spt.Refresh() -} - -func TestServicePrincipalTokenRefreshSetsURL(t *testing.T) { - spt := newServicePrincipalToken() - - c := mocks.NewSender() - s := autorest.DecorateSender(c, - (func() autorest.SendDecorator { - return func(s autorest.Sender) autorest.Sender { - return autorest.SenderFunc(func(r *http.Request) (*http.Response, error) { - if r.URL.String() != TestOAuthConfig.TokenEndpoint.String() { - t.Fatalf("azure: ServicePrincipalToken#Refresh did not correctly set the URL -- expected %v, received %v", - TestOAuthConfig.TokenEndpoint, r.URL) - } - return mocks.NewResponse(), nil - }) - } - })()) - spt.SetSender(s) - spt.Refresh() -} - -func testServicePrincipalTokenRefreshSetsBody(t *testing.T, spt *ServicePrincipalToken, f func(*testing.T, []byte)) { - c := mocks.NewSender() - s := autorest.DecorateSender(c, - (func() autorest.SendDecorator { - return func(s autorest.Sender) autorest.Sender { - return autorest.SenderFunc(func(r *http.Request) (*http.Response, error) { - b, err := ioutil.ReadAll(r.Body) - if err != nil { - t.Fatalf("azure: Failed to read body of Service Principal token request (%v)", err) - } - f(t, b) - return mocks.NewResponse(), nil - }) - } - })()) - spt.SetSender(s) - spt.Refresh() -} - -func TestServicePrincipalTokenManualRefreshSetsBody(t *testing.T) { - sptManual := newServicePrincipalTokenManual() - testServicePrincipalTokenRefreshSetsBody(t, sptManual, func(t *testing.T, b []byte) { - if string(b) != defaultManualFormData { - t.Fatalf("azure: ServicePrincipalToken#Refresh did not correctly set the HTTP Request Body -- expected %v, received %v", - defaultManualFormData, string(b)) - } - }) -} - -func TestServicePrincipalTokenCertficateRefreshSetsBody(t *testing.T) { - sptCert := newServicePrincipalTokenCertificate(t) - testServicePrincipalTokenRefreshSetsBody(t, sptCert, func(t *testing.T, b []byte) { - body := string(b) - - values, _ := url.ParseQuery(body) - if values["client_assertion_type"][0] != "urn:ietf:params:oauth:client-assertion-type:jwt-bearer" || - values["client_id"][0] != "id" || - values["grant_type"][0] != "client_credentials" || - values["resource"][0] != "resource" { - t.Fatalf("azure: ServicePrincipalTokenCertificate#Refresh did not correctly set the HTTP Request Body.") - } - }) -} - -func TestServicePrincipalTokenSecretRefreshSetsBody(t *testing.T) { - spt := newServicePrincipalToken() - testServicePrincipalTokenRefreshSetsBody(t, spt, func(t *testing.T, b []byte) { - if string(b) != defaultFormData { - t.Fatalf("azure: ServicePrincipalToken#Refresh did not correctly set the HTTP Request Body -- expected %v, received %v", - defaultFormData, string(b)) - } - - }) -} - -func TestServicePrincipalTokenRefreshClosesRequestBody(t *testing.T) { - spt := newServicePrincipalToken() - - resp := mocks.NewResponse() - c := mocks.NewSender() - s := autorest.DecorateSender(c, - (func() autorest.SendDecorator { - return func(s autorest.Sender) autorest.Sender { - return autorest.SenderFunc(func(r *http.Request) (*http.Response, error) { - return resp, nil - }) - } - })()) - spt.SetSender(s) - spt.Refresh() - - if resp.Body.(*mocks.Body).IsOpen() { - t.Fatal("azure: ServicePrincipalToken#Refresh failed to close the HTTP Response Body") - } -} - -func TestServicePrincipalTokenRefreshPropagatesErrors(t *testing.T) { - spt := newServicePrincipalToken() - - c := mocks.NewSender() - c.SetError(fmt.Errorf("Faux Error")) - spt.SetSender(c) - - err := spt.Refresh() - if err == nil { - t.Fatal("azure: Failed to propagate the request error") - } -} - -func TestServicePrincipalTokenRefreshReturnsErrorIfNotOk(t *testing.T) { - spt := newServicePrincipalToken() - - c := mocks.NewSender() - c.AppendResponse(mocks.NewResponseWithStatus("401 NotAuthorized", 401)) - spt.SetSender(c) - - err := spt.Refresh() - if err == nil { - t.Fatal("azure: Failed to return an when receiving a status code other than HTTP 200") - } -} - -func TestServicePrincipalTokenRefreshUnmarshals(t *testing.T) { - spt := newServicePrincipalToken() - - expiresOn := strconv.Itoa(int(time.Now().Add(3600 * time.Second).Sub(expirationBase).Seconds())) - j := newTokenJSON(expiresOn, "resource") - resp := mocks.NewResponseWithContent(j) - c := mocks.NewSender() - s := autorest.DecorateSender(c, - (func() autorest.SendDecorator { - return func(s autorest.Sender) autorest.Sender { - return autorest.SenderFunc(func(r *http.Request) (*http.Response, error) { - return resp, nil - }) - } - })()) - spt.SetSender(s) - - err := spt.Refresh() - if err != nil { - t.Fatalf("azure: ServicePrincipalToken#Refresh returned an unexpected error (%v)", err) - } else if spt.AccessToken != "accessToken" || - spt.ExpiresIn != "3600" || - spt.ExpiresOn != expiresOn || - spt.NotBefore != expiresOn || - spt.Resource != "resource" || - spt.Type != "Bearer" { - t.Fatalf("azure: ServicePrincipalToken#Refresh failed correctly unmarshal the JSON -- expected %v, received %v", - j, *spt) - } -} - -func TestServicePrincipalTokenEnsureFreshRefreshes(t *testing.T) { - spt := newServicePrincipalToken() - expireToken(&spt.Token) - - f := false - c := mocks.NewSender() - s := autorest.DecorateSender(c, - (func() autorest.SendDecorator { - return func(s autorest.Sender) autorest.Sender { - return autorest.SenderFunc(func(r *http.Request) (*http.Response, error) { - f = true - return mocks.NewResponse(), nil - }) - } - })()) - spt.SetSender(s) - spt.EnsureFresh() - if !f { - t.Fatal("azure: ServicePrincipalToken#EnsureFresh failed to call Refresh for stale token") - } -} - -func TestServicePrincipalTokenEnsureFreshSkipsIfFresh(t *testing.T) { - spt := newServicePrincipalToken() - setTokenToExpireIn(&spt.Token, 1000*time.Second) - - f := false - c := mocks.NewSender() - s := autorest.DecorateSender(c, - (func() autorest.SendDecorator { - return func(s autorest.Sender) autorest.Sender { - return autorest.SenderFunc(func(r *http.Request) (*http.Response, error) { - f = true - return mocks.NewResponse(), nil - }) - } - })()) - spt.SetSender(s) - spt.EnsureFresh() - if f { - t.Fatal("azure: ServicePrincipalToken#EnsureFresh invoked Refresh for fresh token") - } -} - -func TestServicePrincipalTokenWithAuthorization(t *testing.T) { - spt := newServicePrincipalToken() - setTokenToExpireIn(&spt.Token, 1000*time.Second) - r := mocks.NewRequest() - s := mocks.NewSender() - spt.SetSender(s) - - req, err := autorest.Prepare(r, spt.WithAuthorization()) - if err != nil { - t.Fatalf("azure: ServicePrincipalToken#WithAuthorization returned an error (%v)", err) - } else if req.Header.Get(http.CanonicalHeaderKey("Authorization")) != fmt.Sprintf("Bearer %s", spt.AccessToken) { - t.Fatal("azure: ServicePrincipalToken#WithAuthorization failed to set Authorization header") - } -} - -func TestServicePrincipalTokenWithAuthorizationReturnsErrorIfCannotRefresh(t *testing.T) { - spt := newServicePrincipalToken() - - _, err := autorest.Prepare(&http.Request{}, spt.WithAuthorization()) - if err == nil { - t.Fatal("azure: ServicePrincipalToken#WithAuthorization failed to return an error when refresh fails") - } -} - -func TestRefreshCallback(t *testing.T) { - callbackTriggered := false - spt := newServicePrincipalToken(func(Token) error { - callbackTriggered = true - return nil - }) - - expiresOn := strconv.Itoa(int(time.Now().Add(3600 * time.Second).Sub(expirationBase).Seconds())) - - sender := mocks.NewSender() - j := newTokenJSON(expiresOn, "resource") - sender.AppendResponse(mocks.NewResponseWithContent(j)) - spt.SetSender(sender) - spt.Refresh() - - if !callbackTriggered { - t.Fatalf("azure: RefreshCallback failed to trigger call callback") - } -} - -func TestRefreshCallbackErrorPropagates(t *testing.T) { - errorText := "this is an error text" - spt := newServicePrincipalToken(func(Token) error { - return fmt.Errorf(errorText) - }) - - expiresOn := strconv.Itoa(int(time.Now().Add(3600 * time.Second).Sub(expirationBase).Seconds())) - - sender := mocks.NewSender() - j := newTokenJSON(expiresOn, "resource") - sender.AppendResponse(mocks.NewResponseWithContent(j)) - spt.SetSender(sender) - err := spt.Refresh() - - if err == nil || !strings.Contains(err.Error(), errorText) { - t.Fatalf("azure: RefreshCallback failed to propagate error") - } -} - -// This demonstrates the danger of manual token without a refresh token -func TestServicePrincipalTokenManualRefreshFailsWithoutRefresh(t *testing.T) { - spt := newServicePrincipalTokenManual() - spt.RefreshToken = "" - err := spt.Refresh() - if err == nil { - t.Fatalf("azure: ServicePrincipalToken#Refresh should have failed with a ManualTokenSecret without a refresh token") - } -} - -func newToken() *Token { - return &Token{ - AccessToken: "ASECRETVALUE", - Resource: "https://azure.microsoft.com/", - Type: "Bearer", - } -} - -func newTokenJSON(expiresOn string, resource string) string { - return fmt.Sprintf(`{ - "access_token" : "accessToken", - "expires_in" : "3600", - "expires_on" : "%s", - "not_before" : "%s", - "resource" : "%s", - "token_type" : "Bearer" - }`, - expiresOn, expiresOn, resource) -} - -func newTokenExpiresIn(expireIn time.Duration) *Token { - return setTokenToExpireIn(newToken(), expireIn) -} - -func newTokenExpiresAt(expireAt time.Time) *Token { - return setTokenToExpireAt(newToken(), expireAt) -} - -func expireToken(t *Token) *Token { - return setTokenToExpireIn(t, 0) -} - -func setTokenToExpireAt(t *Token, expireAt time.Time) *Token { - t.ExpiresIn = "3600" - t.ExpiresOn = strconv.Itoa(int(expireAt.Sub(expirationBase).Seconds())) - t.NotBefore = t.ExpiresOn - return t -} - -func setTokenToExpireIn(t *Token, expireIn time.Duration) *Token { - return setTokenToExpireAt(t, time.Now().Add(expireIn)) -} - -func newServicePrincipalToken(callbacks ...TokenRefreshCallback) *ServicePrincipalToken { - spt, _ := NewServicePrincipalToken(TestOAuthConfig, "id", "secret", "resource", callbacks...) - return spt -} - -func newServicePrincipalTokenManual() *ServicePrincipalToken { - token := newToken() - token.RefreshToken = "refreshtoken" - spt, _ := NewServicePrincipalTokenFromManualToken(TestOAuthConfig, "id", "resource", *token) - return spt -} - -func newServicePrincipalTokenCertificate(t *testing.T) *ServicePrincipalToken { - template := x509.Certificate{ - SerialNumber: big.NewInt(0), - Subject: pkix.Name{CommonName: "test"}, - BasicConstraintsValid: true, - } - privateKey, err := rsa.GenerateKey(rand.Reader, 2048) - certificateBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &privateKey.PublicKey, privateKey) - if err != nil { - t.Fatal(err) - } - certificate, err := x509.ParseCertificate(certificateBytes) - if err != nil { - t.Fatal(err) - } - - spt, _ := NewServicePrincipalTokenFromCertificate(TestOAuthConfig, "id", certificate, privateKey, "resource") - return spt -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/client_test.go b/vendor/github.com/Azure/go-autorest/autorest/client_test.go deleted file mode 100644 index fba3aa3b2..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/client_test.go +++ /dev/null @@ -1,315 +0,0 @@ -package autorest - -import ( - "bytes" - "fmt" - "io/ioutil" - "log" - "math/rand" - "net/http" - "reflect" - "testing" - "time" - - "github.com/Azure/go-autorest/autorest/mocks" -) - -func TestLoggingInspectorWithInspection(t *testing.T) { - b := bytes.Buffer{} - c := Client{} - li := LoggingInspector{Logger: log.New(&b, "", 0)} - c.RequestInspector = li.WithInspection() - - Prepare(mocks.NewRequestWithContent("Content"), - c.WithInspection()) - - if len(b.String()) <= 0 { - t.Fatal("autorest: LoggingInspector#WithInspection did not record Request to the log") - } -} - -func TestLoggingInspectorWithInspectionEmitsErrors(t *testing.T) { - b := bytes.Buffer{} - c := Client{} - r := mocks.NewRequestWithContent("Content") - li := LoggingInspector{Logger: log.New(&b, "", 0)} - c.RequestInspector = li.WithInspection() - - if _, err := Prepare(r, - c.WithInspection()); err != nil { - t.Error(err) - } - - if len(b.String()) <= 0 { - t.Fatal("autorest: LoggingInspector#WithInspection did not record Request to the log") - } -} - -func TestLoggingInspectorWithInspectionRestoresBody(t *testing.T) { - b := bytes.Buffer{} - c := Client{} - r := mocks.NewRequestWithContent("Content") - li := LoggingInspector{Logger: log.New(&b, "", 0)} - c.RequestInspector = li.WithInspection() - - Prepare(r, - c.WithInspection()) - - s, _ := ioutil.ReadAll(r.Body) - if len(s) <= 0 { - t.Fatal("autorest: LoggingInspector#WithInspection did not restore the Request body") - } -} - -func TestLoggingInspectorByInspecting(t *testing.T) { - b := bytes.Buffer{} - c := Client{} - li := LoggingInspector{Logger: log.New(&b, "", 0)} - c.ResponseInspector = li.ByInspecting() - - Respond(mocks.NewResponseWithContent("Content"), - c.ByInspecting()) - - if len(b.String()) <= 0 { - t.Fatal("autorest: LoggingInspector#ByInspection did not record Response to the log") - } -} - -func TestLoggingInspectorByInspectingEmitsErrors(t *testing.T) { - b := bytes.Buffer{} - c := Client{} - r := mocks.NewResponseWithContent("Content") - li := LoggingInspector{Logger: log.New(&b, "", 0)} - c.ResponseInspector = li.ByInspecting() - - if err := Respond(r, - c.ByInspecting()); err != nil { - t.Fatal(err) - } - - if len(b.String()) <= 0 { - t.Fatal("autorest: LoggingInspector#ByInspection did not record Response to the log") - } -} - -func TestLoggingInspectorByInspectingRestoresBody(t *testing.T) { - b := bytes.Buffer{} - c := Client{} - r := mocks.NewResponseWithContent("Content") - li := LoggingInspector{Logger: log.New(&b, "", 0)} - c.ResponseInspector = li.ByInspecting() - - Respond(r, - c.ByInspecting()) - - s, _ := ioutil.ReadAll(r.Body) - if len(s) <= 0 { - t.Fatal("autorest: LoggingInspector#ByInspecting did not restore the Response body") - } -} - -func TestNewClientWithUserAgent(t *testing.T) { - ua := "UserAgent" - c := NewClientWithUserAgent(ua) - - if c.UserAgent != ua { - t.Fatalf("autorest: NewClientWithUserAgent failed to set the UserAgent -- expected %s, received %s", - ua, c.UserAgent) - } -} - -func TestClientSenderReturnsHttpClientByDefault(t *testing.T) { - c := Client{} - - if fmt.Sprintf("%T", c.sender()) != "*http.Client" { - t.Fatal("autorest: Client#sender failed to return http.Client by default") - } -} - -func TestClientSenderReturnsSetSender(t *testing.T) { - c := Client{} - - s := mocks.NewSender() - c.Sender = s - - if c.sender() != s { - t.Fatal("autorest: Client#sender failed to return set Sender") - } -} - -func TestClientDoInvokesSender(t *testing.T) { - c := Client{} - - s := mocks.NewSender() - c.Sender = s - - c.Do(&http.Request{}) - if s.Attempts() != 1 { - t.Fatal("autorest: Client#Do failed to invoke the Sender") - } -} - -func TestClientDoSetsUserAgent(t *testing.T) { - ua := "UserAgent" - c := Client{UserAgent: ua} - r := mocks.NewRequest() - s := mocks.NewSender() - c.Sender = s - - c.Do(r) - - if r.UserAgent() != ua { - t.Fatalf("autorest: Client#Do failed to correctly set User-Agent header: %s=%s", - http.CanonicalHeaderKey(headerUserAgent), r.UserAgent()) - } -} - -func TestClientDoSetsAuthorization(t *testing.T) { - r := mocks.NewRequest() - s := mocks.NewSender() - c := Client{Authorizer: mockAuthorizer{}, Sender: s} - - c.Do(r) - if len(r.Header.Get(http.CanonicalHeaderKey(headerAuthorization))) <= 0 { - t.Fatalf("autorest: Client#Send failed to set Authorization header -- %s=%s", - http.CanonicalHeaderKey(headerAuthorization), - r.Header.Get(http.CanonicalHeaderKey(headerAuthorization))) - } -} - -func TestClientDoInvokesRequestInspector(t *testing.T) { - r := mocks.NewRequest() - s := mocks.NewSender() - i := &mockInspector{} - c := Client{RequestInspector: i.WithInspection(), Sender: s} - - c.Do(r) - if !i.wasInvoked { - t.Fatal("autorest: Client#Send failed to invoke the RequestInspector") - } -} - -func TestClientDoInvokesResponseInspector(t *testing.T) { - r := mocks.NewRequest() - s := mocks.NewSender() - i := &mockInspector{} - c := Client{ResponseInspector: i.ByInspecting(), Sender: s} - - c.Do(r) - if !i.wasInvoked { - t.Fatal("autorest: Client#Send failed to invoke the ResponseInspector") - } -} - -func TestClientDoReturnsErrorIfPrepareFails(t *testing.T) { - c := Client{} - s := mocks.NewSender() - c.Authorizer = mockFailingAuthorizer{} - c.Sender = s - - _, err := c.Do(&http.Request{}) - if err == nil { - t.Fatalf("autorest: Client#Do failed to return an error when Prepare failed") - } -} - -func TestClientDoDoesNotSendIfPrepareFails(t *testing.T) { - c := Client{} - s := mocks.NewSender() - c.Authorizer = mockFailingAuthorizer{} - c.Sender = s - - c.Do(&http.Request{}) - if s.Attempts() > 0 { - t.Fatal("autorest: Client#Do failed to invoke the Sender") - } -} - -func TestClientAuthorizerReturnsNullAuthorizerByDefault(t *testing.T) { - c := Client{} - - if fmt.Sprintf("%T", c.authorizer()) != "autorest.NullAuthorizer" { - t.Fatal("autorest: Client#authorizer failed to return the NullAuthorizer by default") - } -} - -func TestClientAuthorizerReturnsSetAuthorizer(t *testing.T) { - c := Client{} - c.Authorizer = mockAuthorizer{} - - if fmt.Sprintf("%T", c.authorizer()) != "autorest.mockAuthorizer" { - t.Fatal("autorest: Client#authorizer failed to return the set Authorizer") - } -} - -func TestClientWithAuthorizer(t *testing.T) { - c := Client{} - c.Authorizer = mockAuthorizer{} - - req, _ := Prepare(&http.Request{}, - c.WithAuthorization()) - - if req.Header.Get(headerAuthorization) == "" { - t.Fatal("autorest: Client#WithAuthorizer failed to return the WithAuthorizer from the active Authorizer") - } -} - -func TestClientWithInspection(t *testing.T) { - c := Client{} - r := &mockInspector{} - c.RequestInspector = r.WithInspection() - - Prepare(&http.Request{}, - c.WithInspection()) - - if !r.wasInvoked { - t.Fatal("autorest: Client#WithInspection failed to invoke RequestInspector") - } -} - -func TestClientWithInspectionSetsDefault(t *testing.T) { - c := Client{} - - r1 := &http.Request{} - r2, _ := Prepare(r1, - c.WithInspection()) - - if !reflect.DeepEqual(r1, r2) { - t.Fatal("autorest: Client#WithInspection failed to provide a default RequestInspector") - } -} - -func TestClientByInspecting(t *testing.T) { - c := Client{} - r := &mockInspector{} - c.ResponseInspector = r.ByInspecting() - - Respond(&http.Response{}, - c.ByInspecting()) - - if !r.wasInvoked { - t.Fatal("autorest: Client#ByInspecting failed to invoke ResponseInspector") - } -} - -func TestClientByInspectingSetsDefault(t *testing.T) { - c := Client{} - - r := &http.Response{} - Respond(r, - c.ByInspecting()) - - if !reflect.DeepEqual(r, &http.Response{}) { - t.Fatal("autorest: Client#ByInspecting failed to provide a default ResponseInspector") - } -} - -func randomString(n int) string { - const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" - r := rand.New(rand.NewSource(time.Now().UTC().UnixNano())) - s := make([]byte, n) - for i := range s { - s[i] = chars[r.Intn(len(chars))] - } - return string(s) -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/date/date_test.go b/vendor/github.com/Azure/go-autorest/autorest/date/date_test.go deleted file mode 100644 index 622f1f7ef..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/date/date_test.go +++ /dev/null @@ -1,223 +0,0 @@ -package date - -import ( - "encoding/json" - "fmt" - "reflect" - "testing" - "time" -) - -func ExampleParseDate() { - d, err := ParseDate("2001-02-03") - if err != nil { - fmt.Println(err) - } - fmt.Println(d) - // Output: 2001-02-03 -} - -func ExampleDate() { - d, err := ParseDate("2001-02-03") - if err != nil { - fmt.Println(err) - } - - t, err := time.Parse(time.RFC3339, "2001-02-04T00:00:00Z") - if err != nil { - fmt.Println(err) - } - - // Date acts as time.Time when the receiver - if d.Before(t) { - fmt.Printf("Before ") - } else { - fmt.Printf("After ") - } - - // Convert Date when needing a time.Time - if t.After(d.ToTime()) { - fmt.Printf("After") - } else { - fmt.Printf("Before") - } - // Output: Before After -} - -func ExampleDate_MarshalBinary() { - d, err := ParseDate("2001-02-03") - if err != nil { - fmt.Println(err) - } - t, err := d.MarshalBinary() - if err != nil { - fmt.Println(err) - } - fmt.Println(string(t)) - // Output: 2001-02-03 -} - -func ExampleDate_UnmarshalBinary() { - d := Date{} - t := "2001-02-03" - - if err := d.UnmarshalBinary([]byte(t)); err != nil { - fmt.Println(err) - } - fmt.Println(d) - // Output: 2001-02-03 -} - -func ExampleDate_MarshalJSON() { - d, err := ParseDate("2001-02-03") - if err != nil { - fmt.Println(err) - } - j, err := json.Marshal(d) - if err != nil { - fmt.Println(err) - } - fmt.Println(string(j)) - // Output: "2001-02-03" -} - -func ExampleDate_UnmarshalJSON() { - var d struct { - Date Date `json:"date"` - } - j := `{"date" : "2001-02-03"}` - - if err := json.Unmarshal([]byte(j), &d); err != nil { - fmt.Println(err) - } - fmt.Println(d.Date) - // Output: 2001-02-03 -} - -func ExampleDate_MarshalText() { - d, err := ParseDate("2001-02-03") - if err != nil { - fmt.Println(err) - } - t, err := d.MarshalText() - if err != nil { - fmt.Println(err) - } - fmt.Println(string(t)) - // Output: 2001-02-03 -} - -func ExampleDate_UnmarshalText() { - d := Date{} - t := "2001-02-03" - - if err := d.UnmarshalText([]byte(t)); err != nil { - fmt.Println(err) - } - fmt.Println(d) - // Output: 2001-02-03 -} - -func TestDateString(t *testing.T) { - d, err := ParseDate("2001-02-03") - if err != nil { - t.Fatalf("date: String failed (%v)", err) - } - if d.String() != "2001-02-03" { - t.Fatalf("date: String failed (%v)", d.String()) - } -} - -func TestDateBinaryRoundTrip(t *testing.T) { - d1, err := ParseDate("2001-02-03") - if err != nil { - t.Fatalf("date: ParseDate failed (%v)", err) - } - t1, err := d1.MarshalBinary() - if err != nil { - t.Fatalf("date: MarshalBinary failed (%v)", err) - } - - d2 := Date{} - if err = d2.UnmarshalBinary(t1); err != nil { - t.Fatalf("date: UnmarshalBinary failed (%v)", err) - } - - if !reflect.DeepEqual(d1, d2) { - t.Fatalf("date: Round-trip Binary failed (%v, %v)", d1, d2) - } -} - -func TestDateJSONRoundTrip(t *testing.T) { - type s struct { - Date Date `json:"date"` - } - var err error - d1 := s{} - d1.Date, err = ParseDate("2001-02-03") - if err != nil { - t.Fatalf("date: ParseDate failed (%v)", err) - } - - j, err := json.Marshal(d1) - if err != nil { - t.Fatalf("date: MarshalJSON failed (%v)", err) - } - - d2 := s{} - if err = json.Unmarshal(j, &d2); err != nil { - t.Fatalf("date: UnmarshalJSON failed (%v)", err) - } - - if !reflect.DeepEqual(d1, d2) { - t.Fatalf("date: Round-trip JSON failed (%v, %v)", d1, d2) - } -} - -func TestDateTextRoundTrip(t *testing.T) { - d1, err := ParseDate("2001-02-03") - if err != nil { - t.Fatalf("date: ParseDate failed (%v)", err) - } - t1, err := d1.MarshalText() - if err != nil { - t.Fatalf("date: MarshalText failed (%v)", err) - } - d2 := Date{} - if err = d2.UnmarshalText(t1); err != nil { - t.Fatalf("date: UnmarshalText failed (%v)", err) - } - - if !reflect.DeepEqual(d1, d2) { - t.Fatalf("date: Round-trip Text failed (%v, %v)", d1, d2) - } -} - -func TestDateToTime(t *testing.T) { - var d Date - d, err := ParseDate("2001-02-03") - if err != nil { - t.Fatalf("date: ParseDate failed (%v)", err) - } - var _ time.Time = d.ToTime() -} - -func TestDateUnmarshalJSONReturnsError(t *testing.T) { - var d struct { - Date Date `json:"date"` - } - j := `{"date" : "February 3, 2001"}` - - if err := json.Unmarshal([]byte(j), &d); err == nil { - t.Fatal("date: Date failed to return error for malformed JSON date") - } -} - -func TestDateUnmarshalTextReturnsError(t *testing.T) { - d := Date{} - txt := "February 3, 2001" - - if err := d.UnmarshalText([]byte(txt)); err == nil { - t.Fatal("date: Date failed to return error for malformed Text date") - } -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/date/time_test.go b/vendor/github.com/Azure/go-autorest/autorest/date/time_test.go deleted file mode 100644 index 0a7dd9eb6..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/date/time_test.go +++ /dev/null @@ -1,263 +0,0 @@ -package date - -import ( - "encoding/json" - "fmt" - "reflect" - "testing" - "time" -) - -func ExampleParseTime() { - d, _ := ParseTime(rfc3339, "2001-02-03T04:05:06Z") - fmt.Println(d) - // Output: 2001-02-03 04:05:06 +0000 UTC -} - -func ExampleTime_MarshalBinary() { - ti, err := ParseTime(rfc3339, "2001-02-03T04:05:06Z") - if err != nil { - fmt.Println(err) - } - d := Time{ti} - t, err := d.MarshalBinary() - if err != nil { - fmt.Println(err) - } - fmt.Println(string(t)) - // Output: 2001-02-03T04:05:06Z -} - -func ExampleTime_UnmarshalBinary() { - d := Time{} - t := "2001-02-03T04:05:06Z" - - if err := d.UnmarshalBinary([]byte(t)); err != nil { - fmt.Println(err) - } - fmt.Println(d) - // Output: 2001-02-03T04:05:06Z -} - -func ExampleTime_MarshalJSON() { - d, err := ParseTime(rfc3339, "2001-02-03T04:05:06Z") - if err != nil { - fmt.Println(err) - } - j, err := json.Marshal(d) - if err != nil { - fmt.Println(err) - } - fmt.Println(string(j)) - // Output: "2001-02-03T04:05:06Z" -} - -func ExampleTime_UnmarshalJSON() { - var d struct { - Time Time `json:"datetime"` - } - j := `{"datetime" : "2001-02-03T04:05:06Z"}` - - if err := json.Unmarshal([]byte(j), &d); err != nil { - fmt.Println(err) - } - fmt.Println(d.Time) - // Output: 2001-02-03T04:05:06Z -} - -func ExampleTime_MarshalText() { - d, err := ParseTime(rfc3339, "2001-02-03T04:05:06Z") - if err != nil { - fmt.Println(err) - } - t, err := d.MarshalText() - if err != nil { - fmt.Println(err) - } - fmt.Println(string(t)) - // Output: 2001-02-03T04:05:06Z -} - -func ExampleTime_UnmarshalText() { - d := Time{} - t := "2001-02-03T04:05:06Z" - - if err := d.UnmarshalText([]byte(t)); err != nil { - fmt.Println(err) - } - fmt.Println(d) - // Output: 2001-02-03T04:05:06Z -} - -func TestUnmarshalTextforInvalidDate(t *testing.T) { - d := Time{} - dt := "2001-02-03T04:05:06AAA" - - if err := d.UnmarshalText([]byte(dt)); err == nil { - t.Fatalf("date: Time#Unmarshal was expecting error for invalid date") - } -} - -func TestUnmarshalJSONforInvalidDate(t *testing.T) { - d := Time{} - dt := `"2001-02-03T04:05:06AAA"` - - if err := d.UnmarshalJSON([]byte(dt)); err == nil { - t.Fatalf("date: Time#Unmarshal was expecting error for invalid date") - } -} - -func TestTimeString(t *testing.T) { - ti, err := ParseTime(rfc3339, "2001-02-03T04:05:06Z") - if err != nil { - fmt.Println(err) - } - d := Time{ti} - if d.String() != "2001-02-03T04:05:06Z" { - t.Fatalf("date: Time#String failed (%v)", d.String()) - } -} - -func TestTimeStringReturnsEmptyStringForError(t *testing.T) { - d := Time{Time: time.Date(20000, 01, 01, 01, 01, 01, 01, time.UTC)} - if d.String() != "" { - t.Fatalf("date: Time#String failed empty string for an error") - } -} - -func TestTimeBinaryRoundTrip(t *testing.T) { - ti, err := ParseTime(rfc3339, "2001-02-03T04:05:06Z") - if err != nil { - t.Fatalf("date: Time#ParseTime failed (%v)", err) - } - d1 := Time{ti} - t1, err := d1.MarshalBinary() - if err != nil { - t.Fatalf("date: Time#MarshalBinary failed (%v)", err) - } - - d2 := Time{} - if err = d2.UnmarshalBinary(t1); err != nil { - t.Fatalf("date: Time#UnmarshalBinary failed (%v)", err) - } - - if !reflect.DeepEqual(d1, d2) { - t.Fatalf("date:Round-trip Binary failed (%v, %v)", d1, d2) - } -} - -func TestTimeJSONRoundTrip(t *testing.T) { - type s struct { - Time Time `json:"datetime"` - } - - ti, err := ParseTime(rfc3339, "2001-02-03T04:05:06Z") - if err != nil { - t.Fatalf("date: Time#ParseTime failed (%v)", err) - } - - d1 := s{Time: Time{ti}} - j, err := json.Marshal(d1) - if err != nil { - t.Fatalf("date: Time#MarshalJSON failed (%v)", err) - } - - d2 := s{} - if err = json.Unmarshal(j, &d2); err != nil { - t.Fatalf("date: Time#UnmarshalJSON failed (%v)", err) - } - - if !reflect.DeepEqual(d1, d2) { - t.Fatalf("date: Round-trip JSON failed (%v, %v)", d1, d2) - } -} - -func TestTimeTextRoundTrip(t *testing.T) { - ti, err := ParseTime(rfc3339, "2001-02-03T04:05:06Z") - if err != nil { - t.Fatalf("date: Time#ParseTime failed (%v)", err) - } - d1 := Time{Time: ti} - t1, err := d1.MarshalText() - if err != nil { - t.Fatalf("date: Time#MarshalText failed (%v)", err) - } - - d2 := Time{} - if err = d2.UnmarshalText(t1); err != nil { - t.Fatalf("date: Time#UnmarshalText failed (%v)", err) - } - - if !reflect.DeepEqual(d1, d2) { - t.Fatalf("date: Round-trip Text failed (%v, %v)", d1, d2) - } -} - -func TestTimeToTime(t *testing.T) { - ti, err := ParseTime(rfc3339, "2001-02-03T04:05:06Z") - d := Time{ti} - if err != nil { - t.Fatalf("date: Time#ParseTime failed (%v)", err) - } - var _ time.Time = d.ToTime() -} - -func TestUnmarshalJSONNoOffset(t *testing.T) { - var d struct { - Time Time `json:"datetime"` - } - j := `{"datetime" : "2001-02-03T04:05:06.789"}` - - if err := json.Unmarshal([]byte(j), &d); err != nil { - t.Fatalf("date: Time#Unmarshal failed (%v)", err) - } -} - -func TestUnmarshalJSONPosOffset(t *testing.T) { - var d struct { - Time Time `json:"datetime"` - } - j := `{"datetime" : "1980-01-02T00:11:35.01+01:00"}` - - if err := json.Unmarshal([]byte(j), &d); err != nil { - t.Fatalf("date: Time#Unmarshal failed (%v)", err) - } -} - -func TestUnmarshalJSONNegOffset(t *testing.T) { - var d struct { - Time Time `json:"datetime"` - } - j := `{"datetime" : "1492-10-12T10:15:01.789-08:00"}` - - if err := json.Unmarshal([]byte(j), &d); err != nil { - t.Fatalf("date: Time#Unmarshal failed (%v)", err) - } -} - -func TestUnmarshalTextNoOffset(t *testing.T) { - d := Time{} - t1 := "2001-02-03T04:05:06" - - if err := d.UnmarshalText([]byte(t1)); err != nil { - t.Fatalf("date: Time#UnmarshalText failed (%v)", err) - } -} - -func TestUnmarshalTextPosOffset(t *testing.T) { - d := Time{} - t1 := "2001-02-03T04:05:06+00:30" - - if err := d.UnmarshalText([]byte(t1)); err != nil { - t.Fatalf("date: Time#UnmarshalText failed (%v)", err) - } -} - -func TestUnmarshalTextNegOffset(t *testing.T) { - d := Time{} - t1 := "2001-02-03T04:05:06-11:00" - - if err := d.UnmarshalText([]byte(t1)); err != nil { - t.Fatalf("date: Time#UnmarshalText failed (%v)", err) - } -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/date/timerfc1123_test.go b/vendor/github.com/Azure/go-autorest/autorest/date/timerfc1123_test.go deleted file mode 100644 index 28f3ce213..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/date/timerfc1123_test.go +++ /dev/null @@ -1,212 +0,0 @@ -package date - -import ( - "encoding/json" - "fmt" - "reflect" - "testing" - "time" -) - -func ExampleTimeRFC1123() { - d, err := ParseTime(rfc1123, "Mon, 02 Jan 2006 15:04:05 MST") - if err != nil { - fmt.Println(err) - } - fmt.Println(d) - // Output: 2006-01-02 15:04:05 +0000 MST -} - -func ExampleTimeRFC1123_MarshalBinary() { - ti, err := ParseTime(rfc1123, "Mon, 02 Jan 2006 15:04:05 MST") - if err != nil { - fmt.Println(err) - } - d := TimeRFC1123{ti} - b, err := d.MarshalBinary() - if err != nil { - fmt.Println(err) - } - fmt.Println(string(b)) - // Output: Mon, 02 Jan 2006 15:04:05 MST -} - -func ExampleTimeRFC1123_UnmarshalBinary() { - d := TimeRFC1123{} - t := "Mon, 02 Jan 2006 15:04:05 MST" - if err := d.UnmarshalBinary([]byte(t)); err != nil { - fmt.Println(err) - } - fmt.Println(d) - // Output: Mon, 02 Jan 2006 15:04:05 MST -} - -func ExampleTimeRFC1123_MarshalJSON() { - ti, err := ParseTime(rfc1123, "Mon, 02 Jan 2006 15:04:05 MST") - if err != nil { - fmt.Println(err) - } - d := TimeRFC1123{ti} - j, err := json.Marshal(d) - if err != nil { - fmt.Println(err) - } - fmt.Println(string(j)) - // Output: "Mon, 02 Jan 2006 15:04:05 MST" -} - -func TestTimeRFC1123MarshalJSONInvalid(t *testing.T) { - ti := time.Date(20000, 01, 01, 00, 00, 00, 00, time.UTC) - d := TimeRFC1123{ti} - if _, err := json.Marshal(d); err == nil { - t.Fatalf("date: TimeRFC1123#Marshal failed for invalid date") - } -} - -func ExampleTimeRFC1123_UnmarshalJSON() { - var d struct { - Time TimeRFC1123 `json:"datetime"` - } - j := `{"datetime" : "Mon, 02 Jan 2006 15:04:05 MST"}` - - if err := json.Unmarshal([]byte(j), &d); err != nil { - fmt.Println(err) - } - fmt.Println(d.Time) - // Output: Mon, 02 Jan 2006 15:04:05 MST -} - -func ExampleTimeRFC1123_MarshalText() { - ti, err := ParseTime(rfc3339, "2001-02-03T04:05:06Z") - if err != nil { - fmt.Println(err) - } - d := TimeRFC1123{ti} - t, err := d.MarshalText() - if err != nil { - fmt.Println(err) - } - fmt.Println(string(t)) - // Output: Sat, 03 Feb 2001 04:05:06 UTC -} - -func ExampleTimeRFC1123_UnmarshalText() { - d := TimeRFC1123{} - t := "Sat, 03 Feb 2001 04:05:06 UTC" - - if err := d.UnmarshalText([]byte(t)); err != nil { - fmt.Println(err) - } - fmt.Println(d) - // Output: Sat, 03 Feb 2001 04:05:06 UTC -} - -func TestUnmarshalJSONforInvalidDateRfc1123(t *testing.T) { - dt := `"Mon, 02 Jan 2000000 15:05 MST"` - d := TimeRFC1123{} - if err := d.UnmarshalJSON([]byte(dt)); err == nil { - t.Fatalf("date: TimeRFC1123#Unmarshal failed for invalid date") - } -} - -func TestUnmarshalTextforInvalidDateRfc1123(t *testing.T) { - dt := "Mon, 02 Jan 2000000 15:05 MST" - d := TimeRFC1123{} - if err := d.UnmarshalText([]byte(dt)); err == nil { - t.Fatalf("date: TimeRFC1123#Unmarshal failed for invalid date") - } -} - -func TestTimeStringRfc1123(t *testing.T) { - ti, err := ParseTime(rfc1123, "Mon, 02 Jan 2006 15:04:05 MST") - if err != nil { - fmt.Println(err) - } - d := TimeRFC1123{ti} - if d.String() != "Mon, 02 Jan 2006 15:04:05 MST" { - t.Fatalf("date: TimeRFC1123#String failed (%v)", d.String()) - } -} - -func TestTimeStringReturnsEmptyStringForErrorRfc1123(t *testing.T) { - d := TimeRFC1123{Time: time.Date(20000, 01, 01, 01, 01, 01, 01, time.UTC)} - if d.String() != "" { - t.Fatalf("date: TimeRFC1123#String failed empty string for an error") - } -} - -func TestTimeBinaryRoundTripRfc1123(t *testing.T) { - ti, err := ParseTime(rfc3339, "2001-02-03T04:05:06Z") - if err != nil { - t.Fatalf("date: TimeRFC1123#ParseTime failed (%v)", err) - } - d1 := TimeRFC1123{ti} - t1, err := d1.MarshalBinary() - if err != nil { - t.Fatalf("date: TimeRFC1123#MarshalBinary failed (%v)", err) - } - - d2 := TimeRFC1123{} - if err = d2.UnmarshalBinary(t1); err != nil { - t.Fatalf("date: TimeRFC1123#UnmarshalBinary failed (%v)", err) - } - - if !reflect.DeepEqual(d1, d2) { - t.Fatalf("date: Round-trip Binary failed (%v, %v)", d1, d2) - } -} - -func TestTimeJSONRoundTripRfc1123(t *testing.T) { - type s struct { - Time TimeRFC1123 `json:"datetime"` - } - var err error - ti, err := ParseTime(rfc1123, "Mon, 02 Jan 2006 15:04:05 MST") - if err != nil { - t.Fatalf("date: TimeRFC1123#ParseTime failed (%v)", err) - } - d1 := s{Time: TimeRFC1123{ti}} - j, err := json.Marshal(d1) - if err != nil { - t.Fatalf("date: TimeRFC1123#MarshalJSON failed (%v)", err) - } - - d2 := s{} - if err = json.Unmarshal(j, &d2); err != nil { - t.Fatalf("date: TimeRFC1123#UnmarshalJSON failed (%v)", err) - } - - if !reflect.DeepEqual(d1, d2) { - t.Fatalf("date: Round-trip JSON failed (%v, %v)", d1, d2) - } -} - -func TestTimeTextRoundTripRfc1123(t *testing.T) { - ti, err := ParseTime(rfc1123, "Mon, 02 Jan 2006 15:04:05 MST") - if err != nil { - t.Fatalf("date: TimeRFC1123#ParseTime failed (%v)", err) - } - d1 := TimeRFC1123{Time: ti} - t1, err := d1.MarshalText() - if err != nil { - t.Fatalf("date: TimeRFC1123#MarshalText failed (%v)", err) - } - - d2 := TimeRFC1123{} - if err = d2.UnmarshalText(t1); err != nil { - t.Fatalf("date: TimeRFC1123#UnmarshalText failed (%v)", err) - } - - if !reflect.DeepEqual(d1, d2) { - t.Fatalf("date: Round-trip Text failed (%v, %v)", d1, d2) - } -} - -func TestTimeToTimeRFC1123(t *testing.T) { - ti, err := ParseTime(rfc1123, "Mon, 02 Jan 2006 15:04:05 MST") - d := TimeRFC1123{ti} - if err != nil { - t.Fatalf("date: TimeRFC1123#ParseTime failed (%v)", err) - } - var _ time.Time = d.ToTime() -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/error_test.go b/vendor/github.com/Azure/go-autorest/autorest/error_test.go deleted file mode 100644 index 1975155ad..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/error_test.go +++ /dev/null @@ -1,188 +0,0 @@ -package autorest - -import ( - "fmt" - "net/http" - "reflect" - "regexp" - "testing" -) - -func TestNewErrorWithError_AssignsPackageType(t *testing.T) { - e := NewErrorWithError(fmt.Errorf("original"), "packageType", "method", nil, "message") - - if e.PackageType != "packageType" { - t.Fatalf("autorest: Error failed to set package type -- expected %v, received %v", "packageType", e.PackageType) - } -} - -func TestNewErrorWithError_AssignsMethod(t *testing.T) { - e := NewErrorWithError(fmt.Errorf("original"), "packageType", "method", nil, "message") - - if e.Method != "method" { - t.Fatalf("autorest: Error failed to set method -- expected %v, received %v", "method", e.Method) - } -} - -func TestNewErrorWithError_AssignsMessage(t *testing.T) { - e := NewErrorWithError(fmt.Errorf("original"), "packageType", "method", nil, "message") - - if e.Message != "message" { - t.Fatalf("autorest: Error failed to set message -- expected %v, received %v", "message", e.Message) - } -} - -func TestNewErrorWithError_AssignsUndefinedStatusCodeIfRespNil(t *testing.T) { - e := NewErrorWithError(nil, "packageType", "method", nil, "message") - if e.StatusCode != UndefinedStatusCode { - t.Fatalf("autorest: Error failed to set status code -- expected %v, received %v", UndefinedStatusCode, e.StatusCode) - } -} - -func TestNewErrorWithError_AssignsStatusCode(t *testing.T) { - e := NewErrorWithError(fmt.Errorf("original"), "packageType", "method", &http.Response{ - StatusCode: http.StatusBadRequest, - Status: http.StatusText(http.StatusBadRequest)}, "message") - - if e.StatusCode != http.StatusBadRequest { - t.Fatalf("autorest: Error failed to set status code -- expected %v, received %v", http.StatusBadRequest, e.StatusCode) - } -} - -func TestNewErrorWithError_AcceptsArgs(t *testing.T) { - e := NewErrorWithError(fmt.Errorf("original"), "packageType", "method", nil, "message %s", "arg") - - if matched, _ := regexp.MatchString(`.*arg.*`, e.Message); !matched { - t.Fatalf("autorest: Error failed to apply message arguments -- expected %v, received %v", - `.*arg.*`, e.Message) - } -} - -func TestNewErrorWithError_AssignsError(t *testing.T) { - err := fmt.Errorf("original") - e := NewErrorWithError(err, "packageType", "method", nil, "message") - - if e.Original != err { - t.Fatalf("autorest: Error failed to set error -- expected %v, received %v", err, e.Original) - } -} - -func TestNewErrorWithResponse_ContainsStatusCode(t *testing.T) { - e := NewErrorWithResponse("packageType", "method", &http.Response{ - StatusCode: http.StatusBadRequest, - Status: http.StatusText(http.StatusBadRequest)}, "message") - - if e.StatusCode != http.StatusBadRequest { - t.Fatalf("autorest: Error failed to set status code -- expected %v, received %v", http.StatusBadRequest, e.StatusCode) - } -} - -func TestNewErrorWithResponse_nilResponse_ReportsUndefinedStatusCode(t *testing.T) { - e := NewErrorWithResponse("packageType", "method", nil, "message") - - if e.StatusCode != UndefinedStatusCode { - t.Fatalf("autorest: Error failed to set status code -- expected %v, received %v", UndefinedStatusCode, e.StatusCode) - } -} - -func TestNewErrorWithResponse_Forwards(t *testing.T) { - e1 := NewError("packageType", "method", "message %s", "arg") - e2 := NewErrorWithResponse("packageType", "method", nil, "message %s", "arg") - - if !reflect.DeepEqual(e1, e2) { - t.Fatal("autorest: NewError did not return an error equivelent to NewErrorWithError") - } -} - -func TestNewErrorWithError_Forwards(t *testing.T) { - e1 := NewError("packageType", "method", "message %s", "arg") - e2 := NewErrorWithError(nil, "packageType", "method", nil, "message %s", "arg") - - if !reflect.DeepEqual(e1, e2) { - t.Fatal("autorest: NewError did not return an error equivelent to NewErrorWithError") - } -} - -func TestNewErrorWithError_DoesNotWrapADetailedError(t *testing.T) { - e1 := NewError("packageType1", "method1", "message1 %s", "arg1") - e2 := NewErrorWithError(e1, "packageType2", "method2", nil, "message2 %s", "arg2") - - if !reflect.DeepEqual(e1, e2) { - t.Fatalf("autorest: NewErrorWithError incorrectly wrapped a DetailedError -- expected %v, received %v", e1, e2) - } -} - -func TestNewErrorWithError_WrapsAnError(t *testing.T) { - e1 := fmt.Errorf("Inner Error") - var e2 interface{} = NewErrorWithError(e1, "packageType", "method", nil, "message") - - if _, ok := e2.(DetailedError); !ok { - t.Fatalf("autorest: NewErrorWithError failed to wrap a standard error -- received %T", e2) - } -} - -func TestDetailedError(t *testing.T) { - err := fmt.Errorf("original") - e := NewErrorWithError(err, "packageType", "method", nil, "message") - - if matched, _ := regexp.MatchString(`.*original.*`, e.Error()); !matched { - t.Fatalf("autorest: Error#Error failed to return original error message -- expected %v, received %v", - `.*original.*`, e.Error()) - } -} - -func TestDetailedErrorConstainsPackageType(t *testing.T) { - e := NewErrorWithError(fmt.Errorf("original"), "packageType", "method", nil, "message") - - if matched, _ := regexp.MatchString(`.*packageType.*`, e.Error()); !matched { - t.Fatalf("autorest: Error#String failed to include PackageType -- expected %v, received %v", - `.*packageType.*`, e.Error()) - } -} - -func TestDetailedErrorConstainsMethod(t *testing.T) { - e := NewErrorWithError(fmt.Errorf("original"), "packageType", "method", nil, "message") - - if matched, _ := regexp.MatchString(`.*method.*`, e.Error()); !matched { - t.Fatalf("autorest: Error#String failed to include Method -- expected %v, received %v", - `.*method.*`, e.Error()) - } -} - -func TestDetailedErrorConstainsMessage(t *testing.T) { - e := NewErrorWithError(fmt.Errorf("original"), "packageType", "method", nil, "message") - - if matched, _ := regexp.MatchString(`.*message.*`, e.Error()); !matched { - t.Fatalf("autorest: Error#String failed to include Message -- expected %v, received %v", - `.*message.*`, e.Error()) - } -} - -func TestDetailedErrorConstainsStatusCode(t *testing.T) { - e := NewErrorWithError(fmt.Errorf("original"), "packageType", "method", &http.Response{ - StatusCode: http.StatusBadRequest, - Status: http.StatusText(http.StatusBadRequest)}, "message") - - if matched, _ := regexp.MatchString(`.*400.*`, e.Error()); !matched { - t.Fatalf("autorest: Error#String failed to include Status Code -- expected %v, received %v", - `.*400.*`, e.Error()) - } -} - -func TestDetailedErrorConstainsOriginal(t *testing.T) { - e := NewErrorWithError(fmt.Errorf("original"), "packageType", "method", nil, "message") - - if matched, _ := regexp.MatchString(`.*original.*`, e.Error()); !matched { - t.Fatalf("autorest: Error#String failed to include Original error -- expected %v, received %v", - `.*original.*`, e.Error()) - } -} - -func TestDetailedErrorSkipsOriginal(t *testing.T) { - e := NewError("packageType", "method", "message") - - if matched, _ := regexp.MatchString(`.*Original.*`, e.Error()); matched { - t.Fatalf("autorest: Error#String included missing Original error -- unexpected %v, received %v", - `.*Original.*`, e.Error()) - } -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/preparer_test.go b/vendor/github.com/Azure/go-autorest/autorest/preparer_test.go deleted file mode 100644 index 1b36379aa..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/preparer_test.go +++ /dev/null @@ -1,718 +0,0 @@ -package autorest - -import ( - "fmt" - "io/ioutil" - "net/http" - "net/url" - "reflect" - "strconv" - "strings" - "testing" - - "github.com/Azure/go-autorest/autorest/mocks" -) - -// PrepareDecorators wrap and invoke a Preparer. Most often, the decorator invokes the passed -// Preparer and decorates the response. -func ExamplePrepareDecorator() { - path := "a/b/c/" - pd := func() PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err == nil { - if r.URL == nil { - return r, fmt.Errorf("ERROR: URL is not set") - } - r.URL.Path += path - } - return r, err - }) - } - } - - r, _ := Prepare(&http.Request{}, - WithBaseURL("https://microsoft.com/"), - pd()) - - fmt.Printf("Path is %s\n", r.URL) - // Output: Path is https://microsoft.com/a/b/c/ -} - -// PrepareDecorators may also modify and then invoke the Preparer. -func ExamplePrepareDecorator_pre() { - pd := func() PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r.Header.Add(http.CanonicalHeaderKey("ContentType"), "application/json") - return p.Prepare(r) - }) - } - } - - r, _ := Prepare(&http.Request{Header: http.Header{}}, - pd()) - - fmt.Printf("ContentType is %s\n", r.Header.Get("ContentType")) - // Output: ContentType is application/json -} - -// Create a sequence of three Preparers that build up the URL path. -func ExampleCreatePreparer() { - p := CreatePreparer( - WithBaseURL("https://microsoft.com/"), - WithPath("a"), - WithPath("b"), - WithPath("c")) - r, err := p.Prepare(&http.Request{}) - if err != nil { - fmt.Printf("ERROR: %v\n", err) - } else { - fmt.Println(r.URL) - } - // Output: https://microsoft.com/a/b/c -} - -// Create and apply separate Preparers -func ExampleCreatePreparer_multiple() { - params := map[string]interface{}{ - "param1": "a", - "param2": "c", - } - - p1 := CreatePreparer(WithBaseURL("https://microsoft.com/")) - p2 := CreatePreparer(WithPathParameters("/{param1}/b/{param2}/", params)) - - r, err := p1.Prepare(&http.Request{}) - if err != nil { - fmt.Printf("ERROR: %v\n", err) - } - - r, err = p2.Prepare(r) - if err != nil { - fmt.Printf("ERROR: %v\n", err) - } else { - fmt.Println(r.URL) - } - // Output: https://microsoft.com/a/b/c/ -} - -// Create and chain separate Preparers -func ExampleCreatePreparer_chain() { - params := map[string]interface{}{ - "param1": "a", - "param2": "c", - } - - p := CreatePreparer(WithBaseURL("https://microsoft.com/")) - p = DecoratePreparer(p, WithPathParameters("/{param1}/b/{param2}/", params)) - - r, err := p.Prepare(&http.Request{}) - if err != nil { - fmt.Printf("ERROR: %v\n", err) - } else { - fmt.Println(r.URL) - } - // Output: https://microsoft.com/a/b/c/ -} - -// Create and prepare an http.Request in one call -func ExamplePrepare() { - r, err := Prepare(&http.Request{}, - AsGet(), - WithBaseURL("https://microsoft.com/"), - WithPath("a/b/c/")) - if err != nil { - fmt.Printf("ERROR: %v\n", err) - } else { - fmt.Printf("%s %s", r.Method, r.URL) - } - // Output: GET https://microsoft.com/a/b/c/ -} - -// Create a request for a supplied base URL and path -func ExampleWithBaseURL() { - r, err := Prepare(&http.Request{}, - WithBaseURL("https://microsoft.com/a/b/c/")) - if err != nil { - fmt.Printf("ERROR: %v\n", err) - } else { - fmt.Println(r.URL) - } - // Output: https://microsoft.com/a/b/c/ -} - -func ExampleWithBaseURL_second() { - _, err := Prepare(&http.Request{}, WithBaseURL(":")) - fmt.Println(err) - // Output: parse :: missing protocol scheme -} - -// Create a request with a custom HTTP header -func ExampleWithHeader() { - r, err := Prepare(&http.Request{}, - WithBaseURL("https://microsoft.com/a/b/c/"), - WithHeader("x-foo", "bar")) - if err != nil { - fmt.Printf("ERROR: %v\n", err) - } else { - fmt.Printf("Header %s=%s\n", "x-foo", r.Header.Get("x-foo")) - } - // Output: Header x-foo=bar -} - -// Create a request whose Body is the JSON encoding of a structure -func ExampleWithFormData() { - v := url.Values{} - v.Add("name", "Rob Pike") - v.Add("age", "42") - - r, err := Prepare(&http.Request{}, - WithFormData(v)) - if err != nil { - fmt.Printf("ERROR: %v\n", err) - } - - b, err := ioutil.ReadAll(r.Body) - if err != nil { - fmt.Printf("ERROR: %v\n", err) - } else { - fmt.Printf("Request Body contains %s\n", string(b)) - } - // Output: Request Body contains age=42&name=Rob+Pike -} - -// Create a request whose Body is the JSON encoding of a structure -func ExampleWithJSON() { - t := mocks.T{Name: "Rob Pike", Age: 42} - - r, err := Prepare(&http.Request{}, - WithJSON(&t)) - if err != nil { - fmt.Printf("ERROR: %v\n", err) - } - - b, err := ioutil.ReadAll(r.Body) - if err != nil { - fmt.Printf("ERROR: %v\n", err) - } else { - fmt.Printf("Request Body contains %s\n", string(b)) - } - // Output: Request Body contains {"name":"Rob Pike","age":42} -} - -// Create a request from a path with escaped parameters -func ExampleWithEscapedPathParameters() { - params := map[string]interface{}{ - "param1": "a b c", - "param2": "d e f", - } - r, err := Prepare(&http.Request{}, - WithBaseURL("https://microsoft.com/"), - WithEscapedPathParameters("/{param1}/b/{param2}/", params)) - if err != nil { - fmt.Printf("ERROR: %v\n", err) - } else { - fmt.Println(r.URL) - } - // Output: https://microsoft.com/a+b+c/b/d+e+f/ -} - -// Create a request from a path with parameters -func ExampleWithPathParameters() { - params := map[string]interface{}{ - "param1": "a", - "param2": "c", - } - r, err := Prepare(&http.Request{}, - WithBaseURL("https://microsoft.com/"), - WithPathParameters("/{param1}/b/{param2}/", params)) - if err != nil { - fmt.Printf("ERROR: %v\n", err) - } else { - fmt.Println(r.URL) - } - // Output: https://microsoft.com/a/b/c/ -} - -// Create a request with query parameters -func ExampleWithQueryParameters() { - params := map[string]interface{}{ - "q1": "value1", - "q2": "value2", - } - r, err := Prepare(&http.Request{}, - WithBaseURL("https://microsoft.com/"), - WithPath("/a/b/c/"), - WithQueryParameters(params)) - if err != nil { - fmt.Printf("ERROR: %v\n", err) - } else { - fmt.Println(r.URL) - } - // Output: https://microsoft.com/a/b/c/?q1=value1&q2=value2 -} - -func TestWithPathWithInvalidPath(t *testing.T) { - p := "path%2*end" - if _, err := Prepare(&http.Request{}, WithBaseURL("https://microsoft.com/"), WithPath(p)); err == nil { - t.Fatalf("autorest: WithPath should fail for invalid URL escape error for path '%v' ", p) - } - -} - -func TestWithPathParametersWithInvalidPath(t *testing.T) { - p := "path%2*end" - m := map[string]interface{}{ - "path1": p, - } - if _, err := Prepare(&http.Request{}, WithBaseURL("https://microsoft.com/"), WithPathParameters("/{path1}/", m)); err == nil { - t.Fatalf("autorest: WithPath should fail for invalid URL escape for path '%v' ", p) - } - -} - -func TestCreatePreparerDoesNotModify(t *testing.T) { - r1 := &http.Request{} - p := CreatePreparer() - r2, err := p.Prepare(r1) - if err != nil { - t.Fatalf("autorest: CreatePreparer failed (%v)", err) - } - if !reflect.DeepEqual(r1, r2) { - t.Fatalf("autorest: CreatePreparer without decorators modified the request") - } -} - -func TestCreatePreparerRunsDecoratorsInOrder(t *testing.T) { - p := CreatePreparer(WithBaseURL("https://microsoft.com/"), WithPath("1"), WithPath("2"), WithPath("3")) - r, err := p.Prepare(&http.Request{}) - if err != nil { - t.Fatalf("autorest: CreatePreparer failed (%v)", err) - } - if r.URL.String() != "https:/1/2/3" && r.URL.Host != "microsoft.com" { - t.Fatalf("autorest: CreatePreparer failed to run decorators in order") - } -} - -func TestAsContentType(t *testing.T) { - r, err := Prepare(mocks.NewRequest(), AsContentType("application/text")) - if err != nil { - fmt.Printf("ERROR: %v", err) - } - if r.Header.Get(headerContentType) != "application/text" { - t.Fatalf("autorest: AsContentType failed to add header (%s=%s)", headerContentType, r.Header.Get(headerContentType)) - } -} - -func TestAsFormURLEncoded(t *testing.T) { - r, err := Prepare(mocks.NewRequest(), AsFormURLEncoded()) - if err != nil { - fmt.Printf("ERROR: %v", err) - } - if r.Header.Get(headerContentType) != mimeTypeFormPost { - t.Fatalf("autorest: AsFormURLEncoded failed to add header (%s=%s)", headerContentType, r.Header.Get(headerContentType)) - } -} - -func TestAsJSON(t *testing.T) { - r, err := Prepare(mocks.NewRequest(), AsJSON()) - if err != nil { - fmt.Printf("ERROR: %v", err) - } - if r.Header.Get(headerContentType) != mimeTypeJSON { - t.Fatalf("autorest: AsJSON failed to add header (%s=%s)", headerContentType, r.Header.Get(headerContentType)) - } -} - -func TestWithNothing(t *testing.T) { - r1 := mocks.NewRequest() - r2, err := Prepare(r1, WithNothing()) - if err != nil { - t.Fatalf("autorest: WithNothing returned an unexpected error (%v)", err) - } - - if !reflect.DeepEqual(r1, r2) { - t.Fatal("azure: WithNothing modified the passed HTTP Request") - } -} - -func TestWithBearerAuthorization(t *testing.T) { - r, err := Prepare(mocks.NewRequest(), WithBearerAuthorization("SOME-TOKEN")) - if err != nil { - fmt.Printf("ERROR: %v", err) - } - if r.Header.Get(headerAuthorization) != "Bearer SOME-TOKEN" { - t.Fatalf("autorest: WithBearerAuthorization failed to add header (%s=%s)", headerAuthorization, r.Header.Get(headerAuthorization)) - } -} - -func TestWithUserAgent(t *testing.T) { - ua := "User Agent Go" - r, err := Prepare(mocks.NewRequest(), WithUserAgent(ua)) - if err != nil { - fmt.Printf("ERROR: %v", err) - } - if r.UserAgent() != ua || r.Header.Get(headerUserAgent) != ua { - t.Fatalf("autorest: WithUserAgent failed to add header (%s=%s)", headerUserAgent, r.Header.Get(headerUserAgent)) - } -} - -func TestWithMethod(t *testing.T) { - r, _ := Prepare(mocks.NewRequest(), WithMethod("HEAD")) - if r.Method != "HEAD" { - t.Fatal("autorest: WithMethod failed to set HTTP method header") - } -} - -func TestAsDelete(t *testing.T) { - r, _ := Prepare(mocks.NewRequest(), AsDelete()) - if r.Method != "DELETE" { - t.Fatal("autorest: AsDelete failed to set HTTP method header to DELETE") - } -} - -func TestAsGet(t *testing.T) { - r, _ := Prepare(mocks.NewRequest(), AsGet()) - if r.Method != "GET" { - t.Fatal("autorest: AsGet failed to set HTTP method header to GET") - } -} - -func TestAsHead(t *testing.T) { - r, _ := Prepare(mocks.NewRequest(), AsHead()) - if r.Method != "HEAD" { - t.Fatal("autorest: AsHead failed to set HTTP method header to HEAD") - } -} - -func TestAsOptions(t *testing.T) { - r, _ := Prepare(mocks.NewRequest(), AsOptions()) - if r.Method != "OPTIONS" { - t.Fatal("autorest: AsOptions failed to set HTTP method header to OPTIONS") - } -} - -func TestAsPatch(t *testing.T) { - r, _ := Prepare(mocks.NewRequest(), AsPatch()) - if r.Method != "PATCH" { - t.Fatal("autorest: AsPatch failed to set HTTP method header to PATCH") - } -} - -func TestAsPost(t *testing.T) { - r, _ := Prepare(mocks.NewRequest(), AsPost()) - if r.Method != "POST" { - t.Fatal("autorest: AsPost failed to set HTTP method header to POST") - } -} - -func TestAsPut(t *testing.T) { - r, _ := Prepare(mocks.NewRequest(), AsPut()) - if r.Method != "PUT" { - t.Fatal("autorest: AsPut failed to set HTTP method header to PUT") - } -} - -func TestPrepareWithNullRequest(t *testing.T) { - _, err := Prepare(nil) - if err == nil { - t.Fatal("autorest: Prepare failed to return an error when given a null http.Request") - } -} - -func TestWithFormDataSetsContentLength(t *testing.T) { - v := url.Values{} - v.Add("name", "Rob Pike") - v.Add("age", "42") - - r, err := Prepare(&http.Request{}, - WithFormData(v)) - if err != nil { - t.Fatalf("autorest: WithFormData failed with error (%v)", err) - } - - b, err := ioutil.ReadAll(r.Body) - if err != nil { - t.Fatalf("autorest: WithFormData failed with error (%v)", err) - } - - expected := "name=Rob+Pike&age=42" - if !(string(b) == "name=Rob+Pike&age=42" || string(b) == "age=42&name=Rob+Pike") { - t.Fatalf("autorest:WithFormData failed to return correct string got (%v), expected (%v)", string(b), expected) - } - - if r.ContentLength != int64(len(b)) { - t.Fatalf("autorest:WithFormData set Content-Length to %v, expected %v", r.ContentLength, len(b)) - } -} - -func TestWithMultiPartFormDataSetsContentLength(t *testing.T) { - v := map[string]interface{}{ - "file": ioutil.NopCloser(strings.NewReader("Hello Gopher")), - "age": "42", - } - - r, err := Prepare(&http.Request{}, - WithMultiPartFormData(v)) - if err != nil { - t.Fatalf("autorest: WithMultiPartFormData failed with error (%v)", err) - } - - b, err := ioutil.ReadAll(r.Body) - if err != nil { - t.Fatalf("autorest: WithMultiPartFormData failed with error (%v)", err) - } - - if r.ContentLength != int64(len(b)) { - t.Fatalf("autorest:WithMultiPartFormData set Content-Length to %v, expected %v", r.ContentLength, len(b)) - } -} - -func TestWithMultiPartFormDataWithNoFile(t *testing.T) { - v := map[string]interface{}{ - "file": "no file", - "age": "42", - } - - r, err := Prepare(&http.Request{}, - WithMultiPartFormData(v)) - if err != nil { - t.Fatalf("autorest: WithMultiPartFormData failed with error (%v)", err) - } - - b, err := ioutil.ReadAll(r.Body) - if err != nil { - t.Fatalf("autorest: WithMultiPartFormData failed with error (%v)", err) - } - - if r.ContentLength != int64(len(b)) { - t.Fatalf("autorest:WithMultiPartFormData set Content-Length to %v, expected %v", r.ContentLength, len(b)) - } -} - -func TestWithFile(t *testing.T) { - r, err := Prepare(&http.Request{}, - WithFile(ioutil.NopCloser(strings.NewReader("Hello Gopher")))) - if err != nil { - t.Fatalf("autorest: WithFile failed with error (%v)", err) - } - - b, err := ioutil.ReadAll(r.Body) - if err != nil { - t.Fatalf("autorest: WithFile failed with error (%v)", err) - } - if r.ContentLength != int64(len(b)) { - t.Fatalf("autorest:WithFile set Content-Length to %v, expected %v", r.ContentLength, len(b)) - } -} - -func TestWithBool_SetsTheBody(t *testing.T) { - r, err := Prepare(&http.Request{}, - WithBool(false)) - if err != nil { - t.Fatalf("autorest: WithBool failed with error (%v)", err) - } - - s, err := ioutil.ReadAll(r.Body) - if err != nil { - t.Fatalf("autorest: WithBool failed with error (%v)", err) - } - - if r.ContentLength != int64(len(fmt.Sprintf("%v", false))) { - t.Fatalf("autorest: WithBool set Content-Length to %v, expected %v", r.ContentLength, int64(len(fmt.Sprintf("%v", false)))) - } - - v, err := strconv.ParseBool(string(s)) - if err != nil || v { - t.Fatalf("autorest: WithBool incorrectly encoded the boolean as %v", s) - } -} - -func TestWithFloat32_SetsTheBody(t *testing.T) { - r, err := Prepare(&http.Request{}, - WithFloat32(42.0)) - if err != nil { - t.Fatalf("autorest: WithFloat32 failed with error (%v)", err) - } - - s, err := ioutil.ReadAll(r.Body) - if err != nil { - t.Fatalf("autorest: WithFloat32 failed with error (%v)", err) - } - - if r.ContentLength != int64(len(fmt.Sprintf("%v", 42.0))) { - t.Fatalf("autorest: WithFloat32 set Content-Length to %v, expected %v", r.ContentLength, int64(len(fmt.Sprintf("%v", 42.0)))) - } - - v, err := strconv.ParseFloat(string(s), 32) - if err != nil || float32(v) != float32(42.0) { - t.Fatalf("autorest: WithFloat32 incorrectly encoded the boolean as %v", s) - } -} - -func TestWithFloat64_SetsTheBody(t *testing.T) { - r, err := Prepare(&http.Request{}, - WithFloat64(42.0)) - if err != nil { - t.Fatalf("autorest: WithFloat64 failed with error (%v)", err) - } - - s, err := ioutil.ReadAll(r.Body) - if err != nil { - t.Fatalf("autorest: WithFloat64 failed with error (%v)", err) - } - - if r.ContentLength != int64(len(fmt.Sprintf("%v", 42.0))) { - t.Fatalf("autorest: WithFloat64 set Content-Length to %v, expected %v", r.ContentLength, int64(len(fmt.Sprintf("%v", 42.0)))) - } - - v, err := strconv.ParseFloat(string(s), 64) - if err != nil || v != float64(42.0) { - t.Fatalf("autorest: WithFloat64 incorrectly encoded the boolean as %v", s) - } -} - -func TestWithInt32_SetsTheBody(t *testing.T) { - r, err := Prepare(&http.Request{}, - WithInt32(42)) - if err != nil { - t.Fatalf("autorest: WithInt32 failed with error (%v)", err) - } - - s, err := ioutil.ReadAll(r.Body) - if err != nil { - t.Fatalf("autorest: WithInt32 failed with error (%v)", err) - } - - if r.ContentLength != int64(len(fmt.Sprintf("%v", 42))) { - t.Fatalf("autorest: WithInt32 set Content-Length to %v, expected %v", r.ContentLength, int64(len(fmt.Sprintf("%v", 42)))) - } - - v, err := strconv.ParseInt(string(s), 10, 32) - if err != nil || int32(v) != int32(42) { - t.Fatalf("autorest: WithInt32 incorrectly encoded the boolean as %v", s) - } -} - -func TestWithInt64_SetsTheBody(t *testing.T) { - r, err := Prepare(&http.Request{}, - WithInt64(42)) - if err != nil { - t.Fatalf("autorest: WithInt64 failed with error (%v)", err) - } - - s, err := ioutil.ReadAll(r.Body) - if err != nil { - t.Fatalf("autorest: WithInt64 failed with error (%v)", err) - } - - if r.ContentLength != int64(len(fmt.Sprintf("%v", 42))) { - t.Fatalf("autorest: WithInt64 set Content-Length to %v, expected %v", r.ContentLength, int64(len(fmt.Sprintf("%v", 42)))) - } - - v, err := strconv.ParseInt(string(s), 10, 64) - if err != nil || v != int64(42) { - t.Fatalf("autorest: WithInt64 incorrectly encoded the boolean as %v", s) - } -} - -func TestWithString_SetsTheBody(t *testing.T) { - r, err := Prepare(&http.Request{}, - WithString("value")) - if err != nil { - t.Fatalf("autorest: WithString failed with error (%v)", err) - } - - s, err := ioutil.ReadAll(r.Body) - if err != nil { - t.Fatalf("autorest: WithString failed with error (%v)", err) - } - - if r.ContentLength != int64(len("value")) { - t.Fatalf("autorest: WithString set Content-Length to %v, expected %v", r.ContentLength, int64(len("value"))) - } - - if string(s) != "value" { - t.Fatalf("autorest: WithString incorrectly encoded the string as %v", s) - } -} - -func TestWithJSONSetsContentLength(t *testing.T) { - r, err := Prepare(&http.Request{}, - WithJSON(&mocks.T{Name: "Rob Pike", Age: 42})) - if err != nil { - t.Fatalf("autorest: WithJSON failed with error (%v)", err) - } - - b, err := ioutil.ReadAll(r.Body) - if err != nil { - t.Fatalf("autorest: WithJSON failed with error (%v)", err) - } - - if r.ContentLength != int64(len(b)) { - t.Fatalf("autorest:WithJSON set Content-Length to %v, expected %v", r.ContentLength, len(b)) - } -} - -func TestWithHeaderAllocatesHeaders(t *testing.T) { - r, err := Prepare(mocks.NewRequest(), WithHeader("x-foo", "bar")) - if err != nil { - t.Fatalf("autorest: WithHeader failed (%v)", err) - } - if r.Header.Get("x-foo") != "bar" { - t.Fatalf("autorest: WithHeader failed to add header (%s=%s)", "x-foo", r.Header.Get("x-foo")) - } -} - -func TestWithPathCatchesNilURL(t *testing.T) { - _, err := Prepare(&http.Request{}, WithPath("a")) - if err == nil { - t.Fatalf("autorest: WithPath failed to catch a nil URL") - } -} - -func TestWithEscapedPathParametersCatchesNilURL(t *testing.T) { - _, err := Prepare(&http.Request{}, WithEscapedPathParameters("", map[string]interface{}{"foo": "bar"})) - if err == nil { - t.Fatalf("autorest: WithEscapedPathParameters failed to catch a nil URL") - } -} - -func TestWithPathParametersCatchesNilURL(t *testing.T) { - _, err := Prepare(&http.Request{}, WithPathParameters("", map[string]interface{}{"foo": "bar"})) - if err == nil { - t.Fatalf("autorest: WithPathParameters failed to catch a nil URL") - } -} - -func TestWithQueryParametersCatchesNilURL(t *testing.T) { - _, err := Prepare(&http.Request{}, WithQueryParameters(map[string]interface{}{"foo": "bar"})) - if err == nil { - t.Fatalf("autorest: WithQueryParameters failed to catch a nil URL") - } -} - -func TestModifyingExistingRequest(t *testing.T) { - r, err := Prepare(mocks.NewRequestForURL("https://bing.com"), WithPath("search"), WithQueryParameters(map[string]interface{}{"q": "golang"})) - if err != nil { - t.Fatalf("autorest: Preparing an existing request returned an error (%v)", err) - } - if r.URL.String() != "https:/search?q=golang" && r.URL.Host != "bing.com" { - t.Fatalf("autorest: Preparing an existing request failed (%s)", r.URL) - } -} - -func TestWithAuthorizer(t *testing.T) { - r1 := mocks.NewRequest() - - na := &NullAuthorizer{} - r2, err := Prepare(r1, - na.WithAuthorization()) - if err != nil { - t.Fatalf("autorest: NullAuthorizer#WithAuthorization returned an unexpected error (%v)", err) - } else if !reflect.DeepEqual(r1, r2) { - t.Fatalf("autorest: NullAuthorizer#WithAuthorization modified the request -- received %v, expected %v", r2, r1) - } -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/responder_test.go b/vendor/github.com/Azure/go-autorest/autorest/responder_test.go deleted file mode 100644 index ed647d501..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/responder_test.go +++ /dev/null @@ -1,535 +0,0 @@ -package autorest - -import ( - "bytes" - "fmt" - "net/http" - "reflect" - "strings" - "testing" - - "github.com/Azure/go-autorest/autorest/mocks" -) - -func ExampleWithErrorUnlessOK() { - r := mocks.NewResponse() - r.Request = mocks.NewRequest() - - // Respond and leave the response body open (for a subsequent responder to close) - err := Respond(r, - WithErrorUnlessOK(), - ByClosingIfError()) - - if err == nil { - fmt.Printf("%s of %s returned HTTP 200", r.Request.Method, r.Request.URL) - - // Complete handling the response and close the body - Respond(r, - ByClosing()) - } - // Output: GET of https://microsoft.com/a/b/c/ returned HTTP 200 -} - -func ExampleByUnmarshallingJSON() { - c := ` - { - "name" : "Rob Pike", - "age" : 42 - } - ` - - type V struct { - Name string `json:"name"` - Age int `json:"age"` - } - - v := &V{} - - Respond(mocks.NewResponseWithContent(c), - ByUnmarshallingJSON(v), - ByClosing()) - - fmt.Printf("%s is %d years old\n", v.Name, v.Age) - // Output: Rob Pike is 42 years old -} - -func ExampleByUnmarshallingXML() { - c := ` - - Rob Pike - 42 - ` - - type V struct { - Name string `xml:"Name"` - Age int `xml:"Age"` - } - - v := &V{} - - Respond(mocks.NewResponseWithContent(c), - ByUnmarshallingXML(v), - ByClosing()) - - fmt.Printf("%s is %d years old\n", v.Name, v.Age) - // Output: Rob Pike is 42 years old -} - -func TestCreateResponderDoesNotModify(t *testing.T) { - r1 := mocks.NewResponse() - r2 := mocks.NewResponse() - p := CreateResponder() - err := p.Respond(r1) - if err != nil { - t.Fatalf("autorest: CreateResponder failed (%v)", err) - } - if !reflect.DeepEqual(r1, r2) { - t.Fatalf("autorest: CreateResponder without decorators modified the response") - } -} - -func TestCreateResponderRunsDecoratorsInOrder(t *testing.T) { - s := "" - - d := func(n int) RespondDecorator { - return func(r Responder) Responder { - return ResponderFunc(func(resp *http.Response) error { - err := r.Respond(resp) - if err == nil { - s += fmt.Sprintf("%d", n) - } - return err - }) - } - } - - p := CreateResponder(d(1), d(2), d(3)) - err := p.Respond(&http.Response{}) - if err != nil { - t.Fatalf("autorest: Respond failed (%v)", err) - } - - if s != "123" { - t.Fatalf("autorest: CreateResponder invoked decorators in an incorrect order; expected '123', received '%s'", s) - } -} - -func TestByIgnoring(t *testing.T) { - r := mocks.NewResponse() - - Respond(r, - (func() RespondDecorator { - return func(r Responder) Responder { - return ResponderFunc(func(r2 *http.Response) error { - r1 := mocks.NewResponse() - if !reflect.DeepEqual(r1, r2) { - t.Fatalf("autorest: ByIgnoring modified the HTTP Response -- received %v, expected %v", r2, r1) - } - return nil - }) - } - })(), - ByIgnoring(), - ByClosing()) -} - -func TestByCopying_Copies(t *testing.T) { - r := mocks.NewResponseWithContent(jsonT) - b := &bytes.Buffer{} - - err := Respond(r, - ByCopying(b), - ByUnmarshallingJSON(&mocks.T{}), - ByClosing()) - if err != nil { - t.Fatalf("autorest: ByCopying returned an unexpected error -- %v", err) - } - if b.String() != jsonT { - t.Fatalf("autorest: ByCopying failed to copy the bytes read") - } -} - -func TestByCopying_ReturnsNestedErrors(t *testing.T) { - r := mocks.NewResponseWithContent(jsonT) - - r.Body.Close() - err := Respond(r, - ByCopying(&bytes.Buffer{}), - ByUnmarshallingJSON(&mocks.T{}), - ByClosing()) - if err == nil { - t.Fatalf("autorest: ByCopying failed to return the expected error") - } -} - -func TestByCopying_AcceptsNilReponse(t *testing.T) { - r := mocks.NewResponse() - - Respond(r, - (func() RespondDecorator { - return func(r Responder) Responder { - return ResponderFunc(func(resp *http.Response) error { - resp.Body.Close() - r.Respond(nil) - return nil - }) - } - })(), - ByCopying(&bytes.Buffer{})) -} - -func TestByCopying_AcceptsNilBody(t *testing.T) { - r := mocks.NewResponse() - - Respond(r, - (func() RespondDecorator { - return func(r Responder) Responder { - return ResponderFunc(func(resp *http.Response) error { - resp.Body.Close() - resp.Body = nil - r.Respond(resp) - return nil - }) - } - })(), - ByCopying(&bytes.Buffer{})) -} - -func TestByClosing(t *testing.T) { - r := mocks.NewResponse() - err := Respond(r, ByClosing()) - if err != nil { - t.Fatalf("autorest: ByClosing failed (%v)", err) - } - if r.Body.(*mocks.Body).IsOpen() { - t.Fatalf("autorest: ByClosing did not close the response body") - } -} - -func TestByClosingAcceptsNilResponse(t *testing.T) { - r := mocks.NewResponse() - - Respond(r, - (func() RespondDecorator { - return func(r Responder) Responder { - return ResponderFunc(func(resp *http.Response) error { - resp.Body.Close() - r.Respond(nil) - return nil - }) - } - })(), - ByClosing()) -} - -func TestByClosingAcceptsNilBody(t *testing.T) { - r := mocks.NewResponse() - - Respond(r, - (func() RespondDecorator { - return func(r Responder) Responder { - return ResponderFunc(func(resp *http.Response) error { - resp.Body.Close() - resp.Body = nil - r.Respond(resp) - return nil - }) - } - })(), - ByClosing()) -} - -func TestByClosingClosesEvenAfterErrors(t *testing.T) { - var e error - - r := mocks.NewResponse() - Respond(r, - withErrorRespondDecorator(&e), - ByClosing()) - - if r.Body.(*mocks.Body).IsOpen() { - t.Fatalf("autorest: ByClosing did not close the response body after an error occurred") - } -} - -func TestByClosingClosesReturnsNestedErrors(t *testing.T) { - var e error - - r := mocks.NewResponse() - err := Respond(r, - withErrorRespondDecorator(&e), - ByClosing()) - - if err == nil || !reflect.DeepEqual(e, err) { - t.Fatalf("autorest: ByClosing failed to return a nested error") - } -} - -func TestByClosingIfErrorAcceptsNilResponse(t *testing.T) { - var e error - - r := mocks.NewResponse() - - Respond(r, - withErrorRespondDecorator(&e), - (func() RespondDecorator { - return func(r Responder) Responder { - return ResponderFunc(func(resp *http.Response) error { - resp.Body.Close() - r.Respond(nil) - return nil - }) - } - })(), - ByClosingIfError()) -} - -func TestByClosingIfErrorAcceptsNilBody(t *testing.T) { - var e error - - r := mocks.NewResponse() - - Respond(r, - withErrorRespondDecorator(&e), - (func() RespondDecorator { - return func(r Responder) Responder { - return ResponderFunc(func(resp *http.Response) error { - resp.Body.Close() - resp.Body = nil - r.Respond(resp) - return nil - }) - } - })(), - ByClosingIfError()) -} - -func TestByClosingIfErrorClosesIfAnErrorOccurs(t *testing.T) { - var e error - - r := mocks.NewResponse() - Respond(r, - withErrorRespondDecorator(&e), - ByClosingIfError()) - - if r.Body.(*mocks.Body).IsOpen() { - t.Fatalf("autorest: ByClosingIfError did not close the response body after an error occurred") - } -} - -func TestByClosingIfErrorDoesNotClosesIfNoErrorOccurs(t *testing.T) { - r := mocks.NewResponse() - Respond(r, - ByClosingIfError()) - - if !r.Body.(*mocks.Body).IsOpen() { - t.Fatalf("autorest: ByClosingIfError closed the response body even though no error occurred") - } -} - -func TestByUnmarshallingJSON(t *testing.T) { - v := &mocks.T{} - r := mocks.NewResponseWithContent(jsonT) - err := Respond(r, - ByUnmarshallingJSON(v), - ByClosing()) - if err != nil { - t.Fatalf("autorest: ByUnmarshallingJSON failed (%v)", err) - } - if v.Name != "Rob Pike" || v.Age != 42 { - t.Fatalf("autorest: ByUnmarshallingJSON failed to properly unmarshal") - } -} - -func TestByUnmarshallingJSON_HandlesReadErrors(t *testing.T) { - v := &mocks.T{} - r := mocks.NewResponseWithContent(jsonT) - r.Body.(*mocks.Body).Close() - - err := Respond(r, - ByUnmarshallingJSON(v), - ByClosing()) - if err == nil { - t.Fatalf("autorest: ByUnmarshallingJSON failed to receive / respond to read error") - } -} - -func TestByUnmarshallingJSONIncludesJSONInErrors(t *testing.T) { - v := &mocks.T{} - j := jsonT[0 : len(jsonT)-2] - r := mocks.NewResponseWithContent(j) - err := Respond(r, - ByUnmarshallingJSON(v), - ByClosing()) - if err == nil || !strings.Contains(err.Error(), j) { - t.Fatalf("autorest: ByUnmarshallingJSON failed to return JSON in error (%v)", err) - } -} - -func TestByUnmarshallingJSONEmptyInput(t *testing.T) { - v := &mocks.T{} - r := mocks.NewResponseWithContent(``) - err := Respond(r, - ByUnmarshallingJSON(v), - ByClosing()) - if err != nil { - t.Fatalf("autorest: ByUnmarshallingJSON failed to return nil in case of empty JSON (%v)", err) - } -} - -func TestByUnmarshallingXML(t *testing.T) { - v := &mocks.T{} - r := mocks.NewResponseWithContent(xmlT) - err := Respond(r, - ByUnmarshallingXML(v), - ByClosing()) - if err != nil { - t.Fatalf("autorest: ByUnmarshallingXML failed (%v)", err) - } - if v.Name != "Rob Pike" || v.Age != 42 { - t.Fatalf("autorest: ByUnmarshallingXML failed to properly unmarshal") - } -} - -func TestByUnmarshallingXML_HandlesReadErrors(t *testing.T) { - v := &mocks.T{} - r := mocks.NewResponseWithContent(xmlT) - r.Body.(*mocks.Body).Close() - - err := Respond(r, - ByUnmarshallingXML(v), - ByClosing()) - if err == nil { - t.Fatalf("autorest: ByUnmarshallingXML failed to receive / respond to read error") - } -} - -func TestByUnmarshallingXMLIncludesXMLInErrors(t *testing.T) { - v := &mocks.T{} - x := xmlT[0 : len(xmlT)-2] - r := mocks.NewResponseWithContent(x) - err := Respond(r, - ByUnmarshallingXML(v), - ByClosing()) - if err == nil || !strings.Contains(err.Error(), x) { - t.Fatalf("autorest: ByUnmarshallingXML failed to return XML in error (%v)", err) - } -} - -func TestRespondAcceptsNullResponse(t *testing.T) { - err := Respond(nil) - if err != nil { - t.Fatalf("autorest: Respond returned an unexpected error when given a null Response (%v)", err) - } -} - -func TestWithErrorUnlessStatusCode(t *testing.T) { - r := mocks.NewResponse() - r.Request = mocks.NewRequest() - r.Status = "400 BadRequest" - r.StatusCode = http.StatusBadRequest - - err := Respond(r, - WithErrorUnlessStatusCode(http.StatusBadRequest, http.StatusUnauthorized, http.StatusInternalServerError), - ByClosingIfError()) - - if err != nil { - t.Fatalf("autorest: WithErrorUnlessStatusCode returned an error (%v) for an acceptable status code (%s)", err, r.Status) - } -} - -func TestWithErrorUnlessStatusCodeEmitsErrorForUnacceptableStatusCode(t *testing.T) { - r := mocks.NewResponse() - r.Request = mocks.NewRequest() - r.Status = "400 BadRequest" - r.StatusCode = http.StatusBadRequest - - err := Respond(r, - WithErrorUnlessStatusCode(http.StatusOK, http.StatusUnauthorized, http.StatusInternalServerError), - ByClosingIfError()) - - if err == nil { - t.Fatalf("autorest: WithErrorUnlessStatusCode failed to return an error for an unacceptable status code (%s)", r.Status) - } -} - -func TestWithErrorUnlessOK(t *testing.T) { - r := mocks.NewResponse() - r.Request = mocks.NewRequest() - - err := Respond(r, - WithErrorUnlessOK(), - ByClosingIfError()) - - if err != nil { - t.Fatalf("autorest: WithErrorUnlessOK returned an error for OK status code (%v)", err) - } -} - -func TestWithErrorUnlessOKEmitsErrorIfNotOK(t *testing.T) { - r := mocks.NewResponse() - r.Request = mocks.NewRequest() - r.Status = "400 BadRequest" - r.StatusCode = http.StatusBadRequest - - err := Respond(r, - WithErrorUnlessOK(), - ByClosingIfError()) - - if err == nil { - t.Fatalf("autorest: WithErrorUnlessOK failed to return an error for a non-OK status code (%v)", err) - } -} - -func TestExtractHeader(t *testing.T) { - r := mocks.NewResponse() - v := []string{"v1", "v2", "v3"} - mocks.SetResponseHeaderValues(r, mocks.TestHeader, v) - - if !reflect.DeepEqual(ExtractHeader(mocks.TestHeader, r), v) { - t.Fatalf("autorest: ExtractHeader failed to retrieve the expected header -- expected [%s]%v, received [%s]%v", - mocks.TestHeader, v, mocks.TestHeader, ExtractHeader(mocks.TestHeader, r)) - } -} - -func TestExtractHeaderHandlesMissingHeader(t *testing.T) { - var v []string - r := mocks.NewResponse() - - if !reflect.DeepEqual(ExtractHeader(mocks.TestHeader, r), v) { - t.Fatalf("autorest: ExtractHeader failed to handle a missing header -- expected %v, received %v", - v, ExtractHeader(mocks.TestHeader, r)) - } -} - -func TestExtractHeaderValue(t *testing.T) { - r := mocks.NewResponse() - v := "v1" - mocks.SetResponseHeader(r, mocks.TestHeader, v) - - if ExtractHeaderValue(mocks.TestHeader, r) != v { - t.Fatalf("autorest: ExtractHeader failed to retrieve the expected header -- expected [%s]%v, received [%s]%v", - mocks.TestHeader, v, mocks.TestHeader, ExtractHeaderValue(mocks.TestHeader, r)) - } -} - -func TestExtractHeaderValueHandlesMissingHeader(t *testing.T) { - r := mocks.NewResponse() - v := "" - - if ExtractHeaderValue(mocks.TestHeader, r) != v { - t.Fatalf("autorest: ExtractHeader failed to retrieve the expected header -- expected [%s]%v, received [%s]%v", - mocks.TestHeader, v, mocks.TestHeader, ExtractHeaderValue(mocks.TestHeader, r)) - } -} - -func TestExtractHeaderValueRetrievesFirstValue(t *testing.T) { - r := mocks.NewResponse() - v := []string{"v1", "v2", "v3"} - mocks.SetResponseHeaderValues(r, mocks.TestHeader, v) - - if ExtractHeaderValue(mocks.TestHeader, r) != v[0] { - t.Fatalf("autorest: ExtractHeader failed to retrieve the expected header -- expected [%s]%v, received [%s]%v", - mocks.TestHeader, v[0], mocks.TestHeader, ExtractHeaderValue(mocks.TestHeader, r)) - } -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/sender_test.go b/vendor/github.com/Azure/go-autorest/autorest/sender_test.go deleted file mode 100644 index 496333a06..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/sender_test.go +++ /dev/null @@ -1,732 +0,0 @@ -package autorest - -import ( - "bytes" - "fmt" - "log" - "net/http" - "os" - "reflect" - "sync" - "testing" - "time" - - "github.com/Azure/go-autorest/autorest/mocks" -) - -func ExampleSendWithSender() { - r := mocks.NewResponseWithStatus("202 Accepted", http.StatusAccepted) - mocks.SetAcceptedHeaders(r) - - client := mocks.NewSender() - client.AppendAndRepeatResponse(r, 10) - - logger := log.New(os.Stdout, "autorest: ", 0) - na := NullAuthorizer{} - - req, _ := Prepare(&http.Request{}, - AsGet(), - WithBaseURL("https://microsoft.com/a/b/c/"), - na.WithAuthorization()) - - r, _ = SendWithSender(client, req, - WithLogging(logger), - DoErrorIfStatusCode(http.StatusAccepted), - DoCloseIfError(), - DoRetryForAttempts(5, time.Duration(0))) - - Respond(r, - ByClosing()) - - // Output: - // autorest: Sending GET https://microsoft.com/a/b/c/ - // autorest: GET https://microsoft.com/a/b/c/ received 202 Accepted - // autorest: Sending GET https://microsoft.com/a/b/c/ - // autorest: GET https://microsoft.com/a/b/c/ received 202 Accepted - // autorest: Sending GET https://microsoft.com/a/b/c/ - // autorest: GET https://microsoft.com/a/b/c/ received 202 Accepted - // autorest: Sending GET https://microsoft.com/a/b/c/ - // autorest: GET https://microsoft.com/a/b/c/ received 202 Accepted - // autorest: Sending GET https://microsoft.com/a/b/c/ - // autorest: GET https://microsoft.com/a/b/c/ received 202 Accepted -} - -func ExampleDoRetryForAttempts() { - client := mocks.NewSender() - client.SetAndRepeatError(fmt.Errorf("Faux Error"), 10) - - // Retry with backoff -- ensure returned Bodies are closed - r, _ := SendWithSender(client, mocks.NewRequest(), - DoCloseIfError(), - DoRetryForAttempts(5, time.Duration(0))) - - Respond(r, - ByClosing()) - - fmt.Printf("Retry stopped after %d attempts", client.Attempts()) - // Output: Retry stopped after 5 attempts -} - -func ExampleDoErrorIfStatusCode() { - client := mocks.NewSender() - client.AppendAndRepeatResponse(mocks.NewResponseWithStatus("204 NoContent", http.StatusNoContent), 10) - - // Chain decorators to retry the request, up to five times, if the status code is 204 - r, _ := SendWithSender(client, mocks.NewRequest(), - DoErrorIfStatusCode(http.StatusNoContent), - DoCloseIfError(), - DoRetryForAttempts(5, time.Duration(0))) - - Respond(r, - ByClosing()) - - fmt.Printf("Retry stopped after %d attempts with code %s", client.Attempts(), r.Status) - // Output: Retry stopped after 5 attempts with code 204 NoContent -} - -func TestSendWithSenderRunsDecoratorsInOrder(t *testing.T) { - client := mocks.NewSender() - s := "" - - r, err := SendWithSender(client, mocks.NewRequest(), - withMessage(&s, "a"), - withMessage(&s, "b"), - withMessage(&s, "c")) - if err != nil { - t.Fatalf("autorest: SendWithSender returned an error (%v)", err) - } - - Respond(r, - ByClosing()) - - if s != "abc" { - t.Fatalf("autorest: SendWithSender invoke decorators out of order; expected 'abc', received '%s'", s) - } -} - -func TestCreateSender(t *testing.T) { - f := false - - s := CreateSender( - (func() SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (*http.Response, error) { - f = true - return nil, nil - }) - } - })()) - s.Do(&http.Request{}) - - if !f { - t.Fatal("autorest: CreateSender failed to apply supplied decorator") - } -} - -func TestSend(t *testing.T) { - f := false - - Send(&http.Request{}, - (func() SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (*http.Response, error) { - f = true - return nil, nil - }) - } - })()) - - if !f { - t.Fatal("autorest: Send failed to apply supplied decorator") - } -} - -func TestAfterDelayWaits(t *testing.T) { - client := mocks.NewSender() - - d := 2 * time.Second - - tt := time.Now() - r, _ := SendWithSender(client, mocks.NewRequest(), - AfterDelay(d)) - s := time.Since(tt) - if s < d { - t.Fatal("autorest: AfterDelay failed to wait for at least the specified duration") - } - - Respond(r, - ByClosing()) -} - -func TestAfterDelay_Cancels(t *testing.T) { - client := mocks.NewSender() - cancel := make(chan struct{}) - delay := 5 * time.Second - - var wg sync.WaitGroup - wg.Add(1) - tt := time.Now() - go func() { - req := mocks.NewRequest() - req.Cancel = cancel - wg.Done() - SendWithSender(client, req, - AfterDelay(delay)) - }() - wg.Wait() - close(cancel) - time.Sleep(5 * time.Millisecond) - if time.Since(tt) >= delay { - t.Fatal("autorest: AfterDelay failed to cancel") - } -} - -func TestAfterDelayDoesNotWaitTooLong(t *testing.T) { - client := mocks.NewSender() - - d := 5 * time.Millisecond - start := time.Now() - r, _ := SendWithSender(client, mocks.NewRequest(), - AfterDelay(d)) - - if time.Since(start) > (5 * d) { - t.Fatal("autorest: AfterDelay waited too long (exceeded 5 times specified duration)") - } - - Respond(r, - ByClosing()) -} - -func TestAsIs(t *testing.T) { - client := mocks.NewSender() - - r1 := mocks.NewResponse() - client.AppendResponse(r1) - - r2, err := SendWithSender(client, mocks.NewRequest(), - AsIs()) - if err != nil { - t.Fatalf("autorest: AsIs returned an unexpected error (%v)", err) - } else if !reflect.DeepEqual(r1, r2) { - t.Fatalf("autorest: AsIs modified the response -- received %v, expected %v", r2, r1) - } - - Respond(r1, - ByClosing()) - Respond(r2, - ByClosing()) -} - -func TestDoCloseIfError(t *testing.T) { - client := mocks.NewSender() - client.AppendResponse(mocks.NewResponseWithStatus("400 BadRequest", http.StatusBadRequest)) - - r, _ := SendWithSender(client, mocks.NewRequest(), - DoErrorIfStatusCode(http.StatusBadRequest), - DoCloseIfError()) - - if r.Body.(*mocks.Body).IsOpen() { - t.Fatal("autorest: Expected DoCloseIfError to close response body -- it was left open") - } - - Respond(r, - ByClosing()) -} - -func TestDoCloseIfErrorAcceptsNilResponse(t *testing.T) { - client := mocks.NewSender() - - SendWithSender(client, mocks.NewRequest(), - (func() SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (*http.Response, error) { - resp, err := s.Do(r) - if err != nil { - resp.Body.Close() - } - return nil, fmt.Errorf("Faux Error") - }) - } - })(), - DoCloseIfError()) -} - -func TestDoCloseIfErrorAcceptsNilBody(t *testing.T) { - client := mocks.NewSender() - - SendWithSender(client, mocks.NewRequest(), - (func() SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (*http.Response, error) { - resp, err := s.Do(r) - if err != nil { - resp.Body.Close() - } - resp.Body = nil - return resp, fmt.Errorf("Faux Error") - }) - } - })(), - DoCloseIfError()) -} - -func TestDoErrorIfStatusCode(t *testing.T) { - client := mocks.NewSender() - client.AppendResponse(mocks.NewResponseWithStatus("400 BadRequest", http.StatusBadRequest)) - - r, err := SendWithSender(client, mocks.NewRequest(), - DoErrorIfStatusCode(http.StatusBadRequest), - DoCloseIfError()) - if err == nil { - t.Fatal("autorest: DoErrorIfStatusCode failed to emit an error for passed code") - } - - Respond(r, - ByClosing()) -} - -func TestDoErrorIfStatusCodeIgnoresStatusCodes(t *testing.T) { - client := mocks.NewSender() - client.AppendResponse(newAcceptedResponse()) - - r, err := SendWithSender(client, mocks.NewRequest(), - DoErrorIfStatusCode(http.StatusBadRequest), - DoCloseIfError()) - if err != nil { - t.Fatal("autorest: DoErrorIfStatusCode failed to ignore a status code") - } - - Respond(r, - ByClosing()) -} - -func TestDoErrorUnlessStatusCode(t *testing.T) { - client := mocks.NewSender() - client.AppendResponse(mocks.NewResponseWithStatus("400 BadRequest", http.StatusBadRequest)) - - r, err := SendWithSender(client, mocks.NewRequest(), - DoErrorUnlessStatusCode(http.StatusAccepted), - DoCloseIfError()) - if err == nil { - t.Fatal("autorest: DoErrorUnlessStatusCode failed to emit an error for an unknown status code") - } - - Respond(r, - ByClosing()) -} - -func TestDoErrorUnlessStatusCodeIgnoresStatusCodes(t *testing.T) { - client := mocks.NewSender() - client.AppendResponse(newAcceptedResponse()) - - r, err := SendWithSender(client, mocks.NewRequest(), - DoErrorUnlessStatusCode(http.StatusAccepted), - DoCloseIfError()) - if err != nil { - t.Fatal("autorest: DoErrorUnlessStatusCode emitted an error for a knonwn status code") - } - - Respond(r, - ByClosing()) -} - -func TestDoRetryForAttemptsStopsAfterSuccess(t *testing.T) { - client := mocks.NewSender() - - r, err := SendWithSender(client, mocks.NewRequest(), - DoRetryForAttempts(5, time.Duration(0))) - if client.Attempts() != 1 { - t.Fatalf("autorest: DoRetryForAttempts failed to stop after success -- expected attempts %v, actual %v", - 1, client.Attempts()) - } - if err != nil { - t.Fatalf("autorest: DoRetryForAttempts returned an unexpected error (%v)", err) - } - - Respond(r, - ByClosing()) -} - -func TestDoRetryForAttemptsStopsAfterAttempts(t *testing.T) { - client := mocks.NewSender() - client.SetAndRepeatError(fmt.Errorf("Faux Error"), 10) - - r, err := SendWithSender(client, mocks.NewRequest(), - DoRetryForAttempts(5, time.Duration(0)), - DoCloseIfError()) - if err == nil { - t.Fatal("autorest: Mock client failed to emit errors") - } - - Respond(r, - ByClosing()) - - if client.Attempts() != 5 { - t.Fatal("autorest: DoRetryForAttempts failed to stop after specified number of attempts") - } -} - -func TestDoRetryForAttemptsReturnsResponse(t *testing.T) { - client := mocks.NewSender() - client.SetError(fmt.Errorf("Faux Error")) - - r, err := SendWithSender(client, mocks.NewRequest(), - DoRetryForAttempts(1, time.Duration(0))) - if err == nil { - t.Fatal("autorest: Mock client failed to emit errors") - } - - if r == nil { - t.Fatal("autorest: DoRetryForAttempts failed to return the underlying response") - } - - Respond(r, - ByClosing()) -} - -func TestDoRetryForDurationStopsAfterSuccess(t *testing.T) { - client := mocks.NewSender() - - r, err := SendWithSender(client, mocks.NewRequest(), - DoRetryForDuration(10*time.Millisecond, time.Duration(0))) - if client.Attempts() != 1 { - t.Fatalf("autorest: DoRetryForDuration failed to stop after success -- expected attempts %v, actual %v", - 1, client.Attempts()) - } - if err != nil { - t.Fatalf("autorest: DoRetryForDuration returned an unexpected error (%v)", err) - } - - Respond(r, - ByClosing()) -} - -func TestDoRetryForDurationStopsAfterDuration(t *testing.T) { - client := mocks.NewSender() - client.SetAndRepeatError(fmt.Errorf("Faux Error"), -1) - - d := 5 * time.Millisecond - start := time.Now() - r, err := SendWithSender(client, mocks.NewRequest(), - DoRetryForDuration(d, time.Duration(0)), - DoCloseIfError()) - if err == nil { - t.Fatal("autorest: Mock client failed to emit errors") - } - - if time.Since(start) < d { - t.Fatal("autorest: DoRetryForDuration failed stopped too soon") - } - - Respond(r, - ByClosing()) -} - -func TestDoRetryForDurationStopsWithinReason(t *testing.T) { - client := mocks.NewSender() - client.SetAndRepeatError(fmt.Errorf("Faux Error"), -1) - - d := 5 * time.Second - start := time.Now() - r, err := SendWithSender(client, mocks.NewRequest(), - DoRetryForDuration(d, time.Duration(0)), - DoCloseIfError()) - if err == nil { - t.Fatal("autorest: Mock client failed to emit errors") - } - - if time.Since(start) > (5 * d) { - t.Fatal("autorest: DoRetryForDuration failed stopped soon enough (exceeded 5 times specified duration)") - } - - Respond(r, - ByClosing()) -} - -func TestDoRetryForDurationReturnsResponse(t *testing.T) { - client := mocks.NewSender() - client.SetAndRepeatError(fmt.Errorf("Faux Error"), -1) - - r, err := SendWithSender(client, mocks.NewRequest(), - DoRetryForDuration(10*time.Millisecond, time.Duration(0)), - DoCloseIfError()) - if err == nil { - t.Fatal("autorest: Mock client failed to emit errors") - } - - if r == nil { - t.Fatal("autorest: DoRetryForDuration failed to return the underlying response") - } - - Respond(r, - ByClosing()) -} - -func TestDelayForBackoff(t *testing.T) { - d := 2 * time.Second - start := time.Now() - DelayForBackoff(d, 1, nil) - if time.Since(start) < d { - t.Fatal("autorest: DelayForBackoff did not delay as long as expected") - } -} - -func TestDelayForBackoff_Cancels(t *testing.T) { - cancel := make(chan struct{}) - delay := 5 * time.Second - - var wg sync.WaitGroup - wg.Add(1) - start := time.Now() - go func() { - wg.Done() - DelayForBackoff(delay, 1, cancel) - }() - wg.Wait() - close(cancel) - time.Sleep(5 * time.Millisecond) - if time.Since(start) >= delay { - t.Fatal("autorest: DelayForBackoff failed to cancel") - } -} - -func TestDelayForBackoffWithinReason(t *testing.T) { - d := 5 * time.Second - start := time.Now() - DelayForBackoff(d, 1, nil) - if time.Since(start) > (5 * d) { - t.Fatal("autorest: DelayForBackoff delayed too long (exceeded 5 times the specified duration)") - } -} - -func TestDoPollForStatusCodes_IgnoresUnspecifiedStatusCodes(t *testing.T) { - client := mocks.NewSender() - - r, _ := SendWithSender(client, mocks.NewRequest(), - DoPollForStatusCodes(time.Duration(0), time.Duration(0))) - - if client.Attempts() != 1 { - t.Fatalf("autorest: Sender#DoPollForStatusCodes polled for unspecified status code") - } - - Respond(r, - ByClosing()) -} - -func TestDoPollForStatusCodes_PollsForSpecifiedStatusCodes(t *testing.T) { - client := mocks.NewSender() - client.AppendResponse(newAcceptedResponse()) - - r, _ := SendWithSender(client, mocks.NewRequest(), - DoPollForStatusCodes(time.Millisecond, time.Millisecond, http.StatusAccepted)) - - if client.Attempts() != 2 { - t.Fatalf("autorest: Sender#DoPollForStatusCodes failed to poll for specified status code") - } - - Respond(r, - ByClosing()) -} - -func TestDoPollForStatusCodes_CanBeCanceled(t *testing.T) { - cancel := make(chan struct{}) - delay := 5 * time.Second - - r := mocks.NewResponse() - mocks.SetAcceptedHeaders(r) - client := mocks.NewSender() - client.AppendAndRepeatResponse(r, 100) - - var wg sync.WaitGroup - wg.Add(1) - start := time.Now() - go func() { - wg.Done() - r, _ := SendWithSender(client, mocks.NewRequest(), - DoPollForStatusCodes(time.Millisecond, time.Millisecond, http.StatusAccepted)) - Respond(r, - ByClosing()) - }() - wg.Wait() - close(cancel) - time.Sleep(5 * time.Millisecond) - if time.Since(start) >= delay { - t.Fatalf("autorest: Sender#DoPollForStatusCodes failed to cancel") - } -} - -func TestDoPollForStatusCodes_ClosesAllNonreturnedResponseBodiesWhenPolling(t *testing.T) { - resp := newAcceptedResponse() - - client := mocks.NewSender() - client.AppendAndRepeatResponse(resp, 2) - - r, _ := SendWithSender(client, mocks.NewRequest(), - DoPollForStatusCodes(time.Millisecond, time.Millisecond, http.StatusAccepted)) - - if resp.Body.(*mocks.Body).IsOpen() || resp.Body.(*mocks.Body).CloseAttempts() < 2 { - t.Fatalf("autorest: Sender#DoPollForStatusCodes did not close unreturned response bodies") - } - - Respond(r, - ByClosing()) -} - -func TestDoPollForStatusCodes_LeavesLastResponseBodyOpen(t *testing.T) { - client := mocks.NewSender() - client.AppendResponse(newAcceptedResponse()) - - r, _ := SendWithSender(client, mocks.NewRequest(), - DoPollForStatusCodes(time.Millisecond, time.Millisecond, http.StatusAccepted)) - - if !r.Body.(*mocks.Body).IsOpen() { - t.Fatalf("autorest: Sender#DoPollForStatusCodes did not leave open the body of the last response") - } - - Respond(r, - ByClosing()) -} - -func TestDoPollForStatusCodes_StopsPollingAfterAnError(t *testing.T) { - client := mocks.NewSender() - client.AppendAndRepeatResponse(newAcceptedResponse(), 5) - client.SetError(fmt.Errorf("Faux Error")) - client.SetEmitErrorAfter(1) - - r, _ := SendWithSender(client, mocks.NewRequest(), - DoPollForStatusCodes(time.Millisecond, time.Millisecond, http.StatusAccepted)) - - if client.Attempts() > 2 { - t.Fatalf("autorest: Sender#DoPollForStatusCodes failed to stop polling after receiving an error") - } - - Respond(r, - ByClosing()) -} - -func TestDoPollForStatusCodes_ReturnsPollingError(t *testing.T) { - client := mocks.NewSender() - client.AppendAndRepeatResponse(newAcceptedResponse(), 5) - client.SetError(fmt.Errorf("Faux Error")) - client.SetEmitErrorAfter(1) - - r, err := SendWithSender(client, mocks.NewRequest(), - DoPollForStatusCodes(time.Millisecond, time.Millisecond, http.StatusAccepted)) - - if err == nil { - t.Fatalf("autorest: Sender#DoPollForStatusCodes failed to return error from polling") - } - - Respond(r, - ByClosing()) -} - -func TestWithLogging_Logs(t *testing.T) { - buf := &bytes.Buffer{} - logger := log.New(buf, "autorest: ", 0) - client := mocks.NewSender() - - r, _ := SendWithSender(client, &http.Request{}, - WithLogging(logger)) - - if buf.String() == "" { - t.Fatal("autorest: Sender#WithLogging failed to log the request") - } - - Respond(r, - ByClosing()) -} - -func TestWithLogging_HandlesMissingResponse(t *testing.T) { - buf := &bytes.Buffer{} - logger := log.New(buf, "autorest: ", 0) - client := mocks.NewSender() - client.AppendResponse(nil) - client.SetError(fmt.Errorf("Faux Error")) - - r, err := SendWithSender(client, &http.Request{}, - WithLogging(logger)) - - if r != nil || err == nil { - t.Fatal("autorest: Sender#WithLogging returned a valid response -- expecting nil") - } - if buf.String() == "" { - t.Fatal("autorest: Sender#WithLogging failed to log the request for a nil response") - } - - Respond(r, - ByClosing()) -} - -func TestDoRetryForStatusCodesWithSuccess(t *testing.T) { - client := mocks.NewSender() - client.AppendAndRepeatResponse(mocks.NewResponseWithStatus("408 Request Timeout", http.StatusRequestTimeout), 2) - client.AppendResponse(mocks.NewResponseWithStatus("200 OK", http.StatusOK)) - - r, _ := SendWithSender(client, mocks.NewRequest(), - DoRetryForStatusCodes(5, time.Duration(2*time.Second), http.StatusRequestTimeout), - ) - - Respond(r, - ByClosing()) - - if client.Attempts() != 3 { - t.Fatalf("autorest: Sender#DoRetryForStatusCodes -- Got: StatusCode %v in %v attempts; Want: StatusCode 200 OK in 2 attempts -- ", - r.Status, client.Attempts()-1) - } -} - -func TestDoRetryForStatusCodesWithNoSuccess(t *testing.T) { - client := mocks.NewSender() - client.AppendAndRepeatResponse(mocks.NewResponseWithStatus("504 Gateway Timeout", http.StatusGatewayTimeout), 5) - - r, _ := SendWithSender(client, mocks.NewRequest(), - DoRetryForStatusCodes(2, time.Duration(2*time.Second), http.StatusGatewayTimeout), - ) - Respond(r, - ByClosing()) - - if client.Attempts() != 3 { - t.Fatalf("autorest: Sender#DoRetryForStatusCodes -- Got: failed stop after %v retry attempts; Want: Stop after 2 retry attempts", - client.Attempts()-1) - } -} - -func TestDoRetryForStatusCodes_CodeNotInRetryList(t *testing.T) { - client := mocks.NewSender() - client.AppendAndRepeatResponse(mocks.NewResponseWithStatus("204 No Content", http.StatusNoContent), 1) - - r, _ := SendWithSender(client, mocks.NewRequest(), - DoRetryForStatusCodes(6, time.Duration(2*time.Second), http.StatusGatewayTimeout), - ) - - Respond(r, - ByClosing()) - - if client.Attempts() != 1 || r.Status != "204 No Content" { - t.Fatalf("autorest: Sender#DoRetryForStatusCodes -- Got: Retry attempts %v for StatusCode %v; Want: 0 attempts for StatusCode 204", - client.Attempts(), r.Status) - } -} - -func TestDoRetryForStatusCodes_RequestBodyReadError(t *testing.T) { - client := mocks.NewSender() - client.AppendAndRepeatResponse(mocks.NewResponseWithStatus("204 No Content", http.StatusNoContent), 2) - - r, err := SendWithSender(client, mocks.NewRequestWithCloseBody(), - DoRetryForStatusCodes(6, time.Duration(2*time.Second), http.StatusGatewayTimeout), - ) - - Respond(r, - ByClosing()) - - if err == nil || client.Attempts() != 0 { - t.Fatalf("autorest: Sender#DoRetryForStatusCodes -- Got: Not failed for request body read error; Want: Failed for body read error - %v", err) - } -} - -func newAcceptedResponse() *http.Response { - resp := mocks.NewResponseWithStatus("202 Accepted", http.StatusAccepted) - mocks.SetAcceptedHeaders(resp) - return resp -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/to/convert_test.go b/vendor/github.com/Azure/go-autorest/autorest/to/convert_test.go deleted file mode 100644 index 8c9835392..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/to/convert_test.go +++ /dev/null @@ -1,220 +0,0 @@ -package to - -import ( - "reflect" - "testing" -) - -func TestString(t *testing.T) { - v := "" - if String(&v) != v { - t.Fatalf("to: String failed to return the correct string -- expected %v, received %v", - v, String(&v)) - } -} - -func TestStringHandlesNil(t *testing.T) { - if String(nil) != "" { - t.Fatalf("to: String failed to correctly convert nil -- expected %v, received %v", - "", String(nil)) - } -} - -func TestStringPtr(t *testing.T) { - v := "" - if *StringPtr(v) != v { - t.Fatalf("to: StringPtr failed to return the correct string -- expected %v, received %v", - v, *StringPtr(v)) - } -} - -func TestStringSlice(t *testing.T) { - v := []string{} - if out := StringSlice(&v); !reflect.DeepEqual(out, v) { - t.Fatalf("to: StringSlice failed to return the correct slice -- expected %v, received %v", - v, out) - } -} - -func TestStringSliceHandlesNil(t *testing.T) { - if out := StringSlice(nil); out != nil { - t.Fatalf("to: StringSlice failed to correctly convert nil -- expected %v, received %v", - nil, out) - } -} - -func TestStringSlicePtr(t *testing.T) { - v := []string{"a", "b"} - if out := StringSlicePtr(v); !reflect.DeepEqual(*out, v) { - t.Fatalf("to: StringSlicePtr failed to return the correct slice -- expected %v, received %v", - v, *out) - } -} - -func TestStringMap(t *testing.T) { - msp := map[string]*string{"foo": StringPtr("foo"), "bar": StringPtr("bar"), "baz": StringPtr("baz")} - for k, v := range StringMap(msp) { - if *msp[k] != v { - t.Fatalf("to: StringMap incorrectly converted an entry -- expected [%s]%v, received[%s]%v", - k, v, k, *msp[k]) - } - } -} - -func TestStringMapHandlesNil(t *testing.T) { - msp := map[string]*string{"foo": StringPtr("foo"), "bar": nil, "baz": StringPtr("baz")} - for k, v := range StringMap(msp) { - if msp[k] == nil && v != "" { - t.Fatalf("to: StringMap incorrectly converted a nil entry -- expected [%s]%v, received[%s]%v", - k, v, k, *msp[k]) - } - } -} - -func TestStringMapPtr(t *testing.T) { - ms := map[string]string{"foo": "foo", "bar": "bar", "baz": "baz"} - for k, msp := range *StringMapPtr(ms) { - if ms[k] != *msp { - t.Fatalf("to: StringMapPtr incorrectly converted an entry -- expected [%s]%v, received[%s]%v", - k, ms[k], k, *msp) - } - } -} - -func TestBool(t *testing.T) { - v := false - if Bool(&v) != v { - t.Fatalf("to: Bool failed to return the correct string -- expected %v, received %v", - v, Bool(&v)) - } -} - -func TestBoolHandlesNil(t *testing.T) { - if Bool(nil) != false { - t.Fatalf("to: Bool failed to correctly convert nil -- expected %v, received %v", - false, Bool(nil)) - } -} - -func TestBoolPtr(t *testing.T) { - v := false - if *BoolPtr(v) != v { - t.Fatalf("to: BoolPtr failed to return the correct string -- expected %v, received %v", - v, *BoolPtr(v)) - } -} - -func TestInt(t *testing.T) { - v := 0 - if Int(&v) != v { - t.Fatalf("to: Int failed to return the correct string -- expected %v, received %v", - v, Int(&v)) - } -} - -func TestIntHandlesNil(t *testing.T) { - if Int(nil) != 0 { - t.Fatalf("to: Int failed to correctly convert nil -- expected %v, received %v", - 0, Int(nil)) - } -} - -func TestIntPtr(t *testing.T) { - v := 0 - if *IntPtr(v) != v { - t.Fatalf("to: IntPtr failed to return the correct string -- expected %v, received %v", - v, *IntPtr(v)) - } -} - -func TestInt32(t *testing.T) { - v := int32(0) - if Int32(&v) != v { - t.Fatalf("to: Int32 failed to return the correct string -- expected %v, received %v", - v, Int32(&v)) - } -} - -func TestInt32HandlesNil(t *testing.T) { - if Int32(nil) != int32(0) { - t.Fatalf("to: Int32 failed to correctly convert nil -- expected %v, received %v", - 0, Int32(nil)) - } -} - -func TestInt32Ptr(t *testing.T) { - v := int32(0) - if *Int32Ptr(v) != v { - t.Fatalf("to: Int32Ptr failed to return the correct string -- expected %v, received %v", - v, *Int32Ptr(v)) - } -} - -func TestInt64(t *testing.T) { - v := int64(0) - if Int64(&v) != v { - t.Fatalf("to: Int64 failed to return the correct string -- expected %v, received %v", - v, Int64(&v)) - } -} - -func TestInt64HandlesNil(t *testing.T) { - if Int64(nil) != int64(0) { - t.Fatalf("to: Int64 failed to correctly convert nil -- expected %v, received %v", - 0, Int64(nil)) - } -} - -func TestInt64Ptr(t *testing.T) { - v := int64(0) - if *Int64Ptr(v) != v { - t.Fatalf("to: Int64Ptr failed to return the correct string -- expected %v, received %v", - v, *Int64Ptr(v)) - } -} - -func TestFloat32(t *testing.T) { - v := float32(0) - if Float32(&v) != v { - t.Fatalf("to: Float32 failed to return the correct string -- expected %v, received %v", - v, Float32(&v)) - } -} - -func TestFloat32HandlesNil(t *testing.T) { - if Float32(nil) != float32(0) { - t.Fatalf("to: Float32 failed to correctly convert nil -- expected %v, received %v", - 0, Float32(nil)) - } -} - -func TestFloat32Ptr(t *testing.T) { - v := float32(0) - if *Float32Ptr(v) != v { - t.Fatalf("to: Float32Ptr failed to return the correct string -- expected %v, received %v", - v, *Float32Ptr(v)) - } -} - -func TestFloat64(t *testing.T) { - v := float64(0) - if Float64(&v) != v { - t.Fatalf("to: Float64 failed to return the correct string -- expected %v, received %v", - v, Float64(&v)) - } -} - -func TestFloat64HandlesNil(t *testing.T) { - if Float64(nil) != float64(0) { - t.Fatalf("to: Float64 failed to correctly convert nil -- expected %v, received %v", - 0, Float64(nil)) - } -} - -func TestFloat64Ptr(t *testing.T) { - v := float64(0) - if *Float64Ptr(v) != v { - t.Fatalf("to: Float64Ptr failed to return the correct string -- expected %v, received %v", - v, *Float64Ptr(v)) - } -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/utility_test.go b/vendor/github.com/Azure/go-autorest/autorest/utility_test.go deleted file mode 100644 index 99c16c97c..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/utility_test.go +++ /dev/null @@ -1,368 +0,0 @@ -package autorest - -import ( - "bytes" - "encoding/json" - "encoding/xml" - "fmt" - "net/http" - "net/url" - "reflect" - "sort" - "strings" - "testing" - - "github.com/Azure/go-autorest/autorest/mocks" -) - -const ( - jsonT = ` - { - "name":"Rob Pike", - "age":42 - }` - xmlT = ` - - Rob Pike - 42 - ` -) - -func TestNewDecoderCreatesJSONDecoder(t *testing.T) { - d := NewDecoder(EncodedAsJSON, strings.NewReader(jsonT)) - _, ok := d.(*json.Decoder) - if d == nil || !ok { - t.Fatal("autorest: NewDecoder failed to create a JSON decoder when requested") - } -} - -func TestNewDecoderCreatesXMLDecoder(t *testing.T) { - d := NewDecoder(EncodedAsXML, strings.NewReader(xmlT)) - _, ok := d.(*xml.Decoder) - if d == nil || !ok { - t.Fatal("autorest: NewDecoder failed to create an XML decoder when requested") - } -} - -func TestNewDecoderReturnsNilForUnknownEncoding(t *testing.T) { - d := NewDecoder("unknown", strings.NewReader(xmlT)) - if d != nil { - t.Fatal("autorest: NewDecoder created a decoder for an unknown encoding") - } -} - -func TestCopyAndDecodeDecodesJSON(t *testing.T) { - _, err := CopyAndDecode(EncodedAsJSON, strings.NewReader(jsonT), &mocks.T{}) - if err != nil { - t.Fatalf("autorest: CopyAndDecode returned an error with valid JSON - %v", err) - } -} - -func TestCopyAndDecodeDecodesXML(t *testing.T) { - _, err := CopyAndDecode(EncodedAsXML, strings.NewReader(xmlT), &mocks.T{}) - if err != nil { - t.Fatalf("autorest: CopyAndDecode returned an error with valid XML - %v", err) - } -} - -func TestCopyAndDecodeReturnsJSONDecodingErrors(t *testing.T) { - _, err := CopyAndDecode(EncodedAsJSON, strings.NewReader(jsonT[0:len(jsonT)-2]), &mocks.T{}) - if err == nil { - t.Fatalf("autorest: CopyAndDecode failed to return an error with invalid JSON") - } -} - -func TestCopyAndDecodeReturnsXMLDecodingErrors(t *testing.T) { - _, err := CopyAndDecode(EncodedAsXML, strings.NewReader(xmlT[0:len(xmlT)-2]), &mocks.T{}) - if err == nil { - t.Fatalf("autorest: CopyAndDecode failed to return an error with invalid XML") - } -} - -func TestCopyAndDecodeAlwaysReturnsACopy(t *testing.T) { - b, _ := CopyAndDecode(EncodedAsJSON, strings.NewReader(jsonT), &mocks.T{}) - if b.String() != jsonT { - t.Fatalf("autorest: CopyAndDecode failed to return a valid copy of the data - %v", b.String()) - } -} - -func TestTeeReadCloser_Copies(t *testing.T) { - v := &mocks.T{} - r := mocks.NewResponseWithContent(jsonT) - b := &bytes.Buffer{} - - r.Body = TeeReadCloser(r.Body, b) - - err := Respond(r, - ByUnmarshallingJSON(v), - ByClosing()) - if err != nil { - t.Fatalf("autorest: TeeReadCloser returned an unexpected error -- %v", err) - } - if b.String() != jsonT { - t.Fatalf("autorest: TeeReadCloser failed to copy the bytes read") - } -} - -func TestTeeReadCloser_PassesReadErrors(t *testing.T) { - v := &mocks.T{} - r := mocks.NewResponseWithContent(jsonT) - - r.Body.(*mocks.Body).Close() - r.Body = TeeReadCloser(r.Body, &bytes.Buffer{}) - - err := Respond(r, - ByUnmarshallingJSON(v), - ByClosing()) - if err == nil { - t.Fatalf("autorest: TeeReadCloser failed to return the expected error") - } -} - -func TestTeeReadCloser_ClosesWrappedReader(t *testing.T) { - v := &mocks.T{} - r := mocks.NewResponseWithContent(jsonT) - - b := r.Body.(*mocks.Body) - r.Body = TeeReadCloser(r.Body, &bytes.Buffer{}) - err := Respond(r, - ByUnmarshallingJSON(v), - ByClosing()) - if err != nil { - t.Fatalf("autorest: TeeReadCloser returned an unexpected error -- %v", err) - } - if b.IsOpen() { - t.Fatalf("autorest: TeeReadCloser failed to close the nested io.ReadCloser") - } -} - -func TestContainsIntFindsValue(t *testing.T) { - ints := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} - v := 5 - if !containsInt(ints, v) { - t.Fatalf("autorest: containsInt failed to find %v in %v", v, ints) - } -} - -func TestContainsIntDoesNotFindValue(t *testing.T) { - ints := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} - v := 42 - if containsInt(ints, v) { - t.Fatalf("autorest: containsInt unexpectedly found %v in %v", v, ints) - } -} - -func TestContainsIntAcceptsEmptyList(t *testing.T) { - ints := make([]int, 10) - if containsInt(ints, 42) { - t.Fatalf("autorest: containsInt failed to handle an empty list") - } -} - -func TestContainsIntAcceptsNilList(t *testing.T) { - var ints []int - if containsInt(ints, 42) { - t.Fatalf("autorest: containsInt failed to handle an nil list") - } -} - -func TestEscapeStrings(t *testing.T) { - m := map[string]string{ - "string": "a long string with = odd characters", - "int": "42", - "nil": "", - } - r := map[string]string{ - "string": "a+long+string+with+%3D+odd+characters", - "int": "42", - "nil": "", - } - v := escapeValueStrings(m) - if !reflect.DeepEqual(v, r) { - t.Fatalf("autorest: ensureValueStrings returned %v\n", v) - } -} - -func TestEnsureStrings(t *testing.T) { - m := map[string]interface{}{ - "string": "string", - "int": 42, - "nil": nil, - "bytes": []byte{255, 254, 253}, - } - r := map[string]string{ - "string": "string", - "int": "42", - "nil": "", - "bytes": string([]byte{255, 254, 253}), - } - v := ensureValueStrings(m) - if !reflect.DeepEqual(v, r) { - t.Fatalf("autorest: ensureValueStrings returned %v\n", v) - } -} - -func ExampleString() { - m := []string{ - "string1", - "string2", - "string3", - } - - fmt.Println(String(m, ",")) - // Output: string1,string2,string3 -} - -func TestStringWithValidString(t *testing.T) { - i := 123 - if String(i) != "123" { - t.Fatal("autorest: String method failed to convert integer 123 to string") - } -} - -func TestEncodeWithValidPath(t *testing.T) { - s := Encode("Path", "Hello Gopher") - if s != "Hello%20Gopher" { - t.Fatalf("autorest: Encode method failed for valid path encoding. Got: %v; Want: %v", s, "Hello%20Gopher") - } -} - -func TestEncodeWithValidQuery(t *testing.T) { - s := Encode("Query", "Hello Gopher") - if s != "Hello+Gopher" { - t.Fatalf("autorest: Encode method failed for valid query encoding. Got: '%v'; Want: 'Hello+Gopher'", s) - } -} - -func TestEncodeWithValidNotPathQuery(t *testing.T) { - s := Encode("Host", "Hello Gopher") - if s != "Hello Gopher" { - t.Fatalf("autorest: Encode method failed for parameter not query or path. Got: '%v'; Want: 'Hello Gopher'", s) - } -} - -func TestMapToValues(t *testing.T) { - m := map[string]interface{}{ - "a": "a", - "b": 2, - } - v := url.Values{} - v.Add("a", "a") - v.Add("b", "2") - if !isEqual(v, MapToValues(m)) { - t.Fatalf("autorest: MapToValues method failed to return correct values - expected(%v) got(%v)", v, MapToValues(m)) - } -} - -func TestMapToValuesWithArrayValues(t *testing.T) { - m := map[string]interface{}{ - "a": []string{"a", "b"}, - "b": 2, - "c": []int{3, 4}, - } - v := url.Values{} - v.Add("a", "a") - v.Add("a", "b") - v.Add("b", "2") - v.Add("c", "3") - v.Add("c", "4") - - if !isEqual(v, MapToValues(m)) { - t.Fatalf("autorest: MapToValues method failed to return correct values - expected(%v) got(%v)", v, MapToValues(m)) - } -} - -func isEqual(v, u url.Values) bool { - for key, value := range v { - if len(u[key]) == 0 { - return false - } - sort.Strings(value) - sort.Strings(u[key]) - for i := range value { - if value[i] != u[key][i] { - return false - } - } - u.Del(key) - } - if len(u) > 0 { - return false - } - return true -} - -func doEnsureBodyClosed(t *testing.T) SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (*http.Response, error) { - resp, err := s.Do(r) - if resp != nil && resp.Body != nil && resp.Body.(*mocks.Body).IsOpen() { - t.Fatal("autorest: Expected Body to be closed -- it was left open") - } - return resp, err - }) - } -} - -type mockAuthorizer struct{} - -func (ma mockAuthorizer) WithAuthorization() PrepareDecorator { - return WithHeader(headerAuthorization, mocks.TestAuthorizationHeader) -} - -type mockFailingAuthorizer struct{} - -func (mfa mockFailingAuthorizer) WithAuthorization() PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - return r, fmt.Errorf("ERROR: mockFailingAuthorizer returned expected error") - }) - } -} - -type mockInspector struct { - wasInvoked bool -} - -func (mi *mockInspector) WithInspection() PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - mi.wasInvoked = true - return p.Prepare(r) - }) - } -} - -func (mi *mockInspector) ByInspecting() RespondDecorator { - return func(r Responder) Responder { - return ResponderFunc(func(resp *http.Response) error { - mi.wasInvoked = true - return r.Respond(resp) - }) - } -} - -func withMessage(output *string, msg string) SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (*http.Response, error) { - resp, err := s.Do(r) - if err == nil { - *output += msg - } - return resp, err - }) - } -} - -func withErrorRespondDecorator(e *error) RespondDecorator { - return func(r Responder) Responder { - return ResponderFunc(func(resp *http.Response) error { - err := r.Respond(resp) - if err != nil { - return err - } - *e = fmt.Errorf("autorest: Faux Respond Error") - return *e - }) - } -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/validation/validation_test.go b/vendor/github.com/Azure/go-autorest/autorest/validation/validation_test.go deleted file mode 100644 index fdf822846..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/validation/validation_test.go +++ /dev/null @@ -1,2417 +0,0 @@ -package validation - -import ( - "fmt" - "reflect" - "strings" - "testing" - - "github.com/stretchr/testify/require" -) - -func TestCheckForUniqueInArrayTrue(t *testing.T) { - require.Equal(t, checkForUniqueInArray(reflect.ValueOf([]int{1, 2, 3})), true) -} - -func TestCheckForUniqueInArrayFalse(t *testing.T) { - require.Equal(t, checkForUniqueInArray(reflect.ValueOf([]int{1, 2, 3, 3})), false) -} - -func TestCheckForUniqueInArrayEmpty(t *testing.T) { - require.Equal(t, checkForUniqueInArray(reflect.ValueOf([]int{})), false) -} - -func TestCheckForUniqueInMapTrue(t *testing.T) { - require.Equal(t, checkForUniqueInMap(reflect.ValueOf(map[string]int{"one": 1, "two": 2})), true) -} - -func TestCheckForUniqueInMapFalse(t *testing.T) { - require.Equal(t, checkForUniqueInMap(reflect.ValueOf(map[int]string{1: "one", 2: "one"})), false) -} - -func TestCheckForUniqueInMapEmpty(t *testing.T) { - require.Equal(t, checkForUniqueInMap(reflect.ValueOf(map[int]string{})), false) -} - -func TestCheckEmpty_WithValueEmptyRuleTrue(t *testing.T) { - var x interface{} - v := Constraint{ - Target: "str", - Name: Empty, - Rule: true, - Chain: nil, - } - expected := createError(reflect.ValueOf(x), v, "value can not be null or empty; required parameter") - require.Equal(t, checkEmpty(reflect.ValueOf(x), v).Error(), expected.Error()) -} - -func TestCheckEmpty_WithEmptyStringRuleFalse(t *testing.T) { - var x interface{} - v := Constraint{ - Target: "str", - Name: Empty, - Rule: false, - Chain: nil, - } - require.Nil(t, checkEmpty(reflect.ValueOf(x), v)) -} - -func TestCheckEmpty_IncorrectRule(t *testing.T) { - var x interface{} - v := Constraint{ - Target: "str", - Name: Empty, - Rule: 10, - Chain: nil, - } - expected := createError(reflect.ValueOf(x), v, fmt.Sprintf("rule must be bool value for %v constraint; got: %v", v.Name, v.Rule)) - require.Equal(t, checkEmpty(reflect.ValueOf(x), v).Error(), expected.Error()) -} - -func TestCheckEmpty_WithErrorArray(t *testing.T) { - var x interface{} = []string{} - v := Constraint{ - Target: "str", - Name: Empty, - Rule: true, - Chain: nil, - } - expected := createError(reflect.ValueOf(x), v, "value can not be null or empty; required parameter") - require.Equal(t, checkEmpty(reflect.ValueOf(x), v).Error(), expected.Error()) -} - -func TestCheckNil_WithNilValueRuleTrue(t *testing.T) { - var x interface{} - v := Constraint{ - Target: "x", - Name: Null, - Rule: true, - Chain: []Constraint{ - {"x", MaxItems, 4, nil}, - }, - } - expected := createError(reflect.ValueOf(x), v, "value can not be null; required parameter") - require.Equal(t, checkNil(reflect.ValueOf(x), v).Error(), expected.Error()) -} - -func TestCheckNil_WithNilValueRuleFalse(t *testing.T) { - var x interface{} - v := Constraint{ - Target: "x", - Name: Null, - Rule: false, - Chain: []Constraint{ - {"x", MaxItems, 4, nil}, - }, - } - require.Nil(t, checkNil(reflect.ValueOf(x), v)) -} - -func TestCheckNil_IncorrectRule(t *testing.T) { - var x interface{} - c := Constraint{ - Target: "str", - Name: Null, - Rule: 10, - Chain: nil, - } - expected := createError(reflect.ValueOf(x), c, fmt.Sprintf("rule must be bool value for %v constraint; got: %v", c.Name, c.Rule)) - require.Equal(t, checkNil(reflect.ValueOf(x), c).Error(), expected.Error()) -} - -func TestValidateArrayMap_WithNilValueRuleTrue(t *testing.T) { - var a []string - var x interface{} = a - c := Constraint{ - Target: "arr", - Name: Null, - Rule: true, - Chain: nil, - } - expected := createError(reflect.ValueOf(x), c, "value can not be null; required parameter") - require.Equal(t, validateArrayMap(reflect.ValueOf(x), c), expected) -} - -func TestValidateArrayMap_WithNilValueRuleFalse(t *testing.T) { - var x interface{} = []string{} - c := Constraint{ - Target: "arr", - Name: Null, - Rule: false, - Chain: nil, - } - require.Nil(t, validateArrayMap(reflect.ValueOf(x), c)) -} - -func TestValidateArrayMap_WithValueRuleNullTrue(t *testing.T) { - var x interface{} = []string{"1", "2"} - c := Constraint{ - Target: "arr", - Name: Null, - Rule: false, - Chain: nil, - } - require.Nil(t, validateArrayMap(reflect.ValueOf(x), c)) -} - -func TestValidateArrayMap_WithEmptyValueRuleTrue(t *testing.T) { - var x interface{} = []string{} - c := Constraint{ - Target: "arr", - Name: Empty, - Rule: true, - Chain: nil, - } - expected := createError(reflect.ValueOf(x), c, "value can not be null or empty; required parameter") - require.Equal(t, validateArrayMap(reflect.ValueOf(x), c), expected) -} - -func TestValidateArrayMap_WithEmptyValueRuleFalse(t *testing.T) { - var x interface{} = []string{} - c := Constraint{ - Target: "arr", - Name: Empty, - Rule: false, - Chain: nil, - } - require.Nil(t, validateArrayMap(reflect.ValueOf(x), c)) -} - -func TestValidateArrayMap_WithEmptyRuleEmptyTrue(t *testing.T) { - var x interface{} = []string{"1", "2"} - c := Constraint{ - Target: "arr", - Name: Empty, - Rule: false, - Chain: nil, - } - require.Nil(t, validateArrayMap(reflect.ValueOf(x), c)) -} - -func TestValidateArrayMap_MaxItemsIncorrectRule(t *testing.T) { - var x interface{} = []string{"1", "2"} - c := Constraint{ - Target: "arr", - Name: MaxItems, - Rule: false, - Chain: nil, - } - expected := createError(reflect.ValueOf(x), c, fmt.Sprintf("rule must be integer for %v constraint; got: %v", c.Name, c.Rule)) - require.Equal(t, validateArrayMap(reflect.ValueOf(x), c).Error(), expected.Error()) -} - -func TestValidateArrayMap_MaxItemsNoError(t *testing.T) { - var x interface{} = []string{"1", "2"} - c := Constraint{ - Target: "arr", - Name: MaxItems, - Rule: 2, - Chain: nil, - } - require.Nil(t, validateArrayMap(reflect.ValueOf(x), c)) -} - -func TestValidateArrayMap_MaxItemsWithError(t *testing.T) { - var x interface{} = []string{"1", "2", "3"} - c := Constraint{ - Target: "arr", - Name: MaxItems, - Rule: 2, - Chain: nil, - } - expected := createError(reflect.ValueOf(x), c, fmt.Sprintf("maximum item limit is %v; got: 3", c.Rule)) - require.Equal(t, validateArrayMap(reflect.ValueOf(x), c).Error(), expected.Error()) -} - -func TestValidateArrayMap_MaxItemsWithEmpty(t *testing.T) { - var x interface{} = []string{} - c := Constraint{ - Target: "arr", - Name: MaxItems, - Rule: 2, - Chain: nil, - } - require.Nil(t, validateArrayMap(reflect.ValueOf(x), c)) -} - -func TestValidateArrayMap_MinItemsIncorrectRule(t *testing.T) { - var x interface{} = []int{1, 2} - c := Constraint{ - Target: "arr", - Name: MinItems, - Rule: false, - Chain: nil, - } - expected := createError(reflect.ValueOf(x), c, fmt.Sprintf("rule must be integer for %v constraint; got: %v", c.Name, c.Rule)) - require.Equal(t, validateArrayMap(reflect.ValueOf(x), c).Error(), expected.Error()) -} - -func TestValidateArrayMap_MinItemsNoError1(t *testing.T) { - c := Constraint{ - Target: "arr", - Name: MinItems, - Rule: 2, - Chain: nil, - } - require.Nil(t, validateArrayMap(reflect.ValueOf([]int{1, 2}), c)) -} - -func TestValidateArrayMap_MinItemsNoError2(t *testing.T) { - c := Constraint{ - Target: "arr", - Name: MinItems, - Rule: 2, - Chain: nil, - } - require.Nil(t, validateArrayMap(reflect.ValueOf([]int{1, 2, 3}), c)) -} - -func TestValidateArrayMap_MinItemsWithError(t *testing.T) { - var x interface{} = []int{1} - c := Constraint{ - Target: "arr", - Name: MinItems, - Rule: 2, - Chain: nil, - } - expected := createError(reflect.ValueOf(x), c, fmt.Sprintf("minimum item limit is %v; got: 1", c.Rule)) - require.Equal(t, validateArrayMap(reflect.ValueOf(x), c).Error(), expected.Error()) -} - -func TestValidateArrayMap_MinItemsWithEmpty(t *testing.T) { - var x interface{} = []int{} - c := Constraint{ - Target: "arr", - Name: MinItems, - Rule: 2, - Chain: nil, - } - expected := createError(reflect.ValueOf(x), c, fmt.Sprintf("minimum item limit is %v; got: 0", c.Rule)) - require.Equal(t, validateArrayMap(reflect.ValueOf(x), c).Error(), expected.Error()) -} - -func TestValidateArrayMap_Map_MaxItemsIncorrectRule(t *testing.T) { - var x interface{} = map[int]string{1: "1", 2: "2"} - c := Constraint{ - Target: "arr", - Name: MaxItems, - Rule: false, - Chain: nil, - } - require.Equal(t, strings.Contains(validateArrayMap(reflect.ValueOf(x), c).Error(), - fmt.Sprintf("rule must be integer for %v constraint; got: %v", c.Name, c.Rule)), true) -} - -func TestValidateArrayMap_Map_MaxItemsNoError(t *testing.T) { - var x interface{} = map[int]string{1: "1", 2: "2"} - c := Constraint{ - Target: "arr", - Name: MaxItems, - Rule: 2, - Chain: nil, - } - require.Nil(t, validateArrayMap(reflect.ValueOf(x), c)) -} - -func TestValidateArrayMap_Map_MaxItemsWithError(t *testing.T) { - a := map[int]string{1: "1", 2: "2", 3: "3"} - var x interface{} = a - c := Constraint{ - Target: "arr", - Name: MaxItems, - Rule: 2, - Chain: nil, - } - require.Equal(t, strings.Contains(validateArrayMap(reflect.ValueOf(x), c).Error(), - fmt.Sprintf("maximum item limit is %v; got: %v", c.Rule, len(a))), true) -} - -func TestValidateArrayMap_Map_MaxItemsWithEmpty(t *testing.T) { - a := map[int]string{} - var x interface{} = a - c := Constraint{ - Target: "arr", - Name: MaxItems, - Rule: 2, - Chain: nil, - } - require.Nil(t, validateArrayMap(reflect.ValueOf(x), c)) -} - -func TestValidateArrayMap_Map_MinItemsIncorrectRule(t *testing.T) { - var x interface{} = map[int]string{1: "1", 2: "2"} - c := Constraint{ - Target: "arr", - Name: MinItems, - Rule: false, - Chain: nil, - } - require.Equal(t, strings.Contains(validateArrayMap(reflect.ValueOf(x), c).Error(), - fmt.Sprintf("rule must be integer for %v constraint; got: %v", c.Name, c.Rule)), true) -} - -func TestValidateArrayMap_Map_MinItemsNoError1(t *testing.T) { - var x interface{} = map[int]string{1: "1", 2: "2"} - require.Nil(t, validateArrayMap(reflect.ValueOf(x), - Constraint{ - Target: "arr", - Name: MinItems, - Rule: 2, - Chain: nil, - })) -} - -func TestValidateArrayMap_Map_MinItemsNoError2(t *testing.T) { - var x interface{} = map[int]string{1: "1", 2: "2", 3: "3"} - c := Constraint{ - Target: "arr", - Name: MinItems, - Rule: 2, - Chain: nil, - } - require.Nil(t, validateArrayMap(reflect.ValueOf(x), c)) -} - -func TestValidateArrayMap_Map_MinItemsWithError(t *testing.T) { - a := map[int]string{1: "1"} - var x interface{} = a - c := Constraint{ - Target: "arr", - Name: MinItems, - Rule: 2, - Chain: nil, - } - expected := createError(reflect.ValueOf(x), c, fmt.Sprintf("minimum item limit is %v; got: %v", c.Rule, len(a))) - require.Equal(t, validateArrayMap(reflect.ValueOf(x), c).Error(), expected.Error()) -} - -func TestValidateArrayMap_Map_MinItemsWithEmpty(t *testing.T) { - a := map[int]string{} - var x interface{} = a - c := Constraint{ - Target: "arr", - Name: MinItems, - Rule: 2, - Chain: nil, - } - expected := createError(reflect.ValueOf(x), c, fmt.Sprintf("minimum item limit is %v; got: %v", c.Rule, len(a))) - require.Equal(t, validateArrayMap(reflect.ValueOf(x), c).Error(), expected.Error()) -} - -// func TestValidateArrayMap_Map_MinItemsNil(t *testing.T) { -// var a map[int]float64 -// var x interface{} = a -// c := Constraint{ -// Target: "str", -// Name: MinItems, -// Rule: true, -// Chain: nil, -// } -// expected := createError(reflect.Value(x), c, fmt.Sprintf("all items in parameter %v must be unique; got:%v", c.Target, x)) -// if z := validateArrayMap(reflect.ValueOf(x), c); strings.Contains(z.Error(), "all items in parameter str must be unique;") { -// t.Fatalf("autorest/validation: valiateArrayMap failed to return error \nexpect: %v;\ngot: %v", expected, z) -// } -// } - -func TestValidateArrayMap_Map_UniqueItemsTrue(t *testing.T) { - var x interface{} = map[float64]int{1.2: 1, 1.4: 2} - c := Constraint{ - Target: "str", - Name: UniqueItems, - Rule: true, - Chain: nil, - } - require.Nil(t, validateArrayMap(reflect.ValueOf(x), c)) -} - -func TestValidateArrayMap_Map_UniqueItemsFalse(t *testing.T) { - var x interface{} = map[string]string{"1": "1", "2": "2", "3": "1"} - c := Constraint{ - Target: "str", - Name: UniqueItems, - Rule: true, - Chain: nil, - } - z := validateArrayMap(reflect.ValueOf(x), c) - require.Equal(t, strings.Contains(z.Error(), - fmt.Sprintf("all items in parameter %q must be unique", c.Target)), true) -} - -func TestValidateArrayMap_Map_UniqueItemsEmpty(t *testing.T) { - // Consider Empty map as not unique returns false - var x interface{} = map[int]float64{} - c := Constraint{ - Target: "str", - Name: UniqueItems, - Rule: true, - Chain: nil, - } - z := validateArrayMap(reflect.ValueOf(x), c) - require.Equal(t, strings.Contains(z.Error(), - fmt.Sprintf("all items in parameter %q must be unique", c.Target)), true) -} - -func TestValidateArrayMap_Map_UniqueItemsNil(t *testing.T) { - var a map[int]float64 - var x interface{} = a - c := Constraint{ - Target: "str", - Name: UniqueItems, - Rule: true, - Chain: nil, - } - z := validateArrayMap(reflect.ValueOf(x), c) - require.Equal(t, strings.Contains(z.Error(), - fmt.Sprintf("all items in parameter %q must be unique; got:%v", c.Target, x)), true) -} - -func TestValidateArrayMap_Array_UniqueItemsTrue(t *testing.T) { - var x interface{} = []int{1, 2} - c := Constraint{ - Target: "str", - Name: UniqueItems, - Rule: true, - Chain: nil, - } - require.Nil(t, validateArrayMap(reflect.ValueOf(x), c)) -} - -func TestValidateArrayMap_Array_UniqueItemsFalse(t *testing.T) { - var x interface{} = []string{"1", "2", "1"} - c := Constraint{ - Target: "str", - Name: UniqueItems, - Rule: true, - Chain: nil, - } - z := validateArrayMap(reflect.ValueOf(x), c) - require.Equal(t, strings.Contains(z.Error(), - fmt.Sprintf("all items in parameter %q must be unique; got:%v", c.Target, x)), true) -} - -func TestValidateArrayMap_Array_UniqueItemsEmpty(t *testing.T) { - // Consider Empty array as not unique returns false - var x interface{} = []float64{} - c := Constraint{ - Target: "str", - Name: UniqueItems, - Rule: true, - Chain: nil, - } - z := validateArrayMap(reflect.ValueOf(x), c) - require.Equal(t, strings.Contains(z.Error(), - fmt.Sprintf("all items in parameter %q must be unique; got:%v", c.Target, x)), true) -} - -func TestValidateArrayMap_Array_UniqueItemsNil(t *testing.T) { - // Consider nil array as not unique returns false - var a []float64 - var x interface{} = a - c := Constraint{ - Target: "str", - Name: UniqueItems, - Rule: true, - Chain: nil, - } - z := validateArrayMap(reflect.ValueOf(x), c) - require.Equal(t, strings.Contains(z.Error(), - fmt.Sprintf("all items in parameter %q must be unique; got:%v", c.Target, x)), true) -} - -func TestValidateArrayMap_Array_UniqueItemsInvalidType(t *testing.T) { - var x interface{} = "hello" - c := Constraint{ - Target: "str", - Name: UniqueItems, - Rule: true, - Chain: nil, - } - z := validateArrayMap(reflect.ValueOf(x), c) - require.Equal(t, strings.Contains(z.Error(), - fmt.Sprintf("type must be array, slice or map for constraint %v; got: %v", c.Name, reflect.ValueOf(x).Kind())), true) -} - -func TestValidateArrayMap_Array_UniqueItemsInvalidConstraint(t *testing.T) { - var x interface{} = "hello" - c := Constraint{ - Target: "str", - Name: "sdad", - Rule: true, - Chain: nil, - } - z := validateArrayMap(reflect.ValueOf(x), c) - require.Equal(t, strings.Contains(z.Error(), - fmt.Sprintf("constraint %v is not applicable to array, slice and map type", c.Name)), true) -} - -func TestValidateArrayMap_ValidateChainConstraint1(t *testing.T) { - a := []int{1, 2, 3, 4} - var x interface{} = a - c := Constraint{ - Target: "str", - Name: Null, - Rule: true, - Chain: []Constraint{ - {"str", MaxItems, 3, nil}, - }, - } - z := validateArrayMap(reflect.ValueOf(x), c) - require.Equal(t, strings.Contains(z.Error(), - fmt.Sprintf("maximum item limit is %v; got: %v", (c.Chain)[0].Rule, len(a))), true) -} - -func TestValidateArrayMap_ValidateChainConstraint2(t *testing.T) { - a := []int{1, 2, 3, 4} - var x interface{} = a - c := Constraint{ - Target: "str", - Name: Empty, - Rule: true, - Chain: []Constraint{ - {"str", MaxItems, 3, nil}, - }, - } - z := validateArrayMap(reflect.ValueOf(x), c) - require.Equal(t, strings.Contains(z.Error(), - fmt.Sprintf("maximum item limit is %v; got: %v", (c.Chain)[0].Rule, len(a))), true) -} - -func TestValidateArrayMap_ValidateChainConstraint3(t *testing.T) { - var a []string - var x interface{} = a - c := Constraint{ - Target: "str", - Name: Null, - Rule: true, - Chain: []Constraint{ - {"str", MaxItems, 3, nil}, - }, - } - z := validateArrayMap(reflect.ValueOf(x), c) - require.Equal(t, strings.Contains(z.Error(), - fmt.Sprintf("value can not be null; required parameter")), true) -} - -func TestValidateArrayMap_ValidateChainConstraint4(t *testing.T) { - var x interface{} = []int{} - c := Constraint{ - Target: "str", - Name: Empty, - Rule: true, - Chain: []Constraint{ - {"str", MaxItems, 3, nil}, - }, - } - z := validateArrayMap(reflect.ValueOf(x), c) - require.Equal(t, strings.Contains(z.Error(), - fmt.Sprintf("value can not be null or empty; required parameter")), true) -} - -func TestValidateArrayMap_ValidateChainConstraintNilNotRequired(t *testing.T) { - var a []int - var x interface{} = a - c := Constraint{ - Target: "str", - Name: Null, - Rule: false, - Chain: []Constraint{ - {"str", MaxItems, 3, nil}, - }, - } - require.Nil(t, validateArrayMap(reflect.ValueOf(x), c)) -} - -func TestValidateArrayMap_ValidateChainConstraintEmptyNotRequired(t *testing.T) { - var x interface{} = map[string]int{} - c := Constraint{ - Target: "str", - Name: Empty, - Rule: false, - Chain: []Constraint{ - {"str", MaxItems, 3, nil}, - }, - } - require.Nil(t, validateArrayMap(reflect.ValueOf(x), c)) -} - -func TestValidateArrayMap_ReadOnlyWithError(t *testing.T) { - var x interface{} = []int{1, 2} - c := Constraint{ - Target: "str", - Name: ReadOnly, - Rule: true, - Chain: []Constraint{ - {"str", MaxItems, 3, nil}, - }, - } - z := validateArrayMap(reflect.ValueOf(x), c) - require.Equal(t, strings.Contains(z.Error(), - fmt.Sprintf("readonly parameter; must send as nil or empty in request")), true) -} - -func TestValidateArrayMap_ReadOnlyWithoutError(t *testing.T) { - var x interface{} = []int{} - c := Constraint{ - Target: "str", - Name: ReadOnly, - Rule: true, - Chain: nil, - } - require.Nil(t, validateArrayMap(reflect.ValueOf(x), c)) -} - -func TestValidateString_ReadOnly(t *testing.T) { - var x interface{} = "Hello Gopher" - c := Constraint{ - Target: "str", - Name: ReadOnly, - Rule: true, - Chain: nil, - } - require.Equal(t, strings.Contains(validateString(reflect.ValueOf(x), c).Error(), - fmt.Sprintf("readonly parameter; must send as nil or empty in request")), true) -} - -func TestValidateString_EmptyTrue(t *testing.T) { - // Empty true means parameter is required but Empty returns error - c := Constraint{ - Target: "str", - Name: Empty, - Rule: true, - Chain: nil, - } - require.Equal(t, strings.Contains(validateString(reflect.ValueOf(""), c).Error(), - fmt.Sprintf("value can not be null or empty; required parameter")), true) -} - -func TestValidateString_EmptyFalse(t *testing.T) { - // Empty false means parameter is not required and Empty return nil - var x interface{} - c := Constraint{ - Target: "str", - Name: Empty, - Rule: false, - Chain: nil, - } - require.Nil(t, validateString(reflect.ValueOf(x), c)) -} - -func TestValidateString_MaxLengthInvalid(t *testing.T) { - // Empty true means parameter is required but Empty returns error - var x interface{} = "Hello" - c := Constraint{ - Target: "str", - Name: MaxLength, - Rule: 4, - Chain: nil, - } - require.Equal(t, strings.Contains(validateString(reflect.ValueOf(x), c).Error(), - fmt.Sprintf("value length must be less than %v", c.Rule)), true) -} - -func TestValidateString_MaxLengthValid(t *testing.T) { - // Empty false means parameter is not required and Empty return nil - c := Constraint{ - Target: "str", - Name: MaxLength, - Rule: 7, - Chain: nil, - } - require.Nil(t, validateString(reflect.ValueOf("Hello"), c)) -} - -func TestValidateString_MaxLengthRuleInvalid(t *testing.T) { - var x interface{} = "Hello" - c := Constraint{ - Target: "str", - Name: MaxLength, - Rule: true, // must be int for maxLength - Chain: nil, - } - require.Equal(t, strings.Contains(validateString(reflect.ValueOf(x), c).Error(), - fmt.Sprintf("rule must be integer value for %v constraint; got: %v", c.Name, c.Rule)), true) -} - -func TestValidateString_MinLengthInvalid(t *testing.T) { - var x interface{} = "Hello" - c := Constraint{ - Target: "str", - Name: MinLength, - Rule: 10, - Chain: nil, - } - require.Equal(t, strings.Contains(validateString(reflect.ValueOf(x), c).Error(), - fmt.Sprintf("value length must be greater than %v", c.Rule)), true) -} - -func TestValidateString_MinLengthValid(t *testing.T) { - c := Constraint{ - Target: "str", - Name: MinLength, - Rule: 2, - Chain: nil, - } - require.Nil(t, validateString(reflect.ValueOf("Hello"), c)) -} - -func TestValidateString_MinLengthRuleInvalid(t *testing.T) { - var x interface{} = "Hello" - c := Constraint{ - Target: "str", - Name: MinLength, - Rule: true, // must be int for minLength - Chain: nil, - } - require.Equal(t, strings.Contains(validateString(reflect.ValueOf(x), c).Error(), - fmt.Sprintf("rule must be integer value for %v constraint; got: %v", c.Name, c.Rule)), true) -} - -func TestValidateString_PatternInvalidPattern(t *testing.T) { - var x interface{} = "Hello" - c := Constraint{ - Target: "str", - Name: Pattern, - Rule: `^[[:alnum:$`, - Chain: nil, - } - require.Equal(t, strings.Contains(validateString(reflect.ValueOf(x), c).Error(), - "error parsing regexp: missing closing ]"), true) -} - -func TestValidateString_PatternMatch1(t *testing.T) { - c := Constraint{ - Target: "str", - Name: Pattern, - Rule: `^http://\w+$`, - Chain: nil, - } - require.Nil(t, validateString(reflect.ValueOf("http://masd"), c)) -} - -func TestValidateString_PatternMatch2(t *testing.T) { - c := Constraint{ - Target: "str", - Name: Pattern, - Rule: `^[a-zA-Z0-9]+$`, - Chain: nil, - } - require.Nil(t, validateString(reflect.ValueOf("asdadad2323sad"), c)) -} - -func TestValidateString_PatternNotMatch(t *testing.T) { - var x interface{} = "asdad@@ad2323sad" - c := Constraint{ - Target: "str", - Name: Pattern, - Rule: `^[a-zA-Z0-9]+$`, - Chain: nil, - } - require.Equal(t, strings.Contains(validateString(reflect.ValueOf(x), c).Error(), - fmt.Sprintf("value doesn't match pattern %v", c.Rule)), true) -} - -func TestValidateString_InvalidConstraint(t *testing.T) { - var x interface{} = "asdad@@ad2323sad" - c := Constraint{ - Target: "str", - Name: UniqueItems, - Rule: "^[a-zA-Z0-9]+$", - Chain: nil, - } - require.Equal(t, strings.Contains(validateString(reflect.ValueOf(x), c).Error(), - fmt.Sprintf("constraint %s is not applicable to string type", c.Name)), true) -} - -func TestValidateFloat_InvalidConstraint(t *testing.T) { - var x interface{} = 1.4 - c := Constraint{ - Target: "str", - Name: UniqueItems, - Rule: 3.0, - Chain: nil, - } - require.Equal(t, strings.Contains(validateFloat(reflect.ValueOf(x), c).Error(), - fmt.Sprintf("constraint %v is not applicable for type float", c.Name)), true) -} - -func TestValidateFloat_InvalidRuleValue(t *testing.T) { - var x interface{} = 1.4 - c := Constraint{ - Target: "str", - Name: ExclusiveMinimum, - Rule: 3, - Chain: nil, - } - require.Equal(t, strings.Contains(validateFloat(reflect.ValueOf(x), c).Error(), - fmt.Sprintf("rule must be float value for %v constraint; got: %v", c.Name, c.Rule)), true) -} - -func TestValidateFloat_ExclusiveMinimumConstraintValid(t *testing.T) { - c := Constraint{ - Target: "str", - Name: ExclusiveMinimum, - Rule: 1.0, - Chain: nil, - } - require.Nil(t, validateFloat(reflect.ValueOf(1.42), c)) -} - -func TestValidateFloat_ExclusiveMinimumConstraintInvalid(t *testing.T) { - var x interface{} = 1.4 - c := Constraint{ - Target: "str", - Name: ExclusiveMinimum, - Rule: 1.5, - Chain: nil, - } - require.Equal(t, strings.Contains(validateFloat(reflect.ValueOf(x), c).Error(), - fmt.Sprintf("value must be greater than %v", c.Rule)), true) -} - -func TestValidateFloat_ExclusiveMinimumConstraintBoundary(t *testing.T) { - var x interface{} = 1.42 - c := Constraint{ - Target: "str", - Name: ExclusiveMinimum, - Rule: 1.42, - Chain: nil, - } - require.Equal(t, strings.Contains(validateFloat(reflect.ValueOf(x), c).Error(), - fmt.Sprintf("value must be greater than %v", c.Rule)), true) -} - -func TestValidateFloat_exclusiveMaximumConstraintValid(t *testing.T) { - c := Constraint{ - Target: "str", - Name: ExclusiveMaximum, - Rule: 2.0, - Chain: nil, - } - require.Nil(t, validateFloat(reflect.ValueOf(1.42), c)) -} - -func TestValidateFloat_exclusiveMaximumConstraintInvalid(t *testing.T) { - var x interface{} = 1.42 - c := Constraint{ - Target: "str", - Name: ExclusiveMaximum, - Rule: 1.2, - Chain: nil, - } - require.Equal(t, strings.Contains(validateFloat(reflect.ValueOf(x), c).Error(), - fmt.Sprintf("value must be less than %v", c.Rule)), true) -} - -func TestValidateFloat_exclusiveMaximumConstraintBoundary(t *testing.T) { - var x interface{} = 1.42 - c := Constraint{ - Target: "str", - Name: ExclusiveMaximum, - Rule: 1.42, - Chain: nil, - } - require.Equal(t, strings.Contains(validateFloat(reflect.ValueOf(x), c).Error(), - fmt.Sprintf("value must be less than %v", c.Rule)), true) -} - -func TestValidateFloat_inclusiveMaximumConstraintValid(t *testing.T) { - c := Constraint{ - Target: "str", - Name: InclusiveMaximum, - Rule: 2.0, - Chain: nil, - } - require.Nil(t, validateFloat(reflect.ValueOf(1.42), c)) -} - -func TestValidateFloat_inclusiveMaximumConstraintInvalid(t *testing.T) { - var x interface{} = 1.42 - c := Constraint{ - Target: "str", - Name: InclusiveMaximum, - Rule: 1.2, - Chain: nil, - } - require.Equal(t, strings.Contains(validateFloat(reflect.ValueOf(x), c).Error(), - fmt.Sprintf("value must be less than or equal to %v", c.Rule)), true) - -} - -func TestValidateFloat_inclusiveMaximumConstraintBoundary(t *testing.T) { - c := Constraint{ - Target: "str", - Name: InclusiveMaximum, - Rule: 1.42, - Chain: nil, - } - require.Nil(t, validateFloat(reflect.ValueOf(1.42), c)) -} - -func TestValidateFloat_InclusiveMinimumConstraintValid(t *testing.T) { - c := Constraint{ - Target: "str", - Name: InclusiveMinimum, - Rule: 1.0, - Chain: nil, - } - require.Nil(t, validateFloat(reflect.ValueOf(1.42), c)) -} - -func TestValidateFloat_InclusiveMinimumConstraintInvalid(t *testing.T) { - var x interface{} = 1.42 - c := Constraint{ - Target: "str", - Name: InclusiveMinimum, - Rule: 1.5, - Chain: nil, - } - require.Equal(t, strings.Contains(validateFloat(reflect.ValueOf(x), c).Error(), - fmt.Sprintf("value must be greater than or equal to %v", c.Rule)), true) - -} - -func TestValidateFloat_InclusiveMinimumConstraintBoundary(t *testing.T) { - c := Constraint{ - Target: "str", - Name: InclusiveMinimum, - Rule: 1.42, - Chain: nil, - } - require.Nil(t, validateFloat(reflect.ValueOf(1.42), c)) -} - -func TestValidateInt_InvalidConstraint(t *testing.T) { - var x interface{} = 1 - c := Constraint{ - Target: "str", - Name: UniqueItems, - Rule: 3, - Chain: nil, - } - require.Equal(t, strings.Contains(validateInt(reflect.ValueOf(x), c).Error(), - fmt.Sprintf("constraint %s is not applicable for type integer", c.Name)), true) -} - -func TestValidateInt_InvalidRuleValue(t *testing.T) { - var x interface{} = 1 - c := Constraint{ - Target: "str", - Name: ExclusiveMinimum, - Rule: 3.4, - Chain: nil, - } - require.Equal(t, strings.Contains(validateInt(reflect.ValueOf(x), c).Error(), - fmt.Sprintf("rule must be integer value for %v constraint; got: %v", c.Name, c.Rule)), true) -} - -func TestValidateInt_ExclusiveMinimumConstraintValid(t *testing.T) { - c := Constraint{ - Target: "str", - Name: ExclusiveMinimum, - Rule: 1, - Chain: nil, - } - require.Nil(t, validateInt(reflect.ValueOf(3), c)) -} - -func TestValidateInt_ExclusiveMinimumConstraintInvalid(t *testing.T) { - var x interface{} = 1 - c := Constraint{ - Target: "str", - Name: ExclusiveMinimum, - Rule: 3, - Chain: nil, - } - require.Equal(t, validateInt(reflect.ValueOf(x), c).Error(), - createError(reflect.ValueOf(x), c, fmt.Sprintf("value must be greater than %v", c.Rule)).Error()) -} - -func TestValidateInt_ExclusiveMinimumConstraintBoundary(t *testing.T) { - var x interface{} = 1 - c := Constraint{ - Target: "str", - Name: ExclusiveMinimum, - Rule: 1, - Chain: nil, - } - require.Equal(t, validateInt(reflect.ValueOf(x), c).Error(), - createError(reflect.ValueOf(x), c, fmt.Sprintf("value must be greater than %v", c.Rule)).Error()) -} - -func TestValidateInt_exclusiveMaximumConstraintValid(t *testing.T) { - c := Constraint{ - Target: "str", - Name: ExclusiveMaximum, - Rule: 2, - Chain: nil, - } - require.Nil(t, validateInt(reflect.ValueOf(1), c)) -} - -func TestValidateInt_exclusiveMaximumConstraintInvalid(t *testing.T) { - var x interface{} = 2 - c := Constraint{ - Target: "str", - Name: ExclusiveMaximum, - Rule: 1, - Chain: nil, - } - require.Equal(t, validateInt(reflect.ValueOf(x), c).Error(), - createError(reflect.ValueOf(x), c, fmt.Sprintf("value must be less than %v", c.Rule)).Error()) -} - -func TestValidateInt_exclusiveMaximumConstraintBoundary(t *testing.T) { - var x interface{} = 1 - c := Constraint{ - Target: "str", - Name: ExclusiveMaximum, - Rule: 1, - Chain: nil, - } - require.Equal(t, validateInt(reflect.ValueOf(x), c).Error(), - createError(reflect.ValueOf(x), c, fmt.Sprintf("value must be less than %v", c.Rule)).Error()) -} - -func TestValidateInt_inclusiveMaximumConstraintValid(t *testing.T) { - c := Constraint{ - Target: "str", - Name: InclusiveMaximum, - Rule: 2, - Chain: nil, - } - require.Nil(t, validateInt(reflect.ValueOf(1), c)) -} - -func TestValidateInt_inclusiveMaximumConstraintInvalid(t *testing.T) { - var x interface{} = 2 - c := Constraint{ - Target: "str", - Name: InclusiveMaximum, - Rule: 1, - Chain: nil, - } - require.Equal(t, validateInt(reflect.ValueOf(x), c).Error(), - createError(reflect.ValueOf(x), c, fmt.Sprintf("value must be less than or equal to %v", c.Rule)).Error()) -} - -func TestValidateInt_inclusiveMaximumConstraintBoundary(t *testing.T) { - c := Constraint{ - Target: "str", - Name: InclusiveMaximum, - Rule: 1, - Chain: nil, - } - require.Nil(t, validateInt(reflect.ValueOf(1), c)) -} - -func TestValidateInt_InclusiveMinimumConstraintValid(t *testing.T) { - c := Constraint{ - Target: "str", - Name: InclusiveMinimum, - Rule: 1, - Chain: nil, - } - require.Nil(t, validateInt(reflect.ValueOf(1), c)) -} - -func TestValidateInt_InclusiveMinimumConstraintInvalid(t *testing.T) { - var x interface{} = 1 - c := Constraint{ - Target: "str", - Name: InclusiveMinimum, - Rule: 2, - Chain: nil, - } - require.Equal(t, validateInt(reflect.ValueOf(x), c).Error(), - createError(reflect.ValueOf(x), c, fmt.Sprintf("value must be greater than or equal to %v", c.Rule)).Error()) -} - -func TestValidateInt_InclusiveMinimumConstraintBoundary(t *testing.T) { - c := Constraint{ - Target: "str", - Name: InclusiveMinimum, - Rule: 1, - Chain: nil, - } - require.Nil(t, validateInt(reflect.ValueOf(1), c)) -} - -func TestValidateInt_MultipleOfWithoutError(t *testing.T) { - c := Constraint{ - Target: "str", - Name: MultipleOf, - Rule: 10, - Chain: nil, - } - require.Nil(t, validateInt(reflect.ValueOf(2300), c)) -} - -func TestValidateInt_MultipleOfWithError(t *testing.T) { - c := Constraint{ - Target: "str", - Name: MultipleOf, - Rule: 11, - Chain: nil, - } - require.Equal(t, validateInt(reflect.ValueOf(2300), c).Error(), - createError(reflect.ValueOf(2300), c, fmt.Sprintf("value must be a multiple of %v", c.Rule)).Error()) -} - -func TestValidatePointer_NilTrue(t *testing.T) { - var z *int - var x interface{} = z - c := Constraint{ - Target: "ptr", - Name: Null, - Rule: true, // Required property - Chain: nil, - } - require.Equal(t, validatePtr(reflect.ValueOf(x), c).Error(), - createError(reflect.ValueOf(x), c, "value can not be null; required parameter").Error()) -} - -func TestValidatePointer_NilFalse(t *testing.T) { - var z *int - var x interface{} = z - c := Constraint{ - Target: "ptr", - Name: Null, - Rule: false, // not required property - Chain: nil, - } - require.Nil(t, validatePtr(reflect.ValueOf(x), c)) -} - -func TestValidatePointer_NilReadonlyValid(t *testing.T) { - var z *int - var x interface{} = z - c := Constraint{ - Target: "ptr", - Name: ReadOnly, - Rule: true, - Chain: nil, - } - require.Nil(t, validatePtr(reflect.ValueOf(x), c)) -} - -func TestValidatePointer_NilReadonlyInvalid(t *testing.T) { - z := 10 - var x interface{} = &z - c := Constraint{ - Target: "ptr", - Name: ReadOnly, - Rule: true, - Chain: nil, - } - require.Equal(t, validatePtr(reflect.ValueOf(x), c).Error(), - createError(reflect.ValueOf(z), c, "readonly parameter; must send as nil or empty in request").Error()) -} - -func TestValidatePointer_IntValid(t *testing.T) { - z := 10 - var x interface{} = &z - c := Constraint{ - Target: "ptr", - Name: InclusiveMinimum, - Rule: 3, - Chain: nil, - } - require.Nil(t, validatePtr(reflect.ValueOf(x), c)) -} - -func TestValidatePointer_IntInvalid(t *testing.T) { - z := 10 - var x interface{} = &z - c := Constraint{ - Target: "ptr", - Name: Null, - Rule: true, - Chain: []Constraint{ - { - Target: "ptr", - Name: InclusiveMinimum, - Rule: 11, - Chain: nil, - }, - }, - } - require.Equal(t, validatePtr(reflect.ValueOf(x), c).Error(), - createError(reflect.ValueOf(10), c.Chain[0], "value must be greater than or equal to 11").Error()) -} - -func TestValidatePointer_IntInvalidConstraint(t *testing.T) { - z := 10 - var x interface{} = &z - c := Constraint{ - Target: "ptr", - Name: Null, - Rule: true, - Chain: []Constraint{ - { - Target: "ptr", - Name: MaxItems, - Rule: 3, - Chain: nil, - }, - }, - } - require.Equal(t, validatePtr(reflect.ValueOf(x), c).Error(), - createError(reflect.ValueOf(10), c.Chain[0], - fmt.Sprintf("constraint %v is not applicable for type integer", MaxItems)).Error()) -} - -func TestValidatePointer_ValidInt64(t *testing.T) { - z := int64(10) - var x interface{} = &z - c := Constraint{ - Target: "ptr", - Name: Null, - Rule: true, - Chain: []Constraint{ - { - Target: "ptr", - Name: InclusiveMinimum, - Rule: 3, - Chain: nil, - }, - }} - require.Nil(t, validatePtr(reflect.ValueOf(x), c)) -} - -func TestValidatePointer_InvalidConstraintInt64(t *testing.T) { - z := int64(10) - var x interface{} = &z - c := Constraint{ - Target: "ptr", - Name: Null, - Rule: true, - Chain: []Constraint{ - { - Target: "ptr", - Name: MaxItems, - Rule: 3, - Chain: nil, - }, - }, - } - require.Equal(t, validatePtr(reflect.ValueOf(x), c).Error(), - createError(reflect.ValueOf(10), c.Chain[0], - fmt.Sprintf("constraint %v is not applicable for type integer", MaxItems)).Error()) -} - -func TestValidatePointer_ValidFloat(t *testing.T) { - z := 10.1 - var x interface{} = &z - c := Constraint{ - Target: "ptr", - Name: Null, - Rule: true, - Chain: []Constraint{ - { - Target: "ptr", - Name: InclusiveMinimum, - Rule: 3.0, - Chain: nil, - }}} - require.Nil(t, validatePtr(reflect.ValueOf(x), c)) -} - -func TestValidatePointer_InvalidFloat(t *testing.T) { - z := 10.1 - var x interface{} = &z - c := Constraint{ - Target: "ptr", - Name: Null, - Rule: true, - Chain: []Constraint{ - { - Target: "ptr", - Name: InclusiveMinimum, - Rule: 12.0, - Chain: nil, - }}, - } - require.Equal(t, validatePtr(reflect.ValueOf(x), c).Error(), - createError(reflect.ValueOf(10.1), c.Chain[0], - "value must be greater than or equal to 12").Error()) -} - -func TestValidatePointer_InvalidConstraintFloat(t *testing.T) { - z := 10.1 - var x interface{} = &z - c := Constraint{ - Target: "ptr", - Name: Null, - Rule: true, - Chain: []Constraint{ - { - Target: "ptr", - Name: MaxItems, - Rule: 3.0, - Chain: nil, - }}, - } - require.Equal(t, validatePtr(reflect.ValueOf(x), c).Error(), - createError(reflect.ValueOf(10.1), c.Chain[0], - fmt.Sprintf("constraint %v is not applicable for type float", MaxItems)).Error()) -} - -func TestValidatePointer_StringValid(t *testing.T) { - z := "hello" - var x interface{} = &z - c := Constraint{ - Target: "ptr", - Name: Null, - Rule: true, - Chain: []Constraint{ - { - Target: "ptr", - Name: Pattern, - Rule: "^[a-z]+$", - Chain: nil, - }}} - require.Nil(t, validatePtr(reflect.ValueOf(x), c)) -} - -func TestValidatePointer_StringInvalid(t *testing.T) { - z := "hello" - var x interface{} = &z - c := Constraint{ - Target: "ptr", - Name: Null, - Rule: true, - Chain: []Constraint{ - { - Target: "ptr", - Name: MaxLength, - Rule: 2, - Chain: nil, - }}} - require.Equal(t, validatePtr(reflect.ValueOf(x), c).Error(), - createError(reflect.ValueOf("hello"), c.Chain[0], - "value length must be less than 2").Error()) -} - -func TestValidatePointer_ArrayValid(t *testing.T) { - c := Constraint{ - Target: "ptr", - Name: Null, - Rule: true, - Chain: []Constraint{ - { - Target: "ptr", - Name: UniqueItems, - Rule: "true", - Chain: nil, - }}} - require.Nil(t, validatePtr(reflect.ValueOf(&[]string{"1", "2"}), c)) -} - -func TestValidatePointer_ArrayInvalid(t *testing.T) { - z := []string{"1", "2", "2"} - var x interface{} = &z - c := Constraint{ - Target: "ptr", - Name: Null, - Rule: true, - Chain: []Constraint{{ - Target: "ptr", - Name: UniqueItems, - Rule: true, - Chain: nil, - }}, - } - require.Equal(t, validatePtr(reflect.ValueOf(x), c).Error(), - createError(reflect.ValueOf(z), c.Chain[0], - fmt.Sprintf("all items in parameter %q must be unique; got:%v", c.Target, z)).Error()) -} - -func TestValidatePointer_MapValid(t *testing.T) { - c := Constraint{ - Target: "ptr", - Name: Null, - Rule: true, - Chain: []Constraint{ - { - Target: "ptr", - Name: UniqueItems, - Rule: true, - Chain: nil, - }}} - require.Nil(t, validatePtr(reflect.ValueOf(&map[interface{}]string{1: "1", "1": "2"}), c)) -} - -func TestValidatePointer_MapInvalid(t *testing.T) { - z := map[interface{}]string{1: "1", "1": "2", 1.3: "2"} - var x interface{} = &z - c := Constraint{ - Target: "ptr", - Name: Null, - Rule: true, - Chain: []Constraint{{ - Target: "ptr", - Name: UniqueItems, - Rule: true, - Chain: nil, - }}, - } - require.Equal(t, strings.Contains(validatePtr(reflect.ValueOf(x), c).Error(), - fmt.Sprintf("all items in parameter %q must be unique;", c.Target)), true) -} - -type Child struct { - I string -} -type Product struct { - C *Child - Str *string - Name string - Arr *[]string - M *map[string]string - Num *int32 -} - -type Sample struct { - M *map[string]*string - Name string -} - -func TestValidatePointer_StructWithError(t *testing.T) { - s := "hello" - var x interface{} = &Product{ - C: &Child{"100"}, - Str: &s, - Name: "Gopher", - } - c := Constraint{ - "p", Null, "True", - []Constraint{ - {"C", Null, true, - []Constraint{ - {"I", MaxLength, 2, nil}, - }}, - {"Str", MaxLength, 2, nil}, - {"Name", MaxLength, 5, nil}, - }, - } - require.Equal(t, validatePtr(reflect.ValueOf(x), c).Error(), - createError(reflect.ValueOf("100"), c.Chain[0].Chain[0], - "value length must be less than 2").Error()) -} - -func TestValidatePointer_WithNilStruct(t *testing.T) { - var p *Product - var x interface{} = p - c := Constraint{ - "p", Null, true, - []Constraint{ - {"C", Null, true, - []Constraint{ - {"I", Empty, true, - []Constraint{ - {"I", MaxLength, 5, nil}, - }}, - }}, - {"Str", MaxLength, 2, nil}, - {"Name", MaxLength, 5, nil}, - }, - } - require.Equal(t, validatePtr(reflect.ValueOf(x), c).Error(), - createError(reflect.ValueOf(x), c, - fmt.Sprintf("value can not be null; required parameter")).Error()) -} - -func TestValidatePointer_StructWithNoError(t *testing.T) { - s := "hello" - var x interface{} = &Product{ - C: &Child{"100"}, - Str: &s, - Name: "Gopher", - } - c := Constraint{ - "p", Null, true, - []Constraint{ - {"C", Null, true, - []Constraint{ - {"I", Empty, true, - []Constraint{ - {"I", MaxLength, 5, nil}, - }}, - }}, - }, - } - require.Nil(t, validatePtr(reflect.ValueOf(x), c)) -} - -func TestValidateStruct_FieldNotExist(t *testing.T) { - s := "hello" - var x interface{} = Product{ - C: &Child{"100"}, - Str: &s, - Name: "Gopher", - } - c := Constraint{ - "C", Null, true, - []Constraint{ - {"Name", Empty, true, nil}, - }, - } - s = "Name" - require.Equal(t, validateStruct(reflect.ValueOf(x), c).Error(), - createError(reflect.ValueOf(Child{"100"}), c.Chain[0], - fmt.Sprintf("field %q doesn't exist", s)).Error()) -} - -func TestValidateStruct_WithChainConstraint(t *testing.T) { - s := "hello" - var x interface{} = Product{ - C: &Child{"100"}, - Str: &s, - Name: "Gopher", - } - c := Constraint{ - "C", Null, true, - []Constraint{ - {"I", Empty, true, - []Constraint{ - {"I", MaxLength, 2, nil}, - }}, - }, - } - require.Equal(t, validateStruct(reflect.ValueOf(x), c).Error(), - createError(reflect.ValueOf("100"), c.Chain[0].Chain[0], "value length must be less than 2").Error()) -} - -func TestValidateStruct_WithoutChainConstraint(t *testing.T) { - s := "hello" - var x interface{} = Product{ - C: &Child{""}, - Str: &s, - Name: "Gopher", - } - c := Constraint{"C", Null, true, - []Constraint{ - {"I", Empty, true, nil}, // throw error for Empty - }} - require.Equal(t, validateStruct(reflect.ValueOf(x), c).Error(), - createError(reflect.ValueOf(""), c.Chain[0], "value can not be null or empty; required parameter").Error()) -} - -func TestValidateStruct_WithArrayNull(t *testing.T) { - s := "hello" - var x interface{} = Product{ - C: &Child{""}, - Str: &s, - Name: "Gopher", - Arr: nil, - } - c := Constraint{"Arr", Null, true, - []Constraint{ - {"Arr", MaxItems, 4, nil}, - {"Arr", MinItems, 2, nil}, - }, - } - require.Equal(t, validateStruct(reflect.ValueOf(x), c).Error(), - createError(reflect.ValueOf(x.(Product).Arr), c, "value can not be null; required parameter").Error()) -} - -func TestValidateStruct_WithArrayEmptyError(t *testing.T) { - // arr := []string{} - var x interface{} = Product{ - Arr: &[]string{}, - } - c := Constraint{ - "Arr", Null, true, - []Constraint{ - {"Arr", Empty, true, nil}, - {"Arr", MaxItems, 4, nil}, - {"Arr", MinItems, 2, nil}, - }} - - require.Equal(t, validateStruct(reflect.ValueOf(x), c).Error(), - createError(reflect.ValueOf(*(x.(Product).Arr)), c.Chain[0], - fmt.Sprintf("value can not be null or empty; required parameter")).Error()) -} - -func TestValidateStruct_WithArrayEmptyWithoutError(t *testing.T) { - var x interface{} = Product{ - Arr: &[]string{}, - } - c := Constraint{ - "Arr", Null, true, - []Constraint{ - {"Arr", Empty, false, nil}, - {"Arr", MaxItems, 4, nil}, - }, - } - require.Nil(t, validateStruct(reflect.ValueOf(x), c)) -} - -func TestValidateStruct_ArrayWithError(t *testing.T) { - arr := []string{"1", "1"} - var x interface{} = Product{ - Arr: &arr, - } - c := Constraint{ - "Arr", Null, true, - []Constraint{ - {"Arr", Empty, true, nil}, - {"Arr", MaxItems, 4, nil}, - {"Arr", UniqueItems, true, nil}, - }, - } - s := "Arr" - require.Equal(t, validateStruct(reflect.ValueOf(x), c).Error(), - createError(reflect.ValueOf(*(x.(Product).Arr)), c.Chain[2], - fmt.Sprintf("all items in parameter %q must be unique; got:%v", s, *(x.(Product).Arr))).Error()) -} - -func TestValidateStruct_MapWithError(t *testing.T) { - m := map[string]string{ - "a": "hello", - "b": "hello", - } - var x interface{} = Product{ - M: &m, - } - c := Constraint{ - "M", Null, true, - []Constraint{ - {"M", Empty, true, nil}, - {"M", MaxItems, 4, nil}, - {"M", UniqueItems, true, nil}, - }, - } - - s := "M" - require.Equal(t, strings.Contains(validateStruct(reflect.ValueOf(x), c).Error(), - fmt.Sprintf("all items in parameter %q must be unique;", s)), true) -} - -func TestValidateStruct_MapWithNoError(t *testing.T) { - m := map[string]string{} - var x interface{} = Product{ - M: &m, - } - c := Constraint{ - "M", Null, true, - []Constraint{ - {"M", Empty, false, nil}, - {"M", MaxItems, 4, nil}, - }, - } - require.Nil(t, validateStruct(reflect.ValueOf(x), c)) -} - -func TestValidateStruct_MapNilNoError(t *testing.T) { - var m map[string]string - var x interface{} = Product{ - M: &m, - } - c := Constraint{ - "M", Null, false, - []Constraint{ - {"M", Empty, false, nil}, - {"M", MaxItems, 4, nil}, - }, - } - require.Nil(t, validateStruct(reflect.ValueOf(x), c)) -} - -func TestValidate_MapValidationWithError(t *testing.T) { - var x1 interface{} = &Product{ - Arr: &[]string{"1", "2"}, - M: &map[string]string{"a": "hello"}, - } - s := "hello" - var x2 interface{} = &Sample{ - M: &map[string]*string{"a": &s}, - } - v := []Validation{ - {x1, - []Constraint{{"x1", Null, true, - []Constraint{ - {"Arr", Null, true, - []Constraint{ - {"Arr", Empty, true, nil}, - {"Arr", MaxItems, 4, nil}, - {"Arr", UniqueItems, true, nil}, - }, - }, - {"M", Null, false, - []Constraint{ - {"M", Empty, false, nil}, - {"M", MinItems, 1, nil}, - {"M", UniqueItems, true, nil}, - }, - }, - }, - }}}, - {x2, - []Constraint{ - {"x2", Null, true, - []Constraint{ - {"M", Null, false, - []Constraint{ - {"M", Empty, false, nil}, - {"M", MinItems, 2, nil}, - {"M", UniqueItems, true, nil}, - }, - }, - }, - }, - {"Name", Empty, true, nil}, - }}, - } - - z := Validate(v).Error() - require.Equal(t, strings.Contains(z, "minimum item limit is 2; got: 1"), true) - require.Equal(t, strings.Contains(z, "MinItems"), true) -} - -func TestValidate_MapValidationWithoutError(t *testing.T) { - var x1 interface{} = &Product{ - Arr: &[]string{"1", "2"}, - M: &map[string]string{"a": "hello"}, - } - s := "hello" - var x2 interface{} = &Sample{ - M: &map[string]*string{"a": &s}, - } - v := []Validation{ - {x1, - []Constraint{{"x1", Null, true, - []Constraint{ - {"Arr", Null, true, - []Constraint{ - {"Arr", Empty, true, nil}, - {"Arr", MaxItems, 4, nil}, - {"Arr", UniqueItems, true, nil}, - }, - }, - {"M", Null, false, - []Constraint{ - {"M", Empty, false, nil}, - {"M", MinItems, 1, nil}, - {"M", UniqueItems, true, nil}, - }, - }, - }, - }}}, - {x2, - []Constraint{ - {"x2", Null, true, - []Constraint{ - {"M", Null, false, - []Constraint{ - {"M", Empty, false, nil}, - {"M", MinItems, 1, nil}, - {"M", UniqueItems, true, nil}, - }, - }, - }, - }, - {"Name", Empty, true, nil}, - }}, - } - require.Nil(t, Validate(v)) -} - -func TestValidate_UnknownType(t *testing.T) { - var c chan int - v := []Validation{ - {c, - []Constraint{{"c", Null, true, nil}}}, - } - require.Equal(t, Validate(v).Error(), - createError(reflect.ValueOf(c), v[0].Constraints[0], - fmt.Sprintf("unknown type %v", reflect.ValueOf(c).Kind())).Error()) -} - -func TestValidate_example1(t *testing.T) { - var x1 interface{} = Product{ - Arr: &[]string{"1", "1"}, - M: &map[string]string{"a": "hello"}, - } - s := "hello" - var x2 interface{} = Sample{ - M: &map[string]*string{"a": &s}, - } - v := []Validation{ - {x1, - []Constraint{{"Arr", Null, true, - []Constraint{ - {"Arr", Empty, true, nil}, - {"Arr", MaxItems, 4, nil}, - {"Arr", UniqueItems, true, nil}, - }}, - {"M", Null, false, - []Constraint{ - {"M", Empty, false, nil}, - {"M", MinItems, 1, nil}, - {"M", UniqueItems, true, nil}, - }, - }, - }}, - {x2, - []Constraint{ - {"M", Null, false, - []Constraint{ - {"M", Empty, false, nil}, - {"M", MinItems, 1, nil}, - {"M", UniqueItems, true, nil}, - }, - }, - {"Name", Empty, true, nil}, - }}, - } - s = "Arr" - require.Equal(t, Validate(v).Error(), - createError(reflect.ValueOf([]string{"1", "1"}), v[0].Constraints[0].Chain[2], - fmt.Sprintf("all items in parameter %q must be unique; got:%v", s, []string{"1", "1"})).Error()) -} - -func TestValidate_Int(t *testing.T) { - n := int32(100) - v := []Validation{ - {n, - []Constraint{ - {"n", MultipleOf, 10, nil}, - {"n", ExclusiveMinimum, 100, nil}, - }, - }, - } - require.Equal(t, Validate(v).Error(), - createError(reflect.ValueOf(n), v[0].Constraints[1], - "value must be greater than 100").Error()) -} - -func TestValidate_IntPointer(t *testing.T) { - n := int32(100) - p := &n - v := []Validation{ - {p, - []Constraint{ - {"p", Null, true, []Constraint{ - {"p", ExclusiveMinimum, 100, nil}, - }}, - }, - }, - } - require.Equal(t, Validate(v).Error(), - createError(reflect.ValueOf(n), v[0].Constraints[0].Chain[0], - "value must be greater than 100").Error()) - - // required paramter - p = nil - v = []Validation{ - {p, - []Constraint{ - {"p", Null, true, []Constraint{ - {"p", ExclusiveMinimum, 100, nil}, - }}, - }, - }, - } - require.Equal(t, Validate(v).Error(), - createError(reflect.ValueOf(v[0].TargetValue), v[0].Constraints[0], - "value can not be null; required parameter").Error()) - - // Not required - p = nil - v = []Validation{ - {p, - []Constraint{ - {"p", Null, false, []Constraint{ - {"p", ExclusiveMinimum, 100, nil}, - }}, - }, - }, - } - require.Nil(t, Validate(v)) -} - -func TestValidate_IntStruct(t *testing.T) { - n := int32(100) - p := &Product{ - Num: &n, - } - - v := []Validation{ - {p, []Constraint{{"p", Null, true, - []Constraint{ - {"Num", Null, true, []Constraint{ - {"Num", ExclusiveMinimum, 100, nil}, - }}, - }, - }}}, - } - require.Equal(t, Validate(v).Error(), - createError(reflect.ValueOf(n), v[0].Constraints[0].Chain[0].Chain[0], - "value must be greater than 100").Error()) - - // required paramter - p = &Product{} - v = []Validation{ - {p, []Constraint{{"p", Null, true, - []Constraint{ - {"p.Num", Null, true, []Constraint{ - {"p.Num", ExclusiveMinimum, 100, nil}, - }}, - }, - }}}, - } - require.Equal(t, Validate(v).Error(), - createError(reflect.ValueOf(p.Num), v[0].Constraints[0].Chain[0], - "value can not be null; required parameter").Error()) - - // Not required - p = &Product{} - v = []Validation{ - {p, []Constraint{{"p", Null, true, - []Constraint{ - {"Num", Null, false, []Constraint{ - {"Num", ExclusiveMinimum, 100, nil}, - }}, - }, - }}}, - } - require.Nil(t, Validate(v)) - - // Parent not required - p = nil - v = []Validation{ - {p, []Constraint{{"p", Null, false, - []Constraint{ - {"Num", Null, false, []Constraint{ - {"Num", ExclusiveMinimum, 100, nil}, - }}, - }, - }}}, - } - require.Nil(t, Validate(v)) -} - -func TestValidate_String(t *testing.T) { - s := "hello" - v := []Validation{ - {s, - []Constraint{ - {"s", Empty, true, nil}, - {"s", Empty, true, - []Constraint{{"s", MaxLength, 3, nil}}}, - }, - }, - } - require.Equal(t, Validate(v).Error(), - createError(reflect.ValueOf(s), v[0].Constraints[1].Chain[0], - "value length must be less than 3").Error()) - - // required paramter - s = "" - v = []Validation{ - {s, - []Constraint{ - {"s", Empty, true, nil}, - {"s", Empty, true, - []Constraint{{"s", MaxLength, 3, nil}}}, - }, - }, - } - require.Equal(t, Validate(v).Error(), - createError(reflect.ValueOf(s), v[0].Constraints[1], - "value can not be null or empty; required parameter").Error()) - - // not required paramter - s = "" - v = []Validation{ - {s, - []Constraint{ - {"s", Empty, false, nil}, - {"s", Empty, false, - []Constraint{{"s", MaxLength, 3, nil}}}, - }, - }, - } - require.Nil(t, Validate(v)) -} - -func TestValidate_StringStruct(t *testing.T) { - s := "hello" - p := &Product{ - Str: &s, - } - - v := []Validation{ - {p, []Constraint{{"p", Null, true, - []Constraint{ - {"p.Str", Null, true, []Constraint{ - {"p.Str", Empty, true, nil}, - {"p.Str", MaxLength, 3, nil}, - }}, - }, - }}}, - } - // e := ValidationError{ - // Constraint: MaxLength, - // Target: "Str", - // TargetValue: s, - // Details: fmt.Sprintf("value length must be less than 3", s), - // } - // if z := Validate(v); !reflect.DeepEqual(e, z) { - // t.Fatalf("autorest/validation: Validate failed to return error \nexpect: %v\ngot: %v", e, z) - // } - require.Equal(t, Validate(v).Error(), - createError(reflect.ValueOf(s), v[0].Constraints[0].Chain[0].Chain[1], - "value length must be less than 3").Error()) - - // required paramter - can't be Empty - s = "" - p = &Product{ - Str: &s, - } - v = []Validation{ - {p, []Constraint{{"p", Null, true, - []Constraint{ - {"Str", Null, true, []Constraint{ - {"Str", Empty, true, nil}, - {"Str", MaxLength, 3, nil}, - }}, - }, - }}}, - } - require.Equal(t, Validate(v).Error(), - createError(reflect.ValueOf(s), v[0].Constraints[0].Chain[0].Chain[0], - "value can not be null or empty; required parameter").Error()) - - // required paramter - can't be null - p = &Product{} - v = []Validation{ - {p, []Constraint{{"p", Null, true, - []Constraint{ - {"p.Str", Null, true, []Constraint{ - {"p.Str", Empty, true, nil}, - {"p.Str", MaxLength, 3, nil}, - }}, - }, - }}}, - } - require.Equal(t, Validate(v).Error(), - createError(reflect.ValueOf(p.Str), v[0].Constraints[0].Chain[0], - "value can not be null; required parameter").Error()) - - // Not required - p = &Product{} - v = []Validation{ - {p, []Constraint{{"p", Null, true, - []Constraint{ - {"Str", Null, false, []Constraint{ - {"Str", Empty, true, nil}, - {"Str", MaxLength, 3, nil}, - }}, - }, - }}}, - } - require.Nil(t, Validate(v)) - - // Parent not required - p = nil - v = []Validation{ - {p, []Constraint{{"p", Null, false, - []Constraint{ - {"Str", Null, true, []Constraint{ - {"Str", Empty, true, nil}, - {"Str", MaxLength, 3, nil}, - }}, - }, - }}}, - } - require.Nil(t, Validate(v)) -} - -func TestValidate_Array(t *testing.T) { - s := []string{"hello"} - v := []Validation{ - {s, - []Constraint{ - {"s", Null, true, - []Constraint{ - {"s", Empty, true, nil}, - {"s", MinItems, 2, nil}, - }}, - }, - }, - } - require.Equal(t, Validate(v).Error(), - createError(reflect.ValueOf(s), v[0].Constraints[0].Chain[1], - fmt.Sprintf("minimum item limit is 2; got: %v", len(s))).Error()) - - // Empty array - v = []Validation{ - {[]string{}, - []Constraint{ - {"s", Null, true, - []Constraint{ - {"s", Empty, true, nil}, - {"s", MinItems, 2, nil}}}, - }, - }, - } - require.Equal(t, Validate(v).Error(), - createError(reflect.ValueOf([]string{}), v[0].Constraints[0].Chain[0], - "value can not be null or empty; required parameter").Error()) - - // null array - var s1 []string - v = []Validation{ - {s1, - []Constraint{ - {"s1", Null, true, - []Constraint{ - {"s1", Empty, true, nil}, - {"s1", MinItems, 2, nil}}}, - }, - }, - } - require.Equal(t, Validate(v).Error(), - createError(reflect.ValueOf(s1), v[0].Constraints[0], - "value can not be null; required parameter").Error()) - - // not required paramter - v = []Validation{ - {s1, - []Constraint{ - {"s1", Null, false, - []Constraint{ - {"s1", Empty, true, nil}, - {"s1", MinItems, 2, nil}}}, - }, - }, - } - require.Nil(t, Validate(v)) -} - -func TestValidate_ArrayPointer(t *testing.T) { - s := []string{"hello"} - v := []Validation{ - {&s, - []Constraint{ - {"s", Null, true, - []Constraint{ - {"s", Empty, true, nil}, - {"s", MinItems, 2, nil}, - }}, - }, - }, - } - require.Equal(t, Validate(v).Error(), - createError(reflect.ValueOf(s), v[0].Constraints[0].Chain[1], - fmt.Sprintf("minimum item limit is 2; got: %v", len(s))).Error()) - - // Empty array - v = []Validation{ - {&[]string{}, - []Constraint{ - {"s", Null, true, - []Constraint{ - {"s", Empty, true, nil}, - {"s", MinItems, 2, nil}}}, - }, - }, - } - require.Equal(t, Validate(v).Error(), - createError(reflect.ValueOf([]string{}), v[0].Constraints[0].Chain[0], - "value can not be null or empty; required parameter").Error()) - - // null array - var s1 *[]string - v = []Validation{ - {s1, - []Constraint{ - {"s1", Null, true, - []Constraint{ - {"s1", Empty, true, nil}, - {"s1", MinItems, 2, nil}}}, - }, - }, - } - require.Equal(t, Validate(v).Error(), - createError(reflect.ValueOf(s1), v[0].Constraints[0], - "value can not be null; required parameter").Error()) - - // not required paramter - v = []Validation{ - {s1, - []Constraint{ - {"s1", Null, false, - []Constraint{ - {"s1", Empty, true, nil}, - {"s1", MinItems, 2, nil}}}, - }, - }, - } - require.Nil(t, Validate(v)) -} - -func TestValidate_ArrayInStruct(t *testing.T) { - s := []string{"hello"} - p := &Product{ - Arr: &s, - } - - v := []Validation{ - {p, []Constraint{{"p", Null, true, - []Constraint{ - {"p.Arr", Null, true, []Constraint{ - {"p.Arr", Empty, true, nil}, - {"p.Arr", MinItems, 2, nil}, - }}, - }, - }}}, - } - require.Equal(t, Validate(v).Error(), - createError(reflect.ValueOf(s), v[0].Constraints[0].Chain[0].Chain[1], - fmt.Sprintf("minimum item limit is 2; got: %v", len(s))).Error()) - - // required paramter - can't be Empty - p = &Product{ - Arr: &[]string{}, - } - v = []Validation{ - {p, []Constraint{{"p", Null, true, - []Constraint{ - {"p.Arr", Null, true, []Constraint{ - {"p.Arr", Empty, true, nil}, - {"p.Arr", MinItems, 2, nil}, - }}, - }, - }}}, - } - require.Equal(t, Validate(v).Error(), - createError(reflect.ValueOf([]string{}), v[0].Constraints[0].Chain[0].Chain[0], - "value can not be null or empty; required parameter").Error()) - - // required paramter - can't be null - p = &Product{} - v = []Validation{ - {p, []Constraint{{"p", Null, true, - []Constraint{ - {"p.Arr", Null, true, []Constraint{ - {"p.Arr", Empty, true, nil}, - {"p.Arr", MinItems, 2, nil}, - }}, - }, - }}}, - } - require.Equal(t, Validate(v).Error(), - createError(reflect.ValueOf(p.Arr), v[0].Constraints[0].Chain[0], - "value can not be null; required parameter").Error()) - - // Not required - v = []Validation{ - {&Product{}, []Constraint{{"p", Null, true, - []Constraint{ - {"Arr", Null, false, []Constraint{ - {"Arr", Empty, true, nil}, - {"Arr", MinItems, 2, nil}, - }}, - }, - }}}, - } - require.Nil(t, Validate(v)) - - // Parent not required - p = nil - v = []Validation{ - {p, []Constraint{{"p", Null, false, - []Constraint{ - {"Arr", Null, true, []Constraint{ - {"Arr", Empty, true, nil}, - {"Arr", MinItems, 2, nil}, - }}, - }, - }}}, - } - require.Nil(t, Validate(v)) -} - -func TestValidate_StructInStruct(t *testing.T) { - p := &Product{ - C: &Child{I: "hello"}, - } - v := []Validation{ - {p, []Constraint{{"p", Null, true, - []Constraint{{"C", Null, true, - []Constraint{{"I", MinLength, 7, nil}}}, - }, - }}}, - } - require.Equal(t, Validate(v).Error(), - createError(reflect.ValueOf(p.C.I), v[0].Constraints[0].Chain[0].Chain[0], - "value length must be greater than 7").Error()) - - // required paramter - can't be Empty - p = &Product{ - C: &Child{I: ""}, - } - - v = []Validation{ - {p, []Constraint{{"p", Null, true, - []Constraint{{"C", Null, true, - []Constraint{{"I", Empty, true, nil}}}, - }, - }}}, - } - require.Equal(t, Validate(v).Error(), - createError(reflect.ValueOf(p.C.I), v[0].Constraints[0].Chain[0].Chain[0], - "value can not be null or empty; required parameter").Error()) - - // required paramter - can't be null - p = &Product{} - v = []Validation{ - {p, []Constraint{{"p", Null, true, - []Constraint{{"C", Null, true, - []Constraint{{"I", Empty, true, nil}}}, - }, - }}}, - } - require.Equal(t, Validate(v).Error(), - createError(reflect.ValueOf(p.C), v[0].Constraints[0].Chain[0], - "value can not be null; required parameter").Error()) - - // Not required - v = []Validation{ - {&Product{}, []Constraint{{"p", Null, true, - []Constraint{{"p.C", Null, false, - []Constraint{{"p.C.I", Empty, true, nil}}}, - }, - }}}, - } - require.Nil(t, Validate(v)) - - // Parent not required - p = nil - v = []Validation{ - {p, []Constraint{{"p", Null, false, - []Constraint{{"p.C", Null, false, - []Constraint{{"p.C.I", Empty, true, nil}}}, - }, - }}}, - } - require.Nil(t, Validate(v)) -} - -func TestNewErrorWithValidationError(t *testing.T) { - p := &Product{} - v := []Validation{ - {p, []Constraint{{"p", Null, true, - []Constraint{{"p.C", Null, true, - []Constraint{{"p.C.I", Empty, true, nil}}}, - }, - }}}, - } - err := createError(reflect.ValueOf(p.C), v[0].Constraints[0].Chain[0], "value can not be null; required parameter") - z := fmt.Sprintf("batch.AccountClient#Create: Invalid input: %s", - err.Error()) - require.Equal(t, NewErrorWithValidationError(err, "batch.AccountClient", "Create").Error(), z) -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/version_test.go b/vendor/github.com/Azure/go-autorest/autorest/version_test.go deleted file mode 100644 index 14925fe4e..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/version_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package autorest - -import ( - "testing" -) - -func TestVersion(t *testing.T) { - v := "7.0.0" - if Version() != v { - t.Fatalf("autorest: Version failed to return the expected version -- expected %s, received %s", - v, Version()) - } -} diff --git a/vendor/github.com/Azure/go-autorest/glide.lock b/vendor/github.com/Azure/go-autorest/glide.lock deleted file mode 100644 index ac8b791e6..000000000 --- a/vendor/github.com/Azure/go-autorest/glide.lock +++ /dev/null @@ -1,40 +0,0 @@ -hash: 51202aefdfe9c4a992f96ab58f6cacf21cdbd1b66efe955c9030bca736ac816d -updated: 2016-10-25T10:45:46.536665-07:00 -imports: -- name: github.com/dgrijalva/jwt-go - version: 24c63f56522a87ec5339cc3567883f1039378fdb - subpackages: - - . -- name: golang.org/x/crypto - version: d3c1194e7ce73913451befd89c26ca6d222f641e - repo: https://github.com/golang/crypto.git - vcs: git - subpackages: - - pkcs12 - - pkcs12/internal/rc2 -- name: golang.org/x/net - version: 65dfc08770ce66f74becfdff5f8ab01caef4e946 - repo: https://github.com/golang/net.git - vcs: git - subpackages: - - . -- name: golang.org/x/text - version: 16e1d1f27f7aba51c74c0aeb7a7ee31a75c5c63c - repo: https://github.com/golang/text.git - vcs: git - subpackages: - - . -testImports: -- name: github.com/davecgh/go-spew - version: 5215b55f46b2b919f50a1df0eaa5886afe4e3b3d - subpackages: - - spew -- name: github.com/pmezard/go-difflib - version: d8ed2627bdf02c080bf22230dbb337003b7aba2d - subpackages: - - difflib -- name: github.com/stretchr/testify - version: d77da356e56a7428ad25149ca77381849a6a5232 - subpackages: - - require - - assert diff --git a/vendor/github.com/Azure/go-autorest/glide.yaml b/vendor/github.com/Azure/go-autorest/glide.yaml deleted file mode 100644 index e26b4a156..000000000 --- a/vendor/github.com/Azure/go-autorest/glide.yaml +++ /dev/null @@ -1,26 +0,0 @@ -package: github.com/Azure/go-autorest -import: -- package: github.com/dgrijalva/jwt-go - subpackages: - - . -- package: golang.org/x/crypto - vcs: git - repo: https://github.com/golang/crypto.git - subpackages: - - /pkcs12 -- package: golang.org/x/net - vcs: git - repo: https://github.com/golang/net.git - subpackages: - - . -- package: golang.org/x/text - vcs: git - repo: https://github.com/golang/text.git - subpackages: - - . -testImports: -- package: github.com/stretchr/testify - vcs: git - repo: https://github.com/stretchr/testify.git - subpackages: - - /require diff --git a/vendor/github.com/PuerkitoBio/purell/.gitignore b/vendor/github.com/PuerkitoBio/purell/.gitignore deleted file mode 100644 index 748e4c807..000000000 --- a/vendor/github.com/PuerkitoBio/purell/.gitignore +++ /dev/null @@ -1,5 +0,0 @@ -*.sublime-* -.DS_Store -*.swp -*.swo -tags diff --git a/vendor/github.com/PuerkitoBio/purell/.travis.yml b/vendor/github.com/PuerkitoBio/purell/.travis.yml deleted file mode 100644 index facfc91c6..000000000 --- a/vendor/github.com/PuerkitoBio/purell/.travis.yml +++ /dev/null @@ -1,7 +0,0 @@ -language: go - -go: - - 1.4 - - 1.5 - - 1.6 - - tip diff --git a/vendor/github.com/PuerkitoBio/purell/README.md b/vendor/github.com/PuerkitoBio/purell/README.md deleted file mode 100644 index 09e8a32cb..000000000 --- a/vendor/github.com/PuerkitoBio/purell/README.md +++ /dev/null @@ -1,187 +0,0 @@ -# Purell - -Purell is a tiny Go library to normalize URLs. It returns a pure URL. Pure-ell. Sanitizer and all. Yeah, I know... - -Based on the [wikipedia paper][wiki] and the [RFC 3986 document][rfc]. - -[![build status](https://secure.travis-ci.org/PuerkitoBio/purell.png)](http://travis-ci.org/PuerkitoBio/purell) - -## Install - -`go get github.com/PuerkitoBio/purell` - -## Changelog - -* **2016-11-14 (v1.1.0)** : IDN: Conform to RFC 5895: Fold character width (thanks to @beeker1121). -* **2016-07-27 (v1.0.0)** : Normalize IDN to ASCII (thanks to @zenovich). -* **2015-02-08** : Add fix for relative paths issue ([PR #5][pr5]) and add fix for unnecessary encoding of reserved characters ([see issue #7][iss7]). -* **v0.2.0** : Add benchmarks, Attempt IDN support. -* **v0.1.0** : Initial release. - -## Examples - -From `example_test.go` (note that in your code, you would import "github.com/PuerkitoBio/purell", and would prefix references to its methods and constants with "purell."): - -```go -package purell - -import ( - "fmt" - "net/url" -) - -func ExampleNormalizeURLString() { - if normalized, err := NormalizeURLString("hTTp://someWEBsite.com:80/Amazing%3f/url/", - FlagLowercaseScheme|FlagLowercaseHost|FlagUppercaseEscapes); err != nil { - panic(err) - } else { - fmt.Print(normalized) - } - // Output: http://somewebsite.com:80/Amazing%3F/url/ -} - -func ExampleMustNormalizeURLString() { - normalized := MustNormalizeURLString("hTTpS://someWEBsite.com:443/Amazing%fa/url/", - FlagsUnsafeGreedy) - fmt.Print(normalized) - - // Output: http://somewebsite.com/Amazing%FA/url -} - -func ExampleNormalizeURL() { - if u, err := url.Parse("Http://SomeUrl.com:8080/a/b/.././c///g?c=3&a=1&b=9&c=0#target"); err != nil { - panic(err) - } else { - normalized := NormalizeURL(u, FlagsUsuallySafeGreedy|FlagRemoveDuplicateSlashes|FlagRemoveFragment) - fmt.Print(normalized) - } - - // Output: http://someurl.com:8080/a/c/g?c=3&a=1&b=9&c=0 -} -``` - -## API - -As seen in the examples above, purell offers three methods, `NormalizeURLString(string, NormalizationFlags) (string, error)`, `MustNormalizeURLString(string, NormalizationFlags) (string)` and `NormalizeURL(*url.URL, NormalizationFlags) (string)`. They all normalize the provided URL based on the specified flags. Here are the available flags: - -```go -const ( - // Safe normalizations - FlagLowercaseScheme NormalizationFlags = 1 << iota // HTTP://host -> http://host, applied by default in Go1.1 - FlagLowercaseHost // http://HOST -> http://host - FlagUppercaseEscapes // http://host/t%ef -> http://host/t%EF - FlagDecodeUnnecessaryEscapes // http://host/t%41 -> http://host/tA - FlagEncodeNecessaryEscapes // http://host/!"#$ -> http://host/%21%22#$ - FlagRemoveDefaultPort // http://host:80 -> http://host - FlagRemoveEmptyQuerySeparator // http://host/path? -> http://host/path - - // Usually safe normalizations - FlagRemoveTrailingSlash // http://host/path/ -> http://host/path - FlagAddTrailingSlash // http://host/path -> http://host/path/ (should choose only one of these add/remove trailing slash flags) - FlagRemoveDotSegments // http://host/path/./a/b/../c -> http://host/path/a/c - - // Unsafe normalizations - FlagRemoveDirectoryIndex // http://host/path/index.html -> http://host/path/ - FlagRemoveFragment // http://host/path#fragment -> http://host/path - FlagForceHTTP // https://host -> http://host - FlagRemoveDuplicateSlashes // http://host/path//a///b -> http://host/path/a/b - FlagRemoveWWW // http://www.host/ -> http://host/ - FlagAddWWW // http://host/ -> http://www.host/ (should choose only one of these add/remove WWW flags) - FlagSortQuery // http://host/path?c=3&b=2&a=1&b=1 -> http://host/path?a=1&b=1&b=2&c=3 - - // Normalizations not in the wikipedia article, required to cover tests cases - // submitted by jehiah - FlagDecodeDWORDHost // http://1113982867 -> http://66.102.7.147 - FlagDecodeOctalHost // http://0102.0146.07.0223 -> http://66.102.7.147 - FlagDecodeHexHost // http://0x42660793 -> http://66.102.7.147 - FlagRemoveUnnecessaryHostDots // http://.host../path -> http://host/path - FlagRemoveEmptyPortSeparator // http://host:/path -> http://host/path - - // Convenience set of safe normalizations - FlagsSafe NormalizationFlags = FlagLowercaseHost | FlagLowercaseScheme | FlagUppercaseEscapes | FlagDecodeUnnecessaryEscapes | FlagEncodeNecessaryEscapes | FlagRemoveDefaultPort | FlagRemoveEmptyQuerySeparator - - // For convenience sets, "greedy" uses the "remove trailing slash" and "remove www. prefix" flags, - // while "non-greedy" uses the "add (or keep) the trailing slash" and "add www. prefix". - - // Convenience set of usually safe normalizations (includes FlagsSafe) - FlagsUsuallySafeGreedy NormalizationFlags = FlagsSafe | FlagRemoveTrailingSlash | FlagRemoveDotSegments - FlagsUsuallySafeNonGreedy NormalizationFlags = FlagsSafe | FlagAddTrailingSlash | FlagRemoveDotSegments - - // Convenience set of unsafe normalizations (includes FlagsUsuallySafe) - FlagsUnsafeGreedy NormalizationFlags = FlagsUsuallySafeGreedy | FlagRemoveDirectoryIndex | FlagRemoveFragment | FlagForceHTTP | FlagRemoveDuplicateSlashes | FlagRemoveWWW | FlagSortQuery - FlagsUnsafeNonGreedy NormalizationFlags = FlagsUsuallySafeNonGreedy | FlagRemoveDirectoryIndex | FlagRemoveFragment | FlagForceHTTP | FlagRemoveDuplicateSlashes | FlagAddWWW | FlagSortQuery - - // Convenience set of all available flags - FlagsAllGreedy = FlagsUnsafeGreedy | FlagDecodeDWORDHost | FlagDecodeOctalHost | FlagDecodeHexHost | FlagRemoveUnnecessaryHostDots | FlagRemoveEmptyPortSeparator - FlagsAllNonGreedy = FlagsUnsafeNonGreedy | FlagDecodeDWORDHost | FlagDecodeOctalHost | FlagDecodeHexHost | FlagRemoveUnnecessaryHostDots | FlagRemoveEmptyPortSeparator -) -``` - -For convenience, the set of flags `FlagsSafe`, `FlagsUsuallySafe[Greedy|NonGreedy]`, `FlagsUnsafe[Greedy|NonGreedy]` and `FlagsAll[Greedy|NonGreedy]` are provided for the similarly grouped normalizations on [wikipedia's URL normalization page][wiki]. You can add (using the bitwise OR `|` operator) or remove (using the bitwise AND NOT `&^` operator) individual flags from the sets if required, to build your own custom set. - -The [full godoc reference is available on gopkgdoc][godoc]. - -Some things to note: - -* `FlagDecodeUnnecessaryEscapes`, `FlagEncodeNecessaryEscapes`, `FlagUppercaseEscapes` and `FlagRemoveEmptyQuerySeparator` are always implicitly set, because internally, the URL string is parsed as an URL object, which automatically decodes unnecessary escapes, uppercases and encodes necessary ones, and removes empty query separators (an unnecessary `?` at the end of the url). So this operation cannot **not** be done. For this reason, `FlagRemoveEmptyQuerySeparator` (as well as the other three) has been included in the `FlagsSafe` convenience set, instead of `FlagsUnsafe`, where Wikipedia puts it. - -* The `FlagDecodeUnnecessaryEscapes` decodes the following escapes (*from -> to*): - - %24 -> $ - - %26 -> & - - %2B-%3B -> +,-./0123456789:; - - %3D -> = - - %40-%5A -> @ABCDEFGHIJKLMNOPQRSTUVWXYZ - - %5F -> _ - - %61-%7A -> abcdefghijklmnopqrstuvwxyz - - %7E -> ~ - - -* When the `NormalizeURL` function is used (passing an URL object), this source URL object is modified (that is, after the call, the URL object will be modified to reflect the normalization). - -* The *replace IP with domain name* normalization (`http://208.77.188.166/ → http://www.example.com/`) is obviously not possible for a library without making some network requests. This is not implemented in purell. - -* The *remove unused query string parameters* and *remove default query parameters* are also not implemented, since this is a very case-specific normalization, and it is quite trivial to do with an URL object. - -### Safe vs Usually Safe vs Unsafe - -Purell allows you to control the level of risk you take while normalizing an URL. You can aggressively normalize, play it totally safe, or anything in between. - -Consider the following URL: - -`HTTPS://www.RooT.com/toto/t%45%1f///a/./b/../c/?z=3&w=2&a=4&w=1#invalid` - -Normalizing with the `FlagsSafe` gives: - -`https://www.root.com/toto/tE%1F///a/./b/../c/?z=3&w=2&a=4&w=1#invalid` - -With the `FlagsUsuallySafeGreedy`: - -`https://www.root.com/toto/tE%1F///a/c?z=3&w=2&a=4&w=1#invalid` - -And with `FlagsUnsafeGreedy`: - -`http://root.com/toto/tE%1F/a/c?a=4&w=1&w=2&z=3` - -## TODOs - -* Add a class/default instance to allow specifying custom directory index names? At the moment, removing directory index removes `(^|/)((?:default|index)\.\w{1,4})$`. - -## Thanks / Contributions - -@rogpeppe -@jehiah -@opennota -@pchristopher1275 -@zenovich -@beeker1121 - -## License - -The [BSD 3-Clause license][bsd]. - -[bsd]: http://opensource.org/licenses/BSD-3-Clause -[wiki]: http://en.wikipedia.org/wiki/URL_normalization -[rfc]: http://tools.ietf.org/html/rfc3986#section-6 -[godoc]: http://go.pkgdoc.org/github.com/PuerkitoBio/purell -[pr5]: https://github.com/PuerkitoBio/purell/pull/5 -[iss7]: https://github.com/PuerkitoBio/purell/issues/7 diff --git a/vendor/github.com/PuerkitoBio/purell/bench_test.go b/vendor/github.com/PuerkitoBio/purell/bench_test.go deleted file mode 100644 index 7549731fc..000000000 --- a/vendor/github.com/PuerkitoBio/purell/bench_test.go +++ /dev/null @@ -1,57 +0,0 @@ -package purell - -import ( - "testing" -) - -var ( - safeUrl = "HttPS://..iaMHost..Test:443/paTh^A%ef//./%41PaTH/..//?" - usuallySafeUrl = "HttPS://..iaMHost..Test:443/paTh^A%ef//./%41PaTH/../final/" - unsafeUrl = "HttPS://..www.iaMHost..Test:443/paTh^A%ef//./%41PaTH/../final/index.html?t=val1&a=val4&z=val5&a=val1#fragment" - allDWORDUrl = "HttPS://1113982867:/paTh^A%ef//./%41PaTH/../final/index.html?t=val1&a=val4&z=val5&a=val1#fragment" - allOctalUrl = "HttPS://0102.0146.07.0223:/paTh^A%ef//./%41PaTH/../final/index.html?t=val1&a=val4&z=val5&a=val1#fragment" - allHexUrl = "HttPS://0x42660793:/paTh^A%ef//./%41PaTH/../final/index.html?t=val1&a=val4&z=val5&a=val1#fragment" - allCombinedUrl = "HttPS://..0x42660793.:/paTh^A%ef//./%41PaTH/../final/index.html?t=val1&a=val4&z=val5&a=val1#fragment" -) - -func BenchmarkSafe(b *testing.B) { - for i := 0; i < b.N; i++ { - NormalizeURLString(safeUrl, FlagsSafe) - } -} - -func BenchmarkUsuallySafe(b *testing.B) { - for i := 0; i < b.N; i++ { - NormalizeURLString(usuallySafeUrl, FlagsUsuallySafeGreedy) - } -} - -func BenchmarkUnsafe(b *testing.B) { - for i := 0; i < b.N; i++ { - NormalizeURLString(unsafeUrl, FlagsUnsafeGreedy) - } -} - -func BenchmarkAllDWORD(b *testing.B) { - for i := 0; i < b.N; i++ { - NormalizeURLString(allDWORDUrl, FlagsAllGreedy) - } -} - -func BenchmarkAllOctal(b *testing.B) { - for i := 0; i < b.N; i++ { - NormalizeURLString(allOctalUrl, FlagsAllGreedy) - } -} - -func BenchmarkAllHex(b *testing.B) { - for i := 0; i < b.N; i++ { - NormalizeURLString(allHexUrl, FlagsAllGreedy) - } -} - -func BenchmarkAllCombined(b *testing.B) { - for i := 0; i < b.N; i++ { - NormalizeURLString(allCombinedUrl, FlagsAllGreedy) - } -} diff --git a/vendor/github.com/PuerkitoBio/purell/example_test.go b/vendor/github.com/PuerkitoBio/purell/example_test.go deleted file mode 100644 index 997b95369..000000000 --- a/vendor/github.com/PuerkitoBio/purell/example_test.go +++ /dev/null @@ -1,35 +0,0 @@ -package purell - -import ( - "fmt" - "net/url" -) - -func ExampleNormalizeURLString() { - if normalized, err := NormalizeURLString("hTTp://someWEBsite.com:80/Amazing%3f/url/", - FlagLowercaseScheme|FlagLowercaseHost|FlagUppercaseEscapes); err != nil { - panic(err) - } else { - fmt.Print(normalized) - } - // Output: http://somewebsite.com:80/Amazing%3F/url/ -} - -func ExampleMustNormalizeURLString() { - normalized := MustNormalizeURLString("hTTpS://someWEBsite.com:443/Amazing%fa/url/", - FlagsUnsafeGreedy) - fmt.Print(normalized) - - // Output: http://somewebsite.com/Amazing%FA/url -} - -func ExampleNormalizeURL() { - if u, err := url.Parse("Http://SomeUrl.com:8080/a/b/.././c///g?c=3&a=1&b=9&c=0#target"); err != nil { - panic(err) - } else { - normalized := NormalizeURL(u, FlagsUsuallySafeGreedy|FlagRemoveDuplicateSlashes|FlagRemoveFragment) - fmt.Print(normalized) - } - - // Output: http://someurl.com:8080/a/c/g?c=3&a=1&b=9&c=0 -} diff --git a/vendor/github.com/PuerkitoBio/purell/purell_test.go b/vendor/github.com/PuerkitoBio/purell/purell_test.go deleted file mode 100644 index a3732e5a3..000000000 --- a/vendor/github.com/PuerkitoBio/purell/purell_test.go +++ /dev/null @@ -1,768 +0,0 @@ -package purell - -import ( - "fmt" - "net/url" - "testing" -) - -type testCase struct { - nm string - src string - flgs NormalizationFlags - res string - parsed bool -} - -var ( - cases = [...]*testCase{ - &testCase{ - "LowerScheme", - "HTTP://www.SRC.ca", - FlagLowercaseScheme, - "http://www.SRC.ca", - false, - }, - &testCase{ - "LowerScheme2", - "http://www.SRC.ca", - FlagLowercaseScheme, - "http://www.SRC.ca", - false, - }, - &testCase{ - "LowerHost", - "HTTP://www.SRC.ca/", - FlagLowercaseHost, - "http://www.src.ca/", // Since Go1.1, scheme is automatically lowercased - false, - }, - &testCase{ - "UpperEscapes", - `http://www.whatever.com/Some%aa%20Special%8Ecases/`, - FlagUppercaseEscapes, - "http://www.whatever.com/Some%AA%20Special%8Ecases/", - false, - }, - &testCase{ - "UnnecessaryEscapes", - `http://www.toto.com/%41%42%2E%44/%32%33%52%2D/%5f%7E`, - FlagDecodeUnnecessaryEscapes, - "http://www.toto.com/AB.D/23R-/_~", - false, - }, - &testCase{ - "RemoveDefaultPort", - "HTTP://www.SRC.ca:80/", - FlagRemoveDefaultPort, - "http://www.SRC.ca/", // Since Go1.1, scheme is automatically lowercased - false, - }, - &testCase{ - "RemoveDefaultPort2", - "HTTP://www.SRC.ca:80", - FlagRemoveDefaultPort, - "http://www.SRC.ca", // Since Go1.1, scheme is automatically lowercased - false, - }, - &testCase{ - "RemoveDefaultPort3", - "HTTP://www.SRC.ca:8080", - FlagRemoveDefaultPort, - "http://www.SRC.ca:8080", // Since Go1.1, scheme is automatically lowercased - false, - }, - &testCase{ - "Safe", - "HTTP://www.SRC.ca:80/to%1ato%8b%ee/OKnow%41%42%43%7e", - FlagsSafe, - "http://www.src.ca/to%1Ato%8B%EE/OKnowABC~", - false, - }, - &testCase{ - "BothLower", - "HTTP://www.SRC.ca:80/to%1ato%8b%ee/OKnow%41%42%43%7e", - FlagLowercaseHost | FlagLowercaseScheme, - "http://www.src.ca:80/to%1Ato%8B%EE/OKnowABC~", - false, - }, - &testCase{ - "RemoveTrailingSlash", - "HTTP://www.SRC.ca:80/", - FlagRemoveTrailingSlash, - "http://www.SRC.ca:80", // Since Go1.1, scheme is automatically lowercased - false, - }, - &testCase{ - "RemoveTrailingSlash2", - "HTTP://www.SRC.ca:80/toto/titi/", - FlagRemoveTrailingSlash, - "http://www.SRC.ca:80/toto/titi", // Since Go1.1, scheme is automatically lowercased - false, - }, - &testCase{ - "RemoveTrailingSlash3", - "HTTP://www.SRC.ca:80/toto/titi/fin/?a=1", - FlagRemoveTrailingSlash, - "http://www.SRC.ca:80/toto/titi/fin?a=1", // Since Go1.1, scheme is automatically lowercased - false, - }, - &testCase{ - "AddTrailingSlash", - "HTTP://www.SRC.ca:80", - FlagAddTrailingSlash, - "http://www.SRC.ca:80/", // Since Go1.1, scheme is automatically lowercased - false, - }, - &testCase{ - "AddTrailingSlash2", - "HTTP://www.SRC.ca:80/toto/titi.html", - FlagAddTrailingSlash, - "http://www.SRC.ca:80/toto/titi.html/", // Since Go1.1, scheme is automatically lowercased - false, - }, - &testCase{ - "AddTrailingSlash3", - "HTTP://www.SRC.ca:80/toto/titi/fin?a=1", - FlagAddTrailingSlash, - "http://www.SRC.ca:80/toto/titi/fin/?a=1", // Since Go1.1, scheme is automatically lowercased - false, - }, - &testCase{ - "RemoveDotSegments", - "HTTP://root/a/b/./../../c/", - FlagRemoveDotSegments, - "http://root/c/", // Since Go1.1, scheme is automatically lowercased - false, - }, - &testCase{ - "RemoveDotSegments2", - "HTTP://root/../a/b/./../c/../d", - FlagRemoveDotSegments, - "http://root/a/d", // Since Go1.1, scheme is automatically lowercased - false, - }, - &testCase{ - "UsuallySafe", - "HTTP://www.SRC.ca:80/to%1ato%8b%ee/./c/d/../OKnow%41%42%43%7e/?a=b#test", - FlagsUsuallySafeGreedy, - "http://www.src.ca/to%1Ato%8B%EE/c/OKnowABC~?a=b#test", - false, - }, - &testCase{ - "RemoveDirectoryIndex", - "HTTP://root/a/b/c/default.aspx", - FlagRemoveDirectoryIndex, - "http://root/a/b/c/", // Since Go1.1, scheme is automatically lowercased - false, - }, - &testCase{ - "RemoveDirectoryIndex2", - "HTTP://root/a/b/c/default#a=b", - FlagRemoveDirectoryIndex, - "http://root/a/b/c/default#a=b", // Since Go1.1, scheme is automatically lowercased - false, - }, - &testCase{ - "RemoveFragment", - "HTTP://root/a/b/c/default#toto=tata", - FlagRemoveFragment, - "http://root/a/b/c/default", // Since Go1.1, scheme is automatically lowercased - false, - }, - &testCase{ - "ForceHTTP", - "https://root/a/b/c/default#toto=tata", - FlagForceHTTP, - "http://root/a/b/c/default#toto=tata", - false, - }, - &testCase{ - "RemoveDuplicateSlashes", - "https://root/a//b///c////default#toto=tata", - FlagRemoveDuplicateSlashes, - "https://root/a/b/c/default#toto=tata", - false, - }, - &testCase{ - "RemoveDuplicateSlashes2", - "https://root//a//b///c////default#toto=tata", - FlagRemoveDuplicateSlashes, - "https://root/a/b/c/default#toto=tata", - false, - }, - &testCase{ - "RemoveWWW", - "https://www.root/a/b/c/", - FlagRemoveWWW, - "https://root/a/b/c/", - false, - }, - &testCase{ - "RemoveWWW2", - "https://WwW.Root/a/b/c/", - FlagRemoveWWW, - "https://Root/a/b/c/", - false, - }, - &testCase{ - "AddWWW", - "https://Root/a/b/c/", - FlagAddWWW, - "https://www.Root/a/b/c/", - false, - }, - &testCase{ - "SortQuery", - "http://root/toto/?b=4&a=1&c=3&b=2&a=5", - FlagSortQuery, - "http://root/toto/?a=1&a=5&b=2&b=4&c=3", - false, - }, - &testCase{ - "RemoveEmptyQuerySeparator", - "http://root/toto/?", - FlagRemoveEmptyQuerySeparator, - "http://root/toto/", - false, - }, - &testCase{ - "Unsafe", - "HTTPS://www.RooT.com/toto/t%45%1f///a/./b/../c/?z=3&w=2&a=4&w=1#invalid", - FlagsUnsafeGreedy, - "http://root.com/toto/tE%1F/a/c?a=4&w=1&w=2&z=3", - false, - }, - &testCase{ - "Safe2", - "HTTPS://www.RooT.com/toto/t%45%1f///a/./b/../c/?z=3&w=2&a=4&w=1#invalid", - FlagsSafe, - "https://www.root.com/toto/tE%1F///a/./b/../c/?z=3&w=2&a=4&w=1#invalid", - false, - }, - &testCase{ - "UsuallySafe2", - "HTTPS://www.RooT.com/toto/t%45%1f///a/./b/../c/?z=3&w=2&a=4&w=1#invalid", - FlagsUsuallySafeGreedy, - "https://www.root.com/toto/tE%1F///a/c?z=3&w=2&a=4&w=1#invalid", - false, - }, - &testCase{ - "AddTrailingSlashBug", - "http://src.ca/", - FlagsAllNonGreedy, - "http://www.src.ca/", - false, - }, - &testCase{ - "SourceModified", - "HTTPS://www.RooT.com/toto/t%45%1f///a/./b/../c/?z=3&w=2&a=4&w=1#invalid", - FlagsUnsafeGreedy, - "http://root.com/toto/tE%1F/a/c?a=4&w=1&w=2&z=3", - true, - }, - &testCase{ - "IPv6-1", - "http://[2001:db8:1f70::999:de8:7648:6e8]/test", - FlagsSafe | FlagRemoveDotSegments, - "http://[2001:db8:1f70::999:de8:7648:6e8]/test", - false, - }, - &testCase{ - "IPv6-2", - "http://[::ffff:192.168.1.1]/test", - FlagsSafe | FlagRemoveDotSegments, - "http://[::ffff:192.168.1.1]/test", - false, - }, - &testCase{ - "IPv6-3", - "http://[::ffff:192.168.1.1]:80/test", - FlagsSafe | FlagRemoveDotSegments, - "http://[::ffff:192.168.1.1]/test", - false, - }, - &testCase{ - "IPv6-4", - "htTps://[::fFff:192.168.1.1]:443/test", - FlagsSafe | FlagRemoveDotSegments, - "https://[::ffff:192.168.1.1]/test", - false, - }, - &testCase{ - "FTP", - "ftp://user:pass@ftp.foo.net/foo/bar", - FlagsSafe | FlagRemoveDotSegments, - "ftp://user:pass@ftp.foo.net/foo/bar", - false, - }, - &testCase{ - "Standard-1", - "http://www.foo.com:80/foo", - FlagsSafe | FlagRemoveDotSegments, - "http://www.foo.com/foo", - false, - }, - &testCase{ - "Standard-2", - "http://www.foo.com:8000/foo", - FlagsSafe | FlagRemoveDotSegments, - "http://www.foo.com:8000/foo", - false, - }, - &testCase{ - "Standard-3", - "http://www.foo.com/%7ebar", - FlagsSafe | FlagRemoveDotSegments, - "http://www.foo.com/~bar", - false, - }, - &testCase{ - "Standard-4", - "http://www.foo.com/%7Ebar", - FlagsSafe | FlagRemoveDotSegments, - "http://www.foo.com/~bar", - false, - }, - &testCase{ - "Standard-5", - "http://USER:pass@www.Example.COM/foo/bar", - FlagsSafe | FlagRemoveDotSegments, - "http://USER:pass@www.example.com/foo/bar", - false, - }, - &testCase{ - "Standard-6", - "http://test.example/?a=%26&b=1", - FlagsSafe | FlagRemoveDotSegments, - "http://test.example/?a=%26&b=1", - false, - }, - &testCase{ - "Standard-7", - "http://test.example/%25/?p=%20val%20%25", - FlagsSafe | FlagRemoveDotSegments, - "http://test.example/%25/?p=%20val%20%25", - false, - }, - &testCase{ - "Standard-8", - "http://test.example/path/with a%20space+/", - FlagsSafe | FlagRemoveDotSegments, - "http://test.example/path/with%20a%20space+/", - false, - }, - &testCase{ - "Standard-9", - "http://test.example/?", - FlagsSafe | FlagRemoveDotSegments, - "http://test.example/", - false, - }, - &testCase{ - "Standard-10", - "http://a.COM/path/?b&a", - FlagsSafe | FlagRemoveDotSegments, - "http://a.com/path/?b&a", - false, - }, - &testCase{ - "StandardCasesAddTrailingSlash", - "http://test.example?", - FlagsSafe | FlagAddTrailingSlash, - "http://test.example/", - false, - }, - &testCase{ - "OctalIP-1", - "http://0123.011.0.4/", - FlagsSafe | FlagDecodeOctalHost, - "http://0123.011.0.4/", - false, - }, - &testCase{ - "OctalIP-2", - "http://0102.0146.07.0223/", - FlagsSafe | FlagDecodeOctalHost, - "http://66.102.7.147/", - false, - }, - &testCase{ - "OctalIP-3", - "http://0102.0146.07.0223.:23/", - FlagsSafe | FlagDecodeOctalHost, - "http://66.102.7.147.:23/", - false, - }, - &testCase{ - "OctalIP-4", - "http://USER:pass@0102.0146.07.0223../", - FlagsSafe | FlagDecodeOctalHost, - "http://USER:pass@66.102.7.147../", - false, - }, - &testCase{ - "DWORDIP-1", - "http://123.1113982867/", - FlagsSafe | FlagDecodeDWORDHost, - "http://123.1113982867/", - false, - }, - &testCase{ - "DWORDIP-2", - "http://1113982867/", - FlagsSafe | FlagDecodeDWORDHost, - "http://66.102.7.147/", - false, - }, - &testCase{ - "DWORDIP-3", - "http://1113982867.:23/", - FlagsSafe | FlagDecodeDWORDHost, - "http://66.102.7.147.:23/", - false, - }, - &testCase{ - "DWORDIP-4", - "http://USER:pass@1113982867../", - FlagsSafe | FlagDecodeDWORDHost, - "http://USER:pass@66.102.7.147../", - false, - }, - &testCase{ - "HexIP-1", - "http://0x123.1113982867/", - FlagsSafe | FlagDecodeHexHost, - "http://0x123.1113982867/", - false, - }, - &testCase{ - "HexIP-2", - "http://0x42660793/", - FlagsSafe | FlagDecodeHexHost, - "http://66.102.7.147/", - false, - }, - &testCase{ - "HexIP-3", - "http://0x42660793.:23/", - FlagsSafe | FlagDecodeHexHost, - "http://66.102.7.147.:23/", - false, - }, - &testCase{ - "HexIP-4", - "http://USER:pass@0x42660793../", - FlagsSafe | FlagDecodeHexHost, - "http://USER:pass@66.102.7.147../", - false, - }, - &testCase{ - "UnnecessaryHostDots-1", - "http://.www.foo.com../foo/bar.html", - FlagsSafe | FlagRemoveUnnecessaryHostDots, - "http://www.foo.com/foo/bar.html", - false, - }, - &testCase{ - "UnnecessaryHostDots-2", - "http://www.foo.com./foo/bar.html", - FlagsSafe | FlagRemoveUnnecessaryHostDots, - "http://www.foo.com/foo/bar.html", - false, - }, - &testCase{ - "UnnecessaryHostDots-3", - "http://www.foo.com.:81/foo", - FlagsSafe | FlagRemoveUnnecessaryHostDots, - "http://www.foo.com:81/foo", - false, - }, - &testCase{ - "UnnecessaryHostDots-4", - "http://www.example.com./", - FlagsSafe | FlagRemoveUnnecessaryHostDots, - "http://www.example.com/", - false, - }, - &testCase{ - "EmptyPort-1", - "http://www.thedraymin.co.uk:/main/?p=308", - FlagsSafe | FlagRemoveEmptyPortSeparator, - "http://www.thedraymin.co.uk/main/?p=308", - false, - }, - &testCase{ - "EmptyPort-2", - "http://www.src.ca:", - FlagsSafe | FlagRemoveEmptyPortSeparator, - "http://www.src.ca", - false, - }, - &testCase{ - "Slashes-1", - "http://test.example/foo/bar/.", - FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, - "http://test.example/foo/bar/", - false, - }, - &testCase{ - "Slashes-2", - "http://test.example/foo/bar/./", - FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, - "http://test.example/foo/bar/", - false, - }, - &testCase{ - "Slashes-3", - "http://test.example/foo/bar/..", - FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, - "http://test.example/foo/", - false, - }, - &testCase{ - "Slashes-4", - "http://test.example/foo/bar/../", - FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, - "http://test.example/foo/", - false, - }, - &testCase{ - "Slashes-5", - "http://test.example/foo/bar/../baz", - FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, - "http://test.example/foo/baz", - false, - }, - &testCase{ - "Slashes-6", - "http://test.example/foo/bar/../..", - FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, - "http://test.example/", - false, - }, - &testCase{ - "Slashes-7", - "http://test.example/foo/bar/../../", - FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, - "http://test.example/", - false, - }, - &testCase{ - "Slashes-8", - "http://test.example/foo/bar/../../baz", - FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, - "http://test.example/baz", - false, - }, - &testCase{ - "Slashes-9", - "http://test.example/foo/bar/../../../baz", - FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, - "http://test.example/baz", - false, - }, - &testCase{ - "Slashes-10", - "http://test.example/foo/bar/../../../../baz", - FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, - "http://test.example/baz", - false, - }, - &testCase{ - "Slashes-11", - "http://test.example/./foo", - FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, - "http://test.example/foo", - false, - }, - &testCase{ - "Slashes-12", - "http://test.example/../foo", - FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, - "http://test.example/foo", - false, - }, - &testCase{ - "Slashes-13", - "http://test.example/foo.", - FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, - "http://test.example/foo.", - false, - }, - &testCase{ - "Slashes-14", - "http://test.example/.foo", - FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, - "http://test.example/.foo", - false, - }, - &testCase{ - "Slashes-15", - "http://test.example/foo..", - FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, - "http://test.example/foo..", - false, - }, - &testCase{ - "Slashes-16", - "http://test.example/..foo", - FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, - "http://test.example/..foo", - false, - }, - &testCase{ - "Slashes-17", - "http://test.example/./../foo", - FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, - "http://test.example/foo", - false, - }, - &testCase{ - "Slashes-18", - "http://test.example/./foo/.", - FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, - "http://test.example/foo/", - false, - }, - &testCase{ - "Slashes-19", - "http://test.example/foo/./bar", - FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, - "http://test.example/foo/bar", - false, - }, - &testCase{ - "Slashes-20", - "http://test.example/foo/../bar", - FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, - "http://test.example/bar", - false, - }, - &testCase{ - "Slashes-21", - "http://test.example/foo//", - FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, - "http://test.example/foo/", - false, - }, - &testCase{ - "Slashes-22", - "http://test.example/foo///bar//", - FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, - "http://test.example/foo/bar/", - false, - }, - &testCase{ - "Relative", - "foo/bar", - FlagsAllGreedy, - "foo/bar", - false, - }, - &testCase{ - "Relative-1", - "./../foo", - FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, - "foo", - false, - }, - &testCase{ - "Relative-2", - "./foo/bar/../baz/../bang/..", - FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, - "foo/", - false, - }, - &testCase{ - "Relative-3", - "foo///bar//", - FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, - "foo/bar/", - false, - }, - &testCase{ - "Relative-4", - "www.youtube.com", - FlagsUsuallySafeGreedy, - "www.youtube.com", - false, - }, - /*&testCase{ - "UrlNorm-5", - "http://ja.wikipedia.org/wiki/%E3%82%AD%E3%83%A3%E3%82%BF%E3%83%94%E3%83%A9%E3%83%BC%E3%82%B8%E3%83%A3%E3%83%91%E3%83%B3", - FlagsSafe | FlagRemoveDotSegments, - "http://ja.wikipedia.org/wiki/\xe3\x82\xad\xe3\x83\xa3\xe3\x82\xbf\xe3\x83\x94\xe3\x83\xa9\xe3\x83\xbc\xe3\x82\xb8\xe3\x83\xa3\xe3\x83\x91\xe3\x83\xb3", - false, - }, - &testCase{ - "UrlNorm-1", - "http://test.example/?a=%e3%82%82%26", - FlagsAllGreedy, - "http://test.example/?a=\xe3\x82\x82%26", - false, - },*/ - } -) - -func TestRunner(t *testing.T) { - for _, tc := range cases { - runCase(tc, t) - } -} - -func runCase(tc *testCase, t *testing.T) { - t.Logf("running %s...", tc.nm) - if tc.parsed { - u, e := url.Parse(tc.src) - if e != nil { - t.Errorf("%s - FAIL : %s", tc.nm, e) - return - } else { - NormalizeURL(u, tc.flgs) - if s := u.String(); s != tc.res { - t.Errorf("%s - FAIL expected '%s', got '%s'", tc.nm, tc.res, s) - } - } - } else { - if s, e := NormalizeURLString(tc.src, tc.flgs); e != nil { - t.Errorf("%s - FAIL : %s", tc.nm, e) - } else if s != tc.res { - t.Errorf("%s - FAIL expected '%s', got '%s'", tc.nm, tc.res, s) - } - } -} - -func TestDecodeUnnecessaryEscapesAll(t *testing.T) { - var url = "http://host/" - - for i := 0; i < 256; i++ { - url += fmt.Sprintf("%%%02x", i) - } - if s, e := NormalizeURLString(url, FlagDecodeUnnecessaryEscapes); e != nil { - t.Fatalf("Got error %s", e.Error()) - } else { - const want = "http://host/%00%01%02%03%04%05%06%07%08%09%0A%0B%0C%0D%0E%0F%10%11%12%13%14%15%16%17%18%19%1A%1B%1C%1D%1E%1F%20!%22%23$%25&'()*+,-./0123456789:;%3C=%3E%3F@ABCDEFGHIJKLMNOPQRSTUVWXYZ[%5C]%5E_%60abcdefghijklmnopqrstuvwxyz%7B%7C%7D~%7F%80%81%82%83%84%85%86%87%88%89%8A%8B%8C%8D%8E%8F%90%91%92%93%94%95%96%97%98%99%9A%9B%9C%9D%9E%9F%A0%A1%A2%A3%A4%A5%A6%A7%A8%A9%AA%AB%AC%AD%AE%AF%B0%B1%B2%B3%B4%B5%B6%B7%B8%B9%BA%BB%BC%BD%BE%BF%C0%C1%C2%C3%C4%C5%C6%C7%C8%C9%CA%CB%CC%CD%CE%CF%D0%D1%D2%D3%D4%D5%D6%D7%D8%D9%DA%DB%DC%DD%DE%DF%E0%E1%E2%E3%E4%E5%E6%E7%E8%E9%EA%EB%EC%ED%EE%EF%F0%F1%F2%F3%F4%F5%F6%F7%F8%F9%FA%FB%FC%FD%FE%FF" - if s != want { - t.Errorf("DecodeUnnecessaryEscapesAll:\nwant\n%s\ngot\n%s", want, s) - } - } -} - -func TestEncodeNecessaryEscapesAll(t *testing.T) { - var url = "http://host/" - - for i := 0; i < 256; i++ { - if i != 0x25 { - url += string(i) - } - } - if s, e := NormalizeURLString(url, FlagEncodeNecessaryEscapes); e != nil { - t.Fatalf("Got error %s", e.Error()) - } else { - const want = "http://host/%00%01%02%03%04%05%06%07%08%09%0A%0B%0C%0D%0E%0F%10%11%12%13%14%15%16%17%18%19%1A%1B%1C%1D%1E%1F%20!%22#$&'()*+,-./0123456789:;%3C=%3E?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[%5C]%5E_%60abcdefghijklmnopqrstuvwxyz%7B%7C%7D~%7F%C2%80%C2%81%C2%82%C2%83%C2%84%C2%85%C2%86%C2%87%C2%88%C2%89%C2%8A%C2%8B%C2%8C%C2%8D%C2%8E%C2%8F%C2%90%C2%91%C2%92%C2%93%C2%94%C2%95%C2%96%C2%97%C2%98%C2%99%C2%9A%C2%9B%C2%9C%C2%9D%C2%9E%C2%9F%C2%A0%C2%A1%C2%A2%C2%A3%C2%A4%C2%A5%C2%A6%C2%A7%C2%A8%C2%A9%C2%AA%C2%AB%C2%AC%C2%AD%C2%AE%C2%AF%C2%B0%C2%B1%C2%B2%C2%B3%C2%B4%C2%B5%C2%B6%C2%B7%C2%B8%C2%B9%C2%BA%C2%BB%C2%BC%C2%BD%C2%BE%C2%BF%C3%80%C3%81%C3%82%C3%83%C3%84%C3%85%C3%86%C3%87%C3%88%C3%89%C3%8A%C3%8B%C3%8C%C3%8D%C3%8E%C3%8F%C3%90%C3%91%C3%92%C3%93%C3%94%C3%95%C3%96%C3%97%C3%98%C3%99%C3%9A%C3%9B%C3%9C%C3%9D%C3%9E%C3%9F%C3%A0%C3%A1%C3%A2%C3%A3%C3%A4%C3%A5%C3%A6%C3%A7%C3%A8%C3%A9%C3%AA%C3%AB%C3%AC%C3%AD%C3%AE%C3%AF%C3%B0%C3%B1%C3%B2%C3%B3%C3%B4%C3%B5%C3%B6%C3%B7%C3%B8%C3%B9%C3%BA%C3%BB%C3%BC%C3%BD%C3%BE%C3%BF" - if s != want { - t.Errorf("EncodeNecessaryEscapesAll:\nwant\n%s\ngot\n%s", want, s) - } - } -} diff --git a/vendor/github.com/PuerkitoBio/purell/urlnorm_test.go b/vendor/github.com/PuerkitoBio/purell/urlnorm_test.go deleted file mode 100644 index d1b2ca6c0..000000000 --- a/vendor/github.com/PuerkitoBio/purell/urlnorm_test.go +++ /dev/null @@ -1,53 +0,0 @@ -package purell - -import ( - "testing" -) - -// Test cases merged from PR #1 -// Originally from https://github.com/jehiah/urlnorm/blob/master/test_urlnorm.py - -func assertMap(t *testing.T, cases map[string]string, f NormalizationFlags) { - for bad, good := range cases { - s, e := NormalizeURLString(bad, f) - if e != nil { - t.Errorf("%s normalizing %v to %v", e.Error(), bad, good) - } else { - if s != good { - t.Errorf("source: %v expected: %v got: %v", bad, good, s) - } - } - } -} - -// This tests normalization to a unicode representation -// precent escapes for unreserved values are unescaped to their unicode value -// tests normalization to idna domains -// test ip word handling, ipv6 address handling, and trailing domain periods -// in general, this matches google chromes unescaping for things in the address bar. -// spaces are converted to '+' (perhaphs controversial) -// http://code.google.com/p/google-url/ probably is another good reference for this approach -func TestUrlnorm(t *testing.T) { - testcases := map[string]string{ - "http://test.example/?a=%e3%82%82%26": "http://test.example/?a=%e3%82%82%26", - //"http://test.example/?a=%e3%82%82%26": "http://test.example/?a=\xe3\x82\x82%26", //should return a unicode character - "http://s.xn--q-bga.DE/": "http://s.xn--q-bga.de/", //should be in idna format - "http://XBLA\u306eXbox.com": "http://xn--xblaxbox-jf4g.com", //test utf8 and unicode - "http://президент.рф": "http://xn--d1abbgf6aiiy.xn--p1ai", - "http://ПРЕЗИДЕНТ.РФ": "http://xn--d1abbgf6aiiy.xn--p1ai", - "http://ab¥ヲ₩○.com": "http://xn--ab-ida8983azmfnvs.com", //test width folding - "http://\u00e9.com": "http://xn--9ca.com", - "http://e\u0301.com": "http://xn--9ca.com", - "http://ja.wikipedia.org/wiki/%E3%82%AD%E3%83%A3%E3%82%BF%E3%83%94%E3%83%A9%E3%83%BC%E3%82%B8%E3%83%A3%E3%83%91%E3%83%B3": "http://ja.wikipedia.org/wiki/%E3%82%AD%E3%83%A3%E3%82%BF%E3%83%94%E3%83%A9%E3%83%BC%E3%82%B8%E3%83%A3%E3%83%91%E3%83%B3", - //"http://ja.wikipedia.org/wiki/%E3%82%AD%E3%83%A3%E3%82%BF%E3%83%94%E3%83%A9%E3%83%BC%E3%82%B8%E3%83%A3%E3%83%91%E3%83%B3": "http://ja.wikipedia.org/wiki/\xe3\x82\xad\xe3\x83\xa3\xe3\x82\xbf\xe3\x83\x94\xe3\x83\xa9\xe3\x83\xbc\xe3\x82\xb8\xe3\x83\xa3\xe3\x83\x91\xe3\x83\xb3", - - "http://test.example/\xe3\x82\xad": "http://test.example/%E3%82%AD", - //"http://test.example/\xe3\x82\xad": "http://test.example/\xe3\x82\xad", - "http://test.example/?p=%23val#test-%23-val%25": "http://test.example/?p=%23val#test-%23-val%25", //check that %23 (#) is not escaped where it shouldn't be - - "http://test.domain/I%C3%B1t%C3%ABrn%C3%A2ti%C3%B4n%EF%BF%BDliz%C3%A6ti%C3%B8n": "http://test.domain/I%C3%B1t%C3%ABrn%C3%A2ti%C3%B4n%EF%BF%BDliz%C3%A6ti%C3%B8n", - //"http://test.domain/I%C3%B1t%C3%ABrn%C3%A2ti%C3%B4n%EF%BF%BDliz%C3%A6ti%C3%B8n": "http://test.domain/I\xc3\xb1t\xc3\xabrn\xc3\xa2ti\xc3\xb4n\xef\xbf\xbdliz\xc3\xa6ti\xc3\xb8n", - } - - assertMap(t, testcases, FlagsSafe|FlagRemoveDotSegments) -} diff --git a/vendor/github.com/PuerkitoBio/urlesc/.travis.yml b/vendor/github.com/PuerkitoBio/urlesc/.travis.yml deleted file mode 100644 index ba6b225f9..000000000 --- a/vendor/github.com/PuerkitoBio/urlesc/.travis.yml +++ /dev/null @@ -1,15 +0,0 @@ -language: go - -go: - - 1.4.x - - 1.5.x - - 1.6.x - - 1.7.x - - 1.8.x - - tip - -install: - - go build . - -script: - - go test -v diff --git a/vendor/github.com/PuerkitoBio/urlesc/README.md b/vendor/github.com/PuerkitoBio/urlesc/README.md deleted file mode 100644 index 57aff0a53..000000000 --- a/vendor/github.com/PuerkitoBio/urlesc/README.md +++ /dev/null @@ -1,16 +0,0 @@ -urlesc [![Build Status](https://travis-ci.org/PuerkitoBio/urlesc.svg?branch=master)](https://travis-ci.org/PuerkitoBio/urlesc) [![GoDoc](http://godoc.org/github.com/PuerkitoBio/urlesc?status.svg)](http://godoc.org/github.com/PuerkitoBio/urlesc) -====== - -Package urlesc implements query escaping as per RFC 3986. - -It contains some parts of the net/url package, modified so as to allow -some reserved characters incorrectly escaped by net/url (see [issue 5684](https://github.com/golang/go/issues/5684)). - -## Install - - go get github.com/PuerkitoBio/urlesc - -## License - -Go license (BSD-3-Clause) - diff --git a/vendor/github.com/PuerkitoBio/urlesc/urlesc_test.go b/vendor/github.com/PuerkitoBio/urlesc/urlesc_test.go deleted file mode 100644 index 45202e1dd..000000000 --- a/vendor/github.com/PuerkitoBio/urlesc/urlesc_test.go +++ /dev/null @@ -1,641 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package urlesc - -import ( - "net/url" - "testing" -) - -type URLTest struct { - in string - out *url.URL - roundtrip string // expected result of reserializing the URL; empty means same as "in". -} - -var urltests = []URLTest{ - // no path - { - "http://www.google.com", - &url.URL{ - Scheme: "http", - Host: "www.google.com", - }, - "", - }, - // path - { - "http://www.google.com/", - &url.URL{ - Scheme: "http", - Host: "www.google.com", - Path: "/", - }, - "", - }, - // path with hex escaping - { - "http://www.google.com/file%20one%26two", - &url.URL{ - Scheme: "http", - Host: "www.google.com", - Path: "/file one&two", - }, - "http://www.google.com/file%20one&two", - }, - // user - { - "ftp://webmaster@www.google.com/", - &url.URL{ - Scheme: "ftp", - User: url.User("webmaster"), - Host: "www.google.com", - Path: "/", - }, - "", - }, - // escape sequence in username - { - "ftp://john%20doe@www.google.com/", - &url.URL{ - Scheme: "ftp", - User: url.User("john doe"), - Host: "www.google.com", - Path: "/", - }, - "ftp://john%20doe@www.google.com/", - }, - // query - { - "http://www.google.com/?q=go+language", - &url.URL{ - Scheme: "http", - Host: "www.google.com", - Path: "/", - RawQuery: "q=go+language", - }, - "", - }, - // query with hex escaping: NOT parsed - { - "http://www.google.com/?q=go%20language", - &url.URL{ - Scheme: "http", - Host: "www.google.com", - Path: "/", - RawQuery: "q=go%20language", - }, - "", - }, - // %20 outside query - { - "http://www.google.com/a%20b?q=c+d", - &url.URL{ - Scheme: "http", - Host: "www.google.com", - Path: "/a b", - RawQuery: "q=c+d", - }, - "", - }, - // path without leading /, so no parsing - { - "http:www.google.com/?q=go+language", - &url.URL{ - Scheme: "http", - Opaque: "www.google.com/", - RawQuery: "q=go+language", - }, - "http:www.google.com/?q=go+language", - }, - // path without leading /, so no parsing - { - "http:%2f%2fwww.google.com/?q=go+language", - &url.URL{ - Scheme: "http", - Opaque: "%2f%2fwww.google.com/", - RawQuery: "q=go+language", - }, - "http:%2f%2fwww.google.com/?q=go+language", - }, - // non-authority with path - { - "mailto:/webmaster@golang.org", - &url.URL{ - Scheme: "mailto", - Path: "/webmaster@golang.org", - }, - "mailto:///webmaster@golang.org", // unfortunate compromise - }, - // non-authority - { - "mailto:webmaster@golang.org", - &url.URL{ - Scheme: "mailto", - Opaque: "webmaster@golang.org", - }, - "", - }, - // unescaped :// in query should not create a scheme - { - "/foo?query=http://bad", - &url.URL{ - Path: "/foo", - RawQuery: "query=http://bad", - }, - "", - }, - // leading // without scheme should create an authority - { - "//foo", - &url.URL{ - Host: "foo", - }, - "", - }, - // leading // without scheme, with userinfo, path, and query - { - "//user@foo/path?a=b", - &url.URL{ - User: url.User("user"), - Host: "foo", - Path: "/path", - RawQuery: "a=b", - }, - "", - }, - // Three leading slashes isn't an authority, but doesn't return an error. - // (We can't return an error, as this code is also used via - // ServeHTTP -> ReadRequest -> Parse, which is arguably a - // different URL parsing context, but currently shares the - // same codepath) - { - "///threeslashes", - &url.URL{ - Path: "///threeslashes", - }, - "", - }, - { - "http://user:password@google.com", - &url.URL{ - Scheme: "http", - User: url.UserPassword("user", "password"), - Host: "google.com", - }, - "http://user:password@google.com", - }, - // unescaped @ in username should not confuse host - { - "http://j@ne:password@google.com", - &url.URL{ - Scheme: "http", - User: url.UserPassword("j@ne", "password"), - Host: "google.com", - }, - "http://j%40ne:password@google.com", - }, - // unescaped @ in password should not confuse host - { - "http://jane:p@ssword@google.com", - &url.URL{ - Scheme: "http", - User: url.UserPassword("jane", "p@ssword"), - Host: "google.com", - }, - "http://jane:p%40ssword@google.com", - }, - { - "http://j@ne:password@google.com/p@th?q=@go", - &url.URL{ - Scheme: "http", - User: url.UserPassword("j@ne", "password"), - Host: "google.com", - Path: "/p@th", - RawQuery: "q=@go", - }, - "http://j%40ne:password@google.com/p@th?q=@go", - }, - { - "http://www.google.com/?q=go+language#foo", - &url.URL{ - Scheme: "http", - Host: "www.google.com", - Path: "/", - RawQuery: "q=go+language", - Fragment: "foo", - }, - "", - }, - { - "http://www.google.com/?q=go+language#foo%26bar", - &url.URL{ - Scheme: "http", - Host: "www.google.com", - Path: "/", - RawQuery: "q=go+language", - Fragment: "foo&bar", - }, - "http://www.google.com/?q=go+language#foo&bar", - }, - { - "file:///home/adg/rabbits", - &url.URL{ - Scheme: "file", - Host: "", - Path: "/home/adg/rabbits", - }, - "file:///home/adg/rabbits", - }, - // "Windows" paths are no exception to the rule. - // See golang.org/issue/6027, especially comment #9. - { - "file:///C:/FooBar/Baz.txt", - &url.URL{ - Scheme: "file", - Host: "", - Path: "/C:/FooBar/Baz.txt", - }, - "file:///C:/FooBar/Baz.txt", - }, - // case-insensitive scheme - { - "MaIlTo:webmaster@golang.org", - &url.URL{ - Scheme: "mailto", - Opaque: "webmaster@golang.org", - }, - "mailto:webmaster@golang.org", - }, - // Relative path - { - "a/b/c", - &url.URL{ - Path: "a/b/c", - }, - "a/b/c", - }, - // escaped '?' in username and password - { - "http://%3Fam:pa%3Fsword@google.com", - &url.URL{ - Scheme: "http", - User: url.UserPassword("?am", "pa?sword"), - Host: "google.com", - }, - "", - }, - // escaped '?' and '#' in path - { - "http://example.com/%3F%23", - &url.URL{ - Scheme: "http", - Host: "example.com", - Path: "?#", - }, - "", - }, - // unescaped [ ] ! ' ( ) * in path - { - "http://example.com/[]!'()*", - &url.URL{ - Scheme: "http", - Host: "example.com", - Path: "[]!'()*", - }, - "http://example.com/[]!'()*", - }, - // escaped : / ? # [ ] @ in username and password - { - "http://%3A%2F%3F:%23%5B%5D%40@example.com", - &url.URL{ - Scheme: "http", - User: url.UserPassword(":/?", "#[]@"), - Host: "example.com", - }, - "", - }, - // unescaped ! $ & ' ( ) * + , ; = in username and password - { - "http://!$&'():*+,;=@example.com", - &url.URL{ - Scheme: "http", - User: url.UserPassword("!$&'()", "*+,;="), - Host: "example.com", - }, - "", - }, - // unescaped = : / . ? = in query component - { - "http://example.com/?q=http://google.com/?q=", - &url.URL{ - Scheme: "http", - Host: "example.com", - Path: "/", - RawQuery: "q=http://google.com/?q=", - }, - "", - }, - // unescaped : / ? [ ] @ ! $ & ' ( ) * + , ; = in fragment - { - "http://example.com/#:/?%23[]@!$&'()*+,;=", - &url.URL{ - Scheme: "http", - Host: "example.com", - Path: "/", - Fragment: ":/?#[]@!$&'()*+,;=", - }, - "", - }, -} - -func DoTestString(t *testing.T, parse func(string) (*url.URL, error), name string, tests []URLTest) { - for _, tt := range tests { - u, err := parse(tt.in) - if err != nil { - t.Errorf("%s(%q) returned error %s", name, tt.in, err) - continue - } - expected := tt.in - if len(tt.roundtrip) > 0 { - expected = tt.roundtrip - } - s := Escape(u) - if s != expected { - t.Errorf("Escape(%s(%q)) == %q (expected %q)", name, tt.in, s, expected) - } - } -} - -func TestURLString(t *testing.T) { - DoTestString(t, url.Parse, "Parse", urltests) - - // no leading slash on path should prepend - // slash on String() call - noslash := URLTest{ - "http://www.google.com/search", - &url.URL{ - Scheme: "http", - Host: "www.google.com", - Path: "search", - }, - "", - } - s := Escape(noslash.out) - if s != noslash.in { - t.Errorf("Expected %s; go %s", noslash.in, s) - } -} - -type EscapeTest struct { - in string - out string - err error -} - -var escapeTests = []EscapeTest{ - { - "", - "", - nil, - }, - { - "abc", - "abc", - nil, - }, - { - "one two", - "one+two", - nil, - }, - { - "10%", - "10%25", - nil, - }, - { - " ?&=#+%!<>#\"{}|\\^[]`☺\t:/@$'()*,;", - "+?%26%3D%23%2B%25%21%3C%3E%23%22%7B%7D%7C%5C%5E%5B%5D%60%E2%98%BA%09%3A/%40%24%27%28%29%2A%2C%3B", - nil, - }, -} - -func TestEscape(t *testing.T) { - for _, tt := range escapeTests { - actual := QueryEscape(tt.in) - if tt.out != actual { - t.Errorf("QueryEscape(%q) = %q, want %q", tt.in, actual, tt.out) - } - - // for bonus points, verify that escape:unescape is an identity. - roundtrip, err := url.QueryUnescape(actual) - if roundtrip != tt.in || err != nil { - t.Errorf("QueryUnescape(%q) = %q, %s; want %q, %s", actual, roundtrip, err, tt.in, "[no error]") - } - } -} - -var resolveReferenceTests = []struct { - base, rel, expected string -}{ - // Absolute URL references - {"http://foo.com?a=b", "https://bar.com/", "https://bar.com/"}, - {"http://foo.com/", "https://bar.com/?a=b", "https://bar.com/?a=b"}, - {"http://foo.com/bar", "mailto:foo@example.com", "mailto:foo@example.com"}, - - // Path-absolute references - {"http://foo.com/bar", "/baz", "http://foo.com/baz"}, - {"http://foo.com/bar?a=b#f", "/baz", "http://foo.com/baz"}, - {"http://foo.com/bar?a=b", "/baz?c=d", "http://foo.com/baz?c=d"}, - - // Scheme-relative - {"https://foo.com/bar?a=b", "//bar.com/quux", "https://bar.com/quux"}, - - // Path-relative references: - - // ... current directory - {"http://foo.com", ".", "http://foo.com/"}, - {"http://foo.com/bar", ".", "http://foo.com/"}, - {"http://foo.com/bar/", ".", "http://foo.com/bar/"}, - - // ... going down - {"http://foo.com", "bar", "http://foo.com/bar"}, - {"http://foo.com/", "bar", "http://foo.com/bar"}, - {"http://foo.com/bar/baz", "quux", "http://foo.com/bar/quux"}, - - // ... going up - {"http://foo.com/bar/baz", "../quux", "http://foo.com/quux"}, - {"http://foo.com/bar/baz", "../../../../../quux", "http://foo.com/quux"}, - {"http://foo.com/bar", "..", "http://foo.com/"}, - {"http://foo.com/bar/baz", "./..", "http://foo.com/"}, - // ".." in the middle (issue 3560) - {"http://foo.com/bar/baz", "quux/dotdot/../tail", "http://foo.com/bar/quux/tail"}, - {"http://foo.com/bar/baz", "quux/./dotdot/../tail", "http://foo.com/bar/quux/tail"}, - {"http://foo.com/bar/baz", "quux/./dotdot/.././tail", "http://foo.com/bar/quux/tail"}, - {"http://foo.com/bar/baz", "quux/./dotdot/./../tail", "http://foo.com/bar/quux/tail"}, - {"http://foo.com/bar/baz", "quux/./dotdot/dotdot/././../../tail", "http://foo.com/bar/quux/tail"}, - {"http://foo.com/bar/baz", "quux/./dotdot/dotdot/./.././../tail", "http://foo.com/bar/quux/tail"}, - {"http://foo.com/bar/baz", "quux/./dotdot/dotdot/dotdot/./../../.././././tail", "http://foo.com/bar/quux/tail"}, - {"http://foo.com/bar/baz", "quux/./dotdot/../dotdot/../dot/./tail/..", "http://foo.com/bar/quux/dot/"}, - - // Remove any dot-segments prior to forming the target URI. - // http://tools.ietf.org/html/rfc3986#section-5.2.4 - {"http://foo.com/dot/./dotdot/../foo/bar", "../baz", "http://foo.com/dot/baz"}, - - // Triple dot isn't special - {"http://foo.com/bar", "...", "http://foo.com/..."}, - - // Fragment - {"http://foo.com/bar", ".#frag", "http://foo.com/#frag"}, - - // RFC 3986: Normal Examples - // http://tools.ietf.org/html/rfc3986#section-5.4.1 - {"http://a/b/c/d;p?q", "g:h", "g:h"}, - {"http://a/b/c/d;p?q", "g", "http://a/b/c/g"}, - {"http://a/b/c/d;p?q", "./g", "http://a/b/c/g"}, - {"http://a/b/c/d;p?q", "g/", "http://a/b/c/g/"}, - {"http://a/b/c/d;p?q", "/g", "http://a/g"}, - {"http://a/b/c/d;p?q", "//g", "http://g"}, - {"http://a/b/c/d;p?q", "?y", "http://a/b/c/d;p?y"}, - {"http://a/b/c/d;p?q", "g?y", "http://a/b/c/g?y"}, - {"http://a/b/c/d;p?q", "#s", "http://a/b/c/d;p?q#s"}, - {"http://a/b/c/d;p?q", "g#s", "http://a/b/c/g#s"}, - {"http://a/b/c/d;p?q", "g?y#s", "http://a/b/c/g?y#s"}, - {"http://a/b/c/d;p?q", ";x", "http://a/b/c/;x"}, - {"http://a/b/c/d;p?q", "g;x", "http://a/b/c/g;x"}, - {"http://a/b/c/d;p?q", "g;x?y#s", "http://a/b/c/g;x?y#s"}, - {"http://a/b/c/d;p?q", "", "http://a/b/c/d;p?q"}, - {"http://a/b/c/d;p?q", ".", "http://a/b/c/"}, - {"http://a/b/c/d;p?q", "./", "http://a/b/c/"}, - {"http://a/b/c/d;p?q", "..", "http://a/b/"}, - {"http://a/b/c/d;p?q", "../", "http://a/b/"}, - {"http://a/b/c/d;p?q", "../g", "http://a/b/g"}, - {"http://a/b/c/d;p?q", "../..", "http://a/"}, - {"http://a/b/c/d;p?q", "../../", "http://a/"}, - {"http://a/b/c/d;p?q", "../../g", "http://a/g"}, - - // RFC 3986: Abnormal Examples - // http://tools.ietf.org/html/rfc3986#section-5.4.2 - {"http://a/b/c/d;p?q", "../../../g", "http://a/g"}, - {"http://a/b/c/d;p?q", "../../../../g", "http://a/g"}, - {"http://a/b/c/d;p?q", "/./g", "http://a/g"}, - {"http://a/b/c/d;p?q", "/../g", "http://a/g"}, - {"http://a/b/c/d;p?q", "g.", "http://a/b/c/g."}, - {"http://a/b/c/d;p?q", ".g", "http://a/b/c/.g"}, - {"http://a/b/c/d;p?q", "g..", "http://a/b/c/g.."}, - {"http://a/b/c/d;p?q", "..g", "http://a/b/c/..g"}, - {"http://a/b/c/d;p?q", "./../g", "http://a/b/g"}, - {"http://a/b/c/d;p?q", "./g/.", "http://a/b/c/g/"}, - {"http://a/b/c/d;p?q", "g/./h", "http://a/b/c/g/h"}, - {"http://a/b/c/d;p?q", "g/../h", "http://a/b/c/h"}, - {"http://a/b/c/d;p?q", "g;x=1/./y", "http://a/b/c/g;x=1/y"}, - {"http://a/b/c/d;p?q", "g;x=1/../y", "http://a/b/c/y"}, - {"http://a/b/c/d;p?q", "g?y/./x", "http://a/b/c/g?y/./x"}, - {"http://a/b/c/d;p?q", "g?y/../x", "http://a/b/c/g?y/../x"}, - {"http://a/b/c/d;p?q", "g#s/./x", "http://a/b/c/g#s/./x"}, - {"http://a/b/c/d;p?q", "g#s/../x", "http://a/b/c/g#s/../x"}, - - // Extras. - {"https://a/b/c/d;p?q", "//g?q", "https://g?q"}, - {"https://a/b/c/d;p?q", "//g#s", "https://g#s"}, - {"https://a/b/c/d;p?q", "//g/d/e/f?y#s", "https://g/d/e/f?y#s"}, - {"https://a/b/c/d;p#s", "?y", "https://a/b/c/d;p?y"}, - {"https://a/b/c/d;p?q#s", "?y", "https://a/b/c/d;p?y"}, -} - -func TestResolveReference(t *testing.T) { - mustParse := func(url_ string) *url.URL { - u, err := url.Parse(url_) - if err != nil { - t.Fatalf("Expected URL to parse: %q, got error: %v", url_, err) - } - return u - } - opaque := &url.URL{Scheme: "scheme", Opaque: "opaque"} - for _, test := range resolveReferenceTests { - base := mustParse(test.base) - rel := mustParse(test.rel) - url := base.ResolveReference(rel) - if Escape(url) != test.expected { - t.Errorf("URL(%q).ResolveReference(%q) == %q, got %q", test.base, test.rel, test.expected, Escape(url)) - } - // Ensure that new instances are returned. - if base == url { - t.Errorf("Expected URL.ResolveReference to return new URL instance.") - } - // Test the convenience wrapper too. - url, err := base.Parse(test.rel) - if err != nil { - t.Errorf("URL(%q).Parse(%q) failed: %v", test.base, test.rel, err) - } else if Escape(url) != test.expected { - t.Errorf("URL(%q).Parse(%q) == %q, got %q", test.base, test.rel, test.expected, Escape(url)) - } else if base == url { - // Ensure that new instances are returned for the wrapper too. - t.Errorf("Expected URL.Parse to return new URL instance.") - } - // Ensure Opaque resets the URL. - url = base.ResolveReference(opaque) - if *url != *opaque { - t.Errorf("ResolveReference failed to resolve opaque URL: want %#v, got %#v", url, opaque) - } - // Test the convenience wrapper with an opaque URL too. - url, err = base.Parse("scheme:opaque") - if err != nil { - t.Errorf(`URL(%q).Parse("scheme:opaque") failed: %v`, test.base, err) - } else if *url != *opaque { - t.Errorf("Parse failed to resolve opaque URL: want %#v, got %#v", url, opaque) - } else if base == url { - // Ensure that new instances are returned, again. - t.Errorf("Expected URL.Parse to return new URL instance.") - } - } -} - -type shouldEscapeTest struct { - in byte - mode encoding - escape bool -} - -var shouldEscapeTests = []shouldEscapeTest{ - // Unreserved characters (§2.3) - {'a', encodePath, false}, - {'a', encodeUserPassword, false}, - {'a', encodeQueryComponent, false}, - {'a', encodeFragment, false}, - {'z', encodePath, false}, - {'A', encodePath, false}, - {'Z', encodePath, false}, - {'0', encodePath, false}, - {'9', encodePath, false}, - {'-', encodePath, false}, - {'-', encodeUserPassword, false}, - {'-', encodeQueryComponent, false}, - {'-', encodeFragment, false}, - {'.', encodePath, false}, - {'_', encodePath, false}, - {'~', encodePath, false}, - - // User information (§3.2.1) - {':', encodeUserPassword, true}, - {'/', encodeUserPassword, true}, - {'?', encodeUserPassword, true}, - {'@', encodeUserPassword, true}, - {'$', encodeUserPassword, false}, - {'&', encodeUserPassword, false}, - {'+', encodeUserPassword, false}, - {',', encodeUserPassword, false}, - {';', encodeUserPassword, false}, - {'=', encodeUserPassword, false}, -} - -func TestShouldEscape(t *testing.T) { - for _, tt := range shouldEscapeTests { - if shouldEscape(tt.in, tt.mode) != tt.escape { - t.Errorf("shouldEscape(%q, %v) returned %v; expected %v", tt.in, tt.mode, !tt.escape, tt.escape) - } - } -} diff --git a/vendor/github.com/alecthomas/template/README.md b/vendor/github.com/alecthomas/template/README.md deleted file mode 100644 index ef6a8ee30..000000000 --- a/vendor/github.com/alecthomas/template/README.md +++ /dev/null @@ -1,25 +0,0 @@ -# Go's `text/template` package with newline elision - -This is a fork of Go 1.4's [text/template](http://golang.org/pkg/text/template/) package with one addition: a backslash immediately after a closing delimiter will delete all subsequent newlines until a non-newline. - -eg. - -``` -{{if true}}\ -hello -{{end}}\ -``` - -Will result in: - -``` -hello\n -``` - -Rather than: - -``` -\n -hello\n -\n -``` diff --git a/vendor/github.com/alecthomas/template/example_test.go b/vendor/github.com/alecthomas/template/example_test.go deleted file mode 100644 index 461ec0503..000000000 --- a/vendor/github.com/alecthomas/template/example_test.go +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package template_test - -import ( - "log" - "os" - - "github.com/alecthomas/template" -) - -func ExampleTemplate() { - // Define a template. - const letter = ` -Dear {{.Name}}, -{{if .Attended}} -It was a pleasure to see you at the wedding.{{else}} -It is a shame you couldn't make it to the wedding.{{end}} -{{with .Gift}}Thank you for the lovely {{.}}. -{{end}} -Best wishes, -Josie -` - - // Prepare some data to insert into the template. - type Recipient struct { - Name, Gift string - Attended bool - } - var recipients = []Recipient{ - {"Aunt Mildred", "bone china tea set", true}, - {"Uncle John", "moleskin pants", false}, - {"Cousin Rodney", "", false}, - } - - // Create a new template and parse the letter into it. - t := template.Must(template.New("letter").Parse(letter)) - - // Execute the template for each recipient. - for _, r := range recipients { - err := t.Execute(os.Stdout, r) - if err != nil { - log.Println("executing template:", err) - } - } - - // Output: - // Dear Aunt Mildred, - // - // It was a pleasure to see you at the wedding. - // Thank you for the lovely bone china tea set. - // - // Best wishes, - // Josie - // - // Dear Uncle John, - // - // It is a shame you couldn't make it to the wedding. - // Thank you for the lovely moleskin pants. - // - // Best wishes, - // Josie - // - // Dear Cousin Rodney, - // - // It is a shame you couldn't make it to the wedding. - // - // Best wishes, - // Josie -} diff --git a/vendor/github.com/alecthomas/template/examplefiles_test.go b/vendor/github.com/alecthomas/template/examplefiles_test.go deleted file mode 100644 index 0c7181d2f..000000000 --- a/vendor/github.com/alecthomas/template/examplefiles_test.go +++ /dev/null @@ -1,183 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package template_test - -import ( - "io" - "io/ioutil" - "log" - "os" - "path/filepath" - - "github.com/alecthomas/template" -) - -// templateFile defines the contents of a template to be stored in a file, for testing. -type templateFile struct { - name string - contents string -} - -func createTestDir(files []templateFile) string { - dir, err := ioutil.TempDir("", "template") - if err != nil { - log.Fatal(err) - } - for _, file := range files { - f, err := os.Create(filepath.Join(dir, file.name)) - if err != nil { - log.Fatal(err) - } - defer f.Close() - _, err = io.WriteString(f, file.contents) - if err != nil { - log.Fatal(err) - } - } - return dir -} - -// Here we demonstrate loading a set of templates from a directory. -func ExampleTemplate_glob() { - // Here we create a temporary directory and populate it with our sample - // template definition files; usually the template files would already - // exist in some location known to the program. - dir := createTestDir([]templateFile{ - // T0.tmpl is a plain template file that just invokes T1. - {"T0.tmpl", `T0 invokes T1: ({{template "T1"}})`}, - // T1.tmpl defines a template, T1 that invokes T2. - {"T1.tmpl", `{{define "T1"}}T1 invokes T2: ({{template "T2"}}){{end}}`}, - // T2.tmpl defines a template T2. - {"T2.tmpl", `{{define "T2"}}This is T2{{end}}`}, - }) - // Clean up after the test; another quirk of running as an example. - defer os.RemoveAll(dir) - - // pattern is the glob pattern used to find all the template files. - pattern := filepath.Join(dir, "*.tmpl") - - // Here starts the example proper. - // T0.tmpl is the first name matched, so it becomes the starting template, - // the value returned by ParseGlob. - tmpl := template.Must(template.ParseGlob(pattern)) - - err := tmpl.Execute(os.Stdout, nil) - if err != nil { - log.Fatalf("template execution: %s", err) - } - // Output: - // T0 invokes T1: (T1 invokes T2: (This is T2)) -} - -// This example demonstrates one way to share some templates -// and use them in different contexts. In this variant we add multiple driver -// templates by hand to an existing bundle of templates. -func ExampleTemplate_helpers() { - // Here we create a temporary directory and populate it with our sample - // template definition files; usually the template files would already - // exist in some location known to the program. - dir := createTestDir([]templateFile{ - // T1.tmpl defines a template, T1 that invokes T2. - {"T1.tmpl", `{{define "T1"}}T1 invokes T2: ({{template "T2"}}){{end}}`}, - // T2.tmpl defines a template T2. - {"T2.tmpl", `{{define "T2"}}This is T2{{end}}`}, - }) - // Clean up after the test; another quirk of running as an example. - defer os.RemoveAll(dir) - - // pattern is the glob pattern used to find all the template files. - pattern := filepath.Join(dir, "*.tmpl") - - // Here starts the example proper. - // Load the helpers. - templates := template.Must(template.ParseGlob(pattern)) - // Add one driver template to the bunch; we do this with an explicit template definition. - _, err := templates.Parse("{{define `driver1`}}Driver 1 calls T1: ({{template `T1`}})\n{{end}}") - if err != nil { - log.Fatal("parsing driver1: ", err) - } - // Add another driver template. - _, err = templates.Parse("{{define `driver2`}}Driver 2 calls T2: ({{template `T2`}})\n{{end}}") - if err != nil { - log.Fatal("parsing driver2: ", err) - } - // We load all the templates before execution. This package does not require - // that behavior but html/template's escaping does, so it's a good habit. - err = templates.ExecuteTemplate(os.Stdout, "driver1", nil) - if err != nil { - log.Fatalf("driver1 execution: %s", err) - } - err = templates.ExecuteTemplate(os.Stdout, "driver2", nil) - if err != nil { - log.Fatalf("driver2 execution: %s", err) - } - // Output: - // Driver 1 calls T1: (T1 invokes T2: (This is T2)) - // Driver 2 calls T2: (This is T2) -} - -// This example demonstrates how to use one group of driver -// templates with distinct sets of helper templates. -func ExampleTemplate_share() { - // Here we create a temporary directory and populate it with our sample - // template definition files; usually the template files would already - // exist in some location known to the program. - dir := createTestDir([]templateFile{ - // T0.tmpl is a plain template file that just invokes T1. - {"T0.tmpl", "T0 ({{.}} version) invokes T1: ({{template `T1`}})\n"}, - // T1.tmpl defines a template, T1 that invokes T2. Note T2 is not defined - {"T1.tmpl", `{{define "T1"}}T1 invokes T2: ({{template "T2"}}){{end}}`}, - }) - // Clean up after the test; another quirk of running as an example. - defer os.RemoveAll(dir) - - // pattern is the glob pattern used to find all the template files. - pattern := filepath.Join(dir, "*.tmpl") - - // Here starts the example proper. - // Load the drivers. - drivers := template.Must(template.ParseGlob(pattern)) - - // We must define an implementation of the T2 template. First we clone - // the drivers, then add a definition of T2 to the template name space. - - // 1. Clone the helper set to create a new name space from which to run them. - first, err := drivers.Clone() - if err != nil { - log.Fatal("cloning helpers: ", err) - } - // 2. Define T2, version A, and parse it. - _, err = first.Parse("{{define `T2`}}T2, version A{{end}}") - if err != nil { - log.Fatal("parsing T2: ", err) - } - - // Now repeat the whole thing, using a different version of T2. - // 1. Clone the drivers. - second, err := drivers.Clone() - if err != nil { - log.Fatal("cloning drivers: ", err) - } - // 2. Define T2, version B, and parse it. - _, err = second.Parse("{{define `T2`}}T2, version B{{end}}") - if err != nil { - log.Fatal("parsing T2: ", err) - } - - // Execute the templates in the reverse order to verify the - // first is unaffected by the second. - err = second.ExecuteTemplate(os.Stdout, "T0.tmpl", "second") - if err != nil { - log.Fatalf("second execution: %s", err) - } - err = first.ExecuteTemplate(os.Stdout, "T0.tmpl", "first") - if err != nil { - log.Fatalf("first: execution: %s", err) - } - - // Output: - // T0 (second version) invokes T1: (T1 invokes T2: (T2, version B)) - // T0 (first version) invokes T1: (T1 invokes T2: (T2, version A)) -} diff --git a/vendor/github.com/alecthomas/template/examplefunc_test.go b/vendor/github.com/alecthomas/template/examplefunc_test.go deleted file mode 100644 index 8767cfdcc..000000000 --- a/vendor/github.com/alecthomas/template/examplefunc_test.go +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package template_test - -import ( - "log" - "os" - "strings" - - "github.com/alecthomas/template" -) - -// This example demonstrates a custom function to process template text. -// It installs the strings.Title function and uses it to -// Make Title Text Look Good In Our Template's Output. -func ExampleTemplate_func() { - // First we create a FuncMap with which to register the function. - funcMap := template.FuncMap{ - // The name "title" is what the function will be called in the template text. - "title": strings.Title, - } - - // A simple template definition to test our function. - // We print the input text several ways: - // - the original - // - title-cased - // - title-cased and then printed with %q - // - printed with %q and then title-cased. - const templateText = ` -Input: {{printf "%q" .}} -Output 0: {{title .}} -Output 1: {{title . | printf "%q"}} -Output 2: {{printf "%q" . | title}} -` - - // Create a template, add the function map, and parse the text. - tmpl, err := template.New("titleTest").Funcs(funcMap).Parse(templateText) - if err != nil { - log.Fatalf("parsing: %s", err) - } - - // Run the template to verify the output. - err = tmpl.Execute(os.Stdout, "the go programming language") - if err != nil { - log.Fatalf("execution: %s", err) - } - - // Output: - // Input: "the go programming language" - // Output 0: The Go Programming Language - // Output 1: "The Go Programming Language" - // Output 2: "The Go Programming Language" -} diff --git a/vendor/github.com/alecthomas/template/exec_test.go b/vendor/github.com/alecthomas/template/exec_test.go deleted file mode 100644 index 69c213ed2..000000000 --- a/vendor/github.com/alecthomas/template/exec_test.go +++ /dev/null @@ -1,1044 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package template - -import ( - "bytes" - "errors" - "flag" - "fmt" - "reflect" - "strings" - "testing" -) - -var debug = flag.Bool("debug", false, "show the errors produced by the tests") - -// T has lots of interesting pieces to use to test execution. -type T struct { - // Basics - True bool - I int - U16 uint16 - X string - FloatZero float64 - ComplexZero complex128 - // Nested structs. - U *U - // Struct with String method. - V0 V - V1, V2 *V - // Struct with Error method. - W0 W - W1, W2 *W - // Slices - SI []int - SIEmpty []int - SB []bool - // Maps - MSI map[string]int - MSIone map[string]int // one element, for deterministic output - MSIEmpty map[string]int - MXI map[interface{}]int - MII map[int]int - SMSI []map[string]int - // Empty interfaces; used to see if we can dig inside one. - Empty0 interface{} // nil - Empty1 interface{} - Empty2 interface{} - Empty3 interface{} - Empty4 interface{} - // Non-empty interface. - NonEmptyInterface I - // Stringer. - Str fmt.Stringer - Err error - // Pointers - PI *int - PS *string - PSI *[]int - NIL *int - // Function (not method) - BinaryFunc func(string, string) string - VariadicFunc func(...string) string - VariadicFuncInt func(int, ...string) string - NilOKFunc func(*int) bool - ErrFunc func() (string, error) - // Template to test evaluation of templates. - Tmpl *Template - // Unexported field; cannot be accessed by template. - unexported int -} - -type U struct { - V string -} - -type V struct { - j int -} - -func (v *V) String() string { - if v == nil { - return "nilV" - } - return fmt.Sprintf("<%d>", v.j) -} - -type W struct { - k int -} - -func (w *W) Error() string { - if w == nil { - return "nilW" - } - return fmt.Sprintf("[%d]", w.k) -} - -var tVal = &T{ - True: true, - I: 17, - U16: 16, - X: "x", - U: &U{"v"}, - V0: V{6666}, - V1: &V{7777}, // leave V2 as nil - W0: W{888}, - W1: &W{999}, // leave W2 as nil - SI: []int{3, 4, 5}, - SB: []bool{true, false}, - MSI: map[string]int{"one": 1, "two": 2, "three": 3}, - MSIone: map[string]int{"one": 1}, - MXI: map[interface{}]int{"one": 1}, - MII: map[int]int{1: 1}, - SMSI: []map[string]int{ - {"one": 1, "two": 2}, - {"eleven": 11, "twelve": 12}, - }, - Empty1: 3, - Empty2: "empty2", - Empty3: []int{7, 8}, - Empty4: &U{"UinEmpty"}, - NonEmptyInterface: new(T), - Str: bytes.NewBuffer([]byte("foozle")), - Err: errors.New("erroozle"), - PI: newInt(23), - PS: newString("a string"), - PSI: newIntSlice(21, 22, 23), - BinaryFunc: func(a, b string) string { return fmt.Sprintf("[%s=%s]", a, b) }, - VariadicFunc: func(s ...string) string { return fmt.Sprint("<", strings.Join(s, "+"), ">") }, - VariadicFuncInt: func(a int, s ...string) string { return fmt.Sprint(a, "=<", strings.Join(s, "+"), ">") }, - NilOKFunc: func(s *int) bool { return s == nil }, - ErrFunc: func() (string, error) { return "bla", nil }, - Tmpl: Must(New("x").Parse("test template")), // "x" is the value of .X -} - -// A non-empty interface. -type I interface { - Method0() string -} - -var iVal I = tVal - -// Helpers for creation. -func newInt(n int) *int { - return &n -} - -func newString(s string) *string { - return &s -} - -func newIntSlice(n ...int) *[]int { - p := new([]int) - *p = make([]int, len(n)) - copy(*p, n) - return p -} - -// Simple methods with and without arguments. -func (t *T) Method0() string { - return "M0" -} - -func (t *T) Method1(a int) int { - return a -} - -func (t *T) Method2(a uint16, b string) string { - return fmt.Sprintf("Method2: %d %s", a, b) -} - -func (t *T) Method3(v interface{}) string { - return fmt.Sprintf("Method3: %v", v) -} - -func (t *T) Copy() *T { - n := new(T) - *n = *t - return n -} - -func (t *T) MAdd(a int, b []int) []int { - v := make([]int, len(b)) - for i, x := range b { - v[i] = x + a - } - return v -} - -var myError = errors.New("my error") - -// MyError returns a value and an error according to its argument. -func (t *T) MyError(error bool) (bool, error) { - if error { - return true, myError - } - return false, nil -} - -// A few methods to test chaining. -func (t *T) GetU() *U { - return t.U -} - -func (u *U) TrueFalse(b bool) string { - if b { - return "true" - } - return "" -} - -func typeOf(arg interface{}) string { - return fmt.Sprintf("%T", arg) -} - -type execTest struct { - name string - input string - output string - data interface{} - ok bool -} - -// bigInt and bigUint are hex string representing numbers either side -// of the max int boundary. -// We do it this way so the test doesn't depend on ints being 32 bits. -var ( - bigInt = fmt.Sprintf("0x%x", int(1<", tVal, true}, - {"map .one interface", "{{.MXI.one}}", "1", tVal, true}, - {"map .WRONG args", "{{.MSI.one 1}}", "", tVal, false}, - {"map .WRONG type", "{{.MII.one}}", "", tVal, false}, - - // Dots of all kinds to test basic evaluation. - {"dot int", "<{{.}}>", "<13>", 13, true}, - {"dot uint", "<{{.}}>", "<14>", uint(14), true}, - {"dot float", "<{{.}}>", "<15.1>", 15.1, true}, - {"dot bool", "<{{.}}>", "", true, true}, - {"dot complex", "<{{.}}>", "<(16.2-17i)>", 16.2 - 17i, true}, - {"dot string", "<{{.}}>", "", "hello", true}, - {"dot slice", "<{{.}}>", "<[-1 -2 -3]>", []int{-1, -2, -3}, true}, - {"dot map", "<{{.}}>", "", map[string]int{"two": 22}, true}, - {"dot struct", "<{{.}}>", "<{7 seven}>", struct { - a int - b string - }{7, "seven"}, true}, - - // Variables. - {"$ int", "{{$}}", "123", 123, true}, - {"$.I", "{{$.I}}", "17", tVal, true}, - {"$.U.V", "{{$.U.V}}", "v", tVal, true}, - {"declare in action", "{{$x := $.U.V}}{{$x}}", "v", tVal, true}, - - // Type with String method. - {"V{6666}.String()", "-{{.V0}}-", "-<6666>-", tVal, true}, - {"&V{7777}.String()", "-{{.V1}}-", "-<7777>-", tVal, true}, - {"(*V)(nil).String()", "-{{.V2}}-", "-nilV-", tVal, true}, - - // Type with Error method. - {"W{888}.Error()", "-{{.W0}}-", "-[888]-", tVal, true}, - {"&W{999}.Error()", "-{{.W1}}-", "-[999]-", tVal, true}, - {"(*W)(nil).Error()", "-{{.W2}}-", "-nilW-", tVal, true}, - - // Pointers. - {"*int", "{{.PI}}", "23", tVal, true}, - {"*string", "{{.PS}}", "a string", tVal, true}, - {"*[]int", "{{.PSI}}", "[21 22 23]", tVal, true}, - {"*[]int[1]", "{{index .PSI 1}}", "22", tVal, true}, - {"NIL", "{{.NIL}}", "", tVal, true}, - - // Empty interfaces holding values. - {"empty nil", "{{.Empty0}}", "", tVal, true}, - {"empty with int", "{{.Empty1}}", "3", tVal, true}, - {"empty with string", "{{.Empty2}}", "empty2", tVal, true}, - {"empty with slice", "{{.Empty3}}", "[7 8]", tVal, true}, - {"empty with struct", "{{.Empty4}}", "{UinEmpty}", tVal, true}, - {"empty with struct, field", "{{.Empty4.V}}", "UinEmpty", tVal, true}, - - // Method calls. - {".Method0", "-{{.Method0}}-", "-M0-", tVal, true}, - {".Method1(1234)", "-{{.Method1 1234}}-", "-1234-", tVal, true}, - {".Method1(.I)", "-{{.Method1 .I}}-", "-17-", tVal, true}, - {".Method2(3, .X)", "-{{.Method2 3 .X}}-", "-Method2: 3 x-", tVal, true}, - {".Method2(.U16, `str`)", "-{{.Method2 .U16 `str`}}-", "-Method2: 16 str-", tVal, true}, - {".Method2(.U16, $x)", "{{if $x := .X}}-{{.Method2 .U16 $x}}{{end}}-", "-Method2: 16 x-", tVal, true}, - {".Method3(nil constant)", "-{{.Method3 nil}}-", "-Method3: -", tVal, true}, - {".Method3(nil value)", "-{{.Method3 .MXI.unset}}-", "-Method3: -", tVal, true}, - {"method on var", "{{if $x := .}}-{{$x.Method2 .U16 $x.X}}{{end}}-", "-Method2: 16 x-", tVal, true}, - {"method on chained var", - "{{range .MSIone}}{{if $.U.TrueFalse $.True}}{{$.U.TrueFalse $.True}}{{else}}WRONG{{end}}{{end}}", - "true", tVal, true}, - {"chained method", - "{{range .MSIone}}{{if $.GetU.TrueFalse $.True}}{{$.U.TrueFalse $.True}}{{else}}WRONG{{end}}{{end}}", - "true", tVal, true}, - {"chained method on variable", - "{{with $x := .}}{{with .SI}}{{$.GetU.TrueFalse $.True}}{{end}}{{end}}", - "true", tVal, true}, - {".NilOKFunc not nil", "{{call .NilOKFunc .PI}}", "false", tVal, true}, - {".NilOKFunc nil", "{{call .NilOKFunc nil}}", "true", tVal, true}, - - // Function call builtin. - {".BinaryFunc", "{{call .BinaryFunc `1` `2`}}", "[1=2]", tVal, true}, - {".VariadicFunc0", "{{call .VariadicFunc}}", "<>", tVal, true}, - {".VariadicFunc2", "{{call .VariadicFunc `he` `llo`}}", "", tVal, true}, - {".VariadicFuncInt", "{{call .VariadicFuncInt 33 `he` `llo`}}", "33=", tVal, true}, - {"if .BinaryFunc call", "{{ if .BinaryFunc}}{{call .BinaryFunc `1` `2`}}{{end}}", "[1=2]", tVal, true}, - {"if not .BinaryFunc call", "{{ if not .BinaryFunc}}{{call .BinaryFunc `1` `2`}}{{else}}No{{end}}", "No", tVal, true}, - {"Interface Call", `{{stringer .S}}`, "foozle", map[string]interface{}{"S": bytes.NewBufferString("foozle")}, true}, - {".ErrFunc", "{{call .ErrFunc}}", "bla", tVal, true}, - - // Erroneous function calls (check args). - {".BinaryFuncTooFew", "{{call .BinaryFunc `1`}}", "", tVal, false}, - {".BinaryFuncTooMany", "{{call .BinaryFunc `1` `2` `3`}}", "", tVal, false}, - {".BinaryFuncBad0", "{{call .BinaryFunc 1 3}}", "", tVal, false}, - {".BinaryFuncBad1", "{{call .BinaryFunc `1` 3}}", "", tVal, false}, - {".VariadicFuncBad0", "{{call .VariadicFunc 3}}", "", tVal, false}, - {".VariadicFuncIntBad0", "{{call .VariadicFuncInt}}", "", tVal, false}, - {".VariadicFuncIntBad`", "{{call .VariadicFuncInt `x`}}", "", tVal, false}, - {".VariadicFuncNilBad", "{{call .VariadicFunc nil}}", "", tVal, false}, - - // Pipelines. - {"pipeline", "-{{.Method0 | .Method2 .U16}}-", "-Method2: 16 M0-", tVal, true}, - {"pipeline func", "-{{call .VariadicFunc `llo` | call .VariadicFunc `he` }}-", "->-", tVal, true}, - - // Parenthesized expressions - {"parens in pipeline", "{{printf `%d %d %d` (1) (2 | add 3) (add 4 (add 5 6))}}", "1 5 15", tVal, true}, - - // Parenthesized expressions with field accesses - {"parens: $ in paren", "{{($).X}}", "x", tVal, true}, - {"parens: $.GetU in paren", "{{($.GetU).V}}", "v", tVal, true}, - {"parens: $ in paren in pipe", "{{($ | echo).X}}", "x", tVal, true}, - {"parens: spaces and args", `{{(makemap "up" "down" "left" "right").left}}`, "right", tVal, true}, - - // If. - {"if true", "{{if true}}TRUE{{end}}", "TRUE", tVal, true}, - {"if false", "{{if false}}TRUE{{else}}FALSE{{end}}", "FALSE", tVal, true}, - {"if nil", "{{if nil}}TRUE{{end}}", "", tVal, false}, - {"if 1", "{{if 1}}NON-ZERO{{else}}ZERO{{end}}", "NON-ZERO", tVal, true}, - {"if 0", "{{if 0}}NON-ZERO{{else}}ZERO{{end}}", "ZERO", tVal, true}, - {"if 1.5", "{{if 1.5}}NON-ZERO{{else}}ZERO{{end}}", "NON-ZERO", tVal, true}, - {"if 0.0", "{{if .FloatZero}}NON-ZERO{{else}}ZERO{{end}}", "ZERO", tVal, true}, - {"if 1.5i", "{{if 1.5i}}NON-ZERO{{else}}ZERO{{end}}", "NON-ZERO", tVal, true}, - {"if 0.0i", "{{if .ComplexZero}}NON-ZERO{{else}}ZERO{{end}}", "ZERO", tVal, true}, - {"if emptystring", "{{if ``}}NON-EMPTY{{else}}EMPTY{{end}}", "EMPTY", tVal, true}, - {"if string", "{{if `notempty`}}NON-EMPTY{{else}}EMPTY{{end}}", "NON-EMPTY", tVal, true}, - {"if emptyslice", "{{if .SIEmpty}}NON-EMPTY{{else}}EMPTY{{end}}", "EMPTY", tVal, true}, - {"if slice", "{{if .SI}}NON-EMPTY{{else}}EMPTY{{end}}", "NON-EMPTY", tVal, true}, - {"if emptymap", "{{if .MSIEmpty}}NON-EMPTY{{else}}EMPTY{{end}}", "EMPTY", tVal, true}, - {"if map", "{{if .MSI}}NON-EMPTY{{else}}EMPTY{{end}}", "NON-EMPTY", tVal, true}, - {"if map unset", "{{if .MXI.none}}NON-ZERO{{else}}ZERO{{end}}", "ZERO", tVal, true}, - {"if map not unset", "{{if not .MXI.none}}ZERO{{else}}NON-ZERO{{end}}", "ZERO", tVal, true}, - {"if $x with $y int", "{{if $x := true}}{{with $y := .I}}{{$x}},{{$y}}{{end}}{{end}}", "true,17", tVal, true}, - {"if $x with $x int", "{{if $x := true}}{{with $x := .I}}{{$x}},{{end}}{{$x}}{{end}}", "17,true", tVal, true}, - {"if else if", "{{if false}}FALSE{{else if true}}TRUE{{end}}", "TRUE", tVal, true}, - {"if else chain", "{{if eq 1 3}}1{{else if eq 2 3}}2{{else if eq 3 3}}3{{end}}", "3", tVal, true}, - - // Print etc. - {"print", `{{print "hello, print"}}`, "hello, print", tVal, true}, - {"print 123", `{{print 1 2 3}}`, "1 2 3", tVal, true}, - {"print nil", `{{print nil}}`, "", tVal, true}, - {"println", `{{println 1 2 3}}`, "1 2 3\n", tVal, true}, - {"printf int", `{{printf "%04x" 127}}`, "007f", tVal, true}, - {"printf float", `{{printf "%g" 3.5}}`, "3.5", tVal, true}, - {"printf complex", `{{printf "%g" 1+7i}}`, "(1+7i)", tVal, true}, - {"printf string", `{{printf "%s" "hello"}}`, "hello", tVal, true}, - {"printf function", `{{printf "%#q" zeroArgs}}`, "`zeroArgs`", tVal, true}, - {"printf field", `{{printf "%s" .U.V}}`, "v", tVal, true}, - {"printf method", `{{printf "%s" .Method0}}`, "M0", tVal, true}, - {"printf dot", `{{with .I}}{{printf "%d" .}}{{end}}`, "17", tVal, true}, - {"printf var", `{{with $x := .I}}{{printf "%d" $x}}{{end}}`, "17", tVal, true}, - {"printf lots", `{{printf "%d %s %g %s" 127 "hello" 7-3i .Method0}}`, "127 hello (7-3i) M0", tVal, true}, - - // HTML. - {"html", `{{html ""}}`, - "<script>alert("XSS");</script>", nil, true}, - {"html pipeline", `{{printf "" | html}}`, - "<script>alert("XSS");</script>", nil, true}, - {"html", `{{html .PS}}`, "a string", tVal, true}, - - // JavaScript. - {"js", `{{js .}}`, `It\'d be nice.`, `It'd be nice.`, true}, - - // URL query. - {"urlquery", `{{"http://www.example.org/"|urlquery}}`, "http%3A%2F%2Fwww.example.org%2F", nil, true}, - - // Booleans - {"not", "{{not true}} {{not false}}", "false true", nil, true}, - {"and", "{{and false 0}} {{and 1 0}} {{and 0 true}} {{and 1 1}}", "false 0 0 1", nil, true}, - {"or", "{{or 0 0}} {{or 1 0}} {{or 0 true}} {{or 1 1}}", "0 1 true 1", nil, true}, - {"boolean if", "{{if and true 1 `hi`}}TRUE{{else}}FALSE{{end}}", "TRUE", tVal, true}, - {"boolean if not", "{{if and true 1 `hi` | not}}TRUE{{else}}FALSE{{end}}", "FALSE", nil, true}, - - // Indexing. - {"slice[0]", "{{index .SI 0}}", "3", tVal, true}, - {"slice[1]", "{{index .SI 1}}", "4", tVal, true}, - {"slice[HUGE]", "{{index .SI 10}}", "", tVal, false}, - {"slice[WRONG]", "{{index .SI `hello`}}", "", tVal, false}, - {"map[one]", "{{index .MSI `one`}}", "1", tVal, true}, - {"map[two]", "{{index .MSI `two`}}", "2", tVal, true}, - {"map[NO]", "{{index .MSI `XXX`}}", "0", tVal, true}, - {"map[nil]", "{{index .MSI nil}}", "0", tVal, true}, - {"map[WRONG]", "{{index .MSI 10}}", "", tVal, false}, - {"double index", "{{index .SMSI 1 `eleven`}}", "11", tVal, true}, - - // Len. - {"slice", "{{len .SI}}", "3", tVal, true}, - {"map", "{{len .MSI }}", "3", tVal, true}, - {"len of int", "{{len 3}}", "", tVal, false}, - {"len of nothing", "{{len .Empty0}}", "", tVal, false}, - - // With. - {"with true", "{{with true}}{{.}}{{end}}", "true", tVal, true}, - {"with false", "{{with false}}{{.}}{{else}}FALSE{{end}}", "FALSE", tVal, true}, - {"with 1", "{{with 1}}{{.}}{{else}}ZERO{{end}}", "1", tVal, true}, - {"with 0", "{{with 0}}{{.}}{{else}}ZERO{{end}}", "ZERO", tVal, true}, - {"with 1.5", "{{with 1.5}}{{.}}{{else}}ZERO{{end}}", "1.5", tVal, true}, - {"with 0.0", "{{with .FloatZero}}{{.}}{{else}}ZERO{{end}}", "ZERO", tVal, true}, - {"with 1.5i", "{{with 1.5i}}{{.}}{{else}}ZERO{{end}}", "(0+1.5i)", tVal, true}, - {"with 0.0i", "{{with .ComplexZero}}{{.}}{{else}}ZERO{{end}}", "ZERO", tVal, true}, - {"with emptystring", "{{with ``}}{{.}}{{else}}EMPTY{{end}}", "EMPTY", tVal, true}, - {"with string", "{{with `notempty`}}{{.}}{{else}}EMPTY{{end}}", "notempty", tVal, true}, - {"with emptyslice", "{{with .SIEmpty}}{{.}}{{else}}EMPTY{{end}}", "EMPTY", tVal, true}, - {"with slice", "{{with .SI}}{{.}}{{else}}EMPTY{{end}}", "[3 4 5]", tVal, true}, - {"with emptymap", "{{with .MSIEmpty}}{{.}}{{else}}EMPTY{{end}}", "EMPTY", tVal, true}, - {"with map", "{{with .MSIone}}{{.}}{{else}}EMPTY{{end}}", "map[one:1]", tVal, true}, - {"with empty interface, struct field", "{{with .Empty4}}{{.V}}{{end}}", "UinEmpty", tVal, true}, - {"with $x int", "{{with $x := .I}}{{$x}}{{end}}", "17", tVal, true}, - {"with $x struct.U.V", "{{with $x := $}}{{$x.U.V}}{{end}}", "v", tVal, true}, - {"with variable and action", "{{with $x := $}}{{$y := $.U.V}}{{$y}}{{end}}", "v", tVal, true}, - - // Range. - {"range []int", "{{range .SI}}-{{.}}-{{end}}", "-3--4--5-", tVal, true}, - {"range empty no else", "{{range .SIEmpty}}-{{.}}-{{end}}", "", tVal, true}, - {"range []int else", "{{range .SI}}-{{.}}-{{else}}EMPTY{{end}}", "-3--4--5-", tVal, true}, - {"range empty else", "{{range .SIEmpty}}-{{.}}-{{else}}EMPTY{{end}}", "EMPTY", tVal, true}, - {"range []bool", "{{range .SB}}-{{.}}-{{end}}", "-true--false-", tVal, true}, - {"range []int method", "{{range .SI | .MAdd .I}}-{{.}}-{{end}}", "-20--21--22-", tVal, true}, - {"range map", "{{range .MSI}}-{{.}}-{{end}}", "-1--3--2-", tVal, true}, - {"range empty map no else", "{{range .MSIEmpty}}-{{.}}-{{end}}", "", tVal, true}, - {"range map else", "{{range .MSI}}-{{.}}-{{else}}EMPTY{{end}}", "-1--3--2-", tVal, true}, - {"range empty map else", "{{range .MSIEmpty}}-{{.}}-{{else}}EMPTY{{end}}", "EMPTY", tVal, true}, - {"range empty interface", "{{range .Empty3}}-{{.}}-{{else}}EMPTY{{end}}", "-7--8-", tVal, true}, - {"range empty nil", "{{range .Empty0}}-{{.}}-{{end}}", "", tVal, true}, - {"range $x SI", "{{range $x := .SI}}<{{$x}}>{{end}}", "<3><4><5>", tVal, true}, - {"range $x $y SI", "{{range $x, $y := .SI}}<{{$x}}={{$y}}>{{end}}", "<0=3><1=4><2=5>", tVal, true}, - {"range $x MSIone", "{{range $x := .MSIone}}<{{$x}}>{{end}}", "<1>", tVal, true}, - {"range $x $y MSIone", "{{range $x, $y := .MSIone}}<{{$x}}={{$y}}>{{end}}", "", tVal, true}, - {"range $x PSI", "{{range $x := .PSI}}<{{$x}}>{{end}}", "<21><22><23>", tVal, true}, - {"declare in range", "{{range $x := .PSI}}<{{$foo:=$x}}{{$x}}>{{end}}", "<21><22><23>", tVal, true}, - {"range count", `{{range $i, $x := count 5}}[{{$i}}]{{$x}}{{end}}`, "[0]a[1]b[2]c[3]d[4]e", tVal, true}, - {"range nil count", `{{range $i, $x := count 0}}{{else}}empty{{end}}`, "empty", tVal, true}, - - // Cute examples. - {"or as if true", `{{or .SI "slice is empty"}}`, "[3 4 5]", tVal, true}, - {"or as if false", `{{or .SIEmpty "slice is empty"}}`, "slice is empty", tVal, true}, - - // Error handling. - {"error method, error", "{{.MyError true}}", "", tVal, false}, - {"error method, no error", "{{.MyError false}}", "false", tVal, true}, - - // Fixed bugs. - // Must separate dot and receiver; otherwise args are evaluated with dot set to variable. - {"bug0", "{{range .MSIone}}{{if $.Method1 .}}X{{end}}{{end}}", "X", tVal, true}, - // Do not loop endlessly in indirect for non-empty interfaces. - // The bug appears with *interface only; looped forever. - {"bug1", "{{.Method0}}", "M0", &iVal, true}, - // Was taking address of interface field, so method set was empty. - {"bug2", "{{$.NonEmptyInterface.Method0}}", "M0", tVal, true}, - // Struct values were not legal in with - mere oversight. - {"bug3", "{{with $}}{{.Method0}}{{end}}", "M0", tVal, true}, - // Nil interface values in if. - {"bug4", "{{if .Empty0}}non-nil{{else}}nil{{end}}", "nil", tVal, true}, - // Stringer. - {"bug5", "{{.Str}}", "foozle", tVal, true}, - {"bug5a", "{{.Err}}", "erroozle", tVal, true}, - // Args need to be indirected and dereferenced sometimes. - {"bug6a", "{{vfunc .V0 .V1}}", "vfunc", tVal, true}, - {"bug6b", "{{vfunc .V0 .V0}}", "vfunc", tVal, true}, - {"bug6c", "{{vfunc .V1 .V0}}", "vfunc", tVal, true}, - {"bug6d", "{{vfunc .V1 .V1}}", "vfunc", tVal, true}, - // Legal parse but illegal execution: non-function should have no arguments. - {"bug7a", "{{3 2}}", "", tVal, false}, - {"bug7b", "{{$x := 1}}{{$x 2}}", "", tVal, false}, - {"bug7c", "{{$x := 1}}{{3 | $x}}", "", tVal, false}, - // Pipelined arg was not being type-checked. - {"bug8a", "{{3|oneArg}}", "", tVal, false}, - {"bug8b", "{{4|dddArg 3}}", "", tVal, false}, - // A bug was introduced that broke map lookups for lower-case names. - {"bug9", "{{.cause}}", "neglect", map[string]string{"cause": "neglect"}, true}, - // Field chain starting with function did not work. - {"bug10", "{{mapOfThree.three}}-{{(mapOfThree).three}}", "3-3", 0, true}, - // Dereferencing nil pointer while evaluating function arguments should not panic. Issue 7333. - {"bug11", "{{valueString .PS}}", "", T{}, false}, - // 0xef gave constant type float64. Issue 8622. - {"bug12xe", "{{printf `%T` 0xef}}", "int", T{}, true}, - {"bug12xE", "{{printf `%T` 0xEE}}", "int", T{}, true}, - {"bug12Xe", "{{printf `%T` 0Xef}}", "int", T{}, true}, - {"bug12XE", "{{printf `%T` 0XEE}}", "int", T{}, true}, - // Chained nodes did not work as arguments. Issue 8473. - {"bug13", "{{print (.Copy).I}}", "17", tVal, true}, -} - -func zeroArgs() string { - return "zeroArgs" -} - -func oneArg(a string) string { - return "oneArg=" + a -} - -func dddArg(a int, b ...string) string { - return fmt.Sprintln(a, b) -} - -// count returns a channel that will deliver n sequential 1-letter strings starting at "a" -func count(n int) chan string { - if n == 0 { - return nil - } - c := make(chan string) - go func() { - for i := 0; i < n; i++ { - c <- "abcdefghijklmnop"[i : i+1] - } - close(c) - }() - return c -} - -// vfunc takes a *V and a V -func vfunc(V, *V) string { - return "vfunc" -} - -// valueString takes a string, not a pointer. -func valueString(v string) string { - return "value is ignored" -} - -func add(args ...int) int { - sum := 0 - for _, x := range args { - sum += x - } - return sum -} - -func echo(arg interface{}) interface{} { - return arg -} - -func makemap(arg ...string) map[string]string { - if len(arg)%2 != 0 { - panic("bad makemap") - } - m := make(map[string]string) - for i := 0; i < len(arg); i += 2 { - m[arg[i]] = arg[i+1] - } - return m -} - -func stringer(s fmt.Stringer) string { - return s.String() -} - -func mapOfThree() interface{} { - return map[string]int{"three": 3} -} - -func testExecute(execTests []execTest, template *Template, t *testing.T) { - b := new(bytes.Buffer) - funcs := FuncMap{ - "add": add, - "count": count, - "dddArg": dddArg, - "echo": echo, - "makemap": makemap, - "mapOfThree": mapOfThree, - "oneArg": oneArg, - "stringer": stringer, - "typeOf": typeOf, - "valueString": valueString, - "vfunc": vfunc, - "zeroArgs": zeroArgs, - } - for _, test := range execTests { - var tmpl *Template - var err error - if template == nil { - tmpl, err = New(test.name).Funcs(funcs).Parse(test.input) - } else { - tmpl, err = template.New(test.name).Funcs(funcs).Parse(test.input) - } - if err != nil { - t.Errorf("%s: parse error: %s", test.name, err) - continue - } - b.Reset() - err = tmpl.Execute(b, test.data) - switch { - case !test.ok && err == nil: - t.Errorf("%s: expected error; got none", test.name) - continue - case test.ok && err != nil: - t.Errorf("%s: unexpected execute error: %s", test.name, err) - continue - case !test.ok && err != nil: - // expected error, got one - if *debug { - fmt.Printf("%s: %s\n\t%s\n", test.name, test.input, err) - } - } - result := b.String() - if result != test.output { - t.Errorf("%s: expected\n\t%q\ngot\n\t%q", test.name, test.output, result) - } - } -} - -func TestExecute(t *testing.T) { - testExecute(execTests, nil, t) -} - -var delimPairs = []string{ - "", "", // default - "{{", "}}", // same as default - "<<", ">>", // distinct - "|", "|", // same - "(日)", "(本)", // peculiar -} - -func TestDelims(t *testing.T) { - const hello = "Hello, world" - var value = struct{ Str string }{hello} - for i := 0; i < len(delimPairs); i += 2 { - text := ".Str" - left := delimPairs[i+0] - trueLeft := left - right := delimPairs[i+1] - trueRight := right - if left == "" { // default case - trueLeft = "{{" - } - if right == "" { // default case - trueRight = "}}" - } - text = trueLeft + text + trueRight - // Now add a comment - text += trueLeft + "/*comment*/" + trueRight - // Now add an action containing a string. - text += trueLeft + `"` + trueLeft + `"` + trueRight - // At this point text looks like `{{.Str}}{{/*comment*/}}{{"{{"}}`. - tmpl, err := New("delims").Delims(left, right).Parse(text) - if err != nil { - t.Fatalf("delim %q text %q parse err %s", left, text, err) - } - var b = new(bytes.Buffer) - err = tmpl.Execute(b, value) - if err != nil { - t.Fatalf("delim %q exec err %s", left, err) - } - if b.String() != hello+trueLeft { - t.Errorf("expected %q got %q", hello+trueLeft, b.String()) - } - } -} - -// Check that an error from a method flows back to the top. -func TestExecuteError(t *testing.T) { - b := new(bytes.Buffer) - tmpl := New("error") - _, err := tmpl.Parse("{{.MyError true}}") - if err != nil { - t.Fatalf("parse error: %s", err) - } - err = tmpl.Execute(b, tVal) - if err == nil { - t.Errorf("expected error; got none") - } else if !strings.Contains(err.Error(), myError.Error()) { - if *debug { - fmt.Printf("test execute error: %s\n", err) - } - t.Errorf("expected myError; got %s", err) - } -} - -const execErrorText = `line 1 -line 2 -line 3 -{{template "one" .}} -{{define "one"}}{{template "two" .}}{{end}} -{{define "two"}}{{template "three" .}}{{end}} -{{define "three"}}{{index "hi" $}}{{end}}` - -// Check that an error from a nested template contains all the relevant information. -func TestExecError(t *testing.T) { - tmpl, err := New("top").Parse(execErrorText) - if err != nil { - t.Fatal("parse error:", err) - } - var b bytes.Buffer - err = tmpl.Execute(&b, 5) // 5 is out of range indexing "hi" - if err == nil { - t.Fatal("expected error") - } - const want = `template: top:7:20: executing "three" at : error calling index: index out of range: 5` - got := err.Error() - if got != want { - t.Errorf("expected\n%q\ngot\n%q", want, got) - } -} - -func TestJSEscaping(t *testing.T) { - testCases := []struct { - in, exp string - }{ - {`a`, `a`}, - {`'foo`, `\'foo`}, - {`Go "jump" \`, `Go \"jump\" \\`}, - {`Yukihiro says "今日は世界"`, `Yukihiro says \"今日は世界\"`}, - {"unprintable \uFDFF", `unprintable \uFDFF`}, - {``, `\x3Chtml\x3E`}, - } - for _, tc := range testCases { - s := JSEscapeString(tc.in) - if s != tc.exp { - t.Errorf("JS escaping [%s] got [%s] want [%s]", tc.in, s, tc.exp) - } - } -} - -// A nice example: walk a binary tree. - -type Tree struct { - Val int - Left, Right *Tree -} - -// Use different delimiters to test Set.Delims. -const treeTemplate = ` - (define "tree") - [ - (.Val) - (with .Left) - (template "tree" .) - (end) - (with .Right) - (template "tree" .) - (end) - ] - (end) -` - -func TestTree(t *testing.T) { - var tree = &Tree{ - 1, - &Tree{ - 2, &Tree{ - 3, - &Tree{ - 4, nil, nil, - }, - nil, - }, - &Tree{ - 5, - &Tree{ - 6, nil, nil, - }, - nil, - }, - }, - &Tree{ - 7, - &Tree{ - 8, - &Tree{ - 9, nil, nil, - }, - nil, - }, - &Tree{ - 10, - &Tree{ - 11, nil, nil, - }, - nil, - }, - }, - } - tmpl, err := New("root").Delims("(", ")").Parse(treeTemplate) - if err != nil { - t.Fatal("parse error:", err) - } - var b bytes.Buffer - stripSpace := func(r rune) rune { - if r == '\t' || r == '\n' { - return -1 - } - return r - } - const expect = "[1[2[3[4]][5[6]]][7[8[9]][10[11]]]]" - // First by looking up the template. - err = tmpl.Lookup("tree").Execute(&b, tree) - if err != nil { - t.Fatal("exec error:", err) - } - result := strings.Map(stripSpace, b.String()) - if result != expect { - t.Errorf("expected %q got %q", expect, result) - } - // Then direct to execution. - b.Reset() - err = tmpl.ExecuteTemplate(&b, "tree", tree) - if err != nil { - t.Fatal("exec error:", err) - } - result = strings.Map(stripSpace, b.String()) - if result != expect { - t.Errorf("expected %q got %q", expect, result) - } -} - -func TestExecuteOnNewTemplate(t *testing.T) { - // This is issue 3872. - _ = New("Name").Templates() -} - -const testTemplates = `{{define "one"}}one{{end}}{{define "two"}}two{{end}}` - -func TestMessageForExecuteEmpty(t *testing.T) { - // Test a truly empty template. - tmpl := New("empty") - var b bytes.Buffer - err := tmpl.Execute(&b, 0) - if err == nil { - t.Fatal("expected initial error") - } - got := err.Error() - want := `template: empty: "empty" is an incomplete or empty template` - if got != want { - t.Errorf("expected error %s got %s", want, got) - } - // Add a non-empty template to check that the error is helpful. - tests, err := New("").Parse(testTemplates) - if err != nil { - t.Fatal(err) - } - tmpl.AddParseTree("secondary", tests.Tree) - err = tmpl.Execute(&b, 0) - if err == nil { - t.Fatal("expected second error") - } - got = err.Error() - want = `template: empty: "empty" is an incomplete or empty template; defined templates are: "secondary"` - if got != want { - t.Errorf("expected error %s got %s", want, got) - } - // Make sure we can execute the secondary. - err = tmpl.ExecuteTemplate(&b, "secondary", 0) - if err != nil { - t.Fatal(err) - } -} - -func TestFinalForPrintf(t *testing.T) { - tmpl, err := New("").Parse(`{{"x" | printf}}`) - if err != nil { - t.Fatal(err) - } - var b bytes.Buffer - err = tmpl.Execute(&b, 0) - if err != nil { - t.Fatal(err) - } -} - -type cmpTest struct { - expr string - truth string - ok bool -} - -var cmpTests = []cmpTest{ - {"eq true true", "true", true}, - {"eq true false", "false", true}, - {"eq 1+2i 1+2i", "true", true}, - {"eq 1+2i 1+3i", "false", true}, - {"eq 1.5 1.5", "true", true}, - {"eq 1.5 2.5", "false", true}, - {"eq 1 1", "true", true}, - {"eq 1 2", "false", true}, - {"eq `xy` `xy`", "true", true}, - {"eq `xy` `xyz`", "false", true}, - {"eq .Uthree .Uthree", "true", true}, - {"eq .Uthree .Ufour", "false", true}, - {"eq 3 4 5 6 3", "true", true}, - {"eq 3 4 5 6 7", "false", true}, - {"ne true true", "false", true}, - {"ne true false", "true", true}, - {"ne 1+2i 1+2i", "false", true}, - {"ne 1+2i 1+3i", "true", true}, - {"ne 1.5 1.5", "false", true}, - {"ne 1.5 2.5", "true", true}, - {"ne 1 1", "false", true}, - {"ne 1 2", "true", true}, - {"ne `xy` `xy`", "false", true}, - {"ne `xy` `xyz`", "true", true}, - {"ne .Uthree .Uthree", "false", true}, - {"ne .Uthree .Ufour", "true", true}, - {"lt 1.5 1.5", "false", true}, - {"lt 1.5 2.5", "true", true}, - {"lt 1 1", "false", true}, - {"lt 1 2", "true", true}, - {"lt `xy` `xy`", "false", true}, - {"lt `xy` `xyz`", "true", true}, - {"lt .Uthree .Uthree", "false", true}, - {"lt .Uthree .Ufour", "true", true}, - {"le 1.5 1.5", "true", true}, - {"le 1.5 2.5", "true", true}, - {"le 2.5 1.5", "false", true}, - {"le 1 1", "true", true}, - {"le 1 2", "true", true}, - {"le 2 1", "false", true}, - {"le `xy` `xy`", "true", true}, - {"le `xy` `xyz`", "true", true}, - {"le `xyz` `xy`", "false", true}, - {"le .Uthree .Uthree", "true", true}, - {"le .Uthree .Ufour", "true", true}, - {"le .Ufour .Uthree", "false", true}, - {"gt 1.5 1.5", "false", true}, - {"gt 1.5 2.5", "false", true}, - {"gt 1 1", "false", true}, - {"gt 2 1", "true", true}, - {"gt 1 2", "false", true}, - {"gt `xy` `xy`", "false", true}, - {"gt `xy` `xyz`", "false", true}, - {"gt .Uthree .Uthree", "false", true}, - {"gt .Uthree .Ufour", "false", true}, - {"gt .Ufour .Uthree", "true", true}, - {"ge 1.5 1.5", "true", true}, - {"ge 1.5 2.5", "false", true}, - {"ge 2.5 1.5", "true", true}, - {"ge 1 1", "true", true}, - {"ge 1 2", "false", true}, - {"ge 2 1", "true", true}, - {"ge `xy` `xy`", "true", true}, - {"ge `xy` `xyz`", "false", true}, - {"ge `xyz` `xy`", "true", true}, - {"ge .Uthree .Uthree", "true", true}, - {"ge .Uthree .Ufour", "false", true}, - {"ge .Ufour .Uthree", "true", true}, - // Mixing signed and unsigned integers. - {"eq .Uthree .Three", "true", true}, - {"eq .Three .Uthree", "true", true}, - {"le .Uthree .Three", "true", true}, - {"le .Three .Uthree", "true", true}, - {"ge .Uthree .Three", "true", true}, - {"ge .Three .Uthree", "true", true}, - {"lt .Uthree .Three", "false", true}, - {"lt .Three .Uthree", "false", true}, - {"gt .Uthree .Three", "false", true}, - {"gt .Three .Uthree", "false", true}, - {"eq .Ufour .Three", "false", true}, - {"lt .Ufour .Three", "false", true}, - {"gt .Ufour .Three", "true", true}, - {"eq .NegOne .Uthree", "false", true}, - {"eq .Uthree .NegOne", "false", true}, - {"ne .NegOne .Uthree", "true", true}, - {"ne .Uthree .NegOne", "true", true}, - {"lt .NegOne .Uthree", "true", true}, - {"lt .Uthree .NegOne", "false", true}, - {"le .NegOne .Uthree", "true", true}, - {"le .Uthree .NegOne", "false", true}, - {"gt .NegOne .Uthree", "false", true}, - {"gt .Uthree .NegOne", "true", true}, - {"ge .NegOne .Uthree", "false", true}, - {"ge .Uthree .NegOne", "true", true}, - {"eq (index `x` 0) 'x'", "true", true}, // The example that triggered this rule. - {"eq (index `x` 0) 'y'", "false", true}, - // Errors - {"eq `xy` 1", "", false}, // Different types. - {"eq 2 2.0", "", false}, // Different types. - {"lt true true", "", false}, // Unordered types. - {"lt 1+0i 1+0i", "", false}, // Unordered types. -} - -func TestComparison(t *testing.T) { - b := new(bytes.Buffer) - var cmpStruct = struct { - Uthree, Ufour uint - NegOne, Three int - }{3, 4, -1, 3} - for _, test := range cmpTests { - text := fmt.Sprintf("{{if %s}}true{{else}}false{{end}}", test.expr) - tmpl, err := New("empty").Parse(text) - if err != nil { - t.Fatalf("%q: %s", test.expr, err) - } - b.Reset() - err = tmpl.Execute(b, &cmpStruct) - if test.ok && err != nil { - t.Errorf("%s errored incorrectly: %s", test.expr, err) - continue - } - if !test.ok && err == nil { - t.Errorf("%s did not error", test.expr) - continue - } - if b.String() != test.truth { - t.Errorf("%s: want %s; got %s", test.expr, test.truth, b.String()) - } - } -} diff --git a/vendor/github.com/alecthomas/template/multi_test.go b/vendor/github.com/alecthomas/template/multi_test.go deleted file mode 100644 index 8d103623c..000000000 --- a/vendor/github.com/alecthomas/template/multi_test.go +++ /dev/null @@ -1,293 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package template - -// Tests for mulitple-template parsing and execution. - -import ( - "bytes" - "fmt" - "strings" - "testing" - - "github.com/alecthomas/template/parse" -) - -const ( - noError = true - hasError = false -) - -type multiParseTest struct { - name string - input string - ok bool - names []string - results []string -} - -var multiParseTests = []multiParseTest{ - {"empty", "", noError, - nil, - nil}, - {"one", `{{define "foo"}} FOO {{end}}`, noError, - []string{"foo"}, - []string{" FOO "}}, - {"two", `{{define "foo"}} FOO {{end}}{{define "bar"}} BAR {{end}}`, noError, - []string{"foo", "bar"}, - []string{" FOO ", " BAR "}}, - // errors - {"missing end", `{{define "foo"}} FOO `, hasError, - nil, - nil}, - {"malformed name", `{{define "foo}} FOO `, hasError, - nil, - nil}, -} - -func TestMultiParse(t *testing.T) { - for _, test := range multiParseTests { - template, err := New("root").Parse(test.input) - switch { - case err == nil && !test.ok: - t.Errorf("%q: expected error; got none", test.name) - continue - case err != nil && test.ok: - t.Errorf("%q: unexpected error: %v", test.name, err) - continue - case err != nil && !test.ok: - // expected error, got one - if *debug { - fmt.Printf("%s: %s\n\t%s\n", test.name, test.input, err) - } - continue - } - if template == nil { - continue - } - if len(template.tmpl) != len(test.names)+1 { // +1 for root - t.Errorf("%s: wrong number of templates; wanted %d got %d", test.name, len(test.names), len(template.tmpl)) - continue - } - for i, name := range test.names { - tmpl, ok := template.tmpl[name] - if !ok { - t.Errorf("%s: can't find template %q", test.name, name) - continue - } - result := tmpl.Root.String() - if result != test.results[i] { - t.Errorf("%s=(%q): got\n\t%v\nexpected\n\t%v", test.name, test.input, result, test.results[i]) - } - } - } -} - -var multiExecTests = []execTest{ - {"empty", "", "", nil, true}, - {"text", "some text", "some text", nil, true}, - {"invoke x", `{{template "x" .SI}}`, "TEXT", tVal, true}, - {"invoke x no args", `{{template "x"}}`, "TEXT", tVal, true}, - {"invoke dot int", `{{template "dot" .I}}`, "17", tVal, true}, - {"invoke dot []int", `{{template "dot" .SI}}`, "[3 4 5]", tVal, true}, - {"invoke dotV", `{{template "dotV" .U}}`, "v", tVal, true}, - {"invoke nested int", `{{template "nested" .I}}`, "17", tVal, true}, - {"variable declared by template", `{{template "nested" $x:=.SI}},{{index $x 1}}`, "[3 4 5],4", tVal, true}, - - // User-defined function: test argument evaluator. - {"testFunc literal", `{{oneArg "joe"}}`, "oneArg=joe", tVal, true}, - {"testFunc .", `{{oneArg .}}`, "oneArg=joe", "joe", true}, -} - -// These strings are also in testdata/*. -const multiText1 = ` - {{define "x"}}TEXT{{end}} - {{define "dotV"}}{{.V}}{{end}} -` - -const multiText2 = ` - {{define "dot"}}{{.}}{{end}} - {{define "nested"}}{{template "dot" .}}{{end}} -` - -func TestMultiExecute(t *testing.T) { - // Declare a couple of templates first. - template, err := New("root").Parse(multiText1) - if err != nil { - t.Fatalf("parse error for 1: %s", err) - } - _, err = template.Parse(multiText2) - if err != nil { - t.Fatalf("parse error for 2: %s", err) - } - testExecute(multiExecTests, template, t) -} - -func TestParseFiles(t *testing.T) { - _, err := ParseFiles("DOES NOT EXIST") - if err == nil { - t.Error("expected error for non-existent file; got none") - } - template := New("root") - _, err = template.ParseFiles("testdata/file1.tmpl", "testdata/file2.tmpl") - if err != nil { - t.Fatalf("error parsing files: %v", err) - } - testExecute(multiExecTests, template, t) -} - -func TestParseGlob(t *testing.T) { - _, err := ParseGlob("DOES NOT EXIST") - if err == nil { - t.Error("expected error for non-existent file; got none") - } - _, err = New("error").ParseGlob("[x") - if err == nil { - t.Error("expected error for bad pattern; got none") - } - template := New("root") - _, err = template.ParseGlob("testdata/file*.tmpl") - if err != nil { - t.Fatalf("error parsing files: %v", err) - } - testExecute(multiExecTests, template, t) -} - -// In these tests, actual content (not just template definitions) comes from the parsed files. - -var templateFileExecTests = []execTest{ - {"test", `{{template "tmpl1.tmpl"}}{{template "tmpl2.tmpl"}}`, "template1\n\ny\ntemplate2\n\nx\n", 0, true}, -} - -func TestParseFilesWithData(t *testing.T) { - template, err := New("root").ParseFiles("testdata/tmpl1.tmpl", "testdata/tmpl2.tmpl") - if err != nil { - t.Fatalf("error parsing files: %v", err) - } - testExecute(templateFileExecTests, template, t) -} - -func TestParseGlobWithData(t *testing.T) { - template, err := New("root").ParseGlob("testdata/tmpl*.tmpl") - if err != nil { - t.Fatalf("error parsing files: %v", err) - } - testExecute(templateFileExecTests, template, t) -} - -const ( - cloneText1 = `{{define "a"}}{{template "b"}}{{template "c"}}{{end}}` - cloneText2 = `{{define "b"}}b{{end}}` - cloneText3 = `{{define "c"}}root{{end}}` - cloneText4 = `{{define "c"}}clone{{end}}` -) - -func TestClone(t *testing.T) { - // Create some templates and clone the root. - root, err := New("root").Parse(cloneText1) - if err != nil { - t.Fatal(err) - } - _, err = root.Parse(cloneText2) - if err != nil { - t.Fatal(err) - } - clone := Must(root.Clone()) - // Add variants to both. - _, err = root.Parse(cloneText3) - if err != nil { - t.Fatal(err) - } - _, err = clone.Parse(cloneText4) - if err != nil { - t.Fatal(err) - } - // Verify that the clone is self-consistent. - for k, v := range clone.tmpl { - if k == clone.name && v.tmpl[k] != clone { - t.Error("clone does not contain root") - } - if v != v.tmpl[v.name] { - t.Errorf("clone does not contain self for %q", k) - } - } - // Execute root. - var b bytes.Buffer - err = root.ExecuteTemplate(&b, "a", 0) - if err != nil { - t.Fatal(err) - } - if b.String() != "broot" { - t.Errorf("expected %q got %q", "broot", b.String()) - } - // Execute copy. - b.Reset() - err = clone.ExecuteTemplate(&b, "a", 0) - if err != nil { - t.Fatal(err) - } - if b.String() != "bclone" { - t.Errorf("expected %q got %q", "bclone", b.String()) - } -} - -func TestAddParseTree(t *testing.T) { - // Create some templates. - root, err := New("root").Parse(cloneText1) - if err != nil { - t.Fatal(err) - } - _, err = root.Parse(cloneText2) - if err != nil { - t.Fatal(err) - } - // Add a new parse tree. - tree, err := parse.Parse("cloneText3", cloneText3, "", "", nil, builtins) - if err != nil { - t.Fatal(err) - } - added, err := root.AddParseTree("c", tree["c"]) - // Execute. - var b bytes.Buffer - err = added.ExecuteTemplate(&b, "a", 0) - if err != nil { - t.Fatal(err) - } - if b.String() != "broot" { - t.Errorf("expected %q got %q", "broot", b.String()) - } -} - -// Issue 7032 -func TestAddParseTreeToUnparsedTemplate(t *testing.T) { - master := "{{define \"master\"}}{{end}}" - tmpl := New("master") - tree, err := parse.Parse("master", master, "", "", nil) - if err != nil { - t.Fatalf("unexpected parse err: %v", err) - } - masterTree := tree["master"] - tmpl.AddParseTree("master", masterTree) // used to panic -} - -func TestRedefinition(t *testing.T) { - var tmpl *Template - var err error - if tmpl, err = New("tmpl1").Parse(`{{define "test"}}foo{{end}}`); err != nil { - t.Fatalf("parse 1: %v", err) - } - if _, err = tmpl.Parse(`{{define "test"}}bar{{end}}`); err == nil { - t.Fatal("expected error") - } - if !strings.Contains(err.Error(), "redefinition") { - t.Fatalf("expected redefinition error; got %v", err) - } - if _, err = tmpl.New("tmpl2").Parse(`{{define "test"}}bar{{end}}`); err == nil { - t.Fatal("expected error") - } - if !strings.Contains(err.Error(), "redefinition") { - t.Fatalf("expected redefinition error; got %v", err) - } -} diff --git a/vendor/github.com/alecthomas/template/parse/lex_test.go b/vendor/github.com/alecthomas/template/parse/lex_test.go deleted file mode 100644 index 3b921076a..000000000 --- a/vendor/github.com/alecthomas/template/parse/lex_test.go +++ /dev/null @@ -1,468 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package parse - -import ( - "fmt" - "testing" -) - -// Make the types prettyprint. -var itemName = map[itemType]string{ - itemError: "error", - itemBool: "bool", - itemChar: "char", - itemCharConstant: "charconst", - itemComplex: "complex", - itemColonEquals: ":=", - itemEOF: "EOF", - itemField: "field", - itemIdentifier: "identifier", - itemLeftDelim: "left delim", - itemLeftParen: "(", - itemNumber: "number", - itemPipe: "pipe", - itemRawString: "raw string", - itemRightDelim: "right delim", - itemElideNewline: "elide newline", - itemRightParen: ")", - itemSpace: "space", - itemString: "string", - itemVariable: "variable", - - // keywords - itemDot: ".", - itemDefine: "define", - itemElse: "else", - itemIf: "if", - itemEnd: "end", - itemNil: "nil", - itemRange: "range", - itemTemplate: "template", - itemWith: "with", -} - -func (i itemType) String() string { - s := itemName[i] - if s == "" { - return fmt.Sprintf("item%d", int(i)) - } - return s -} - -type lexTest struct { - name string - input string - items []item -} - -var ( - tEOF = item{itemEOF, 0, ""} - tFor = item{itemIdentifier, 0, "for"} - tLeft = item{itemLeftDelim, 0, "{{"} - tLpar = item{itemLeftParen, 0, "("} - tPipe = item{itemPipe, 0, "|"} - tQuote = item{itemString, 0, `"abc \n\t\" "`} - tRange = item{itemRange, 0, "range"} - tRight = item{itemRightDelim, 0, "}}"} - tElideNewline = item{itemElideNewline, 0, "\\"} - tRpar = item{itemRightParen, 0, ")"} - tSpace = item{itemSpace, 0, " "} - raw = "`" + `abc\n\t\" ` + "`" - tRawQuote = item{itemRawString, 0, raw} -) - -var lexTests = []lexTest{ - {"empty", "", []item{tEOF}}, - {"spaces", " \t\n", []item{{itemText, 0, " \t\n"}, tEOF}}, - {"text", `now is the time`, []item{{itemText, 0, "now is the time"}, tEOF}}, - {"elide newline", "{{}}\\", []item{tLeft, tRight, tElideNewline, tEOF}}, - {"text with comment", "hello-{{/* this is a comment */}}-world", []item{ - {itemText, 0, "hello-"}, - {itemText, 0, "-world"}, - tEOF, - }}, - {"punctuation", "{{,@% }}", []item{ - tLeft, - {itemChar, 0, ","}, - {itemChar, 0, "@"}, - {itemChar, 0, "%"}, - tSpace, - tRight, - tEOF, - }}, - {"parens", "{{((3))}}", []item{ - tLeft, - tLpar, - tLpar, - {itemNumber, 0, "3"}, - tRpar, - tRpar, - tRight, - tEOF, - }}, - {"empty action", `{{}}`, []item{tLeft, tRight, tEOF}}, - {"for", `{{for}}`, []item{tLeft, tFor, tRight, tEOF}}, - {"quote", `{{"abc \n\t\" "}}`, []item{tLeft, tQuote, tRight, tEOF}}, - {"raw quote", "{{" + raw + "}}", []item{tLeft, tRawQuote, tRight, tEOF}}, - {"numbers", "{{1 02 0x14 -7.2i 1e3 +1.2e-4 4.2i 1+2i}}", []item{ - tLeft, - {itemNumber, 0, "1"}, - tSpace, - {itemNumber, 0, "02"}, - tSpace, - {itemNumber, 0, "0x14"}, - tSpace, - {itemNumber, 0, "-7.2i"}, - tSpace, - {itemNumber, 0, "1e3"}, - tSpace, - {itemNumber, 0, "+1.2e-4"}, - tSpace, - {itemNumber, 0, "4.2i"}, - tSpace, - {itemComplex, 0, "1+2i"}, - tRight, - tEOF, - }}, - {"characters", `{{'a' '\n' '\'' '\\' '\u00FF' '\xFF' '本'}}`, []item{ - tLeft, - {itemCharConstant, 0, `'a'`}, - tSpace, - {itemCharConstant, 0, `'\n'`}, - tSpace, - {itemCharConstant, 0, `'\''`}, - tSpace, - {itemCharConstant, 0, `'\\'`}, - tSpace, - {itemCharConstant, 0, `'\u00FF'`}, - tSpace, - {itemCharConstant, 0, `'\xFF'`}, - tSpace, - {itemCharConstant, 0, `'本'`}, - tRight, - tEOF, - }}, - {"bools", "{{true false}}", []item{ - tLeft, - {itemBool, 0, "true"}, - tSpace, - {itemBool, 0, "false"}, - tRight, - tEOF, - }}, - {"dot", "{{.}}", []item{ - tLeft, - {itemDot, 0, "."}, - tRight, - tEOF, - }}, - {"nil", "{{nil}}", []item{ - tLeft, - {itemNil, 0, "nil"}, - tRight, - tEOF, - }}, - {"dots", "{{.x . .2 .x.y.z}}", []item{ - tLeft, - {itemField, 0, ".x"}, - tSpace, - {itemDot, 0, "."}, - tSpace, - {itemNumber, 0, ".2"}, - tSpace, - {itemField, 0, ".x"}, - {itemField, 0, ".y"}, - {itemField, 0, ".z"}, - tRight, - tEOF, - }}, - {"keywords", "{{range if else end with}}", []item{ - tLeft, - {itemRange, 0, "range"}, - tSpace, - {itemIf, 0, "if"}, - tSpace, - {itemElse, 0, "else"}, - tSpace, - {itemEnd, 0, "end"}, - tSpace, - {itemWith, 0, "with"}, - tRight, - tEOF, - }}, - {"variables", "{{$c := printf $ $hello $23 $ $var.Field .Method}}", []item{ - tLeft, - {itemVariable, 0, "$c"}, - tSpace, - {itemColonEquals, 0, ":="}, - tSpace, - {itemIdentifier, 0, "printf"}, - tSpace, - {itemVariable, 0, "$"}, - tSpace, - {itemVariable, 0, "$hello"}, - tSpace, - {itemVariable, 0, "$23"}, - tSpace, - {itemVariable, 0, "$"}, - tSpace, - {itemVariable, 0, "$var"}, - {itemField, 0, ".Field"}, - tSpace, - {itemField, 0, ".Method"}, - tRight, - tEOF, - }}, - {"variable invocation", "{{$x 23}}", []item{ - tLeft, - {itemVariable, 0, "$x"}, - tSpace, - {itemNumber, 0, "23"}, - tRight, - tEOF, - }}, - {"pipeline", `intro {{echo hi 1.2 |noargs|args 1 "hi"}} outro`, []item{ - {itemText, 0, "intro "}, - tLeft, - {itemIdentifier, 0, "echo"}, - tSpace, - {itemIdentifier, 0, "hi"}, - tSpace, - {itemNumber, 0, "1.2"}, - tSpace, - tPipe, - {itemIdentifier, 0, "noargs"}, - tPipe, - {itemIdentifier, 0, "args"}, - tSpace, - {itemNumber, 0, "1"}, - tSpace, - {itemString, 0, `"hi"`}, - tRight, - {itemText, 0, " outro"}, - tEOF, - }}, - {"declaration", "{{$v := 3}}", []item{ - tLeft, - {itemVariable, 0, "$v"}, - tSpace, - {itemColonEquals, 0, ":="}, - tSpace, - {itemNumber, 0, "3"}, - tRight, - tEOF, - }}, - {"2 declarations", "{{$v , $w := 3}}", []item{ - tLeft, - {itemVariable, 0, "$v"}, - tSpace, - {itemChar, 0, ","}, - tSpace, - {itemVariable, 0, "$w"}, - tSpace, - {itemColonEquals, 0, ":="}, - tSpace, - {itemNumber, 0, "3"}, - tRight, - tEOF, - }}, - {"field of parenthesized expression", "{{(.X).Y}}", []item{ - tLeft, - tLpar, - {itemField, 0, ".X"}, - tRpar, - {itemField, 0, ".Y"}, - tRight, - tEOF, - }}, - // errors - {"badchar", "#{{\x01}}", []item{ - {itemText, 0, "#"}, - tLeft, - {itemError, 0, "unrecognized character in action: U+0001"}, - }}, - {"unclosed action", "{{\n}}", []item{ - tLeft, - {itemError, 0, "unclosed action"}, - }}, - {"EOF in action", "{{range", []item{ - tLeft, - tRange, - {itemError, 0, "unclosed action"}, - }}, - {"unclosed quote", "{{\"\n\"}}", []item{ - tLeft, - {itemError, 0, "unterminated quoted string"}, - }}, - {"unclosed raw quote", "{{`xx\n`}}", []item{ - tLeft, - {itemError, 0, "unterminated raw quoted string"}, - }}, - {"unclosed char constant", "{{'\n}}", []item{ - tLeft, - {itemError, 0, "unterminated character constant"}, - }}, - {"bad number", "{{3k}}", []item{ - tLeft, - {itemError, 0, `bad number syntax: "3k"`}, - }}, - {"unclosed paren", "{{(3}}", []item{ - tLeft, - tLpar, - {itemNumber, 0, "3"}, - {itemError, 0, `unclosed left paren`}, - }}, - {"extra right paren", "{{3)}}", []item{ - tLeft, - {itemNumber, 0, "3"}, - tRpar, - {itemError, 0, `unexpected right paren U+0029 ')'`}, - }}, - - // Fixed bugs - // Many elements in an action blew the lookahead until - // we made lexInsideAction not loop. - {"long pipeline deadlock", "{{|||||}}", []item{ - tLeft, - tPipe, - tPipe, - tPipe, - tPipe, - tPipe, - tRight, - tEOF, - }}, - {"text with bad comment", "hello-{{/*/}}-world", []item{ - {itemText, 0, "hello-"}, - {itemError, 0, `unclosed comment`}, - }}, - {"text with comment close separted from delim", "hello-{{/* */ }}-world", []item{ - {itemText, 0, "hello-"}, - {itemError, 0, `comment ends before closing delimiter`}, - }}, - // This one is an error that we can't catch because it breaks templates with - // minimized JavaScript. Should have fixed it before Go 1.1. - {"unmatched right delimiter", "hello-{.}}-world", []item{ - {itemText, 0, "hello-{.}}-world"}, - tEOF, - }}, -} - -// collect gathers the emitted items into a slice. -func collect(t *lexTest, left, right string) (items []item) { - l := lex(t.name, t.input, left, right) - for { - item := l.nextItem() - items = append(items, item) - if item.typ == itemEOF || item.typ == itemError { - break - } - } - return -} - -func equal(i1, i2 []item, checkPos bool) bool { - if len(i1) != len(i2) { - return false - } - for k := range i1 { - if i1[k].typ != i2[k].typ { - return false - } - if i1[k].val != i2[k].val { - return false - } - if checkPos && i1[k].pos != i2[k].pos { - return false - } - } - return true -} - -func TestLex(t *testing.T) { - for _, test := range lexTests { - items := collect(&test, "", "") - if !equal(items, test.items, false) { - t.Errorf("%s: got\n\t%+v\nexpected\n\t%v", test.name, items, test.items) - } - } -} - -// Some easy cases from above, but with delimiters $$ and @@ -var lexDelimTests = []lexTest{ - {"punctuation", "$$,@%{{}}@@", []item{ - tLeftDelim, - {itemChar, 0, ","}, - {itemChar, 0, "@"}, - {itemChar, 0, "%"}, - {itemChar, 0, "{"}, - {itemChar, 0, "{"}, - {itemChar, 0, "}"}, - {itemChar, 0, "}"}, - tRightDelim, - tEOF, - }}, - {"empty action", `$$@@`, []item{tLeftDelim, tRightDelim, tEOF}}, - {"for", `$$for@@`, []item{tLeftDelim, tFor, tRightDelim, tEOF}}, - {"quote", `$$"abc \n\t\" "@@`, []item{tLeftDelim, tQuote, tRightDelim, tEOF}}, - {"raw quote", "$$" + raw + "@@", []item{tLeftDelim, tRawQuote, tRightDelim, tEOF}}, -} - -var ( - tLeftDelim = item{itemLeftDelim, 0, "$$"} - tRightDelim = item{itemRightDelim, 0, "@@"} -) - -func TestDelims(t *testing.T) { - for _, test := range lexDelimTests { - items := collect(&test, "$$", "@@") - if !equal(items, test.items, false) { - t.Errorf("%s: got\n\t%v\nexpected\n\t%v", test.name, items, test.items) - } - } -} - -var lexPosTests = []lexTest{ - {"empty", "", []item{tEOF}}, - {"punctuation", "{{,@%#}}", []item{ - {itemLeftDelim, 0, "{{"}, - {itemChar, 2, ","}, - {itemChar, 3, "@"}, - {itemChar, 4, "%"}, - {itemChar, 5, "#"}, - {itemRightDelim, 6, "}}"}, - {itemEOF, 8, ""}, - }}, - {"sample", "0123{{hello}}xyz", []item{ - {itemText, 0, "0123"}, - {itemLeftDelim, 4, "{{"}, - {itemIdentifier, 6, "hello"}, - {itemRightDelim, 11, "}}"}, - {itemText, 13, "xyz"}, - {itemEOF, 16, ""}, - }}, -} - -// The other tests don't check position, to make the test cases easier to construct. -// This one does. -func TestPos(t *testing.T) { - for _, test := range lexPosTests { - items := collect(&test, "", "") - if !equal(items, test.items, true) { - t.Errorf("%s: got\n\t%v\nexpected\n\t%v", test.name, items, test.items) - if len(items) == len(test.items) { - // Detailed print; avoid item.String() to expose the position value. - for i := range items { - if !equal(items[i:i+1], test.items[i:i+1], true) { - i1 := items[i] - i2 := test.items[i] - t.Errorf("\t#%d: got {%v %d %q} expected {%v %d %q}", i, i1.typ, i1.pos, i1.val, i2.typ, i2.pos, i2.val) - } - } - } - } - } -} diff --git a/vendor/github.com/alecthomas/template/parse/parse_test.go b/vendor/github.com/alecthomas/template/parse/parse_test.go deleted file mode 100644 index c73640fb8..000000000 --- a/vendor/github.com/alecthomas/template/parse/parse_test.go +++ /dev/null @@ -1,426 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package parse - -import ( - "flag" - "fmt" - "strings" - "testing" -) - -var debug = flag.Bool("debug", false, "show the errors produced by the main tests") - -type numberTest struct { - text string - isInt bool - isUint bool - isFloat bool - isComplex bool - int64 - uint64 - float64 - complex128 -} - -var numberTests = []numberTest{ - // basics - {"0", true, true, true, false, 0, 0, 0, 0}, - {"-0", true, true, true, false, 0, 0, 0, 0}, // check that -0 is a uint. - {"73", true, true, true, false, 73, 73, 73, 0}, - {"073", true, true, true, false, 073, 073, 073, 0}, - {"0x73", true, true, true, false, 0x73, 0x73, 0x73, 0}, - {"-73", true, false, true, false, -73, 0, -73, 0}, - {"+73", true, false, true, false, 73, 0, 73, 0}, - {"100", true, true, true, false, 100, 100, 100, 0}, - {"1e9", true, true, true, false, 1e9, 1e9, 1e9, 0}, - {"-1e9", true, false, true, false, -1e9, 0, -1e9, 0}, - {"-1.2", false, false, true, false, 0, 0, -1.2, 0}, - {"1e19", false, true, true, false, 0, 1e19, 1e19, 0}, - {"-1e19", false, false, true, false, 0, 0, -1e19, 0}, - {"4i", false, false, false, true, 0, 0, 0, 4i}, - {"-1.2+4.2i", false, false, false, true, 0, 0, 0, -1.2 + 4.2i}, - {"073i", false, false, false, true, 0, 0, 0, 73i}, // not octal! - // complex with 0 imaginary are float (and maybe integer) - {"0i", true, true, true, true, 0, 0, 0, 0}, - {"-1.2+0i", false, false, true, true, 0, 0, -1.2, -1.2}, - {"-12+0i", true, false, true, true, -12, 0, -12, -12}, - {"13+0i", true, true, true, true, 13, 13, 13, 13}, - // funny bases - {"0123", true, true, true, false, 0123, 0123, 0123, 0}, - {"-0x0", true, true, true, false, 0, 0, 0, 0}, - {"0xdeadbeef", true, true, true, false, 0xdeadbeef, 0xdeadbeef, 0xdeadbeef, 0}, - // character constants - {`'a'`, true, true, true, false, 'a', 'a', 'a', 0}, - {`'\n'`, true, true, true, false, '\n', '\n', '\n', 0}, - {`'\\'`, true, true, true, false, '\\', '\\', '\\', 0}, - {`'\''`, true, true, true, false, '\'', '\'', '\'', 0}, - {`'\xFF'`, true, true, true, false, 0xFF, 0xFF, 0xFF, 0}, - {`'パ'`, true, true, true, false, 0x30d1, 0x30d1, 0x30d1, 0}, - {`'\u30d1'`, true, true, true, false, 0x30d1, 0x30d1, 0x30d1, 0}, - {`'\U000030d1'`, true, true, true, false, 0x30d1, 0x30d1, 0x30d1, 0}, - // some broken syntax - {text: "+-2"}, - {text: "0x123."}, - {text: "1e."}, - {text: "0xi."}, - {text: "1+2."}, - {text: "'x"}, - {text: "'xx'"}, - // Issue 8622 - 0xe parsed as floating point. Very embarrassing. - {"0xef", true, true, true, false, 0xef, 0xef, 0xef, 0}, -} - -func TestNumberParse(t *testing.T) { - for _, test := range numberTests { - // If fmt.Sscan thinks it's complex, it's complex. We can't trust the output - // because imaginary comes out as a number. - var c complex128 - typ := itemNumber - var tree *Tree - if test.text[0] == '\'' { - typ = itemCharConstant - } else { - _, err := fmt.Sscan(test.text, &c) - if err == nil { - typ = itemComplex - } - } - n, err := tree.newNumber(0, test.text, typ) - ok := test.isInt || test.isUint || test.isFloat || test.isComplex - if ok && err != nil { - t.Errorf("unexpected error for %q: %s", test.text, err) - continue - } - if !ok && err == nil { - t.Errorf("expected error for %q", test.text) - continue - } - if !ok { - if *debug { - fmt.Printf("%s\n\t%s\n", test.text, err) - } - continue - } - if n.IsComplex != test.isComplex { - t.Errorf("complex incorrect for %q; should be %t", test.text, test.isComplex) - } - if test.isInt { - if !n.IsInt { - t.Errorf("expected integer for %q", test.text) - } - if n.Int64 != test.int64 { - t.Errorf("int64 for %q should be %d Is %d", test.text, test.int64, n.Int64) - } - } else if n.IsInt { - t.Errorf("did not expect integer for %q", test.text) - } - if test.isUint { - if !n.IsUint { - t.Errorf("expected unsigned integer for %q", test.text) - } - if n.Uint64 != test.uint64 { - t.Errorf("uint64 for %q should be %d Is %d", test.text, test.uint64, n.Uint64) - } - } else if n.IsUint { - t.Errorf("did not expect unsigned integer for %q", test.text) - } - if test.isFloat { - if !n.IsFloat { - t.Errorf("expected float for %q", test.text) - } - if n.Float64 != test.float64 { - t.Errorf("float64 for %q should be %g Is %g", test.text, test.float64, n.Float64) - } - } else if n.IsFloat { - t.Errorf("did not expect float for %q", test.text) - } - if test.isComplex { - if !n.IsComplex { - t.Errorf("expected complex for %q", test.text) - } - if n.Complex128 != test.complex128 { - t.Errorf("complex128 for %q should be %g Is %g", test.text, test.complex128, n.Complex128) - } - } else if n.IsComplex { - t.Errorf("did not expect complex for %q", test.text) - } - } -} - -type parseTest struct { - name string - input string - ok bool - result string // what the user would see in an error message. -} - -const ( - noError = true - hasError = false -) - -var parseTests = []parseTest{ - {"empty", "", noError, - ``}, - {"comment", "{{/*\n\n\n*/}}", noError, - ``}, - {"spaces", " \t\n", noError, - `" \t\n"`}, - {"text", "some text", noError, - `"some text"`}, - {"emptyAction", "{{}}", hasError, - `{{}}`}, - {"field", "{{.X}}", noError, - `{{.X}}`}, - {"simple command", "{{printf}}", noError, - `{{printf}}`}, - {"$ invocation", "{{$}}", noError, - "{{$}}"}, - {"variable invocation", "{{with $x := 3}}{{$x 23}}{{end}}", noError, - "{{with $x := 3}}{{$x 23}}{{end}}"}, - {"variable with fields", "{{$.I}}", noError, - "{{$.I}}"}, - {"multi-word command", "{{printf `%d` 23}}", noError, - "{{printf `%d` 23}}"}, - {"pipeline", "{{.X|.Y}}", noError, - `{{.X | .Y}}`}, - {"pipeline with decl", "{{$x := .X|.Y}}", noError, - `{{$x := .X | .Y}}`}, - {"nested pipeline", "{{.X (.Y .Z) (.A | .B .C) (.E)}}", noError, - `{{.X (.Y .Z) (.A | .B .C) (.E)}}`}, - {"field applied to parentheses", "{{(.Y .Z).Field}}", noError, - `{{(.Y .Z).Field}}`}, - {"simple if", "{{if .X}}hello{{end}}", noError, - `{{if .X}}"hello"{{end}}`}, - {"if with else", "{{if .X}}true{{else}}false{{end}}", noError, - `{{if .X}}"true"{{else}}"false"{{end}}`}, - {"if with else if", "{{if .X}}true{{else if .Y}}false{{end}}", noError, - `{{if .X}}"true"{{else}}{{if .Y}}"false"{{end}}{{end}}`}, - {"if else chain", "+{{if .X}}X{{else if .Y}}Y{{else if .Z}}Z{{end}}+", noError, - `"+"{{if .X}}"X"{{else}}{{if .Y}}"Y"{{else}}{{if .Z}}"Z"{{end}}{{end}}{{end}}"+"`}, - {"simple range", "{{range .X}}hello{{end}}", noError, - `{{range .X}}"hello"{{end}}`}, - {"chained field range", "{{range .X.Y.Z}}hello{{end}}", noError, - `{{range .X.Y.Z}}"hello"{{end}}`}, - {"nested range", "{{range .X}}hello{{range .Y}}goodbye{{end}}{{end}}", noError, - `{{range .X}}"hello"{{range .Y}}"goodbye"{{end}}{{end}}`}, - {"range with else", "{{range .X}}true{{else}}false{{end}}", noError, - `{{range .X}}"true"{{else}}"false"{{end}}`}, - {"range over pipeline", "{{range .X|.M}}true{{else}}false{{end}}", noError, - `{{range .X | .M}}"true"{{else}}"false"{{end}}`}, - {"range []int", "{{range .SI}}{{.}}{{end}}", noError, - `{{range .SI}}{{.}}{{end}}`}, - {"range 1 var", "{{range $x := .SI}}{{.}}{{end}}", noError, - `{{range $x := .SI}}{{.}}{{end}}`}, - {"range 2 vars", "{{range $x, $y := .SI}}{{.}}{{end}}", noError, - `{{range $x, $y := .SI}}{{.}}{{end}}`}, - {"constants", "{{range .SI 1 -3.2i true false 'a' nil}}{{end}}", noError, - `{{range .SI 1 -3.2i true false 'a' nil}}{{end}}`}, - {"template", "{{template `x`}}", noError, - `{{template "x"}}`}, - {"template with arg", "{{template `x` .Y}}", noError, - `{{template "x" .Y}}`}, - {"with", "{{with .X}}hello{{end}}", noError, - `{{with .X}}"hello"{{end}}`}, - {"with with else", "{{with .X}}hello{{else}}goodbye{{end}}", noError, - `{{with .X}}"hello"{{else}}"goodbye"{{end}}`}, - {"elide newline", "{{true}}\\\n ", noError, - `{{true}}" "`}, - // Errors. - {"unclosed action", "hello{{range", hasError, ""}, - {"unmatched end", "{{end}}", hasError, ""}, - {"missing end", "hello{{range .x}}", hasError, ""}, - {"missing end after else", "hello{{range .x}}{{else}}", hasError, ""}, - {"undefined function", "hello{{undefined}}", hasError, ""}, - {"undefined variable", "{{$x}}", hasError, ""}, - {"variable undefined after end", "{{with $x := 4}}{{end}}{{$x}}", hasError, ""}, - {"variable undefined in template", "{{template $v}}", hasError, ""}, - {"declare with field", "{{with $x.Y := 4}}{{end}}", hasError, ""}, - {"template with field ref", "{{template .X}}", hasError, ""}, - {"template with var", "{{template $v}}", hasError, ""}, - {"invalid punctuation", "{{printf 3, 4}}", hasError, ""}, - {"multidecl outside range", "{{with $v, $u := 3}}{{end}}", hasError, ""}, - {"too many decls in range", "{{range $u, $v, $w := 3}}{{end}}", hasError, ""}, - {"dot applied to parentheses", "{{printf (printf .).}}", hasError, ""}, - {"adjacent args", "{{printf 3`x`}}", hasError, ""}, - {"adjacent args with .", "{{printf `x`.}}", hasError, ""}, - {"extra end after if", "{{if .X}}a{{else if .Y}}b{{end}}{{end}}", hasError, ""}, - {"invalid newline elision", "{{true}}\\{{true}}", hasError, ""}, - // Equals (and other chars) do not assignments make (yet). - {"bug0a", "{{$x := 0}}{{$x}}", noError, "{{$x := 0}}{{$x}}"}, - {"bug0b", "{{$x = 1}}{{$x}}", hasError, ""}, - {"bug0c", "{{$x ! 2}}{{$x}}", hasError, ""}, - {"bug0d", "{{$x % 3}}{{$x}}", hasError, ""}, - // Check the parse fails for := rather than comma. - {"bug0e", "{{range $x := $y := 3}}{{end}}", hasError, ""}, - // Another bug: variable read must ignore following punctuation. - {"bug1a", "{{$x:=.}}{{$x!2}}", hasError, ""}, // ! is just illegal here. - {"bug1b", "{{$x:=.}}{{$x+2}}", hasError, ""}, // $x+2 should not parse as ($x) (+2). - {"bug1c", "{{$x:=.}}{{$x +2}}", noError, "{{$x := .}}{{$x +2}}"}, // It's OK with a space. -} - -var builtins = map[string]interface{}{ - "printf": fmt.Sprintf, -} - -func testParse(doCopy bool, t *testing.T) { - textFormat = "%q" - defer func() { textFormat = "%s" }() - for _, test := range parseTests { - tmpl, err := New(test.name).Parse(test.input, "", "", make(map[string]*Tree), builtins) - switch { - case err == nil && !test.ok: - t.Errorf("%q: expected error; got none", test.name) - continue - case err != nil && test.ok: - t.Errorf("%q: unexpected error: %v", test.name, err) - continue - case err != nil && !test.ok: - // expected error, got one - if *debug { - fmt.Printf("%s: %s\n\t%s\n", test.name, test.input, err) - } - continue - } - var result string - if doCopy { - result = tmpl.Root.Copy().String() - } else { - result = tmpl.Root.String() - } - if result != test.result { - t.Errorf("%s=(%q): got\n\t%v\nexpected\n\t%v", test.name, test.input, result, test.result) - } - } -} - -func TestParse(t *testing.T) { - testParse(false, t) -} - -// Same as TestParse, but we copy the node first -func TestParseCopy(t *testing.T) { - testParse(true, t) -} - -type isEmptyTest struct { - name string - input string - empty bool -} - -var isEmptyTests = []isEmptyTest{ - {"empty", ``, true}, - {"nonempty", `hello`, false}, - {"spaces only", " \t\n \t\n", true}, - {"definition", `{{define "x"}}something{{end}}`, true}, - {"definitions and space", "{{define `x`}}something{{end}}\n\n{{define `y`}}something{{end}}\n\n", true}, - {"definitions and text", "{{define `x`}}something{{end}}\nx\n{{define `y`}}something{{end}}\ny\n", false}, - {"definition and action", "{{define `x`}}something{{end}}{{if 3}}foo{{end}}", false}, -} - -func TestIsEmpty(t *testing.T) { - if !IsEmptyTree(nil) { - t.Errorf("nil tree is not empty") - } - for _, test := range isEmptyTests { - tree, err := New("root").Parse(test.input, "", "", make(map[string]*Tree), nil) - if err != nil { - t.Errorf("%q: unexpected error: %v", test.name, err) - continue - } - if empty := IsEmptyTree(tree.Root); empty != test.empty { - t.Errorf("%q: expected %t got %t", test.name, test.empty, empty) - } - } -} - -func TestErrorContextWithTreeCopy(t *testing.T) { - tree, err := New("root").Parse("{{if true}}{{end}}", "", "", make(map[string]*Tree), nil) - if err != nil { - t.Fatalf("unexpected tree parse failure: %v", err) - } - treeCopy := tree.Copy() - wantLocation, wantContext := tree.ErrorContext(tree.Root.Nodes[0]) - gotLocation, gotContext := treeCopy.ErrorContext(treeCopy.Root.Nodes[0]) - if wantLocation != gotLocation { - t.Errorf("wrong error location want %q got %q", wantLocation, gotLocation) - } - if wantContext != gotContext { - t.Errorf("wrong error location want %q got %q", wantContext, gotContext) - } -} - -// All failures, and the result is a string that must appear in the error message. -var errorTests = []parseTest{ - // Check line numbers are accurate. - {"unclosed1", - "line1\n{{", - hasError, `unclosed1:2: unexpected unclosed action in command`}, - {"unclosed2", - "line1\n{{define `x`}}line2\n{{", - hasError, `unclosed2:3: unexpected unclosed action in command`}, - // Specific errors. - {"function", - "{{foo}}", - hasError, `function "foo" not defined`}, - {"comment", - "{{/*}}", - hasError, `unclosed comment`}, - {"lparen", - "{{.X (1 2 3}}", - hasError, `unclosed left paren`}, - {"rparen", - "{{.X 1 2 3)}}", - hasError, `unexpected ")"`}, - {"space", - "{{`x`3}}", - hasError, `missing space?`}, - {"idchar", - "{{a#}}", - hasError, `'#'`}, - {"charconst", - "{{'a}}", - hasError, `unterminated character constant`}, - {"stringconst", - `{{"a}}`, - hasError, `unterminated quoted string`}, - {"rawstringconst", - "{{`a}}", - hasError, `unterminated raw quoted string`}, - {"number", - "{{0xi}}", - hasError, `number syntax`}, - {"multidefine", - "{{define `a`}}a{{end}}{{define `a`}}b{{end}}", - hasError, `multiple definition of template`}, - {"eof", - "{{range .X}}", - hasError, `unexpected EOF`}, - {"variable", - // Declare $x so it's defined, to avoid that error, and then check we don't parse a declaration. - "{{$x := 23}}{{with $x.y := 3}}{{$x 23}}{{end}}", - hasError, `unexpected ":="`}, - {"multidecl", - "{{$a,$b,$c := 23}}", - hasError, `too many declarations`}, - {"undefvar", - "{{$a}}", - hasError, `undefined variable`}, -} - -func TestErrors(t *testing.T) { - for _, test := range errorTests { - _, err := New(test.name).Parse(test.input, "", "", make(map[string]*Tree)) - if err == nil { - t.Errorf("%q: expected error", test.name) - continue - } - if !strings.Contains(err.Error(), test.result) { - t.Errorf("%q: error %q does not contain %q", test.name, err, test.result) - } - } -} diff --git a/vendor/github.com/alecthomas/units/README.md b/vendor/github.com/alecthomas/units/README.md deleted file mode 100644 index bee884e3c..000000000 --- a/vendor/github.com/alecthomas/units/README.md +++ /dev/null @@ -1,11 +0,0 @@ -# Units - Helpful unit multipliers and functions for Go - -The goal of this package is to have functionality similar to the [time](http://golang.org/pkg/time/) package. - -It allows for code like this: - -```go -n, err := ParseBase2Bytes("1KB") -// n == 1024 -n = units.Mebibyte * 512 -``` diff --git a/vendor/github.com/alecthomas/units/bytes_test.go b/vendor/github.com/alecthomas/units/bytes_test.go deleted file mode 100644 index 6cbc79de4..000000000 --- a/vendor/github.com/alecthomas/units/bytes_test.go +++ /dev/null @@ -1,49 +0,0 @@ -package units - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestBase2BytesString(t *testing.T) { - assert.Equal(t, Base2Bytes(0).String(), "0B") - assert.Equal(t, Base2Bytes(1025).String(), "1KiB1B") - assert.Equal(t, Base2Bytes(1048577).String(), "1MiB1B") -} - -func TestParseBase2Bytes(t *testing.T) { - n, err := ParseBase2Bytes("0B") - assert.NoError(t, err) - assert.Equal(t, 0, int(n)) - n, err = ParseBase2Bytes("1KB") - assert.NoError(t, err) - assert.Equal(t, 1024, int(n)) - n, err = ParseBase2Bytes("1MB1KB25B") - assert.NoError(t, err) - assert.Equal(t, 1049625, int(n)) - n, err = ParseBase2Bytes("1.5MB") - assert.NoError(t, err) - assert.Equal(t, 1572864, int(n)) -} - -func TestMetricBytesString(t *testing.T) { - assert.Equal(t, MetricBytes(0).String(), "0B") - assert.Equal(t, MetricBytes(1001).String(), "1KB1B") - assert.Equal(t, MetricBytes(1001025).String(), "1MB1KB25B") -} - -func TestParseMetricBytes(t *testing.T) { - n, err := ParseMetricBytes("0B") - assert.NoError(t, err) - assert.Equal(t, 0, int(n)) - n, err = ParseMetricBytes("1KB1B") - assert.NoError(t, err) - assert.Equal(t, 1001, int(n)) - n, err = ParseMetricBytes("1MB1KB25B") - assert.NoError(t, err) - assert.Equal(t, 1001025, int(n)) - n, err = ParseMetricBytes("1.5MB") - assert.NoError(t, err) - assert.Equal(t, 1500000, int(n)) -} diff --git a/vendor/github.com/aws/aws-sdk-go/.gitignore b/vendor/github.com/aws/aws-sdk-go/.gitignore deleted file mode 100644 index fb11ceca0..000000000 --- a/vendor/github.com/aws/aws-sdk-go/.gitignore +++ /dev/null @@ -1,11 +0,0 @@ -dist -/doc -/doc-staging -.yardoc -Gemfile.lock -awstesting/integration/smoke/**/importmarker__.go -awstesting/integration/smoke/_test/ -/vendor/bin/ -/vendor/pkg/ -/vendor/src/ -/private/model/cli/gen-api/gen-api diff --git a/vendor/github.com/aws/aws-sdk-go/.godoc_config b/vendor/github.com/aws/aws-sdk-go/.godoc_config deleted file mode 100644 index 395878d6c..000000000 --- a/vendor/github.com/aws/aws-sdk-go/.godoc_config +++ /dev/null @@ -1,14 +0,0 @@ -{ - "PkgHandler": { - "Pattern": "/sdk-for-go/api/", - "StripPrefix": "/sdk-for-go/api", - "Include": ["/src/github.com/aws/aws-sdk-go/aws", "/src/github.com/aws/aws-sdk-go/service"], - "Exclude": ["/src/cmd", "/src/github.com/aws/aws-sdk-go/awstesting", "/src/github.com/aws/aws-sdk-go/awsmigrate"], - "IgnoredSuffixes": ["iface"] - }, - "Github": { - "Tag": "master", - "Repo": "/aws/aws-sdk-go", - "UseGithub": true - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/.travis.yml b/vendor/github.com/aws/aws-sdk-go/.travis.yml deleted file mode 100644 index 130d91151..000000000 --- a/vendor/github.com/aws/aws-sdk-go/.travis.yml +++ /dev/null @@ -1,25 +0,0 @@ -language: go - -sudo: required - -go: - - 1.5 - - 1.6 - - 1.7 - - 1.8 - - 1.9 - - tip - -# Use Go 1.5's vendoring experiment for 1.5 tests. -env: - - GO15VENDOREXPERIMENT=1 - -install: - - make get-deps - -script: - - make unit-with-race-cover - -matrix: - allow_failures: - - go: tip diff --git a/vendor/github.com/aws/aws-sdk-go/CHANGELOG.md b/vendor/github.com/aws/aws-sdk-go/CHANGELOG.md deleted file mode 100644 index 552ff9794..000000000 --- a/vendor/github.com/aws/aws-sdk-go/CHANGELOG.md +++ /dev/null @@ -1,2022 +0,0 @@ -Release v1.12.10 (2017-10-12) -=== - -### Service Client Updates -* `service/codecommit`: Updates service API and documentation - * This release includes the DeleteBranch API and a change to the contents of a Commit object. -* `service/dms`: Updates service API and documentation - * This change includes addition of new optional parameter to an existing API -* `service/elasticbeanstalk`: Updates service API and documentation - * Added the ability to add, delete or update Tags -* `service/polly`: Updates service API - * Amazon Polly exposes two new voices: "Matthew" (US English) and "Takumi" (Japanese) -* `service/rds`: Updates service API and documentation - * You can now call DescribeValidDBInstanceModifications to learn what modifications you can make to your DB instance. You can use this information when you call ModifyDBInstance. - -Release v1.12.9 (2017-10-11) -=== - -### Service Client Updates -* `service/ecr`: Updates service API, documentation, and paginators - * Adds support for new API set used to manage Amazon ECR repository lifecycle policies. Amazon ECR lifecycle policies enable you to specify the lifecycle management of images in a repository. The configuration is a set of one or more rules, where each rule defines an action for Amazon ECR to apply to an image. This allows the automation of cleaning up unused images, for example expiring images based on age or status. A lifecycle policy preview API is provided as well, which allows you to see the impact of a lifecycle policy on an image repository before you execute it -* `service/email`: Updates service API and documentation - * Added content related to email template management and templated email sending operations. -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -Release v1.12.8 (2017-10-10) -=== - -### Service Client Updates -* `service/ec2`: Updates service API and documentation - * This release includes updates to AWS Virtual Private Gateway. -* `service/elasticloadbalancingv2`: Updates service API and documentation -* `service/opsworkscm`: Updates service API and documentation - * Provide engine specific information for node associations. - -Release v1.12.7 (2017-10-06) -=== - -### Service Client Updates -* `service/sqs`: Updates service documentation - * Documentation updates regarding availability of FIFO queues and miscellaneous corrections. - -Release v1.12.6 (2017-10-05) -=== - -### Service Client Updates -* `service/redshift`: Updates service API and documentation - * DescribeEventSubscriptions API supports tag keys and tag values as request parameters. - -Release v1.12.5 (2017-10-04) -=== - -### Service Client Updates -* `service/kinesisanalytics`: Updates service API and documentation - * Kinesis Analytics now supports schema discovery on objects in S3. Additionally, Kinesis Analytics now supports input data preprocessing through Lambda. -* `service/route53domains`: Updates service API and documentation - * Added a new API that checks whether a domain name can be transferred to Amazon Route 53. - -### SDK Bugs -* `service/s3/s3crypto`: Correct PutObjectRequest documentation ([#1568](https://github.com/aws/aws-sdk-go/pull/1568)) - * s3Crypto's PutObjectRequest docstring example was using an incorrect value. Corrected the type used in the example. -Release v1.12.4 (2017-10-03) -=== - -### Service Client Updates -* `service/ec2`: Updates service API, documentation, and waiters - * This release includes service updates to AWS VPN. -* `service/ssm`: Updates service API and documentation - * EC2 Systems Manager support for tagging SSM Documents. Also support for tag-based permissions to restrict access to SSM Documents based on these tags. - -Release v1.12.3 (2017-10-02) -=== - -### Service Client Updates -* `service/cloudhsm`: Updates service documentation and paginators - * Documentation updates for CloudHSM - -Release v1.12.2 (2017-09-29) -=== - -### Service Client Updates -* `service/appstream`: Updates service API and documentation - * Includes APIs for managing and accessing image builders, and deleting images. -* `service/codebuild`: Updates service API and documentation - * Adding support for Building GitHub Pull Requests in AWS CodeBuild -* `service/mturk-requester`: Updates service API and documentation -* `service/organizations`: Updates service API and documentation - * This release flags the HandshakeParty structure's Type and Id fields as 'required'. They effectively were required in the past, as you received an error if you did not include them. This is now reflected at the API definition level. -* `service/route53`: Updates service API and documentation - * This change allows customers to reset elements of health check. - -### SDK Bugs -* `private/protocol/query`: Fix query protocol handling of nested byte slices ([#1557](https://github.com/aws/aws-sdk-go/issues/1557)) - * Fixes the query protocol to correctly marshal nested []byte values of API operations. -* `service/s3`: Fix PutObject and UploadPart API to include ContentMD5 field ([#1559](https://github.com/aws/aws-sdk-go/pull/1559)) - * Fixes the SDK's S3 PutObject and UploadPart API code generation to correctly render the ContentMD5 field into the associated input types for these two API operations. - * Fixes [#1553](https://github.com/aws/aws-sdk-go/pull/1553) -Release v1.12.1 (2017-09-27) -=== - -### Service Client Updates -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/pinpoint`: Updates service API and documentation - * Added two new push notification channels: Amazon Device Messaging (ADM) and, for push notification support in China, Baidu Cloud Push. Added support for APNs auth via .p8 key file. Added operation for direct message deliveries to user IDs, enabling you to message an individual user on multiple endpoints. - -Release v1.12.0 (2017-09-26) -=== - -### SDK Bugs -* `API Marshaler`: Revert REST JSON and XML protocol marshaler improvements - * Bug [#1550](https://github.com/aws/aws-sdk-go/issues/1550) identified a missed condition in the Amazon Route 53 RESTXML protocol marshaling causing requests to that service to fail. Reverting the marshaler improvements until the bug can be fixed. - -Release v1.11.0 (2017-09-26) -=== - -### Service Client Updates -* `service/cloudformation`: Updates service API and documentation - * You can now prevent a stack from being accidentally deleted by enabling termination protection on the stack. If you attempt to delete a stack with termination protection enabled, the deletion fails and the stack, including its status, remains unchanged. You can enable termination protection on a stack when you create it. Termination protection on stacks is disabled by default. After creation, you can set termination protection on a stack whose status is CREATE_COMPLETE, UPDATE_COMPLETE, or UPDATE_ROLLBACK_COMPLETE. - -### SDK Features -* Add dep Go dependency management metadata files (#1544) - * Adds the Go `dep` dependency management metadata files to the SDK. - * Fixes [#1451](https://github.com/aws/aws-sdk-go/issues/1451) - * Fixes [#634](https://github.com/aws/aws-sdk-go/issues/634) -* `service/dynamodb/expression`: Add expression building utility for DynamoDB ([#1527](https://github.com/aws/aws-sdk-go/pull/1527)) - * Adds a new package, expression, to the SDK providing builder utilities to create DynamoDB expressions safely taking advantage of type safety. -* `API Marshaler`: Add generated marshalers for RESTXML protocol ([#1409](https://github.com/aws/aws-sdk-go/pull/1409)) - * Updates the RESTXML protocol marshaler to use generated code instead of reflection for REST XML based services. -* `API Marshaler`: Add generated marshalers for RESTJSON protocol ([#1547](https://github.com/aws/aws-sdk-go/pull/1547)) - * Updates the RESTJSON protocol marshaler to use generated code instead of reflection for REST JSON based services. - -### SDK Enhancements -* `private/protocol`: Update format of REST JSON and XMl benchmarks ([#1546](https://github.com/aws/aws-sdk-go/pull/1546)) - * Updates the format of the REST JSON and XML benchmarks to be readable. RESTJSON benchmarks were updated to more accurately bench building of the protocol. - -Release v1.10.51 (2017-09-22) -=== - -### Service Client Updates -* `service/config`: Updates service API and documentation -* `service/ecs`: Updates service API and documentation - * Amazon ECS users can now add and drop Linux capabilities to their containers through the use of docker's cap-add and cap-drop features. Customers can specify the capabilities they wish to add or drop for each container in their task definition. -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/rds`: Updates service documentation - * Documentation updates for rds - -Release v1.10.50 (2017-09-21) -=== - -### Service Client Updates -* `service/budgets`: Updates service API - * Including "DuplicateRecordException" in UpdateNotification and UpdateSubscriber. -* `service/ec2`: Updates service API and documentation - * Add EC2 APIs to copy Amazon FPGA Images (AFIs) within the same region and across multiple regions, delete AFIs, and modify AFI attributes. AFI attributes include name, description and granting/denying other AWS accounts to load the AFI. -* `service/logs`: Updates service API and documentation - * Adds support for associating LogGroups with KMS Keys. - -### SDK Bugs -* Fix greengrass service model being duplicated with different casing. ([#1541](https://github.com/aws/aws-sdk-go/pull/1541)) - * Fixes [#1540](https://github.com/aws/aws-sdk-go/issues/1540) - * Fixes [#1539](https://github.com/aws/aws-sdk-go/issues/1539) -Release v1.10.49 (2017-09-20) -=== - -### Service Client Updates -* `service/Greengrass`: Adds new service -* `service/appstream`: Updates service API and documentation - * API updates for supporting On-Demand fleets. -* `service/codepipeline`: Updates service API and documentation - * This change includes a PipelineMetadata object that is part of the output from the GetPipeline API that includes the Pipeline ARN, created, and updated timestamp. -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/rds`: Updates service API and documentation - * Introduces the --option-group-name parameter to the ModifyDBSnapshot CLI command. You can specify this parameter when you upgrade an Oracle DB snapshot. The same option group considerations apply when upgrading a DB snapshot as when upgrading a DB instance. For more information, see http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_UpgradeDBInstance.Oracle.html#USER_UpgradeDBInstance.Oracle.OGPG.OG -* `service/runtime.lex`: Updates service API and documentation - -Release v1.10.48 (2017-09-19) -=== - -### Service Client Updates -* `service/ec2`: Updates service API - * Fixed bug in EC2 clients preventing ElasticGpuSet from being set. - -### SDK Enhancements -* `aws/credentials`: Add EnvProviderName constant. ([#1531](https://github.com/aws/aws-sdk-go/issues/1531)) - * Adds the "EnvConfigCredentials" string literal as EnvProviderName constant. - * Fixes [#1444](https://github.com/aws/aws-sdk-go/issues/1444) - -Release v1.10.47 (2017-09-18) -=== - -### Service Client Updates -* `service/ec2`: Updates service API and documentation - * Amazon EC2 now lets you opt for Spot instances to be stopped in the event of an interruption instead of being terminated. Your Spot request can be fulfilled again by restarting instances from a previously stopped state, subject to availability of capacity at or below your preferred price. When you submit a persistent Spot request, you can choose from "terminate" or "stop" as the instance interruption behavior. Choosing "stop" will shutdown your Spot instances so you can continue from this stopped state later on. This feature is only available for instances with Amazon EBS volume as their root device. -* `service/email`: Updates service API and documentation - * Amazon Simple Email Service (Amazon SES) now lets you customize the domains used for tracking open and click events. Previously, open and click tracking links referred to destinations hosted on domains operated by Amazon SES. With this feature, you can use your own branded domains for capturing open and click events. -* `service/iam`: Updates service API and documentation - * A new API, DeleteServiceLinkedRole, submits a service-linked role deletion request and returns a DeletionTaskId, which you can use to check the status of the deletion. - -Release v1.10.46 (2017-09-15) -=== - -### Service Client Updates -* `service/apigateway`: Updates service API and documentation - * Add a new enum "REQUEST" to '--type ' field in the current create-authorizer API, and make "identitySource" optional. - -Release v1.10.45 (2017-09-14) -=== - -### Service Client Updates -* `service/codebuild`: Updates service API and documentation - * Supporting Parameter Store in environment variables for AWS CodeBuild -* `service/organizations`: Updates service documentation - * Documentation updates for AWS Organizations -* `service/servicecatalog`: Updates service API, documentation, and paginators - * This release of Service Catalog adds API support to copy products. - -Release v1.10.44 (2017-09-13) -=== - -### Service Client Updates -* `service/autoscaling`: Updates service API and documentation - * Customers can create Life Cycle Hooks at the time of creating Auto Scaling Groups through the CreateAutoScalingGroup API -* `service/batch`: Updates service documentation and examples - * Documentation updates for batch -* `service/ec2`: Updates service API - * You are now able to create and launch EC2 x1e.32xlarge instance, a new EC2 instance in the X1 family, in us-east-1, us-west-2, eu-west-1, and ap-northeast-1. x1e.32xlarge offers 128 vCPUs, 3,904 GiB of DDR4 instance memory, high memory bandwidth, large L3 caches, and leading reliability capabilities to boost the performance and reliability of in-memory applications. -* `service/events`: Updates service API and documentation - * Exposes ConcurrentModificationException as one of the valid exceptions for PutPermission and RemovePermission operation. - -### SDK Enhancements -* `service/autoscaling`: Fix documentation for PutScalingPolicy.AutoScalingGroupName [#1522](https://github.com/aws/aws-sdk-go/pull/1522) -* `service/s3/s3manager`: Clarify S3 Upload manager Concurrency config [#1521](https://github.com/aws/aws-sdk-go/pull/1521) - * Fixes [#1458](https://github.com/aws/aws-sdk-go/issues/1458) -* `service/dynamodb/dynamodbattribute`: Add support for time alias. [#1520](https://github.com/aws/aws-sdk-go/pull/1520) - * Related to [#1505](https://github.com/aws/aws-sdk-go/pull/1505) - -Release v1.10.43 (2017-09-12) -=== - -### Service Client Updates -* `service/ec2`: Updates service API - * Fixed bug in EC2 clients preventing HostOfferingSet from being set -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -Release v1.10.42 (2017-09-12) -=== - -### Service Client Updates -* `service/devicefarm`: Updates service API and documentation - * DeviceFarm has added support for two features - RemoteDebugging and Customer Artifacts. Customers can now do remote Debugging on their Private Devices and can now retrieve custom files generated by their tests on the device and the device host (execution environment) on both public and private devices. - -Release v1.10.41 (2017-09-08) -=== - -### Service Client Updates -* `service/logs`: Updates service API and documentation - * Adds support for the PutResourcePolicy, DescribeResourcePolicy and DeleteResourcePolicy APIs. - -Release v1.10.40 (2017-09-07) -=== - -### Service Client Updates -* `service/application-autoscaling`: Updates service documentation -* `service/ec2`: Updates service API and documentation - * With Tagging support, you can add Key and Value metadata to search, filter and organize your NAT Gateways according to your organization's needs. -* `service/elasticloadbalancingv2`: Updates service API and documentation -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/lex-models`: Updates service API and documentation -* `service/route53`: Updates service API and documentation - * You can configure Amazon Route 53 to log information about the DNS queries that Amazon Route 53 receives for your domains and subdomains. When you configure query logging, Amazon Route 53 starts to send logs to CloudWatch Logs. You can use various tools, including the AWS console, to access the query logs. - -Release v1.10.39 (2017-09-06) -=== - -### Service Client Updates -* `service/budgets`: Updates service API and documentation - * Add an optional "thresholdType" to notifications to support percentage or absolute value thresholds. - -Release v1.10.38 (2017-09-05) -=== - -### Service Client Updates -* `service/codestar`: Updates service API and documentation - * Added support to tag CodeStar projects. Tags can be used to organize and find CodeStar projects on key-value pairs that you can choose. For example, you could add a tag with a key of "Release" and a value of "Beta" to projects your organization is working on for an upcoming beta release. -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -Release v1.10.37 (2017-09-01) -=== - -### Service Client Updates -* `service/MobileHub`: Adds new service -* `service/gamelift`: Updates service API and documentation - * GameLift VPC resources can be peered with any other AWS VPC. R4 memory-optimized instances now available to deploy. -* `service/ssm`: Updates service API and documentation - * Adding KMS encryption support to SSM Inventory Resource Data Sync. Exposes the ClientToken parameter on SSM StartAutomationExecution to provide idempotent execution requests. - -Release v1.10.36 (2017-08-31) -=== - -### Service Client Updates -* `service/codebuild`: Updates service API, documentation, and examples - * The AWS CodeBuild HTTP API now provides the BatchDeleteBuilds operation, which enables you to delete existing builds. -* `service/ec2`: Updates service API and documentation - * Descriptions for Security Group Rules enables customers to be able to define a description for ingress and egress security group rules . The Descriptions for Security Group Rules feature supports one description field per Security Group rule for both ingress and egress rules . Descriptions for Security Group Rules provides a simple way to describe the purpose or function of a Security Group Rule allowing for easier customer identification of configuration elements . Prior to the release of Descriptions for Security Group Rules , customers had to maintain a separate system outside of AWS if they wanted to track Security Group Rule mapping and their purpose for being implemented. If a security group rule has already been created and you would like to update or change your description for that security group rule you can use the UpdateSecurityGroupRuleDescription API. -* `service/elasticloadbalancingv2`: Updates service API and documentation -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/lex-models`: Updates service API and documentation - -### SDK Bugs -* `aws/signer/v4`: Revert [#1491](https://github.com/aws/aws-sdk-go/issues/1491) as change conflicts with an undocumented AWS v4 signature test case. - * Related to: [#1495](https://github.com/aws/aws-sdk-go/issues/1495). -Release v1.10.35 (2017-08-30) -=== - -### Service Client Updates -* `service/application-autoscaling`: Updates service API and documentation -* `service/organizations`: Updates service API and documentation - * The exception ConstraintViolationException now contains a new reason subcode MASTERACCOUNT_MISSING_CONTACT_INFO to make it easier to understand why attempting to remove an account from an Organization can fail. We also improved several other of the text descriptions and examples. - -Release v1.10.34 (2017-08-29) -=== - -### Service Client Updates -* `service/config`: Updates service API and documentation -* `service/ec2`: Updates service API and documentation - * Provides capability to add secondary CIDR blocks to a VPC. - -### SDK Bugs -* `aws/signer/v4`: Fix Signing Unordered Multi Value Query Parameters ([#1491](https://github.com/aws/aws-sdk-go/pull/1491)) - * Removes sorting of query string values when calculating v4 signing as this is not part of the spec. The spec only requires the keys, not values, to be sorted which is achieved by Query.Encode(). -Release v1.10.33 (2017-08-25) -=== - -### Service Client Updates -* `service/cloudformation`: Updates service API and documentation - * Rollback triggers enable you to have AWS CloudFormation monitor the state of your application during stack creation and updating, and to roll back that operation if the application breaches the threshold of any of the alarms you've specified. -* `service/gamelift`: Updates service API - * Update spelling of MatchmakingTicket status values for internal consistency. -* `service/rds`: Updates service API and documentation - * Option group options now contain additional properties that identify requirements for certain options. Check these properties to determine if your DB instance must be in a VPC or have auto minor upgrade turned on before you can use an option. Check to see if you can downgrade the version of an option after you have installed it. - -### SDK Enhancements -* `example/service/ec2`: Add EC2 list instances example ([#1492](https://github.com/aws/aws-sdk-go/pull/1492)) - -Release v1.10.32 (2017-08-25) -=== - -### Service Client Updates -* `service/rekognition`: Updates service API, documentation, and examples - * Update the enum value of LandmarkType and GenderType to be consistent with service response - -Release v1.10.31 (2017-08-23) -=== - -### Service Client Updates -* `service/appstream`: Updates service documentation - * Documentation updates for appstream -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -Release v1.10.30 (2017-08-22) -=== - -### Service Client Updates -* `service/ssm`: Updates service API and documentation - * Changes to associations in Systems Manager State Manager can now be recorded. Previously, when you edited associations, you could not go back and review older association settings. Now, associations are versioned, and can be named using human-readable strings, allowing you to see a trail of association changes. You can also perform rate-based scheduling, which allows you to schedule associations more granularly. - -Release v1.10.29 (2017-08-21) -=== - -### Service Client Updates -* `service/firehose`: Updates service API, documentation, and paginators - * This change will allow customers to attach a Firehose delivery stream to an existing Kinesis stream directly. You no longer need a forwarder to move data from a Kinesis stream to a Firehose delivery stream. You can now run your streaming applications on your Kinesis stream and easily attach a Firehose delivery stream to it for data delivery to S3, Redshift, or Elasticsearch concurrently. -* `service/route53`: Updates service API and documentation - * Amazon Route 53 now supports CAA resource record type. A CAA record controls which certificate authorities are allowed to issue certificates for the domain or subdomain. - -Release v1.10.28 (2017-08-18) -=== - -### Service Client Updates -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -Release v1.10.27 (2017-08-16) -=== - -### Service Client Updates -* `service/gamelift`: Updates service API and documentation - * The Matchmaking Grouping Service is a new feature that groups player match requests for a given game together into game sessions based on developer configured rules. - -### SDK Enhancements -* `aws/arn`: aws/arn: Package for parsing and producing ARNs ([#1463](https://github.com/aws/aws-sdk-go/pull/1463)) - * Adds the `arn` package for AWS ARN parsing and building. Use this package to build AWS ARNs for services such as outlined in the [documentation](http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html). - -### SDK Bugs -* `aws/signer/v4`: Correct V4 presign signature to include content sha25 in URL ([#1469](https://github.com/aws/aws-sdk-go/pull/1469)) - * Updates the V4 signer so that when a Presign is generated the `X-Amz-Content-Sha256` header is added to the query string instead of being required to be in the header. This allows you to generate presigned URLs for GET requests, e.g S3.GetObject that do not require additional headers to be set by the downstream users of the presigned URL. - * Related To: [#1467](https://github.com/aws/aws-sdk-go/issues/1467) - -Release v1.10.26 (2017-08-15) -=== - -### Service Client Updates -* `service/ec2`: Updates service API - * Fixed bug in EC2 clients preventing HostReservation from being set -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -Release v1.10.25 (2017-08-14) -=== - -### Service Client Updates -* `service/AWS Glue`: Adds new service -* `service/batch`: Updates service API and documentation - * This release enhances the DescribeJobs API to include the CloudWatch logStreamName attribute in ContainerDetail and ContainerDetailAttempt -* `service/cloudhsmv2`: Adds new service - * CloudHSM provides hardware security modules for protecting sensitive data and cryptographic keys within an EC2 VPC, and enable the customer to maintain control over key access and use. This is a second-generation of the service that will improve security, lower cost and provide better customer usability. -* `service/elasticfilesystem`: Updates service API, documentation, and paginators - * Customers can create encrypted EFS file systems and specify a KMS master key to encrypt it with. -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/mgh`: Adds new service - * AWS Migration Hub provides a single location to track migrations across multiple AWS and partner solutions. Using Migration Hub allows you to choose the AWS and partner migration tools that best fit your needs, while providing visibility into the status of your entire migration portfolio. Migration Hub also provides key metrics and progress for individual applications, regardless of which tools are being used to migrate them. For example, you might use AWS Database Migration Service, AWS Server Migration Service, and partner migration tools to migrate an application comprised of a database, virtualized web servers, and a bare metal server. Using Migration Hub will provide you with a single screen that shows the migration progress of all the resources in the application. This allows you to quickly get progress updates across all of your migrations, easily identify and troubleshoot any issues, and reduce the overall time and effort spent on your migration projects. Migration Hub is available to all AWS customers at no additional charge. You only pay for the cost of the migration tools you use, and any resources being consumed on AWS. -* `service/ssm`: Updates service API and documentation - * Systems Manager Maintenance Windows include the following changes or enhancements: New task options using Systems Manager Automation, AWS Lambda, and AWS Step Functions; enhanced ability to edit the targets of a Maintenance Window, including specifying a target name and description, and ability to edit the owner field; enhanced ability to edits tasks; enhanced support for Run Command parameters; and you can now use a --safe flag when attempting to deregister a target. If this flag is enabled when you attempt to deregister a target, the system returns an error if the target is referenced by any task. Also, Systems Manager now includes Configuration Compliance to scan your fleet of managed instances for patch compliance and configuration inconsistencies. You can collect and aggregate data from multiple AWS accounts and Regions, and then drill down into specific resources that aren't compliant. -* `service/storagegateway`: Updates service API and documentation - * Add optional field ForceDelete to DeleteFileShare api. - -Release v1.10.24 (2017-08-11) -=== - -### Service Client Updates -* `service/codedeploy`: Updates service API and documentation - * Adds support for specifying Application Load Balancers in deployment groups, for both in-place and blue/green deployments. -* `service/cognito-idp`: Updates service API and documentation -* `service/ec2`: Updates service API and documentation - * Provides customers an opportunity to recover an EIP that was released - -Release v1.10.23 (2017-08-10) -=== - -### Service Client Updates -* `service/clouddirectory`: Updates service API and documentation - * Enable BatchDetachPolicy -* `service/codebuild`: Updates service API - * Supporting Bitbucket as source type in AWS CodeBuild. - -Release v1.10.22 (2017-08-09) -=== - -### Service Client Updates -* `service/rds`: Updates service documentation - * Documentation updates for RDS. - -Release v1.10.21 (2017-08-09) -=== - -### Service Client Updates -* `service/elasticbeanstalk`: Updates service API and documentation - * Add support for paginating the result of DescribeEnvironments Include the ARN of described environments in DescribeEnvironments output - -### SDK Enhancements -* `aws`: Add pointer conversion utilities to transform int64 to time.Time [#1433](https://github.com/aws/aws-sdk-go/pull/1433) - * Adds `SecondsTimeValue` and `MillisecondsTimeValue` utilities. - -Release v1.10.20 (2017-08-01) -=== - -### Service Client Updates -* `service/codedeploy`: Updates service API and documentation - * AWS CodeDeploy now supports the use of multiple tag groups in a single deployment group (an intersection of tags) to identify the instances for a deployment. When you create or update a deployment group, use the new ec2TagSet and onPremisesTagSet structures to specify up to three groups of tags. Only instances that are identified by at least one tag in each of the tag groups are included in the deployment group. -* `service/config`: Updates service API and documentation -* `service/ec2`: Updates service waiters - * Ec2 SpotInstanceRequestFulfilled waiter update -* `service/elasticloadbalancingv2`: Updates service waiters -* `service/email`: Updates service API, documentation, paginators, and examples - * This update adds information about publishing email open and click events. This update also adds information about publishing email events to Amazon Simple Notification Service (Amazon SNS). -* `service/pinpoint`: Updates service API and documentation - * This release of the Pinpoint SDK enables App management - create, delete, update operations, Raw Content delivery for APNs and GCM campaign messages and From Address override. - -Release v1.10.19 (2017-08-01) -=== - -### Service Client Updates -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/inspector`: Updates service API, documentation, and paginators - * Inspector's StopAssessmentRun API has been updated with a new input option - stopAction. This request parameter can be set to either START_EVALUATION or SKIP_EVALUATION. START_EVALUATION (the default value, and the previous behavior) stops the AWS agent data collection and begins the results evaluation for findings generation based on the data collected so far. SKIP_EVALUATION cancels the assessment run immediately, after which no findings are generated. -* `service/ssm`: Updates service API and documentation - * Adds a SendAutomationSignal API to SSM Service. This API is used to send a signal to an automation execution to change the current behavior or status of the execution. - -Release v1.10.18 (2017-07-27) -=== - -### Service Client Updates -* `service/ec2`: Updates service API and documentation - * The CreateDefaultVPC API enables you to create a new default VPC . You no longer need to contact AWS support, if your default VPC has been deleted. -* `service/kinesisanalytics`: Updates service API and documentation - * Added additional exception types and clarified documentation. - -Release v1.10.17 (2017-07-27) -=== - -### Service Client Updates -* `service/dynamodb`: Updates service documentation and examples - * Corrected a typo. -* `service/ec2`: Updates service API and documentation - * Amazon EC2 Elastic GPUs allow you to easily attach low-cost graphics acceleration to current generation EC2 instances. With Amazon EC2 Elastic GPUs, you can configure the right amount of graphics acceleration to your particular workload without being constrained by fixed hardware configurations and limited GPU selection. -* `service/monitoring`: Updates service documentation - * This release adds high resolution features to CloudWatch, with support for Custom Metrics down to 1 second and Alarms down to 10 seconds. - -Release v1.10.16 (2017-07-26) -=== - -### Service Client Updates -* `service/clouddirectory`: Updates service API and documentation - * Cloud Directory adds support for additional batch operations. -* `service/cloudformation`: Updates service API and documentation - * AWS CloudFormation StackSets enables you to manage stacks across multiple accounts and regions. - -### SDK Enhancements -* `aws/signer/v4`: Optimize V4 signer's header duplicate space stripping. [#1417](https://github.com/aws/aws-sdk-go/pull/1417) - -Release v1.10.15 (2017-07-24) -=== - -### Service Client Updates -* `service/appstream`: Updates service API, documentation, and waiters - * Amazon AppStream 2.0 image builders and fleets can now access applications and network resources that rely on Microsoft Active Directory (AD) for authentication and permissions. This new feature allows you to join your streaming instances to your AD, so you can use your existing AD user management tools. -* `service/ec2`: Updates service API and documentation - * Spot Fleet tagging capability allows customers to automatically tag instances launched by Spot Fleet. You can use this feature to label or distinguish instances created by distinct Spot Fleets. Tagging your EC2 instances also enables you to see instance cost allocation by tag in your AWS bill. - -### SDK Bugs -* `aws/signer/v4`: Fix out of bounds panic in stripExcessSpaces [#1412](https://github.com/aws/aws-sdk-go/pull/1412) - * Fixes the out of bands panic in stripExcessSpaces caused by an incorrect calculation of the stripToIdx value. Simplified to code also. - * Fixes [#1411](https://github.com/aws/aws-sdk-go/issues/1411) -Release v1.10.14 (2017-07-20) -=== - -### Service Client Updates -* `service/elasticmapreduce`: Updates service API and documentation - * Amazon EMR now includes the ability to use a custom Amazon Linux AMI and adjustable root volume size when launching a cluster. - -Release v1.10.13 (2017-07-19) -=== - -### Service Client Updates -* `service/budgets`: Updates service API and documentation - * Update budget Management API's to list/create/update RI_UTILIZATION type budget. Update budget Management API's to support DAILY timeUnit for RI_UTILIZATION type budget. - -### SDK Enhancements -* `service/s3`: Use interfaces assertions instead of ValuesAtPath for S3 field lookups. [#1401](https://github.com/aws/aws-sdk-go/pull/1401) - * Improves the performance across the board for all S3 API calls by removing the usage of `ValuesAtPath` being used for every S3 API call. - -### SDK Bugs -* `aws/request`: waiter test bug - * waiters_test.go file would sometimes fail due to travis hiccups. This occurs because a test would sometimes fail the cancel check and succeed the timeout. However, the timeout check should never occur in that test. This fix introduces a new field that dictates how waiters will sleep. -Release v1.10.12 (2017-07-17) -=== - -### Service Client Updates -* `service/cognito-idp`: Updates service API and documentation -* `service/lambda`: Updates service API and documentation - * Lambda@Edge lets you run code closer to your end users without provisioning or managing servers. With Lambda@Edge, your code runs in AWS edge locations, allowing you to respond to your end users at the lowest latency. Your code is triggered by Amazon CloudFront events, such as requests to and from origin servers and viewers, and it is ready to execute at every AWS edge location whenever a request for content is received. You just upload your Node.js code to AWS Lambda and Lambda takes care of everything required to run and scale your code with high availability. You only pay for the compute time you consume - there is no charge when your code is not running. - -Release v1.10.11 (2017-07-14) -=== - -### Service Client Updates -* `service/discovery`: Updates service API and documentation - * Adding feature to the Export API for Discovery Service to allow filters for the export task to allow export based on per agent id. -* `service/ec2`: Updates service API - * New EC2 GPU Graphics instance -* `service/marketplacecommerceanalytics`: Updates service documentation - * Update to Documentation Model For New Report Cadence / Reformat of Docs - -Release v1.10.10 (2017-07-13) -=== - -### Service Client Updates -* `service/apigateway`: Updates service API and documentation - * Adds support for management of gateway responses. -* `service/ec2`: Updates service API and documentation - * X-ENI (or Cross-Account ENI) is a new feature that allows the attachment or association of Elastic Network Interfaces (ENI) between VPCs in different AWS accounts located in the same availability zone. With this new capability, service providers and partners can deliver managed solutions in a variety of new architectural patterns where the provider and consumer of the service are in different AWS accounts. -* `service/lex-models`: Updates service documentation - -Release v1.10.9 (2017-07-12) -=== - -### Service Client Updates -* `service/autoscaling`: Updates service API and documentation - * Auto Scaling now supports a new type of scaling policy called target tracking scaling policies that you can use to set up dynamic scaling for your application. -* `service/swf`: Updates service API, documentation, paginators, and examples - * Added support for attaching control data to Lambda tasks. Control data lets you attach arbitrary strings to your decisions and history events. - -Release v1.10.8 (2017-07-06) -=== - -### Service Client Updates -* `service/ds`: Updates service API, documentation, and paginators - * You can now improve the resilience and performance of your Microsoft AD directory by deploying additional domain controllers. Added UpdateNumberofDomainControllers API that allows you to update the number of domain controllers you want for your directory, and DescribeDomainControllers API that allows you to describe the detailed information of each domain controller of your directory. Also added the 'DesiredNumberOfDomainControllers' field to the DescribeDirectories API output for Microsoft AD. -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/kinesis`: Updates service API and documentation - * You can now encrypt your data at rest within an Amazon Kinesis Stream using server-side encryption. Server-side encryption via AWS KMS makes it easy for customers to meet strict data management requirements by encrypting their data at rest within the Amazon Kinesis Streams, a fully managed real-time data processing service. -* `service/kms`: Updates service API and documentation - * This release of AWS Key Management Service introduces the ability to determine whether a key is AWS managed or customer managed. -* `service/ssm`: Updates service API and documentation - * Amazon EC2 Systems Manager now expands Patching support to Amazon Linux, Red Hat and Ubuntu in addition to the already supported Windows Server. - -Release v1.10.7 (2017-07-05) -=== - -### Service Client Updates -* `service/monitoring`: Updates service API and documentation - * We are excited to announce the availability of APIs and CloudFormation support for CloudWatch Dashboards. You can use the new dashboard APIs or CloudFormation templates to dynamically build and maintain dashboards to monitor your infrastructure and applications. There are four new dashboard APIs - PutDashboard, GetDashboard, DeleteDashboards, and ListDashboards APIs. PutDashboard is used to create a new dashboard or modify an existing one whereas GetDashboard is the API to get the details of a specific dashboard. ListDashboards and DeleteDashboards are used to get the names or delete multiple dashboards respectively. Getting started with dashboard APIs is similar to any other AWS APIs. The APIs can be accessed through AWS SDK or through CLI tools. -* `service/route53`: Updates service API and documentation - * Bug fix for InvalidChangeBatch exception. - -### SDK Enhancements -* `service/s3/s3manager`: adding cleanup function to batch objects [#1375](https://github.com/aws/aws-sdk-go/issues/1375) - * This enhancement will add an After field that will be called after each iteration of the batch operation. - -Release v1.10.6 (2017-06-30) -=== - -### Service Client Updates -* `service/marketplacecommerceanalytics`: Updates service documentation - * Documentation updates for AWS Marketplace Commerce Analytics. -* `service/s3`: Updates service API and documentation - * API Update for S3: Adding Object Tagging Header to MultipartUpload Initialization - -Release v1.10.5 (2017-06-29) -=== - -### Service Client Updates -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/events`: Updates service API and documentation - * CloudWatch Events now allows different AWS accounts to share events with each other through a new resource called event bus. Event buses accept events from AWS services, other AWS accounts and PutEvents API calls. Currently all AWS accounts have one default event bus. To send events to another account, customers simply write rules to match the events of interest and attach an event bus in the receiving account as the target to the rule. The PutTargets API has been updated to allow adding cross account event buses as targets. In addition, we have released two new APIs - PutPermission and RemovePermission - that enables customers to add/remove permissions to their default event bus. -* `service/gamelift`: Updates service API and documentation - * Allow developers to download GameLift fleet creation logs to assist with debugging. -* `service/ssm`: Updates service API and documentation - * Adding Resource Data Sync support to SSM Inventory. New APIs: * CreateResourceDataSync - creates a new resource data sync configuration, * ListResourceDataSync - lists existing resource data sync configurations, * DeleteResourceDataSync - deletes an existing resource data sync configuration. - -Release v1.10.4 (2017-06-27) -=== - -### Service Client Updates -* `service/servicecatalog`: Updates service API, documentation, and paginators - * Proper tagging of resources is critical to post-launch operations such as billing, cost allocation, and resource management. By using Service Catalog's TagOption Library, administrators can define a library of re-usable TagOptions that conform to company standards, and associate these with Service Catalog portfolios and products. Learn how to move your current tags to the new library, create new TagOptions, and view and associate your library items with portfolios and products. Understand how to ensure that the right tags are created on products launched through Service Catalog and how to provide users with defined selectable tags. - -### SDK Bugs -* `aws/signer/v4`: checking length on `stripExcessSpaces` [#1372](https://github.com/aws/aws-sdk-go/issues/1372) - * Fixes a bug where `stripExcessSpaces` did not check length against the slice. - * Fixes: [#1371](https://github.com/aws/aws-sdk-go/issues/1371) -Release v1.10.3 (2017-06-23) -=== - -### Service Client Updates -* `service/lambda`: Updates service API and documentation - * The Lambda Invoke API will now throw new exception InvalidRuntimeException (status code 502) for invokes with deprecated runtimes. - -Release v1.10.2 (2017-06-22) -=== - -### Service Client Updates -* `service/codepipeline`: Updates service API, documentation, and paginators - * A new API, ListPipelineExecutions, enables you to retrieve summary information about the most recent executions in a pipeline, including pipeline execution ID, status, start time, and last updated time. You can request information for a maximum of 100 executions. Pipeline execution data is available for the most recent 12 months of activity. -* `service/dms`: Updates service API and documentation - * Added tagging for DMS certificates. -* `service/elasticloadbalancing`: Updates service waiters -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/lightsail`: Updates service API and documentation - * This release adds a new nextPageToken property to the result of the GetOperationsForResource API. Developers can now get the next set of items in a list by making subsequent calls to GetOperationsForResource API with the token from the previous call. This release also deprecates the nextPageCount property, which previously returned null (use the nextPageToken property instead). This release also deprecates the customImageName property on the CreateInstancesRequest class, which was previously ignored by the API. -* `service/route53`: Updates service API and documentation - * This release reintroduces the HealthCheckInUse exception. - -Release v1.10.1 (2017-06-21) -=== - -### Service Client Updates -* `service/dax`: Adds new service - * Amazon DynamoDB Accelerator (DAX) is a fully managed, highly available, in-memory cache for DynamoDB that delivers up to a 10x performance improvement - from milliseconds to microseconds - even at millions of requests per second. DAX does all the heavy lifting required to add in-memory acceleration to your DynamoDB tables, without requiring developers to manage cache invalidation, data population, or cluster management. -* `service/route53`: Updates service API and documentation - * Amazon Route 53 now supports multivalue answers in response to DNS queries, which lets you route traffic approximately randomly to multiple resources, such as web servers. Create one multivalue answer record for each resource and, optionally, associate an Amazon Route 53 health check with each record, and Amazon Route 53 responds to DNS queries with up to eight healthy records. -* `service/ssm`: Updates service API, documentation, and paginators - * Adding hierarchy support to the SSM Parameter Store API. Added support tor tagging. New APIs: GetParameter - retrieves one parameter, DeleteParameters - deletes multiple parameters (max number 10), GetParametersByPath - retrieves parameters located in the hierarchy. Updated APIs: PutParameter - added ability to enforce parameter value by applying regex (AllowedPattern), DescribeParameters - modified to support Tag filtering. -* `service/waf`: Updates service API and documentation - * You can now create, edit, update, and delete a new type of WAF rule with a rate tracking component. -* `service/waf-regional`: Updates service API and documentation - -Release v1.10.0 (2017-06-20) -=== - -### Service Client Updates -* `service/workdocs`: Updates service API and documentation - * This release provides a new API to retrieve the activities performed by WorkDocs users. - -### SDK Features -* `aws/credentials/plugincreds`: Add support for Go plugin for credentials [#1320](https://github.com/aws/aws-sdk-go/pull/1320) - * Adds support for using plugins to retrieve credentials for API requests. This change adds a new package plugincreds under aws/credentials. See the `example/aws/credentials/plugincreds` folder in the SDK for example usage. - -Release v1.9.00 (2017-06-19) -=== - -### Service Client Updates -* `service/organizations`: Updates service API and documentation - * Improvements to Exception Modeling - -### SDK Features -* `service/s3/s3manager`: Adds batch operations to s3manager [#1333](https://github.com/aws/aws-sdk-go/pull/1333) - * Allows for batch upload, download, and delete of objects. Also adds the interface pattern to allow for easy traversal of objects. E.G `DownloadWithIterator`, `UploadWithIterator`, and `BatchDelete`. `BatchDelete` also contains a utility iterator using the `ListObjects` API to easily delete a list of objects. - -Release v1.8.44 (2017-06-16) -=== - -### Service Client Updates -* `service/xray`: Updates service API, documentation, and paginators - * Add a response time histogram to the services in response of GetServiceGraph API. - -Release v1.8.43 (2017-06-15) -=== - -### Service Client Updates -* `service/ec2`: Updates service API and documentation - * Adds API to describe Amazon FPGA Images (AFIs) available to customers, which includes public AFIs, private AFIs that you own, and AFIs owned by other AWS accounts for which you have load permissions. -* `service/ecs`: Updates service API and documentation - * Added support for cpu, memory, and memory reservation container overrides on the RunTask and StartTask APIs. -* `service/iot`: Updates service API and documentation - * Revert the last release: remove CertificatePem from DescribeCertificate API. -* `service/servicecatalog`: Updates service API, documentation, and paginators - * Added ProvisioningArtifactSummaries to DescribeProductAsAdmin's output to show the provisioning artifacts belong to the product. Allow filtering by SourceProductId in SearchProductsAsAdmin for AWS Marketplace products. Added a verbose option to DescribeProvisioningArtifact to display the CloudFormation template used to create the provisioning artifact.Added DescribeProvisionedProduct API. Changed the type of ProvisionedProduct's Status to be distinct from Record's Status. New ProvisionedProduct's Status are AVAILABLE, UNDER_CHANGE, TAINTED, ERROR. Changed Record's Status set of values to CREATED, IN_PROGRESS, IN_PROGRESS_IN_ERROR, SUCCEEDED, FAILED. - -### SDK Bugs -* `private/model/api`: Fix RESTXML support for XML Namespace [#1343](https://github.com/aws/aws-sdk-go/pull/1343) - * Fixes a bug with the SDK's generation of services using the REST XML protocol not annotating shape references with the XML Namespace attribute. - * Fixes [#1334](https://github.com/aws/aws-sdk-go/pull/1334) -Release v1.8.42 (2017-06-14) -=== - -### Service Client Updates -* `service/applicationautoscaling`: Updates service API and documentation -* `service/clouddirectory`: Updates service documentation - * Documentation update for Cloud Directory - -Release v1.8.41 (2017-06-13) -=== - -### Service Client Updates -* `service/configservice`: Updates service API - -Release v1.8.40 (2017-06-13) -=== - -### Service Client Updates -* `service/rds`: Updates service API and documentation - * API Update for RDS: this update enables copy-on-write, a new Aurora MySQL Compatible Edition feature that allows users to restore their database, and support copy of TDE enabled snapshot cross region. - -### SDK Bugs -* `aws/request`: Fix NewErrParamMinLen to use correct ParamMinLenErrCode [#1336](https://github.com/aws/aws-sdk-go/issues/1336) - * Fixes the `NewErrParamMinLen` function returning the wrong error code. `ParamMinLenErrCode` should be returned not `ParamMinValueErrCode`. - * Fixes [#1335](https://github.com/aws/aws-sdk-go/issues/1335) -Release v1.8.39 (2017-06-09) -=== - -### Service Client Updates -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/opsworks`: Updates service API and documentation - * Tagging Support for AWS OpsWorks Stacks - -Release v1.8.38 (2017-06-08) -=== - -### Service Client Updates -* `service/iot`: Updates service API and documentation - * In addition to using certificate ID, AWS IoT customers can now obtain the description of a certificate with the certificate PEM. -* `service/pinpoint`: Updates service API and documentation - * Starting today Amazon Pinpoint adds SMS Text and Email Messaging support in addition to Mobile Push Notifications, providing developers, product managers and marketers with multi-channel messaging capabilities to drive user engagement in their applications. Pinpoint also enables backend services and applications to message users directly and provides advanced user and app analytics to understand user behavior and messaging performance. -* `service/rekognition`: Updates service API and documentation - * API Update for AmazonRekognition: Adding RecognizeCelebrities API - -Release v1.8.37 (2017-06-07) -=== - -### Service Client Updates -* `service/codebuild`: Updates service API and documentation - * Add support to APIs for privileged containers. This change would allow performing privileged operations like starting the Docker daemon inside builds possible in custom docker images. -* `service/greengrass`: Adds new service - * AWS Greengrass is software that lets you run local compute, messaging, and device state synchronization for connected devices in a secure way. With AWS Greengrass, connected devices can run AWS Lambda functions, keep device data in sync, and communicate with other devices securely even when not connected to the Internet. Using AWS Lambda, Greengrass ensures your IoT devices can respond quickly to local events, operate with intermittent connections, and minimize the cost of transmitting IoT data to the cloud. - -Release v1.8.36 (2017-06-06) -=== - -### Service Client Updates -* `service/acm`: Updates service documentation - * Documentation update for AWS Certificate Manager. -* `service/cloudfront`: Updates service documentation - * Doc update to fix incorrect prefix in S3OriginConfig -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/iot`: Updates service API - * Update client side validation for SalesForce action. - -Release v1.8.35 (2017-06-05) -=== - -### Service Client Updates -* `service/appstream`: Updates service API and documentation - * AppStream 2.0 Custom Security Groups allows you to easily control what network resources your streaming instances and images have access to. You can assign up to 5 security groups per Fleet to control the inbound and outbound network access to your streaming instances to specific IP ranges, network protocols, or ports. -* `service/iot`: Updates service API, documentation, paginators, and examples - * Added Salesforce action to IoT Rules Engine. - -Release v1.8.34 (2017-06-02) -=== - -### Service Client Updates -* `service/kinesisanalytics`: Updates service API, documentation, and paginators - * Kinesis Analytics publishes error messages CloudWatch logs in case of application misconfigurations -* `service/workdocs`: Updates service API and documentation - * This release includes new APIs to manage tags and custom metadata on resources and also new APIs to add and retrieve comments at the document level. - -Release v1.8.33 (2017-06-01) -=== - -### Service Client Updates -* `service/codedeploy`: Updates service API and documentation - * AWS CodeDeploy has improved how it manages connections to GitHub accounts and repositories. You can now create and store up to 25 connections to GitHub accounts in order to associate AWS CodeDeploy applications with GitHub repositories. Each connection can support multiple repositories. You can create connections to up to 25 different GitHub accounts, or create more than one connection to a single account. The ListGitHubAccountTokenNames command has been introduced to retrieve the names of stored connections to GitHub accounts that you have created. The name of the connection to GitHub used for an AWS CodeDeploy application is also included in the ApplicationInfo structure. Two new fields, lastAttemptedDeployment and lastSuccessfulDeployment, have been added to DeploymentGroupInfo to improve the handling of deployment group information in the AWS CodeDeploy console. Information about these latest deployments can also be retrieved using the GetDeploymentGroup and BatchGetDeployment group requests. Also includes a region update (us-gov-west-1). -* `service/cognitoidentityprovider`: Updates service API, documentation, and paginators -* `service/elbv2`: Updates service API and documentation -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/lexmodelbuildingservice`: Updates service documentation and examples - -### SDK Enhancements -* `aws/defaults`: Exports shared credentials and config default filenames used by the SDK. [#1308](https://github.com/aws/aws-sdk-go/pull/1308) - * Adds SharedCredentialsFilename and SharedConfigFilename functions to defaults package. - -### SDK Bugs -* `aws/credentials`: Fixes shared credential provider's default filename on Windows. [#1308](https://github.com/aws/aws-sdk-go/pull/1308) - * The shared credentials provider would attempt to use the wrong filename on Windows if the `HOME` environment variable was defined. -* `service/s3/s3manager`: service/s3/s3manager: Fix Downloader ignoring Range get parameter [#1311](https://github.com/aws/aws-sdk-go/pull/1311) - * Fixes the S3 Download Manager ignoring the GetObjectInput's Range parameter. If this parameter is provided it will force the downloader to fallback to a single GetObject request disabling concurrency and automatic part size gets. - * Fixes [#1296](https://github.com/aws/aws-sdk-go/issues/1296) -Release v1.8.32 (2017-05-31) -=== - -### Service Client Updates -* `service/rds`: Updates service API and documentation - * Amazon RDS customers can now easily and quickly stop and start their DB instances. - -Release v1.8.31 (2017-05-30) -=== - -### Service Client Updates -* `service/clouddirectory`: Updates service API, documentation, and paginators - * Cloud Directory has launched support for Typed Links, enabling customers to create object-to-object relationships that are not hierarchical in nature. Typed Links enable customers to quickly query for data along these relationships. Customers can also enforce referential integrity using Typed Links, ensuring data in use is not inadvertently deleted. -* `service/s3`: Updates service paginators and examples - * New example snippets for Amazon S3. - -Release v1.8.30 (2017-05-25) -=== - -### Service Client Updates -* `service/appstream`: Updates service API and documentation - * Support added for persistent user storage, backed by S3. -* `service/rekognition`: Updates service API and documentation - * Updated the CompareFaces API response to include orientation information, unmatched faces, landmarks, pose, and quality of the compared faces. - -Release v1.8.29 (2017-05-24) -=== - -### Service Client Updates -* `service/iam`: Updates service API - * The unique ID and access key lengths were extended from 32 to 128 -* `service/storagegateway`: Updates service API and documentation - * Two Storage Gateway data types, Tape and TapeArchive, each have a new response element, TapeUsedInBytes. This element helps you manage your virtual tapes. By using TapeUsedInBytes, you can see the amount of data written to each virtual tape. -* `service/sts`: Updates service API, documentation, and paginators - * The unique ID and access key lengths were extended from 32 to 128. - -Release v1.8.28 (2017-05-23) -=== - -### Service Client Updates -* `service/databasemigrationservice`: Updates service API, documentation, paginators, and examples - * This release adds support for using Amazon S3 and Amazon DynamoDB as targets for database migration, and using MongoDB as a source for database migration. For more information, see the AWS Database Migration Service documentation. - -Release v1.8.27 (2017-05-22) -=== - -### Service Client Updates -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/resourcegroupstaggingapi`: Updates service API, documentation, and paginators - * You can now specify the number of resources returned per page in GetResources operation, as an optional parameter, to easily manage the list of resources returned by your queries. - -### SDK Bugs -* `aws/request`: Add support for PUT temporary redirects (307) [#1283](https://github.com/aws/aws-sdk-go/issues/1283) - * Adds support for Go 1.8's GetBody function allowing the SDK's http request using PUT and POST methods to be redirected with temporary redirects with 307 status code. - * Fixes: [#1267](https://github.com/aws/aws-sdk-go/issues/1267) -* `aws/request`: Add handling for retrying temporary errors during unmarshal [#1289](https://github.com/aws/aws-sdk-go/issues/1289) - * Adds support for retrying temporary errors that occur during unmarshaling of a request's response body. - * Fixes: [#1275](https://github.com/aws/aws-sdk-go/issues/1275) -Release v1.8.26 (2017-05-18) -=== - -### Service Client Updates -* `service/athena`: Adds new service - * This release adds support for Amazon Athena. Amazon Athena is an interactive query service that makes it easy to analyze data in Amazon S3 using standard SQL. Athena is serverless, so there is no infrastructure to manage, and you pay only for the queries that you run. -* `service/lightsail`: Updates service API, documentation, and paginators - * This release adds new APIs that make it easier to set network port configurations on Lightsail instances. Developers can now make a single request to both open and close public ports on an instance using the PutInstancePublicPorts operation. - -### SDK Bugs -* `aws/request`: Fix logging from reporting wrong retry request errors #1281 - * Fixes the SDK's retry request logging to report the the actual error that occurred, not a stubbed Unknown error message. - * Fixes the SDK's response logger to not output the response log multiple times per retry. -Release v1.8.25 (2017-05-17) -=== - -### Service Client Updates -* `service/autoscaling`: Updates service documentation, paginators, and examples - * Various Auto Scaling documentation updates -* `service/cloudwatchevents`: Updates service documentation - * Various CloudWatch Events documentation updates. -* `service/cloudwatchlogs`: Updates service documentation and paginators - * Various CloudWatch Logs documentation updates. -* `service/polly`: Updates service API - * Amazon Polly adds new German voice "Vicki" - -Release v1.8.24 (2017-05-16) -=== - -### Service Client Updates -* `service/codedeploy`: Updates service API and documentation - * This release introduces the previousRevision field in the responses to the GetDeployment and BatchGetDeployments actions. previousRevision provides information about the application revision that was deployed to the deployment group before the most recent successful deployment. Also, the fileExistsBehavior parameter has been added for CreateDeployment action requests. In the past, if the AWS CodeDeploy agent detected files in a target location that weren't part of the application revision from the most recent successful deployment, it would fail the current deployment by default. This new parameter provides options for how the agent handles these files: fail the deployment, retain the content, or overwrite the content. -* `service/gamelift`: Updates service API and documentation - * Allow developers to specify how metrics are grouped in CloudWatch for their GameLift fleets. Developers can also specify how many concurrent game sessions activate on a per-instance basis. -* `service/inspector`: Updates service API, documentation, paginators, and examples - * Adds ability to produce an assessment report that includes detailed and comprehensive results of a specified assessment run. -* `service/kms`: Updates service documentation - * Update documentation for KMS. - -Release v1.8.23 (2017-05-15) -=== - -### Service Client Updates -* `service/ssm`: Updates service API and documentation - * UpdateAssociation API now supports updating document name and targets of an association. GetAutomationExecution API can return FailureDetails as an optional field to the StepExecution Object, which contains failure type, failure stage as well as other failure related information for a failed step. - -### SDK Enhancements -* `aws/session`: SDK should be able to load multiple custom shared config files. [#1258](https://github.com/aws/aws-sdk-go/issues/1258) - * This change adds a `SharedConfigFiles` field to the `session.Options` type that allows you to specify the files, and their order, the SDK will use for loading shared configuration and credentials from when the `Session` is created. Use the `NewSessionWithOptions` Session constructor to specify these options. You'll also most likely want to enable support for the shared configuration file's additional attributes by setting `session.Option`'s `SharedConfigState` to `session.SharedConfigEnabled`. - -Release v1.8.22 (2017-05-11) -=== - -### Service Client Updates -* `service/elb`: Updates service API, documentation, and paginators -* `service/elbv2`: Updates service API and documentation -* `service/lexmodelbuildingservice`: Updates service API and documentation -* `service/organizations`: Updates service API, documentation, paginators, and examples - * AWS Organizations APIs that return an Account object now include the email address associated with the account’s root user. - -Release v1.8.21 (2017-05-09) -=== - -### Service Client Updates -* `service/codestar`: Updates service documentation - * Updated documentation for AWS CodeStar. -* `service/workspaces`: Updates service API, documentation, and paginators - * Doc-only Update for WorkSpaces - -Release v1.8.20 (2017-05-04) -=== - -### Service Client Updates -* `service/ecs`: Updates service API, documentation, and paginators - * Exposes container instance registration time in ECS:DescribeContainerInstances. -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/marketplaceentitlementservice`: Adds new service -* `service/lambda`: Updates service API and documentation - * Support for UpdateFunctionCode DryRun option - -Release v1.8.19 (2017-04-28) -=== - -### Service Client Updates -* `service/cloudformation`: Updates service waiters and paginators - * Adding back the removed waiters and paginators. - -Release v1.8.18 (2017-04-28) -=== - -### Service Client Updates -* `service/cloudformation`: Updates service API, documentation, waiters, paginators, and examples - * API update for CloudFormation: New optional parameter ClientRequestToken which can be used as an idempotency token to safely retry certain operations as well as tagging StackEvents. -* `service/rds`: Updates service API, documentation, and examples - * The DescribeDBClusterSnapshots API now returns a SourceDBClusterSnapshotArn field which identifies the source DB cluster snapshot of a copied snapshot. -* `service/rekognition`: Updates service API - * Fix for missing file type check -* `service/snowball`: Updates service API, documentation, and paginators - * The Snowball API has a new exception that can be thrown for list operation requests. -* `service/sqs`: Updates service API, documentation, and paginators - * Adding server-side encryption (SSE) support to SQS by integrating with AWS KMS; adding new queue attributes to SQS CreateQueue, SetQueueAttributes and GetQueueAttributes APIs to support SSE. - -Release v1.8.17 (2017-04-26) -=== - -### Service Client Updates -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/rds`: Updates service API and documentation - * With Amazon Relational Database Service (Amazon RDS) running MySQL or Amazon Aurora, you can now authenticate to your DB instance using IAM database authentication. - -Release v1.8.16 (2017-04-21) -=== - -### Service Client Updates -* `service/appstream`: Updates service API, documentation, and paginators - * The new feature named "Default Internet Access" will enable Internet access from AppStream 2.0 instances - image builders and fleet instances. Admins will check a flag either through AWS management console for AppStream 2.0 or through API while creating an image builder or while creating/updating a fleet. -* `service/kinesis`: Updates service API, documentation, waiters, and paginators - * Adds a new waiter, StreamNotExists, to Kinesis. - -### SDK Enhancements -* `aws/endpoints`: Add utilities improving endpoints lookup (#1218) - * Adds several utilities to the endpoints packages to make looking up partitions, regions, and services easier. - * Fixes #994 - -### SDK Bugs -* `private/protocol/xml/xmlutil`: Fix unmarshaling dropping errors (#1219) - * The XML unmarshaler would drop any serialization or body read error that occurred on the floor effectively hiding any errors that would occur. - * Fixes #1205 -Release v1.8.15 (2017-04-20) -=== - -### Service Client Updates -* `service/devicefarm`: Updates service API and documentation - * API Update for AWS Device Farm: Support for Deals and Promotions -* `service/directconnect`: Updates service documentation - * Documentation updates for AWS Direct Connect. -* `service/elbv2`: Updates service waiters -* `service/kms`: Updates service documentation and examples - * Doc-only update for Key Management Service (KMS): Update docs for GrantConstraints and GenerateRandom -* `service/route53`: Updates service documentation - * Release notes: SDK documentation now includes examples for ChangeResourceRecordSets for all types of resource record set, such as weighted, alias, and failover. -* `service/route53domains`: Updates service API, documentation, and paginators - * Adding examples and other documentation updates. - -### SDK Enhancements -* `service/s3`: Add utilities to make getting a bucket's region easier (#1207) - * Adds two features which make it easier to get a bucket's region, `s3.NormalizeBucketLocation` and `s3manager.GetBucketRegion`. - -### SDK Bugs -* `service/s3`: Fix HeadObject's incorrect documented error codes (#1213) - * The HeadObject's model incorrectly states that the operation can return the NoSuchKey error code. - * Fixes #1208 - -Release v1.8.14 (2017-04-19) -=== - -### Service Client Updates -* `service/apigateway`: Updates service API and documentation - * Add support for "embed" property. -* `service/codestar`: Adds new service - * AWS CodeStar is a cloud-based service for creating, managing, and working with software development projects on AWS. An AWS CodeStar project creates and integrates AWS services for your project development toolchain. AWS CodeStar also manages the permissions required for project users. -* `service/ec2`: Updates service API and documentation - * Adds support for creating an Amazon FPGA Image (AFI) from a specified design checkpoint (DCP). -* `service/iam`: Updates service API and documentation - * This changes introduces a new IAM role type, Service Linked Role, which works like a normal role but must be managed via services' control. -* `service/lambda`: Updates service API and documentation - * Lambda integration with CloudDebugger service to enable customers to enable tracing for the Lambda functions and send trace information to the CloudDebugger service. -* `service/lexmodelbuildingservice`: Adds new service -* `service/polly`: Updates service API, documentation, and paginators - * API Update for Amazon Polly: Add support for speech marks -* `service/rekognition`: Updates service API and documentation - * Given an image, the API detects explicit or suggestive adult content in the image and returns a list of corresponding labels with confidence scores, as well as a taxonomy (parent-child relation) for each label. - -Release v1.8.13 (2017-04-18) -=== - -### Service Client Updates -* `service/lambda`: Updates service API and documentation - * You can use tags to group and filter your Lambda functions, making it easier to analyze them for billing allocation purposes. For more information, see Tagging Lambda Functions. You can now write or upgrade your Lambda functions using Python version 3.6. For more information, see Programming Model for Authoring Lambda Functions in Python. Note: Features will be rolled out in the US regions on 4/19. - -### SDK Enhancements -* `aws/request`: add support for appengine's custom standard library (#1190) - * Remove syscall error checking on appengine platforms. - -Release v1.8.12 (2017-04-11) -=== - -### Service Client Updates -* `service/apigateway`: Updates service API and documentation - * API Gateway request validators -* `service/batch`: Updates service API and documentation - * API Update for AWS Batch: Customer provided AMI for MANAGED Compute Environment -* `service/gamelift`: Updates service API and documentation - * Allows developers to utilize an improved workflow when calling our Queues API and introduces a new feature that allows developers to specify a maximum allowable latency per Queue. -* `service/opsworks`: Updates service API, documentation, and paginators - * Cloudwatch Logs agent configuration can now be attached to OpsWorks Layers using CreateLayer and UpdateLayer. OpsWorks will then automatically install and manage the CloudWatch Logs agent on the instances part of the OpsWorks Layer. - -### SDK Bugs -* `aws/client`: Fix clients polluting handler list (#1197) - * Fixes the clients potentially polluting the passed in handler list with the client's customizations. This change ensures every client always works with a clean copy of the request handlers and it cannot pollute the handlers back upstream. - * Fixes #1184 -* `aws/request`: Fix waiter error match condition (#1195) - * Fixes the waiters's matching overwriting the request's err, effectively ignoring the error condition. This broke waiters with the FailureWaiterState matcher state. -Release v1.8.11 (2017-04-07) -=== - -### Service Client Updates -* `service/redshift`: Updates service API, documentation, and paginators - * This update adds the GetClusterCredentials API which is used to get temporary login credentials to the cluster. AccountWithRestoreAccess now has a new member AccountAlias, this is the identifier of the AWS support account authorized to restore the specified snapshot. This is added to support the feature where the customer can share their snapshot with the Amazon Redshift Support Account without having to manually specify the AWS Redshift Service account ID on the AWS Console/API. - -Release v1.8.10 (2017-04-06) -=== - -### Service Client Updates -* `service/elbv2`: Updates service documentation - -Release v1.8.9 (2017-04-05) -=== - -### Service Client Updates -* `service/elasticache`: Updates service API, documentation, paginators, and examples - * ElastiCache added support for testing the Elasticache Multi-AZ feature with Automatic Failover. - -Release v1.8.8 (2017-04-04) -=== - -### Service Client Updates -* `service/cloudwatch`: Updates service API, documentation, and paginators - * Amazon Web Services announced the immediate availability of two additional alarm configuration rules for Amazon CloudWatch Alarms. The first rule is for configuring missing data treatment. Customers have the options to treat missing data as alarm threshold breached, alarm threshold not breached, maintain alarm state and the current default treatment. The second rule is for alarms based on percentiles metrics that can trigger unnecassarily if the percentile is calculated from a small number of samples. The new rule can treat percentiles with low sample counts as same as missing data. If the first rule is enabled, the same treatment will be applied when an alarm encounters a percentile with low sample counts. - -Release v1.8.7 (2017-04-03) -=== - -### Service Client Updates -* `service/lexruntimeservice`: Updates service API and documentation - * Adds support to PostContent for speech input - -### SDK Enhancements -* `aws/request`: Improve handler copy, push back, push front performance (#1171) - * Minor optimization to the handler list's handling of copying and pushing request handlers to the handler list. -* Update codegen header to use Go std wording (#1172) - * Go recently accepted the proposal for standard generated file header wording in, https://golang.org/s/generatedcode. - -### SDK Bugs -* `service/dynamodb`: Fix DynamoDB using custom retryer (#1170) - * Fixes (#1139) the DynamoDB service client clobbering any custom retryer that was passed into the service client or Session's config. -Release v1.8.6 (2017-04-01) -=== - -### Service Client Updates -* `service/clouddirectory`: Updates service API and documentation - * ListObjectAttributes now supports filtering by facet. -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -Release v1.8.5 (2017-03-30) -=== - -### Service Client Updates -* `service/cloudformation`: Updates service waiters and paginators - * Adding paginators for ListExports and ListImports -* `service/cloudfront`: Adds new service - * Amazon CloudFront now supports user configurable HTTP Read and Keep-Alive Idle Timeouts for your Custom Origin Servers -* `service/configservice`: Updates service documentation -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/resourcegroupstaggingapi`: Adds new service -* `service/storagegateway`: Updates service API and documentation - * File gateway mode in AWS Storage gateway provides access to objects in S3 as files on a Network File System (NFS) mount point. Once a file share is created, any changes made externally to the S3 bucket will not be reflected by the gateway. Using the cache refresh feature in this update, the customer can trigger an on-demand scan of the keys in their S3 bucket and refresh the file namespace cached on the gateway. It takes as an input the fileShare ARN and refreshes the cache for only that file share. Additionally there is new functionality on file gateway that allows you configure what squash options they would like on their file share, this allows a customer to configure their gateway to not squash root permissions. This can be done by setting options in NfsOptions for CreateNfsFileShare and UpdateNfsFileShare APIs. - -Release v1.8.4 (2017-03-28) -=== - -### Service Client Updates -* `service/batch`: Updates service API, documentation, and paginators - * Customers can now provide a retryStrategy as part of the RegisterJobDefinition and SubmitJob API calls. The retryStrategy object has a number value for attempts. This is the number of non successful executions before a job is considered FAILED. In addition, the JobDetail object now has an attempts field and shows all execution attempts. -* `service/ec2`: Updates service API and documentation - * Customers can now tag their Amazon EC2 Instances and Amazon EBS Volumes at - the time of their creation. You can do this from the EC2 Instance launch - wizard or through the RunInstances or CreateVolume APIs. By tagging - resources at the time of creation, you can eliminate the need to run custom - tagging scripts after resource creation. In addition, you can now set - resource-level permissions on the CreateVolume, CreateTags, DeleteTags, and - the RunInstances APIs. This allows you to implement stronger security - policies by giving you more granular control over which users and groups - have access to these APIs. You can also enforce the use of tagging and - control what tag keys and values are set on your resources. When you combine - tag usage and resource-level IAM policies together, you can ensure your - instances and volumes are properly secured upon creation and achieve more - accurate cost allocation reporting. These new features are provided at no - additional cost. - -### SDK Enhancements -* `aws/request`: Add retry support for RequestTimeoutException (#1158) - * Adds support for retrying RequestTimeoutException error code that is returned by some services. - -### SDK Bugs -* `private/model/api`: Fix Waiter and Paginators panic on nil param inputs (#1157) - * Corrects the code generation for Paginators and waiters that caused a panic if nil input parameters were used with the operations. -Release v1.8.3 (2017-03-27) -=== - -## Service Client Updates -* `service/ssm`: Updates service API, documentation, and paginators - * Updated validation rules for SendCommand and RegisterTaskWithMaintenanceWindow APIs. -Release v1.8.2 (2017-03-24) -=== - -Service Client Updates ---- -* `service/applicationautoscaling`: Updates service API, documentation, and paginators - * Application AutoScaling is launching support for a new target resource (AppStream 2.0 Fleets) as a scalable target. -* `service/cloudtrail`: Updates service API and documentation - * Doc-only Update for CloudTrail: Add required parameters for GetEventSelectors and PutEventSelectors - -Release v1.8.1 (2017-03-23) -=== - -Service Client Updates ---- -* `service/applicationdiscoveryservice`: Updates service API, documentation, and paginators - * Adds export configuration options to the AWS Discovery Service API. -* `service/elbv2`: Updates waiters -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/lambda`: Updates service API and paginators - * Adds support for new runtime Node.js v6.10 for AWS Lambda service - -Release v1.8.0 (2017-03-22) -=== - -Service Client Updates ---- -* `service/codebuild`: Updates service documentation -* `service/directconnect`: Updates service API - * Deprecated DescribeConnectionLoa, DescribeInterconnectLoa, AllocateConnectionOnInterconnect and DescribeConnectionsOnInterconnect operations in favor of DescribeLoa, DescribeLoa, AllocateHostedConnection and DescribeHostedConnections respectively. -* `service/marketplacecommerceanalytics`: Updates service API, documentation, and paginators - * This update adds a new data set, us_sales_and_use_tax_records, which enables AWS Marketplace sellers to programmatically access to their U.S. Sales and Use Tax report data. -* `service/pinpoint`: Updates service API and documentation - * Amazon Pinpoint User Segmentation - * Added ability to segment endpoints by user attributes in addition to endpoint attributes. Amazon Pinpoint Event Stream Preview - * Added functionality to publish raw app analytics and campaign events data as events streams to Kinesis and Kinesis Firehose - * The feature provides developers with increased flexibility of exporting raw events to S3, Redshift, Elasticsearch using a Kinesis Firehose stream or enable real time event processing use cases using a Kinesis stream -* `service/rekognition`: Updates service documentation. - -SDK Features ---- -* `aws/request`: Add support for context.Context to SDK API operation requests (#1132) - * Adds support for context.Context to the SDK by adding `WithContext` methods for each API operation, Paginators and Waiters. e.g `PutObjectWithContext`. This change also adds the ability to provide request functional options to the method calls instead of requiring you to use the `Request` API operation method (e.g `PutObjectRequest`). - * Adds a `Complete` Request handler list that will be called ever time a request is completed. This includes both success and failure. Complete will only be called once per API operation request. - * `private/waiter` package moved from the private group to `aws/request/waiter` and made publicly available. - * Adds Context support to all API operations, Waiters(WaitUntil) and Paginators(Pages) methods. - * Adds Context support for s3manager and s3crypto clients. - -SDK Enhancements ---- -* `aws/signer/v4`: Adds support for unsigned payload signer config (#1130) - * Adds configuration option to the v4.Signer to specify the request's body should not be signed. This will only correclty function on services that support unsigned payload. e.g. S3, Glacier. - -SDK Bug Fixes ---- -* `service/s3`: Fix S3 HostID to be available in S3 request error message (#1131) - * Adds a new type s3.RequestFailure which exposes the S3 HostID value from a S3 API operation response. This is helpful when you have an error with S3, and need to contact support. Both RequestID and HostID are needed. -* `private/model/api`: Do not return a link if uid is empty (#1133) - * Fixes SDK's doc generation to not generate API reference doc links if the SDK us unable to create a valid link. -* `aws/request`: Optimization to handler list copy to prevent multiple alloc calls. (#1134) -Release v1.7.9 (2017-03-13) -=== - -Service Client Updates ---- -* `service/devicefarm`: Updates service API, documentation, paginators, and examples - * Network shaping allows users to simulate network connections and conditions while testing their Android, iOS, and web apps with AWS Device Farm. -* `service/cloudwatchevents`: Updates service API, documentation, and examples - -SDK Enhancement -=== -* `aws/session`: Add support for side loaded CA bundles (#1117) - * Adds supports for side loading Certificate Authority bundle files to the SDK using AWS_CA_BUNDLE environment variable or CustomCABundle session option. -* `service/s3/s3crypto`: Add support for AES/CBC/PKCS5Padding (#1124) - -SDK Bug -=== -* `service/rds`: Fixing issue when not providing `SourceRegion` on cross -region operations (#1127) -* `service/rds`: Enables cross region for `CopyDBClusterSnapshot` and -`CreateDBCluster` (#1128) - -Release v1.7.8 (2017-03-10) -=== - -Service Client Updates ---- -* `service/codedeploy`: Updates service paginators - * Add paginators for Codedeploy -* `service/emr`: Updates service API, documentation, and paginators - * This release includes support for instance fleets in Amazon EMR. - -Release v1.7.7 (2017-03-09) -=== - -Service Client Updates ---- -* `service/apigateway`: Updates service API, documentation, and paginators - * API Gateway has added support for ACM certificates on custom domain names. Both Amazon-issued certificates and uploaded third-part certificates are supported. -* `service/clouddirectory`: Updates service API, documentation, and paginators - * Introduces a new Cloud Directory API that enables you to retrieve all available parent paths for any type of object (a node, leaf node, policy node, and index node) in a hierarchy. - -Release v1.7.6 (2017-03-09) -=== - -Service Client Updates ---- -* `service/organizations`: Updates service documentation and examples - * Doc-only Update for Organizations: Add SDK Code Snippets -* `service/workdocs`: Adds new service - * The Administrative SDKs for Amazon WorkDocs provides full administrator level access to WorkDocs site resources, allowing developers to integrate their applications to manage WorkDocs users, content and permissions programmatically - -Release v1.7.5 (2017-03-08) -=== - -Service Client Updates ---- -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/rds`: Updates service API and documentation - * Add support to using encrypted clusters as cross-region replication masters. Update CopyDBClusterSnapshot API to support encrypted cross region copy of Aurora cluster snapshots. - -Release v1.7.4 (2017-03-06) -=== - -Service Client Updates ---- -* `service/budgets`: Updates service API and paginators - * When creating or editing a budget via the AWS Budgets API you can define notifications that are sent to subscribers when the actual or forecasted value for cost or usage exceeds the notificationThreshold associated with the budget notification object. Starting today, the maximum allowed value for the notificationThreshold was raised from 100 to 300. This change was made to give you more flexibility when setting budget notifications. -* `service/cloudtrail`: Updates service documentation and paginators - * Doc-only update for AWSCloudTrail: Updated links/descriptions -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/opsworkscm`: Updates service API, documentation, and paginators - * OpsWorks for Chef Automate has added a new field "AssociatePublicIpAddress" to the CreateServer request, "CloudFormationStackArn" to the Server model and "TERMINATED" server state. - - -Release v1.7.3 (2017-02-28) -=== - -Service Client Updates ---- -* `service/mturk`: Renaming service - * service/mechanicalturkrequesterservice was renamed to service/mturk. Be sure to change any references of the old client to the new. - -Release v1.7.2 (2017-02-28) -=== - -Service Client Updates ---- -* `service/dynamodb`: Updates service API and documentation - * Release notes: Time to Live (TTL) is a feature that allows you to define when items in a table expire and can be purged from the database, so that you don't have to track expired data and delete it manually. With TTL enabled on a DynamoDB table, you can set a timestamp for deletion on a per-item basis, allowing you to limit storage usage to only those records that are relevant. -* `service/iam`: Updates service API, documentation, and paginators - * This release adds support for AWS Organizations service control policies (SCPs) to SimulatePrincipalPolicy operation. If there are SCPs associated with the simulated user's account, their effect on the result is captured in the OrganizationDecisionDetail element in the EvaluationResult. -* `service/mechanicalturkrequesterservice`: Adds new service - * Amazon Mechanical Turk is a web service that provides an on-demand, scalable, human workforce to complete jobs that humans can do better than computers, for example, recognizing objects in photos. -* `service/organizations`: Adds new service - * AWS Organizations is a web service that enables you to consolidate your multiple AWS accounts into an organization and centrally manage your accounts and their resources. -* `service/dynamodbstreams`: Updates service API, documentation, and paginators -* `service/waf`: Updates service API, documentation, and paginators - * Aws WAF - For GetSampledRequests action, changed max number of samples from 100 to 500. -* `service/wafregional`: Updates service API, documentation, and paginators - -Release v1.7.1 (2017-02-24) -=== - -Service Client Updates ---- -* `service/elasticsearchservice`: Updates service API, documentation, paginators, and examples - * Added three new API calls to existing Amazon Elasticsearch service to expose Amazon Elasticsearch imposed limits to customers. - -Release v1.7.0 (2017-02-23) -=== - -Service Client Updates ---- -* `service/ec2`: Updates service API - * New EC2 I3 instance type - -SDK Bug ---- -* `service/s3/s3manager`: Adding support for SSE (#1097) - * Fixes SSE fields not being applied to a part during multi part upload. - -SDK Feature ---- -* `aws/session`: Add support for AssumeRoles with MFA (#1088) - * Adds support for assuming IAM roles with MFA enabled. A TokenProvider func was added to stscreds.AssumeRoleProvider that will be called each time the role's credentials need to be refreshed. A basic token provider that sources the MFA token from stdin as stscreds.StdinTokenProvider. -* `aws/session`: Update SDK examples and docs to use session.Must (#1099) - * Updates the SDK's example and docs to use session.Must where possible to highlight its usage as apposed to session error checking that is most cases errors will be terminal to the application anyways. -Release v1.6.27 (2017-02-22) -=== - -Service Client Updates ---- -* `service/clouddirectory`: Updates service documentation - * ListObjectAttributes documentation updated based on forum feedback -* `service/elasticbeanstalk`: Updates service API, documentation, and paginators - * Elastic Beanstalk adds support for creating and managing custom platform. -* `service/gamelift`: Updates service API, documentation, and paginators - * Allow developers to configure global queues for creating GameSessions. Allow PlayerData on PlayerSessions to store player-specific data. -* `service/route53`: Updates service API, documentation, and examples - * Added support for operations CreateVPCAssociationAuthorization and DeleteVPCAssociationAuthorization to throw a ConcurrentModification error when a conflicting modification occurs in parallel to the authorizations in place for a given hosted zone. - -Release v1.6.26 (2017-02-21) -=== - -Service Client Updates ---- -* `service/ec2`: Updates service API and documentation - * Added the billingProduct parameter to the RegisterImage API. - -Release v1.6.25 (2017-02-17) -=== - -Service Client Updates ---- -* `service/directconnect`: Updates service API, documentation, and paginators - * This update will introduce the ability for Direct Connect customers to take advantage of Link Aggregation (LAG). This allows you to bundle many individual physical interfaces into a single logical interface, referred to as a LAG. This makes administration much simpler as the majority of configuration is done on the LAG while you are free to add or remove physical interfaces from the bundle as bandwidth demand increases or decreases. A concrete example of the simplification added by LAG is that customers need only a single BGP session as opposed to one session per physical connection. - -Release v1.6.24 (2017-02-16) -=== - -Service Client Updates ---- -* `service/cognitoidentity`: Updates service API, documentation, and paginators - * Allow createIdentityPool and updateIdentityPool API to set server side token check value on identity pool -* `service/configservice`: Updates service API and documentation - * AWS Config now supports a new test mode for the PutEvaluations API. Set the TestMode parameter to true in your custom rule to verify whether your AWS Lambda function will deliver evaluation results to AWS Config. No updates occur to your existing evaluations, and evaluation results are not sent to AWS Config. - -Release v1.6.23 (2017-02-15) -=== - -Service Client Updates ---- -* `service/kms`: Updates service API, documentation, paginators, and examples - * his release of AWS Key Management Service introduces the ability to tag keys. Tagging keys can help you organize your keys and track your KMS costs in the cost allocation report. This release also increases the maximum length of a key ID to accommodate ARNs that include a long key alias. - -Release v1.6.22 (2017-02-14) -=== - -Service Client Updates ---- -* `service/ec2`: Updates service API, documentation, and paginators - * Adds support for the new Modify Volumes apis. - -Release v1.6.21 (2017-02-11) -=== - -Service Client Updates ---- -* `service/storagegateway`: Updates service API, documentation, and paginators - * File gateway mode in AWS Storage gateway provides access to objects in S3 as files on a Network File System (NFS) mount point. This is done by creating Nfs file shares using existing APIs CreateNfsFileShare. Using the feature in this update, the customer can restrict the clients that have read/write access to the gateway by specifying the list of clients as a list of IP addresses or CIDR blocks. This list can be specified using the API CreateNfsFileShare while creating new file shares, or UpdateNfsFileShare while update existing file shares. To find out the list of clients that have access, the existing API DescribeNfsFileShare will now output the list of clients that have access. - -Release v1.6.20 (2017-02-09) -=== - -Service Client Updates ---- -* `service/ec2`: Updates service API and documentation - * This feature allows customers to associate an IAM profile to running instances that do not have any. -* `service/rekognition`: Updates service API and documentation - * DetectFaces and IndexFaces operations now return an estimate of the age of the face as an age range. - -SDK Features ---- -* `aws/endpoints`: Add option to resolve unknown endpoints (#1074) -Release v1.6.19 (2017-02-08) -=== - -Service Client Updates ---- -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/glacier`: Updates service examples - * Doc Update -* `service/lexruntimeservice`: Adds new service - * Preview release - -SDK Bug Fixes ---- -* `private/protocol/json`: Fixes json to throw an error if a float number is (+/-)Inf and NaN (#1068) -* `private/model/api`: Fix documentation error listing (#1067) - -SDK Features ---- -* `private/model`: Add service response error code generation (#1061) - -Release v1.6.18 (2017-01-27) -=== - -Service Client Updates ---- -* `service/clouddirectory`: Adds new service - * Amazon Cloud Directory is a highly scalable, high performance, multi-tenant directory service in the cloud. Its web-based directories make it easy for you to organize and manage application resources such as users, groups, locations, devices, policies, and the rich relationships between them. -* `service/codedeploy`: Updates service API, documentation, and paginators - * This release of AWS CodeDeploy introduces support for blue/green deployments. In a blue/green deployment, the current set of instances in a deployment group is replaced by new instances that have the latest application revision installed on them. After traffic is rerouted behind a load balancer to the replacement instances, the original instances can be terminated automatically or kept running for other uses. -* `service/ec2`: Updates service API and documentation - * Adds instance health check functionality to replace unhealthy EC2 Spot fleet instances with fresh ones. -* `service/rds`: Updates service API and documentation - * Snapshot Engine Version Upgrade - -Release v1.6.17 (2017-01-25) -=== - -Service Client Updates ---- -* `service/elbv2`: Updates service API, documentation, and paginators - * Application Load Balancers now support native Internet Protocol version 6 (IPv6) in an Amazon Virtual Private Cloud (VPC). With this ability, clients can now connect to the Application Load Balancer in a dual-stack mode via either IPv4 or IPv6. -* `service/rds`: Updates service API and documentation - * Cross Region Read Replica Copying (CreateDBInstanceReadReplica) - -Release v1.6.16 (2017-01-24) -=== - -Service Client Updates ---- -* `service/codebuild`: Updates service documentation and paginators - * Documentation updates -* `service/codecommit`: Updates service API, documentation, and paginators - * AWS CodeCommit now includes the option to view the differences between a commit and its parent commit from within the console. You can view the differences inline (Unified view) or side by side (Split view). To view information about the differences between a commit and something other than its parent, you can use the AWS CLI and the get-differences and get-blob commands, or you can use the GetDifferences and GetBlob APIs. -* `service/ecs`: Updates service API and documentation - * Amazon ECS now supports a state for container instances that can be used to drain a container instance in preparation for maintenance or cluster scale down. - -Release v1.6.15 (2017-01-20) -=== - -Service Client Updates ---- -* `service/acm`: Updates service API, documentation, and paginators - * Update for AWS Certificate Manager: Updated response elements for DescribeCertificate API in support of managed renewal -* `service/health`: Updates service documentation - -Release v1.6.14 (2017-01-19) -=== - -Service Client Updates ---- -* `service/ec2`: Updates service API, documentation, and paginators - * Amazon EC2 Spot instances now support dedicated tenancy, providing the ability to run Spot instances single-tenant manner on physically isolated hardware within a VPC to satisfy security, privacy, or other compliance requirements. Dedicated Spot instances can be requested using RequestSpotInstances and RequestSpotFleet. - -Release v1.6.13 (2017-01-18) -=== - -Service Client Updates ---- -* `service/rds`: Updates service API, documentation, and paginators - -Release v1.6.12 (2017-01-17) -=== - -Service Client Updates ---- -* `service/dynamodb`: Updates service API, documentation, and paginators - * Tagging Support for Amazon DynamoDB Tables and Indexes -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/glacier`: Updates service API, paginators, and examples - * Doc-only Update for Glacier: Added code snippets -* `service/polly`: Updates service documentation and examples - * Doc-only update for Amazon Polly -- added snippets -* `service/rekognition`: Updates service documentation and paginators - * Added code samples to Rekognition reference topics. -* `service/route53`: Updates service API and paginators - * Add ca-central-1 and eu-west-2 enum values to CloudWatchRegion enum - -Release v1.6.11 (2017-01-16) -=== - -Service Client Updates ---- -* `service/configservice`: Updates service API, documentation, and paginators -* `service/costandusagereportservice`: Adds new service - * The AWS Cost and Usage Report Service API allows you to enable and disable the Cost & Usage report, as well as modify the report name, the data granularity, and the delivery preferences. -* `service/dynamodb`: Updates service API, documentation, and examples - * Snippets for the DynamoDB API. -* `service/elasticache`: Updates service API, documentation, and examples - * Adds new code examples. -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -Release v1.6.10 (2017-01-04) -=== - -Service Client Updates ---- -* `service/configservice`: Updates service API and documentation - * AWSConfig is planning to add support for OversizedConfigurationItemChangeNotification message type in putConfigRule. After this release customers can use/write rules based on OversizedConfigurationItemChangeNotification mesage type. -* `service/efs`: Updates service API, documentation, and examples - * Doc-only Update for EFS: Added code snippets -* `service/iam`: Updates service documentation and examples -* `service/lambda`: Updates service documentation and examples - * Doc only updates for Lambda: Added code snippets -* `service/marketplacecommerceanalytics`: Updates service API and documentation - * Added support for data set disbursed_amount_by_instance_hours, with historical data available starting 2012-09-04. New data is published to this data set every 30 days. -* `service/rds`: Updates service documentation - * Updated documentation for CopyDBSnapshot. -* `service/rekognition`: Updates service documentation and examples - * Doc-only Update for Rekognition: Added code snippets -* `service/snowball`: Updates service examples -* `service/dynamodbstreams`: Updates service API and examples - * Doc-only Update for DynamoDB Streams: Added code snippets - -SDK Feature ---- -* `private/model/api`: Increasing the readability of code generated files. (#1024) -Release v1.6.9 (2016-12-30) -=== - -Service Client Updates ---- -* `service/codedeploy`: Updates service API and documentation - * CodeDeploy will support Iam Session Arns in addition to Iam User Arns for on premise host authentication. -* `service/ecs`: Updates service API and documentation - * Amazon EC2 Container Service (ECS) now supports the ability to customize the placement of tasks on container instances. -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -Release v1.6.8 (2016-12-22) -=== - -Service Client Updates ---- -* `service/apigateway`: Updates service API and documentation - * Amazon API Gateway is adding support for generating SDKs in more languages. This update introduces two new operations used to dynamically discover these SDK types and what configuration each type accepts. -* `service/directoryservice`: Updates service documentation - * Added code snippets for the DS SDKs -* `service/elasticbeanstalk`: Updates service API and documentation -* `service/iam`: Updates service API and documentation - * Adds service-specific credentials to IAM service to make it easier to onboard CodeCommit customers. These are username/password credentials that work with a single service. -* `service/kms`: Updates service API, documentation, and examples - * Update docs and add SDK examples - -Release v1.6.7 (2016-12-22) -=== - -Service Client Updates ---- -* `service/ecr`: Updates service API and documentation -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/rds`: Updates service API and documentation - * Cross Region Encrypted Snapshot Copying (CopyDBSnapshot) - -Release v1.6.6 (2016-12-20) -=== - -Service Client Updates ---- -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/firehose`: Updates service API, documentation, and examples - * Processing feature enables users to process and modify records before Amazon Firehose delivers them to destinations. -* `service/route53`: Updates service API and documentation - * Enum updates for eu-west-2 and ca-central-1 -* `service/storagegateway`: Updates service API, documentation, and examples - * File gateway is a new mode in the AWS Storage Gateway that support a file interface into S3, alongside the current block-based volume and VTL storage. File gateway combines a service and virtual software appliance, enabling you to store and retrieve objects in Amazon S3 using industry standard file protocols such as NFS. The software appliance, or gateway, is deployed into your on-premises environment as a virtual machine (VM) running on VMware ESXi. The gateway provides access to objects in S3 as files on a Network File System (NFS) mount point. - -Release v1.6.5 (2016-12-19) -=== - -Service Client Updates ---- -* `service/cloudformation`: Updates service documentation - * Minor doc update for CloudFormation. -* `service/cloudtrail`: Updates service paginators -* `service/cognitoidentity`: Updates service API and documentation - * We are adding Groups to Cognito user pools. Developers can perform CRUD operations on groups, add and remove users from groups, list users in groups, etc. We are adding fine-grained role-based access control for Cognito identity pools. Developers can configure an identity pool to get the IAM role from an authenticated user's token, or they can configure rules that will map a user to a different role -* `service/applicationdiscoveryservice`: Updates service API and documentation - * Adds new APIs to group discovered servers into Applications with get summary and neighbors. Includes additional filters for ListConfigurations and DescribeAgents API. -* `service/inspector`: Updates service API, documentation, and examples - * Doc-only Update for Inspector: Adding SDK code snippets for Inspector -* `service/sqs`: Updates service documentation - -SDK Bug Fixes ---- -* `aws/request`: Add PriorRequestNotComplete to throttle retry codes (#1011) - * Fixes: Not retrying when PriorRequestNotComplete #1009 - -SDK Feature ---- -* `private/model/api`: Adds crosslinking to service documentation (#1010) - -Release v1.6.4 (2016-12-15) -=== - -Service Client Updates ---- -* `service/cognitoidentityprovider`: Updates service API and documentation -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/ssm`: Updates service API and documentation - * This will provide customers with access to the Patch Baseline and Patch Compliance APIs. - -SDK Bug Fixes ---- -* `service/route53`: Fix URL path cleaning for Route53 API requests (#1006) - * Fixes: SerializationError when using Route53 ChangeResourceRecordSets #1005 -* `aws/request`: Add PriorRequestNotComplete to throttle retry codes (#1002) - * Fixes: Not retrying when PriorRequestNotComplete #1001 - -Release v1.6.3 (2016-12-14) -=== - -Service Client Updates ---- -* `service/batch`: Adds new service - * AWS Batch is a batch computing service that lets customers define queues and compute environments and then submit work as batch jobs. -* `service/databasemigrationservice`: Updates service API and documentation - * Adds support for SSL enabled Oracle endpoints and task modification. -* `service/elasticbeanstalk`: Updates service documentation -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/cloudwatchlogs`: Updates service API and documentation - * Add support for associating LogGroups with AWSTagris tags -* `service/marketplacecommerceanalytics`: Updates service API and documentation - * Add new enum to DataSetType: sales_compensation_billed_revenue -* `service/rds`: Updates service documentation - * Doc-only Update for RDS: New versions available in CreateDBInstance -* `service/sts`: Updates service documentation - * Adding Code Snippet Examples for SDKs for STS - -SDK Bug Fixes ---- -* `aws/request`: Fix retrying timeout requests (#981) - * Fixes: Requests Retrying is broken if the error was caused due to a client timeout #947 -* `aws/request`: Fix for Go 1.8 request incorrectly sent with body (#991) - * Fixes: service/route53: ListHostedZones hangs and then fails with go1.8 #984 -* private/protocol/rest: Use RawPath instead of Opaque (#993) - * Fixes: HTTP2 request failing with REST protocol services, e.g AWS X-Ray -* private/model/api: Generate REST-JSON JSONVersion correctly (#998) - * Fixes: REST-JSON protocol service code missing JSONVersion metadata. - -Release v1.6.2 (2016-12-08) -=== - -Service Client Updates ---- -* `service/cloudfront`: Add lambda function associations to cache behaviors -* `service/codepipeline`: This is a doc-only update request to incorporate some recent minor revisions to the doc content. -* `service/rds`: Updates service API and documentation -* `service/wafregional`: With this new feature, customers can use AWS WAF directly on Application Load Balancers in a VPC within available regions to protect their websites and web services from malicious attacks such as SQL injection, Cross Site Scripting, bad bots, etc. - -Release v1.6.1 (2016-12-07) -=== - -Service Client Updates ---- -* `service/config`: Updates service API -* `service/s3`: Updates service API -* `service/sqs`: Updates service API and documentation - -Release v1.6.0 (2016-12-06) -=== - -Service Client Updates ---- -* `service/config`: Updates service API and documentation -* `service/ec2`: Updates service API -* `service/sts`: Updates service API, documentation, and examples - -SDK Bug Fixes ---- -* private/protocol/xml/xmlutil: Fix SDK XML unmarshaler #975 - * Fixes GetBucketACL Grantee required type always nil. #916 - -SDK Feature ---- -* aws/endpoints: Add endpoint metadata to SDK #961 - * Adds Region and Endpoint metadata to the SDK. This allows you to enumerate regions and endpoint metadata based on a defined model embedded in the SDK. - -Release v1.5.13 (2016-12-01) -=== - -Service Client Updates ---- -* `service/apigateway`: Updates service API and documentation -* `service/appstream`: Adds new service -* `service/codebuild`: Adds new service -* `service/directconnect`: Updates service API and documentation -* `service/ec2`: Adds new service -* `service/elasticbeanstalk`: Updates service API and documentation -* `service/health`: Adds new service -* `service/lambda`: Updates service API and documentation -* `service/opsworkscm`: Adds new service -* `service/pinpoint`: Adds new service -* `service/shield`: Adds new service -* `service/ssm`: Updates service API and documentation -* `service/states`: Adds new service -* `service/xray`: Adds new service - -Release v1.5.12 (2016-11-30) -=== - -Service Client Updates ---- -* `service/lightsail`: Adds new service -* `service/polly`: Adds new service -* `service/rekognition`: Adds new service -* `service/snowball`: Updates service API and documentation - -Release v1.5.11 (2016-11-29) -=== - -Service Client Updates ---- -`service/s3`: Updates service API and documentation - -Release v1.5.10 (2016-11-22) -=== - -Service Client Updates ---- -* `service/cloudformation`: Updates service API and documentation -* `service/glacier`: Updates service API, documentation, and examples -* `service/route53`: Updates service API and documentation -* `service/s3`: Updates service API and documentation - -SDK Bug Fixes ---- -* `private/protocol/xml/xmlutil`: Fixes xml marshaler to unmarshal properly -into tagged fields -[#916](https://github.com/aws/aws-sdk-go/issues/916) - -Release v1.5.9 (2016-11-22) -=== - -Service Client Updates ---- -* `service/cloudtrail`: Updates service API and documentation -* `service/ecs`: Updates service API and documentation - -Release v1.5.8 (2016-11-18) -=== - -Service Client Updates ---- -* `service/application-autoscaling`: Updates service API and documentation -* `service/elasticmapreduce`: Updates service API and documentation -* `service/elastictranscoder`: Updates service API, documentation, and examples -* `service/gamelift`: Updates service API and documentation -* `service/lambda`: Updates service API and documentation - -Release v1.5.7 (2016-11-18) -=== - -Service Client Updates ---- -* `service/apigateway`: Updates service API and documentation -* `service/meteringmarketplace`: Updates service API and documentation -* `service/monitoring`: Updates service API and documentation -* `service/sqs`: Updates service API, documentation, and examples - -Release v1.5.6 (2016-11-16) -=== - -Service Client Updates ---- -`service/route53`: Updates service API and documentation -`service/servicecatalog`: Updates service API and documentation - -Release v1.5.5 (2016-11-15) -=== - -Service Client Updates ---- -* `service/ds`: Updates service API and documentation -* `service/elasticache`: Updates service API and documentation -* `service/kinesis`: Updates service API and documentation - -Release v1.5.4 (2016-11-15) -=== - -Service Client Updates ---- -* `service/cognito-idp`: Updates service API and documentation - -Release v1.5.3 (2016-11-11) -=== - -Service Client Updates ---- -* `service/cloudformation`: Updates service documentation and examples -* `service/logs`: Updates service API and documentation - -Release v1.5.2 (2016-11-03) -=== - -Service Client Updates ---- -* `service/directconnect`: Updates service API and documentation - -Release v1.5.1 (2016-11-02) -=== - -Service Client Updates ---- -* `service/email`: Updates service API and documentation - -Release v1.5.0 (2016-11-01) -=== - -Service Client Updates ---- -* `service/cloudformation`: Updates service API and documentation -* `service/ecr`: Updates service paginators - -SDK Feature Updates ---- -* `private/model/api`: Add generated setters for API parameters (#918) - * Adds setters to the SDK's API parameter types, and are a convenience method that reduce the need to use `aws.String` and like utility. - -Release v1.4.22 (2016-10-25) -=== - -Service Client Updates ---- -* `service/elasticloadbalancingv2`: Updates service documentation. -* `service/autoscaling`: Updates service documentation. - -Release v1.4.21 (2016-10-24) -=== - -Service Client Updates ---- -* `service/sms`: AWS Server Migration Service (SMS) is an agentless service which makes it easier and faster for you to migrate thousands of on-premises workloads to AWS. AWS SMS allows you to automate, schedule, and track incremental replications of live server volumes, making it easier for you to coordinate large-scale server migrations. -* `service/ecs`: Updates documentation. - -SDK Feature Updates ---- -* `private/models/api`: Improve code generation of documentation. - -Release v1.4.20 (2016-10-20) -=== - -Service Client Updates ---- -* `service/budgets`: Adds new service, AWS Budgets. -* `service/waf`: Updates service documentation. - -Release v1.4.19 (2016-10-18) -=== - -Service Client Updates ---- -* `service/cloudfront`: Updates service API and documentation. - * Ability to use Amazon CloudFront to deliver your content both via IPv6 and IPv4 using HTTP/HTTPS. -* `service/configservice`: Update service API and documentation. -* `service/iot`: Updates service API and documentation. -* `service/kinesisanalytics`: Updates service API and documentation. - * Whenever Amazon Kinesis Analytics is not able to detect schema for the given streaming source on DiscoverInputSchema API, we would return the raw records that was sampled to detect the schema. -* `service/rds`: Updates service API and documentation. - * Amazon Aurora integrates with other AWS services to allow you to extend your Aurora DB cluster to utilize other capabilities in the AWS cloud. Permission to access other AWS services is granted by creating an IAM role with the necessary permissions, and then associating the role with your DB cluster. - -SDK Feature Updates ---- -* `service/dynamodb/dynamodbattribute`: Add UnmarshalListOfMaps #897 - * Adds support for unmarshaling a list of maps. This is useful for unmarshaling the DynamoDB AttributeValue list of maps returned by APIs like Query and Scan. - -Release v1.4.18 (2016-10-17) -=== - -Service Model Updates ---- -* `service/route53`: Updates service API and documentation. - -Release v1.4.17 -=== - -Service Model Updates ---- -* `service/acm`: Update service API, and documentation. - * This change allows users to import third-party SSL/TLS certificates into ACM. -* `service/elasticbeanstalk`: Update service API, documentation, and pagination. - * Elastic Beanstalk DescribeApplicationVersions API is being updated to support pagination. -* `service/gamelift`: Update service API, and documentation. - * New APIs to protect game developer resource (builds, alias, fleets, instances, game sessions and player sessions) against abuse. - -SDK Features ---- -* `service/s3`: Add support for accelerate with dualstack [#887](https://github.com/aws/aws-sdk-go/issues/887) - -Release v1.4.16 (2016-10-13) -=== - -Service Model Updates ---- -* `service/ecr`: Update Amazon EC2 Container Registry service model - * DescribeImages is a new api used to expose image metadata which today includes image size and image creation timestamp. -* `service/elasticache`: Update Amazon ElastiCache service model - * Elasticache is launching a new major engine release of Redis, 3.2 (providing stability updates and new command sets over 2.8), as well as ElasticSupport for enabling Redis Cluster in 3.2, which provides support for multiple node groups to horizontally scale data, as well as superior engine failover capabilities - -SDK Bug Fixes ---- -* `aws/session`: Skip shared config on read errors [#883](https://github.com/aws/aws-sdk-go/issues/883) -* `aws/signer/v4`: Add support for URL.EscapedPath to signer [#885](https://github.com/aws/aws-sdk-go/issues/885) - -SDK Features ---- -* `private/model/api`: Add docs for errors to API operations [#881](https://github.com/aws/aws-sdk-go/issues/881) -* `private/model/api`: Improve field and waiter doc strings [#879](https://github.com/aws/aws-sdk-go/issues/879) -* `service/dynamodb/dynamodbattribute`: Allow multiple struct tag elements [#886](https://github.com/aws/aws-sdk-go/issues/886) -* Add build tags to internal SDK tools [#880](https://github.com/aws/aws-sdk-go/issues/880) - -Release v1.4.15 (2016-10-06) -=== - -Service Model Updates ---- -* `service/cognitoidentityprovider`: Update Amazon Cognito Identity Provider service model -* `service/devicefarm`: Update AWS Device Farm documentation -* `service/opsworks`: Update AWS OpsWorks service model -* `service/s3`: Update Amazon Simple Storage Service model -* `service/waf`: Update AWS WAF service model - -SDK Bug Fixes ---- -* `aws/request`: Fix HTTP Request Body race condition [#874](https://github.com/aws/aws-sdk-go/issues/874) - -SDK Feature Updates ---- -* `aws/ec2metadata`: Add support for EC2 User Data [#872](https://github.com/aws/aws-sdk-go/issues/872) -* `aws/signer/v4`: Remove logic determining if request needs to be resigned [#876](https://github.com/aws/aws-sdk-go/issues/876) - -Release v1.4.14 (2016-09-29) -=== -* `service/ec2`: api, documentation, and paginators updates. -* `service/s3`: api and documentation updates. - -Release v1.4.13 (2016-09-27) -=== -* `service/codepipeline`: documentation updates. -* `service/cloudformation`: api and documentation updates. -* `service/kms`: documentation updates. -* `service/elasticfilesystem`: documentation updates. -* `service/snowball`: documentation updates. diff --git a/vendor/github.com/aws/aws-sdk-go/CHANGELOG_PENDING.md b/vendor/github.com/aws/aws-sdk-go/CHANGELOG_PENDING.md deleted file mode 100644 index 8a1927a39..000000000 --- a/vendor/github.com/aws/aws-sdk-go/CHANGELOG_PENDING.md +++ /dev/null @@ -1,5 +0,0 @@ -### SDK Features - -### SDK Enhancements - -### SDK Bugs diff --git a/vendor/github.com/aws/aws-sdk-go/CONTRIBUTING.md b/vendor/github.com/aws/aws-sdk-go/CONTRIBUTING.md deleted file mode 100644 index 6f422a95e..000000000 --- a/vendor/github.com/aws/aws-sdk-go/CONTRIBUTING.md +++ /dev/null @@ -1,127 +0,0 @@ -Contributing to the AWS SDK for Go - -We work hard to provide a high-quality and useful SDK, and we greatly value -feedback and contributions from our community. Whether it's a bug report, -new feature, correction, or additional documentation, we welcome your issues -and pull requests. Please read through this document before submitting any -issues or pull requests to ensure we have all the necessary information to -effectively respond to your bug report or contribution. - - -## Filing Bug Reports - -You can file bug reports against the SDK on the [GitHub issues][issues] page. - -If you are filing a report for a bug or regression in the SDK, it's extremely -helpful to provide as much information as possible when opening the original -issue. This helps us reproduce and investigate the possible bug without having -to wait for this extra information to be provided. Please read the following -guidelines prior to filing a bug report. - -1. Search through existing [issues][] to ensure that your specific issue has - not yet been reported. If it is a common issue, it is likely there is - already a bug report for your problem. - -2. Ensure that you have tested the latest version of the SDK. Although you - may have an issue against an older version of the SDK, we cannot provide - bug fixes for old versions. It's also possible that the bug may have been - fixed in the latest release. - -3. Provide as much information about your environment, SDK version, and - relevant dependencies as possible. For example, let us know what version - of Go you are using, which and version of the operating system, and the - the environment your code is running in. e.g Container. - -4. Provide a minimal test case that reproduces your issue or any error - information you related to your problem. We can provide feedback much - more quickly if we know what operations you are calling in the SDK. If - you cannot provide a full test case, provide as much code as you can - to help us diagnose the problem. Any relevant information should be provided - as well, like whether this is a persistent issue, or if it only occurs - some of the time. - - -## Submitting Pull Requests - -We are always happy to receive code and documentation contributions to the SDK. -Please be aware of the following notes prior to opening a pull request: - -1. The SDK is released under the [Apache license][license]. Any code you submit - will be released under that license. For substantial contributions, we may - ask you to sign a [Contributor License Agreement (CLA)][cla]. - -2. If you would like to implement support for a significant feature that is not - yet available in the SDK, please talk to us beforehand to avoid any - duplication of effort. - -3. Wherever possible, pull requests should contain tests as appropriate. - Bugfixes should contain tests that exercise the corrected behavior (i.e., the - test should fail without the bugfix and pass with it), and new features - should be accompanied by tests exercising the feature. - -4. Pull requests that contain failing tests will not be merged until the test - failures are addressed. Pull requests that cause a significant drop in the - SDK's test coverage percentage are unlikely to be merged until tests have - been added. - -5. The JSON files under the SDK's `models` folder are sourced from outside the SDK. - Such as `models/apis/ec2/2016-11-15/api.json`. We will not accept pull requests - directly on these models. If you discover an issue with the models please - create a [GitHub issue][issues] describing the issue. - -### Testing - -To run the tests locally, running the `make unit` command will `go get` the -SDK's testing dependencies, and run vet, link and unit tests for the SDK. - -``` -make unit -``` - -Standard go testing functionality is supported as well. To test SDK code that -is tagged with `codegen` you'll need to set the build tag in the go test -command. The `make unit` command will do this automatically. - -``` -go test -tags codegen ./private/... -``` - -See the `Makefile` for additional testing tags that can be used in testing. - -To test on multiple platform the SDK includes several DockerFiles under the -`awstesting/sandbox` folder, and associated make recipes to to execute -unit testing within environments configured for specific Go versions. - -``` -make sandbox-test-go18 -``` - -To run all sandbox environments use the following make recipe - -``` -# Optionally update the Go tip that will be used during the batch testing -make update-aws-golang-tip - -# Run all SDK tests for supported Go versions in sandboxes -make sandbox-test -``` - -In addition the sandbox environment include make recipes for interactive modes -so you can run command within the Docker container and context of the SDK. - -``` -make sandbox-go18 -``` - -### Changelog - -You can see all release changes in the `CHANGELOG.md` file at the root of the -repository. The release notes added to this file will contain service client -updates, and major SDK changes. - -[issues]: https://github.com/aws/aws-sdk-go/issues -[pr]: https://github.com/aws/aws-sdk-go/pulls -[license]: http://aws.amazon.com/apache2.0/ -[cla]: http://en.wikipedia.org/wiki/Contributor_License_Agreement -[releasenotes]: https://github.com/aws/aws-sdk-go/releases - diff --git a/vendor/github.com/aws/aws-sdk-go/Gopkg.lock b/vendor/github.com/aws/aws-sdk-go/Gopkg.lock deleted file mode 100644 index 854c94fdf..000000000 --- a/vendor/github.com/aws/aws-sdk-go/Gopkg.lock +++ /dev/null @@ -1,20 +0,0 @@ -# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. - - -[[projects]] - name = "github.com/go-ini/ini" - packages = ["."] - revision = "300e940a926eb277d3901b20bdfcc54928ad3642" - version = "v1.25.4" - -[[projects]] - name = "github.com/jmespath/go-jmespath" - packages = ["."] - revision = "0b12d6b5" - -[solve-meta] - analyzer-name = "dep" - analyzer-version = 1 - inputs-digest = "51a86a867df617990082dec6b868e4efe2fdb2ed0e02a3daa93cd30f962b5085" - solver-name = "gps-cdcl" - solver-version = 1 diff --git a/vendor/github.com/aws/aws-sdk-go/Gopkg.toml b/vendor/github.com/aws/aws-sdk-go/Gopkg.toml deleted file mode 100644 index 664fc5955..000000000 --- a/vendor/github.com/aws/aws-sdk-go/Gopkg.toml +++ /dev/null @@ -1,48 +0,0 @@ - -# Gopkg.toml example -# -# Refer to https://github.com/golang/dep/blob/master/docs/Gopkg.toml.md -# for detailed Gopkg.toml documentation. -# -# required = ["github.com/user/thing/cmd/thing"] -# ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"] -# -# [[constraint]] -# name = "github.com/user/project" -# version = "1.0.0" -# -# [[constraint]] -# name = "github.com/user/project2" -# branch = "dev" -# source = "github.com/myfork/project2" -# -# [[override]] -# name = "github.com/x/y" -# version = "2.4.0" - -ignored = [ - # Testing/Example/Codegen dependencies - "github.com/stretchr/testify", - "github.com/stretchr/testify/assert", - "github.com/stretchr/testify/require", - "github.com/go-sql-driver/mysql", - "github.com/gucumber/gucumber", - "github.com/pkg/errors", - "golang.org/x/net", - "golang.org/x/net/html", - "golang.org/x/net/http2", - "golang.org/x/text", - "golang.org/x/text/html", - "golang.org/x/tools", - "golang.org/x/tools/go/loader", -] - - -[[constraint]] - name = "github.com/go-ini/ini" - version = "1.25.4" - -[[constraint]] - name = "github.com/jmespath/go-jmespath" - revision = "0b12d6b5" - #version = "0.2.2" diff --git a/vendor/github.com/aws/aws-sdk-go/Makefile b/vendor/github.com/aws/aws-sdk-go/Makefile deleted file mode 100644 index 83ccc1e62..000000000 --- a/vendor/github.com/aws/aws-sdk-go/Makefile +++ /dev/null @@ -1,187 +0,0 @@ -LINTIGNOREDOT='awstesting/integration.+should not use dot imports' -LINTIGNOREDOC='service/[^/]+/(api|service|waiters)\.go:.+(comment on exported|should have comment or be unexported)' -LINTIGNORECONST='service/[^/]+/(api|service|waiters)\.go:.+(type|struct field|const|func) ([^ ]+) should be ([^ ]+)' -LINTIGNORESTUTTER='service/[^/]+/(api|service)\.go:.+(and that stutters)' -LINTIGNOREINFLECT='service/[^/]+/(api|errors|service)\.go:.+(method|const) .+ should be ' -LINTIGNOREINFLECTS3UPLOAD='service/s3/s3manager/upload\.go:.+struct field SSEKMSKeyId should be ' -LINTIGNOREDEPS='vendor/.+\.go' -LINTIGNOREPKGCOMMENT='service/[^/]+/doc_custom.go:.+package comment should be of the form' -UNIT_TEST_TAGS="example codegen awsinclude" - -SDK_WITH_VENDOR_PKGS=$(shell go list -tags ${UNIT_TEST_TAGS} ./... | grep -v "/vendor/src") -SDK_ONLY_PKGS=$(shell go list ./... | grep -v "/vendor/") -SDK_UNIT_TEST_ONLY_PKGS=$(shell go list -tags ${UNIT_TEST_TAGS} ./... | grep -v "/vendor/") -SDK_GO_1_4=$(shell go version | grep "go1.4") -SDK_GO_1_5=$(shell go version | grep "go1.5") -SDK_GO_VERSION=$(shell go version | awk '''{print $$3}''' | tr -d '''\n''') - -all: get-deps generate unit - -help: - @echo "Please use \`make ' where is one of" - @echo " api_info to print a list of services and versions" - @echo " docs to build SDK documentation" - @echo " build to go build the SDK" - @echo " unit to run unit tests" - @echo " integration to run integration tests" - @echo " performance to run performance tests" - @echo " verify to verify tests" - @echo " lint to lint the SDK" - @echo " vet to vet the SDK" - @echo " generate to go generate and make services" - @echo " gen-test to generate protocol tests" - @echo " gen-services to generate services" - @echo " get-deps to go get the SDK dependencies" - @echo " get-deps-tests to get the SDK's test dependencies" - @echo " get-deps-verify to get the SDK's verification dependencies" - -generate: gen-test gen-endpoints gen-services - -gen-test: gen-protocol-test - -gen-services: - go generate ./service - -gen-protocol-test: - go generate ./private/protocol/... - -gen-endpoints: - go generate ./models/endpoints/ - -build: - @echo "go build SDK and vendor packages" - @go build ${SDK_ONLY_PKGS} - -unit: get-deps-tests build verify - @echo "go test SDK and vendor packages" - @go test -tags ${UNIT_TEST_TAGS} $(SDK_UNIT_TEST_ONLY_PKGS) - -unit-with-race-cover: get-deps-tests build verify - @echo "go test SDK and vendor packages" - @go test -tags ${UNIT_TEST_TAGS} -race -cpu=1,2,4 $(SDK_UNIT_TEST_ONLY_PKGS) - -integration: get-deps-tests integ-custom smoke-tests performance - -integ-custom: - go test -tags "integration" ./awstesting/integration/customizations/... - -cleanup-integ: - go run -tags "integration" ./awstesting/cmd/bucket_cleanup/main.go "aws-sdk-go-integration" - -smoke-tests: get-deps-tests - gucumber -go-tags "integration" ./awstesting/integration/smoke - -performance: get-deps-tests - AWS_TESTING_LOG_RESULTS=${log-detailed} AWS_TESTING_REGION=$(region) AWS_TESTING_DB_TABLE=$(table) gucumber -go-tags "integration" ./awstesting/performance - -sandbox-tests: sandbox-test-go15 sandbox-test-go15-novendorexp sandbox-test-go16 sandbox-test-go17 sandbox-test-go18 sandbox-test-go19 sandbox-test-gotip - -sandbox-build-go15: - docker build -f ./awstesting/sandbox/Dockerfile.test.go1.5 -t "aws-sdk-go-1.5" . -sandbox-go15: sandbox-build-go15 - docker run -i -t aws-sdk-go-1.5 bash -sandbox-test-go15: sandbox-build-go15 - docker run -t aws-sdk-go-1.5 - -sandbox-build-go15-novendorexp: - docker build -f ./awstesting/sandbox/Dockerfile.test.go1.5-novendorexp -t "aws-sdk-go-1.5-novendorexp" . -sandbox-go15-novendorexp: sandbox-build-go15-novendorexp - docker run -i -t aws-sdk-go-1.5-novendorexp bash -sandbox-test-go15-novendorexp: sandbox-build-go15-novendorexp - docker run -t aws-sdk-go-1.5-novendorexp - -sandbox-build-go16: - docker build -f ./awstesting/sandbox/Dockerfile.test.go1.6 -t "aws-sdk-go-1.6" . -sandbox-go16: sandbox-build-go16 - docker run -i -t aws-sdk-go-1.6 bash -sandbox-test-go16: sandbox-build-go16 - docker run -t aws-sdk-go-1.6 - -sandbox-build-go17: - docker build -f ./awstesting/sandbox/Dockerfile.test.go1.7 -t "aws-sdk-go-1.7" . -sandbox-go17: sandbox-build-go17 - docker run -i -t aws-sdk-go-1.7 bash -sandbox-test-go17: sandbox-build-go17 - docker run -t aws-sdk-go-1.7 - -sandbox-build-go18: - docker build -f ./awstesting/sandbox/Dockerfile.test.go1.8 -t "aws-sdk-go-1.8" . -sandbox-go18: sandbox-build-go18 - docker run -i -t aws-sdk-go-1.8 bash -sandbox-test-go18: sandbox-build-go18 - docker run -t aws-sdk-go-1.8 - -sandbox-build-go19: - docker build -f ./awstesting/sandbox/Dockerfile.test.go1.8 -t "aws-sdk-go-1.9" . -sandbox-go19: sandbox-build-go19 - docker run -i -t aws-sdk-go-1.9 bash -sandbox-test-go19: sandbox-build-go19 - docker run -t aws-sdk-go-1.9 - -sandbox-build-gotip: - @echo "Run make update-aws-golang-tip, if this test fails because missing aws-golang:tip container" - docker build -f ./awstesting/sandbox/Dockerfile.test.gotip -t "aws-sdk-go-tip" . -sandbox-gotip: sandbox-build-gotip - docker run -i -t aws-sdk-go-tip bash -sandbox-test-gotip: sandbox-build-gotip - docker run -t aws-sdk-go-tip - -update-aws-golang-tip: - docker build --no-cache=true -f ./awstesting/sandbox/Dockerfile.golang-tip -t "aws-golang:tip" . - -verify: get-deps-verify lint vet - -lint: - @echo "go lint SDK and vendor packages" - @lint=`if [ \( -z "${SDK_GO_1_4}" \) -a \( -z "${SDK_GO_1_5}" \) ]; then golint ./...; else echo "skipping golint"; fi`; \ - lint=`echo "$$lint" | grep -E -v -e ${LINTIGNOREDOT} -e ${LINTIGNOREDOC} -e ${LINTIGNORECONST} -e ${LINTIGNORESTUTTER} -e ${LINTIGNOREINFLECT} -e ${LINTIGNOREDEPS} -e ${LINTIGNOREINFLECTS3UPLOAD} -e ${LINTIGNOREPKGCOMMENT}`; \ - echo "$$lint"; \ - if [ "$$lint" != "" ] && [ "$$lint" != "skipping golint" ]; then exit 1; fi - -SDK_BASE_FOLDERS=$(shell ls -d */ | grep -v vendor | grep -v awsmigrate) -ifneq (,$(findstring go1.4, ${SDK_GO_VERSION})) - GO_VET_CMD=echo skipping go vet, ${SDK_GO_VERSION} -else ifneq (,$(findstring go1.6, ${SDK_GO_VERSION})) - GO_VET_CMD=go tool vet --all -shadow -example=false -else - GO_VET_CMD=go tool vet --all -shadow -endif - -vet: - ${GO_VET_CMD} ${SDK_BASE_FOLDERS} - -get-deps: get-deps-tests get-deps-verify - @echo "go get SDK dependencies" - @go get -v $(SDK_ONLY_PKGS) - -get-deps-tests: - @echo "go get SDK testing dependencies" - go get github.com/gucumber/gucumber/cmd/gucumber - go get github.com/stretchr/testify - go get github.com/smartystreets/goconvey - go get golang.org/x/net/html - go get golang.org/x/net/http2 - -get-deps-verify: - @echo "go get SDK verification utilities" - @if [ \( -z "${SDK_GO_1_4}" \) -a \( -z "${SDK_GO_1_5}" \) ]; then go get github.com/golang/lint/golint; else echo "skipped getting golint"; fi - -bench: - @echo "go bench SDK packages" - @go test -run NONE -bench . -benchmem -tags 'bench' $(SDK_ONLY_PKGS) - -bench-protocol: - @echo "go bench SDK protocol marshallers" - @go test -run NONE -bench . -benchmem -tags 'bench' ./private/protocol/... - -docs: - @echo "generate SDK docs" - @# This env variable, DOCS, is for internal use - @if [ -z ${AWS_DOC_GEN_TOOL} ]; then\ - rm -rf doc && bundle install && bundle exec yard;\ - else\ - $(AWS_DOC_GEN_TOOL) `pwd`;\ - fi - -api_info: - @go run private/model/cli/api-info/api-info.go diff --git a/vendor/github.com/aws/aws-sdk-go/README.md b/vendor/github.com/aws/aws-sdk-go/README.md deleted file mode 100644 index d8acfdd00..000000000 --- a/vendor/github.com/aws/aws-sdk-go/README.md +++ /dev/null @@ -1,449 +0,0 @@ -[![API Reference](http://img.shields.io/badge/api-reference-blue.svg)](http://docs.aws.amazon.com/sdk-for-go/api) [![Join the chat at https://gitter.im/aws/aws-sdk-go](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/aws/aws-sdk-go?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) [![Build Status](https://img.shields.io/travis/aws/aws-sdk-go.svg)](https://travis-ci.org/aws/aws-sdk-go) [![Apache V2 License](http://img.shields.io/badge/license-Apache%20V2-blue.svg)](https://github.com/aws/aws-sdk-go/blob/master/LICENSE.txt) - -# AWS SDK for Go - -aws-sdk-go is the official AWS SDK for the Go programming language. - -Checkout our [release notes](https://github.com/aws/aws-sdk-go/releases) for information about the latest bug fixes, updates, and features added to the SDK. - -## Installing - -If you are using Go 1.5 with the `GO15VENDOREXPERIMENT=1` vendoring flag, or 1.6 and higher you can use the following command to retrieve the SDK. The SDK's non-testing dependencies will be included and are vendored in the `vendor` folder. - - go get -u github.com/aws/aws-sdk-go - -Otherwise if your Go environment does not have vendoring support enabled, or you do not want to include the vendored SDK's dependencies you can use the following command to retrieve the SDK and its non-testing dependencies using `go get`. - - go get -u github.com/aws/aws-sdk-go/aws/... - go get -u github.com/aws/aws-sdk-go/service/... - -If you're looking to retrieve just the SDK without any dependencies use the following command. - - go get -d github.com/aws/aws-sdk-go/ - -These two processes will still include the `vendor` folder and it should be deleted if its not going to be used by your environment. - - rm -rf $GOPATH/src/github.com/aws/aws-sdk-go/vendor - -## Getting Help - -Please use these community resources for getting help. We use the GitHub issues for tracking bugs and feature requests. - -* Ask a question on [StackOverflow](http://stackoverflow.com/) and tag it with the [`aws-sdk-go`](http://stackoverflow.com/questions/tagged/aws-sdk-go) tag. -* Come join the AWS SDK for Go community chat on [gitter](https://gitter.im/aws/aws-sdk-go). -* Open a support ticket with [AWS Support](http://docs.aws.amazon.com/awssupport/latest/user/getting-started.html). -* If you think you may have found a bug, please open an [issue](https://github.com/aws/aws-sdk-go/issues/new). - -## Opening Issues - -If you encounter a bug with the AWS SDK for Go we would like to hear about it. Search the [existing issues](https://github.com/aws/aws-sdk-go/issues) and see if others are also experiencing the issue before opening a new issue. Please include the version of AWS SDK for Go, Go language, and OS you’re using. Please also include repro case when appropriate. - -The GitHub issues are intended for bug reports and feature requests. For help and questions with using AWS SDK for GO please make use of the resources listed in the [Getting Help](https://github.com/aws/aws-sdk-go#getting-help) section. Keeping the list of open issues lean will help us respond in a timely manner. - -## Reference Documentation - -[`Getting Started Guide`](https://aws.amazon.com/sdk-for-go/) - This document is a general introduction how to configure and make requests with the SDK. If this is your first time using the SDK, this documentation and the API documentation will help you get started. This document focuses on the syntax and behavior of the SDK. The [Service Developer Guide](https://aws.amazon.com/documentation/) will help you get started using specific AWS services. - -[`SDK API Reference Documentation`](https://docs.aws.amazon.com/sdk-for-go/api/) - Use this document to look up all API operation input and output parameters for AWS services supported by the SDK. The API reference also includes documentation of the SDK, and examples how to using the SDK, service client API operations, and API operation require parameters. - -[`Service Developer Guide`](https://aws.amazon.com/documentation/) - Use this documentation to learn how to interface with an AWS service. These are great guides both, if you're getting started with a service, or looking for more information on a service. You should not need this document for coding, though in some cases, services may supply helpful samples that you might want to look out for. - -[`SDK Examples`](https://github.com/aws/aws-sdk-go/tree/master/example) - Included in the SDK's repo are a several hand crafted examples using the SDK features and AWS services. - -## Overview of SDK's Packages - -The SDK is composed of two main components, SDK core, and service clients. -The SDK core packages are all available under the aws package at the root of -the SDK. Each client for a supported AWS service is available within its own -package under the service folder at the root of the SDK. - - * aws - SDK core, provides common shared types such as Config, Logger, - and utilities to make working with API parameters easier. - - * awserr - Provides the error interface that the SDK will use for all - errors that occur in the SDK's processing. This includes service API - response errors as well. The Error type is made up of a code and message. - Cast the SDK's returned error type to awserr.Error and call the Code - method to compare returned error to specific error codes. See the package's - documentation for additional values that can be extracted such as RequestID. - - * credentials - Provides the types and built in credentials providers - the SDK will use to retrieve AWS credentials to make API requests with. - Nested under this folder are also additional credentials providers such as - stscreds for assuming IAM roles, and ec2rolecreds for EC2 Instance roles. - - * endpoints - Provides the AWS Regions and Endpoints metadata for the SDK. - Use this to lookup AWS service endpoint information such as which services - are in a region, and what regions a service is in. Constants are also provided - for all region identifiers, e.g UsWest2RegionID for "us-west-2". - - * session - Provides initial default configuration, and load - configuration from external sources such as environment and shared - credentials file. - - * request - Provides the API request sending, and retry logic for the SDK. - This package also includes utilities for defining your own request - retryer, and configuring how the SDK processes the request. - - * service - Clients for AWS services. All services supported by the SDK are - available under this folder. - -## How to Use the SDK's AWS Service Clients - -The SDK includes the Go types and utilities you can use to make requests to -AWS service APIs. Within the service folder at the root of the SDK you'll find -a package for each AWS service the SDK supports. All service clients follows -a common pattern of creation and usage. - -When creating a client for an AWS service you'll first need to have a Session -value constructed. The Session provides shared configuration that can be shared -between your service clients. When service clients are created you can pass -in additional configuration via the aws.Config type to override configuration -provided by in the Session to create service client instances with custom -configuration. - -Once the service's client is created you can use it to make API requests the -AWS service. These clients are safe to use concurrently. - -## Configuring the SDK - -In the AWS SDK for Go, you can configure settings for service clients, such -as the log level and maximum number of retries. Most settings are optional; -however, for each service client, you must specify a region and your credentials. -The SDK uses these values to send requests to the correct AWS region and sign -requests with the correct credentials. You can specify these values as part -of a session or as environment variables. - -See the SDK's [configuration guide][config_guide] for more information. - -See the [session][session_pkg] package documentation for more information on how to use Session -with the SDK. - -See the [Config][config_typ] type in the [aws][aws_pkg] package for more information on configuration -options. - -[config_guide]: https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/configuring-sdk.html -[session_pkg]: https://docs.aws.amazon.com/sdk-for-go/api/aws/session/ -[config_typ]: https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config -[aws_pkg]: https://docs.aws.amazon.com/sdk-for-go/api/aws/ - -### Configuring Credentials - -When using the SDK you'll generally need your AWS credentials to authenticate -with AWS services. The SDK supports multiple methods of supporting these -credentials. By default the SDK will source credentials automatically from -its default credential chain. See the session package for more information -on this chain, and how to configure it. The common items in the credential -chain are the following: - - * Environment Credentials - Set of environment variables that are useful - when sub processes are created for specific roles. - - * Shared Credentials file (~/.aws/credentials) - This file stores your - credentials based on a profile name and is useful for local development. - - * EC2 Instance Role Credentials - Use EC2 Instance Role to assign credentials - to application running on an EC2 instance. This removes the need to manage - credential files in production. - -Credentials can be configured in code as well by setting the Config's Credentials -value to a custom provider or using one of the providers included with the -SDK to bypass the default credential chain and use a custom one. This is -helpful when you want to instruct the SDK to only use a specific set of -credentials or providers. - -This example creates a credential provider for assuming an IAM role, "myRoleARN" -and configures the S3 service client to use that role for API requests. - -```go - // Initial credentials loaded from SDK's default credential chain. Such as - // the environment, shared credentials (~/.aws/credentials), or EC2 Instance - // Role. These credentials will be used to to make the STS Assume Role API. - sess := session.Must(session.NewSession()) - - // Create the credentials from AssumeRoleProvider to assume the role - // referenced by the "myRoleARN" ARN. - creds := stscreds.NewCredentials(sess, "myRoleArn") - - // Create service client value configured for credentials - // from assumed role. - svc := s3.New(sess, &aws.Config{Credentials: creds}) -``` - -See the [credentials][credentials_pkg] package documentation for more information on credential -providers included with the SDK, and how to customize the SDK's usage of -credentials. - -The SDK has support for the shared configuration file (~/.aws/config). This -support can be enabled by setting the environment variable, "AWS_SDK_LOAD_CONFIG=1", -or enabling the feature in code when creating a Session via the -Option's SharedConfigState parameter. - -```go - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) -``` - -[credentials_pkg]: https://docs.aws.amazon.com/sdk-for-go/api/aws/credentials - -### Configuring AWS Region - -In addition to the credentials you'll need to specify the region the SDK -will use to make AWS API requests to. In the SDK you can specify the region -either with an environment variable, or directly in code when a Session or -service client is created. The last value specified in code wins if the region -is specified multiple ways. - -To set the region via the environment variable set the "AWS_REGION" to the -region you want to the SDK to use. Using this method to set the region will -allow you to run your application in multiple regions without needing additional -code in the application to select the region. - - AWS_REGION=us-west-2 - -The endpoints package includes constants for all regions the SDK knows. The -values are all suffixed with RegionID. These values are helpful, because they -reduce the need to type the region string manually. - -To set the region on a Session use the aws package's Config struct parameter -Region to the AWS region you want the service clients created from the session to -use. This is helpful when you want to create multiple service clients, and -all of the clients make API requests to the same region. - -```go - sess := session.Must(session.NewSession(&aws.Config{ - Region: aws.String(endpoints.UsWest2RegionID), - })) -``` - -See the [endpoints][endpoints_pkg] package for the AWS Regions and Endpoints metadata. - -In addition to setting the region when creating a Session you can also set -the region on a per service client bases. This overrides the region of a -Session. This is helpful when you want to create service clients in specific -regions different from the Session's region. - -```go - svc := s3.New(sess, &aws.Config{ - Region: aws.String(endpoints.UsWest2RegionID), - }) -``` - -See the [Config][config_typ] type in the [aws][aws_pkg] package for more information and additional -options such as setting the Endpoint, and other service client configuration options. - -[endpoints_pkg]: https://docs.aws.amazon.com/sdk-for-go/api/aws/endpoints/ - -## Making API Requests - -Once the client is created you can make an API request to the service. -Each API method takes a input parameter, and returns the service response -and an error. The SDK provides methods for making the API call in multiple ways. - -In this list we'll use the S3 ListObjects API as an example for the different -ways of making API requests. - - * ListObjects - Base API operation that will make the API request to the service. - - * ListObjectsRequest - API methods suffixed with Request will construct the - API request, but not send it. This is also helpful when you want to get a - presigned URL for a request, and share the presigned URL instead of your - application making the request directly. - - * ListObjectsPages - Same as the base API operation, but uses a callback to - automatically handle pagination of the API's response. - - * ListObjectsWithContext - Same as base API operation, but adds support for - the Context pattern. This is helpful for controlling the canceling of in - flight requests. See the Go standard library context package for more - information. This method also takes request package's Option functional - options as the variadic argument for modifying how the request will be - made, or extracting information from the raw HTTP response. - - * ListObjectsPagesWithContext - same as ListObjectsPages, but adds support for - the Context pattern. Similar to ListObjectsWithContext this method also - takes the request package's Option function option types as the variadic - argument. - -In addition to the API operations the SDK also includes several higher level -methods that abstract checking for and waiting for an AWS resource to be in -a desired state. In this list we'll use WaitUntilBucketExists to demonstrate -the different forms of waiters. - - * WaitUntilBucketExists. - Method to make API request to query an AWS service for - a resource's state. Will return successfully when that state is accomplished. - - * WaitUntilBucketExistsWithContext - Same as WaitUntilBucketExists, but adds - support for the Context pattern. In addition these methods take request - package's WaiterOptions to configure the waiter, and how underlying request - will be made by the SDK. - -The API method will document which error codes the service might return for -the operation. These errors will also be available as const strings prefixed -with "ErrCode" in the service client's package. If there are no errors listed -in the API's SDK documentation you'll need to consult the AWS service's API -documentation for the errors that could be returned. - -```go - ctx := context.Background() - - result, err := svc.GetObjectWithContext(ctx, &s3.GetObjectInput{ - Bucket: aws.String("my-bucket"), - Key: aws.String("my-key"), - }) - if err != nil { - // Cast err to awserr.Error to handle specific error codes. - aerr, ok := err.(awserr.Error) - if ok && aerr.Code() == s3.ErrCodeNoSuchKey { - // Specific error code handling - } - return err - } - - // Make sure to close the body when done with it for S3 GetObject APIs or - // will leak connections. - defer result.Body.Close() - - fmt.Println("Object Size:", aws.StringValue(result.ContentLength)) -``` - -### API Request Pagination and Resource Waiters - -Pagination helper methods are suffixed with "Pages", and provide the -functionality needed to round trip API page requests. Pagination methods -take a callback function that will be called for each page of the API's response. - -```go - objects := []string{} - err := svc.ListObjectsPagesWithContext(ctx, &s3.ListObjectsInput{ - Bucket: aws.String(myBucket), - }, func(p *s3.ListObjectsOutput, lastPage bool) bool { - for _, o := range p.Contents { - objects = append(objects, aws.StringValue(o.Key)) - } - return true // continue paging - }) - if err != nil { - panic(fmt.Sprintf("failed to list objects for bucket, %s, %v", myBucket, err)) - } - - fmt.Println("Objects in bucket:", objects) -``` - -Waiter helper methods provide the functionality to wait for an AWS resource -state. These methods abstract the logic needed to to check the state of an -AWS resource, and wait until that resource is in a desired state. The waiter -will block until the resource is in the state that is desired, an error occurs, -or the waiter times out. If a resource times out the error code returned will -be request.WaiterResourceNotReadyErrorCode. - -```go - err := svc.WaitUntilBucketExistsWithContext(ctx, &s3.HeadBucketInput{ - Bucket: aws.String(myBucket), - }) - if err != nil { - aerr, ok := err.(awserr.Error) - if ok && aerr.Code() == request.WaiterResourceNotReadyErrorCode { - fmt.Fprintf(os.Stderr, "timed out while waiting for bucket to exist") - } - panic(fmt.Errorf("failed to wait for bucket to exist, %v", err)) - } - fmt.Println("Bucket", myBucket, "exists") -``` - -## Complete SDK Example - -This example shows a complete working Go file which will upload a file to S3 -and use the Context pattern to implement timeout logic that will cancel the -request if it takes too long. This example highlights how to use sessions, -create a service client, make a request, handle the error, and process the -response. - -```go - package main - - import ( - "context" - "flag" - "fmt" - "os" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - ) - - // Uploads a file to S3 given a bucket and object key. Also takes a duration - // value to terminate the update if it doesn't complete within that time. - // - // The AWS Region needs to be provided in the AWS shared config or on the - // environment variable as `AWS_REGION`. Credentials also must be provided - // Will default to shared config file, but can load from environment if provided. - // - // Usage: - // # Upload myfile.txt to myBucket/myKey. Must complete within 10 minutes or will fail - // go run withContext.go -b mybucket -k myKey -d 10m < myfile.txt - func main() { - var bucket, key string - var timeout time.Duration - - flag.StringVar(&bucket, "b", "", "Bucket name.") - flag.StringVar(&key, "k", "", "Object key name.") - flag.DurationVar(&timeout, "d", 0, "Upload timeout.") - flag.Parse() - - // All clients require a Session. The Session provides the client with - // shared configuration such as region, endpoint, and credentials. A - // Session should be shared where possible to take advantage of - // configuration and credential caching. See the session package for - // more information. - sess := session.Must(session.NewSession()) - - // Create a new instance of the service's client with a Session. - // Optional aws.Config values can also be provided as variadic arguments - // to the New function. This option allows you to provide service - // specific configuration. - svc := s3.New(sess) - - // Create a context with a timeout that will abort the upload if it takes - // more than the passed in timeout. - ctx := context.Background() - var cancelFn func() - if timeout > 0 { - ctx, cancelFn = context.WithTimeout(ctx, timeout) - } - // Ensure the context is canceled to prevent leaking. - // See context package for more information, https://golang.org/pkg/context/ - defer cancelFn() - - // Uploads the object to S3. The Context will interrupt the request if the - // timeout expires. - _, err := svc.PutObjectWithContext(ctx, &s3.PutObjectInput{ - Bucket: aws.String(bucket), - Key: aws.String(key), - Body: os.Stdin, - }) - if err != nil { - if aerr, ok := err.(awserr.Error); ok && aerr.Code() == request.CanceledErrorCode { - // If the SDK can determine the request or retry delay was canceled - // by a context the CanceledErrorCode error code will be returned. - fmt.Fprintf(os.Stderr, "upload canceled due to timeout, %v\n", err) - } else { - fmt.Fprintf(os.Stderr, "failed to upload object, %v\n", err) - } - os.Exit(1) - } - - fmt.Printf("successfully uploaded file to %s/%s\n", bucket, key) - } -``` - -## License - -This SDK is distributed under the -[Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0), -see LICENSE.txt and NOTICE.txt for more information. diff --git a/vendor/github.com/aws/aws-sdk-go/aws/awsutil/copy_test.go b/vendor/github.com/aws/aws-sdk-go/aws/awsutil/copy_test.go deleted file mode 100644 index 007b37be1..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/awsutil/copy_test.go +++ /dev/null @@ -1,353 +0,0 @@ -package awsutil_test - -import ( - "bytes" - "fmt" - "io" - "io/ioutil" - "reflect" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws/awsutil" -) - -func ExampleCopy() { - type Foo struct { - A int - B []*string - } - - // Create the initial value - str1 := "hello" - str2 := "bye bye" - f1 := &Foo{A: 1, B: []*string{&str1, &str2}} - - // Do the copy - var f2 Foo - awsutil.Copy(&f2, f1) - - // Print the result - fmt.Println(awsutil.Prettify(f2)) - - // Output: - // { - // A: 1, - // B: ["hello","bye bye"] - // } -} - -func TestCopy1(t *testing.T) { - type Bar struct { - a *int - B *int - c int - D int - } - type Foo struct { - A int - B []*string - C map[string]*int - D *time.Time - E *Bar - } - - // Create the initial value - str1 := "hello" - str2 := "bye bye" - int1 := 1 - int2 := 2 - intPtr1 := 1 - intPtr2 := 2 - now := time.Now() - f1 := &Foo{ - A: 1, - B: []*string{&str1, &str2}, - C: map[string]*int{ - "A": &int1, - "B": &int2, - }, - D: &now, - E: &Bar{ - &intPtr1, - &intPtr2, - 2, - 3, - }, - } - - // Do the copy - var f2 Foo - awsutil.Copy(&f2, f1) - - // Values are equal - if v1, v2 := f2.A, f1.A; v1 != v2 { - t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) - } - if v1, v2 := f2.B, f1.B; !reflect.DeepEqual(v1, v2) { - t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) - } - if v1, v2 := f2.C, f1.C; !reflect.DeepEqual(v1, v2) { - t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) - } - if v1, v2 := f2.D, f1.D; !v1.Equal(*v2) { - t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) - } - if v1, v2 := f2.E.B, f1.E.B; !reflect.DeepEqual(v1, v2) { - t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) - } - if v1, v2 := f2.E.D, f1.E.D; v1 != v2 { - t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) - } - - // But pointers are not! - str3 := "nothello" - int3 := 57 - f2.A = 100 - *f2.B[0] = str3 - *f2.C["B"] = int3 - *f2.D = time.Now() - f2.E.a = &int3 - *f2.E.B = int3 - f2.E.c = 5 - f2.E.D = 5 - if v1, v2 := f2.A, f1.A; v1 == v2 { - t.Errorf("expected values to be not equivalent, but received %v", v1) - } - if v1, v2 := f2.B, f1.B; reflect.DeepEqual(v1, v2) { - t.Errorf("expected values to be not equivalent, but received %v", v1) - } - if v1, v2 := f2.C, f1.C; reflect.DeepEqual(v1, v2) { - t.Errorf("expected values to be not equivalent, but received %v", v1) - } - if v1, v2 := f2.D, f1.D; v1 == v2 { - t.Errorf("expected values to be not equivalent, but received %v", v1) - } - if v1, v2 := f2.E.a, f1.E.a; v1 == v2 { - t.Errorf("expected values to be not equivalent, but received %v", v1) - } - if v1, v2 := f2.E.B, f1.E.B; v1 == v2 { - t.Errorf("expected values to be not equivalent, but received %v", v1) - } - if v1, v2 := f2.E.c, f1.E.c; v1 == v2 { - t.Errorf("expected values to be not equivalent, but received %v", v1) - } - if v1, v2 := f2.E.D, f1.E.D; v1 == v2 { - t.Errorf("expected values to be not equivalent, but received %v", v1) - } -} - -func TestCopyNestedWithUnexported(t *testing.T) { - type Bar struct { - a int - B int - } - type Foo struct { - A string - B Bar - } - - f1 := &Foo{A: "string", B: Bar{a: 1, B: 2}} - - var f2 Foo - awsutil.Copy(&f2, f1) - - // Values match - if v1, v2 := f2.A, f1.A; v1 != v2 { - t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) - } - if v1, v2 := f2.B, f1.B; v1 == v2 { - t.Errorf("expected values to be not equivalent, but received %v", v1) - } - if v1, v2 := f2.B.a, f1.B.a; v1 == v2 { - t.Errorf("expected values to be not equivalent, but received %v", v1) - } - if v1, v2 := f2.B.B, f2.B.B; v1 != v2 { - t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) - } -} - -func TestCopyIgnoreNilMembers(t *testing.T) { - type Foo struct { - A *string - B []string - C map[string]string - } - - f := &Foo{} - if v1 := f.A; v1 != nil { - t.Errorf("expected nil, but received %v", v1) - } - if v1 := f.B; v1 != nil { - t.Errorf("expected nil, but received %v", v1) - } - if v1 := f.C; v1 != nil { - t.Errorf("expected nil, but received %v", v1) - } - - var f2 Foo - awsutil.Copy(&f2, f) - if v1 := f2.A; v1 != nil { - t.Errorf("expected nil, but received %v", v1) - } - if v1 := f2.B; v1 != nil { - t.Errorf("expected nil, but received %v", v1) - } - if v1 := f2.C; v1 != nil { - t.Errorf("expected nil, but received %v", v1) - } - - fcopy := awsutil.CopyOf(f) - f3 := fcopy.(*Foo) - if v1 := f3.A; v1 != nil { - t.Errorf("expected nil, but received %v", v1) - } - if v1 := f3.B; v1 != nil { - t.Errorf("expected nil, but received %v", v1) - } - if v1 := f3.C; v1 != nil { - t.Errorf("expected nil, but received %v", v1) - } -} - -func TestCopyPrimitive(t *testing.T) { - str := "hello" - var s string - awsutil.Copy(&s, &str) - if v1, v2 := "hello", s; v1 != v2 { - t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) - } -} - -func TestCopyNil(t *testing.T) { - var s string - awsutil.Copy(&s, nil) - if v1, v2 := "", s; v1 != v2 { - t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) - } -} - -func TestCopyReader(t *testing.T) { - var buf io.Reader = bytes.NewReader([]byte("hello world")) - var r io.Reader - awsutil.Copy(&r, buf) - b, err := ioutil.ReadAll(r) - if err != nil { - t.Errorf("expected no error, but received %v", err) - } - if v1, v2 := []byte("hello world"), b; !bytes.Equal(v1, v2) { - t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) - } - - // empty bytes because this is not a deep copy - b, err = ioutil.ReadAll(buf) - if err != nil { - t.Errorf("expected no error, but received %v", err) - } - if v1, v2 := []byte(""), b; !bytes.Equal(v1, v2) { - t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) - } -} - -func TestCopyDifferentStructs(t *testing.T) { - type SrcFoo struct { - A int - B []*string - C map[string]*int - SrcUnique string - SameNameDiffType int - unexportedPtr *int - ExportedPtr *int - } - type DstFoo struct { - A int - B []*string - C map[string]*int - DstUnique int - SameNameDiffType string - unexportedPtr *int - ExportedPtr *int - } - - // Create the initial value - str1 := "hello" - str2 := "bye bye" - int1 := 1 - int2 := 2 - f1 := &SrcFoo{ - A: 1, - B: []*string{&str1, &str2}, - C: map[string]*int{ - "A": &int1, - "B": &int2, - }, - SrcUnique: "unique", - SameNameDiffType: 1, - unexportedPtr: &int1, - ExportedPtr: &int2, - } - - // Do the copy - var f2 DstFoo - awsutil.Copy(&f2, f1) - - // Values are equal - if v1, v2 := f2.A, f1.A; v1 != v2 { - t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) - } - if v1, v2 := f2.B, f1.B; !reflect.DeepEqual(v1, v2) { - t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) - } - if v1, v2 := f2.C, f1.C; !reflect.DeepEqual(v1, v2) { - t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) - } - if v1, v2 := "unique", f1.SrcUnique; v1 != v2 { - t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) - } - if v1, v2 := 1, f1.SameNameDiffType; v1 != v2 { - t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) - } - if v1, v2 := 0, f2.DstUnique; v1 != v2 { - t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) - } - if v1, v2 := "", f2.SameNameDiffType; v1 != v2 { - t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) - } - if v1, v2 := int1, *f1.unexportedPtr; v1 != v2 { - t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) - } - if v1 := f2.unexportedPtr; v1 != nil { - t.Errorf("expected nil, but received %v", v1) - } - if v1, v2 := int2, *f1.ExportedPtr; v1 != v2 { - t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) - } - if v1, v2 := int2, *f2.ExportedPtr; v1 != v2 { - t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) - } -} - -func ExampleCopyOf() { - type Foo struct { - A int - B []*string - } - - // Create the initial value - str1 := "hello" - str2 := "bye bye" - f1 := &Foo{A: 1, B: []*string{&str1, &str2}} - - // Do the copy - v := awsutil.CopyOf(f1) - var f2 *Foo = v.(*Foo) - - // Print the result - fmt.Println(awsutil.Prettify(f2)) - - // Output: - // { - // A: 1, - // B: ["hello","bye bye"] - // } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/awsutil/equal_test.go b/vendor/github.com/aws/aws-sdk-go/aws/awsutil/equal_test.go deleted file mode 100644 index 18d3c5b8e..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/awsutil/equal_test.go +++ /dev/null @@ -1,30 +0,0 @@ -package awsutil_test - -import ( - "testing" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awsutil" -) - -func TestDeepEqual(t *testing.T) { - cases := []struct { - a, b interface{} - equal bool - }{ - {"a", "a", true}, - {"a", "b", false}, - {"a", aws.String(""), false}, - {"a", nil, false}, - {"a", aws.String("a"), true}, - {(*bool)(nil), (*bool)(nil), true}, - {(*bool)(nil), (*string)(nil), false}, - {nil, nil, true}, - } - - for i, c := range cases { - if awsutil.DeepEqual(c.a, c.b) != c.equal { - t.Errorf("%d, a:%v b:%v, %t", i, c.a, c.b, c.equal) - } - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/awsutil/path_value_test.go b/vendor/github.com/aws/aws-sdk-go/aws/awsutil/path_value_test.go deleted file mode 100644 index 58a05d6ce..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/awsutil/path_value_test.go +++ /dev/null @@ -1,182 +0,0 @@ -package awsutil_test - -import ( - "strings" - "testing" - - "github.com/aws/aws-sdk-go/aws/awsutil" -) - -type Struct struct { - A []Struct - z []Struct - B *Struct - D *Struct - C string - E map[string]string -} - -var data = Struct{ - A: []Struct{{C: "value1"}, {C: "value2"}, {C: "value3"}}, - z: []Struct{{C: "value1"}, {C: "value2"}, {C: "value3"}}, - B: &Struct{B: &Struct{C: "terminal"}, D: &Struct{C: "terminal2"}}, - C: "initial", -} -var data2 = Struct{A: []Struct{ - {A: []Struct{{C: "1"}, {C: "1"}, {C: "1"}, {C: "1"}, {C: "1"}}}, - {A: []Struct{{C: "2"}, {C: "2"}, {C: "2"}, {C: "2"}, {C: "2"}}}, -}} - -func TestValueAtPathSuccess(t *testing.T) { - var testCases = []struct { - expect []interface{} - data interface{} - path string - }{ - {[]interface{}{"initial"}, data, "C"}, - {[]interface{}{"value1"}, data, "A[0].C"}, - {[]interface{}{"value2"}, data, "A[1].C"}, - {[]interface{}{"value3"}, data, "A[2].C"}, - {[]interface{}{"value3"}, data, "a[2].c"}, - {[]interface{}{"value3"}, data, "A[-1].C"}, - {[]interface{}{"value1", "value2", "value3"}, data, "A[].C"}, - {[]interface{}{"terminal"}, data, "B . B . C"}, - {[]interface{}{"initial"}, data, "A.D.X || C"}, - {[]interface{}{"initial"}, data, "A[0].B || C"}, - {[]interface{}{ - Struct{A: []Struct{{C: "1"}, {C: "1"}, {C: "1"}, {C: "1"}, {C: "1"}}}, - Struct{A: []Struct{{C: "2"}, {C: "2"}, {C: "2"}, {C: "2"}, {C: "2"}}}, - }, data2, "A"}, - } - for i, c := range testCases { - v, err := awsutil.ValuesAtPath(c.data, c.path) - if err != nil { - t.Errorf("case %v, expected no error, %v", i, c.path) - } - if e, a := c.expect, v; !awsutil.DeepEqual(e, a) { - t.Errorf("case %v, %v", i, c.path) - } - } -} - -func TestValueAtPathFailure(t *testing.T) { - var testCases = []struct { - expect []interface{} - errContains string - data interface{} - path string - }{ - {nil, "", data, "C.x"}, - {nil, "SyntaxError: Invalid token: tDot", data, ".x"}, - {nil, "", data, "X.Y.Z"}, - {nil, "", data, "A[100].C"}, - {nil, "", data, "A[3].C"}, - {nil, "", data, "B.B.C.Z"}, - {nil, "", data, "z[-1].C"}, - {nil, "", nil, "A.B.C"}, - {[]interface{}{}, "", Struct{}, "A"}, - {nil, "", data, "A[0].B.C"}, - {nil, "", data, "D"}, - } - - for i, c := range testCases { - v, err := awsutil.ValuesAtPath(c.data, c.path) - if c.errContains != "" { - if !strings.Contains(err.Error(), c.errContains) { - t.Errorf("case %v, expected error, %v", i, c.path) - } - continue - } else { - if err != nil { - t.Errorf("case %v, expected no error, %v", i, c.path) - } - } - if e, a := c.expect, v; !awsutil.DeepEqual(e, a) { - t.Errorf("case %v, %v", i, c.path) - } - } -} - -func TestSetValueAtPathSuccess(t *testing.T) { - var s Struct - awsutil.SetValueAtPath(&s, "C", "test1") - awsutil.SetValueAtPath(&s, "B.B.C", "test2") - awsutil.SetValueAtPath(&s, "B.D.C", "test3") - if e, a := "test1", s.C; e != a { - t.Errorf("expected %v, but received %v", e, a) - } - if e, a := "test2", s.B.B.C; e != a { - t.Errorf("expected %v, but received %v", e, a) - } - if e, a := "test3", s.B.D.C; e != a { - t.Errorf("expected %v, but received %v", e, a) - } - - awsutil.SetValueAtPath(&s, "B.*.C", "test0") - if e, a := "test0", s.B.B.C; e != a { - t.Errorf("expected %v, but received %v", e, a) - } - if e, a := "test0", s.B.D.C; e != a { - t.Errorf("expected %v, but received %v", e, a) - } - - var s2 Struct - awsutil.SetValueAtPath(&s2, "b.b.c", "test0") - if e, a := "test0", s2.B.B.C; e != a { - t.Errorf("expected %v, but received %v", e, a) - } - awsutil.SetValueAtPath(&s2, "A", []Struct{{}}) - if e, a := []Struct{{}}, s2.A; !awsutil.DeepEqual(e, a) { - t.Errorf("expected %v, but received %v", e, a) - } - - str := "foo" - - s3 := Struct{} - awsutil.SetValueAtPath(&s3, "b.b.c", str) - if e, a := "foo", s3.B.B.C; e != a { - t.Errorf("expected %v, but received %v", e, a) - } - - s3 = Struct{B: &Struct{B: &Struct{C: str}}} - awsutil.SetValueAtPath(&s3, "b.b.c", nil) - if e, a := "", s3.B.B.C; e != a { - t.Errorf("expected %v, but received %v", e, a) - } - - s3 = Struct{} - awsutil.SetValueAtPath(&s3, "b.b.c", nil) - if e, a := "", s3.B.B.C; e != a { - t.Errorf("expected %v, but received %v", e, a) - } - - s3 = Struct{} - awsutil.SetValueAtPath(&s3, "b.b.c", &str) - if e, a := "foo", s3.B.B.C; e != a { - t.Errorf("expected %v, but received %v", e, a) - } - - var s4 struct{ Name *string } - awsutil.SetValueAtPath(&s4, "Name", str) - if e, a := str, *s4.Name; e != a { - t.Errorf("expected %v, but received %v", e, a) - } - - s4 = struct{ Name *string }{} - awsutil.SetValueAtPath(&s4, "Name", nil) - if e, a := (*string)(nil), s4.Name; e != a { - t.Errorf("expected %v, but received %v", e, a) - } - - s4 = struct{ Name *string }{Name: &str} - awsutil.SetValueAtPath(&s4, "Name", nil) - if e, a := (*string)(nil), s4.Name; e != a { - t.Errorf("expected %v, but received %v", e, a) - } - - s4 = struct{ Name *string }{} - awsutil.SetValueAtPath(&s4, "Name", &str) - if e, a := str, *s4.Name; e != a { - t.Errorf("expected %v, but received %v", e, a) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/client/client_test.go b/vendor/github.com/aws/aws-sdk-go/aws/client/client_test.go deleted file mode 100644 index 30d3b9997..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/client/client_test.go +++ /dev/null @@ -1,78 +0,0 @@ -package client - -import ( - "testing" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/client/metadata" - "github.com/aws/aws-sdk-go/aws/request" -) - -func pushBackTestHandler(name string, list *request.HandlerList) *bool { - called := false - (*list).PushBackNamed(request.NamedHandler{ - Name: name, - Fn: func(r *request.Request) { - called = true - }, - }) - - return &called -} - -func pushFrontTestHandler(name string, list *request.HandlerList) *bool { - called := false - (*list).PushFrontNamed(request.NamedHandler{ - Name: name, - Fn: func(r *request.Request) { - called = true - }, - }) - - return &called -} - -func TestNewClient_CopyHandlers(t *testing.T) { - handlers := request.Handlers{} - firstCalled := pushBackTestHandler("first", &handlers.Send) - secondCalled := pushBackTestHandler("second", &handlers.Send) - - var clientHandlerCalled *bool - c := New(aws.Config{}, metadata.ClientInfo{}, handlers, - func(c *Client) { - clientHandlerCalled = pushFrontTestHandler("client handler", &c.Handlers.Send) - }, - ) - - if e, a := 2, handlers.Send.Len(); e != a { - t.Errorf("expect %d original handlers, got %d", e, a) - } - if e, a := 3, c.Handlers.Send.Len(); e != a { - t.Errorf("expect %d client handlers, got %d", e, a) - } - - handlers.Send.Run(nil) - if !*firstCalled { - t.Errorf("expect first handler to of been called") - } - *firstCalled = false - if !*secondCalled { - t.Errorf("expect second handler to of been called") - } - *secondCalled = false - if *clientHandlerCalled { - t.Errorf("expect client handler to not of been called, but was") - } - - c.Handlers.Send.Run(nil) - if !*firstCalled { - t.Errorf("expect client's first handler to of been called") - } - if !*secondCalled { - t.Errorf("expect client's second handler to of been called") - } - if !*clientHandlerCalled { - t.Errorf("expect client's client handler to of been called") - } - -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/client/logger_test.go b/vendor/github.com/aws/aws-sdk-go/aws/client/logger_test.go deleted file mode 100644 index b8d600c9c..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/client/logger_test.go +++ /dev/null @@ -1,57 +0,0 @@ -package client - -import ( - "bytes" - "io" - "testing" -) - -type mockCloser struct { - closed bool -} - -func (closer *mockCloser) Read(b []byte) (int, error) { - return 0, io.EOF -} - -func (closer *mockCloser) Close() error { - closer.closed = true - return nil -} - -func TestTeeReaderCloser(t *testing.T) { - expected := "FOO" - buf := bytes.NewBuffer([]byte(expected)) - lw := bytes.NewBuffer(nil) - c := &mockCloser{} - closer := teeReaderCloser{ - io.TeeReader(buf, lw), - c, - } - - b := make([]byte, len(expected)) - _, err := closer.Read(b) - closer.Close() - - if expected != lw.String() { - t.Errorf("Expected %q, but received %q", expected, lw.String()) - } - - if err != nil { - t.Errorf("Expected 'nil', but received %v", err) - } - - if !c.closed { - t.Error("Expected 'true', but received 'false'") - } -} - -func TestLogWriter(t *testing.T) { - expected := "FOO" - lw := &logWriter{nil, bytes.NewBuffer(nil)} - lw.Write([]byte(expected)) - - if expected != lw.buf.String() { - t.Errorf("Expected %q, but received %q", expected, lw.buf.String()) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/config_test.go b/vendor/github.com/aws/aws-sdk-go/aws/config_test.go deleted file mode 100644 index fe97a31fc..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/config_test.go +++ /dev/null @@ -1,86 +0,0 @@ -package aws - -import ( - "net/http" - "reflect" - "testing" - - "github.com/aws/aws-sdk-go/aws/credentials" -) - -var testCredentials = credentials.NewStaticCredentials("AKID", "SECRET", "SESSION") - -var copyTestConfig = Config{ - Credentials: testCredentials, - Endpoint: String("CopyTestEndpoint"), - Region: String("COPY_TEST_AWS_REGION"), - DisableSSL: Bool(true), - HTTPClient: http.DefaultClient, - LogLevel: LogLevel(LogDebug), - Logger: NewDefaultLogger(), - MaxRetries: Int(3), - DisableParamValidation: Bool(true), - DisableComputeChecksums: Bool(true), - S3ForcePathStyle: Bool(true), -} - -func TestCopy(t *testing.T) { - want := copyTestConfig - got := copyTestConfig.Copy() - if !reflect.DeepEqual(*got, want) { - t.Errorf("Copy() = %+v", got) - t.Errorf(" want %+v", want) - } - - got.Region = String("other") - if got.Region == want.Region { - t.Errorf("Expect setting copy values not not reflect in source") - } -} - -func TestCopyReturnsNewInstance(t *testing.T) { - want := copyTestConfig - got := copyTestConfig.Copy() - if got == &want { - t.Errorf("Copy() = %p; want different instance as source %p", got, &want) - } -} - -var mergeTestZeroValueConfig = Config{} - -var mergeTestConfig = Config{ - Credentials: testCredentials, - Endpoint: String("MergeTestEndpoint"), - Region: String("MERGE_TEST_AWS_REGION"), - DisableSSL: Bool(true), - HTTPClient: http.DefaultClient, - LogLevel: LogLevel(LogDebug), - Logger: NewDefaultLogger(), - MaxRetries: Int(10), - DisableParamValidation: Bool(true), - DisableComputeChecksums: Bool(true), - S3ForcePathStyle: Bool(true), -} - -var mergeTests = []struct { - cfg *Config - in *Config - want *Config -}{ - {&Config{}, nil, &Config{}}, - {&Config{}, &mergeTestZeroValueConfig, &Config{}}, - {&Config{}, &mergeTestConfig, &mergeTestConfig}, -} - -func TestMerge(t *testing.T) { - for i, tt := range mergeTests { - got := tt.cfg.Copy() - got.MergeIn(tt.in) - if !reflect.DeepEqual(got, tt.want) { - t.Errorf("Config %d %+v", i, tt.cfg) - t.Errorf(" Merge(%+v)", tt.in) - t.Errorf(" got %+v", got) - t.Errorf(" want %+v", tt.want) - } - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/context_test.go b/vendor/github.com/aws/aws-sdk-go/aws/context_test.go deleted file mode 100644 index d80a1bb6d..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/context_test.go +++ /dev/null @@ -1,37 +0,0 @@ -package aws_test - -import ( - "fmt" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/awstesting" -) - -func TestSleepWithContext(t *testing.T) { - ctx := &awstesting.FakeContext{DoneCh: make(chan struct{})} - - err := aws.SleepWithContext(ctx, 1*time.Millisecond) - if err != nil { - t.Errorf("expect context to not be canceled, got %v", err) - } -} - -func TestSleepWithContext_Canceled(t *testing.T) { - ctx := &awstesting.FakeContext{DoneCh: make(chan struct{})} - - expectErr := fmt.Errorf("context canceled") - - ctx.Error = expectErr - close(ctx.DoneCh) - - err := aws.SleepWithContext(ctx, 1*time.Millisecond) - if err == nil { - t.Fatalf("expect error, did not get one") - } - - if e, a := expectErr, err; e != a { - t.Errorf("expect %v error, got %v", e, a) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/convert_types_test.go b/vendor/github.com/aws/aws-sdk-go/aws/convert_types_test.go deleted file mode 100644 index 1a9461e1b..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/convert_types_test.go +++ /dev/null @@ -1,641 +0,0 @@ -package aws - -import ( - "reflect" - "testing" - "time" -) - -var testCasesStringSlice = [][]string{ - {"a", "b", "c", "d", "e"}, - {"a", "b", "", "", "e"}, -} - -func TestStringSlice(t *testing.T) { - for idx, in := range testCasesStringSlice { - if in == nil { - continue - } - out := StringSlice(in) - if e, a := len(out), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - for i := range out { - if e, a := in[i], *(out[i]); e != a { - t.Errorf("Unexpected value at idx %d", idx) - } - } - - out2 := StringValueSlice(out) - if e, a := len(out2), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - if e, a := in, out2; !reflect.DeepEqual(e, a) { - t.Errorf("Unexpected value at idx %d", idx) - } - } -} - -var testCasesStringValueSlice = [][]*string{ - {String("a"), String("b"), nil, String("c")}, -} - -func TestStringValueSlice(t *testing.T) { - for idx, in := range testCasesStringValueSlice { - if in == nil { - continue - } - out := StringValueSlice(in) - if e, a := len(out), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - for i := range out { - if in[i] == nil { - if out[i] != "" { - t.Errorf("Unexpected value at idx %d", idx) - } - } else { - if e, a := *(in[i]), out[i]; e != a { - t.Errorf("Unexpected value at idx %d", idx) - } - } - } - - out2 := StringSlice(out) - if e, a := len(out2), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - for i := range out2 { - if in[i] == nil { - if *(out2[i]) != "" { - t.Errorf("Unexpected value at idx %d", idx) - } - } else { - if e, a := *in[i], *out2[i]; e != a { - t.Errorf("Unexpected value at idx %d", idx) - } - } - } - } -} - -var testCasesStringMap = []map[string]string{ - {"a": "1", "b": "2", "c": "3"}, -} - -func TestStringMap(t *testing.T) { - for idx, in := range testCasesStringMap { - if in == nil { - continue - } - out := StringMap(in) - if e, a := len(out), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - for i := range out { - if e, a := in[i], *(out[i]); e != a { - t.Errorf("Unexpected value at idx %d", idx) - } - } - - out2 := StringValueMap(out) - if e, a := len(out2), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - if e, a := in, out2; !reflect.DeepEqual(e, a) { - t.Errorf("Unexpected value at idx %d", idx) - } - } -} - -var testCasesBoolSlice = [][]bool{ - {true, true, false, false}, -} - -func TestBoolSlice(t *testing.T) { - for idx, in := range testCasesBoolSlice { - if in == nil { - continue - } - out := BoolSlice(in) - if e, a := len(out), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - for i := range out { - if e, a := in[i], *(out[i]); e != a { - t.Errorf("Unexpected value at idx %d", idx) - } - } - - out2 := BoolValueSlice(out) - if e, a := len(out2), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - if e, a := in, out2; !reflect.DeepEqual(e, a) { - t.Errorf("Unexpected value at idx %d", idx) - } - } -} - -var testCasesBoolValueSlice = [][]*bool{} - -func TestBoolValueSlice(t *testing.T) { - for idx, in := range testCasesBoolValueSlice { - if in == nil { - continue - } - out := BoolValueSlice(in) - if e, a := len(out), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - for i := range out { - if in[i] == nil { - if out[i] { - t.Errorf("Unexpected value at idx %d", idx) - } - } else { - if e, a := *(in[i]), out[i]; e != a { - t.Errorf("Unexpected value at idx %d", idx) - } - } - } - - out2 := BoolSlice(out) - if e, a := len(out2), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - for i := range out2 { - if in[i] == nil { - if *(out2[i]) { - t.Errorf("Unexpected value at idx %d", idx) - } - } else { - if e, a := in[i], out2[i]; e != a { - t.Errorf("Unexpected value at idx %d", idx) - } - } - } - } -} - -var testCasesBoolMap = []map[string]bool{ - {"a": true, "b": false, "c": true}, -} - -func TestBoolMap(t *testing.T) { - for idx, in := range testCasesBoolMap { - if in == nil { - continue - } - out := BoolMap(in) - if e, a := len(out), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - for i := range out { - if e, a := in[i], *(out[i]); e != a { - t.Errorf("Unexpected value at idx %d", idx) - } - } - - out2 := BoolValueMap(out) - if e, a := len(out2), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - if e, a := in, out2; !reflect.DeepEqual(e, a) { - t.Errorf("Unexpected value at idx %d", idx) - } - } -} - -var testCasesIntSlice = [][]int{ - {1, 2, 3, 4}, -} - -func TestIntSlice(t *testing.T) { - for idx, in := range testCasesIntSlice { - if in == nil { - continue - } - out := IntSlice(in) - if e, a := len(out), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - for i := range out { - if e, a := in[i], *(out[i]); e != a { - t.Errorf("Unexpected value at idx %d", idx) - } - } - - out2 := IntValueSlice(out) - if e, a := len(out2), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - if e, a := in, out2; !reflect.DeepEqual(e, a) { - t.Errorf("Unexpected value at idx %d", idx) - } - } -} - -var testCasesIntValueSlice = [][]*int{} - -func TestIntValueSlice(t *testing.T) { - for idx, in := range testCasesIntValueSlice { - if in == nil { - continue - } - out := IntValueSlice(in) - if e, a := len(out), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - for i := range out { - if in[i] == nil { - if out[i] != 0 { - t.Errorf("Unexpected value at idx %d", idx) - } - } else { - if e, a := *(in[i]), out[i]; e != a { - t.Errorf("Unexpected value at idx %d", idx) - } - } - } - - out2 := IntSlice(out) - if e, a := len(out2), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - for i := range out2 { - if in[i] == nil { - if *(out2[i]) != 0 { - t.Errorf("Unexpected value at idx %d", idx) - } - } else { - if e, a := in[i], out2[i]; e != a { - t.Errorf("Unexpected value at idx %d", idx) - } - } - } - } -} - -var testCasesIntMap = []map[string]int{ - {"a": 3, "b": 2, "c": 1}, -} - -func TestIntMap(t *testing.T) { - for idx, in := range testCasesIntMap { - if in == nil { - continue - } - out := IntMap(in) - if e, a := len(out), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - for i := range out { - if e, a := in[i], *(out[i]); e != a { - t.Errorf("Unexpected value at idx %d", idx) - } - } - - out2 := IntValueMap(out) - if e, a := len(out2), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - if e, a := in, out2; !reflect.DeepEqual(e, a) { - t.Errorf("Unexpected value at idx %d", idx) - } - } -} - -var testCasesInt64Slice = [][]int64{ - {1, 2, 3, 4}, -} - -func TestInt64Slice(t *testing.T) { - for idx, in := range testCasesInt64Slice { - if in == nil { - continue - } - out := Int64Slice(in) - if e, a := len(out), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - for i := range out { - if e, a := in[i], *(out[i]); e != a { - t.Errorf("Unexpected value at idx %d", idx) - } - } - - out2 := Int64ValueSlice(out) - if e, a := len(out2), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - if e, a := in, out2; !reflect.DeepEqual(e, a) { - t.Errorf("Unexpected value at idx %d", idx) - } - } -} - -var testCasesInt64ValueSlice = [][]*int64{} - -func TestInt64ValueSlice(t *testing.T) { - for idx, in := range testCasesInt64ValueSlice { - if in == nil { - continue - } - out := Int64ValueSlice(in) - if e, a := len(out), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - for i := range out { - if in[i] == nil { - if out[i] != 0 { - t.Errorf("Unexpected value at idx %d", idx) - } - } else { - if e, a := *(in[i]), out[i]; e != a { - t.Errorf("Unexpected value at idx %d", idx) - } - } - } - - out2 := Int64Slice(out) - if e, a := len(out2), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - for i := range out2 { - if in[i] == nil { - if *(out2[i]) != 0 { - t.Errorf("Unexpected value at idx %d", idx) - } - } else { - if e, a := in[i], out2[i]; e != a { - t.Errorf("Unexpected value at idx %d", idx) - } - } - } - } -} - -var testCasesInt64Map = []map[string]int64{ - {"a": 3, "b": 2, "c": 1}, -} - -func TestInt64Map(t *testing.T) { - for idx, in := range testCasesInt64Map { - if in == nil { - continue - } - out := Int64Map(in) - if e, a := len(out), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - for i := range out { - if e, a := in[i], *(out[i]); e != a { - t.Errorf("Unexpected value at idx %d", idx) - } - } - - out2 := Int64ValueMap(out) - if e, a := len(out2), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - if e, a := in, out2; !reflect.DeepEqual(e, a) { - t.Errorf("Unexpected value at idx %d", idx) - } - } -} - -var testCasesFloat64Slice = [][]float64{ - {1, 2, 3, 4}, -} - -func TestFloat64Slice(t *testing.T) { - for idx, in := range testCasesFloat64Slice { - if in == nil { - continue - } - out := Float64Slice(in) - if e, a := len(out), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - for i := range out { - if e, a := in[i], *(out[i]); e != a { - t.Errorf("Unexpected value at idx %d", idx) - } - } - - out2 := Float64ValueSlice(out) - if e, a := len(out2), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - if e, a := in, out2; !reflect.DeepEqual(e, a) { - t.Errorf("Unexpected value at idx %d", idx) - } - } -} - -var testCasesFloat64ValueSlice = [][]*float64{} - -func TestFloat64ValueSlice(t *testing.T) { - for idx, in := range testCasesFloat64ValueSlice { - if in == nil { - continue - } - out := Float64ValueSlice(in) - if e, a := len(out), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - for i := range out { - if in[i] == nil { - if out[i] != 0 { - t.Errorf("Unexpected value at idx %d", idx) - } - } else { - if e, a := *(in[i]), out[i]; e != a { - t.Errorf("Unexpected value at idx %d", idx) - } - } - } - - out2 := Float64Slice(out) - if e, a := len(out2), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - for i := range out2 { - if in[i] == nil { - if *(out2[i]) != 0 { - t.Errorf("Unexpected value at idx %d", idx) - } - } else { - if e, a := in[i], out2[i]; e != a { - t.Errorf("Unexpected value at idx %d", idx) - } - } - } - } -} - -var testCasesFloat64Map = []map[string]float64{ - {"a": 3, "b": 2, "c": 1}, -} - -func TestFloat64Map(t *testing.T) { - for idx, in := range testCasesFloat64Map { - if in == nil { - continue - } - out := Float64Map(in) - if e, a := len(out), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - for i := range out { - if e, a := in[i], *(out[i]); e != a { - t.Errorf("Unexpected value at idx %d", idx) - } - } - - out2 := Float64ValueMap(out) - if e, a := len(out2), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - if e, a := in, out2; !reflect.DeepEqual(e, a) { - t.Errorf("Unexpected value at idx %d", idx) - } - } -} - -var testCasesTimeSlice = [][]time.Time{ - {time.Now(), time.Now().AddDate(100, 0, 0)}, -} - -func TestTimeSlice(t *testing.T) { - for idx, in := range testCasesTimeSlice { - if in == nil { - continue - } - out := TimeSlice(in) - if e, a := len(out), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - for i := range out { - if e, a := in[i], *(out[i]); e != a { - t.Errorf("Unexpected value at idx %d", idx) - } - } - - out2 := TimeValueSlice(out) - if e, a := len(out2), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - if e, a := in, out2; !reflect.DeepEqual(e, a) { - t.Errorf("Unexpected value at idx %d", idx) - } - } -} - -var testCasesTimeValueSlice = [][]*time.Time{} - -func TestTimeValueSlice(t *testing.T) { - for idx, in := range testCasesTimeValueSlice { - if in == nil { - continue - } - out := TimeValueSlice(in) - if e, a := len(out), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - for i := range out { - if in[i] == nil { - if !out[i].IsZero() { - t.Errorf("Unexpected value at idx %d", idx) - } - } else { - if e, a := *(in[i]), out[i]; e != a { - t.Errorf("Unexpected value at idx %d", idx) - } - } - } - - out2 := TimeSlice(out) - if e, a := len(out2), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - for i := range out2 { - if in[i] == nil { - if !(*(out2[i])).IsZero() { - t.Errorf("Unexpected value at idx %d", idx) - } - } else { - if e, a := in[i], out2[i]; e != a { - t.Errorf("Unexpected value at idx %d", idx) - } - } - } - } -} - -var testCasesTimeMap = []map[string]time.Time{ - {"a": time.Now().AddDate(-100, 0, 0), "b": time.Now()}, -} - -func TestTimeMap(t *testing.T) { - for idx, in := range testCasesTimeMap { - if in == nil { - continue - } - out := TimeMap(in) - if e, a := len(out), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - for i := range out { - if e, a := in[i], *(out[i]); e != a { - t.Errorf("Unexpected value at idx %d", idx) - } - } - - out2 := TimeValueMap(out) - if e, a := len(out2), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - if e, a := in, out2; !reflect.DeepEqual(e, a) { - t.Errorf("Unexpected value at idx %d", idx) - } - } -} - -type TimeValueTestCase struct { - in int64 - outSecs time.Time - outMillis time.Time -} - -var testCasesTimeValue = []TimeValueTestCase{ - { - in: int64(1501558289000), - outSecs: time.Unix(1501558289, 0), - outMillis: time.Unix(1501558289, 0), - }, - { - in: int64(1501558289001), - outSecs: time.Unix(1501558289, 0), - outMillis: time.Unix(1501558289, 1*1000000), - }, -} - -func TestSecondsTimeValue(t *testing.T) { - for idx, testCase := range testCasesTimeValue { - out := SecondsTimeValue(&testCase.in) - if e, a := testCase.outSecs, out; e != a { - t.Errorf("Unexpected value for time value at %d", idx) - } - } -} - -func TestMillisecondsTimeValue(t *testing.T) { - for idx, testCase := range testCasesTimeValue { - out := MillisecondsTimeValue(&testCase.in) - if e, a := testCase.outMillis, out; e != a { - t.Errorf("Unexpected value for time value at %d", idx) - } - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/handlers_1_8_test.go b/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/handlers_1_8_test.go deleted file mode 100644 index b47afc249..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/handlers_1_8_test.go +++ /dev/null @@ -1,64 +0,0 @@ -// +build go1.8 - -package corehandlers_test - -import ( - "crypto/tls" - "net/http" - "testing" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/awstesting" - "github.com/aws/aws-sdk-go/service/s3" - "golang.org/x/net/http2" -) - -func TestSendHandler_HEADNoBody(t *testing.T) { - TLSBundleCertFile, TLSBundleKeyFile, TLSBundleCAFile, err := awstesting.CreateTLSBundleFiles() - if err != nil { - panic(err) - } - defer awstesting.CleanupTLSBundleFiles(TLSBundleCertFile, TLSBundleKeyFile, TLSBundleCAFile) - - endpoint, err := awstesting.CreateTLSServer(TLSBundleCertFile, TLSBundleKeyFile, nil) - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - - transport := http.DefaultTransport.(*http.Transport) - // test server's certificate is self-signed certificate - transport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true} - http2.ConfigureTransport(transport) - - sess, err := session.NewSessionWithOptions(session.Options{ - Config: aws.Config{ - HTTPClient: &http.Client{}, - Endpoint: aws.String(endpoint), - Region: aws.String("mock-region"), - Credentials: credentials.AnonymousCredentials, - S3ForcePathStyle: aws.Bool(true), - }, - }) - - svc := s3.New(sess) - - req, _ := svc.HeadObjectRequest(&s3.HeadObjectInput{ - Bucket: aws.String("bucketname"), - Key: aws.String("keyname"), - }) - - if e, a := request.NoBody, req.HTTPRequest.Body; e != a { - t.Fatalf("expect %T request body, got %T", e, a) - } - - err = req.Send() - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - if e, a := http.StatusOK, req.HTTPResponse.StatusCode; e != a { - t.Errorf("expect %d status code, got %d", e, a) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/handlers_test.go b/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/handlers_test.go deleted file mode 100644 index 1d715c9f3..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/handlers_test.go +++ /dev/null @@ -1,398 +0,0 @@ -package corehandlers_test - -import ( - "bytes" - "fmt" - "io/ioutil" - "net/http" - "net/http/httptest" - "os" - "strings" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/corehandlers" - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/awstesting" - "github.com/aws/aws-sdk-go/awstesting/unit" - "github.com/aws/aws-sdk-go/service/s3" -) - -func TestValidateEndpointHandler(t *testing.T) { - os.Clearenv() - - svc := awstesting.NewClient(aws.NewConfig().WithRegion("us-west-2")) - svc.Handlers.Clear() - svc.Handlers.Validate.PushBackNamed(corehandlers.ValidateEndpointHandler) - - req := svc.NewRequest(&request.Operation{Name: "Operation"}, nil, nil) - err := req.Build() - - if err != nil { - t.Errorf("expect no error, got %v", err) - } -} - -func TestValidateEndpointHandlerErrorRegion(t *testing.T) { - os.Clearenv() - - svc := awstesting.NewClient() - svc.Handlers.Clear() - svc.Handlers.Validate.PushBackNamed(corehandlers.ValidateEndpointHandler) - - req := svc.NewRequest(&request.Operation{Name: "Operation"}, nil, nil) - err := req.Build() - - if err == nil { - t.Errorf("expect error, got none") - } - if e, a := aws.ErrMissingRegion, err; e != a { - t.Errorf("expect %v to be %v", e, a) - } -} - -type mockCredsProvider struct { - expired bool - retrieveCalled bool -} - -func (m *mockCredsProvider) Retrieve() (credentials.Value, error) { - m.retrieveCalled = true - return credentials.Value{ProviderName: "mockCredsProvider"}, nil -} - -func (m *mockCredsProvider) IsExpired() bool { - return m.expired -} - -func TestAfterRetryRefreshCreds(t *testing.T) { - os.Clearenv() - credProvider := &mockCredsProvider{} - - svc := awstesting.NewClient(&aws.Config{ - Credentials: credentials.NewCredentials(credProvider), - MaxRetries: aws.Int(1), - }) - - svc.Handlers.Clear() - svc.Handlers.ValidateResponse.PushBack(func(r *request.Request) { - r.Error = awserr.New("UnknownError", "", nil) - r.HTTPResponse = &http.Response{StatusCode: 400, Body: ioutil.NopCloser(bytes.NewBuffer([]byte{}))} - }) - svc.Handlers.UnmarshalError.PushBack(func(r *request.Request) { - r.Error = awserr.New("ExpiredTokenException", "", nil) - }) - svc.Handlers.AfterRetry.PushBackNamed(corehandlers.AfterRetryHandler) - - if !svc.Config.Credentials.IsExpired() { - t.Errorf("Expect to start out expired") - } - if credProvider.retrieveCalled { - t.Errorf("expect not called") - } - - req := svc.NewRequest(&request.Operation{Name: "Operation"}, nil, nil) - req.Send() - - if !svc.Config.Credentials.IsExpired() { - t.Errorf("Expect to start out expired") - } - if credProvider.retrieveCalled { - t.Errorf("expect not called") - } - - _, err := svc.Config.Credentials.Get() - if err != nil { - t.Errorf("expect no error, got %v", err) - } - if !credProvider.retrieveCalled { - t.Errorf("expect not called") - } -} - -func TestAfterRetryWithContextCanceled(t *testing.T) { - c := awstesting.NewClient() - - req := c.NewRequest(&request.Operation{Name: "Operation"}, nil, nil) - - ctx := &awstesting.FakeContext{DoneCh: make(chan struct{}, 0)} - req.SetContext(ctx) - - req.Error = fmt.Errorf("some error") - req.Retryable = aws.Bool(true) - req.HTTPResponse = &http.Response{ - StatusCode: 500, - } - - close(ctx.DoneCh) - ctx.Error = fmt.Errorf("context canceled") - - corehandlers.AfterRetryHandler.Fn(req) - - if req.Error == nil { - t.Fatalf("expect error but didn't receive one") - } - - aerr := req.Error.(awserr.Error) - - if e, a := request.CanceledErrorCode, aerr.Code(); e != a { - t.Errorf("expect %q, error code got %q", e, a) - } -} - -func TestAfterRetryWithContext(t *testing.T) { - c := awstesting.NewClient() - - req := c.NewRequest(&request.Operation{Name: "Operation"}, nil, nil) - - ctx := &awstesting.FakeContext{DoneCh: make(chan struct{}, 0)} - req.SetContext(ctx) - - req.Error = fmt.Errorf("some error") - req.Retryable = aws.Bool(true) - req.HTTPResponse = &http.Response{ - StatusCode: 500, - } - - corehandlers.AfterRetryHandler.Fn(req) - - if req.Error != nil { - t.Fatalf("expect no error, got %v", req.Error) - } - if e, a := 1, req.RetryCount; e != a { - t.Errorf("expect retry count to be %d, got %d", e, a) - } -} - -func TestSendWithContextCanceled(t *testing.T) { - c := awstesting.NewClient(&aws.Config{ - SleepDelay: func(dur time.Duration) { - t.Errorf("SleepDelay should not be called") - }, - }) - - req := c.NewRequest(&request.Operation{Name: "Operation"}, nil, nil) - - ctx := &awstesting.FakeContext{DoneCh: make(chan struct{}, 0)} - req.SetContext(ctx) - - req.Error = fmt.Errorf("some error") - req.Retryable = aws.Bool(true) - req.HTTPResponse = &http.Response{ - StatusCode: 500, - } - - close(ctx.DoneCh) - ctx.Error = fmt.Errorf("context canceled") - - corehandlers.SendHandler.Fn(req) - - if req.Error == nil { - t.Fatalf("expect error but didn't receive one") - } - - aerr := req.Error.(awserr.Error) - - if e, a := request.CanceledErrorCode, aerr.Code(); e != a { - t.Errorf("expect %q, error code got %q", e, a) - } -} - -type testSendHandlerTransport struct{} - -func (t *testSendHandlerTransport) RoundTrip(r *http.Request) (*http.Response, error) { - return nil, fmt.Errorf("mock error") -} - -func TestSendHandlerError(t *testing.T) { - svc := awstesting.NewClient(&aws.Config{ - HTTPClient: &http.Client{ - Transport: &testSendHandlerTransport{}, - }, - }) - svc.Handlers.Clear() - svc.Handlers.Send.PushBackNamed(corehandlers.SendHandler) - r := svc.NewRequest(&request.Operation{Name: "Operation"}, nil, nil) - - r.Send() - - if r.Error == nil { - t.Errorf("expect error, got none") - } - if r.HTTPResponse == nil { - t.Errorf("expect response, got none") - } -} - -func TestSendWithoutFollowRedirects(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - switch r.URL.Path { - case "/original": - w.Header().Set("Location", "/redirected") - w.WriteHeader(301) - case "/redirected": - t.Fatalf("expect not to redirect, but was") - } - })) - - svc := awstesting.NewClient(&aws.Config{ - DisableSSL: aws.Bool(true), - Endpoint: aws.String(server.URL), - }) - svc.Handlers.Clear() - svc.Handlers.Send.PushBackNamed(corehandlers.SendHandler) - - r := svc.NewRequest(&request.Operation{ - Name: "Operation", - HTTPPath: "/original", - }, nil, nil) - r.DisableFollowRedirects = true - - err := r.Send() - if err != nil { - t.Errorf("expect no error, got %v", err) - } - if e, a := 301, r.HTTPResponse.StatusCode; e != a { - t.Errorf("expect %d status code, got %d", e, a) - } -} - -func TestValidateReqSigHandler(t *testing.T) { - cases := []struct { - Req *request.Request - Resign bool - }{ - { - Req: &request.Request{ - Config: aws.Config{Credentials: credentials.AnonymousCredentials}, - Time: time.Now().Add(-15 * time.Minute), - }, - Resign: false, - }, - { - Req: &request.Request{ - Time: time.Now().Add(-15 * time.Minute), - }, - Resign: true, - }, - { - Req: &request.Request{ - Time: time.Now().Add(-1 * time.Minute), - }, - Resign: false, - }, - } - - for i, c := range cases { - resigned := false - c.Req.Handlers.Sign.PushBack(func(r *request.Request) { - resigned = true - }) - - corehandlers.ValidateReqSigHandler.Fn(c.Req) - - if c.Req.Error != nil { - t.Errorf("expect no error, got %v", c.Req.Error) - } - if e, a := c.Resign, resigned; e != a { - t.Errorf("%d, expect %v to be %v", i, e, a) - } - } -} - -func setupContentLengthTestServer(t *testing.T, hasContentLength bool, contentLength int64) *httptest.Server { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - _, ok := r.Header["Content-Length"] - if e, a := hasContentLength, ok; e != a { - t.Errorf("expect %v to be %v", e, a) - } - if hasContentLength { - if e, a := contentLength, r.ContentLength; e != a { - t.Errorf("expect %v to be %v", e, a) - } - } - - b, err := ioutil.ReadAll(r.Body) - if err != nil { - t.Errorf("expect no error, got %v", err) - } - r.Body.Close() - - authHeader := r.Header.Get("Authorization") - if hasContentLength { - if e, a := "content-length", authHeader; !strings.Contains(a, e) { - t.Errorf("expect %v to be in %v", e, a) - } - } else { - if e, a := "content-length", authHeader; strings.Contains(a, e) { - t.Errorf("expect %v to not be in %v", e, a) - } - } - - if e, a := contentLength, int64(len(b)); e != a { - t.Errorf("expect %v to be %v", e, a) - } - })) - - return server -} - -func TestBuildContentLength_ZeroBody(t *testing.T) { - server := setupContentLengthTestServer(t, false, 0) - - svc := s3.New(unit.Session, &aws.Config{ - Endpoint: aws.String(server.URL), - S3ForcePathStyle: aws.Bool(true), - DisableSSL: aws.Bool(true), - }) - _, err := svc.GetObject(&s3.GetObjectInput{ - Bucket: aws.String("bucketname"), - Key: aws.String("keyname"), - }) - - if err != nil { - t.Errorf("expect no error, got %v", err) - } -} - -func TestBuildContentLength_NegativeBody(t *testing.T) { - server := setupContentLengthTestServer(t, false, 0) - - svc := s3.New(unit.Session, &aws.Config{ - Endpoint: aws.String(server.URL), - S3ForcePathStyle: aws.Bool(true), - DisableSSL: aws.Bool(true), - }) - req, _ := svc.GetObjectRequest(&s3.GetObjectInput{ - Bucket: aws.String("bucketname"), - Key: aws.String("keyname"), - }) - - req.HTTPRequest.Header.Set("Content-Length", "-1") - - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } -} - -func TestBuildContentLength_WithBody(t *testing.T) { - server := setupContentLengthTestServer(t, true, 1024) - - svc := s3.New(unit.Session, &aws.Config{ - Endpoint: aws.String(server.URL), - S3ForcePathStyle: aws.Bool(true), - DisableSSL: aws.Bool(true), - }) - _, err := svc.PutObject(&s3.PutObjectInput{ - Bucket: aws.String("bucketname"), - Key: aws.String("keyname"), - Body: bytes.NewReader(make([]byte, 1024)), - }) - - if err != nil { - t.Errorf("expect no error, got %v", err) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/param_validator_test.go b/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/param_validator_test.go deleted file mode 100644 index e1d8a08fd..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/param_validator_test.go +++ /dev/null @@ -1,286 +0,0 @@ -package corehandlers_test - -import ( - "fmt" - "testing" - "reflect" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/client" - "github.com/aws/aws-sdk-go/aws/client/metadata" - "github.com/aws/aws-sdk-go/aws/corehandlers" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/awstesting/unit" - "github.com/aws/aws-sdk-go/service/kinesis" -) - -var testSvc = func() *client.Client { - s := &client.Client{ - Config: aws.Config{}, - ClientInfo: metadata.ClientInfo{ - ServiceName: "mock-service", - APIVersion: "2015-01-01", - }, - } - return s -}() - -type StructShape struct { - _ struct{} `type:"structure"` - - RequiredList []*ConditionalStructShape `required:"true"` - RequiredMap map[string]*ConditionalStructShape `required:"true"` - RequiredBool *bool `required:"true"` - OptionalStruct *ConditionalStructShape - - hiddenParameter *string -} - -func (s *StructShape) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "StructShape"} - if s.RequiredList == nil { - invalidParams.Add(request.NewErrParamRequired("RequiredList")) - } - if s.RequiredMap == nil { - invalidParams.Add(request.NewErrParamRequired("RequiredMap")) - } - if s.RequiredBool == nil { - invalidParams.Add(request.NewErrParamRequired("RequiredBool")) - } - if s.RequiredList != nil { - for i, v := range s.RequiredList { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "RequiredList", i), err.(request.ErrInvalidParams)) - } - } - } - if s.RequiredMap != nil { - for i, v := range s.RequiredMap { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "RequiredMap", i), err.(request.ErrInvalidParams)) - } - } - } - if s.OptionalStruct != nil { - if err := s.OptionalStruct.Validate(); err != nil { - invalidParams.AddNested("OptionalStruct", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -type ConditionalStructShape struct { - _ struct{} `type:"structure"` - - Name *string `required:"true"` -} - -func (s *ConditionalStructShape) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ConditionalStructShape"} - if s.Name == nil { - invalidParams.Add(request.NewErrParamRequired("Name")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -func TestNoErrors(t *testing.T) { - input := &StructShape{ - RequiredList: []*ConditionalStructShape{}, - RequiredMap: map[string]*ConditionalStructShape{ - "key1": {Name: aws.String("Name")}, - "key2": {Name: aws.String("Name")}, - }, - RequiredBool: aws.Bool(true), - OptionalStruct: &ConditionalStructShape{Name: aws.String("Name")}, - } - - req := testSvc.NewRequest(&request.Operation{}, input, nil) - corehandlers.ValidateParametersHandler.Fn(req) - if req.Error != nil { - t.Fatalf("expect no error, got %v", req.Error) - } -} - -func TestMissingRequiredParameters(t *testing.T) { - input := &StructShape{} - req := testSvc.NewRequest(&request.Operation{}, input, nil) - corehandlers.ValidateParametersHandler.Fn(req) - - if req.Error == nil { - t.Fatalf("expect error") - } - if e, a := "InvalidParameter", req.Error.(awserr.Error).Code(); e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "3 validation error(s) found.", req.Error.(awserr.Error).Message(); e != a { - t.Errorf("expect %v, got %v", e, a) - } - - errs := req.Error.(awserr.BatchedErrors).OrigErrs() - if e, a := 3, len(errs); e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "ParamRequiredError: missing required field, StructShape.RequiredList.", errs[0].Error(); e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "ParamRequiredError: missing required field, StructShape.RequiredMap.", errs[1].Error(); e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "ParamRequiredError: missing required field, StructShape.RequiredBool.", errs[2].Error(); e != a { - t.Errorf("expect %v, got %v", e, a) - } - - if e, a := "InvalidParameter: 3 validation error(s) found.\n- missing required field, StructShape.RequiredList.\n- missing required field, StructShape.RequiredMap.\n- missing required field, StructShape.RequiredBool.\n", req.Error.Error(); e != a { - t.Errorf("expect %v, got %v", e, a) - } -} - -func TestNestedMissingRequiredParameters(t *testing.T) { - input := &StructShape{ - RequiredList: []*ConditionalStructShape{{}}, - RequiredMap: map[string]*ConditionalStructShape{ - "key1": {Name: aws.String("Name")}, - "key2": {}, - }, - RequiredBool: aws.Bool(true), - OptionalStruct: &ConditionalStructShape{}, - } - - req := testSvc.NewRequest(&request.Operation{}, input, nil) - corehandlers.ValidateParametersHandler.Fn(req) - - if req.Error == nil { - t.Fatalf("expect error") - } - if e, a := "InvalidParameter", req.Error.(awserr.Error).Code(); e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "3 validation error(s) found.", req.Error.(awserr.Error).Message(); e != a { - t.Errorf("expect %v, got %v", e, a) - } - - errs := req.Error.(awserr.BatchedErrors).OrigErrs() - if e, a := 3, len(errs); e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "ParamRequiredError: missing required field, StructShape.RequiredList[0].Name.", errs[0].Error(); e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "ParamRequiredError: missing required field, StructShape.RequiredMap[key2].Name.", errs[1].Error(); e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "ParamRequiredError: missing required field, StructShape.OptionalStruct.Name.", errs[2].Error(); e != a { - t.Errorf("expect %v, got %v", e, a) - } -} - -type testInput struct { - StringField *string `min:"5"` - ListField []string `min:"3"` - MapField map[string]string `min:"4"` -} - -func (s testInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "testInput"} - if s.StringField != nil && len(*s.StringField) < 5 { - invalidParams.Add(request.NewErrParamMinLen("StringField", 5)) - } - if s.ListField != nil && len(s.ListField) < 3 { - invalidParams.Add(request.NewErrParamMinLen("ListField", 3)) - } - if s.MapField != nil && len(s.MapField) < 4 { - invalidParams.Add(request.NewErrParamMinLen("MapField", 4)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -var testsFieldMin = []struct { - err awserr.Error - in testInput -}{ - { - err: func() awserr.Error { - invalidParams := request.ErrInvalidParams{Context: "testInput"} - invalidParams.Add(request.NewErrParamMinLen("StringField", 5)) - return invalidParams - }(), - in: testInput{StringField: aws.String("abcd")}, - }, - { - err: func() awserr.Error { - invalidParams := request.ErrInvalidParams{Context: "testInput"} - invalidParams.Add(request.NewErrParamMinLen("StringField", 5)) - invalidParams.Add(request.NewErrParamMinLen("ListField", 3)) - return invalidParams - }(), - in: testInput{StringField: aws.String("abcd"), ListField: []string{"a", "b"}}, - }, - { - err: func() awserr.Error { - invalidParams := request.ErrInvalidParams{Context: "testInput"} - invalidParams.Add(request.NewErrParamMinLen("StringField", 5)) - invalidParams.Add(request.NewErrParamMinLen("ListField", 3)) - invalidParams.Add(request.NewErrParamMinLen("MapField", 4)) - return invalidParams - }(), - in: testInput{StringField: aws.String("abcd"), ListField: []string{"a", "b"}, MapField: map[string]string{"a": "a", "b": "b"}}, - }, - { - err: nil, - in: testInput{StringField: aws.String("abcde"), - ListField: []string{"a", "b", "c"}, MapField: map[string]string{"a": "a", "b": "b", "c": "c", "d": "d"}}, - }, -} - -func TestValidateFieldMinParameter(t *testing.T) { - for i, c := range testsFieldMin { - req := testSvc.NewRequest(&request.Operation{}, &c.in, nil) - corehandlers.ValidateParametersHandler.Fn(req) - - if e, a := c.err, req.Error; !reflect.DeepEqual(e,a) { - t.Errorf("%d, expect %v, got %v", i, e, a) - } - } -} - -func BenchmarkValidateAny(b *testing.B) { - input := &kinesis.PutRecordsInput{ - StreamName: aws.String("stream"), - } - for i := 0; i < 100; i++ { - record := &kinesis.PutRecordsRequestEntry{ - Data: make([]byte, 10000), - PartitionKey: aws.String("partition"), - } - input.Records = append(input.Records, record) - } - - req, _ := kinesis.New(unit.Session).PutRecordsRequest(input) - - b.ResetTimer() - for i := 0; i < b.N; i++ { - corehandlers.ValidateParametersHandler.Fn(req) - if err := req.Error; err != nil { - b.Fatalf("validation failed: %v", err) - } - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/chain_provider_test.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/chain_provider_test.go deleted file mode 100644 index 3b393a2ed..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/chain_provider_test.go +++ /dev/null @@ -1,154 +0,0 @@ -package credentials - -import ( - "testing" - - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/stretchr/testify/assert" -) - -type secondStubProvider struct { - creds Value - expired bool - err error -} - -func (s *secondStubProvider) Retrieve() (Value, error) { - s.expired = false - s.creds.ProviderName = "secondStubProvider" - return s.creds, s.err -} -func (s *secondStubProvider) IsExpired() bool { - return s.expired -} - -func TestChainProviderWithNames(t *testing.T) { - p := &ChainProvider{ - Providers: []Provider{ - &stubProvider{err: awserr.New("FirstError", "first provider error", nil)}, - &stubProvider{err: awserr.New("SecondError", "second provider error", nil)}, - &secondStubProvider{ - creds: Value{ - AccessKeyID: "AKIF", - SecretAccessKey: "NOSECRET", - SessionToken: "", - }, - }, - &stubProvider{ - creds: Value{ - AccessKeyID: "AKID", - SecretAccessKey: "SECRET", - SessionToken: "", - }, - }, - }, - } - - creds, err := p.Retrieve() - assert.Nil(t, err, "Expect no error") - assert.Equal(t, "secondStubProvider", creds.ProviderName, "Expect provider name to match") - - // Also check credentials - assert.Equal(t, "AKIF", creds.AccessKeyID, "Expect access key ID to match") - assert.Equal(t, "NOSECRET", creds.SecretAccessKey, "Expect secret access key to match") - assert.Empty(t, creds.SessionToken, "Expect session token to be empty") - -} - -func TestChainProviderGet(t *testing.T) { - p := &ChainProvider{ - Providers: []Provider{ - &stubProvider{err: awserr.New("FirstError", "first provider error", nil)}, - &stubProvider{err: awserr.New("SecondError", "second provider error", nil)}, - &stubProvider{ - creds: Value{ - AccessKeyID: "AKID", - SecretAccessKey: "SECRET", - SessionToken: "", - }, - }, - }, - } - - creds, err := p.Retrieve() - assert.Nil(t, err, "Expect no error") - assert.Equal(t, "AKID", creds.AccessKeyID, "Expect access key ID to match") - assert.Equal(t, "SECRET", creds.SecretAccessKey, "Expect secret access key to match") - assert.Empty(t, creds.SessionToken, "Expect session token to be empty") -} - -func TestChainProviderIsExpired(t *testing.T) { - stubProvider := &stubProvider{expired: true} - p := &ChainProvider{ - Providers: []Provider{ - stubProvider, - }, - } - - assert.True(t, p.IsExpired(), "Expect expired to be true before any Retrieve") - _, err := p.Retrieve() - assert.Nil(t, err, "Expect no error") - assert.False(t, p.IsExpired(), "Expect not expired after retrieve") - - stubProvider.expired = true - assert.True(t, p.IsExpired(), "Expect return of expired provider") - - _, err = p.Retrieve() - assert.False(t, p.IsExpired(), "Expect not expired after retrieve") -} - -func TestChainProviderWithNoProvider(t *testing.T) { - p := &ChainProvider{ - Providers: []Provider{}, - } - - assert.True(t, p.IsExpired(), "Expect expired with no providers") - _, err := p.Retrieve() - assert.Equal(t, - ErrNoValidProvidersFoundInChain, - err, - "Expect no providers error returned") -} - -func TestChainProviderWithNoValidProvider(t *testing.T) { - errs := []error{ - awserr.New("FirstError", "first provider error", nil), - awserr.New("SecondError", "second provider error", nil), - } - p := &ChainProvider{ - Providers: []Provider{ - &stubProvider{err: errs[0]}, - &stubProvider{err: errs[1]}, - }, - } - - assert.True(t, p.IsExpired(), "Expect expired with no providers") - _, err := p.Retrieve() - - assert.Equal(t, - ErrNoValidProvidersFoundInChain, - err, - "Expect no providers error returned") -} - -func TestChainProviderWithNoValidProviderWithVerboseEnabled(t *testing.T) { - errs := []error{ - awserr.New("FirstError", "first provider error", nil), - awserr.New("SecondError", "second provider error", nil), - } - p := &ChainProvider{ - VerboseErrors: true, - Providers: []Provider{ - &stubProvider{err: errs[0]}, - &stubProvider{err: errs[1]}, - }, - } - - assert.True(t, p.IsExpired(), "Expect expired with no providers") - _, err := p.Retrieve() - - assert.Equal(t, - awserr.NewBatchError("NoCredentialProviders", "no valid providers in chain", errs), - err, - "Expect no providers error returned") -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/credentials_test.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/credentials_test.go deleted file mode 100644 index 7b79ba985..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/credentials_test.go +++ /dev/null @@ -1,73 +0,0 @@ -package credentials - -import ( - "testing" - - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/stretchr/testify/assert" -) - -type stubProvider struct { - creds Value - expired bool - err error -} - -func (s *stubProvider) Retrieve() (Value, error) { - s.expired = false - s.creds.ProviderName = "stubProvider" - return s.creds, s.err -} -func (s *stubProvider) IsExpired() bool { - return s.expired -} - -func TestCredentialsGet(t *testing.T) { - c := NewCredentials(&stubProvider{ - creds: Value{ - AccessKeyID: "AKID", - SecretAccessKey: "SECRET", - SessionToken: "", - }, - expired: true, - }) - - creds, err := c.Get() - assert.Nil(t, err, "Expected no error") - assert.Equal(t, "AKID", creds.AccessKeyID, "Expect access key ID to match") - assert.Equal(t, "SECRET", creds.SecretAccessKey, "Expect secret access key to match") - assert.Empty(t, creds.SessionToken, "Expect session token to be empty") -} - -func TestCredentialsGetWithError(t *testing.T) { - c := NewCredentials(&stubProvider{err: awserr.New("provider error", "", nil), expired: true}) - - _, err := c.Get() - assert.Equal(t, "provider error", err.(awserr.Error).Code(), "Expected provider error") -} - -func TestCredentialsExpire(t *testing.T) { - stub := &stubProvider{} - c := NewCredentials(stub) - - stub.expired = false - assert.True(t, c.IsExpired(), "Expected to start out expired") - c.Expire() - assert.True(t, c.IsExpired(), "Expected to be expired") - - c.forceRefresh = false - assert.False(t, c.IsExpired(), "Expected not to be expired") - - stub.expired = true - assert.True(t, c.IsExpired(), "Expected to be expired") -} - -func TestCredentialsGetWithProviderName(t *testing.T) { - stub := &stubProvider{} - - c := NewCredentials(stub) - - creds, err := c.Get() - assert.Nil(t, err, "Expected no error") - assert.Equal(t, creds.ProviderName, "stubProvider", "Expected provider name to match") -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds/ec2_role_provider_test.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds/ec2_role_provider_test.go deleted file mode 100644 index cccd4bffe..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds/ec2_role_provider_test.go +++ /dev/null @@ -1,159 +0,0 @@ -package ec2rolecreds_test - -import ( - "fmt" - "net/http" - "net/http/httptest" - "testing" - "time" - - "github.com/stretchr/testify/assert" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds" - "github.com/aws/aws-sdk-go/aws/ec2metadata" - "github.com/aws/aws-sdk-go/awstesting/unit" -) - -const credsRespTmpl = `{ - "Code": "Success", - "Type": "AWS-HMAC", - "AccessKeyId" : "accessKey", - "SecretAccessKey" : "secret", - "Token" : "token", - "Expiration" : "%s", - "LastUpdated" : "2009-11-23T0:00:00Z" -}` - -const credsFailRespTmpl = `{ - "Code": "ErrorCode", - "Message": "ErrorMsg", - "LastUpdated": "2009-11-23T0:00:00Z" -}` - -func initTestServer(expireOn string, failAssume bool) *httptest.Server { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.URL.Path == "/latest/meta-data/iam/security-credentials" { - fmt.Fprintln(w, "RoleName") - } else if r.URL.Path == "/latest/meta-data/iam/security-credentials/RoleName" { - if failAssume { - fmt.Fprintf(w, credsFailRespTmpl) - } else { - fmt.Fprintf(w, credsRespTmpl, expireOn) - } - } else { - http.Error(w, "bad request", http.StatusBadRequest) - } - })) - - return server -} - -func TestEC2RoleProvider(t *testing.T) { - server := initTestServer("2014-12-16T01:51:37Z", false) - defer server.Close() - - p := &ec2rolecreds.EC2RoleProvider{ - Client: ec2metadata.New(unit.Session, &aws.Config{Endpoint: aws.String(server.URL + "/latest")}), - } - - creds, err := p.Retrieve() - assert.Nil(t, err, "Expect no error, %v", err) - - assert.Equal(t, "accessKey", creds.AccessKeyID, "Expect access key ID to match") - assert.Equal(t, "secret", creds.SecretAccessKey, "Expect secret access key to match") - assert.Equal(t, "token", creds.SessionToken, "Expect session token to match") -} - -func TestEC2RoleProviderFailAssume(t *testing.T) { - server := initTestServer("2014-12-16T01:51:37Z", true) - defer server.Close() - - p := &ec2rolecreds.EC2RoleProvider{ - Client: ec2metadata.New(unit.Session, &aws.Config{Endpoint: aws.String(server.URL + "/latest")}), - } - - creds, err := p.Retrieve() - assert.Error(t, err, "Expect error") - - e := err.(awserr.Error) - assert.Equal(t, "ErrorCode", e.Code()) - assert.Equal(t, "ErrorMsg", e.Message()) - assert.Nil(t, e.OrigErr()) - - assert.Equal(t, "", creds.AccessKeyID, "Expect access key ID to match") - assert.Equal(t, "", creds.SecretAccessKey, "Expect secret access key to match") - assert.Equal(t, "", creds.SessionToken, "Expect session token to match") -} - -func TestEC2RoleProviderIsExpired(t *testing.T) { - server := initTestServer("2014-12-16T01:51:37Z", false) - defer server.Close() - - p := &ec2rolecreds.EC2RoleProvider{ - Client: ec2metadata.New(unit.Session, &aws.Config{Endpoint: aws.String(server.URL + "/latest")}), - } - p.CurrentTime = func() time.Time { - return time.Date(2014, 12, 15, 21, 26, 0, 0, time.UTC) - } - - assert.True(t, p.IsExpired(), "Expect creds to be expired before retrieve.") - - _, err := p.Retrieve() - assert.Nil(t, err, "Expect no error, %v", err) - - assert.False(t, p.IsExpired(), "Expect creds to not be expired after retrieve.") - - p.CurrentTime = func() time.Time { - return time.Date(3014, 12, 15, 21, 26, 0, 0, time.UTC) - } - - assert.True(t, p.IsExpired(), "Expect creds to be expired.") -} - -func TestEC2RoleProviderExpiryWindowIsExpired(t *testing.T) { - server := initTestServer("2014-12-16T01:51:37Z", false) - defer server.Close() - - p := &ec2rolecreds.EC2RoleProvider{ - Client: ec2metadata.New(unit.Session, &aws.Config{Endpoint: aws.String(server.URL + "/latest")}), - ExpiryWindow: time.Hour * 1, - } - p.CurrentTime = func() time.Time { - return time.Date(2014, 12, 15, 0, 51, 37, 0, time.UTC) - } - - assert.True(t, p.IsExpired(), "Expect creds to be expired before retrieve.") - - _, err := p.Retrieve() - assert.Nil(t, err, "Expect no error, %v", err) - - assert.False(t, p.IsExpired(), "Expect creds to not be expired after retrieve.") - - p.CurrentTime = func() time.Time { - return time.Date(2014, 12, 16, 0, 55, 37, 0, time.UTC) - } - - assert.True(t, p.IsExpired(), "Expect creds to be expired.") -} - -func BenchmarkEC3RoleProvider(b *testing.B) { - server := initTestServer("2014-12-16T01:51:37Z", false) - defer server.Close() - - p := &ec2rolecreds.EC2RoleProvider{ - Client: ec2metadata.New(unit.Session, &aws.Config{Endpoint: aws.String(server.URL + "/latest")}), - } - _, err := p.Retrieve() - if err != nil { - b.Fatal(err) - } - - b.ResetTimer() - for i := 0; i < b.N; i++ { - if _, err := p.Retrieve(); err != nil { - b.Fatal(err) - } - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/endpointcreds/provider_test.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/endpointcreds/provider_test.go deleted file mode 100644 index ad057a355..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/endpointcreds/provider_test.go +++ /dev/null @@ -1,111 +0,0 @@ -package endpointcreds_test - -import ( - "encoding/json" - "fmt" - "net/http" - "net/http/httptest" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/credentials/endpointcreds" - "github.com/aws/aws-sdk-go/awstesting/unit" - "github.com/stretchr/testify/assert" -) - -func TestRetrieveRefreshableCredentials(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "/path/to/endpoint", r.URL.Path) - assert.Equal(t, "application/json", r.Header.Get("Accept")) - assert.Equal(t, "else", r.URL.Query().Get("something")) - - encoder := json.NewEncoder(w) - err := encoder.Encode(map[string]interface{}{ - "AccessKeyID": "AKID", - "SecretAccessKey": "SECRET", - "Token": "TOKEN", - "Expiration": time.Now().Add(1 * time.Hour), - }) - - if err != nil { - fmt.Println("failed to write out creds", err) - } - })) - - client := endpointcreds.NewProviderClient(*unit.Session.Config, - unit.Session.Handlers, - server.URL+"/path/to/endpoint?something=else", - ) - creds, err := client.Retrieve() - - assert.NoError(t, err) - - assert.Equal(t, "AKID", creds.AccessKeyID) - assert.Equal(t, "SECRET", creds.SecretAccessKey) - assert.Equal(t, "TOKEN", creds.SessionToken) - assert.False(t, client.IsExpired()) - - client.(*endpointcreds.Provider).CurrentTime = func() time.Time { - return time.Now().Add(2 * time.Hour) - } - - assert.True(t, client.IsExpired()) -} - -func TestRetrieveStaticCredentials(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - encoder := json.NewEncoder(w) - err := encoder.Encode(map[string]interface{}{ - "AccessKeyID": "AKID", - "SecretAccessKey": "SECRET", - }) - - if err != nil { - fmt.Println("failed to write out creds", err) - } - })) - - client := endpointcreds.NewProviderClient(*unit.Session.Config, unit.Session.Handlers, server.URL) - creds, err := client.Retrieve() - - assert.NoError(t, err) - - assert.Equal(t, "AKID", creds.AccessKeyID) - assert.Equal(t, "SECRET", creds.SecretAccessKey) - assert.Empty(t, creds.SessionToken) - assert.False(t, client.IsExpired()) -} - -func TestFailedRetrieveCredentials(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(400) - encoder := json.NewEncoder(w) - err := encoder.Encode(map[string]interface{}{ - "Code": "Error", - "Message": "Message", - }) - - if err != nil { - fmt.Println("failed to write error", err) - } - })) - - client := endpointcreds.NewProviderClient(*unit.Session.Config, unit.Session.Handlers, server.URL) - creds, err := client.Retrieve() - - assert.Error(t, err) - aerr := err.(awserr.Error) - - assert.Equal(t, "CredentialsEndpointError", aerr.Code()) - assert.Equal(t, "failed to load credentials", aerr.Message()) - - aerr = aerr.OrigErr().(awserr.Error) - assert.Equal(t, "Error", aerr.Code()) - assert.Equal(t, "Message", aerr.Message()) - - assert.Empty(t, creds.AccessKeyID) - assert.Empty(t, creds.SecretAccessKey) - assert.Empty(t, creds.SessionToken) - assert.True(t, client.IsExpired()) -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/env_provider_test.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/env_provider_test.go deleted file mode 100644 index 53f6ce256..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/env_provider_test.go +++ /dev/null @@ -1,70 +0,0 @@ -package credentials - -import ( - "github.com/stretchr/testify/assert" - "os" - "testing" -) - -func TestEnvProviderRetrieve(t *testing.T) { - os.Clearenv() - os.Setenv("AWS_ACCESS_KEY_ID", "access") - os.Setenv("AWS_SECRET_ACCESS_KEY", "secret") - os.Setenv("AWS_SESSION_TOKEN", "token") - - e := EnvProvider{} - creds, err := e.Retrieve() - assert.Nil(t, err, "Expect no error") - - assert.Equal(t, "access", creds.AccessKeyID, "Expect access key ID to match") - assert.Equal(t, "secret", creds.SecretAccessKey, "Expect secret access key to match") - assert.Equal(t, "token", creds.SessionToken, "Expect session token to match") -} - -func TestEnvProviderIsExpired(t *testing.T) { - os.Clearenv() - os.Setenv("AWS_ACCESS_KEY_ID", "access") - os.Setenv("AWS_SECRET_ACCESS_KEY", "secret") - os.Setenv("AWS_SESSION_TOKEN", "token") - - e := EnvProvider{} - - assert.True(t, e.IsExpired(), "Expect creds to be expired before retrieve.") - - _, err := e.Retrieve() - assert.Nil(t, err, "Expect no error") - - assert.False(t, e.IsExpired(), "Expect creds to not be expired after retrieve.") -} - -func TestEnvProviderNoAccessKeyID(t *testing.T) { - os.Clearenv() - os.Setenv("AWS_SECRET_ACCESS_KEY", "secret") - - e := EnvProvider{} - creds, err := e.Retrieve() - assert.Equal(t, ErrAccessKeyIDNotFound, err, "ErrAccessKeyIDNotFound expected, but was %#v error: %#v", creds, err) -} - -func TestEnvProviderNoSecretAccessKey(t *testing.T) { - os.Clearenv() - os.Setenv("AWS_ACCESS_KEY_ID", "access") - - e := EnvProvider{} - creds, err := e.Retrieve() - assert.Equal(t, ErrSecretAccessKeyNotFound, err, "ErrSecretAccessKeyNotFound expected, but was %#v error: %#v", creds, err) -} - -func TestEnvProviderAlternateNames(t *testing.T) { - os.Clearenv() - os.Setenv("AWS_ACCESS_KEY", "access") - os.Setenv("AWS_SECRET_KEY", "secret") - - e := EnvProvider{} - creds, err := e.Retrieve() - assert.Nil(t, err, "Expect no error") - - assert.Equal(t, "access", creds.AccessKeyID, "Expected access key ID") - assert.Equal(t, "secret", creds.SecretAccessKey, "Expected secret access key") - assert.Empty(t, creds.SessionToken, "Expected no token") -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/example.ini b/vendor/github.com/aws/aws-sdk-go/aws/credentials/example.ini deleted file mode 100644 index 7fc91d9d2..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/example.ini +++ /dev/null @@ -1,12 +0,0 @@ -[default] -aws_access_key_id = accessKey -aws_secret_access_key = secret -aws_session_token = token - -[no_token] -aws_access_key_id = accessKey -aws_secret_access_key = secret - -[with_colon] -aws_access_key_id: accessKey -aws_secret_access_key: secret diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/shared_credentials_provider_test.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/shared_credentials_provider_test.go deleted file mode 100644 index 1eb45f263..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/shared_credentials_provider_test.go +++ /dev/null @@ -1,136 +0,0 @@ -package credentials - -import ( - "os" - "path/filepath" - "testing" - - "github.com/aws/aws-sdk-go/internal/shareddefaults" - "github.com/stretchr/testify/assert" -) - -func TestSharedCredentialsProvider(t *testing.T) { - os.Clearenv() - - p := SharedCredentialsProvider{Filename: "example.ini", Profile: ""} - creds, err := p.Retrieve() - assert.Nil(t, err, "Expect no error") - - assert.Equal(t, "accessKey", creds.AccessKeyID, "Expect access key ID to match") - assert.Equal(t, "secret", creds.SecretAccessKey, "Expect secret access key to match") - assert.Equal(t, "token", creds.SessionToken, "Expect session token to match") -} - -func TestSharedCredentialsProviderIsExpired(t *testing.T) { - os.Clearenv() - - p := SharedCredentialsProvider{Filename: "example.ini", Profile: ""} - - assert.True(t, p.IsExpired(), "Expect creds to be expired before retrieve") - - _, err := p.Retrieve() - assert.Nil(t, err, "Expect no error") - - assert.False(t, p.IsExpired(), "Expect creds to not be expired after retrieve") -} - -func TestSharedCredentialsProviderWithAWS_SHARED_CREDENTIALS_FILE(t *testing.T) { - os.Clearenv() - os.Setenv("AWS_SHARED_CREDENTIALS_FILE", "example.ini") - p := SharedCredentialsProvider{} - creds, err := p.Retrieve() - - assert.Nil(t, err, "Expect no error") - - assert.Equal(t, "accessKey", creds.AccessKeyID, "Expect access key ID to match") - assert.Equal(t, "secret", creds.SecretAccessKey, "Expect secret access key to match") - assert.Equal(t, "token", creds.SessionToken, "Expect session token to match") -} - -func TestSharedCredentialsProviderWithAWS_SHARED_CREDENTIALS_FILEAbsPath(t *testing.T) { - os.Clearenv() - wd, err := os.Getwd() - assert.NoError(t, err) - os.Setenv("AWS_SHARED_CREDENTIALS_FILE", filepath.Join(wd, "example.ini")) - p := SharedCredentialsProvider{} - creds, err := p.Retrieve() - assert.Nil(t, err, "Expect no error") - - assert.Equal(t, "accessKey", creds.AccessKeyID, "Expect access key ID to match") - assert.Equal(t, "secret", creds.SecretAccessKey, "Expect secret access key to match") - assert.Equal(t, "token", creds.SessionToken, "Expect session token to match") -} - -func TestSharedCredentialsProviderWithAWS_PROFILE(t *testing.T) { - os.Clearenv() - os.Setenv("AWS_PROFILE", "no_token") - - p := SharedCredentialsProvider{Filename: "example.ini", Profile: ""} - creds, err := p.Retrieve() - assert.Nil(t, err, "Expect no error") - - assert.Equal(t, "accessKey", creds.AccessKeyID, "Expect access key ID to match") - assert.Equal(t, "secret", creds.SecretAccessKey, "Expect secret access key to match") - assert.Empty(t, creds.SessionToken, "Expect no token") -} - -func TestSharedCredentialsProviderWithoutTokenFromProfile(t *testing.T) { - os.Clearenv() - - p := SharedCredentialsProvider{Filename: "example.ini", Profile: "no_token"} - creds, err := p.Retrieve() - assert.Nil(t, err, "Expect no error") - - assert.Equal(t, "accessKey", creds.AccessKeyID, "Expect access key ID to match") - assert.Equal(t, "secret", creds.SecretAccessKey, "Expect secret access key to match") - assert.Empty(t, creds.SessionToken, "Expect no token") -} - -func TestSharedCredentialsProviderColonInCredFile(t *testing.T) { - os.Clearenv() - - p := SharedCredentialsProvider{Filename: "example.ini", Profile: "with_colon"} - creds, err := p.Retrieve() - assert.Nil(t, err, "Expect no error") - - assert.Equal(t, "accessKey", creds.AccessKeyID, "Expect access key ID to match") - assert.Equal(t, "secret", creds.SecretAccessKey, "Expect secret access key to match") - assert.Empty(t, creds.SessionToken, "Expect no token") -} - -func TestSharedCredentialsProvider_DefaultFilename(t *testing.T) { - os.Clearenv() - os.Setenv("USERPROFILE", "profile_dir") - os.Setenv("HOME", "home_dir") - - // default filename and profile - p := SharedCredentialsProvider{} - - filename, err := p.filename() - - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - - if e, a := shareddefaults.SharedCredentialsFilename(), filename; e != a { - t.Errorf("expect %q filename, got %q", e, a) - } -} - -func BenchmarkSharedCredentialsProvider(b *testing.B) { - os.Clearenv() - - p := SharedCredentialsProvider{Filename: "example.ini", Profile: ""} - _, err := p.Retrieve() - if err != nil { - b.Fatal(err) - } - - b.ResetTimer() - for i := 0; i < b.N; i++ { - _, err := p.Retrieve() - if err != nil { - b.Fatal(err) - } - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/static_provider_test.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/static_provider_test.go deleted file mode 100644 index ea0123696..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/static_provider_test.go +++ /dev/null @@ -1,34 +0,0 @@ -package credentials - -import ( - "github.com/stretchr/testify/assert" - "testing" -) - -func TestStaticProviderGet(t *testing.T) { - s := StaticProvider{ - Value: Value{ - AccessKeyID: "AKID", - SecretAccessKey: "SECRET", - SessionToken: "", - }, - } - - creds, err := s.Retrieve() - assert.Nil(t, err, "Expect no error") - assert.Equal(t, "AKID", creds.AccessKeyID, "Expect access key ID to match") - assert.Equal(t, "SECRET", creds.SecretAccessKey, "Expect secret access key to match") - assert.Empty(t, creds.SessionToken, "Expect no session token") -} - -func TestStaticProviderIsExpired(t *testing.T) { - s := StaticProvider{ - Value: Value{ - AccessKeyID: "AKID", - SecretAccessKey: "SECRET", - SessionToken: "", - }, - } - - assert.False(t, s.IsExpired(), "Expect static credentials to never expire") -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/stscreds/assume_role_provider_test.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/stscreds/assume_role_provider_test.go deleted file mode 100644 index 4c0212a01..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/stscreds/assume_role_provider_test.go +++ /dev/null @@ -1,150 +0,0 @@ -package stscreds - -import ( - "fmt" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/sts" - "github.com/stretchr/testify/assert" -) - -type stubSTS struct { - TestInput func(*sts.AssumeRoleInput) -} - -func (s *stubSTS) AssumeRole(input *sts.AssumeRoleInput) (*sts.AssumeRoleOutput, error) { - if s.TestInput != nil { - s.TestInput(input) - } - expiry := time.Now().Add(60 * time.Minute) - return &sts.AssumeRoleOutput{ - Credentials: &sts.Credentials{ - // Just reflect the role arn to the provider. - AccessKeyId: input.RoleArn, - SecretAccessKey: aws.String("assumedSecretAccessKey"), - SessionToken: aws.String("assumedSessionToken"), - Expiration: &expiry, - }, - }, nil -} - -func TestAssumeRoleProvider(t *testing.T) { - stub := &stubSTS{} - p := &AssumeRoleProvider{ - Client: stub, - RoleARN: "roleARN", - } - - creds, err := p.Retrieve() - assert.Nil(t, err, "Expect no error") - - assert.Equal(t, "roleARN", creds.AccessKeyID, "Expect access key ID to be reflected role ARN") - assert.Equal(t, "assumedSecretAccessKey", creds.SecretAccessKey, "Expect secret access key to match") - assert.Equal(t, "assumedSessionToken", creds.SessionToken, "Expect session token to match") -} - -func TestAssumeRoleProvider_WithTokenCode(t *testing.T) { - stub := &stubSTS{ - TestInput: func(in *sts.AssumeRoleInput) { - assert.Equal(t, "0123456789", *in.SerialNumber) - assert.Equal(t, "code", *in.TokenCode) - }, - } - p := &AssumeRoleProvider{ - Client: stub, - RoleARN: "roleARN", - SerialNumber: aws.String("0123456789"), - TokenCode: aws.String("code"), - } - - creds, err := p.Retrieve() - assert.Nil(t, err, "Expect no error") - - assert.Equal(t, "roleARN", creds.AccessKeyID, "Expect access key ID to be reflected role ARN") - assert.Equal(t, "assumedSecretAccessKey", creds.SecretAccessKey, "Expect secret access key to match") - assert.Equal(t, "assumedSessionToken", creds.SessionToken, "Expect session token to match") -} - -func TestAssumeRoleProvider_WithTokenProvider(t *testing.T) { - stub := &stubSTS{ - TestInput: func(in *sts.AssumeRoleInput) { - assert.Equal(t, "0123456789", *in.SerialNumber) - assert.Equal(t, "code", *in.TokenCode) - }, - } - p := &AssumeRoleProvider{ - Client: stub, - RoleARN: "roleARN", - SerialNumber: aws.String("0123456789"), - TokenProvider: func() (string, error) { - return "code", nil - }, - } - - creds, err := p.Retrieve() - assert.Nil(t, err, "Expect no error") - - assert.Equal(t, "roleARN", creds.AccessKeyID, "Expect access key ID to be reflected role ARN") - assert.Equal(t, "assumedSecretAccessKey", creds.SecretAccessKey, "Expect secret access key to match") - assert.Equal(t, "assumedSessionToken", creds.SessionToken, "Expect session token to match") -} - -func TestAssumeRoleProvider_WithTokenProviderError(t *testing.T) { - stub := &stubSTS{ - TestInput: func(in *sts.AssumeRoleInput) { - assert.Fail(t, "API request should not of been called") - }, - } - p := &AssumeRoleProvider{ - Client: stub, - RoleARN: "roleARN", - SerialNumber: aws.String("0123456789"), - TokenProvider: func() (string, error) { - return "", fmt.Errorf("error occurred") - }, - } - - creds, err := p.Retrieve() - assert.Error(t, err) - - assert.Empty(t, creds.AccessKeyID) - assert.Empty(t, creds.SecretAccessKey) - assert.Empty(t, creds.SessionToken) -} - -func TestAssumeRoleProvider_MFAWithNoToken(t *testing.T) { - stub := &stubSTS{ - TestInput: func(in *sts.AssumeRoleInput) { - assert.Fail(t, "API request should not of been called") - }, - } - p := &AssumeRoleProvider{ - Client: stub, - RoleARN: "roleARN", - SerialNumber: aws.String("0123456789"), - } - - creds, err := p.Retrieve() - assert.Error(t, err) - - assert.Empty(t, creds.AccessKeyID) - assert.Empty(t, creds.SecretAccessKey) - assert.Empty(t, creds.SessionToken) -} - -func BenchmarkAssumeRoleProvider(b *testing.B) { - stub := &stubSTS{} - p := &AssumeRoleProvider{ - Client: stub, - RoleARN: "roleARN", - } - - b.ResetTimer() - for i := 0; i < b.N; i++ { - if _, err := p.Retrieve(); err != nil { - b.Fatal(err) - } - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/defaults/defaults_test.go b/vendor/github.com/aws/aws-sdk-go/aws/defaults/defaults_test.go deleted file mode 100644 index d3e4a86b6..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/defaults/defaults_test.go +++ /dev/null @@ -1,88 +0,0 @@ -package defaults - -import ( - "fmt" - "os" - "testing" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds" - "github.com/aws/aws-sdk-go/aws/credentials/endpointcreds" - "github.com/aws/aws-sdk-go/aws/request" -) - -func TestHTTPCredProvider(t *testing.T) { - cases := []struct { - Host string - Fail bool - }{ - {"localhost", false}, {"127.0.0.1", false}, - {"www.example.com", true}, {"169.254.170.2", true}, - } - - defer os.Clearenv() - - for i, c := range cases { - u := fmt.Sprintf("http://%s/abc/123", c.Host) - os.Setenv(httpProviderEnvVar, u) - - provider := RemoteCredProvider(aws.Config{}, request.Handlers{}) - if provider == nil { - t.Fatalf("%d, expect provider not to be nil, but was", i) - } - - if c.Fail { - creds, err := provider.Retrieve() - if err == nil { - t.Fatalf("%d, expect error but got none", i) - } else { - aerr := err.(awserr.Error) - if e, a := "CredentialsEndpointError", aerr.Code(); e != a { - t.Errorf("%d, expect %s error code, got %s", i, e, a) - } - } - if e, a := endpointcreds.ProviderName, creds.ProviderName; e != a { - t.Errorf("%d, expect %s provider name got %s", i, e, a) - } - } else { - httpProvider := provider.(*endpointcreds.Provider) - if e, a := u, httpProvider.Client.Endpoint; e != a { - t.Errorf("%d, expect %q endpoint, got %q", i, e, a) - } - } - } -} - -func TestECSCredProvider(t *testing.T) { - defer os.Clearenv() - os.Setenv(ecsCredsProviderEnvVar, "/abc/123") - - provider := RemoteCredProvider(aws.Config{}, request.Handlers{}) - if provider == nil { - t.Fatalf("expect provider not to be nil, but was") - } - - httpProvider := provider.(*endpointcreds.Provider) - if httpProvider == nil { - t.Fatalf("expect provider not to be nil, but was") - } - if e, a := "http://169.254.170.2/abc/123", httpProvider.Client.Endpoint; e != a { - t.Errorf("expect %q endpoint, got %q", e, a) - } -} - -func TestDefaultEC2RoleProvider(t *testing.T) { - provider := RemoteCredProvider(aws.Config{}, request.Handlers{}) - if provider == nil { - t.Fatalf("expect provider not to be nil, but was") - } - - ec2Provider := provider.(*ec2rolecreds.EC2RoleProvider) - if ec2Provider == nil { - t.Fatalf("expect provider not to be nil, but was") - } - if e, a := "http://169.254.169.254/latest", ec2Provider.Client.Endpoint; e != a { - t.Errorf("expect %q endpoint, got %q", e, a) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/api_test.go b/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/api_test.go deleted file mode 100644 index 7dde1fb36..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/api_test.go +++ /dev/null @@ -1,289 +0,0 @@ -package ec2metadata_test - -import ( - "bytes" - "fmt" - "io" - "io/ioutil" - "net/http" - "net/http/httptest" - "path" - "strings" - "testing" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/ec2metadata" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/awstesting/unit" -) - -const instanceIdentityDocument = `{ - "devpayProductCodes" : null, - "availabilityZone" : "us-east-1d", - "privateIp" : "10.158.112.84", - "version" : "2010-08-31", - "region" : "us-east-1", - "instanceId" : "i-1234567890abcdef0", - "billingProducts" : null, - "instanceType" : "t1.micro", - "accountId" : "123456789012", - "pendingTime" : "2015-11-19T16:32:11Z", - "imageId" : "ami-5fb8c835", - "kernelId" : "aki-919dcaf8", - "ramdiskId" : null, - "architecture" : "x86_64" -}` - -const validIamInfo = `{ - "Code" : "Success", - "LastUpdated" : "2016-03-17T12:27:32Z", - "InstanceProfileArn" : "arn:aws:iam::123456789012:instance-profile/my-instance-profile", - "InstanceProfileId" : "AIPAABCDEFGHIJKLMN123" -}` - -const unsuccessfulIamInfo = `{ - "Code" : "Failed", - "LastUpdated" : "2016-03-17T12:27:32Z", - "InstanceProfileArn" : "arn:aws:iam::123456789012:instance-profile/my-instance-profile", - "InstanceProfileId" : "AIPAABCDEFGHIJKLMN123" -}` - -func initTestServer(path string, resp string) *httptest.Server { - return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.RequestURI != path { - http.Error(w, "not found", http.StatusNotFound) - return - } - - w.Write([]byte(resp)) - })) -} - -func TestEndpoint(t *testing.T) { - c := ec2metadata.New(unit.Session) - op := &request.Operation{ - Name: "GetMetadata", - HTTPMethod: "GET", - HTTPPath: path.Join("/", "meta-data", "testpath"), - } - - req := c.NewRequest(op, nil, nil) - if e, a := "http://169.254.169.254/latest", req.ClientInfo.Endpoint; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "http://169.254.169.254/latest/meta-data/testpath", req.HTTPRequest.URL.String(); e != a { - t.Errorf("expect %v, got %v", e, a) - } -} - -func TestGetMetadata(t *testing.T) { - server := initTestServer( - "/latest/meta-data/some/path", - "success", // real response includes suffix - ) - defer server.Close() - c := ec2metadata.New(unit.Session, &aws.Config{Endpoint: aws.String(server.URL + "/latest")}) - - resp, err := c.GetMetadata("some/path") - - if err != nil { - t.Errorf("expect no error, got %v", err) - } - if e, a := "success", resp; e != a { - t.Errorf("expect %v, got %v", e, a) - } -} - -func TestGetUserData(t *testing.T) { - server := initTestServer( - "/latest/user-data", - "success", // real response includes suffix - ) - defer server.Close() - c := ec2metadata.New(unit.Session, &aws.Config{Endpoint: aws.String(server.URL + "/latest")}) - - resp, err := c.GetUserData() - - if err != nil { - t.Errorf("expect no error, got %v", err) - } - if e, a := "success", resp; e != a { - t.Errorf("expect %v, got %v", e, a) - } -} - -func TestGetUserData_Error(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - reader := strings.NewReader(` - - - - 404 - Not Found - - -

404 - Not Found

- -`) - w.Header().Set("Content-Type", "text/html") - w.Header().Set("Content-Length", fmt.Sprintf("%d", reader.Len())) - w.WriteHeader(http.StatusNotFound) - io.Copy(w, reader) - })) - - defer server.Close() - c := ec2metadata.New(unit.Session, &aws.Config{Endpoint: aws.String(server.URL + "/latest")}) - - resp, err := c.GetUserData() - if err == nil { - t.Errorf("expect error") - } - if len(resp) != 0 { - t.Errorf("expect empty, got %v", resp) - } - - aerr := err.(awserr.Error) - if e, a := "NotFoundError", aerr.Code(); e != a { - t.Errorf("expect %v, got %v", e, a) - } -} - -func TestGetRegion(t *testing.T) { - server := initTestServer( - "/latest/meta-data/placement/availability-zone", - "us-west-2a", // real response includes suffix - ) - defer server.Close() - c := ec2metadata.New(unit.Session, &aws.Config{Endpoint: aws.String(server.URL + "/latest")}) - - region, err := c.Region() - - if err != nil { - t.Errorf("expect no error, got %v", err) - } - if e, a := "us-west-2", region; e != a { - t.Errorf("expect %v, got %v", e, a) - } -} - -func TestMetadataAvailable(t *testing.T) { - server := initTestServer( - "/latest/meta-data/instance-id", - "instance-id", - ) - defer server.Close() - c := ec2metadata.New(unit.Session, &aws.Config{Endpoint: aws.String(server.URL + "/latest")}) - - if !c.Available() { - t.Errorf("expect available") - } -} - -func TestMetadataIAMInfo_success(t *testing.T) { - server := initTestServer( - "/latest/meta-data/iam/info", - validIamInfo, - ) - defer server.Close() - c := ec2metadata.New(unit.Session, &aws.Config{Endpoint: aws.String(server.URL + "/latest")}) - - iamInfo, err := c.IAMInfo() - if err != nil { - t.Errorf("expect no error, got %v", err) - } - if e, a := "Success", iamInfo.Code; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "arn:aws:iam::123456789012:instance-profile/my-instance-profile", iamInfo.InstanceProfileArn; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "AIPAABCDEFGHIJKLMN123", iamInfo.InstanceProfileID; e != a { - t.Errorf("expect %v, got %v", e, a) - } -} - -func TestMetadataIAMInfo_failure(t *testing.T) { - server := initTestServer( - "/latest/meta-data/iam/info", - unsuccessfulIamInfo, - ) - defer server.Close() - c := ec2metadata.New(unit.Session, &aws.Config{Endpoint: aws.String(server.URL + "/latest")}) - - iamInfo, err := c.IAMInfo() - if err == nil { - t.Errorf("expect error") - } - if e, a := "", iamInfo.Code; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "", iamInfo.InstanceProfileArn; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "", iamInfo.InstanceProfileID; e != a { - t.Errorf("expect %v, got %v", e, a) - } -} - -func TestMetadataNotAvailable(t *testing.T) { - c := ec2metadata.New(unit.Session) - c.Handlers.Send.Clear() - c.Handlers.Send.PushBack(func(r *request.Request) { - r.HTTPResponse = &http.Response{ - StatusCode: int(0), - Status: http.StatusText(int(0)), - Body: ioutil.NopCloser(bytes.NewReader([]byte{})), - } - r.Error = awserr.New("RequestError", "send request failed", nil) - r.Retryable = aws.Bool(true) // network errors are retryable - }) - - if c.Available() { - t.Errorf("expect not available") - } -} - -func TestMetadataErrorResponse(t *testing.T) { - c := ec2metadata.New(unit.Session) - c.Handlers.Send.Clear() - c.Handlers.Send.PushBack(func(r *request.Request) { - r.HTTPResponse = &http.Response{ - StatusCode: http.StatusBadRequest, - Status: http.StatusText(http.StatusBadRequest), - Body: ioutil.NopCloser(strings.NewReader("error message text")), - } - r.Retryable = aws.Bool(false) // network errors are retryable - }) - - data, err := c.GetMetadata("uri/path") - if len(data) != 0 { - t.Errorf("expect empty, got %v", data) - } - if e, a := "error message text", err.Error(); !strings.Contains(a, e) { - t.Errorf("expect %v to be in %v", e, a) - } -} - -func TestEC2RoleProviderInstanceIdentity(t *testing.T) { - server := initTestServer( - "/latest/dynamic/instance-identity/document", - instanceIdentityDocument, - ) - defer server.Close() - c := ec2metadata.New(unit.Session, &aws.Config{Endpoint: aws.String(server.URL + "/latest")}) - - doc, err := c.GetInstanceIdentityDocument() - if err != nil { - t.Errorf("expect no error, got %v", err) - } - if e, a := doc.AccountID, "123456789012"; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := doc.AvailabilityZone, "us-east-1d"; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := doc.Region, "us-east-1"; e != a { - t.Errorf("expect %v, got %v", e, a) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/service_test.go b/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/service_test.go deleted file mode 100644 index c2bc21587..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/service_test.go +++ /dev/null @@ -1,78 +0,0 @@ -package ec2metadata_test - -import ( - "net/http" - "net/http/httptest" - "sync" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/ec2metadata" - "github.com/aws/aws-sdk-go/awstesting/unit" - "github.com/stretchr/testify/assert" -) - -func TestClientOverrideDefaultHTTPClientTimeout(t *testing.T) { - svc := ec2metadata.New(unit.Session) - - assert.NotEqual(t, http.DefaultClient, svc.Config.HTTPClient) - assert.Equal(t, 5*time.Second, svc.Config.HTTPClient.Timeout) -} - -func TestClientNotOverrideDefaultHTTPClientTimeout(t *testing.T) { - http.DefaultClient.Transport = &http.Transport{} - defer func() { - http.DefaultClient.Transport = nil - }() - - svc := ec2metadata.New(unit.Session) - - assert.Equal(t, http.DefaultClient, svc.Config.HTTPClient) - - tr, ok := svc.Config.HTTPClient.Transport.(*http.Transport) - assert.True(t, ok) - assert.NotNil(t, tr) - assert.Nil(t, tr.Dial) -} - -func TestClientDisableOverrideDefaultHTTPClientTimeout(t *testing.T) { - svc := ec2metadata.New(unit.Session, aws.NewConfig().WithEC2MetadataDisableTimeoutOverride(true)) - - assert.Equal(t, http.DefaultClient, svc.Config.HTTPClient) -} - -func TestClientOverrideDefaultHTTPClientTimeoutRace(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Write([]byte("us-east-1a")) - })) - - cfg := aws.NewConfig().WithEndpoint(server.URL) - runEC2MetadataClients(t, cfg, 100) -} - -func TestClientOverrideDefaultHTTPClientTimeoutRaceWithTransport(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Write([]byte("us-east-1a")) - })) - - cfg := aws.NewConfig().WithEndpoint(server.URL).WithHTTPClient(&http.Client{ - Transport: http.DefaultTransport, - }) - - runEC2MetadataClients(t, cfg, 100) -} - -func runEC2MetadataClients(t *testing.T, cfg *aws.Config, atOnce int) { - var wg sync.WaitGroup - wg.Add(atOnce) - for i := 0; i < atOnce; i++ { - go func() { - svc := ec2metadata.New(unit.Session, cfg) - _, err := svc.Region() - assert.NoError(t, err) - wg.Done() - }() - } - wg.Wait() -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/decode_test.go b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/decode_test.go deleted file mode 100644 index 319390721..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/decode_test.go +++ /dev/null @@ -1,117 +0,0 @@ -package endpoints - -import ( - "strings" - "testing" -) - -func TestDecodeEndpoints_V3(t *testing.T) { - const v3Doc = ` -{ - "version": 3, - "partitions": [ - { - "defaults": { - "hostname": "{service}.{region}.{dnsSuffix}", - "protocols": [ - "https" - ], - "signatureVersions": [ - "v4" - ] - }, - "dnsSuffix": "amazonaws.com", - "partition": "aws", - "partitionName": "AWS Standard", - "regionRegex": "^(us|eu|ap|sa|ca)\\-\\w+\\-\\d+$", - "regions": { - "ap-northeast-1": { - "description": "Asia Pacific (Tokyo)" - } - }, - "services": { - "acm": { - "endpoints": { - "ap-northeast-1": {} - } - }, - "s3": { - "endpoints": { - "ap-northeast-1": {} - } - } - } - } - ] -}` - - resolver, err := DecodeModel(strings.NewReader(v3Doc)) - if err != nil { - t.Fatalf("expected no error, got %v", err) - } - - endpoint, err := resolver.EndpointFor("acm", "ap-northeast-1") - if err != nil { - t.Fatalf("failed to resolve endpoint, %v", err) - } - - if a, e := endpoint.URL, "https://acm.ap-northeast-1.amazonaws.com"; a != e { - t.Errorf("expected %q URL got %q", e, a) - } - - p := resolver.(partitions)[0] - - s3Defaults := p.Services["s3"].Defaults - if a, e := s3Defaults.HasDualStack, boxedTrue; a != e { - t.Errorf("expect s3 service to have dualstack enabled") - } - if a, e := s3Defaults.DualStackHostname, "{service}.dualstack.{region}.{dnsSuffix}"; a != e { - t.Errorf("expect s3 dualstack host pattern to be %q, got %q", e, a) - } - - ec2metaEndpoint := p.Services["ec2metadata"].Endpoints["aws-global"] - if a, e := ec2metaEndpoint.Hostname, "169.254.169.254/latest"; a != e { - t.Errorf("expect ec2metadata host to be %q, got %q", e, a) - } -} - -func TestDecodeEndpoints_NoPartitions(t *testing.T) { - const doc = `{ "version": 3 }` - - resolver, err := DecodeModel(strings.NewReader(doc)) - if err == nil { - t.Fatalf("expected error") - } - - if resolver != nil { - t.Errorf("expect resolver to be nil") - } -} - -func TestDecodeEndpoints_UnsupportedVersion(t *testing.T) { - const doc = `{ "version": 2 }` - - resolver, err := DecodeModel(strings.NewReader(doc)) - if err == nil { - t.Fatalf("expected error decoding model") - } - - if resolver != nil { - t.Errorf("expect resolver to be nil") - } -} - -func TestDecodeModelOptionsSet(t *testing.T) { - var actual DecodeModelOptions - actual.Set(func(o *DecodeModelOptions) { - o.SkipCustomizations = true - }) - - expect := DecodeModelOptions{ - SkipCustomizations: true, - } - - if actual != expect { - t.Errorf("expect %v options got %v", expect, actual) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/endpoints_test.go b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/endpoints_test.go deleted file mode 100644 index 9c0e09db6..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/endpoints_test.go +++ /dev/null @@ -1,335 +0,0 @@ -package endpoints - -import "testing" - -func TestEnumDefaultPartitions(t *testing.T) { - resolver := DefaultResolver() - enum, ok := resolver.(EnumPartitions) - - if ok != true { - t.Fatalf("resolver must satisfy EnumPartition interface") - } - - ps := enum.Partitions() - - if a, e := len(ps), len(defaultPartitions); a != e { - t.Errorf("expected %d partitions, got %d", e, a) - } -} - -func TestEnumDefaultRegions(t *testing.T) { - expectPart := defaultPartitions[0] - partEnum := defaultPartitions[0].Partition() - - regEnum := partEnum.Regions() - - if a, e := len(regEnum), len(expectPart.Regions); a != e { - t.Errorf("expected %d regions, got %d", e, a) - } -} - -func TestEnumPartitionServices(t *testing.T) { - expectPart := testPartitions[0] - partEnum := testPartitions[0].Partition() - - if a, e := partEnum.ID(), "part-id"; a != e { - t.Errorf("expect %q partition ID, got %q", e, a) - } - - svcEnum := partEnum.Services() - - if a, e := len(svcEnum), len(expectPart.Services); a != e { - t.Errorf("expected %d regions, got %d", e, a) - } -} - -func TestEnumRegionServices(t *testing.T) { - p := testPartitions[0].Partition() - - rs := p.Regions() - - if a, e := len(rs), 2; a != e { - t.Errorf("expect %d regions got %d", e, a) - } - - if _, ok := rs["us-east-1"]; !ok { - t.Errorf("expect us-east-1 region to be found, was not") - } - if _, ok := rs["us-west-2"]; !ok { - t.Errorf("expect us-west-2 region to be found, was not") - } - - r := rs["us-east-1"] - - if a, e := r.ID(), "us-east-1"; a != e { - t.Errorf("expect %q region ID, got %q", e, a) - } - - ss := r.Services() - if a, e := len(ss), 1; a != e { - t.Errorf("expect %d services for us-east-1, got %d", e, a) - } - - if _, ok := ss["service1"]; !ok { - t.Errorf("expect service1 service to be found, was not") - } - - resolved, err := r.ResolveEndpoint("service1") - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - - if a, e := resolved.URL, "https://service1.us-east-1.amazonaws.com"; a != e { - t.Errorf("expect %q resolved URL, got %q", e, a) - } -} - -func TestEnumServiceRegions(t *testing.T) { - p := testPartitions[0].Partition() - - rs := p.Services()["service1"].Regions() - if e, a := 2, len(rs); e != a { - t.Errorf("expect %d regions, got %d", e, a) - } - - if _, ok := rs["us-east-1"]; !ok { - t.Errorf("expect region to be found") - } - if _, ok := rs["us-west-2"]; !ok { - t.Errorf("expect region to be found") - } -} - -func TestEnumServicesEndpoints(t *testing.T) { - p := testPartitions[0].Partition() - - ss := p.Services() - - if a, e := len(ss), 5; a != e { - t.Errorf("expect %d regions got %d", e, a) - } - - if _, ok := ss["service1"]; !ok { - t.Errorf("expect service1 region to be found, was not") - } - if _, ok := ss["service2"]; !ok { - t.Errorf("expect service2 region to be found, was not") - } - - s := ss["service1"] - if a, e := s.ID(), "service1"; a != e { - t.Errorf("expect %q service ID, got %q", e, a) - } - - resolved, err := s.ResolveEndpoint("us-west-2") - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - - if a, e := resolved.URL, "https://service1.us-west-2.amazonaws.com"; a != e { - t.Errorf("expect %q resolved URL, got %q", e, a) - } -} - -func TestEnumEndpoints(t *testing.T) { - p := testPartitions[0].Partition() - s := p.Services()["service1"] - - es := s.Endpoints() - if a, e := len(es), 2; a != e { - t.Errorf("expect %d endpoints for service2, got %d", e, a) - } - if _, ok := es["us-east-1"]; !ok { - t.Errorf("expect us-east-1 to be found, was not") - } - - e := es["us-east-1"] - if a, e := e.ID(), "us-east-1"; a != e { - t.Errorf("expect %q endpoint ID, got %q", e, a) - } - if a, e := e.ServiceID(), "service1"; a != e { - t.Errorf("expect %q service ID, got %q", e, a) - } - - resolved, err := e.ResolveEndpoint() - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - - if a, e := resolved.URL, "https://service1.us-east-1.amazonaws.com"; a != e { - t.Errorf("expect %q resolved URL, got %q", e, a) - } -} - -func TestResolveEndpointForPartition(t *testing.T) { - enum := testPartitions.Partitions()[0] - - expected, err := testPartitions.EndpointFor("service1", "us-east-1") - - actual, err := enum.EndpointFor("service1", "us-east-1") - if err != nil { - t.Fatalf("unexpected error, %v", err) - } - - if expected != actual { - t.Errorf("expect resolved endpoint to be %v, but got %v", expected, actual) - } -} - -func TestAddScheme(t *testing.T) { - cases := []struct { - In string - Expect string - DisableSSL bool - }{ - { - In: "https://example.com", - Expect: "https://example.com", - }, - { - In: "example.com", - Expect: "https://example.com", - }, - { - In: "http://example.com", - Expect: "http://example.com", - }, - { - In: "example.com", - Expect: "http://example.com", - DisableSSL: true, - }, - { - In: "https://example.com", - Expect: "https://example.com", - DisableSSL: true, - }, - } - - for i, c := range cases { - actual := AddScheme(c.In, c.DisableSSL) - if actual != c.Expect { - t.Errorf("%d, expect URL to be %q, got %q", i, c.Expect, actual) - } - } -} - -func TestResolverFunc(t *testing.T) { - var resolver Resolver - - resolver = ResolverFunc(func(s, r string, opts ...func(*Options)) (ResolvedEndpoint, error) { - return ResolvedEndpoint{ - URL: "https://service.region.dnssuffix.com", - SigningRegion: "region", - SigningName: "service", - }, nil - }) - - resolved, err := resolver.EndpointFor("service", "region", func(o *Options) { - o.DisableSSL = true - }) - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - - if a, e := resolved.URL, "https://service.region.dnssuffix.com"; a != e { - t.Errorf("expect %q endpoint URL, got %q", e, a) - } - - if a, e := resolved.SigningRegion, "region"; a != e { - t.Errorf("expect %q region, got %q", e, a) - } - if a, e := resolved.SigningName, "service"; a != e { - t.Errorf("expect %q signing name, got %q", e, a) - } -} - -func TestOptionsSet(t *testing.T) { - var actual Options - actual.Set(DisableSSLOption, UseDualStackOption, StrictMatchingOption) - - expect := Options{ - DisableSSL: true, - UseDualStack: true, - StrictMatching: true, - } - - if actual != expect { - t.Errorf("expect %v options got %v", expect, actual) - } -} - -func TestRegionsForService(t *testing.T) { - ps := DefaultPartitions() - - var expect map[string]Region - var serviceID string - for _, s := range ps[0].Services() { - expect = s.Regions() - serviceID = s.ID() - if len(expect) > 0 { - break - } - } - - actual, ok := RegionsForService(ps, ps[0].ID(), serviceID) - if !ok { - t.Fatalf("expect regions to be found, was not") - } - - if len(actual) == 0 { - t.Fatalf("expect service %s to have regions", serviceID) - } - if e, a := len(expect), len(actual); e != a { - t.Fatalf("expect %d regions, got %d", e, a) - } - - for id, r := range actual { - if e, a := id, r.ID(); e != a { - t.Errorf("expect %s region id, got %s", e, a) - } - if _, ok := expect[id]; !ok { - t.Errorf("expect %s region to be found", id) - } - } -} - -func TestRegionsForService_NotFound(t *testing.T) { - ps := testPartitions.Partitions() - - actual, ok := RegionsForService(ps, ps[0].ID(), "service-not-exists") - if ok { - t.Fatalf("expect no regions to be found, but were") - } - if len(actual) != 0 { - t.Errorf("expect no regions, got %v", actual) - } -} - -func TestPartitionForRegion(t *testing.T) { - ps := DefaultPartitions() - expect := ps[len(ps)%2] - - var regionID string - for id := range expect.Regions() { - regionID = id - break - } - - actual, ok := PartitionForRegion(ps, regionID) - if !ok { - t.Fatalf("expect partition to be found") - } - if e, a := expect.ID(), actual.ID(); e != a { - t.Errorf("expect %s partition, got %s", e, a) - } -} - -func TestPartitionForRegion_NotFound(t *testing.T) { - ps := DefaultPartitions() - - actual, ok := PartitionForRegion(ps, "regionNotExists") - if ok { - t.Errorf("expect no partition to be found, got %v", actual) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/example_test.go b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/example_test.go deleted file mode 100644 index 007fed2f9..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/example_test.go +++ /dev/null @@ -1,66 +0,0 @@ -package endpoints_test - -import ( - "fmt" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/endpoints" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - "github.com/aws/aws-sdk-go/service/sqs" -) - -func ExampleEnumPartitions() { - resolver := endpoints.DefaultResolver() - partitions := resolver.(endpoints.EnumPartitions).Partitions() - - for _, p := range partitions { - fmt.Println("Regions for", p.ID()) - for id := range p.Regions() { - fmt.Println("*", id) - } - - fmt.Println("Services for", p.ID()) - for id := range p.Services() { - fmt.Println("*", id) - } - } -} - -func ExampleResolverFunc() { - myCustomResolver := func(service, region string, optFns ...func(*endpoints.Options)) (endpoints.ResolvedEndpoint, error) { - if service == endpoints.S3ServiceID { - return endpoints.ResolvedEndpoint{ - URL: "s3.custom.endpoint.com", - SigningRegion: "custom-signing-region", - }, nil - } - - return endpoints.DefaultResolver().EndpointFor(service, region, optFns...) - } - - sess := session.Must(session.NewSession(&aws.Config{ - Region: aws.String("us-west-2"), - EndpointResolver: endpoints.ResolverFunc(myCustomResolver), - })) - - // Create the S3 service client with the shared session. This will - // automatically use the S3 custom endpoint configured in the custom - // endpoint resolver wrapping the default endpoint resolver. - s3Svc := s3.New(sess) - // Operation calls will be made to the custom endpoint. - s3Svc.GetObject(&s3.GetObjectInput{ - Bucket: aws.String("myBucket"), - Key: aws.String("myObjectKey"), - }) - - // Create the SQS service client with the shared session. This will - // fallback to the default endpoint resolver because the customization - // passes any non S3 service endpoint resolve to the default resolver. - sqsSvc := sqs.New(sess) - // Operation calls will be made to the default endpoint for SQS for the - // region configured. - sqsSvc.ReceiveMessage(&sqs.ReceiveMessageInput{ - QueueUrl: aws.String("my-queue-url"), - }) -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/v3model_test.go b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/v3model_test.go deleted file mode 100644 index 1385cb427..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/v3model_test.go +++ /dev/null @@ -1,354 +0,0 @@ -package endpoints - -import ( - "encoding/json" - "regexp" - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestUnmarshalRegionRegex(t *testing.T) { - var input = []byte(` -{ - "regionRegex": "^(us|eu|ap|sa|ca)\\-\\w+\\-\\d+$" -}`) - - p := partition{} - err := json.Unmarshal(input, &p) - assert.NoError(t, err) - - expectRegexp, err := regexp.Compile(`^(us|eu|ap|sa|ca)\-\w+\-\d+$`) - assert.NoError(t, err) - - assert.Equal(t, expectRegexp.String(), p.RegionRegex.Regexp.String()) -} - -func TestUnmarshalRegion(t *testing.T) { - var input = []byte(` -{ - "aws-global": { - "description": "AWS partition-global endpoint" - }, - "us-east-1": { - "description": "US East (N. Virginia)" - } -}`) - - rs := regions{} - err := json.Unmarshal(input, &rs) - assert.NoError(t, err) - - assert.Len(t, rs, 2) - r, ok := rs["aws-global"] - assert.True(t, ok) - assert.Equal(t, "AWS partition-global endpoint", r.Description) - - r, ok = rs["us-east-1"] - assert.True(t, ok) - assert.Equal(t, "US East (N. Virginia)", r.Description) -} - -func TestUnmarshalServices(t *testing.T) { - var input = []byte(` -{ - "acm": { - "endpoints": { - "us-east-1": {} - } - }, - "apigateway": { - "isRegionalized": true, - "endpoints": { - "us-east-1": {}, - "us-west-2": {} - } - }, - "notRegionalized": { - "isRegionalized": false, - "endpoints": { - "us-east-1": {}, - "us-west-2": {} - } - } -}`) - - ss := services{} - err := json.Unmarshal(input, &ss) - assert.NoError(t, err) - - assert.Len(t, ss, 3) - s, ok := ss["acm"] - assert.True(t, ok) - assert.Len(t, s.Endpoints, 1) - assert.Equal(t, boxedBoolUnset, s.IsRegionalized) - - s, ok = ss["apigateway"] - assert.True(t, ok) - assert.Len(t, s.Endpoints, 2) - assert.Equal(t, boxedTrue, s.IsRegionalized) - - s, ok = ss["notRegionalized"] - assert.True(t, ok) - assert.Len(t, s.Endpoints, 2) - assert.Equal(t, boxedFalse, s.IsRegionalized) -} - -func TestUnmarshalEndpoints(t *testing.T) { - var inputs = []byte(` -{ - "aws-global": { - "hostname": "cloudfront.amazonaws.com", - "protocols": [ - "http", - "https" - ], - "signatureVersions": [ "v4" ], - "credentialScope": { - "region": "us-east-1", - "service": "serviceName" - }, - "sslCommonName": "commonName" - }, - "us-east-1": {} -}`) - - es := endpoints{} - err := json.Unmarshal(inputs, &es) - assert.NoError(t, err) - - assert.Len(t, es, 2) - s, ok := es["aws-global"] - assert.True(t, ok) - assert.Equal(t, "cloudfront.amazonaws.com", s.Hostname) - assert.Equal(t, []string{"http", "https"}, s.Protocols) - assert.Equal(t, []string{"v4"}, s.SignatureVersions) - assert.Equal(t, credentialScope{"us-east-1", "serviceName"}, s.CredentialScope) - assert.Equal(t, "commonName", s.SSLCommonName) -} - -func TestEndpointResolve(t *testing.T) { - defs := []endpoint{ - { - Hostname: "{service}.{region}.{dnsSuffix}", - SignatureVersions: []string{"v2"}, - SSLCommonName: "sslCommonName", - }, - { - Hostname: "other-hostname", - Protocols: []string{"http"}, - CredentialScope: credentialScope{ - Region: "signing_region", - Service: "signing_service", - }, - }, - } - - e := endpoint{ - Hostname: "{service}.{region}.{dnsSuffix}", - Protocols: []string{"http", "https"}, - SignatureVersions: []string{"v4"}, - SSLCommonName: "new sslCommonName", - } - - resolved := e.resolve("service", "region", "dnsSuffix", - defs, Options{}, - ) - - assert.Equal(t, "https://service.region.dnsSuffix", resolved.URL) - assert.Equal(t, "signing_service", resolved.SigningName) - assert.Equal(t, "signing_region", resolved.SigningRegion) - assert.Equal(t, "v4", resolved.SigningMethod) -} - -func TestEndpointMergeIn(t *testing.T) { - expected := endpoint{ - Hostname: "other hostname", - Protocols: []string{"http"}, - SignatureVersions: []string{"v4"}, - SSLCommonName: "ssl common name", - CredentialScope: credentialScope{ - Region: "region", - Service: "service", - }, - } - - actual := endpoint{} - actual.mergeIn(endpoint{ - Hostname: "other hostname", - Protocols: []string{"http"}, - SignatureVersions: []string{"v4"}, - SSLCommonName: "ssl common name", - CredentialScope: credentialScope{ - Region: "region", - Service: "service", - }, - }) - - assert.Equal(t, expected, actual) -} - -var testPartitions = partitions{ - partition{ - ID: "part-id", - Name: "partitionName", - DNSSuffix: "amazonaws.com", - RegionRegex: regionRegex{ - Regexp: func() *regexp.Regexp { - reg, _ := regexp.Compile("^(us|eu|ap|sa|ca)\\-\\w+\\-\\d+$") - return reg - }(), - }, - Defaults: endpoint{ - Hostname: "{service}.{region}.{dnsSuffix}", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - Regions: regions{ - "us-east-1": region{ - Description: "region description", - }, - "us-west-2": region{}, - }, - Services: services{ - "s3": service{}, - "service1": service{ - Endpoints: endpoints{ - "us-east-1": {}, - "us-west-2": { - HasDualStack: boxedTrue, - DualStackHostname: "{service}.dualstack.{region}.{dnsSuffix}", - }, - }, - }, - "service2": service{}, - "httpService": service{ - Defaults: endpoint{ - Protocols: []string{"http"}, - }, - }, - "globalService": service{ - IsRegionalized: boxedFalse, - PartitionEndpoint: "aws-global", - Endpoints: endpoints{ - "aws-global": endpoint{ - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Hostname: "globalService.amazonaws.com", - }, - }, - }, - }, - }, -} - -func TestResolveEndpoint(t *testing.T) { - resolved, err := testPartitions.EndpointFor("service2", "us-west-2") - - assert.NoError(t, err) - assert.Equal(t, "https://service2.us-west-2.amazonaws.com", resolved.URL) - assert.Equal(t, "us-west-2", resolved.SigningRegion) - assert.Equal(t, "service2", resolved.SigningName) -} - -func TestResolveEndpoint_DisableSSL(t *testing.T) { - resolved, err := testPartitions.EndpointFor("service2", "us-west-2", DisableSSLOption) - - assert.NoError(t, err) - assert.Equal(t, "http://service2.us-west-2.amazonaws.com", resolved.URL) - assert.Equal(t, "us-west-2", resolved.SigningRegion) - assert.Equal(t, "service2", resolved.SigningName) -} - -func TestResolveEndpoint_UseDualStack(t *testing.T) { - resolved, err := testPartitions.EndpointFor("service1", "us-west-2", UseDualStackOption) - - assert.NoError(t, err) - assert.Equal(t, "https://service1.dualstack.us-west-2.amazonaws.com", resolved.URL) - assert.Equal(t, "us-west-2", resolved.SigningRegion) - assert.Equal(t, "service1", resolved.SigningName) -} - -func TestResolveEndpoint_HTTPProtocol(t *testing.T) { - resolved, err := testPartitions.EndpointFor("httpService", "us-west-2") - - assert.NoError(t, err) - assert.Equal(t, "http://httpService.us-west-2.amazonaws.com", resolved.URL) - assert.Equal(t, "us-west-2", resolved.SigningRegion) - assert.Equal(t, "httpService", resolved.SigningName) -} - -func TestResolveEndpoint_UnknownService(t *testing.T) { - _, err := testPartitions.EndpointFor("unknownservice", "us-west-2") - - assert.Error(t, err) - - _, ok := err.(UnknownServiceError) - assert.True(t, ok, "expect error to be UnknownServiceError") -} - -func TestResolveEndpoint_ResolveUnknownService(t *testing.T) { - resolved, err := testPartitions.EndpointFor("unknown-service", "us-region-1", - ResolveUnknownServiceOption) - - assert.NoError(t, err) - - assert.Equal(t, "https://unknown-service.us-region-1.amazonaws.com", resolved.URL) - assert.Equal(t, "us-region-1", resolved.SigningRegion) - assert.Equal(t, "unknown-service", resolved.SigningName) -} - -func TestResolveEndpoint_UnknownMatchedRegion(t *testing.T) { - resolved, err := testPartitions.EndpointFor("service2", "us-region-1") - - assert.NoError(t, err) - assert.Equal(t, "https://service2.us-region-1.amazonaws.com", resolved.URL) - assert.Equal(t, "us-region-1", resolved.SigningRegion) - assert.Equal(t, "service2", resolved.SigningName) -} - -func TestResolveEndpoint_UnknownRegion(t *testing.T) { - resolved, err := testPartitions.EndpointFor("service2", "unknownregion") - - assert.NoError(t, err) - assert.Equal(t, "https://service2.unknownregion.amazonaws.com", resolved.URL) - assert.Equal(t, "unknownregion", resolved.SigningRegion) - assert.Equal(t, "service2", resolved.SigningName) -} - -func TestResolveEndpoint_StrictPartitionUnknownEndpoint(t *testing.T) { - _, err := testPartitions[0].EndpointFor("service2", "unknownregion", StrictMatchingOption) - - assert.Error(t, err) - - _, ok := err.(UnknownEndpointError) - assert.True(t, ok, "expect error to be UnknownEndpointError") -} - -func TestResolveEndpoint_StrictPartitionsUnknownEndpoint(t *testing.T) { - _, err := testPartitions.EndpointFor("service2", "us-region-1", StrictMatchingOption) - - assert.Error(t, err) - - _, ok := err.(UnknownEndpointError) - assert.True(t, ok, "expect error to be UnknownEndpointError") -} - -func TestResolveEndpoint_NotRegionalized(t *testing.T) { - resolved, err := testPartitions.EndpointFor("globalService", "us-west-2") - - assert.NoError(t, err) - assert.Equal(t, "https://globalService.amazonaws.com", resolved.URL) - assert.Equal(t, "us-east-1", resolved.SigningRegion) - assert.Equal(t, "globalService", resolved.SigningName) -} - -func TestResolveEndpoint_AwsGlobal(t *testing.T) { - resolved, err := testPartitions.EndpointFor("globalService", "aws-global") - - assert.NoError(t, err) - assert.Equal(t, "https://globalService.amazonaws.com", resolved.URL) - assert.Equal(t, "us-east-1", resolved.SigningRegion) - assert.Equal(t, "globalService", resolved.SigningName) -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/connection_reset_error_other_test.go b/vendor/github.com/aws/aws-sdk-go/aws/request/connection_reset_error_other_test.go deleted file mode 100644 index aba8eb4e8..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/connection_reset_error_other_test.go +++ /dev/null @@ -1,9 +0,0 @@ -// +build appengine plan9 - -package request_test - -import ( - "errors" -) - -var stubConnectionResetError = errors.New("connection reset") diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/connection_reset_error_test.go b/vendor/github.com/aws/aws-sdk-go/aws/request/connection_reset_error_test.go deleted file mode 100644 index bb5f6bddc..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/connection_reset_error_test.go +++ /dev/null @@ -1,11 +0,0 @@ -// +build !appengine,!plan9 - -package request_test - -import ( - "net" - "os" - "syscall" -) - -var stubConnectionResetError = &net.OpError{Err: &os.SyscallError{Syscall: "read", Err: syscall.ECONNRESET}} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/handlers_test.go b/vendor/github.com/aws/aws-sdk-go/aws/request/handlers_test.go deleted file mode 100644 index b2da558d6..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/handlers_test.go +++ /dev/null @@ -1,266 +0,0 @@ -package request_test - -import ( - "reflect" - "testing" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/awstesting/unit" - "github.com/aws/aws-sdk-go/service/s3" -) - -func TestHandlerList(t *testing.T) { - s := "" - r := &request.Request{} - l := request.HandlerList{} - l.PushBack(func(r *request.Request) { - s += "a" - r.Data = s - }) - l.Run(r) - if e, a := "a", s; e != a { - t.Errorf("expect %q update got %q", e, a) - } - if e, a := "a", r.Data.(string); e != a { - t.Errorf("expect %q data update got %q", e, a) - } -} - -func TestMultipleHandlers(t *testing.T) { - r := &request.Request{} - l := request.HandlerList{} - l.PushBack(func(r *request.Request) { r.Data = nil }) - l.PushFront(func(r *request.Request) { r.Data = aws.Bool(true) }) - l.Run(r) - if r.Data != nil { - t.Error("Expected handler to execute") - } -} - -func TestNamedHandlers(t *testing.T) { - l := request.HandlerList{} - named := request.NamedHandler{Name: "Name", Fn: func(r *request.Request) {}} - named2 := request.NamedHandler{Name: "NotName", Fn: func(r *request.Request) {}} - l.PushBackNamed(named) - l.PushBackNamed(named) - l.PushBackNamed(named2) - l.PushBack(func(r *request.Request) {}) - if e, a := 4, l.Len(); e != a { - t.Errorf("expect %d list length, got %d", e, a) - } - l.Remove(named) - if e, a := 2, l.Len(); e != a { - t.Errorf("expect %d list length, got %d", e, a) - } -} - -func TestSwapHandlers(t *testing.T) { - firstHandlerCalled := 0 - swappedOutHandlerCalled := 0 - swappedInHandlerCalled := 0 - - l := request.HandlerList{} - named := request.NamedHandler{Name: "Name", Fn: func(r *request.Request) { - firstHandlerCalled++ - }} - named2 := request.NamedHandler{Name: "SwapOutName", Fn: func(r *request.Request) { - swappedOutHandlerCalled++ - }} - l.PushBackNamed(named) - l.PushBackNamed(named2) - l.PushBackNamed(named) - - l.SwapNamed(request.NamedHandler{Name: "SwapOutName", Fn: func(r *request.Request) { - swappedInHandlerCalled++ - }}) - - l.Run(&request.Request{}) - - if e, a := 2, firstHandlerCalled; e != a { - t.Errorf("expect first handler to be called %d, was called %d times", e, a) - } - if n := swappedOutHandlerCalled; n != 0 { - t.Errorf("expect swapped out handler to not be called, was called %d times", n) - } - if e, a := 1, swappedInHandlerCalled; e != a { - t.Errorf("expect swapped in handler to be called %d, was called %d times", e, a) - } -} - -func TestSetBackNamed_Exists(t *testing.T) { - firstHandlerCalled := 0 - swappedOutHandlerCalled := 0 - swappedInHandlerCalled := 0 - - l := request.HandlerList{} - named := request.NamedHandler{Name: "Name", Fn: func(r *request.Request) { - firstHandlerCalled++ - }} - named2 := request.NamedHandler{Name: "SwapOutName", Fn: func(r *request.Request) { - swappedOutHandlerCalled++ - }} - l.PushBackNamed(named) - l.PushBackNamed(named2) - - l.SetBackNamed(request.NamedHandler{Name: "SwapOutName", Fn: func(r *request.Request) { - swappedInHandlerCalled++ - }}) - - l.Run(&request.Request{}) - - if e, a := 1, firstHandlerCalled; e != a { - t.Errorf("expect first handler to be called %d, was called %d times", e, a) - } - if n := swappedOutHandlerCalled; n != 0 { - t.Errorf("expect swapped out handler to not be called, was called %d times", n) - } - if e, a := 1, swappedInHandlerCalled; e != a { - t.Errorf("expect swapped in handler to be called %d, was called %d times", e, a) - } -} - -func TestSetBackNamed_NotExists(t *testing.T) { - firstHandlerCalled := 0 - secondHandlerCalled := 0 - swappedInHandlerCalled := 0 - - l := request.HandlerList{} - named := request.NamedHandler{Name: "Name", Fn: func(r *request.Request) { - firstHandlerCalled++ - }} - named2 := request.NamedHandler{Name: "OtherName", Fn: func(r *request.Request) { - secondHandlerCalled++ - }} - l.PushBackNamed(named) - l.PushBackNamed(named2) - - l.SetBackNamed(request.NamedHandler{Name: "SwapOutName", Fn: func(r *request.Request) { - swappedInHandlerCalled++ - }}) - - l.Run(&request.Request{}) - - if e, a := 1, firstHandlerCalled; e != a { - t.Errorf("expect first handler to be called %d, was called %d times", e, a) - } - if e, a := 1, secondHandlerCalled; e != a { - t.Errorf("expect second handler to be called %d, was called %d times", e, a) - } - if e, a := 1, swappedInHandlerCalled; e != a { - t.Errorf("expect swapped in handler to be called %d, was called %d times", e, a) - } -} - -func TestLoggedHandlers(t *testing.T) { - expectedHandlers := []string{"name1", "name2"} - l := request.HandlerList{} - loggedHandlers := []string{} - l.AfterEachFn = request.HandlerListLogItem - cfg := aws.Config{Logger: aws.LoggerFunc(func(args ...interface{}) { - loggedHandlers = append(loggedHandlers, args[2].(string)) - })} - - named1 := request.NamedHandler{Name: "name1", Fn: func(r *request.Request) {}} - named2 := request.NamedHandler{Name: "name2", Fn: func(r *request.Request) {}} - l.PushBackNamed(named1) - l.PushBackNamed(named2) - l.Run(&request.Request{Config: cfg}) - - if !reflect.DeepEqual(expectedHandlers, loggedHandlers) { - t.Errorf("expect handlers executed %v to match logged handlers, %v", - expectedHandlers, loggedHandlers) - } -} - -func TestStopHandlers(t *testing.T) { - l := request.HandlerList{} - stopAt := 1 - l.AfterEachFn = func(item request.HandlerListRunItem) bool { - return item.Index != stopAt - } - - called := 0 - l.PushBackNamed(request.NamedHandler{Name: "name1", Fn: func(r *request.Request) { - called++ - }}) - l.PushBackNamed(request.NamedHandler{Name: "name2", Fn: func(r *request.Request) { - called++ - }}) - l.PushBackNamed(request.NamedHandler{Name: "name3", Fn: func(r *request.Request) { - t.Fatalf("third handler should not be called") - }}) - l.Run(&request.Request{}) - - if e, a := 2, called; e != a { - t.Errorf("expect %d handlers called, got %d", e, a) - } -} - -func BenchmarkNewRequest(b *testing.B) { - svc := s3.New(unit.Session) - - for i := 0; i < b.N; i++ { - r, _ := svc.GetObjectRequest(nil) - if r == nil { - b.Fatal("r should not be nil") - } - } -} - -func BenchmarkHandlersCopy(b *testing.B) { - handlers := request.Handlers{} - - handlers.Validate.PushBack(func(r *request.Request) {}) - handlers.Validate.PushBack(func(r *request.Request) {}) - handlers.Build.PushBack(func(r *request.Request) {}) - handlers.Build.PushBack(func(r *request.Request) {}) - handlers.Send.PushBack(func(r *request.Request) {}) - handlers.Send.PushBack(func(r *request.Request) {}) - handlers.Unmarshal.PushBack(func(r *request.Request) {}) - handlers.Unmarshal.PushBack(func(r *request.Request) {}) - - for i := 0; i < b.N; i++ { - h := handlers.Copy() - if e, a := handlers.Validate.Len(), h.Validate.Len(); e != a { - b.Fatalf("expected %d handlers got %d", e, a) - } - } -} - -func BenchmarkHandlersPushBack(b *testing.B) { - handlers := request.Handlers{} - - for i := 0; i < b.N; i++ { - h := handlers.Copy() - h.Validate.PushBack(func(r *request.Request) {}) - h.Validate.PushBack(func(r *request.Request) {}) - h.Validate.PushBack(func(r *request.Request) {}) - h.Validate.PushBack(func(r *request.Request) {}) - } -} - -func BenchmarkHandlersPushFront(b *testing.B) { - handlers := request.Handlers{} - - for i := 0; i < b.N; i++ { - h := handlers.Copy() - h.Validate.PushFront(func(r *request.Request) {}) - h.Validate.PushFront(func(r *request.Request) {}) - h.Validate.PushFront(func(r *request.Request) {}) - h.Validate.PushFront(func(r *request.Request) {}) - } -} - -func BenchmarkHandlersClear(b *testing.B) { - handlers := request.Handlers{} - - for i := 0; i < b.N; i++ { - h := handlers.Copy() - h.Validate.PushFront(func(r *request.Request) {}) - h.Validate.PushFront(func(r *request.Request) {}) - h.Validate.PushFront(func(r *request.Request) {}) - h.Validate.PushFront(func(r *request.Request) {}) - h.Clear() - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/http_request_copy_test.go b/vendor/github.com/aws/aws-sdk-go/aws/request/http_request_copy_test.go deleted file mode 100644 index 4a4f8550b..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/http_request_copy_test.go +++ /dev/null @@ -1,34 +0,0 @@ -package request - -import ( - "bytes" - "io/ioutil" - "net/http" - "net/url" - "sync" - "testing" -) - -func TestRequestCopyRace(t *testing.T) { - origReq := &http.Request{URL: &url.URL{}, Header: http.Header{}} - origReq.Header.Set("Header", "OrigValue") - - var wg sync.WaitGroup - for i := 0; i < 100; i++ { - wg.Add(1) - go func() { - req := copyHTTPRequest(origReq, ioutil.NopCloser(&bytes.Buffer{})) - req.Header.Set("Header", "Value") - go func() { - req2 := copyHTTPRequest(req, ioutil.NopCloser(&bytes.Buffer{})) - req2.Header.Add("Header", "Value2") - }() - _ = req.Header.Get("Header") - wg.Done() - }() - _ = origReq.Header.Get("Header") - } - origReq.Header.Get("Header") - - wg.Wait() -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/http_request_retry_test.go b/vendor/github.com/aws/aws-sdk-go/aws/request/http_request_retry_test.go deleted file mode 100644 index 2ce9ef4c3..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/http_request_retry_test.go +++ /dev/null @@ -1,37 +0,0 @@ -// +build go1.5 - -package request_test - -import ( - "errors" - "strings" - "testing" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/awstesting/mock" - "github.com/stretchr/testify/assert" -) - -func TestRequestCancelRetry(t *testing.T) { - c := make(chan struct{}) - - reqNum := 0 - s := mock.NewMockClient(aws.NewConfig().WithMaxRetries(10)) - s.Handlers.Validate.Clear() - s.Handlers.Unmarshal.Clear() - s.Handlers.UnmarshalMeta.Clear() - s.Handlers.UnmarshalError.Clear() - s.Handlers.Send.PushFront(func(r *request.Request) { - reqNum++ - r.Error = errors.New("net/http: request canceled") - }) - out := &testData{} - r := s.NewRequest(&request.Operation{Name: "Operation"}, nil, out) - r.HTTPRequest.Cancel = c - close(c) - - err := r.Send() - assert.True(t, strings.Contains(err.Error(), "canceled")) - assert.Equal(t, 1, reqNum) -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/offset_reader_test.go b/vendor/github.com/aws/aws-sdk-go/aws/request/offset_reader_test.go deleted file mode 100644 index 01856e316..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/offset_reader_test.go +++ /dev/null @@ -1,139 +0,0 @@ -package request - -import ( - "bytes" - "io" - "math/rand" - "sync" - "testing" - "time" - - "github.com/stretchr/testify/assert" -) - -func TestOffsetReaderRead(t *testing.T) { - buf := []byte("testData") - reader := &offsetReader{buf: bytes.NewReader(buf)} - - tempBuf := make([]byte, len(buf)) - - n, err := reader.Read(tempBuf) - - assert.Equal(t, n, len(buf)) - assert.Nil(t, err) - assert.Equal(t, buf, tempBuf) -} - -func TestOffsetReaderSeek(t *testing.T) { - buf := []byte("testData") - reader := newOffsetReader(bytes.NewReader(buf), 0) - - orig, err := reader.Seek(0, 1) - assert.NoError(t, err) - assert.Equal(t, int64(0), orig) - - n, err := reader.Seek(0, 2) - assert.NoError(t, err) - assert.Equal(t, int64(len(buf)), n) - - n, err = reader.Seek(orig, 0) - assert.NoError(t, err) - assert.Equal(t, int64(0), n) -} - -func TestOffsetReaderClose(t *testing.T) { - buf := []byte("testData") - reader := &offsetReader{buf: bytes.NewReader(buf)} - - err := reader.Close() - assert.Nil(t, err) - - tempBuf := make([]byte, len(buf)) - n, err := reader.Read(tempBuf) - assert.Equal(t, n, 0) - assert.Equal(t, err, io.EOF) -} - -func TestOffsetReaderCloseAndCopy(t *testing.T) { - buf := []byte("testData") - tempBuf := make([]byte, len(buf)) - reader := &offsetReader{buf: bytes.NewReader(buf)} - - newReader := reader.CloseAndCopy(0) - - n, err := reader.Read(tempBuf) - assert.Equal(t, n, 0) - assert.Equal(t, err, io.EOF) - - n, err = newReader.Read(tempBuf) - assert.Equal(t, n, len(buf)) - assert.Nil(t, err) - assert.Equal(t, buf, tempBuf) -} - -func TestOffsetReaderCloseAndCopyOffset(t *testing.T) { - buf := []byte("testData") - tempBuf := make([]byte, len(buf)) - reader := &offsetReader{buf: bytes.NewReader(buf)} - - newReader := reader.CloseAndCopy(4) - n, err := newReader.Read(tempBuf) - assert.Equal(t, n, len(buf)-4) - assert.Nil(t, err) - - expected := []byte{'D', 'a', 't', 'a', 0, 0, 0, 0} - assert.Equal(t, expected, tempBuf) -} - -func TestOffsetReaderRace(t *testing.T) { - wg := sync.WaitGroup{} - - f := func(reader *offsetReader) { - defer wg.Done() - var err error - buf := make([]byte, 1) - _, err = reader.Read(buf) - for err != io.EOF { - _, err = reader.Read(buf) - } - - } - - closeFn := func(reader *offsetReader) { - defer wg.Done() - time.Sleep(time.Duration(rand.Intn(20)+1) * time.Millisecond) - reader.Close() - } - for i := 0; i < 50; i++ { - reader := &offsetReader{buf: bytes.NewReader(make([]byte, 1024*1024))} - wg.Add(1) - go f(reader) - wg.Add(1) - go closeFn(reader) - } - wg.Wait() -} - -func BenchmarkOffsetReader(b *testing.B) { - bufSize := 1024 * 1024 * 100 - buf := make([]byte, bufSize) - reader := &offsetReader{buf: bytes.NewReader(buf)} - - tempBuf := make([]byte, 1024) - - for i := 0; i < b.N; i++ { - reader.Read(tempBuf) - } -} - -func BenchmarkBytesReader(b *testing.B) { - bufSize := 1024 * 1024 * 100 - buf := make([]byte, bufSize) - reader := bytes.NewReader(buf) - - tempBuf := make([]byte, 1024) - - for i := 0; i < b.N; i++ { - reader.Read(tempBuf) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/request_1_5_test.go b/vendor/github.com/aws/aws-sdk-go/aws/request/request_1_5_test.go deleted file mode 100644 index 91b4e7b3b..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/request_1_5_test.go +++ /dev/null @@ -1,11 +0,0 @@ -// +build !go1.6 - -package request_test - -import ( - "errors" - - "github.com/aws/aws-sdk-go/aws/awserr" -) - -var errTimeout = awserr.New("foo", "bar", errors.New("net/http: request canceled Timeout")) diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/request_1_6_test.go b/vendor/github.com/aws/aws-sdk-go/aws/request/request_1_6_test.go deleted file mode 100644 index d0314abe9..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/request_1_6_test.go +++ /dev/null @@ -1,51 +0,0 @@ -// +build go1.6 - -package request_test - -import ( - "errors" - "testing" - - "github.com/stretchr/testify/assert" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/client" - "github.com/aws/aws-sdk-go/aws/client/metadata" - "github.com/aws/aws-sdk-go/aws/defaults" - "github.com/aws/aws-sdk-go/aws/request" -) - -// go version 1.4 and 1.5 do not return an error. Version 1.5 will url encode -// the uri while 1.4 will not -func TestRequestInvalidEndpoint(t *testing.T) { - endpoint := "http://localhost:90 " - - r := request.New( - aws.Config{}, - metadata.ClientInfo{Endpoint: endpoint}, - defaults.Handlers(), - client.DefaultRetryer{}, - &request.Operation{}, - nil, - nil, - ) - - assert.Error(t, r.Error) -} - -type timeoutErr struct { - error -} - -var errTimeout = awserr.New("foo", "bar", &timeoutErr{ - errors.New("net/http: request canceled"), -}) - -func (e *timeoutErr) Timeout() bool { - return true -} - -func (e *timeoutErr) Temporary() bool { - return true -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/request_1_7_test.go b/vendor/github.com/aws/aws-sdk-go/aws/request/request_1_7_test.go deleted file mode 100644 index ca6150cb0..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/request_1_7_test.go +++ /dev/null @@ -1,24 +0,0 @@ -// +build !go1.8 - -package request - -import ( - "net/http" - "strings" - "testing" -) - -func TestResetBody_WithEmptyBody(t *testing.T) { - r := Request{ - HTTPRequest: &http.Request{}, - } - - reader := strings.NewReader("") - r.Body = reader - - r.ResetBody() - - if a, e := r.HTTPRequest.Body, (noBody{}); a != e { - t.Errorf("expected request body to be set to reader, got %#v", r.HTTPRequest.Body) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/request_1_8_test.go b/vendor/github.com/aws/aws-sdk-go/aws/request/request_1_8_test.go deleted file mode 100644 index 8f3b0f04e..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/request_1_8_test.go +++ /dev/null @@ -1,85 +0,0 @@ -// +build go1.8 - -package request_test - -import ( - "bytes" - "io" - "net/http" - "net/http/httptest" - "strings" - "testing" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/awstesting" - "github.com/aws/aws-sdk-go/awstesting/unit" -) - -func TestResetBody_WithEmptyBody(t *testing.T) { - r := request.Request{ - HTTPRequest: &http.Request{}, - } - - reader := strings.NewReader("") - r.Body = reader - - r.ResetBody() - - if a, e := r.HTTPRequest.Body, http.NoBody; a != e { - t.Errorf("expected request body to be set to reader, got %#v", - r.HTTPRequest.Body) - } -} - -func TestRequest_FollowPUTRedirects(t *testing.T) { - const bodySize = 1024 - - redirectHit := 0 - endpointHit := 0 - - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - switch r.URL.Path { - case "/redirect-me": - u := *r.URL - u.Path = "/endpoint" - w.Header().Set("Location", u.String()) - w.WriteHeader(307) - redirectHit++ - case "/endpoint": - b := bytes.Buffer{} - io.Copy(&b, r.Body) - r.Body.Close() - if e, a := bodySize, b.Len(); e != a { - t.Fatalf("expect %d body size, got %d", e, a) - } - endpointHit++ - default: - t.Fatalf("unexpected endpoint used, %q", r.URL.String()) - } - })) - - svc := awstesting.NewClient(&aws.Config{ - Region: unit.Session.Config.Region, - DisableSSL: aws.Bool(true), - Endpoint: aws.String(server.URL), - }) - - req := svc.NewRequest(&request.Operation{ - Name: "Operation", - HTTPMethod: "PUT", - HTTPPath: "/redirect-me", - }, &struct{}{}, &struct{}{}) - req.SetReaderBody(bytes.NewReader(make([]byte, bodySize))) - - err := req.Send() - if err != nil { - t.Errorf("expect no error, got %v", err) - } - if e, a := 1, redirectHit; e != a { - t.Errorf("expect %d redirect hits, got %d", e, a) - } - if e, a := 1, endpointHit; e != a { - t.Errorf("expect %d endpoint hits, got %d", e, a) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/request_context_test.go b/vendor/github.com/aws/aws-sdk-go/aws/request/request_context_test.go deleted file mode 100644 index 2af286756..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/request_context_test.go +++ /dev/null @@ -1,46 +0,0 @@ -package request_test - -import ( - "fmt" - "strings" - "testing" - - "github.com/aws/aws-sdk-go/aws/corehandlers" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/awstesting" -) - -func TestRequest_SetContext(t *testing.T) { - svc := awstesting.NewClient() - svc.Handlers.Clear() - svc.Handlers.Send.PushBackNamed(corehandlers.SendHandler) - - r := svc.NewRequest(&request.Operation{Name: "Operation"}, nil, nil) - ctx := &awstesting.FakeContext{DoneCh: make(chan struct{})} - r.SetContext(ctx) - - ctx.Error = fmt.Errorf("context canceled") - close(ctx.DoneCh) - - err := r.Send() - if err == nil { - t.Fatalf("expected error, got none") - } - - // Only check against canceled because go 1.6 will not use the context's - // Err(). - if e, a := "canceled", err.Error(); !strings.Contains(a, e) { - t.Errorf("expect %q to be in %q, but was not", e, a) - } -} - -func TestRequest_SetContextPanic(t *testing.T) { - defer func() { - if r := recover(); r == nil { - t.Fatalf("expect SetContext to panic, did not") - } - }() - r := &request.Request{} - - r.SetContext(nil) -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/request_internal_test.go b/vendor/github.com/aws/aws-sdk-go/aws/request/request_internal_test.go deleted file mode 100644 index 966f93455..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/request_internal_test.go +++ /dev/null @@ -1,27 +0,0 @@ -package request - -import ( - "testing" -) - -func TestCopy(t *testing.T) { - handlers := Handlers{} - op := &Operation{} - op.HTTPMethod = "Foo" - req := &Request{} - req.Operation = op - req.Handlers = handlers - - r := req.copy() - - if r == req { - t.Fatal("expect request pointer copy to be different") - } - if r.Operation == req.Operation { - t.Errorf("expect request operation pointer to be different") - } - - if e, a := req.Operation.HTTPMethod, r.Operation.HTTPMethod; e != a { - t.Errorf("expect %q http method, got %q", e, a) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/request_pagination_test.go b/vendor/github.com/aws/aws-sdk-go/aws/request/request_pagination_test.go deleted file mode 100644 index 73a95bad8..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/request_pagination_test.go +++ /dev/null @@ -1,604 +0,0 @@ -package request_test - -import ( - "testing" - - "github.com/stretchr/testify/assert" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/awstesting" - "github.com/aws/aws-sdk-go/awstesting/unit" - "github.com/aws/aws-sdk-go/service/dynamodb" - "github.com/aws/aws-sdk-go/service/route53" - "github.com/aws/aws-sdk-go/service/s3" -) - -// Use DynamoDB methods for simplicity -func TestPaginationQueryPage(t *testing.T) { - db := dynamodb.New(unit.Session) - tokens, pages, numPages, gotToEnd := []map[string]*dynamodb.AttributeValue{}, []map[string]*dynamodb.AttributeValue{}, 0, false - - reqNum := 0 - resps := []*dynamodb.QueryOutput{ - { - LastEvaluatedKey: map[string]*dynamodb.AttributeValue{"key": {S: aws.String("key1")}}, - Count: aws.Int64(1), - Items: []map[string]*dynamodb.AttributeValue{ - { - "key": {S: aws.String("key1")}, - }, - }, - }, - { - LastEvaluatedKey: map[string]*dynamodb.AttributeValue{"key": {S: aws.String("key2")}}, - Count: aws.Int64(1), - Items: []map[string]*dynamodb.AttributeValue{ - { - "key": {S: aws.String("key2")}, - }, - }, - }, - { - LastEvaluatedKey: map[string]*dynamodb.AttributeValue{}, - Count: aws.Int64(1), - Items: []map[string]*dynamodb.AttributeValue{ - { - "key": {S: aws.String("key3")}, - }, - }, - }, - } - - db.Handlers.Send.Clear() // mock sending - db.Handlers.Unmarshal.Clear() - db.Handlers.UnmarshalMeta.Clear() - db.Handlers.ValidateResponse.Clear() - db.Handlers.Build.PushBack(func(r *request.Request) { - in := r.Params.(*dynamodb.QueryInput) - if in == nil { - tokens = append(tokens, nil) - } else if len(in.ExclusiveStartKey) != 0 { - tokens = append(tokens, in.ExclusiveStartKey) - } - }) - db.Handlers.Unmarshal.PushBack(func(r *request.Request) { - r.Data = resps[reqNum] - reqNum++ - }) - - params := &dynamodb.QueryInput{ - Limit: aws.Int64(2), - TableName: aws.String("tablename"), - } - err := db.QueryPages(params, func(p *dynamodb.QueryOutput, last bool) bool { - numPages++ - for _, item := range p.Items { - pages = append(pages, item) - } - if last { - if gotToEnd { - assert.Fail(t, "last=true happened twice") - } - gotToEnd = true - } - return true - }) - assert.Nil(t, err) - - assert.Equal(t, - []map[string]*dynamodb.AttributeValue{ - {"key": {S: aws.String("key1")}}, - {"key": {S: aws.String("key2")}}, - }, tokens) - assert.Equal(t, - []map[string]*dynamodb.AttributeValue{ - {"key": {S: aws.String("key1")}}, - {"key": {S: aws.String("key2")}}, - {"key": {S: aws.String("key3")}}, - }, pages) - assert.Equal(t, 3, numPages) - assert.True(t, gotToEnd) - assert.Nil(t, params.ExclusiveStartKey) -} - -// Use DynamoDB methods for simplicity -func TestPagination(t *testing.T) { - db := dynamodb.New(unit.Session) - tokens, pages, numPages, gotToEnd := []string{}, []string{}, 0, false - - reqNum := 0 - resps := []*dynamodb.ListTablesOutput{ - {TableNames: []*string{aws.String("Table1"), aws.String("Table2")}, LastEvaluatedTableName: aws.String("Table2")}, - {TableNames: []*string{aws.String("Table3"), aws.String("Table4")}, LastEvaluatedTableName: aws.String("Table4")}, - {TableNames: []*string{aws.String("Table5")}}, - } - - db.Handlers.Send.Clear() // mock sending - db.Handlers.Unmarshal.Clear() - db.Handlers.UnmarshalMeta.Clear() - db.Handlers.ValidateResponse.Clear() - db.Handlers.Build.PushBack(func(r *request.Request) { - in := r.Params.(*dynamodb.ListTablesInput) - if in == nil { - tokens = append(tokens, "") - } else if in.ExclusiveStartTableName != nil { - tokens = append(tokens, *in.ExclusiveStartTableName) - } - }) - db.Handlers.Unmarshal.PushBack(func(r *request.Request) { - r.Data = resps[reqNum] - reqNum++ - }) - - params := &dynamodb.ListTablesInput{Limit: aws.Int64(2)} - err := db.ListTablesPages(params, func(p *dynamodb.ListTablesOutput, last bool) bool { - numPages++ - for _, t := range p.TableNames { - pages = append(pages, *t) - } - if last { - if gotToEnd { - assert.Fail(t, "last=true happened twice") - } - gotToEnd = true - } - return true - }) - - assert.Equal(t, []string{"Table2", "Table4"}, tokens) - assert.Equal(t, []string{"Table1", "Table2", "Table3", "Table4", "Table5"}, pages) - assert.Equal(t, 3, numPages) - assert.True(t, gotToEnd) - assert.Nil(t, err) - assert.Nil(t, params.ExclusiveStartTableName) -} - -// Use DynamoDB methods for simplicity -func TestPaginationEachPage(t *testing.T) { - db := dynamodb.New(unit.Session) - tokens, pages, numPages, gotToEnd := []string{}, []string{}, 0, false - - reqNum := 0 - resps := []*dynamodb.ListTablesOutput{ - {TableNames: []*string{aws.String("Table1"), aws.String("Table2")}, LastEvaluatedTableName: aws.String("Table2")}, - {TableNames: []*string{aws.String("Table3"), aws.String("Table4")}, LastEvaluatedTableName: aws.String("Table4")}, - {TableNames: []*string{aws.String("Table5")}}, - } - - db.Handlers.Send.Clear() // mock sending - db.Handlers.Unmarshal.Clear() - db.Handlers.UnmarshalMeta.Clear() - db.Handlers.ValidateResponse.Clear() - db.Handlers.Build.PushBack(func(r *request.Request) { - in := r.Params.(*dynamodb.ListTablesInput) - if in == nil { - tokens = append(tokens, "") - } else if in.ExclusiveStartTableName != nil { - tokens = append(tokens, *in.ExclusiveStartTableName) - } - }) - db.Handlers.Unmarshal.PushBack(func(r *request.Request) { - r.Data = resps[reqNum] - reqNum++ - }) - - params := &dynamodb.ListTablesInput{Limit: aws.Int64(2)} - req, _ := db.ListTablesRequest(params) - err := req.EachPage(func(p interface{}, last bool) bool { - numPages++ - for _, t := range p.(*dynamodb.ListTablesOutput).TableNames { - pages = append(pages, *t) - } - if last { - if gotToEnd { - assert.Fail(t, "last=true happened twice") - } - gotToEnd = true - } - - return true - }) - - assert.Equal(t, []string{"Table2", "Table4"}, tokens) - assert.Equal(t, []string{"Table1", "Table2", "Table3", "Table4", "Table5"}, pages) - assert.Equal(t, 3, numPages) - assert.True(t, gotToEnd) - assert.Nil(t, err) -} - -// Use DynamoDB methods for simplicity -func TestPaginationEarlyExit(t *testing.T) { - db := dynamodb.New(unit.Session) - numPages, gotToEnd := 0, false - - reqNum := 0 - resps := []*dynamodb.ListTablesOutput{ - {TableNames: []*string{aws.String("Table1"), aws.String("Table2")}, LastEvaluatedTableName: aws.String("Table2")}, - {TableNames: []*string{aws.String("Table3"), aws.String("Table4")}, LastEvaluatedTableName: aws.String("Table4")}, - {TableNames: []*string{aws.String("Table5")}}, - } - - db.Handlers.Send.Clear() // mock sending - db.Handlers.Unmarshal.Clear() - db.Handlers.UnmarshalMeta.Clear() - db.Handlers.ValidateResponse.Clear() - db.Handlers.Unmarshal.PushBack(func(r *request.Request) { - r.Data = resps[reqNum] - reqNum++ - }) - - params := &dynamodb.ListTablesInput{Limit: aws.Int64(2)} - err := db.ListTablesPages(params, func(p *dynamodb.ListTablesOutput, last bool) bool { - numPages++ - if numPages == 2 { - return false - } - if last { - if gotToEnd { - assert.Fail(t, "last=true happened twice") - } - gotToEnd = true - } - return true - }) - - assert.Equal(t, 2, numPages) - assert.False(t, gotToEnd) - assert.Nil(t, err) -} - -func TestSkipPagination(t *testing.T) { - client := s3.New(unit.Session) - client.Handlers.Send.Clear() // mock sending - client.Handlers.Unmarshal.Clear() - client.Handlers.UnmarshalMeta.Clear() - client.Handlers.ValidateResponse.Clear() - client.Handlers.Unmarshal.PushBack(func(r *request.Request) { - r.Data = &s3.HeadBucketOutput{} - }) - - req, _ := client.HeadBucketRequest(&s3.HeadBucketInput{Bucket: aws.String("bucket")}) - - numPages, gotToEnd := 0, false - req.EachPage(func(p interface{}, last bool) bool { - numPages++ - if last { - gotToEnd = true - } - return true - }) - assert.Equal(t, 1, numPages) - assert.True(t, gotToEnd) -} - -// Use S3 for simplicity -func TestPaginationTruncation(t *testing.T) { - client := s3.New(unit.Session) - - reqNum := 0 - resps := []*s3.ListObjectsOutput{ - {IsTruncated: aws.Bool(true), Contents: []*s3.Object{{Key: aws.String("Key1")}}}, - {IsTruncated: aws.Bool(true), Contents: []*s3.Object{{Key: aws.String("Key2")}}}, - {IsTruncated: aws.Bool(false), Contents: []*s3.Object{{Key: aws.String("Key3")}}}, - {IsTruncated: aws.Bool(true), Contents: []*s3.Object{{Key: aws.String("Key4")}}}, - } - - client.Handlers.Send.Clear() // mock sending - client.Handlers.Unmarshal.Clear() - client.Handlers.UnmarshalMeta.Clear() - client.Handlers.ValidateResponse.Clear() - client.Handlers.Unmarshal.PushBack(func(r *request.Request) { - r.Data = resps[reqNum] - reqNum++ - }) - - params := &s3.ListObjectsInput{Bucket: aws.String("bucket")} - - results := []string{} - err := client.ListObjectsPages(params, func(p *s3.ListObjectsOutput, last bool) bool { - results = append(results, *p.Contents[0].Key) - return true - }) - - assert.Equal(t, []string{"Key1", "Key2", "Key3"}, results) - assert.Nil(t, err) - - // Try again without truncation token at all - reqNum = 0 - resps[1].IsTruncated = nil - resps[2].IsTruncated = aws.Bool(true) - results = []string{} - err = client.ListObjectsPages(params, func(p *s3.ListObjectsOutput, last bool) bool { - results = append(results, *p.Contents[0].Key) - return true - }) - - assert.Equal(t, []string{"Key1", "Key2"}, results) - assert.Nil(t, err) -} - -func TestPaginationNilToken(t *testing.T) { - client := route53.New(unit.Session) - - reqNum := 0 - resps := []*route53.ListResourceRecordSetsOutput{ - { - ResourceRecordSets: []*route53.ResourceRecordSet{ - {Name: aws.String("first.example.com.")}, - }, - IsTruncated: aws.Bool(true), - NextRecordName: aws.String("second.example.com."), - NextRecordType: aws.String("MX"), - NextRecordIdentifier: aws.String("second"), - MaxItems: aws.String("1"), - }, - { - ResourceRecordSets: []*route53.ResourceRecordSet{ - {Name: aws.String("second.example.com.")}, - }, - IsTruncated: aws.Bool(true), - NextRecordName: aws.String("third.example.com."), - NextRecordType: aws.String("MX"), - MaxItems: aws.String("1"), - }, - { - ResourceRecordSets: []*route53.ResourceRecordSet{ - {Name: aws.String("third.example.com.")}, - }, - IsTruncated: aws.Bool(false), - MaxItems: aws.String("1"), - }, - } - client.Handlers.Send.Clear() // mock sending - client.Handlers.Unmarshal.Clear() - client.Handlers.UnmarshalMeta.Clear() - client.Handlers.ValidateResponse.Clear() - - idents := []string{} - client.Handlers.Build.PushBack(func(r *request.Request) { - p := r.Params.(*route53.ListResourceRecordSetsInput) - idents = append(idents, aws.StringValue(p.StartRecordIdentifier)) - - }) - client.Handlers.Unmarshal.PushBack(func(r *request.Request) { - r.Data = resps[reqNum] - reqNum++ - }) - - params := &route53.ListResourceRecordSetsInput{ - HostedZoneId: aws.String("id-zone"), - } - - results := []string{} - err := client.ListResourceRecordSetsPages(params, func(p *route53.ListResourceRecordSetsOutput, last bool) bool { - results = append(results, *p.ResourceRecordSets[0].Name) - return true - }) - - assert.NoError(t, err) - assert.Equal(t, []string{"", "second", ""}, idents) - assert.Equal(t, []string{"first.example.com.", "second.example.com.", "third.example.com."}, results) -} - -func TestPaginationNilInput(t *testing.T) { - // Code generation doesn't have a great way to verify the code is correct - // other than being run via unit tests in the SDK. This should be fixed - // So code generation can be validated independently. - - client := s3.New(unit.Session) - client.Handlers.Validate.Clear() - client.Handlers.Send.Clear() // mock sending - client.Handlers.Unmarshal.Clear() - client.Handlers.UnmarshalMeta.Clear() - client.Handlers.ValidateResponse.Clear() - client.Handlers.Unmarshal.PushBack(func(r *request.Request) { - r.Data = &s3.ListObjectsOutput{} - }) - - gotToEnd := false - numPages := 0 - err := client.ListObjectsPages(nil, func(p *s3.ListObjectsOutput, last bool) bool { - numPages++ - if last { - gotToEnd = true - } - return true - }) - - if err != nil { - t.Fatalf("expect no error, but got %v", err) - } - if e, a := 1, numPages; e != a { - t.Errorf("expect %d number pages but got %d", e, a) - } - if !gotToEnd { - t.Errorf("expect to of gotten to end, did not") - } -} - -func TestPaginationWithContextNilInput(t *testing.T) { - // Code generation doesn't have a great way to verify the code is correct - // other than being run via unit tests in the SDK. This should be fixed - // So code generation can be validated independently. - - client := s3.New(unit.Session) - client.Handlers.Validate.Clear() - client.Handlers.Send.Clear() // mock sending - client.Handlers.Unmarshal.Clear() - client.Handlers.UnmarshalMeta.Clear() - client.Handlers.ValidateResponse.Clear() - client.Handlers.Unmarshal.PushBack(func(r *request.Request) { - r.Data = &s3.ListObjectsOutput{} - }) - - gotToEnd := false - numPages := 0 - ctx := &awstesting.FakeContext{DoneCh: make(chan struct{})} - err := client.ListObjectsPagesWithContext(ctx, nil, func(p *s3.ListObjectsOutput, last bool) bool { - numPages++ - if last { - gotToEnd = true - } - return true - }) - - if err != nil { - t.Fatalf("expect no error, but got %v", err) - } - if e, a := 1, numPages; e != a { - t.Errorf("expect %d number pages but got %d", e, a) - } - if !gotToEnd { - t.Errorf("expect to of gotten to end, did not") - } -} - -type testPageInput struct { - NextToken string -} -type testPageOutput struct { - Value string - NextToken *string -} - -func TestPagination_Standalone(t *testing.T) { - expect := []struct { - Value, PrevToken, NextToken string - }{ - {"FirstValue", "InitalToken", "FirstToken"}, - {"SecondValue", "FirstToken", "SecondToken"}, - {"ThirdValue", "SecondToken", ""}, - } - input := testPageInput{ - NextToken: expect[0].PrevToken, - } - - c := awstesting.NewClient() - i := 0 - p := request.Pagination{ - NewRequest: func() (*request.Request, error) { - r := c.NewRequest( - &request.Operation{ - Name: "Operation", - Paginator: &request.Paginator{ - InputTokens: []string{"NextToken"}, - OutputTokens: []string{"NextToken"}, - }, - }, - &input, &testPageOutput{}, - ) - // Setup handlers for testing - r.Handlers.Clear() - r.Handlers.Build.PushBack(func(req *request.Request) { - in := req.Params.(*testPageInput) - if e, a := expect[i].PrevToken, in.NextToken; e != a { - t.Errorf("%d, expect NextToken input %q, got %q", i, e, a) - } - }) - r.Handlers.Unmarshal.PushBack(func(req *request.Request) { - out := &testPageOutput{ - Value: expect[i].Value, - } - if len(expect[i].NextToken) > 0 { - out.NextToken = aws.String(expect[i].NextToken) - } - req.Data = out - }) - return r, nil - }, - } - - for p.Next() { - data := p.Page().(*testPageOutput) - - if e, a := expect[i].Value, data.Value; e != a { - t.Errorf("%d, expect Value to be %q, got %q", i, e, a) - } - if e, a := expect[i].NextToken, aws.StringValue(data.NextToken); e != a { - t.Errorf("%d, expect NextToken to be %q, got %q", i, e, a) - } - - i++ - } - if e, a := len(expect), i; e != a { - t.Errorf("expected to process %d pages, did %d", e, a) - } - if err := p.Err(); err != nil { - t.Fatalf("%d, expected no error, got %v", i, err) - } -} - -// Benchmarks -var benchResps = []*dynamodb.ListTablesOutput{ - {TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")}, - {TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")}, - {TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")}, - {TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")}, - {TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")}, - {TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")}, - {TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")}, - {TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")}, - {TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")}, - {TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")}, - {TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")}, - {TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")}, - {TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")}, - {TableNames: []*string{aws.String("TABLE")}}, -} - -var benchDb = func() *dynamodb.DynamoDB { - db := dynamodb.New(unit.Session) - db.Handlers.Send.Clear() // mock sending - db.Handlers.Unmarshal.Clear() - db.Handlers.UnmarshalMeta.Clear() - db.Handlers.ValidateResponse.Clear() - return db -} - -func BenchmarkCodegenIterator(b *testing.B) { - reqNum := 0 - db := benchDb() - db.Handlers.Unmarshal.PushBack(func(r *request.Request) { - r.Data = benchResps[reqNum] - reqNum++ - }) - - input := &dynamodb.ListTablesInput{Limit: aws.Int64(2)} - iter := func(fn func(*dynamodb.ListTablesOutput, bool) bool) error { - page, _ := db.ListTablesRequest(input) - for ; page != nil; page = page.NextPage() { - page.Send() - out := page.Data.(*dynamodb.ListTablesOutput) - if result := fn(out, !page.HasNextPage()); page.Error != nil || !result { - return page.Error - } - } - return nil - } - - for i := 0; i < b.N; i++ { - reqNum = 0 - iter(func(p *dynamodb.ListTablesOutput, last bool) bool { - return true - }) - } -} - -func BenchmarkEachPageIterator(b *testing.B) { - reqNum := 0 - db := benchDb() - db.Handlers.Unmarshal.PushBack(func(r *request.Request) { - r.Data = benchResps[reqNum] - reqNum++ - }) - - input := &dynamodb.ListTablesInput{Limit: aws.Int64(2)} - for i := 0; i < b.N; i++ { - reqNum = 0 - req, _ := db.ListTablesRequest(input) - req.EachPage(func(p interface{}, last bool) bool { - return true - }) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/request_resetbody_test.go b/vendor/github.com/aws/aws-sdk-go/aws/request/request_resetbody_test.go deleted file mode 100644 index 4a9172480..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/request_resetbody_test.go +++ /dev/null @@ -1,58 +0,0 @@ -package request - -import ( - "bytes" - "net/http" - "strings" - "testing" - - "github.com/aws/aws-sdk-go/aws" -) - -func TestResetBody_WithBodyContents(t *testing.T) { - r := Request{ - HTTPRequest: &http.Request{}, - } - - reader := strings.NewReader("abc") - r.Body = reader - - r.ResetBody() - - if v, ok := r.HTTPRequest.Body.(*offsetReader); !ok || v == nil { - t.Errorf("expected request body to be set to reader, got %#v", - r.HTTPRequest.Body) - } -} - -func TestResetBody_ExcludeUnseekableBodyByMethod(t *testing.T) { - cases := []struct { - Method string - IsNoBody bool - }{ - {"GET", true}, - {"HEAD", true}, - {"DELETE", true}, - {"PUT", false}, - {"PATCH", false}, - {"POST", false}, - } - - reader := aws.ReadSeekCloser(bytes.NewBuffer([]byte("abc"))) - - for i, c := range cases { - r := Request{ - HTTPRequest: &http.Request{}, - Operation: &Operation{ - HTTPMethod: c.Method, - }, - } - - r.SetReaderBody(reader) - - if a, e := r.HTTPRequest.Body == NoBody, c.IsNoBody; a != e { - t.Errorf("%d, expect body to be set to noBody(%t), but was %t", i, e, a) - } - } - -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/request_test.go b/vendor/github.com/aws/aws-sdk-go/aws/request/request_test.go deleted file mode 100644 index 4d9258c0a..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/request_test.go +++ /dev/null @@ -1,844 +0,0 @@ -package request_test - -import ( - "bytes" - "encoding/json" - "fmt" - "io" - "io/ioutil" - "net/http" - "net/http/httptest" - "reflect" - "runtime" - "strconv" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/client" - "github.com/aws/aws-sdk-go/aws/client/metadata" - "github.com/aws/aws-sdk-go/aws/corehandlers" - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/aws/signer/v4" - "github.com/aws/aws-sdk-go/awstesting" - "github.com/aws/aws-sdk-go/awstesting/unit" - "github.com/aws/aws-sdk-go/private/protocol/jsonrpc" - "github.com/aws/aws-sdk-go/private/protocol/rest" -) - -type testData struct { - Data string -} - -func body(str string) io.ReadCloser { - return ioutil.NopCloser(bytes.NewReader([]byte(str))) -} - -func unmarshal(req *request.Request) { - defer req.HTTPResponse.Body.Close() - if req.Data != nil { - json.NewDecoder(req.HTTPResponse.Body).Decode(req.Data) - } - return -} - -func unmarshalError(req *request.Request) { - bodyBytes, err := ioutil.ReadAll(req.HTTPResponse.Body) - if err != nil { - req.Error = awserr.New("UnmarshaleError", req.HTTPResponse.Status, err) - return - } - if len(bodyBytes) == 0 { - req.Error = awserr.NewRequestFailure( - awserr.New("UnmarshaleError", req.HTTPResponse.Status, fmt.Errorf("empty body")), - req.HTTPResponse.StatusCode, - "", - ) - return - } - var jsonErr jsonErrorResponse - if err := json.Unmarshal(bodyBytes, &jsonErr); err != nil { - req.Error = awserr.New("UnmarshaleError", "JSON unmarshal", err) - return - } - req.Error = awserr.NewRequestFailure( - awserr.New(jsonErr.Code, jsonErr.Message, nil), - req.HTTPResponse.StatusCode, - "", - ) -} - -type jsonErrorResponse struct { - Code string `json:"__type"` - Message string `json:"message"` -} - -// test that retries occur for 5xx status codes -func TestRequestRecoverRetry5xx(t *testing.T) { - reqNum := 0 - reqs := []http.Response{ - {StatusCode: 500, Body: body(`{"__type":"UnknownError","message":"An error occurred."}`)}, - {StatusCode: 501, Body: body(`{"__type":"UnknownError","message":"An error occurred."}`)}, - {StatusCode: 200, Body: body(`{"data":"valid"}`)}, - } - - s := awstesting.NewClient(aws.NewConfig().WithMaxRetries(10)) - s.Handlers.Validate.Clear() - s.Handlers.Unmarshal.PushBack(unmarshal) - s.Handlers.UnmarshalError.PushBack(unmarshalError) - s.Handlers.Send.Clear() // mock sending - s.Handlers.Send.PushBack(func(r *request.Request) { - r.HTTPResponse = &reqs[reqNum] - reqNum++ - }) - out := &testData{} - r := s.NewRequest(&request.Operation{Name: "Operation"}, nil, out) - err := r.Send() - if err != nil { - t.Fatalf("expect no error, but got %v", err) - } - if e, a := 2, int(r.RetryCount); e != a { - t.Errorf("expect %d retry count, got %d", e, a) - } - if e, a := "valid", out.Data; e != a { - t.Errorf("expect %q output got %q", e, a) - } -} - -// test that retries occur for 4xx status codes with a response type that can be retried - see `shouldRetry` -func TestRequestRecoverRetry4xxRetryable(t *testing.T) { - reqNum := 0 - reqs := []http.Response{ - {StatusCode: 400, Body: body(`{"__type":"Throttling","message":"Rate exceeded."}`)}, - {StatusCode: 429, Body: body(`{"__type":"ProvisionedThroughputExceededException","message":"Rate exceeded."}`)}, - {StatusCode: 200, Body: body(`{"data":"valid"}`)}, - } - - s := awstesting.NewClient(aws.NewConfig().WithMaxRetries(10)) - s.Handlers.Validate.Clear() - s.Handlers.Unmarshal.PushBack(unmarshal) - s.Handlers.UnmarshalError.PushBack(unmarshalError) - s.Handlers.Send.Clear() // mock sending - s.Handlers.Send.PushBack(func(r *request.Request) { - r.HTTPResponse = &reqs[reqNum] - reqNum++ - }) - out := &testData{} - r := s.NewRequest(&request.Operation{Name: "Operation"}, nil, out) - err := r.Send() - if err != nil { - t.Fatalf("expect no error, but got %v", err) - } - if e, a := 2, int(r.RetryCount); e != a { - t.Errorf("expect %d retry count, got %d", e, a) - } - if e, a := "valid", out.Data; e != a { - t.Errorf("expect %q output got %q", e, a) - } -} - -// test that retries don't occur for 4xx status codes with a response type that can't be retried -func TestRequest4xxUnretryable(t *testing.T) { - s := awstesting.NewClient(aws.NewConfig().WithMaxRetries(10)) - s.Handlers.Validate.Clear() - s.Handlers.Unmarshal.PushBack(unmarshal) - s.Handlers.UnmarshalError.PushBack(unmarshalError) - s.Handlers.Send.Clear() // mock sending - s.Handlers.Send.PushBack(func(r *request.Request) { - r.HTTPResponse = &http.Response{StatusCode: 401, Body: body(`{"__type":"SignatureDoesNotMatch","message":"Signature does not match."}`)} - }) - out := &testData{} - r := s.NewRequest(&request.Operation{Name: "Operation"}, nil, out) - err := r.Send() - if err == nil { - t.Fatalf("expect error, but did not get one") - } - aerr := err.(awserr.RequestFailure) - if e, a := 401, aerr.StatusCode(); e != a { - t.Errorf("expect %d status code, got %d", e, a) - } - if e, a := "SignatureDoesNotMatch", aerr.Code(); e != a { - t.Errorf("expect %q error code, got %q", e, a) - } - if e, a := "Signature does not match.", aerr.Message(); e != a { - t.Errorf("expect %q error message, got %q", e, a) - } - if e, a := 0, int(r.RetryCount); e != a { - t.Errorf("expect %d retry count, got %d", e, a) - } -} - -func TestRequestExhaustRetries(t *testing.T) { - delays := []time.Duration{} - sleepDelay := func(delay time.Duration) { - delays = append(delays, delay) - } - - reqNum := 0 - reqs := []http.Response{ - {StatusCode: 500, Body: body(`{"__type":"UnknownError","message":"An error occurred."}`)}, - {StatusCode: 500, Body: body(`{"__type":"UnknownError","message":"An error occurred."}`)}, - {StatusCode: 500, Body: body(`{"__type":"UnknownError","message":"An error occurred."}`)}, - {StatusCode: 500, Body: body(`{"__type":"UnknownError","message":"An error occurred."}`)}, - } - - s := awstesting.NewClient(aws.NewConfig().WithSleepDelay(sleepDelay)) - s.Handlers.Validate.Clear() - s.Handlers.Unmarshal.PushBack(unmarshal) - s.Handlers.UnmarshalError.PushBack(unmarshalError) - s.Handlers.Send.Clear() // mock sending - s.Handlers.Send.PushBack(func(r *request.Request) { - r.HTTPResponse = &reqs[reqNum] - reqNum++ - }) - r := s.NewRequest(&request.Operation{Name: "Operation"}, nil, nil) - err := r.Send() - if err == nil { - t.Fatalf("expect error, but did not get one") - } - aerr := err.(awserr.RequestFailure) - if e, a := 500, aerr.StatusCode(); e != a { - t.Errorf("expect %d status code, got %d", e, a) - } - if e, a := "UnknownError", aerr.Code(); e != a { - t.Errorf("expect %q error code, got %q", e, a) - } - if e, a := "An error occurred.", aerr.Message(); e != a { - t.Errorf("expect %q error message, got %q", e, a) - } - if e, a := 3, int(r.RetryCount); e != a { - t.Errorf("expect %d retry count, got %d", e, a) - } - - expectDelays := []struct{ min, max time.Duration }{{30, 59}, {60, 118}, {120, 236}} - for i, v := range delays { - min := expectDelays[i].min * time.Millisecond - max := expectDelays[i].max * time.Millisecond - if !(min <= v && v <= max) { - t.Errorf("Expect delay to be within range, i:%d, v:%s, min:%s, max:%s", - i, v, min, max) - } - } -} - -// test that the request is retried after the credentials are expired. -func TestRequestRecoverExpiredCreds(t *testing.T) { - reqNum := 0 - reqs := []http.Response{ - {StatusCode: 400, Body: body(`{"__type":"ExpiredTokenException","message":"expired token"}`)}, - {StatusCode: 200, Body: body(`{"data":"valid"}`)}, - } - - s := awstesting.NewClient(&aws.Config{MaxRetries: aws.Int(10), Credentials: credentials.NewStaticCredentials("AKID", "SECRET", "")}) - s.Handlers.Validate.Clear() - s.Handlers.Unmarshal.PushBack(unmarshal) - s.Handlers.UnmarshalError.PushBack(unmarshalError) - - credExpiredBeforeRetry := false - credExpiredAfterRetry := false - - s.Handlers.AfterRetry.PushBack(func(r *request.Request) { - credExpiredAfterRetry = r.Config.Credentials.IsExpired() - }) - - s.Handlers.Sign.Clear() - s.Handlers.Sign.PushBack(func(r *request.Request) { - r.Config.Credentials.Get() - }) - s.Handlers.Send.Clear() // mock sending - s.Handlers.Send.PushBack(func(r *request.Request) { - r.HTTPResponse = &reqs[reqNum] - reqNum++ - }) - out := &testData{} - r := s.NewRequest(&request.Operation{Name: "Operation"}, nil, out) - err := r.Send() - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - - if credExpiredBeforeRetry { - t.Errorf("Expect valid creds before retry check") - } - if !credExpiredAfterRetry { - t.Errorf("Expect expired creds after retry check") - } - if s.Config.Credentials.IsExpired() { - t.Errorf("Expect valid creds after cred expired recovery") - } - - if e, a := 1, int(r.RetryCount); e != a { - t.Errorf("expect %d retry count, got %d", e, a) - } - if e, a := "valid", out.Data; e != a { - t.Errorf("expect %q output got %q", e, a) - } -} - -func TestMakeAddtoUserAgentHandler(t *testing.T) { - fn := request.MakeAddToUserAgentHandler("name", "version", "extra1", "extra2") - r := &request.Request{HTTPRequest: &http.Request{Header: http.Header{}}} - r.HTTPRequest.Header.Set("User-Agent", "foo/bar") - fn(r) - - if e, a := "foo/bar name/version (extra1; extra2)", r.HTTPRequest.Header.Get("User-Agent"); e != a { - t.Errorf("expect %q user agent, got %q", e, a) - } -} - -func TestMakeAddtoUserAgentFreeFormHandler(t *testing.T) { - fn := request.MakeAddToUserAgentFreeFormHandler("name/version (extra1; extra2)") - r := &request.Request{HTTPRequest: &http.Request{Header: http.Header{}}} - r.HTTPRequest.Header.Set("User-Agent", "foo/bar") - fn(r) - - if e, a := "foo/bar name/version (extra1; extra2)", r.HTTPRequest.Header.Get("User-Agent"); e != a { - t.Errorf("expect %q user agent, got %q", e, a) - } -} - -func TestRequestUserAgent(t *testing.T) { - s := awstesting.NewClient(&aws.Config{Region: aws.String("us-east-1")}) - // s.Handlers.Validate.Clear() - - req := s.NewRequest(&request.Operation{Name: "Operation"}, nil, &testData{}) - req.HTTPRequest.Header.Set("User-Agent", "foo/bar") - if err := req.Build(); err != nil { - t.Fatalf("expect no error, got %v", err) - } - - expectUA := fmt.Sprintf("foo/bar %s/%s (%s; %s; %s)", - aws.SDKName, aws.SDKVersion, runtime.Version(), runtime.GOOS, runtime.GOARCH) - if e, a := expectUA, req.HTTPRequest.Header.Get("User-Agent"); e != a { - t.Errorf("expect %q user agent, got %q", e, a) - } -} - -func TestRequestThrottleRetries(t *testing.T) { - delays := []time.Duration{} - sleepDelay := func(delay time.Duration) { - delays = append(delays, delay) - } - - reqNum := 0 - reqs := []http.Response{ - {StatusCode: 500, Body: body(`{"__type":"Throttling","message":"An error occurred."}`)}, - {StatusCode: 500, Body: body(`{"__type":"Throttling","message":"An error occurred."}`)}, - {StatusCode: 500, Body: body(`{"__type":"Throttling","message":"An error occurred."}`)}, - {StatusCode: 500, Body: body(`{"__type":"Throttling","message":"An error occurred."}`)}, - } - - s := awstesting.NewClient(aws.NewConfig().WithSleepDelay(sleepDelay)) - s.Handlers.Validate.Clear() - s.Handlers.Unmarshal.PushBack(unmarshal) - s.Handlers.UnmarshalError.PushBack(unmarshalError) - s.Handlers.Send.Clear() // mock sending - s.Handlers.Send.PushBack(func(r *request.Request) { - r.HTTPResponse = &reqs[reqNum] - reqNum++ - }) - r := s.NewRequest(&request.Operation{Name: "Operation"}, nil, nil) - err := r.Send() - if err == nil { - t.Fatalf("expect error, but did not get one") - } - aerr := err.(awserr.RequestFailure) - if e, a := 500, aerr.StatusCode(); e != a { - t.Errorf("expect %d status code, got %d", e, a) - } - if e, a := "Throttling", aerr.Code(); e != a { - t.Errorf("expect %q error code, got %q", e, a) - } - if e, a := "An error occurred.", aerr.Message(); e != a { - t.Errorf("expect %q error message, got %q", e, a) - } - if e, a := 3, int(r.RetryCount); e != a { - t.Errorf("expect %d retry count, got %d", e, a) - } - - expectDelays := []struct{ min, max time.Duration }{{500, 999}, {1000, 1998}, {2000, 3996}} - for i, v := range delays { - min := expectDelays[i].min * time.Millisecond - max := expectDelays[i].max * time.Millisecond - if !(min <= v && v <= max) { - t.Errorf("Expect delay to be within range, i:%d, v:%s, min:%s, max:%s", - i, v, min, max) - } - } -} - -// test that retries occur for request timeouts when response.Body can be nil -func TestRequestRecoverTimeoutWithNilBody(t *testing.T) { - reqNum := 0 - reqs := []*http.Response{ - {StatusCode: 0, Body: nil}, // body can be nil when requests time out - {StatusCode: 200, Body: body(`{"data":"valid"}`)}, - } - errors := []error{ - errTimeout, nil, - } - - s := awstesting.NewClient(aws.NewConfig().WithMaxRetries(10)) - s.Handlers.Validate.Clear() - s.Handlers.Unmarshal.PushBack(unmarshal) - s.Handlers.UnmarshalError.PushBack(unmarshalError) - s.Handlers.AfterRetry.Clear() // force retry on all errors - s.Handlers.AfterRetry.PushBack(func(r *request.Request) { - if r.Error != nil { - r.Error = nil - r.Retryable = aws.Bool(true) - r.RetryCount++ - } - }) - s.Handlers.Send.Clear() // mock sending - s.Handlers.Send.PushBack(func(r *request.Request) { - r.HTTPResponse = reqs[reqNum] - r.Error = errors[reqNum] - reqNum++ - }) - out := &testData{} - r := s.NewRequest(&request.Operation{Name: "Operation"}, nil, out) - err := r.Send() - if err != nil { - t.Fatalf("expect no error, but got %v", err) - } - if e, a := 1, int(r.RetryCount); e != a { - t.Errorf("expect %d retry count, got %d", e, a) - } - if e, a := "valid", out.Data; e != a { - t.Errorf("expect %q output got %q", e, a) - } -} - -func TestRequestRecoverTimeoutWithNilResponse(t *testing.T) { - reqNum := 0 - reqs := []*http.Response{ - nil, - {StatusCode: 200, Body: body(`{"data":"valid"}`)}, - } - errors := []error{ - errTimeout, - nil, - } - - s := awstesting.NewClient(aws.NewConfig().WithMaxRetries(10)) - s.Handlers.Validate.Clear() - s.Handlers.Unmarshal.PushBack(unmarshal) - s.Handlers.UnmarshalError.PushBack(unmarshalError) - s.Handlers.AfterRetry.Clear() // force retry on all errors - s.Handlers.AfterRetry.PushBack(func(r *request.Request) { - if r.Error != nil { - r.Error = nil - r.Retryable = aws.Bool(true) - r.RetryCount++ - } - }) - s.Handlers.Send.Clear() // mock sending - s.Handlers.Send.PushBack(func(r *request.Request) { - r.HTTPResponse = reqs[reqNum] - r.Error = errors[reqNum] - reqNum++ - }) - out := &testData{} - r := s.NewRequest(&request.Operation{Name: "Operation"}, nil, out) - err := r.Send() - if err != nil { - t.Fatalf("expect no error, but got %v", err) - } - if e, a := 1, int(r.RetryCount); e != a { - t.Errorf("expect %d retry count, got %d", e, a) - } - if e, a := "valid", out.Data; e != a { - t.Errorf("expect %q output got %q", e, a) - } -} - -func TestRequest_NoBody(t *testing.T) { - cases := []string{ - "GET", "HEAD", "DELETE", - "PUT", "POST", "PATCH", - } - - for i, c := range cases { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if v := r.TransferEncoding; len(v) > 0 { - t.Errorf("%d, expect no body sent with Transfer-Encoding, %v", i, v) - } - - outMsg := []byte(`{"Value": "abc"}`) - - if b, err := ioutil.ReadAll(r.Body); err != nil { - t.Fatalf("%d, expect no error reading request body, got %v", i, err) - } else if n := len(b); n > 0 { - t.Errorf("%d, expect no request body, got %d bytes", i, n) - } - - w.Header().Set("Content-Length", strconv.Itoa(len(outMsg))) - if _, err := w.Write(outMsg); err != nil { - t.Fatalf("%d, expect no error writing server response, got %v", i, err) - } - })) - - s := awstesting.NewClient(&aws.Config{ - Region: aws.String("mock-region"), - MaxRetries: aws.Int(0), - Endpoint: aws.String(server.URL), - DisableSSL: aws.Bool(true), - }) - s.Handlers.Build.PushBack(rest.Build) - s.Handlers.Validate.Clear() - s.Handlers.Unmarshal.PushBack(unmarshal) - s.Handlers.UnmarshalError.PushBack(unmarshalError) - - in := struct { - Bucket *string `location:"uri" locationName:"bucket"` - Key *string `location:"uri" locationName:"key"` - }{ - Bucket: aws.String("mybucket"), Key: aws.String("myKey"), - } - - out := struct { - Value *string - }{} - - r := s.NewRequest(&request.Operation{ - Name: "OpName", HTTPMethod: c, HTTPPath: "/{bucket}/{key+}", - }, &in, &out) - - if err := r.Send(); err != nil { - t.Fatalf("%d, expect no error sending request, got %v", i, err) - } - } -} - -func TestIsSerializationErrorRetryable(t *testing.T) { - testCases := []struct { - err error - expected bool - }{ - { - err: awserr.New(request.ErrCodeSerialization, "foo error", nil), - expected: false, - }, - { - err: awserr.New("ErrFoo", "foo error", nil), - expected: false, - }, - { - err: nil, - expected: false, - }, - { - err: awserr.New(request.ErrCodeSerialization, "foo error", stubConnectionResetError), - expected: true, - }, - } - - for i, c := range testCases { - r := &request.Request{ - Error: c.err, - } - if r.IsErrorRetryable() != c.expected { - t.Errorf("Case %d: Expected %v, but received %v", i+1, c.expected, !c.expected) - } - } -} - -func TestWithLogLevel(t *testing.T) { - r := &request.Request{} - - opt := request.WithLogLevel(aws.LogDebugWithHTTPBody) - r.ApplyOptions(opt) - - if !r.Config.LogLevel.Matches(aws.LogDebugWithHTTPBody) { - t.Errorf("expect log level to be set, but was not, %v", - r.Config.LogLevel.Value()) - } -} - -func TestWithGetResponseHeader(t *testing.T) { - r := &request.Request{} - - var val, val2 string - r.ApplyOptions( - request.WithGetResponseHeader("x-a-header", &val), - request.WithGetResponseHeader("x-second-header", &val2), - ) - - r.HTTPResponse = &http.Response{ - Header: func() http.Header { - h := http.Header{} - h.Set("x-a-header", "first") - h.Set("x-second-header", "second") - return h - }(), - } - r.Handlers.Complete.Run(r) - - if e, a := "first", val; e != a { - t.Errorf("expect %q header value got %q", e, a) - } - if e, a := "second", val2; e != a { - t.Errorf("expect %q header value got %q", e, a) - } -} - -func TestWithGetResponseHeaders(t *testing.T) { - r := &request.Request{} - - var headers http.Header - opt := request.WithGetResponseHeaders(&headers) - - r.ApplyOptions(opt) - - r.HTTPResponse = &http.Response{ - Header: func() http.Header { - h := http.Header{} - h.Set("x-a-header", "headerValue") - return h - }(), - } - r.Handlers.Complete.Run(r) - - if e, a := "headerValue", headers.Get("x-a-header"); e != a { - t.Errorf("expect %q header value got %q", e, a) - } -} - -type connResetCloser struct { -} - -func (rc *connResetCloser) Read(b []byte) (int, error) { - return 0, stubConnectionResetError -} - -func (rc *connResetCloser) Close() error { - return nil -} - -func TestSerializationErrConnectionReset(t *testing.T) { - count := 0 - handlers := request.Handlers{} - handlers.Send.PushBack(func(r *request.Request) { - count++ - r.HTTPResponse = &http.Response{} - r.HTTPResponse.Body = &connResetCloser{} - }) - - handlers.Sign.PushBackNamed(v4.SignRequestHandler) - handlers.Build.PushBackNamed(jsonrpc.BuildHandler) - handlers.Unmarshal.PushBackNamed(jsonrpc.UnmarshalHandler) - handlers.UnmarshalMeta.PushBackNamed(jsonrpc.UnmarshalMetaHandler) - handlers.UnmarshalError.PushBackNamed(jsonrpc.UnmarshalErrorHandler) - handlers.AfterRetry.PushBackNamed(corehandlers.AfterRetryHandler) - - op := &request.Operation{ - Name: "op", - HTTPMethod: "POST", - HTTPPath: "/", - } - - meta := metadata.ClientInfo{ - ServiceName: "fooService", - SigningName: "foo", - SigningRegion: "foo", - Endpoint: "localhost", - APIVersion: "2001-01-01", - JSONVersion: "1.1", - TargetPrefix: "Foo", - } - cfg := unit.Session.Config.Copy() - cfg.MaxRetries = aws.Int(5) - - req := request.New( - *cfg, - meta, - handlers, - client.DefaultRetryer{NumMaxRetries: 5}, - op, - &struct { - }{}, - &struct { - }{}, - ) - - osErr := stubConnectionResetError - req.ApplyOptions(request.WithResponseReadTimeout(time.Second)) - err := req.Send() - if err == nil { - t.Error("Expected rror 'SerializationError', but received nil") - } - if aerr, ok := err.(awserr.Error); ok && aerr.Code() != "SerializationError" { - t.Errorf("Expected 'SerializationError', but received %q", aerr.Code()) - } else if !ok { - t.Errorf("Expected 'awserr.Error', but received %v", reflect.TypeOf(err)) - } else if aerr.OrigErr().Error() != osErr.Error() { - t.Errorf("Expected %q, but received %q", osErr.Error(), aerr.OrigErr().Error()) - } - - if count != 6 { - t.Errorf("Expected '6', but received %d", count) - } -} - -type testRetryer struct { - shouldRetry bool -} - -func (d *testRetryer) MaxRetries() int { - return 3 -} - -// RetryRules returns the delay duration before retrying this request again -func (d *testRetryer) RetryRules(r *request.Request) time.Duration { - return time.Duration(time.Millisecond) -} - -func (d *testRetryer) ShouldRetry(r *request.Request) bool { - d.shouldRetry = true - if r.Retryable != nil { - return *r.Retryable - } - - if r.HTTPResponse.StatusCode >= 500 { - return true - } - return r.IsErrorRetryable() -} - -func TestEnforceShouldRetryCheck(t *testing.T) { - tp := &http.Transport{ - Proxy: http.ProxyFromEnvironment, - ResponseHeaderTimeout: 1 * time.Millisecond, - } - - client := &http.Client{Transport: tp} - - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - // This server should wait forever. Requests will timeout and the SDK should - // attempt to retry. - select {} - })) - - retryer := &testRetryer{} - s := awstesting.NewClient(&aws.Config{ - Region: aws.String("mock-region"), - MaxRetries: aws.Int(0), - Endpoint: aws.String(server.URL), - DisableSSL: aws.Bool(true), - Retryer: retryer, - HTTPClient: client, - EnforceShouldRetryCheck: aws.Bool(true), - }) - - s.Handlers.Validate.Clear() - s.Handlers.Unmarshal.PushBack(unmarshal) - s.Handlers.UnmarshalError.PushBack(unmarshalError) - - out := &testData{} - r := s.NewRequest(&request.Operation{Name: "Operation"}, nil, out) - err := r.Send() - if err == nil { - t.Fatalf("expect error, but got nil") - } - if e, a := 3, int(r.RetryCount); e != a { - t.Errorf("expect %d retry count, got %d", e, a) - } - if !retryer.shouldRetry { - t.Errorf("expect 'true' for ShouldRetry, but got %v", retryer.shouldRetry) - } -} - -type errReader struct { - err error -} - -func (reader *errReader) Read(b []byte) (int, error) { - return 0, reader.err -} - -func (reader *errReader) Close() error { - return nil -} - -func TestIsNoBodyReader(t *testing.T) { - cases := []struct { - reader io.ReadCloser - expect bool - }{ - {ioutil.NopCloser(bytes.NewReader([]byte("abc"))), false}, - {ioutil.NopCloser(bytes.NewReader(nil)), false}, - {nil, false}, - {request.NoBody, true}, - } - - for i, c := range cases { - if e, a := c.expect, request.NoBody == c.reader; e != a { - t.Errorf("%d, expect %t match, but was %t", i, e, a) - } - } -} - -func TestRequest_TemporaryRetry(t *testing.T) { - done := make(chan struct{}) - - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Length", "1024") - w.WriteHeader(http.StatusOK) - - w.Write(make([]byte, 100)) - - f := w.(http.Flusher) - f.Flush() - - <-done - })) - - client := &http.Client{ - Timeout: 100 * time.Millisecond, - } - - svc := awstesting.NewClient(&aws.Config{ - Region: unit.Session.Config.Region, - MaxRetries: aws.Int(1), - HTTPClient: client, - DisableSSL: aws.Bool(true), - Endpoint: aws.String(server.URL), - }) - - req := svc.NewRequest(&request.Operation{ - Name: "name", HTTPMethod: "GET", HTTPPath: "/path", - }, &struct{}{}, &struct{}{}) - - req.Handlers.Unmarshal.PushBack(func(r *request.Request) { - defer req.HTTPResponse.Body.Close() - _, err := io.Copy(ioutil.Discard, req.HTTPResponse.Body) - r.Error = awserr.New(request.ErrCodeSerialization, "error", err) - }) - - err := req.Send() - if err == nil { - t.Errorf("expect error, got none") - } - close(done) - - aerr := err.(awserr.Error) - if e, a := request.ErrCodeSerialization, aerr.Code(); e != a { - t.Errorf("expect %q error code, got %q", e, a) - } - - if e, a := 1, req.RetryCount; e != a { - t.Errorf("expect %d retries, got %d", e, a) - } - - type temporary interface { - Temporary() bool - } - - terr := aerr.OrigErr().(temporary) - if !terr.Temporary() { - t.Errorf("expect temporary error, was not") - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/retryer_test.go b/vendor/github.com/aws/aws-sdk-go/aws/request/retryer_test.go deleted file mode 100644 index a8787487e..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/retryer_test.go +++ /dev/null @@ -1,62 +0,0 @@ -package request - -import ( - "errors" - "fmt" - "testing" - - "github.com/aws/aws-sdk-go/aws/awserr" -) - -func TestRequestThrottling(t *testing.T) { - req := Request{} - - req.Error = awserr.New("Throttling", "", nil) - if e, a := true, req.IsErrorThrottle(); e != a { - t.Errorf("expect %t to be throttled, was %t", e, a) - } -} - -type mockTempError bool - -func (e mockTempError) Error() string { - return fmt.Sprintf("mock temporary error: %t", e.Temporary()) -} -func (e mockTempError) Temporary() bool { - return bool(e) -} - -func TestIsErrorRetryable(t *testing.T) { - cases := []struct { - Err error - IsTemp bool - }{ - { - Err: awserr.New(ErrCodeSerialization, "temporary error", mockTempError(true)), - IsTemp: true, - }, - { - Err: awserr.New(ErrCodeSerialization, "temporary error", mockTempError(false)), - IsTemp: false, - }, - { - Err: awserr.New(ErrCodeSerialization, "some error", errors.New("blah")), - IsTemp: false, - }, - { - Err: awserr.New("SomeError", "some error", nil), - IsTemp: false, - }, - { - Err: awserr.New("RequestError", "some error", nil), - IsTemp: true, - }, - } - - for i, c := range cases { - retryable := IsErrorRetryable(c.Err) - if e, a := c.IsTemp, retryable; e != a { - t.Errorf("%d, expect %t temporary error, got %t", i, e, a) - } - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/timeout_read_closer_benchmark_test.go b/vendor/github.com/aws/aws-sdk-go/aws/request/timeout_read_closer_benchmark_test.go deleted file mode 100644 index 33e1b2d18..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/timeout_read_closer_benchmark_test.go +++ /dev/null @@ -1,76 +0,0 @@ -package request_test - -import ( - "bytes" - "io/ioutil" - "net/http" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws/client" - "github.com/aws/aws-sdk-go/aws/client/metadata" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/aws/signer/v4" - "github.com/aws/aws-sdk-go/awstesting/unit" - "github.com/aws/aws-sdk-go/private/protocol/jsonrpc" -) - -func BenchmarkTimeoutReadCloser(b *testing.B) { - resp := ` - { - "Bar": "qux" - } - ` - - handlers := request.Handlers{} - - handlers.Send.PushBack(func(r *request.Request) { - r.HTTPResponse = &http.Response{ - StatusCode: http.StatusOK, - Body: ioutil.NopCloser(bytes.NewBuffer([]byte(resp))), - } - }) - handlers.Sign.PushBackNamed(v4.SignRequestHandler) - handlers.Build.PushBackNamed(jsonrpc.BuildHandler) - handlers.Unmarshal.PushBackNamed(jsonrpc.UnmarshalHandler) - handlers.UnmarshalMeta.PushBackNamed(jsonrpc.UnmarshalMetaHandler) - handlers.UnmarshalError.PushBackNamed(jsonrpc.UnmarshalErrorHandler) - - op := &request.Operation{ - Name: "op", - HTTPMethod: "POST", - HTTPPath: "/", - } - - meta := metadata.ClientInfo{ - ServiceName: "fooService", - SigningName: "foo", - SigningRegion: "foo", - Endpoint: "localhost", - APIVersion: "2001-01-01", - JSONVersion: "1.1", - TargetPrefix: "Foo", - } - - req := request.New( - *unit.Session.Config, - meta, - handlers, - client.DefaultRetryer{NumMaxRetries: 5}, - op, - &struct { - Foo *string - }{}, - &struct { - Bar *string - }{}, - ) - - req.ApplyOptions(request.WithResponseReadTimeout(15 * time.Second)) - for i := 0; i < b.N; i++ { - err := req.Send() - if err != nil { - b.Errorf("Expected no error, but received %v", err) - } - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/timeout_read_closer_test.go b/vendor/github.com/aws/aws-sdk-go/aws/request/timeout_read_closer_test.go deleted file mode 100644 index c814158da..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/timeout_read_closer_test.go +++ /dev/null @@ -1,118 +0,0 @@ -package request - -import ( - "bytes" - "io" - "io/ioutil" - "net/http" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws/awserr" -) - -type testReader struct { - duration time.Duration - count int -} - -func (r *testReader) Read(b []byte) (int, error) { - if r.count > 0 { - r.count-- - return len(b), nil - } - time.Sleep(r.duration) - return 0, io.EOF -} - -func (r *testReader) Close() error { - return nil -} - -func TestTimeoutReadCloser(t *testing.T) { - reader := timeoutReadCloser{ - reader: &testReader{ - duration: time.Second, - count: 5, - }, - duration: time.Millisecond, - } - b := make([]byte, 100) - _, err := reader.Read(b) - if err != nil { - t.Log(err) - } -} - -func TestTimeoutReadCloserSameDuration(t *testing.T) { - reader := timeoutReadCloser{ - reader: &testReader{ - duration: time.Millisecond, - count: 5, - }, - duration: time.Millisecond, - } - b := make([]byte, 100) - _, err := reader.Read(b) - if err != nil { - t.Log(err) - } -} - -func TestWithResponseReadTimeout(t *testing.T) { - r := Request{ - HTTPResponse: &http.Response{ - Body: ioutil.NopCloser(bytes.NewReader(nil)), - }, - } - r.ApplyOptions(WithResponseReadTimeout(time.Second)) - err := r.Send() - if err != nil { - t.Error(err) - } - v, ok := r.HTTPResponse.Body.(*timeoutReadCloser) - if !ok { - t.Error("Expected the body to be a timeoutReadCloser") - } - if v.duration != time.Second { - t.Errorf("Expected %v, but receive %v\n", time.Second, v.duration) - } -} - -func TestAdaptToResponseTimeout(t *testing.T) { - testCases := []struct { - childErr error - r Request - expectedRootCode string - }{ - { - childErr: awserr.New(ErrCodeResponseTimeout, "timeout!", nil), - r: Request{ - Error: awserr.New("ErrTest", "FooBar", awserr.New(ErrCodeResponseTimeout, "timeout!", nil)), - }, - expectedRootCode: ErrCodeResponseTimeout, - }, - { - childErr: awserr.New(ErrCodeResponseTimeout+"1", "timeout!", nil), - r: Request{ - Error: awserr.New("ErrTest", "FooBar", awserr.New(ErrCodeResponseTimeout+"1", "timeout!", nil)), - }, - expectedRootCode: "ErrTest", - }, - { - r: Request{ - Error: awserr.New("ErrTest", "FooBar", nil), - }, - expectedRootCode: "ErrTest", - }, - } - - for i, c := range testCases { - adaptToResponseTimeoutError(&c.r) - if aerr, ok := c.r.Error.(awserr.Error); !ok { - t.Errorf("Case %d: Expected 'awserr', but received %v", i+1, c.r.Error) - } else if aerr.Code() != c.expectedRootCode { - t.Errorf("Case %d: Expected %q, but received %s", i+1, c.expectedRootCode, aerr.Code()) - } - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/waiter_test.go b/vendor/github.com/aws/aws-sdk-go/aws/request/waiter_test.go deleted file mode 100644 index db0f92df1..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/waiter_test.go +++ /dev/null @@ -1,654 +0,0 @@ -package request_test - -import ( - "bytes" - "fmt" - "io/ioutil" - "net/http" - "testing" - "time" - - "github.com/stretchr/testify/assert" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/client" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/awstesting" - "github.com/aws/aws-sdk-go/awstesting/unit" - "github.com/aws/aws-sdk-go/service/s3" -) - -type mockClient struct { - *client.Client -} -type MockInput struct{} -type MockOutput struct { - States []*MockState -} -type MockState struct { - State *string -} - -func (c *mockClient) MockRequest(input *MockInput) (*request.Request, *MockOutput) { - op := &request.Operation{ - Name: "Mock", - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &MockInput{} - } - - output := &MockOutput{} - req := c.NewRequest(op, input, output) - req.Data = output - return req, output -} - -func BuildNewMockRequest(c *mockClient, in *MockInput) func([]request.Option) (*request.Request, error) { - return func(opts []request.Option) (*request.Request, error) { - req, _ := c.MockRequest(in) - req.ApplyOptions(opts...) - return req, nil - } -} - -func TestWaiterPathAll(t *testing.T) { - svc := &mockClient{Client: awstesting.NewClient(&aws.Config{ - Region: aws.String("mock-region"), - })} - svc.Handlers.Send.Clear() // mock sending - svc.Handlers.Unmarshal.Clear() - svc.Handlers.UnmarshalMeta.Clear() - svc.Handlers.ValidateResponse.Clear() - - reqNum := 0 - resps := []*MockOutput{ - { // Request 1 - States: []*MockState{ - {State: aws.String("pending")}, - {State: aws.String("pending")}, - }, - }, - { // Request 2 - States: []*MockState{ - {State: aws.String("running")}, - {State: aws.String("pending")}, - }, - }, - { // Request 3 - States: []*MockState{ - {State: aws.String("running")}, - {State: aws.String("running")}, - }, - }, - } - - numBuiltReq := 0 - svc.Handlers.Build.PushBack(func(r *request.Request) { - numBuiltReq++ - }) - svc.Handlers.Unmarshal.PushBack(func(r *request.Request) { - if reqNum >= len(resps) { - assert.Fail(t, "too many polling requests made") - return - } - r.Data = resps[reqNum] - reqNum++ - }) - - w := request.Waiter{ - MaxAttempts: 10, - Delay: request.ConstantWaiterDelay(0), - SleepWithContext: aws.SleepWithContext, - Acceptors: []request.WaiterAcceptor{ - { - State: request.SuccessWaiterState, - Matcher: request.PathAllWaiterMatch, - Argument: "States[].State", - Expected: "running", - }, - }, - NewRequest: BuildNewMockRequest(svc, &MockInput{}), - } - - err := w.WaitWithContext(aws.BackgroundContext()) - assert.NoError(t, err) - assert.Equal(t, 3, numBuiltReq) - assert.Equal(t, 3, reqNum) -} - -func TestWaiterPath(t *testing.T) { - svc := &mockClient{Client: awstesting.NewClient(&aws.Config{ - Region: aws.String("mock-region"), - })} - svc.Handlers.Send.Clear() // mock sending - svc.Handlers.Unmarshal.Clear() - svc.Handlers.UnmarshalMeta.Clear() - svc.Handlers.ValidateResponse.Clear() - - reqNum := 0 - resps := []*MockOutput{ - { // Request 1 - States: []*MockState{ - {State: aws.String("pending")}, - {State: aws.String("pending")}, - }, - }, - { // Request 2 - States: []*MockState{ - {State: aws.String("running")}, - {State: aws.String("pending")}, - }, - }, - { // Request 3 - States: []*MockState{ - {State: aws.String("running")}, - {State: aws.String("running")}, - }, - }, - } - - numBuiltReq := 0 - svc.Handlers.Build.PushBack(func(r *request.Request) { - numBuiltReq++ - }) - svc.Handlers.Unmarshal.PushBack(func(r *request.Request) { - if reqNum >= len(resps) { - assert.Fail(t, "too many polling requests made") - return - } - r.Data = resps[reqNum] - reqNum++ - }) - - w := request.Waiter{ - MaxAttempts: 10, - Delay: request.ConstantWaiterDelay(0), - SleepWithContext: aws.SleepWithContext, - Acceptors: []request.WaiterAcceptor{ - { - State: request.SuccessWaiterState, - Matcher: request.PathWaiterMatch, - Argument: "States[].State", - Expected: "running", - }, - }, - NewRequest: BuildNewMockRequest(svc, &MockInput{}), - } - - err := w.WaitWithContext(aws.BackgroundContext()) - assert.NoError(t, err) - assert.Equal(t, 3, numBuiltReq) - assert.Equal(t, 3, reqNum) -} - -func TestWaiterFailure(t *testing.T) { - svc := &mockClient{Client: awstesting.NewClient(&aws.Config{ - Region: aws.String("mock-region"), - })} - svc.Handlers.Send.Clear() // mock sending - svc.Handlers.Unmarshal.Clear() - svc.Handlers.UnmarshalMeta.Clear() - svc.Handlers.ValidateResponse.Clear() - - reqNum := 0 - resps := []*MockOutput{ - { // Request 1 - States: []*MockState{ - {State: aws.String("pending")}, - {State: aws.String("pending")}, - }, - }, - { // Request 2 - States: []*MockState{ - {State: aws.String("running")}, - {State: aws.String("pending")}, - }, - }, - { // Request 3 - States: []*MockState{ - {State: aws.String("running")}, - {State: aws.String("stopping")}, - }, - }, - } - - numBuiltReq := 0 - svc.Handlers.Build.PushBack(func(r *request.Request) { - numBuiltReq++ - }) - svc.Handlers.Unmarshal.PushBack(func(r *request.Request) { - if reqNum >= len(resps) { - assert.Fail(t, "too many polling requests made") - return - } - r.Data = resps[reqNum] - reqNum++ - }) - - w := request.Waiter{ - MaxAttempts: 10, - Delay: request.ConstantWaiterDelay(0), - SleepWithContext: aws.SleepWithContext, - Acceptors: []request.WaiterAcceptor{ - { - State: request.SuccessWaiterState, - Matcher: request.PathAllWaiterMatch, - Argument: "States[].State", - Expected: "running", - }, - { - State: request.FailureWaiterState, - Matcher: request.PathAnyWaiterMatch, - Argument: "States[].State", - Expected: "stopping", - }, - }, - NewRequest: BuildNewMockRequest(svc, &MockInput{}), - } - - err := w.WaitWithContext(aws.BackgroundContext()).(awserr.Error) - assert.Error(t, err) - assert.Equal(t, request.WaiterResourceNotReadyErrorCode, err.Code()) - assert.Equal(t, "failed waiting for successful resource state", err.Message()) - assert.Equal(t, 3, numBuiltReq) - assert.Equal(t, 3, reqNum) -} - -func TestWaiterError(t *testing.T) { - svc := &mockClient{Client: awstesting.NewClient(&aws.Config{ - Region: aws.String("mock-region"), - })} - svc.Handlers.Send.Clear() // mock sending - svc.Handlers.Unmarshal.Clear() - svc.Handlers.UnmarshalMeta.Clear() - svc.Handlers.UnmarshalError.Clear() - svc.Handlers.ValidateResponse.Clear() - - reqNum := 0 - resps := []*MockOutput{ - { // Request 1 - States: []*MockState{ - {State: aws.String("pending")}, - {State: aws.String("pending")}, - }, - }, - { // Request 1, error case retry - }, - { // Request 2, error case failure - }, - { // Request 3 - States: []*MockState{ - {State: aws.String("running")}, - {State: aws.String("running")}, - }, - }, - } - reqErrs := make([]error, len(resps)) - reqErrs[1] = awserr.New("MockException", "mock exception message", nil) - reqErrs[2] = awserr.New("FailureException", "mock failure exception message", nil) - - numBuiltReq := 0 - svc.Handlers.Build.PushBack(func(r *request.Request) { - numBuiltReq++ - }) - svc.Handlers.Send.PushBack(func(r *request.Request) { - code := 200 - if reqNum == 1 { - code = 400 - } - r.HTTPResponse = &http.Response{ - StatusCode: code, - Status: http.StatusText(code), - Body: ioutil.NopCloser(bytes.NewReader([]byte{})), - } - }) - svc.Handlers.Unmarshal.PushBack(func(r *request.Request) { - if reqNum >= len(resps) { - assert.Fail(t, "too many polling requests made") - return - } - r.Data = resps[reqNum] - reqNum++ - }) - svc.Handlers.UnmarshalMeta.PushBack(func(r *request.Request) { - // If there was an error unmarshal error will be called instead of unmarshal - // need to increment count here also - if err := reqErrs[reqNum]; err != nil { - r.Error = err - reqNum++ - } - }) - - w := request.Waiter{ - MaxAttempts: 10, - Delay: request.ConstantWaiterDelay(0), - SleepWithContext: aws.SleepWithContext, - Acceptors: []request.WaiterAcceptor{ - { - State: request.SuccessWaiterState, - Matcher: request.PathAllWaiterMatch, - Argument: "States[].State", - Expected: "running", - }, - { - State: request.RetryWaiterState, - Matcher: request.ErrorWaiterMatch, - Argument: "", - Expected: "MockException", - }, - { - State: request.FailureWaiterState, - Matcher: request.ErrorWaiterMatch, - Argument: "", - Expected: "FailureException", - }, - }, - NewRequest: BuildNewMockRequest(svc, &MockInput{}), - } - - err := w.WaitWithContext(aws.BackgroundContext()) - if err == nil { - t.Fatalf("expected error, but did not get one") - } - aerr := err.(awserr.Error) - if e, a := request.WaiterResourceNotReadyErrorCode, aerr.Code(); e != a { - t.Errorf("expect %q error code, got %q", e, a) - } - if e, a := 3, numBuiltReq; e != a { - t.Errorf("expect %d built requests got %d", e, a) - } - if e, a := 3, reqNum; e != a { - t.Errorf("expect %d reqNum got %d", e, a) - } -} - -func TestWaiterStatus(t *testing.T) { - svc := &mockClient{Client: awstesting.NewClient(&aws.Config{ - Region: aws.String("mock-region"), - })} - svc.Handlers.Send.Clear() // mock sending - svc.Handlers.Unmarshal.Clear() - svc.Handlers.UnmarshalMeta.Clear() - svc.Handlers.ValidateResponse.Clear() - - reqNum := 0 - svc.Handlers.Build.PushBack(func(r *request.Request) { - reqNum++ - }) - svc.Handlers.Send.PushBack(func(r *request.Request) { - code := 200 - if reqNum == 3 { - code = 404 - r.Error = awserr.New("NotFound", "Not Found", nil) - } - r.HTTPResponse = &http.Response{ - StatusCode: code, - Status: http.StatusText(code), - Body: ioutil.NopCloser(bytes.NewReader([]byte{})), - } - }) - - w := request.Waiter{ - MaxAttempts: 10, - Delay: request.ConstantWaiterDelay(0), - SleepWithContext: aws.SleepWithContext, - Acceptors: []request.WaiterAcceptor{ - { - State: request.SuccessWaiterState, - Matcher: request.StatusWaiterMatch, - Argument: "", - Expected: 404, - }, - }, - NewRequest: BuildNewMockRequest(svc, &MockInput{}), - } - - err := w.WaitWithContext(aws.BackgroundContext()) - assert.NoError(t, err) - assert.Equal(t, 3, reqNum) -} - -func TestWaiter_ApplyOptions(t *testing.T) { - w := request.Waiter{} - - logger := aws.NewDefaultLogger() - - w.ApplyOptions( - request.WithWaiterLogger(logger), - request.WithWaiterRequestOptions(request.WithLogLevel(aws.LogDebug)), - request.WithWaiterMaxAttempts(2), - request.WithWaiterDelay(request.ConstantWaiterDelay(5*time.Second)), - ) - - if e, a := logger, w.Logger; e != a { - t.Errorf("expect logger to be set, and match, was not, %v, %v", e, a) - } - - if len(w.RequestOptions) != 1 { - t.Fatalf("expect request options to be set to only a single option, %v", w.RequestOptions) - } - r := request.Request{} - r.ApplyOptions(w.RequestOptions...) - if e, a := aws.LogDebug, r.Config.LogLevel.Value(); e != a { - t.Errorf("expect %v loglevel got %v", e, a) - } - - if e, a := 2, w.MaxAttempts; e != a { - t.Errorf("expect %d retryer max attempts, got %d", e, a) - } - if e, a := 5*time.Second, w.Delay(0); e != a { - t.Errorf("expect %d retryer delay, got %d", e, a) - } -} - -func TestWaiter_WithContextCanceled(t *testing.T) { - c := awstesting.NewClient() - - ctx := &awstesting.FakeContext{DoneCh: make(chan struct{})} - reqCount := 0 - - w := request.Waiter{ - Name: "TestWaiter", - MaxAttempts: 10, - Delay: request.ConstantWaiterDelay(1 * time.Millisecond), - SleepWithContext: aws.SleepWithContext, - Acceptors: []request.WaiterAcceptor{ - { - State: request.SuccessWaiterState, - Matcher: request.StatusWaiterMatch, - Expected: 200, - }, - }, - Logger: aws.NewDefaultLogger(), - NewRequest: func(opts []request.Option) (*request.Request, error) { - req := c.NewRequest(&request.Operation{Name: "Operation"}, nil, nil) - req.HTTPResponse = &http.Response{StatusCode: http.StatusNotFound} - req.Handlers.Clear() - req.Data = struct{}{} - req.Handlers.Send.PushBack(func(r *request.Request) { - if reqCount == 1 { - ctx.Error = fmt.Errorf("context canceled") - close(ctx.DoneCh) - } - reqCount++ - }) - - return req, nil - }, - } - - w.SleepWithContext = func(c aws.Context, delay time.Duration) error { - context := c.(*awstesting.FakeContext) - select { - case <-context.DoneCh: - return context.Err() - default: - return nil - } - } - - err := w.WaitWithContext(ctx) - - if err == nil { - t.Fatalf("expect waiter to be canceled.") - } - aerr := err.(awserr.Error) - if e, a := request.CanceledErrorCode, aerr.Code(); e != a { - t.Errorf("expect %q error code, got %q", e, a) - } - if e, a := 2, reqCount; e != a { - t.Errorf("expect %d requests, got %d", e, a) - } -} - -func TestWaiter_WithContext(t *testing.T) { - c := awstesting.NewClient() - - ctx := &awstesting.FakeContext{DoneCh: make(chan struct{})} - reqCount := 0 - - statuses := []int{http.StatusNotFound, http.StatusOK} - - w := request.Waiter{ - Name: "TestWaiter", - MaxAttempts: 10, - Delay: request.ConstantWaiterDelay(1 * time.Millisecond), - SleepWithContext: aws.SleepWithContext, - Acceptors: []request.WaiterAcceptor{ - { - State: request.SuccessWaiterState, - Matcher: request.StatusWaiterMatch, - Expected: 200, - }, - }, - Logger: aws.NewDefaultLogger(), - NewRequest: func(opts []request.Option) (*request.Request, error) { - req := c.NewRequest(&request.Operation{Name: "Operation"}, nil, nil) - req.HTTPResponse = &http.Response{StatusCode: statuses[reqCount]} - req.Handlers.Clear() - req.Data = struct{}{} - req.Handlers.Send.PushBack(func(r *request.Request) { - if reqCount == 1 { - ctx.Error = fmt.Errorf("context canceled") - close(ctx.DoneCh) - } - reqCount++ - }) - - return req, nil - }, - } - - err := w.WaitWithContext(ctx) - - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - if e, a := 2, reqCount; e != a { - t.Errorf("expect %d requests, got %d", e, a) - } -} - -func TestWaiter_AttemptsExpires(t *testing.T) { - c := awstesting.NewClient() - - ctx := &awstesting.FakeContext{DoneCh: make(chan struct{})} - reqCount := 0 - - w := request.Waiter{ - Name: "TestWaiter", - MaxAttempts: 2, - Delay: request.ConstantWaiterDelay(1 * time.Millisecond), - SleepWithContext: aws.SleepWithContext, - Acceptors: []request.WaiterAcceptor{ - { - State: request.SuccessWaiterState, - Matcher: request.StatusWaiterMatch, - Expected: 200, - }, - }, - Logger: aws.NewDefaultLogger(), - NewRequest: func(opts []request.Option) (*request.Request, error) { - req := c.NewRequest(&request.Operation{Name: "Operation"}, nil, nil) - req.HTTPResponse = &http.Response{StatusCode: http.StatusNotFound} - req.Handlers.Clear() - req.Data = struct{}{} - req.Handlers.Send.PushBack(func(r *request.Request) { - reqCount++ - }) - - return req, nil - }, - } - - err := w.WaitWithContext(ctx) - - if err == nil { - t.Fatalf("expect error did not get one") - } - aerr := err.(awserr.Error) - if e, a := request.WaiterResourceNotReadyErrorCode, aerr.Code(); e != a { - t.Errorf("expect %q error code, got %q", e, a) - } - if e, a := 2, reqCount; e != a { - t.Errorf("expect %d requests, got %d", e, a) - } -} - -func TestWaiterNilInput(t *testing.T) { - // Code generation doesn't have a great way to verify the code is correct - // other than being run via unit tests in the SDK. This should be fixed - // So code generation can be validated independently. - - client := s3.New(unit.Session) - client.Handlers.Validate.Clear() - client.Handlers.Send.Clear() // mock sending - client.Handlers.Send.PushBack(func(r *request.Request) { - r.HTTPResponse = &http.Response{ - StatusCode: http.StatusOK, - } - }) - client.Handlers.Unmarshal.Clear() - client.Handlers.UnmarshalMeta.Clear() - client.Handlers.ValidateResponse.Clear() - client.Config.SleepDelay = func(dur time.Duration) {} - - // Ensure waiters do not panic on nil input. It doesn't make sense to - // call a waiter without an input, Validation will - err := client.WaitUntilBucketExists(nil) - if err != nil { - t.Fatalf("expect no error, but got %v", err) - } -} - -func TestWaiterWithContextNilInput(t *testing.T) { - // Code generation doesn't have a great way to verify the code is correct - // other than being run via unit tests in the SDK. This should be fixed - // So code generation can be validated independently. - - client := s3.New(unit.Session) - client.Handlers.Validate.Clear() - client.Handlers.Send.Clear() // mock sending - client.Handlers.Send.PushBack(func(r *request.Request) { - r.HTTPResponse = &http.Response{ - StatusCode: http.StatusOK, - } - }) - client.Handlers.Unmarshal.Clear() - client.Handlers.UnmarshalMeta.Clear() - client.Handlers.ValidateResponse.Clear() - - // Ensure waiters do not panic on nil input - ctx := &awstesting.FakeContext{DoneCh: make(chan struct{})} - err := client.WaitUntilBucketExistsWithContext(ctx, nil, - request.WithWaiterDelay(request.ConstantWaiterDelay(0)), - request.WithWaiterMaxAttempts(1), - ) - if err != nil { - t.Fatalf("expect no error, but got %v", err) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/session/custom_ca_bundle_test.go b/vendor/github.com/aws/aws-sdk-go/aws/session/custom_ca_bundle_test.go deleted file mode 100644 index a89c0af59..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/session/custom_ca_bundle_test.go +++ /dev/null @@ -1,243 +0,0 @@ -package session - -import ( - "bytes" - "fmt" - "net" - "net/http" - "os" - "strings" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/awstesting" -) - -var TLSBundleCertFile string -var TLSBundleKeyFile string -var TLSBundleCAFile string - -func TestMain(m *testing.M) { - var err error - - TLSBundleCertFile, TLSBundleKeyFile, TLSBundleCAFile, err = awstesting.CreateTLSBundleFiles() - if err != nil { - panic(err) - } - - fmt.Println("TestMain", TLSBundleCertFile, TLSBundleKeyFile) - - code := m.Run() - - err = awstesting.CleanupTLSBundleFiles(TLSBundleCertFile, TLSBundleKeyFile, TLSBundleCAFile) - if err != nil { - panic(err) - } - - os.Exit(code) -} - -func TestNewSession_WithCustomCABundle_Env(t *testing.T) { - oldEnv := initSessionTestEnv() - defer awstesting.PopEnv(oldEnv) - - endpoint, err := awstesting.CreateTLSServer(TLSBundleCertFile, TLSBundleKeyFile, nil) - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - - os.Setenv("AWS_CA_BUNDLE", TLSBundleCAFile) - - s, err := NewSession(&aws.Config{ - HTTPClient: &http.Client{}, - Endpoint: aws.String(endpoint), - Region: aws.String("mock-region"), - Credentials: credentials.AnonymousCredentials, - }) - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - if s == nil { - t.Fatalf("expect session to be created, got none") - } - - req, _ := http.NewRequest("GET", *s.Config.Endpoint, nil) - resp, err := s.Config.HTTPClient.Do(req) - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - if e, a := http.StatusOK, resp.StatusCode; e != a { - t.Errorf("expect %d status code, got %d", e, a) - } -} - -func TestNewSession_WithCustomCABundle_EnvNotExists(t *testing.T) { - oldEnv := initSessionTestEnv() - defer awstesting.PopEnv(oldEnv) - - os.Setenv("AWS_CA_BUNDLE", "file-not-exists") - - s, err := NewSession() - if err == nil { - t.Fatalf("expect error, got none") - } - if e, a := "LoadCustomCABundleError", err.(awserr.Error).Code(); e != a { - t.Errorf("expect %s error code, got %s", e, a) - } - if s != nil { - t.Errorf("expect nil session, got %v", s) - } -} - -func TestNewSession_WithCustomCABundle_Option(t *testing.T) { - oldEnv := initSessionTestEnv() - defer awstesting.PopEnv(oldEnv) - - endpoint, err := awstesting.CreateTLSServer(TLSBundleCertFile, TLSBundleKeyFile, nil) - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - - s, err := NewSessionWithOptions(Options{ - Config: aws.Config{ - HTTPClient: &http.Client{}, - Endpoint: aws.String(endpoint), - Region: aws.String("mock-region"), - Credentials: credentials.AnonymousCredentials, - }, - CustomCABundle: bytes.NewReader(awstesting.TLSBundleCA), - }) - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - if s == nil { - t.Fatalf("expect session to be created, got none") - } - - req, _ := http.NewRequest("GET", *s.Config.Endpoint, nil) - resp, err := s.Config.HTTPClient.Do(req) - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - if e, a := http.StatusOK, resp.StatusCode; e != a { - t.Errorf("expect %d status code, got %d", e, a) - } -} - -func TestNewSession_WithCustomCABundle_OptionPriority(t *testing.T) { - oldEnv := initSessionTestEnv() - defer awstesting.PopEnv(oldEnv) - - endpoint, err := awstesting.CreateTLSServer(TLSBundleCertFile, TLSBundleKeyFile, nil) - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - - os.Setenv("AWS_CA_BUNDLE", "file-not-exists") - - s, err := NewSessionWithOptions(Options{ - Config: aws.Config{ - HTTPClient: &http.Client{}, - Endpoint: aws.String(endpoint), - Region: aws.String("mock-region"), - Credentials: credentials.AnonymousCredentials, - }, - CustomCABundle: bytes.NewReader(awstesting.TLSBundleCA), - }) - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - if s == nil { - t.Fatalf("expect session to be created, got none") - } - - req, _ := http.NewRequest("GET", *s.Config.Endpoint, nil) - resp, err := s.Config.HTTPClient.Do(req) - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - if e, a := http.StatusOK, resp.StatusCode; e != a { - t.Errorf("expect %d status code, got %d", e, a) - } -} - -type mockRoundTripper struct{} - -func (m *mockRoundTripper) RoundTrip(r *http.Request) (*http.Response, error) { - return nil, nil -} - -func TestNewSession_WithCustomCABundle_UnsupportedTransport(t *testing.T) { - oldEnv := initSessionTestEnv() - defer awstesting.PopEnv(oldEnv) - - s, err := NewSessionWithOptions(Options{ - Config: aws.Config{ - HTTPClient: &http.Client{ - Transport: &mockRoundTripper{}, - }, - }, - CustomCABundle: bytes.NewReader(awstesting.TLSBundleCA), - }) - if err == nil { - t.Fatalf("expect error, got none") - } - if e, a := "LoadCustomCABundleError", err.(awserr.Error).Code(); e != a { - t.Errorf("expect %s error code, got %s", e, a) - } - if s != nil { - t.Errorf("expect nil session, got %v", s) - } - aerrMsg := err.(awserr.Error).Message() - if e, a := "transport unsupported type", aerrMsg; !strings.Contains(a, e) { - t.Errorf("expect %s to be in %s", e, a) - } -} - -func TestNewSession_WithCustomCABundle_TransportSet(t *testing.T) { - oldEnv := initSessionTestEnv() - defer awstesting.PopEnv(oldEnv) - - endpoint, err := awstesting.CreateTLSServer(TLSBundleCertFile, TLSBundleKeyFile, nil) - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - - s, err := NewSessionWithOptions(Options{ - Config: aws.Config{ - Endpoint: aws.String(endpoint), - Region: aws.String("mock-region"), - Credentials: credentials.AnonymousCredentials, - HTTPClient: &http.Client{ - Transport: &http.Transport{ - Proxy: http.ProxyFromEnvironment, - Dial: (&net.Dialer{ - Timeout: 30 * time.Second, - KeepAlive: 30 * time.Second, - DualStack: true, - }).Dial, - TLSHandshakeTimeout: 2 * time.Second, - }, - }, - }, - CustomCABundle: bytes.NewReader(awstesting.TLSBundleCA), - }) - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - if s == nil { - t.Fatalf("expect session to be created, got none") - } - - req, _ := http.NewRequest("GET", *s.Config.Endpoint, nil) - resp, err := s.Config.HTTPClient.Do(req) - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - if e, a := http.StatusOK, resp.StatusCode; e != a { - t.Errorf("expect %d status code, got %d", e, a) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/session/env_config_test.go b/vendor/github.com/aws/aws-sdk-go/aws/session/env_config_test.go deleted file mode 100644 index 10e3662a2..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/session/env_config_test.go +++ /dev/null @@ -1,279 +0,0 @@ -package session - -import ( - "os" - "reflect" - "testing" - - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/awstesting" -) - -func TestLoadEnvConfig_Creds(t *testing.T) { - env := awstesting.StashEnv() - defer awstesting.PopEnv(env) - - cases := []struct { - Env map[string]string - Val credentials.Value - }{ - { - Env: map[string]string{ - "AWS_ACCESS_KEY": "AKID", - }, - Val: credentials.Value{}, - }, - { - Env: map[string]string{ - "AWS_ACCESS_KEY_ID": "AKID", - }, - Val: credentials.Value{}, - }, - { - Env: map[string]string{ - "AWS_SECRET_KEY": "SECRET", - }, - Val: credentials.Value{}, - }, - { - Env: map[string]string{ - "AWS_SECRET_ACCESS_KEY": "SECRET", - }, - Val: credentials.Value{}, - }, - { - Env: map[string]string{ - "AWS_ACCESS_KEY_ID": "AKID", - "AWS_SECRET_ACCESS_KEY": "SECRET", - }, - Val: credentials.Value{ - AccessKeyID: "AKID", SecretAccessKey: "SECRET", - ProviderName: "EnvConfigCredentials", - }, - }, - { - Env: map[string]string{ - "AWS_ACCESS_KEY": "AKID", - "AWS_SECRET_KEY": "SECRET", - }, - Val: credentials.Value{ - AccessKeyID: "AKID", SecretAccessKey: "SECRET", - ProviderName: "EnvConfigCredentials", - }, - }, - { - Env: map[string]string{ - "AWS_ACCESS_KEY": "AKID", - "AWS_SECRET_KEY": "SECRET", - "AWS_SESSION_TOKEN": "TOKEN", - }, - Val: credentials.Value{ - AccessKeyID: "AKID", SecretAccessKey: "SECRET", SessionToken: "TOKEN", - ProviderName: "EnvConfigCredentials", - }, - }, - } - - for _, c := range cases { - os.Clearenv() - - for k, v := range c.Env { - os.Setenv(k, v) - } - - cfg := loadEnvConfig() - if !reflect.DeepEqual(c.Val, cfg.Creds) { - t.Errorf("expect credentials to match.\n%s", - awstesting.SprintExpectActual(c.Val, cfg.Creds)) - } - } -} - -func TestLoadEnvConfig(t *testing.T) { - env := awstesting.StashEnv() - defer awstesting.PopEnv(env) - - cases := []struct { - Env map[string]string - UseSharedConfigCall bool - Config envConfig - }{ - { - Env: map[string]string{ - "AWS_REGION": "region", - "AWS_PROFILE": "profile", - }, - Config: envConfig{ - Region: "region", Profile: "profile", - }, - }, - { - Env: map[string]string{ - "AWS_REGION": "region", - "AWS_DEFAULT_REGION": "default_region", - "AWS_PROFILE": "profile", - "AWS_DEFAULT_PROFILE": "default_profile", - }, - Config: envConfig{ - Region: "region", Profile: "profile", - }, - }, - { - Env: map[string]string{ - "AWS_REGION": "region", - "AWS_DEFAULT_REGION": "default_region", - "AWS_PROFILE": "profile", - "AWS_DEFAULT_PROFILE": "default_profile", - "AWS_SDK_LOAD_CONFIG": "1", - }, - Config: envConfig{ - Region: "region", Profile: "profile", - EnableSharedConfig: true, - }, - }, - { - Env: map[string]string{ - "AWS_DEFAULT_REGION": "default_region", - "AWS_DEFAULT_PROFILE": "default_profile", - }, - }, - { - Env: map[string]string{ - "AWS_DEFAULT_REGION": "default_region", - "AWS_DEFAULT_PROFILE": "default_profile", - "AWS_SDK_LOAD_CONFIG": "1", - }, - Config: envConfig{ - Region: "default_region", Profile: "default_profile", - EnableSharedConfig: true, - }, - }, - { - Env: map[string]string{ - "AWS_REGION": "region", - "AWS_PROFILE": "profile", - }, - Config: envConfig{ - Region: "region", Profile: "profile", - EnableSharedConfig: true, - }, - UseSharedConfigCall: true, - }, - { - Env: map[string]string{ - "AWS_REGION": "region", - "AWS_DEFAULT_REGION": "default_region", - "AWS_PROFILE": "profile", - "AWS_DEFAULT_PROFILE": "default_profile", - }, - Config: envConfig{ - Region: "region", Profile: "profile", - EnableSharedConfig: true, - }, - UseSharedConfigCall: true, - }, - { - Env: map[string]string{ - "AWS_REGION": "region", - "AWS_DEFAULT_REGION": "default_region", - "AWS_PROFILE": "profile", - "AWS_DEFAULT_PROFILE": "default_profile", - "AWS_SDK_LOAD_CONFIG": "1", - }, - Config: envConfig{ - Region: "region", Profile: "profile", - EnableSharedConfig: true, - }, - UseSharedConfigCall: true, - }, - { - Env: map[string]string{ - "AWS_DEFAULT_REGION": "default_region", - "AWS_DEFAULT_PROFILE": "default_profile", - }, - Config: envConfig{ - Region: "default_region", Profile: "default_profile", - EnableSharedConfig: true, - }, - UseSharedConfigCall: true, - }, - { - Env: map[string]string{ - "AWS_DEFAULT_REGION": "default_region", - "AWS_DEFAULT_PROFILE": "default_profile", - "AWS_SDK_LOAD_CONFIG": "1", - }, - Config: envConfig{ - Region: "default_region", Profile: "default_profile", - EnableSharedConfig: true, - }, - UseSharedConfigCall: true, - }, - { - Env: map[string]string{ - "AWS_CA_BUNDLE": "custom_ca_bundle", - }, - Config: envConfig{ - CustomCABundle: "custom_ca_bundle", - }, - }, - { - Env: map[string]string{ - "AWS_CA_BUNDLE": "custom_ca_bundle", - }, - Config: envConfig{ - CustomCABundle: "custom_ca_bundle", - EnableSharedConfig: true, - }, - UseSharedConfigCall: true, - }, - { - Env: map[string]string{ - "AWS_SHARED_CREDENTIALS_FILE": "/path/to/credentials/file", - "AWS_CONFIG_FILE": "/path/to/config/file", - }, - Config: envConfig{ - SharedCredentialsFile: "/path/to/credentials/file", - SharedConfigFile: "/path/to/config/file", - }, - }, - } - - for _, c := range cases { - os.Clearenv() - - for k, v := range c.Env { - os.Setenv(k, v) - } - - var cfg envConfig - if c.UseSharedConfigCall { - cfg = loadSharedEnvConfig() - } else { - cfg = loadEnvConfig() - } - - if !reflect.DeepEqual(c.Config, cfg) { - t.Errorf("expect config to match.\n%s", - awstesting.SprintExpectActual(c.Config, cfg)) - } - } -} - -func TestSetEnvValue(t *testing.T) { - env := awstesting.StashEnv() - defer awstesting.PopEnv(env) - - os.Setenv("empty_key", "") - os.Setenv("second_key", "2") - os.Setenv("third_key", "3") - - var dst string - setFromEnvVal(&dst, []string{ - "empty_key", "first_key", "second_key", "third_key", - }) - - if e, a := "2", dst; e != a { - t.Errorf("expect %s value from environment, got %s", e, a) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/session/session_test.go b/vendor/github.com/aws/aws-sdk-go/aws/session/session_test.go deleted file mode 100644 index d0ab360e2..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/session/session_test.go +++ /dev/null @@ -1,428 +0,0 @@ -package session - -import ( - "bytes" - "fmt" - "net/http" - "net/http/httptest" - "os" - "testing" - "time" - - "github.com/stretchr/testify/assert" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/aws/defaults" - "github.com/aws/aws-sdk-go/awstesting" - "github.com/aws/aws-sdk-go/service/s3" -) - -func TestNewDefaultSession(t *testing.T) { - oldEnv := initSessionTestEnv() - defer awstesting.PopEnv(oldEnv) - - s := New(&aws.Config{Region: aws.String("region")}) - - assert.Equal(t, "region", *s.Config.Region) - assert.Equal(t, http.DefaultClient, s.Config.HTTPClient) - assert.NotNil(t, s.Config.Logger) - assert.Equal(t, aws.LogOff, *s.Config.LogLevel) -} - -func TestNew_WithCustomCreds(t *testing.T) { - oldEnv := initSessionTestEnv() - defer awstesting.PopEnv(oldEnv) - - customCreds := credentials.NewStaticCredentials("AKID", "SECRET", "TOKEN") - s := New(&aws.Config{Credentials: customCreds}) - - assert.Equal(t, customCreds, s.Config.Credentials) -} - -type mockLogger struct { - *bytes.Buffer -} - -func (w mockLogger) Log(args ...interface{}) { - fmt.Fprintln(w, args...) -} - -func TestNew_WithSessionLoadError(t *testing.T) { - oldEnv := initSessionTestEnv() - defer awstesting.PopEnv(oldEnv) - - os.Setenv("AWS_SDK_LOAD_CONFIG", "1") - os.Setenv("AWS_CONFIG_FILE", testConfigFilename) - os.Setenv("AWS_PROFILE", "assume_role_invalid_source_profile") - - logger := bytes.Buffer{} - s := New(&aws.Config{Logger: &mockLogger{&logger}}) - - assert.NotNil(t, s) - - svc := s3.New(s) - _, err := svc.ListBuckets(&s3.ListBucketsInput{}) - - assert.Error(t, err) - assert.Contains(t, logger.String(), "ERROR: failed to create session with AWS_SDK_LOAD_CONFIG enabled") - assert.Contains(t, err.Error(), SharedConfigAssumeRoleError{ - RoleARN: "assume_role_invalid_source_profile_role_arn", - }.Error()) -} - -func TestSessionCopy(t *testing.T) { - oldEnv := initSessionTestEnv() - defer awstesting.PopEnv(oldEnv) - - os.Setenv("AWS_REGION", "orig_region") - - s := Session{ - Config: defaults.Config(), - Handlers: defaults.Handlers(), - } - - newSess := s.Copy(&aws.Config{Region: aws.String("new_region")}) - - assert.Equal(t, "orig_region", *s.Config.Region) - assert.Equal(t, "new_region", *newSess.Config.Region) -} - -func TestSessionClientConfig(t *testing.T) { - s, err := NewSession(&aws.Config{Region: aws.String("orig_region")}) - assert.NoError(t, err) - - cfg := s.ClientConfig("s3", &aws.Config{Region: aws.String("us-west-2")}) - - assert.Equal(t, "https://s3-us-west-2.amazonaws.com", cfg.Endpoint) - assert.Equal(t, "us-west-2", cfg.SigningRegion) - assert.Equal(t, "us-west-2", *cfg.Config.Region) -} - -func TestNewSession_NoCredentials(t *testing.T) { - oldEnv := initSessionTestEnv() - defer awstesting.PopEnv(oldEnv) - - s, err := NewSession() - assert.NoError(t, err) - - assert.NotNil(t, s.Config.Credentials) - assert.NotEqual(t, credentials.AnonymousCredentials, s.Config.Credentials) -} - -func TestNewSessionWithOptions_OverrideProfile(t *testing.T) { - oldEnv := initSessionTestEnv() - defer awstesting.PopEnv(oldEnv) - - os.Setenv("AWS_SDK_LOAD_CONFIG", "1") - os.Setenv("AWS_SHARED_CREDENTIALS_FILE", testConfigFilename) - os.Setenv("AWS_PROFILE", "other_profile") - - s, err := NewSessionWithOptions(Options{ - Profile: "full_profile", - }) - assert.NoError(t, err) - - assert.Equal(t, "full_profile_region", *s.Config.Region) - - creds, err := s.Config.Credentials.Get() - assert.NoError(t, err) - assert.Equal(t, "full_profile_akid", creds.AccessKeyID) - assert.Equal(t, "full_profile_secret", creds.SecretAccessKey) - assert.Empty(t, creds.SessionToken) - assert.Contains(t, creds.ProviderName, "SharedConfigCredentials") -} - -func TestNewSessionWithOptions_OverrideSharedConfigEnable(t *testing.T) { - oldEnv := initSessionTestEnv() - defer awstesting.PopEnv(oldEnv) - - os.Setenv("AWS_SDK_LOAD_CONFIG", "0") - os.Setenv("AWS_SHARED_CREDENTIALS_FILE", testConfigFilename) - os.Setenv("AWS_PROFILE", "full_profile") - - s, err := NewSessionWithOptions(Options{ - SharedConfigState: SharedConfigEnable, - }) - assert.NoError(t, err) - - assert.Equal(t, "full_profile_region", *s.Config.Region) - - creds, err := s.Config.Credentials.Get() - assert.NoError(t, err) - assert.Equal(t, "full_profile_akid", creds.AccessKeyID) - assert.Equal(t, "full_profile_secret", creds.SecretAccessKey) - assert.Empty(t, creds.SessionToken) - assert.Contains(t, creds.ProviderName, "SharedConfigCredentials") -} - -func TestNewSessionWithOptions_OverrideSharedConfigDisable(t *testing.T) { - oldEnv := initSessionTestEnv() - defer awstesting.PopEnv(oldEnv) - - os.Setenv("AWS_SDK_LOAD_CONFIG", "1") - os.Setenv("AWS_SHARED_CREDENTIALS_FILE", testConfigFilename) - os.Setenv("AWS_PROFILE", "full_profile") - - s, err := NewSessionWithOptions(Options{ - SharedConfigState: SharedConfigDisable, - }) - assert.NoError(t, err) - - assert.Empty(t, *s.Config.Region) - - creds, err := s.Config.Credentials.Get() - assert.NoError(t, err) - assert.Equal(t, "full_profile_akid", creds.AccessKeyID) - assert.Equal(t, "full_profile_secret", creds.SecretAccessKey) - assert.Empty(t, creds.SessionToken) - assert.Contains(t, creds.ProviderName, "SharedConfigCredentials") -} - -func TestNewSessionWithOptions_OverrideSharedConfigFiles(t *testing.T) { - oldEnv := initSessionTestEnv() - defer awstesting.PopEnv(oldEnv) - - os.Setenv("AWS_SDK_LOAD_CONFIG", "1") - os.Setenv("AWS_SHARED_CREDENTIALS_FILE", testConfigFilename) - os.Setenv("AWS_PROFILE", "config_file_load_order") - - s, err := NewSessionWithOptions(Options{ - SharedConfigFiles: []string{testConfigOtherFilename}, - }) - assert.NoError(t, err) - - assert.Equal(t, "shared_config_other_region", *s.Config.Region) - - creds, err := s.Config.Credentials.Get() - assert.NoError(t, err) - assert.Equal(t, "shared_config_other_akid", creds.AccessKeyID) - assert.Equal(t, "shared_config_other_secret", creds.SecretAccessKey) - assert.Empty(t, creds.SessionToken) - assert.Contains(t, creds.ProviderName, "SharedConfigCredentials") -} - -func TestNewSessionWithOptions_Overrides(t *testing.T) { - cases := []struct { - InEnvs map[string]string - InProfile string - OutRegion string - OutCreds credentials.Value - }{ - { - InEnvs: map[string]string{ - "AWS_SDK_LOAD_CONFIG": "0", - "AWS_SHARED_CREDENTIALS_FILE": testConfigFilename, - "AWS_PROFILE": "other_profile", - }, - InProfile: "full_profile", - OutRegion: "full_profile_region", - OutCreds: credentials.Value{ - AccessKeyID: "full_profile_akid", - SecretAccessKey: "full_profile_secret", - ProviderName: "SharedConfigCredentials", - }, - }, - { - InEnvs: map[string]string{ - "AWS_SDK_LOAD_CONFIG": "0", - "AWS_SHARED_CREDENTIALS_FILE": testConfigFilename, - "AWS_REGION": "env_region", - "AWS_ACCESS_KEY": "env_akid", - "AWS_SECRET_ACCESS_KEY": "env_secret", - "AWS_PROFILE": "other_profile", - }, - InProfile: "full_profile", - OutRegion: "env_region", - OutCreds: credentials.Value{ - AccessKeyID: "env_akid", - SecretAccessKey: "env_secret", - ProviderName: "EnvConfigCredentials", - }, - }, - { - InEnvs: map[string]string{ - "AWS_SDK_LOAD_CONFIG": "0", - "AWS_SHARED_CREDENTIALS_FILE": testConfigFilename, - "AWS_CONFIG_FILE": testConfigOtherFilename, - "AWS_PROFILE": "shared_profile", - }, - InProfile: "config_file_load_order", - OutRegion: "shared_config_region", - OutCreds: credentials.Value{ - AccessKeyID: "shared_config_akid", - SecretAccessKey: "shared_config_secret", - ProviderName: "SharedConfigCredentials", - }, - }, - } - - for _, c := range cases { - oldEnv := initSessionTestEnv() - defer awstesting.PopEnv(oldEnv) - - for k, v := range c.InEnvs { - os.Setenv(k, v) - } - - s, err := NewSessionWithOptions(Options{ - Profile: c.InProfile, - SharedConfigState: SharedConfigEnable, - }) - assert.NoError(t, err) - - creds, err := s.Config.Credentials.Get() - assert.NoError(t, err) - assert.Equal(t, c.OutRegion, *s.Config.Region) - assert.Equal(t, c.OutCreds.AccessKeyID, creds.AccessKeyID) - assert.Equal(t, c.OutCreds.SecretAccessKey, creds.SecretAccessKey) - assert.Equal(t, c.OutCreds.SessionToken, creds.SessionToken) - assert.Contains(t, creds.ProviderName, c.OutCreds.ProviderName) - } -} - -const assumeRoleRespMsg = ` - - - - arn:aws:sts::account_id:assumed-role/role/session_name - AKID:session_name - - - AKID - SECRET - SESSION_TOKEN - %s - - - - request-id - - -` - -func TestSesisonAssumeRole(t *testing.T) { - oldEnv := initSessionTestEnv() - defer awstesting.PopEnv(oldEnv) - - os.Setenv("AWS_REGION", "us-east-1") - os.Setenv("AWS_SDK_LOAD_CONFIG", "1") - os.Setenv("AWS_SHARED_CREDENTIALS_FILE", testConfigFilename) - os.Setenv("AWS_PROFILE", "assume_role_w_creds") - - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Write([]byte(fmt.Sprintf(assumeRoleRespMsg, time.Now().Add(15*time.Minute).Format("2006-01-02T15:04:05Z")))) - })) - - s, err := NewSession(&aws.Config{Endpoint: aws.String(server.URL), DisableSSL: aws.Bool(true)}) - - creds, err := s.Config.Credentials.Get() - assert.NoError(t, err) - assert.Equal(t, "AKID", creds.AccessKeyID) - assert.Equal(t, "SECRET", creds.SecretAccessKey) - assert.Equal(t, "SESSION_TOKEN", creds.SessionToken) - assert.Contains(t, creds.ProviderName, "AssumeRoleProvider") -} - -func TestSessionAssumeRole_WithMFA(t *testing.T) { - oldEnv := initSessionTestEnv() - defer awstesting.PopEnv(oldEnv) - - os.Setenv("AWS_REGION", "us-east-1") - os.Setenv("AWS_SDK_LOAD_CONFIG", "1") - os.Setenv("AWS_SHARED_CREDENTIALS_FILE", testConfigFilename) - os.Setenv("AWS_PROFILE", "assume_role_w_creds") - - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.FormValue("SerialNumber"), "0123456789") - assert.Equal(t, r.FormValue("TokenCode"), "tokencode") - - w.Write([]byte(fmt.Sprintf(assumeRoleRespMsg, time.Now().Add(15*time.Minute).Format("2006-01-02T15:04:05Z")))) - })) - - customProviderCalled := false - sess, err := NewSessionWithOptions(Options{ - Profile: "assume_role_w_mfa", - Config: aws.Config{ - Region: aws.String("us-east-1"), - Endpoint: aws.String(server.URL), - DisableSSL: aws.Bool(true), - }, - SharedConfigState: SharedConfigEnable, - AssumeRoleTokenProvider: func() (string, error) { - customProviderCalled = true - - return "tokencode", nil - }, - }) - assert.NoError(t, err) - - creds, err := sess.Config.Credentials.Get() - assert.NoError(t, err) - assert.True(t, customProviderCalled) - - assert.Equal(t, "AKID", creds.AccessKeyID) - assert.Equal(t, "SECRET", creds.SecretAccessKey) - assert.Equal(t, "SESSION_TOKEN", creds.SessionToken) - assert.Contains(t, creds.ProviderName, "AssumeRoleProvider") -} - -func TestSessionAssumeRole_WithMFA_NoTokenProvider(t *testing.T) { - oldEnv := initSessionTestEnv() - defer awstesting.PopEnv(oldEnv) - - os.Setenv("AWS_REGION", "us-east-1") - os.Setenv("AWS_SDK_LOAD_CONFIG", "1") - os.Setenv("AWS_SHARED_CREDENTIALS_FILE", testConfigFilename) - os.Setenv("AWS_PROFILE", "assume_role_w_creds") - - _, err := NewSessionWithOptions(Options{ - Profile: "assume_role_w_mfa", - SharedConfigState: SharedConfigEnable, - }) - assert.Equal(t, err, AssumeRoleTokenProviderNotSetError{}) -} - -func TestSessionAssumeRole_DisableSharedConfig(t *testing.T) { - // Backwards compatibility with Shared config disabled - // assume role should not be built into the config. - oldEnv := initSessionTestEnv() - defer awstesting.PopEnv(oldEnv) - - os.Setenv("AWS_SDK_LOAD_CONFIG", "0") - os.Setenv("AWS_SHARED_CREDENTIALS_FILE", testConfigFilename) - os.Setenv("AWS_PROFILE", "assume_role_w_creds") - - s, err := NewSession() - assert.NoError(t, err) - - creds, err := s.Config.Credentials.Get() - assert.NoError(t, err) - assert.Equal(t, "assume_role_w_creds_akid", creds.AccessKeyID) - assert.Equal(t, "assume_role_w_creds_secret", creds.SecretAccessKey) - assert.Contains(t, creds.ProviderName, "SharedConfigCredentials") -} - -func TestSessionAssumeRole_InvalidSourceProfile(t *testing.T) { - // Backwards compatibility with Shared config disabled - // assume role should not be built into the config. - oldEnv := initSessionTestEnv() - defer awstesting.PopEnv(oldEnv) - - os.Setenv("AWS_SDK_LOAD_CONFIG", "1") - os.Setenv("AWS_SHARED_CREDENTIALS_FILE", testConfigFilename) - os.Setenv("AWS_PROFILE", "assume_role_invalid_source_profile") - - s, err := NewSession() - assert.Error(t, err) - assert.Contains(t, err.Error(), "SharedConfigAssumeRoleError: failed to load assume role") - assert.Nil(t, s) -} - -func initSessionTestEnv() (oldEnv []string) { - oldEnv = awstesting.StashEnv() - os.Setenv("AWS_CONFIG_FILE", "file_not_exists") - os.Setenv("AWS_SHARED_CREDENTIALS_FILE", "file_not_exists") - - return oldEnv -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/session/shared_config_test.go b/vendor/github.com/aws/aws-sdk-go/aws/session/shared_config_test.go deleted file mode 100644 index 3a07b8d97..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/session/shared_config_test.go +++ /dev/null @@ -1,274 +0,0 @@ -package session - -import ( - "fmt" - "path/filepath" - "testing" - - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/go-ini/ini" - "github.com/stretchr/testify/assert" -) - -var ( - testConfigFilename = filepath.Join("testdata", "shared_config") - testConfigOtherFilename = filepath.Join("testdata", "shared_config_other") -) - -func TestLoadSharedConfig(t *testing.T) { - cases := []struct { - Filenames []string - Profile string - Expected sharedConfig - Err error - }{ - { - Filenames: []string{"file_not_exists"}, - Profile: "default", - }, - { - Filenames: []string{testConfigFilename}, - Expected: sharedConfig{ - Region: "default_region", - }, - }, - { - Filenames: []string{testConfigOtherFilename, testConfigFilename}, - Profile: "config_file_load_order", - Expected: sharedConfig{ - Region: "shared_config_region", - Creds: credentials.Value{ - AccessKeyID: "shared_config_akid", - SecretAccessKey: "shared_config_secret", - ProviderName: fmt.Sprintf("SharedConfigCredentials: %s", testConfigFilename), - }, - }, - }, - { - Filenames: []string{testConfigFilename, testConfigOtherFilename}, - Profile: "config_file_load_order", - Expected: sharedConfig{ - Region: "shared_config_other_region", - Creds: credentials.Value{ - AccessKeyID: "shared_config_other_akid", - SecretAccessKey: "shared_config_other_secret", - ProviderName: fmt.Sprintf("SharedConfigCredentials: %s", testConfigOtherFilename), - }, - }, - }, - { - Filenames: []string{testConfigOtherFilename, testConfigFilename}, - Profile: "assume_role", - Expected: sharedConfig{ - AssumeRole: assumeRoleConfig{ - RoleARN: "assume_role_role_arn", - SourceProfile: "complete_creds", - }, - AssumeRoleSource: &sharedConfig{ - Creds: credentials.Value{ - AccessKeyID: "complete_creds_akid", - SecretAccessKey: "complete_creds_secret", - ProviderName: fmt.Sprintf("SharedConfigCredentials: %s", testConfigFilename), - }, - }, - }, - }, - { - Filenames: []string{testConfigOtherFilename, testConfigFilename}, - Profile: "assume_role_invalid_source_profile", - Expected: sharedConfig{ - AssumeRole: assumeRoleConfig{ - RoleARN: "assume_role_invalid_source_profile_role_arn", - SourceProfile: "profile_not_exists", - }, - }, - Err: SharedConfigAssumeRoleError{RoleARN: "assume_role_invalid_source_profile_role_arn"}, - }, - { - Filenames: []string{testConfigOtherFilename, testConfigFilename}, - Profile: "assume_role_w_creds", - Expected: sharedConfig{ - Creds: credentials.Value{ - AccessKeyID: "assume_role_w_creds_akid", - SecretAccessKey: "assume_role_w_creds_secret", - ProviderName: fmt.Sprintf("SharedConfigCredentials: %s", testConfigFilename), - }, - AssumeRole: assumeRoleConfig{ - RoleARN: "assume_role_w_creds_role_arn", - SourceProfile: "assume_role_w_creds", - ExternalID: "1234", - RoleSessionName: "assume_role_w_creds_session_name", - }, - AssumeRoleSource: &sharedConfig{ - Creds: credentials.Value{ - AccessKeyID: "assume_role_w_creds_akid", - SecretAccessKey: "assume_role_w_creds_secret", - ProviderName: fmt.Sprintf("SharedConfigCredentials: %s", testConfigFilename), - }, - }, - }, - }, - { - Filenames: []string{testConfigOtherFilename, testConfigFilename}, - Profile: "assume_role_wo_creds", - Expected: sharedConfig{ - AssumeRole: assumeRoleConfig{ - RoleARN: "assume_role_wo_creds_role_arn", - SourceProfile: "assume_role_wo_creds", - }, - }, - Err: SharedConfigAssumeRoleError{RoleARN: "assume_role_wo_creds_role_arn"}, - }, - { - Filenames: []string{filepath.Join("testdata", "shared_config_invalid_ini")}, - Profile: "profile_name", - Err: SharedConfigLoadError{Filename: filepath.Join("testdata", "shared_config_invalid_ini")}, - }, - } - - for i, c := range cases { - cfg, err := loadSharedConfig(c.Profile, c.Filenames) - if c.Err != nil { - assert.Contains(t, err.Error(), c.Err.Error(), "expected error, %d", i) - continue - } - - assert.NoError(t, err, "unexpected error, %d", i) - assert.Equal(t, c.Expected, cfg, "not equal, %d", i) - } -} - -func TestLoadSharedConfigFromFile(t *testing.T) { - filename := testConfigFilename - f, err := ini.Load(filename) - if err != nil { - t.Fatalf("failed to load test config file, %s, %v", filename, err) - } - iniFile := sharedConfigFile{IniData: f, Filename: filename} - - cases := []struct { - Profile string - Expected sharedConfig - Err error - }{ - { - Profile: "default", - Expected: sharedConfig{Region: "default_region"}, - }, - { - Profile: "alt_profile_name", - Expected: sharedConfig{Region: "alt_profile_name_region"}, - }, - { - Profile: "short_profile_name_first", - Expected: sharedConfig{Region: "short_profile_name_first_short"}, - }, - { - Profile: "partial_creds", - Expected: sharedConfig{}, - }, - { - Profile: "complete_creds", - Expected: sharedConfig{ - Creds: credentials.Value{ - AccessKeyID: "complete_creds_akid", - SecretAccessKey: "complete_creds_secret", - ProviderName: fmt.Sprintf("SharedConfigCredentials: %s", testConfigFilename), - }, - }, - }, - { - Profile: "complete_creds_with_token", - Expected: sharedConfig{ - Creds: credentials.Value{ - AccessKeyID: "complete_creds_with_token_akid", - SecretAccessKey: "complete_creds_with_token_secret", - SessionToken: "complete_creds_with_token_token", - ProviderName: fmt.Sprintf("SharedConfigCredentials: %s", testConfigFilename), - }, - }, - }, - { - Profile: "full_profile", - Expected: sharedConfig{ - Creds: credentials.Value{ - AccessKeyID: "full_profile_akid", - SecretAccessKey: "full_profile_secret", - ProviderName: fmt.Sprintf("SharedConfigCredentials: %s", testConfigFilename), - }, - Region: "full_profile_region", - }, - }, - { - Profile: "partial_assume_role", - Expected: sharedConfig{}, - }, - { - Profile: "assume_role", - Expected: sharedConfig{ - AssumeRole: assumeRoleConfig{ - RoleARN: "assume_role_role_arn", - SourceProfile: "complete_creds", - }, - }, - }, - { - Profile: "assume_role_w_mfa", - Expected: sharedConfig{ - AssumeRole: assumeRoleConfig{ - RoleARN: "assume_role_role_arn", - SourceProfile: "complete_creds", - MFASerial: "0123456789", - }, - }, - }, - { - Profile: "does_not_exists", - Err: SharedConfigProfileNotExistsError{Profile: "does_not_exists"}, - }, - } - - for i, c := range cases { - cfg := sharedConfig{} - - err := cfg.setFromIniFile(c.Profile, iniFile) - if c.Err != nil { - assert.Contains(t, err.Error(), c.Err.Error(), "expected error, %d", i) - continue - } - - assert.NoError(t, err, "unexpected error, %d", i) - assert.Equal(t, c.Expected, cfg, "not equal, %d", i) - } -} - -func TestLoadSharedConfigIniFiles(t *testing.T) { - cases := []struct { - Filenames []string - Expected []sharedConfigFile - }{ - { - Filenames: []string{"not_exists", testConfigFilename}, - Expected: []sharedConfigFile{ - {Filename: testConfigFilename}, - }, - }, - { - Filenames: []string{testConfigFilename, testConfigOtherFilename}, - Expected: []sharedConfigFile{ - {Filename: testConfigFilename}, - {Filename: testConfigOtherFilename}, - }, - }, - } - - for i, c := range cases { - files, err := loadSharedConfigIniFiles(c.Filenames) - assert.NoError(t, err, "unexpected error, %d", i) - assert.Equal(t, len(c.Expected), len(files), "expected num files, %d", i) - - for i, expectedFile := range c.Expected { - assert.Equal(t, expectedFile.Filename, files[i].Filename) - } - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/functional_1_5_test.go b/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/functional_1_5_test.go deleted file mode 100644 index 2e591c27f..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/functional_1_5_test.go +++ /dev/null @@ -1,86 +0,0 @@ -// +build go1.5 - -package v4_test - -import ( - "fmt" - "net/http" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws/signer/v4" - "github.com/aws/aws-sdk-go/awstesting/unit" -) - -func TestStandaloneSign(t *testing.T) { - creds := unit.Session.Config.Credentials - signer := v4.NewSigner(creds) - - for _, c := range standaloneSignCases { - host := fmt.Sprintf("https://%s.%s.%s.amazonaws.com", - c.SubDomain, c.Region, c.Service) - - req, err := http.NewRequest("GET", host, nil) - if err != nil { - t.Errorf("expected no error, but received %v", err) - } - - // URL.EscapedPath() will be used by the signer to get the - // escaped form of the request's URI path. - req.URL.Path = c.OrigURI - req.URL.RawQuery = c.OrigQuery - - _, err = signer.Sign(req, nil, c.Service, c.Region, time.Unix(0, 0)) - if err != nil { - t.Errorf("expected no error, but received %v", err) - } - - actual := req.Header.Get("Authorization") - if e, a := c.ExpSig, actual; e != a { - t.Errorf("expected %v, but recieved %v", e, a) - } - if e, a := c.OrigURI, req.URL.Path; e != a { - t.Errorf("expected %v, but recieved %v", e, a) - } - if e, a := c.EscapedURI, req.URL.EscapedPath(); e != a { - t.Errorf("expected %v, but recieved %v", e, a) - } - } -} - -func TestStandaloneSign_RawPath(t *testing.T) { - creds := unit.Session.Config.Credentials - signer := v4.NewSigner(creds) - - for _, c := range standaloneSignCases { - host := fmt.Sprintf("https://%s.%s.%s.amazonaws.com", - c.SubDomain, c.Region, c.Service) - - req, err := http.NewRequest("GET", host, nil) - if err != nil { - t.Errorf("expected no error, but received %v", err) - } - - // URL.EscapedPath() will be used by the signer to get the - // escaped form of the request's URI path. - req.URL.Path = c.OrigURI - req.URL.RawPath = c.EscapedURI - req.URL.RawQuery = c.OrigQuery - - _, err = signer.Sign(req, nil, c.Service, c.Region, time.Unix(0, 0)) - if err != nil { - t.Errorf("expected no error, but received %v", err) - } - - actual := req.Header.Get("Authorization") - if e, a := c.ExpSig, actual; e != a { - t.Errorf("expected %v, but recieved %v", e, a) - } - if e, a := c.OrigURI, req.URL.Path; e != a { - t.Errorf("expected %v, but recieved %v", e, a) - } - if e, a := c.EscapedURI, req.URL.EscapedPath(); e != a { - t.Errorf("expected %v, but recieved %v", e, a) - } - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/functional_test.go b/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/functional_test.go deleted file mode 100644 index c5341a935..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/functional_test.go +++ /dev/null @@ -1,166 +0,0 @@ -package v4_test - -import ( - "net/http" - "net/url" - "reflect" - "strings" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/signer/v4" - "github.com/aws/aws-sdk-go/awstesting/unit" - "github.com/aws/aws-sdk-go/service/s3" -) - -var standaloneSignCases = []struct { - OrigURI string - OrigQuery string - Region, Service, SubDomain string - ExpSig string - EscapedURI string -}{ - { - OrigURI: `/logs-*/_search`, - OrigQuery: `pretty=true`, - Region: "us-west-2", Service: "es", SubDomain: "hostname-clusterkey", - EscapedURI: `/logs-%2A/_search`, - ExpSig: `AWS4-HMAC-SHA256 Credential=AKID/19700101/us-west-2/es/aws4_request, SignedHeaders=host;x-amz-date;x-amz-security-token, Signature=79d0760751907af16f64a537c1242416dacf51204a7dd5284492d15577973b91`, - }, -} - -func TestPresignHandler(t *testing.T) { - svc := s3.New(unit.Session) - req, _ := svc.PutObjectRequest(&s3.PutObjectInput{ - Bucket: aws.String("bucket"), - Key: aws.String("key"), - ContentDisposition: aws.String("a+b c$d"), - ACL: aws.String("public-read"), - }) - req.Time = time.Unix(0, 0) - urlstr, err := req.Presign(5 * time.Minute) - - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - - expectedHost := "bucket.s3.mock-region.amazonaws.com" - expectedDate := "19700101T000000Z" - expectedHeaders := "content-disposition;host;x-amz-acl" - expectedSig := "a46583256431b09eb45ba4af2e6286d96a9835ed13721023dc8076dfdcb90fcb" - expectedCred := "AKID/19700101/mock-region/s3/aws4_request" - - u, _ := url.Parse(urlstr) - urlQ := u.Query() - if e, a := expectedHost, u.Host; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := expectedSig, urlQ.Get("X-Amz-Signature"); e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := expectedCred, urlQ.Get("X-Amz-Credential"); e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := expectedHeaders, urlQ.Get("X-Amz-SignedHeaders"); e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := expectedDate, urlQ.Get("X-Amz-Date"); e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "300", urlQ.Get("X-Amz-Expires"); e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "UNSIGNED-PAYLOAD", urlQ.Get("X-Amz-Content-Sha256"); e != a { - t.Errorf("expect %v, got %v", e, a) - } - - if e, a := "+", urlstr; strings.Contains(a, e) { // + encoded as %20 - t.Errorf("expect %v not to be in %v", e, a) - } -} - -func TestPresignRequest(t *testing.T) { - svc := s3.New(unit.Session) - req, _ := svc.PutObjectRequest(&s3.PutObjectInput{ - Bucket: aws.String("bucket"), - Key: aws.String("key"), - ContentDisposition: aws.String("a+b c$d"), - ACL: aws.String("public-read"), - }) - req.Time = time.Unix(0, 0) - urlstr, headers, err := req.PresignRequest(5 * time.Minute) - - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - - expectedHost := "bucket.s3.mock-region.amazonaws.com" - expectedDate := "19700101T000000Z" - expectedHeaders := "content-disposition;host;x-amz-acl" - expectedSig := "a46583256431b09eb45ba4af2e6286d96a9835ed13721023dc8076dfdcb90fcb" - expectedCred := "AKID/19700101/mock-region/s3/aws4_request" - expectedHeaderMap := http.Header{ - "x-amz-acl": []string{"public-read"}, - "content-disposition": []string{"a+b c$d"}, - } - - u, _ := url.Parse(urlstr) - urlQ := u.Query() - if e, a := expectedHost, u.Host; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := expectedSig, urlQ.Get("X-Amz-Signature"); e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := expectedCred, urlQ.Get("X-Amz-Credential"); e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := expectedHeaders, urlQ.Get("X-Amz-SignedHeaders"); e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := expectedDate, urlQ.Get("X-Amz-Date"); e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := expectedHeaderMap, headers; !reflect.DeepEqual(e, a) { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "300", urlQ.Get("X-Amz-Expires"); e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "UNSIGNED-PAYLOAD", urlQ.Get("X-Amz-Content-Sha256"); e != a { - t.Errorf("expect %v, got %v", e, a) - } - - if e, a := "+", urlstr; strings.Contains(a, e) { // + encoded as %20 - t.Errorf("expect %v not to be in %v", e, a) - } -} - -func TestStandaloneSign_CustomURIEscape(t *testing.T) { - var expectSig = `AWS4-HMAC-SHA256 Credential=AKID/19700101/us-east-1/es/aws4_request, SignedHeaders=host;x-amz-date;x-amz-security-token, Signature=6601e883cc6d23871fd6c2a394c5677ea2b8c82b04a6446786d64cd74f520967` - - creds := unit.Session.Config.Credentials - signer := v4.NewSigner(creds, func(s *v4.Signer) { - s.DisableURIPathEscaping = true - }) - - host := "https://subdomain.us-east-1.es.amazonaws.com" - req, err := http.NewRequest("GET", host, nil) - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - - req.URL.Path = `/log-*/_search` - req.URL.Opaque = "//subdomain.us-east-1.es.amazonaws.com/log-%2A/_search" - - _, err = signer.Sign(req, nil, "es", "us-east-1", time.Unix(0, 0)) - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - - actual := req.Header.Get("Authorization") - if e, a := expectSig, actual; e != a { - t.Errorf("expect %v, got %v", e, a) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/header_rules_test.go b/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/header_rules_test.go deleted file mode 100644 index f4be951ac..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/header_rules_test.go +++ /dev/null @@ -1,77 +0,0 @@ -package v4 - -import ( - "testing" -) - -func TestRuleCheckWhitelist(t *testing.T) { - w := whitelist{ - mapRule{ - "Cache-Control": struct{}{}, - }, - } - - if !w.IsValid("Cache-Control") { - t.Error("expected true value") - } - if w.IsValid("Cache-") { - t.Error("expected false value") - } -} - -func TestRuleCheckBlacklist(t *testing.T) { - b := blacklist{ - mapRule{ - "Cache-Control": struct{}{}, - }, - } - - if b.IsValid("Cache-Control") { - t.Error("expected false value") - } - if !b.IsValid("Cache-") { - t.Error("expected true value") - } -} - -func TestRuleCheckPattern(t *testing.T) { - p := patterns{"X-Amz-Meta-"} - - if !p.IsValid("X-Amz-Meta-") { - t.Error("expected true value") - } - if !p.IsValid("X-Amz-Meta-Star") { - t.Error("expected true value") - } - if p.IsValid("Cache-") { - t.Error("expected false value") - } -} - -func TestRuleComplexWhitelist(t *testing.T) { - w := rules{ - whitelist{ - mapRule{ - "Cache-Control": struct{}{}, - }, - }, - patterns{"X-Amz-Meta-"}, - } - - r := rules{ - inclusiveRules{patterns{"X-Amz-"}, blacklist{w}}, - } - - if !r.IsValid("X-Amz-Blah") { - t.Error("expected true value") - } - if r.IsValid("X-Amz-Meta-") { - t.Error("expected false value") - } - if r.IsValid("X-Amz-Meta-Star") { - t.Error("expected false value") - } - if r.IsValid("Cache-Control") { - t.Error("expected false value") - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/v4_test.go b/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/v4_test.go deleted file mode 100644 index 45d0eb886..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/v4_test.go +++ /dev/null @@ -1,644 +0,0 @@ -package v4 - -import ( - "bytes" - "io" - "io/ioutil" - "net/http" - "net/http/httptest" - "reflect" - "strings" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/awstesting" -) - -func TestStripExcessHeaders(t *testing.T) { - vals := []string{ - "", - "123", - "1 2 3", - "1 2 3 ", - " 1 2 3", - "1 2 3", - "1 23", - "1 2 3", - "1 2 ", - " 1 2 ", - "12 3", - "12 3 1", - "12 3 1", - "12 3 1abc123", - } - - expected := []string{ - "", - "123", - "1 2 3", - "1 2 3", - "1 2 3", - "1 2 3", - "1 23", - "1 2 3", - "1 2", - "1 2", - "12 3", - "12 3 1", - "12 3 1", - "12 3 1abc123", - } - - stripExcessSpaces(vals) - for i := 0; i < len(vals); i++ { - if e, a := expected[i], vals[i]; e != a { - t.Errorf("%d, expect %v, got %v", i, e, a) - } - } -} - -func buildRequest(serviceName, region, body string) (*http.Request, io.ReadSeeker) { - endpoint := "https://" + serviceName + "." + region + ".amazonaws.com" - reader := strings.NewReader(body) - req, _ := http.NewRequest("POST", endpoint, reader) - req.URL.Opaque = "//example.org/bucket/key-._~,!@#$%^&*()" - req.Header.Add("X-Amz-Target", "prefix.Operation") - req.Header.Add("Content-Type", "application/x-amz-json-1.0") - req.Header.Add("Content-Length", string(len(body))) - req.Header.Add("X-Amz-Meta-Other-Header", "some-value=!@#$%^&* (+)") - req.Header.Add("X-Amz-Meta-Other-Header_With_Underscore", "some-value=!@#$%^&* (+)") - req.Header.Add("X-amz-Meta-Other-Header_With_Underscore", "some-value=!@#$%^&* (+)") - return req, reader -} - -func buildSigner() Signer { - return Signer{ - Credentials: credentials.NewStaticCredentials("AKID", "SECRET", "SESSION"), - } -} - -func removeWS(text string) string { - text = strings.Replace(text, " ", "", -1) - text = strings.Replace(text, "\n", "", -1) - text = strings.Replace(text, "\t", "", -1) - return text -} - -func assertEqual(t *testing.T, expected, given string) { - if removeWS(expected) != removeWS(given) { - t.Errorf("\nExpected: %s\nGiven: %s", expected, given) - } -} - -func TestPresignRequest(t *testing.T) { - req, body := buildRequest("dynamodb", "us-east-1", "{}") - - signer := buildSigner() - signer.Presign(req, body, "dynamodb", "us-east-1", 300*time.Second, time.Unix(0, 0)) - - expectedDate := "19700101T000000Z" - expectedHeaders := "content-length;content-type;host;x-amz-meta-other-header;x-amz-meta-other-header_with_underscore" - expectedSig := "ea7856749041f727690c580569738282e99c79355fe0d8f125d3b5535d2ece83" - expectedCred := "AKID/19700101/us-east-1/dynamodb/aws4_request" - expectedTarget := "prefix.Operation" - - q := req.URL.Query() - if e, a := expectedSig, q.Get("X-Amz-Signature"); e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := expectedCred, q.Get("X-Amz-Credential"); e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := expectedHeaders, q.Get("X-Amz-SignedHeaders"); e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := expectedDate, q.Get("X-Amz-Date"); e != a { - t.Errorf("expect %v, got %v", e, a) - } - if a := q.Get("X-Amz-Meta-Other-Header"); len(a) != 0 { - t.Errorf("expect %v to be empty", a) - } - if e, a := expectedTarget, q.Get("X-Amz-Target"); e != a { - t.Errorf("expect %v, got %v", e, a) - } -} - -func TestPresignBodyWithArrayRequest(t *testing.T) { - req, body := buildRequest("dynamodb", "us-east-1", "{}") - req.URL.RawQuery = "Foo=z&Foo=o&Foo=m&Foo=a" - - signer := buildSigner() - signer.Presign(req, body, "dynamodb", "us-east-1", 300*time.Second, time.Unix(0, 0)) - - expectedDate := "19700101T000000Z" - expectedHeaders := "content-length;content-type;host;x-amz-meta-other-header;x-amz-meta-other-header_with_underscore" - expectedSig := "fef6002062400bbf526d70f1a6456abc0fb2e213fe1416012737eebd42a62924" - expectedCred := "AKID/19700101/us-east-1/dynamodb/aws4_request" - expectedTarget := "prefix.Operation" - - q := req.URL.Query() - if e, a := expectedSig, q.Get("X-Amz-Signature"); e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := expectedCred, q.Get("X-Amz-Credential"); e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := expectedHeaders, q.Get("X-Amz-SignedHeaders"); e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := expectedDate, q.Get("X-Amz-Date"); e != a { - t.Errorf("expect %v, got %v", e, a) - } - if a := q.Get("X-Amz-Meta-Other-Header"); len(a) != 0 { - t.Errorf("expect %v to be empty, was not", a) - } - if e, a := expectedTarget, q.Get("X-Amz-Target"); e != a { - t.Errorf("expect %v, got %v", e, a) - } -} - -func TestSignRequest(t *testing.T) { - req, body := buildRequest("dynamodb", "us-east-1", "{}") - signer := buildSigner() - signer.Sign(req, body, "dynamodb", "us-east-1", time.Unix(0, 0)) - - expectedDate := "19700101T000000Z" - expectedSig := "AWS4-HMAC-SHA256 Credential=AKID/19700101/us-east-1/dynamodb/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date;x-amz-meta-other-header;x-amz-meta-other-header_with_underscore;x-amz-security-token;x-amz-target, Signature=ea766cabd2ec977d955a3c2bae1ae54f4515d70752f2207618396f20aa85bd21" - - q := req.Header - if e, a := expectedSig, q.Get("Authorization"); e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := expectedDate, q.Get("X-Amz-Date"); e != a { - t.Errorf("expect %v, got %v", e, a) - } -} - -func TestSignBodyS3(t *testing.T) { - req, body := buildRequest("s3", "us-east-1", "hello") - signer := buildSigner() - signer.Sign(req, body, "s3", "us-east-1", time.Now()) - hash := req.Header.Get("X-Amz-Content-Sha256") - if e, a := "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824", hash; e != a { - t.Errorf("expect %v, got %v", e, a) - } -} - -func TestSignBodyGlacier(t *testing.T) { - req, body := buildRequest("glacier", "us-east-1", "hello") - signer := buildSigner() - signer.Sign(req, body, "glacier", "us-east-1", time.Now()) - hash := req.Header.Get("X-Amz-Content-Sha256") - if e, a := "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824", hash; e != a { - t.Errorf("expect %v, got %v", e, a) - } -} - -func TestPresignEmptyBodyS3(t *testing.T) { - req, body := buildRequest("s3", "us-east-1", "hello") - signer := buildSigner() - signer.Presign(req, body, "s3", "us-east-1", 5*time.Minute, time.Now()) - hash := req.Header.Get("X-Amz-Content-Sha256") - if e, a := "UNSIGNED-PAYLOAD", hash; e != a { - t.Errorf("expect %v, got %v", e, a) - } -} - -func TestSignPrecomputedBodyChecksum(t *testing.T) { - req, body := buildRequest("dynamodb", "us-east-1", "hello") - req.Header.Set("X-Amz-Content-Sha256", "PRECOMPUTED") - signer := buildSigner() - signer.Sign(req, body, "dynamodb", "us-east-1", time.Now()) - hash := req.Header.Get("X-Amz-Content-Sha256") - if e, a := "PRECOMPUTED", hash; e != a { - t.Errorf("expect %v, got %v", e, a) - } -} - -func TestAnonymousCredentials(t *testing.T) { - svc := awstesting.NewClient(&aws.Config{Credentials: credentials.AnonymousCredentials}) - r := svc.NewRequest( - &request.Operation{ - Name: "BatchGetItem", - HTTPMethod: "POST", - HTTPPath: "/", - }, - nil, - nil, - ) - SignSDKRequest(r) - - urlQ := r.HTTPRequest.URL.Query() - if a := urlQ.Get("X-Amz-Signature"); len(a) != 0 { - t.Errorf("expect %v to be empty, was not", a) - } - if a := urlQ.Get("X-Amz-Credential"); len(a) != 0 { - t.Errorf("expect %v to be empty, was not", a) - } - if a := urlQ.Get("X-Amz-SignedHeaders"); len(a) != 0 { - t.Errorf("expect %v to be empty, was not", a) - } - if a := urlQ.Get("X-Amz-Date"); len(a) != 0 { - t.Errorf("expect %v to be empty, was not", a) - } - - hQ := r.HTTPRequest.Header - if a := hQ.Get("Authorization"); len(a) != 0 { - t.Errorf("expect %v to be empty, was not", a) - } - if a := hQ.Get("X-Amz-Date"); len(a) != 0 { - t.Errorf("expect %v to be empty, was not", a) - } -} - -func TestIgnoreResignRequestWithValidCreds(t *testing.T) { - svc := awstesting.NewClient(&aws.Config{ - Credentials: credentials.NewStaticCredentials("AKID", "SECRET", "SESSION"), - Region: aws.String("us-west-2"), - }) - r := svc.NewRequest( - &request.Operation{ - Name: "BatchGetItem", - HTTPMethod: "POST", - HTTPPath: "/", - }, - nil, - nil, - ) - - SignSDKRequest(r) - sig := r.HTTPRequest.Header.Get("Authorization") - - signSDKRequestWithCurrTime(r, func() time.Time { - // Simulate one second has passed so that signature's date changes - // when it is resigned. - return time.Now().Add(1 * time.Second) - }) - if e, a := sig, r.HTTPRequest.Header.Get("Authorization"); e == a { - t.Errorf("expect %v to be %v, but was not", e, a) - } -} - -func TestIgnorePreResignRequestWithValidCreds(t *testing.T) { - svc := awstesting.NewClient(&aws.Config{ - Credentials: credentials.NewStaticCredentials("AKID", "SECRET", "SESSION"), - Region: aws.String("us-west-2"), - }) - r := svc.NewRequest( - &request.Operation{ - Name: "BatchGetItem", - HTTPMethod: "POST", - HTTPPath: "/", - }, - nil, - nil, - ) - r.ExpireTime = time.Minute * 10 - - SignSDKRequest(r) - sig := r.HTTPRequest.URL.Query().Get("X-Amz-Signature") - - signSDKRequestWithCurrTime(r, func() time.Time { - // Simulate one second has passed so that signature's date changes - // when it is resigned. - return time.Now().Add(1 * time.Second) - }) - if e, a := sig, r.HTTPRequest.URL.Query().Get("X-Amz-Signature"); e == a { - t.Errorf("expect %v to be %v, but was not", e, a) - } -} - -func TestResignRequestExpiredCreds(t *testing.T) { - creds := credentials.NewStaticCredentials("AKID", "SECRET", "SESSION") - svc := awstesting.NewClient(&aws.Config{Credentials: creds}) - r := svc.NewRequest( - &request.Operation{ - Name: "BatchGetItem", - HTTPMethod: "POST", - HTTPPath: "/", - }, - nil, - nil, - ) - SignSDKRequest(r) - querySig := r.HTTPRequest.Header.Get("Authorization") - var origSignedHeaders string - for _, p := range strings.Split(querySig, ", ") { - if strings.HasPrefix(p, "SignedHeaders=") { - origSignedHeaders = p[len("SignedHeaders="):] - break - } - } - if a := origSignedHeaders; len(a) == 0 { - t.Errorf("expect not to be empty, but was") - } - if e, a := origSignedHeaders, "authorization"; strings.Contains(a, e) { - t.Errorf("expect %v to not be in %v, but was", e, a) - } - origSignedAt := r.LastSignedAt - - creds.Expire() - - signSDKRequestWithCurrTime(r, func() time.Time { - // Simulate one second has passed so that signature's date changes - // when it is resigned. - return time.Now().Add(1 * time.Second) - }) - updatedQuerySig := r.HTTPRequest.Header.Get("Authorization") - if e, a := querySig, updatedQuerySig; e == a { - t.Errorf("expect %v to be %v, was not", e, a) - } - - var updatedSignedHeaders string - for _, p := range strings.Split(updatedQuerySig, ", ") { - if strings.HasPrefix(p, "SignedHeaders=") { - updatedSignedHeaders = p[len("SignedHeaders="):] - break - } - } - if a := updatedSignedHeaders; len(a) == 0 { - t.Errorf("expect not to be empty, but was") - } - if e, a := updatedQuerySig, "authorization"; strings.Contains(a, e) { - t.Errorf("expect %v to not be in %v, but was", e, a) - } - if e, a := origSignedAt, r.LastSignedAt; e == a { - t.Errorf("expect %v to be %v, was not", e, a) - } -} - -func TestPreResignRequestExpiredCreds(t *testing.T) { - provider := &credentials.StaticProvider{Value: credentials.Value{ - AccessKeyID: "AKID", - SecretAccessKey: "SECRET", - SessionToken: "SESSION", - }} - creds := credentials.NewCredentials(provider) - svc := awstesting.NewClient(&aws.Config{Credentials: creds}) - r := svc.NewRequest( - &request.Operation{ - Name: "BatchGetItem", - HTTPMethod: "POST", - HTTPPath: "/", - }, - nil, - nil, - ) - r.ExpireTime = time.Minute * 10 - - SignSDKRequest(r) - querySig := r.HTTPRequest.URL.Query().Get("X-Amz-Signature") - signedHeaders := r.HTTPRequest.URL.Query().Get("X-Amz-SignedHeaders") - if a := signedHeaders; len(a) == 0 { - t.Errorf("expect not to be empty, but was") - } - origSignedAt := r.LastSignedAt - - creds.Expire() - - signSDKRequestWithCurrTime(r, func() time.Time { - // Simulate the request occurred 15 minutes in the past - return time.Now().Add(-48 * time.Hour) - }) - if e, a := querySig, r.HTTPRequest.URL.Query().Get("X-Amz-Signature"); e == a { - t.Errorf("expect %v to be %v, was not", e, a) - } - resignedHeaders := r.HTTPRequest.URL.Query().Get("X-Amz-SignedHeaders") - if e, a := signedHeaders, resignedHeaders; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := signedHeaders, "x-amz-signedHeaders"; strings.Contains(a, e) { - t.Errorf("expect %v to not be in %v, but was", e, a) - } - if e, a := origSignedAt, r.LastSignedAt; e == a { - t.Errorf("expect %v to be %v, was not", e, a) - } -} - -func TestResignRequestExpiredRequest(t *testing.T) { - creds := credentials.NewStaticCredentials("AKID", "SECRET", "SESSION") - svc := awstesting.NewClient(&aws.Config{Credentials: creds}) - r := svc.NewRequest( - &request.Operation{ - Name: "BatchGetItem", - HTTPMethod: "POST", - HTTPPath: "/", - }, - nil, - nil, - ) - - SignSDKRequest(r) - querySig := r.HTTPRequest.Header.Get("Authorization") - origSignedAt := r.LastSignedAt - - signSDKRequestWithCurrTime(r, func() time.Time { - // Simulate the request occurred 15 minutes in the past - return time.Now().Add(15 * time.Minute) - }) - if e, a := querySig, r.HTTPRequest.Header.Get("Authorization"); e == a { - t.Errorf("expect %v to be %v, was not", e, a) - } - if e, a := origSignedAt, r.LastSignedAt; e == a { - t.Errorf("expect %v to be %v, was not", e, a) - } -} - -func TestSignWithRequestBody(t *testing.T) { - creds := credentials.NewStaticCredentials("AKID", "SECRET", "SESSION") - signer := NewSigner(creds) - - expectBody := []byte("abc123") - - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - b, err := ioutil.ReadAll(r.Body) - r.Body.Close() - if err != nil { - t.Errorf("expect no error, got %v", err) - } - if e, a := expectBody, b; !reflect.DeepEqual(e, a) { - t.Errorf("expect %v, got %v", e, a) - } - w.WriteHeader(http.StatusOK) - })) - - req, err := http.NewRequest("POST", server.URL, nil) - - _, err = signer.Sign(req, bytes.NewReader(expectBody), "service", "region", time.Now()) - if err != nil { - t.Errorf("expect not no error, got %v", err) - } - - resp, err := http.DefaultClient.Do(req) - if err != nil { - t.Errorf("expect not no error, got %v", err) - } - if e, a := http.StatusOK, resp.StatusCode; e != a { - t.Errorf("expect %v, got %v", e, a) - } -} - -func TestSignWithRequestBody_Overwrite(t *testing.T) { - creds := credentials.NewStaticCredentials("AKID", "SECRET", "SESSION") - signer := NewSigner(creds) - - var expectBody []byte - - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - b, err := ioutil.ReadAll(r.Body) - r.Body.Close() - if err != nil { - t.Errorf("expect not no error, got %v", err) - } - if e, a := len(expectBody), len(b); e != a { - t.Errorf("expect %v, got %v", e, a) - } - w.WriteHeader(http.StatusOK) - })) - - req, err := http.NewRequest("GET", server.URL, strings.NewReader("invalid body")) - - _, err = signer.Sign(req, nil, "service", "region", time.Now()) - req.ContentLength = 0 - - if err != nil { - t.Errorf("expect not no error, got %v", err) - } - - resp, err := http.DefaultClient.Do(req) - if err != nil { - t.Errorf("expect not no error, got %v", err) - } - if e, a := http.StatusOK, resp.StatusCode; e != a { - t.Errorf("expect %v, got %v", e, a) - } -} - -func TestBuildCanonicalRequest(t *testing.T) { - req, body := buildRequest("dynamodb", "us-east-1", "{}") - req.URL.RawQuery = "Foo=z&Foo=o&Foo=m&Foo=a" - ctx := &signingCtx{ - ServiceName: "dynamodb", - Region: "us-east-1", - Request: req, - Body: body, - Query: req.URL.Query(), - Time: time.Now(), - ExpireTime: 5 * time.Second, - } - - ctx.buildCanonicalString() - expected := "https://example.org/bucket/key-._~,!@#$%^&*()?Foo=z&Foo=o&Foo=m&Foo=a" - if e, a := expected, ctx.Request.URL.String(); e != a { - t.Errorf("expect %v, got %v", e, a) - } -} - -func TestSignWithBody_ReplaceRequestBody(t *testing.T) { - creds := credentials.NewStaticCredentials("AKID", "SECRET", "SESSION") - req, seekerBody := buildRequest("dynamodb", "us-east-1", "{}") - req.Body = ioutil.NopCloser(bytes.NewReader([]byte{})) - - s := NewSigner(creds) - origBody := req.Body - - _, err := s.Sign(req, seekerBody, "dynamodb", "us-east-1", time.Now()) - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - - if req.Body == origBody { - t.Errorf("expeect request body to not be origBody") - } - - if req.Body == nil { - t.Errorf("expect request body to be changed but was nil") - } -} - -func TestSignWithBody_NoReplaceRequestBody(t *testing.T) { - creds := credentials.NewStaticCredentials("AKID", "SECRET", "SESSION") - req, seekerBody := buildRequest("dynamodb", "us-east-1", "{}") - req.Body = ioutil.NopCloser(bytes.NewReader([]byte{})) - - s := NewSigner(creds, func(signer *Signer) { - signer.DisableRequestBodyOverwrite = true - }) - - origBody := req.Body - - _, err := s.Sign(req, seekerBody, "dynamodb", "us-east-1", time.Now()) - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - - if req.Body != origBody { - t.Errorf("expect request body to not be chagned") - } -} - -func TestRequestHost(t *testing.T) { - req, body := buildRequest("dynamodb", "us-east-1", "{}") - req.URL.RawQuery = "Foo=z&Foo=o&Foo=m&Foo=a" - req.Host = "myhost" - ctx := &signingCtx{ - ServiceName: "dynamodb", - Region: "us-east-1", - Request: req, - Body: body, - Query: req.URL.Query(), - Time: time.Now(), - ExpireTime: 5 * time.Second, - } - - ctx.buildCanonicalHeaders(ignoredHeaders, ctx.Request.Header) - if !strings.Contains(ctx.canonicalHeaders, "host:"+req.Host) { - t.Errorf("canonical host header invalid") - } -} - -func BenchmarkPresignRequest(b *testing.B) { - signer := buildSigner() - req, body := buildRequest("dynamodb", "us-east-1", "{}") - for i := 0; i < b.N; i++ { - signer.Presign(req, body, "dynamodb", "us-east-1", 300*time.Second, time.Now()) - } -} - -func BenchmarkSignRequest(b *testing.B) { - signer := buildSigner() - req, body := buildRequest("dynamodb", "us-east-1", "{}") - for i := 0; i < b.N; i++ { - signer.Sign(req, body, "dynamodb", "us-east-1", time.Now()) - } -} - -var stripExcessSpaceCases = []string{ - `AWS4-HMAC-SHA256 Credential=AKIDFAKEIDFAKEID/20160628/us-west-2/s3/aws4_request, SignedHeaders=host;x-amz-date, Signature=1234567890abcdef1234567890abcdef1234567890abcdef`, - `123 321 123 321`, - ` 123 321 123 321 `, - ` 123 321 123 321 `, - "123", - "1 2 3", - " 1 2 3", - "1 2 3", - "1 23", - "1 2 3", - "1 2 ", - " 1 2 ", - "12 3", - "12 3 1", - "12 3 1", - "12 3 1abc123", -} - -func BenchmarkStripExcessSpaces(b *testing.B) { - for i := 0; i < b.N; i++ { - // Make sure to start with a copy of the cases - cases := append([]string{}, stripExcessSpaceCases...) - stripExcessSpaces(cases) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/types_test.go b/vendor/github.com/aws/aws-sdk-go/aws/types_test.go deleted file mode 100644 index e399ef573..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/types_test.go +++ /dev/null @@ -1,92 +0,0 @@ -package aws - -import ( - "bytes" - "math/rand" - "testing" -) - -func TestWriteAtBuffer(t *testing.T) { - b := &WriteAtBuffer{} - - n, err := b.WriteAt([]byte{1}, 0) - if err != nil { - t.Errorf("expected no error, but received %v", err) - } - if e, a := 1, n; e != a { - t.Errorf("expected %d, but recieved %d", e, a) - } - - n, err = b.WriteAt([]byte{1, 1, 1}, 5) - if err != nil { - t.Errorf("expected no error, but received %v", err) - } - if e, a := 3, n; e != a { - t.Errorf("expected %d, but recieved %d", e, a) - } - - n, err = b.WriteAt([]byte{2}, 1) - if err != nil { - t.Errorf("expected no error, but received %v", err) - } - if e, a := 1, n; e != a { - t.Errorf("expected %d, but recieved %d", e, a) - } - - n, err = b.WriteAt([]byte{3}, 2) - if err != nil { - t.Errorf("expected no error, but received %v", err) - } - if e, a := 1, n; e != a { - t.Errorf("expected %d, but received %d", e, a) - } - - if !bytes.Equal([]byte{1, 2, 3, 0, 0, 1, 1, 1}, b.Bytes()) { - t.Errorf("expected %v, but received %v", []byte{1, 2, 3, 0, 0, 1, 1, 1}, b.Bytes()) - } -} - -func BenchmarkWriteAtBuffer(b *testing.B) { - buf := &WriteAtBuffer{} - r := rand.New(rand.NewSource(1)) - - b.ResetTimer() - for i := 0; i < b.N; i++ { - to := r.Intn(10) * 4096 - bs := make([]byte, to) - buf.WriteAt(bs, r.Int63n(10)*4096) - } -} - -func BenchmarkWriteAtBufferOrderedWrites(b *testing.B) { - // test the performance of a WriteAtBuffer when written in an - // ordered fashion. This is similar to the behavior of the - // s3.Downloader, since downloads the first chunk of the file, then - // the second, and so on. - // - // This test simulates a 150MB file being written in 30 ordered 5MB chunks. - chunk := int64(5e6) - max := chunk * 30 - // we'll write the same 5MB chunk every time - tmp := make([]byte, chunk) - for i := 0; i < b.N; i++ { - buf := &WriteAtBuffer{} - for i := int64(0); i < max; i += chunk { - buf.WriteAt(tmp, i) - } - } -} - -func BenchmarkWriteAtBufferParallel(b *testing.B) { - buf := &WriteAtBuffer{} - r := rand.New(rand.NewSource(1)) - - b.ResetTimer() - b.RunParallel(func(pb *testing.PB) { - for pb.Next() { - to := r.Intn(10) * 4096 - bs := make([]byte, to) - buf.WriteAt(bs, r.Int63n(10)*4096) - } - }) -} diff --git a/vendor/github.com/aws/aws-sdk-go/buildspec.yml b/vendor/github.com/aws/aws-sdk-go/buildspec.yml deleted file mode 100644 index 427208edf..000000000 --- a/vendor/github.com/aws/aws-sdk-go/buildspec.yml +++ /dev/null @@ -1,21 +0,0 @@ -version: 0.2 - -phases: - build: - commands: - - echo Build started on `date` - - export GOPATH=/go - - export SDK_CB_ROOT=`pwd` - - export SDK_GO_ROOT=/go/src/github.com/aws/aws-sdk-go - - mkdir -p /go/src/github.com/aws - - ln -s $SDK_CB_ROOT $SDK_GO_ROOT - - cd $SDK_GO_ROOT - - make unit - - cd $SDK_CB_ROOT - - #echo Compiling the Go code... - post_build: - commands: - - echo Build completed on `date` -#artifacts: -# files: -# - hello diff --git a/vendor/github.com/aws/aws-sdk-go/doc.go b/vendor/github.com/aws/aws-sdk-go/doc.go deleted file mode 100644 index 3e077e51d..000000000 --- a/vendor/github.com/aws/aws-sdk-go/doc.go +++ /dev/null @@ -1,405 +0,0 @@ -// Package sdk is the official AWS SDK for the Go programming language. -// -// The AWS SDK for Go provides APIs and utilities that developers can use to -// build Go applications that use AWS services, such as Amazon Elastic Compute -// Cloud (Amazon EC2) and Amazon Simple Storage Service (Amazon S3). -// -// The SDK removes the complexity of coding directly against a web service -// interface. It hides a lot of the lower-level plumbing, such as authentication, -// request retries, and error handling. -// -// The SDK also includes helpful utilities on top of the AWS APIs that add additional -// capabilities and functionality. For example, the Amazon S3 Download and Upload -// Manager will automatically split up large objects into multiple parts and -// transfer them concurrently. -// -// See the s3manager package documentation for more information. -// https://docs.aws.amazon.com/sdk-for-go/api/service/s3/s3manager/ -// -// Getting More Information -// -// Checkout the Getting Started Guide and API Reference Docs detailed the SDK's -// components and details on each AWS client the SDK supports. -// -// The Getting Started Guide provides examples and detailed description of how -// to get setup with the SDK. -// https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/welcome.html -// -// The API Reference Docs include a detailed breakdown of the SDK's components -// such as utilities and AWS clients. Use this as a reference of the Go types -// included with the SDK, such as AWS clients, API operations, and API parameters. -// https://docs.aws.amazon.com/sdk-for-go/api/ -// -// Overview of SDK's Packages -// -// The SDK is composed of two main components, SDK core, and service clients. -// The SDK core packages are all available under the aws package at the root of -// the SDK. Each client for a supported AWS service is available within its own -// package under the service folder at the root of the SDK. -// -// * aws - SDK core, provides common shared types such as Config, Logger, -// and utilities to make working with API parameters easier. -// -// * awserr - Provides the error interface that the SDK will use for all -// errors that occur in the SDK's processing. This includes service API -// response errors as well. The Error type is made up of a code and message. -// Cast the SDK's returned error type to awserr.Error and call the Code -// method to compare returned error to specific error codes. See the package's -// documentation for additional values that can be extracted such as RequestId. -// -// * credentials - Provides the types and built in credentials providers -// the SDK will use to retrieve AWS credentials to make API requests with. -// Nested under this folder are also additional credentials providers such as -// stscreds for assuming IAM roles, and ec2rolecreds for EC2 Instance roles. -// -// * endpoints - Provides the AWS Regions and Endpoints metadata for the SDK. -// Use this to lookup AWS service endpoint information such as which services -// are in a region, and what regions a service is in. Constants are also provided -// for all region identifiers, e.g UsWest2RegionID for "us-west-2". -// -// * session - Provides initial default configuration, and load -// configuration from external sources such as environment and shared -// credentials file. -// -// * request - Provides the API request sending, and retry logic for the SDK. -// This package also includes utilities for defining your own request -// retryer, and configuring how the SDK processes the request. -// -// * service - Clients for AWS services. All services supported by the SDK are -// available under this folder. -// -// How to Use the SDK's AWS Service Clients -// -// The SDK includes the Go types and utilities you can use to make requests to -// AWS service APIs. Within the service folder at the root of the SDK you'll find -// a package for each AWS service the SDK supports. All service clients follows -// a common pattern of creation and usage. -// -// When creating a client for an AWS service you'll first need to have a Session -// value constructed. The Session provides shared configuration that can be shared -// between your service clients. When service clients are created you can pass -// in additional configuration via the aws.Config type to override configuration -// provided by in the Session to create service client instances with custom -// configuration. -// -// Once the service's client is created you can use it to make API requests the -// AWS service. These clients are safe to use concurrently. -// -// Configuring the SDK -// -// In the AWS SDK for Go, you can configure settings for service clients, such -// as the log level and maximum number of retries. Most settings are optional; -// however, for each service client, you must specify a region and your credentials. -// The SDK uses these values to send requests to the correct AWS region and sign -// requests with the correct credentials. You can specify these values as part -// of a session or as environment variables. -// -// See the SDK's configuration guide for more information. -// https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/configuring-sdk.html -// -// See the session package documentation for more information on how to use Session -// with the SDK. -// https://docs.aws.amazon.com/sdk-for-go/api/aws/session/ -// -// See the Config type in the aws package for more information on configuration -// options. -// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config -// -// Configuring Credentials -// -// When using the SDK you'll generally need your AWS credentials to authenticate -// with AWS services. The SDK supports multiple methods of supporting these -// credentials. By default the SDK will source credentials automatically from -// its default credential chain. See the session package for more information -// on this chain, and how to configure it. The common items in the credential -// chain are the following: -// -// * Environment Credentials - Set of environment variables that are useful -// when sub processes are created for specific roles. -// -// * Shared Credentials file (~/.aws/credentials) - This file stores your -// credentials based on a profile name and is useful for local development. -// -// * EC2 Instance Role Credentials - Use EC2 Instance Role to assign credentials -// to application running on an EC2 instance. This removes the need to manage -// credential files in production. -// -// Credentials can be configured in code as well by setting the Config's Credentials -// value to a custom provider or using one of the providers included with the -// SDK to bypass the default credential chain and use a custom one. This is -// helpful when you want to instruct the SDK to only use a specific set of -// credentials or providers. -// -// This example creates a credential provider for assuming an IAM role, "myRoleARN" -// and configures the S3 service client to use that role for API requests. -// -// // Initial credentials loaded from SDK's default credential chain. Such as -// // the environment, shared credentials (~/.aws/credentials), or EC2 Instance -// // Role. These credentials will be used to to make the STS Assume Role API. -// sess := session.Must(session.NewSession()) -// -// // Create the credentials from AssumeRoleProvider to assume the role -// // referenced by the "myRoleARN" ARN. -// creds := stscreds.NewCredentials(sess, "myRoleArn") -// -// // Create service client value configured for credentials -// // from assumed role. -// svc := s3.New(sess, &aws.Config{Credentials: creds})/ -// -// See the credentials package documentation for more information on credential -// providers included with the SDK, and how to customize the SDK's usage of -// credentials. -// https://docs.aws.amazon.com/sdk-for-go/api/aws/credentials -// -// The SDK has support for the shared configuration file (~/.aws/config). This -// support can be enabled by setting the environment variable, "AWS_SDK_LOAD_CONFIG=1", -// or enabling the feature in code when creating a Session via the -// Option's SharedConfigState parameter. -// -// sess := session.Must(session.NewSessionWithOptions(session.Options{ -// SharedConfigState: session.SharedConfigEnable, -// })) -// -// Configuring AWS Region -// -// In addition to the credentials you'll need to specify the region the SDK -// will use to make AWS API requests to. In the SDK you can specify the region -// either with an environment variable, or directly in code when a Session or -// service client is created. The last value specified in code wins if the region -// is specified multiple ways. -// -// To set the region via the environment variable set the "AWS_REGION" to the -// region you want to the SDK to use. Using this method to set the region will -// allow you to run your application in multiple regions without needing additional -// code in the application to select the region. -// -// AWS_REGION=us-west-2 -// -// The endpoints package includes constants for all regions the SDK knows. The -// values are all suffixed with RegionID. These values are helpful, because they -// reduce the need to type the region string manually. -// -// To set the region on a Session use the aws package's Config struct parameter -// Region to the AWS region you want the service clients created from the session to -// use. This is helpful when you want to create multiple service clients, and -// all of the clients make API requests to the same region. -// -// sess := session.Must(session.NewSession(&aws.Config{ -// Region: aws.String(endpoints.UsWest2RegionID), -// })) -// -// See the endpoints package for the AWS Regions and Endpoints metadata. -// https://docs.aws.amazon.com/sdk-for-go/api/aws/endpoints/ -// -// In addition to setting the region when creating a Session you can also set -// the region on a per service client bases. This overrides the region of a -// Session. This is helpful when you want to create service clients in specific -// regions different from the Session's region. -// -// svc := s3.New(sess, &aws.Config{ -// Region: aws.String(ednpoints.UsWest2RegionID), -// }) -// -// See the Config type in the aws package for more information and additional -// options such as setting the Endpoint, and other service client configuration options. -// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config -// -// Making API Requests -// -// Once the client is created you can make an API request to the service. -// Each API method takes a input parameter, and returns the service response -// and an error. The SDK provides methods for making the API call in multiple ways. -// -// In this list we'll use the S3 ListObjects API as an example for the different -// ways of making API requests. -// -// * ListObjects - Base API operation that will make the API request to the service. -// -// * ListObjectsRequest - API methods suffixed with Request will construct the -// API request, but not send it. This is also helpful when you want to get a -// presigned URL for a request, and share the presigned URL instead of your -// application making the request directly. -// -// * ListObjectsPages - Same as the base API operation, but uses a callback to -// automatically handle pagination of the API's response. -// -// * ListObjectsWithContext - Same as base API operation, but adds support for -// the Context pattern. This is helpful for controlling the canceling of in -// flight requests. See the Go standard library context package for more -// information. This method also takes request package's Option functional -// options as the variadic argument for modifying how the request will be -// made, or extracting information from the raw HTTP response. -// -// * ListObjectsPagesWithContext - same as ListObjectsPages, but adds support for -// the Context pattern. Similar to ListObjectsWithContext this method also -// takes the request package's Option function option types as the variadic -// argument. -// -// In addition to the API operations the SDK also includes several higher level -// methods that abstract checking for and waiting for an AWS resource to be in -// a desired state. In this list we'll use WaitUntilBucketExists to demonstrate -// the different forms of waiters. -// -// * WaitUntilBucketExists. - Method to make API request to query an AWS service for -// a resource's state. Will return successfully when that state is accomplished. -// -// * WaitUntilBucketExistsWithContext - Same as WaitUntilBucketExists, but adds -// support for the Context pattern. In addition these methods take request -// package's WaiterOptions to configure the waiter, and how underlying request -// will be made by the SDK. -// -// The API method will document which error codes the service might return for -// the operation. These errors will also be available as const strings prefixed -// with "ErrCode" in the service client's package. If there are no errors listed -// in the API's SDK documentation you'll need to consult the AWS service's API -// documentation for the errors that could be returned. -// -// ctx := context.Background() -// -// result, err := svc.GetObjectWithContext(ctx, &s3.GetObjectInput{ -// Bucket: aws.String("my-bucket"), -// Key: aws.String("my-key"), -// }) -// if err != nil { -// // Cast err to awserr.Error to handle specific error codes. -// aerr, ok := err.(awserr.Error) -// if ok && aerr.Code() == s3.ErrCodeNoSuchKey { -// // Specific error code handling -// } -// return err -// } -// -// // Make sure to close the body when done with it for S3 GetObject APIs or -// // will leak connections. -// defer result.Body.Close() -// -// fmt.Println("Object Size:", aws.StringValue(result.ContentLength)) -// -// API Request Pagination and Resource Waiters -// -// Pagination helper methods are suffixed with "Pages", and provide the -// functionality needed to round trip API page requests. Pagination methods -// take a callback function that will be called for each page of the API's response. -// -// objects := []string{} -// err := svc.ListObjectsPagesWithContext(ctx, &s3.ListObjectsInput{ -// Bucket: aws.String(myBucket), -// }, func(p *s3.ListObjectsOutput, lastPage bool) bool { -// for _, o := range p.Contents { -// objects = append(objects, aws.StringValue(o.Key)) -// } -// return true // continue paging -// }) -// if err != nil { -// panic(fmt.Sprintf("failed to list objects for bucket, %s, %v", myBucket, err)) -// } -// -// fmt.Println("Objects in bucket:", objects) -// -// Waiter helper methods provide the functionality to wait for an AWS resource -// state. These methods abstract the logic needed to to check the state of an -// AWS resource, and wait until that resource is in a desired state. The waiter -// will block until the resource is in the state that is desired, an error occurs, -// or the waiter times out. If a resource times out the error code returned will -// be request.WaiterResourceNotReadyErrorCode. -// -// err := svc.WaitUntilBucketExistsWithContext(ctx, &s3.HeadBucketInput{ -// Bucket: aws.String(myBucket), -// }) -// if err != nil { -// aerr, ok := err.(awserr.Error) -// if ok && aerr.Code() == request.WaiterResourceNotReadyErrorCode { -// fmt.Fprintf(os.Stderr, "timed out while waiting for bucket to exist") -// } -// panic(fmt.Errorf("failed to wait for bucket to exist, %v", err)) -// } -// fmt.Println("Bucket", myBucket, "exists") -// -// Complete SDK Example -// -// This example shows a complete working Go file which will upload a file to S3 -// and use the Context pattern to implement timeout logic that will cancel the -// request if it takes too long. This example highlights how to use sessions, -// create a service client, make a request, handle the error, and process the -// response. -// -// package main -// -// import ( -// "context" -// "flag" -// "fmt" -// "os" -// "time" -// -// "github.com/aws/aws-sdk-go/aws" -// "github.com/aws/aws-sdk-go/aws/awserr" -// "github.com/aws/aws-sdk-go/aws/request" -// "github.com/aws/aws-sdk-go/aws/session" -// "github.com/aws/aws-sdk-go/service/s3" -// ) -// -// // Uploads a file to S3 given a bucket and object key. Also takes a duration -// // value to terminate the update if it doesn't complete within that time. -// // -// // The AWS Region needs to be provided in the AWS shared config or on the -// // environment variable as `AWS_REGION`. Credentials also must be provided -// // Will default to shared config file, but can load from environment if provided. -// // -// // Usage: -// // # Upload myfile.txt to myBucket/myKey. Must complete within 10 minutes or will fail -// // go run withContext.go -b mybucket -k myKey -d 10m < myfile.txt -// func main() { -// var bucket, key string -// var timeout time.Duration -// -// flag.StringVar(&bucket, "b", "", "Bucket name.") -// flag.StringVar(&key, "k", "", "Object key name.") -// flag.DurationVar(&timeout, "d", 0, "Upload timeout.") -// flag.Parse() -// -// // All clients require a Session. The Session provides the client with -// // shared configuration such as region, endpoint, and credentials. A -// // Session should be shared where possible to take advantage of -// // configuration and credential caching. See the session package for -// // more information. -// sess := session.Must(session.NewSession()) -// -// // Create a new instance of the service's client with a Session. -// // Optional aws.Config values can also be provided as variadic arguments -// // to the New function. This option allows you to provide service -// // specific configuration. -// svc := s3.New(sess) -// -// // Create a context with a timeout that will abort the upload if it takes -// // more than the passed in timeout. -// ctx := context.Background() -// var cancelFn func() -// if timeout > 0 { -// ctx, cancelFn = context.WithTimeout(ctx, timeout) -// } -// // Ensure the context is canceled to prevent leaking. -// // See context package for more information, https://golang.org/pkg/context/ -// defer cancelFn() -// -// // Uploads the object to S3. The Context will interrupt the request if the -// // timeout expires. -// _, err := svc.PutObjectWithContext(ctx, &s3.PutObjectInput{ -// Bucket: aws.String(bucket), -// Key: aws.String(key), -// Body: os.Stdin, -// }) -// if err != nil { -// if aerr, ok := err.(awserr.Error); ok && aerr.Code() == request.CanceledErrorCode { -// // If the SDK can determine the request or retry delay was canceled -// // by a context the CanceledErrorCode error code will be returned. -// fmt.Fprintf(os.Stderr, "upload canceled due to timeout, %v\n", err) -// } else { -// fmt.Fprintf(os.Stderr, "failed to upload object, %v\n", err) -// } -// os.Exit(1) -// } -// -// fmt.Printf("successfully uploaded file to %s/%s\n", bucket, key) -// } -package sdk diff --git a/vendor/github.com/aws/aws-sdk-go/internal/shareddefaults/shared_config_other_test.go b/vendor/github.com/aws/aws-sdk-go/internal/shareddefaults/shared_config_other_test.go deleted file mode 100644 index a2fd4558b..000000000 --- a/vendor/github.com/aws/aws-sdk-go/internal/shareddefaults/shared_config_other_test.go +++ /dev/null @@ -1,40 +0,0 @@ -package shareddefaults_test - -import ( - "os" - "path/filepath" - "testing" - - "github.com/aws/aws-sdk-go/awstesting" - "github.com/aws/aws-sdk-go/internal/shareddefaults" -) - -func TestSharedCredsFilename(t *testing.T) { - env := awstesting.StashEnv() - defer awstesting.PopEnv(env) - - os.Setenv("HOME", "home_dir") - os.Setenv("USERPROFILE", "profile_dir") - - expect := filepath.Join("home_dir", ".aws", "credentials") - - name := shareddefaults.SharedCredentialsFilename() - if e, a := expect, name; e != a { - t.Errorf("expect %q shared creds filename, got %q", e, a) - } -} - -func TestSharedConfigFilename(t *testing.T) { - env := awstesting.StashEnv() - defer awstesting.PopEnv(env) - - os.Setenv("HOME", "home_dir") - os.Setenv("USERPROFILE", "profile_dir") - - expect := filepath.Join("home_dir", ".aws", "config") - - name := shareddefaults.SharedConfigFilename() - if e, a := expect, name; e != a { - t.Errorf("expect %q shared config filename, got %q", e, a) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/internal/shareddefaults/shared_config_windows_test.go b/vendor/github.com/aws/aws-sdk-go/internal/shareddefaults/shared_config_windows_test.go deleted file mode 100644 index afe96b17d..000000000 --- a/vendor/github.com/aws/aws-sdk-go/internal/shareddefaults/shared_config_windows_test.go +++ /dev/null @@ -1,40 +0,0 @@ -package shareddefaults_test - -import ( - "os" - "path/filepath" - "testing" - - "github.com/aws/aws-sdk-go/awstesting" - "github.com/aws/aws-sdk-go/internal/shareddefaults" -) - -func TestSharedCredsFilename(t *testing.T) { - env := awstesting.StashEnv() - defer awstesting.PopEnv(env) - - os.Setenv("HOME", "home_dir") - os.Setenv("USERPROFILE", "profile_dir") - - expect := filepath.Join("profile_dir", ".aws", "credentials") - - name := shareddefaults.SharedCredentialsFilename() - if e, a := expect, name; e != a { - t.Errorf("expect %q shared creds filename, got %q", e, a) - } -} - -func TestSharedConfigFilename(t *testing.T) { - env := awstesting.StashEnv() - defer awstesting.PopEnv(env) - - os.Setenv("HOME", "home_dir") - os.Setenv("USERPROFILE", "profile_dir") - - expect := filepath.Join("profile_dir", ".aws", "config") - - name := shareddefaults.SharedConfigFilename() - if e, a := expect, name; e != a { - t.Errorf("expect %q shared config filename, got %q", e, a) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/README.md b/vendor/github.com/aws/aws-sdk-go/private/README.md deleted file mode 100644 index 5bdb4c50a..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/README.md +++ /dev/null @@ -1,4 +0,0 @@ -## AWS SDK for Go Private packages ## -`private` is a collection of packages used internally by the SDK, and is subject to have breaking changes. This package is not `internal` so that if you really need to use its functionality, and understand breaking changes will be made, you are able to. - -These packages will be refactored in the future so that the API generator and model parsers are exposed cleanly on their own. Making it easier for you to generate your own code based on the API models. diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/ec2query/build_bench_test.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/ec2query/build_bench_test.go deleted file mode 100644 index e135b9360..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/ec2query/build_bench_test.go +++ /dev/null @@ -1,85 +0,0 @@ -// +build bench - -package ec2query_test - -import ( - "testing" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/awstesting" - "github.com/aws/aws-sdk-go/private/protocol/ec2query" - "github.com/aws/aws-sdk-go/service/ec2" -) - -func BenchmarkEC2QueryBuild_Complex_ec2AuthorizeSecurityGroupEgress(b *testing.B) { - params := &ec2.AuthorizeSecurityGroupEgressInput{ - GroupId: aws.String("String"), // Required - CidrIp: aws.String("String"), - DryRun: aws.Bool(true), - FromPort: aws.Int64(1), - IpPermissions: []*ec2.IpPermission{ - { // Required - FromPort: aws.Int64(1), - IpProtocol: aws.String("String"), - IpRanges: []*ec2.IpRange{ - { // Required - CidrIp: aws.String("String"), - }, - // More values... - }, - PrefixListIds: []*ec2.PrefixListId{ - { // Required - PrefixListId: aws.String("String"), - }, - // More values... - }, - ToPort: aws.Int64(1), - UserIdGroupPairs: []*ec2.UserIdGroupPair{ - { // Required - GroupId: aws.String("String"), - GroupName: aws.String("String"), - UserId: aws.String("String"), - }, - // More values... - }, - }, - // More values... - }, - IpProtocol: aws.String("String"), - SourceSecurityGroupName: aws.String("String"), - SourceSecurityGroupOwnerId: aws.String("String"), - ToPort: aws.Int64(1), - } - - benchEC2QueryBuild(b, "AuthorizeSecurityGroupEgress", params) -} - -func BenchmarkEC2QueryBuild_Simple_ec2AttachNetworkInterface(b *testing.B) { - params := &ec2.AttachNetworkInterfaceInput{ - DeviceIndex: aws.Int64(1), // Required - InstanceId: aws.String("String"), // Required - NetworkInterfaceId: aws.String("String"), // Required - DryRun: aws.Bool(true), - } - - benchEC2QueryBuild(b, "AttachNetworkInterface", params) -} - -func benchEC2QueryBuild(b *testing.B, opName string, params interface{}) { - svc := awstesting.NewClient() - svc.ServiceName = "ec2" - svc.APIVersion = "2015-04-15" - - for i := 0; i < b.N; i++ { - r := svc.NewRequest(&request.Operation{ - Name: opName, - HTTPMethod: "POST", - HTTPPath: "/", - }, params, nil) - ec2query.Build(r) - if r.Error != nil { - b.Fatal("Unexpected error", r.Error) - } - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/ec2query/build_test.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/ec2query/build_test.go deleted file mode 100644 index 93fe83fd5..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/ec2query/build_test.go +++ /dev/null @@ -1,1760 +0,0 @@ -package ec2query_test - -import ( - "bytes" - "encoding/json" - "encoding/xml" - "fmt" - "io" - "io/ioutil" - "net/http" - "net/url" - "reflect" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/client" - "github.com/aws/aws-sdk-go/aws/client/metadata" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/aws/signer/v4" - "github.com/aws/aws-sdk-go/awstesting" - "github.com/aws/aws-sdk-go/awstesting/unit" - "github.com/aws/aws-sdk-go/private/protocol" - "github.com/aws/aws-sdk-go/private/protocol/ec2query" - "github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil" - "github.com/aws/aws-sdk-go/private/util" -) - -var _ bytes.Buffer // always import bytes -var _ http.Request -var _ json.Marshaler -var _ time.Time -var _ xmlutil.XMLNode -var _ xml.Attr -var _ = ioutil.Discard -var _ = util.Trim("") -var _ = url.Values{} -var _ = io.EOF -var _ = aws.String -var _ = fmt.Println -var _ = reflect.Value{} - -func init() { - protocol.RandReader = &awstesting.ZeroReader{} -} - -// InputService1ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// InputService1ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type InputService1ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the InputService1ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a InputService1ProtocolTest client from just a session. -// svc := inputservice1protocoltest.New(mySession) -// -// // Create a InputService1ProtocolTest client with additional configuration -// svc := inputservice1protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewInputService1ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService1ProtocolTest { - c := p.ClientConfig("inputservice1protocoltest", cfgs...) - return newInputService1ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newInputService1ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *InputService1ProtocolTest { - svc := &InputService1ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "inputservice1protocoltest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "2014-01-01", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a InputService1ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService1ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opInputService1TestCaseOperation1 = "OperationName" - -// InputService1TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the InputService1TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService1TestCaseOperation1 for more information on using the InputService1TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService1TestCaseOperation1Request method. -// req, resp := client.InputService1TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService1ProtocolTest) InputService1TestCaseOperation1Request(input *InputService1TestShapeInputService1TestCaseOperation1Input) (req *request.Request, output *InputService1TestShapeInputService1TestCaseOperation1Output) { - op := &request.Operation{ - Name: opInputService1TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &InputService1TestShapeInputService1TestCaseOperation1Input{} - } - - output = &InputService1TestShapeInputService1TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(ec2query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService1TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService1TestCaseOperation1 for usage and error information. -func (c *InputService1ProtocolTest) InputService1TestCaseOperation1(input *InputService1TestShapeInputService1TestCaseOperation1Input) (*InputService1TestShapeInputService1TestCaseOperation1Output, error) { - req, out := c.InputService1TestCaseOperation1Request(input) - return out, req.Send() -} - -// InputService1TestCaseOperation1WithContext is the same as InputService1TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService1TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService1ProtocolTest) InputService1TestCaseOperation1WithContext(ctx aws.Context, input *InputService1TestShapeInputService1TestCaseOperation1Input, opts ...request.Option) (*InputService1TestShapeInputService1TestCaseOperation1Output, error) { - req, out := c.InputService1TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type InputService1TestShapeInputService1TestCaseOperation1Input struct { - _ struct{} `type:"structure"` - - Bar *string `type:"string"` - - Foo *string `type:"string"` -} - -// SetBar sets the Bar field's value. -func (s *InputService1TestShapeInputService1TestCaseOperation1Input) SetBar(v string) *InputService1TestShapeInputService1TestCaseOperation1Input { - s.Bar = &v - return s -} - -// SetFoo sets the Foo field's value. -func (s *InputService1TestShapeInputService1TestCaseOperation1Input) SetFoo(v string) *InputService1TestShapeInputService1TestCaseOperation1Input { - s.Foo = &v - return s -} - -type InputService1TestShapeInputService1TestCaseOperation1Output struct { - _ struct{} `type:"structure"` -} - -// InputService2ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// InputService2ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type InputService2ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the InputService2ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a InputService2ProtocolTest client from just a session. -// svc := inputservice2protocoltest.New(mySession) -// -// // Create a InputService2ProtocolTest client with additional configuration -// svc := inputservice2protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewInputService2ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService2ProtocolTest { - c := p.ClientConfig("inputservice2protocoltest", cfgs...) - return newInputService2ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newInputService2ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *InputService2ProtocolTest { - svc := &InputService2ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "inputservice2protocoltest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "2014-01-01", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a InputService2ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService2ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opInputService2TestCaseOperation1 = "OperationName" - -// InputService2TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the InputService2TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService2TestCaseOperation1 for more information on using the InputService2TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService2TestCaseOperation1Request method. -// req, resp := client.InputService2TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService2ProtocolTest) InputService2TestCaseOperation1Request(input *InputService2TestShapeInputService2TestCaseOperation1Input) (req *request.Request, output *InputService2TestShapeInputService2TestCaseOperation1Output) { - op := &request.Operation{ - Name: opInputService2TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &InputService2TestShapeInputService2TestCaseOperation1Input{} - } - - output = &InputService2TestShapeInputService2TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(ec2query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService2TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService2TestCaseOperation1 for usage and error information. -func (c *InputService2ProtocolTest) InputService2TestCaseOperation1(input *InputService2TestShapeInputService2TestCaseOperation1Input) (*InputService2TestShapeInputService2TestCaseOperation1Output, error) { - req, out := c.InputService2TestCaseOperation1Request(input) - return out, req.Send() -} - -// InputService2TestCaseOperation1WithContext is the same as InputService2TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService2TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService2ProtocolTest) InputService2TestCaseOperation1WithContext(ctx aws.Context, input *InputService2TestShapeInputService2TestCaseOperation1Input, opts ...request.Option) (*InputService2TestShapeInputService2TestCaseOperation1Output, error) { - req, out := c.InputService2TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type InputService2TestShapeInputService2TestCaseOperation1Input struct { - _ struct{} `type:"structure"` - - Bar *string `locationName:"barLocationName" type:"string"` - - Foo *string `type:"string"` - - Yuck *string `locationName:"yuckLocationName" queryName:"yuckQueryName" type:"string"` -} - -// SetBar sets the Bar field's value. -func (s *InputService2TestShapeInputService2TestCaseOperation1Input) SetBar(v string) *InputService2TestShapeInputService2TestCaseOperation1Input { - s.Bar = &v - return s -} - -// SetFoo sets the Foo field's value. -func (s *InputService2TestShapeInputService2TestCaseOperation1Input) SetFoo(v string) *InputService2TestShapeInputService2TestCaseOperation1Input { - s.Foo = &v - return s -} - -// SetYuck sets the Yuck field's value. -func (s *InputService2TestShapeInputService2TestCaseOperation1Input) SetYuck(v string) *InputService2TestShapeInputService2TestCaseOperation1Input { - s.Yuck = &v - return s -} - -type InputService2TestShapeInputService2TestCaseOperation1Output struct { - _ struct{} `type:"structure"` -} - -// InputService3ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// InputService3ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type InputService3ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the InputService3ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a InputService3ProtocolTest client from just a session. -// svc := inputservice3protocoltest.New(mySession) -// -// // Create a InputService3ProtocolTest client with additional configuration -// svc := inputservice3protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewInputService3ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService3ProtocolTest { - c := p.ClientConfig("inputservice3protocoltest", cfgs...) - return newInputService3ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newInputService3ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *InputService3ProtocolTest { - svc := &InputService3ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "inputservice3protocoltest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "2014-01-01", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a InputService3ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService3ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opInputService3TestCaseOperation1 = "OperationName" - -// InputService3TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the InputService3TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService3TestCaseOperation1 for more information on using the InputService3TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService3TestCaseOperation1Request method. -// req, resp := client.InputService3TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService3ProtocolTest) InputService3TestCaseOperation1Request(input *InputService3TestShapeInputService3TestCaseOperation1Input) (req *request.Request, output *InputService3TestShapeInputService3TestCaseOperation1Output) { - op := &request.Operation{ - Name: opInputService3TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &InputService3TestShapeInputService3TestCaseOperation1Input{} - } - - output = &InputService3TestShapeInputService3TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(ec2query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService3TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService3TestCaseOperation1 for usage and error information. -func (c *InputService3ProtocolTest) InputService3TestCaseOperation1(input *InputService3TestShapeInputService3TestCaseOperation1Input) (*InputService3TestShapeInputService3TestCaseOperation1Output, error) { - req, out := c.InputService3TestCaseOperation1Request(input) - return out, req.Send() -} - -// InputService3TestCaseOperation1WithContext is the same as InputService3TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService3TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService3ProtocolTest) InputService3TestCaseOperation1WithContext(ctx aws.Context, input *InputService3TestShapeInputService3TestCaseOperation1Input, opts ...request.Option) (*InputService3TestShapeInputService3TestCaseOperation1Output, error) { - req, out := c.InputService3TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type InputService3TestShapeInputService3TestCaseOperation1Input struct { - _ struct{} `type:"structure"` - - StructArg *InputService3TestShapeStructType `locationName:"Struct" type:"structure"` -} - -// SetStructArg sets the StructArg field's value. -func (s *InputService3TestShapeInputService3TestCaseOperation1Input) SetStructArg(v *InputService3TestShapeStructType) *InputService3TestShapeInputService3TestCaseOperation1Input { - s.StructArg = v - return s -} - -type InputService3TestShapeInputService3TestCaseOperation1Output struct { - _ struct{} `type:"structure"` -} - -type InputService3TestShapeStructType struct { - _ struct{} `type:"structure"` - - ScalarArg *string `locationName:"Scalar" type:"string"` -} - -// SetScalarArg sets the ScalarArg field's value. -func (s *InputService3TestShapeStructType) SetScalarArg(v string) *InputService3TestShapeStructType { - s.ScalarArg = &v - return s -} - -// InputService4ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// InputService4ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type InputService4ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the InputService4ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a InputService4ProtocolTest client from just a session. -// svc := inputservice4protocoltest.New(mySession) -// -// // Create a InputService4ProtocolTest client with additional configuration -// svc := inputservice4protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewInputService4ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService4ProtocolTest { - c := p.ClientConfig("inputservice4protocoltest", cfgs...) - return newInputService4ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newInputService4ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *InputService4ProtocolTest { - svc := &InputService4ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "inputservice4protocoltest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "2014-01-01", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a InputService4ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService4ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opInputService4TestCaseOperation1 = "OperationName" - -// InputService4TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the InputService4TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService4TestCaseOperation1 for more information on using the InputService4TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService4TestCaseOperation1Request method. -// req, resp := client.InputService4TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService4ProtocolTest) InputService4TestCaseOperation1Request(input *InputService4TestShapeInputService4TestCaseOperation1Input) (req *request.Request, output *InputService4TestShapeInputService4TestCaseOperation1Output) { - op := &request.Operation{ - Name: opInputService4TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &InputService4TestShapeInputService4TestCaseOperation1Input{} - } - - output = &InputService4TestShapeInputService4TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(ec2query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService4TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService4TestCaseOperation1 for usage and error information. -func (c *InputService4ProtocolTest) InputService4TestCaseOperation1(input *InputService4TestShapeInputService4TestCaseOperation1Input) (*InputService4TestShapeInputService4TestCaseOperation1Output, error) { - req, out := c.InputService4TestCaseOperation1Request(input) - return out, req.Send() -} - -// InputService4TestCaseOperation1WithContext is the same as InputService4TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService4TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService4ProtocolTest) InputService4TestCaseOperation1WithContext(ctx aws.Context, input *InputService4TestShapeInputService4TestCaseOperation1Input, opts ...request.Option) (*InputService4TestShapeInputService4TestCaseOperation1Output, error) { - req, out := c.InputService4TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type InputService4TestShapeInputService4TestCaseOperation1Input struct { - _ struct{} `type:"structure"` - - ListArg []*string `type:"list"` -} - -// SetListArg sets the ListArg field's value. -func (s *InputService4TestShapeInputService4TestCaseOperation1Input) SetListArg(v []*string) *InputService4TestShapeInputService4TestCaseOperation1Input { - s.ListArg = v - return s -} - -type InputService4TestShapeInputService4TestCaseOperation1Output struct { - _ struct{} `type:"structure"` -} - -// InputService5ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// InputService5ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type InputService5ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the InputService5ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a InputService5ProtocolTest client from just a session. -// svc := inputservice5protocoltest.New(mySession) -// -// // Create a InputService5ProtocolTest client with additional configuration -// svc := inputservice5protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewInputService5ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService5ProtocolTest { - c := p.ClientConfig("inputservice5protocoltest", cfgs...) - return newInputService5ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newInputService5ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *InputService5ProtocolTest { - svc := &InputService5ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "inputservice5protocoltest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "2014-01-01", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a InputService5ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService5ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opInputService5TestCaseOperation1 = "OperationName" - -// InputService5TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the InputService5TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService5TestCaseOperation1 for more information on using the InputService5TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService5TestCaseOperation1Request method. -// req, resp := client.InputService5TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService5ProtocolTest) InputService5TestCaseOperation1Request(input *InputService5TestShapeInputService5TestCaseOperation1Input) (req *request.Request, output *InputService5TestShapeInputService5TestCaseOperation1Output) { - op := &request.Operation{ - Name: opInputService5TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &InputService5TestShapeInputService5TestCaseOperation1Input{} - } - - output = &InputService5TestShapeInputService5TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(ec2query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService5TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService5TestCaseOperation1 for usage and error information. -func (c *InputService5ProtocolTest) InputService5TestCaseOperation1(input *InputService5TestShapeInputService5TestCaseOperation1Input) (*InputService5TestShapeInputService5TestCaseOperation1Output, error) { - req, out := c.InputService5TestCaseOperation1Request(input) - return out, req.Send() -} - -// InputService5TestCaseOperation1WithContext is the same as InputService5TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService5TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService5ProtocolTest) InputService5TestCaseOperation1WithContext(ctx aws.Context, input *InputService5TestShapeInputService5TestCaseOperation1Input, opts ...request.Option) (*InputService5TestShapeInputService5TestCaseOperation1Output, error) { - req, out := c.InputService5TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type InputService5TestShapeInputService5TestCaseOperation1Input struct { - _ struct{} `type:"structure"` - - ListArg []*string `locationName:"ListMemberName" locationNameList:"item" type:"list"` -} - -// SetListArg sets the ListArg field's value. -func (s *InputService5TestShapeInputService5TestCaseOperation1Input) SetListArg(v []*string) *InputService5TestShapeInputService5TestCaseOperation1Input { - s.ListArg = v - return s -} - -type InputService5TestShapeInputService5TestCaseOperation1Output struct { - _ struct{} `type:"structure"` -} - -// InputService6ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// InputService6ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type InputService6ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the InputService6ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a InputService6ProtocolTest client from just a session. -// svc := inputservice6protocoltest.New(mySession) -// -// // Create a InputService6ProtocolTest client with additional configuration -// svc := inputservice6protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewInputService6ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService6ProtocolTest { - c := p.ClientConfig("inputservice6protocoltest", cfgs...) - return newInputService6ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newInputService6ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *InputService6ProtocolTest { - svc := &InputService6ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "inputservice6protocoltest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "2014-01-01", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a InputService6ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService6ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opInputService6TestCaseOperation1 = "OperationName" - -// InputService6TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the InputService6TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService6TestCaseOperation1 for more information on using the InputService6TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService6TestCaseOperation1Request method. -// req, resp := client.InputService6TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService6ProtocolTest) InputService6TestCaseOperation1Request(input *InputService6TestShapeInputService6TestCaseOperation1Input) (req *request.Request, output *InputService6TestShapeInputService6TestCaseOperation1Output) { - op := &request.Operation{ - Name: opInputService6TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &InputService6TestShapeInputService6TestCaseOperation1Input{} - } - - output = &InputService6TestShapeInputService6TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(ec2query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService6TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService6TestCaseOperation1 for usage and error information. -func (c *InputService6ProtocolTest) InputService6TestCaseOperation1(input *InputService6TestShapeInputService6TestCaseOperation1Input) (*InputService6TestShapeInputService6TestCaseOperation1Output, error) { - req, out := c.InputService6TestCaseOperation1Request(input) - return out, req.Send() -} - -// InputService6TestCaseOperation1WithContext is the same as InputService6TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService6TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService6ProtocolTest) InputService6TestCaseOperation1WithContext(ctx aws.Context, input *InputService6TestShapeInputService6TestCaseOperation1Input, opts ...request.Option) (*InputService6TestShapeInputService6TestCaseOperation1Output, error) { - req, out := c.InputService6TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type InputService6TestShapeInputService6TestCaseOperation1Input struct { - _ struct{} `type:"structure"` - - ListArg []*string `locationName:"ListMemberName" queryName:"ListQueryName" locationNameList:"item" type:"list"` -} - -// SetListArg sets the ListArg field's value. -func (s *InputService6TestShapeInputService6TestCaseOperation1Input) SetListArg(v []*string) *InputService6TestShapeInputService6TestCaseOperation1Input { - s.ListArg = v - return s -} - -type InputService6TestShapeInputService6TestCaseOperation1Output struct { - _ struct{} `type:"structure"` -} - -// InputService7ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// InputService7ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type InputService7ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the InputService7ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a InputService7ProtocolTest client from just a session. -// svc := inputservice7protocoltest.New(mySession) -// -// // Create a InputService7ProtocolTest client with additional configuration -// svc := inputservice7protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewInputService7ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService7ProtocolTest { - c := p.ClientConfig("inputservice7protocoltest", cfgs...) - return newInputService7ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newInputService7ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *InputService7ProtocolTest { - svc := &InputService7ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "inputservice7protocoltest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "2014-01-01", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a InputService7ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService7ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opInputService7TestCaseOperation1 = "OperationName" - -// InputService7TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the InputService7TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService7TestCaseOperation1 for more information on using the InputService7TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService7TestCaseOperation1Request method. -// req, resp := client.InputService7TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService7ProtocolTest) InputService7TestCaseOperation1Request(input *InputService7TestShapeInputService7TestCaseOperation1Input) (req *request.Request, output *InputService7TestShapeInputService7TestCaseOperation1Output) { - op := &request.Operation{ - Name: opInputService7TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &InputService7TestShapeInputService7TestCaseOperation1Input{} - } - - output = &InputService7TestShapeInputService7TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(ec2query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService7TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService7TestCaseOperation1 for usage and error information. -func (c *InputService7ProtocolTest) InputService7TestCaseOperation1(input *InputService7TestShapeInputService7TestCaseOperation1Input) (*InputService7TestShapeInputService7TestCaseOperation1Output, error) { - req, out := c.InputService7TestCaseOperation1Request(input) - return out, req.Send() -} - -// InputService7TestCaseOperation1WithContext is the same as InputService7TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService7TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService7ProtocolTest) InputService7TestCaseOperation1WithContext(ctx aws.Context, input *InputService7TestShapeInputService7TestCaseOperation1Input, opts ...request.Option) (*InputService7TestShapeInputService7TestCaseOperation1Output, error) { - req, out := c.InputService7TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type InputService7TestShapeInputService7TestCaseOperation1Input struct { - _ struct{} `type:"structure"` - - // BlobArg is automatically base64 encoded/decoded by the SDK. - BlobArg []byte `type:"blob"` -} - -// SetBlobArg sets the BlobArg field's value. -func (s *InputService7TestShapeInputService7TestCaseOperation1Input) SetBlobArg(v []byte) *InputService7TestShapeInputService7TestCaseOperation1Input { - s.BlobArg = v - return s -} - -type InputService7TestShapeInputService7TestCaseOperation1Output struct { - _ struct{} `type:"structure"` -} - -// InputService8ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// InputService8ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type InputService8ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the InputService8ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a InputService8ProtocolTest client from just a session. -// svc := inputservice8protocoltest.New(mySession) -// -// // Create a InputService8ProtocolTest client with additional configuration -// svc := inputservice8protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewInputService8ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService8ProtocolTest { - c := p.ClientConfig("inputservice8protocoltest", cfgs...) - return newInputService8ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newInputService8ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *InputService8ProtocolTest { - svc := &InputService8ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "inputservice8protocoltest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "2014-01-01", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a InputService8ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService8ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opInputService8TestCaseOperation1 = "OperationName" - -// InputService8TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the InputService8TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService8TestCaseOperation1 for more information on using the InputService8TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService8TestCaseOperation1Request method. -// req, resp := client.InputService8TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService8ProtocolTest) InputService8TestCaseOperation1Request(input *InputService8TestShapeInputService8TestCaseOperation1Input) (req *request.Request, output *InputService8TestShapeInputService8TestCaseOperation1Output) { - op := &request.Operation{ - Name: opInputService8TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &InputService8TestShapeInputService8TestCaseOperation1Input{} - } - - output = &InputService8TestShapeInputService8TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(ec2query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService8TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService8TestCaseOperation1 for usage and error information. -func (c *InputService8ProtocolTest) InputService8TestCaseOperation1(input *InputService8TestShapeInputService8TestCaseOperation1Input) (*InputService8TestShapeInputService8TestCaseOperation1Output, error) { - req, out := c.InputService8TestCaseOperation1Request(input) - return out, req.Send() -} - -// InputService8TestCaseOperation1WithContext is the same as InputService8TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService8TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService8ProtocolTest) InputService8TestCaseOperation1WithContext(ctx aws.Context, input *InputService8TestShapeInputService8TestCaseOperation1Input, opts ...request.Option) (*InputService8TestShapeInputService8TestCaseOperation1Output, error) { - req, out := c.InputService8TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type InputService8TestShapeInputService8TestCaseOperation1Input struct { - _ struct{} `type:"structure"` - - TimeArg *time.Time `type:"timestamp" timestampFormat:"iso8601"` -} - -// SetTimeArg sets the TimeArg field's value. -func (s *InputService8TestShapeInputService8TestCaseOperation1Input) SetTimeArg(v time.Time) *InputService8TestShapeInputService8TestCaseOperation1Input { - s.TimeArg = &v - return s -} - -type InputService8TestShapeInputService8TestCaseOperation1Output struct { - _ struct{} `type:"structure"` -} - -// InputService9ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// InputService9ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type InputService9ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the InputService9ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a InputService9ProtocolTest client from just a session. -// svc := inputservice9protocoltest.New(mySession) -// -// // Create a InputService9ProtocolTest client with additional configuration -// svc := inputservice9protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewInputService9ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService9ProtocolTest { - c := p.ClientConfig("inputservice9protocoltest", cfgs...) - return newInputService9ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newInputService9ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *InputService9ProtocolTest { - svc := &InputService9ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "inputservice9protocoltest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "2014-01-01", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a InputService9ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService9ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opInputService9TestCaseOperation1 = "OperationName" - -// InputService9TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the InputService9TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService9TestCaseOperation1 for more information on using the InputService9TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService9TestCaseOperation1Request method. -// req, resp := client.InputService9TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService9ProtocolTest) InputService9TestCaseOperation1Request(input *InputService9TestShapeInputService9TestCaseOperation2Input) (req *request.Request, output *InputService9TestShapeInputService9TestCaseOperation1Output) { - op := &request.Operation{ - Name: opInputService9TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &InputService9TestShapeInputService9TestCaseOperation2Input{} - } - - output = &InputService9TestShapeInputService9TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(ec2query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService9TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService9TestCaseOperation1 for usage and error information. -func (c *InputService9ProtocolTest) InputService9TestCaseOperation1(input *InputService9TestShapeInputService9TestCaseOperation2Input) (*InputService9TestShapeInputService9TestCaseOperation1Output, error) { - req, out := c.InputService9TestCaseOperation1Request(input) - return out, req.Send() -} - -// InputService9TestCaseOperation1WithContext is the same as InputService9TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService9TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService9ProtocolTest) InputService9TestCaseOperation1WithContext(ctx aws.Context, input *InputService9TestShapeInputService9TestCaseOperation2Input, opts ...request.Option) (*InputService9TestShapeInputService9TestCaseOperation1Output, error) { - req, out := c.InputService9TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opInputService9TestCaseOperation2 = "OperationName" - -// InputService9TestCaseOperation2Request generates a "aws/request.Request" representing the -// client's request for the InputService9TestCaseOperation2 operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService9TestCaseOperation2 for more information on using the InputService9TestCaseOperation2 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService9TestCaseOperation2Request method. -// req, resp := client.InputService9TestCaseOperation2Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService9ProtocolTest) InputService9TestCaseOperation2Request(input *InputService9TestShapeInputService9TestCaseOperation2Input) (req *request.Request, output *InputService9TestShapeInputService9TestCaseOperation2Output) { - op := &request.Operation{ - Name: opInputService9TestCaseOperation2, - HTTPPath: "/", - } - - if input == nil { - input = &InputService9TestShapeInputService9TestCaseOperation2Input{} - } - - output = &InputService9TestShapeInputService9TestCaseOperation2Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(ec2query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService9TestCaseOperation2 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService9TestCaseOperation2 for usage and error information. -func (c *InputService9ProtocolTest) InputService9TestCaseOperation2(input *InputService9TestShapeInputService9TestCaseOperation2Input) (*InputService9TestShapeInputService9TestCaseOperation2Output, error) { - req, out := c.InputService9TestCaseOperation2Request(input) - return out, req.Send() -} - -// InputService9TestCaseOperation2WithContext is the same as InputService9TestCaseOperation2 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService9TestCaseOperation2 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService9ProtocolTest) InputService9TestCaseOperation2WithContext(ctx aws.Context, input *InputService9TestShapeInputService9TestCaseOperation2Input, opts ...request.Option) (*InputService9TestShapeInputService9TestCaseOperation2Output, error) { - req, out := c.InputService9TestCaseOperation2Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type InputService9TestShapeInputService9TestCaseOperation1Output struct { - _ struct{} `type:"structure"` -} - -type InputService9TestShapeInputService9TestCaseOperation2Input struct { - _ struct{} `type:"structure"` - - Token *string `type:"string" idempotencyToken:"true"` -} - -// SetToken sets the Token field's value. -func (s *InputService9TestShapeInputService9TestCaseOperation2Input) SetToken(v string) *InputService9TestShapeInputService9TestCaseOperation2Input { - s.Token = &v - return s -} - -type InputService9TestShapeInputService9TestCaseOperation2Output struct { - _ struct{} `type:"structure"` -} - -// -// Tests begin here -// - -func TestInputService1ProtocolTestScalarMembersCase1(t *testing.T) { - svc := NewInputService1ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService1TestShapeInputService1TestCaseOperation1Input{ - Bar: aws.String("val2"), - Foo: aws.String("val1"), - } - req, _ := svc.InputService1TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - ec2query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&Bar=val2&Foo=val1&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService2ProtocolTestStructureWithLocationNameAndQueryNameAppliedToMembersCase1(t *testing.T) { - svc := NewInputService2ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService2TestShapeInputService2TestCaseOperation1Input{ - Bar: aws.String("val2"), - Foo: aws.String("val1"), - Yuck: aws.String("val3"), - } - req, _ := svc.InputService2TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - ec2query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&BarLocationName=val2&Foo=val1&Version=2014-01-01&yuckQueryName=val3`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService3ProtocolTestNestedStructureMembersCase1(t *testing.T) { - svc := NewInputService3ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService3TestShapeInputService3TestCaseOperation1Input{ - StructArg: &InputService3TestShapeStructType{ - ScalarArg: aws.String("foo"), - }, - } - req, _ := svc.InputService3TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - ec2query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&Struct.Scalar=foo&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService4ProtocolTestListTypesCase1(t *testing.T) { - svc := NewInputService4ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService4TestShapeInputService4TestCaseOperation1Input{ - ListArg: []*string{ - aws.String("foo"), - aws.String("bar"), - aws.String("baz"), - }, - } - req, _ := svc.InputService4TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - ec2query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&ListArg.1=foo&ListArg.2=bar&ListArg.3=baz&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService5ProtocolTestListWithLocationNameAppliedToMemberCase1(t *testing.T) { - svc := NewInputService5ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService5TestShapeInputService5TestCaseOperation1Input{ - ListArg: []*string{ - aws.String("a"), - aws.String("b"), - aws.String("c"), - }, - } - req, _ := svc.InputService5TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - ec2query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&ListMemberName.1=a&ListMemberName.2=b&ListMemberName.3=c&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService6ProtocolTestListWithLocationNameAndQueryNameCase1(t *testing.T) { - svc := NewInputService6ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService6TestShapeInputService6TestCaseOperation1Input{ - ListArg: []*string{ - aws.String("a"), - aws.String("b"), - aws.String("c"), - }, - } - req, _ := svc.InputService6TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - ec2query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&ListQueryName.1=a&ListQueryName.2=b&ListQueryName.3=c&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService7ProtocolTestBase64EncodedBlobsCase1(t *testing.T) { - svc := NewInputService7ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService7TestShapeInputService7TestCaseOperation1Input{ - BlobArg: []byte("foo"), - } - req, _ := svc.InputService7TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - ec2query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&BlobArg=Zm9v&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService8ProtocolTestTimestampValuesCase1(t *testing.T) { - svc := NewInputService8ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService8TestShapeInputService8TestCaseOperation1Input{ - TimeArg: aws.Time(time.Unix(1422172800, 0)), - } - req, _ := svc.InputService8TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - ec2query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&TimeArg=2015-01-25T08%3A00%3A00Z&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService9ProtocolTestIdempotencyTokenAutoFillCase1(t *testing.T) { - svc := NewInputService9ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService9TestShapeInputService9TestCaseOperation2Input{ - Token: aws.String("abc123"), - } - req, _ := svc.InputService9TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - ec2query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&Token=abc123&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService9ProtocolTestIdempotencyTokenAutoFillCase2(t *testing.T) { - svc := NewInputService9ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService9TestShapeInputService9TestCaseOperation2Input{} - req, _ := svc.InputService9TestCaseOperation2Request(input) - r := req.HTTPRequest - - // build request - ec2query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&Token=00000000-0000-4000-8000-000000000000&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/ec2query/unmarshal_test.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/ec2query/unmarshal_test.go deleted file mode 100644 index a63b32985..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/ec2query/unmarshal_test.go +++ /dev/null @@ -1,1678 +0,0 @@ -package ec2query_test - -import ( - "bytes" - "encoding/json" - "encoding/xml" - "fmt" - "io" - "io/ioutil" - "net/http" - "net/url" - "reflect" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/client" - "github.com/aws/aws-sdk-go/aws/client/metadata" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/aws/signer/v4" - "github.com/aws/aws-sdk-go/awstesting" - "github.com/aws/aws-sdk-go/awstesting/unit" - "github.com/aws/aws-sdk-go/private/protocol" - "github.com/aws/aws-sdk-go/private/protocol/ec2query" - "github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil" - "github.com/aws/aws-sdk-go/private/util" -) - -var _ bytes.Buffer // always import bytes -var _ http.Request -var _ json.Marshaler -var _ time.Time -var _ xmlutil.XMLNode -var _ xml.Attr -var _ = ioutil.Discard -var _ = util.Trim("") -var _ = url.Values{} -var _ = io.EOF -var _ = aws.String -var _ = fmt.Println -var _ = reflect.Value{} - -func init() { - protocol.RandReader = &awstesting.ZeroReader{} -} - -// OutputService1ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// OutputService1ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type OutputService1ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the OutputService1ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a OutputService1ProtocolTest client from just a session. -// svc := outputservice1protocoltest.New(mySession) -// -// // Create a OutputService1ProtocolTest client with additional configuration -// svc := outputservice1protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewOutputService1ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService1ProtocolTest { - c := p.ClientConfig("outputservice1protocoltest", cfgs...) - return newOutputService1ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newOutputService1ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *OutputService1ProtocolTest { - svc := &OutputService1ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "outputservice1protocoltest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a OutputService1ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService1ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService1TestCaseOperation1 = "OperationName" - -// OutputService1TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the OutputService1TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See OutputService1TestCaseOperation1 for more information on using the OutputService1TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the OutputService1TestCaseOperation1Request method. -// req, resp := client.OutputService1TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *OutputService1ProtocolTest) OutputService1TestCaseOperation1Request(input *OutputService1TestShapeOutputService1TestCaseOperation1Input) (req *request.Request, output *OutputService1TestShapeOutputService1TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService1TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &OutputService1TestShapeOutputService1TestCaseOperation1Input{} - } - - output = &OutputService1TestShapeOutputService1TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - return -} - -// OutputService1TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation OutputService1TestCaseOperation1 for usage and error information. -func (c *OutputService1ProtocolTest) OutputService1TestCaseOperation1(input *OutputService1TestShapeOutputService1TestCaseOperation1Input) (*OutputService1TestShapeOutputService1TestCaseOperation1Output, error) { - req, out := c.OutputService1TestCaseOperation1Request(input) - return out, req.Send() -} - -// OutputService1TestCaseOperation1WithContext is the same as OutputService1TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See OutputService1TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *OutputService1ProtocolTest) OutputService1TestCaseOperation1WithContext(ctx aws.Context, input *OutputService1TestShapeOutputService1TestCaseOperation1Input, opts ...request.Option) (*OutputService1TestShapeOutputService1TestCaseOperation1Output, error) { - req, out := c.OutputService1TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type OutputService1TestShapeOutputService1TestCaseOperation1Input struct { - _ struct{} `type:"structure"` -} - -type OutputService1TestShapeOutputService1TestCaseOperation1Output struct { - _ struct{} `type:"structure"` - - Char *string `type:"character"` - - Double *float64 `type:"double"` - - FalseBool *bool `type:"boolean"` - - Float *float64 `type:"float"` - - Long *int64 `type:"long"` - - Num *int64 `locationName:"FooNum" type:"integer"` - - Str *string `type:"string"` - - TrueBool *bool `type:"boolean"` -} - -// SetChar sets the Char field's value. -func (s *OutputService1TestShapeOutputService1TestCaseOperation1Output) SetChar(v string) *OutputService1TestShapeOutputService1TestCaseOperation1Output { - s.Char = &v - return s -} - -// SetDouble sets the Double field's value. -func (s *OutputService1TestShapeOutputService1TestCaseOperation1Output) SetDouble(v float64) *OutputService1TestShapeOutputService1TestCaseOperation1Output { - s.Double = &v - return s -} - -// SetFalseBool sets the FalseBool field's value. -func (s *OutputService1TestShapeOutputService1TestCaseOperation1Output) SetFalseBool(v bool) *OutputService1TestShapeOutputService1TestCaseOperation1Output { - s.FalseBool = &v - return s -} - -// SetFloat sets the Float field's value. -func (s *OutputService1TestShapeOutputService1TestCaseOperation1Output) SetFloat(v float64) *OutputService1TestShapeOutputService1TestCaseOperation1Output { - s.Float = &v - return s -} - -// SetLong sets the Long field's value. -func (s *OutputService1TestShapeOutputService1TestCaseOperation1Output) SetLong(v int64) *OutputService1TestShapeOutputService1TestCaseOperation1Output { - s.Long = &v - return s -} - -// SetNum sets the Num field's value. -func (s *OutputService1TestShapeOutputService1TestCaseOperation1Output) SetNum(v int64) *OutputService1TestShapeOutputService1TestCaseOperation1Output { - s.Num = &v - return s -} - -// SetStr sets the Str field's value. -func (s *OutputService1TestShapeOutputService1TestCaseOperation1Output) SetStr(v string) *OutputService1TestShapeOutputService1TestCaseOperation1Output { - s.Str = &v - return s -} - -// SetTrueBool sets the TrueBool field's value. -func (s *OutputService1TestShapeOutputService1TestCaseOperation1Output) SetTrueBool(v bool) *OutputService1TestShapeOutputService1TestCaseOperation1Output { - s.TrueBool = &v - return s -} - -// OutputService2ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// OutputService2ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type OutputService2ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the OutputService2ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a OutputService2ProtocolTest client from just a session. -// svc := outputservice2protocoltest.New(mySession) -// -// // Create a OutputService2ProtocolTest client with additional configuration -// svc := outputservice2protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewOutputService2ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService2ProtocolTest { - c := p.ClientConfig("outputservice2protocoltest", cfgs...) - return newOutputService2ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newOutputService2ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *OutputService2ProtocolTest { - svc := &OutputService2ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "outputservice2protocoltest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a OutputService2ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService2ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService2TestCaseOperation1 = "OperationName" - -// OutputService2TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the OutputService2TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See OutputService2TestCaseOperation1 for more information on using the OutputService2TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the OutputService2TestCaseOperation1Request method. -// req, resp := client.OutputService2TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *OutputService2ProtocolTest) OutputService2TestCaseOperation1Request(input *OutputService2TestShapeOutputService2TestCaseOperation1Input) (req *request.Request, output *OutputService2TestShapeOutputService2TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService2TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &OutputService2TestShapeOutputService2TestCaseOperation1Input{} - } - - output = &OutputService2TestShapeOutputService2TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - return -} - -// OutputService2TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation OutputService2TestCaseOperation1 for usage and error information. -func (c *OutputService2ProtocolTest) OutputService2TestCaseOperation1(input *OutputService2TestShapeOutputService2TestCaseOperation1Input) (*OutputService2TestShapeOutputService2TestCaseOperation1Output, error) { - req, out := c.OutputService2TestCaseOperation1Request(input) - return out, req.Send() -} - -// OutputService2TestCaseOperation1WithContext is the same as OutputService2TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See OutputService2TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *OutputService2ProtocolTest) OutputService2TestCaseOperation1WithContext(ctx aws.Context, input *OutputService2TestShapeOutputService2TestCaseOperation1Input, opts ...request.Option) (*OutputService2TestShapeOutputService2TestCaseOperation1Output, error) { - req, out := c.OutputService2TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type OutputService2TestShapeOutputService2TestCaseOperation1Input struct { - _ struct{} `type:"structure"` -} - -type OutputService2TestShapeOutputService2TestCaseOperation1Output struct { - _ struct{} `type:"structure"` - - // Blob is automatically base64 encoded/decoded by the SDK. - Blob []byte `type:"blob"` -} - -// SetBlob sets the Blob field's value. -func (s *OutputService2TestShapeOutputService2TestCaseOperation1Output) SetBlob(v []byte) *OutputService2TestShapeOutputService2TestCaseOperation1Output { - s.Blob = v - return s -} - -// OutputService3ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// OutputService3ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type OutputService3ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the OutputService3ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a OutputService3ProtocolTest client from just a session. -// svc := outputservice3protocoltest.New(mySession) -// -// // Create a OutputService3ProtocolTest client with additional configuration -// svc := outputservice3protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewOutputService3ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService3ProtocolTest { - c := p.ClientConfig("outputservice3protocoltest", cfgs...) - return newOutputService3ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newOutputService3ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *OutputService3ProtocolTest { - svc := &OutputService3ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "outputservice3protocoltest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a OutputService3ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService3ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService3TestCaseOperation1 = "OperationName" - -// OutputService3TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the OutputService3TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See OutputService3TestCaseOperation1 for more information on using the OutputService3TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the OutputService3TestCaseOperation1Request method. -// req, resp := client.OutputService3TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *OutputService3ProtocolTest) OutputService3TestCaseOperation1Request(input *OutputService3TestShapeOutputService3TestCaseOperation1Input) (req *request.Request, output *OutputService3TestShapeOutputService3TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService3TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &OutputService3TestShapeOutputService3TestCaseOperation1Input{} - } - - output = &OutputService3TestShapeOutputService3TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - return -} - -// OutputService3TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation OutputService3TestCaseOperation1 for usage and error information. -func (c *OutputService3ProtocolTest) OutputService3TestCaseOperation1(input *OutputService3TestShapeOutputService3TestCaseOperation1Input) (*OutputService3TestShapeOutputService3TestCaseOperation1Output, error) { - req, out := c.OutputService3TestCaseOperation1Request(input) - return out, req.Send() -} - -// OutputService3TestCaseOperation1WithContext is the same as OutputService3TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See OutputService3TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *OutputService3ProtocolTest) OutputService3TestCaseOperation1WithContext(ctx aws.Context, input *OutputService3TestShapeOutputService3TestCaseOperation1Input, opts ...request.Option) (*OutputService3TestShapeOutputService3TestCaseOperation1Output, error) { - req, out := c.OutputService3TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type OutputService3TestShapeOutputService3TestCaseOperation1Input struct { - _ struct{} `type:"structure"` -} - -type OutputService3TestShapeOutputService3TestCaseOperation1Output struct { - _ struct{} `type:"structure"` - - ListMember []*string `type:"list"` -} - -// SetListMember sets the ListMember field's value. -func (s *OutputService3TestShapeOutputService3TestCaseOperation1Output) SetListMember(v []*string) *OutputService3TestShapeOutputService3TestCaseOperation1Output { - s.ListMember = v - return s -} - -// OutputService4ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// OutputService4ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type OutputService4ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the OutputService4ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a OutputService4ProtocolTest client from just a session. -// svc := outputservice4protocoltest.New(mySession) -// -// // Create a OutputService4ProtocolTest client with additional configuration -// svc := outputservice4protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewOutputService4ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService4ProtocolTest { - c := p.ClientConfig("outputservice4protocoltest", cfgs...) - return newOutputService4ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newOutputService4ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *OutputService4ProtocolTest { - svc := &OutputService4ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "outputservice4protocoltest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a OutputService4ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService4ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService4TestCaseOperation1 = "OperationName" - -// OutputService4TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the OutputService4TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See OutputService4TestCaseOperation1 for more information on using the OutputService4TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the OutputService4TestCaseOperation1Request method. -// req, resp := client.OutputService4TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *OutputService4ProtocolTest) OutputService4TestCaseOperation1Request(input *OutputService4TestShapeOutputService4TestCaseOperation1Input) (req *request.Request, output *OutputService4TestShapeOutputService4TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService4TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &OutputService4TestShapeOutputService4TestCaseOperation1Input{} - } - - output = &OutputService4TestShapeOutputService4TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - return -} - -// OutputService4TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation OutputService4TestCaseOperation1 for usage and error information. -func (c *OutputService4ProtocolTest) OutputService4TestCaseOperation1(input *OutputService4TestShapeOutputService4TestCaseOperation1Input) (*OutputService4TestShapeOutputService4TestCaseOperation1Output, error) { - req, out := c.OutputService4TestCaseOperation1Request(input) - return out, req.Send() -} - -// OutputService4TestCaseOperation1WithContext is the same as OutputService4TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See OutputService4TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *OutputService4ProtocolTest) OutputService4TestCaseOperation1WithContext(ctx aws.Context, input *OutputService4TestShapeOutputService4TestCaseOperation1Input, opts ...request.Option) (*OutputService4TestShapeOutputService4TestCaseOperation1Output, error) { - req, out := c.OutputService4TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type OutputService4TestShapeOutputService4TestCaseOperation1Input struct { - _ struct{} `type:"structure"` -} - -type OutputService4TestShapeOutputService4TestCaseOperation1Output struct { - _ struct{} `type:"structure"` - - ListMember []*string `locationNameList:"item" type:"list"` -} - -// SetListMember sets the ListMember field's value. -func (s *OutputService4TestShapeOutputService4TestCaseOperation1Output) SetListMember(v []*string) *OutputService4TestShapeOutputService4TestCaseOperation1Output { - s.ListMember = v - return s -} - -// OutputService5ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// OutputService5ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type OutputService5ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the OutputService5ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a OutputService5ProtocolTest client from just a session. -// svc := outputservice5protocoltest.New(mySession) -// -// // Create a OutputService5ProtocolTest client with additional configuration -// svc := outputservice5protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewOutputService5ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService5ProtocolTest { - c := p.ClientConfig("outputservice5protocoltest", cfgs...) - return newOutputService5ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newOutputService5ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *OutputService5ProtocolTest { - svc := &OutputService5ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "outputservice5protocoltest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a OutputService5ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService5ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService5TestCaseOperation1 = "OperationName" - -// OutputService5TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the OutputService5TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See OutputService5TestCaseOperation1 for more information on using the OutputService5TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the OutputService5TestCaseOperation1Request method. -// req, resp := client.OutputService5TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *OutputService5ProtocolTest) OutputService5TestCaseOperation1Request(input *OutputService5TestShapeOutputService5TestCaseOperation1Input) (req *request.Request, output *OutputService5TestShapeOutputService5TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService5TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &OutputService5TestShapeOutputService5TestCaseOperation1Input{} - } - - output = &OutputService5TestShapeOutputService5TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - return -} - -// OutputService5TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation OutputService5TestCaseOperation1 for usage and error information. -func (c *OutputService5ProtocolTest) OutputService5TestCaseOperation1(input *OutputService5TestShapeOutputService5TestCaseOperation1Input) (*OutputService5TestShapeOutputService5TestCaseOperation1Output, error) { - req, out := c.OutputService5TestCaseOperation1Request(input) - return out, req.Send() -} - -// OutputService5TestCaseOperation1WithContext is the same as OutputService5TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See OutputService5TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *OutputService5ProtocolTest) OutputService5TestCaseOperation1WithContext(ctx aws.Context, input *OutputService5TestShapeOutputService5TestCaseOperation1Input, opts ...request.Option) (*OutputService5TestShapeOutputService5TestCaseOperation1Output, error) { - req, out := c.OutputService5TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type OutputService5TestShapeOutputService5TestCaseOperation1Input struct { - _ struct{} `type:"structure"` -} - -type OutputService5TestShapeOutputService5TestCaseOperation1Output struct { - _ struct{} `type:"structure"` - - ListMember []*string `type:"list" flattened:"true"` -} - -// SetListMember sets the ListMember field's value. -func (s *OutputService5TestShapeOutputService5TestCaseOperation1Output) SetListMember(v []*string) *OutputService5TestShapeOutputService5TestCaseOperation1Output { - s.ListMember = v - return s -} - -// OutputService6ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// OutputService6ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type OutputService6ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the OutputService6ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a OutputService6ProtocolTest client from just a session. -// svc := outputservice6protocoltest.New(mySession) -// -// // Create a OutputService6ProtocolTest client with additional configuration -// svc := outputservice6protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewOutputService6ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService6ProtocolTest { - c := p.ClientConfig("outputservice6protocoltest", cfgs...) - return newOutputService6ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newOutputService6ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *OutputService6ProtocolTest { - svc := &OutputService6ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "outputservice6protocoltest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a OutputService6ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService6ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService6TestCaseOperation1 = "OperationName" - -// OutputService6TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the OutputService6TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See OutputService6TestCaseOperation1 for more information on using the OutputService6TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the OutputService6TestCaseOperation1Request method. -// req, resp := client.OutputService6TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *OutputService6ProtocolTest) OutputService6TestCaseOperation1Request(input *OutputService6TestShapeOutputService6TestCaseOperation1Input) (req *request.Request, output *OutputService6TestShapeOutputService6TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService6TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &OutputService6TestShapeOutputService6TestCaseOperation1Input{} - } - - output = &OutputService6TestShapeOutputService6TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - return -} - -// OutputService6TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation OutputService6TestCaseOperation1 for usage and error information. -func (c *OutputService6ProtocolTest) OutputService6TestCaseOperation1(input *OutputService6TestShapeOutputService6TestCaseOperation1Input) (*OutputService6TestShapeOutputService6TestCaseOperation1Output, error) { - req, out := c.OutputService6TestCaseOperation1Request(input) - return out, req.Send() -} - -// OutputService6TestCaseOperation1WithContext is the same as OutputService6TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See OutputService6TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *OutputService6ProtocolTest) OutputService6TestCaseOperation1WithContext(ctx aws.Context, input *OutputService6TestShapeOutputService6TestCaseOperation1Input, opts ...request.Option) (*OutputService6TestShapeOutputService6TestCaseOperation1Output, error) { - req, out := c.OutputService6TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type OutputService6TestShapeOutputService6TestCaseOperation1Input struct { - _ struct{} `type:"structure"` -} - -type OutputService6TestShapeOutputService6TestCaseOperation1Output struct { - _ struct{} `type:"structure"` - - Map map[string]*OutputService6TestShapeStructureType `type:"map"` -} - -// SetMap sets the Map field's value. -func (s *OutputService6TestShapeOutputService6TestCaseOperation1Output) SetMap(v map[string]*OutputService6TestShapeStructureType) *OutputService6TestShapeOutputService6TestCaseOperation1Output { - s.Map = v - return s -} - -type OutputService6TestShapeStructureType struct { - _ struct{} `type:"structure"` - - Foo *string `locationName:"foo" type:"string"` -} - -// SetFoo sets the Foo field's value. -func (s *OutputService6TestShapeStructureType) SetFoo(v string) *OutputService6TestShapeStructureType { - s.Foo = &v - return s -} - -// OutputService7ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// OutputService7ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type OutputService7ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the OutputService7ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a OutputService7ProtocolTest client from just a session. -// svc := outputservice7protocoltest.New(mySession) -// -// // Create a OutputService7ProtocolTest client with additional configuration -// svc := outputservice7protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewOutputService7ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService7ProtocolTest { - c := p.ClientConfig("outputservice7protocoltest", cfgs...) - return newOutputService7ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newOutputService7ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *OutputService7ProtocolTest { - svc := &OutputService7ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "outputservice7protocoltest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a OutputService7ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService7ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService7TestCaseOperation1 = "OperationName" - -// OutputService7TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the OutputService7TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See OutputService7TestCaseOperation1 for more information on using the OutputService7TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the OutputService7TestCaseOperation1Request method. -// req, resp := client.OutputService7TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *OutputService7ProtocolTest) OutputService7TestCaseOperation1Request(input *OutputService7TestShapeOutputService7TestCaseOperation1Input) (req *request.Request, output *OutputService7TestShapeOutputService7TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService7TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &OutputService7TestShapeOutputService7TestCaseOperation1Input{} - } - - output = &OutputService7TestShapeOutputService7TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - return -} - -// OutputService7TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation OutputService7TestCaseOperation1 for usage and error information. -func (c *OutputService7ProtocolTest) OutputService7TestCaseOperation1(input *OutputService7TestShapeOutputService7TestCaseOperation1Input) (*OutputService7TestShapeOutputService7TestCaseOperation1Output, error) { - req, out := c.OutputService7TestCaseOperation1Request(input) - return out, req.Send() -} - -// OutputService7TestCaseOperation1WithContext is the same as OutputService7TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See OutputService7TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *OutputService7ProtocolTest) OutputService7TestCaseOperation1WithContext(ctx aws.Context, input *OutputService7TestShapeOutputService7TestCaseOperation1Input, opts ...request.Option) (*OutputService7TestShapeOutputService7TestCaseOperation1Output, error) { - req, out := c.OutputService7TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type OutputService7TestShapeOutputService7TestCaseOperation1Input struct { - _ struct{} `type:"structure"` -} - -type OutputService7TestShapeOutputService7TestCaseOperation1Output struct { - _ struct{} `type:"structure"` - - Map map[string]*string `type:"map" flattened:"true"` -} - -// SetMap sets the Map field's value. -func (s *OutputService7TestShapeOutputService7TestCaseOperation1Output) SetMap(v map[string]*string) *OutputService7TestShapeOutputService7TestCaseOperation1Output { - s.Map = v - return s -} - -// OutputService8ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// OutputService8ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type OutputService8ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the OutputService8ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a OutputService8ProtocolTest client from just a session. -// svc := outputservice8protocoltest.New(mySession) -// -// // Create a OutputService8ProtocolTest client with additional configuration -// svc := outputservice8protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewOutputService8ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService8ProtocolTest { - c := p.ClientConfig("outputservice8protocoltest", cfgs...) - return newOutputService8ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newOutputService8ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *OutputService8ProtocolTest { - svc := &OutputService8ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "outputservice8protocoltest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a OutputService8ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService8ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService8TestCaseOperation1 = "OperationName" - -// OutputService8TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the OutputService8TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See OutputService8TestCaseOperation1 for more information on using the OutputService8TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the OutputService8TestCaseOperation1Request method. -// req, resp := client.OutputService8TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *OutputService8ProtocolTest) OutputService8TestCaseOperation1Request(input *OutputService8TestShapeOutputService8TestCaseOperation1Input) (req *request.Request, output *OutputService8TestShapeOutputService8TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService8TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &OutputService8TestShapeOutputService8TestCaseOperation1Input{} - } - - output = &OutputService8TestShapeOutputService8TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - return -} - -// OutputService8TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation OutputService8TestCaseOperation1 for usage and error information. -func (c *OutputService8ProtocolTest) OutputService8TestCaseOperation1(input *OutputService8TestShapeOutputService8TestCaseOperation1Input) (*OutputService8TestShapeOutputService8TestCaseOperation1Output, error) { - req, out := c.OutputService8TestCaseOperation1Request(input) - return out, req.Send() -} - -// OutputService8TestCaseOperation1WithContext is the same as OutputService8TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See OutputService8TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *OutputService8ProtocolTest) OutputService8TestCaseOperation1WithContext(ctx aws.Context, input *OutputService8TestShapeOutputService8TestCaseOperation1Input, opts ...request.Option) (*OutputService8TestShapeOutputService8TestCaseOperation1Output, error) { - req, out := c.OutputService8TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type OutputService8TestShapeOutputService8TestCaseOperation1Input struct { - _ struct{} `type:"structure"` -} - -type OutputService8TestShapeOutputService8TestCaseOperation1Output struct { - _ struct{} `type:"structure"` - - Map map[string]*string `locationNameKey:"foo" locationNameValue:"bar" type:"map" flattened:"true"` -} - -// SetMap sets the Map field's value. -func (s *OutputService8TestShapeOutputService8TestCaseOperation1Output) SetMap(v map[string]*string) *OutputService8TestShapeOutputService8TestCaseOperation1Output { - s.Map = v - return s -} - -// OutputService9ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// OutputService9ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type OutputService9ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the OutputService9ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a OutputService9ProtocolTest client from just a session. -// svc := outputservice9protocoltest.New(mySession) -// -// // Create a OutputService9ProtocolTest client with additional configuration -// svc := outputservice9protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewOutputService9ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService9ProtocolTest { - c := p.ClientConfig("outputservice9protocoltest", cfgs...) - return newOutputService9ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newOutputService9ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *OutputService9ProtocolTest { - svc := &OutputService9ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "outputservice9protocoltest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a OutputService9ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService9ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService9TestCaseOperation1 = "OperationName" - -// OutputService9TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the OutputService9TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See OutputService9TestCaseOperation1 for more information on using the OutputService9TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the OutputService9TestCaseOperation1Request method. -// req, resp := client.OutputService9TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *OutputService9ProtocolTest) OutputService9TestCaseOperation1Request(input *OutputService9TestShapeOutputService9TestCaseOperation1Input) (req *request.Request, output *OutputService9TestShapeOutputService9TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService9TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &OutputService9TestShapeOutputService9TestCaseOperation1Input{} - } - - output = &OutputService9TestShapeOutputService9TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - return -} - -// OutputService9TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation OutputService9TestCaseOperation1 for usage and error information. -func (c *OutputService9ProtocolTest) OutputService9TestCaseOperation1(input *OutputService9TestShapeOutputService9TestCaseOperation1Input) (*OutputService9TestShapeOutputService9TestCaseOperation1Output, error) { - req, out := c.OutputService9TestCaseOperation1Request(input) - return out, req.Send() -} - -// OutputService9TestCaseOperation1WithContext is the same as OutputService9TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See OutputService9TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *OutputService9ProtocolTest) OutputService9TestCaseOperation1WithContext(ctx aws.Context, input *OutputService9TestShapeOutputService9TestCaseOperation1Input, opts ...request.Option) (*OutputService9TestShapeOutputService9TestCaseOperation1Output, error) { - req, out := c.OutputService9TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type OutputService9TestShapeOutputService9TestCaseOperation1Input struct { - _ struct{} `type:"structure"` -} - -type OutputService9TestShapeOutputService9TestCaseOperation1Output struct { - _ struct{} `type:"structure"` - - Foo *string `type:"string"` -} - -// SetFoo sets the Foo field's value. -func (s *OutputService9TestShapeOutputService9TestCaseOperation1Output) SetFoo(v string) *OutputService9TestShapeOutputService9TestCaseOperation1Output { - s.Foo = &v - return s -} - -// -// Tests begin here -// - -func TestOutputService1ProtocolTestScalarMembersCase1(t *testing.T) { - svc := NewOutputService1ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - - buf := bytes.NewReader([]byte("myname123falsetrue1.21.3200arequest-id")) - req, out := svc.OutputService1TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - ec2query.UnmarshalMeta(req) - ec2query.Unmarshal(req) - if req.Error != nil { - t.Errorf("expect not error, got %v", req.Error) - } - - // assert response - if out == nil { - t.Errorf("expect not to be nil") - } - if e, a := "a", *out.Char; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := 1.3, *out.Double; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := false, *out.FalseBool; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := 1.2, *out.Float; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := int64(200), *out.Long; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := int64(123), *out.Num; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "myname", *out.Str; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := true, *out.TrueBool; e != a { - t.Errorf("expect %v, got %v", e, a) - } - -} - -func TestOutputService2ProtocolTestBlobCase1(t *testing.T) { - svc := NewOutputService2ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - - buf := bytes.NewReader([]byte("dmFsdWU=requestid")) - req, out := svc.OutputService2TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - ec2query.UnmarshalMeta(req) - ec2query.Unmarshal(req) - if req.Error != nil { - t.Errorf("expect not error, got %v", req.Error) - } - - // assert response - if out == nil { - t.Errorf("expect not to be nil") - } - if e, a := "value", string(out.Blob); e != a { - t.Errorf("expect %v, got %v", e, a) - } - -} - -func TestOutputService3ProtocolTestListsCase1(t *testing.T) { - svc := NewOutputService3ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - - buf := bytes.NewReader([]byte("abc123requestid")) - req, out := svc.OutputService3TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - ec2query.UnmarshalMeta(req) - ec2query.Unmarshal(req) - if req.Error != nil { - t.Errorf("expect not error, got %v", req.Error) - } - - // assert response - if out == nil { - t.Errorf("expect not to be nil") - } - if e, a := "abc", *out.ListMember[0]; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "123", *out.ListMember[1]; e != a { - t.Errorf("expect %v, got %v", e, a) - } - -} - -func TestOutputService4ProtocolTestListWithCustomMemberNameCase1(t *testing.T) { - svc := NewOutputService4ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - - buf := bytes.NewReader([]byte("abc123requestid")) - req, out := svc.OutputService4TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - ec2query.UnmarshalMeta(req) - ec2query.Unmarshal(req) - if req.Error != nil { - t.Errorf("expect not error, got %v", req.Error) - } - - // assert response - if out == nil { - t.Errorf("expect not to be nil") - } - if e, a := "abc", *out.ListMember[0]; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "123", *out.ListMember[1]; e != a { - t.Errorf("expect %v, got %v", e, a) - } - -} - -func TestOutputService5ProtocolTestFlattenedListCase1(t *testing.T) { - svc := NewOutputService5ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - - buf := bytes.NewReader([]byte("abc123requestid")) - req, out := svc.OutputService5TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - ec2query.UnmarshalMeta(req) - ec2query.Unmarshal(req) - if req.Error != nil { - t.Errorf("expect not error, got %v", req.Error) - } - - // assert response - if out == nil { - t.Errorf("expect not to be nil") - } - if e, a := "abc", *out.ListMember[0]; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "123", *out.ListMember[1]; e != a { - t.Errorf("expect %v, got %v", e, a) - } - -} - -func TestOutputService6ProtocolTestNormalMapCase1(t *testing.T) { - svc := NewOutputService6ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - - buf := bytes.NewReader([]byte("quxbarbazbamrequestid")) - req, out := svc.OutputService6TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - ec2query.UnmarshalMeta(req) - ec2query.Unmarshal(req) - if req.Error != nil { - t.Errorf("expect not error, got %v", req.Error) - } - - // assert response - if out == nil { - t.Errorf("expect not to be nil") - } - if e, a := "bam", *out.Map["baz"].Foo; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "bar", *out.Map["qux"].Foo; e != a { - t.Errorf("expect %v, got %v", e, a) - } - -} - -func TestOutputService7ProtocolTestFlattenedMapCase1(t *testing.T) { - svc := NewOutputService7ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - - buf := bytes.NewReader([]byte("quxbarbazbamrequestid")) - req, out := svc.OutputService7TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - ec2query.UnmarshalMeta(req) - ec2query.Unmarshal(req) - if req.Error != nil { - t.Errorf("expect not error, got %v", req.Error) - } - - // assert response - if out == nil { - t.Errorf("expect not to be nil") - } - if e, a := "bam", *out.Map["baz"]; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "bar", *out.Map["qux"]; e != a { - t.Errorf("expect %v, got %v", e, a) - } - -} - -func TestOutputService8ProtocolTestNamedMapCase1(t *testing.T) { - svc := NewOutputService8ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - - buf := bytes.NewReader([]byte("quxbarbazbamrequestid")) - req, out := svc.OutputService8TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - ec2query.UnmarshalMeta(req) - ec2query.Unmarshal(req) - if req.Error != nil { - t.Errorf("expect not error, got %v", req.Error) - } - - // assert response - if out == nil { - t.Errorf("expect not to be nil") - } - if e, a := "bam", *out.Map["baz"]; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "bar", *out.Map["qux"]; e != a { - t.Errorf("expect %v, got %v", e, a) - } - -} - -func TestOutputService9ProtocolTestEmptyStringCase1(t *testing.T) { - svc := NewOutputService9ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - - buf := bytes.NewReader([]byte("requestid")) - req, out := svc.OutputService9TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - ec2query.UnmarshalMeta(req) - ec2query.Unmarshal(req) - if req.Error != nil { - t.Errorf("expect not error, got %v", req.Error) - } - - // assert response - if out == nil { - t.Errorf("expect not to be nil") - } - if e, a := "", *out.Foo; e != a { - t.Errorf("expect %v, got %v", e, a) - } - -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/idempotency_test.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/idempotency_test.go deleted file mode 100644 index b6ea23562..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/idempotency_test.go +++ /dev/null @@ -1,106 +0,0 @@ -package protocol_test - -import ( - "reflect" - "testing" - - "github.com/aws/aws-sdk-go/private/protocol" - "github.com/stretchr/testify/assert" -) - -func TestCanSetIdempotencyToken(t *testing.T) { - cases := []struct { - CanSet bool - Case interface{} - }{ - { - true, - struct { - Field *string `idempotencyToken:"true"` - }{}, - }, - { - true, - struct { - Field string `idempotencyToken:"true"` - }{}, - }, - { - false, - struct { - Field *string `idempotencyToken:"true"` - }{Field: new(string)}, - }, - { - false, - struct { - Field string `idempotencyToken:"true"` - }{Field: "value"}, - }, - { - false, - struct { - Field *int `idempotencyToken:"true"` - }{}, - }, - { - false, - struct { - Field *string - }{}, - }, - } - - for i, c := range cases { - v := reflect.Indirect(reflect.ValueOf(c.Case)) - ty := v.Type() - canSet := protocol.CanSetIdempotencyToken(v.Field(0), ty.Field(0)) - assert.Equal(t, c.CanSet, canSet, "Expect case %d can set to match", i) - } -} - -func TestSetIdempotencyToken(t *testing.T) { - cases := []struct { - Case interface{} - }{ - { - &struct { - Field *string `idempotencyToken:"true"` - }{}, - }, - { - &struct { - Field string `idempotencyToken:"true"` - }{}, - }, - { - &struct { - Field *string `idempotencyToken:"true"` - }{Field: new(string)}, - }, - { - &struct { - Field string `idempotencyToken:"true"` - }{Field: ""}, - }, - } - - for i, c := range cases { - v := reflect.Indirect(reflect.ValueOf(c.Case)) - - protocol.SetIdempotencyToken(v.Field(0)) - assert.NotEmpty(t, v.Field(0).Interface(), "Expect case %d to be set", i) - } -} - -func TestUUIDVersion4(t *testing.T) { - uuid := protocol.UUIDVersion4(make([]byte, 16)) - assert.Equal(t, `00000000-0000-4000-8000-000000000000`, uuid) - - b := make([]byte, 16) - for i := 0; i < len(b); i++ { - b[i] = 1 - } - uuid = protocol.UUIDVersion4(b) - assert.Equal(t, `01010101-0101-4101-8101-010101010101`, uuid) -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/protocol_test.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/protocol_test.go deleted file mode 100644 index eb2e155be..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/protocol_test.go +++ /dev/null @@ -1,203 +0,0 @@ -package protocol_test - -import ( - "net/http" - "net/url" - "testing" - - "github.com/stretchr/testify/assert" - - "github.com/aws/aws-sdk-go/aws/client/metadata" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/awstesting" - "github.com/aws/aws-sdk-go/private/protocol" - "github.com/aws/aws-sdk-go/private/protocol/ec2query" - "github.com/aws/aws-sdk-go/private/protocol/jsonrpc" - "github.com/aws/aws-sdk-go/private/protocol/query" - "github.com/aws/aws-sdk-go/private/protocol/rest" - "github.com/aws/aws-sdk-go/private/protocol/restjson" - "github.com/aws/aws-sdk-go/private/protocol/restxml" -) - -func xmlData(set bool, b []byte, size, delta int) { - const openingTags = "" - const closingTags = "" - if !set { - copy(b, []byte(openingTags)) - } - if size == 0 { - copy(b[delta-len(closingTags):], []byte(closingTags)) - } -} - -func jsonData(set bool, b []byte, size, delta int) { - if !set { - copy(b, []byte("{\"A\": \"")) - } - if size == 0 { - copy(b[delta-len("\"}"):], []byte("\"}")) - } -} - -func buildNewRequest(data interface{}) *request.Request { - v := url.Values{} - v.Set("test", "TEST") - v.Add("test1", "TEST1") - - req := &request.Request{ - HTTPRequest: &http.Request{ - Header: make(http.Header), - Body: &awstesting.ReadCloser{Size: 2048}, - URL: &url.URL{ - RawQuery: v.Encode(), - }, - }, - Params: &struct { - LocationName string `locationName:"test"` - }{ - "Test", - }, - ClientInfo: metadata.ClientInfo{ - ServiceName: "test", - TargetPrefix: "test", - JSONVersion: "test", - APIVersion: "test", - Endpoint: "test", - SigningName: "test", - SigningRegion: "test", - }, - Operation: &request.Operation{ - Name: "test", - }, - } - req.HTTPResponse = &http.Response{ - Body: &awstesting.ReadCloser{Size: 2048}, - Header: http.Header{ - "X-Amzn-Requestid": []string{"1"}, - }, - StatusCode: http.StatusOK, - } - - if data == nil { - data = &struct { - _ struct{} `type:"structure"` - LocationName *string `locationName:"testName"` - Location *string `location:"statusCode"` - A *string `type:"string"` - }{} - } - - req.Data = data - - return req -} - -type expected struct { - dataType int - closed bool - size int - errExists bool -} - -const ( - jsonType = iota - xmlType -) - -func checkForLeak(data interface{}, build, fn func(*request.Request), t *testing.T, result expected) { - req := buildNewRequest(data) - reader := req.HTTPResponse.Body.(*awstesting.ReadCloser) - switch result.dataType { - case jsonType: - reader.FillData = jsonData - case xmlType: - reader.FillData = xmlData - } - build(req) - fn(req) - - if result.errExists { - assert.NotNil(t, req.Error) - } else { - assert.Nil(t, req.Error) - } - - assert.Equal(t, reader.Closed, result.closed) - assert.Equal(t, reader.Size, result.size) -} - -func TestJSONRpc(t *testing.T) { - checkForLeak(nil, jsonrpc.Build, jsonrpc.Unmarshal, t, expected{jsonType, true, 0, false}) - checkForLeak(nil, jsonrpc.Build, jsonrpc.UnmarshalMeta, t, expected{jsonType, false, 2048, false}) - checkForLeak(nil, jsonrpc.Build, jsonrpc.UnmarshalError, t, expected{jsonType, true, 0, true}) -} - -func TestQuery(t *testing.T) { - checkForLeak(nil, query.Build, query.Unmarshal, t, expected{jsonType, true, 0, false}) - checkForLeak(nil, query.Build, query.UnmarshalMeta, t, expected{jsonType, false, 2048, false}) - checkForLeak(nil, query.Build, query.UnmarshalError, t, expected{jsonType, true, 0, true}) -} - -func TestRest(t *testing.T) { - // case 1: Payload io.ReadSeeker - checkForLeak(nil, rest.Build, rest.Unmarshal, t, expected{jsonType, false, 2048, false}) - checkForLeak(nil, query.Build, query.UnmarshalMeta, t, expected{jsonType, false, 2048, false}) - - // case 2: Payload *string - // should close the body - dataStr := struct { - _ struct{} `type:"structure" payload:"Payload"` - LocationName *string `locationName:"testName"` - Location *string `location:"statusCode"` - A *string `type:"string"` - Payload *string `locationName:"payload" type:"blob" required:"true"` - }{} - checkForLeak(&dataStr, rest.Build, rest.Unmarshal, t, expected{jsonType, true, 0, false}) - checkForLeak(&dataStr, query.Build, query.UnmarshalMeta, t, expected{jsonType, false, 2048, false}) - - // case 3: Payload []byte - // should close the body - dataBytes := struct { - _ struct{} `type:"structure" payload:"Payload"` - LocationName *string `locationName:"testName"` - Location *string `location:"statusCode"` - A *string `type:"string"` - Payload []byte `locationName:"payload" type:"blob" required:"true"` - }{} - checkForLeak(&dataBytes, rest.Build, rest.Unmarshal, t, expected{jsonType, true, 0, false}) - checkForLeak(&dataBytes, query.Build, query.UnmarshalMeta, t, expected{jsonType, false, 2048, false}) - - // case 4: Payload unsupported type - // should close the body - dataUnsupported := struct { - _ struct{} `type:"structure" payload:"Payload"` - LocationName *string `locationName:"testName"` - Location *string `location:"statusCode"` - A *string `type:"string"` - Payload string `locationName:"payload" type:"blob" required:"true"` - }{} - checkForLeak(&dataUnsupported, rest.Build, rest.Unmarshal, t, expected{jsonType, true, 0, true}) - checkForLeak(&dataUnsupported, query.Build, query.UnmarshalMeta, t, expected{jsonType, false, 2048, false}) -} - -func TestRestJSON(t *testing.T) { - checkForLeak(nil, restjson.Build, restjson.Unmarshal, t, expected{jsonType, true, 0, false}) - checkForLeak(nil, restjson.Build, restjson.UnmarshalMeta, t, expected{jsonType, false, 2048, false}) - checkForLeak(nil, restjson.Build, restjson.UnmarshalError, t, expected{jsonType, true, 0, true}) -} - -func TestRestXML(t *testing.T) { - checkForLeak(nil, restxml.Build, restxml.Unmarshal, t, expected{xmlType, true, 0, false}) - checkForLeak(nil, restxml.Build, restxml.UnmarshalMeta, t, expected{xmlType, false, 2048, false}) - checkForLeak(nil, restxml.Build, restxml.UnmarshalError, t, expected{xmlType, true, 0, true}) -} - -func TestXML(t *testing.T) { - checkForLeak(nil, ec2query.Build, ec2query.Unmarshal, t, expected{jsonType, true, 0, false}) - checkForLeak(nil, ec2query.Build, ec2query.UnmarshalMeta, t, expected{jsonType, false, 2048, false}) - checkForLeak(nil, ec2query.Build, ec2query.UnmarshalError, t, expected{jsonType, true, 0, true}) -} - -func TestProtocol(t *testing.T) { - checkForLeak(nil, restxml.Build, protocol.UnmarshalDiscardBody, t, expected{xmlType, true, 0, false}) -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/query/build_test.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/query/build_test.go deleted file mode 100644 index f9990923a..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/query/build_test.go +++ /dev/null @@ -1,3657 +0,0 @@ -package query_test - -import ( - "bytes" - "encoding/json" - "encoding/xml" - "fmt" - "io" - "io/ioutil" - "net/http" - "net/url" - "reflect" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/client" - "github.com/aws/aws-sdk-go/aws/client/metadata" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/aws/signer/v4" - "github.com/aws/aws-sdk-go/awstesting" - "github.com/aws/aws-sdk-go/awstesting/unit" - "github.com/aws/aws-sdk-go/private/protocol" - "github.com/aws/aws-sdk-go/private/protocol/query" - "github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil" - "github.com/aws/aws-sdk-go/private/util" -) - -var _ bytes.Buffer // always import bytes -var _ http.Request -var _ json.Marshaler -var _ time.Time -var _ xmlutil.XMLNode -var _ xml.Attr -var _ = ioutil.Discard -var _ = util.Trim("") -var _ = url.Values{} -var _ = io.EOF -var _ = aws.String -var _ = fmt.Println -var _ = reflect.Value{} - -func init() { - protocol.RandReader = &awstesting.ZeroReader{} -} - -// InputService1ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// InputService1ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type InputService1ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the InputService1ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a InputService1ProtocolTest client from just a session. -// svc := inputservice1protocoltest.New(mySession) -// -// // Create a InputService1ProtocolTest client with additional configuration -// svc := inputservice1protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewInputService1ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService1ProtocolTest { - c := p.ClientConfig("inputservice1protocoltest", cfgs...) - return newInputService1ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newInputService1ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *InputService1ProtocolTest { - svc := &InputService1ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "inputservice1protocoltest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "2014-01-01", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a InputService1ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService1ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opInputService1TestCaseOperation1 = "OperationName" - -// InputService1TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the InputService1TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService1TestCaseOperation1 for more information on using the InputService1TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService1TestCaseOperation1Request method. -// req, resp := client.InputService1TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService1ProtocolTest) InputService1TestCaseOperation1Request(input *InputService1TestShapeInputService1TestCaseOperation3Input) (req *request.Request, output *InputService1TestShapeInputService1TestCaseOperation1Output) { - op := &request.Operation{ - Name: opInputService1TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &InputService1TestShapeInputService1TestCaseOperation3Input{} - } - - output = &InputService1TestShapeInputService1TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService1TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService1TestCaseOperation1 for usage and error information. -func (c *InputService1ProtocolTest) InputService1TestCaseOperation1(input *InputService1TestShapeInputService1TestCaseOperation3Input) (*InputService1TestShapeInputService1TestCaseOperation1Output, error) { - req, out := c.InputService1TestCaseOperation1Request(input) - return out, req.Send() -} - -// InputService1TestCaseOperation1WithContext is the same as InputService1TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService1TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService1ProtocolTest) InputService1TestCaseOperation1WithContext(ctx aws.Context, input *InputService1TestShapeInputService1TestCaseOperation3Input, opts ...request.Option) (*InputService1TestShapeInputService1TestCaseOperation1Output, error) { - req, out := c.InputService1TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opInputService1TestCaseOperation2 = "OperationName" - -// InputService1TestCaseOperation2Request generates a "aws/request.Request" representing the -// client's request for the InputService1TestCaseOperation2 operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService1TestCaseOperation2 for more information on using the InputService1TestCaseOperation2 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService1TestCaseOperation2Request method. -// req, resp := client.InputService1TestCaseOperation2Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService1ProtocolTest) InputService1TestCaseOperation2Request(input *InputService1TestShapeInputService1TestCaseOperation3Input) (req *request.Request, output *InputService1TestShapeInputService1TestCaseOperation2Output) { - op := &request.Operation{ - Name: opInputService1TestCaseOperation2, - HTTPPath: "/", - } - - if input == nil { - input = &InputService1TestShapeInputService1TestCaseOperation3Input{} - } - - output = &InputService1TestShapeInputService1TestCaseOperation2Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService1TestCaseOperation2 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService1TestCaseOperation2 for usage and error information. -func (c *InputService1ProtocolTest) InputService1TestCaseOperation2(input *InputService1TestShapeInputService1TestCaseOperation3Input) (*InputService1TestShapeInputService1TestCaseOperation2Output, error) { - req, out := c.InputService1TestCaseOperation2Request(input) - return out, req.Send() -} - -// InputService1TestCaseOperation2WithContext is the same as InputService1TestCaseOperation2 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService1TestCaseOperation2 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService1ProtocolTest) InputService1TestCaseOperation2WithContext(ctx aws.Context, input *InputService1TestShapeInputService1TestCaseOperation3Input, opts ...request.Option) (*InputService1TestShapeInputService1TestCaseOperation2Output, error) { - req, out := c.InputService1TestCaseOperation2Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opInputService1TestCaseOperation3 = "OperationName" - -// InputService1TestCaseOperation3Request generates a "aws/request.Request" representing the -// client's request for the InputService1TestCaseOperation3 operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService1TestCaseOperation3 for more information on using the InputService1TestCaseOperation3 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService1TestCaseOperation3Request method. -// req, resp := client.InputService1TestCaseOperation3Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService1ProtocolTest) InputService1TestCaseOperation3Request(input *InputService1TestShapeInputService1TestCaseOperation3Input) (req *request.Request, output *InputService1TestShapeInputService1TestCaseOperation3Output) { - op := &request.Operation{ - Name: opInputService1TestCaseOperation3, - HTTPPath: "/", - } - - if input == nil { - input = &InputService1TestShapeInputService1TestCaseOperation3Input{} - } - - output = &InputService1TestShapeInputService1TestCaseOperation3Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService1TestCaseOperation3 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService1TestCaseOperation3 for usage and error information. -func (c *InputService1ProtocolTest) InputService1TestCaseOperation3(input *InputService1TestShapeInputService1TestCaseOperation3Input) (*InputService1TestShapeInputService1TestCaseOperation3Output, error) { - req, out := c.InputService1TestCaseOperation3Request(input) - return out, req.Send() -} - -// InputService1TestCaseOperation3WithContext is the same as InputService1TestCaseOperation3 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService1TestCaseOperation3 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService1ProtocolTest) InputService1TestCaseOperation3WithContext(ctx aws.Context, input *InputService1TestShapeInputService1TestCaseOperation3Input, opts ...request.Option) (*InputService1TestShapeInputService1TestCaseOperation3Output, error) { - req, out := c.InputService1TestCaseOperation3Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type InputService1TestShapeInputService1TestCaseOperation1Output struct { - _ struct{} `type:"structure"` -} - -type InputService1TestShapeInputService1TestCaseOperation2Output struct { - _ struct{} `type:"structure"` -} - -type InputService1TestShapeInputService1TestCaseOperation3Input struct { - _ struct{} `type:"structure"` - - Bar *string `type:"string"` - - Baz *bool `type:"boolean"` - - Foo *string `type:"string"` -} - -// SetBar sets the Bar field's value. -func (s *InputService1TestShapeInputService1TestCaseOperation3Input) SetBar(v string) *InputService1TestShapeInputService1TestCaseOperation3Input { - s.Bar = &v - return s -} - -// SetBaz sets the Baz field's value. -func (s *InputService1TestShapeInputService1TestCaseOperation3Input) SetBaz(v bool) *InputService1TestShapeInputService1TestCaseOperation3Input { - s.Baz = &v - return s -} - -// SetFoo sets the Foo field's value. -func (s *InputService1TestShapeInputService1TestCaseOperation3Input) SetFoo(v string) *InputService1TestShapeInputService1TestCaseOperation3Input { - s.Foo = &v - return s -} - -type InputService1TestShapeInputService1TestCaseOperation3Output struct { - _ struct{} `type:"structure"` -} - -// InputService2ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// InputService2ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type InputService2ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the InputService2ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a InputService2ProtocolTest client from just a session. -// svc := inputservice2protocoltest.New(mySession) -// -// // Create a InputService2ProtocolTest client with additional configuration -// svc := inputservice2protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewInputService2ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService2ProtocolTest { - c := p.ClientConfig("inputservice2protocoltest", cfgs...) - return newInputService2ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newInputService2ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *InputService2ProtocolTest { - svc := &InputService2ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "inputservice2protocoltest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "2014-01-01", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a InputService2ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService2ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opInputService2TestCaseOperation1 = "OperationName" - -// InputService2TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the InputService2TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService2TestCaseOperation1 for more information on using the InputService2TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService2TestCaseOperation1Request method. -// req, resp := client.InputService2TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService2ProtocolTest) InputService2TestCaseOperation1Request(input *InputService2TestShapeInputService2TestCaseOperation1Input) (req *request.Request, output *InputService2TestShapeInputService2TestCaseOperation1Output) { - op := &request.Operation{ - Name: opInputService2TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &InputService2TestShapeInputService2TestCaseOperation1Input{} - } - - output = &InputService2TestShapeInputService2TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService2TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService2TestCaseOperation1 for usage and error information. -func (c *InputService2ProtocolTest) InputService2TestCaseOperation1(input *InputService2TestShapeInputService2TestCaseOperation1Input) (*InputService2TestShapeInputService2TestCaseOperation1Output, error) { - req, out := c.InputService2TestCaseOperation1Request(input) - return out, req.Send() -} - -// InputService2TestCaseOperation1WithContext is the same as InputService2TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService2TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService2ProtocolTest) InputService2TestCaseOperation1WithContext(ctx aws.Context, input *InputService2TestShapeInputService2TestCaseOperation1Input, opts ...request.Option) (*InputService2TestShapeInputService2TestCaseOperation1Output, error) { - req, out := c.InputService2TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type InputService2TestShapeInputService2TestCaseOperation1Input struct { - _ struct{} `type:"structure"` - - StructArg *InputService2TestShapeStructType `type:"structure"` -} - -// SetStructArg sets the StructArg field's value. -func (s *InputService2TestShapeInputService2TestCaseOperation1Input) SetStructArg(v *InputService2TestShapeStructType) *InputService2TestShapeInputService2TestCaseOperation1Input { - s.StructArg = v - return s -} - -type InputService2TestShapeInputService2TestCaseOperation1Output struct { - _ struct{} `type:"structure"` -} - -type InputService2TestShapeStructType struct { - _ struct{} `type:"structure"` - - ScalarArg *string `type:"string"` -} - -// SetScalarArg sets the ScalarArg field's value. -func (s *InputService2TestShapeStructType) SetScalarArg(v string) *InputService2TestShapeStructType { - s.ScalarArg = &v - return s -} - -// InputService3ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// InputService3ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type InputService3ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the InputService3ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a InputService3ProtocolTest client from just a session. -// svc := inputservice3protocoltest.New(mySession) -// -// // Create a InputService3ProtocolTest client with additional configuration -// svc := inputservice3protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewInputService3ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService3ProtocolTest { - c := p.ClientConfig("inputservice3protocoltest", cfgs...) - return newInputService3ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newInputService3ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *InputService3ProtocolTest { - svc := &InputService3ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "inputservice3protocoltest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "2014-01-01", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a InputService3ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService3ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opInputService3TestCaseOperation1 = "OperationName" - -// InputService3TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the InputService3TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService3TestCaseOperation1 for more information on using the InputService3TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService3TestCaseOperation1Request method. -// req, resp := client.InputService3TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService3ProtocolTest) InputService3TestCaseOperation1Request(input *InputService3TestShapeInputService3TestCaseOperation2Input) (req *request.Request, output *InputService3TestShapeInputService3TestCaseOperation1Output) { - op := &request.Operation{ - Name: opInputService3TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &InputService3TestShapeInputService3TestCaseOperation2Input{} - } - - output = &InputService3TestShapeInputService3TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService3TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService3TestCaseOperation1 for usage and error information. -func (c *InputService3ProtocolTest) InputService3TestCaseOperation1(input *InputService3TestShapeInputService3TestCaseOperation2Input) (*InputService3TestShapeInputService3TestCaseOperation1Output, error) { - req, out := c.InputService3TestCaseOperation1Request(input) - return out, req.Send() -} - -// InputService3TestCaseOperation1WithContext is the same as InputService3TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService3TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService3ProtocolTest) InputService3TestCaseOperation1WithContext(ctx aws.Context, input *InputService3TestShapeInputService3TestCaseOperation2Input, opts ...request.Option) (*InputService3TestShapeInputService3TestCaseOperation1Output, error) { - req, out := c.InputService3TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opInputService3TestCaseOperation2 = "OperationName" - -// InputService3TestCaseOperation2Request generates a "aws/request.Request" representing the -// client's request for the InputService3TestCaseOperation2 operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService3TestCaseOperation2 for more information on using the InputService3TestCaseOperation2 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService3TestCaseOperation2Request method. -// req, resp := client.InputService3TestCaseOperation2Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService3ProtocolTest) InputService3TestCaseOperation2Request(input *InputService3TestShapeInputService3TestCaseOperation2Input) (req *request.Request, output *InputService3TestShapeInputService3TestCaseOperation2Output) { - op := &request.Operation{ - Name: opInputService3TestCaseOperation2, - HTTPPath: "/", - } - - if input == nil { - input = &InputService3TestShapeInputService3TestCaseOperation2Input{} - } - - output = &InputService3TestShapeInputService3TestCaseOperation2Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService3TestCaseOperation2 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService3TestCaseOperation2 for usage and error information. -func (c *InputService3ProtocolTest) InputService3TestCaseOperation2(input *InputService3TestShapeInputService3TestCaseOperation2Input) (*InputService3TestShapeInputService3TestCaseOperation2Output, error) { - req, out := c.InputService3TestCaseOperation2Request(input) - return out, req.Send() -} - -// InputService3TestCaseOperation2WithContext is the same as InputService3TestCaseOperation2 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService3TestCaseOperation2 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService3ProtocolTest) InputService3TestCaseOperation2WithContext(ctx aws.Context, input *InputService3TestShapeInputService3TestCaseOperation2Input, opts ...request.Option) (*InputService3TestShapeInputService3TestCaseOperation2Output, error) { - req, out := c.InputService3TestCaseOperation2Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type InputService3TestShapeInputService3TestCaseOperation1Output struct { - _ struct{} `type:"structure"` -} - -type InputService3TestShapeInputService3TestCaseOperation2Input struct { - _ struct{} `type:"structure"` - - ListArg []*string `type:"list"` -} - -// SetListArg sets the ListArg field's value. -func (s *InputService3TestShapeInputService3TestCaseOperation2Input) SetListArg(v []*string) *InputService3TestShapeInputService3TestCaseOperation2Input { - s.ListArg = v - return s -} - -type InputService3TestShapeInputService3TestCaseOperation2Output struct { - _ struct{} `type:"structure"` -} - -// InputService4ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// InputService4ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type InputService4ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the InputService4ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a InputService4ProtocolTest client from just a session. -// svc := inputservice4protocoltest.New(mySession) -// -// // Create a InputService4ProtocolTest client with additional configuration -// svc := inputservice4protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewInputService4ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService4ProtocolTest { - c := p.ClientConfig("inputservice4protocoltest", cfgs...) - return newInputService4ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newInputService4ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *InputService4ProtocolTest { - svc := &InputService4ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "inputservice4protocoltest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "2014-01-01", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a InputService4ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService4ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opInputService4TestCaseOperation1 = "OperationName" - -// InputService4TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the InputService4TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService4TestCaseOperation1 for more information on using the InputService4TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService4TestCaseOperation1Request method. -// req, resp := client.InputService4TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService4ProtocolTest) InputService4TestCaseOperation1Request(input *InputService4TestShapeInputService4TestCaseOperation2Input) (req *request.Request, output *InputService4TestShapeInputService4TestCaseOperation1Output) { - op := &request.Operation{ - Name: opInputService4TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &InputService4TestShapeInputService4TestCaseOperation2Input{} - } - - output = &InputService4TestShapeInputService4TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService4TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService4TestCaseOperation1 for usage and error information. -func (c *InputService4ProtocolTest) InputService4TestCaseOperation1(input *InputService4TestShapeInputService4TestCaseOperation2Input) (*InputService4TestShapeInputService4TestCaseOperation1Output, error) { - req, out := c.InputService4TestCaseOperation1Request(input) - return out, req.Send() -} - -// InputService4TestCaseOperation1WithContext is the same as InputService4TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService4TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService4ProtocolTest) InputService4TestCaseOperation1WithContext(ctx aws.Context, input *InputService4TestShapeInputService4TestCaseOperation2Input, opts ...request.Option) (*InputService4TestShapeInputService4TestCaseOperation1Output, error) { - req, out := c.InputService4TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opInputService4TestCaseOperation2 = "OperationName" - -// InputService4TestCaseOperation2Request generates a "aws/request.Request" representing the -// client's request for the InputService4TestCaseOperation2 operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService4TestCaseOperation2 for more information on using the InputService4TestCaseOperation2 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService4TestCaseOperation2Request method. -// req, resp := client.InputService4TestCaseOperation2Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService4ProtocolTest) InputService4TestCaseOperation2Request(input *InputService4TestShapeInputService4TestCaseOperation2Input) (req *request.Request, output *InputService4TestShapeInputService4TestCaseOperation2Output) { - op := &request.Operation{ - Name: opInputService4TestCaseOperation2, - HTTPPath: "/", - } - - if input == nil { - input = &InputService4TestShapeInputService4TestCaseOperation2Input{} - } - - output = &InputService4TestShapeInputService4TestCaseOperation2Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService4TestCaseOperation2 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService4TestCaseOperation2 for usage and error information. -func (c *InputService4ProtocolTest) InputService4TestCaseOperation2(input *InputService4TestShapeInputService4TestCaseOperation2Input) (*InputService4TestShapeInputService4TestCaseOperation2Output, error) { - req, out := c.InputService4TestCaseOperation2Request(input) - return out, req.Send() -} - -// InputService4TestCaseOperation2WithContext is the same as InputService4TestCaseOperation2 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService4TestCaseOperation2 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService4ProtocolTest) InputService4TestCaseOperation2WithContext(ctx aws.Context, input *InputService4TestShapeInputService4TestCaseOperation2Input, opts ...request.Option) (*InputService4TestShapeInputService4TestCaseOperation2Output, error) { - req, out := c.InputService4TestCaseOperation2Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type InputService4TestShapeInputService4TestCaseOperation1Output struct { - _ struct{} `type:"structure"` -} - -type InputService4TestShapeInputService4TestCaseOperation2Input struct { - _ struct{} `type:"structure"` - - ListArg []*string `type:"list" flattened:"true"` - - NamedListArg []*string `locationNameList:"Foo" type:"list" flattened:"true"` - - ScalarArg *string `type:"string"` -} - -// SetListArg sets the ListArg field's value. -func (s *InputService4TestShapeInputService4TestCaseOperation2Input) SetListArg(v []*string) *InputService4TestShapeInputService4TestCaseOperation2Input { - s.ListArg = v - return s -} - -// SetNamedListArg sets the NamedListArg field's value. -func (s *InputService4TestShapeInputService4TestCaseOperation2Input) SetNamedListArg(v []*string) *InputService4TestShapeInputService4TestCaseOperation2Input { - s.NamedListArg = v - return s -} - -// SetScalarArg sets the ScalarArg field's value. -func (s *InputService4TestShapeInputService4TestCaseOperation2Input) SetScalarArg(v string) *InputService4TestShapeInputService4TestCaseOperation2Input { - s.ScalarArg = &v - return s -} - -type InputService4TestShapeInputService4TestCaseOperation2Output struct { - _ struct{} `type:"structure"` -} - -// InputService5ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// InputService5ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type InputService5ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the InputService5ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a InputService5ProtocolTest client from just a session. -// svc := inputservice5protocoltest.New(mySession) -// -// // Create a InputService5ProtocolTest client with additional configuration -// svc := inputservice5protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewInputService5ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService5ProtocolTest { - c := p.ClientConfig("inputservice5protocoltest", cfgs...) - return newInputService5ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newInputService5ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *InputService5ProtocolTest { - svc := &InputService5ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "inputservice5protocoltest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "2014-01-01", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a InputService5ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService5ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opInputService5TestCaseOperation1 = "OperationName" - -// InputService5TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the InputService5TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService5TestCaseOperation1 for more information on using the InputService5TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService5TestCaseOperation1Request method. -// req, resp := client.InputService5TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService5ProtocolTest) InputService5TestCaseOperation1Request(input *InputService5TestShapeInputService5TestCaseOperation1Input) (req *request.Request, output *InputService5TestShapeInputService5TestCaseOperation1Output) { - op := &request.Operation{ - Name: opInputService5TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &InputService5TestShapeInputService5TestCaseOperation1Input{} - } - - output = &InputService5TestShapeInputService5TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService5TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService5TestCaseOperation1 for usage and error information. -func (c *InputService5ProtocolTest) InputService5TestCaseOperation1(input *InputService5TestShapeInputService5TestCaseOperation1Input) (*InputService5TestShapeInputService5TestCaseOperation1Output, error) { - req, out := c.InputService5TestCaseOperation1Request(input) - return out, req.Send() -} - -// InputService5TestCaseOperation1WithContext is the same as InputService5TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService5TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService5ProtocolTest) InputService5TestCaseOperation1WithContext(ctx aws.Context, input *InputService5TestShapeInputService5TestCaseOperation1Input, opts ...request.Option) (*InputService5TestShapeInputService5TestCaseOperation1Output, error) { - req, out := c.InputService5TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type InputService5TestShapeInputService5TestCaseOperation1Input struct { - _ struct{} `type:"structure"` - - MapArg map[string]*string `type:"map" flattened:"true"` -} - -// SetMapArg sets the MapArg field's value. -func (s *InputService5TestShapeInputService5TestCaseOperation1Input) SetMapArg(v map[string]*string) *InputService5TestShapeInputService5TestCaseOperation1Input { - s.MapArg = v - return s -} - -type InputService5TestShapeInputService5TestCaseOperation1Output struct { - _ struct{} `type:"structure"` -} - -// InputService6ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// InputService6ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type InputService6ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the InputService6ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a InputService6ProtocolTest client from just a session. -// svc := inputservice6protocoltest.New(mySession) -// -// // Create a InputService6ProtocolTest client with additional configuration -// svc := inputservice6protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewInputService6ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService6ProtocolTest { - c := p.ClientConfig("inputservice6protocoltest", cfgs...) - return newInputService6ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newInputService6ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *InputService6ProtocolTest { - svc := &InputService6ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "inputservice6protocoltest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "2014-01-01", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a InputService6ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService6ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opInputService6TestCaseOperation1 = "OperationName" - -// InputService6TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the InputService6TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService6TestCaseOperation1 for more information on using the InputService6TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService6TestCaseOperation1Request method. -// req, resp := client.InputService6TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService6ProtocolTest) InputService6TestCaseOperation1Request(input *InputService6TestShapeInputService6TestCaseOperation1Input) (req *request.Request, output *InputService6TestShapeInputService6TestCaseOperation1Output) { - op := &request.Operation{ - Name: opInputService6TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &InputService6TestShapeInputService6TestCaseOperation1Input{} - } - - output = &InputService6TestShapeInputService6TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService6TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService6TestCaseOperation1 for usage and error information. -func (c *InputService6ProtocolTest) InputService6TestCaseOperation1(input *InputService6TestShapeInputService6TestCaseOperation1Input) (*InputService6TestShapeInputService6TestCaseOperation1Output, error) { - req, out := c.InputService6TestCaseOperation1Request(input) - return out, req.Send() -} - -// InputService6TestCaseOperation1WithContext is the same as InputService6TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService6TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService6ProtocolTest) InputService6TestCaseOperation1WithContext(ctx aws.Context, input *InputService6TestShapeInputService6TestCaseOperation1Input, opts ...request.Option) (*InputService6TestShapeInputService6TestCaseOperation1Output, error) { - req, out := c.InputService6TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type InputService6TestShapeInputService6TestCaseOperation1Input struct { - _ struct{} `type:"structure"` - - ListArg []*string `locationNameList:"item" type:"list"` -} - -// SetListArg sets the ListArg field's value. -func (s *InputService6TestShapeInputService6TestCaseOperation1Input) SetListArg(v []*string) *InputService6TestShapeInputService6TestCaseOperation1Input { - s.ListArg = v - return s -} - -type InputService6TestShapeInputService6TestCaseOperation1Output struct { - _ struct{} `type:"structure"` -} - -// InputService7ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// InputService7ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type InputService7ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the InputService7ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a InputService7ProtocolTest client from just a session. -// svc := inputservice7protocoltest.New(mySession) -// -// // Create a InputService7ProtocolTest client with additional configuration -// svc := inputservice7protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewInputService7ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService7ProtocolTest { - c := p.ClientConfig("inputservice7protocoltest", cfgs...) - return newInputService7ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newInputService7ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *InputService7ProtocolTest { - svc := &InputService7ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "inputservice7protocoltest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "2014-01-01", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a InputService7ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService7ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opInputService7TestCaseOperation1 = "OperationName" - -// InputService7TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the InputService7TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService7TestCaseOperation1 for more information on using the InputService7TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService7TestCaseOperation1Request method. -// req, resp := client.InputService7TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService7ProtocolTest) InputService7TestCaseOperation1Request(input *InputService7TestShapeInputService7TestCaseOperation1Input) (req *request.Request, output *InputService7TestShapeInputService7TestCaseOperation1Output) { - op := &request.Operation{ - Name: opInputService7TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &InputService7TestShapeInputService7TestCaseOperation1Input{} - } - - output = &InputService7TestShapeInputService7TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService7TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService7TestCaseOperation1 for usage and error information. -func (c *InputService7ProtocolTest) InputService7TestCaseOperation1(input *InputService7TestShapeInputService7TestCaseOperation1Input) (*InputService7TestShapeInputService7TestCaseOperation1Output, error) { - req, out := c.InputService7TestCaseOperation1Request(input) - return out, req.Send() -} - -// InputService7TestCaseOperation1WithContext is the same as InputService7TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService7TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService7ProtocolTest) InputService7TestCaseOperation1WithContext(ctx aws.Context, input *InputService7TestShapeInputService7TestCaseOperation1Input, opts ...request.Option) (*InputService7TestShapeInputService7TestCaseOperation1Output, error) { - req, out := c.InputService7TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type InputService7TestShapeInputService7TestCaseOperation1Input struct { - _ struct{} `type:"structure"` - - ListArg []*string `locationNameList:"ListArgLocation" type:"list" flattened:"true"` - - ScalarArg *string `type:"string"` -} - -// SetListArg sets the ListArg field's value. -func (s *InputService7TestShapeInputService7TestCaseOperation1Input) SetListArg(v []*string) *InputService7TestShapeInputService7TestCaseOperation1Input { - s.ListArg = v - return s -} - -// SetScalarArg sets the ScalarArg field's value. -func (s *InputService7TestShapeInputService7TestCaseOperation1Input) SetScalarArg(v string) *InputService7TestShapeInputService7TestCaseOperation1Input { - s.ScalarArg = &v - return s -} - -type InputService7TestShapeInputService7TestCaseOperation1Output struct { - _ struct{} `type:"structure"` -} - -// InputService8ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// InputService8ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type InputService8ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the InputService8ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a InputService8ProtocolTest client from just a session. -// svc := inputservice8protocoltest.New(mySession) -// -// // Create a InputService8ProtocolTest client with additional configuration -// svc := inputservice8protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewInputService8ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService8ProtocolTest { - c := p.ClientConfig("inputservice8protocoltest", cfgs...) - return newInputService8ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newInputService8ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *InputService8ProtocolTest { - svc := &InputService8ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "inputservice8protocoltest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "2014-01-01", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a InputService8ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService8ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opInputService8TestCaseOperation1 = "OperationName" - -// InputService8TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the InputService8TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService8TestCaseOperation1 for more information on using the InputService8TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService8TestCaseOperation1Request method. -// req, resp := client.InputService8TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService8ProtocolTest) InputService8TestCaseOperation1Request(input *InputService8TestShapeInputService8TestCaseOperation1Input) (req *request.Request, output *InputService8TestShapeInputService8TestCaseOperation1Output) { - op := &request.Operation{ - Name: opInputService8TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &InputService8TestShapeInputService8TestCaseOperation1Input{} - } - - output = &InputService8TestShapeInputService8TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService8TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService8TestCaseOperation1 for usage and error information. -func (c *InputService8ProtocolTest) InputService8TestCaseOperation1(input *InputService8TestShapeInputService8TestCaseOperation1Input) (*InputService8TestShapeInputService8TestCaseOperation1Output, error) { - req, out := c.InputService8TestCaseOperation1Request(input) - return out, req.Send() -} - -// InputService8TestCaseOperation1WithContext is the same as InputService8TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService8TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService8ProtocolTest) InputService8TestCaseOperation1WithContext(ctx aws.Context, input *InputService8TestShapeInputService8TestCaseOperation1Input, opts ...request.Option) (*InputService8TestShapeInputService8TestCaseOperation1Output, error) { - req, out := c.InputService8TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type InputService8TestShapeInputService8TestCaseOperation1Input struct { - _ struct{} `type:"structure"` - - MapArg map[string]*string `type:"map"` -} - -// SetMapArg sets the MapArg field's value. -func (s *InputService8TestShapeInputService8TestCaseOperation1Input) SetMapArg(v map[string]*string) *InputService8TestShapeInputService8TestCaseOperation1Input { - s.MapArg = v - return s -} - -type InputService8TestShapeInputService8TestCaseOperation1Output struct { - _ struct{} `type:"structure"` -} - -// InputService9ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// InputService9ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type InputService9ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the InputService9ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a InputService9ProtocolTest client from just a session. -// svc := inputservice9protocoltest.New(mySession) -// -// // Create a InputService9ProtocolTest client with additional configuration -// svc := inputservice9protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewInputService9ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService9ProtocolTest { - c := p.ClientConfig("inputservice9protocoltest", cfgs...) - return newInputService9ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newInputService9ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *InputService9ProtocolTest { - svc := &InputService9ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "inputservice9protocoltest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "2014-01-01", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a InputService9ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService9ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opInputService9TestCaseOperation1 = "OperationName" - -// InputService9TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the InputService9TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService9TestCaseOperation1 for more information on using the InputService9TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService9TestCaseOperation1Request method. -// req, resp := client.InputService9TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService9ProtocolTest) InputService9TestCaseOperation1Request(input *InputService9TestShapeInputService9TestCaseOperation1Input) (req *request.Request, output *InputService9TestShapeInputService9TestCaseOperation1Output) { - op := &request.Operation{ - Name: opInputService9TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &InputService9TestShapeInputService9TestCaseOperation1Input{} - } - - output = &InputService9TestShapeInputService9TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService9TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService9TestCaseOperation1 for usage and error information. -func (c *InputService9ProtocolTest) InputService9TestCaseOperation1(input *InputService9TestShapeInputService9TestCaseOperation1Input) (*InputService9TestShapeInputService9TestCaseOperation1Output, error) { - req, out := c.InputService9TestCaseOperation1Request(input) - return out, req.Send() -} - -// InputService9TestCaseOperation1WithContext is the same as InputService9TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService9TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService9ProtocolTest) InputService9TestCaseOperation1WithContext(ctx aws.Context, input *InputService9TestShapeInputService9TestCaseOperation1Input, opts ...request.Option) (*InputService9TestShapeInputService9TestCaseOperation1Output, error) { - req, out := c.InputService9TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type InputService9TestShapeInputService9TestCaseOperation1Input struct { - _ struct{} `type:"structure"` - - MapArg map[string]*string `locationNameKey:"TheKey" locationNameValue:"TheValue" type:"map"` -} - -// SetMapArg sets the MapArg field's value. -func (s *InputService9TestShapeInputService9TestCaseOperation1Input) SetMapArg(v map[string]*string) *InputService9TestShapeInputService9TestCaseOperation1Input { - s.MapArg = v - return s -} - -type InputService9TestShapeInputService9TestCaseOperation1Output struct { - _ struct{} `type:"structure"` -} - -// InputService10ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// InputService10ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type InputService10ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the InputService10ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a InputService10ProtocolTest client from just a session. -// svc := inputservice10protocoltest.New(mySession) -// -// // Create a InputService10ProtocolTest client with additional configuration -// svc := inputservice10protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewInputService10ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService10ProtocolTest { - c := p.ClientConfig("inputservice10protocoltest", cfgs...) - return newInputService10ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newInputService10ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *InputService10ProtocolTest { - svc := &InputService10ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "inputservice10protocoltest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "2014-01-01", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a InputService10ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService10ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opInputService10TestCaseOperation1 = "OperationName" - -// InputService10TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the InputService10TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService10TestCaseOperation1 for more information on using the InputService10TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService10TestCaseOperation1Request method. -// req, resp := client.InputService10TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService10ProtocolTest) InputService10TestCaseOperation1Request(input *InputService10TestShapeInputService10TestCaseOperation1Input) (req *request.Request, output *InputService10TestShapeInputService10TestCaseOperation1Output) { - op := &request.Operation{ - Name: opInputService10TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &InputService10TestShapeInputService10TestCaseOperation1Input{} - } - - output = &InputService10TestShapeInputService10TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService10TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService10TestCaseOperation1 for usage and error information. -func (c *InputService10ProtocolTest) InputService10TestCaseOperation1(input *InputService10TestShapeInputService10TestCaseOperation1Input) (*InputService10TestShapeInputService10TestCaseOperation1Output, error) { - req, out := c.InputService10TestCaseOperation1Request(input) - return out, req.Send() -} - -// InputService10TestCaseOperation1WithContext is the same as InputService10TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService10TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService10ProtocolTest) InputService10TestCaseOperation1WithContext(ctx aws.Context, input *InputService10TestShapeInputService10TestCaseOperation1Input, opts ...request.Option) (*InputService10TestShapeInputService10TestCaseOperation1Output, error) { - req, out := c.InputService10TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type InputService10TestShapeInputService10TestCaseOperation1Input struct { - _ struct{} `type:"structure"` - - // BlobArg is automatically base64 encoded/decoded by the SDK. - BlobArg []byte `type:"blob"` -} - -// SetBlobArg sets the BlobArg field's value. -func (s *InputService10TestShapeInputService10TestCaseOperation1Input) SetBlobArg(v []byte) *InputService10TestShapeInputService10TestCaseOperation1Input { - s.BlobArg = v - return s -} - -type InputService10TestShapeInputService10TestCaseOperation1Output struct { - _ struct{} `type:"structure"` -} - -// InputService11ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// InputService11ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type InputService11ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the InputService11ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a InputService11ProtocolTest client from just a session. -// svc := inputservice11protocoltest.New(mySession) -// -// // Create a InputService11ProtocolTest client with additional configuration -// svc := inputservice11protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewInputService11ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService11ProtocolTest { - c := p.ClientConfig("inputservice11protocoltest", cfgs...) - return newInputService11ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newInputService11ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *InputService11ProtocolTest { - svc := &InputService11ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "inputservice11protocoltest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "2014-01-01", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a InputService11ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService11ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opInputService11TestCaseOperation1 = "OperationName" - -// InputService11TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the InputService11TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService11TestCaseOperation1 for more information on using the InputService11TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService11TestCaseOperation1Request method. -// req, resp := client.InputService11TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService11ProtocolTest) InputService11TestCaseOperation1Request(input *InputService11TestShapeInputService11TestCaseOperation1Input) (req *request.Request, output *InputService11TestShapeInputService11TestCaseOperation1Output) { - op := &request.Operation{ - Name: opInputService11TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &InputService11TestShapeInputService11TestCaseOperation1Input{} - } - - output = &InputService11TestShapeInputService11TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService11TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService11TestCaseOperation1 for usage and error information. -func (c *InputService11ProtocolTest) InputService11TestCaseOperation1(input *InputService11TestShapeInputService11TestCaseOperation1Input) (*InputService11TestShapeInputService11TestCaseOperation1Output, error) { - req, out := c.InputService11TestCaseOperation1Request(input) - return out, req.Send() -} - -// InputService11TestCaseOperation1WithContext is the same as InputService11TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService11TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService11ProtocolTest) InputService11TestCaseOperation1WithContext(ctx aws.Context, input *InputService11TestShapeInputService11TestCaseOperation1Input, opts ...request.Option) (*InputService11TestShapeInputService11TestCaseOperation1Output, error) { - req, out := c.InputService11TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type InputService11TestShapeInputService11TestCaseOperation1Input struct { - _ struct{} `type:"structure"` - - BlobArgs [][]byte `type:"list" flattened:"true"` -} - -// SetBlobArgs sets the BlobArgs field's value. -func (s *InputService11TestShapeInputService11TestCaseOperation1Input) SetBlobArgs(v [][]byte) *InputService11TestShapeInputService11TestCaseOperation1Input { - s.BlobArgs = v - return s -} - -type InputService11TestShapeInputService11TestCaseOperation1Output struct { - _ struct{} `type:"structure"` -} - -// InputService12ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// InputService12ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type InputService12ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the InputService12ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a InputService12ProtocolTest client from just a session. -// svc := inputservice12protocoltest.New(mySession) -// -// // Create a InputService12ProtocolTest client with additional configuration -// svc := inputservice12protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewInputService12ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService12ProtocolTest { - c := p.ClientConfig("inputservice12protocoltest", cfgs...) - return newInputService12ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newInputService12ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *InputService12ProtocolTest { - svc := &InputService12ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "inputservice12protocoltest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "2014-01-01", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a InputService12ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService12ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opInputService12TestCaseOperation1 = "OperationName" - -// InputService12TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the InputService12TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService12TestCaseOperation1 for more information on using the InputService12TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService12TestCaseOperation1Request method. -// req, resp := client.InputService12TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService12ProtocolTest) InputService12TestCaseOperation1Request(input *InputService12TestShapeInputService12TestCaseOperation1Input) (req *request.Request, output *InputService12TestShapeInputService12TestCaseOperation1Output) { - op := &request.Operation{ - Name: opInputService12TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &InputService12TestShapeInputService12TestCaseOperation1Input{} - } - - output = &InputService12TestShapeInputService12TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService12TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService12TestCaseOperation1 for usage and error information. -func (c *InputService12ProtocolTest) InputService12TestCaseOperation1(input *InputService12TestShapeInputService12TestCaseOperation1Input) (*InputService12TestShapeInputService12TestCaseOperation1Output, error) { - req, out := c.InputService12TestCaseOperation1Request(input) - return out, req.Send() -} - -// InputService12TestCaseOperation1WithContext is the same as InputService12TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService12TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService12ProtocolTest) InputService12TestCaseOperation1WithContext(ctx aws.Context, input *InputService12TestShapeInputService12TestCaseOperation1Input, opts ...request.Option) (*InputService12TestShapeInputService12TestCaseOperation1Output, error) { - req, out := c.InputService12TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type InputService12TestShapeInputService12TestCaseOperation1Input struct { - _ struct{} `type:"structure"` - - TimeArg *time.Time `type:"timestamp" timestampFormat:"iso8601"` -} - -// SetTimeArg sets the TimeArg field's value. -func (s *InputService12TestShapeInputService12TestCaseOperation1Input) SetTimeArg(v time.Time) *InputService12TestShapeInputService12TestCaseOperation1Input { - s.TimeArg = &v - return s -} - -type InputService12TestShapeInputService12TestCaseOperation1Output struct { - _ struct{} `type:"structure"` -} - -// InputService13ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// InputService13ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type InputService13ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the InputService13ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a InputService13ProtocolTest client from just a session. -// svc := inputservice13protocoltest.New(mySession) -// -// // Create a InputService13ProtocolTest client with additional configuration -// svc := inputservice13protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewInputService13ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService13ProtocolTest { - c := p.ClientConfig("inputservice13protocoltest", cfgs...) - return newInputService13ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newInputService13ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *InputService13ProtocolTest { - svc := &InputService13ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "inputservice13protocoltest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "2014-01-01", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a InputService13ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService13ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opInputService13TestCaseOperation1 = "OperationName" - -// InputService13TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the InputService13TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService13TestCaseOperation1 for more information on using the InputService13TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService13TestCaseOperation1Request method. -// req, resp := client.InputService13TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService13ProtocolTest) InputService13TestCaseOperation1Request(input *InputService13TestShapeInputService13TestCaseOperation6Input) (req *request.Request, output *InputService13TestShapeInputService13TestCaseOperation1Output) { - op := &request.Operation{ - Name: opInputService13TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &InputService13TestShapeInputService13TestCaseOperation6Input{} - } - - output = &InputService13TestShapeInputService13TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService13TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService13TestCaseOperation1 for usage and error information. -func (c *InputService13ProtocolTest) InputService13TestCaseOperation1(input *InputService13TestShapeInputService13TestCaseOperation6Input) (*InputService13TestShapeInputService13TestCaseOperation1Output, error) { - req, out := c.InputService13TestCaseOperation1Request(input) - return out, req.Send() -} - -// InputService13TestCaseOperation1WithContext is the same as InputService13TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService13TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService13ProtocolTest) InputService13TestCaseOperation1WithContext(ctx aws.Context, input *InputService13TestShapeInputService13TestCaseOperation6Input, opts ...request.Option) (*InputService13TestShapeInputService13TestCaseOperation1Output, error) { - req, out := c.InputService13TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opInputService13TestCaseOperation2 = "OperationName" - -// InputService13TestCaseOperation2Request generates a "aws/request.Request" representing the -// client's request for the InputService13TestCaseOperation2 operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService13TestCaseOperation2 for more information on using the InputService13TestCaseOperation2 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService13TestCaseOperation2Request method. -// req, resp := client.InputService13TestCaseOperation2Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService13ProtocolTest) InputService13TestCaseOperation2Request(input *InputService13TestShapeInputService13TestCaseOperation6Input) (req *request.Request, output *InputService13TestShapeInputService13TestCaseOperation2Output) { - op := &request.Operation{ - Name: opInputService13TestCaseOperation2, - HTTPPath: "/", - } - - if input == nil { - input = &InputService13TestShapeInputService13TestCaseOperation6Input{} - } - - output = &InputService13TestShapeInputService13TestCaseOperation2Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService13TestCaseOperation2 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService13TestCaseOperation2 for usage and error information. -func (c *InputService13ProtocolTest) InputService13TestCaseOperation2(input *InputService13TestShapeInputService13TestCaseOperation6Input) (*InputService13TestShapeInputService13TestCaseOperation2Output, error) { - req, out := c.InputService13TestCaseOperation2Request(input) - return out, req.Send() -} - -// InputService13TestCaseOperation2WithContext is the same as InputService13TestCaseOperation2 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService13TestCaseOperation2 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService13ProtocolTest) InputService13TestCaseOperation2WithContext(ctx aws.Context, input *InputService13TestShapeInputService13TestCaseOperation6Input, opts ...request.Option) (*InputService13TestShapeInputService13TestCaseOperation2Output, error) { - req, out := c.InputService13TestCaseOperation2Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opInputService13TestCaseOperation3 = "OperationName" - -// InputService13TestCaseOperation3Request generates a "aws/request.Request" representing the -// client's request for the InputService13TestCaseOperation3 operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService13TestCaseOperation3 for more information on using the InputService13TestCaseOperation3 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService13TestCaseOperation3Request method. -// req, resp := client.InputService13TestCaseOperation3Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService13ProtocolTest) InputService13TestCaseOperation3Request(input *InputService13TestShapeInputService13TestCaseOperation6Input) (req *request.Request, output *InputService13TestShapeInputService13TestCaseOperation3Output) { - op := &request.Operation{ - Name: opInputService13TestCaseOperation3, - HTTPPath: "/", - } - - if input == nil { - input = &InputService13TestShapeInputService13TestCaseOperation6Input{} - } - - output = &InputService13TestShapeInputService13TestCaseOperation3Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService13TestCaseOperation3 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService13TestCaseOperation3 for usage and error information. -func (c *InputService13ProtocolTest) InputService13TestCaseOperation3(input *InputService13TestShapeInputService13TestCaseOperation6Input) (*InputService13TestShapeInputService13TestCaseOperation3Output, error) { - req, out := c.InputService13TestCaseOperation3Request(input) - return out, req.Send() -} - -// InputService13TestCaseOperation3WithContext is the same as InputService13TestCaseOperation3 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService13TestCaseOperation3 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService13ProtocolTest) InputService13TestCaseOperation3WithContext(ctx aws.Context, input *InputService13TestShapeInputService13TestCaseOperation6Input, opts ...request.Option) (*InputService13TestShapeInputService13TestCaseOperation3Output, error) { - req, out := c.InputService13TestCaseOperation3Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opInputService13TestCaseOperation4 = "OperationName" - -// InputService13TestCaseOperation4Request generates a "aws/request.Request" representing the -// client's request for the InputService13TestCaseOperation4 operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService13TestCaseOperation4 for more information on using the InputService13TestCaseOperation4 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService13TestCaseOperation4Request method. -// req, resp := client.InputService13TestCaseOperation4Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService13ProtocolTest) InputService13TestCaseOperation4Request(input *InputService13TestShapeInputService13TestCaseOperation6Input) (req *request.Request, output *InputService13TestShapeInputService13TestCaseOperation4Output) { - op := &request.Operation{ - Name: opInputService13TestCaseOperation4, - HTTPPath: "/", - } - - if input == nil { - input = &InputService13TestShapeInputService13TestCaseOperation6Input{} - } - - output = &InputService13TestShapeInputService13TestCaseOperation4Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService13TestCaseOperation4 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService13TestCaseOperation4 for usage and error information. -func (c *InputService13ProtocolTest) InputService13TestCaseOperation4(input *InputService13TestShapeInputService13TestCaseOperation6Input) (*InputService13TestShapeInputService13TestCaseOperation4Output, error) { - req, out := c.InputService13TestCaseOperation4Request(input) - return out, req.Send() -} - -// InputService13TestCaseOperation4WithContext is the same as InputService13TestCaseOperation4 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService13TestCaseOperation4 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService13ProtocolTest) InputService13TestCaseOperation4WithContext(ctx aws.Context, input *InputService13TestShapeInputService13TestCaseOperation6Input, opts ...request.Option) (*InputService13TestShapeInputService13TestCaseOperation4Output, error) { - req, out := c.InputService13TestCaseOperation4Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opInputService13TestCaseOperation5 = "OperationName" - -// InputService13TestCaseOperation5Request generates a "aws/request.Request" representing the -// client's request for the InputService13TestCaseOperation5 operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService13TestCaseOperation5 for more information on using the InputService13TestCaseOperation5 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService13TestCaseOperation5Request method. -// req, resp := client.InputService13TestCaseOperation5Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService13ProtocolTest) InputService13TestCaseOperation5Request(input *InputService13TestShapeInputService13TestCaseOperation6Input) (req *request.Request, output *InputService13TestShapeInputService13TestCaseOperation5Output) { - op := &request.Operation{ - Name: opInputService13TestCaseOperation5, - HTTPPath: "/", - } - - if input == nil { - input = &InputService13TestShapeInputService13TestCaseOperation6Input{} - } - - output = &InputService13TestShapeInputService13TestCaseOperation5Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService13TestCaseOperation5 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService13TestCaseOperation5 for usage and error information. -func (c *InputService13ProtocolTest) InputService13TestCaseOperation5(input *InputService13TestShapeInputService13TestCaseOperation6Input) (*InputService13TestShapeInputService13TestCaseOperation5Output, error) { - req, out := c.InputService13TestCaseOperation5Request(input) - return out, req.Send() -} - -// InputService13TestCaseOperation5WithContext is the same as InputService13TestCaseOperation5 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService13TestCaseOperation5 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService13ProtocolTest) InputService13TestCaseOperation5WithContext(ctx aws.Context, input *InputService13TestShapeInputService13TestCaseOperation6Input, opts ...request.Option) (*InputService13TestShapeInputService13TestCaseOperation5Output, error) { - req, out := c.InputService13TestCaseOperation5Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opInputService13TestCaseOperation6 = "OperationName" - -// InputService13TestCaseOperation6Request generates a "aws/request.Request" representing the -// client's request for the InputService13TestCaseOperation6 operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService13TestCaseOperation6 for more information on using the InputService13TestCaseOperation6 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService13TestCaseOperation6Request method. -// req, resp := client.InputService13TestCaseOperation6Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService13ProtocolTest) InputService13TestCaseOperation6Request(input *InputService13TestShapeInputService13TestCaseOperation6Input) (req *request.Request, output *InputService13TestShapeInputService13TestCaseOperation6Output) { - op := &request.Operation{ - Name: opInputService13TestCaseOperation6, - HTTPPath: "/", - } - - if input == nil { - input = &InputService13TestShapeInputService13TestCaseOperation6Input{} - } - - output = &InputService13TestShapeInputService13TestCaseOperation6Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService13TestCaseOperation6 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService13TestCaseOperation6 for usage and error information. -func (c *InputService13ProtocolTest) InputService13TestCaseOperation6(input *InputService13TestShapeInputService13TestCaseOperation6Input) (*InputService13TestShapeInputService13TestCaseOperation6Output, error) { - req, out := c.InputService13TestCaseOperation6Request(input) - return out, req.Send() -} - -// InputService13TestCaseOperation6WithContext is the same as InputService13TestCaseOperation6 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService13TestCaseOperation6 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService13ProtocolTest) InputService13TestCaseOperation6WithContext(ctx aws.Context, input *InputService13TestShapeInputService13TestCaseOperation6Input, opts ...request.Option) (*InputService13TestShapeInputService13TestCaseOperation6Output, error) { - req, out := c.InputService13TestCaseOperation6Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type InputService13TestShapeInputService13TestCaseOperation1Output struct { - _ struct{} `type:"structure"` -} - -type InputService13TestShapeInputService13TestCaseOperation2Output struct { - _ struct{} `type:"structure"` -} - -type InputService13TestShapeInputService13TestCaseOperation3Output struct { - _ struct{} `type:"structure"` -} - -type InputService13TestShapeInputService13TestCaseOperation4Output struct { - _ struct{} `type:"structure"` -} - -type InputService13TestShapeInputService13TestCaseOperation5Output struct { - _ struct{} `type:"structure"` -} - -type InputService13TestShapeInputService13TestCaseOperation6Input struct { - _ struct{} `type:"structure"` - - RecursiveStruct *InputService13TestShapeRecursiveStructType `type:"structure"` -} - -// SetRecursiveStruct sets the RecursiveStruct field's value. -func (s *InputService13TestShapeInputService13TestCaseOperation6Input) SetRecursiveStruct(v *InputService13TestShapeRecursiveStructType) *InputService13TestShapeInputService13TestCaseOperation6Input { - s.RecursiveStruct = v - return s -} - -type InputService13TestShapeInputService13TestCaseOperation6Output struct { - _ struct{} `type:"structure"` -} - -type InputService13TestShapeRecursiveStructType struct { - _ struct{} `type:"structure"` - - NoRecurse *string `type:"string"` - - RecursiveList []*InputService13TestShapeRecursiveStructType `type:"list"` - - RecursiveMap map[string]*InputService13TestShapeRecursiveStructType `type:"map"` - - RecursiveStruct *InputService13TestShapeRecursiveStructType `type:"structure"` -} - -// SetNoRecurse sets the NoRecurse field's value. -func (s *InputService13TestShapeRecursiveStructType) SetNoRecurse(v string) *InputService13TestShapeRecursiveStructType { - s.NoRecurse = &v - return s -} - -// SetRecursiveList sets the RecursiveList field's value. -func (s *InputService13TestShapeRecursiveStructType) SetRecursiveList(v []*InputService13TestShapeRecursiveStructType) *InputService13TestShapeRecursiveStructType { - s.RecursiveList = v - return s -} - -// SetRecursiveMap sets the RecursiveMap field's value. -func (s *InputService13TestShapeRecursiveStructType) SetRecursiveMap(v map[string]*InputService13TestShapeRecursiveStructType) *InputService13TestShapeRecursiveStructType { - s.RecursiveMap = v - return s -} - -// SetRecursiveStruct sets the RecursiveStruct field's value. -func (s *InputService13TestShapeRecursiveStructType) SetRecursiveStruct(v *InputService13TestShapeRecursiveStructType) *InputService13TestShapeRecursiveStructType { - s.RecursiveStruct = v - return s -} - -// InputService14ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// InputService14ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type InputService14ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the InputService14ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a InputService14ProtocolTest client from just a session. -// svc := inputservice14protocoltest.New(mySession) -// -// // Create a InputService14ProtocolTest client with additional configuration -// svc := inputservice14protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewInputService14ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService14ProtocolTest { - c := p.ClientConfig("inputservice14protocoltest", cfgs...) - return newInputService14ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newInputService14ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *InputService14ProtocolTest { - svc := &InputService14ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "inputservice14protocoltest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "2014-01-01", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a InputService14ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService14ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opInputService14TestCaseOperation1 = "OperationName" - -// InputService14TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the InputService14TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService14TestCaseOperation1 for more information on using the InputService14TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService14TestCaseOperation1Request method. -// req, resp := client.InputService14TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService14ProtocolTest) InputService14TestCaseOperation1Request(input *InputService14TestShapeInputService14TestCaseOperation2Input) (req *request.Request, output *InputService14TestShapeInputService14TestCaseOperation1Output) { - op := &request.Operation{ - Name: opInputService14TestCaseOperation1, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &InputService14TestShapeInputService14TestCaseOperation2Input{} - } - - output = &InputService14TestShapeInputService14TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService14TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService14TestCaseOperation1 for usage and error information. -func (c *InputService14ProtocolTest) InputService14TestCaseOperation1(input *InputService14TestShapeInputService14TestCaseOperation2Input) (*InputService14TestShapeInputService14TestCaseOperation1Output, error) { - req, out := c.InputService14TestCaseOperation1Request(input) - return out, req.Send() -} - -// InputService14TestCaseOperation1WithContext is the same as InputService14TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService14TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService14ProtocolTest) InputService14TestCaseOperation1WithContext(ctx aws.Context, input *InputService14TestShapeInputService14TestCaseOperation2Input, opts ...request.Option) (*InputService14TestShapeInputService14TestCaseOperation1Output, error) { - req, out := c.InputService14TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opInputService14TestCaseOperation2 = "OperationName" - -// InputService14TestCaseOperation2Request generates a "aws/request.Request" representing the -// client's request for the InputService14TestCaseOperation2 operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService14TestCaseOperation2 for more information on using the InputService14TestCaseOperation2 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService14TestCaseOperation2Request method. -// req, resp := client.InputService14TestCaseOperation2Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService14ProtocolTest) InputService14TestCaseOperation2Request(input *InputService14TestShapeInputService14TestCaseOperation2Input) (req *request.Request, output *InputService14TestShapeInputService14TestCaseOperation2Output) { - op := &request.Operation{ - Name: opInputService14TestCaseOperation2, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &InputService14TestShapeInputService14TestCaseOperation2Input{} - } - - output = &InputService14TestShapeInputService14TestCaseOperation2Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService14TestCaseOperation2 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService14TestCaseOperation2 for usage and error information. -func (c *InputService14ProtocolTest) InputService14TestCaseOperation2(input *InputService14TestShapeInputService14TestCaseOperation2Input) (*InputService14TestShapeInputService14TestCaseOperation2Output, error) { - req, out := c.InputService14TestCaseOperation2Request(input) - return out, req.Send() -} - -// InputService14TestCaseOperation2WithContext is the same as InputService14TestCaseOperation2 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService14TestCaseOperation2 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService14ProtocolTest) InputService14TestCaseOperation2WithContext(ctx aws.Context, input *InputService14TestShapeInputService14TestCaseOperation2Input, opts ...request.Option) (*InputService14TestShapeInputService14TestCaseOperation2Output, error) { - req, out := c.InputService14TestCaseOperation2Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type InputService14TestShapeInputService14TestCaseOperation1Output struct { - _ struct{} `type:"structure"` -} - -type InputService14TestShapeInputService14TestCaseOperation2Input struct { - _ struct{} `type:"structure"` - - Token *string `type:"string" idempotencyToken:"true"` -} - -// SetToken sets the Token field's value. -func (s *InputService14TestShapeInputService14TestCaseOperation2Input) SetToken(v string) *InputService14TestShapeInputService14TestCaseOperation2Input { - s.Token = &v - return s -} - -type InputService14TestShapeInputService14TestCaseOperation2Output struct { - _ struct{} `type:"structure"` -} - -// -// Tests begin here -// - -func TestInputService1ProtocolTestScalarMembersCase1(t *testing.T) { - svc := NewInputService1ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService1TestShapeInputService1TestCaseOperation3Input{ - Bar: aws.String("val2"), - Foo: aws.String("val1"), - } - req, _ := svc.InputService1TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&Bar=val2&Foo=val1&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService1ProtocolTestScalarMembersCase2(t *testing.T) { - svc := NewInputService1ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService1TestShapeInputService1TestCaseOperation3Input{ - Baz: aws.Bool(true), - } - req, _ := svc.InputService1TestCaseOperation2Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&Baz=true&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService1ProtocolTestScalarMembersCase3(t *testing.T) { - svc := NewInputService1ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService1TestShapeInputService1TestCaseOperation3Input{ - Baz: aws.Bool(false), - } - req, _ := svc.InputService1TestCaseOperation3Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&Baz=false&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService2ProtocolTestNestedStructureMembersCase1(t *testing.T) { - svc := NewInputService2ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService2TestShapeInputService2TestCaseOperation1Input{ - StructArg: &InputService2TestShapeStructType{ - ScalarArg: aws.String("foo"), - }, - } - req, _ := svc.InputService2TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&StructArg.ScalarArg=foo&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService3ProtocolTestListTypesCase1(t *testing.T) { - svc := NewInputService3ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService3TestShapeInputService3TestCaseOperation2Input{ - ListArg: []*string{ - aws.String("foo"), - aws.String("bar"), - aws.String("baz"), - }, - } - req, _ := svc.InputService3TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&ListArg.member.1=foo&ListArg.member.2=bar&ListArg.member.3=baz&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService3ProtocolTestListTypesCase2(t *testing.T) { - svc := NewInputService3ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService3TestShapeInputService3TestCaseOperation2Input{ - ListArg: []*string{}, - } - req, _ := svc.InputService3TestCaseOperation2Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&ListArg=&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService4ProtocolTestFlattenedListCase1(t *testing.T) { - svc := NewInputService4ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService4TestShapeInputService4TestCaseOperation2Input{ - ListArg: []*string{ - aws.String("a"), - aws.String("b"), - aws.String("c"), - }, - ScalarArg: aws.String("foo"), - } - req, _ := svc.InputService4TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&ListArg.1=a&ListArg.2=b&ListArg.3=c&ScalarArg=foo&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService4ProtocolTestFlattenedListCase2(t *testing.T) { - svc := NewInputService4ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService4TestShapeInputService4TestCaseOperation2Input{ - NamedListArg: []*string{ - aws.String("a"), - }, - } - req, _ := svc.InputService4TestCaseOperation2Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&Foo.1=a&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService5ProtocolTestSerializeFlattenedMapTypeCase1(t *testing.T) { - svc := NewInputService5ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService5TestShapeInputService5TestCaseOperation1Input{ - MapArg: map[string]*string{ - "key1": aws.String("val1"), - "key2": aws.String("val2"), - }, - } - req, _ := svc.InputService5TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&MapArg.1.key=key1&MapArg.1.value=val1&MapArg.2.key=key2&MapArg.2.value=val2&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService6ProtocolTestNonFlattenedListWithLocationNameCase1(t *testing.T) { - svc := NewInputService6ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService6TestShapeInputService6TestCaseOperation1Input{ - ListArg: []*string{ - aws.String("a"), - aws.String("b"), - aws.String("c"), - }, - } - req, _ := svc.InputService6TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&ListArg.item.1=a&ListArg.item.2=b&ListArg.item.3=c&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService7ProtocolTestFlattenedListWithLocationNameCase1(t *testing.T) { - svc := NewInputService7ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService7TestShapeInputService7TestCaseOperation1Input{ - ListArg: []*string{ - aws.String("a"), - aws.String("b"), - aws.String("c"), - }, - ScalarArg: aws.String("foo"), - } - req, _ := svc.InputService7TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&ListArgLocation.1=a&ListArgLocation.2=b&ListArgLocation.3=c&ScalarArg=foo&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService8ProtocolTestSerializeMapTypeCase1(t *testing.T) { - svc := NewInputService8ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService8TestShapeInputService8TestCaseOperation1Input{ - MapArg: map[string]*string{ - "key1": aws.String("val1"), - "key2": aws.String("val2"), - }, - } - req, _ := svc.InputService8TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&MapArg.entry.1.key=key1&MapArg.entry.1.value=val1&MapArg.entry.2.key=key2&MapArg.entry.2.value=val2&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService9ProtocolTestSerializeMapTypeWithLocationNameCase1(t *testing.T) { - svc := NewInputService9ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService9TestShapeInputService9TestCaseOperation1Input{ - MapArg: map[string]*string{ - "key1": aws.String("val1"), - "key2": aws.String("val2"), - }, - } - req, _ := svc.InputService9TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&MapArg.entry.1.TheKey=key1&MapArg.entry.1.TheValue=val1&MapArg.entry.2.TheKey=key2&MapArg.entry.2.TheValue=val2&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService10ProtocolTestBase64EncodedBlobsCase1(t *testing.T) { - svc := NewInputService10ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService10TestShapeInputService10TestCaseOperation1Input{ - BlobArg: []byte("foo"), - } - req, _ := svc.InputService10TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&BlobArg=Zm9v&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService11ProtocolTestBase64EncodedBlobsNestedCase1(t *testing.T) { - svc := NewInputService11ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService11TestShapeInputService11TestCaseOperation1Input{ - BlobArgs: [][]byte{ - []byte("foo"), - }, - } - req, _ := svc.InputService11TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&BlobArgs.1=Zm9v&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService12ProtocolTestTimestampValuesCase1(t *testing.T) { - svc := NewInputService12ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService12TestShapeInputService12TestCaseOperation1Input{ - TimeArg: aws.Time(time.Unix(1422172800, 0)), - } - req, _ := svc.InputService12TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&TimeArg=2015-01-25T08%3A00%3A00Z&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService13ProtocolTestRecursiveShapesCase1(t *testing.T) { - svc := NewInputService13ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService13TestShapeInputService13TestCaseOperation6Input{ - RecursiveStruct: &InputService13TestShapeRecursiveStructType{ - NoRecurse: aws.String("foo"), - }, - } - req, _ := svc.InputService13TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&RecursiveStruct.NoRecurse=foo&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService13ProtocolTestRecursiveShapesCase2(t *testing.T) { - svc := NewInputService13ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService13TestShapeInputService13TestCaseOperation6Input{ - RecursiveStruct: &InputService13TestShapeRecursiveStructType{ - RecursiveStruct: &InputService13TestShapeRecursiveStructType{ - NoRecurse: aws.String("foo"), - }, - }, - } - req, _ := svc.InputService13TestCaseOperation2Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&RecursiveStruct.RecursiveStruct.NoRecurse=foo&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService13ProtocolTestRecursiveShapesCase3(t *testing.T) { - svc := NewInputService13ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService13TestShapeInputService13TestCaseOperation6Input{ - RecursiveStruct: &InputService13TestShapeRecursiveStructType{ - RecursiveStruct: &InputService13TestShapeRecursiveStructType{ - RecursiveStruct: &InputService13TestShapeRecursiveStructType{ - RecursiveStruct: &InputService13TestShapeRecursiveStructType{ - NoRecurse: aws.String("foo"), - }, - }, - }, - }, - } - req, _ := svc.InputService13TestCaseOperation3Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&RecursiveStruct.RecursiveStruct.RecursiveStruct.RecursiveStruct.NoRecurse=foo&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService13ProtocolTestRecursiveShapesCase4(t *testing.T) { - svc := NewInputService13ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService13TestShapeInputService13TestCaseOperation6Input{ - RecursiveStruct: &InputService13TestShapeRecursiveStructType{ - RecursiveList: []*InputService13TestShapeRecursiveStructType{ - { - NoRecurse: aws.String("foo"), - }, - { - NoRecurse: aws.String("bar"), - }, - }, - }, - } - req, _ := svc.InputService13TestCaseOperation4Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&RecursiveStruct.RecursiveList.member.1.NoRecurse=foo&RecursiveStruct.RecursiveList.member.2.NoRecurse=bar&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService13ProtocolTestRecursiveShapesCase5(t *testing.T) { - svc := NewInputService13ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService13TestShapeInputService13TestCaseOperation6Input{ - RecursiveStruct: &InputService13TestShapeRecursiveStructType{ - RecursiveList: []*InputService13TestShapeRecursiveStructType{ - { - NoRecurse: aws.String("foo"), - }, - { - RecursiveStruct: &InputService13TestShapeRecursiveStructType{ - NoRecurse: aws.String("bar"), - }, - }, - }, - }, - } - req, _ := svc.InputService13TestCaseOperation5Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&RecursiveStruct.RecursiveList.member.1.NoRecurse=foo&RecursiveStruct.RecursiveList.member.2.RecursiveStruct.NoRecurse=bar&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService13ProtocolTestRecursiveShapesCase6(t *testing.T) { - svc := NewInputService13ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService13TestShapeInputService13TestCaseOperation6Input{ - RecursiveStruct: &InputService13TestShapeRecursiveStructType{ - RecursiveMap: map[string]*InputService13TestShapeRecursiveStructType{ - "bar": { - NoRecurse: aws.String("bar"), - }, - "foo": { - NoRecurse: aws.String("foo"), - }, - }, - }, - } - req, _ := svc.InputService13TestCaseOperation6Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&RecursiveStruct.RecursiveMap.entry.1.key=foo&RecursiveStruct.RecursiveMap.entry.1.value.NoRecurse=foo&RecursiveStruct.RecursiveMap.entry.2.key=bar&RecursiveStruct.RecursiveMap.entry.2.value.NoRecurse=bar&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService14ProtocolTestIdempotencyTokenAutoFillCase1(t *testing.T) { - svc := NewInputService14ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService14TestShapeInputService14TestCaseOperation2Input{ - Token: aws.String("abc123"), - } - req, _ := svc.InputService14TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&Token=abc123&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService14ProtocolTestIdempotencyTokenAutoFillCase2(t *testing.T) { - svc := NewInputService14ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService14TestShapeInputService14TestCaseOperation2Input{} - req, _ := svc.InputService14TestCaseOperation2Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&Token=00000000-0000-4000-8000-000000000000&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/query/unmarshal_test.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/query/unmarshal_test.go deleted file mode 100644 index c13bc06e5..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/query/unmarshal_test.go +++ /dev/null @@ -1,2800 +0,0 @@ -package query_test - -import ( - "bytes" - "encoding/json" - "encoding/xml" - "fmt" - "io" - "io/ioutil" - "net/http" - "net/url" - "reflect" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/client" - "github.com/aws/aws-sdk-go/aws/client/metadata" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/aws/signer/v4" - "github.com/aws/aws-sdk-go/awstesting" - "github.com/aws/aws-sdk-go/awstesting/unit" - "github.com/aws/aws-sdk-go/private/protocol" - "github.com/aws/aws-sdk-go/private/protocol/query" - "github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil" - "github.com/aws/aws-sdk-go/private/util" -) - -var _ bytes.Buffer // always import bytes -var _ http.Request -var _ json.Marshaler -var _ time.Time -var _ xmlutil.XMLNode -var _ xml.Attr -var _ = ioutil.Discard -var _ = util.Trim("") -var _ = url.Values{} -var _ = io.EOF -var _ = aws.String -var _ = fmt.Println -var _ = reflect.Value{} - -func init() { - protocol.RandReader = &awstesting.ZeroReader{} -} - -// OutputService1ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// OutputService1ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type OutputService1ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the OutputService1ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a OutputService1ProtocolTest client from just a session. -// svc := outputservice1protocoltest.New(mySession) -// -// // Create a OutputService1ProtocolTest client with additional configuration -// svc := outputservice1protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewOutputService1ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService1ProtocolTest { - c := p.ClientConfig("outputservice1protocoltest", cfgs...) - return newOutputService1ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newOutputService1ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *OutputService1ProtocolTest { - svc := &OutputService1ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "outputservice1protocoltest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a OutputService1ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService1ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService1TestCaseOperation1 = "OperationName" - -// OutputService1TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the OutputService1TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See OutputService1TestCaseOperation1 for more information on using the OutputService1TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the OutputService1TestCaseOperation1Request method. -// req, resp := client.OutputService1TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *OutputService1ProtocolTest) OutputService1TestCaseOperation1Request(input *OutputService1TestShapeOutputService1TestCaseOperation1Input) (req *request.Request, output *OutputService1TestShapeOutputService1TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService1TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &OutputService1TestShapeOutputService1TestCaseOperation1Input{} - } - - output = &OutputService1TestShapeOutputService1TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - return -} - -// OutputService1TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation OutputService1TestCaseOperation1 for usage and error information. -func (c *OutputService1ProtocolTest) OutputService1TestCaseOperation1(input *OutputService1TestShapeOutputService1TestCaseOperation1Input) (*OutputService1TestShapeOutputService1TestCaseOperation1Output, error) { - req, out := c.OutputService1TestCaseOperation1Request(input) - return out, req.Send() -} - -// OutputService1TestCaseOperation1WithContext is the same as OutputService1TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See OutputService1TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *OutputService1ProtocolTest) OutputService1TestCaseOperation1WithContext(ctx aws.Context, input *OutputService1TestShapeOutputService1TestCaseOperation1Input, opts ...request.Option) (*OutputService1TestShapeOutputService1TestCaseOperation1Output, error) { - req, out := c.OutputService1TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type OutputService1TestShapeOutputService1TestCaseOperation1Input struct { - _ struct{} `type:"structure"` -} - -type OutputService1TestShapeOutputService1TestCaseOperation1Output struct { - _ struct{} `type:"structure"` - - Char *string `type:"character"` - - Double *float64 `type:"double"` - - FalseBool *bool `type:"boolean"` - - Float *float64 `type:"float"` - - Long *int64 `type:"long"` - - Num *int64 `locationName:"FooNum" type:"integer"` - - Str *string `type:"string"` - - Timestamp *time.Time `type:"timestamp" timestampFormat:"iso8601"` - - TrueBool *bool `type:"boolean"` -} - -// SetChar sets the Char field's value. -func (s *OutputService1TestShapeOutputService1TestCaseOperation1Output) SetChar(v string) *OutputService1TestShapeOutputService1TestCaseOperation1Output { - s.Char = &v - return s -} - -// SetDouble sets the Double field's value. -func (s *OutputService1TestShapeOutputService1TestCaseOperation1Output) SetDouble(v float64) *OutputService1TestShapeOutputService1TestCaseOperation1Output { - s.Double = &v - return s -} - -// SetFalseBool sets the FalseBool field's value. -func (s *OutputService1TestShapeOutputService1TestCaseOperation1Output) SetFalseBool(v bool) *OutputService1TestShapeOutputService1TestCaseOperation1Output { - s.FalseBool = &v - return s -} - -// SetFloat sets the Float field's value. -func (s *OutputService1TestShapeOutputService1TestCaseOperation1Output) SetFloat(v float64) *OutputService1TestShapeOutputService1TestCaseOperation1Output { - s.Float = &v - return s -} - -// SetLong sets the Long field's value. -func (s *OutputService1TestShapeOutputService1TestCaseOperation1Output) SetLong(v int64) *OutputService1TestShapeOutputService1TestCaseOperation1Output { - s.Long = &v - return s -} - -// SetNum sets the Num field's value. -func (s *OutputService1TestShapeOutputService1TestCaseOperation1Output) SetNum(v int64) *OutputService1TestShapeOutputService1TestCaseOperation1Output { - s.Num = &v - return s -} - -// SetStr sets the Str field's value. -func (s *OutputService1TestShapeOutputService1TestCaseOperation1Output) SetStr(v string) *OutputService1TestShapeOutputService1TestCaseOperation1Output { - s.Str = &v - return s -} - -// SetTimestamp sets the Timestamp field's value. -func (s *OutputService1TestShapeOutputService1TestCaseOperation1Output) SetTimestamp(v time.Time) *OutputService1TestShapeOutputService1TestCaseOperation1Output { - s.Timestamp = &v - return s -} - -// SetTrueBool sets the TrueBool field's value. -func (s *OutputService1TestShapeOutputService1TestCaseOperation1Output) SetTrueBool(v bool) *OutputService1TestShapeOutputService1TestCaseOperation1Output { - s.TrueBool = &v - return s -} - -// OutputService2ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// OutputService2ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type OutputService2ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the OutputService2ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a OutputService2ProtocolTest client from just a session. -// svc := outputservice2protocoltest.New(mySession) -// -// // Create a OutputService2ProtocolTest client with additional configuration -// svc := outputservice2protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewOutputService2ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService2ProtocolTest { - c := p.ClientConfig("outputservice2protocoltest", cfgs...) - return newOutputService2ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newOutputService2ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *OutputService2ProtocolTest { - svc := &OutputService2ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "outputservice2protocoltest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a OutputService2ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService2ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService2TestCaseOperation1 = "OperationName" - -// OutputService2TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the OutputService2TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See OutputService2TestCaseOperation1 for more information on using the OutputService2TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the OutputService2TestCaseOperation1Request method. -// req, resp := client.OutputService2TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *OutputService2ProtocolTest) OutputService2TestCaseOperation1Request(input *OutputService2TestShapeOutputService2TestCaseOperation1Input) (req *request.Request, output *OutputService2TestShapeOutputService2TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService2TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &OutputService2TestShapeOutputService2TestCaseOperation1Input{} - } - - output = &OutputService2TestShapeOutputService2TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - return -} - -// OutputService2TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation OutputService2TestCaseOperation1 for usage and error information. -func (c *OutputService2ProtocolTest) OutputService2TestCaseOperation1(input *OutputService2TestShapeOutputService2TestCaseOperation1Input) (*OutputService2TestShapeOutputService2TestCaseOperation1Output, error) { - req, out := c.OutputService2TestCaseOperation1Request(input) - return out, req.Send() -} - -// OutputService2TestCaseOperation1WithContext is the same as OutputService2TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See OutputService2TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *OutputService2ProtocolTest) OutputService2TestCaseOperation1WithContext(ctx aws.Context, input *OutputService2TestShapeOutputService2TestCaseOperation1Input, opts ...request.Option) (*OutputService2TestShapeOutputService2TestCaseOperation1Output, error) { - req, out := c.OutputService2TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type OutputService2TestShapeOutputService2TestCaseOperation1Input struct { - _ struct{} `type:"structure"` -} - -type OutputService2TestShapeOutputService2TestCaseOperation1Output struct { - _ struct{} `type:"structure"` - - Num *int64 `type:"integer"` - - Str *string `type:"string"` -} - -// SetNum sets the Num field's value. -func (s *OutputService2TestShapeOutputService2TestCaseOperation1Output) SetNum(v int64) *OutputService2TestShapeOutputService2TestCaseOperation1Output { - s.Num = &v - return s -} - -// SetStr sets the Str field's value. -func (s *OutputService2TestShapeOutputService2TestCaseOperation1Output) SetStr(v string) *OutputService2TestShapeOutputService2TestCaseOperation1Output { - s.Str = &v - return s -} - -// OutputService3ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// OutputService3ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type OutputService3ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the OutputService3ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a OutputService3ProtocolTest client from just a session. -// svc := outputservice3protocoltest.New(mySession) -// -// // Create a OutputService3ProtocolTest client with additional configuration -// svc := outputservice3protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewOutputService3ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService3ProtocolTest { - c := p.ClientConfig("outputservice3protocoltest", cfgs...) - return newOutputService3ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newOutputService3ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *OutputService3ProtocolTest { - svc := &OutputService3ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "outputservice3protocoltest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a OutputService3ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService3ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService3TestCaseOperation1 = "OperationName" - -// OutputService3TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the OutputService3TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See OutputService3TestCaseOperation1 for more information on using the OutputService3TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the OutputService3TestCaseOperation1Request method. -// req, resp := client.OutputService3TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *OutputService3ProtocolTest) OutputService3TestCaseOperation1Request(input *OutputService3TestShapeOutputService3TestCaseOperation1Input) (req *request.Request, output *OutputService3TestShapeOutputService3TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService3TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &OutputService3TestShapeOutputService3TestCaseOperation1Input{} - } - - output = &OutputService3TestShapeOutputService3TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - return -} - -// OutputService3TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation OutputService3TestCaseOperation1 for usage and error information. -func (c *OutputService3ProtocolTest) OutputService3TestCaseOperation1(input *OutputService3TestShapeOutputService3TestCaseOperation1Input) (*OutputService3TestShapeOutputService3TestCaseOperation1Output, error) { - req, out := c.OutputService3TestCaseOperation1Request(input) - return out, req.Send() -} - -// OutputService3TestCaseOperation1WithContext is the same as OutputService3TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See OutputService3TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *OutputService3ProtocolTest) OutputService3TestCaseOperation1WithContext(ctx aws.Context, input *OutputService3TestShapeOutputService3TestCaseOperation1Input, opts ...request.Option) (*OutputService3TestShapeOutputService3TestCaseOperation1Output, error) { - req, out := c.OutputService3TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type OutputService3TestShapeOutputService3TestCaseOperation1Input struct { - _ struct{} `type:"structure"` -} - -type OutputService3TestShapeOutputService3TestCaseOperation1Output struct { - _ struct{} `type:"structure"` - - // Blob is automatically base64 encoded/decoded by the SDK. - Blob []byte `type:"blob"` -} - -// SetBlob sets the Blob field's value. -func (s *OutputService3TestShapeOutputService3TestCaseOperation1Output) SetBlob(v []byte) *OutputService3TestShapeOutputService3TestCaseOperation1Output { - s.Blob = v - return s -} - -// OutputService4ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// OutputService4ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type OutputService4ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the OutputService4ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a OutputService4ProtocolTest client from just a session. -// svc := outputservice4protocoltest.New(mySession) -// -// // Create a OutputService4ProtocolTest client with additional configuration -// svc := outputservice4protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewOutputService4ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService4ProtocolTest { - c := p.ClientConfig("outputservice4protocoltest", cfgs...) - return newOutputService4ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newOutputService4ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *OutputService4ProtocolTest { - svc := &OutputService4ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "outputservice4protocoltest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a OutputService4ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService4ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService4TestCaseOperation1 = "OperationName" - -// OutputService4TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the OutputService4TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See OutputService4TestCaseOperation1 for more information on using the OutputService4TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the OutputService4TestCaseOperation1Request method. -// req, resp := client.OutputService4TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *OutputService4ProtocolTest) OutputService4TestCaseOperation1Request(input *OutputService4TestShapeOutputService4TestCaseOperation1Input) (req *request.Request, output *OutputService4TestShapeOutputService4TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService4TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &OutputService4TestShapeOutputService4TestCaseOperation1Input{} - } - - output = &OutputService4TestShapeOutputService4TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - return -} - -// OutputService4TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation OutputService4TestCaseOperation1 for usage and error information. -func (c *OutputService4ProtocolTest) OutputService4TestCaseOperation1(input *OutputService4TestShapeOutputService4TestCaseOperation1Input) (*OutputService4TestShapeOutputService4TestCaseOperation1Output, error) { - req, out := c.OutputService4TestCaseOperation1Request(input) - return out, req.Send() -} - -// OutputService4TestCaseOperation1WithContext is the same as OutputService4TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See OutputService4TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *OutputService4ProtocolTest) OutputService4TestCaseOperation1WithContext(ctx aws.Context, input *OutputService4TestShapeOutputService4TestCaseOperation1Input, opts ...request.Option) (*OutputService4TestShapeOutputService4TestCaseOperation1Output, error) { - req, out := c.OutputService4TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type OutputService4TestShapeOutputService4TestCaseOperation1Input struct { - _ struct{} `type:"structure"` -} - -type OutputService4TestShapeOutputService4TestCaseOperation1Output struct { - _ struct{} `type:"structure"` - - ListMember []*string `type:"list"` -} - -// SetListMember sets the ListMember field's value. -func (s *OutputService4TestShapeOutputService4TestCaseOperation1Output) SetListMember(v []*string) *OutputService4TestShapeOutputService4TestCaseOperation1Output { - s.ListMember = v - return s -} - -// OutputService5ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// OutputService5ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type OutputService5ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the OutputService5ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a OutputService5ProtocolTest client from just a session. -// svc := outputservice5protocoltest.New(mySession) -// -// // Create a OutputService5ProtocolTest client with additional configuration -// svc := outputservice5protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewOutputService5ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService5ProtocolTest { - c := p.ClientConfig("outputservice5protocoltest", cfgs...) - return newOutputService5ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newOutputService5ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *OutputService5ProtocolTest { - svc := &OutputService5ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "outputservice5protocoltest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a OutputService5ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService5ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService5TestCaseOperation1 = "OperationName" - -// OutputService5TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the OutputService5TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See OutputService5TestCaseOperation1 for more information on using the OutputService5TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the OutputService5TestCaseOperation1Request method. -// req, resp := client.OutputService5TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *OutputService5ProtocolTest) OutputService5TestCaseOperation1Request(input *OutputService5TestShapeOutputService5TestCaseOperation1Input) (req *request.Request, output *OutputService5TestShapeOutputService5TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService5TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &OutputService5TestShapeOutputService5TestCaseOperation1Input{} - } - - output = &OutputService5TestShapeOutputService5TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - return -} - -// OutputService5TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation OutputService5TestCaseOperation1 for usage and error information. -func (c *OutputService5ProtocolTest) OutputService5TestCaseOperation1(input *OutputService5TestShapeOutputService5TestCaseOperation1Input) (*OutputService5TestShapeOutputService5TestCaseOperation1Output, error) { - req, out := c.OutputService5TestCaseOperation1Request(input) - return out, req.Send() -} - -// OutputService5TestCaseOperation1WithContext is the same as OutputService5TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See OutputService5TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *OutputService5ProtocolTest) OutputService5TestCaseOperation1WithContext(ctx aws.Context, input *OutputService5TestShapeOutputService5TestCaseOperation1Input, opts ...request.Option) (*OutputService5TestShapeOutputService5TestCaseOperation1Output, error) { - req, out := c.OutputService5TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type OutputService5TestShapeOutputService5TestCaseOperation1Input struct { - _ struct{} `type:"structure"` -} - -type OutputService5TestShapeOutputService5TestCaseOperation1Output struct { - _ struct{} `type:"structure"` - - ListMember []*string `locationNameList:"item" type:"list"` -} - -// SetListMember sets the ListMember field's value. -func (s *OutputService5TestShapeOutputService5TestCaseOperation1Output) SetListMember(v []*string) *OutputService5TestShapeOutputService5TestCaseOperation1Output { - s.ListMember = v - return s -} - -// OutputService6ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// OutputService6ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type OutputService6ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the OutputService6ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a OutputService6ProtocolTest client from just a session. -// svc := outputservice6protocoltest.New(mySession) -// -// // Create a OutputService6ProtocolTest client with additional configuration -// svc := outputservice6protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewOutputService6ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService6ProtocolTest { - c := p.ClientConfig("outputservice6protocoltest", cfgs...) - return newOutputService6ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newOutputService6ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *OutputService6ProtocolTest { - svc := &OutputService6ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "outputservice6protocoltest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a OutputService6ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService6ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService6TestCaseOperation1 = "OperationName" - -// OutputService6TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the OutputService6TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See OutputService6TestCaseOperation1 for more information on using the OutputService6TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the OutputService6TestCaseOperation1Request method. -// req, resp := client.OutputService6TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *OutputService6ProtocolTest) OutputService6TestCaseOperation1Request(input *OutputService6TestShapeOutputService6TestCaseOperation1Input) (req *request.Request, output *OutputService6TestShapeOutputService6TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService6TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &OutputService6TestShapeOutputService6TestCaseOperation1Input{} - } - - output = &OutputService6TestShapeOutputService6TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - return -} - -// OutputService6TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation OutputService6TestCaseOperation1 for usage and error information. -func (c *OutputService6ProtocolTest) OutputService6TestCaseOperation1(input *OutputService6TestShapeOutputService6TestCaseOperation1Input) (*OutputService6TestShapeOutputService6TestCaseOperation1Output, error) { - req, out := c.OutputService6TestCaseOperation1Request(input) - return out, req.Send() -} - -// OutputService6TestCaseOperation1WithContext is the same as OutputService6TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See OutputService6TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *OutputService6ProtocolTest) OutputService6TestCaseOperation1WithContext(ctx aws.Context, input *OutputService6TestShapeOutputService6TestCaseOperation1Input, opts ...request.Option) (*OutputService6TestShapeOutputService6TestCaseOperation1Output, error) { - req, out := c.OutputService6TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type OutputService6TestShapeOutputService6TestCaseOperation1Input struct { - _ struct{} `type:"structure"` -} - -type OutputService6TestShapeOutputService6TestCaseOperation1Output struct { - _ struct{} `type:"structure"` - - ListMember []*string `type:"list" flattened:"true"` -} - -// SetListMember sets the ListMember field's value. -func (s *OutputService6TestShapeOutputService6TestCaseOperation1Output) SetListMember(v []*string) *OutputService6TestShapeOutputService6TestCaseOperation1Output { - s.ListMember = v - return s -} - -// OutputService7ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// OutputService7ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type OutputService7ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the OutputService7ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a OutputService7ProtocolTest client from just a session. -// svc := outputservice7protocoltest.New(mySession) -// -// // Create a OutputService7ProtocolTest client with additional configuration -// svc := outputservice7protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewOutputService7ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService7ProtocolTest { - c := p.ClientConfig("outputservice7protocoltest", cfgs...) - return newOutputService7ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newOutputService7ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *OutputService7ProtocolTest { - svc := &OutputService7ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "outputservice7protocoltest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a OutputService7ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService7ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService7TestCaseOperation1 = "OperationName" - -// OutputService7TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the OutputService7TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See OutputService7TestCaseOperation1 for more information on using the OutputService7TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the OutputService7TestCaseOperation1Request method. -// req, resp := client.OutputService7TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *OutputService7ProtocolTest) OutputService7TestCaseOperation1Request(input *OutputService7TestShapeOutputService7TestCaseOperation1Input) (req *request.Request, output *OutputService7TestShapeOutputService7TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService7TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &OutputService7TestShapeOutputService7TestCaseOperation1Input{} - } - - output = &OutputService7TestShapeOutputService7TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - return -} - -// OutputService7TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation OutputService7TestCaseOperation1 for usage and error information. -func (c *OutputService7ProtocolTest) OutputService7TestCaseOperation1(input *OutputService7TestShapeOutputService7TestCaseOperation1Input) (*OutputService7TestShapeOutputService7TestCaseOperation1Output, error) { - req, out := c.OutputService7TestCaseOperation1Request(input) - return out, req.Send() -} - -// OutputService7TestCaseOperation1WithContext is the same as OutputService7TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See OutputService7TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *OutputService7ProtocolTest) OutputService7TestCaseOperation1WithContext(ctx aws.Context, input *OutputService7TestShapeOutputService7TestCaseOperation1Input, opts ...request.Option) (*OutputService7TestShapeOutputService7TestCaseOperation1Output, error) { - req, out := c.OutputService7TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type OutputService7TestShapeOutputService7TestCaseOperation1Input struct { - _ struct{} `type:"structure"` -} - -type OutputService7TestShapeOutputService7TestCaseOperation1Output struct { - _ struct{} `type:"structure"` - - ListMember []*string `type:"list" flattened:"true"` -} - -// SetListMember sets the ListMember field's value. -func (s *OutputService7TestShapeOutputService7TestCaseOperation1Output) SetListMember(v []*string) *OutputService7TestShapeOutputService7TestCaseOperation1Output { - s.ListMember = v - return s -} - -// OutputService8ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// OutputService8ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type OutputService8ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the OutputService8ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a OutputService8ProtocolTest client from just a session. -// svc := outputservice8protocoltest.New(mySession) -// -// // Create a OutputService8ProtocolTest client with additional configuration -// svc := outputservice8protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewOutputService8ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService8ProtocolTest { - c := p.ClientConfig("outputservice8protocoltest", cfgs...) - return newOutputService8ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newOutputService8ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *OutputService8ProtocolTest { - svc := &OutputService8ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "outputservice8protocoltest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a OutputService8ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService8ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService8TestCaseOperation1 = "OperationName" - -// OutputService8TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the OutputService8TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See OutputService8TestCaseOperation1 for more information on using the OutputService8TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the OutputService8TestCaseOperation1Request method. -// req, resp := client.OutputService8TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *OutputService8ProtocolTest) OutputService8TestCaseOperation1Request(input *OutputService8TestShapeOutputService8TestCaseOperation1Input) (req *request.Request, output *OutputService8TestShapeOutputService8TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService8TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &OutputService8TestShapeOutputService8TestCaseOperation1Input{} - } - - output = &OutputService8TestShapeOutputService8TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - return -} - -// OutputService8TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation OutputService8TestCaseOperation1 for usage and error information. -func (c *OutputService8ProtocolTest) OutputService8TestCaseOperation1(input *OutputService8TestShapeOutputService8TestCaseOperation1Input) (*OutputService8TestShapeOutputService8TestCaseOperation1Output, error) { - req, out := c.OutputService8TestCaseOperation1Request(input) - return out, req.Send() -} - -// OutputService8TestCaseOperation1WithContext is the same as OutputService8TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See OutputService8TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *OutputService8ProtocolTest) OutputService8TestCaseOperation1WithContext(ctx aws.Context, input *OutputService8TestShapeOutputService8TestCaseOperation1Input, opts ...request.Option) (*OutputService8TestShapeOutputService8TestCaseOperation1Output, error) { - req, out := c.OutputService8TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type OutputService8TestShapeOutputService8TestCaseOperation1Input struct { - _ struct{} `type:"structure"` -} - -type OutputService8TestShapeOutputService8TestCaseOperation1Output struct { - _ struct{} `type:"structure"` - - List []*OutputService8TestShapeStructureShape `type:"list"` -} - -// SetList sets the List field's value. -func (s *OutputService8TestShapeOutputService8TestCaseOperation1Output) SetList(v []*OutputService8TestShapeStructureShape) *OutputService8TestShapeOutputService8TestCaseOperation1Output { - s.List = v - return s -} - -type OutputService8TestShapeStructureShape struct { - _ struct{} `type:"structure"` - - Bar *string `type:"string"` - - Baz *string `type:"string"` - - Foo *string `type:"string"` -} - -// SetBar sets the Bar field's value. -func (s *OutputService8TestShapeStructureShape) SetBar(v string) *OutputService8TestShapeStructureShape { - s.Bar = &v - return s -} - -// SetBaz sets the Baz field's value. -func (s *OutputService8TestShapeStructureShape) SetBaz(v string) *OutputService8TestShapeStructureShape { - s.Baz = &v - return s -} - -// SetFoo sets the Foo field's value. -func (s *OutputService8TestShapeStructureShape) SetFoo(v string) *OutputService8TestShapeStructureShape { - s.Foo = &v - return s -} - -// OutputService9ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// OutputService9ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type OutputService9ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the OutputService9ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a OutputService9ProtocolTest client from just a session. -// svc := outputservice9protocoltest.New(mySession) -// -// // Create a OutputService9ProtocolTest client with additional configuration -// svc := outputservice9protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewOutputService9ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService9ProtocolTest { - c := p.ClientConfig("outputservice9protocoltest", cfgs...) - return newOutputService9ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newOutputService9ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *OutputService9ProtocolTest { - svc := &OutputService9ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "outputservice9protocoltest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a OutputService9ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService9ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService9TestCaseOperation1 = "OperationName" - -// OutputService9TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the OutputService9TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See OutputService9TestCaseOperation1 for more information on using the OutputService9TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the OutputService9TestCaseOperation1Request method. -// req, resp := client.OutputService9TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *OutputService9ProtocolTest) OutputService9TestCaseOperation1Request(input *OutputService9TestShapeOutputService9TestCaseOperation1Input) (req *request.Request, output *OutputService9TestShapeOutputService9TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService9TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &OutputService9TestShapeOutputService9TestCaseOperation1Input{} - } - - output = &OutputService9TestShapeOutputService9TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - return -} - -// OutputService9TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation OutputService9TestCaseOperation1 for usage and error information. -func (c *OutputService9ProtocolTest) OutputService9TestCaseOperation1(input *OutputService9TestShapeOutputService9TestCaseOperation1Input) (*OutputService9TestShapeOutputService9TestCaseOperation1Output, error) { - req, out := c.OutputService9TestCaseOperation1Request(input) - return out, req.Send() -} - -// OutputService9TestCaseOperation1WithContext is the same as OutputService9TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See OutputService9TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *OutputService9ProtocolTest) OutputService9TestCaseOperation1WithContext(ctx aws.Context, input *OutputService9TestShapeOutputService9TestCaseOperation1Input, opts ...request.Option) (*OutputService9TestShapeOutputService9TestCaseOperation1Output, error) { - req, out := c.OutputService9TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type OutputService9TestShapeOutputService9TestCaseOperation1Input struct { - _ struct{} `type:"structure"` -} - -type OutputService9TestShapeOutputService9TestCaseOperation1Output struct { - _ struct{} `type:"structure"` - - List []*OutputService9TestShapeStructureShape `type:"list" flattened:"true"` -} - -// SetList sets the List field's value. -func (s *OutputService9TestShapeOutputService9TestCaseOperation1Output) SetList(v []*OutputService9TestShapeStructureShape) *OutputService9TestShapeOutputService9TestCaseOperation1Output { - s.List = v - return s -} - -type OutputService9TestShapeStructureShape struct { - _ struct{} `type:"structure"` - - Bar *string `type:"string"` - - Baz *string `type:"string"` - - Foo *string `type:"string"` -} - -// SetBar sets the Bar field's value. -func (s *OutputService9TestShapeStructureShape) SetBar(v string) *OutputService9TestShapeStructureShape { - s.Bar = &v - return s -} - -// SetBaz sets the Baz field's value. -func (s *OutputService9TestShapeStructureShape) SetBaz(v string) *OutputService9TestShapeStructureShape { - s.Baz = &v - return s -} - -// SetFoo sets the Foo field's value. -func (s *OutputService9TestShapeStructureShape) SetFoo(v string) *OutputService9TestShapeStructureShape { - s.Foo = &v - return s -} - -// OutputService10ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// OutputService10ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type OutputService10ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the OutputService10ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a OutputService10ProtocolTest client from just a session. -// svc := outputservice10protocoltest.New(mySession) -// -// // Create a OutputService10ProtocolTest client with additional configuration -// svc := outputservice10protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewOutputService10ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService10ProtocolTest { - c := p.ClientConfig("outputservice10protocoltest", cfgs...) - return newOutputService10ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newOutputService10ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *OutputService10ProtocolTest { - svc := &OutputService10ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "outputservice10protocoltest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a OutputService10ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService10ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService10TestCaseOperation1 = "OperationName" - -// OutputService10TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the OutputService10TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See OutputService10TestCaseOperation1 for more information on using the OutputService10TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the OutputService10TestCaseOperation1Request method. -// req, resp := client.OutputService10TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *OutputService10ProtocolTest) OutputService10TestCaseOperation1Request(input *OutputService10TestShapeOutputService10TestCaseOperation1Input) (req *request.Request, output *OutputService10TestShapeOutputService10TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService10TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &OutputService10TestShapeOutputService10TestCaseOperation1Input{} - } - - output = &OutputService10TestShapeOutputService10TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - return -} - -// OutputService10TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation OutputService10TestCaseOperation1 for usage and error information. -func (c *OutputService10ProtocolTest) OutputService10TestCaseOperation1(input *OutputService10TestShapeOutputService10TestCaseOperation1Input) (*OutputService10TestShapeOutputService10TestCaseOperation1Output, error) { - req, out := c.OutputService10TestCaseOperation1Request(input) - return out, req.Send() -} - -// OutputService10TestCaseOperation1WithContext is the same as OutputService10TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See OutputService10TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *OutputService10ProtocolTest) OutputService10TestCaseOperation1WithContext(ctx aws.Context, input *OutputService10TestShapeOutputService10TestCaseOperation1Input, opts ...request.Option) (*OutputService10TestShapeOutputService10TestCaseOperation1Output, error) { - req, out := c.OutputService10TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type OutputService10TestShapeOutputService10TestCaseOperation1Input struct { - _ struct{} `type:"structure"` -} - -type OutputService10TestShapeOutputService10TestCaseOperation1Output struct { - _ struct{} `type:"structure"` - - List []*string `locationNameList:"NamedList" type:"list" flattened:"true"` -} - -// SetList sets the List field's value. -func (s *OutputService10TestShapeOutputService10TestCaseOperation1Output) SetList(v []*string) *OutputService10TestShapeOutputService10TestCaseOperation1Output { - s.List = v - return s -} - -// OutputService11ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// OutputService11ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type OutputService11ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the OutputService11ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a OutputService11ProtocolTest client from just a session. -// svc := outputservice11protocoltest.New(mySession) -// -// // Create a OutputService11ProtocolTest client with additional configuration -// svc := outputservice11protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewOutputService11ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService11ProtocolTest { - c := p.ClientConfig("outputservice11protocoltest", cfgs...) - return newOutputService11ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newOutputService11ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *OutputService11ProtocolTest { - svc := &OutputService11ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "outputservice11protocoltest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a OutputService11ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService11ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService11TestCaseOperation1 = "OperationName" - -// OutputService11TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the OutputService11TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See OutputService11TestCaseOperation1 for more information on using the OutputService11TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the OutputService11TestCaseOperation1Request method. -// req, resp := client.OutputService11TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *OutputService11ProtocolTest) OutputService11TestCaseOperation1Request(input *OutputService11TestShapeOutputService11TestCaseOperation1Input) (req *request.Request, output *OutputService11TestShapeOutputService11TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService11TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &OutputService11TestShapeOutputService11TestCaseOperation1Input{} - } - - output = &OutputService11TestShapeOutputService11TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - return -} - -// OutputService11TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation OutputService11TestCaseOperation1 for usage and error information. -func (c *OutputService11ProtocolTest) OutputService11TestCaseOperation1(input *OutputService11TestShapeOutputService11TestCaseOperation1Input) (*OutputService11TestShapeOutputService11TestCaseOperation1Output, error) { - req, out := c.OutputService11TestCaseOperation1Request(input) - return out, req.Send() -} - -// OutputService11TestCaseOperation1WithContext is the same as OutputService11TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See OutputService11TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *OutputService11ProtocolTest) OutputService11TestCaseOperation1WithContext(ctx aws.Context, input *OutputService11TestShapeOutputService11TestCaseOperation1Input, opts ...request.Option) (*OutputService11TestShapeOutputService11TestCaseOperation1Output, error) { - req, out := c.OutputService11TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type OutputService11TestShapeOutputService11TestCaseOperation1Input struct { - _ struct{} `type:"structure"` -} - -type OutputService11TestShapeOutputService11TestCaseOperation1Output struct { - _ struct{} `type:"structure"` - - Map map[string]*OutputService11TestShapeStructType `type:"map"` -} - -// SetMap sets the Map field's value. -func (s *OutputService11TestShapeOutputService11TestCaseOperation1Output) SetMap(v map[string]*OutputService11TestShapeStructType) *OutputService11TestShapeOutputService11TestCaseOperation1Output { - s.Map = v - return s -} - -type OutputService11TestShapeStructType struct { - _ struct{} `type:"structure"` - - Foo *string `locationName:"foo" type:"string"` -} - -// SetFoo sets the Foo field's value. -func (s *OutputService11TestShapeStructType) SetFoo(v string) *OutputService11TestShapeStructType { - s.Foo = &v - return s -} - -// OutputService12ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// OutputService12ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type OutputService12ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the OutputService12ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a OutputService12ProtocolTest client from just a session. -// svc := outputservice12protocoltest.New(mySession) -// -// // Create a OutputService12ProtocolTest client with additional configuration -// svc := outputservice12protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewOutputService12ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService12ProtocolTest { - c := p.ClientConfig("outputservice12protocoltest", cfgs...) - return newOutputService12ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newOutputService12ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *OutputService12ProtocolTest { - svc := &OutputService12ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "outputservice12protocoltest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a OutputService12ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService12ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService12TestCaseOperation1 = "OperationName" - -// OutputService12TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the OutputService12TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See OutputService12TestCaseOperation1 for more information on using the OutputService12TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the OutputService12TestCaseOperation1Request method. -// req, resp := client.OutputService12TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *OutputService12ProtocolTest) OutputService12TestCaseOperation1Request(input *OutputService12TestShapeOutputService12TestCaseOperation1Input) (req *request.Request, output *OutputService12TestShapeOutputService12TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService12TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &OutputService12TestShapeOutputService12TestCaseOperation1Input{} - } - - output = &OutputService12TestShapeOutputService12TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - return -} - -// OutputService12TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation OutputService12TestCaseOperation1 for usage and error information. -func (c *OutputService12ProtocolTest) OutputService12TestCaseOperation1(input *OutputService12TestShapeOutputService12TestCaseOperation1Input) (*OutputService12TestShapeOutputService12TestCaseOperation1Output, error) { - req, out := c.OutputService12TestCaseOperation1Request(input) - return out, req.Send() -} - -// OutputService12TestCaseOperation1WithContext is the same as OutputService12TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See OutputService12TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *OutputService12ProtocolTest) OutputService12TestCaseOperation1WithContext(ctx aws.Context, input *OutputService12TestShapeOutputService12TestCaseOperation1Input, opts ...request.Option) (*OutputService12TestShapeOutputService12TestCaseOperation1Output, error) { - req, out := c.OutputService12TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type OutputService12TestShapeOutputService12TestCaseOperation1Input struct { - _ struct{} `type:"structure"` -} - -type OutputService12TestShapeOutputService12TestCaseOperation1Output struct { - _ struct{} `type:"structure"` - - Map map[string]*string `type:"map" flattened:"true"` -} - -// SetMap sets the Map field's value. -func (s *OutputService12TestShapeOutputService12TestCaseOperation1Output) SetMap(v map[string]*string) *OutputService12TestShapeOutputService12TestCaseOperation1Output { - s.Map = v - return s -} - -// OutputService13ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// OutputService13ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type OutputService13ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the OutputService13ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a OutputService13ProtocolTest client from just a session. -// svc := outputservice13protocoltest.New(mySession) -// -// // Create a OutputService13ProtocolTest client with additional configuration -// svc := outputservice13protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewOutputService13ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService13ProtocolTest { - c := p.ClientConfig("outputservice13protocoltest", cfgs...) - return newOutputService13ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newOutputService13ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *OutputService13ProtocolTest { - svc := &OutputService13ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "outputservice13protocoltest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a OutputService13ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService13ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService13TestCaseOperation1 = "OperationName" - -// OutputService13TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the OutputService13TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See OutputService13TestCaseOperation1 for more information on using the OutputService13TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the OutputService13TestCaseOperation1Request method. -// req, resp := client.OutputService13TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *OutputService13ProtocolTest) OutputService13TestCaseOperation1Request(input *OutputService13TestShapeOutputService13TestCaseOperation1Input) (req *request.Request, output *OutputService13TestShapeOutputService13TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService13TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &OutputService13TestShapeOutputService13TestCaseOperation1Input{} - } - - output = &OutputService13TestShapeOutputService13TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - return -} - -// OutputService13TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation OutputService13TestCaseOperation1 for usage and error information. -func (c *OutputService13ProtocolTest) OutputService13TestCaseOperation1(input *OutputService13TestShapeOutputService13TestCaseOperation1Input) (*OutputService13TestShapeOutputService13TestCaseOperation1Output, error) { - req, out := c.OutputService13TestCaseOperation1Request(input) - return out, req.Send() -} - -// OutputService13TestCaseOperation1WithContext is the same as OutputService13TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See OutputService13TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *OutputService13ProtocolTest) OutputService13TestCaseOperation1WithContext(ctx aws.Context, input *OutputService13TestShapeOutputService13TestCaseOperation1Input, opts ...request.Option) (*OutputService13TestShapeOutputService13TestCaseOperation1Output, error) { - req, out := c.OutputService13TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type OutputService13TestShapeOutputService13TestCaseOperation1Input struct { - _ struct{} `type:"structure"` -} - -type OutputService13TestShapeOutputService13TestCaseOperation1Output struct { - _ struct{} `type:"structure"` - - Map map[string]*string `locationName:"Attribute" locationNameKey:"Name" locationNameValue:"Value" type:"map" flattened:"true"` -} - -// SetMap sets the Map field's value. -func (s *OutputService13TestShapeOutputService13TestCaseOperation1Output) SetMap(v map[string]*string) *OutputService13TestShapeOutputService13TestCaseOperation1Output { - s.Map = v - return s -} - -// OutputService14ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// OutputService14ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type OutputService14ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the OutputService14ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a OutputService14ProtocolTest client from just a session. -// svc := outputservice14protocoltest.New(mySession) -// -// // Create a OutputService14ProtocolTest client with additional configuration -// svc := outputservice14protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewOutputService14ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService14ProtocolTest { - c := p.ClientConfig("outputservice14protocoltest", cfgs...) - return newOutputService14ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newOutputService14ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *OutputService14ProtocolTest { - svc := &OutputService14ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "outputservice14protocoltest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a OutputService14ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService14ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService14TestCaseOperation1 = "OperationName" - -// OutputService14TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the OutputService14TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See OutputService14TestCaseOperation1 for more information on using the OutputService14TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the OutputService14TestCaseOperation1Request method. -// req, resp := client.OutputService14TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *OutputService14ProtocolTest) OutputService14TestCaseOperation1Request(input *OutputService14TestShapeOutputService14TestCaseOperation1Input) (req *request.Request, output *OutputService14TestShapeOutputService14TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService14TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &OutputService14TestShapeOutputService14TestCaseOperation1Input{} - } - - output = &OutputService14TestShapeOutputService14TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - return -} - -// OutputService14TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation OutputService14TestCaseOperation1 for usage and error information. -func (c *OutputService14ProtocolTest) OutputService14TestCaseOperation1(input *OutputService14TestShapeOutputService14TestCaseOperation1Input) (*OutputService14TestShapeOutputService14TestCaseOperation1Output, error) { - req, out := c.OutputService14TestCaseOperation1Request(input) - return out, req.Send() -} - -// OutputService14TestCaseOperation1WithContext is the same as OutputService14TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See OutputService14TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *OutputService14ProtocolTest) OutputService14TestCaseOperation1WithContext(ctx aws.Context, input *OutputService14TestShapeOutputService14TestCaseOperation1Input, opts ...request.Option) (*OutputService14TestShapeOutputService14TestCaseOperation1Output, error) { - req, out := c.OutputService14TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type OutputService14TestShapeOutputService14TestCaseOperation1Input struct { - _ struct{} `type:"structure"` -} - -type OutputService14TestShapeOutputService14TestCaseOperation1Output struct { - _ struct{} `type:"structure"` - - Map map[string]*string `locationNameKey:"foo" locationNameValue:"bar" type:"map" flattened:"true"` -} - -// SetMap sets the Map field's value. -func (s *OutputService14TestShapeOutputService14TestCaseOperation1Output) SetMap(v map[string]*string) *OutputService14TestShapeOutputService14TestCaseOperation1Output { - s.Map = v - return s -} - -// OutputService15ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// OutputService15ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type OutputService15ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the OutputService15ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a OutputService15ProtocolTest client from just a session. -// svc := outputservice15protocoltest.New(mySession) -// -// // Create a OutputService15ProtocolTest client with additional configuration -// svc := outputservice15protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewOutputService15ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService15ProtocolTest { - c := p.ClientConfig("outputservice15protocoltest", cfgs...) - return newOutputService15ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newOutputService15ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *OutputService15ProtocolTest { - svc := &OutputService15ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "outputservice15protocoltest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a OutputService15ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService15ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService15TestCaseOperation1 = "OperationName" - -// OutputService15TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the OutputService15TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See OutputService15TestCaseOperation1 for more information on using the OutputService15TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the OutputService15TestCaseOperation1Request method. -// req, resp := client.OutputService15TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *OutputService15ProtocolTest) OutputService15TestCaseOperation1Request(input *OutputService15TestShapeOutputService15TestCaseOperation1Input) (req *request.Request, output *OutputService15TestShapeOutputService15TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService15TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &OutputService15TestShapeOutputService15TestCaseOperation1Input{} - } - - output = &OutputService15TestShapeOutputService15TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - return -} - -// OutputService15TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation OutputService15TestCaseOperation1 for usage and error information. -func (c *OutputService15ProtocolTest) OutputService15TestCaseOperation1(input *OutputService15TestShapeOutputService15TestCaseOperation1Input) (*OutputService15TestShapeOutputService15TestCaseOperation1Output, error) { - req, out := c.OutputService15TestCaseOperation1Request(input) - return out, req.Send() -} - -// OutputService15TestCaseOperation1WithContext is the same as OutputService15TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See OutputService15TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *OutputService15ProtocolTest) OutputService15TestCaseOperation1WithContext(ctx aws.Context, input *OutputService15TestShapeOutputService15TestCaseOperation1Input, opts ...request.Option) (*OutputService15TestShapeOutputService15TestCaseOperation1Output, error) { - req, out := c.OutputService15TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type OutputService15TestShapeOutputService15TestCaseOperation1Input struct { - _ struct{} `type:"structure"` -} - -type OutputService15TestShapeOutputService15TestCaseOperation1Output struct { - _ struct{} `type:"structure"` - - Foo *string `type:"string"` -} - -// SetFoo sets the Foo field's value. -func (s *OutputService15TestShapeOutputService15TestCaseOperation1Output) SetFoo(v string) *OutputService15TestShapeOutputService15TestCaseOperation1Output { - s.Foo = &v - return s -} - -// -// Tests begin here -// - -func TestOutputService1ProtocolTestScalarMembersCase1(t *testing.T) { - svc := NewOutputService1ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - - buf := bytes.NewReader([]byte("myname123falsetrue1.21.3200a2015-01-25T08:00:00Zrequest-id")) - req, out := svc.OutputService1TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - query.UnmarshalMeta(req) - query.Unmarshal(req) - if req.Error != nil { - t.Errorf("expect not error, got %v", req.Error) - } - - // assert response - if out == nil { - t.Errorf("expect not to be nil") - } - if e, a := "a", *out.Char; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := 1.3, *out.Double; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := false, *out.FalseBool; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := 1.2, *out.Float; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := int64(200), *out.Long; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := int64(123), *out.Num; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "myname", *out.Str; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := time.Unix(1.4221728e+09, 0).UTC().String(), out.Timestamp.String(); e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := true, *out.TrueBool; e != a { - t.Errorf("expect %v, got %v", e, a) - } - -} - -func TestOutputService2ProtocolTestNotAllMembersInResponseCase1(t *testing.T) { - svc := NewOutputService2ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - - buf := bytes.NewReader([]byte("mynamerequest-id")) - req, out := svc.OutputService2TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - query.UnmarshalMeta(req) - query.Unmarshal(req) - if req.Error != nil { - t.Errorf("expect not error, got %v", req.Error) - } - - // assert response - if out == nil { - t.Errorf("expect not to be nil") - } - if e, a := "myname", *out.Str; e != a { - t.Errorf("expect %v, got %v", e, a) - } - -} - -func TestOutputService3ProtocolTestBlobCase1(t *testing.T) { - svc := NewOutputService3ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - - buf := bytes.NewReader([]byte("dmFsdWU=requestid")) - req, out := svc.OutputService3TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - query.UnmarshalMeta(req) - query.Unmarshal(req) - if req.Error != nil { - t.Errorf("expect not error, got %v", req.Error) - } - - // assert response - if out == nil { - t.Errorf("expect not to be nil") - } - if e, a := "value", string(out.Blob); e != a { - t.Errorf("expect %v, got %v", e, a) - } - -} - -func TestOutputService4ProtocolTestListsCase1(t *testing.T) { - svc := NewOutputService4ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - - buf := bytes.NewReader([]byte("abc123requestid")) - req, out := svc.OutputService4TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - query.UnmarshalMeta(req) - query.Unmarshal(req) - if req.Error != nil { - t.Errorf("expect not error, got %v", req.Error) - } - - // assert response - if out == nil { - t.Errorf("expect not to be nil") - } - if e, a := "abc", *out.ListMember[0]; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "123", *out.ListMember[1]; e != a { - t.Errorf("expect %v, got %v", e, a) - } - -} - -func TestOutputService5ProtocolTestListWithCustomMemberNameCase1(t *testing.T) { - svc := NewOutputService5ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - - buf := bytes.NewReader([]byte("abc123requestid")) - req, out := svc.OutputService5TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - query.UnmarshalMeta(req) - query.Unmarshal(req) - if req.Error != nil { - t.Errorf("expect not error, got %v", req.Error) - } - - // assert response - if out == nil { - t.Errorf("expect not to be nil") - } - if e, a := "abc", *out.ListMember[0]; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "123", *out.ListMember[1]; e != a { - t.Errorf("expect %v, got %v", e, a) - } - -} - -func TestOutputService6ProtocolTestFlattenedListCase1(t *testing.T) { - svc := NewOutputService6ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - - buf := bytes.NewReader([]byte("abc123requestid")) - req, out := svc.OutputService6TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - query.UnmarshalMeta(req) - query.Unmarshal(req) - if req.Error != nil { - t.Errorf("expect not error, got %v", req.Error) - } - - // assert response - if out == nil { - t.Errorf("expect not to be nil") - } - if e, a := "abc", *out.ListMember[0]; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "123", *out.ListMember[1]; e != a { - t.Errorf("expect %v, got %v", e, a) - } - -} - -func TestOutputService7ProtocolTestFlattenedSingleElementListCase1(t *testing.T) { - svc := NewOutputService7ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - - buf := bytes.NewReader([]byte("abcrequestid")) - req, out := svc.OutputService7TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - query.UnmarshalMeta(req) - query.Unmarshal(req) - if req.Error != nil { - t.Errorf("expect not error, got %v", req.Error) - } - - // assert response - if out == nil { - t.Errorf("expect not to be nil") - } - if e, a := "abc", *out.ListMember[0]; e != a { - t.Errorf("expect %v, got %v", e, a) - } - -} - -func TestOutputService8ProtocolTestListOfStructuresCase1(t *testing.T) { - svc := NewOutputService8ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - - buf := bytes.NewReader([]byte("firstfoofirstbarfirstbazsecondfoosecondbarsecondbazrequestid")) - req, out := svc.OutputService8TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - query.UnmarshalMeta(req) - query.Unmarshal(req) - if req.Error != nil { - t.Errorf("expect not error, got %v", req.Error) - } - - // assert response - if out == nil { - t.Errorf("expect not to be nil") - } - if e, a := "firstbar", *out.List[0].Bar; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "firstbaz", *out.List[0].Baz; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "firstfoo", *out.List[0].Foo; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "secondbar", *out.List[1].Bar; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "secondbaz", *out.List[1].Baz; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "secondfoo", *out.List[1].Foo; e != a { - t.Errorf("expect %v, got %v", e, a) - } - -} - -func TestOutputService9ProtocolTestFlattenedListOfStructuresCase1(t *testing.T) { - svc := NewOutputService9ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - - buf := bytes.NewReader([]byte("firstfoofirstbarfirstbazsecondfoosecondbarsecondbazrequestid")) - req, out := svc.OutputService9TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - query.UnmarshalMeta(req) - query.Unmarshal(req) - if req.Error != nil { - t.Errorf("expect not error, got %v", req.Error) - } - - // assert response - if out == nil { - t.Errorf("expect not to be nil") - } - if e, a := "firstbar", *out.List[0].Bar; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "firstbaz", *out.List[0].Baz; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "firstfoo", *out.List[0].Foo; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "secondbar", *out.List[1].Bar; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "secondbaz", *out.List[1].Baz; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "secondfoo", *out.List[1].Foo; e != a { - t.Errorf("expect %v, got %v", e, a) - } - -} - -func TestOutputService10ProtocolTestFlattenedListWithLocationNameCase1(t *testing.T) { - svc := NewOutputService10ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - - buf := bytes.NewReader([]byte("abrequestid")) - req, out := svc.OutputService10TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - query.UnmarshalMeta(req) - query.Unmarshal(req) - if req.Error != nil { - t.Errorf("expect not error, got %v", req.Error) - } - - // assert response - if out == nil { - t.Errorf("expect not to be nil") - } - if e, a := "a", *out.List[0]; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "b", *out.List[1]; e != a { - t.Errorf("expect %v, got %v", e, a) - } - -} - -func TestOutputService11ProtocolTestNormalMapCase1(t *testing.T) { - svc := NewOutputService11ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - - buf := bytes.NewReader([]byte("quxbarbazbamrequestid")) - req, out := svc.OutputService11TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - query.UnmarshalMeta(req) - query.Unmarshal(req) - if req.Error != nil { - t.Errorf("expect not error, got %v", req.Error) - } - - // assert response - if out == nil { - t.Errorf("expect not to be nil") - } - if e, a := "bam", *out.Map["baz"].Foo; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "bar", *out.Map["qux"].Foo; e != a { - t.Errorf("expect %v, got %v", e, a) - } - -} - -func TestOutputService12ProtocolTestFlattenedMapCase1(t *testing.T) { - svc := NewOutputService12ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - - buf := bytes.NewReader([]byte("quxbarbazbamrequestid")) - req, out := svc.OutputService12TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - query.UnmarshalMeta(req) - query.Unmarshal(req) - if req.Error != nil { - t.Errorf("expect not error, got %v", req.Error) - } - - // assert response - if out == nil { - t.Errorf("expect not to be nil") - } - if e, a := "bam", *out.Map["baz"]; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "bar", *out.Map["qux"]; e != a { - t.Errorf("expect %v, got %v", e, a) - } - -} - -func TestOutputService13ProtocolTestFlattenedMapInShapeDefinitionCase1(t *testing.T) { - svc := NewOutputService13ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - - buf := bytes.NewReader([]byte("quxbarrequestid")) - req, out := svc.OutputService13TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - query.UnmarshalMeta(req) - query.Unmarshal(req) - if req.Error != nil { - t.Errorf("expect not error, got %v", req.Error) - } - - // assert response - if out == nil { - t.Errorf("expect not to be nil") - } - if e, a := "bar", *out.Map["qux"]; e != a { - t.Errorf("expect %v, got %v", e, a) - } - -} - -func TestOutputService14ProtocolTestNamedMapCase1(t *testing.T) { - svc := NewOutputService14ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - - buf := bytes.NewReader([]byte("quxbarbazbamrequestid")) - req, out := svc.OutputService14TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - query.UnmarshalMeta(req) - query.Unmarshal(req) - if req.Error != nil { - t.Errorf("expect not error, got %v", req.Error) - } - - // assert response - if out == nil { - t.Errorf("expect not to be nil") - } - if e, a := "bam", *out.Map["baz"]; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "bar", *out.Map["qux"]; e != a { - t.Errorf("expect %v, got %v", e, a) - } - -} - -func TestOutputService15ProtocolTestEmptyStringCase1(t *testing.T) { - svc := NewOutputService15ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - - buf := bytes.NewReader([]byte("requestid")) - req, out := svc.OutputService15TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - query.UnmarshalMeta(req) - query.Unmarshal(req) - if req.Error != nil { - t.Errorf("expect not error, got %v", req.Error) - } - - // assert response - if out == nil { - t.Errorf("expect not to be nil") - } - if e, a := "", *out.Foo; e != a { - t.Errorf("expect %v, got %v", e, a) - } - -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/build_test.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/build_test.go deleted file mode 100644 index 9f18081a9..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/build_test.go +++ /dev/null @@ -1,63 +0,0 @@ -package rest - -import ( - "net/http" - "net/url" - "testing" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/request" -) - -func TestCleanPath(t *testing.T) { - uri := &url.URL{ - Path: "//foo//bar", - Scheme: "https", - Host: "host", - } - cleanPath(uri) - - expected := "https://host/foo/bar" - if a, e := uri.String(), expected; a != e { - t.Errorf("expect %q URI, got %q", e, a) - } -} - -func TestMarshalPath(t *testing.T) { - in := struct { - Bucket *string `location:"uri" locationName:"bucket"` - Key *string `location:"uri" locationName:"key"` - }{ - Bucket: aws.String("mybucket"), - Key: aws.String("my/cool+thing space/object世界"), - } - - expectURL := `/mybucket/my/cool+thing space/object世界` - expectEscapedURL := `/mybucket/my/cool%2Bthing%20space/object%E4%B8%96%E7%95%8C` - - req := &request.Request{ - HTTPRequest: &http.Request{ - URL: &url.URL{Scheme: "https", Host: "exmaple.com", Path: "/{bucket}/{key+}"}, - }, - Params: &in, - } - - Build(req) - - if req.Error != nil { - t.Fatalf("unexpected error, %v", req.Error) - } - - if a, e := req.HTTPRequest.URL.Path, expectURL; a != e { - t.Errorf("expect %q URI, got %q", e, a) - } - - if a, e := req.HTTPRequest.URL.RawPath, expectEscapedURL; a != e { - t.Errorf("expect %q escaped URI, got %q", e, a) - } - - if a, e := req.HTTPRequest.URL.EscapedPath(), expectEscapedURL; a != e { - t.Errorf("expect %q escaped URI, got %q", e, a) - } - -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/rest_test.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/rest_test.go deleted file mode 100644 index 46457b279..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/rest_test.go +++ /dev/null @@ -1,63 +0,0 @@ -package rest_test - -import ( - "bytes" - "io/ioutil" - "net/http" - "testing" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/client" - "github.com/aws/aws-sdk-go/aws/client/metadata" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/aws/signer/v4" - "github.com/aws/aws-sdk-go/awstesting/unit" - "github.com/aws/aws-sdk-go/private/protocol/rest" -) - -func TestUnsetHeaders(t *testing.T) { - cfg := &aws.Config{Region: aws.String("us-west-2")} - c := unit.Session.ClientConfig("testService", cfg) - svc := client.New( - *cfg, - metadata.ClientInfo{ - ServiceName: "testService", - SigningName: c.SigningName, - SigningRegion: c.SigningRegion, - Endpoint: c.Endpoint, - APIVersion: "", - }, - c.Handlers, - ) - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(rest.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(rest.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(rest.UnmarshalMetaHandler) - op := &request.Operation{ - Name: "test-operation", - HTTPPath: "/", - } - - input := &struct { - Foo aws.JSONValue `location:"header" locationName:"x-amz-foo" type:"jsonvalue"` - Bar aws.JSONValue `location:"header" locationName:"x-amz-bar" type:"jsonvalue"` - }{} - - output := &struct { - Foo aws.JSONValue `location:"header" locationName:"x-amz-foo" type:"jsonvalue"` - Bar aws.JSONValue `location:"header" locationName:"x-amz-bar" type:"jsonvalue"` - }{} - - req := svc.NewRequest(op, input, output) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(bytes.NewBuffer(nil)), Header: http.Header{}} - req.HTTPResponse.Header.Set("X-Amz-Foo", "e30=") - - // unmarshal response - rest.UnmarshalMeta(req) - rest.Unmarshal(req) - if req.Error != nil { - t.Fatal(req.Error) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/unmarshal_test.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/unmarshal_test.go deleted file mode 100644 index 2733e993d..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/unmarshal_test.go +++ /dev/null @@ -1,40 +0,0 @@ -package protocol_test - -import ( - "net/http" - "strings" - "testing" - - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/private/protocol" - "github.com/stretchr/testify/assert" -) - -type mockCloser struct { - *strings.Reader - Closed bool -} - -func (m *mockCloser) Close() error { - m.Closed = true - return nil -} - -func TestUnmarshalDrainBody(t *testing.T) { - b := &mockCloser{Reader: strings.NewReader("example body")} - r := &request.Request{HTTPResponse: &http.Response{ - Body: b, - }} - - protocol.UnmarshalDiscardBody(r) - assert.NoError(t, r.Error) - assert.Equal(t, 0, b.Len()) - assert.True(t, b.Closed) -} - -func TestUnmarshalDrainBodyNoBody(t *testing.T) { - r := &request.Request{HTTPResponse: &http.Response{}} - - protocol.UnmarshalDiscardBody(r) - assert.NoError(t, r.Error) -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/unmarshal_test.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/unmarshal_test.go deleted file mode 100644 index 1185d2328..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/unmarshal_test.go +++ /dev/null @@ -1,142 +0,0 @@ -package xmlutil - -import ( - "encoding/xml" - "fmt" - "io" - "reflect" - "strings" - "testing" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awsutil" -) - -type mockBody struct { - DoneErr error - Body io.Reader -} - -func (m *mockBody) Read(p []byte) (int, error) { - n, err := m.Body.Read(p) - if (n == 0 || err == io.EOF) && m.DoneErr != nil { - return n, m.DoneErr - } - - return n, err -} - -type mockOutput struct { - _ struct{} `type:"structure"` - String *string `type:"string"` - Integer *int64 `type:"integer"` - Nested *mockNestedStruct `type:"structure"` - List []*mockListElem `locationName:"List" locationNameList:"Elem" type:"list"` - Closed *mockClosedTags `type:"structure"` -} -type mockNestedStruct struct { - _ struct{} `type:"structure"` - NestedString *string `type:"string"` - NestedInt *int64 `type:"integer"` -} -type mockClosedTags struct { - _ struct{} `type:"structure" xmlPrefix:"xsi" xmlURI:"http://www.w3.org/2001/XMLSchema-instance"` - Attr *string `locationName:"xsi:attrval" type:"string" xmlAttribute:"true"` -} -type mockListElem struct { - _ struct{} `type:"structure" xmlPrefix:"xsi" xmlURI:"http://www.w3.org/2001/XMLSchema-instance"` - String *string `type:"string"` - NestedElem *mockNestedListElem `type:"structure"` -} -type mockNestedListElem struct { - _ struct{} `type:"structure" xmlPrefix:"xsi" xmlURI:"http://www.w3.org/2001/XMLSchema-instance"` - - String *string `type:"string"` - Type *string `locationName:"xsi:type" type:"string" xmlAttribute:"true"` -} - -func TestUnmarshal(t *testing.T) { - const xmlBodyStr = ` - - string value - 123 - - - nested string value - 321 - - - - - nested elem string value - - elem string value - - -` - - expect := mockOutput{ - String: aws.String("string value"), - Integer: aws.Int64(123), - Closed: &mockClosedTags{ - Attr: aws.String("attr value"), - }, - Nested: &mockNestedStruct{ - NestedString: aws.String("nested string value"), - NestedInt: aws.Int64(321), - }, - List: []*mockListElem{ - { - String: aws.String("elem string value"), - NestedElem: &mockNestedListElem{ - String: aws.String("nested elem string value"), - Type: aws.String("type"), - }, - }, - }, - } - - actual := mockOutput{} - decoder := xml.NewDecoder(strings.NewReader(xmlBodyStr)) - err := UnmarshalXML(&actual, decoder, "") - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - - if !reflect.DeepEqual(expect, actual) { - t.Errorf("expect unmarshal to match\nExpect: %s\nActual: %s", - awsutil.Prettify(expect), awsutil.Prettify(actual)) - } -} - -func TestUnmarshal_UnexpectedEOF(t *testing.T) { - const partialXMLBody = ` - first value - Second val` - - out := struct { - First *string `locationName:"First" type:"string"` - Second *string `locationName:"Second" type:"string"` - }{} - - expect := out - expect.First = aws.String("first") - expect.Second = aws.String("second") - - expectErr := fmt.Errorf("expected read error") - - body := &mockBody{ - DoneErr: expectErr, - Body: strings.NewReader(partialXMLBody), - } - - decoder := xml.NewDecoder(body) - err := UnmarshalXML(&out, decoder, "") - - if err == nil { - t.Fatalf("expect error, got none") - } - if e, a := expectErr, err; e != a { - t.Errorf("expect %v error in %v, but was not", e, a) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/xml_to_struct_test.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/xml_to_struct_test.go deleted file mode 100644 index 77d12bb79..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/xml_to_struct_test.go +++ /dev/null @@ -1,66 +0,0 @@ -package xmlutil_test - -import ( - "net/http" - "net/http/httptest" - "testing" - - "github.com/stretchr/testify/assert" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/awstesting/unit" - "github.com/aws/aws-sdk-go/service/s3" -) - -func TestUnmarshal(t *testing.T) { - xmlVal := []byte(` - - - foo-id - user - - - - - foo-id - user - - FULL_CONTROL - - -`) - - var server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Write(xmlVal) - })) - - sess := unit.Session - sess.Config.Endpoint = &server.URL - sess.Config.S3ForcePathStyle = aws.Bool(true) - svc := s3.New(sess) - - out, err := svc.GetBucketAcl(&s3.GetBucketAclInput{ - Bucket: aws.String("foo"), - }) - - assert.NoError(t, err) - - expected := &s3.GetBucketAclOutput{ - Grants: []*s3.Grant{ - { - Grantee: &s3.Grantee{ - DisplayName: aws.String("user"), - ID: aws.String("foo-id"), - Type: aws.String("type"), - }, - Permission: aws.String("FULL_CONTROL"), - }, - }, - - Owner: &s3.Owner{ - DisplayName: aws.String("user"), - ID: aws.String("foo-id"), - }, - } - assert.Equal(t, expected, out) -} diff --git a/vendor/github.com/aws/aws-sdk-go/service/ec2/customizations_test.go b/vendor/github.com/aws/aws-sdk-go/service/ec2/customizations_test.go deleted file mode 100644 index 08ff2cf0b..000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/ec2/customizations_test.go +++ /dev/null @@ -1,48 +0,0 @@ -package ec2_test - -import ( - "io/ioutil" - "net/url" - "regexp" - "testing" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/awstesting/unit" - "github.com/aws/aws-sdk-go/service/ec2" -) - -func TestCopySnapshotPresignedURL(t *testing.T) { - svc := ec2.New(unit.Session, &aws.Config{Region: aws.String("us-west-2")}) - - func() { - defer func() { - if r := recover(); r != nil { - t.Fatalf("expect CopySnapshotRequest with nill") - } - }() - // Doesn't panic on nil input - req, _ := svc.CopySnapshotRequest(nil) - req.Sign() - }() - - req, _ := svc.CopySnapshotRequest(&ec2.CopySnapshotInput{ - SourceRegion: aws.String("us-west-1"), - SourceSnapshotId: aws.String("snap-id"), - }) - req.Sign() - - b, _ := ioutil.ReadAll(req.HTTPRequest.Body) - q, _ := url.ParseQuery(string(b)) - u, _ := url.QueryUnescape(q.Get("PresignedUrl")) - if e, a := "us-west-2", q.Get("DestinationRegion"); e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "us-west-1", q.Get("SourceRegion"); e != a { - t.Errorf("expect %v, got %v", e, a) - } - - r := regexp.MustCompile(`^https://ec2\.us-west-1\.amazonaws\.com/.+&DestinationRegion=us-west-2`) - if !r.MatchString(u) { - t.Errorf("expect %v to match, got %v", r.String(), u) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/service/ec2/examples_test.go b/vendor/github.com/aws/aws-sdk-go/service/ec2/examples_test.go deleted file mode 100644 index 5111327d8..000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/ec2/examples_test.go +++ /dev/null @@ -1,4201 +0,0 @@ -// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. - -package ec2_test - -import ( - "fmt" - "strings" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/ec2" -) - -var _ time.Duration -var _ strings.Reader -var _ aws.Config - -func parseTime(layout, value string) *time.Time { - t, err := time.Parse(layout, value) - if err != nil { - panic(err) - } - return &t -} - -// To allocate an Elastic IP address for EC2-VPC -// -// This example allocates an Elastic IP address to use with an instance in a VPC. -func ExampleEC2_AllocateAddress_shared00() { - svc := ec2.New(session.New()) - input := &ec2.AllocateAddressInput{ - Domain: aws.String("vpc"), - } - - result, err := svc.AllocateAddress(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To allocate an Elastic IP address for EC2-Classic -// -// This example allocates an Elastic IP address to use with an instance in EC2-Classic. -func ExampleEC2_AllocateAddress_shared01() { - svc := ec2.New(session.New()) - input := &ec2.AllocateAddressInput{} - - result, err := svc.AllocateAddress(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To assign a specific secondary private IP address to an interface -// -// This example assigns the specified secondary private IP address to the specified -// network interface. -func ExampleEC2_AssignPrivateIpAddresses_shared00() { - svc := ec2.New(session.New()) - input := &ec2.AssignPrivateIpAddressesInput{ - NetworkInterfaceId: aws.String("eni-e5aa89a3"), - PrivateIpAddresses: []*string{ - aws.String("10.0.0.82"), - }, - } - - result, err := svc.AssignPrivateIpAddresses(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To assign secondary private IP addresses that Amazon EC2 selects to an interface -// -// This example assigns two secondary private IP addresses to the specified network -// interface. Amazon EC2 automatically assigns these IP addresses from the available -// IP addresses in the CIDR block range of the subnet the network interface is associated -// with. -func ExampleEC2_AssignPrivateIpAddresses_shared01() { - svc := ec2.New(session.New()) - input := &ec2.AssignPrivateIpAddressesInput{ - NetworkInterfaceId: aws.String("eni-e5aa89a3"), - SecondaryPrivateIpAddressCount: aws.Int64(2), - } - - result, err := svc.AssignPrivateIpAddresses(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To associate an Elastic IP address in EC2-VPC -// -// This example associates the specified Elastic IP address with the specified instance -// in a VPC. -func ExampleEC2_AssociateAddress_shared00() { - svc := ec2.New(session.New()) - input := &ec2.AssociateAddressInput{ - AllocationId: aws.String("eipalloc-64d5890a"), - InstanceId: aws.String("i-0b263919b6498b123"), - } - - result, err := svc.AssociateAddress(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To associate an Elastic IP address with a network interface -// -// This example associates the specified Elastic IP address with the specified network -// interface. -func ExampleEC2_AssociateAddress_shared01() { - svc := ec2.New(session.New()) - input := &ec2.AssociateAddressInput{ - AllocationId: aws.String("eipalloc-64d5890a"), - NetworkInterfaceId: aws.String("eni-1a2b3c4d"), - } - - result, err := svc.AssociateAddress(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To associate an Elastic IP address in EC2-Classic -// -// This example associates an Elastic IP address with an instance in EC2-Classic. -func ExampleEC2_AssociateAddress_shared02() { - svc := ec2.New(session.New()) - input := &ec2.AssociateAddressInput{ - InstanceId: aws.String("i-07ffe74c7330ebf53"), - PublicIp: aws.String("198.51.100.0"), - } - - result, err := svc.AssociateAddress(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To associate a DHCP options set with a VPC -// -// This example associates the specified DHCP options set with the specified VPC. -func ExampleEC2_AssociateDhcpOptions_shared00() { - svc := ec2.New(session.New()) - input := &ec2.AssociateDhcpOptionsInput{ - DhcpOptionsId: aws.String("dopt-d9070ebb"), - VpcId: aws.String("vpc-a01106c2"), - } - - result, err := svc.AssociateDhcpOptions(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To associate the default DHCP options set with a VPC -// -// This example associates the default DHCP options set with the specified VPC. -func ExampleEC2_AssociateDhcpOptions_shared01() { - svc := ec2.New(session.New()) - input := &ec2.AssociateDhcpOptionsInput{ - DhcpOptionsId: aws.String("default"), - VpcId: aws.String("vpc-a01106c2"), - } - - result, err := svc.AssociateDhcpOptions(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To associate a route table with a subnet -// -// This example associates the specified route table with the specified subnet. -func ExampleEC2_AssociateRouteTable_shared00() { - svc := ec2.New(session.New()) - input := &ec2.AssociateRouteTableInput{ - RouteTableId: aws.String("rtb-22574640"), - SubnetId: aws.String("subnet-9d4a7b6"), - } - - result, err := svc.AssociateRouteTable(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To attach an Internet gateway to a VPC -// -// This example attaches the specified Internet gateway to the specified VPC. -func ExampleEC2_AttachInternetGateway_shared00() { - svc := ec2.New(session.New()) - input := &ec2.AttachInternetGatewayInput{ - InternetGatewayId: aws.String("igw-c0a643a9"), - VpcId: aws.String("vpc-a01106c2"), - } - - result, err := svc.AttachInternetGateway(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To attach a network interface to an instance -// -// This example attaches the specified network interface to the specified instance. -func ExampleEC2_AttachNetworkInterface_shared00() { - svc := ec2.New(session.New()) - input := &ec2.AttachNetworkInterfaceInput{ - DeviceIndex: aws.Int64(1), - InstanceId: aws.String("i-1234567890abcdef0"), - NetworkInterfaceId: aws.String("eni-e5aa89a3"), - } - - result, err := svc.AttachNetworkInterface(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To attach a volume to an instance -// -// This example attaches a volume (``vol-1234567890abcdef0``) to an instance (``i-01474ef662b89480``) -// as ``/dev/sdf``. -func ExampleEC2_AttachVolume_shared00() { - svc := ec2.New(session.New()) - input := &ec2.AttachVolumeInput{ - Device: aws.String("/dev/sdf"), - InstanceId: aws.String("i-01474ef662b89480"), - VolumeId: aws.String("vol-1234567890abcdef0"), - } - - result, err := svc.AttachVolume(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To cancel a Spot fleet request -// -// This example cancels the specified Spot fleet request and terminates its associated -// Spot Instances. -func ExampleEC2_CancelSpotFleetRequests_shared00() { - svc := ec2.New(session.New()) - input := &ec2.CancelSpotFleetRequestsInput{ - SpotFleetRequestIds: []*string{ - aws.String("sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE"), - }, - TerminateInstances: aws.Bool(true), - } - - result, err := svc.CancelSpotFleetRequests(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To cancel a Spot fleet request without terminating its Spot Instances -// -// This example cancels the specified Spot fleet request without terminating its associated -// Spot Instances. -func ExampleEC2_CancelSpotFleetRequests_shared01() { - svc := ec2.New(session.New()) - input := &ec2.CancelSpotFleetRequestsInput{ - SpotFleetRequestIds: []*string{ - aws.String("sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE"), - }, - TerminateInstances: aws.Bool(false), - } - - result, err := svc.CancelSpotFleetRequests(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To cancel Spot Instance requests -// -// This example cancels a Spot Instance request. -func ExampleEC2_CancelSpotInstanceRequests_shared00() { - svc := ec2.New(session.New()) - input := &ec2.CancelSpotInstanceRequestsInput{ - SpotInstanceRequestIds: []*string{ - aws.String("sir-08b93456"), - }, - } - - result, err := svc.CancelSpotInstanceRequests(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To confirm the product instance -// -// This example determines whether the specified product code is associated with the -// specified instance. -func ExampleEC2_ConfirmProductInstance_shared00() { - svc := ec2.New(session.New()) - input := &ec2.ConfirmProductInstanceInput{ - InstanceId: aws.String("i-1234567890abcdef0"), - ProductCode: aws.String("774F4FF8"), - } - - result, err := svc.ConfirmProductInstance(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To copy a snapshot -// -// This example copies a snapshot with the snapshot ID of ``snap-066877671789bd71b`` -// from the ``us-west-2`` region to the ``us-east-1`` region and adds a short description -// to identify the snapshot. -func ExampleEC2_CopySnapshot_shared00() { - svc := ec2.New(session.New()) - input := &ec2.CopySnapshotInput{ - Description: aws.String("This is my copied snapshot."), - DestinationRegion: aws.String("us-east-1"), - SourceRegion: aws.String("us-west-2"), - SourceSnapshotId: aws.String("snap-066877671789bd71b"), - } - - result, err := svc.CopySnapshot(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To create a customer gateway -// -// This example creates a customer gateway with the specified IP address for its outside -// interface. -func ExampleEC2_CreateCustomerGateway_shared00() { - svc := ec2.New(session.New()) - input := &ec2.CreateCustomerGatewayInput{ - BgpAsn: aws.Int64(65534), - PublicIp: aws.String("12.1.2.3"), - Type: aws.String("ipsec.1"), - } - - result, err := svc.CreateCustomerGateway(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To create a DHCP options set -// -// This example creates a DHCP options set. -func ExampleEC2_CreateDhcpOptions_shared00() { - svc := ec2.New(session.New()) - input := &ec2.CreateDhcpOptionsInput{ - DhcpConfigurations: []*ec2.NewDhcpConfiguration{ - { - Key: aws.String("domain-name-servers"), - Values: []*string{ - aws.String("10.2.5.1"), - aws.String("10.2.5.2"), - }, - }, - }, - } - - result, err := svc.CreateDhcpOptions(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To create an Internet gateway -// -// This example creates an Internet gateway. -func ExampleEC2_CreateInternetGateway_shared00() { - svc := ec2.New(session.New()) - input := &ec2.CreateInternetGatewayInput{} - - result, err := svc.CreateInternetGateway(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To create a key pair -// -// This example creates a key pair named my-key-pair. -func ExampleEC2_CreateKeyPair_shared00() { - svc := ec2.New(session.New()) - input := &ec2.CreateKeyPairInput{ - KeyName: aws.String("my-key-pair"), - } - - result, err := svc.CreateKeyPair(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To create a NAT gateway -// -// This example creates a NAT gateway in subnet subnet-1a2b3c4d and associates an Elastic -// IP address with the allocation ID eipalloc-37fc1a52 with the NAT gateway. -func ExampleEC2_CreateNatGateway_shared00() { - svc := ec2.New(session.New()) - input := &ec2.CreateNatGatewayInput{ - AllocationId: aws.String("eipalloc-37fc1a52"), - SubnetId: aws.String("subnet-1a2b3c4d"), - } - - result, err := svc.CreateNatGateway(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To create a network ACL -// -// This example creates a network ACL for the specified VPC. -func ExampleEC2_CreateNetworkAcl_shared00() { - svc := ec2.New(session.New()) - input := &ec2.CreateNetworkAclInput{ - VpcId: aws.String("vpc-a01106c2"), - } - - result, err := svc.CreateNetworkAcl(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To create a network ACL entry -// -// This example creates an entry for the specified network ACL. The rule allows ingress -// traffic from anywhere (0.0.0.0/0) on UDP port 53 (DNS) into any associated subnet. -func ExampleEC2_CreateNetworkAclEntry_shared00() { - svc := ec2.New(session.New()) - input := &ec2.CreateNetworkAclEntryInput{ - CidrBlock: aws.String("0.0.0.0/0"), - Egress: aws.Bool(false), - NetworkAclId: aws.String("acl-5fb85d36"), - PortRange: &ec2.PortRange{ - From: aws.Int64(53), - To: aws.Int64(53), - }, - Protocol: aws.String("udp"), - RuleAction: aws.String("allow"), - RuleNumber: aws.Int64(100), - } - - result, err := svc.CreateNetworkAclEntry(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To create a network interface -// -// This example creates a network interface for the specified subnet. -func ExampleEC2_CreateNetworkInterface_shared00() { - svc := ec2.New(session.New()) - input := &ec2.CreateNetworkInterfaceInput{ - Description: aws.String("my network interface"), - Groups: []*string{ - aws.String("sg-903004f8"), - }, - PrivateIpAddress: aws.String("10.0.2.17"), - SubnetId: aws.String("subnet-9d4a7b6c"), - } - - result, err := svc.CreateNetworkInterface(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To create a placement group -// -// This example creates a placement group with the specified name. -func ExampleEC2_CreatePlacementGroup_shared00() { - svc := ec2.New(session.New()) - input := &ec2.CreatePlacementGroupInput{ - GroupName: aws.String("my-cluster"), - Strategy: aws.String("cluster"), - } - - result, err := svc.CreatePlacementGroup(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To create a route -// -// This example creates a route for the specified route table. The route matches all -// traffic (0.0.0.0/0) and routes it to the specified Internet gateway. -func ExampleEC2_CreateRoute_shared00() { - svc := ec2.New(session.New()) - input := &ec2.CreateRouteInput{ - DestinationCidrBlock: aws.String("0.0.0.0/0"), - GatewayId: aws.String("igw-c0a643a9"), - RouteTableId: aws.String("rtb-22574640"), - } - - result, err := svc.CreateRoute(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To create a route table -// -// This example creates a route table for the specified VPC. -func ExampleEC2_CreateRouteTable_shared00() { - svc := ec2.New(session.New()) - input := &ec2.CreateRouteTableInput{ - VpcId: aws.String("vpc-a01106c2"), - } - - result, err := svc.CreateRouteTable(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To create a snapshot -// -// This example creates a snapshot of the volume with a volume ID of ``vol-1234567890abcdef0`` -// and a short description to identify the snapshot. -func ExampleEC2_CreateSnapshot_shared00() { - svc := ec2.New(session.New()) - input := &ec2.CreateSnapshotInput{ - Description: aws.String("This is my root volume snapshot."), - VolumeId: aws.String("vol-1234567890abcdef0"), - } - - result, err := svc.CreateSnapshot(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To create a Spot Instance datafeed -// -// This example creates a Spot Instance data feed for your AWS account. -func ExampleEC2_CreateSpotDatafeedSubscription_shared00() { - svc := ec2.New(session.New()) - input := &ec2.CreateSpotDatafeedSubscriptionInput{ - Bucket: aws.String("my-s3-bucket"), - Prefix: aws.String("spotdata"), - } - - result, err := svc.CreateSpotDatafeedSubscription(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To create a subnet -// -// This example creates a subnet in the specified VPC with the specified CIDR block. -// We recommend that you let us select an Availability Zone for you. -func ExampleEC2_CreateSubnet_shared00() { - svc := ec2.New(session.New()) - input := &ec2.CreateSubnetInput{ - CidrBlock: aws.String("10.0.1.0/24"), - VpcId: aws.String("vpc-a01106c2"), - } - - result, err := svc.CreateSubnet(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To add a tag to a resource -// -// This example adds the tag Stack=production to the specified image, or overwrites -// an existing tag for the AMI where the tag key is Stack. -func ExampleEC2_CreateTags_shared00() { - svc := ec2.New(session.New()) - input := &ec2.CreateTagsInput{ - Resources: []*string{ - aws.String("ami-78a54011"), - }, - Tags: []*ec2.Tag{ - { - Key: aws.String("Stack"), - Value: aws.String("production"), - }, - }, - } - - result, err := svc.CreateTags(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To create a new volume -// -// This example creates an 80 GiB General Purpose (SSD) volume in the Availability Zone -// ``us-east-1a``. -func ExampleEC2_CreateVolume_shared00() { - svc := ec2.New(session.New()) - input := &ec2.CreateVolumeInput{ - AvailabilityZone: aws.String("us-east-1a"), - Size: aws.Int64(80), - VolumeType: aws.String("gp2"), - } - - result, err := svc.CreateVolume(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To create a new Provisioned IOPS (SSD) volume from a snapshot -// -// This example creates a new Provisioned IOPS (SSD) volume with 1000 provisioned IOPS -// from a snapshot in the Availability Zone ``us-east-1a``. -func ExampleEC2_CreateVolume_shared01() { - svc := ec2.New(session.New()) - input := &ec2.CreateVolumeInput{ - AvailabilityZone: aws.String("us-east-1a"), - Iops: aws.Int64(1000), - SnapshotId: aws.String("snap-066877671789bd71b"), - VolumeType: aws.String("io1"), - } - - result, err := svc.CreateVolume(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To create a VPC -// -// This example creates a VPC with the specified CIDR block. -func ExampleEC2_CreateVpc_shared00() { - svc := ec2.New(session.New()) - input := &ec2.CreateVpcInput{ - CidrBlock: aws.String("10.0.0.0/16"), - } - - result, err := svc.CreateVpc(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To delete a customer gateway -// -// This example deletes the specified customer gateway. -func ExampleEC2_DeleteCustomerGateway_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DeleteCustomerGatewayInput{ - CustomerGatewayId: aws.String("cgw-0e11f167"), - } - - result, err := svc.DeleteCustomerGateway(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To delete a DHCP options set -// -// This example deletes the specified DHCP options set. -func ExampleEC2_DeleteDhcpOptions_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DeleteDhcpOptionsInput{ - DhcpOptionsId: aws.String("dopt-d9070ebb"), - } - - result, err := svc.DeleteDhcpOptions(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To delete an Internet gateway -// -// This example deletes the specified Internet gateway. -func ExampleEC2_DeleteInternetGateway_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DeleteInternetGatewayInput{ - InternetGatewayId: aws.String("igw-c0a643a9"), - } - - result, err := svc.DeleteInternetGateway(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To delete a key pair -// -// This example deletes the specified key pair. -func ExampleEC2_DeleteKeyPair_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DeleteKeyPairInput{ - KeyName: aws.String("my-key-pair"), - } - - result, err := svc.DeleteKeyPair(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To delete a NAT gateway -// -// This example deletes the specified NAT gateway. -func ExampleEC2_DeleteNatGateway_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DeleteNatGatewayInput{ - NatGatewayId: aws.String("nat-04ae55e711cec5680"), - } - - result, err := svc.DeleteNatGateway(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To delete a network ACL -// -// This example deletes the specified network ACL. -func ExampleEC2_DeleteNetworkAcl_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DeleteNetworkAclInput{ - NetworkAclId: aws.String("acl-5fb85d36"), - } - - result, err := svc.DeleteNetworkAcl(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To delete a network ACL entry -// -// This example deletes ingress rule number 100 from the specified network ACL. -func ExampleEC2_DeleteNetworkAclEntry_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DeleteNetworkAclEntryInput{ - Egress: aws.Bool(true), - NetworkAclId: aws.String("acl-5fb85d36"), - RuleNumber: aws.Int64(100), - } - - result, err := svc.DeleteNetworkAclEntry(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To delete a network interface -// -// This example deletes the specified network interface. -func ExampleEC2_DeleteNetworkInterface_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DeleteNetworkInterfaceInput{ - NetworkInterfaceId: aws.String("eni-e5aa89a3"), - } - - result, err := svc.DeleteNetworkInterface(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To delete a placement group -// -// This example deletes the specified placement group. -// -func ExampleEC2_DeletePlacementGroup_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DeletePlacementGroupInput{ - GroupName: aws.String("my-cluster"), - } - - result, err := svc.DeletePlacementGroup(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To delete a route -// -// This example deletes the specified route from the specified route table. -func ExampleEC2_DeleteRoute_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DeleteRouteInput{ - DestinationCidrBlock: aws.String("0.0.0.0/0"), - RouteTableId: aws.String("rtb-22574640"), - } - - result, err := svc.DeleteRoute(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To delete a route table -// -// This example deletes the specified route table. -func ExampleEC2_DeleteRouteTable_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DeleteRouteTableInput{ - RouteTableId: aws.String("rtb-22574640"), - } - - result, err := svc.DeleteRouteTable(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To delete a snapshot -// -// This example deletes a snapshot with the snapshot ID of ``snap-1234567890abcdef0``. -// If the command succeeds, no output is returned. -func ExampleEC2_DeleteSnapshot_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DeleteSnapshotInput{ - SnapshotId: aws.String("snap-1234567890abcdef0"), - } - - result, err := svc.DeleteSnapshot(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To cancel a Spot Instance data feed subscription -// -// This example deletes a Spot data feed subscription for the account. -func ExampleEC2_DeleteSpotDatafeedSubscription_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DeleteSpotDatafeedSubscriptionInput{} - - result, err := svc.DeleteSpotDatafeedSubscription(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To delete a subnet -// -// This example deletes the specified subnet. -func ExampleEC2_DeleteSubnet_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DeleteSubnetInput{ - SubnetId: aws.String("subnet-9d4a7b6c"), - } - - result, err := svc.DeleteSubnet(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To delete a tag from a resource -// -// This example deletes the tag Stack=test from the specified image. -func ExampleEC2_DeleteTags_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DeleteTagsInput{ - Resources: []*string{ - aws.String("ami-78a54011"), - }, - Tags: []*ec2.Tag{ - { - Key: aws.String("Stack"), - Value: aws.String("test"), - }, - }, - } - - result, err := svc.DeleteTags(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To delete a volume -// -// This example deletes an available volume with the volume ID of ``vol-049df61146c4d7901``. -// If the command succeeds, no output is returned. -func ExampleEC2_DeleteVolume_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DeleteVolumeInput{ - VolumeId: aws.String("vol-049df61146c4d7901"), - } - - result, err := svc.DeleteVolume(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To delete a VPC -// -// This example deletes the specified VPC. -func ExampleEC2_DeleteVpc_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DeleteVpcInput{ - VpcId: aws.String("vpc-a01106c2"), - } - - result, err := svc.DeleteVpc(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe a single attribute for your AWS account -// -// This example describes the supported-platforms attribute for your AWS account. -func ExampleEC2_DescribeAccountAttributes_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DescribeAccountAttributesInput{ - AttributeNames: []*string{ - aws.String("supported-platforms"), - }, - } - - result, err := svc.DescribeAccountAttributes(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe all attributes for your AWS account -// -// This example describes the attributes for your AWS account. -func ExampleEC2_DescribeAccountAttributes_shared01() { - svc := ec2.New(session.New()) - input := &ec2.DescribeAccountAttributesInput{} - - result, err := svc.DescribeAccountAttributes(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe your Elastic IP addresses -// -// This example describes your Elastic IP addresses. -func ExampleEC2_DescribeAddresses_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DescribeAddressesInput{} - - result, err := svc.DescribeAddresses(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe your Elastic IP addresses for EC2-VPC -// -// This example describes your Elastic IP addresses for use with instances in a VPC. -func ExampleEC2_DescribeAddresses_shared01() { - svc := ec2.New(session.New()) - input := &ec2.DescribeAddressesInput{ - Filters: []*ec2.Filter{ - { - Name: aws.String("domain"), - Values: []*string{ - aws.String("vpc"), - }, - }, - }, - } - - result, err := svc.DescribeAddresses(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe your Elastic IP addresses for EC2-Classic -// -// This example describes your Elastic IP addresses for use with instances in EC2-Classic. -func ExampleEC2_DescribeAddresses_shared02() { - svc := ec2.New(session.New()) - input := &ec2.DescribeAddressesInput{ - Filters: []*ec2.Filter{ - { - Name: aws.String("domain"), - Values: []*string{ - aws.String("standard"), - }, - }, - }, - } - - result, err := svc.DescribeAddresses(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe your Availability Zones -// -// This example describes the Availability Zones that are available to you. The response -// includes Availability Zones only for the current region. -func ExampleEC2_DescribeAvailabilityZones_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DescribeAvailabilityZonesInput{} - - result, err := svc.DescribeAvailabilityZones(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe a customer gateway -// -// This example describes the specified customer gateway. -func ExampleEC2_DescribeCustomerGateways_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DescribeCustomerGatewaysInput{ - CustomerGatewayIds: []*string{ - aws.String("cgw-0e11f167"), - }, - } - - result, err := svc.DescribeCustomerGateways(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe a DHCP options set -// -// This example describes the specified DHCP options set. -func ExampleEC2_DescribeDhcpOptions_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DescribeDhcpOptionsInput{ - DhcpOptionsIds: []*string{ - aws.String("dopt-d9070ebb"), - }, - } - - result, err := svc.DescribeDhcpOptions(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe the instance type -// -// This example describes the instance type of the specified instance. -// -func ExampleEC2_DescribeInstanceAttribute_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DescribeInstanceAttributeInput{ - Attribute: aws.String("instanceType"), - InstanceId: aws.String("i-1234567890abcdef0"), - } - - result, err := svc.DescribeInstanceAttribute(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe the disableApiTermination attribute -// -// This example describes the ``disableApiTermination`` attribute of the specified instance. -// -func ExampleEC2_DescribeInstanceAttribute_shared01() { - svc := ec2.New(session.New()) - input := &ec2.DescribeInstanceAttributeInput{ - Attribute: aws.String("disableApiTermination"), - InstanceId: aws.String("i-1234567890abcdef0"), - } - - result, err := svc.DescribeInstanceAttribute(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe the block device mapping for an instance -// -// This example describes the ``blockDeviceMapping`` attribute of the specified instance. -// -func ExampleEC2_DescribeInstanceAttribute_shared02() { - svc := ec2.New(session.New()) - input := &ec2.DescribeInstanceAttributeInput{ - Attribute: aws.String("blockDeviceMapping"), - InstanceId: aws.String("i-1234567890abcdef0"), - } - - result, err := svc.DescribeInstanceAttribute(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe the Internet gateway for a VPC -// -// This example describes the Internet gateway for the specified VPC. -func ExampleEC2_DescribeInternetGateways_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DescribeInternetGatewaysInput{ - Filters: []*ec2.Filter{ - { - Name: aws.String("attachment.vpc-id"), - Values: []*string{ - aws.String("vpc-a01106c2"), - }, - }, - }, - } - - result, err := svc.DescribeInternetGateways(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To display a key pair -// -// This example displays the fingerprint for the specified key. -func ExampleEC2_DescribeKeyPairs_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DescribeKeyPairsInput{ - KeyNames: []*string{ - aws.String("my-key-pair"), - }, - } - - result, err := svc.DescribeKeyPairs(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe your moving addresses -// -// This example describes all of your moving Elastic IP addresses. -func ExampleEC2_DescribeMovingAddresses_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DescribeMovingAddressesInput{} - - result, err := svc.DescribeMovingAddresses(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe a NAT gateway -// -// This example describes the NAT gateway for the specified VPC. -func ExampleEC2_DescribeNatGateways_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DescribeNatGatewaysInput{ - Filter: []*ec2.Filter{ - { - Name: aws.String("vpc-id"), - Values: []*string{ - aws.String("vpc-1a2b3c4d"), - }, - }, - }, - } - - result, err := svc.DescribeNatGateways(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe a network ACL -// -// This example describes the specified network ACL. -func ExampleEC2_DescribeNetworkAcls_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DescribeNetworkAclsInput{ - NetworkAclIds: []*string{ - aws.String("acl-5fb85d36"), - }, - } - - result, err := svc.DescribeNetworkAcls(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe the attachment attribute of a network interface -// -// This example describes the attachment attribute of the specified network interface. -func ExampleEC2_DescribeNetworkInterfaceAttribute_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DescribeNetworkInterfaceAttributeInput{ - Attribute: aws.String("attachment"), - NetworkInterfaceId: aws.String("eni-686ea200"), - } - - result, err := svc.DescribeNetworkInterfaceAttribute(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe the description attribute of a network interface -// -// This example describes the description attribute of the specified network interface. -func ExampleEC2_DescribeNetworkInterfaceAttribute_shared01() { - svc := ec2.New(session.New()) - input := &ec2.DescribeNetworkInterfaceAttributeInput{ - Attribute: aws.String("description"), - NetworkInterfaceId: aws.String("eni-686ea200"), - } - - result, err := svc.DescribeNetworkInterfaceAttribute(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe the groupSet attribute of a network interface -// -// This example describes the groupSet attribute of the specified network interface. -func ExampleEC2_DescribeNetworkInterfaceAttribute_shared02() { - svc := ec2.New(session.New()) - input := &ec2.DescribeNetworkInterfaceAttributeInput{ - Attribute: aws.String("groupSet"), - NetworkInterfaceId: aws.String("eni-686ea200"), - } - - result, err := svc.DescribeNetworkInterfaceAttribute(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe the sourceDestCheck attribute of a network interface -// -// This example describes the sourceDestCheck attribute of the specified network interface. -func ExampleEC2_DescribeNetworkInterfaceAttribute_shared03() { - svc := ec2.New(session.New()) - input := &ec2.DescribeNetworkInterfaceAttributeInput{ - Attribute: aws.String("sourceDestCheck"), - NetworkInterfaceId: aws.String("eni-686ea200"), - } - - result, err := svc.DescribeNetworkInterfaceAttribute(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe a network interface -// - -func ExampleEC2_DescribeNetworkInterfaces_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DescribeNetworkInterfacesInput{ - NetworkInterfaceIds: []*string{ - aws.String("eni-e5aa89a3"), - }, - } - - result, err := svc.DescribeNetworkInterfaces(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe your regions -// -// This example describes all the regions that are available to you. -func ExampleEC2_DescribeRegions_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DescribeRegionsInput{} - - result, err := svc.DescribeRegions(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe a route table -// -// This example describes the specified route table. -func ExampleEC2_DescribeRouteTables_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DescribeRouteTablesInput{ - RouteTableIds: []*string{ - aws.String("rtb-1f382e7d"), - }, - } - - result, err := svc.DescribeRouteTables(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe an available schedule -// -// This example describes a schedule that occurs every week on Sunday, starting on the -// specified date. Note that the output contains a single schedule as an example. -func ExampleEC2_DescribeScheduledInstanceAvailability_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DescribeScheduledInstanceAvailabilityInput{ - FirstSlotStartTimeRange: &ec2.SlotDateTimeRangeRequest{ - EarliestTime: parseTime("2006-01-02T15:04:05Z", "2016-01-31T00:00:00Z"), - LatestTime: parseTime("2006-01-02T15:04:05Z", "2016-01-31T04:00:00Z"), - }, - Recurrence: &ec2.ScheduledInstanceRecurrenceRequest{ - Frequency: aws.String("Weekly"), - Interval: aws.Int64(1), - OccurrenceDays: []*int64{ - aws.Int64(1), - }, - }, - } - - result, err := svc.DescribeScheduledInstanceAvailability(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe your Scheduled Instances -// -// This example describes the specified Scheduled Instance. -func ExampleEC2_DescribeScheduledInstances_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DescribeScheduledInstancesInput{ - ScheduledInstanceIds: []*string{ - aws.String("sci-1234-1234-1234-1234-123456789012"), - }, - } - - result, err := svc.DescribeScheduledInstances(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe snapshot attributes -// -// This example describes the ``createVolumePermission`` attribute on a snapshot with -// the snapshot ID of ``snap-066877671789bd71b``. -func ExampleEC2_DescribeSnapshotAttribute_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DescribeSnapshotAttributeInput{ - Attribute: aws.String("createVolumePermission"), - SnapshotId: aws.String("snap-066877671789bd71b"), - } - - result, err := svc.DescribeSnapshotAttribute(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe a snapshot -// -// This example describes a snapshot with the snapshot ID of ``snap-1234567890abcdef0``. -func ExampleEC2_DescribeSnapshots_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DescribeSnapshotsInput{ - SnapshotIds: []*string{ - aws.String("snap-1234567890abcdef0"), - }, - } - - result, err := svc.DescribeSnapshots(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe snapshots using filters -// -// This example describes all snapshots owned by the ID 012345678910 that are in the -// ``pending`` status. -func ExampleEC2_DescribeSnapshots_shared01() { - svc := ec2.New(session.New()) - input := &ec2.DescribeSnapshotsInput{ - Filters: []*ec2.Filter{ - { - Name: aws.String("status"), - Values: []*string{ - aws.String("pending"), - }, - }, - }, - OwnerIds: []*string{ - aws.String("012345678910"), - }, - } - - result, err := svc.DescribeSnapshots(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe the datafeed for your AWS account -// -// This example describes the Spot Instance datafeed subscription for your AWS account. -func ExampleEC2_DescribeSpotDatafeedSubscription_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DescribeSpotDatafeedSubscriptionInput{} - - result, err := svc.DescribeSpotDatafeedSubscription(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe the Spot Instances associated with a Spot fleet -// -// This example lists the Spot Instances associated with the specified Spot fleet. -func ExampleEC2_DescribeSpotFleetInstances_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DescribeSpotFleetInstancesInput{ - SpotFleetRequestId: aws.String("sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE"), - } - - result, err := svc.DescribeSpotFleetInstances(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe Spot fleet history -// -// This example returns the history for the specified Spot fleet starting at the specified -// time. -func ExampleEC2_DescribeSpotFleetRequestHistory_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DescribeSpotFleetRequestHistoryInput{ - SpotFleetRequestId: aws.String("sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE"), - StartTime: parseTime("2006-01-02T15:04:05Z", "2015-05-26T00:00:00Z"), - } - - result, err := svc.DescribeSpotFleetRequestHistory(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe a Spot fleet request -// -// This example describes the specified Spot fleet request. -func ExampleEC2_DescribeSpotFleetRequests_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DescribeSpotFleetRequestsInput{ - SpotFleetRequestIds: []*string{ - aws.String("sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE"), - }, - } - - result, err := svc.DescribeSpotFleetRequests(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe a Spot Instance request -// -// This example describes the specified Spot Instance request. -func ExampleEC2_DescribeSpotInstanceRequests_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DescribeSpotInstanceRequestsInput{ - SpotInstanceRequestIds: []*string{ - aws.String("sir-08b93456"), - }, - } - - result, err := svc.DescribeSpotInstanceRequests(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe Spot price history for Linux/UNIX (Amazon VPC) -// -// This example returns the Spot Price history for m1.xlarge, Linux/UNIX (Amazon VPC) -// instances for a particular day in January. -func ExampleEC2_DescribeSpotPriceHistory_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DescribeSpotPriceHistoryInput{ - EndTime: parseTime("2006-01-02T15:04:05Z", "2014-01-06T08:09:10"), - InstanceTypes: []*string{ - aws.String("m1.xlarge"), - }, - ProductDescriptions: []*string{ - aws.String("Linux/UNIX (Amazon VPC)"), - }, - StartTime: parseTime("2006-01-02T15:04:05Z", "2014-01-06T07:08:09"), - } - - result, err := svc.DescribeSpotPriceHistory(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe the subnets for a VPC -// -// This example describes the subnets for the specified VPC. -func ExampleEC2_DescribeSubnets_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DescribeSubnetsInput{ - Filters: []*ec2.Filter{ - { - Name: aws.String("vpc-id"), - Values: []*string{ - aws.String("vpc-a01106c2"), - }, - }, - }, - } - - result, err := svc.DescribeSubnets(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe the tags for a single resource -// -// This example describes the tags for the specified instance. -func ExampleEC2_DescribeTags_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DescribeTagsInput{ - Filters: []*ec2.Filter{ - { - Name: aws.String("resource-id"), - Values: []*string{ - aws.String("i-1234567890abcdef8"), - }, - }, - }, - } - - result, err := svc.DescribeTags(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe a volume attribute -// -// This example describes the ``autoEnableIo`` attribute of the volume with the ID ``vol-049df61146c4d7901``. -func ExampleEC2_DescribeVolumeAttribute_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DescribeVolumeAttributeInput{ - Attribute: aws.String("autoEnableIO"), - VolumeId: aws.String("vol-049df61146c4d7901"), - } - - result, err := svc.DescribeVolumeAttribute(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe the status of a single volume -// -// This example describes the status for the volume ``vol-1234567890abcdef0``. -func ExampleEC2_DescribeVolumeStatus_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DescribeVolumeStatusInput{ - VolumeIds: []*string{ - aws.String("vol-1234567890abcdef0"), - }, - } - - result, err := svc.DescribeVolumeStatus(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe the status of impaired volumes -// -// This example describes the status for all volumes that are impaired. In this example -// output, there are no impaired volumes. -func ExampleEC2_DescribeVolumeStatus_shared01() { - svc := ec2.New(session.New()) - input := &ec2.DescribeVolumeStatusInput{ - Filters: []*ec2.Filter{ - { - Name: aws.String("volume-status.status"), - Values: []*string{ - aws.String("impaired"), - }, - }, - }, - } - - result, err := svc.DescribeVolumeStatus(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe all volumes -// -// This example describes all of your volumes in the default region. -func ExampleEC2_DescribeVolumes_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DescribeVolumesInput{} - - result, err := svc.DescribeVolumes(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe volumes that are attached to a specific instance -// -// This example describes all volumes that are both attached to the instance with the -// ID i-1234567890abcdef0 and set to delete when the instance terminates. -func ExampleEC2_DescribeVolumes_shared01() { - svc := ec2.New(session.New()) - input := &ec2.DescribeVolumesInput{ - Filters: []*ec2.Filter{ - { - Name: aws.String("attachment.instance-id"), - Values: []*string{ - aws.String("i-1234567890abcdef0"), - }, - }, - { - Name: aws.String("attachment.delete-on-termination"), - Values: []*string{ - aws.String("true"), - }, - }, - }, - } - - result, err := svc.DescribeVolumes(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe the enableDnsSupport attribute -// -// This example describes the enableDnsSupport attribute. This attribute indicates whether -// DNS resolution is enabled for the VPC. If this attribute is true, the Amazon DNS -// server resolves DNS hostnames for your instances to their corresponding IP addresses; -// otherwise, it does not. -func ExampleEC2_DescribeVpcAttribute_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DescribeVpcAttributeInput{ - Attribute: aws.String("enableDnsSupport"), - VpcId: aws.String("vpc-a01106c2"), - } - - result, err := svc.DescribeVpcAttribute(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe the enableDnsHostnames attribute -// -// This example describes the enableDnsHostnames attribute. This attribute indicates -// whether the instances launched in the VPC get DNS hostnames. If this attribute is -// true, instances in the VPC get DNS hostnames; otherwise, they do not. -func ExampleEC2_DescribeVpcAttribute_shared01() { - svc := ec2.New(session.New()) - input := &ec2.DescribeVpcAttributeInput{ - Attribute: aws.String("enableDnsHostnames"), - VpcId: aws.String("vpc-a01106c2"), - } - - result, err := svc.DescribeVpcAttribute(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe a VPC -// -// This example describes the specified VPC. -func ExampleEC2_DescribeVpcs_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DescribeVpcsInput{ - VpcIds: []*string{ - aws.String("vpc-a01106c2"), - }, - } - - result, err := svc.DescribeVpcs(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To detach an Internet gateway from a VPC -// -// This example detaches the specified Internet gateway from the specified VPC. -func ExampleEC2_DetachInternetGateway_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DetachInternetGatewayInput{ - InternetGatewayId: aws.String("igw-c0a643a9"), - VpcId: aws.String("vpc-a01106c2"), - } - - result, err := svc.DetachInternetGateway(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To detach a network interface from an instance -// -// This example detaches the specified network interface from its attached instance. -func ExampleEC2_DetachNetworkInterface_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DetachNetworkInterfaceInput{ - AttachmentId: aws.String("eni-attach-66c4350a"), - } - - result, err := svc.DetachNetworkInterface(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To detach a volume from an instance -// -// This example detaches the volume (``vol-049df61146c4d7901``) from the instance it -// is attached to. -func ExampleEC2_DetachVolume_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DetachVolumeInput{ - VolumeId: aws.String("vol-1234567890abcdef0"), - } - - result, err := svc.DetachVolume(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To disable route propagation -// -// This example disables the specified virtual private gateway from propagating static -// routes to the specified route table. -func ExampleEC2_DisableVgwRoutePropagation_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DisableVgwRoutePropagationInput{ - GatewayId: aws.String("vgw-9a4cacf3"), - RouteTableId: aws.String("rtb-22574640"), - } - - result, err := svc.DisableVgwRoutePropagation(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To disassociate an Elastic IP address in EC2-VPC -// -// This example disassociates an Elastic IP address from an instance in a VPC. -func ExampleEC2_DisassociateAddress_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DisassociateAddressInput{ - AssociationId: aws.String("eipassoc-2bebb745"), - } - - result, err := svc.DisassociateAddress(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To disassociate an Elastic IP addresses in EC2-Classic -// -// This example disassociates an Elastic IP address from an instance in EC2-Classic. -func ExampleEC2_DisassociateAddress_shared01() { - svc := ec2.New(session.New()) - input := &ec2.DisassociateAddressInput{ - PublicIp: aws.String("198.51.100.0"), - } - - result, err := svc.DisassociateAddress(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To disassociate a route table -// -// This example disassociates the specified route table from its associated subnet. -func ExampleEC2_DisassociateRouteTable_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DisassociateRouteTableInput{ - AssociationId: aws.String("rtbassoc-781d0d1a"), - } - - result, err := svc.DisassociateRouteTable(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To enable route propagation -// -// This example enables the specified virtual private gateway to propagate static routes -// to the specified route table. -func ExampleEC2_EnableVgwRoutePropagation_shared00() { - svc := ec2.New(session.New()) - input := &ec2.EnableVgwRoutePropagationInput{ - GatewayId: aws.String("vgw-9a4cacf3"), - RouteTableId: aws.String("rtb-22574640"), - } - - result, err := svc.EnableVgwRoutePropagation(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To enable I/O for a volume -// -// This example enables I/O on volume ``vol-1234567890abcdef0``. -func ExampleEC2_EnableVolumeIO_shared00() { - svc := ec2.New(session.New()) - input := &ec2.EnableVolumeIOInput{ - VolumeId: aws.String("vol-1234567890abcdef0"), - } - - result, err := svc.EnableVolumeIO(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To modify the attachment attribute of a network interface -// -// This example modifies the attachment attribute of the specified network interface. -func ExampleEC2_ModifyNetworkInterfaceAttribute_shared00() { - svc := ec2.New(session.New()) - input := &ec2.ModifyNetworkInterfaceAttributeInput{ - Attachment: &ec2.NetworkInterfaceAttachmentChanges{ - AttachmentId: aws.String("eni-attach-43348162"), - DeleteOnTermination: aws.Bool(false), - }, - NetworkInterfaceId: aws.String("eni-686ea200"), - } - - result, err := svc.ModifyNetworkInterfaceAttribute(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To modify the description attribute of a network interface -// -// This example modifies the description attribute of the specified network interface. -func ExampleEC2_ModifyNetworkInterfaceAttribute_shared01() { - svc := ec2.New(session.New()) - input := &ec2.ModifyNetworkInterfaceAttributeInput{ - Description: &ec2.AttributeValue{ - Value: aws.String("My description"), - }, - NetworkInterfaceId: aws.String("eni-686ea200"), - } - - result, err := svc.ModifyNetworkInterfaceAttribute(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To modify the groupSet attribute of a network interface -// -// This example command modifies the groupSet attribute of the specified network interface. -func ExampleEC2_ModifyNetworkInterfaceAttribute_shared02() { - svc := ec2.New(session.New()) - input := &ec2.ModifyNetworkInterfaceAttributeInput{ - Groups: []*string{ - aws.String("sg-903004f8"), - aws.String("sg-1a2b3c4d"), - }, - NetworkInterfaceId: aws.String("eni-686ea200"), - } - - result, err := svc.ModifyNetworkInterfaceAttribute(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To modify the sourceDestCheck attribute of a network interface -// -// This example command modifies the sourceDestCheck attribute of the specified network -// interface. -func ExampleEC2_ModifyNetworkInterfaceAttribute_shared03() { - svc := ec2.New(session.New()) - input := &ec2.ModifyNetworkInterfaceAttributeInput{ - NetworkInterfaceId: aws.String("eni-686ea200"), - SourceDestCheck: &ec2.AttributeBooleanValue{ - Value: aws.Bool(false), - }, - } - - result, err := svc.ModifyNetworkInterfaceAttribute(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To modify a snapshot attribute -// -// This example modifies snapshot ``snap-1234567890abcdef0`` to remove the create volume -// permission for a user with the account ID ``123456789012``. If the command succeeds, -// no output is returned. -func ExampleEC2_ModifySnapshotAttribute_shared00() { - svc := ec2.New(session.New()) - input := &ec2.ModifySnapshotAttributeInput{ - Attribute: aws.String("createVolumePermission"), - OperationType: aws.String("remove"), - SnapshotId: aws.String("snap-1234567890abcdef0"), - UserIds: []*string{ - aws.String("123456789012"), - }, - } - - result, err := svc.ModifySnapshotAttribute(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To make a snapshot public -// -// This example makes the snapshot ``snap-1234567890abcdef0`` public. -func ExampleEC2_ModifySnapshotAttribute_shared01() { - svc := ec2.New(session.New()) - input := &ec2.ModifySnapshotAttributeInput{ - Attribute: aws.String("createVolumePermission"), - GroupNames: []*string{ - aws.String("all"), - }, - OperationType: aws.String("add"), - SnapshotId: aws.String("snap-1234567890abcdef0"), - } - - result, err := svc.ModifySnapshotAttribute(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To increase the target capacity of a Spot fleet request -// -// This example increases the target capacity of the specified Spot fleet request. -func ExampleEC2_ModifySpotFleetRequest_shared00() { - svc := ec2.New(session.New()) - input := &ec2.ModifySpotFleetRequestInput{ - SpotFleetRequestId: aws.String("sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE"), - TargetCapacity: aws.Int64(20), - } - - result, err := svc.ModifySpotFleetRequest(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To decrease the target capacity of a Spot fleet request -// -// This example decreases the target capacity of the specified Spot fleet request without -// terminating any Spot Instances as a result. -func ExampleEC2_ModifySpotFleetRequest_shared01() { - svc := ec2.New(session.New()) - input := &ec2.ModifySpotFleetRequestInput{ - ExcessCapacityTerminationPolicy: aws.String("NoTermination "), - SpotFleetRequestId: aws.String("sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE"), - TargetCapacity: aws.Int64(10), - } - - result, err := svc.ModifySpotFleetRequest(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To change a subnet's public IP addressing behavior -// -// This example modifies the specified subnet so that all instances launched into this -// subnet are assigned a public IP address. -func ExampleEC2_ModifySubnetAttribute_shared00() { - svc := ec2.New(session.New()) - input := &ec2.ModifySubnetAttributeInput{ - MapPublicIpOnLaunch: &ec2.AttributeBooleanValue{ - Value: aws.Bool(true), - }, - SubnetId: aws.String("subnet-1a2b3c4d"), - } - - result, err := svc.ModifySubnetAttribute(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To modify a volume attribute -// -// This example sets the ``autoEnableIo`` attribute of the volume with the ID ``vol-1234567890abcdef0`` -// to ``true``. If the command succeeds, no output is returned. -func ExampleEC2_ModifyVolumeAttribute_shared00() { - svc := ec2.New(session.New()) - input := &ec2.ModifyVolumeAttributeInput{ - AutoEnableIO: &ec2.AttributeBooleanValue{ - Value: aws.Bool(true), - }, - DryRun: aws.Bool(true), - VolumeId: aws.String("vol-1234567890abcdef0"), - } - - result, err := svc.ModifyVolumeAttribute(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To modify the enableDnsSupport attribute -// -// This example modifies the enableDnsSupport attribute. This attribute indicates whether -// DNS resolution is enabled for the VPC. If this attribute is true, the Amazon DNS -// server resolves DNS hostnames for instances in the VPC to their corresponding IP -// addresses; otherwise, it does not. -func ExampleEC2_ModifyVpcAttribute_shared00() { - svc := ec2.New(session.New()) - input := &ec2.ModifyVpcAttributeInput{ - EnableDnsSupport: &ec2.AttributeBooleanValue{ - Value: aws.Bool(false), - }, - VpcId: aws.String("vpc-a01106c2"), - } - - result, err := svc.ModifyVpcAttribute(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To modify the enableDnsHostnames attribute -// -// This example modifies the enableDnsHostnames attribute. This attribute indicates -// whether instances launched in the VPC get DNS hostnames. If this attribute is true, -// instances in the VPC get DNS hostnames; otherwise, they do not. -func ExampleEC2_ModifyVpcAttribute_shared01() { - svc := ec2.New(session.New()) - input := &ec2.ModifyVpcAttributeInput{ - EnableDnsHostnames: &ec2.AttributeBooleanValue{ - Value: aws.Bool(false), - }, - VpcId: aws.String("vpc-a01106c2"), - } - - result, err := svc.ModifyVpcAttribute(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To move an address to EC2-VPC -// -// This example moves the specified Elastic IP address to the EC2-VPC platform. -func ExampleEC2_MoveAddressToVpc_shared00() { - svc := ec2.New(session.New()) - input := &ec2.MoveAddressToVpcInput{ - PublicIp: aws.String("54.123.4.56"), - } - - result, err := svc.MoveAddressToVpc(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To purchase a Scheduled Instance -// -// This example purchases a Scheduled Instance. -func ExampleEC2_PurchaseScheduledInstances_shared00() { - svc := ec2.New(session.New()) - input := &ec2.PurchaseScheduledInstancesInput{ - PurchaseRequests: []*ec2.PurchaseRequest{ - { - InstanceCount: aws.Int64(1), - PurchaseToken: aws.String("eyJ2IjoiMSIsInMiOjEsImMiOi..."), - }, - }, - } - - result, err := svc.PurchaseScheduledInstances(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To release an Elastic IP address for EC2-VPC -// -// This example releases an Elastic IP address for use with instances in a VPC. -func ExampleEC2_ReleaseAddress_shared00() { - svc := ec2.New(session.New()) - input := &ec2.ReleaseAddressInput{ - AllocationId: aws.String("eipalloc-64d5890a"), - } - - result, err := svc.ReleaseAddress(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To release an Elastic IP addresses for EC2-Classic -// -// This example releases an Elastic IP address for use with instances in EC2-Classic. -func ExampleEC2_ReleaseAddress_shared01() { - svc := ec2.New(session.New()) - input := &ec2.ReleaseAddressInput{ - PublicIp: aws.String("198.51.100.0"), - } - - result, err := svc.ReleaseAddress(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To replace the network ACL associated with a subnet -// -// This example associates the specified network ACL with the subnet for the specified -// network ACL association. -func ExampleEC2_ReplaceNetworkAclAssociation_shared00() { - svc := ec2.New(session.New()) - input := &ec2.ReplaceNetworkAclAssociationInput{ - AssociationId: aws.String("aclassoc-e5b95c8c"), - NetworkAclId: aws.String("acl-5fb85d36"), - } - - result, err := svc.ReplaceNetworkAclAssociation(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To replace a network ACL entry -// -// This example replaces an entry for the specified network ACL. The new rule 100 allows -// ingress traffic from 203.0.113.12/24 on UDP port 53 (DNS) into any associated subnet. -func ExampleEC2_ReplaceNetworkAclEntry_shared00() { - svc := ec2.New(session.New()) - input := &ec2.ReplaceNetworkAclEntryInput{ - CidrBlock: aws.String("203.0.113.12/24"), - Egress: aws.Bool(false), - NetworkAclId: aws.String("acl-5fb85d36"), - PortRange: &ec2.PortRange{ - From: aws.Int64(53), - To: aws.Int64(53), - }, - Protocol: aws.String("udp"), - RuleAction: aws.String("allow"), - RuleNumber: aws.Int64(100), - } - - result, err := svc.ReplaceNetworkAclEntry(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To replace a route -// -// This example replaces the specified route in the specified table table. The new route -// matches the specified CIDR and sends the traffic to the specified virtual private -// gateway. -func ExampleEC2_ReplaceRoute_shared00() { - svc := ec2.New(session.New()) - input := &ec2.ReplaceRouteInput{ - DestinationCidrBlock: aws.String("10.0.0.0/16"), - GatewayId: aws.String("vgw-9a4cacf3"), - RouteTableId: aws.String("rtb-22574640"), - } - - result, err := svc.ReplaceRoute(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To replace the route table associated with a subnet -// -// This example associates the specified route table with the subnet for the specified -// route table association. -func ExampleEC2_ReplaceRouteTableAssociation_shared00() { - svc := ec2.New(session.New()) - input := &ec2.ReplaceRouteTableAssociationInput{ - AssociationId: aws.String("rtbassoc-781d0d1a"), - RouteTableId: aws.String("rtb-22574640"), - } - - result, err := svc.ReplaceRouteTableAssociation(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To request a Spot fleet in the subnet with the lowest price -// -// This example creates a Spot fleet request with two launch specifications that differ -// only by subnet. The Spot fleet launches the instances in the specified subnet with -// the lowest price. If the instances are launched in a default VPC, they receive a -// public IP address by default. If the instances are launched in a nondefault VPC, -// they do not receive a public IP address by default. Note that you can't specify different -// subnets from the same Availability Zone in a Spot fleet request. -func ExampleEC2_RequestSpotFleet_shared00() { - svc := ec2.New(session.New()) - input := &ec2.RequestSpotFleetInput{ - SpotFleetRequestConfig: &ec2.SpotFleetRequestConfigData{ - IamFleetRole: aws.String("arn:aws:iam::123456789012:role/my-spot-fleet-role"), - LaunchSpecifications: []*ec2.SpotFleetLaunchSpecification{ - { - ImageId: aws.String("ami-1a2b3c4d"), - InstanceType: aws.String("m3.medium"), - KeyName: aws.String("my-key-pair"), - SecurityGroups: []*ec2.GroupIdentifier{ - { - GroupId: aws.String("sg-1a2b3c4d"), - }, - }, - SubnetId: aws.String("subnet-1a2b3c4d, subnet-3c4d5e6f"), - }, - }, - SpotPrice: aws.String("0.04"), - TargetCapacity: aws.Int64(2), - }, - } - - result, err := svc.RequestSpotFleet(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To request a Spot fleet in the Availability Zone with the lowest price -// -// This example creates a Spot fleet request with two launch specifications that differ -// only by Availability Zone. The Spot fleet launches the instances in the specified -// Availability Zone with the lowest price. If your account supports EC2-VPC only, Amazon -// EC2 launches the Spot instances in the default subnet of the Availability Zone. If -// your account supports EC2-Classic, Amazon EC2 launches the instances in EC2-Classic -// in the Availability Zone. -func ExampleEC2_RequestSpotFleet_shared01() { - svc := ec2.New(session.New()) - input := &ec2.RequestSpotFleetInput{ - SpotFleetRequestConfig: &ec2.SpotFleetRequestConfigData{ - IamFleetRole: aws.String("arn:aws:iam::123456789012:role/my-spot-fleet-role"), - LaunchSpecifications: []*ec2.SpotFleetLaunchSpecification{ - { - ImageId: aws.String("ami-1a2b3c4d"), - InstanceType: aws.String("m3.medium"), - KeyName: aws.String("my-key-pair"), - SecurityGroups: []*ec2.GroupIdentifier{ - { - GroupId: aws.String("sg-1a2b3c4d"), - }, - }, - }, - }, - SpotPrice: aws.String("0.04"), - TargetCapacity: aws.Int64(2), - }, - } - - result, err := svc.RequestSpotFleet(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To launch Spot instances in a subnet and assign them public IP addresses -// -// This example assigns public addresses to instances launched in a nondefault VPC. -// Note that when you specify a network interface, you must include the subnet ID and -// security group ID using the network interface. -func ExampleEC2_RequestSpotFleet_shared02() { - svc := ec2.New(session.New()) - input := &ec2.RequestSpotFleetInput{ - SpotFleetRequestConfig: &ec2.SpotFleetRequestConfigData{ - IamFleetRole: aws.String("arn:aws:iam::123456789012:role/my-spot-fleet-role"), - LaunchSpecifications: []*ec2.SpotFleetLaunchSpecification{ - { - ImageId: aws.String("ami-1a2b3c4d"), - InstanceType: aws.String("m3.medium"), - KeyName: aws.String("my-key-pair"), - NetworkInterfaces: []*ec2.InstanceNetworkInterfaceSpecification{ - { - AssociatePublicIpAddress: aws.Bool(true), - DeviceIndex: aws.Int64(0), - Groups: []*string{ - aws.String("sg-1a2b3c4d"), - }, - SubnetId: aws.String("subnet-1a2b3c4d"), - }, - }, - }, - }, - SpotPrice: aws.String("0.04"), - TargetCapacity: aws.Int64(2), - }, - } - - result, err := svc.RequestSpotFleet(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To request a Spot fleet using the diversified allocation strategy -// -// This example creates a Spot fleet request that launches 30 instances using the diversified -// allocation strategy. The launch specifications differ by instance type. The Spot -// fleet distributes the instances across the launch specifications such that there -// are 10 instances of each type. -func ExampleEC2_RequestSpotFleet_shared03() { - svc := ec2.New(session.New()) - input := &ec2.RequestSpotFleetInput{ - SpotFleetRequestConfig: &ec2.SpotFleetRequestConfigData{ - AllocationStrategy: aws.String("diversified"), - IamFleetRole: aws.String("arn:aws:iam::123456789012:role/my-spot-fleet-role"), - LaunchSpecifications: []*ec2.SpotFleetLaunchSpecification{ - { - ImageId: aws.String("ami-1a2b3c4d"), - InstanceType: aws.String("c4.2xlarge"), - SubnetId: aws.String("subnet-1a2b3c4d"), - }, - { - ImageId: aws.String("ami-1a2b3c4d"), - InstanceType: aws.String("m3.2xlarge"), - SubnetId: aws.String("subnet-1a2b3c4d"), - }, - { - ImageId: aws.String("ami-1a2b3c4d"), - InstanceType: aws.String("r3.2xlarge"), - SubnetId: aws.String("subnet-1a2b3c4d"), - }, - }, - SpotPrice: aws.String("0.70"), - TargetCapacity: aws.Int64(30), - }, - } - - result, err := svc.RequestSpotFleet(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To create a one-time Spot Instance request -// -// This example creates a one-time Spot Instance request for five instances in the specified -// Availability Zone. If your account supports EC2-VPC only, Amazon EC2 launches the -// instances in the default subnet of the specified Availability Zone. If your account -// supports EC2-Classic, Amazon EC2 launches the instances in EC2-Classic in the specified -// Availability Zone. -func ExampleEC2_RequestSpotInstances_shared00() { - svc := ec2.New(session.New()) - input := &ec2.RequestSpotInstancesInput{ - InstanceCount: aws.Int64(5), - LaunchSpecification: &ec2.RequestSpotLaunchSpecification{ - IamInstanceProfile: &ec2.IamInstanceProfileSpecification{ - Arn: aws.String("arn:aws:iam::123456789012:instance-profile/my-iam-role"), - }, - ImageId: aws.String("ami-1a2b3c4d"), - InstanceType: aws.String("m3.medium"), - KeyName: aws.String("my-key-pair"), - Placement: &ec2.SpotPlacement{ - AvailabilityZone: aws.String("us-west-2a"), - }, - SecurityGroupIds: []*string{ - aws.String("sg-1a2b3c4d"), - }, - }, - SpotPrice: aws.String("0.03"), - Type: aws.String("one-time"), - } - - result, err := svc.RequestSpotInstances(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To create a one-time Spot Instance request -// -// This example command creates a one-time Spot Instance request for five instances -// in the specified subnet. Amazon EC2 launches the instances in the specified subnet. -// If the VPC is a nondefault VPC, the instances do not receive a public IP address -// by default. -func ExampleEC2_RequestSpotInstances_shared01() { - svc := ec2.New(session.New()) - input := &ec2.RequestSpotInstancesInput{ - InstanceCount: aws.Int64(5), - LaunchSpecification: &ec2.RequestSpotLaunchSpecification{ - IamInstanceProfile: &ec2.IamInstanceProfileSpecification{ - Arn: aws.String("arn:aws:iam::123456789012:instance-profile/my-iam-role"), - }, - ImageId: aws.String("ami-1a2b3c4d"), - InstanceType: aws.String("m3.medium"), - SecurityGroupIds: []*string{ - aws.String("sg-1a2b3c4d"), - }, - SubnetId: aws.String("subnet-1a2b3c4d"), - }, - SpotPrice: aws.String("0.050"), - Type: aws.String("one-time"), - } - - result, err := svc.RequestSpotInstances(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To reset a snapshot attribute -// -// This example resets the create volume permissions for snapshot ``snap-1234567890abcdef0``. -// If the command succeeds, no output is returned. -func ExampleEC2_ResetSnapshotAttribute_shared00() { - svc := ec2.New(session.New()) - input := &ec2.ResetSnapshotAttributeInput{ - Attribute: aws.String("createVolumePermission"), - SnapshotId: aws.String("snap-1234567890abcdef0"), - } - - result, err := svc.ResetSnapshotAttribute(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To restore an address to EC2-Classic -// -// This example restores the specified Elastic IP address to the EC2-Classic platform. -func ExampleEC2_RestoreAddressToClassic_shared00() { - svc := ec2.New(session.New()) - input := &ec2.RestoreAddressToClassicInput{ - PublicIp: aws.String("198.51.100.0"), - } - - result, err := svc.RestoreAddressToClassic(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To launch a Scheduled Instance in a VPC -// -// This example launches the specified Scheduled Instance in a VPC. -func ExampleEC2_RunScheduledInstances_shared00() { - svc := ec2.New(session.New()) - input := &ec2.RunScheduledInstancesInput{ - InstanceCount: aws.Int64(1), - LaunchSpecification: &ec2.ScheduledInstancesLaunchSpecification{ - IamInstanceProfile: &ec2.ScheduledInstancesIamInstanceProfile{ - Name: aws.String("my-iam-role"), - }, - ImageId: aws.String("ami-12345678"), - InstanceType: aws.String("c4.large"), - KeyName: aws.String("my-key-pair"), - NetworkInterfaces: []*ec2.ScheduledInstancesNetworkInterface{ - { - AssociatePublicIpAddress: aws.Bool(true), - DeviceIndex: aws.Int64(0), - Groups: []*string{ - aws.String("sg-12345678"), - }, - SubnetId: aws.String("subnet-12345678"), - }, - }, - }, - ScheduledInstanceId: aws.String("sci-1234-1234-1234-1234-123456789012"), - } - - result, err := svc.RunScheduledInstances(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To launch a Scheduled Instance in EC2-Classic -// -// This example launches the specified Scheduled Instance in EC2-Classic. -func ExampleEC2_RunScheduledInstances_shared01() { - svc := ec2.New(session.New()) - input := &ec2.RunScheduledInstancesInput{ - InstanceCount: aws.Int64(1), - LaunchSpecification: &ec2.ScheduledInstancesLaunchSpecification{ - IamInstanceProfile: &ec2.ScheduledInstancesIamInstanceProfile{ - Name: aws.String("my-iam-role"), - }, - ImageId: aws.String("ami-12345678"), - InstanceType: aws.String("c4.large"), - KeyName: aws.String("my-key-pair"), - Placement: &ec2.ScheduledInstancesPlacement{ - AvailabilityZone: aws.String("us-west-2b"), - }, - SecurityGroupIds: []*string{ - aws.String("sg-12345678"), - }, - }, - ScheduledInstanceId: aws.String("sci-1234-1234-1234-1234-123456789012"), - } - - result, err := svc.RunScheduledInstances(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To unassign a secondary private IP address from a network interface -// -// This example unassigns the specified private IP address from the specified network -// interface. -func ExampleEC2_UnassignPrivateIpAddresses_shared00() { - svc := ec2.New(session.New()) - input := &ec2.UnassignPrivateIpAddressesInput{ - NetworkInterfaceId: aws.String("eni-e5aa89a3"), - PrivateIpAddresses: []*string{ - aws.String("10.0.0.82"), - }, - } - - result, err := svc.UnassignPrivateIpAddresses(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} diff --git a/vendor/github.com/aws/aws-sdk-go/service/generate.go b/vendor/github.com/aws/aws-sdk-go/service/generate.go deleted file mode 100644 index 3ffc9fcc5..000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/generate.go +++ /dev/null @@ -1,5 +0,0 @@ -// Package service contains automatically generated AWS clients. -package service - -//go:generate go run -tags codegen ../private/model/cli/gen-api/main.go -path=../service ../models/apis/*/*/api-2.json -//go:generate gofmt -s -w ../service diff --git a/vendor/github.com/aws/aws-sdk-go/service/sts/customizations_test.go b/vendor/github.com/aws/aws-sdk-go/service/sts/customizations_test.go deleted file mode 100644 index 18972b1f5..000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/sts/customizations_test.go +++ /dev/null @@ -1,45 +0,0 @@ -package sts_test - -import ( - "testing" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/awstesting/unit" - "github.com/aws/aws-sdk-go/service/sts" -) - -var svc = sts.New(unit.Session, &aws.Config{ - Region: aws.String("mock-region"), -}) - -func TestUnsignedRequest_AssumeRoleWithSAML(t *testing.T) { - req, _ := svc.AssumeRoleWithSAMLRequest(&sts.AssumeRoleWithSAMLInput{ - PrincipalArn: aws.String("ARN01234567890123456789"), - RoleArn: aws.String("ARN01234567890123456789"), - SAMLAssertion: aws.String("ASSERT"), - }) - - err := req.Sign() - if err != nil { - t.Errorf("expect no error, got %v", err) - } - if e, a := "", req.HTTPRequest.Header.Get("Authorization"); e != a { - t.Errorf("expect %v, got %v", e, a) - } -} - -func TestUnsignedRequest_AssumeRoleWithWebIdentity(t *testing.T) { - req, _ := svc.AssumeRoleWithWebIdentityRequest(&sts.AssumeRoleWithWebIdentityInput{ - RoleArn: aws.String("ARN01234567890123456789"), - RoleSessionName: aws.String("SESSION"), - WebIdentityToken: aws.String("TOKEN"), - }) - - err := req.Sign() - if err != nil { - t.Errorf("expect no error, got %v", err) - } - if e, a := "", req.HTTPRequest.Header.Get("Authorization"); e != a { - t.Errorf("expect %v, got %v", e, a) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/service/sts/examples_test.go b/vendor/github.com/aws/aws-sdk-go/service/sts/examples_test.go deleted file mode 100644 index d61a9932b..000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/sts/examples_test.go +++ /dev/null @@ -1,282 +0,0 @@ -// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. - -package sts_test - -import ( - "fmt" - "strings" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/sts" -) - -var _ time.Duration -var _ strings.Reader -var _ aws.Config - -func parseTime(layout, value string) *time.Time { - t, err := time.Parse(layout, value) - if err != nil { - panic(err) - } - return &t -} - -// To assume a role -// - -func ExampleSTS_AssumeRole_shared00() { - svc := sts.New(session.New()) - input := &sts.AssumeRoleInput{ - DurationSeconds: aws.Int64(3600), - ExternalId: aws.String("123ABC"), - Policy: aws.String("{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"Stmt1\",\"Effect\":\"Allow\",\"Action\":\"s3:*\",\"Resource\":\"*\"}]}"), - RoleArn: aws.String("arn:aws:iam::123456789012:role/demo"), - RoleSessionName: aws.String("Bob"), - } - - result, err := svc.AssumeRole(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case sts.ErrCodeMalformedPolicyDocumentException: - fmt.Println(sts.ErrCodeMalformedPolicyDocumentException, aerr.Error()) - case sts.ErrCodePackedPolicyTooLargeException: - fmt.Println(sts.ErrCodePackedPolicyTooLargeException, aerr.Error()) - case sts.ErrCodeRegionDisabledException: - fmt.Println(sts.ErrCodeRegionDisabledException, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To assume a role as an OpenID Connect-federated user -// - -func ExampleSTS_AssumeRoleWithWebIdentity_shared00() { - svc := sts.New(session.New()) - input := &sts.AssumeRoleWithWebIdentityInput{ - DurationSeconds: aws.Int64(3600), - ProviderId: aws.String("www.amazon.com"), - RoleArn: aws.String("arn:aws:iam::123456789012:role/FederatedWebIdentityRole"), - RoleSessionName: aws.String("app1"), - WebIdentityToken: aws.String("Atza%7CIQEBLjAsAhRFiXuWpUXuRvQ9PZL3GMFcYevydwIUFAHZwXZXXXXXXXXJnrulxKDHwy87oGKPznh0D6bEQZTSCzyoCtL_8S07pLpr0zMbn6w1lfVZKNTBdDansFBmtGnIsIapjI6xKR02Yc_2bQ8LZbUXSGm6Ry6_BG7PrtLZtj_dfCTj92xNGed-CrKqjG7nPBjNIL016GGvuS5gSvPRUxWES3VYfm1wl7WTI7jn-Pcb6M-buCgHhFOzTQxod27L9CqnOLio7N3gZAGpsp6n1-AJBOCJckcyXe2c6uD0srOJeZlKUm2eTDVMf8IehDVI0r1QOnTV6KzzAI3OY87Vd_cVMQ"), - } - - result, err := svc.AssumeRoleWithWebIdentity(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case sts.ErrCodeMalformedPolicyDocumentException: - fmt.Println(sts.ErrCodeMalformedPolicyDocumentException, aerr.Error()) - case sts.ErrCodePackedPolicyTooLargeException: - fmt.Println(sts.ErrCodePackedPolicyTooLargeException, aerr.Error()) - case sts.ErrCodeIDPRejectedClaimException: - fmt.Println(sts.ErrCodeIDPRejectedClaimException, aerr.Error()) - case sts.ErrCodeIDPCommunicationErrorException: - fmt.Println(sts.ErrCodeIDPCommunicationErrorException, aerr.Error()) - case sts.ErrCodeInvalidIdentityTokenException: - fmt.Println(sts.ErrCodeInvalidIdentityTokenException, aerr.Error()) - case sts.ErrCodeExpiredTokenException: - fmt.Println(sts.ErrCodeExpiredTokenException, aerr.Error()) - case sts.ErrCodeRegionDisabledException: - fmt.Println(sts.ErrCodeRegionDisabledException, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To decode information about an authorization status of a request -// - -func ExampleSTS_DecodeAuthorizationMessage_shared00() { - svc := sts.New(session.New()) - input := &sts.DecodeAuthorizationMessageInput{ - EncodedMessage: aws.String(""), - } - - result, err := svc.DecodeAuthorizationMessage(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case sts.ErrCodeInvalidAuthorizationMessageException: - fmt.Println(sts.ErrCodeInvalidAuthorizationMessageException, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To get details about a calling IAM user -// -// This example shows a request and response made with the credentials for a user named -// Alice in the AWS account 123456789012. -func ExampleSTS_GetCallerIdentity_shared00() { - svc := sts.New(session.New()) - input := &sts.GetCallerIdentityInput{} - - result, err := svc.GetCallerIdentity(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To get details about a calling user federated with AssumeRole -// -// This example shows a request and response made with temporary credentials created -// by AssumeRole. The name of the assumed role is my-role-name, and the RoleSessionName -// is set to my-role-session-name. -func ExampleSTS_GetCallerIdentity_shared01() { - svc := sts.New(session.New()) - input := &sts.GetCallerIdentityInput{} - - result, err := svc.GetCallerIdentity(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To get details about a calling user federated with GetFederationToken -// -// This example shows a request and response made with temporary credentials created -// by using GetFederationToken. The Name parameter is set to my-federated-user-name. -func ExampleSTS_GetCallerIdentity_shared02() { - svc := sts.New(session.New()) - input := &sts.GetCallerIdentityInput{} - - result, err := svc.GetCallerIdentity(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To get temporary credentials for a role by using GetFederationToken -// - -func ExampleSTS_GetFederationToken_shared00() { - svc := sts.New(session.New()) - input := &sts.GetFederationTokenInput{ - DurationSeconds: aws.Int64(3600), - Name: aws.String("Bob"), - Policy: aws.String("{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"Stmt1\",\"Effect\":\"Allow\",\"Action\":\"s3:*\",\"Resource\":\"*\"}]}"), - } - - result, err := svc.GetFederationToken(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case sts.ErrCodeMalformedPolicyDocumentException: - fmt.Println(sts.ErrCodeMalformedPolicyDocumentException, aerr.Error()) - case sts.ErrCodePackedPolicyTooLargeException: - fmt.Println(sts.ErrCodePackedPolicyTooLargeException, aerr.Error()) - case sts.ErrCodeRegionDisabledException: - fmt.Println(sts.ErrCodeRegionDisabledException, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To get temporary credentials for an IAM user or an AWS account -// - -func ExampleSTS_GetSessionToken_shared00() { - svc := sts.New(session.New()) - input := &sts.GetSessionTokenInput{ - DurationSeconds: aws.Int64(3600), - SerialNumber: aws.String("YourMFASerialNumber"), - TokenCode: aws.String("123456"), - } - - result, err := svc.GetSessionToken(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case sts.ErrCodeRegionDisabledException: - fmt.Println(sts.ErrCodeRegionDisabledException, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} diff --git a/vendor/github.com/beorn7/perks/.gitignore b/vendor/github.com/beorn7/perks/.gitignore deleted file mode 100644 index 1bd9209aa..000000000 --- a/vendor/github.com/beorn7/perks/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -*.test -*.prof diff --git a/vendor/github.com/beorn7/perks/README.md b/vendor/github.com/beorn7/perks/README.md deleted file mode 100644 index fc0577770..000000000 --- a/vendor/github.com/beorn7/perks/README.md +++ /dev/null @@ -1,31 +0,0 @@ -# Perks for Go (golang.org) - -Perks contains the Go package quantile that computes approximate quantiles over -an unbounded data stream within low memory and CPU bounds. - -For more information and examples, see: -http://godoc.org/github.com/bmizerany/perks - -A very special thank you and shout out to Graham Cormode (Rutgers University), -Flip Korn (AT&T Labs–Research), S. Muthukrishnan (Rutgers University), and -Divesh Srivastava (AT&T Labs–Research) for their research and publication of -[Effective Computation of Biased Quantiles over Data Streams](http://www.cs.rutgers.edu/~muthu/bquant.pdf) - -Thank you, also: -* Armon Dadgar (@armon) -* Andrew Gerrand (@nf) -* Brad Fitzpatrick (@bradfitz) -* Keith Rarick (@kr) - -FAQ: - -Q: Why not move the quantile package into the project root? -A: I want to add more packages to perks later. - -Copyright (C) 2013 Blake Mizerany - -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/beorn7/perks/quantile/bench_test.go b/vendor/github.com/beorn7/perks/quantile/bench_test.go deleted file mode 100644 index 0bd0e4e77..000000000 --- a/vendor/github.com/beorn7/perks/quantile/bench_test.go +++ /dev/null @@ -1,63 +0,0 @@ -package quantile - -import ( - "testing" -) - -func BenchmarkInsertTargeted(b *testing.B) { - b.ReportAllocs() - - s := NewTargeted(Targets) - b.ResetTimer() - for i := float64(0); i < float64(b.N); i++ { - s.Insert(i) - } -} - -func BenchmarkInsertTargetedSmallEpsilon(b *testing.B) { - s := NewTargeted(TargetsSmallEpsilon) - b.ResetTimer() - for i := float64(0); i < float64(b.N); i++ { - s.Insert(i) - } -} - -func BenchmarkInsertBiased(b *testing.B) { - s := NewLowBiased(0.01) - b.ResetTimer() - for i := float64(0); i < float64(b.N); i++ { - s.Insert(i) - } -} - -func BenchmarkInsertBiasedSmallEpsilon(b *testing.B) { - s := NewLowBiased(0.0001) - b.ResetTimer() - for i := float64(0); i < float64(b.N); i++ { - s.Insert(i) - } -} - -func BenchmarkQuery(b *testing.B) { - s := NewTargeted(Targets) - for i := float64(0); i < 1e6; i++ { - s.Insert(i) - } - b.ResetTimer() - n := float64(b.N) - for i := float64(0); i < n; i++ { - s.Query(i / n) - } -} - -func BenchmarkQuerySmallEpsilon(b *testing.B) { - s := NewTargeted(TargetsSmallEpsilon) - for i := float64(0); i < 1e6; i++ { - s.Insert(i) - } - b.ResetTimer() - n := float64(b.N) - for i := float64(0); i < n; i++ { - s.Query(i / n) - } -} diff --git a/vendor/github.com/beorn7/perks/quantile/example_test.go b/vendor/github.com/beorn7/perks/quantile/example_test.go deleted file mode 100644 index ab3293aaf..000000000 --- a/vendor/github.com/beorn7/perks/quantile/example_test.go +++ /dev/null @@ -1,121 +0,0 @@ -// +build go1.1 - -package quantile_test - -import ( - "bufio" - "fmt" - "log" - "os" - "strconv" - "time" - - "github.com/beorn7/perks/quantile" -) - -func Example_simple() { - ch := make(chan float64) - go sendFloats(ch) - - // Compute the 50th, 90th, and 99th percentile. - q := quantile.NewTargeted(map[float64]float64{ - 0.50: 0.005, - 0.90: 0.001, - 0.99: 0.0001, - }) - for v := range ch { - q.Insert(v) - } - - fmt.Println("perc50:", q.Query(0.50)) - fmt.Println("perc90:", q.Query(0.90)) - fmt.Println("perc99:", q.Query(0.99)) - fmt.Println("count:", q.Count()) - // Output: - // perc50: 5 - // perc90: 16 - // perc99: 223 - // count: 2388 -} - -func Example_mergeMultipleStreams() { - // Scenario: - // We have multiple database shards. On each shard, there is a process - // collecting query response times from the database logs and inserting - // them into a Stream (created via NewTargeted(0.90)), much like the - // Simple example. These processes expose a network interface for us to - // ask them to serialize and send us the results of their - // Stream.Samples so we may Merge and Query them. - // - // NOTES: - // * These sample sets are small, allowing us to get them - // across the network much faster than sending the entire list of data - // points. - // - // * For this to work correctly, we must supply the same quantiles - // a priori the process collecting the samples supplied to NewTargeted, - // even if we do not plan to query them all here. - ch := make(chan quantile.Samples) - getDBQuerySamples(ch) - q := quantile.NewTargeted(map[float64]float64{0.90: 0.001}) - for samples := range ch { - q.Merge(samples) - } - fmt.Println("perc90:", q.Query(0.90)) -} - -func Example_window() { - // Scenario: We want the 90th, 95th, and 99th percentiles for each - // minute. - - ch := make(chan float64) - go sendStreamValues(ch) - - tick := time.NewTicker(1 * time.Minute) - q := quantile.NewTargeted(map[float64]float64{ - 0.90: 0.001, - 0.95: 0.0005, - 0.99: 0.0001, - }) - for { - select { - case t := <-tick.C: - flushToDB(t, q.Samples()) - q.Reset() - case v := <-ch: - q.Insert(v) - } - } -} - -func sendStreamValues(ch chan float64) { - // Use your imagination -} - -func flushToDB(t time.Time, samples quantile.Samples) { - // Use your imagination -} - -// This is a stub for the above example. In reality this would hit the remote -// servers via http or something like it. -func getDBQuerySamples(ch chan quantile.Samples) {} - -func sendFloats(ch chan<- float64) { - f, err := os.Open("exampledata.txt") - if err != nil { - log.Fatal(err) - } - sc := bufio.NewScanner(f) - for sc.Scan() { - b := sc.Bytes() - v, err := strconv.ParseFloat(string(b), 64) - if err != nil { - log.Fatal(err) - } - ch <- v - } - if sc.Err() != nil { - log.Fatal(sc.Err()) - } - close(ch) -} diff --git a/vendor/github.com/beorn7/perks/quantile/exampledata.txt b/vendor/github.com/beorn7/perks/quantile/exampledata.txt deleted file mode 100644 index 1602287d7..000000000 --- a/vendor/github.com/beorn7/perks/quantile/exampledata.txt +++ /dev/null @@ -1,2388 +0,0 @@ -8 -5 -26 -12 -5 -235 -13 -6 -28 -30 -3 -3 -3 -3 -5 -2 -33 -7 -2 -4 -7 -12 -14 -5 -8 -3 -10 -4 -5 -3 -6 -6 -209 -20 -3 -10 -14 -3 -4 -6 -8 -5 -11 -7 -3 -2 -3 -3 -212 -5 -222 -4 -10 -10 -5 -6 -3 -8 -3 -10 -254 -220 -2 -3 -5 -24 -5 -4 -222 -7 -3 -3 -223 -8 -15 -12 -14 -14 -3 -2 -2 -3 -13 -3 -11 -4 -4 -6 -5 -7 -13 -5 -3 -5 -2 -5 -3 -5 -2 -7 -15 -17 -14 -3 -6 -6 -3 -17 -5 -4 -7 -6 -4 -4 -8 -6 -8 -3 -9 -3 -6 -3 -4 -5 -3 -3 -660 -4 -6 -10 -3 -6 -3 -2 -5 -13 -2 -4 -4 -10 -4 -8 -4 -3 -7 -9 -9 -3 -10 -37 -3 -13 -4 -12 -3 -6 -10 -8 -5 -21 -2 -3 -8 -3 -2 -3 -3 -4 -12 -2 -4 -8 -8 -4 -3 -2 -20 -1 -6 -32 -2 -11 -6 -18 -3 -8 -11 -3 -212 -3 -4 -2 -6 -7 -12 -11 -3 -2 -16 -10 -6 -4 -6 -3 -2 -7 -3 -2 -2 -2 -2 -5 -6 -4 -3 -10 -3 -4 -6 -5 -3 -4 -4 -5 -6 -4 -3 -4 -4 -5 -7 -5 -5 -3 -2 -7 -2 -4 -12 -4 -5 -6 -2 -4 -4 -8 -4 -15 -13 -7 -16 -5 -3 -23 -5 -5 -7 -3 -2 -9 -8 -7 -5 -8 -11 -4 -10 -76 -4 -47 -4 -3 -2 -7 -4 -2 -3 -37 -10 -4 -2 -20 -5 -4 -4 -10 -10 -4 -3 -7 -23 -240 -7 -13 -5 -5 -3 -3 -2 -5 -4 -2 -8 -7 -19 -2 -23 -8 -7 -2 -5 -3 -8 -3 -8 -13 -5 -5 -5 -2 -3 -23 -4 -9 -8 -4 -3 -3 -5 -220 -2 -3 -4 -6 -14 -3 -53 -6 -2 -5 -18 -6 -3 -219 -6 -5 -2 -5 -3 -6 -5 -15 -4 -3 -17 -3 -2 -4 -7 -2 -3 -3 -4 -4 -3 -2 -664 -6 -3 -23 -5 -5 -16 -5 -8 -2 -4 -2 -24 -12 -3 -2 -3 -5 -8 -3 -5 -4 -3 -14 -3 -5 -8 -2 -3 -7 -9 -4 -2 -3 -6 -8 -4 -3 -4 -6 -5 -3 -3 -6 -3 -19 -4 -4 -6 -3 -6 -3 -5 -22 -5 -4 -4 -3 -8 -11 -4 -9 -7 -6 -13 -4 -4 -4 -6 -17 -9 -3 -3 -3 -4 -3 -221 -5 -11 -3 -4 -2 -12 -6 -3 -5 -7 -5 -7 -4 -9 -7 -14 -37 -19 -217 -16 -3 -5 -2 -2 -7 -19 -7 -6 -7 -4 -24 -5 -11 -4 -7 -7 -9 -13 -3 -4 -3 -6 -28 -4 -4 -5 -5 -2 -5 -6 -4 -4 -6 -10 -5 -4 -3 -2 -3 -3 -6 -5 -5 -4 -3 -2 -3 -7 -4 -6 -18 -16 -8 -16 -4 -5 -8 -6 -9 -13 -1545 -6 -215 -6 -5 -6 -3 -45 -31 -5 -2 -2 -4 -3 -3 -2 -5 -4 -3 -5 -7 -7 -4 -5 -8 -5 -4 -749 -2 -31 -9 -11 -2 -11 -5 -4 -4 -7 -9 -11 -4 -5 -4 -7 -3 -4 -6 -2 -15 -3 -4 -3 -4 -3 -5 -2 -13 -5 -5 -3 -3 -23 -4 -4 -5 -7 -4 -13 -2 -4 -3 -4 -2 -6 -2 -7 -3 -5 -5 -3 -29 -5 -4 -4 -3 -10 -2 -3 -79 -16 -6 -6 -7 -7 -3 -5 -5 -7 -4 -3 -7 -9 -5 -6 -5 -9 -6 -3 -6 -4 -17 -2 -10 -9 -3 -6 -2 -3 -21 -22 -5 -11 -4 -2 -17 -2 -224 -2 -14 -3 -4 -4 -2 -4 -4 -4 -4 -5 -3 -4 -4 -10 -2 -6 -3 -3 -5 -7 -2 -7 -5 -6 -3 -218 -2 -2 -5 -2 -6 -3 -5 -222 -14 -6 -33 -3 -2 -5 -3 -3 -3 -9 -5 -3 -3 -2 -7 -4 -3 -4 -3 -5 -6 -5 -26 -4 -13 -9 -7 -3 -221 -3 -3 -4 -4 -4 -4 -2 -18 -5 -3 -7 -9 -6 -8 -3 -10 -3 -11 -9 -5 -4 -17 -5 -5 -6 -6 -3 -2 -4 -12 -17 -6 -7 -218 -4 -2 -4 -10 -3 -5 -15 -3 -9 -4 -3 -3 -6 -29 -3 -3 -4 -5 -5 -3 -8 -5 -6 -6 -7 -5 -3 -5 -3 -29 -2 -31 -5 -15 -24 -16 -5 -207 -4 -3 -3 -2 -15 -4 -4 -13 -5 -5 -4 -6 -10 -2 -7 -8 -4 -6 -20 -5 -3 -4 -3 -12 -12 -5 -17 -7 -3 -3 -3 -6 -10 -3 -5 -25 -80 -4 -9 -3 -2 -11 -3 -3 -2 -3 -8 -7 -5 -5 -19 -5 -3 -3 -12 -11 -2 -6 -5 -5 -5 -3 -3 -3 -4 -209 -14 -3 -2 -5 -19 -4 -4 -3 -4 -14 -5 -6 -4 -13 -9 -7 -4 -7 -10 -2 -9 -5 -7 -2 -8 -4 -6 -5 -5 -222 -8 -7 -12 -5 -216 -3 -4 -4 -6 -3 -14 -8 -7 -13 -4 -3 -3 -3 -3 -17 -5 -4 -3 -33 -6 -6 -33 -7 -5 -3 -8 -7 -5 -2 -9 -4 -2 -233 -24 -7 -4 -8 -10 -3 -4 -15 -2 -16 -3 -3 -13 -12 -7 -5 -4 -207 -4 -2 -4 -27 -15 -2 -5 -2 -25 -6 -5 -5 -6 -13 -6 -18 -6 -4 -12 -225 -10 -7 -5 -2 -2 -11 -4 -14 -21 -8 -10 -3 -5 -4 -232 -2 -5 -5 -3 -7 -17 -11 -6 -6 -23 -4 -6 -3 -5 -4 -2 -17 -3 -6 -5 -8 -3 -2 -2 -14 -9 -4 -4 -2 -5 -5 -3 -7 -6 -12 -6 -10 -3 -6 -2 -2 -19 -5 -4 -4 -9 -2 -4 -13 -3 -5 -6 -3 -6 -5 -4 -9 -6 -3 -5 -7 -3 -6 -6 -4 -3 -10 -6 -3 -221 -3 -5 -3 -6 -4 -8 -5 -3 -6 -4 -4 -2 -54 -5 -6 -11 -3 -3 -4 -4 -4 -3 -7 -3 -11 -11 -7 -10 -6 -13 -223 -213 -15 -231 -7 -3 -7 -228 -2 -3 -4 -4 -5 -6 -7 -4 -13 -3 -4 -5 -3 -6 -4 -6 -7 -2 -4 -3 -4 -3 -3 -6 -3 -7 -3 -5 -18 -5 -6 -8 -10 -3 -3 -3 -2 -4 -2 -4 -4 -5 -6 -6 -4 -10 -13 -3 -12 -5 -12 -16 -8 -4 -19 -11 -2 -4 -5 -6 -8 -5 -6 -4 -18 -10 -4 -2 -216 -6 -6 -6 -2 -4 -12 -8 -3 -11 -5 -6 -14 -5 -3 -13 -4 -5 -4 -5 -3 -28 -6 -3 -7 -219 -3 -9 -7 -3 -10 -6 -3 -4 -19 -5 -7 -11 -6 -15 -19 -4 -13 -11 -3 -7 -5 -10 -2 -8 -11 -2 -6 -4 -6 -24 -6 -3 -3 -3 -3 -6 -18 -4 -11 -4 -2 -5 -10 -8 -3 -9 -5 -3 -4 -5 -6 -2 -5 -7 -4 -4 -14 -6 -4 -4 -5 -5 -7 -2 -4 -3 -7 -3 -3 -6 -4 -5 -4 -4 -4 -3 -3 -3 -3 -8 -14 -2 -3 -5 -3 -2 -4 -5 -3 -7 -3 -3 -18 -3 -4 -4 -5 -7 -3 -3 -3 -13 -5 -4 -8 -211 -5 -5 -3 -5 -2 -5 -4 -2 -655 -6 -3 -5 -11 -2 -5 -3 -12 -9 -15 -11 -5 -12 -217 -2 -6 -17 -3 -3 -207 -5 -5 -4 -5 -9 -3 -2 -8 -5 -4 -3 -2 -5 -12 -4 -14 -5 -4 -2 -13 -5 -8 -4 -225 -4 -3 -4 -5 -4 -3 -3 -6 -23 -9 -2 -6 -7 -233 -4 -4 -6 -18 -3 -4 -6 -3 -4 -4 -2 -3 -7 -4 -13 -227 -4 -3 -5 -4 -2 -12 -9 -17 -3 -7 -14 -6 -4 -5 -21 -4 -8 -9 -2 -9 -25 -16 -3 -6 -4 -7 -8 -5 -2 -3 -5 -4 -3 -3 -5 -3 -3 -3 -2 -3 -19 -2 -4 -3 -4 -2 -3 -4 -4 -2 -4 -3 -3 -3 -2 -6 -3 -17 -5 -6 -4 -3 -13 -5 -3 -3 -3 -4 -9 -4 -2 -14 -12 -4 -5 -24 -4 -3 -37 -12 -11 -21 -3 -4 -3 -13 -4 -2 -3 -15 -4 -11 -4 -4 -3 -8 -3 -4 -4 -12 -8 -5 -3 -3 -4 -2 -220 -3 -5 -223 -3 -3 -3 -10 -3 -15 -4 -241 -9 -7 -3 -6 -6 -23 -4 -13 -7 -3 -4 -7 -4 -9 -3 -3 -4 -10 -5 -5 -1 -5 -24 -2 -4 -5 -5 -6 -14 -3 -8 -2 -3 -5 -13 -13 -3 -5 -2 -3 -15 -3 -4 -2 -10 -4 -4 -4 -5 -5 -3 -5 -3 -4 -7 -4 -27 -3 -6 -4 -15 -3 -5 -6 -6 -5 -4 -8 -3 -9 -2 -6 -3 -4 -3 -7 -4 -18 -3 -11 -3 -3 -8 -9 -7 -24 -3 -219 -7 -10 -4 -5 -9 -12 -2 -5 -4 -4 -4 -3 -3 -19 -5 -8 -16 -8 -6 -22 -3 -23 -3 -242 -9 -4 -3 -3 -5 -7 -3 -3 -5 -8 -3 -7 -5 -14 -8 -10 -3 -4 -3 -7 -4 -6 -7 -4 -10 -4 -3 -11 -3 -7 -10 -3 -13 -6 -8 -12 -10 -5 -7 -9 -3 -4 -7 -7 -10 -8 -30 -9 -19 -4 -3 -19 -15 -4 -13 -3 -215 -223 -4 -7 -4 -8 -17 -16 -3 -7 -6 -5 -5 -4 -12 -3 -7 -4 -4 -13 -4 -5 -2 -5 -6 -5 -6 -6 -7 -10 -18 -23 -9 -3 -3 -6 -5 -2 -4 -2 -7 -3 -3 -2 -5 -5 -14 -10 -224 -6 -3 -4 -3 -7 -5 -9 -3 -6 -4 -2 -5 -11 -4 -3 -3 -2 -8 -4 -7 -4 -10 -7 -3 -3 -18 -18 -17 -3 -3 -3 -4 -5 -3 -3 -4 -12 -7 -3 -11 -13 -5 -4 -7 -13 -5 -4 -11 -3 -12 -3 -6 -4 -4 -21 -4 -6 -9 -5 -3 -10 -8 -4 -6 -4 -4 -6 -5 -4 -8 -6 -4 -6 -4 -4 -5 -9 -6 -3 -4 -2 -9 -3 -18 -2 -4 -3 -13 -3 -6 -6 -8 -7 -9 -3 -2 -16 -3 -4 -6 -3 -2 -33 -22 -14 -4 -9 -12 -4 -5 -6 -3 -23 -9 -4 -3 -5 -5 -3 -4 -5 -3 -5 -3 -10 -4 -5 -5 -8 -4 -4 -6 -8 -5 -4 -3 -4 -6 -3 -3 -3 -5 -9 -12 -6 -5 -9 -3 -5 -3 -2 -2 -2 -18 -3 -2 -21 -2 -5 -4 -6 -4 -5 -10 -3 -9 -3 -2 -10 -7 -3 -6 -6 -4 -4 -8 -12 -7 -3 -7 -3 -3 -9 -3 -4 -5 -4 -4 -5 -5 -10 -15 -4 -4 -14 -6 -227 -3 -14 -5 -216 -22 -5 -4 -2 -2 -6 -3 -4 -2 -9 -9 -4 -3 -28 -13 -11 -4 -5 -3 -3 -2 -3 -3 -5 -3 -4 -3 -5 -23 -26 -3 -4 -5 -6 -4 -6 -3 -5 -5 -3 -4 -3 -2 -2 -2 -7 -14 -3 -6 -7 -17 -2 -2 -15 -14 -16 -4 -6 -7 -13 -6 -4 -5 -6 -16 -3 -3 -28 -3 -6 -15 -3 -9 -2 -4 -6 -3 -3 -22 -4 -12 -6 -7 -2 -5 -4 -10 -3 -16 -6 -9 -2 -5 -12 -7 -5 -5 -5 -5 -2 -11 -9 -17 -4 -3 -11 -7 -3 -5 -15 -4 -3 -4 -211 -8 -7 -5 -4 -7 -6 -7 -6 -3 -6 -5 -6 -5 -3 -4 -4 -26 -4 -6 -10 -4 -4 -3 -2 -3 -3 -4 -5 -9 -3 -9 -4 -4 -5 -5 -8 -2 -4 -2 -3 -8 -4 -11 -19 -5 -8 -6 -3 -5 -6 -12 -3 -2 -4 -16 -12 -3 -4 -4 -8 -6 -5 -6 -6 -219 -8 -222 -6 -16 -3 -13 -19 -5 -4 -3 -11 -6 -10 -4 -7 -7 -12 -5 -3 -3 -5 -6 -10 -3 -8 -2 -5 -4 -7 -2 -4 -4 -2 -12 -9 -6 -4 -2 -40 -2 -4 -10 -4 -223 -4 -2 -20 -6 -7 -24 -5 -4 -5 -2 -20 -16 -6 -5 -13 -2 -3 -3 -19 -3 -2 -4 -5 -6 -7 -11 -12 -5 -6 -7 -7 -3 -5 -3 -5 -3 -14 -3 -4 -4 -2 -11 -1 -7 -3 -9 -6 -11 -12 -5 -8 -6 -221 -4 -2 -12 -4 -3 -15 -4 -5 -226 -7 -218 -7 -5 -4 -5 -18 -4 -5 -9 -4 -4 -2 -9 -18 -18 -9 -5 -6 -6 -3 -3 -7 -3 -5 -4 -4 -4 -12 -3 -6 -31 -5 -4 -7 -3 -6 -5 -6 -5 -11 -2 -2 -11 -11 -6 -7 -5 -8 -7 -10 -5 -23 -7 -4 -3 -5 -34 -2 -5 -23 -7 -3 -6 -8 -4 -4 -4 -2 -5 -3 -8 -5 -4 -8 -25 -2 -3 -17 -8 -3 -4 -8 -7 -3 -15 -6 -5 -7 -21 -9 -5 -6 -6 -5 -3 -2 -3 -10 -3 -6 -3 -14 -7 -4 -4 -8 -7 -8 -2 -6 -12 -4 -213 -6 -5 -21 -8 -2 -5 -23 -3 -11 -2 -3 -6 -25 -2 -3 -6 -7 -6 -6 -4 -4 -6 -3 -17 -9 -7 -6 -4 -3 -10 -7 -2 -3 -3 -3 -11 -8 -3 -7 -6 -4 -14 -36 -3 -4 -3 -3 -22 -13 -21 -4 -2 -7 -4 -4 -17 -15 -3 -7 -11 -2 -4 -7 -6 -209 -6 -3 -2 -2 -24 -4 -9 -4 -3 -3 -3 -29 -2 -2 -4 -3 -3 -5 -4 -6 -3 -3 -2 -4 diff --git a/vendor/github.com/beorn7/perks/quantile/stream_test.go b/vendor/github.com/beorn7/perks/quantile/stream_test.go deleted file mode 100644 index 855195097..000000000 --- a/vendor/github.com/beorn7/perks/quantile/stream_test.go +++ /dev/null @@ -1,215 +0,0 @@ -package quantile - -import ( - "math" - "math/rand" - "sort" - "testing" -) - -var ( - Targets = map[float64]float64{ - 0.01: 0.001, - 0.10: 0.01, - 0.50: 0.05, - 0.90: 0.01, - 0.99: 0.001, - } - TargetsSmallEpsilon = map[float64]float64{ - 0.01: 0.0001, - 0.10: 0.001, - 0.50: 0.005, - 0.90: 0.001, - 0.99: 0.0001, - } - LowQuantiles = []float64{0.01, 0.1, 0.5} - HighQuantiles = []float64{0.99, 0.9, 0.5} -) - -const RelativeEpsilon = 0.01 - -func verifyPercsWithAbsoluteEpsilon(t *testing.T, a []float64, s *Stream) { - sort.Float64s(a) - for quantile, epsilon := range Targets { - n := float64(len(a)) - k := int(quantile * n) - if k < 1 { - k = 1 - } - lower := int((quantile - epsilon) * n) - if lower < 1 { - lower = 1 - } - upper := int(math.Ceil((quantile + epsilon) * n)) - if upper > len(a) { - upper = len(a) - } - w, min, max := a[k-1], a[lower-1], a[upper-1] - if g := s.Query(quantile); g < min || g > max { - t.Errorf("q=%f: want %v [%f,%f], got %v", quantile, w, min, max, g) - } - } -} - -func verifyLowPercsWithRelativeEpsilon(t *testing.T, a []float64, s *Stream) { - sort.Float64s(a) - for _, qu := range LowQuantiles { - n := float64(len(a)) - k := int(qu * n) - - lowerRank := int((1 - RelativeEpsilon) * qu * n) - upperRank := int(math.Ceil((1 + RelativeEpsilon) * qu * n)) - w, min, max := a[k-1], a[lowerRank-1], a[upperRank-1] - if g := s.Query(qu); g < min || g > max { - t.Errorf("q=%f: want %v [%f,%f], got %v", qu, w, min, max, g) - } - } -} - -func verifyHighPercsWithRelativeEpsilon(t *testing.T, a []float64, s *Stream) { - sort.Float64s(a) - for _, qu := range HighQuantiles { - n := float64(len(a)) - k := int(qu * n) - - lowerRank := int((1 - (1+RelativeEpsilon)*(1-qu)) * n) - upperRank := int(math.Ceil((1 - (1-RelativeEpsilon)*(1-qu)) * n)) - w, min, max := a[k-1], a[lowerRank-1], a[upperRank-1] - if g := s.Query(qu); g < min || g > max { - t.Errorf("q=%f: want %v [%f,%f], got %v", qu, w, min, max, g) - } - } -} - -func populateStream(s *Stream) []float64 { - a := make([]float64, 0, 1e5+100) - for i := 0; i < cap(a); i++ { - v := rand.NormFloat64() - // Add 5% asymmetric outliers. - if i%20 == 0 { - v = v*v + 1 - } - s.Insert(v) - a = append(a, v) - } - return a -} - -func TestTargetedQuery(t *testing.T) { - rand.Seed(42) - s := NewTargeted(Targets) - a := populateStream(s) - verifyPercsWithAbsoluteEpsilon(t, a, s) -} - -func TestTargetedQuerySmallSampleSize(t *testing.T) { - rand.Seed(42) - s := NewTargeted(TargetsSmallEpsilon) - a := []float64{1, 2, 3, 4, 5} - for _, v := range a { - s.Insert(v) - } - verifyPercsWithAbsoluteEpsilon(t, a, s) - // If not yet flushed, results should be precise: - if !s.flushed() { - for φ, want := range map[float64]float64{ - 0.01: 1, - 0.10: 1, - 0.50: 3, - 0.90: 5, - 0.99: 5, - } { - if got := s.Query(φ); got != want { - t.Errorf("want %f for φ=%f, got %f", want, φ, got) - } - } - } -} - -func TestLowBiasedQuery(t *testing.T) { - rand.Seed(42) - s := NewLowBiased(RelativeEpsilon) - a := populateStream(s) - verifyLowPercsWithRelativeEpsilon(t, a, s) -} - -func TestHighBiasedQuery(t *testing.T) { - rand.Seed(42) - s := NewHighBiased(RelativeEpsilon) - a := populateStream(s) - verifyHighPercsWithRelativeEpsilon(t, a, s) -} - -// BrokenTestTargetedMerge is broken, see Merge doc comment. -func BrokenTestTargetedMerge(t *testing.T) { - rand.Seed(42) - s1 := NewTargeted(Targets) - s2 := NewTargeted(Targets) - a := populateStream(s1) - a = append(a, populateStream(s2)...) - s1.Merge(s2.Samples()) - verifyPercsWithAbsoluteEpsilon(t, a, s1) -} - -// BrokenTestLowBiasedMerge is broken, see Merge doc comment. -func BrokenTestLowBiasedMerge(t *testing.T) { - rand.Seed(42) - s1 := NewLowBiased(RelativeEpsilon) - s2 := NewLowBiased(RelativeEpsilon) - a := populateStream(s1) - a = append(a, populateStream(s2)...) - s1.Merge(s2.Samples()) - verifyLowPercsWithRelativeEpsilon(t, a, s2) -} - -// BrokenTestHighBiasedMerge is broken, see Merge doc comment. -func BrokenTestHighBiasedMerge(t *testing.T) { - rand.Seed(42) - s1 := NewHighBiased(RelativeEpsilon) - s2 := NewHighBiased(RelativeEpsilon) - a := populateStream(s1) - a = append(a, populateStream(s2)...) - s1.Merge(s2.Samples()) - verifyHighPercsWithRelativeEpsilon(t, a, s2) -} - -func TestUncompressed(t *testing.T) { - q := NewTargeted(Targets) - for i := 100; i > 0; i-- { - q.Insert(float64(i)) - } - if g := q.Count(); g != 100 { - t.Errorf("want count 100, got %d", g) - } - // Before compression, Query should have 100% accuracy. - for quantile := range Targets { - w := quantile * 100 - if g := q.Query(quantile); g != w { - t.Errorf("want %f, got %f", w, g) - } - } -} - -func TestUncompressedSamples(t *testing.T) { - q := NewTargeted(map[float64]float64{0.99: 0.001}) - for i := 1; i <= 100; i++ { - q.Insert(float64(i)) - } - if g := q.Samples().Len(); g != 100 { - t.Errorf("want count 100, got %d", g) - } -} - -func TestUncompressedOne(t *testing.T) { - q := NewTargeted(map[float64]float64{0.99: 0.01}) - q.Insert(3.14) - if g := q.Query(0.90); g != 3.14 { - t.Error("want PI, got", g) - } -} - -func TestDefaults(t *testing.T) { - if g := NewTargeted(map[float64]float64{0.99: 0.001}).Query(0.99); g != 0 { - t.Errorf("want 0, got %f", g) - } -} diff --git a/vendor/github.com/cespare/xxhash/README.md b/vendor/github.com/cespare/xxhash/README.md deleted file mode 100644 index e896bcf28..000000000 --- a/vendor/github.com/cespare/xxhash/README.md +++ /dev/null @@ -1,42 +0,0 @@ -# xxhash - -[![GoDoc](https://godoc.org/github.com/cespare/xxhash?status.svg)](https://godoc.org/github.com/cespare/xxhash) - -xxhash is a Go implementation of the 64-bit -[xxHash](http://cyan4973.github.io/xxHash/) algorithm, XXH64. This is a -high-quality hashing algorithm that is much faster than anything in the Go -standard library. - -The API is very small, taking its cue from the other hashing packages in the -standard library: - - $ go doc github.com/cespare/xxhash ! - package xxhash // import "github.com/cespare/xxhash" - - Package xxhash implements the 64-bit variant of xxHash (XXH64) as described - at http://cyan4973.github.io/xxHash/. - - func New() hash.Hash64 - func Sum64(b []byte) uint64 - func Sum64String(s string) uint64 - -This implementation provides a fast pure-Go implementation and an even faster -assembly implementation for amd64. - -## Benchmarks - -Here are some quick benchmarks comparing the pure-Go and assembly -implementations of Sum64 against another popular Go XXH64 implementation, -[github.com/OneOfOne/xxhash](https://github.com/OneOfOne/xxhash): - -| input size | OneOfOne | cespare (noasm) | cespare | -| --- | --- | --- | --- | -| 5 B | 438.34 MB/s | 596.40 MB/s | 711.11 MB/s | -| 100 B | 3676.54 MB/s | 4301.40 MB/s | 4598.95 MB/s | -| 4 KB | 8128.64 MB/s | 8840.83 MB/s | 10549.72 MB/s | -| 10 MB | 7335.19 MB/s | 7736.64 MB/s | 9024.04 MB/s | - -## Projects using this package - -- [InfluxDB](https://github.com/influxdata/influxdb) -- [Prometheus](https://github.com/prometheus/prometheus) diff --git a/vendor/github.com/cespare/xxhash/xxhash_amd64_test.go b/vendor/github.com/cespare/xxhash/xxhash_amd64_test.go deleted file mode 100644 index 75e8d6b96..000000000 --- a/vendor/github.com/cespare/xxhash/xxhash_amd64_test.go +++ /dev/null @@ -1,41 +0,0 @@ -// +build !appengine -// +build gc -// +build !noasm - -package xxhash - -// TODO(caleb): Fix and re-enable with any ideas I get from -// https://groups.google.com/d/msg/golang-nuts/wb5I2tjrwoc/xCzk6uchBgAJ - -//func TestSum64ASM(t *testing.T) { -// for i := 0; i < 500; i++ { -// b := make([]byte, i) -// for j := range b { -// b[j] = byte(j) -// } -// pureGo := sum64Go(b) -// asm := Sum64(b) -// if pureGo != asm { -// t.Fatalf("[i=%d] pure go gave 0x%x; asm gave 0x%x", i, pureGo, asm) -// } -// } -//} - -//func TestWriteBlocksASM(t *testing.T) { -// x0 := New().(*xxh) -// x1 := New().(*xxh) -// for i := 32; i < 500; i++ { -// b := make([]byte, i) -// for j := range b { -// b[j] = byte(j) -// } -// pureGo := writeBlocksGo(x0, b) -// asm := writeBlocks(x1, b) -// if !reflect.DeepEqual(pureGo, asm) { -// t.Fatalf("[i=%d] pure go gave %v; asm gave %v", i, pureGo, asm) -// } -// if !reflect.DeepEqual(x0, x1) { -// t.Fatalf("[i=%d] pure go had state %v; asm had state %v", i, x0, x1) -// } -// } -//} diff --git a/vendor/github.com/cespare/xxhash/xxhash_test.go b/vendor/github.com/cespare/xxhash/xxhash_test.go deleted file mode 100644 index 5118c8894..000000000 --- a/vendor/github.com/cespare/xxhash/xxhash_test.go +++ /dev/null @@ -1,154 +0,0 @@ -package xxhash - -import ( - "bytes" - "encoding/binary" - "fmt" - "hash" - "hash/crc32" - "strings" - "testing" - - OneOfOne "github.com/OneOfOne/xxhash" - "github.com/spaolacci/murmur3" -) - -var result uint64 - -func BenchmarkStringHash(b *testing.B) { - const s = "abcdefghijklmnop" - var r uint64 - b.ReportAllocs() - for n := 0; n < b.N; n++ { - r = Sum64([]byte(s)) - } - result = r -} - -func TestSum(t *testing.T) { - for i, tt := range []struct { - input string - want uint64 - }{ - {"", 0xef46db3751d8e999}, - {"a", 0xd24ec4f1a98c6e5b}, - {"as", 0x1c330fb2d66be179}, - {"asd", 0x631c37ce72a97393}, - {"asdf", 0x415872f599cea71e}, - { - // Exactly 63 characters, which exercises all code paths. - "Call me Ishmael. Some years ago--never mind how long precisely-", - 0x02a2e85470d6fd96, - }, - } { - for chunkSize := 1; chunkSize <= len(tt.input); chunkSize++ { - x := New() - for j := 0; j < len(tt.input); j += chunkSize { - end := j + chunkSize - if end > len(tt.input) { - end = len(tt.input) - } - chunk := []byte(tt.input[j:end]) - n, err := x.Write(chunk) - if err != nil || n != len(chunk) { - t.Fatalf("[i=%d,chunkSize=%d] Write: got (%d, %v); want (%d, nil)", - i, chunkSize, n, err, len(chunk)) - } - } - if got := x.Sum64(); got != tt.want { - t.Fatalf("[i=%d,chunkSize=%d] got 0x%x; want 0x%x", - i, chunkSize, got, tt.want) - } - var b [8]byte - binary.BigEndian.PutUint64(b[:], tt.want) - if got := x.Sum(nil); !bytes.Equal(got, b[:]) { - t.Fatalf("[i=%d,chunkSize=%d] Sum: got %v; want %v", - i, chunkSize, got, b[:]) - } - } - if got := Sum64([]byte(tt.input)); got != tt.want { - t.Fatalf("[i=%d] Sum64: got 0x%x; want 0x%x", i, got, tt.want) - } - if got := Sum64String(tt.input); got != tt.want { - t.Fatalf("[i=%d] Sum64String: got 0x%x; want 0x%x", i, got, tt.want) - } - } -} - -func TestReset(t *testing.T) { - parts := []string{"The quic", "k br", "o", "wn fox jumps", " ov", "er the lazy ", "dog."} - x := New() - for _, part := range parts { - x.Write([]byte(part)) - } - h0 := x.Sum64() - - x.Reset() - x.Write([]byte(strings.Join(parts, ""))) - h1 := x.Sum64() - - if h0 != h1 { - t.Errorf("0x%x != 0x%x", h0, h1) - } -} - -var ( - sink uint64 - sinkb []byte -) - -func sumFunc(h hash.Hash) func(b []byte) uint64 { - return func(b []byte) uint64 { - h.Reset() - h.Write(b) - sinkb = h.Sum(nil) - return 0 // value doesn't matter - } -} - -func BenchmarkHashes(b *testing.B) { - for _, ht := range []struct { - name string - f interface{} - }{ - {"xxhash", Sum64}, - {"xxhash-string", Sum64String}, - {"OneOfOne", OneOfOne.Checksum64}, - {"murmur3", murmur3.Sum64}, - {"CRC-32", sumFunc(crc32.NewIEEE())}, - } { - for _, nt := range []struct { - name string - n int - }{ - {"5 B", 5}, - {"100 B", 100}, - {"4 KB", 4e3}, - {"10 MB", 10e6}, - } { - input := make([]byte, nt.n) - for i := range input { - input[i] = byte(i) - } - benchName := fmt.Sprintf("%s,n=%s", ht.name, nt.name) - if ht.name == "xxhash-string" { - f := ht.f.(func(string) uint64) - s := string(input) - b.Run(benchName, func(b *testing.B) { - b.SetBytes(int64(len(input))) - for i := 0; i < b.N; i++ { - sink = f(s) - } - }) - } else { - f := ht.f.(func([]byte) uint64) - b.Run(benchName, func(b *testing.B) { - b.SetBytes(int64(len(input))) - for i := 0; i < b.N; i++ { - sink = f(input) - } - }) - } - } - } -} diff --git a/vendor/github.com/cockroachdb/cmux/.gitignore b/vendor/github.com/cockroachdb/cmux/.gitignore deleted file mode 100644 index daf913b1b..000000000 --- a/vendor/github.com/cockroachdb/cmux/.gitignore +++ /dev/null @@ -1,24 +0,0 @@ -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe -*.test -*.prof diff --git a/vendor/github.com/cockroachdb/cmux/.travis.yml b/vendor/github.com/cockroachdb/cmux/.travis.yml deleted file mode 100644 index 9343f8d2c..000000000 --- a/vendor/github.com/cockroachdb/cmux/.travis.yml +++ /dev/null @@ -1,29 +0,0 @@ -language: go - -go: - - 1.5 - - 1.6 - - 1.7 - - tip - -matrix: - allow_failures: - - go: tip - -gobuild_args: -race - -before_install: - - if [[ $TRAVIS_GO_VERSION == 1.7* ]]; then go get -u github.com/kisielk/errcheck; fi - - if [[ $TRAVIS_GO_VERSION == 1.7* ]]; then go get -u github.com/golang/lint/golint; fi - -before_script: - - '! gofmt -s -l . | read' - - echo $TRAVIS_GO_VERSION - - if [[ $TRAVIS_GO_VERSION == 1.7* ]]; then golint ./...; fi - - if [[ $TRAVIS_GO_VERSION == 1.7* ]]; then errcheck ./...; fi - - if [[ $TRAVIS_GO_VERSION == 1.7* ]]; then go tool vet .; fi - - if [[ $TRAVIS_GO_VERSION == 1.7* ]]; then go tool vet --shadow .; fi - -script: - - go test -bench . -v ./... - - go test -race -bench . -v ./... diff --git a/vendor/github.com/cockroachdb/cmux/README.md b/vendor/github.com/cockroachdb/cmux/README.md deleted file mode 100644 index 26e1737d7..000000000 --- a/vendor/github.com/cockroachdb/cmux/README.md +++ /dev/null @@ -1,72 +0,0 @@ -# cmux: Connection Mux [![Build Status](https://travis-ci.org/cockroachdb/cmux.svg?branch=master)](https://travis-ci.org/cockroachdb/cmux) [![GoDoc](https://godoc.org/github.com/cockroachdb/cmux?status.svg)](https://godoc.org/github.com/cockroachdb/cmux) - -cmux is a generic Go library to multiplex connections based on their payload. -Using cmux, you can serve gRPC, SSH, HTTPS, HTTP, Go RPC, and pretty much any -other protocol on the same TCP listener. - -## How-To -Simply create your main listener, create a cmux for that listener, -and then match connections: -```go -// Create the main listener. -l, err := net.Listen("tcp", ":23456") -if err != nil { - log.Fatal(err) -} - -// Create a cmux. -m := cmux.New(l) - -// Match connections in order: -// First grpc, then HTTP, and otherwise Go RPC/TCP. -grpcL := m.Match(cmux.HTTP2HeaderField("content-type", "application/grpc")) -httpL := m.Match(cmux.HTTP1Fast()) -trpcL := m.Match(cmux.Any()) // Any means anything that is not yet matched. - -// Create your protocol servers. -grpcS := grpc.NewServer() -grpchello.RegisterGreeterServer(grpcs, &server{}) - -httpS := &http.Server{ - Handler: &helloHTTP1Handler{}, -} - -trpcS := rpc.NewServer() -s.Register(&ExampleRPCRcvr{}) - -// Use the muxed listeners for your servers. -go grpcS.Serve(grpcL) -go httpS.Serve(httpL) -go trpcS.Accept(trpcL) - -// Start serving! -m.Serve() -``` - -There are [more examples on GoDoc](https://godoc.org/github.com/cockroachdb/cmux#pkg-examples). - -## Performance -Since we are only matching the very first bytes of a connection, the -performance overhead on long-lived connections (i.e., RPCs and pipelined HTTP -streams) is negligible. - -## Limitations -* *TLS*: `net/http` uses a [type assertion](https://github.com/golang/go/issues/14221) -to identify TLS connections; since cmux's lookahead-implementing connection -wraps the underlying TLS connection, this type assertion fails. This means you -can serve HTTPS using cmux but `http.Request.TLS` will not be set in your -handlers. If you are able to wrap TLS around cmux, you can work around this -limitation. See https://github.com/cockroachdb/cockroach/commit/83caba2 for an -example of this approach. - -* *Different Protocols on The Same Connection*: `cmux` matches the connection -when it's accepted. For example, one connection can be either gRPC or REST, but -not both. That is, we assume that a client connection is either used for gRPC -or REST. - -# Copyright and License -Copyright 2016 The CMux Authors. All rights reserved. - -See [CONTRIBUTORS](https://github.com/cockroachdb/cmux/blob/master/CONTRIBUTORS) -for the CMux Authors. Code is released under -[the Apache 2 license](https://github.com/cockroachdb/cmux/blob/master/LICENSE). diff --git a/vendor/github.com/cockroachdb/cmux/bench_test.go b/vendor/github.com/cockroachdb/cmux/bench_test.go deleted file mode 100644 index 782b07b23..000000000 --- a/vendor/github.com/cockroachdb/cmux/bench_test.go +++ /dev/null @@ -1,137 +0,0 @@ -// Copyright 2016 The CMux Authors. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -// implied. See the License for the specific language governing -// permissions and limitations under the License. - -package cmux - -import ( - "bytes" - "io" - "net" - "sync" - "testing" - - "golang.org/x/net/http2" -) - -var ( - benchHTTP1Payload = make([]byte, 4096) - benchHTTP2Payload = make([]byte, 4096) -) - -func init() { - copy(benchHTTP1Payload, []byte("GET http://www.w3.org/ HTTP/1.1")) - copy(benchHTTP2Payload, http2.ClientPreface) -} - -type mockConn struct { - net.Conn - r io.Reader -} - -func (c *mockConn) Read(b []byte) (n int, err error) { - return c.r.Read(b) -} - -func discard(l net.Listener) { - for { - if _, err := l.Accept(); err != nil { - return - } - } -} - -func BenchmarkCMuxConnHTTP1(b *testing.B) { - m := New(nil).(*cMux) - l := m.Match(HTTP1Fast()) - - go discard(l) - - donec := make(chan struct{}) - var wg sync.WaitGroup - wg.Add(b.N) - - b.ResetTimer() - b.RunParallel(func(pb *testing.PB) { - for pb.Next() { - wg.Add(1) - m.serve(&mockConn{ - r: bytes.NewReader(benchHTTP1Payload), - }, donec, &wg) - } - }) -} - -func BenchmarkCMuxConnHTTP2(b *testing.B) { - m := New(nil).(*cMux) - l := m.Match(HTTP2()) - go discard(l) - - donec := make(chan struct{}) - var wg sync.WaitGroup - wg.Add(b.N) - - b.ResetTimer() - b.RunParallel(func(pb *testing.PB) { - for pb.Next() { - wg.Add(1) - m.serve(&mockConn{ - r: bytes.NewReader(benchHTTP2Payload), - }, donec, &wg) - } - }) -} - -func BenchmarkCMuxConnHTTP1n2(b *testing.B) { - m := New(nil).(*cMux) - l1 := m.Match(HTTP1Fast()) - l2 := m.Match(HTTP2()) - - go discard(l1) - go discard(l2) - - donec := make(chan struct{}) - var wg sync.WaitGroup - - b.ResetTimer() - b.RunParallel(func(pb *testing.PB) { - for pb.Next() { - wg.Add(1) - m.serve(&mockConn{ - r: bytes.NewReader(benchHTTP2Payload), - }, donec, &wg) - } - }) -} - -func BenchmarkCMuxConnHTTP2n1(b *testing.B) { - m := New(nil).(*cMux) - l2 := m.Match(HTTP2()) - l1 := m.Match(HTTP1Fast()) - - go discard(l1) - go discard(l2) - - donec := make(chan struct{}) - var wg sync.WaitGroup - - b.ResetTimer() - b.RunParallel(func(pb *testing.PB) { - for pb.Next() { - wg.Add(1) - m.serve(&mockConn{ - r: bytes.NewReader(benchHTTP1Payload), - }, donec, &wg) - } - }) -} diff --git a/vendor/github.com/cockroachdb/cmux/cmux_test.go b/vendor/github.com/cockroachdb/cmux/cmux_test.go deleted file mode 100644 index 2ab4f54e8..000000000 --- a/vendor/github.com/cockroachdb/cmux/cmux_test.go +++ /dev/null @@ -1,485 +0,0 @@ -// Copyright 2016 The CMux Authors. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -// implied. See the License for the specific language governing -// permissions and limitations under the License. - -package cmux - -import ( - "errors" - "fmt" - "io" - "io/ioutil" - "net" - "net/http" - "net/rpc" - "runtime" - "sort" - "strings" - "sync" - "sync/atomic" - "testing" - "time" - - "golang.org/x/net/http2" -) - -const ( - testHTTP1Resp = "http1" - rpcVal = 1234 -) - -func safeServe(errCh chan<- error, muxl CMux) { - if err := muxl.Serve(); !strings.Contains(err.Error(), "use of closed network connection") { - errCh <- err - } -} - -func safeDial(t *testing.T, addr net.Addr) (*rpc.Client, func()) { - c, err := rpc.Dial(addr.Network(), addr.String()) - if err != nil { - t.Fatal(err) - } - return c, func() { - if err := c.Close(); err != nil { - t.Fatal(err) - } - } -} - -type chanListener struct { - net.Listener - connCh chan net.Conn -} - -func newChanListener() *chanListener { - return &chanListener{connCh: make(chan net.Conn, 1)} -} - -func (l *chanListener) Accept() (net.Conn, error) { - if c, ok := <-l.connCh; ok { - return c, nil - } - return nil, errors.New("use of closed network connection") -} - -func testListener(t *testing.T) (net.Listener, func()) { - l, err := net.Listen("tcp", ":0") - if err != nil { - t.Fatal(err) - } - return l, func() { - if err := l.Close(); err != nil { - t.Fatal(err) - } - } -} - -type testHTTP1Handler struct{} - -func (h *testHTTP1Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { - fmt.Fprintf(w, testHTTP1Resp) -} - -func runTestHTTPServer(errCh chan<- error, l net.Listener) { - var mu sync.Mutex - conns := make(map[net.Conn]struct{}) - - defer func() { - mu.Lock() - for c := range conns { - if err := c.Close(); err != nil { - errCh <- err - } - } - mu.Unlock() - }() - - s := &http.Server{ - Handler: &testHTTP1Handler{}, - ConnState: func(c net.Conn, state http.ConnState) { - mu.Lock() - switch state { - case http.StateNew: - conns[c] = struct{}{} - case http.StateClosed: - delete(conns, c) - } - mu.Unlock() - }, - } - if err := s.Serve(l); err != ErrListenerClosed { - errCh <- err - } -} - -func runTestHTTP1Client(t *testing.T, addr net.Addr) { - if r, err := http.Get("http://" + addr.String()); err != nil { - t.Fatal(err) - } else { - defer func() { - if err := r.Body.Close(); err != nil { - t.Fatal(err) - } - }() - if b, err := ioutil.ReadAll(r.Body); err != nil { - t.Fatal(err) - } else { - if string(b) != testHTTP1Resp { - t.Fatalf("invalid response: want=%s got=%s", testHTTP1Resp, b) - } - } - } -} - -type TestRPCRcvr struct{} - -func (r TestRPCRcvr) Test(i int, j *int) error { - *j = i - return nil -} - -func runTestRPCServer(errCh chan<- error, l net.Listener) { - s := rpc.NewServer() - if err := s.Register(TestRPCRcvr{}); err != nil { - errCh <- err - } - for { - c, err := l.Accept() - if err != nil { - if err != ErrListenerClosed { - errCh <- err - } - return - } - go s.ServeConn(c) - } -} - -func runTestRPCClient(t *testing.T, addr net.Addr) { - c, cleanup := safeDial(t, addr) - defer cleanup() - - var num int - if err := c.Call("TestRPCRcvr.Test", rpcVal, &num); err != nil { - t.Fatal(err) - } - - if num != rpcVal { - t.Errorf("wrong rpc response: want=%d got=%v", rpcVal, num) - } -} - -func TestRead(t *testing.T) { - defer leakCheck(t)() - errCh := make(chan error) - defer func() { - select { - case err := <-errCh: - t.Fatal(err) - default: - } - }() - const payload = "hello world\r\n" - const mult = 2 - - writer, reader := net.Pipe() - go func() { - if _, err := io.WriteString(writer, strings.Repeat(payload, mult)); err != nil { - t.Fatal(err) - } - if err := writer.Close(); err != nil { - t.Fatal(err) - } - }() - - l := newChanListener() - defer close(l.connCh) - l.connCh <- reader - muxl := New(l) - // Register a bogus matcher to force buffering exactly the right amount. - // Before this fix, this would trigger a bug where `Read` would incorrectly - // report `io.EOF` when only the buffer had been consumed. - muxl.Match(func(r io.Reader) bool { - var b [len(payload)]byte - _, _ = r.Read(b[:]) - return false - }) - anyl := muxl.Match(Any()) - go safeServe(errCh, muxl) - muxedConn, err := anyl.Accept() - if err != nil { - t.Fatal(err) - } - for i := 0; i < mult; i++ { - var b [len(payload)]byte - if n, err := muxedConn.Read(b[:]); err != nil { - t.Error(err) - } else if e := len(b); n != e { - t.Errorf("expected to read %d bytes, but read %d bytes", e, n) - } - } - var b [1]byte - if _, err := muxedConn.Read(b[:]); err != io.EOF { - t.Errorf("unexpected error %v, expected %v", err, io.EOF) - } -} - -func TestAny(t *testing.T) { - defer leakCheck(t)() - errCh := make(chan error) - defer func() { - select { - case err := <-errCh: - t.Fatal(err) - default: - } - }() - l, cleanup := testListener(t) - defer cleanup() - - muxl := New(l) - httpl := muxl.Match(Any()) - - go runTestHTTPServer(errCh, httpl) - go safeServe(errCh, muxl) - - runTestHTTP1Client(t, l.Addr()) -} - -func TestHTTP2(t *testing.T) { - defer leakCheck(t)() - errCh := make(chan error) - defer func() { - select { - case err := <-errCh: - t.Fatal(err) - default: - } - }() - writer, reader := net.Pipe() - go func() { - if _, err := io.WriteString(writer, http2.ClientPreface); err != nil { - t.Fatal(err) - } - if err := writer.Close(); err != nil { - t.Fatal(err) - } - }() - - l := newChanListener() - l.connCh <- reader - muxl := New(l) - // Register a bogus matcher that only reads one byte. - muxl.Match(func(r io.Reader) bool { - var b [1]byte - _, _ = r.Read(b[:]) - return false - }) - h2l := muxl.Match(HTTP2()) - go safeServe(errCh, muxl) - muxedConn, err := h2l.Accept() - close(l.connCh) - if err != nil { - t.Fatal(err) - } - { - var b [len(http2.ClientPreface)]byte - if _, err := muxedConn.Read(b[:]); err != nil { - t.Fatal(err) - } - if string(b[:]) != http2.ClientPreface { - t.Errorf("got unexpected read %s, expected %s", b, http2.ClientPreface) - } - } - { - var b [1]byte - if _, err := muxedConn.Read(b[:]); err != io.EOF { - t.Errorf("unexpected error %v, expected %v", err, io.EOF) - } - } -} - -func TestHTTPGoRPC(t *testing.T) { - defer leakCheck(t)() - errCh := make(chan error) - defer func() { - select { - case err := <-errCh: - t.Fatal(err) - default: - } - }() - l, cleanup := testListener(t) - defer cleanup() - - muxl := New(l) - httpl := muxl.Match(HTTP2(), HTTP1Fast()) - rpcl := muxl.Match(Any()) - - go runTestHTTPServer(errCh, httpl) - go runTestRPCServer(errCh, rpcl) - go safeServe(errCh, muxl) - - runTestHTTP1Client(t, l.Addr()) - runTestRPCClient(t, l.Addr()) -} - -func TestErrorHandler(t *testing.T) { - defer leakCheck(t)() - errCh := make(chan error) - defer func() { - select { - case err := <-errCh: - t.Fatal(err) - default: - } - }() - l, cleanup := testListener(t) - defer cleanup() - - muxl := New(l) - httpl := muxl.Match(HTTP2(), HTTP1Fast()) - - go runTestHTTPServer(errCh, httpl) - go safeServe(errCh, muxl) - - var errCount uint32 - muxl.HandleError(func(err error) bool { - if atomic.AddUint32(&errCount, 1) == 1 { - if _, ok := err.(ErrNotMatched); !ok { - t.Errorf("unexpected error: %v", err) - } - } - return true - }) - - c, cleanup := safeDial(t, l.Addr()) - defer cleanup() - - var num int - for atomic.LoadUint32(&errCount) == 0 { - if err := c.Call("TestRPCRcvr.Test", rpcVal, &num); err == nil { - // The connection is simply closed. - t.Errorf("unexpected rpc success after %d errors", atomic.LoadUint32(&errCount)) - } - } -} - -func TestClose(t *testing.T) { - defer leakCheck(t)() - errCh := make(chan error) - defer func() { - select { - case err := <-errCh: - t.Fatal(err) - default: - } - }() - l := newChanListener() - - c1, c2 := net.Pipe() - - muxl := New(l) - anyl := muxl.Match(Any()) - - go safeServe(errCh, muxl) - - l.connCh <- c1 - - // First connection goes through. - if _, err := anyl.Accept(); err != nil { - t.Fatal(err) - } - - // Second connection is sent - l.connCh <- c2 - - // Listener is closed. - close(l.connCh) - - // Second connection either goes through or it is closed. - if _, err := anyl.Accept(); err != nil { - if err != ErrListenerClosed { - t.Fatal(err) - } - if _, err := c2.Read([]byte{}); err != io.ErrClosedPipe { - t.Fatalf("connection is not closed and is leaked: %v", err) - } - } -} - -// Cribbed from google.golang.org/grpc/test/end2end_test.go. - -// interestingGoroutines returns all goroutines we care about for the purpose -// of leak checking. It excludes testing or runtime ones. -func interestingGoroutines() (gs []string) { - buf := make([]byte, 2<<20) - buf = buf[:runtime.Stack(buf, true)] - for _, g := range strings.Split(string(buf), "\n\n") { - sl := strings.SplitN(g, "\n", 2) - if len(sl) != 2 { - continue - } - stack := strings.TrimSpace(sl[1]) - if strings.HasPrefix(stack, "testing.RunTests") { - continue - } - - if stack == "" || - strings.Contains(stack, "testing.Main(") || - strings.Contains(stack, "testing.tRunner(") || - strings.Contains(stack, "runtime.goexit") || - strings.Contains(stack, "created by runtime.gc") || - strings.Contains(stack, "interestingGoroutines") || - strings.Contains(stack, "runtime.MHeap_Scavenger") { - continue - } - gs = append(gs, g) - } - sort.Strings(gs) - return -} - -// leakCheck snapshots the currently-running goroutines and returns a -// function to be run at the end of tests to see whether any -// goroutines leaked. -func leakCheck(t testing.TB) func() { - orig := map[string]bool{} - for _, g := range interestingGoroutines() { - orig[g] = true - } - return func() { - // Loop, waiting for goroutines to shut down. - // Wait up to 5 seconds, but finish as quickly as possible. - deadline := time.Now().Add(5 * time.Second) - for { - var leaked []string - for _, g := range interestingGoroutines() { - if !orig[g] { - leaked = append(leaked, g) - } - } - if len(leaked) == 0 { - return - } - if time.Now().Before(deadline) { - time.Sleep(50 * time.Millisecond) - continue - } - for _, g := range leaked { - t.Errorf("Leaked goroutine: %v", g) - } - return - } - } -} diff --git a/vendor/github.com/cockroachdb/cmux/example_recursive_test.go b/vendor/github.com/cockroachdb/cmux/example_recursive_test.go deleted file mode 100644 index d7f01065b..000000000 --- a/vendor/github.com/cockroachdb/cmux/example_recursive_test.go +++ /dev/null @@ -1,123 +0,0 @@ -// Copyright 2016 The CMux Authors. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -// implied. See the License for the specific language governing -// permissions and limitations under the License. - -package cmux_test - -import ( - "crypto/rand" - "crypto/tls" - "fmt" - "log" - "net" - "net/http" - "net/rpc" - "strings" - - "github.com/cockroachdb/cmux" -) - -type recursiveHTTPHandler struct{} - -func (h *recursiveHTTPHandler) ServeHTTP(w http.ResponseWriter, - r *http.Request) { - - fmt.Fprintf(w, "example http response") -} - -func recursiveServeHTTP(l net.Listener) { - s := &http.Server{ - Handler: &recursiveHTTPHandler{}, - } - if err := s.Serve(l); err != cmux.ErrListenerClosed { - panic(err) - } -} - -func tlsListener(l net.Listener) net.Listener { - // Load certificates. - certificate, err := tls.LoadX509KeyPair("cert.pem", "key.pem") - if err != nil { - log.Panic(err) - } - - config := &tls.Config{ - Certificates: []tls.Certificate{certificate}, - Rand: rand.Reader, - } - - // Create TLS listener. - tlsl := tls.NewListener(l, config) - return tlsl -} - -type RecursiveRPCRcvr struct{} - -func (r *RecursiveRPCRcvr) Cube(i int, j *int) error { - *j = i * i - return nil -} - -func recursiveServeRPC(l net.Listener) { - s := rpc.NewServer() - if err := s.Register(&RecursiveRPCRcvr{}); err != nil { - panic(err) - } - for { - conn, err := l.Accept() - if err != nil { - if err != cmux.ErrListenerClosed { - panic(err) - } - return - } - go s.ServeConn(conn) - } -} - -// This is an example for serving HTTP, HTTPS, and GoRPC/TLS on the same port. -func Example_recursiveCmux() { - // Create the TCP listener. - l, err := net.Listen("tcp", "127.0.0.1:50051") - if err != nil { - log.Panic(err) - } - - // Create a mux. - tcpm := cmux.New(l) - - // We first match on HTTP 1.1 methods. - httpl := tcpm.Match(cmux.HTTP1Fast()) - - // If not matched, we assume that its TLS. - tlsl := tcpm.Match(cmux.Any()) - tlsl = tlsListener(tlsl) - - // Now, we build another mux recursively to match HTTPS and GoRPC. - // You can use the same trick for SSH. - tlsm := cmux.New(tlsl) - httpsl := tlsm.Match(cmux.HTTP1Fast()) - gorpcl := tlsm.Match(cmux.Any()) - go recursiveServeHTTP(httpl) - go recursiveServeHTTP(httpsl) - go recursiveServeRPC(gorpcl) - - go func() { - if err := tlsm.Serve(); err != cmux.ErrListenerClosed { - panic(err) - } - }() - if err := tcpm.Serve(); !strings.Contains(err.Error(), "use of closed network connection") { - panic(err) - } -} diff --git a/vendor/github.com/cockroachdb/cmux/example_test.go b/vendor/github.com/cockroachdb/cmux/example_test.go deleted file mode 100644 index 3731400ff..000000000 --- a/vendor/github.com/cockroachdb/cmux/example_test.go +++ /dev/null @@ -1,133 +0,0 @@ -// Copyright 2016 The CMux Authors. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -// implied. See the License for the specific language governing -// permissions and limitations under the License. - -package cmux_test - -import ( - "fmt" - "io" - "log" - "net" - "net/http" - "net/rpc" - "strings" - - "golang.org/x/net/context" - "golang.org/x/net/websocket" - "google.golang.org/grpc" - "google.golang.org/grpc/examples/helloworld/helloworld" - - "github.com/cockroachdb/cmux" -) - -type exampleHTTPHandler struct{} - -func (h *exampleHTTPHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { - fmt.Fprintf(w, "example http response") -} - -func serveHTTP(l net.Listener) { - s := &http.Server{ - Handler: &exampleHTTPHandler{}, - } - if err := s.Serve(l); err != cmux.ErrListenerClosed { - panic(err) - } -} - -func EchoServer(ws *websocket.Conn) { - if _, err := io.Copy(ws, ws); err != nil { - panic(err) - } -} - -func serveWS(l net.Listener) { - s := &http.Server{ - Handler: websocket.Handler(EchoServer), - } - if err := s.Serve(l); err != cmux.ErrListenerClosed { - panic(err) - } -} - -type ExampleRPCRcvr struct{} - -func (r *ExampleRPCRcvr) Cube(i int, j *int) error { - *j = i * i - return nil -} - -func serveRPC(l net.Listener) { - s := rpc.NewServer() - if err := s.Register(&ExampleRPCRcvr{}); err != nil { - panic(err) - } - for { - conn, err := l.Accept() - if err != nil { - if err != cmux.ErrListenerClosed { - panic(err) - } - return - } - go s.ServeConn(conn) - } -} - -type grpcServer struct{} - -func (s *grpcServer) SayHello(ctx context.Context, in *helloworld.HelloRequest) ( - *helloworld.HelloReply, error) { - - return &helloworld.HelloReply{Message: "Hello " + in.Name + " from cmux"}, nil -} - -func serveGRPC(l net.Listener) { - grpcs := grpc.NewServer() - helloworld.RegisterGreeterServer(grpcs, &grpcServer{}) - if err := grpcs.Serve(l); err != cmux.ErrListenerClosed { - panic(err) - } -} - -func Example() { - l, err := net.Listen("tcp", "127.0.0.1:50051") - if err != nil { - log.Panic(err) - } - - m := cmux.New(l) - - // We first match the connection against HTTP2 fields. If matched, the - // connection will be sent through the "grpcl" listener. - grpcl := m.Match(cmux.HTTP2HeaderField("content-type", "application/grpc")) - //Otherwise, we match it againts a websocket upgrade request. - wsl := m.Match(cmux.HTTP1HeaderField("Upgrade", "websocket")) - - // Otherwise, we match it againts HTTP1 methods. If matched, - // it is sent through the "httpl" listener. - httpl := m.Match(cmux.HTTP1Fast()) - // If not matched by HTTP, we assume it is an RPC connection. - rpcl := m.Match(cmux.Any()) - - // Then we used the muxed listeners. - go serveGRPC(grpcl) - go serveWS(wsl) - go serveHTTP(httpl) - go serveRPC(rpcl) - - if err := m.Serve(); !strings.Contains(err.Error(), "use of closed network connection") { - panic(err) - } -} diff --git a/vendor/github.com/cockroachdb/cmux/example_tls_test.go b/vendor/github.com/cockroachdb/cmux/example_tls_test.go deleted file mode 100644 index 42f48cdd7..000000000 --- a/vendor/github.com/cockroachdb/cmux/example_tls_test.go +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright 2016 The CMux Authors. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -// implied. See the License for the specific language governing -// permissions and limitations under the License. - -package cmux_test - -import ( - "crypto/rand" - "crypto/tls" - "fmt" - "log" - "net" - "net/http" - "strings" - - "github.com/cockroachdb/cmux" -) - -type anotherHTTPHandler struct{} - -func (h *anotherHTTPHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { - fmt.Fprintf(w, "example http response") -} - -func serveHTTP1(l net.Listener) { - s := &http.Server{ - Handler: &anotherHTTPHandler{}, - } - if err := s.Serve(l); err != cmux.ErrListenerClosed { - panic(err) - } -} - -func serveHTTPS(l net.Listener) { - // Load certificates. - certificate, err := tls.LoadX509KeyPair("cert.pem", "key.pem") - if err != nil { - log.Panic(err) - } - - config := &tls.Config{ - Certificates: []tls.Certificate{certificate}, - Rand: rand.Reader, - } - - // Create TLS listener. - tlsl := tls.NewListener(l, config) - - // Serve HTTP over TLS. - serveHTTP1(tlsl) -} - -// This is an example for serving HTTP and HTTPS on the same port. -func Example_bothHTTPAndHTTPS() { - // Create the TCP listener. - l, err := net.Listen("tcp", "127.0.0.1:50051") - if err != nil { - log.Panic(err) - } - - // Create a mux. - m := cmux.New(l) - - // We first match on HTTP 1.1 methods. - httpl := m.Match(cmux.HTTP1Fast()) - - // If not matched, we assume that its TLS. - // - // Note that you can take this listener, do TLS handshake and - // create another mux to multiplex the connections over TLS. - tlsl := m.Match(cmux.Any()) - - go serveHTTP1(httpl) - go serveHTTPS(tlsl) - - if err := m.Serve(); !strings.Contains(err.Error(), "use of closed network connection") { - panic(err) - } -} diff --git a/vendor/github.com/cockroachdb/cmux/patricia_test.go b/vendor/github.com/cockroachdb/cmux/patricia_test.go deleted file mode 100644 index c13cbcffe..000000000 --- a/vendor/github.com/cockroachdb/cmux/patricia_test.go +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2016 The CMux Authors. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -// implied. See the License for the specific language governing -// permissions and limitations under the License. - -package cmux - -import ( - "strings" - "testing" -) - -func testPTree(t *testing.T, strs ...string) { - pt := newPatriciaTreeString(strs...) - for _, s := range strs { - if !pt.match(strings.NewReader(s)) { - t.Errorf("%s is not matched by %s", s, s) - } - - if !pt.matchPrefix(strings.NewReader(s + s)) { - t.Errorf("%s is not matched as a prefix by %s", s+s, s) - } - - if pt.match(strings.NewReader(s + s)) { - t.Errorf("%s matches %s", s+s, s) - } - - // The following tests are just to catch index out of - // range and off-by-one errors and not the functionality. - pt.matchPrefix(strings.NewReader(s[:len(s)-1])) - pt.match(strings.NewReader(s[:len(s)-1])) - pt.matchPrefix(strings.NewReader(s + "$")) - pt.match(strings.NewReader(s + "$")) - } -} - -func TestPatriciaOnePrefix(t *testing.T) { - testPTree(t, "prefix") -} - -func TestPatriciaNonOverlapping(t *testing.T) { - testPTree(t, "foo", "bar", "dummy") -} - -func TestPatriciaOverlapping(t *testing.T) { - testPTree(t, "foo", "far", "farther", "boo", "ba", "bar") -} diff --git a/vendor/github.com/cockroachdb/cockroach/.codacy.yml b/vendor/github.com/cockroachdb/cockroach/.codacy.yml deleted file mode 100644 index fee16621c..000000000 --- a/vendor/github.com/cockroachdb/cockroach/.codacy.yml +++ /dev/null @@ -1,4 +0,0 @@ ---- -exclude_paths: - - vendor/ - - '*.pb.*' diff --git a/vendor/github.com/cockroachdb/cockroach/.editorconfig b/vendor/github.com/cockroachdb/cockroach/.editorconfig deleted file mode 100644 index 0e4642afc..000000000 --- a/vendor/github.com/cockroachdb/cockroach/.editorconfig +++ /dev/null @@ -1,10 +0,0 @@ -# See http://editorconfig.org - -[*] -end_of_line = lf -insert_final_newline = true -charset = utf-8 - -# For non-go files, we indent with two spaces. In go files we indent -# with tabs but still set indent_size to control the github web viewer. -indent_size=2 diff --git a/vendor/github.com/cockroachdb/cockroach/.gitattributes b/vendor/github.com/cockroachdb/cockroach/.gitattributes deleted file mode 100644 index b72d81bff..000000000 --- a/vendor/github.com/cockroachdb/cockroach/.gitattributes +++ /dev/null @@ -1,7 +0,0 @@ -*.pb.* -diff -embedded.go -diff -pkg/sql/parser/sql.go -diff -pkg/ui/src/js/protos.* -diff -pkg/ui/generated/* -diff -pkg/ui/yarn.lock -merge -glide.lock -merge diff --git a/vendor/github.com/cockroachdb/cockroach/.gitignore b/vendor/github.com/cockroachdb/cockroach/.gitignore deleted file mode 100644 index 14739b136..000000000 --- a/vendor/github.com/cockroachdb/cockroach/.gitignore +++ /dev/null @@ -1,26 +0,0 @@ -# Editor or environment-specific entries should not be committed to the -# repository but can be kept in git's global configuration: -# -# https://help.github.com/articles/ignoring-files/#create-a-global-gitignore -# -# For advice on what entries to include in your global gitignore, please see -# GitHub's gitignore repository, which contains an excellent set of entries for -# many different editing tools: -# -# https://github.com/github/gitignore/tree/master/Global - -artifacts -/bin -/bin.* -.buildinfo -# cockroach-data, cockroach{,.race}-{darwin,linux,windows}-* -/cockroach* -/certs -# make stress, acceptance produce stress.test, acceptance.test -*.test* - -# Custom or private env vars (e.g. internal keys, access tokens, etc). -customenv.mk - -# Generated files containing include paths. -zcgo_flags*.go diff --git a/vendor/github.com/cockroachdb/cockroach/.gitmodules b/vendor/github.com/cockroachdb/cockroach/.gitmodules deleted file mode 100644 index 3c72e6d08..000000000 --- a/vendor/github.com/cockroachdb/cockroach/.gitmodules +++ /dev/null @@ -1,3 +0,0 @@ -[submodule "vendor"] - path = vendor - url = https://github.com/cockroachdb/vendored diff --git a/vendor/github.com/cockroachdb/cockroach/.go-version b/vendor/github.com/cockroachdb/cockroach/.go-version deleted file mode 100644 index 441e14a3a..000000000 --- a/vendor/github.com/cockroachdb/cockroach/.go-version +++ /dev/null @@ -1 +0,0 @@ -GOVERS = go1\.8.* diff --git a/vendor/github.com/cockroachdb/cockroach/.mailmap b/vendor/github.com/cockroachdb/cockroach/.mailmap deleted file mode 100644 index c74d44904..000000000 --- a/vendor/github.com/cockroachdb/cockroach/.mailmap +++ /dev/null @@ -1,50 +0,0 @@ -Andrei Matei -Andrei Matei -Ben Darnell -Ben Darnell -Bram Gruneir -Bram Gruneir -Bram Gruneir -Bram Gruneir -Bram Gruneir -Cuong Do -Cuong Do -Dan Harrison -Dan Harrison -David Taylor -David Taylor -Jessica Edwards -Jessica Edwards -Jesse Seldess -Raphael 'kena' Poss -Raphael 'kena' Poss -Kenji Kaneda -Marc Berhault -Marc Berhault -Matt Jibson -Matt Jibson -Matt Tracy -Matt Tracy -Matt Tracy -Max Lang -Max Lang -Nathan VanBenschoten -Nathan VanBenschoten -Peter Mattis -Peter Mattis -Peter Mattis -Radu Berinde -Radu Berinde -Spencer Kimball -Spencer Kimball -Spencer Kimball -Spencer Kimball -Tamir Duberstein -Tamir Duberstein -Tobias Schottdorf -Tobias Schottdorf -Tobias Schottdorf -Vivek Menezes -Vivek Menezes -Vivek Menezes -Vivek Menezes diff --git a/vendor/github.com/cockroachdb/cockroach/CONTRIBUTING.md b/vendor/github.com/cockroachdb/cockroach/CONTRIBUTING.md deleted file mode 100644 index 30d96330a..000000000 --- a/vendor/github.com/cockroachdb/cockroach/CONTRIBUTING.md +++ /dev/null @@ -1,177 +0,0 @@ -# Contributing to Cockroach - -## Getting and Building - -1. Install the following prerequisites, as necessary: - - A C++ compiler that supports C++11. Note that GCC prior to 6.0 doesn't - work due to https://gcc.gnu.org/bugzilla/show_bug.cgi?id=48891 - - A Go environment with a recent 64-bit version of the toolchain. Note that - the Makefile enforces the specific version required, as it is updated - frequently. - - Git 1.8+ - - Bash (4+ is preferred) - - GNU Make (3.81+ is known to work) - - CMake 2.8.12+ - - XZ Utils (5.2.3+ is known to work), except on macOS, where xz support is - built in to `tar`. - - Optional: NodeJS 6.x and Yarn 0.22.0+. Required when compiling protocol - buffers. - - Note that at least 4GB of RAM is required to build from source and run tests. - -2. Get the CockroachDB code: - - ```shell - go get -d github.com/cockroachdb/cockroach - cd $GOPATH/src/github.com/cockroachdb/cockroach - ``` - -3. Run `make build`, `make test`, or anything else our Makefile offers. Note -that the first time you run `make`, it can take some time to download and -install various dependencies. After running `make build`, the `cockroach` -executable will be in your current directory and can be run as shown in the -[README](README.md). - -### Other Considerations - -- The default binary contains core open-source functionally covered by the - Apache License 2 (APL2) and enterprise functionality covered by the - CockroachDB Community License (CCL). To build a pure open-source (APL2) - version excluding enterprise functionality, use `make buildoss`. See this - [blog post] for more details. - - [blog post]: https://www.cockroachlabs.com/blog/how-were-building-a-business-to-last/ - -- If you edit a `.proto` or `.ts` file, you will need to manually regenerate - the associated `.pb.{go,cc,h}` or `.js` files using `make generate`. - -- We advise to run `make generate` using our embedded Docker setup. - `build/builder.sh` is a wrapper script designed to make this convenient. You - can run `build/builder.sh make generate` from the repository root to get the - intended result. - -- If you plan on working on the UI, check out [the UI README](pkg/ui). - -- To add or update a Go dependency: - - See [`build/README.md`](build/README.md) for details on adding or updating - dependencies. - - Run `make generate` to update generated files. - - Create a PR with all the changes. - -## Style Guide - -[Style Guide](STYLE.md) - -## Code Review Workflow - -+ All contributors need to sign the [Contributor License Agreement](https://cla-assistant.io/cockroachdb/cockroach). - -+ Create a local feature branch to do work on, ideally on one thing at a time. - If you are working on your own fork, see [this tip](http://blog.campoy.cat/2014/03/github-and-go-forking-pull-requests-and.html) - on forking in Go, which ensures that Go import paths will be correct. - - `git checkout -b update-readme` - -+ Hack away and commit your changes locally using `git add` and `git commit`. - Remember to write tests! The following are helpful for running specific - subsets of tests: - - ```shell - make test - # Run all tests in ./pkg/storage - make test PKG=./pkg/storage - # Run all kv tests matching '^TestFoo' with a timeout of 10s - make test PKG=./pkg/kv TESTS='^TestFoo' TESTTIMEOUT=10s - # Run the sql logic tests - make test PKG=./pkg/sql TESTS='TestLogic$$' - # or, using a shortcut, - make testlogic - # Run a specific sql logic subtest - make test PKG=./pkg/sql TESTS='TestLogic$$/select$$' - # or, using a shortcut, - make testlogic FILES=select - ``` - - Logs are disabled during tests by default. To enable them, include - `TESTFLAGS="-v -show-logs"` as an argument the test command: - - ```shell - make test ... TESTFLAGS="-v -show-logs" - ``` - - When you're ready to commit, be sure to write a Good Commit Message™. Consult - https://github.com/erlang/otp/wiki/Writing-good-commit-messages if you're - not sure what constitutes a Good Commit Message™. - In addition to the general rules referenced above, please also prefix your - commit subject line with the affected package, if one can easily be chosen. - For example, the subject line of a commit mostly affecting the - `server/serverpb` package might read: "server/serverpb: made great again". - Commits which affect many packages as a result of a shared dependency change - should probably begin their subjects with the name of the shared dependency. - Finally, some commits may need to affect many packages in a way which does - not point to a specific package; those commits may begin with "*:" or "all:" - to indicate their reach. - -+ Run the linters, code generators, and unit test suites locally: - - ``` - make pre-push - ```` - - This will take several minutes. - -+ When you’re ready for review, groom your work: each commit should pass tests - and contain a substantial (but not overwhelming) unit of work. You may also - want to `git fetch origin` and run - `git rebase -i --exec "make lint test" origin/master` to make sure you're - submitting your changes on top of the newest version of our code. Next, push - to your fork: - - `git push -u update-readme` - -+ Then [create a pull request using GitHub’s UI](https://help.github.com/articles/creating-a-pull-request). If you know of - another GitHub user particularly suited to reviewing your pull request, be - sure to mention them in the pull request body. If you possess the necessary - GitHub privileges, please also [assign them to the pull request using - GitHub's UI](https://help.github.com/articles/assigning-issues-and-pull-requests-to-other-github-users/). - This will help focus and expedite the code review process. - -+ If you get a test failure in CircleCI, check the Test Failure tab to see why - the test failed. When the failure is logged in `excerpt.txt`, you can find - the file from the Artifacts tab and see log messages. (You need to sign in to - see the Artifacts tab.) - -+ Address feedback by amending your commits. If your change contains multiple - commits, address each piece of feedback by amending that commit to which the - particular feedback is aimed. Wait (or ask) for new feedback on those - commits if they are not straightforward. An `LGTM` ("looks good to me") by - someone qualified is usually posted when you're free to go ahead and merge. - Most new contributors aren't allowed to merge themselves; in that case, we'll - do it for you. - -## Debugging - -Peeking into a running cluster can be done in several ways: - -* the [net/trace](https://godoc.org/golang.org/x/net/trace) endpoint at - `/debug/requests`. It has a breakdown of the recent traced requests, in - particularly slow ones. Two families are traced: `node` and `coord`, the - former (and likely more interesting one) containing what happens inside of - `Node`/`Store`/`Replica` and the other inside of the coordinator - (`TxnCoordSender`). -* [pprof](https://golang.org/pkg/net/http/pprof/) gives us (among other things) - heap and cpu profiles; [this golang blog post](http://blog.golang.org/profiling-go-programs) explains it extremely well and - [this one by Dmitry Vuykov](https://software.intel.com/en-us/blogs/2014/05/10/debugging-performance-issues-in-go-programs) - goes into even more detail. - -An easy way to locally run a workload against a cluster are the acceptance -tests. For example, - -```shell -make acceptance TESTS='TestPut$$' TESTFLAGS='-v -d 1200s -l .' TESTTIMEOUT=1210s -``` - -runs the `Put` acceptance test for 20 minutes with logging (useful to look at -the stack trace in case of a node dying). When it starts, all the relevant -commands for `pprof`, `trace` and logs are logged to allow for convenient -inspection of the cluster. diff --git a/vendor/github.com/cockroachdb/cockroach/Makefile b/vendor/github.com/cockroachdb/cockroach/Makefile deleted file mode 100644 index d81763e6a..000000000 --- a/vendor/github.com/cockroachdb/cockroach/Makefile +++ /dev/null @@ -1,329 +0,0 @@ -# Copyright 2014 The Cockroach Authors. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. See the License for the specific language governing -# permissions and limitations under the License. -# -# Author: Andrew Bonventre (andybons@gmail.com) -# Author: Shawn Morel (shawnmorel@gmail.com) -# Author: Spencer Kimball (spencer.kimball@gmail.com) - -# Variables to be overridden on the command line only, e.g. -# -# make test PKG=./pkg/storage TESTFLAGS=--vmodule=raft=1 -# -# Note that environment variable overrides are intentionally ignored. -PKG := ./pkg/... -TAGS := -TESTS := . -BENCHES := -FILES := -TESTTIMEOUT := 4m -RACETIMEOUT := 15m -BENCHTIMEOUT := 5m -TESTFLAGS := -STRESSFLAGS := -DUPLFLAGS := -t 100 -GOFLAGS := -ARCHIVE := cockroach.src.tgz -STARTFLAGS := -s type=mem,size=1GiB --logtostderr -BUILDMODE := install -BUILDTARGET := . -SUFFIX := -INSTALL := install -prefix := /usr/local -bindir := $(prefix)/bin - -# Possible values: -# : use the default toolchain -# release-linux-gnu: target Linux 2.6.32, dynamically link GLIBC 2.12.2 -# release-linux-musl: target Linux 2.6.32, statically link musl 1.1.16 -# release-darwin: target OS X 10.9 -# release-windows: target Windows 8, statically link all non-Windows libraries -# -# All non-empty variants only work in the cockroachdb/builder docker image, as -# they depend on cross-compilation toolchains available there. -# The name of the cockroach binary depends on the release type. -TYPE := - -# We intentionally use LINKFLAGS instead of the more traditional LDFLAGS -# because LDFLAGS has built-in semantics that don't make sense with the Go -# toolchain. -LINKFLAGS ?= - -BUILD_TYPE := development -ifeq ($(TYPE),) -else ifeq ($(TYPE),msan) -NATIVE_SUFFIX := _msan -override GOFLAGS += -msan -# NB: using jemalloc with msan causes segfaults. See -# https://github.com/jemalloc/jemalloc/issues/821. -override TAGS += stdmalloc -MSAN_CPPFLAGS := -fsanitize=memory -fsanitize-memory-track-origins -fno-omit-frame-pointer -I/libcxx_msan/include -I/libcxx_msan/include/c++/v1 -MSAN_LDFLAGS := -fsanitize=memory -stdlib=libc++ -L/libcxx_msan/lib -lc++abi -Wl,-rpath,/libcxx_msan/lib -override CGO_CPPFLAGS += $(MSAN_CPPFLAGS) -override CGO_LDFLAGS += $(MSAN_LDFLAGS) -export CGO_CPPFLAGS -export CGO_LDFLAGS -# NB: CMake doesn't respect CPPFLAGS (!) -# -# See https://bugs.launchpad.net/pantheon-terminal/+bug/1325329. -override CFLAGS += $(MSAN_CPPFLAGS) -override CXXFLAGS += $(MSAN_CPPFLAGS) -override LDFLAGS += $(MSAN_LDFLAGS) -export CFLAGS -export CXXFLAGS -export LDFLAGS -else ifeq ($(TYPE),portable) -override LINKFLAGS += -s -w -extldflags "-static-libgcc -static-libstdc++" -else ifeq ($(TYPE),release-linux-gnu) -# We use a custom toolchain to target old Linux and glibc versions. However, -# this toolchain's libstdc++ version is quite recent and must be statically -# linked to avoid depending on the target's available libstdc++. -XHOST_TRIPLE := x86_64-unknown-linux-gnu -override LINKFLAGS += -s -w -extldflags "-static-libgcc -static-libstdc++" -override GOFLAGS += -installsuffix release-gnu -override SUFFIX := $(SUFFIX)-linux-2.6.32-gnu-amd64 -BUILD_TYPE := release-gnu -else ifeq ($(TYPE),release-linux-musl) -BUILD_TYPE := release-musl -XHOST_TRIPLE := x86_64-unknown-linux-musl -override LINKFLAGS += -s -w -extldflags "-static" -override GOFLAGS += -installsuffix release-musl -override SUFFIX := $(SUFFIX)-linux-2.6.32-musl-amd64 -else ifeq ($(TYPE),release-darwin) -XGOOS := darwin -export CGO_ENABLED := 1 -XHOST_TRIPLE := x86_64-apple-darwin13 -override SUFFIX := $(SUFFIX)-darwin-10.9-amd64 -override LINKFLAGS += -s -w -BUILD_TYPE := release -else ifeq ($(TYPE),release-windows) -XGOOS := windows -export CGO_ENABLED := 1 -XHOST_TRIPLE := x86_64-w64-mingw32 -override SUFFIX := $(SUFFIX)-windows-6.2-amd64 -override LINKFLAGS += -s -w -extldflags "-static" -BUILD_TYPE := release -else -$(error unknown build type $(TYPE)) -endif - -override LINKFLAGS += -X github.com/cockroachdb/cockroach/pkg/build.typ=$(BUILD_TYPE) - -REPO_ROOT := . -include $(REPO_ROOT)/build/common.mk -override TAGS += make $(NATIVE_SPECIFIER_TAG) - -# On macOS 10.11, XCode SDK v8.1 (and possibly others) indicate the presence of -# symbols that don't exist until macOS 10.12. Setting MACOSX_DEPLOYMENT_TARGET -# to the host machine's actual macOS version works around this. See: -# https://github.com/jemalloc/jemalloc/issues/494. -ifdef MACOS -export MACOSX_DEPLOYMENT_TARGET ?= $(shell sw_vers -productVersion) -endif - -XGO := $(strip $(if $(XGOOS),GOOS=$(XGOOS)) $(if $(XGOARCH),GOARCH=$(XGOARCH)) $(if $(XHOST_TRIPLE),CC=$(CC_PATH) CXX=$(CXX_PATH)) $(GO)) - -COCKROACH := ./cockroach$(SUFFIX)$(shell $(XGO) env GOEXE) - -.DEFAULT_GOAL := all -all: $(COCKROACH) - -buildoss: BUILDTARGET = ./pkg/cmd/cockroach-oss - -$(COCKROACH) build buildoss: BUILDMODE = build -i -o $(COCKROACH) - -# The build.utcTime format must remain in sync with TimeFormat in pkg/build/info.go. -$(COCKROACH) build buildoss go-install: override LINKFLAGS += \ - -X "github.com/cockroachdb/cockroach/pkg/build.tag=$(shell cat .buildinfo/tag)" \ - -X "github.com/cockroachdb/cockroach/pkg/build.utcTime=$(shell date -u '+%Y/%m/%d %H:%M:%S')" \ - -X "github.com/cockroachdb/cockroach/pkg/build.rev=$(shell cat .buildinfo/rev)" - -# Note: We pass `-v` to `go build` and `go test -i` so that warnings -# from the linker aren't suppressed. The usage of `-v` also shows when -# dependencies are rebuilt which is useful when switching between -# normal and race test builds. -.PHONY: build buildoss install -$(COCKROACH) build buildoss go-install: $(C_LIBS) $(CGO_FLAGS_FILES) $(BOOTSTRAP_TARGET) .buildinfo/tag .buildinfo/rev - $(XGO) $(BUILDMODE) -v $(GOFLAGS) -tags '$(TAGS)' -ldflags '$(LINKFLAGS)' $(BUILDTARGET) - -.PHONY: install -install: $(COCKROACH) - $(INSTALL) -d -m 755 $(DESTDIR)$(bindir) - $(INSTALL) -m 755 $(COCKROACH) $(DESTDIR)$(bindir)/cockroach - -.PHONY: start -start: $(COCKROACH) -start: - $(COCKROACH) start $(STARTFLAGS) - -# Build, but do not run the tests. -# PKG is expanded and all packages are built and moved to their directory. -.PHONY: testbuild -testbuild: gotestdashi - $(XGO) list -tags '$(TAGS)' -f \ - '$(XGO) test -v $(GOFLAGS) -tags '\''$(TAGS)'\'' -ldflags '\''$(LINKFLAGS)'\'' -i -c {{.ImportPath}} -o {{.Dir}}/{{.Name}}.test' $(PKG) | \ - $(SHELL) - -.PHONY: gotestdashi -gotestdashi: $(C_LIBS) $(CGO_FLAGS_FILES) $(BOOTSTRAP_TARGET) - $(XGO) test -v $(GOFLAGS) -tags '$(TAGS)' -ldflags '$(LINKFLAGS)' -i $(PKG) - -testshort: override TESTFLAGS += -short - -testrace: override GOFLAGS += -race -testrace: export GORACE := halt_on_error=1 -testrace: TESTTIMEOUT := $(RACETIMEOUT) - -# Directory scans in the builder image are excruciatingly slow when running -# Docker for Mac, so we filter out the 20k+ UI dependencies that are -# guaranteed to be irrelevant to save nearly 10s on every Make invocation. -FIND_RELEVANT := find pkg -name node_modules -prune -o - -bin/sql.test: main.go $(shell $(FIND_RELEVANT) ! -name 'zcgo_flags.go' -name '*.go') - $(XGO) test $(GOFLAGS) -tags '$(TAGS)' -ldflags '$(LINKFLAGS)' -c -o bin/sql.test ./pkg/sql - -bench: BENCHES := . -bench: TESTS := - -bench: TESTTIMEOUT := $(BENCHTIMEOUT) - -.PHONY: check test testshort testrace testlogic bench -check test testshort testrace bench: gotestdashi - $(XGO) test $(GOFLAGS) -tags '$(TAGS)' -ldflags '$(LINKFLAGS)' -run "$(TESTS)" $(if $(BENCHES),-bench "$(BENCHES)") -timeout $(TESTTIMEOUT) $(PKG) $(TESTFLAGS) - -# Run make testlogic to run all of the logic tests. Specify test files to run -# with make testlogic FILES="foo bar". -testlogic: TESTS := $(if $(FILES),TestLogic$$//^$(subst $(space),$$|^,$(FILES))$$,TestLogic) -testlogic: TESTFLAGS := -test.v $(if $(FILES),-show-sql) -testlogic: bin/sql.test - cd pkg/sql && sql.test -test.run "$(TESTS)" -test.timeout $(TESTTIMEOUT) $(TESTFLAGS) - -testraceslow: override GOFLAGS += -race -testraceslow: TESTTIMEOUT := $(RACETIMEOUT) - -.PHONY: testslow testraceslow -testslow testraceslow: override TESTFLAGS += -v -testslow testraceslow: gotestdashi - $(XGO) test $(GOFLAGS) -tags '$(TAGS)' -ldflags '$(LINKFLAGS)' -run "$(TESTS)" $(if $(BENCHES),-bench "$(BENCHES)") -timeout $(TESTTIMEOUT) $(PKG) $(TESTFLAGS) | grep -F ': Test' | sed -E 's/(--- PASS: |\(|\))//g' | awk '{ print $$2, $$1 }' | sort -rn | head -n 10 - -stressrace: override GOFLAGS += -race -stressrace: TESTTIMEOUT := $(RACETIMEOUT) - -# Beware! This target is complicated because it needs to handle complexity: -# - PKG may be specified as relative (e.g. './gossip') or absolute (e.g. -# github.com/cockroachdb/cockroach/gossip), and this target needs to create -# the test binary in the correct location and `cd` to the correct directory. -# This is handled by having `go list` produce the command line. -# - PKG may also be recursive (e.g. './pkg/...'). This is also handled by piping -# through `go list`. -# - PKG may not contain any tests! This is handled with an `if` statement that -# checks for the presence of a test binary before running `stress` on it. -.PHONY: stress stressrace -stress stressrace: $(C_LIBS) $(CGO_FLAGS_FILES) $(BOOTSTRAP_TARGET) - $(GO) list -tags '$(TAGS)' -f '$(XGO) test -v $(GOFLAGS) -tags '\''$(TAGS)'\'' -ldflags '\''$(LINKFLAGS)'\'' -i -c {{.ImportPath}} -o '\''{{.Dir}}'\''/stress.test && (cd '\''{{.Dir}}'\'' && if [ -f stress.test ]; then COCKROACH_STRESS=true stress $(STRESSFLAGS) ./stress.test -test.run '\''$(TESTS)'\'' $(if $(BENCHES),-test.bench '\''$(BENCHES)'\'') -test.timeout $(TESTTIMEOUT) $(TESTFLAGS); fi)' $(PKG) | $(SHELL) - -.PHONY: upload-coverage -upload-coverage: $(BOOTSTRAP_TARGET) - $(GO) install ./vendor/github.com/wadey/gocovmerge - $(GO) install ./vendor/github.com/mattn/goveralls - @build/upload-coverage.sh - -.PHONY: acceptance -acceptance: - @pkg/acceptance/run.sh - -.PHONY: dupl -dupl: $(BOOTSTRAP_TARGET) - $(FIND_RELEVANT) \ - -name '*.go' \ - -not -name '*.pb.go' \ - -not -name '*.pb.gw.go' \ - -not -name 'embedded.go' \ - -not -name '*_string.go' \ - -not -name 'sql.go' \ - | dupl -files $(DUPLFLAGS) - -# All packages need to be installed before we can run (some) of the checks and -# code generators reliably. More precisely, anything that uses x/tools/go/loader -# is fragile (this includes stringer, vet and others). The blocking issue is -# https://github.com/golang/go/issues/14120. - -# `go generate` uses stringer and so must depend on gotestdashi per the above -# comment. See https://github.com/golang/go/issues/10249 for details. -.PHONY: generate -generate: gotestdashi - $(GO) generate $(GOFLAGS) -tags '$(TAGS)' -ldflags '$(LINKFLAGS)' $(PKG) - -# The style checks depend on `go vet` and so must depend on gotestdashi per the -# above comment. See https://github.com/golang/go/issues/16086 for details. -.PHONY: lint -lint: override TAGS += lint -lint: gotestdashi - $(XGO) test ./build -v $(GOFLAGS) -tags '$(TAGS)' -ldflags '$(LINKFLAGS)' -run 'TestStyle/$(TESTS)' - -.PHONY: lintshort -lintshort: override TAGS += lint -lintshort: gotestdashi - $(XGO) test ./build -v $(GOFLAGS) -tags '$(TAGS)' -ldflags '$(LINKFLAGS)' -short -run 'TestStyle/$(TESTS)' - -.PHONY: clean -clean: clean-c-deps - $(GO) clean $(GOFLAGS) -tags '$(TAGS)' -ldflags '$(LINKFLAGS)' -i github.com/cockroachdb/... - $(FIND_RELEVANT) -type f \( -name 'zcgo_flags*.go' -o -name '*.test' \) -exec rm {} + - rm -f $(BOOTSTRAP_TARGET) $(ARCHIVE) - -.PHONY: protobuf -protobuf: - $(MAKE) -C $(ORG_ROOT) -f cockroach/build/protobuf.mk - -# pre-push locally runs most of the checks CI will run. Notably, it doesn't run -# the acceptance tests. -.PHONY: pre-push -pre-push: generate lint test - $(MAKE) -C $(REPO_ROOT)/pkg/ui lint test - ! git status --porcelain | read || (git status; git --no-pager diff -a 1>&2; exit 1) - -# archive builds a source tarball out of this repository. Files in the special -# directory build/archive/contents are inserted directly into $(ARCHIVE_BASE). -# All other files in the repository are inserted into the archive with prefix -# $(ARCHIVE_BASE)/src/github.com/cockroachdb/cockroach to allow the extracted -# archive to serve directly as a GOPATH root. -.PHONY: archive -archive: $(ARCHIVE) - -$(ARCHIVE): $(ARCHIVE).tmp - gzip -c $< > $@ - -# TODO(benesch): Make this recipe use `git ls-files --recurse-submodules` -# instead of scripts/ls-files.sh once Git v2.11 is widely deployed. -.INTERMEDIATE: $(ARCHIVE).tmp -$(ARCHIVE).tmp: ARCHIVE_BASE = cockroach-$(shell cat .buildinfo/tag) -$(ARCHIVE).tmp: .buildinfo/tag .buildinfo/rev - scripts/ls-files.sh | $(TAR) -cf $@ -T - $(TAR_XFORM_FLAG),^,$(ARCHIVE_BASE)/src/github.com/cockroachdb/cockroach/, $^ - (cd build/archive/contents && $(TAR) -rf ../../../$@ $(TAR_XFORM_FLAG),^,$(ARCHIVE_BASE)/, *) - -.buildinfo: - @mkdir -p $@ - -.buildinfo/tag: | .buildinfo - @{ git describe --tags --exact-match 2> /dev/null || git rev-parse --short HEAD; } | tr -d \\n > $@ - @git diff-index --quiet HEAD || echo -dirty >> $@ - -.buildinfo/rev: | .buildinfo - @git rev-parse HEAD > $@ - -ifneq ($(GIT_DIR),) -# If we're in a Git checkout, we update the buildinfo information on every build -# to keep it up-to-date. -.buildinfo/tag: .ALWAYS_REBUILD -.buildinfo/rev: .ALWAYS_REBUILD -endif diff --git a/vendor/github.com/cockroachdb/cockroach/README.md b/vendor/github.com/cockroachdb/cockroach/README.md deleted file mode 100644 index 9972bdab5..000000000 --- a/vendor/github.com/cockroachdb/cockroach/README.md +++ /dev/null @@ -1,189 +0,0 @@ -![CockroachDB](docs/media/cockroach_db.png?raw=true "CockroachDB logo") -======================================================================= - -CockroachDB is a cloud-native SQL database for building global, scalable cloud services that survive disasters. - -[![TeamCity CI](https://teamcity.cockroachdb.com/guestAuth/app/rest/builds/buildType:(id:Cockroach_UnitTests)/statusIcon.svg)](https://teamcity.cockroachdb.com/viewLog.html?buildTypeId=Cockroach_UnitTests&buildId=lastFinished&guest=1) -[![GoDoc](https://godoc.org/github.com/cockroachdb/cockroach?status.svg)](https://godoc.org/github.com/cockroachdb/cockroach) -![Version](https://img.shields.io/badge/version-1.0-brightgreen.svg) -[![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/cockroachdb/cockroach?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) - -- [What is CockroachDB?](#what-is-cockroachdb) -- [Docs](#docs) -- [Quickstart](#quickstart) -- [Client Drivers](#client-drivers) -- [Deployment](#deployment) -- [Need Help?](#need-help) -- [Contributing](#contributing) -- [Design](#design) -- [Comparison with Other Databases](#comparison-with-other-databases) -- [See Also](#see-also) - -## What is CockroachDB? - -CockroachDB is a distributed SQL database built on a transactional and -strongly-consistent key-value store. It **scales** horizontally; -**survives** disk, machine, rack, and even datacenter failures with -minimal latency disruption and no manual intervention; supports -**strongly-consistent** ACID transactions; and provides a familiar -**SQL** API for structuring, manipulating, and querying data. - -For more details, see our [FAQ](https://cockroachlabs.com/docs/frequently-asked-questions.html) and original [design document]( -https://github.com/cockroachdb/cockroach#design). - -## Status - -CockroachDB is production-ready. See our -[1.1 milestone](https://github.com/cockroachdb/cockroach/milestone/10) for a list of features planned or in development. - -## Docs - -For guidance on installation, development, deployment, and administration, see our [User Documentation](https://cockroachlabs.com/docs/). - -## Quickstart - -1. [Install CockroachDB](https://www.cockroachlabs.com/docs/install-cockroachdb.html). - -1. [Start a local cluster](https://www.cockroachlabs.com/docs/start-a-local-cluster.html) - and talk to it via the [built-in SQL client](https://www.cockroachlabs.com/docs/use-the-built-in-sql-client.html). - -1. [Learn more about CockroachDB SQL](https://www.cockroachlabs.com/docs/learn-cockroachdb-sql.html). - -1. Use a PostgreSQL-compatible driver or ORM to - [build an app with CockroachDB](https://www.cockroachlabs.com/docs/build-an-app-with-cockroachdb.html). - -1. [Explore core features](https://www.cockroachlabs.com/docs/demo-data-replication.html), - such as data replication, automatic rebalancing, and fault tolerance and recovery. - -## Client Drivers - -CockroachDB supports the PostgreSQL wire protocol, so you can use any available PostgreSQL client drivers to connect from various languages. - -- For recommended drivers that we've tested, see [Install Client Drivers](https://www.cockroachlabs.com/docs/install-client-drivers.html). - -- For tutorials using these drivers, as well as supported ORMs, see [Build an App with CockroachDB](https://www.cockroachlabs.com/docs/build-an-app-with-cockroachdb.html). - -## Deployment - -- [Manual Deployment](https://www.cockroachlabs.com/docs/manual-deployment.html) - Steps to deploy a CockroachDB cluster manually on multiple machines. - -- [Cloud Deployment](https://www.cockroachlabs.com/docs/cloud-deployment.html) - Guides for deploying CockroachDB on various cloud platforms. - -- [Orchestration](https://www.cockroachlabs.com/docs/orchestration.html) - Guides for running CockroachDB with popular open-source orchestration systems. - -## Need Help? - -- [Troubleshooting documentation](https://www.cockroachlabs.com/docs/troubleshooting-overview.html) - - Learn how to troubleshoot common errors, cluster and node setup, and SQL query behavior, - and how to use debug and error logs. - -- [CockroachDB Forum](https://forum.cockroachlabs.com/) and - [Stack Overflow](https://stackoverflow.com/questions/tagged/cockroachdb) - Ask questions, - find answers, and help other users. - -- [Join us on Gitter](https://gitter.im/cockroachdb/cockroach) - This is the most immediate - way to connect with CockroachDB engineers. - -- For filing bugs, suggesting improvements, or requesting new features, help us out by - [opening an issue](https://github.com/cockroachdb/cockroach/issues/new). - -## Contributing - -We're an open source project and welcome contributions. - -1. See [CONTRIBUTING.md](https://github.com/cockroachdb/cockroach/blob/master/CONTRIBUTING.md) to get your local environment set up. - -2. Take a look at our [open issues](https://github.com/cockroachdb/cockroach/issues/), in particular those with the [helpwanted label](https://github.com/cockroachdb/cockroach/labels/helpwanted). - -3. Review our [style guide](https://github.com/cockroachdb/cockroach/blob/master/CONTRIBUTING.md#style-guide) and follow our [code reviews](https://github.com/cockroachdb/cockroach/pulls) to learn about our style and conventions. - -4. Make your changes according to our [code review workflow](https://github.com/cockroachdb/cockroach/blob/master/CONTRIBUTING.md#code-review-workflow). - -## Design - -This is an overview. For an in-depth discussion of the design and architecture, see the full [design doc](https://github.com/cockroachdb/cockroach/blob/master/docs/design.md). - -For another quick design overview, see the [CockroachDB tech talk slides](https://docs.google.com/presentation/d/1tPPhnpJ3UwyYMe4MT8jhqCrE9ZNrUMqsvXAbd97DZ2E/edit#slide=id.p). - -### Design Goals - -CockroachDB is a distributed SQL database built on top of a -transactional and consistent key:value store. - -The primary design goals are support for ACID transactions, horizontal scalability and survivability, hence the name. - -It aims to tolerate disk, machine, rack, and even datacenter failures with minimal latency disruption and no manual intervention. - -CockroachDB nodes are symmetric; a design goal is homogeneous deployment (one binary) with minimal configuration. - -### How it Works in a Nutshell - -CockroachDB implements a single, monolithic sorted map from key to value -where both keys and values are byte strings (not unicode). - -The map is composed of one or more ranges and each range is backed by -data stored in [RocksDB][0] (a variant of [LevelDB][1]), and is -replicated to a total of three or more CockroachDB servers. This -enables CockroachDB to scale linearly — theoretically up to 4 exabytes -(4E) of logical data. - -Ranges are defined by start and end keys. Ranges are merged and split -to maintain total byte size within a globally configurable min/max -size interval. Range sizes default to target 64M in order to -facilitate quick splits and merges and to distribute load at hotspots -within a key range. Range replicas are intended to be located in -disparate datacenters for survivability (e.g. `{ US-East, US-West, -Japan }`, `{ Ireland, US-East, US-West}` , `{ Ireland, US-East, -US-West, Japan, Australia }`). - -Single mutations to ranges are mediated via an instance of a -distributed consensus algorithm to ensure consistency. We’ve chosen to -use the [Raft consensus algorithm][2]. All consensus state is also -stored in [RocksDB][0]. - -A single logical mutation may affect multiple key/value pairs. Logical -mutations have ACID transactional semantics. If all keys affected by a -logical mutation fall within the same range, atomicity and consistency -are guaranteed by [Raft][2]; this is the fast commit path. Otherwise, a -non-locking distributed commit protocol is employed between affected -ranges. - -CockroachDB provides snapshot isolation (SI) and serializable snapshot -isolation (SSI) semantics, allowing externally consistent, lock-free -reads and writes--both from an historical snapshot timestamp and from -the current wall clock time. SI provides lock-free reads and writes -but still allows write skew. SSI eliminates write skew, but introduces -a performance hit in the case of a contentious system. SSI is the -default isolation; clients must consciously decide to trade -correctness for performance. CockroachDB implements a limited form of -linearalizability, providing ordering for any observer or chain of -observers. - -Similar to [Spanner][3] directories, CockroachDB allows configuration of -arbitrary zones of data. This allows replication factor, storage -device type, and/or datacenter location to be chosen to optimize -performance and/or availability. Unlike Spanner, zones are monolithic -and don’t allow movement of fine grained data on the level of entity -groups. - -## Comparison with Other Databases - -To see how key features of CockroachDB stack up against other databases, -visit the [CockroachDB in Comparison](https://www.cockroachlabs.com/docs/cockroachdb-in-comparison.html) page on our website. - -## See Also - -- [Tech Talks](https://www.cockroachlabs.com/community/tech-talks/) by CockroachDB founders and engineers -- [The CockroachDB User documentation](https://cockroachlabs.com/docs/) -- [The CockroachDB Blog](https://www.cockroachlabs.com/blog/) -- Key Design documents: - - [Serializable, Lockless, Distributed: Isolation in CockroachDB](https://www.cockroachlabs.com/blog/serializable-lockless-distributed-isolation-cockroachdb/) - - [Consensus, Made Thrive](https://www.cockroachlabs.com/blog/consensus-made-thrive/) - - [Trust, But Verify: How CockroachDB Checks Replication](https://www.cockroachlabs.com/blog/trust-but-verify-cockroachdb-checks-replication/) - - [Living Without Atomic Clocks](https://www.cockroachlabs.com/blog/living-without-atomic-clocks/) - - [The CockroachDB Architecture Document](https://github.com/cockroachdb/cockroach/blob/master/docs/design.md) - -[0]: http://rocksdb.org/ -[1]: https://github.com/google/leveldb -[2]: https://ramcloud.stanford.edu/wiki/download/attachments/11370504/raft.pdf -[3]: http://research.google.com/archive/spanner.html diff --git a/vendor/github.com/cockroachdb/cockroach/STYLE.md b/vendor/github.com/cockroachdb/cockroach/STYLE.md deleted file mode 100644 index 3948d6bb1..000000000 --- a/vendor/github.com/cockroachdb/cockroach/STYLE.md +++ /dev/null @@ -1,80 +0,0 @@ -# CockroachDB Style guide - -## Go Code -We're following the -[Google Go Code Review](https://code.google.com/p/go-wiki/wiki/CodeReviewComments) -fairly closely. In particular, you want to watch out for proper -punctuation and capitalization in comments. We use two-space indents -in non-Go code (in Go, we follow `gofmt` which indents with -tabs). - -### Line Length -Format your code assuming it will be read in a window 100 columns wide. -Wrap code at 100 characters and comments at 80 unless doing so makes the -code less legible. These values assume tab width is 2 characters. - -### Wrapping Function Signatures -When wrapping function signatures that do not fit on one line, -put the name, arguments, and return types on separate lines, with the closing `)` -at the same indentation as `func` (this helps visually separate the indented -arguments from the indented function body). Example: -```go -func (s *someType) myFunctionName( - arg1 somepackage.SomeArgType, arg2 int, arg3 somepackage.SomeOtherType, -) (somepackage.SomeReturnType, error) { - ... -} -``` - -If the arguments list is too long to fit on a single line, switch to one -argument per line: -```go -func (s *someType) myFunctionName( - arg1 somepackage.SomeArgType, - arg2 int, - arg3 somepackage.SomeOtherType, -) (somepackage.SomeReturnType, error) { - ... -} -``` - -If the return types need to be wrapped, use the same rules: -```go -func (s *someType) myFunctionName( - arg1 somepackage.SomeArgType, arg2 somepackage.SomeOtherType, -) ( - somepackage.SomeReturnType, - somepackage.SomeOtherType, - error, -) { - ... -} -``` - -Exception when omitting repeated types for consecutive arguments: -short and related arguments (e.g. `start, end int64`) should either go on the same line -or the type should be repeated on each line -- no argument should appear by itself -on a line with no type (confusing and brittle when edited). - -### fmt Verbs - -Prefer the most specific verb for your use. In other words, prefer to avoid %v -when possible. However, %v is to be used when formatting bindings which might -be nil and which do not already handle nil formatting. Notably, nil errors -formatted as %s will render as "%!s()" while nil errors formatted as %v -will render as "". Therefore, prefer %v when formatting errors which are -not known to be non-nil. - -### Distinguishing user errors from internal errors - -When creating an error for something that the user did wrong (and thus isn't -indicative of an unexpected situation in our code), use `fmt.Errorf()` to create -the error. - -When creating an error for an unexpected situation, use methods from the -[`errors` package that we use](https://github.com/pkg/errors), such as -`errors.New()`, `errors.Errorf()`, `errors.Wrap()`, or `errors.Wrapf()`. - -The reason for this distinction is somewhat historical (#7424), but maintaining -it will help us immensely if we ever switch to using new error types for the -different situations. diff --git a/vendor/github.com/cockroachdb/cockroach/glide.lock b/vendor/github.com/cockroachdb/cockroach/glide.lock deleted file mode 100644 index be978746b..000000000 --- a/vendor/github.com/cockroachdb/cockroach/glide.lock +++ /dev/null @@ -1,555 +0,0 @@ -hash: ed9efa1aeca5f09ddb183db3d56487d3d2ddd08b697ff8b6acfa0ae74830dbde -updated: 2017-05-17T22:17:36.659304758-04:00 -imports: -- name: cloud.google.com/go - version: ed63fb27efcf32e25fe7837e4662457d3da4c4f2 - subpackages: - - compute/metadata - - iam - - internal - - internal/optional - - internal/version - - storage -- name: github.com/abourget/teamcity - version: e241104394f91bf4e65048f9ea5d0c0f3c25b35e -- name: github.com/aws/aws-sdk-go - version: 0032dd29f2a063a66a9f4b44bf6664da3a5b71cc - subpackages: - - aws - - aws/awserr - - aws/awsutil - - aws/client - - aws/client/metadata - - aws/corehandlers - - aws/credentials - - aws/credentials/ec2rolecreds - - aws/credentials/endpointcreds - - aws/credentials/stscreds - - aws/defaults - - aws/ec2metadata - - aws/endpoints - - aws/request - - aws/session - - aws/signer/v4 - - private/protocol - - private/protocol/query - - private/protocol/query/queryutil - - private/protocol/rest - - private/protocol/restxml - - private/protocol/xml/xmlutil - - service/s3 - - service/sts -- name: github.com/Azure/azure-sdk-for-go - version: 8dd1f3ff407c300cff0a4bfedd969111ca5a7903 - subpackages: - - storage -- name: github.com/Azure/go-ansiterm - version: fa152c58bc15761d0200cb75fe958b89a9d4888e - subpackages: - - winterm -- name: github.com/Azure/go-autorest - version: a2fdd780c9a50455cecd249b00bdc3eb73a78e31 - subpackages: - - autorest - - autorest/azure - - autorest/date - - autorest/to -- name: github.com/backtrace-labs/go-bcd - version: 4ad9137a248599da4b00da0be6e71a75c9e1b8d9 -- name: github.com/biogo/store - version: 913427a1d5e89604e50ea1db0f28f34966d61602 - subpackages: - - llrb -- name: github.com/cenk/backoff - version: 5d150e7eec023ce7a124856b37c68e54b4050ac7 -- name: github.com/certifi/gocertifi - version: a9c833d2837d3b16888d55d5aafa9ffe9afb22b0 -- name: github.com/chzyer/readline - version: 41eea22f717c616615e1e59aa06cf831f9901f35 -- name: github.com/client9/misspell - version: b5fc83876cd1bf9fbb4e39afa9e503c83edce3b5 - subpackages: - - cmd/misspell -- name: github.com/cockroachdb/apd - version: 0ccdf9dd91d85d9f95d131fd2420c78c56f76c1f -- name: github.com/cockroachdb/cmux - version: 30d10be492927e2dcae0089c374c455d42414fcb -- name: github.com/cockroachdb/cockroach-go - version: 6fd53f6d2eea06acb0c7f7aa88e0547acb32441b - subpackages: - - crdb -- name: github.com/cockroachdb/crlfmt - version: ec6cff36e0bd2fa9e2ecd36b9fd6ea70568ad3ce -- name: github.com/cockroachdb/returncheck - version: e91bb28baf9de4a530d3ae7f041953b23dcce9be -- name: github.com/cockroachdb/stress - version: ce09c414594390d1d6432280c7cac55e62c6b0af -- name: github.com/codahale/hdrhistogram - version: 3a0bb77429bd3a61596f5e8a3172445844342120 -- name: github.com/codegangsta/cli - version: 0bdeddeeb0f650497d603c4ad7b20cfe685682f6 -- name: github.com/coreos/etcd - version: 6dd807481cebac062e82c5ecaecdb2c3d0f605ad - subpackages: - - raft - - raft/raftpb -- name: github.com/cpuguy83/go-md2man - version: bcc0a711c5e6bbe72c7cb13d81c7109b45267fd2 - subpackages: - - md2man -- name: github.com/dgrijalva/jwt-go - version: d2709f9f1f31ebcda9651b03077758c1f3a0018c -- name: github.com/docker/distribution - version: a528cc1fc338bd00036dbf1315a74c2ee458b094 - subpackages: - - digestset - - reference -- name: github.com/docker/docker - version: 7248742ae7127347a52ab9d215451c213b7b59da - subpackages: - - api/types - - api/types/blkiodev - - api/types/container - - api/types/events - - api/types/filters - - api/types/mount - - api/types/network - - api/types/reference - - api/types/registry - - api/types/strslice - - api/types/swarm - - api/types/time - - api/types/versions - - api/types/volume - - client - - pkg/jsonlog - - pkg/jsonmessage - - pkg/namesgenerator - - pkg/random - - pkg/stdcopy - - pkg/term - - pkg/term/windows - - pkg/tlsconfig -- name: github.com/docker/go-connections - version: e15c02316c12de00874640cd76311849de2aeed5 - subpackages: - - nat - - sockets - - tlsconfig -- name: github.com/docker/go-units - version: 0dadbb0345b35ec7ef35e228dabb8de89a65bf52 -- name: github.com/dustin/go-humanize - version: 259d2a102b871d17f30e3cd9881a642961a1e486 -- name: github.com/elastic/gosigar - version: 6c665a6256a84b6a2d1e207216e0e0d315e84135 - subpackages: - - sys/windows -- name: github.com/elazarl/go-bindata-assetfs - version: 30f82fa23fd844bd5bb1e5f216db87fd77b5eb43 -- name: github.com/facebookgo/clock - version: 600d898af40aa09a7a93ecb9265d87b0504b6f03 -- name: github.com/getsentry/raven-go - version: 221b2b44fb33f84ed3ea13f3aed62ff48c85636b - repo: https://github.com/cockroachdb/raven-go -- name: github.com/ghemawat/stream - version: 78e682abcae4f96ac7ddbe39912967a5f7cbbaa6 -- name: github.com/go-ini/ini - version: e7fea39b01aea8d5671f6858f0532f56e8bff3a5 -- name: github.com/go-ole/go-ole - version: de8695c8edbf8236f30d6e1376e20b198a028d42 - subpackages: - - oleutil -- name: github.com/gogo/protobuf - version: 100ba4e885062801d56799d78530b73b178a78f3 - subpackages: - - gogoproto - - jsonpb - - plugin/compare - - plugin/defaultcheck - - plugin/description - - plugin/embedcheck - - plugin/enumstringer - - plugin/equal - - plugin/face - - plugin/gostring - - plugin/marshalto - - plugin/oneofcheck - - plugin/populate - - plugin/size - - plugin/stringer - - plugin/testgen - - plugin/union - - plugin/unmarshal - - proto - - protoc-gen-gogo/descriptor - - protoc-gen-gogo/generator - - protoc-gen-gogo/grpc - - protoc-gen-gogo/plugin - - sortkeys - - types - - vanity - - vanity/command -- name: github.com/golang/glog - version: 23def4e6c14b4da8ac2ed8007337bc5eb5007998 -- name: github.com/golang/lint - version: cb00e5669539f047b2f4c53a421a01b0c8e172c6 - subpackages: - - golint -- name: github.com/golang/protobuf - version: c9c7427a2a70d2eb3bafa0ab2dc163e45f143317 - subpackages: - - jsonpb - - proto - - protoc-gen-go/descriptor - - protoc-gen-go/generator - - protoc-gen-go/plugin - - ptypes/any - - ptypes/timestamp -- name: github.com/golang/snappy - version: 553a641470496b2327abcac10b36396bd98e45c9 -- name: github.com/google/btree - version: 316fb6d3f031ae8f4d457c6c5186b9e3ded70435 -- name: github.com/google/go-github - version: 4b7b445665c8ce4f3c10c753b1884e2c4f09e323 - subpackages: - - github -- name: github.com/google/go-querystring - version: 53e6ce116135b80d037921a7fdd5138cf32d7a8a - subpackages: - - query -- name: github.com/google/pprof - version: c0fb62ec88c411cc91194465e54db2632845b650 - subpackages: - - driver - - internal/binutils - - internal/driver - - internal/elfexec - - internal/graph - - internal/measurement - - internal/plugin - - internal/report - - internal/symbolizer - - internal/symbolz - - profile - - third_party/svg -- name: github.com/googleapis/gax-go - version: 9af46dd5a1713e8b5cd71106287eba3cefdde50b -- name: github.com/grpc-ecosystem/grpc-gateway - version: fdcb7eab2d6ed4919e83ddcef4f199c161611e1f - subpackages: - - protoc-gen-grpc-gateway - - protoc-gen-grpc-gateway/descriptor - - protoc-gen-grpc-gateway/generator - - protoc-gen-grpc-gateway/gengateway - - protoc-gen-grpc-gateway/httprule - - runtime - - runtime/internal - - third_party/googleapis/google/api - - utilities -- name: github.com/grpc-ecosystem/grpc-opentracing - version: 6c130eed1e297e1aa4d415a50c90d0c81c52677e - subpackages: - - go/otgrpc -- name: github.com/hashicorp/go-version - version: 03c5bf6be031b6dd45afec16b1cf94fc8938bc77 -- name: github.com/ianlancetaylor/cgosymbolizer - version: 7c5585d44729f382a061b64ec9e7123724abe529 -- name: github.com/ianlancetaylor/demangle - version: 4883227f66371e02c4948937d3e2be1664d9be38 -- name: github.com/inconshreveable/mousetrap - version: 76626ae9c91c4f2a10f34cad8ce83ea42c93bb75 -- name: github.com/jmespath/go-jmespath - version: bd40a432e4c76585ef6b72d3fd96fb9b6dc7b68d -- name: github.com/jteeuwen/go-bindata - version: a0ff2567cfb70903282db057e799fd826784d41d - subpackages: - - go-bindata -- name: github.com/kisielk/errcheck - version: 23699b7e2cbfdb89481023524954ba2aeff6be90 - subpackages: - - internal/errcheck -- name: github.com/kisielk/gotool - version: 0de1eaf82fa3f583ce21fde859f1e7e0c5e9b220 -- name: github.com/knz/strtime - version: 813725a7c183ac304d1ed8fb7e37a567733e9c05 -- name: github.com/kr/pretty - version: cfb55aafdaf3ec08f0db22699ab822c50091b1c4 -- name: github.com/kr/text - version: 7cafcd837844e784b526369c9bce262804aebc60 -- name: github.com/lib/pq - version: 472a0745531a17dbac346e828b4c60e73ddff30c - subpackages: - - oid -- name: github.com/lightstep/lightstep-tracer-go - version: d9d2a958da1b2b4dd282e7685261942e20abd49c - subpackages: - - basictracer - - collectorpb - - lightstep_thrift - - lightsteppb - - thrift_0_9_2/lib/go/thrift - - thrift_rpc -- name: github.com/Masterminds/glide - version: 869001d1571ce5f03fd0078bff188b9d3f272807 - subpackages: - - action - - cache - - cfg - - dependency - - gb - - godep - - godep/strip - - gom - - gpm - - importer - - mirrors - - msg - - path - - repo - - tree - - util -- name: github.com/Masterminds/semver - version: abff1900528dbdaf6f3f5aa92c398be1eaf2a9f7 -- name: github.com/Masterminds/vcs - version: 3084677c2c188840777bff30054f2b553729d329 -- name: github.com/mattn/go-isatty - version: fc9e8d8ef48496124e79ae0df75490096eccf6fe -- name: github.com/mattn/go-runewidth - version: 9e777a8366cce605130a531d2cd6363d07ad7317 - subpackages: - - runewidth.go -- name: github.com/mattn/goveralls - version: a2cbbd7cdce4f5e051016fedf639c64bb05ef031 -- name: github.com/matttproud/golang_protobuf_extensions - version: c12348ce28de40eed0136aa2b644d0ee0650e56c - subpackages: - - pbutil -- name: github.com/mdempsky/unconvert - version: beb68d938016d2dec1d1b078054f4d3db25f97be -- name: github.com/mibk/dupl - version: 3447d9b0cb5a3e7dccb1a9f1c975f35683f304e6 - subpackages: - - job - - output - - suffixtree - - syntax - - syntax/golang -- name: github.com/Microsoft/go-winio - version: d311c76e775b5092c023569caacdbb4e569c3243 -- name: github.com/mitchellh/go-homedir - version: b8bc1bf767474819792c23f32d8286a45736f1c6 -- name: github.com/mitchellh/reflectwalk - version: 8d802ff4ae93611b807597f639c19f76074df5c6 -- name: github.com/montanaflynn/stats - version: 41c34e4914ec3c05d485e564d9028d8861d5d9ad -- name: github.com/olekukonko/tablewriter - version: a0225b3f23b5ce0cbec6d7a66a968f8a59eca9c4 -- name: github.com/opencontainers/go-digest - version: eaa60544f31ccf3b0653b1a118b76d33418ff41b -- name: github.com/opentracing/opentracing-go - version: eaaf4e1eeb7a5373b38e70901270c83577dc6fb9 - subpackages: - - ext - - log -- name: github.com/petermattis/goid - version: 0ded85884ba5c4c9267fcd5a149061f7c3455eee -- name: github.com/pkg/errors - version: c605e284fe17294bda444b34710735b29d1a9d90 -- name: github.com/prometheus/client_model - version: 6f3806018612930941127f2a7c6c453ba2c527d2 - subpackages: - - go -- name: github.com/prometheus/common - version: 49fee292b27bfff7f354ee0f64e1bc4850462edf - subpackages: - - expfmt - - internal/bitbucket.org/ww/goautoneg - - model -- name: github.com/rcrowley/go-metrics - version: 1f30fe9094a513ce4c700b9a54458bbb0c96996c - subpackages: - - exp -- name: github.com/rlmcpherson/s3gof3r - version: 864ae0bf7cf2e20c0002b7ea17f4d84fec1abc14 -- name: github.com/rubyist/circuitbreaker - version: 2074adba5ddc7d5f7559448a9c3066573521c5bf -- name: github.com/russross/blackfriday - version: 0ba0f2b6ed7c475a92e4df8641825cb7a11d1fa3 -- name: github.com/sasha-s/go-deadlock - version: 341000892f3dd25f440e6231e8533eb3688ed7ec -- name: github.com/satori/go.uuid - version: 5bf94b69c6b68ee1b541973bb8e1144db23a194b -- name: github.com/Sirupsen/logrus - version: 5e5dc898656f695e2a086b8e12559febbfc01562 -- name: github.com/spf13/cobra - version: 7aeaa2cce6ae7e18d2a6ee597b60ee137e999bd9 - subpackages: - - doc -- name: github.com/spf13/pflag - version: e57e3eeb33f795204c1ca35f56c44f83227c6e66 -- name: github.com/StackExchange/wmi - version: ea383cf3ba6ec950874b8486cd72356d007c768f -- name: github.com/tebeka/go2xunit - version: 3d745e6f4de3e1e94034d7cfb3cc0c543b080b49 - subpackages: - - lib -- name: github.com/VividCortex/ewma - version: c595cd886c223c6c28fc9ae2727a61b5e4693d85 -- name: github.com/wadey/gocovmerge - version: b5bfa59ec0adc420475f97f89b58045c721d761c -- name: golang.org/x/crypto - version: 728b753d0135da6801d45a38e6f43ff55779c5c2 - subpackages: - - bcrypt - - blowfish - - ssh/terminal -- name: golang.org/x/net - version: a6577fac2d73be281a500b310739095313165611 - subpackages: - - context - - context/ctxhttp - - http2 - - http2/hpack - - idna - - internal/timeseries - - lex/httplex - - proxy - - trace -- name: golang.org/x/oauth2 - version: f047394b6d14284165300fd82dad67edb3a4d7f6 - subpackages: - - google - - internal - - jws - - jwt -- name: golang.org/x/perf - version: 844f0140c89c0be84e3d3143f075ccff10819462 - subpackages: - - benchstat - - cmd/benchstat - - internal/stats - - storage/benchfmt -- name: golang.org/x/sync - version: f52d1811a62927559de87708c8913c1650ce4f26 - subpackages: - - errgroup - - singleflight -- name: golang.org/x/sys - version: 1e4778a9a153163315e71a39674fbe87fe8f30a5 - subpackages: - - unix - - windows -- name: golang.org/x/text - version: 470f45bf29f4147d6fbd7dfd0a02a848e49f5bf4 - subpackages: - - collate - - internal/colltab - - internal/tag - - language - - transform - - unicode/norm - - width -- name: golang.org/x/time - version: 8be79e1e0910c292df4e79c241bb7e8f7e725959 - subpackages: - - rate -- name: golang.org/x/tools - version: bf4b54dc687c73b6ef63de8b8abf0ad3951e3edc - subpackages: - - cmd/goimports - - cmd/gorename - - cmd/goyacc - - cmd/guru - - cmd/guru/serial - - cmd/stringer - - container/intsets - - cover - - go/ast/astutil - - go/buildutil - - go/callgraph - - go/callgraph/static - - go/gcexportdata - - go/gcimporter15 - - go/loader - - go/pointer - - go/ssa - - go/ssa/ssautil - - go/types/typeutil - - imports - - refactor/importgraph - - refactor/rename - - refactor/satisfy -- name: google.golang.org/api - version: 1377dd16e29553e6d668e68fd207a75a66574646 - subpackages: - - gensupport - - googleapi - - googleapi/internal/uritemplates - - googleapi/transport - - internal - - iterator - - option - - storage/v1 - - transport -- name: google.golang.org/appengine - version: 170382fa85b10b94728989dfcf6cc818b335c952 - subpackages: - - internal - - internal/app_identity - - internal/base - - internal/datastore - - internal/log - - internal/modules - - internal/remote_api - - internal/socket - - internal/urlfetch - - socket - - urlfetch -- name: google.golang.org/genproto - version: bb3573be0c484136831138976d444b8754777aff - subpackages: - - googleapis/api/annotations - - googleapis/iam/v1 - - googleapis/rpc/status -- name: google.golang.org/grpc - version: 3419b42955675df23457629c75f58eb8dcd56954 - subpackages: - - codes - - credentials - - credentials/oauth - - grpclb/grpc_lb_v1 - - grpclog - - internal - - keepalive - - metadata - - naming - - peer - - stats - - status - - tap - - transport -- name: gopkg.in/yaml.v2 - version: a3f3340b5840cee44f372bddb5880fcbc419b46a -- name: honnef.co/go/tools - version: aeda00f7ca49ce710df354fc703b08d94d3a23c0 - subpackages: - - callgraph - - callgraph/static - - functions - - gcsizes - - internal/sharedcheck - - lint - - lint/lintutil - - simple - - ssa - - ssa/ssautil - - staticcheck - - staticcheck/vrp - - unused -testImports: -- name: github.com/go-sql-driver/mysql - version: 382e13d099fcf5f5994290892ab258fbebbdc5e3 -- name: github.com/opentracing/basictracer-go - version: 1b32af207119a14b1b231d451df3ed04a72efebf - subpackages: - - wire diff --git a/vendor/github.com/cockroachdb/cockroach/glide.yaml b/vendor/github.com/cockroachdb/cockroach/glide.yaml deleted file mode 100644 index 0b23062d3..000000000 --- a/vendor/github.com/cockroachdb/cockroach/glide.yaml +++ /dev/null @@ -1,62 +0,0 @@ -package: github.com/cockroachdb/cockroach -import: -# Pins due to known upstream issues that prevent updates. -# These must stay until the issue is resolved, and should include a comment -# linking to or summarizing the upstream issue. -# -# https://github.com/docker/docker/issues/29362 -- package: github.com/docker/docker - version: 7248742ae7127347a52ab9d215451c213b7b59da -# We pin glide itself to prevent changes to glide's dependency resolution -# algorithm from modifying our dependencies unexpectedly. -- package: github.com/Masterminds/glide - version: 869001d1571ce5f03fd0078bff188b9d3f272807 - -# https://github.com/cockroachdb/raven-go/pulls/1 avoids banned go/build import. -- package: github.com/getsentry/raven-go - version: aa4f14680cc759ef40791558d93c90c6f629c10f - repo: https://github.com/cockroachdb/raven-go - -# The collation tables must never change. -- package: golang.org/x/text - version: 470f45bf29f4147d6fbd7dfd0a02a848e49f5bf4 - -# TODO(dt,mjibson): API changed -- package: github.com/Azure/azure-sdk-for-go - version: 8dd1f3ff407c300cff0a4bfedd969111ca5a7903 - -# Pins to prevent unintended version changes to libs we care about when adding/ -# removing/changing other deps. These are grouped separately to make it easier -# to comment them out in bulk when running an across-the-board dep update. -- package: cloud.google.com/go - version: ed63fb27efcf32e25fe7837e4662457d3da4c4f2 -- package: github.com/cockroachdb/apd - version: 0ccdf9dd91d85d9f95d131fd2420c78c56f76c1f -- package: github.com/cockroachdb/cmux - version: 30d10be492927e2dcae0089c374c455d42414fcb -- package: github.com/cockroachdb/cockroach-go - version: 6fd53f6d2eea06acb0c7f7aa88e0547acb32441b -- package: github.com/coreos/etcd - version: 6dd807481cebac062e82c5ecaecdb2c3d0f605ad -- package: github.com/gogo/protobuf - version: 100ba4e885062801d56799d78530b73b178a78f3 -- package: github.com/golang/protobuf - version: c9c7427a2a70d2eb3bafa0ab2dc163e45f143317 -- package: github.com/google/btree - version: 316fb6d3f031ae8f4d457c6c5186b9e3ded70435 -- package: github.com/grpc-ecosystem/grpc-gateway - version: fdcb7eab2d6ed4919e83ddcef4f199c161611e1f -- package: github.com/lib/pq - version: 472a0745531a17dbac346e828b4c60e73ddff30c -- package: github.com/spf13/cobra - version: 7aeaa2cce6ae7e18d2a6ee597b60ee137e999bd9 -- package: gopkg.in/yaml.v2 - version: a3f3340b5840cee44f372bddb5880fcbc419b46a -- package: golang.org/x/crypto - version: 728b753d0135da6801d45a38e6f43ff55779c5c2 -- package: golang.org/x/net - version: a6577fac2d73be281a500b310739095313165611 -- package: golang.org/x/sys - version: 1e4778a9a153163315e71a39674fbe87fe8f30a5 -- package: google.golang.org/grpc - version: 3419b42955675df23457629c75f58eb8dcd56954 diff --git a/vendor/github.com/cockroachdb/cockroach/main.go b/vendor/github.com/cockroachdb/cockroach/main.go deleted file mode 100644 index cdce3f397..000000000 --- a/vendor/github.com/cockroachdb/cockroach/main.go +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2014 The Cockroach Authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -// implied. See the License for the specific language governing -// permissions and limitations under the License. -// -// Author: Spencer Kimball (spencer.kimball@gmail.com) - -package main - -// The ccl hook import below means building this will produce CCL'ed binaries. -// This file itself remains Apache2 to preserve the organization of ccl code -// under the /pkg/ccl subtree, but is unused for pure FLOSS builds. -import ( - _ "github.com/cockroachdb/cockroach/pkg/ccl" // ccl init hooks - "github.com/cockroachdb/cockroach/pkg/cli" -) - -func main() { - cli.Main() -} diff --git a/vendor/github.com/cockroachdb/cockroach/pkg/Makefile b/vendor/github.com/cockroachdb/cockroach/pkg/Makefile deleted file mode 100644 index 540448933..000000000 --- a/vendor/github.com/cockroachdb/cockroach/pkg/Makefile +++ /dev/null @@ -1,20 +0,0 @@ -# This is a convenience Makefile which defers all real work to -# ../Makefile. The % rule is run for any target specified on the -# command line. We use the builtin MAKECMDGOALS and MAKEFLAGS -# variables (the command line targets and flags respectively) to -# perform our recursive make invocation. Lastly, we take care to make -# any PKG specification relative to "./pkg". -# -# We use a level of indirection through the "default" rule so that -# specifying multiple targets on the command line (e.g. "make test -# lint") does not result in multiple invocations of the rule. -# -# The rule needs an action (i.e. "@true") because reasons (I'm not -# really sure why - Peter). -%: default - @true - -.PHONY: default -default: - @$(MAKE) -C .. $(MAKECMDGOALS) \ - $(patsubst PKG=%,PKG=./pkg/%,$(filter PKG=%,$(MAKEFLAGS))) diff --git a/vendor/github.com/cockroachdb/cockroach/pkg/ccl/utilccl/license_check.go b/vendor/github.com/cockroachdb/cockroach/pkg/ccl/utilccl/license_check.go new file mode 100644 index 000000000..26bb26f73 --- /dev/null +++ b/vendor/github.com/cockroachdb/cockroach/pkg/ccl/utilccl/license_check.go @@ -0,0 +1,39 @@ +// Copyright 2017 The Cockroach Authors. +// +// Licensed as a CockroachDB Enterprise file under the Cockroach Community +// License (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// https://github.com/cockroachdb/cockroach/blob/master/LICENSE + +package utilccl + +import ( + "github.com/cockroachdb/cockroach/pkg/settings" + "github.com/pkg/errors" +) + +// EnterpriseEnabled is temporary, until #14114 is implemented. +var EnterpriseEnabled = func() *settings.BoolSetting { + s := settings.RegisterBoolSetting("enterprise.enabled", "set to true to enable Enterprise features", false) + s.Hide() + return s +}() + +// CheckEnterpriseEnabled returns a non-nil error if the requested enterprise +// feature is not enabled, including information or a link explaining how to +// enable it. +func CheckEnterpriseEnabled(feature string) error { + if EnterpriseEnabled.Get() { + return nil + } + // TODO(dt): link to some stable URL that then redirects to a helpful page + // that explains what to do here. + link := "https://cockroachlabs.com/pricing" + return errors.Errorf( + "use of %s requires an enterprise license. "+ + "see %s for details on how to enable enterprise features", + feature, + link, + ) +} diff --git a/vendor/github.com/cockroachdb/cockroach/pkg/util/duration.go b/vendor/github.com/cockroachdb/cockroach/pkg/util/duration.go deleted file mode 100644 index d6d8d88a9..000000000 --- a/vendor/github.com/cockroachdb/cockroach/pkg/util/duration.go +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright 2014 The Cockroach Authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -// implied. See the License for the specific language governing -// permissions and limitations under the License. -// -// Author: Tobias Schottdorf - -package util - -import "time" - -// TruncateDuration returns a new duration obtained from the first argument -// by discarding the portions at finer resolution than that given by the -// second argument. -// Example: TruncateDuration(time.Second+1, time.Second) == time.Second. -func TruncateDuration(d time.Duration, r time.Duration) time.Duration { - if r == 0 { - panic("zero passed as resolution") - } - return d - (d % r) -} diff --git a/vendor/github.com/cockroachdb/cockroach/pkg/util/duration_test.go b/vendor/github.com/cockroachdb/cockroach/pkg/util/duration_test.go deleted file mode 100644 index 0e74ae71c..000000000 --- a/vendor/github.com/cockroachdb/cockroach/pkg/util/duration_test.go +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright 2014 The Cockroach Authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -// implied. See the License for the specific language governing -// permissions and limitations under the License. -// -// Author: Tobias Schottdorf - -package util - -import ( - "testing" - "time" -) - -func TestTruncateDuration(t *testing.T) { - zero := time.Duration(0).String() - testCases := []struct { - d, r time.Duration - s string - }{ - {0, 1, zero}, - {0, 1, zero}, - {time.Second, 1, "1s"}, - {time.Second, 2 * time.Second, zero}, - {time.Second + 1, time.Second, "1s"}, - {11 * time.Nanosecond, 10 * time.Nanosecond, "10ns"}, - {time.Hour + time.Nanosecond + 3*time.Millisecond + time.Second, time.Millisecond, "1h0m1.003s"}, - } - for i, tc := range testCases { - if s := TruncateDuration(tc.d, tc.r).String(); s != tc.s { - t.Errorf("%d: (%s,%s) should give %s, but got %s", i, tc.d, tc.r, tc.s, s) - } - } -} diff --git a/vendor/github.com/cockroachdb/cockroach/pkg/util/nocopy.go b/vendor/github.com/cockroachdb/cockroach/pkg/util/nocopy.go deleted file mode 100644 index e10421e28..000000000 --- a/vendor/github.com/cockroachdb/cockroach/pkg/util/nocopy.go +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright 2016 The Cockroach Authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -// implied. See the License for the specific language governing -// permissions and limitations under the License. -// -// Author: Radu Berinde (radu@cockroachlabs.com) - -package util - -// NoCopy may be embedded into structs which must not be copied -// after the first use. -// -// See https://github.com/golang/go/issues/8005#issuecomment-190753527 -// for details. -type NoCopy struct{} - -// Lock is a no-op used by -copylocks checker from `go vet`. -func (*NoCopy) Lock() {} diff --git a/vendor/github.com/cockroachdb/cockroach/pkg/util/pluralize.go b/vendor/github.com/cockroachdb/cockroach/pkg/util/pluralize.go deleted file mode 100644 index 7f8ba2d41..000000000 --- a/vendor/github.com/cockroachdb/cockroach/pkg/util/pluralize.go +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright 2016 The Cockroach Authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -// implied. See the License for the specific language governing -// permissions and limitations under the License. -// -// Author: Peter Mattis (peter@cockroachlabs.com) - -package util - -// Pluralize returns a single character 's' unless n == 1. -func Pluralize(n int64) string { - if n == 1 { - return "" - } - return "s" -} diff --git a/vendor/github.com/cockroachdb/cockroach/pkg/util/protoutil/clone_test.go b/vendor/github.com/cockroachdb/cockroach/pkg/util/protoutil/clone_test.go deleted file mode 100644 index 8233e7547..000000000 --- a/vendor/github.com/cockroachdb/cockroach/pkg/util/protoutil/clone_test.go +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright 2016 The Cockroach Authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -// implied. See the License for the specific language governing -// permissions and limitations under the License. -// -// Author: Tamir Duberstein (tamird@gmail.com) - -package protoutil_test - -import ( - "fmt" - "reflect" - "strings" - "testing" - - "github.com/gogo/protobuf/proto" - - "github.com/cockroachdb/cockroach/pkg/config" - "github.com/cockroachdb/cockroach/pkg/gossip" - "github.com/cockroachdb/cockroach/pkg/roachpb" - "github.com/cockroachdb/cockroach/pkg/sql/sqlbase" - "github.com/cockroachdb/cockroach/pkg/storage/engine/enginepb" - "github.com/cockroachdb/cockroach/pkg/storage/storagebase" - "github.com/cockroachdb/cockroach/pkg/util/protoutil" -) - -func TestCloneProto(t *testing.T) { - testCases := []struct { - pb proto.Message - shouldPanic bool - }{ - // Uncloneable types (all contain UUID fields). - {&roachpb.StoreIdent{}, true}, - {&enginepb.TxnMeta{}, true}, - {&roachpb.Transaction{}, true}, - {&roachpb.Error{}, true}, - - // Cloneable types. This includes all types for which a - // protoutil.Clone call exists in the codebase as of 2016-11-21. - {&config.ZoneConfig{}, false}, - {&gossip.Info{}, false}, - {&gossip.BootstrapInfo{}, false}, - {&sqlbase.IndexDescriptor{}, false}, - {&roachpb.SplitTrigger{}, false}, - {&roachpb.Value{}, false}, - {&storagebase.ReplicaState{}, false}, - {&roachpb.RangeDescriptor{}, false}, - } - for _, tc := range testCases { - var clone proto.Message - var panicObj interface{} - func() { - defer func() { - panicObj = recover() - }() - clone = protoutil.Clone(tc.pb) - }() - - if tc.shouldPanic { - if panicObj == nil { - t.Errorf("%T: expected panic but didn't get one", tc.pb) - } else { - if panicStr := fmt.Sprint(panicObj); !strings.Contains(panicStr, "attempt to clone") { - t.Errorf("%T: got unexpected panic %s", tc.pb, panicStr) - } - } - } else { - if panicObj != nil { - t.Errorf("%T: got unexpected panic %v", tc.pb, panicObj) - } - } - - if panicObj == nil { - realClone := proto.Clone(tc.pb) - if !reflect.DeepEqual(clone, realClone) { - t.Errorf("%T: clone did not equal original. expected:\n%+v\ngot:\n%+v", tc.pb, realClone, clone) - } - } - } -} diff --git a/vendor/github.com/cockroachdb/cockroach/pkg/util/reflect.go b/vendor/github.com/cockroachdb/cockroach/pkg/util/reflect.go deleted file mode 100644 index 781ce41cd..000000000 --- a/vendor/github.com/cockroachdb/cockroach/pkg/util/reflect.go +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright 2016 The Cockroach Authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -// implied. See the License for the specific language governing -// permissions and limitations under the License. -// -// Author: Tamir Duberstein (tamird@gmail.com) - -package util - -import "reflect" - -// EqualPtrFields uses reflection to check two "mirror" structures for matching pointer fields that -// point to the same object. Used to verify cloning/deep copy functions. -func EqualPtrFields(src, dst reflect.Value, prefix string) []string { - t := dst.Type() - if t.Kind() != reflect.Struct { - return nil - } - if srcType := src.Type(); srcType != t { - return nil - } - var res []string - for i := 0; i < t.NumField(); i++ { - srcF, dstF := src.Field(i), dst.Field(i) - switch f := t.Field(i); f.Type.Kind() { - case reflect.Ptr: - if srcF.Interface() == dstF.Interface() { - res = append(res, prefix+f.Name) - } - case reflect.Slice: - if srcF.Pointer() == dstF.Pointer() { - res = append(res, prefix+f.Name) - } - l := dstF.Len() - if srcLen := srcF.Len(); srcLen < l { - l = srcLen - } - for i := 0; i < l; i++ { - res = append(res, EqualPtrFields(srcF.Index(i), dstF.Index(i), f.Name+".")...) - } - case reflect.Struct: - res = append(res, EqualPtrFields(srcF, dstF, f.Name+".")...) - } - } - return res -} diff --git a/vendor/github.com/cockroachdb/cockroach/pkg/util/retry.go b/vendor/github.com/cockroachdb/cockroach/pkg/util/retry.go deleted file mode 100644 index 7ff7e5009..000000000 --- a/vendor/github.com/cockroachdb/cockroach/pkg/util/retry.go +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright 2016 The Cockroach Authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -// implied. See the License for the specific language governing -// permissions and limitations under the License. - -package util - -import ( - "time" - - "github.com/cockroachdb/cockroach/pkg/util/timeutil" -) - -// RetryForDuration will retry the given function until it either returns -// without error, or the given duration has elapsed. The function is invoked -// immediately at first and then successively with an exponential backoff -// starting at 1ns and ending at the specified duration. -func RetryForDuration(duration time.Duration, fn func() error) error { - deadline := timeutil.Now().Add(duration) - var lastErr error - for wait := time.Duration(1); timeutil.Now().Before(deadline); wait *= 2 { - lastErr = fn() - if lastErr == nil { - return nil - } - if wait > time.Second { - wait = time.Second - } - time.Sleep(wait) - } - return lastErr -} diff --git a/vendor/github.com/cockroachdb/cockroach/pkg/util/roundup2.go b/vendor/github.com/cockroachdb/cockroach/pkg/util/roundup2.go deleted file mode 100644 index 613f729a0..000000000 --- a/vendor/github.com/cockroachdb/cockroach/pkg/util/roundup2.go +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright 2016 The Cockroach Authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -// implied. See the License for the specific language governing -// permissions and limitations under the License. -// -// Author: Raphael 'kena' Poss (knz@cockroachlabs.com) - -package util - -// RoundUpPowerOfTwo returns the first power of 2 greater or equal to the number. -// Source: http://graphics.stanford.edu/%7Eseander/bithacks.html#RoundUpPowerOf2 -func RoundUpPowerOfTwo(x int64) int64 { - x-- - x |= x >> 1 - x |= x >> 2 - x |= x >> 4 - x |= x >> 8 - x |= x >> 16 - x |= x >> 32 - return x + 1 -} diff --git a/vendor/github.com/cockroachdb/cockroach/pkg/util/smalltrace.go b/vendor/github.com/cockroachdb/cockroach/pkg/util/smalltrace.go deleted file mode 100644 index 7ce089f88..000000000 --- a/vendor/github.com/cockroachdb/cockroach/pkg/util/smalltrace.go +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright 2016 The Cockroach Authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -// implied. See the License for the specific language governing -// permissions and limitations under the License. -// -// Author: Raphael 'kena' Poss (knz@cockroachlabs.com) - -package util - -import ( - "fmt" - "runtime" - "strings" -) - -// GetSmallTrace produces a ":"-separated single line containing the -// topmost 5 callers from a given skip level. -func GetSmallTrace(skip int) string { - var pcs [5]uintptr - nCallers := runtime.Callers(skip, pcs[:]) - callers := make([]string, 0, nCallers) - frames := runtime.CallersFrames(pcs[:]) - - for { - f, more := frames.Next() - function := strings.TrimPrefix(f.Function, "github.com/cockroachdb/cockroach/pkg/") - callers = append(callers, fmt.Sprintf("%s:%d", function, f.Line)) - if !more { - break - } - } - - return strings.Join(callers, ",") -} diff --git a/vendor/github.com/cockroachdb/cockroach/pkg/util/smalltrace_test.go b/vendor/github.com/cockroachdb/cockroach/pkg/util/smalltrace_test.go deleted file mode 100644 index 5c627c22e..000000000 --- a/vendor/github.com/cockroachdb/cockroach/pkg/util/smalltrace_test.go +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright 2016 The Cockroach Authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -// implied. See the License for the specific language governing -// permissions and limitations under the License. -// -// Author: Raphael 'kena' Poss (knz@cockroachlabs.com) - -package util - -import ( - "strings" - "testing" -) - -func testSmallTrace2(t *testing.T) { - s := GetSmallTrace(2) - if !strings.Contains(s, "util.testSmallTrace:32,util.TestGenerateSmallTrace:36") { - t.Fatalf("trace not generated properly: %q", s) - } -} - -func testSmallTrace(t *testing.T) { - testSmallTrace2(t) -} - -func TestGenerateSmallTrace(t *testing.T) { - testSmallTrace(t) -} diff --git a/vendor/github.com/cockroachdb/cockroach/pkg/util/syncutil/mutex_sync_test.go b/vendor/github.com/cockroachdb/cockroach/pkg/util/syncutil/mutex_sync_test.go deleted file mode 100644 index fe0da37cc..000000000 --- a/vendor/github.com/cockroachdb/cockroach/pkg/util/syncutil/mutex_sync_test.go +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright 2017 The Cockroach Authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -// implied. See the License for the specific language governing -// permissions and limitations under the License. - -// +build !deadlock - -package syncutil - -import "testing" - -func TestAssertHeld(t *testing.T) { - type mutex interface { - Lock() - Unlock() - AssertHeld() - } - - testCases := []struct { - m mutex - }{ - {&Mutex{}}, - {&RWMutex{}}, - } - for _, c := range testCases { - // The normal, successful case. - c.m.Lock() - c.m.AssertHeld() - c.m.Unlock() - - func() { - defer func() { - if r := recover(); r == nil { - t.Fatal("did not get expected panic") - } else if a, e := r.(string), "mutex is not locked"; a != e { - t.Fatalf("got %q, expected %q", a, e) - } - }() - c.m.AssertHeld() - }() - } -} diff --git a/vendor/github.com/cockroachdb/cockroach/pkg/util/testaddr_default.go b/vendor/github.com/cockroachdb/cockroach/pkg/util/testaddr_default.go deleted file mode 100644 index 8b27be5ae..000000000 --- a/vendor/github.com/cockroachdb/cockroach/pkg/util/testaddr_default.go +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2016 The Cockroach Authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -// implied. See the License for the specific language governing -// permissions and limitations under the License. See the AUTHORS file -// for names of contributors. -// -// Author: Ben Darnell - -// +build !linux - -package util - -func init() { - IsolatedTestAddr = TestAddr -} diff --git a/vendor/github.com/cockroachdb/cockroach/pkg/util/testaddr_random.go b/vendor/github.com/cockroachdb/cockroach/pkg/util/testaddr_random.go deleted file mode 100644 index a554f3e7f..000000000 --- a/vendor/github.com/cockroachdb/cockroach/pkg/util/testaddr_random.go +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2016 The Cockroach Authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -// implied. See the License for the specific language governing -// permissions and limitations under the License. See the AUTHORS file -// for names of contributors. -// -// Author: Ben Darnell - -// +build linux - -package util - -import ( - "fmt" - - "github.com/cockroachdb/cockroach/pkg/util/randutil" -) - -func init() { - r, _ := randutil.NewPseudoRand() - // 127.255.255.255 is special (broadcast), so choose values less - // than 255. - a := r.Intn(255) - b := r.Intn(255) - c := r.Intn(255) - IsolatedTestAddr = NewUnresolvedAddr("tcp", fmt.Sprintf("127.%d.%d.%d:0", a, b, c)) -} diff --git a/vendor/github.com/cockroachdb/cockroach/pkg/util/topk.go b/vendor/github.com/cockroachdb/cockroach/pkg/util/topk.go deleted file mode 100644 index 6ded7239d..000000000 --- a/vendor/github.com/cockroachdb/cockroach/pkg/util/topk.go +++ /dev/null @@ -1,109 +0,0 @@ -// Copyright 2016 The Cockroach Authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -// implied. See the License for the specific language governing -// permissions and limitations under the License. -// -// Author: Radu Berinde (radu@cockroachlabs.com) - -package util - -import ( - "fmt" - "math/rand" - "sort" -) - -var vals []int - -// moveTopKToFront swaps elements in the range [start, end) so that all elements -// in the range [start, k) are <= than all elements in the range [k, end). -func moveTopKToFront(data sort.Interface, start, end, k int, rng *rand.Rand) { - if k < start || k > end { - panic(fmt.Sprintf("k (%d) outside of range [%d, %d)", k, start, end)) - } - if k == start || k == end { - return - } - - // The strategy is to choose a random pivot and partition the data into - // three regions: elements < pivot, elements == pivot, elements > pivot. - // - // We first partition into two regions: elements <= pivot and - // elements > pivot and further refine the first region if necessary. - - // Choose a random pivot and move it to the front. - data.Swap(start, start+rng.Intn(end-start)) - pivot := start - l, r := start+1, end - for l < r { - // Invariants: - // - elements in the range [start, l) are <= pivot - // - elements in the range [r, end) are > pivot - if !data.Less(pivot, l) { - l++ - } else if data.Less(pivot, r-1) { - r-- - } else { - data.Swap(l, r-1) - l++ - r-- - } - } - mid := l - // Everything in the range [start, mid) is <= than the pivot. - // Everything in the range [mid, end) is > than the pivot. - if k >= mid { - // In this case, we eliminated at least the pivot (and all elements - // equal to it). - moveTopKToFront(data, mid, end, k, rng) - return - } - - // If we eliminated a decent amount of elements, we can recurse on [0, mid). - // If the elements were distinct we would do this unconditionally, but in - // general we could have a lot of elements equal to the pivot. - if end-mid > (end-start)/4 { - moveTopKToFront(data, start, mid, k, rng) - return - } - - // Now we work on the range [0, mid). Move everything that is equal to the - // pivot to the back. - data.Swap(pivot, mid-1) - pivot = mid - 1 - for l, r = start, pivot-1; l <= r; { - if data.Less(l, pivot) { - l++ - } else { - data.Swap(l, r) - r-- - } - } - // Now everything in the range [start, l) is < than the pivot. Everything in the - // range [l, mid) is equal to the pivot. If k is in the [l, mid) range we - // are done, otherwise we recurse on [start, l). - if k <= l { - moveTopKToFront(data, start, l, k, rng) - } -} - -// MoveTopKToFront moves the top K elements to the front. It makes O(n) calls to -// data.Less and data.Swap (with very high probability). It uses Hoare's -// selection algorithm (aka quickselect). -func MoveTopKToFront(data sort.Interface, k int) { - if data.Len() <= k { - return - } - // We want the call to be deterministic so we use a predictable seed. - r := rand.New(rand.NewSource(int64(data.Len()*1000 + k))) - moveTopKToFront(data, 0, data.Len(), k, r) -} diff --git a/vendor/github.com/cockroachdb/cockroach/pkg/util/topk_test.go b/vendor/github.com/cockroachdb/cockroach/pkg/util/topk_test.go deleted file mode 100644 index 48b7e855b..000000000 --- a/vendor/github.com/cockroachdb/cockroach/pkg/util/topk_test.go +++ /dev/null @@ -1,125 +0,0 @@ -// Copyright 2016 The Cockroach Authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -// implied. See the License for the specific language governing -// permissions and limitations under the License. -// -// Author: Radu Berinde (radu@cockroachlabs.com) - -package util - -import ( - "math/rand" - "sort" - "testing" -) - -// testMoveTopKToFront runs MoveTopKToFront for the given k and verifies the -// result. -func testMoveTopKToFront(t *testing.T, k int, data ...int) { - // Make a copy of the values. - vals = append([]int(nil), data...) - MoveTopKToFront(sort.IntSlice(vals), k) - for l := 0; l < k; l++ { - for r := k; r < len(data); r++ { - if vals[l] > vals[r] { - t.Errorf("Error for k=%d: vals[%d]=%d is greater than vals[%d]=%d", - k, l, vals[l], r, vals[r]) - } - } - } -} - -// testMoveTopKToFront runs MoveTopKToFront for all possible Ks and verifies the -// result. -func testMoveTopKToFrontAllK(t *testing.T, data ...int) { - for k := 0; k <= len(data); k++ { - testMoveTopKToFront(t, k, data...) - } -} - -func TestMoveTopKToFront(t *testing.T) { - // Test all possible arrays of length up to 4 with values between 0 and 4. - for a := 0; a <= 4; a++ { - testMoveTopKToFrontAllK(t, a) - for b := 0; b <= 4; b++ { - testMoveTopKToFrontAllK(t, a, b) - for c := 0; c <= 4; c++ { - testMoveTopKToFrontAllK(t, a, b, c) - for d := 0; d <= 4; d++ { - testMoveTopKToFrontAllK(t, a, b, c, d) - } - } - } - } - - // Misc tests. - tests := [][]int{ - {0, 1, 2, 3, 4, 5, 6, 7}, - {7, 6, 5, 4, 3, 2, 1, 0}, - {7, 0, 6, 1, 5, 2, 4, 3}, - {0, 9, 2, 1, 5, 1, 7, 8, 8, 7}, - {0, 2, 9, 11, 6, 1, 7, 1, 5, 1, 4, 3, 0, 11}, - } - for _, data := range tests { - testMoveTopKToFrontAllK(t, data...) - } - - // Random tests: data of size N with random values in [0, M). - Ns := []int{10, 100} - Ms := []int{2, 10, 100, 1000} - for _, n := range Ns { - for _, m := range Ms { - data := make([]int, n) - for _, i := range data { - data[i] = rand.Intn(m) - } - testMoveTopKToFrontAllK(t, data...) - } - } -} - -func benchmarkMoveTopKToFront(b *testing.B, data []int) { - tmp := make([]int, len(data)) - - ks := []int{len(data) / 100, len(data) / 10, len(data) / 2} - b.ResetTimer() - for i := 0; i < b.N; i++ { - b.StopTimer() - copy(tmp, data) - b.StartTimer() - MoveTopKToFront(sort.IntSlice(tmp), ks[i%len(ks)]) - } -} - -func BenchmarkMoveTopKToFrontRand(b *testing.B) { - data := make([]int, 100000) - for _, i := range data { - data[i] = rand.Intn(len(data)) - } - benchmarkMoveTopKToFront(b, data) -} - -func BenchmarkMoveTopKToFrontSorted(b *testing.B) { - data := make([]int, 100000) - for _, i := range data { - data[i] = i - } - benchmarkMoveTopKToFront(b, data) -} - -func BenchmarkMoveTopKToFrontRevSorted(b *testing.B) { - data := make([]int, 100000) - for _, i := range data { - data[i] = -i - } - benchmarkMoveTopKToFront(b, data) -} diff --git a/vendor/github.com/cockroachdb/cockroach/pkg/util/unresolved_addr.go b/vendor/github.com/cockroachdb/cockroach/pkg/util/unresolved_addr.go deleted file mode 100644 index 6a4f286e5..000000000 --- a/vendor/github.com/cockroachdb/cockroach/pkg/util/unresolved_addr.go +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright 2015 The Cockroach Authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -// implied. See the License for the specific language governing -// permissions and limitations under the License. -// -// Author: Tamir Duberstein (tamird@gmail.com) - -package util - -import ( - "fmt" - "net" -) - -// TestAddr is an address to use for test servers. Listening on port 0 -// causes the kernel to allocate an unused port. -var TestAddr = NewUnresolvedAddr("tcp", "127.0.0.1:0") - -// IsolatedTestAddr is initialized in testaddr_*.go - -// IsolatedTestAddr is an address to use for tests that need extra -// isolation by using more addresses than 127.0.0.1 (support for this -// is platform-specific and only enabled on Linux). Both TestAddr and -// IsolatedTestAddr guarantee that the chosen port is not in use when -// allocated, but IsolatedTestAddr draws from a larger pool of -// addresses so that when tests are run in a tight loop the system is -// less likely to run out of available ports or give a port to one -// test immediately after it was closed by another. -// -// IsolatedTestAddr should be used for tests that open and close a -// large number of sockets, or tests which stop a server and rely on -// seeing a "connection refused" error afterwards. It cannot be used -// with tests that operate in secure mode since our test certificates -// are only valid for 127.0.0.1. -var IsolatedTestAddr *UnresolvedAddr - -// MakeUnresolvedAddr populates an UnresolvedAddr from a network and raw -// address string. -func MakeUnresolvedAddr(network, addr string) UnresolvedAddr { - return UnresolvedAddr{ - NetworkField: network, - AddressField: addr, - } -} - -// NewUnresolvedAddr creates a new UnresolvedAddr from a network and raw -// address string. -func NewUnresolvedAddr(network, addr string) *UnresolvedAddr { - return &UnresolvedAddr{ - NetworkField: network, - AddressField: addr, - } -} - -// Note that we make *UnresolvedAddr implement the net.Addr interface, not -// UnresolvedAddr. This is done because assigning a non-empty struct to an -// interface requires an allocation, while assigning a pointer to an interface -// is allocation free. Using an *UnresolvedAddr makes it both clear that an -// allocation is occurring and allows us to avoid an allocation when an -// UnresolvedAddr is a field of a struct (e.g. NodeDescriptor.Address). -var _ net.Addr = &UnresolvedAddr{} - -// Network returns the address's network name. -func (a *UnresolvedAddr) Network() string { - return a.NetworkField -} - -// IsEmpty returns true if the address has no network or address specified. -func (a UnresolvedAddr) IsEmpty() bool { - return a == (UnresolvedAddr{}) -} - -// String returns the address's string form. -func (a *UnresolvedAddr) String() string { - return a.AddressField -} - -// Resolve attempts to resolve a into a net.Addr. -func (a UnresolvedAddr) Resolve() (net.Addr, error) { - switch a.NetworkField { - case "tcp", "tcp4", "tcp6": - return net.ResolveTCPAddr(a.NetworkField, a.AddressField) - case "udp", "udp4", "udp6": - return net.ResolveUDPAddr(a.NetworkField, a.AddressField) - case "unix", "unixgram", "unixpacket": - return net.ResolveUnixAddr(a.NetworkField, a.AddressField) - } - return nil, fmt.Errorf("network %s not supported", a.NetworkField) -} diff --git a/vendor/github.com/cockroachdb/cockroach/pkg/util/unresolved_addr.pb.go b/vendor/github.com/cockroachdb/cockroach/pkg/util/unresolved_addr.pb.go deleted file mode 100644 index df21418ce..000000000 --- a/vendor/github.com/cockroachdb/cockroach/pkg/util/unresolved_addr.pb.go +++ /dev/null @@ -1,353 +0,0 @@ -// Code generated by protoc-gen-gogo. -// source: cockroach/pkg/util/unresolved_addr.proto -// DO NOT EDIT! - -/* - Package util is a generated protocol buffer package. - - It is generated from these files: - cockroach/pkg/util/unresolved_addr.proto - - It has these top-level messages: - UnresolvedAddr -*/ -package util - -import proto "github.com/gogo/protobuf/proto" -import fmt "fmt" -import math "math" - -import io "io" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package - -// / UnresolvedAddr is an unresolved version of net.Addr. -type UnresolvedAddr struct { - NetworkField string `protobuf:"bytes,1,opt,name=network_field,json=networkField" json:"network_field"` - AddressField string `protobuf:"bytes,2,opt,name=address_field,json=addressField" json:"address_field"` -} - -func (m *UnresolvedAddr) Reset() { *m = UnresolvedAddr{} } -func (*UnresolvedAddr) ProtoMessage() {} -func (*UnresolvedAddr) Descriptor() ([]byte, []int) { return fileDescriptorUnresolvedAddr, []int{0} } - -func init() { - proto.RegisterType((*UnresolvedAddr)(nil), "cockroach.util.UnresolvedAddr") -} -func (m *UnresolvedAddr) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalTo(dAtA) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *UnresolvedAddr) MarshalTo(dAtA []byte) (int, error) { - var i int - _ = i - var l int - _ = l - dAtA[i] = 0xa - i++ - i = encodeVarintUnresolvedAddr(dAtA, i, uint64(len(m.NetworkField))) - i += copy(dAtA[i:], m.NetworkField) - dAtA[i] = 0x12 - i++ - i = encodeVarintUnresolvedAddr(dAtA, i, uint64(len(m.AddressField))) - i += copy(dAtA[i:], m.AddressField) - return i, nil -} - -func encodeFixed64UnresolvedAddr(dAtA []byte, offset int, v uint64) int { - dAtA[offset] = uint8(v) - dAtA[offset+1] = uint8(v >> 8) - dAtA[offset+2] = uint8(v >> 16) - dAtA[offset+3] = uint8(v >> 24) - dAtA[offset+4] = uint8(v >> 32) - dAtA[offset+5] = uint8(v >> 40) - dAtA[offset+6] = uint8(v >> 48) - dAtA[offset+7] = uint8(v >> 56) - return offset + 8 -} -func encodeFixed32UnresolvedAddr(dAtA []byte, offset int, v uint32) int { - dAtA[offset] = uint8(v) - dAtA[offset+1] = uint8(v >> 8) - dAtA[offset+2] = uint8(v >> 16) - dAtA[offset+3] = uint8(v >> 24) - return offset + 4 -} -func encodeVarintUnresolvedAddr(dAtA []byte, offset int, v uint64) int { - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return offset + 1 -} -func (m *UnresolvedAddr) Size() (n int) { - var l int - _ = l - l = len(m.NetworkField) - n += 1 + l + sovUnresolvedAddr(uint64(l)) - l = len(m.AddressField) - n += 1 + l + sovUnresolvedAddr(uint64(l)) - return n -} - -func sovUnresolvedAddr(x uint64) (n int) { - for { - n++ - x >>= 7 - if x == 0 { - break - } - } - return n -} -func sozUnresolvedAddr(x uint64) (n int) { - return sovUnresolvedAddr(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *UnresolvedAddr) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowUnresolvedAddr - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: UnresolvedAddr: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: UnresolvedAddr: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field NetworkField", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowUnresolvedAddr - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthUnresolvedAddr - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.NetworkField = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field AddressField", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowUnresolvedAddr - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthUnresolvedAddr - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.AddressField = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipUnresolvedAddr(dAtA[iNdEx:]) - if err != nil { - return err - } - if skippy < 0 { - return ErrInvalidLengthUnresolvedAddr - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipUnresolvedAddr(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowUnresolvedAddr - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowUnresolvedAddr - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - return iNdEx, nil - case 1: - iNdEx += 8 - return iNdEx, nil - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowUnresolvedAddr - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - iNdEx += length - if length < 0 { - return 0, ErrInvalidLengthUnresolvedAddr - } - return iNdEx, nil - case 3: - for { - var innerWire uint64 - var start int = iNdEx - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowUnresolvedAddr - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - innerWire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - innerWireType := int(innerWire & 0x7) - if innerWireType == 4 { - break - } - next, err := skipUnresolvedAddr(dAtA[start:]) - if err != nil { - return 0, err - } - iNdEx = start + next - } - return iNdEx, nil - case 4: - return iNdEx, nil - case 5: - iNdEx += 4 - return iNdEx, nil - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - } - panic("unreachable") -} - -var ( - ErrInvalidLengthUnresolvedAddr = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowUnresolvedAddr = fmt.Errorf("proto: integer overflow") -) - -func init() { - proto.RegisterFile("cockroach/pkg/util/unresolved_addr.proto", fileDescriptorUnresolvedAddr) -} - -var fileDescriptorUnresolvedAddr = []byte{ - // 187 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xd2, 0x48, 0xce, 0x4f, 0xce, - 0x2e, 0xca, 0x4f, 0x4c, 0xce, 0xd0, 0x2f, 0xc8, 0x4e, 0xd7, 0x2f, 0x2d, 0xc9, 0xcc, 0xd1, 0x2f, - 0xcd, 0x2b, 0x4a, 0x2d, 0xce, 0xcf, 0x29, 0x4b, 0x4d, 0x89, 0x4f, 0x4c, 0x49, 0x29, 0xd2, 0x2b, - 0x28, 0xca, 0x2f, 0xc9, 0x17, 0xe2, 0x83, 0xab, 0xd4, 0x03, 0xa9, 0x92, 0x12, 0x49, 0xcf, 0x4f, - 0xcf, 0x07, 0x4b, 0xe9, 0x83, 0x58, 0x10, 0x55, 0x4a, 0x39, 0x5c, 0x7c, 0xa1, 0x70, 0xed, 0x8e, - 0x29, 0x29, 0x45, 0x42, 0x9a, 0x5c, 0xbc, 0x79, 0xa9, 0x25, 0xe5, 0xf9, 0x45, 0xd9, 0xf1, 0x69, - 0x99, 0xa9, 0x39, 0x29, 0x12, 0x8c, 0x0a, 0x8c, 0x1a, 0x9c, 0x4e, 0x2c, 0x27, 0xee, 0xc9, 0x33, - 0x04, 0xf1, 0x40, 0xa5, 0xdc, 0x40, 0x32, 0x20, 0xa5, 0x20, 0x0b, 0x53, 0x8b, 0x8b, 0xa1, 0x4a, - 0x99, 0x90, 0x95, 0x42, 0xa5, 0xc0, 0x4a, 0xad, 0x58, 0x66, 0x2c, 0x90, 0x67, 0x70, 0x92, 0x3b, - 0xf1, 0x50, 0x8e, 0xe1, 0xc4, 0x23, 0x39, 0xc6, 0x0b, 0x8f, 0xe4, 0x18, 0x6f, 0x3c, 0x92, 0x63, - 0x7c, 0xf0, 0x48, 0x8e, 0x71, 0xc2, 0x63, 0x39, 0x86, 0x28, 0x16, 0x90, 0x1b, 0x01, 0x01, 0x00, - 0x00, 0xff, 0xff, 0xb6, 0x49, 0xa7, 0xee, 0xde, 0x00, 0x00, 0x00, -} diff --git a/vendor/github.com/cockroachdb/cockroach/pkg/util/unresolved_addr.proto b/vendor/github.com/cockroachdb/cockroach/pkg/util/unresolved_addr.proto deleted file mode 100644 index 695c1f10b..000000000 --- a/vendor/github.com/cockroachdb/cockroach/pkg/util/unresolved_addr.proto +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2015 The Cockroach Authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -// implied. See the License for the specific language governing -// permissions and limitations under the License. -// -// Author: Tamir Duberstein (tamird@gmail.com) - -syntax = "proto2"; -package cockroach.util; -option go_package = "util"; - -import "gogoproto/gogo.proto"; - -// / UnresolvedAddr is an unresolved version of net.Addr. -message UnresolvedAddr { - option (gogoproto.goproto_stringer) = false; - - optional string network_field = 1 [(gogoproto.nullable) = false]; - optional string address_field = 2 [(gogoproto.nullable) = false]; -} diff --git a/vendor/github.com/cockroachdb/cockroach/pkg/util/unresolved_addr_test.go b/vendor/github.com/cockroachdb/cockroach/pkg/util/unresolved_addr_test.go deleted file mode 100644 index a167313e5..000000000 --- a/vendor/github.com/cockroachdb/cockroach/pkg/util/unresolved_addr_test.go +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright 2014 The Cockroach Authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -// implied. See the License for the specific language governing -// permissions and limitations under the License. -// -// Author: jqmp (jaqueramaphan@gmail.com) - -package util - -import ( - "net" - "testing" -) - -func TestUnresolvedAddr(t *testing.T) { - tcpAddr, err := net.ResolveTCPAddr("tcp", "127.0.0.1:12345") - if err != nil { - t.Fatal(err) - } - addr := MakeUnresolvedAddr(tcpAddr.Network(), tcpAddr.String()) - tcpAddr2, err := addr.Resolve() - if err != nil { - t.Fatal(err) - } - if tcpAddr2.Network() != tcpAddr.Network() { - t.Errorf("networks differ: %s != %s", tcpAddr2.Network(), tcpAddr.Network()) - } - if tcpAddr2.String() != tcpAddr.String() { - t.Errorf("strings differ: %s != %s", tcpAddr2.String(), tcpAddr.String()) - } -} diff --git a/vendor/github.com/cockroachdb/cockroach/scripts/authors.sh b/vendor/github.com/cockroachdb/cockroach/scripts/authors.sh new file mode 100755 index 000000000..94ccf6d3f --- /dev/null +++ b/vendor/github.com/cockroachdb/cockroach/scripts/authors.sh @@ -0,0 +1,15 @@ +#! /bin/sh + +# This script produces the list of authors for a given source file, +# listed in decreasing order of the number of commits by that author +# that have touched the file. + +file=${1:?} + +git log --no-merges --format='%aN <%aE>' "$file" \ + | sort \ + | uniq -c \ + | sort -nr \ + | sed -e 's/^ *//g' \ + | cut -d' ' -f2- \ + | sed -e 's,^,// Author: ,g' diff --git a/vendor/github.com/davecgh/go-spew/.gitignore b/vendor/github.com/davecgh/go-spew/.gitignore deleted file mode 100644 index 00268614f..000000000 --- a/vendor/github.com/davecgh/go-spew/.gitignore +++ /dev/null @@ -1,22 +0,0 @@ -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe diff --git a/vendor/github.com/davecgh/go-spew/.travis.yml b/vendor/github.com/davecgh/go-spew/.travis.yml deleted file mode 100644 index 984e0736e..000000000 --- a/vendor/github.com/davecgh/go-spew/.travis.yml +++ /dev/null @@ -1,14 +0,0 @@ -language: go -go: - - 1.5.4 - - 1.6.3 - - 1.7 -install: - - go get -v golang.org/x/tools/cmd/cover -script: - - go test -v -tags=safe ./spew - - go test -v -tags=testcgo ./spew -covermode=count -coverprofile=profile.cov -after_success: - - go get -v github.com/mattn/goveralls - - export PATH=$PATH:$HOME/gopath/bin - - goveralls -coverprofile=profile.cov -service=travis-ci diff --git a/vendor/github.com/davecgh/go-spew/README.md b/vendor/github.com/davecgh/go-spew/README.md deleted file mode 100644 index 262430449..000000000 --- a/vendor/github.com/davecgh/go-spew/README.md +++ /dev/null @@ -1,205 +0,0 @@ -go-spew -======= - -[![Build Status](https://img.shields.io/travis/davecgh/go-spew.svg)] -(https://travis-ci.org/davecgh/go-spew) [![ISC License] -(http://img.shields.io/badge/license-ISC-blue.svg)](http://copyfree.org) [![Coverage Status] -(https://img.shields.io/coveralls/davecgh/go-spew.svg)] -(https://coveralls.io/r/davecgh/go-spew?branch=master) - - -Go-spew implements a deep pretty printer for Go data structures to aid in -debugging. A comprehensive suite of tests with 100% test coverage is provided -to ensure proper functionality. See `test_coverage.txt` for the gocov coverage -report. Go-spew is licensed under the liberal ISC license, so it may be used in -open source or commercial projects. - -If you're interested in reading about how this package came to life and some -of the challenges involved in providing a deep pretty printer, there is a blog -post about it -[here](https://web.archive.org/web/20160304013555/https://blog.cyphertite.com/go-spew-a-journey-into-dumping-go-data-structures/). - -## Documentation - -[![GoDoc](https://img.shields.io/badge/godoc-reference-blue.svg)] -(http://godoc.org/github.com/davecgh/go-spew/spew) - -Full `go doc` style documentation for the project can be viewed online without -installing this package by using the excellent GoDoc site here: -http://godoc.org/github.com/davecgh/go-spew/spew - -You can also view the documentation locally once the package is installed with -the `godoc` tool by running `godoc -http=":6060"` and pointing your browser to -http://localhost:6060/pkg/github.com/davecgh/go-spew/spew - -## Installation - -```bash -$ go get -u github.com/davecgh/go-spew/spew -``` - -## Quick Start - -Add this import line to the file you're working in: - -```Go -import "github.com/davecgh/go-spew/spew" -``` - -To dump a variable with full newlines, indentation, type, and pointer -information use Dump, Fdump, or Sdump: - -```Go -spew.Dump(myVar1, myVar2, ...) -spew.Fdump(someWriter, myVar1, myVar2, ...) -str := spew.Sdump(myVar1, myVar2, ...) -``` - -Alternatively, if you would prefer to use format strings with a compacted inline -printing style, use the convenience wrappers Printf, Fprintf, etc with %v (most -compact), %+v (adds pointer addresses), %#v (adds types), or %#+v (adds types -and pointer addresses): - -```Go -spew.Printf("myVar1: %v -- myVar2: %+v", myVar1, myVar2) -spew.Printf("myVar3: %#v -- myVar4: %#+v", myVar3, myVar4) -spew.Fprintf(someWriter, "myVar1: %v -- myVar2: %+v", myVar1, myVar2) -spew.Fprintf(someWriter, "myVar3: %#v -- myVar4: %#+v", myVar3, myVar4) -``` - -## Debugging a Web Application Example - -Here is an example of how you can use `spew.Sdump()` to help debug a web application. Please be sure to wrap your output using the `html.EscapeString()` function for safety reasons. You should also only use this debugging technique in a development environment, never in production. - -```Go -package main - -import ( - "fmt" - "html" - "net/http" - - "github.com/davecgh/go-spew/spew" -) - -func handler(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "text/html") - fmt.Fprintf(w, "Hi there, %s!", r.URL.Path[1:]) - fmt.Fprintf(w, "") -} - -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 deleted file mode 100644 index 9579497e4..000000000 --- a/vendor/github.com/davecgh/go-spew/cov_report.sh +++ /dev/null @@ -1,22 +0,0 @@ -#!/bin/sh - -# This script uses gocov to generate a test coverage report. -# The gocov tool my be obtained with the following command: -# go get github.com/axw/gocov/gocov -# -# It will be installed to $GOPATH/bin, so ensure that location is in your $PATH. - -# Check for gocov. -if ! type gocov >/dev/null 2>&1; then - echo >&2 "This script requires the gocov tool." - echo >&2 "You may obtain it with the following command:" - echo >&2 "go get github.com/axw/gocov/gocov" - exit 1 -fi - -# Only run the cgo tests if gcc is installed. -if type gcc >/dev/null 2>&1; then - (cd spew && gocov test -tags testcgo | gocov report) -else - (cd spew && gocov test | gocov report) -fi diff --git a/vendor/github.com/davecgh/go-spew/spew/common_test.go b/vendor/github.com/davecgh/go-spew/spew/common_test.go deleted file mode 100644 index 0f5ce47dc..000000000 --- a/vendor/github.com/davecgh/go-spew/spew/common_test.go +++ /dev/null @@ -1,298 +0,0 @@ -/* - * Copyright (c) 2013-2016 Dave Collins - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -package spew_test - -import ( - "fmt" - "reflect" - "testing" - - "github.com/davecgh/go-spew/spew" -) - -// custom type to test Stinger interface on non-pointer receiver. -type stringer string - -// String implements the Stringer interface for testing invocation of custom -// stringers on types with non-pointer receivers. -func (s stringer) String() string { - return "stringer " + string(s) -} - -// custom type to test Stinger interface on pointer receiver. -type pstringer string - -// String implements the Stringer interface for testing invocation of custom -// stringers on types with only pointer receivers. -func (s *pstringer) String() string { - return "stringer " + string(*s) -} - -// xref1 and xref2 are cross referencing structs for testing circular reference -// detection. -type xref1 struct { - ps2 *xref2 -} -type xref2 struct { - ps1 *xref1 -} - -// indirCir1, indirCir2, and indirCir3 are used to generate an indirect circular -// reference for testing detection. -type indirCir1 struct { - ps2 *indirCir2 -} -type indirCir2 struct { - ps3 *indirCir3 -} -type indirCir3 struct { - ps1 *indirCir1 -} - -// embed is used to test embedded structures. -type embed struct { - a string -} - -// embedwrap is used to test embedded structures. -type embedwrap struct { - *embed - e *embed -} - -// panicer is used to intentionally cause a panic for testing spew properly -// handles them -type panicer int - -func (p panicer) String() string { - panic("test panic") -} - -// customError is used to test custom error interface invocation. -type customError int - -func (e customError) Error() string { - return fmt.Sprintf("error: %d", int(e)) -} - -// stringizeWants converts a slice of wanted test output into a format suitable -// for a test error message. -func stringizeWants(wants []string) string { - s := "" - for i, want := range wants { - if i > 0 { - s += fmt.Sprintf("want%d: %s", i+1, want) - } else { - s += "want: " + want - } - } - return s -} - -// testFailed returns whether or not a test failed by checking if the result -// of the test is in the slice of wanted strings. -func testFailed(result string, wants []string) bool { - for _, want := range wants { - if result == want { - return false - } - } - return true -} - -type sortableStruct struct { - x int -} - -func (ss sortableStruct) String() string { - return fmt.Sprintf("ss.%d", ss.x) -} - -type unsortableStruct struct { - x int -} - -type sortTestCase struct { - input []reflect.Value - expected []reflect.Value -} - -func helpTestSortValues(tests []sortTestCase, cs *spew.ConfigState, t *testing.T) { - getInterfaces := func(values []reflect.Value) []interface{} { - interfaces := []interface{}{} - for _, v := range values { - interfaces = append(interfaces, v.Interface()) - } - return interfaces - } - - for _, test := range tests { - spew.SortValues(test.input, cs) - // reflect.DeepEqual cannot really make sense of reflect.Value, - // probably because of all the pointer tricks. For instance, - // v(2.0) != v(2.0) on a 32-bits system. Turn them into interface{} - // instead. - input := getInterfaces(test.input) - expected := getInterfaces(test.expected) - if !reflect.DeepEqual(input, expected) { - t.Errorf("Sort mismatch:\n %v != %v", input, expected) - } - } -} - -// TestSortValues ensures the sort functionality for relect.Value based sorting -// works as intended. -func TestSortValues(t *testing.T) { - v := reflect.ValueOf - - a := v("a") - b := v("b") - c := v("c") - embedA := v(embed{"a"}) - embedB := v(embed{"b"}) - embedC := v(embed{"c"}) - tests := []sortTestCase{ - // No values. - { - []reflect.Value{}, - []reflect.Value{}, - }, - // Bools. - { - []reflect.Value{v(false), v(true), v(false)}, - []reflect.Value{v(false), v(false), v(true)}, - }, - // Ints. - { - []reflect.Value{v(2), v(1), v(3)}, - []reflect.Value{v(1), v(2), v(3)}, - }, - // Uints. - { - []reflect.Value{v(uint8(2)), v(uint8(1)), v(uint8(3))}, - []reflect.Value{v(uint8(1)), v(uint8(2)), v(uint8(3))}, - }, - // Floats. - { - []reflect.Value{v(2.0), v(1.0), v(3.0)}, - []reflect.Value{v(1.0), v(2.0), v(3.0)}, - }, - // Strings. - { - []reflect.Value{b, a, c}, - []reflect.Value{a, b, c}, - }, - // Array - { - []reflect.Value{v([3]int{3, 2, 1}), v([3]int{1, 3, 2}), v([3]int{1, 2, 3})}, - []reflect.Value{v([3]int{1, 2, 3}), v([3]int{1, 3, 2}), v([3]int{3, 2, 1})}, - }, - // Uintptrs. - { - []reflect.Value{v(uintptr(2)), v(uintptr(1)), v(uintptr(3))}, - []reflect.Value{v(uintptr(1)), v(uintptr(2)), v(uintptr(3))}, - }, - // SortableStructs. - { - // Note: not sorted - DisableMethods is set. - []reflect.Value{v(sortableStruct{2}), v(sortableStruct{1}), v(sortableStruct{3})}, - []reflect.Value{v(sortableStruct{2}), v(sortableStruct{1}), v(sortableStruct{3})}, - }, - // UnsortableStructs. - { - // Note: not sorted - SpewKeys is false. - []reflect.Value{v(unsortableStruct{2}), v(unsortableStruct{1}), v(unsortableStruct{3})}, - []reflect.Value{v(unsortableStruct{2}), v(unsortableStruct{1}), v(unsortableStruct{3})}, - }, - // Invalid. - { - []reflect.Value{embedB, embedA, embedC}, - []reflect.Value{embedB, embedA, embedC}, - }, - } - cs := spew.ConfigState{DisableMethods: true, SpewKeys: false} - helpTestSortValues(tests, &cs, t) -} - -// TestSortValuesWithMethods ensures the sort functionality for relect.Value -// based sorting works as intended when using string methods. -func TestSortValuesWithMethods(t *testing.T) { - v := reflect.ValueOf - - a := v("a") - b := v("b") - c := v("c") - tests := []sortTestCase{ - // Ints. - { - []reflect.Value{v(2), v(1), v(3)}, - []reflect.Value{v(1), v(2), v(3)}, - }, - // Strings. - { - []reflect.Value{b, a, c}, - []reflect.Value{a, b, c}, - }, - // SortableStructs. - { - []reflect.Value{v(sortableStruct{2}), v(sortableStruct{1}), v(sortableStruct{3})}, - []reflect.Value{v(sortableStruct{1}), v(sortableStruct{2}), v(sortableStruct{3})}, - }, - // UnsortableStructs. - { - // Note: not sorted - SpewKeys is false. - []reflect.Value{v(unsortableStruct{2}), v(unsortableStruct{1}), v(unsortableStruct{3})}, - []reflect.Value{v(unsortableStruct{2}), v(unsortableStruct{1}), v(unsortableStruct{3})}, - }, - } - cs := spew.ConfigState{DisableMethods: false, SpewKeys: false} - helpTestSortValues(tests, &cs, t) -} - -// TestSortValuesWithSpew ensures the sort functionality for relect.Value -// based sorting works as intended when using spew to stringify keys. -func TestSortValuesWithSpew(t *testing.T) { - v := reflect.ValueOf - - a := v("a") - b := v("b") - c := v("c") - tests := []sortTestCase{ - // Ints. - { - []reflect.Value{v(2), v(1), v(3)}, - []reflect.Value{v(1), v(2), v(3)}, - }, - // Strings. - { - []reflect.Value{b, a, c}, - []reflect.Value{a, b, c}, - }, - // SortableStructs. - { - []reflect.Value{v(sortableStruct{2}), v(sortableStruct{1}), v(sortableStruct{3})}, - []reflect.Value{v(sortableStruct{1}), v(sortableStruct{2}), v(sortableStruct{3})}, - }, - // UnsortableStructs. - { - []reflect.Value{v(unsortableStruct{2}), v(unsortableStruct{1}), v(unsortableStruct{3})}, - []reflect.Value{v(unsortableStruct{1}), v(unsortableStruct{2}), v(unsortableStruct{3})}, - }, - } - cs := spew.ConfigState{DisableMethods: true, SpewKeys: true} - helpTestSortValues(tests, &cs, t) -} diff --git a/vendor/github.com/davecgh/go-spew/spew/dump_test.go b/vendor/github.com/davecgh/go-spew/spew/dump_test.go deleted file mode 100644 index 5aad9c7af..000000000 --- a/vendor/github.com/davecgh/go-spew/spew/dump_test.go +++ /dev/null @@ -1,1042 +0,0 @@ -/* - * Copyright (c) 2013-2016 Dave Collins - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -/* -Test Summary: -NOTE: For each test, a nil pointer, a single pointer and double pointer to the -base test element are also tested to ensure proper indirection across all types. - -- Max int8, int16, int32, int64, int -- Max uint8, uint16, uint32, uint64, uint -- Boolean true and false -- Standard complex64 and complex128 -- Array containing standard ints -- Array containing type with custom formatter on pointer receiver only -- Array containing interfaces -- Array containing bytes -- Slice containing standard float32 values -- Slice containing type with custom formatter on pointer receiver only -- Slice containing interfaces -- Slice containing bytes -- Nil slice -- Standard string -- Nil interface -- Sub-interface -- Map with string keys and int vals -- Map with custom formatter type on pointer receiver only keys and vals -- Map with interface keys and values -- Map with nil interface value -- Struct with primitives -- Struct that contains another struct -- Struct that contains custom type with Stringer pointer interface via both - exported and unexported fields -- Struct that contains embedded struct and field to same struct -- Uintptr to 0 (null pointer) -- Uintptr address of real variable -- Unsafe.Pointer to 0 (null pointer) -- Unsafe.Pointer to address of real variable -- Nil channel -- Standard int channel -- Function with no params and no returns -- Function with param and no returns -- Function with multiple params and multiple returns -- Struct that is circular through self referencing -- Structs that are circular through cross referencing -- Structs that are indirectly circular -- Type that panics in its Stringer interface -*/ - -package spew_test - -import ( - "bytes" - "fmt" - "testing" - "unsafe" - - "github.com/davecgh/go-spew/spew" -) - -// dumpTest is used to describe a test to be performed against the Dump method. -type dumpTest struct { - in interface{} - wants []string -} - -// dumpTests houses all of the tests to be performed against the Dump method. -var dumpTests = make([]dumpTest, 0) - -// addDumpTest is a helper method to append the passed input and desired result -// to dumpTests -func addDumpTest(in interface{}, wants ...string) { - test := dumpTest{in, wants} - dumpTests = append(dumpTests, test) -} - -func addIntDumpTests() { - // Max int8. - v := int8(127) - nv := (*int8)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "int8" - vs := "127" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") - - // Max int16. - v2 := int16(32767) - nv2 := (*int16)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "int16" - v2s := "32767" - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") - addDumpTest(nv2, "(*"+v2t+")()\n") - - // Max int32. - v3 := int32(2147483647) - nv3 := (*int32)(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "int32" - v3s := "2147483647" - addDumpTest(v3, "("+v3t+") "+v3s+"\n") - addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s+")\n") - addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s+")\n") - addDumpTest(nv3, "(*"+v3t+")()\n") - - // Max int64. - v4 := int64(9223372036854775807) - nv4 := (*int64)(nil) - pv4 := &v4 - v4Addr := fmt.Sprintf("%p", pv4) - pv4Addr := fmt.Sprintf("%p", &pv4) - v4t := "int64" - v4s := "9223372036854775807" - addDumpTest(v4, "("+v4t+") "+v4s+"\n") - addDumpTest(pv4, "(*"+v4t+")("+v4Addr+")("+v4s+")\n") - addDumpTest(&pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")("+v4s+")\n") - addDumpTest(nv4, "(*"+v4t+")()\n") - - // Max int. - v5 := int(2147483647) - nv5 := (*int)(nil) - pv5 := &v5 - v5Addr := fmt.Sprintf("%p", pv5) - pv5Addr := fmt.Sprintf("%p", &pv5) - v5t := "int" - v5s := "2147483647" - addDumpTest(v5, "("+v5t+") "+v5s+"\n") - addDumpTest(pv5, "(*"+v5t+")("+v5Addr+")("+v5s+")\n") - addDumpTest(&pv5, "(**"+v5t+")("+pv5Addr+"->"+v5Addr+")("+v5s+")\n") - addDumpTest(nv5, "(*"+v5t+")()\n") -} - -func addUintDumpTests() { - // Max uint8. - v := uint8(255) - nv := (*uint8)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "uint8" - vs := "255" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") - - // Max uint16. - v2 := uint16(65535) - nv2 := (*uint16)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "uint16" - v2s := "65535" - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") - addDumpTest(nv2, "(*"+v2t+")()\n") - - // Max uint32. - v3 := uint32(4294967295) - nv3 := (*uint32)(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "uint32" - v3s := "4294967295" - addDumpTest(v3, "("+v3t+") "+v3s+"\n") - addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s+")\n") - addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s+")\n") - addDumpTest(nv3, "(*"+v3t+")()\n") - - // Max uint64. - v4 := uint64(18446744073709551615) - nv4 := (*uint64)(nil) - pv4 := &v4 - v4Addr := fmt.Sprintf("%p", pv4) - pv4Addr := fmt.Sprintf("%p", &pv4) - v4t := "uint64" - v4s := "18446744073709551615" - addDumpTest(v4, "("+v4t+") "+v4s+"\n") - addDumpTest(pv4, "(*"+v4t+")("+v4Addr+")("+v4s+")\n") - addDumpTest(&pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")("+v4s+")\n") - addDumpTest(nv4, "(*"+v4t+")()\n") - - // Max uint. - v5 := uint(4294967295) - nv5 := (*uint)(nil) - pv5 := &v5 - v5Addr := fmt.Sprintf("%p", pv5) - pv5Addr := fmt.Sprintf("%p", &pv5) - v5t := "uint" - v5s := "4294967295" - addDumpTest(v5, "("+v5t+") "+v5s+"\n") - addDumpTest(pv5, "(*"+v5t+")("+v5Addr+")("+v5s+")\n") - addDumpTest(&pv5, "(**"+v5t+")("+pv5Addr+"->"+v5Addr+")("+v5s+")\n") - addDumpTest(nv5, "(*"+v5t+")()\n") -} - -func addBoolDumpTests() { - // Boolean true. - v := bool(true) - nv := (*bool)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "bool" - vs := "true" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") - - // Boolean false. - v2 := bool(false) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "bool" - v2s := "false" - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") -} - -func addFloatDumpTests() { - // Standard float32. - v := float32(3.1415) - nv := (*float32)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "float32" - vs := "3.1415" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") - - // Standard float64. - v2 := float64(3.1415926) - nv2 := (*float64)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "float64" - v2s := "3.1415926" - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") - addDumpTest(nv2, "(*"+v2t+")()\n") -} - -func addComplexDumpTests() { - // Standard complex64. - v := complex(float32(6), -2) - nv := (*complex64)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "complex64" - vs := "(6-2i)" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") - - // Standard complex128. - v2 := complex(float64(-6), 2) - nv2 := (*complex128)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "complex128" - v2s := "(-6+2i)" - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") - addDumpTest(nv2, "(*"+v2t+")()\n") -} - -func addArrayDumpTests() { - // Array containing standard ints. - v := [3]int{1, 2, 3} - vLen := fmt.Sprintf("%d", len(v)) - vCap := fmt.Sprintf("%d", cap(v)) - nv := (*[3]int)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "int" - vs := "(len=" + vLen + " cap=" + vCap + ") {\n (" + vt + ") 1,\n (" + - vt + ") 2,\n (" + vt + ") 3\n}" - addDumpTest(v, "([3]"+vt+") "+vs+"\n") - addDumpTest(pv, "(*[3]"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**[3]"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*[3]"+vt+")()\n") - - // Array containing type with custom formatter on pointer receiver only. - v2i0 := pstringer("1") - v2i1 := pstringer("2") - v2i2 := pstringer("3") - v2 := [3]pstringer{v2i0, v2i1, v2i2} - v2i0Len := fmt.Sprintf("%d", len(v2i0)) - v2i1Len := fmt.Sprintf("%d", len(v2i1)) - v2i2Len := fmt.Sprintf("%d", len(v2i2)) - v2Len := fmt.Sprintf("%d", len(v2)) - v2Cap := fmt.Sprintf("%d", cap(v2)) - nv2 := (*[3]pstringer)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "spew_test.pstringer" - v2sp := "(len=" + v2Len + " cap=" + v2Cap + ") {\n (" + v2t + - ") (len=" + v2i0Len + ") stringer 1,\n (" + v2t + - ") (len=" + v2i1Len + ") stringer 2,\n (" + v2t + - ") (len=" + v2i2Len + ") " + "stringer 3\n}" - v2s := v2sp - if spew.UnsafeDisabled { - v2s = "(len=" + v2Len + " cap=" + v2Cap + ") {\n (" + v2t + - ") (len=" + v2i0Len + ") \"1\",\n (" + v2t + ") (len=" + - v2i1Len + ") \"2\",\n (" + v2t + ") (len=" + v2i2Len + - ") " + "\"3\"\n}" - } - addDumpTest(v2, "([3]"+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*[3]"+v2t+")("+v2Addr+")("+v2sp+")\n") - addDumpTest(&pv2, "(**[3]"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2sp+")\n") - addDumpTest(nv2, "(*[3]"+v2t+")()\n") - - // Array containing interfaces. - v3i0 := "one" - v3 := [3]interface{}{v3i0, int(2), uint(3)} - v3i0Len := fmt.Sprintf("%d", len(v3i0)) - v3Len := fmt.Sprintf("%d", len(v3)) - v3Cap := fmt.Sprintf("%d", cap(v3)) - nv3 := (*[3]interface{})(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "[3]interface {}" - v3t2 := "string" - v3t3 := "int" - v3t4 := "uint" - v3s := "(len=" + v3Len + " cap=" + v3Cap + ") {\n (" + v3t2 + ") " + - "(len=" + v3i0Len + ") \"one\",\n (" + v3t3 + ") 2,\n (" + - v3t4 + ") 3\n}" - addDumpTest(v3, "("+v3t+") "+v3s+"\n") - addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s+")\n") - addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s+")\n") - addDumpTest(nv3, "(*"+v3t+")()\n") - - // Array containing bytes. - v4 := [34]byte{ - 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, - 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, - 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, - 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, - 0x31, 0x32, - } - v4Len := fmt.Sprintf("%d", len(v4)) - v4Cap := fmt.Sprintf("%d", cap(v4)) - nv4 := (*[34]byte)(nil) - pv4 := &v4 - v4Addr := fmt.Sprintf("%p", pv4) - pv4Addr := fmt.Sprintf("%p", &pv4) - v4t := "[34]uint8" - v4s := "(len=" + v4Len + " cap=" + v4Cap + ") " + - "{\n 00000000 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20" + - " |............... |\n" + - " 00000010 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30" + - " |!\"#$%&'()*+,-./0|\n" + - " 00000020 31 32 " + - " |12|\n}" - addDumpTest(v4, "("+v4t+") "+v4s+"\n") - addDumpTest(pv4, "(*"+v4t+")("+v4Addr+")("+v4s+")\n") - addDumpTest(&pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")("+v4s+")\n") - addDumpTest(nv4, "(*"+v4t+")()\n") -} - -func addSliceDumpTests() { - // Slice containing standard float32 values. - v := []float32{3.14, 6.28, 12.56} - vLen := fmt.Sprintf("%d", len(v)) - vCap := fmt.Sprintf("%d", cap(v)) - nv := (*[]float32)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "float32" - vs := "(len=" + vLen + " cap=" + vCap + ") {\n (" + vt + ") 3.14,\n (" + - vt + ") 6.28,\n (" + vt + ") 12.56\n}" - addDumpTest(v, "([]"+vt+") "+vs+"\n") - addDumpTest(pv, "(*[]"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**[]"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*[]"+vt+")()\n") - - // Slice containing type with custom formatter on pointer receiver only. - v2i0 := pstringer("1") - v2i1 := pstringer("2") - v2i2 := pstringer("3") - v2 := []pstringer{v2i0, v2i1, v2i2} - v2i0Len := fmt.Sprintf("%d", len(v2i0)) - v2i1Len := fmt.Sprintf("%d", len(v2i1)) - v2i2Len := fmt.Sprintf("%d", len(v2i2)) - v2Len := fmt.Sprintf("%d", len(v2)) - v2Cap := fmt.Sprintf("%d", cap(v2)) - nv2 := (*[]pstringer)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "spew_test.pstringer" - v2s := "(len=" + v2Len + " cap=" + v2Cap + ") {\n (" + v2t + ") (len=" + - v2i0Len + ") stringer 1,\n (" + v2t + ") (len=" + v2i1Len + - ") stringer 2,\n (" + v2t + ") (len=" + v2i2Len + ") " + - "stringer 3\n}" - addDumpTest(v2, "([]"+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*[]"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**[]"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") - addDumpTest(nv2, "(*[]"+v2t+")()\n") - - // Slice containing interfaces. - v3i0 := "one" - v3 := []interface{}{v3i0, int(2), uint(3), nil} - v3i0Len := fmt.Sprintf("%d", len(v3i0)) - v3Len := fmt.Sprintf("%d", len(v3)) - v3Cap := fmt.Sprintf("%d", cap(v3)) - nv3 := (*[]interface{})(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "[]interface {}" - v3t2 := "string" - v3t3 := "int" - v3t4 := "uint" - v3t5 := "interface {}" - v3s := "(len=" + v3Len + " cap=" + v3Cap + ") {\n (" + v3t2 + ") " + - "(len=" + v3i0Len + ") \"one\",\n (" + v3t3 + ") 2,\n (" + - v3t4 + ") 3,\n (" + v3t5 + ") \n}" - addDumpTest(v3, "("+v3t+") "+v3s+"\n") - addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s+")\n") - addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s+")\n") - addDumpTest(nv3, "(*"+v3t+")()\n") - - // Slice containing bytes. - v4 := []byte{ - 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, - 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, - 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, - 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, - 0x31, 0x32, - } - v4Len := fmt.Sprintf("%d", len(v4)) - v4Cap := fmt.Sprintf("%d", cap(v4)) - nv4 := (*[]byte)(nil) - pv4 := &v4 - v4Addr := fmt.Sprintf("%p", pv4) - pv4Addr := fmt.Sprintf("%p", &pv4) - v4t := "[]uint8" - v4s := "(len=" + v4Len + " cap=" + v4Cap + ") " + - "{\n 00000000 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20" + - " |............... |\n" + - " 00000010 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30" + - " |!\"#$%&'()*+,-./0|\n" + - " 00000020 31 32 " + - " |12|\n}" - addDumpTest(v4, "("+v4t+") "+v4s+"\n") - addDumpTest(pv4, "(*"+v4t+")("+v4Addr+")("+v4s+")\n") - addDumpTest(&pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")("+v4s+")\n") - addDumpTest(nv4, "(*"+v4t+")()\n") - - // Nil slice. - v5 := []int(nil) - nv5 := (*[]int)(nil) - pv5 := &v5 - v5Addr := fmt.Sprintf("%p", pv5) - pv5Addr := fmt.Sprintf("%p", &pv5) - v5t := "[]int" - v5s := "" - addDumpTest(v5, "("+v5t+") "+v5s+"\n") - addDumpTest(pv5, "(*"+v5t+")("+v5Addr+")("+v5s+")\n") - addDumpTest(&pv5, "(**"+v5t+")("+pv5Addr+"->"+v5Addr+")("+v5s+")\n") - addDumpTest(nv5, "(*"+v5t+")()\n") -} - -func addStringDumpTests() { - // Standard string. - v := "test" - vLen := fmt.Sprintf("%d", len(v)) - nv := (*string)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "string" - vs := "(len=" + vLen + ") \"test\"" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") -} - -func addInterfaceDumpTests() { - // Nil interface. - var v interface{} - nv := (*interface{})(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "interface {}" - vs := "" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") - - // Sub-interface. - v2 := interface{}(uint16(65535)) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "uint16" - v2s := "65535" - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") -} - -func addMapDumpTests() { - // Map with string keys and int vals. - k := "one" - kk := "two" - m := map[string]int{k: 1, kk: 2} - klen := fmt.Sprintf("%d", len(k)) // not kLen to shut golint up - kkLen := fmt.Sprintf("%d", len(kk)) - mLen := fmt.Sprintf("%d", len(m)) - nilMap := map[string]int(nil) - nm := (*map[string]int)(nil) - pm := &m - mAddr := fmt.Sprintf("%p", pm) - pmAddr := fmt.Sprintf("%p", &pm) - mt := "map[string]int" - mt1 := "string" - mt2 := "int" - ms := "(len=" + mLen + ") {\n (" + mt1 + ") (len=" + klen + ") " + - "\"one\": (" + mt2 + ") 1,\n (" + mt1 + ") (len=" + kkLen + - ") \"two\": (" + mt2 + ") 2\n}" - ms2 := "(len=" + mLen + ") {\n (" + mt1 + ") (len=" + kkLen + ") " + - "\"two\": (" + mt2 + ") 2,\n (" + mt1 + ") (len=" + klen + - ") \"one\": (" + mt2 + ") 1\n}" - addDumpTest(m, "("+mt+") "+ms+"\n", "("+mt+") "+ms2+"\n") - addDumpTest(pm, "(*"+mt+")("+mAddr+")("+ms+")\n", - "(*"+mt+")("+mAddr+")("+ms2+")\n") - addDumpTest(&pm, "(**"+mt+")("+pmAddr+"->"+mAddr+")("+ms+")\n", - "(**"+mt+")("+pmAddr+"->"+mAddr+")("+ms2+")\n") - addDumpTest(nm, "(*"+mt+")()\n") - addDumpTest(nilMap, "("+mt+") \n") - - // Map with custom formatter type on pointer receiver only keys and vals. - k2 := pstringer("one") - v2 := pstringer("1") - m2 := map[pstringer]pstringer{k2: v2} - k2Len := fmt.Sprintf("%d", len(k2)) - v2Len := fmt.Sprintf("%d", len(v2)) - m2Len := fmt.Sprintf("%d", len(m2)) - nilMap2 := map[pstringer]pstringer(nil) - nm2 := (*map[pstringer]pstringer)(nil) - pm2 := &m2 - m2Addr := fmt.Sprintf("%p", pm2) - pm2Addr := fmt.Sprintf("%p", &pm2) - m2t := "map[spew_test.pstringer]spew_test.pstringer" - m2t1 := "spew_test.pstringer" - m2t2 := "spew_test.pstringer" - m2s := "(len=" + m2Len + ") {\n (" + m2t1 + ") (len=" + k2Len + ") " + - "stringer one: (" + m2t2 + ") (len=" + v2Len + ") stringer 1\n}" - if spew.UnsafeDisabled { - m2s = "(len=" + m2Len + ") {\n (" + m2t1 + ") (len=" + k2Len + - ") " + "\"one\": (" + m2t2 + ") (len=" + v2Len + - ") \"1\"\n}" - } - addDumpTest(m2, "("+m2t+") "+m2s+"\n") - addDumpTest(pm2, "(*"+m2t+")("+m2Addr+")("+m2s+")\n") - addDumpTest(&pm2, "(**"+m2t+")("+pm2Addr+"->"+m2Addr+")("+m2s+")\n") - addDumpTest(nm2, "(*"+m2t+")()\n") - addDumpTest(nilMap2, "("+m2t+") \n") - - // Map with interface keys and values. - k3 := "one" - k3Len := fmt.Sprintf("%d", len(k3)) - m3 := map[interface{}]interface{}{k3: 1} - m3Len := fmt.Sprintf("%d", len(m3)) - nilMap3 := map[interface{}]interface{}(nil) - nm3 := (*map[interface{}]interface{})(nil) - pm3 := &m3 - m3Addr := fmt.Sprintf("%p", pm3) - pm3Addr := fmt.Sprintf("%p", &pm3) - m3t := "map[interface {}]interface {}" - m3t1 := "string" - m3t2 := "int" - m3s := "(len=" + m3Len + ") {\n (" + m3t1 + ") (len=" + k3Len + ") " + - "\"one\": (" + m3t2 + ") 1\n}" - addDumpTest(m3, "("+m3t+") "+m3s+"\n") - addDumpTest(pm3, "(*"+m3t+")("+m3Addr+")("+m3s+")\n") - addDumpTest(&pm3, "(**"+m3t+")("+pm3Addr+"->"+m3Addr+")("+m3s+")\n") - addDumpTest(nm3, "(*"+m3t+")()\n") - addDumpTest(nilMap3, "("+m3t+") \n") - - // Map with nil interface value. - k4 := "nil" - k4Len := fmt.Sprintf("%d", len(k4)) - m4 := map[string]interface{}{k4: nil} - m4Len := fmt.Sprintf("%d", len(m4)) - nilMap4 := map[string]interface{}(nil) - nm4 := (*map[string]interface{})(nil) - pm4 := &m4 - m4Addr := fmt.Sprintf("%p", pm4) - pm4Addr := fmt.Sprintf("%p", &pm4) - m4t := "map[string]interface {}" - m4t1 := "string" - m4t2 := "interface {}" - m4s := "(len=" + m4Len + ") {\n (" + m4t1 + ") (len=" + k4Len + ")" + - " \"nil\": (" + m4t2 + ") \n}" - addDumpTest(m4, "("+m4t+") "+m4s+"\n") - addDumpTest(pm4, "(*"+m4t+")("+m4Addr+")("+m4s+")\n") - addDumpTest(&pm4, "(**"+m4t+")("+pm4Addr+"->"+m4Addr+")("+m4s+")\n") - addDumpTest(nm4, "(*"+m4t+")()\n") - addDumpTest(nilMap4, "("+m4t+") \n") -} - -func addStructDumpTests() { - // Struct with primitives. - type s1 struct { - a int8 - b uint8 - } - v := s1{127, 255} - nv := (*s1)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "spew_test.s1" - vt2 := "int8" - vt3 := "uint8" - vs := "{\n a: (" + vt2 + ") 127,\n b: (" + vt3 + ") 255\n}" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") - - // Struct that contains another struct. - type s2 struct { - s1 s1 - b bool - } - v2 := s2{s1{127, 255}, true} - nv2 := (*s2)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "spew_test.s2" - v2t2 := "spew_test.s1" - v2t3 := "int8" - v2t4 := "uint8" - v2t5 := "bool" - v2s := "{\n s1: (" + v2t2 + ") {\n a: (" + v2t3 + ") 127,\n b: (" + - v2t4 + ") 255\n },\n b: (" + v2t5 + ") true\n}" - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") - addDumpTest(nv2, "(*"+v2t+")()\n") - - // Struct that contains custom type with Stringer pointer interface via both - // exported and unexported fields. - type s3 struct { - s pstringer - S pstringer - } - v3 := s3{"test", "test2"} - nv3 := (*s3)(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "spew_test.s3" - v3t2 := "spew_test.pstringer" - v3s := "{\n s: (" + v3t2 + ") (len=4) stringer test,\n S: (" + v3t2 + - ") (len=5) stringer test2\n}" - v3sp := v3s - if spew.UnsafeDisabled { - v3s = "{\n s: (" + v3t2 + ") (len=4) \"test\",\n S: (" + - v3t2 + ") (len=5) \"test2\"\n}" - v3sp = "{\n s: (" + v3t2 + ") (len=4) \"test\",\n S: (" + - v3t2 + ") (len=5) stringer test2\n}" - } - addDumpTest(v3, "("+v3t+") "+v3s+"\n") - addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3sp+")\n") - addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3sp+")\n") - addDumpTest(nv3, "(*"+v3t+")()\n") - - // Struct that contains embedded struct and field to same struct. - e := embed{"embedstr"} - eLen := fmt.Sprintf("%d", len("embedstr")) - v4 := embedwrap{embed: &e, e: &e} - nv4 := (*embedwrap)(nil) - pv4 := &v4 - eAddr := fmt.Sprintf("%p", &e) - v4Addr := fmt.Sprintf("%p", pv4) - pv4Addr := fmt.Sprintf("%p", &pv4) - v4t := "spew_test.embedwrap" - v4t2 := "spew_test.embed" - v4t3 := "string" - v4s := "{\n embed: (*" + v4t2 + ")(" + eAddr + ")({\n a: (" + v4t3 + - ") (len=" + eLen + ") \"embedstr\"\n }),\n e: (*" + v4t2 + - ")(" + eAddr + ")({\n a: (" + v4t3 + ") (len=" + eLen + ")" + - " \"embedstr\"\n })\n}" - addDumpTest(v4, "("+v4t+") "+v4s+"\n") - addDumpTest(pv4, "(*"+v4t+")("+v4Addr+")("+v4s+")\n") - addDumpTest(&pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")("+v4s+")\n") - addDumpTest(nv4, "(*"+v4t+")()\n") -} - -func addUintptrDumpTests() { - // Null pointer. - v := uintptr(0) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "uintptr" - vs := "" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - - // Address of real variable. - i := 1 - v2 := uintptr(unsafe.Pointer(&i)) - nv2 := (*uintptr)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "uintptr" - v2s := fmt.Sprintf("%p", &i) - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") - addDumpTest(nv2, "(*"+v2t+")()\n") -} - -func addUnsafePointerDumpTests() { - // Null pointer. - v := unsafe.Pointer(uintptr(0)) - nv := (*unsafe.Pointer)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "unsafe.Pointer" - vs := "" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") - - // Address of real variable. - i := 1 - v2 := unsafe.Pointer(&i) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "unsafe.Pointer" - v2s := fmt.Sprintf("%p", &i) - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") - addDumpTest(nv, "(*"+vt+")()\n") -} - -func addChanDumpTests() { - // Nil channel. - var v chan int - pv := &v - nv := (*chan int)(nil) - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "chan int" - vs := "" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") - - // Real channel. - v2 := make(chan int) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "chan int" - v2s := fmt.Sprintf("%p", v2) - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") -} - -func addFuncDumpTests() { - // Function with no params and no returns. - v := addIntDumpTests - nv := (*func())(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "func()" - vs := fmt.Sprintf("%p", v) - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") - - // Function with param and no returns. - v2 := TestDump - nv2 := (*func(*testing.T))(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "func(*testing.T)" - v2s := fmt.Sprintf("%p", v2) - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") - addDumpTest(nv2, "(*"+v2t+")()\n") - - // Function with multiple params and multiple returns. - var v3 = func(i int, s string) (b bool, err error) { - return true, nil - } - nv3 := (*func(int, string) (bool, error))(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "func(int, string) (bool, error)" - v3s := fmt.Sprintf("%p", v3) - addDumpTest(v3, "("+v3t+") "+v3s+"\n") - addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s+")\n") - addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s+")\n") - addDumpTest(nv3, "(*"+v3t+")()\n") -} - -func addCircularDumpTests() { - // Struct that is circular through self referencing. - type circular struct { - c *circular - } - v := circular{nil} - v.c = &v - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "spew_test.circular" - vs := "{\n c: (*" + vt + ")(" + vAddr + ")({\n c: (*" + vt + ")(" + - vAddr + ")()\n })\n}" - vs2 := "{\n c: (*" + vt + ")(" + vAddr + ")()\n}" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs2+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs2+")\n") - - // Structs that are circular through cross referencing. - v2 := xref1{nil} - ts2 := xref2{&v2} - v2.ps2 = &ts2 - pv2 := &v2 - ts2Addr := fmt.Sprintf("%p", &ts2) - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "spew_test.xref1" - v2t2 := "spew_test.xref2" - v2s := "{\n ps2: (*" + v2t2 + ")(" + ts2Addr + ")({\n ps1: (*" + v2t + - ")(" + v2Addr + ")({\n ps2: (*" + v2t2 + ")(" + ts2Addr + - ")()\n })\n })\n}" - v2s2 := "{\n ps2: (*" + v2t2 + ")(" + ts2Addr + ")({\n ps1: (*" + v2t + - ")(" + v2Addr + ")()\n })\n}" - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s2+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s2+")\n") - - // Structs that are indirectly circular. - v3 := indirCir1{nil} - tic2 := indirCir2{nil} - tic3 := indirCir3{&v3} - tic2.ps3 = &tic3 - v3.ps2 = &tic2 - pv3 := &v3 - tic2Addr := fmt.Sprintf("%p", &tic2) - tic3Addr := fmt.Sprintf("%p", &tic3) - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "spew_test.indirCir1" - v3t2 := "spew_test.indirCir2" - v3t3 := "spew_test.indirCir3" - v3s := "{\n ps2: (*" + v3t2 + ")(" + tic2Addr + ")({\n ps3: (*" + v3t3 + - ")(" + tic3Addr + ")({\n ps1: (*" + v3t + ")(" + v3Addr + - ")({\n ps2: (*" + v3t2 + ")(" + tic2Addr + - ")()\n })\n })\n })\n}" - v3s2 := "{\n ps2: (*" + v3t2 + ")(" + tic2Addr + ")({\n ps3: (*" + v3t3 + - ")(" + tic3Addr + ")({\n ps1: (*" + v3t + ")(" + v3Addr + - ")()\n })\n })\n}" - addDumpTest(v3, "("+v3t+") "+v3s+"\n") - addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s2+")\n") - addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s2+")\n") -} - -func addPanicDumpTests() { - // Type that panics in its Stringer interface. - v := panicer(127) - nv := (*panicer)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "spew_test.panicer" - vs := "(PANIC=test panic)127" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") -} - -func addErrorDumpTests() { - // Type that has a custom Error interface. - v := customError(127) - nv := (*customError)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "spew_test.customError" - vs := "error: 127" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") -} - -// TestDump executes all of the tests described by dumpTests. -func TestDump(t *testing.T) { - // Setup tests. - addIntDumpTests() - addUintDumpTests() - addBoolDumpTests() - addFloatDumpTests() - addComplexDumpTests() - addArrayDumpTests() - addSliceDumpTests() - addStringDumpTests() - addInterfaceDumpTests() - addMapDumpTests() - addStructDumpTests() - addUintptrDumpTests() - addUnsafePointerDumpTests() - addChanDumpTests() - addFuncDumpTests() - addCircularDumpTests() - addPanicDumpTests() - addErrorDumpTests() - addCgoDumpTests() - - t.Logf("Running %d tests", len(dumpTests)) - for i, test := range dumpTests { - buf := new(bytes.Buffer) - spew.Fdump(buf, test.in) - s := buf.String() - if testFailed(s, test.wants) { - t.Errorf("Dump #%d\n got: %s %s", i, s, stringizeWants(test.wants)) - continue - } - } -} - -func TestDumpSortedKeys(t *testing.T) { - cfg := spew.ConfigState{SortKeys: true} - s := cfg.Sdump(map[int]string{1: "1", 3: "3", 2: "2"}) - expected := "(map[int]string) (len=3) {\n(int) 1: (string) (len=1) " + - "\"1\",\n(int) 2: (string) (len=1) \"2\",\n(int) 3: (string) " + - "(len=1) \"3\"\n" + - "}\n" - if s != expected { - t.Errorf("Sorted keys mismatch:\n %v %v", s, expected) - } - - s = cfg.Sdump(map[stringer]int{"1": 1, "3": 3, "2": 2}) - expected = "(map[spew_test.stringer]int) (len=3) {\n" + - "(spew_test.stringer) (len=1) stringer 1: (int) 1,\n" + - "(spew_test.stringer) (len=1) stringer 2: (int) 2,\n" + - "(spew_test.stringer) (len=1) stringer 3: (int) 3\n" + - "}\n" - if s != expected { - t.Errorf("Sorted keys mismatch:\n %v %v", s, expected) - } - - s = cfg.Sdump(map[pstringer]int{pstringer("1"): 1, pstringer("3"): 3, pstringer("2"): 2}) - expected = "(map[spew_test.pstringer]int) (len=3) {\n" + - "(spew_test.pstringer) (len=1) stringer 1: (int) 1,\n" + - "(spew_test.pstringer) (len=1) stringer 2: (int) 2,\n" + - "(spew_test.pstringer) (len=1) stringer 3: (int) 3\n" + - "}\n" - if spew.UnsafeDisabled { - expected = "(map[spew_test.pstringer]int) (len=3) {\n" + - "(spew_test.pstringer) (len=1) \"1\": (int) 1,\n" + - "(spew_test.pstringer) (len=1) \"2\": (int) 2,\n" + - "(spew_test.pstringer) (len=1) \"3\": (int) 3\n" + - "}\n" - } - if s != expected { - t.Errorf("Sorted keys mismatch:\n %v %v", s, expected) - } - - s = cfg.Sdump(map[customError]int{customError(1): 1, customError(3): 3, customError(2): 2}) - expected = "(map[spew_test.customError]int) (len=3) {\n" + - "(spew_test.customError) error: 1: (int) 1,\n" + - "(spew_test.customError) error: 2: (int) 2,\n" + - "(spew_test.customError) error: 3: (int) 3\n" + - "}\n" - if s != expected { - t.Errorf("Sorted keys mismatch:\n %v %v", s, expected) - } - -} diff --git a/vendor/github.com/davecgh/go-spew/spew/dumpcgo_test.go b/vendor/github.com/davecgh/go-spew/spew/dumpcgo_test.go deleted file mode 100644 index 6ab180809..000000000 --- a/vendor/github.com/davecgh/go-spew/spew/dumpcgo_test.go +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright (c) 2013-2016 Dave Collins -// -// Permission to use, copy, modify, and distribute this software for any -// purpose with or without fee is hereby granted, provided that the above -// copyright notice and this permission notice appear in all copies. -// -// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -// NOTE: Due to the following build constraints, this file will only be compiled -// when both cgo is supported and "-tags testcgo" is added to the go test -// command line. This means the cgo tests are only added (and hence run) when -// specifially requested. This configuration is used because spew itself -// does not require cgo to run even though it does handle certain cgo types -// specially. Rather than forcing all clients to require cgo and an external -// C compiler just to run the tests, this scheme makes them optional. -// +build cgo,testcgo - -package spew_test - -import ( - "fmt" - - "github.com/davecgh/go-spew/spew/testdata" -) - -func addCgoDumpTests() { - // C char pointer. - v := testdata.GetCgoCharPointer() - nv := testdata.GetCgoNullCharPointer() - pv := &v - vcAddr := fmt.Sprintf("%p", v) - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "*testdata._Ctype_char" - vs := "116" - addDumpTest(v, "("+vt+")("+vcAddr+")("+vs+")\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+"->"+vcAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+"->"+vcAddr+")("+vs+")\n") - addDumpTest(nv, "("+vt+")()\n") - - // C char array. - v2, v2l, v2c := testdata.GetCgoCharArray() - v2Len := fmt.Sprintf("%d", v2l) - v2Cap := fmt.Sprintf("%d", v2c) - v2t := "[6]testdata._Ctype_char" - v2s := "(len=" + v2Len + " cap=" + v2Cap + ") " + - "{\n 00000000 74 65 73 74 32 00 " + - " |test2.|\n}" - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - - // C unsigned char array. - v3, v3l, v3c := testdata.GetCgoUnsignedCharArray() - v3Len := fmt.Sprintf("%d", v3l) - v3Cap := fmt.Sprintf("%d", v3c) - v3t := "[6]testdata._Ctype_unsignedchar" - v3t2 := "[6]testdata._Ctype_uchar" - v3s := "(len=" + v3Len + " cap=" + v3Cap + ") " + - "{\n 00000000 74 65 73 74 33 00 " + - " |test3.|\n}" - addDumpTest(v3, "("+v3t+") "+v3s+"\n", "("+v3t2+") "+v3s+"\n") - - // C signed char array. - v4, v4l, v4c := testdata.GetCgoSignedCharArray() - v4Len := fmt.Sprintf("%d", v4l) - v4Cap := fmt.Sprintf("%d", v4c) - v4t := "[6]testdata._Ctype_schar" - v4t2 := "testdata._Ctype_schar" - v4s := "(len=" + v4Len + " cap=" + v4Cap + ") " + - "{\n (" + v4t2 + ") 116,\n (" + v4t2 + ") 101,\n (" + v4t2 + - ") 115,\n (" + v4t2 + ") 116,\n (" + v4t2 + ") 52,\n (" + v4t2 + - ") 0\n}" - addDumpTest(v4, "("+v4t+") "+v4s+"\n") - - // C uint8_t array. - v5, v5l, v5c := testdata.GetCgoUint8tArray() - v5Len := fmt.Sprintf("%d", v5l) - v5Cap := fmt.Sprintf("%d", v5c) - v5t := "[6]testdata._Ctype_uint8_t" - v5s := "(len=" + v5Len + " cap=" + v5Cap + ") " + - "{\n 00000000 74 65 73 74 35 00 " + - " |test5.|\n}" - addDumpTest(v5, "("+v5t+") "+v5s+"\n") - - // C typedefed unsigned char array. - v6, v6l, v6c := testdata.GetCgoTypdefedUnsignedCharArray() - v6Len := fmt.Sprintf("%d", v6l) - v6Cap := fmt.Sprintf("%d", v6c) - v6t := "[6]testdata._Ctype_custom_uchar_t" - v6s := "(len=" + v6Len + " cap=" + v6Cap + ") " + - "{\n 00000000 74 65 73 74 36 00 " + - " |test6.|\n}" - addDumpTest(v6, "("+v6t+") "+v6s+"\n") -} diff --git a/vendor/github.com/davecgh/go-spew/spew/dumpnocgo_test.go b/vendor/github.com/davecgh/go-spew/spew/dumpnocgo_test.go deleted file mode 100644 index 52a0971fb..000000000 --- a/vendor/github.com/davecgh/go-spew/spew/dumpnocgo_test.go +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (c) 2013 Dave Collins -// -// Permission to use, copy, modify, and distribute this software for any -// purpose with or without fee is hereby granted, provided that the above -// copyright notice and this permission notice appear in all copies. -// -// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -// NOTE: Due to the following build constraints, this file will only be compiled -// when either cgo is not supported or "-tags testcgo" is not added to the go -// test command line. This file intentionally does not setup any cgo tests in -// this scenario. -// +build !cgo !testcgo - -package spew_test - -func addCgoDumpTests() { - // Don't add any tests for cgo since this file is only compiled when - // there should not be any cgo tests. -} diff --git a/vendor/github.com/davecgh/go-spew/spew/example_test.go b/vendor/github.com/davecgh/go-spew/spew/example_test.go deleted file mode 100644 index c6ec8c6d5..000000000 --- a/vendor/github.com/davecgh/go-spew/spew/example_test.go +++ /dev/null @@ -1,226 +0,0 @@ -/* - * Copyright (c) 2013-2016 Dave Collins - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -package spew_test - -import ( - "fmt" - - "github.com/davecgh/go-spew/spew" -) - -type Flag int - -const ( - flagOne Flag = iota - flagTwo -) - -var flagStrings = map[Flag]string{ - flagOne: "flagOne", - flagTwo: "flagTwo", -} - -func (f Flag) String() string { - if s, ok := flagStrings[f]; ok { - return s - } - return fmt.Sprintf("Unknown flag (%d)", int(f)) -} - -type Bar struct { - data uintptr -} - -type Foo struct { - unexportedField Bar - ExportedField map[interface{}]interface{} -} - -// This example demonstrates how to use Dump to dump variables to stdout. -func ExampleDump() { - // The following package level declarations are assumed for this example: - /* - type Flag int - - const ( - flagOne Flag = iota - flagTwo - ) - - var flagStrings = map[Flag]string{ - flagOne: "flagOne", - flagTwo: "flagTwo", - } - - func (f Flag) String() string { - if s, ok := flagStrings[f]; ok { - return s - } - return fmt.Sprintf("Unknown flag (%d)", int(f)) - } - - type Bar struct { - data uintptr - } - - type Foo struct { - unexportedField Bar - ExportedField map[interface{}]interface{} - } - */ - - // Setup some sample data structures for the example. - bar := Bar{uintptr(0)} - s1 := Foo{bar, map[interface{}]interface{}{"one": true}} - f := Flag(5) - b := []byte{ - 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, - 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, - 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, - 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, - 0x31, 0x32, - } - - // Dump! - spew.Dump(s1, f, b) - - // Output: - // (spew_test.Foo) { - // unexportedField: (spew_test.Bar) { - // data: (uintptr) - // }, - // ExportedField: (map[interface {}]interface {}) (len=1) { - // (string) (len=3) "one": (bool) true - // } - // } - // (spew_test.Flag) Unknown flag (5) - // ([]uint8) (len=34 cap=34) { - // 00000000 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 |............... | - // 00000010 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30 |!"#$%&'()*+,-./0| - // 00000020 31 32 |12| - // } - // -} - -// This example demonstrates how to use Printf to display a variable with a -// format string and inline formatting. -func ExamplePrintf() { - // Create a double pointer to a uint 8. - ui8 := uint8(5) - pui8 := &ui8 - ppui8 := &pui8 - - // Create a circular data type. - type circular struct { - ui8 uint8 - c *circular - } - c := circular{ui8: 1} - c.c = &c - - // Print! - spew.Printf("ppui8: %v\n", ppui8) - spew.Printf("circular: %v\n", c) - - // Output: - // ppui8: <**>5 - // circular: {1 <*>{1 <*>}} -} - -// This example demonstrates how to use a ConfigState. -func ExampleConfigState() { - // Modify the indent level of the ConfigState only. The global - // configuration is not modified. - scs := spew.ConfigState{Indent: "\t"} - - // Output using the ConfigState instance. - v := map[string]int{"one": 1} - scs.Printf("v: %v\n", v) - scs.Dump(v) - - // Output: - // v: map[one:1] - // (map[string]int) (len=1) { - // (string) (len=3) "one": (int) 1 - // } -} - -// This example demonstrates how to use ConfigState.Dump to dump variables to -// stdout -func ExampleConfigState_Dump() { - // See the top-level Dump example for details on the types used in this - // example. - - // Create two ConfigState instances with different indentation. - scs := spew.ConfigState{Indent: "\t"} - scs2 := spew.ConfigState{Indent: " "} - - // Setup some sample data structures for the example. - bar := Bar{uintptr(0)} - s1 := Foo{bar, map[interface{}]interface{}{"one": true}} - - // Dump using the ConfigState instances. - scs.Dump(s1) - scs2.Dump(s1) - - // Output: - // (spew_test.Foo) { - // unexportedField: (spew_test.Bar) { - // data: (uintptr) - // }, - // ExportedField: (map[interface {}]interface {}) (len=1) { - // (string) (len=3) "one": (bool) true - // } - // } - // (spew_test.Foo) { - // unexportedField: (spew_test.Bar) { - // data: (uintptr) - // }, - // ExportedField: (map[interface {}]interface {}) (len=1) { - // (string) (len=3) "one": (bool) true - // } - // } - // -} - -// This example demonstrates how to use ConfigState.Printf to display a variable -// with a format string and inline formatting. -func ExampleConfigState_Printf() { - // See the top-level Dump example for details on the types used in this - // example. - - // Create two ConfigState instances and modify the method handling of the - // first ConfigState only. - scs := spew.NewDefaultConfig() - scs2 := spew.NewDefaultConfig() - scs.DisableMethods = true - - // Alternatively - // scs := spew.ConfigState{Indent: " ", DisableMethods: true} - // scs2 := spew.ConfigState{Indent: " "} - - // This is of type Flag which implements a Stringer and has raw value 1. - f := flagTwo - - // Dump using the ConfigState instances. - scs.Printf("f: %v\n", f) - scs2.Printf("f: %v\n", f) - - // Output: - // f: 1 - // f: flagTwo -} diff --git a/vendor/github.com/davecgh/go-spew/spew/format_test.go b/vendor/github.com/davecgh/go-spew/spew/format_test.go deleted file mode 100644 index f9b93abe8..000000000 --- a/vendor/github.com/davecgh/go-spew/spew/format_test.go +++ /dev/null @@ -1,1558 +0,0 @@ -/* - * Copyright (c) 2013-2016 Dave Collins - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -/* -Test Summary: -NOTE: For each test, a nil pointer, a single pointer and double pointer to the -base test element are also tested to ensure proper indirection across all types. - -- Max int8, int16, int32, int64, int -- Max uint8, uint16, uint32, uint64, uint -- Boolean true and false -- Standard complex64 and complex128 -- Array containing standard ints -- Array containing type with custom formatter on pointer receiver only -- Array containing interfaces -- Slice containing standard float32 values -- Slice containing type with custom formatter on pointer receiver only -- Slice containing interfaces -- Nil slice -- Standard string -- Nil interface -- Sub-interface -- Map with string keys and int vals -- Map with custom formatter type on pointer receiver only keys and vals -- Map with interface keys and values -- Map with nil interface value -- Struct with primitives -- Struct that contains another struct -- Struct that contains custom type with Stringer pointer interface via both - exported and unexported fields -- Struct that contains embedded struct and field to same struct -- Uintptr to 0 (null pointer) -- Uintptr address of real variable -- Unsafe.Pointer to 0 (null pointer) -- Unsafe.Pointer to address of real variable -- Nil channel -- Standard int channel -- Function with no params and no returns -- Function with param and no returns -- Function with multiple params and multiple returns -- Struct that is circular through self referencing -- Structs that are circular through cross referencing -- Structs that are indirectly circular -- Type that panics in its Stringer interface -- Type that has a custom Error interface -- %x passthrough with uint -- %#x passthrough with uint -- %f passthrough with precision -- %f passthrough with width and precision -- %d passthrough with width -- %q passthrough with string -*/ - -package spew_test - -import ( - "bytes" - "fmt" - "testing" - "unsafe" - - "github.com/davecgh/go-spew/spew" -) - -// formatterTest is used to describe a test to be performed against NewFormatter. -type formatterTest struct { - format string - in interface{} - wants []string -} - -// formatterTests houses all of the tests to be performed against NewFormatter. -var formatterTests = make([]formatterTest, 0) - -// addFormatterTest is a helper method to append the passed input and desired -// result to formatterTests. -func addFormatterTest(format string, in interface{}, wants ...string) { - test := formatterTest{format, in, wants} - formatterTests = append(formatterTests, test) -} - -func addIntFormatterTests() { - // Max int8. - v := int8(127) - nv := (*int8)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "int8" - vs := "127" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Max int16. - v2 := int16(32767) - nv2 := (*int16)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "int16" - v2s := "32767" - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%v", nv2, "") - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") - - // Max int32. - v3 := int32(2147483647) - nv3 := (*int32)(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "int32" - v3s := "2147483647" - addFormatterTest("%v", v3, v3s) - addFormatterTest("%v", pv3, "<*>"+v3s) - addFormatterTest("%v", &pv3, "<**>"+v3s) - addFormatterTest("%v", nv3, "") - addFormatterTest("%+v", v3, v3s) - addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s) - addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%#v", v3, "("+v3t+")"+v3s) - addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s) - addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s) - addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") - addFormatterTest("%#+v", v3, "("+v3t+")"+v3s) - addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s) - addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s) - addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") - - // Max int64. - v4 := int64(9223372036854775807) - nv4 := (*int64)(nil) - pv4 := &v4 - v4Addr := fmt.Sprintf("%p", pv4) - pv4Addr := fmt.Sprintf("%p", &pv4) - v4t := "int64" - v4s := "9223372036854775807" - addFormatterTest("%v", v4, v4s) - addFormatterTest("%v", pv4, "<*>"+v4s) - addFormatterTest("%v", &pv4, "<**>"+v4s) - addFormatterTest("%v", nv4, "") - addFormatterTest("%+v", v4, v4s) - addFormatterTest("%+v", pv4, "<*>("+v4Addr+")"+v4s) - addFormatterTest("%+v", &pv4, "<**>("+pv4Addr+"->"+v4Addr+")"+v4s) - addFormatterTest("%+v", nv4, "") - addFormatterTest("%#v", v4, "("+v4t+")"+v4s) - addFormatterTest("%#v", pv4, "(*"+v4t+")"+v4s) - addFormatterTest("%#v", &pv4, "(**"+v4t+")"+v4s) - addFormatterTest("%#v", nv4, "(*"+v4t+")"+"") - addFormatterTest("%#+v", v4, "("+v4t+")"+v4s) - addFormatterTest("%#+v", pv4, "(*"+v4t+")("+v4Addr+")"+v4s) - addFormatterTest("%#+v", &pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")"+v4s) - addFormatterTest("%#+v", nv4, "(*"+v4t+")"+"") - - // Max int. - v5 := int(2147483647) - nv5 := (*int)(nil) - pv5 := &v5 - v5Addr := fmt.Sprintf("%p", pv5) - pv5Addr := fmt.Sprintf("%p", &pv5) - v5t := "int" - v5s := "2147483647" - addFormatterTest("%v", v5, v5s) - addFormatterTest("%v", pv5, "<*>"+v5s) - addFormatterTest("%v", &pv5, "<**>"+v5s) - addFormatterTest("%v", nv5, "") - addFormatterTest("%+v", v5, v5s) - addFormatterTest("%+v", pv5, "<*>("+v5Addr+")"+v5s) - addFormatterTest("%+v", &pv5, "<**>("+pv5Addr+"->"+v5Addr+")"+v5s) - addFormatterTest("%+v", nv5, "") - addFormatterTest("%#v", v5, "("+v5t+")"+v5s) - addFormatterTest("%#v", pv5, "(*"+v5t+")"+v5s) - addFormatterTest("%#v", &pv5, "(**"+v5t+")"+v5s) - addFormatterTest("%#v", nv5, "(*"+v5t+")"+"") - addFormatterTest("%#+v", v5, "("+v5t+")"+v5s) - addFormatterTest("%#+v", pv5, "(*"+v5t+")("+v5Addr+")"+v5s) - addFormatterTest("%#+v", &pv5, "(**"+v5t+")("+pv5Addr+"->"+v5Addr+")"+v5s) - addFormatterTest("%#+v", nv5, "(*"+v5t+")"+"") -} - -func addUintFormatterTests() { - // Max uint8. - v := uint8(255) - nv := (*uint8)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "uint8" - vs := "255" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Max uint16. - v2 := uint16(65535) - nv2 := (*uint16)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "uint16" - v2s := "65535" - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%v", nv2, "") - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") - - // Max uint32. - v3 := uint32(4294967295) - nv3 := (*uint32)(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "uint32" - v3s := "4294967295" - addFormatterTest("%v", v3, v3s) - addFormatterTest("%v", pv3, "<*>"+v3s) - addFormatterTest("%v", &pv3, "<**>"+v3s) - addFormatterTest("%v", nv3, "") - addFormatterTest("%+v", v3, v3s) - addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s) - addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%#v", v3, "("+v3t+")"+v3s) - addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s) - addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s) - addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") - addFormatterTest("%#+v", v3, "("+v3t+")"+v3s) - addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s) - addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s) - addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") - - // Max uint64. - v4 := uint64(18446744073709551615) - nv4 := (*uint64)(nil) - pv4 := &v4 - v4Addr := fmt.Sprintf("%p", pv4) - pv4Addr := fmt.Sprintf("%p", &pv4) - v4t := "uint64" - v4s := "18446744073709551615" - addFormatterTest("%v", v4, v4s) - addFormatterTest("%v", pv4, "<*>"+v4s) - addFormatterTest("%v", &pv4, "<**>"+v4s) - addFormatterTest("%v", nv4, "") - addFormatterTest("%+v", v4, v4s) - addFormatterTest("%+v", pv4, "<*>("+v4Addr+")"+v4s) - addFormatterTest("%+v", &pv4, "<**>("+pv4Addr+"->"+v4Addr+")"+v4s) - addFormatterTest("%+v", nv4, "") - addFormatterTest("%#v", v4, "("+v4t+")"+v4s) - addFormatterTest("%#v", pv4, "(*"+v4t+")"+v4s) - addFormatterTest("%#v", &pv4, "(**"+v4t+")"+v4s) - addFormatterTest("%#v", nv4, "(*"+v4t+")"+"") - addFormatterTest("%#+v", v4, "("+v4t+")"+v4s) - addFormatterTest("%#+v", pv4, "(*"+v4t+")("+v4Addr+")"+v4s) - addFormatterTest("%#+v", &pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")"+v4s) - addFormatterTest("%#+v", nv4, "(*"+v4t+")"+"") - - // Max uint. - v5 := uint(4294967295) - nv5 := (*uint)(nil) - pv5 := &v5 - v5Addr := fmt.Sprintf("%p", pv5) - pv5Addr := fmt.Sprintf("%p", &pv5) - v5t := "uint" - v5s := "4294967295" - addFormatterTest("%v", v5, v5s) - addFormatterTest("%v", pv5, "<*>"+v5s) - addFormatterTest("%v", &pv5, "<**>"+v5s) - addFormatterTest("%v", nv5, "") - addFormatterTest("%+v", v5, v5s) - addFormatterTest("%+v", pv5, "<*>("+v5Addr+")"+v5s) - addFormatterTest("%+v", &pv5, "<**>("+pv5Addr+"->"+v5Addr+")"+v5s) - addFormatterTest("%+v", nv5, "") - addFormatterTest("%#v", v5, "("+v5t+")"+v5s) - addFormatterTest("%#v", pv5, "(*"+v5t+")"+v5s) - addFormatterTest("%#v", &pv5, "(**"+v5t+")"+v5s) - addFormatterTest("%#v", nv5, "(*"+v5t+")"+"") - addFormatterTest("%#+v", v5, "("+v5t+")"+v5s) - addFormatterTest("%#+v", pv5, "(*"+v5t+")("+v5Addr+")"+v5s) - addFormatterTest("%#+v", &pv5, "(**"+v5t+")("+pv5Addr+"->"+v5Addr+")"+v5s) - addFormatterTest("%#v", nv5, "(*"+v5t+")"+"") -} - -func addBoolFormatterTests() { - // Boolean true. - v := bool(true) - nv := (*bool)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "bool" - vs := "true" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Boolean false. - v2 := bool(false) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "bool" - v2s := "false" - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) -} - -func addFloatFormatterTests() { - // Standard float32. - v := float32(3.1415) - nv := (*float32)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "float32" - vs := "3.1415" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Standard float64. - v2 := float64(3.1415926) - nv2 := (*float64)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "float64" - v2s := "3.1415926" - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") -} - -func addComplexFormatterTests() { - // Standard complex64. - v := complex(float32(6), -2) - nv := (*complex64)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "complex64" - vs := "(6-2i)" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Standard complex128. - v2 := complex(float64(-6), 2) - nv2 := (*complex128)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "complex128" - v2s := "(-6+2i)" - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") -} - -func addArrayFormatterTests() { - // Array containing standard ints. - v := [3]int{1, 2, 3} - nv := (*[3]int)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "[3]int" - vs := "[1 2 3]" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Array containing type with custom formatter on pointer receiver only. - v2 := [3]pstringer{"1", "2", "3"} - nv2 := (*[3]pstringer)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "[3]spew_test.pstringer" - v2sp := "[stringer 1 stringer 2 stringer 3]" - v2s := v2sp - if spew.UnsafeDisabled { - v2s = "[1 2 3]" - } - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2sp) - addFormatterTest("%v", &pv2, "<**>"+v2sp) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2sp) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2sp) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2sp) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2sp) - addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2sp) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2sp) - addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") - - // Array containing interfaces. - v3 := [3]interface{}{"one", int(2), uint(3)} - nv3 := (*[3]interface{})(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "[3]interface {}" - v3t2 := "string" - v3t3 := "int" - v3t4 := "uint" - v3s := "[one 2 3]" - v3s2 := "[(" + v3t2 + ")one (" + v3t3 + ")2 (" + v3t4 + ")3]" - addFormatterTest("%v", v3, v3s) - addFormatterTest("%v", pv3, "<*>"+v3s) - addFormatterTest("%v", &pv3, "<**>"+v3s) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%+v", v3, v3s) - addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s) - addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%#v", v3, "("+v3t+")"+v3s2) - addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s2) - addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s2) - addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") - addFormatterTest("%#+v", v3, "("+v3t+")"+v3s2) - addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s2) - addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s2) - addFormatterTest("%#+v", nv3, "(*"+v3t+")"+"") -} - -func addSliceFormatterTests() { - // Slice containing standard float32 values. - v := []float32{3.14, 6.28, 12.56} - nv := (*[]float32)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "[]float32" - vs := "[3.14 6.28 12.56]" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Slice containing type with custom formatter on pointer receiver only. - v2 := []pstringer{"1", "2", "3"} - nv2 := (*[]pstringer)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "[]spew_test.pstringer" - v2s := "[stringer 1 stringer 2 stringer 3]" - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") - - // Slice containing interfaces. - v3 := []interface{}{"one", int(2), uint(3), nil} - nv3 := (*[]interface{})(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "[]interface {}" - v3t2 := "string" - v3t3 := "int" - v3t4 := "uint" - v3t5 := "interface {}" - v3s := "[one 2 3 ]" - v3s2 := "[(" + v3t2 + ")one (" + v3t3 + ")2 (" + v3t4 + ")3 (" + v3t5 + - ")]" - addFormatterTest("%v", v3, v3s) - addFormatterTest("%v", pv3, "<*>"+v3s) - addFormatterTest("%v", &pv3, "<**>"+v3s) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%+v", v3, v3s) - addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s) - addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%#v", v3, "("+v3t+")"+v3s2) - addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s2) - addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s2) - addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") - addFormatterTest("%#+v", v3, "("+v3t+")"+v3s2) - addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s2) - addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s2) - addFormatterTest("%#+v", nv3, "(*"+v3t+")"+"") - - // Nil slice. - var v4 []int - nv4 := (*[]int)(nil) - pv4 := &v4 - v4Addr := fmt.Sprintf("%p", pv4) - pv4Addr := fmt.Sprintf("%p", &pv4) - v4t := "[]int" - v4s := "" - addFormatterTest("%v", v4, v4s) - addFormatterTest("%v", pv4, "<*>"+v4s) - addFormatterTest("%v", &pv4, "<**>"+v4s) - addFormatterTest("%+v", nv4, "") - addFormatterTest("%+v", v4, v4s) - addFormatterTest("%+v", pv4, "<*>("+v4Addr+")"+v4s) - addFormatterTest("%+v", &pv4, "<**>("+pv4Addr+"->"+v4Addr+")"+v4s) - addFormatterTest("%+v", nv4, "") - addFormatterTest("%#v", v4, "("+v4t+")"+v4s) - addFormatterTest("%#v", pv4, "(*"+v4t+")"+v4s) - addFormatterTest("%#v", &pv4, "(**"+v4t+")"+v4s) - addFormatterTest("%#v", nv4, "(*"+v4t+")"+"") - addFormatterTest("%#+v", v4, "("+v4t+")"+v4s) - addFormatterTest("%#+v", pv4, "(*"+v4t+")("+v4Addr+")"+v4s) - addFormatterTest("%#+v", &pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")"+v4s) - addFormatterTest("%#+v", nv4, "(*"+v4t+")"+"") -} - -func addStringFormatterTests() { - // Standard string. - v := "test" - nv := (*string)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "string" - vs := "test" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") -} - -func addInterfaceFormatterTests() { - // Nil interface. - var v interface{} - nv := (*interface{})(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "interface {}" - vs := "" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Sub-interface. - v2 := interface{}(uint16(65535)) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "uint16" - v2s := "65535" - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) -} - -func addMapFormatterTests() { - // Map with string keys and int vals. - v := map[string]int{"one": 1, "two": 2} - nilMap := map[string]int(nil) - nv := (*map[string]int)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "map[string]int" - vs := "map[one:1 two:2]" - vs2 := "map[two:2 one:1]" - addFormatterTest("%v", v, vs, vs2) - addFormatterTest("%v", pv, "<*>"+vs, "<*>"+vs2) - addFormatterTest("%v", &pv, "<**>"+vs, "<**>"+vs2) - addFormatterTest("%+v", nilMap, "") - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs, vs2) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs, "<*>("+vAddr+")"+vs2) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs, - "<**>("+pvAddr+"->"+vAddr+")"+vs2) - addFormatterTest("%+v", nilMap, "") - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs, "("+vt+")"+vs2) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs, "(*"+vt+")"+vs2) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs, "(**"+vt+")"+vs2) - addFormatterTest("%#v", nilMap, "("+vt+")"+"") - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs, "("+vt+")"+vs2) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs, - "(*"+vt+")("+vAddr+")"+vs2) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs, - "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs2) - addFormatterTest("%#+v", nilMap, "("+vt+")"+"") - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Map with custom formatter type on pointer receiver only keys and vals. - v2 := map[pstringer]pstringer{"one": "1"} - nv2 := (*map[pstringer]pstringer)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "map[spew_test.pstringer]spew_test.pstringer" - v2s := "map[stringer one:stringer 1]" - if spew.UnsafeDisabled { - v2s = "map[one:1]" - } - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") - - // Map with interface keys and values. - v3 := map[interface{}]interface{}{"one": 1} - nv3 := (*map[interface{}]interface{})(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "map[interface {}]interface {}" - v3t1 := "string" - v3t2 := "int" - v3s := "map[one:1]" - v3s2 := "map[(" + v3t1 + ")one:(" + v3t2 + ")1]" - addFormatterTest("%v", v3, v3s) - addFormatterTest("%v", pv3, "<*>"+v3s) - addFormatterTest("%v", &pv3, "<**>"+v3s) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%+v", v3, v3s) - addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s) - addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%#v", v3, "("+v3t+")"+v3s2) - addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s2) - addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s2) - addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") - addFormatterTest("%#+v", v3, "("+v3t+")"+v3s2) - addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s2) - addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s2) - addFormatterTest("%#+v", nv3, "(*"+v3t+")"+"") - - // Map with nil interface value - v4 := map[string]interface{}{"nil": nil} - nv4 := (*map[string]interface{})(nil) - pv4 := &v4 - v4Addr := fmt.Sprintf("%p", pv4) - pv4Addr := fmt.Sprintf("%p", &pv4) - v4t := "map[string]interface {}" - v4t1 := "interface {}" - v4s := "map[nil:]" - v4s2 := "map[nil:(" + v4t1 + ")]" - addFormatterTest("%v", v4, v4s) - addFormatterTest("%v", pv4, "<*>"+v4s) - addFormatterTest("%v", &pv4, "<**>"+v4s) - addFormatterTest("%+v", nv4, "") - addFormatterTest("%+v", v4, v4s) - addFormatterTest("%+v", pv4, "<*>("+v4Addr+")"+v4s) - addFormatterTest("%+v", &pv4, "<**>("+pv4Addr+"->"+v4Addr+")"+v4s) - addFormatterTest("%+v", nv4, "") - addFormatterTest("%#v", v4, "("+v4t+")"+v4s2) - addFormatterTest("%#v", pv4, "(*"+v4t+")"+v4s2) - addFormatterTest("%#v", &pv4, "(**"+v4t+")"+v4s2) - addFormatterTest("%#v", nv4, "(*"+v4t+")"+"") - addFormatterTest("%#+v", v4, "("+v4t+")"+v4s2) - addFormatterTest("%#+v", pv4, "(*"+v4t+")("+v4Addr+")"+v4s2) - addFormatterTest("%#+v", &pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")"+v4s2) - addFormatterTest("%#+v", nv4, "(*"+v4t+")"+"") -} - -func addStructFormatterTests() { - // Struct with primitives. - type s1 struct { - a int8 - b uint8 - } - v := s1{127, 255} - nv := (*s1)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "spew_test.s1" - vt2 := "int8" - vt3 := "uint8" - vs := "{127 255}" - vs2 := "{a:127 b:255}" - vs3 := "{a:(" + vt2 + ")127 b:(" + vt3 + ")255}" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs2) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs2) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs2) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs3) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs3) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs3) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs3) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs3) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs3) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Struct that contains another struct. - type s2 struct { - s1 s1 - b bool - } - v2 := s2{s1{127, 255}, true} - nv2 := (*s2)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "spew_test.s2" - v2t2 := "spew_test.s1" - v2t3 := "int8" - v2t4 := "uint8" - v2t5 := "bool" - v2s := "{{127 255} true}" - v2s2 := "{s1:{a:127 b:255} b:true}" - v2s3 := "{s1:(" + v2t2 + "){a:(" + v2t3 + ")127 b:(" + v2t4 + ")255} b:(" + - v2t5 + ")true}" - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%+v", v2, v2s2) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s2) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s2) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%#v", v2, "("+v2t+")"+v2s3) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s3) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s3) - addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s3) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s3) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s3) - addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") - - // Struct that contains custom type with Stringer pointer interface via both - // exported and unexported fields. - type s3 struct { - s pstringer - S pstringer - } - v3 := s3{"test", "test2"} - nv3 := (*s3)(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "spew_test.s3" - v3t2 := "spew_test.pstringer" - v3s := "{stringer test stringer test2}" - v3sp := v3s - v3s2 := "{s:stringer test S:stringer test2}" - v3s2p := v3s2 - v3s3 := "{s:(" + v3t2 + ")stringer test S:(" + v3t2 + ")stringer test2}" - v3s3p := v3s3 - if spew.UnsafeDisabled { - v3s = "{test test2}" - v3sp = "{test stringer test2}" - v3s2 = "{s:test S:test2}" - v3s2p = "{s:test S:stringer test2}" - v3s3 = "{s:(" + v3t2 + ")test S:(" + v3t2 + ")test2}" - v3s3p = "{s:(" + v3t2 + ")test S:(" + v3t2 + ")stringer test2}" - } - addFormatterTest("%v", v3, v3s) - addFormatterTest("%v", pv3, "<*>"+v3sp) - addFormatterTest("%v", &pv3, "<**>"+v3sp) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%+v", v3, v3s2) - addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s2p) - addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s2p) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%#v", v3, "("+v3t+")"+v3s3) - addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s3p) - addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s3p) - addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") - addFormatterTest("%#+v", v3, "("+v3t+")"+v3s3) - addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s3p) - addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s3p) - addFormatterTest("%#+v", nv3, "(*"+v3t+")"+"") - - // Struct that contains embedded struct and field to same struct. - e := embed{"embedstr"} - v4 := embedwrap{embed: &e, e: &e} - nv4 := (*embedwrap)(nil) - pv4 := &v4 - eAddr := fmt.Sprintf("%p", &e) - v4Addr := fmt.Sprintf("%p", pv4) - pv4Addr := fmt.Sprintf("%p", &pv4) - v4t := "spew_test.embedwrap" - v4t2 := "spew_test.embed" - v4t3 := "string" - v4s := "{<*>{embedstr} <*>{embedstr}}" - v4s2 := "{embed:<*>(" + eAddr + "){a:embedstr} e:<*>(" + eAddr + - "){a:embedstr}}" - v4s3 := "{embed:(*" + v4t2 + "){a:(" + v4t3 + ")embedstr} e:(*" + v4t2 + - "){a:(" + v4t3 + ")embedstr}}" - v4s4 := "{embed:(*" + v4t2 + ")(" + eAddr + "){a:(" + v4t3 + - ")embedstr} e:(*" + v4t2 + ")(" + eAddr + "){a:(" + v4t3 + ")embedstr}}" - addFormatterTest("%v", v4, v4s) - addFormatterTest("%v", pv4, "<*>"+v4s) - addFormatterTest("%v", &pv4, "<**>"+v4s) - addFormatterTest("%+v", nv4, "") - addFormatterTest("%+v", v4, v4s2) - addFormatterTest("%+v", pv4, "<*>("+v4Addr+")"+v4s2) - addFormatterTest("%+v", &pv4, "<**>("+pv4Addr+"->"+v4Addr+")"+v4s2) - addFormatterTest("%+v", nv4, "") - addFormatterTest("%#v", v4, "("+v4t+")"+v4s3) - addFormatterTest("%#v", pv4, "(*"+v4t+")"+v4s3) - addFormatterTest("%#v", &pv4, "(**"+v4t+")"+v4s3) - addFormatterTest("%#v", nv4, "(*"+v4t+")"+"") - addFormatterTest("%#+v", v4, "("+v4t+")"+v4s4) - addFormatterTest("%#+v", pv4, "(*"+v4t+")("+v4Addr+")"+v4s4) - addFormatterTest("%#+v", &pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")"+v4s4) - addFormatterTest("%#+v", nv4, "(*"+v4t+")"+"") -} - -func addUintptrFormatterTests() { - // Null pointer. - v := uintptr(0) - nv := (*uintptr)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "uintptr" - vs := "" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Address of real variable. - i := 1 - v2 := uintptr(unsafe.Pointer(&i)) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "uintptr" - v2s := fmt.Sprintf("%p", &i) - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) -} - -func addUnsafePointerFormatterTests() { - // Null pointer. - v := unsafe.Pointer(uintptr(0)) - nv := (*unsafe.Pointer)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "unsafe.Pointer" - vs := "" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Address of real variable. - i := 1 - v2 := unsafe.Pointer(&i) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "unsafe.Pointer" - v2s := fmt.Sprintf("%p", &i) - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) -} - -func addChanFormatterTests() { - // Nil channel. - var v chan int - pv := &v - nv := (*chan int)(nil) - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "chan int" - vs := "" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Real channel. - v2 := make(chan int) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "chan int" - v2s := fmt.Sprintf("%p", v2) - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) -} - -func addFuncFormatterTests() { - // Function with no params and no returns. - v := addIntFormatterTests - nv := (*func())(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "func()" - vs := fmt.Sprintf("%p", v) - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Function with param and no returns. - v2 := TestFormatter - nv2 := (*func(*testing.T))(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "func(*testing.T)" - v2s := fmt.Sprintf("%p", v2) - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") - - // Function with multiple params and multiple returns. - var v3 = func(i int, s string) (b bool, err error) { - return true, nil - } - nv3 := (*func(int, string) (bool, error))(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "func(int, string) (bool, error)" - v3s := fmt.Sprintf("%p", v3) - addFormatterTest("%v", v3, v3s) - addFormatterTest("%v", pv3, "<*>"+v3s) - addFormatterTest("%v", &pv3, "<**>"+v3s) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%+v", v3, v3s) - addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s) - addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%#v", v3, "("+v3t+")"+v3s) - addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s) - addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s) - addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") - addFormatterTest("%#+v", v3, "("+v3t+")"+v3s) - addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s) - addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s) - addFormatterTest("%#+v", nv3, "(*"+v3t+")"+"") -} - -func addCircularFormatterTests() { - // Struct that is circular through self referencing. - type circular struct { - c *circular - } - v := circular{nil} - v.c = &v - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "spew_test.circular" - vs := "{<*>{<*>}}" - vs2 := "{<*>}" - vs3 := "{c:<*>(" + vAddr + "){c:<*>(" + vAddr + ")}}" - vs4 := "{c:<*>(" + vAddr + ")}" - vs5 := "{c:(*" + vt + "){c:(*" + vt + ")}}" - vs6 := "{c:(*" + vt + ")}" - vs7 := "{c:(*" + vt + ")(" + vAddr + "){c:(*" + vt + ")(" + vAddr + - ")}}" - vs8 := "{c:(*" + vt + ")(" + vAddr + ")}" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs2) - addFormatterTest("%v", &pv, "<**>"+vs2) - addFormatterTest("%+v", v, vs3) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs4) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs4) - addFormatterTest("%#v", v, "("+vt+")"+vs5) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs6) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs6) - addFormatterTest("%#+v", v, "("+vt+")"+vs7) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs8) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs8) - - // Structs that are circular through cross referencing. - v2 := xref1{nil} - ts2 := xref2{&v2} - v2.ps2 = &ts2 - pv2 := &v2 - ts2Addr := fmt.Sprintf("%p", &ts2) - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "spew_test.xref1" - v2t2 := "spew_test.xref2" - v2s := "{<*>{<*>{<*>}}}" - v2s2 := "{<*>{<*>}}" - v2s3 := "{ps2:<*>(" + ts2Addr + "){ps1:<*>(" + v2Addr + "){ps2:<*>(" + - ts2Addr + ")}}}" - v2s4 := "{ps2:<*>(" + ts2Addr + "){ps1:<*>(" + v2Addr + ")}}" - v2s5 := "{ps2:(*" + v2t2 + "){ps1:(*" + v2t + "){ps2:(*" + v2t2 + - ")}}}" - v2s6 := "{ps2:(*" + v2t2 + "){ps1:(*" + v2t + ")}}" - v2s7 := "{ps2:(*" + v2t2 + ")(" + ts2Addr + "){ps1:(*" + v2t + - ")(" + v2Addr + "){ps2:(*" + v2t2 + ")(" + ts2Addr + - ")}}}" - v2s8 := "{ps2:(*" + v2t2 + ")(" + ts2Addr + "){ps1:(*" + v2t + - ")(" + v2Addr + ")}}" - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s2) - addFormatterTest("%v", &pv2, "<**>"+v2s2) - addFormatterTest("%+v", v2, v2s3) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s4) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s4) - addFormatterTest("%#v", v2, "("+v2t+")"+v2s5) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s6) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s6) - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s7) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s8) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s8) - - // Structs that are indirectly circular. - v3 := indirCir1{nil} - tic2 := indirCir2{nil} - tic3 := indirCir3{&v3} - tic2.ps3 = &tic3 - v3.ps2 = &tic2 - pv3 := &v3 - tic2Addr := fmt.Sprintf("%p", &tic2) - tic3Addr := fmt.Sprintf("%p", &tic3) - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "spew_test.indirCir1" - v3t2 := "spew_test.indirCir2" - v3t3 := "spew_test.indirCir3" - v3s := "{<*>{<*>{<*>{<*>}}}}" - v3s2 := "{<*>{<*>{<*>}}}" - v3s3 := "{ps2:<*>(" + tic2Addr + "){ps3:<*>(" + tic3Addr + "){ps1:<*>(" + - v3Addr + "){ps2:<*>(" + tic2Addr + ")}}}}" - v3s4 := "{ps2:<*>(" + tic2Addr + "){ps3:<*>(" + tic3Addr + "){ps1:<*>(" + - v3Addr + ")}}}" - v3s5 := "{ps2:(*" + v3t2 + "){ps3:(*" + v3t3 + "){ps1:(*" + v3t + - "){ps2:(*" + v3t2 + ")}}}}" - v3s6 := "{ps2:(*" + v3t2 + "){ps3:(*" + v3t3 + "){ps1:(*" + v3t + - ")}}}" - v3s7 := "{ps2:(*" + v3t2 + ")(" + tic2Addr + "){ps3:(*" + v3t3 + ")(" + - tic3Addr + "){ps1:(*" + v3t + ")(" + v3Addr + "){ps2:(*" + v3t2 + - ")(" + tic2Addr + ")}}}}" - v3s8 := "{ps2:(*" + v3t2 + ")(" + tic2Addr + "){ps3:(*" + v3t3 + ")(" + - tic3Addr + "){ps1:(*" + v3t + ")(" + v3Addr + ")}}}" - addFormatterTest("%v", v3, v3s) - addFormatterTest("%v", pv3, "<*>"+v3s2) - addFormatterTest("%v", &pv3, "<**>"+v3s2) - addFormatterTest("%+v", v3, v3s3) - addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s4) - addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s4) - addFormatterTest("%#v", v3, "("+v3t+")"+v3s5) - addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s6) - addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s6) - addFormatterTest("%#+v", v3, "("+v3t+")"+v3s7) - addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s8) - addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s8) -} - -func addPanicFormatterTests() { - // Type that panics in its Stringer interface. - v := panicer(127) - nv := (*panicer)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "spew_test.panicer" - vs := "(PANIC=test panic)127" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") -} - -func addErrorFormatterTests() { - // Type that has a custom Error interface. - v := customError(127) - nv := (*customError)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "spew_test.customError" - vs := "error: 127" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") -} - -func addPassthroughFormatterTests() { - // %x passthrough with uint. - v := uint(4294967295) - pv := &v - vAddr := fmt.Sprintf("%x", pv) - pvAddr := fmt.Sprintf("%x", &pv) - vs := "ffffffff" - addFormatterTest("%x", v, vs) - addFormatterTest("%x", pv, vAddr) - addFormatterTest("%x", &pv, pvAddr) - - // %#x passthrough with uint. - v2 := int(2147483647) - pv2 := &v2 - v2Addr := fmt.Sprintf("%#x", pv2) - pv2Addr := fmt.Sprintf("%#x", &pv2) - v2s := "0x7fffffff" - addFormatterTest("%#x", v2, v2s) - addFormatterTest("%#x", pv2, v2Addr) - addFormatterTest("%#x", &pv2, pv2Addr) - - // %f passthrough with precision. - addFormatterTest("%.2f", 3.1415, "3.14") - addFormatterTest("%.3f", 3.1415, "3.142") - addFormatterTest("%.4f", 3.1415, "3.1415") - - // %f passthrough with width and precision. - addFormatterTest("%5.2f", 3.1415, " 3.14") - addFormatterTest("%6.3f", 3.1415, " 3.142") - addFormatterTest("%7.4f", 3.1415, " 3.1415") - - // %d passthrough with width. - addFormatterTest("%3d", 127, "127") - addFormatterTest("%4d", 127, " 127") - addFormatterTest("%5d", 127, " 127") - - // %q passthrough with string. - addFormatterTest("%q", "test", "\"test\"") -} - -// TestFormatter executes all of the tests described by formatterTests. -func TestFormatter(t *testing.T) { - // Setup tests. - addIntFormatterTests() - addUintFormatterTests() - addBoolFormatterTests() - addFloatFormatterTests() - addComplexFormatterTests() - addArrayFormatterTests() - addSliceFormatterTests() - addStringFormatterTests() - addInterfaceFormatterTests() - addMapFormatterTests() - addStructFormatterTests() - addUintptrFormatterTests() - addUnsafePointerFormatterTests() - addChanFormatterTests() - addFuncFormatterTests() - addCircularFormatterTests() - addPanicFormatterTests() - addErrorFormatterTests() - addPassthroughFormatterTests() - - t.Logf("Running %d tests", len(formatterTests)) - for i, test := range formatterTests { - buf := new(bytes.Buffer) - spew.Fprintf(buf, test.format, test.in) - s := buf.String() - if testFailed(s, test.wants) { - t.Errorf("Formatter #%d format: %s got: %s %s", i, test.format, s, - stringizeWants(test.wants)) - continue - } - } -} - -type testStruct struct { - x int -} - -func (ts testStruct) String() string { - return fmt.Sprintf("ts.%d", ts.x) -} - -type testStructP struct { - x int -} - -func (ts *testStructP) String() string { - return fmt.Sprintf("ts.%d", ts.x) -} - -func TestPrintSortedKeys(t *testing.T) { - cfg := spew.ConfigState{SortKeys: true} - s := cfg.Sprint(map[int]string{1: "1", 3: "3", 2: "2"}) - expected := "map[1:1 2:2 3:3]" - if s != expected { - t.Errorf("Sorted keys mismatch 1:\n %v %v", s, expected) - } - - s = cfg.Sprint(map[stringer]int{"1": 1, "3": 3, "2": 2}) - expected = "map[stringer 1:1 stringer 2:2 stringer 3:3]" - if s != expected { - t.Errorf("Sorted keys mismatch 2:\n %v %v", s, expected) - } - - s = cfg.Sprint(map[pstringer]int{pstringer("1"): 1, pstringer("3"): 3, pstringer("2"): 2}) - expected = "map[stringer 1:1 stringer 2:2 stringer 3:3]" - if spew.UnsafeDisabled { - expected = "map[1:1 2:2 3:3]" - } - if s != expected { - t.Errorf("Sorted keys mismatch 3:\n %v %v", s, expected) - } - - s = cfg.Sprint(map[testStruct]int{testStruct{1}: 1, testStruct{3}: 3, testStruct{2}: 2}) - expected = "map[ts.1:1 ts.2:2 ts.3:3]" - if s != expected { - t.Errorf("Sorted keys mismatch 4:\n %v %v", s, expected) - } - - if !spew.UnsafeDisabled { - s = cfg.Sprint(map[testStructP]int{testStructP{1}: 1, testStructP{3}: 3, testStructP{2}: 2}) - expected = "map[ts.1:1 ts.2:2 ts.3:3]" - if s != expected { - t.Errorf("Sorted keys mismatch 5:\n %v %v", s, expected) - } - } - - s = cfg.Sprint(map[customError]int{customError(1): 1, customError(3): 3, customError(2): 2}) - expected = "map[error: 1:1 error: 2:2 error: 3:3]" - if s != expected { - t.Errorf("Sorted keys mismatch 6:\n %v %v", s, expected) - } -} diff --git a/vendor/github.com/davecgh/go-spew/spew/internal_test.go b/vendor/github.com/davecgh/go-spew/spew/internal_test.go deleted file mode 100644 index 20a9cfefc..000000000 --- a/vendor/github.com/davecgh/go-spew/spew/internal_test.go +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright (c) 2013-2016 Dave Collins - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -/* -This test file is part of the spew package rather than than the spew_test -package because it needs access to internals to properly test certain cases -which are not possible via the public interface since they should never happen. -*/ - -package spew - -import ( - "bytes" - "reflect" - "testing" -) - -// dummyFmtState implements a fake fmt.State to use for testing invalid -// reflect.Value handling. This is necessary because the fmt package catches -// invalid values before invoking the formatter on them. -type dummyFmtState struct { - bytes.Buffer -} - -func (dfs *dummyFmtState) Flag(f int) bool { - if f == int('+') { - return true - } - return false -} - -func (dfs *dummyFmtState) Precision() (int, bool) { - return 0, false -} - -func (dfs *dummyFmtState) Width() (int, bool) { - return 0, false -} - -// TestInvalidReflectValue ensures the dump and formatter code handles an -// invalid reflect value properly. This needs access to internal state since it -// should never happen in real code and therefore can't be tested via the public -// API. -func TestInvalidReflectValue(t *testing.T) { - i := 1 - - // Dump invalid reflect value. - v := new(reflect.Value) - buf := new(bytes.Buffer) - d := dumpState{w: buf, cs: &Config} - d.dump(*v) - s := buf.String() - want := "" - if s != want { - t.Errorf("InvalidReflectValue #%d\n got: %s want: %s", i, s, want) - } - i++ - - // Formatter invalid reflect value. - buf2 := new(dummyFmtState) - f := formatState{value: *v, cs: &Config, fs: buf2} - f.format(*v) - s = buf2.String() - want = "" - if s != want { - t.Errorf("InvalidReflectValue #%d got: %s want: %s", i, s, want) - } -} - -// SortValues makes the internal sortValues function available to the test -// package. -func SortValues(values []reflect.Value, cs *ConfigState) { - sortValues(values, cs) -} diff --git a/vendor/github.com/davecgh/go-spew/spew/internalunsafe_test.go b/vendor/github.com/davecgh/go-spew/spew/internalunsafe_test.go deleted file mode 100644 index a0c612ec3..000000000 --- a/vendor/github.com/davecgh/go-spew/spew/internalunsafe_test.go +++ /dev/null @@ -1,102 +0,0 @@ -// Copyright (c) 2013-2016 Dave Collins - -// Permission to use, copy, modify, and distribute this software for any -// purpose with or without fee is hereby granted, provided that the above -// copyright notice and this permission notice appear in all copies. - -// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -// NOTE: Due to the following build constraints, this file will only be compiled -// when the code is not running on Google App Engine, compiled by GopherJS, and -// "-tags safe" is not added to the go build command line. The "disableunsafe" -// tag is deprecated and thus should not be used. -// +build !js,!appengine,!safe,!disableunsafe - -/* -This test file is part of the spew package rather than than the spew_test -package because it needs access to internals to properly test certain cases -which are not possible via the public interface since they should never happen. -*/ - -package spew - -import ( - "bytes" - "reflect" - "testing" - "unsafe" -) - -// changeKind uses unsafe to intentionally change the kind of a reflect.Value to -// the maximum kind value which does not exist. This is needed to test the -// fallback code which punts to the standard fmt library for new types that -// might get added to the language. -func changeKind(v *reflect.Value, readOnly bool) { - rvf := (*uintptr)(unsafe.Pointer(uintptr(unsafe.Pointer(v)) + offsetFlag)) - *rvf = *rvf | ((1< - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -package spew_test - -import ( - "bytes" - "fmt" - "io/ioutil" - "os" - "testing" - - "github.com/davecgh/go-spew/spew" -) - -// spewFunc is used to identify which public function of the spew package or -// ConfigState a test applies to. -type spewFunc int - -const ( - fCSFdump spewFunc = iota - fCSFprint - fCSFprintf - fCSFprintln - fCSPrint - fCSPrintln - fCSSdump - fCSSprint - fCSSprintf - fCSSprintln - fCSErrorf - fCSNewFormatter - fErrorf - fFprint - fFprintln - fPrint - fPrintln - fSdump - fSprint - fSprintf - fSprintln -) - -// Map of spewFunc values to names for pretty printing. -var spewFuncStrings = map[spewFunc]string{ - fCSFdump: "ConfigState.Fdump", - fCSFprint: "ConfigState.Fprint", - fCSFprintf: "ConfigState.Fprintf", - fCSFprintln: "ConfigState.Fprintln", - fCSSdump: "ConfigState.Sdump", - fCSPrint: "ConfigState.Print", - fCSPrintln: "ConfigState.Println", - fCSSprint: "ConfigState.Sprint", - fCSSprintf: "ConfigState.Sprintf", - fCSSprintln: "ConfigState.Sprintln", - fCSErrorf: "ConfigState.Errorf", - fCSNewFormatter: "ConfigState.NewFormatter", - fErrorf: "spew.Errorf", - fFprint: "spew.Fprint", - fFprintln: "spew.Fprintln", - fPrint: "spew.Print", - fPrintln: "spew.Println", - fSdump: "spew.Sdump", - fSprint: "spew.Sprint", - fSprintf: "spew.Sprintf", - fSprintln: "spew.Sprintln", -} - -func (f spewFunc) String() string { - if s, ok := spewFuncStrings[f]; ok { - return s - } - return fmt.Sprintf("Unknown spewFunc (%d)", int(f)) -} - -// spewTest is used to describe a test to be performed against the public -// functions of the spew package or ConfigState. -type spewTest struct { - cs *spew.ConfigState - f spewFunc - format string - in interface{} - want string -} - -// spewTests houses the tests to be performed against the public functions of -// the spew package and ConfigState. -// -// These tests are only intended to ensure the public functions are exercised -// and are intentionally not exhaustive of types. The exhaustive type -// tests are handled in the dump and format tests. -var spewTests []spewTest - -// redirStdout is a helper function to return the standard output from f as a -// byte slice. -func redirStdout(f func()) ([]byte, error) { - tempFile, err := ioutil.TempFile("", "ss-test") - if err != nil { - return nil, err - } - fileName := tempFile.Name() - defer os.Remove(fileName) // Ignore error - - origStdout := os.Stdout - os.Stdout = tempFile - f() - os.Stdout = origStdout - tempFile.Close() - - return ioutil.ReadFile(fileName) -} - -func initSpewTests() { - // Config states with various settings. - scsDefault := spew.NewDefaultConfig() - scsNoMethods := &spew.ConfigState{Indent: " ", DisableMethods: true} - scsNoPmethods := &spew.ConfigState{Indent: " ", DisablePointerMethods: true} - scsMaxDepth := &spew.ConfigState{Indent: " ", MaxDepth: 1} - scsContinue := &spew.ConfigState{Indent: " ", ContinueOnMethod: true} - scsNoPtrAddr := &spew.ConfigState{DisablePointerAddresses: true} - scsNoCap := &spew.ConfigState{DisableCapacities: true} - - // Variables for tests on types which implement Stringer interface with and - // without a pointer receiver. - ts := stringer("test") - tps := pstringer("test") - - type ptrTester struct { - s *struct{} - } - tptr := &ptrTester{s: &struct{}{}} - - // depthTester is used to test max depth handling for structs, array, slices - // and maps. - type depthTester struct { - ic indirCir1 - arr [1]string - slice []string - m map[string]int - } - dt := depthTester{indirCir1{nil}, [1]string{"arr"}, []string{"slice"}, - map[string]int{"one": 1}} - - // Variable for tests on types which implement error interface. - te := customError(10) - - spewTests = []spewTest{ - {scsDefault, fCSFdump, "", int8(127), "(int8) 127\n"}, - {scsDefault, fCSFprint, "", int16(32767), "32767"}, - {scsDefault, fCSFprintf, "%v", int32(2147483647), "2147483647"}, - {scsDefault, fCSFprintln, "", int(2147483647), "2147483647\n"}, - {scsDefault, fCSPrint, "", int64(9223372036854775807), "9223372036854775807"}, - {scsDefault, fCSPrintln, "", uint8(255), "255\n"}, - {scsDefault, fCSSdump, "", uint8(64), "(uint8) 64\n"}, - {scsDefault, fCSSprint, "", complex(1, 2), "(1+2i)"}, - {scsDefault, fCSSprintf, "%v", complex(float32(3), 4), "(3+4i)"}, - {scsDefault, fCSSprintln, "", complex(float64(5), 6), "(5+6i)\n"}, - {scsDefault, fCSErrorf, "%#v", uint16(65535), "(uint16)65535"}, - {scsDefault, fCSNewFormatter, "%v", uint32(4294967295), "4294967295"}, - {scsDefault, fErrorf, "%v", uint64(18446744073709551615), "18446744073709551615"}, - {scsDefault, fFprint, "", float32(3.14), "3.14"}, - {scsDefault, fFprintln, "", float64(6.28), "6.28\n"}, - {scsDefault, fPrint, "", true, "true"}, - {scsDefault, fPrintln, "", false, "false\n"}, - {scsDefault, fSdump, "", complex(-10, -20), "(complex128) (-10-20i)\n"}, - {scsDefault, fSprint, "", complex(-1, -2), "(-1-2i)"}, - {scsDefault, fSprintf, "%v", complex(float32(-3), -4), "(-3-4i)"}, - {scsDefault, fSprintln, "", complex(float64(-5), -6), "(-5-6i)\n"}, - {scsNoMethods, fCSFprint, "", ts, "test"}, - {scsNoMethods, fCSFprint, "", &ts, "<*>test"}, - {scsNoMethods, fCSFprint, "", tps, "test"}, - {scsNoMethods, fCSFprint, "", &tps, "<*>test"}, - {scsNoPmethods, fCSFprint, "", ts, "stringer test"}, - {scsNoPmethods, fCSFprint, "", &ts, "<*>stringer test"}, - {scsNoPmethods, fCSFprint, "", tps, "test"}, - {scsNoPmethods, fCSFprint, "", &tps, "<*>stringer test"}, - {scsMaxDepth, fCSFprint, "", dt, "{{} [] [] map[]}"}, - {scsMaxDepth, fCSFdump, "", dt, "(spew_test.depthTester) {\n" + - " ic: (spew_test.indirCir1) {\n \n },\n" + - " arr: ([1]string) (len=1 cap=1) {\n \n },\n" + - " slice: ([]string) (len=1 cap=1) {\n \n },\n" + - " m: (map[string]int) (len=1) {\n \n }\n}\n"}, - {scsContinue, fCSFprint, "", ts, "(stringer test) test"}, - {scsContinue, fCSFdump, "", ts, "(spew_test.stringer) " + - "(len=4) (stringer test) \"test\"\n"}, - {scsContinue, fCSFprint, "", te, "(error: 10) 10"}, - {scsContinue, fCSFdump, "", te, "(spew_test.customError) " + - "(error: 10) 10\n"}, - {scsNoPtrAddr, fCSFprint, "", tptr, "<*>{<*>{}}"}, - {scsNoPtrAddr, fCSSdump, "", tptr, "(*spew_test.ptrTester)({\ns: (*struct {})({\n})\n})\n"}, - {scsNoCap, fCSSdump, "", make([]string, 0, 10), "([]string) {\n}\n"}, - {scsNoCap, fCSSdump, "", make([]string, 1, 10), "([]string) (len=1) {\n(string) \"\"\n}\n"}, - } -} - -// TestSpew executes all of the tests described by spewTests. -func TestSpew(t *testing.T) { - initSpewTests() - - t.Logf("Running %d tests", len(spewTests)) - for i, test := range spewTests { - buf := new(bytes.Buffer) - switch test.f { - case fCSFdump: - test.cs.Fdump(buf, test.in) - - case fCSFprint: - test.cs.Fprint(buf, test.in) - - case fCSFprintf: - test.cs.Fprintf(buf, test.format, test.in) - - case fCSFprintln: - test.cs.Fprintln(buf, test.in) - - case fCSPrint: - b, err := redirStdout(func() { test.cs.Print(test.in) }) - if err != nil { - t.Errorf("%v #%d %v", test.f, i, err) - continue - } - buf.Write(b) - - case fCSPrintln: - b, err := redirStdout(func() { test.cs.Println(test.in) }) - if err != nil { - t.Errorf("%v #%d %v", test.f, i, err) - continue - } - buf.Write(b) - - case fCSSdump: - str := test.cs.Sdump(test.in) - buf.WriteString(str) - - case fCSSprint: - str := test.cs.Sprint(test.in) - buf.WriteString(str) - - case fCSSprintf: - str := test.cs.Sprintf(test.format, test.in) - buf.WriteString(str) - - case fCSSprintln: - str := test.cs.Sprintln(test.in) - buf.WriteString(str) - - case fCSErrorf: - err := test.cs.Errorf(test.format, test.in) - buf.WriteString(err.Error()) - - case fCSNewFormatter: - fmt.Fprintf(buf, test.format, test.cs.NewFormatter(test.in)) - - case fErrorf: - err := spew.Errorf(test.format, test.in) - buf.WriteString(err.Error()) - - case fFprint: - spew.Fprint(buf, test.in) - - case fFprintln: - spew.Fprintln(buf, test.in) - - case fPrint: - b, err := redirStdout(func() { spew.Print(test.in) }) - if err != nil { - t.Errorf("%v #%d %v", test.f, i, err) - continue - } - buf.Write(b) - - case fPrintln: - b, err := redirStdout(func() { spew.Println(test.in) }) - if err != nil { - t.Errorf("%v #%d %v", test.f, i, err) - continue - } - buf.Write(b) - - case fSdump: - str := spew.Sdump(test.in) - buf.WriteString(str) - - case fSprint: - str := spew.Sprint(test.in) - buf.WriteString(str) - - case fSprintf: - str := spew.Sprintf(test.format, test.in) - buf.WriteString(str) - - case fSprintln: - str := spew.Sprintln(test.in) - buf.WriteString(str) - - default: - t.Errorf("%v #%d unrecognized function", test.f, i) - continue - } - s := buf.String() - if test.want != s { - t.Errorf("ConfigState #%d\n got: %s want: %s", i, s, test.want) - continue - } - } -} diff --git a/vendor/github.com/davecgh/go-spew/test_coverage.txt b/vendor/github.com/davecgh/go-spew/test_coverage.txt deleted file mode 100644 index 2cd087a2a..000000000 --- a/vendor/github.com/davecgh/go-spew/test_coverage.txt +++ /dev/null @@ -1,61 +0,0 @@ - -github.com/davecgh/go-spew/spew/dump.go dumpState.dump 100.00% (88/88) -github.com/davecgh/go-spew/spew/format.go formatState.format 100.00% (82/82) -github.com/davecgh/go-spew/spew/format.go formatState.formatPtr 100.00% (52/52) -github.com/davecgh/go-spew/spew/dump.go dumpState.dumpPtr 100.00% (44/44) -github.com/davecgh/go-spew/spew/dump.go dumpState.dumpSlice 100.00% (39/39) -github.com/davecgh/go-spew/spew/common.go handleMethods 100.00% (30/30) -github.com/davecgh/go-spew/spew/common.go printHexPtr 100.00% (18/18) -github.com/davecgh/go-spew/spew/common.go unsafeReflectValue 100.00% (13/13) -github.com/davecgh/go-spew/spew/format.go formatState.constructOrigFormat 100.00% (12/12) -github.com/davecgh/go-spew/spew/dump.go fdump 100.00% (11/11) -github.com/davecgh/go-spew/spew/format.go formatState.Format 100.00% (11/11) -github.com/davecgh/go-spew/spew/common.go init 100.00% (10/10) -github.com/davecgh/go-spew/spew/common.go printComplex 100.00% (9/9) -github.com/davecgh/go-spew/spew/common.go valuesSorter.Less 100.00% (8/8) -github.com/davecgh/go-spew/spew/format.go formatState.buildDefaultFormat 100.00% (7/7) -github.com/davecgh/go-spew/spew/format.go formatState.unpackValue 100.00% (5/5) -github.com/davecgh/go-spew/spew/dump.go dumpState.indent 100.00% (4/4) -github.com/davecgh/go-spew/spew/common.go catchPanic 100.00% (4/4) -github.com/davecgh/go-spew/spew/config.go ConfigState.convertArgs 100.00% (4/4) -github.com/davecgh/go-spew/spew/spew.go convertArgs 100.00% (4/4) -github.com/davecgh/go-spew/spew/format.go newFormatter 100.00% (3/3) -github.com/davecgh/go-spew/spew/dump.go Sdump 100.00% (3/3) -github.com/davecgh/go-spew/spew/common.go printBool 100.00% (3/3) -github.com/davecgh/go-spew/spew/common.go sortValues 100.00% (3/3) -github.com/davecgh/go-spew/spew/config.go ConfigState.Sdump 100.00% (3/3) -github.com/davecgh/go-spew/spew/dump.go dumpState.unpackValue 100.00% (3/3) -github.com/davecgh/go-spew/spew/spew.go Printf 100.00% (1/1) -github.com/davecgh/go-spew/spew/spew.go Println 100.00% (1/1) -github.com/davecgh/go-spew/spew/spew.go Sprint 100.00% (1/1) -github.com/davecgh/go-spew/spew/spew.go Sprintf 100.00% (1/1) -github.com/davecgh/go-spew/spew/spew.go Sprintln 100.00% (1/1) -github.com/davecgh/go-spew/spew/common.go printFloat 100.00% (1/1) -github.com/davecgh/go-spew/spew/config.go NewDefaultConfig 100.00% (1/1) -github.com/davecgh/go-spew/spew/common.go printInt 100.00% (1/1) -github.com/davecgh/go-spew/spew/common.go printUint 100.00% (1/1) -github.com/davecgh/go-spew/spew/common.go valuesSorter.Len 100.00% (1/1) -github.com/davecgh/go-spew/spew/common.go valuesSorter.Swap 100.00% (1/1) -github.com/davecgh/go-spew/spew/config.go ConfigState.Errorf 100.00% (1/1) -github.com/davecgh/go-spew/spew/config.go ConfigState.Fprint 100.00% (1/1) -github.com/davecgh/go-spew/spew/config.go ConfigState.Fprintf 100.00% (1/1) -github.com/davecgh/go-spew/spew/config.go ConfigState.Fprintln 100.00% (1/1) -github.com/davecgh/go-spew/spew/config.go ConfigState.Print 100.00% (1/1) -github.com/davecgh/go-spew/spew/config.go ConfigState.Printf 100.00% (1/1) -github.com/davecgh/go-spew/spew/config.go ConfigState.Println 100.00% (1/1) -github.com/davecgh/go-spew/spew/config.go ConfigState.Sprint 100.00% (1/1) -github.com/davecgh/go-spew/spew/config.go ConfigState.Sprintf 100.00% (1/1) -github.com/davecgh/go-spew/spew/config.go ConfigState.Sprintln 100.00% (1/1) -github.com/davecgh/go-spew/spew/config.go ConfigState.NewFormatter 100.00% (1/1) -github.com/davecgh/go-spew/spew/config.go ConfigState.Fdump 100.00% (1/1) -github.com/davecgh/go-spew/spew/config.go ConfigState.Dump 100.00% (1/1) -github.com/davecgh/go-spew/spew/dump.go Fdump 100.00% (1/1) -github.com/davecgh/go-spew/spew/dump.go Dump 100.00% (1/1) -github.com/davecgh/go-spew/spew/spew.go Fprintln 100.00% (1/1) -github.com/davecgh/go-spew/spew/format.go NewFormatter 100.00% (1/1) -github.com/davecgh/go-spew/spew/spew.go Errorf 100.00% (1/1) -github.com/davecgh/go-spew/spew/spew.go Fprint 100.00% (1/1) -github.com/davecgh/go-spew/spew/spew.go Fprintf 100.00% (1/1) -github.com/davecgh/go-spew/spew/spew.go Print 100.00% (1/1) -github.com/davecgh/go-spew/spew ------------------------------- 100.00% (505/505) - diff --git a/vendor/github.com/dgrijalva/jwt-go/.gitignore b/vendor/github.com/dgrijalva/jwt-go/.gitignore deleted file mode 100644 index 80bed650e..000000000 --- a/vendor/github.com/dgrijalva/jwt-go/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -.DS_Store -bin - - diff --git a/vendor/github.com/dgrijalva/jwt-go/.travis.yml b/vendor/github.com/dgrijalva/jwt-go/.travis.yml deleted file mode 100644 index bde823d8a..000000000 --- a/vendor/github.com/dgrijalva/jwt-go/.travis.yml +++ /dev/null @@ -1,8 +0,0 @@ -language: go - -go: - - 1.3 - - 1.4 - - 1.5 - - 1.6 - - tip diff --git a/vendor/github.com/dgrijalva/jwt-go/MIGRATION_GUIDE.md b/vendor/github.com/dgrijalva/jwt-go/MIGRATION_GUIDE.md deleted file mode 100644 index fd62e9490..000000000 --- a/vendor/github.com/dgrijalva/jwt-go/MIGRATION_GUIDE.md +++ /dev/null @@ -1,96 +0,0 @@ -## Migration Guide from v2 -> v3 - -Version 3 adds several new, frequently requested features. To do so, it introduces a few breaking changes. We've worked to keep these as minimal as possible. This guide explains the breaking changes and how you can quickly update your code. - -### `Token.Claims` is now an interface type - -The most requested feature from the 2.0 verison of this library was the ability to provide a custom type to the JSON parser for claims. This was implemented by introducing a new interface, `Claims`, to replace `map[string]interface{}`. We also included two concrete implementations of `Claims`: `MapClaims` and `StandardClaims`. - -`MapClaims` is an alias for `map[string]interface{}` with built in validation behavior. It is the default claims type when using `Parse`. The usage is unchanged except you must type cast the claims property. - -The old example for parsing a token looked like this.. - -```go - if token, err := jwt.Parse(tokenString, keyLookupFunc); err == nil { - fmt.Printf("Token for user %v expires %v", token.Claims["user"], token.Claims["exp"]) - } -``` - -is now directly mapped to... - -```go - if token, err := jwt.Parse(tokenString, keyLookupFunc); err == nil { - claims := token.Claims.(jwt.MapClaims) - fmt.Printf("Token for user %v expires %v", claims["user"], claims["exp"]) - } -``` - -`StandardClaims` is designed to be embedded in your custom type. You can supply a custom claims type with the new `ParseWithClaims` function. Here's an example of using a custom claims type. - -```go - type MyCustomClaims struct { - User string - *StandardClaims - } - - if token, err := jwt.ParseWithClaims(tokenString, &MyCustomClaims{}, keyLookupFunc); err == nil { - claims := token.Claims.(*MyCustomClaims) - fmt.Printf("Token for user %v expires %v", claims.User, claims.StandardClaims.ExpiresAt) - } -``` - -### `ParseFromRequest` has been moved - -To keep this library focused on the tokens without becoming overburdened with complex request processing logic, `ParseFromRequest` and its new companion `ParseFromRequestWithClaims` have been moved to a subpackage, `request`. The method signatues have also been augmented to receive a new argument: `Extractor`. - -`Extractors` do the work of picking the token string out of a request. The interface is simple and composable. - -This simple parsing example: - -```go - if token, err := jwt.ParseFromRequest(tokenString, req, keyLookupFunc); err == nil { - fmt.Printf("Token for user %v expires %v", token.Claims["user"], token.Claims["exp"]) - } -``` - -is directly mapped to: - -```go - if token, err := request.ParseFromRequest(tokenString, request.OAuth2Extractor, req, keyLookupFunc); err == nil { - fmt.Printf("Token for user %v expires %v", token.Claims["user"], token.Claims["exp"]) - } -``` - -There are several concrete `Extractor` types provided for your convenience: - -* `HeaderExtractor` will search a list of headers until one contains content. -* `ArgumentExtractor` will search a list of keys in request query and form arguments until one contains content. -* `MultiExtractor` will try a list of `Extractors` in order until one returns content. -* `AuthorizationHeaderExtractor` will look in the `Authorization` header for a `Bearer` token. -* `OAuth2Extractor` searches the places an OAuth2 token would be specified (per the spec): `Authorization` header and `access_token` argument -* `PostExtractionFilter` wraps an `Extractor`, allowing you to process the content before it's parsed. A simple example is stripping the `Bearer ` text from a header - - -### RSA signing methods no longer accept `[]byte` keys - -Due to a [critical vulnerability](https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/), we've decided the convenience of accepting `[]byte` instead of `rsa.PublicKey` or `rsa.PrivateKey` isn't worth the risk of misuse. - -To replace this behavior, we've added two helper methods: `ParseRSAPrivateKeyFromPEM(key []byte) (*rsa.PrivateKey, error)` and `ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error)`. These are just simple helpers for unpacking PEM encoded PKCS1 and PKCS8 keys. If your keys are encoded any other way, all you need to do is convert them to the `crypto/rsa` package's types. - -```go - func keyLookupFunc(*Token) (interface{}, error) { - // Don't forget to validate the alg is what you expect: - if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok { - return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"]) - } - - // Look up key - key, err := lookupPublicKey(token.Header["kid"]) - if err != nil { - return nil, err - } - - // Unpack key from PEM encoded PKCS8 - return jwt.ParseRSAPublicKeyFromPEM(key) - } -``` diff --git a/vendor/github.com/dgrijalva/jwt-go/README.md b/vendor/github.com/dgrijalva/jwt-go/README.md deleted file mode 100644 index 00f613672..000000000 --- a/vendor/github.com/dgrijalva/jwt-go/README.md +++ /dev/null @@ -1,85 +0,0 @@ -A [go](http://www.golang.org) (or 'golang' for search engine friendliness) implementation of [JSON Web Tokens](http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html) - -[![Build Status](https://travis-ci.org/dgrijalva/jwt-go.svg?branch=master)](https://travis-ci.org/dgrijalva/jwt-go) - -**BREAKING CHANGES:*** Version 3.0.0 is here. It includes _a lot_ of changes including a few that break the API. We've tried to break as few things as possible, so there should just be a few type signature changes. A full list of breaking changes is available in `VERSION_HISTORY.md`. See `MIGRATION_GUIDE.md` for more information on updating your code. - -**NOTICE:** A vulnerability in JWT was [recently published](https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/). As this library doesn't force users to validate the `alg` is what they expected, it's possible your usage is effected. There will be an update soon to remedy this, and it will likey require backwards-incompatible changes to the API. In the short term, please make sure your implementation verifies the `alg` is what you expect. - - -## What the heck is a JWT? - -JWT.io has [a great introduction](https://jwt.io/introduction) to JSON Web Tokens. - -In short, it's a signed JSON object that does something useful (for example, authentication). It's commonly used for `Bearer` tokens in Oauth 2. A token is made of three parts, separated by `.`'s. The first two parts are JSON objects, that have been [base64url](http://tools.ietf.org/html/rfc4648) encoded. The last part is the signature, encoded the same way. - -The first part is called the header. It contains the necessary information for verifying the last part, the signature. For example, which encryption method was used for signing and what key was used. - -The part in the middle is the interesting bit. It's called the Claims and contains the actual stuff you care about. Refer to [the RFC](http://self-issued.info/docs/draft-jones-json-web-token.html) for information about reserved keys and the proper way to add your own. - -## What's in the box? - -This library supports the parsing and verification as well as the generation and signing of JWTs. Current supported signing algorithms are HMAC SHA, RSA, RSA-PSS, and ECDSA, though hooks are present for adding your own. - -## Examples - -See [the project documentation](https://godoc.org/github.com/dgrijalva/jwt-go) for examples of usage: - -* [Simple example of parsing and validating a token](https://godoc.org/github.com/dgrijalva/jwt-go#example_Parse_hmac) -* [Simple example of building and signing a token](https://godoc.org/github.com/dgrijalva/jwt-go#example_New_hmac) -* [Directory of Examples](https://godoc.org/github.com/dgrijalva/jwt-go#pkg-examples) - -## Extensions - -This library publishes all the necessary components for adding your own signing methods. Simply implement the `SigningMethod` interface and register a factory method using `RegisterSigningMethod`. - -Here's an example of an extension that integrates with the Google App Engine signing tools: https://github.com/someone1/gcp-jwt-go - -## Compliance - -This library was last reviewed to comply with [RTF 7519](http://www.rfc-editor.org/info/rfc7519) dated May 2015 with a few notable differences: - -* In order to protect against accidental use of [Unsecured JWTs](http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html#UnsecuredJWT), tokens using `alg=none` will only be accepted if the constant `jwt.UnsafeAllowNoneSignatureType` is provided as the key. - -## Project Status & Versioning - -This library is considered production ready. Feedback and feature requests are appreciated. The API should be considered stable. There should be very few backwards-incompatible changes outside of major version updates (and only with good reason). - -This project uses [Semantic Versioning 2.0.0](http://semver.org). Accepted pull requests will land on `master`. Periodically, versions will be tagged from `master`. You can find all the releases on [the project releases page](https://github.com/dgrijalva/jwt-go/releases). - -While we try to make it obvious when we make breaking changes, there isn't a great mechanism for pushing announcements out to users. You may want to use this alternative package include: `gopkg.in/dgrijalva/jwt-go.v2`. It will do the right thing WRT semantic versioning. - -## Usage Tips - -### Signing vs Encryption - -A token is simply a JSON object that is signed by its author. this tells you exactly two things about the data: - -* The author of the token was in the possession of the signing secret -* The data has not been modified since it was signed - -It's important to know that JWT does not provide encryption, which means anyone who has access to the token can read its contents. If you need to protect (encrypt) the data, there is a companion spec, `JWE`, that provides this functionality. JWE is currently outside the scope of this library. - -### Choosing a Signing Method - -There are several signing methods available, and you should probably take the time to learn about the various options before choosing one. The principal design decision is most likely going to be symmetric vs asymmetric. - -Symmetric signing methods, such as HSA, use only a single secret. This is probably the simplest signing method to use since any `[]byte` can be used as a valid secret. They are also slightly computationally faster to use, though this rarely is enough to matter. Symmetric signing methods work the best when both producers and consumers of tokens are trusted, or even the same system. Since the same secret is used to both sign and validate tokens, you can't easily distribute the key for validation. - -Asymmetric signing methods, such as RSA, use different keys for signing and verifying tokens. This makes it possible to produce tokens with a private key, and allow any consumer to access the public key for verification. - -### JWT and OAuth - -It's worth mentioning that OAuth and JWT are not the same thing. A JWT token is simply a signed JSON object. It can be used anywhere such a thing is useful. There is some confusion, though, as JWT is the most common type of bearer token used in OAuth2 authentication. - -Without going too far down the rabbit hole, here's a description of the interaction of these technologies: - -* OAuth is a protocol for allowing an identity provider to be separate from the service a user is logging in to. For example, whenever you use Facebook to log into a different service (Yelp, Spotify, etc), you are using OAuth. -* OAuth defines several options for passing around authentication data. One popular method is called a "bearer token". A bearer token is simply a string that _should_ only be held by an authenticated user. Thus, simply presenting this token proves your identity. You can probably derive from here why a JWT might make a good bearer token. -* Because bearer tokens are used for authentication, it's important they're kept secret. This is why transactions that use bearer tokens typically happen over SSL. - -## More - -Documentation can be found [on godoc.org](http://godoc.org/github.com/dgrijalva/jwt-go). - -The command line utility included in this project (cmd/jwt) provides a straightforward example of token creation and parsing as well as a useful tool for debugging your own integration. You'll also find several implementation examples in to documentation. diff --git a/vendor/github.com/dgrijalva/jwt-go/VERSION_HISTORY.md b/vendor/github.com/dgrijalva/jwt-go/VERSION_HISTORY.md deleted file mode 100644 index b605b4509..000000000 --- a/vendor/github.com/dgrijalva/jwt-go/VERSION_HISTORY.md +++ /dev/null @@ -1,105 +0,0 @@ -## `jwt-go` Version History - -#### 3.0.0 - -* **Compatibility Breaking Changes**: See MIGRATION_GUIDE.md for tips on updating your code - * Dropped support for `[]byte` keys when using RSA signing methods. This convenience feature could contribute to security vulnerabilities involving mismatched key types with signing methods. - * `ParseFromRequest` has been moved to `request` subpackage and usage has changed - * The `Claims` property on `Token` is now type `Claims` instead of `map[string]interface{}`. The default value is type `MapClaims`, which is an alias to `map[string]interface{}`. This makes it possible to use a custom type when decoding claims. -* Other Additions and Changes - * Added `Claims` interface type to allow users to decode the claims into a custom type - * Added `ParseWithClaims`, which takes a third argument of type `Claims`. Use this function instead of `Parse` if you have a custom type you'd like to decode into. - * Dramatically improved the functionality and flexibility of `ParseFromRequest`, which is now in the `request` subpackage - * Added `ParseFromRequestWithClaims` which is the `FromRequest` equivalent of `ParseWithClaims` - * Added new interface type `Extractor`, which is used for extracting JWT strings from http requests. Used with `ParseFromRequest` and `ParseFromRequestWithClaims`. - * Added several new, more specific, validation errors to error type bitmask - * Moved examples from README to executable example files - * Signing method registry is now thread safe - * Added new property to `ValidationError`, which contains the raw error returned by calls made by parse/verify (such as those returned by keyfunc or json parser) - -#### 2.7.0 - -This will likely be the last backwards compatible release before 3.0.0, excluding essential bug fixes. - -* Added new option `-show` to the `jwt` command that will just output the decoded token without verifying -* Error text for expired tokens includes how long it's been expired -* Fixed incorrect error returned from `ParseRSAPublicKeyFromPEM` -* Documentation updates - -#### 2.6.0 - -* Exposed inner error within ValidationError -* Fixed validation errors when using UseJSONNumber flag -* Added several unit tests - -#### 2.5.0 - -* Added support for signing method none. You shouldn't use this. The API tries to make this clear. -* Updated/fixed some documentation -* Added more helpful error message when trying to parse tokens that begin with `BEARER ` - -#### 2.4.0 - -* Added new type, Parser, to allow for configuration of various parsing parameters - * You can now specify a list of valid signing methods. Anything outside this set will be rejected. - * You can now opt to use the `json.Number` type instead of `float64` when parsing token JSON -* Added support for [Travis CI](https://travis-ci.org/dgrijalva/jwt-go) -* Fixed some bugs with ECDSA parsing - -#### 2.3.0 - -* Added support for ECDSA signing methods -* Added support for RSA PSS signing methods (requires go v1.4) - -#### 2.2.0 - -* Gracefully handle a `nil` `Keyfunc` being passed to `Parse`. Result will now be the parsed token and an error, instead of a panic. - -#### 2.1.0 - -Backwards compatible API change that was missed in 2.0.0. - -* The `SignedString` method on `Token` now takes `interface{}` instead of `[]byte` - -#### 2.0.0 - -There were two major reasons for breaking backwards compatibility with this update. The first was a refactor required to expand the width of the RSA and HMAC-SHA signing implementations. There will likely be no required code changes to support this change. - -The second update, while unfortunately requiring a small change in integration, is required to open up this library to other signing methods. Not all keys used for all signing methods have a single standard on-disk representation. Requiring `[]byte` as the type for all keys proved too limiting. Additionally, this implementation allows for pre-parsed tokens to be reused, which might matter in an application that parses a high volume of tokens with a small set of keys. Backwards compatibilty has been maintained for passing `[]byte` to the RSA signing methods, but they will also accept `*rsa.PublicKey` and `*rsa.PrivateKey`. - -It is likely the only integration change required here will be to change `func(t *jwt.Token) ([]byte, error)` to `func(t *jwt.Token) (interface{}, error)` when calling `Parse`. - -* **Compatibility Breaking Changes** - * `SigningMethodHS256` is now `*SigningMethodHMAC` instead of `type struct` - * `SigningMethodRS256` is now `*SigningMethodRSA` instead of `type struct` - * `KeyFunc` now returns `interface{}` instead of `[]byte` - * `SigningMethod.Sign` now takes `interface{}` instead of `[]byte` for the key - * `SigningMethod.Verify` now takes `interface{}` instead of `[]byte` for the key -* Renamed type `SigningMethodHS256` to `SigningMethodHMAC`. Specific sizes are now just instances of this type. - * Added public package global `SigningMethodHS256` - * Added public package global `SigningMethodHS384` - * Added public package global `SigningMethodHS512` -* Renamed type `SigningMethodRS256` to `SigningMethodRSA`. Specific sizes are now just instances of this type. - * Added public package global `SigningMethodRS256` - * Added public package global `SigningMethodRS384` - * Added public package global `SigningMethodRS512` -* Moved sample private key for HMAC tests from an inline value to a file on disk. Value is unchanged. -* Refactored the RSA implementation to be easier to read -* Exposed helper methods `ParseRSAPrivateKeyFromPEM` and `ParseRSAPublicKeyFromPEM` - -#### 1.0.2 - -* Fixed bug in parsing public keys from certificates -* Added more tests around the parsing of keys for RS256 -* Code refactoring in RS256 implementation. No functional changes - -#### 1.0.1 - -* Fixed panic if RS256 signing method was passed an invalid key - -#### 1.0.0 - -* First versioned release -* API stabilized -* Supports creating, signing, parsing, and validating JWT tokens -* Supports RS256 and HS256 signing methods \ No newline at end of file diff --git a/vendor/github.com/dgrijalva/jwt-go/ecdsa_test.go b/vendor/github.com/dgrijalva/jwt-go/ecdsa_test.go deleted file mode 100644 index 753047b1e..000000000 --- a/vendor/github.com/dgrijalva/jwt-go/ecdsa_test.go +++ /dev/null @@ -1,100 +0,0 @@ -package jwt_test - -import ( - "crypto/ecdsa" - "io/ioutil" - "strings" - "testing" - - "github.com/dgrijalva/jwt-go" -) - -var ecdsaTestData = []struct { - name string - keys map[string]string - tokenString string - alg string - claims map[string]interface{} - valid bool -}{ - { - "Basic ES256", - map[string]string{"private": "test/ec256-private.pem", "public": "test/ec256-public.pem"}, - "eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiJ9.eyJmb28iOiJiYXIifQ.feG39E-bn8HXAKhzDZq7yEAPWYDhZlwTn3sePJnU9VrGMmwdXAIEyoOnrjreYlVM_Z4N13eK9-TmMTWyfKJtHQ", - "ES256", - map[string]interface{}{"foo": "bar"}, - true, - }, - { - "Basic ES384", - map[string]string{"private": "test/ec384-private.pem", "public": "test/ec384-public.pem"}, - "eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzM4NCJ9.eyJmb28iOiJiYXIifQ.ngAfKMbJUh0WWubSIYe5GMsA-aHNKwFbJk_wq3lq23aPp8H2anb1rRILIzVR0gUf4a8WzDtrzmiikuPWyCS6CN4-PwdgTk-5nehC7JXqlaBZU05p3toM3nWCwm_LXcld", - "ES384", - map[string]interface{}{"foo": "bar"}, - true, - }, - { - "Basic ES512", - map[string]string{"private": "test/ec512-private.pem", "public": "test/ec512-public.pem"}, - "eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzUxMiJ9.eyJmb28iOiJiYXIifQ.AAU0TvGQOcdg2OvrwY73NHKgfk26UDekh9Prz-L_iWuTBIBqOFCWwwLsRiHB1JOddfKAls5do1W0jR_F30JpVd-6AJeTjGKA4C1A1H6gIKwRY0o_tFDIydZCl_lMBMeG5VNFAjO86-WCSKwc3hqaGkq1MugPRq_qrF9AVbuEB4JPLyL5", - "ES512", - map[string]interface{}{"foo": "bar"}, - true, - }, - { - "basic ES256 invalid: foo => bar", - map[string]string{"private": "test/ec256-private.pem", "public": "test/ec256-public.pem"}, - "eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.MEQCIHoSJnmGlPaVQDqacx_2XlXEhhqtWceVopjomc2PJLtdAiAUTeGPoNYxZw0z8mgOnnIcjoxRuNDVZvybRZF3wR1l8W", - "ES256", - map[string]interface{}{"foo": "bar"}, - false, - }, -} - -func TestECDSAVerify(t *testing.T) { - for _, data := range ecdsaTestData { - var err error - - key, _ := ioutil.ReadFile(data.keys["public"]) - - var ecdsaKey *ecdsa.PublicKey - if ecdsaKey, err = jwt.ParseECPublicKeyFromPEM(key); err != nil { - t.Errorf("Unable to parse ECDSA public key: %v", err) - } - - parts := strings.Split(data.tokenString, ".") - - method := jwt.GetSigningMethod(data.alg) - err = method.Verify(strings.Join(parts[0:2], "."), parts[2], ecdsaKey) - if data.valid && err != nil { - t.Errorf("[%v] Error while verifying key: %v", data.name, err) - } - if !data.valid && err == nil { - t.Errorf("[%v] Invalid key passed validation", data.name) - } - } -} - -func TestECDSASign(t *testing.T) { - for _, data := range ecdsaTestData { - var err error - key, _ := ioutil.ReadFile(data.keys["private"]) - - var ecdsaKey *ecdsa.PrivateKey - if ecdsaKey, err = jwt.ParseECPrivateKeyFromPEM(key); err != nil { - t.Errorf("Unable to parse ECDSA private key: %v", err) - } - - if data.valid { - parts := strings.Split(data.tokenString, ".") - method := jwt.GetSigningMethod(data.alg) - sig, err := method.Sign(strings.Join(parts[0:2], "."), ecdsaKey) - if err != nil { - t.Errorf("[%v] Error signing token: %v", data.name, err) - } - if sig == parts[2] { - t.Errorf("[%v] Identical signatures\nbefore:\n%v\nafter:\n%v", data.name, parts[2], sig) - } - } - } -} diff --git a/vendor/github.com/dgrijalva/jwt-go/example_test.go b/vendor/github.com/dgrijalva/jwt-go/example_test.go deleted file mode 100644 index ae8b788a0..000000000 --- a/vendor/github.com/dgrijalva/jwt-go/example_test.go +++ /dev/null @@ -1,114 +0,0 @@ -package jwt_test - -import ( - "fmt" - "github.com/dgrijalva/jwt-go" - "time" -) - -// Example (atypical) using the StandardClaims type by itself to parse a token. -// The StandardClaims type is designed to be embedded into your custom types -// to provide standard validation features. You can use it alone, but there's -// no way to retrieve other fields after parsing. -// See the CustomClaimsType example for intended usage. -func ExampleNewWithClaims_standardClaims() { - mySigningKey := []byte("AllYourBase") - - // Create the Claims - claims := &jwt.StandardClaims{ - ExpiresAt: 15000, - Issuer: "test", - } - - token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) - ss, err := token.SignedString(mySigningKey) - fmt.Printf("%v %v", ss, err) - //Output: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1MDAwLCJpc3MiOiJ0ZXN0In0.QsODzZu3lUZMVdhbO76u3Jv02iYCvEHcYVUI1kOWEU0 -} - -// Example creating a token using a custom claims type. The StandardClaim is embedded -// in the custom type to allow for easy encoding, parsing and validation of standard claims. -func ExampleNewWithClaims_customClaimsType() { - mySigningKey := []byte("AllYourBase") - - type MyCustomClaims struct { - Foo string `json:"foo"` - jwt.StandardClaims - } - - // Create the Claims - claims := MyCustomClaims{ - "bar", - jwt.StandardClaims{ - ExpiresAt: 15000, - Issuer: "test", - }, - } - - token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) - ss, err := token.SignedString(mySigningKey) - fmt.Printf("%v %v", ss, err) - //Output: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJleHAiOjE1MDAwLCJpc3MiOiJ0ZXN0In0.HE7fK0xOQwFEr4WDgRWj4teRPZ6i3GLwD5YCm6Pwu_c -} - -// Example creating a token using a custom claims type. The StandardClaim is embedded -// in the custom type to allow for easy encoding, parsing and validation of standard claims. -func ExampleParseWithClaims_customClaimsType() { - tokenString := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJleHAiOjE1MDAwLCJpc3MiOiJ0ZXN0In0.HE7fK0xOQwFEr4WDgRWj4teRPZ6i3GLwD5YCm6Pwu_c" - - type MyCustomClaims struct { - Foo string `json:"foo"` - jwt.StandardClaims - } - - // sample token is expired. override time so it parses as valid - at(time.Unix(0, 0), func() { - token, err := jwt.ParseWithClaims(tokenString, &MyCustomClaims{}, func(token *jwt.Token) (interface{}, error) { - return []byte("AllYourBase"), nil - }) - - if claims, ok := token.Claims.(*MyCustomClaims); ok && token.Valid { - fmt.Printf("%v %v", claims.Foo, claims.StandardClaims.ExpiresAt) - } else { - fmt.Println(err) - } - }) - - // Output: bar 15000 -} - -// Override time value for tests. Restore default value after. -func at(t time.Time, f func()) { - jwt.TimeFunc = func() time.Time { - return t - } - f() - jwt.TimeFunc = time.Now -} - -// An example of parsing the error types using bitfield checks -func ExampleParse_errorChecking() { - // Token from another example. This token is expired - var tokenString = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJleHAiOjE1MDAwLCJpc3MiOiJ0ZXN0In0.HE7fK0xOQwFEr4WDgRWj4teRPZ6i3GLwD5YCm6Pwu_c" - - token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) { - return []byte("AllYourBase"), nil - }) - - if token.Valid { - fmt.Println("You look nice today") - } else if ve, ok := err.(*jwt.ValidationError); ok { - if ve.Errors&jwt.ValidationErrorMalformed != 0 { - fmt.Println("That's not even a token") - } else if ve.Errors&(jwt.ValidationErrorExpired|jwt.ValidationErrorNotValidYet) != 0 { - // Token is either expired or not active yet - fmt.Println("Timing is everything") - } else { - fmt.Println("Couldn't handle this token:", err) - } - } else { - fmt.Println("Couldn't handle this token:", err) - } - - // Output: Timing is everything -} diff --git a/vendor/github.com/dgrijalva/jwt-go/hmac_example_test.go b/vendor/github.com/dgrijalva/jwt-go/hmac_example_test.go deleted file mode 100644 index 8fb567820..000000000 --- a/vendor/github.com/dgrijalva/jwt-go/hmac_example_test.go +++ /dev/null @@ -1,64 +0,0 @@ -package jwt_test - -import ( - "fmt" - "github.com/dgrijalva/jwt-go" - "io/ioutil" - "time" -) - -// For HMAC signing method, the key can be any []byte. It is recommended to generate -// a key using crypto/rand or something equivalent. You need the same key for signing -// and validating. -var hmacSampleSecret []byte - -func init() { - // Load sample key data - if keyData, e := ioutil.ReadFile("test/hmacTestKey"); e == nil { - hmacSampleSecret = keyData - } else { - panic(e) - } -} - -// Example creating, signing, and encoding a JWT token using the HMAC signing method -func ExampleNew_hmac() { - // Create a new token object, specifying signing method and the claims - // you would like it to contain. - token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{ - "foo": "bar", - "nbf": time.Date(2015, 10, 10, 12, 0, 0, 0, time.UTC).Unix(), - }) - - // Sign and get the complete encoded token as a string using the secret - tokenString, err := token.SignedString(hmacSampleSecret) - - fmt.Println(tokenString, err) - // Output: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJuYmYiOjE0NDQ0Nzg0MDB9.u1riaD1rW97opCoAuRCTy4w58Br-Zk-bh7vLiRIsrpU -} - -// Example parsing and validating a token using the HMAC signing method -func ExampleParse_hmac() { - // sample token string taken from the New example - tokenString := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJuYmYiOjE0NDQ0Nzg0MDB9.u1riaD1rW97opCoAuRCTy4w58Br-Zk-bh7vLiRIsrpU" - - // Parse takes the token string and a function for looking up the key. The latter is especially - // useful if you use multiple keys for your application. The standard is to use 'kid' in the - // head of the token to identify which key to use, but the parsed token (head and claims) is provided - // to the callback, providing flexibility. - token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) { - // Don't forget to validate the alg is what you expect: - if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { - return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"]) - } - return hmacSampleSecret, nil - }) - - if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid { - fmt.Println(claims["foo"], claims["nbf"]) - } else { - fmt.Println(err) - } - - // Output: bar 1.4444784e+09 -} diff --git a/vendor/github.com/dgrijalva/jwt-go/hmac_test.go b/vendor/github.com/dgrijalva/jwt-go/hmac_test.go deleted file mode 100644 index c7e114f4f..000000000 --- a/vendor/github.com/dgrijalva/jwt-go/hmac_test.go +++ /dev/null @@ -1,91 +0,0 @@ -package jwt_test - -import ( - "github.com/dgrijalva/jwt-go" - "io/ioutil" - "strings" - "testing" -) - -var hmacTestData = []struct { - name string - tokenString string - alg string - claims map[string]interface{} - valid bool -}{ - { - "web sample", - "eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk", - "HS256", - map[string]interface{}{"iss": "joe", "exp": 1300819380, "http://example.com/is_root": true}, - true, - }, - { - "HS384", - "eyJhbGciOiJIUzM4NCIsInR5cCI6IkpXVCJ9.eyJleHAiOjEuMzAwODE5MzhlKzA5LCJodHRwOi8vZXhhbXBsZS5jb20vaXNfcm9vdCI6dHJ1ZSwiaXNzIjoiam9lIn0.KWZEuOD5lbBxZ34g7F-SlVLAQ_r5KApWNWlZIIMyQVz5Zs58a7XdNzj5_0EcNoOy", - "HS384", - map[string]interface{}{"iss": "joe", "exp": 1300819380, "http://example.com/is_root": true}, - true, - }, - { - "HS512", - "eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJleHAiOjEuMzAwODE5MzhlKzA5LCJodHRwOi8vZXhhbXBsZS5jb20vaXNfcm9vdCI6dHJ1ZSwiaXNzIjoiam9lIn0.CN7YijRX6Aw1n2jyI2Id1w90ja-DEMYiWixhYCyHnrZ1VfJRaFQz1bEbjjA5Fn4CLYaUG432dEYmSbS4Saokmw", - "HS512", - map[string]interface{}{"iss": "joe", "exp": 1300819380, "http://example.com/is_root": true}, - true, - }, - { - "web sample: invalid", - "eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXo", - "HS256", - map[string]interface{}{"iss": "joe", "exp": 1300819380, "http://example.com/is_root": true}, - false, - }, -} - -// Sample data from http://tools.ietf.org/html/draft-jones-json-web-signature-04#appendix-A.1 -var hmacTestKey, _ = ioutil.ReadFile("test/hmacTestKey") - -func TestHMACVerify(t *testing.T) { - for _, data := range hmacTestData { - parts := strings.Split(data.tokenString, ".") - - method := jwt.GetSigningMethod(data.alg) - err := method.Verify(strings.Join(parts[0:2], "."), parts[2], hmacTestKey) - if data.valid && err != nil { - t.Errorf("[%v] Error while verifying key: %v", data.name, err) - } - if !data.valid && err == nil { - t.Errorf("[%v] Invalid key passed validation", data.name) - } - } -} - -func TestHMACSign(t *testing.T) { - for _, data := range hmacTestData { - if data.valid { - parts := strings.Split(data.tokenString, ".") - method := jwt.GetSigningMethod(data.alg) - sig, err := method.Sign(strings.Join(parts[0:2], "."), hmacTestKey) - if err != nil { - t.Errorf("[%v] Error signing token: %v", data.name, err) - } - if sig != parts[2] { - t.Errorf("[%v] Incorrect signature.\nwas:\n%v\nexpecting:\n%v", data.name, sig, parts[2]) - } - } - } -} - -func BenchmarkHS256Signing(b *testing.B) { - benchmarkSigning(b, jwt.SigningMethodHS256, hmacTestKey) -} - -func BenchmarkHS384Signing(b *testing.B) { - benchmarkSigning(b, jwt.SigningMethodHS384, hmacTestKey) -} - -func BenchmarkHS512Signing(b *testing.B) { - benchmarkSigning(b, jwt.SigningMethodHS512, hmacTestKey) -} diff --git a/vendor/github.com/dgrijalva/jwt-go/http_example_test.go b/vendor/github.com/dgrijalva/jwt-go/http_example_test.go deleted file mode 100644 index 82e9c50a4..000000000 --- a/vendor/github.com/dgrijalva/jwt-go/http_example_test.go +++ /dev/null @@ -1,216 +0,0 @@ -package jwt_test - -// Example HTTP auth using asymmetric crypto/RSA keys -// This is based on a (now outdated) example at https://gist.github.com/cryptix/45c33ecf0ae54828e63b - -import ( - "bytes" - "crypto/rsa" - "fmt" - "github.com/dgrijalva/jwt-go" - "github.com/dgrijalva/jwt-go/request" - "io" - "io/ioutil" - "log" - "net" - "net/http" - "net/url" - "strings" - "time" -) - -// location of the files used for signing and verification -const ( - privKeyPath = "test/sample_key" // openssl genrsa -out app.rsa keysize - pubKeyPath = "test/sample_key.pub" // openssl rsa -in app.rsa -pubout > app.rsa.pub -) - -var ( - verifyKey *rsa.PublicKey - signKey *rsa.PrivateKey - serverPort int - // storing sample username/password pairs - // don't do this on a real server - users = map[string]string{ - "test": "known", - } -) - -// read the key files before starting http handlers -func init() { - signBytes, err := ioutil.ReadFile(privKeyPath) - fatal(err) - - signKey, err = jwt.ParseRSAPrivateKeyFromPEM(signBytes) - fatal(err) - - verifyBytes, err := ioutil.ReadFile(pubKeyPath) - fatal(err) - - verifyKey, err = jwt.ParseRSAPublicKeyFromPEM(verifyBytes) - fatal(err) - - http.HandleFunc("/authenticate", authHandler) - http.HandleFunc("/restricted", restrictedHandler) - - // Setup listener - listener, err := net.ListenTCP("tcp", &net.TCPAddr{}) - serverPort = listener.Addr().(*net.TCPAddr).Port - - log.Println("Listening...") - go func() { - fatal(http.Serve(listener, nil)) - }() -} - -var start func() - -func fatal(err error) { - if err != nil { - log.Fatal(err) - } -} - -// Define some custom types were going to use within our tokens -type CustomerInfo struct { - Name string - Kind string -} - -type CustomClaimsExample struct { - *jwt.StandardClaims - TokenType string - CustomerInfo -} - -func Example_getTokenViaHTTP() { - // See func authHandler for an example auth handler that produces a token - res, err := http.PostForm(fmt.Sprintf("http://localhost:%v/authenticate", serverPort), url.Values{ - "user": {"test"}, - "pass": {"known"}, - }) - if err != nil { - fatal(err) - } - - if res.StatusCode != 200 { - fmt.Println("Unexpected status code", res.StatusCode) - } - - // Read the token out of the response body - buf := new(bytes.Buffer) - io.Copy(buf, res.Body) - res.Body.Close() - tokenString := strings.TrimSpace(buf.String()) - - // Parse the token - token, err := jwt.ParseWithClaims(tokenString, &CustomClaimsExample{}, func(token *jwt.Token) (interface{}, error) { - // since we only use the one private key to sign the tokens, - // we also only use its public counter part to verify - return verifyKey, nil - }) - fatal(err) - - claims := token.Claims.(*CustomClaimsExample) - fmt.Println(claims.CustomerInfo.Name) - - //Output: test -} - -func Example_useTokenViaHTTP() { - - // Make a sample token - // In a real world situation, this token will have been acquired from - // some other API call (see Example_getTokenViaHTTP) - token, err := createToken("foo") - fatal(err) - - // Make request. See func restrictedHandler for example request processor - req, err := http.NewRequest("GET", fmt.Sprintf("http://localhost:%v/restricted", serverPort), nil) - fatal(err) - req.Header.Set("Authorization", fmt.Sprintf("Bearer %v", token)) - res, err := http.DefaultClient.Do(req) - fatal(err) - - // Read the response body - buf := new(bytes.Buffer) - io.Copy(buf, res.Body) - res.Body.Close() - fmt.Println(buf.String()) - - // Output: Welcome, foo -} - -func createToken(user string) (string, error) { - // create a signer for rsa 256 - t := jwt.New(jwt.GetSigningMethod("RS256")) - - // set our claims - t.Claims = &CustomClaimsExample{ - &jwt.StandardClaims{ - // set the expire time - // see http://tools.ietf.org/html/draft-ietf-oauth-json-web-token-20#section-4.1.4 - ExpiresAt: time.Now().Add(time.Minute * 1).Unix(), - }, - "level1", - CustomerInfo{user, "human"}, - } - - // Creat token string - return t.SignedString(signKey) -} - -// reads the form values, checks them and creates the token -func authHandler(w http.ResponseWriter, r *http.Request) { - // make sure its post - if r.Method != "POST" { - w.WriteHeader(http.StatusBadRequest) - fmt.Fprintln(w, "No POST", r.Method) - return - } - - user := r.FormValue("user") - pass := r.FormValue("pass") - - log.Printf("Authenticate: user[%s] pass[%s]\n", user, pass) - - // check values - if user != "test" || pass != "known" { - w.WriteHeader(http.StatusForbidden) - fmt.Fprintln(w, "Wrong info") - return - } - - tokenString, err := createToken(user) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - fmt.Fprintln(w, "Sorry, error while Signing Token!") - log.Printf("Token Signing error: %v\n", err) - return - } - - w.Header().Set("Content-Type", "application/jwt") - w.WriteHeader(http.StatusOK) - fmt.Fprintln(w, tokenString) -} - -// only accessible with a valid token -func restrictedHandler(w http.ResponseWriter, r *http.Request) { - // Get token from request - token, err := request.ParseFromRequestWithClaims(r, request.OAuth2Extractor, &CustomClaimsExample{}, func(token *jwt.Token) (interface{}, error) { - // since we only use the one private key to sign the tokens, - // we also only use its public counter part to verify - return verifyKey, nil - }) - - // If the token is missing or invalid, return error - if err != nil { - w.WriteHeader(http.StatusUnauthorized) - fmt.Fprintln(w, "Invalid token:", err) - return - } - - // Token is valid - fmt.Fprintln(w, "Welcome,", token.Claims.(*CustomClaimsExample).Name) - return -} diff --git a/vendor/github.com/dgrijalva/jwt-go/none_test.go b/vendor/github.com/dgrijalva/jwt-go/none_test.go deleted file mode 100644 index 29a69efef..000000000 --- a/vendor/github.com/dgrijalva/jwt-go/none_test.go +++ /dev/null @@ -1,72 +0,0 @@ -package jwt_test - -import ( - "github.com/dgrijalva/jwt-go" - "strings" - "testing" -) - -var noneTestData = []struct { - name string - tokenString string - alg string - key interface{} - claims map[string]interface{} - valid bool -}{ - { - "Basic", - "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.", - "none", - jwt.UnsafeAllowNoneSignatureType, - map[string]interface{}{"foo": "bar"}, - true, - }, - { - "Basic - no key", - "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.", - "none", - nil, - map[string]interface{}{"foo": "bar"}, - false, - }, - { - "Signed", - "eyJhbGciOiJSUzM4NCIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.W-jEzRfBigtCWsinvVVuldiuilzVdU5ty0MvpLaSaqK9PlAWWlDQ1VIQ_qSKzwL5IXaZkvZFJXT3yL3n7OUVu7zCNJzdwznbC8Z-b0z2lYvcklJYi2VOFRcGbJtXUqgjk2oGsiqUMUMOLP70TTefkpsgqDxbRh9CDUfpOJgW-dU7cmgaoswe3wjUAUi6B6G2YEaiuXC0XScQYSYVKIzgKXJV8Zw-7AN_DBUI4GkTpsvQ9fVVjZM9csQiEXhYekyrKu1nu_POpQonGd8yqkIyXPECNmmqH5jH4sFiF67XhD7_JpkvLziBpI-uh86evBUadmHhb9Otqw3uV3NTaXLzJw", - "none", - jwt.UnsafeAllowNoneSignatureType, - map[string]interface{}{"foo": "bar"}, - false, - }, -} - -func TestNoneVerify(t *testing.T) { - for _, data := range noneTestData { - parts := strings.Split(data.tokenString, ".") - - method := jwt.GetSigningMethod(data.alg) - err := method.Verify(strings.Join(parts[0:2], "."), parts[2], data.key) - if data.valid && err != nil { - t.Errorf("[%v] Error while verifying key: %v", data.name, err) - } - if !data.valid && err == nil { - t.Errorf("[%v] Invalid key passed validation", data.name) - } - } -} - -func TestNoneSign(t *testing.T) { - for _, data := range noneTestData { - if data.valid { - parts := strings.Split(data.tokenString, ".") - method := jwt.GetSigningMethod(data.alg) - sig, err := method.Sign(strings.Join(parts[0:2], "."), data.key) - if err != nil { - t.Errorf("[%v] Error signing token: %v", data.name, err) - } - if sig != parts[2] { - t.Errorf("[%v] Incorrect signature.\nwas:\n%v\nexpecting:\n%v", data.name, sig, parts[2]) - } - } - } -} diff --git a/vendor/github.com/dgrijalva/jwt-go/parser_test.go b/vendor/github.com/dgrijalva/jwt-go/parser_test.go deleted file mode 100644 index 0c86801b9..000000000 --- a/vendor/github.com/dgrijalva/jwt-go/parser_test.go +++ /dev/null @@ -1,252 +0,0 @@ -package jwt_test - -import ( - "crypto/rsa" - "encoding/json" - "fmt" - "reflect" - "testing" - "time" - - "github.com/dgrijalva/jwt-go" - "github.com/dgrijalva/jwt-go/test" -) - -var keyFuncError error = fmt.Errorf("error loading key") - -var ( - jwtTestDefaultKey *rsa.PublicKey - defaultKeyFunc jwt.Keyfunc = func(t *jwt.Token) (interface{}, error) { return jwtTestDefaultKey, nil } - emptyKeyFunc jwt.Keyfunc = func(t *jwt.Token) (interface{}, error) { return nil, nil } - errorKeyFunc jwt.Keyfunc = func(t *jwt.Token) (interface{}, error) { return nil, keyFuncError } - nilKeyFunc jwt.Keyfunc = nil -) - -func init() { - jwtTestDefaultKey = test.LoadRSAPublicKeyFromDisk("test/sample_key.pub") -} - -var jwtTestData = []struct { - name string - tokenString string - keyfunc jwt.Keyfunc - claims jwt.Claims - valid bool - errors uint32 - parser *jwt.Parser -}{ - { - "basic", - "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.FhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg", - defaultKeyFunc, - jwt.MapClaims{"foo": "bar"}, - true, - 0, - nil, - }, - { - "basic expired", - "", // autogen - defaultKeyFunc, - jwt.MapClaims{"foo": "bar", "exp": float64(time.Now().Unix() - 100)}, - false, - jwt.ValidationErrorExpired, - nil, - }, - { - "basic nbf", - "", // autogen - defaultKeyFunc, - jwt.MapClaims{"foo": "bar", "nbf": float64(time.Now().Unix() + 100)}, - false, - jwt.ValidationErrorNotValidYet, - nil, - }, - { - "expired and nbf", - "", // autogen - defaultKeyFunc, - jwt.MapClaims{"foo": "bar", "nbf": float64(time.Now().Unix() + 100), "exp": float64(time.Now().Unix() - 100)}, - false, - jwt.ValidationErrorNotValidYet | jwt.ValidationErrorExpired, - nil, - }, - { - "basic invalid", - "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.EhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg", - defaultKeyFunc, - jwt.MapClaims{"foo": "bar"}, - false, - jwt.ValidationErrorSignatureInvalid, - nil, - }, - { - "basic nokeyfunc", - "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.FhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg", - nilKeyFunc, - jwt.MapClaims{"foo": "bar"}, - false, - jwt.ValidationErrorUnverifiable, - nil, - }, - { - "basic nokey", - "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.FhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg", - emptyKeyFunc, - jwt.MapClaims{"foo": "bar"}, - false, - jwt.ValidationErrorSignatureInvalid, - nil, - }, - { - "basic errorkey", - "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.FhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg", - errorKeyFunc, - jwt.MapClaims{"foo": "bar"}, - false, - jwt.ValidationErrorUnverifiable, - nil, - }, - { - "invalid signing method", - "", - defaultKeyFunc, - jwt.MapClaims{"foo": "bar"}, - false, - jwt.ValidationErrorSignatureInvalid, - &jwt.Parser{ValidMethods: []string{"HS256"}}, - }, - { - "valid signing method", - "", - defaultKeyFunc, - jwt.MapClaims{"foo": "bar"}, - true, - 0, - &jwt.Parser{ValidMethods: []string{"RS256", "HS256"}}, - }, - { - "JSON Number", - "", - defaultKeyFunc, - jwt.MapClaims{"foo": json.Number("123.4")}, - true, - 0, - &jwt.Parser{UseJSONNumber: true}, - }, - { - "Standard Claims", - "", - defaultKeyFunc, - &jwt.StandardClaims{ - ExpiresAt: time.Now().Add(time.Second * 10).Unix(), - }, - true, - 0, - &jwt.Parser{UseJSONNumber: true}, - }, - { - "JSON Number - basic expired", - "", // autogen - defaultKeyFunc, - jwt.MapClaims{"foo": "bar", "exp": json.Number(fmt.Sprintf("%v", time.Now().Unix()-100))}, - false, - jwt.ValidationErrorExpired, - &jwt.Parser{UseJSONNumber: true}, - }, - { - "JSON Number - basic nbf", - "", // autogen - defaultKeyFunc, - jwt.MapClaims{"foo": "bar", "nbf": json.Number(fmt.Sprintf("%v", time.Now().Unix()+100))}, - false, - jwt.ValidationErrorNotValidYet, - &jwt.Parser{UseJSONNumber: true}, - }, - { - "JSON Number - expired and nbf", - "", // autogen - defaultKeyFunc, - jwt.MapClaims{"foo": "bar", "nbf": json.Number(fmt.Sprintf("%v", time.Now().Unix()+100)), "exp": json.Number(fmt.Sprintf("%v", time.Now().Unix()-100))}, - false, - jwt.ValidationErrorNotValidYet | jwt.ValidationErrorExpired, - &jwt.Parser{UseJSONNumber: true}, - }, -} - -func TestParser_Parse(t *testing.T) { - privateKey := test.LoadRSAPrivateKeyFromDisk("test/sample_key") - - // Iterate over test data set and run tests - for _, data := range jwtTestData { - // If the token string is blank, use helper function to generate string - if data.tokenString == "" { - data.tokenString = test.MakeSampleToken(data.claims, privateKey) - } - - // Parse the token - var token *jwt.Token - var err error - var parser = data.parser - if parser == nil { - parser = new(jwt.Parser) - } - // Figure out correct claims type - switch data.claims.(type) { - case jwt.MapClaims: - token, err = parser.ParseWithClaims(data.tokenString, jwt.MapClaims{}, data.keyfunc) - case *jwt.StandardClaims: - token, err = parser.ParseWithClaims(data.tokenString, &jwt.StandardClaims{}, data.keyfunc) - } - - // Verify result matches expectation - if !reflect.DeepEqual(data.claims, token.Claims) { - t.Errorf("[%v] Claims mismatch. Expecting: %v Got: %v", data.name, data.claims, token.Claims) - } - - if data.valid && err != nil { - t.Errorf("[%v] Error while verifying token: %T:%v", data.name, err, err) - } - - if !data.valid && err == nil { - t.Errorf("[%v] Invalid token passed validation", data.name) - } - - if (err == nil && !token.Valid) || (err != nil && token.Valid) { - t.Errorf("[%v] Inconsistent behavior between returned error and token.Valid") - } - - if data.errors != 0 { - if err == nil { - t.Errorf("[%v] Expecting error. Didn't get one.", data.name) - } else { - - ve := err.(*jwt.ValidationError) - // compare the bitfield part of the error - if e := ve.Errors; e != data.errors { - t.Errorf("[%v] Errors don't match expectation. %v != %v", data.name, e, data.errors) - } - - if err.Error() == keyFuncError.Error() && ve.Inner != keyFuncError { - t.Errorf("[%v] Inner error does not match expectation. %v != %v", data.name, ve.Inner, keyFuncError) - } - } - } - if data.valid && token.Signature == "" { - t.Errorf("[%v] Signature is left unpopulated after parsing", data.name) - } - } -} - -// Helper method for benchmarking various methods -func benchmarkSigning(b *testing.B, method jwt.SigningMethod, key interface{}) { - t := jwt.New(method) - b.RunParallel(func(pb *testing.PB) { - for pb.Next() { - if _, err := t.SignedString(key); err != nil { - b.Fatal(err) - } - } - }) - -} diff --git a/vendor/github.com/dgrijalva/jwt-go/rsa_pss_test.go b/vendor/github.com/dgrijalva/jwt-go/rsa_pss_test.go deleted file mode 100644 index 9045aaf34..000000000 --- a/vendor/github.com/dgrijalva/jwt-go/rsa_pss_test.go +++ /dev/null @@ -1,96 +0,0 @@ -// +build go1.4 - -package jwt_test - -import ( - "crypto/rsa" - "io/ioutil" - "strings" - "testing" - - "github.com/dgrijalva/jwt-go" -) - -var rsaPSSTestData = []struct { - name string - tokenString string - alg string - claims map[string]interface{} - valid bool -}{ - { - "Basic PS256", - "eyJhbGciOiJQUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.PPG4xyDVY8ffp4CcxofNmsTDXsrVG2npdQuibLhJbv4ClyPTUtR5giNSvuxo03kB6I8VXVr0Y9X7UxhJVEoJOmULAwRWaUsDnIewQa101cVhMa6iR8X37kfFoiZ6NkS-c7henVkkQWu2HtotkEtQvN5hFlk8IevXXPmvZlhQhwzB1sGzGYnoi1zOfuL98d3BIjUjtlwii5w6gYG2AEEzp7HnHCsb3jIwUPdq86Oe6hIFjtBwduIK90ca4UqzARpcfwxHwVLMpatKask00AgGVI0ysdk0BLMjmLutquD03XbThHScC2C2_Pp4cHWgMzvbgLU2RYYZcZRKr46QeNgz9w", - "PS256", - map[string]interface{}{"foo": "bar"}, - true, - }, - { - "Basic PS384", - "eyJhbGciOiJQUzM4NCIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.w7-qqgj97gK4fJsq_DCqdYQiylJjzWONvD0qWWWhqEOFk2P1eDULPnqHRnjgTXoO4HAw4YIWCsZPet7nR3Xxq4ZhMqvKW8b7KlfRTb9cH8zqFvzMmybQ4jv2hKc3bXYqVow3AoR7hN_CWXI3Dv6Kd2X5xhtxRHI6IL39oTVDUQ74LACe-9t4c3QRPuj6Pq1H4FAT2E2kW_0KOc6EQhCLWEhm2Z2__OZskDC8AiPpP8Kv4k2vB7l0IKQu8Pr4RcNBlqJdq8dA5D3hk5TLxP8V5nG1Ib80MOMMqoS3FQvSLyolFX-R_jZ3-zfq6Ebsqr0yEb0AH2CfsECF7935Pa0FKQ", - "PS384", - map[string]interface{}{"foo": "bar"}, - true, - }, - { - "Basic PS512", - "eyJhbGciOiJQUzUxMiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.GX1HWGzFaJevuSLavqqFYaW8_TpvcjQ8KfC5fXiSDzSiT9UD9nB_ikSmDNyDILNdtjZLSvVKfXxZJqCfefxAtiozEDDdJthZ-F0uO4SPFHlGiXszvKeodh7BuTWRI2wL9-ZO4mFa8nq3GMeQAfo9cx11i7nfN8n2YNQ9SHGovG7_T_AvaMZB_jT6jkDHpwGR9mz7x1sycckEo6teLdHRnH_ZdlHlxqknmyTu8Odr5Xh0sJFOL8BepWbbvIIn-P161rRHHiDWFv6nhlHwZnVzjx7HQrWSGb6-s2cdLie9QL_8XaMcUpjLkfOMKkDOfHo6AvpL7Jbwi83Z2ZTHjJWB-A", - "PS512", - map[string]interface{}{"foo": "bar"}, - true, - }, - { - "basic PS256 invalid: foo => bar", - "eyJhbGciOiJQUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.PPG4xyDVY8ffp4CcxofNmsTDXsrVG2npdQuibLhJbv4ClyPTUtR5giNSvuxo03kB6I8VXVr0Y9X7UxhJVEoJOmULAwRWaUsDnIewQa101cVhMa6iR8X37kfFoiZ6NkS-c7henVkkQWu2HtotkEtQvN5hFlk8IevXXPmvZlhQhwzB1sGzGYnoi1zOfuL98d3BIjUjtlwii5w6gYG2AEEzp7HnHCsb3jIwUPdq86Oe6hIFjtBwduIK90ca4UqzARpcfwxHwVLMpatKask00AgGVI0ysdk0BLMjmLutquD03XbThHScC2C2_Pp4cHWgMzvbgLU2RYYZcZRKr46QeNgz9W", - "PS256", - map[string]interface{}{"foo": "bar"}, - false, - }, -} - -func TestRSAPSSVerify(t *testing.T) { - var err error - - key, _ := ioutil.ReadFile("test/sample_key.pub") - var rsaPSSKey *rsa.PublicKey - if rsaPSSKey, err = jwt.ParseRSAPublicKeyFromPEM(key); err != nil { - t.Errorf("Unable to parse RSA public key: %v", err) - } - - for _, data := range rsaPSSTestData { - parts := strings.Split(data.tokenString, ".") - - method := jwt.GetSigningMethod(data.alg) - err := method.Verify(strings.Join(parts[0:2], "."), parts[2], rsaPSSKey) - if data.valid && err != nil { - t.Errorf("[%v] Error while verifying key: %v", data.name, err) - } - if !data.valid && err == nil { - t.Errorf("[%v] Invalid key passed validation", data.name) - } - } -} - -func TestRSAPSSSign(t *testing.T) { - var err error - - key, _ := ioutil.ReadFile("test/sample_key") - var rsaPSSKey *rsa.PrivateKey - if rsaPSSKey, err = jwt.ParseRSAPrivateKeyFromPEM(key); err != nil { - t.Errorf("Unable to parse RSA private key: %v", err) - } - - for _, data := range rsaPSSTestData { - if data.valid { - parts := strings.Split(data.tokenString, ".") - method := jwt.GetSigningMethod(data.alg) - sig, err := method.Sign(strings.Join(parts[0:2], "."), rsaPSSKey) - if err != nil { - t.Errorf("[%v] Error signing token: %v", data.name, err) - } - if sig == parts[2] { - t.Errorf("[%v] Signatures shouldn't match\nnew:\n%v\noriginal:\n%v", data.name, sig, parts[2]) - } - } - } -} diff --git a/vendor/github.com/dgrijalva/jwt-go/rsa_test.go b/vendor/github.com/dgrijalva/jwt-go/rsa_test.go deleted file mode 100644 index 2e0f78536..000000000 --- a/vendor/github.com/dgrijalva/jwt-go/rsa_test.go +++ /dev/null @@ -1,176 +0,0 @@ -package jwt_test - -import ( - "github.com/dgrijalva/jwt-go" - "io/ioutil" - "strings" - "testing" -) - -var rsaTestData = []struct { - name string - tokenString string - alg string - claims map[string]interface{} - valid bool -}{ - { - "Basic RS256", - "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.FhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg", - "RS256", - map[string]interface{}{"foo": "bar"}, - true, - }, - { - "Basic RS384", - "eyJhbGciOiJSUzM4NCIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.W-jEzRfBigtCWsinvVVuldiuilzVdU5ty0MvpLaSaqK9PlAWWlDQ1VIQ_qSKzwL5IXaZkvZFJXT3yL3n7OUVu7zCNJzdwznbC8Z-b0z2lYvcklJYi2VOFRcGbJtXUqgjk2oGsiqUMUMOLP70TTefkpsgqDxbRh9CDUfpOJgW-dU7cmgaoswe3wjUAUi6B6G2YEaiuXC0XScQYSYVKIzgKXJV8Zw-7AN_DBUI4GkTpsvQ9fVVjZM9csQiEXhYekyrKu1nu_POpQonGd8yqkIyXPECNmmqH5jH4sFiF67XhD7_JpkvLziBpI-uh86evBUadmHhb9Otqw3uV3NTaXLzJw", - "RS384", - map[string]interface{}{"foo": "bar"}, - true, - }, - { - "Basic RS512", - "eyJhbGciOiJSUzUxMiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.zBlLlmRrUxx4SJPUbV37Q1joRcI9EW13grnKduK3wtYKmDXbgDpF1cZ6B-2Jsm5RB8REmMiLpGms-EjXhgnyh2TSHE-9W2gA_jvshegLWtwRVDX40ODSkTb7OVuaWgiy9y7llvcknFBTIg-FnVPVpXMmeV_pvwQyhaz1SSwSPrDyxEmksz1hq7YONXhXPpGaNbMMeDTNP_1oj8DZaqTIL9TwV8_1wb2Odt_Fy58Ke2RVFijsOLdnyEAjt2n9Mxihu9i3PhNBkkxa2GbnXBfq3kzvZ_xxGGopLdHhJjcGWXO-NiwI9_tiu14NRv4L2xC0ItD9Yz68v2ZIZEp_DuzwRQ", - "RS512", - map[string]interface{}{"foo": "bar"}, - true, - }, - { - "basic invalid: foo => bar", - "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.EhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg", - "RS256", - map[string]interface{}{"foo": "bar"}, - false, - }, -} - -func TestRSAVerify(t *testing.T) { - keyData, _ := ioutil.ReadFile("test/sample_key.pub") - key, _ := jwt.ParseRSAPublicKeyFromPEM(keyData) - - for _, data := range rsaTestData { - parts := strings.Split(data.tokenString, ".") - - method := jwt.GetSigningMethod(data.alg) - err := method.Verify(strings.Join(parts[0:2], "."), parts[2], key) - if data.valid && err != nil { - t.Errorf("[%v] Error while verifying key: %v", data.name, err) - } - if !data.valid && err == nil { - t.Errorf("[%v] Invalid key passed validation", data.name) - } - } -} - -func TestRSASign(t *testing.T) { - keyData, _ := ioutil.ReadFile("test/sample_key") - key, _ := jwt.ParseRSAPrivateKeyFromPEM(keyData) - - for _, data := range rsaTestData { - if data.valid { - parts := strings.Split(data.tokenString, ".") - method := jwt.GetSigningMethod(data.alg) - sig, err := method.Sign(strings.Join(parts[0:2], "."), key) - if err != nil { - t.Errorf("[%v] Error signing token: %v", data.name, err) - } - if sig != parts[2] { - t.Errorf("[%v] Incorrect signature.\nwas:\n%v\nexpecting:\n%v", data.name, sig, parts[2]) - } - } - } -} - -func TestRSAVerifyWithPreParsedPrivateKey(t *testing.T) { - key, _ := ioutil.ReadFile("test/sample_key.pub") - parsedKey, err := jwt.ParseRSAPublicKeyFromPEM(key) - if err != nil { - t.Fatal(err) - } - testData := rsaTestData[0] - parts := strings.Split(testData.tokenString, ".") - err = jwt.SigningMethodRS256.Verify(strings.Join(parts[0:2], "."), parts[2], parsedKey) - if err != nil { - t.Errorf("[%v] Error while verifying key: %v", testData.name, err) - } -} - -func TestRSAWithPreParsedPrivateKey(t *testing.T) { - key, _ := ioutil.ReadFile("test/sample_key") - parsedKey, err := jwt.ParseRSAPrivateKeyFromPEM(key) - if err != nil { - t.Fatal(err) - } - testData := rsaTestData[0] - parts := strings.Split(testData.tokenString, ".") - sig, err := jwt.SigningMethodRS256.Sign(strings.Join(parts[0:2], "."), parsedKey) - if err != nil { - t.Errorf("[%v] Error signing token: %v", testData.name, err) - } - if sig != parts[2] { - t.Errorf("[%v] Incorrect signature.\nwas:\n%v\nexpecting:\n%v", testData.name, sig, parts[2]) - } -} - -func TestRSAKeyParsing(t *testing.T) { - key, _ := ioutil.ReadFile("test/sample_key") - pubKey, _ := ioutil.ReadFile("test/sample_key.pub") - badKey := []byte("All your base are belong to key") - - // Test parsePrivateKey - if _, e := jwt.ParseRSAPrivateKeyFromPEM(key); e != nil { - t.Errorf("Failed to parse valid private key: %v", e) - } - - if k, e := jwt.ParseRSAPrivateKeyFromPEM(pubKey); e == nil { - t.Errorf("Parsed public key as valid private key: %v", k) - } - - if k, e := jwt.ParseRSAPrivateKeyFromPEM(badKey); e == nil { - t.Errorf("Parsed invalid key as valid private key: %v", k) - } - - // Test parsePublicKey - if _, e := jwt.ParseRSAPublicKeyFromPEM(pubKey); e != nil { - t.Errorf("Failed to parse valid public key: %v", e) - } - - if k, e := jwt.ParseRSAPublicKeyFromPEM(key); e == nil { - t.Errorf("Parsed private key as valid public key: %v", k) - } - - if k, e := jwt.ParseRSAPublicKeyFromPEM(badKey); e == nil { - t.Errorf("Parsed invalid key as valid private key: %v", k) - } - -} - -func BenchmarkRS256Signing(b *testing.B) { - key, _ := ioutil.ReadFile("test/sample_key") - parsedKey, err := jwt.ParseRSAPrivateKeyFromPEM(key) - if err != nil { - b.Fatal(err) - } - - benchmarkSigning(b, jwt.SigningMethodRS256, parsedKey) -} - -func BenchmarkRS384Signing(b *testing.B) { - key, _ := ioutil.ReadFile("test/sample_key") - parsedKey, err := jwt.ParseRSAPrivateKeyFromPEM(key) - if err != nil { - b.Fatal(err) - } - - benchmarkSigning(b, jwt.SigningMethodRS384, parsedKey) -} - -func BenchmarkRS512Signing(b *testing.B) { - key, _ := ioutil.ReadFile("test/sample_key") - parsedKey, err := jwt.ParseRSAPrivateKeyFromPEM(key) - if err != nil { - b.Fatal(err) - } - - benchmarkSigning(b, jwt.SigningMethodRS512, parsedKey) -} diff --git a/vendor/github.com/docker/distribution/.gitignore b/vendor/github.com/docker/distribution/.gitignore deleted file mode 100644 index 1c3ae0a77..000000000 --- a/vendor/github.com/docker/distribution/.gitignore +++ /dev/null @@ -1,37 +0,0 @@ -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe -*.test -*.prof - -# never checkin from the bin file (for now) -bin/* - -# Test key files -*.pem - -# Cover profiles -*.out - -# Editor/IDE specific files. -*.sublime-project -*.sublime-workspace diff --git a/vendor/github.com/docker/distribution/.mailmap b/vendor/github.com/docker/distribution/.mailmap deleted file mode 100644 index 2d68669f3..000000000 --- a/vendor/github.com/docker/distribution/.mailmap +++ /dev/null @@ -1,19 +0,0 @@ -Stephen J Day Stephen Day -Stephen J Day Stephen Day -Olivier Gambier Olivier Gambier -Brian Bland Brian Bland -Brian Bland Brian Bland -Josh Hawn Josh Hawn -Richard Scothern Richard -Richard Scothern Richard Scothern -Andrew Meredith Andrew Meredith -harche harche -Jessie Frazelle -Sharif Nassar Sharif Nassar -Sven Dowideit Sven Dowideit -Vincent Giersch Vincent Giersch -davidli davidli -Omer Cohen Omer Cohen -Eric Yang Eric Yang -Nikita Tarasov Nikita -Misty Stanley-Jones Misty Stanley-Jones diff --git a/vendor/github.com/docker/distribution/BUILDING.md b/vendor/github.com/docker/distribution/BUILDING.md deleted file mode 100644 index 2d5a10119..000000000 --- a/vendor/github.com/docker/distribution/BUILDING.md +++ /dev/null @@ -1,119 +0,0 @@ - -# Building the registry source - -## Use-case - -This is useful if you intend to actively work on the registry. - -### Alternatives - -Most people should use the [official Registry docker image](https://hub.docker.com/r/library/registry/). - -People looking for advanced operational use cases might consider rolling their own image with a custom Dockerfile inheriting `FROM registry:2`. - -OS X users who want to run natively can do so following [the instructions here](https://github.com/docker/docker.github.io/blob/master/registry/recipes/osx-setup-guide.md). - -### Gotchas - -You are expected to know your way around with go & git. - -If you are a casual user with no development experience, and no preliminary knowledge of go, building from source is probably not a good solution for you. - -## Build the development environment - -The first prerequisite of properly building distribution targets is to have a Go -development environment setup. Please follow [How to Write Go Code](https://golang.org/doc/code.html) -for proper setup. If done correctly, you should have a GOROOT and GOPATH set in the -environment. - -If a Go development environment is setup, one can use `go get` to install the -`registry` command from the current latest: - - go get github.com/docker/distribution/cmd/registry - -The above will install the source repository into the `GOPATH`. - -Now create the directory for the registry data (this might require you to set permissions properly) - - mkdir -p /var/lib/registry - -... or alternatively `export REGISTRY_STORAGE_FILESYSTEM_ROOTDIRECTORY=/somewhere` if you want to store data into another location. - -The `registry` -binary can then be run with the following: - - $ $GOPATH/bin/registry --version - $GOPATH/bin/registry github.com/docker/distribution v2.0.0-alpha.1+unknown - -> __NOTE:__ While you do not need to use `go get` to checkout the distribution -> project, for these build instructions to work, the project must be checked -> out in the correct location in the `GOPATH`. This should almost always be -> `$GOPATH/src/github.com/docker/distribution`. - -The registry can be run with the default config using the following -incantation: - - $ $GOPATH/bin/registry serve $GOPATH/src/github.com/docker/distribution/cmd/registry/config-example.yml - INFO[0000] endpoint local-5003 disabled, skipping app.id=34bbec38-a91a-494a-9a3f-b72f9010081f version=v2.0.0-alpha.1+unknown - INFO[0000] endpoint local-8083 disabled, skipping app.id=34bbec38-a91a-494a-9a3f-b72f9010081f version=v2.0.0-alpha.1+unknown - INFO[0000] listening on :5000 app.id=34bbec38-a91a-494a-9a3f-b72f9010081f version=v2.0.0-alpha.1+unknown - INFO[0000] debug server listening localhost:5001 - -If it is working, one should see the above log messages. - -### Repeatable Builds - -For the full development experience, one should `cd` into -`$GOPATH/src/github.com/docker/distribution`. From there, the regular `go` -commands, such as `go test`, should work per package (please see -[Developing](#developing) if they don't work). - -A `Makefile` has been provided as a convenience to support repeatable builds. -Please install the following into `GOPATH` for it to work: - - go get github.com/tools/godep github.com/golang/lint/golint - -**TODO(stevvooe):** Add a `make setup` command to Makefile to run this. Have to think about how to interact with Godeps properly. - -Once these commands are available in the `GOPATH`, run `make` to get a full -build: - - $ make - + clean - + fmt - + vet - + lint - + build - github.com/docker/docker/vendor/src/code.google.com/p/go/src/pkg/archive/tar - github.com/Sirupsen/logrus - github.com/docker/libtrust - ... - github.com/yvasiyarov/gorelic - github.com/docker/distribution/registry/handlers - github.com/docker/distribution/cmd/registry - + test - ... - ok github.com/docker/distribution/digest 7.875s - ok github.com/docker/distribution/manifest 0.028s - ok github.com/docker/distribution/notifications 17.322s - ? github.com/docker/distribution/registry [no test files] - ok github.com/docker/distribution/registry/api/v2 0.101s - ? github.com/docker/distribution/registry/auth [no test files] - ok github.com/docker/distribution/registry/auth/silly 0.011s - ... - + /Users/sday/go/src/github.com/docker/distribution/bin/registry - + /Users/sday/go/src/github.com/docker/distribution/bin/registry-api-descriptor-template - + binaries - -The above provides a repeatable build using the contents of the vendored -Godeps directory. This includes formatting, vetting, linting, building, -testing and generating tagged binaries. We can verify this worked by running -the registry binary generated in the "./bin" directory: - - $ ./bin/registry -version - ./bin/registry github.com/docker/distribution v2.0.0-alpha.2-80-g16d8b2c.m - -### Optional build tags - -Optional [build tags](http://golang.org/pkg/go/build/) can be provided using -the environment variable `DOCKER_BUILDTAGS`. diff --git a/vendor/github.com/docker/distribution/CHANGELOG.md b/vendor/github.com/docker/distribution/CHANGELOG.md deleted file mode 100644 index b1a5c6824..000000000 --- a/vendor/github.com/docker/distribution/CHANGELOG.md +++ /dev/null @@ -1,114 +0,0 @@ -# Changelog - -## 2.6.1 (2017-04-05) - -#### Registry -- Fix `Forwarded` header handling, revert use of `X-Forwarded-Port` -- Use driver `Stat` for registry health check - -## 2.6.0 (2017-01-18) - -#### Storage -- S3: fixed bug in delete due to read-after-write inconsistency -- S3: allow EC2 IAM roles to be used when authorizing region endpoints -- S3: add Object ACL Support -- S3: fix delete method's notion of subpaths -- S3: use multipart upload API in `Move` method for performance -- S3: add v2 signature signing for legacy S3 clones -- Swift: add simple heuristic to detect incomplete DLOs during read ops -- Swift: support different user and tenant domains -- Swift: bulk deletes in chunks -- Aliyun OSS: fix delete method's notion of subpaths -- Aliyun OSS: optimize data copy after upload finishes -- Azure: close leaking response body -- Fix storage drivers dropping non-EOF errors when listing repositories -- Compare path properly when listing repositories in catalog -- Add a foreign layer URL host whitelist -- Improve catalog enumerate runtime - -#### Registry -- Export `storage.CreateOptions` in top-level package -- Enable notifications to endpoints that use self-signed certificates -- Properly validate multi-URL foreign layers -- Add control over validation of URLs in pushed manifests -- Proxy mode: fix socket leak when pull is cancelled -- Tag service: properly handle error responses on HEAD request -- Support for custom authentication URL in proxying registry -- Add configuration option to disable access logging -- Add notification filtering by target media type -- Manifest: `References()` returns all children -- Honor `X-Forwarded-Port` and Forwarded headers -- Reference: Preserve tag and digest in With* functions -- Add policy configuration for enforcing repository classes - -#### Client -- Changes the client Tags `All()` method to follow links -- Allow registry clients to connect via HTTP2 -- Better handling of OAuth errors in client - -#### Spec -- Manifest: clarify relationship between urls and foreign layers -- Authorization: add support for repository classes - -#### Manifest -- Override media type returned from `Stat()` for existing manifests -- Add plugin mediatype to distribution manifest - -#### Docs -- Document `TOOMANYREQUESTS` error code -- Document required Let's Encrypt port -- Improve documentation around implementation of OAuth2 -- Improve documentation for configuration - -#### Auth -- Add support for registry type in scope -- Add support for using v2 ping challenges for v1 -- Add leeway to JWT `nbf` and `exp` checking -- htpasswd: dynamically parse htpasswd file -- Fix missing auth headers with PATCH HTTP request when pushing to default port - -#### Dockerfile -- Update to go1.7 -- Reorder Dockerfile steps for better layer caching - -#### Notes - -Documentation has moved to the documentation repository at -`github.com/docker/docker.github.io/tree/master/registry` - -The registry is go 1.7 compliant, and passes newer, more restrictive `lint` and `vet` ing. - - -## 2.5.0 (2016-06-14) - -#### Storage -- Ensure uploads directory is cleaned after upload is committed -- Add ability to cap concurrent operations in filesystem driver -- S3: Add 'us-gov-west-1' to the valid region list -- Swift: Handle ceph not returning Last-Modified header for HEAD requests -- Add redirect middleware - -#### Registry -- Add support for blobAccessController middleware -- Add support for layers from foreign sources -- Remove signature store -- Add support for Let's Encrypt -- Correct yaml key names in configuration - -#### Client -- Add option to get content digest from manifest get - -#### Spec -- Update the auth spec scope grammar to reflect the fact that hostnames are optionally supported -- Clarify API documentation around catalog fetch behavior - -#### API -- Support returning HTTP 429 (Too Many Requests) - -#### Documentation -- Update auth documentation examples to show "expires in" as int - -#### Docker Image -- Use Alpine Linux as base image - - diff --git a/vendor/github.com/docker/distribution/CONTRIBUTING.md b/vendor/github.com/docker/distribution/CONTRIBUTING.md deleted file mode 100644 index 7cc7aedff..000000000 --- a/vendor/github.com/docker/distribution/CONTRIBUTING.md +++ /dev/null @@ -1,140 +0,0 @@ -# Contributing to the registry - -## Before reporting an issue... - -### If your problem is with... - - - automated builds - - your account on the [Docker Hub](https://hub.docker.com/) - - any other [Docker Hub](https://hub.docker.com/) issue - -Then please do not report your issue here - you should instead report it to [https://support.docker.com](https://support.docker.com) - -### If you... - - - need help setting up your registry - - can't figure out something - - are not sure what's going on or what your problem is - -Then please do not open an issue here yet - you should first try one of the following support forums: - - - irc: #docker-distribution on freenode - - mailing-list: or https://groups.google.com/a/dockerproject.org/forum/#!forum/distribution - -## Reporting an issue properly - -By following these simple rules you will get better and faster feedback on your issue. - - - search the bugtracker for an already reported issue - -### If you found an issue that describes your problem: - - - please read other user comments first, and confirm this is the same issue: a given error condition might be indicative of different problems - you may also find a workaround in the comments - - please refrain from adding "same thing here" or "+1" comments - - you don't need to comment on an issue to get notified of updates: just hit the "subscribe" button - - comment if you have some new, technical and relevant information to add to the case - - __DO NOT__ comment on closed issues or merged PRs. If you think you have a related problem, open up a new issue and reference the PR or issue. - -### If you have not found an existing issue that describes your problem: - - 1. create a new issue, with a succinct title that describes your issue: - - bad title: "It doesn't work with my docker" - - good title: "Private registry push fail: 400 error with E_INVALID_DIGEST" - 2. copy the output of: - - `docker version` - - `docker info` - - `docker exec registry -version` - 3. copy the command line you used to launch your Registry - 4. restart your docker daemon in debug mode (add `-D` to the daemon launch arguments) - 5. reproduce your problem and get your docker daemon logs showing the error - 6. if relevant, copy your registry logs that show the error - 7. provide any relevant detail about your specific Registry configuration (e.g., storage backend used) - 8. indicate if you are using an enterprise proxy, Nginx, or anything else between you and your Registry - -## Contributing a patch for a known bug, or a small correction - -You should follow the basic GitHub workflow: - - 1. fork - 2. commit a change - 3. make sure the tests pass - 4. PR - -Additionally, you must [sign your commits](https://github.com/docker/docker/blob/master/CONTRIBUTING.md#sign-your-work). It's very simple: - - - configure your name with git: `git config user.name "Real Name" && git config user.email mail@example.com` - - sign your commits using `-s`: `git commit -s -m "My commit"` - -Some simple rules to ensure quick merge: - - - clearly point to the issue(s) you want to fix in your PR comment (e.g., `closes #12345`) - - prefer multiple (smaller) PRs addressing individual issues over a big one trying to address multiple issues at once - - if you need to amend your PR following comments, please squash instead of adding more commits - -## Contributing new features - -You are heavily encouraged to first discuss what you want to do. You can do so on the irc channel, or by opening an issue that clearly describes the use case you want to fulfill, or the problem you are trying to solve. - -If this is a major new feature, you should then submit a proposal that describes your technical solution and reasoning. -If you did discuss it first, this will likely be greenlighted very fast. It's advisable to address all feedback on this proposal before starting actual work. - -Then you should submit your implementation, clearly linking to the issue (and possible proposal). - -Your PR will be reviewed by the community, then ultimately by the project maintainers, before being merged. - -It's mandatory to: - - - interact respectfully with other community members and maintainers - more generally, you are expected to abide by the [Docker community rules](https://github.com/docker/docker/blob/master/CONTRIBUTING.md#docker-community-guidelines) - - address maintainers' comments and modify your submission accordingly - - write tests for any new code - -Complying to these simple rules will greatly accelerate the review process, and will ensure you have a pleasant experience in contributing code to the Registry. - -Have a look at a great, successful contribution: the [Swift driver PR](https://github.com/docker/distribution/pull/493) - -## Coding Style - -Unless explicitly stated, we follow all coding guidelines from the Go -community. While some of these standards may seem arbitrary, they somehow seem -to result in a solid, consistent codebase. - -It is possible that the code base does not currently comply with these -guidelines. We are not looking for a massive PR that fixes this, since that -goes against the spirit of the guidelines. All new contributions should make a -best effort to clean up and make the code base better than they left it. -Obviously, apply your best judgement. Remember, the goal here is to make the -code base easier for humans to navigate and understand. Always keep that in -mind when nudging others to comply. - -The rules: - -1. All code should be formatted with `gofmt -s`. -2. All code should pass the default levels of - [`golint`](https://github.com/golang/lint). -3. All code should follow the guidelines covered in [Effective - Go](http://golang.org/doc/effective_go.html) and [Go Code Review - Comments](https://github.com/golang/go/wiki/CodeReviewComments). -4. Comment the code. Tell us the why, the history and the context. -5. Document _all_ declarations and methods, even private ones. Declare - expectations, caveats and anything else that may be important. If a type - gets exported, having the comments already there will ensure it's ready. -6. Variable name length should be proportional to its context and no longer. - `noCommaALongVariableNameLikeThisIsNotMoreClearWhenASimpleCommentWouldDo`. - In practice, short methods will have short variable names and globals will - have longer names. -7. No underscores in package names. If you need a compound name, step back, - and re-examine why you need a compound name. If you still think you need a - compound name, lose the underscore. -8. No utils or helpers packages. If a function is not general enough to - warrant its own package, it has not been written generally enough to be a - part of a util package. Just leave it unexported and well-documented. -9. All tests should run with `go test` and outside tooling should not be - required. No, we don't need another unit testing framework. Assertion - packages are acceptable if they provide _real_ incremental value. -10. Even though we call these "rules" above, they are actually just - guidelines. Since you've read all the rules, you now know that. - -If you are having trouble getting into the mood of idiomatic Go, we recommend -reading through [Effective Go](http://golang.org/doc/effective_go.html). The -[Go Blog](http://blog.golang.org/) is also a great resource. Drinking the -kool-aid is a lot easier than going thirsty. diff --git a/vendor/github.com/docker/distribution/Dockerfile b/vendor/github.com/docker/distribution/Dockerfile deleted file mode 100644 index 426954a11..000000000 --- a/vendor/github.com/docker/distribution/Dockerfile +++ /dev/null @@ -1,18 +0,0 @@ -FROM golang:1.7-alpine - -ENV DISTRIBUTION_DIR /go/src/github.com/docker/distribution -ENV DOCKER_BUILDTAGS include_oss include_gcs - -RUN set -ex \ - && apk add --no-cache make git - -WORKDIR $DISTRIBUTION_DIR -COPY . $DISTRIBUTION_DIR -COPY cmd/registry/config-dev.yml /etc/docker/registry/config.yml - -RUN make PREFIX=/go clean binaries - -VOLUME ["/var/lib/registry"] -EXPOSE 5000 -ENTRYPOINT ["registry"] -CMD ["serve", "/etc/docker/registry/config.yml"] diff --git a/vendor/github.com/docker/distribution/MAINTAINERS b/vendor/github.com/docker/distribution/MAINTAINERS deleted file mode 100644 index bda400150..000000000 --- a/vendor/github.com/docker/distribution/MAINTAINERS +++ /dev/null @@ -1,58 +0,0 @@ -# Distribution maintainers file -# -# This file describes who runs the docker/distribution project and how. -# This is a living document - if you see something out of date or missing, speak up! -# -# It is structured to be consumable by both humans and programs. -# To extract its contents programmatically, use any TOML-compliant parser. -# -# This file is compiled into the MAINTAINERS file in docker/opensource. -# -[Org] - [Org."Core maintainers"] - people = [ - "aaronlehmann", - "dmcgowan", - "dmp42", - "richardscothern", - "shykes", - "stevvooe", - ] - -[people] - -# A reference list of all people associated with the project. -# All other sections should refer to people by their canonical key -# in the people section. - - # ADD YOURSELF HERE IN ALPHABETICAL ORDER - - [people.aaronlehmann] - Name = "Aaron Lehmann" - Email = "aaron.lehmann@docker.com" - GitHub = "aaronlehmann" - - [people.dmcgowan] - Name = "Derek McGowan" - Email = "derek@mcgstyle.net" - GitHub = "dmcgowan" - - [people.dmp42] - Name = "Olivier Gambier" - Email = "olivier@docker.com" - GitHub = "dmp42" - - [people.richardscothern] - Name = "Richard Scothern" - Email = "richard.scothern@gmail.com" - GitHub = "richardscothern" - - [people.shykes] - Name = "Solomon Hykes" - Email = "solomon@docker.com" - GitHub = "shykes" - - [people.stevvooe] - Name = "Stephen Day" - Email = "stephen.day@docker.com" - GitHub = "stevvooe" diff --git a/vendor/github.com/docker/distribution/Makefile b/vendor/github.com/docker/distribution/Makefile deleted file mode 100644 index 47b8f1d0b..000000000 --- a/vendor/github.com/docker/distribution/Makefile +++ /dev/null @@ -1,109 +0,0 @@ -# Set an output prefix, which is the local directory if not specified -PREFIX?=$(shell pwd) - - -# Used to populate version variable in main package. -VERSION=$(shell git describe --match 'v[0-9]*' --dirty='.m' --always) - -# Allow turning off function inlining and variable registerization -ifeq (${DISABLE_OPTIMIZATION},true) - GO_GCFLAGS=-gcflags "-N -l" - VERSION:="$(VERSION)-noopt" -endif - -GO_LDFLAGS=-ldflags "-X `go list ./version`.Version=$(VERSION)" - -.PHONY: all build binaries clean dep-restore dep-save dep-validate fmt lint test test-full vet -.DEFAULT: all -all: fmt vet lint build test binaries - -AUTHORS: .mailmap .git/HEAD - git log --format='%aN <%aE>' | sort -fu > $@ - -# This only needs to be generated by hand when cutting full releases. -version/version.go: - ./version/version.sh > $@ - -# Required for go 1.5 to build -GO15VENDOREXPERIMENT := 1 - -# Go files -GOFILES=$(shell find . -type f -name '*.go') - -# Package list -PKGS=$(shell go list -tags "${DOCKER_BUILDTAGS}" ./... | grep -v ^github.com/docker/distribution/vendor/) - -# Resolving binary dependencies for specific targets -GOLINT=$(shell which golint || echo '') -GODEP=$(shell which godep || echo '') - -${PREFIX}/bin/registry: $(GOFILES) - @echo "+ $@" - @go build -tags "${DOCKER_BUILDTAGS}" -o $@ ${GO_LDFLAGS} ${GO_GCFLAGS} ./cmd/registry - -${PREFIX}/bin/digest: $(GOFILES) - @echo "+ $@" - @go build -tags "${DOCKER_BUILDTAGS}" -o $@ ${GO_LDFLAGS} ${GO_GCFLAGS} ./cmd/digest - -${PREFIX}/bin/registry-api-descriptor-template: $(GOFILES) - @echo "+ $@" - @go build -o $@ ${GO_LDFLAGS} ${GO_GCFLAGS} ./cmd/registry-api-descriptor-template - -docs/spec/api.md: docs/spec/api.md.tmpl ${PREFIX}/bin/registry-api-descriptor-template - ./bin/registry-api-descriptor-template $< > $@ - -vet: - @echo "+ $@" - @go vet -tags "${DOCKER_BUILDTAGS}" $(PKGS) - -fmt: - @echo "+ $@" - @test -z "$$(gofmt -s -l . 2>&1 | grep -v ^vendor/ | tee /dev/stderr)" || \ - (echo >&2 "+ please format Go code with 'gofmt -s'" && false) - -lint: - @echo "+ $@" - $(if $(GOLINT), , \ - $(error Please install golint: `go get -u github.com/golang/lint/golint`)) - @test -z "$$($(GOLINT) ./... 2>&1 | grep -v ^vendor/ | tee /dev/stderr)" - -build: - @echo "+ $@" - @go build -tags "${DOCKER_BUILDTAGS}" -v ${GO_LDFLAGS} $(PKGS) - -test: - @echo "+ $@" - @go test -test.short -tags "${DOCKER_BUILDTAGS}" $(PKGS) - -test-full: - @echo "+ $@" - @go test -tags "${DOCKER_BUILDTAGS}" $(PKGS) - -binaries: ${PREFIX}/bin/registry ${PREFIX}/bin/digest ${PREFIX}/bin/registry-api-descriptor-template - @echo "+ $@" - -clean: - @echo "+ $@" - @rm -rf "${PREFIX}/bin/registry" "${PREFIX}/bin/digest" "${PREFIX}/bin/registry-api-descriptor-template" - -dep-save: - @echo "+ $@" - $(if $(GODEP), , \ - $(error Please install godep: go get github.com/tools/godep)) - @$(GODEP) save $(PKGS) - -dep-restore: - @echo "+ $@" - $(if $(GODEP), , \ - $(error Please install godep: go get github.com/tools/godep)) - @$(GODEP) restore -v - -dep-validate: dep-restore - @echo "+ $@" - @rm -Rf .vendor.bak - @mv vendor .vendor.bak - @rm -Rf Godeps - @$(GODEP) save ./... - @test -z "$$(diff -r vendor .vendor.bak 2>&1 | tee /dev/stderr)" || \ - (echo >&2 "+ borked dependencies! what you have in Godeps/Godeps.json does not match with what you have in vendor" && false) - @rm -Rf .vendor.bak diff --git a/vendor/github.com/docker/distribution/README.md b/vendor/github.com/docker/distribution/README.md deleted file mode 100644 index a6e8db0fb..000000000 --- a/vendor/github.com/docker/distribution/README.md +++ /dev/null @@ -1,131 +0,0 @@ -# Distribution - -The Docker toolset to pack, ship, store, and deliver content. - -This repository's main product is the Docker Registry 2.0 implementation -for storing and distributing Docker images. It supersedes the -[docker/docker-registry](https://github.com/docker/docker-registry) -project with a new API design, focused around security and performance. - - - -[![Circle CI](https://circleci.com/gh/docker/distribution/tree/master.svg?style=svg)](https://circleci.com/gh/docker/distribution/tree/master) -[![GoDoc](https://godoc.org/github.com/docker/distribution?status.svg)](https://godoc.org/github.com/docker/distribution) - -This repository contains the following components: - -|**Component** |Description | -|--------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| **registry** | An implementation of the [Docker Registry HTTP API V2](docs/spec/api.md) for use with docker 1.6+. | -| **libraries** | A rich set of libraries for interacting with distribution components. Please see [godoc](https://godoc.org/github.com/docker/distribution) for details. **Note**: These libraries are **unstable**. | -| **specifications** | _Distribution_ related specifications are available in [docs/spec](docs/spec) | -| **documentation** | Docker's full documentation set is available at [docs.docker.com](https://docs.docker.com). This repository [contains the subset](docs/) related just to the registry. | - -### How does this integrate with Docker engine? - -This project should provide an implementation to a V2 API for use in the [Docker -core project](https://github.com/docker/docker). The API should be embeddable -and simplify the process of securely pulling and pushing content from `docker` -daemons. - -### What are the long term goals of the Distribution project? - -The _Distribution_ project has the further long term goal of providing a -secure tool chain for distributing content. The specifications, APIs and tools -should be as useful with Docker as they are without. - -Our goal is to design a professional grade and extensible content distribution -system that allow users to: - -* Enjoy an efficient, secured and reliable way to store, manage, package and - exchange content -* Hack/roll their own on top of healthy open-source components -* Implement their own home made solution through good specs, and solid - extensions mechanism. - -## More about Registry 2.0 - -The new registry implementation provides the following benefits: - -- faster push and pull -- new, more efficient implementation -- simplified deployment -- pluggable storage backend -- webhook notifications - -For information on upcoming functionality, please see [ROADMAP.md](ROADMAP.md). - -### Who needs to deploy a registry? - -By default, Docker users pull images from Docker's public registry instance. -[Installing Docker](https://docs.docker.com/engine/installation/) gives users this -ability. Users can also push images to a repository on Docker's public registry, -if they have a [Docker Hub](https://hub.docker.com/) account. - -For some users and even companies, this default behavior is sufficient. For -others, it is not. - -For example, users with their own software products may want to maintain a -registry for private, company images. Also, you may wish to deploy your own -image repository for images used to test or in continuous integration. For these -use cases and others, [deploying your own registry instance](https://github.com/docker/docker.github.io/blob/master/registry/deploying.md) -may be the better choice. - -### Migration to Registry 2.0 - -For those who have previously deployed their own registry based on the Registry -1.0 implementation and wish to deploy a Registry 2.0 while retaining images, -data migration is required. A tool to assist with migration efforts has been -created. For more information see [docker/migrator] -(https://github.com/docker/migrator). - -## Contribute - -Please see [CONTRIBUTING.md](CONTRIBUTING.md) for details on how to contribute -issues, fixes, and patches to this project. If you are contributing code, see -the instructions for [building a development environment](BUILDING.md). - -## Support - -If any issues are encountered while using the _Distribution_ project, several -avenues are available for support: - - - - - - - - - - - - - - - - - - -
- IRC - - #docker-distribution on FreeNode -
- Issue Tracker - - github.com/docker/distribution/issues -
- Google Groups - - https://groups.google.com/a/dockerproject.org/forum/#!forum/distribution -
- Mailing List - - docker@dockerproject.org -
- - -## License - -This project is distributed under [Apache License, Version 2.0](LICENSE). diff --git a/vendor/github.com/docker/distribution/RELEASE-CHECKLIST.md b/vendor/github.com/docker/distribution/RELEASE-CHECKLIST.md deleted file mode 100644 index 49235cecd..000000000 --- a/vendor/github.com/docker/distribution/RELEASE-CHECKLIST.md +++ /dev/null @@ -1,36 +0,0 @@ -## Registry Release Checklist - -10. Compile release notes detailing features and since the last release. Update the `CHANGELOG.md` file. - -20. Update the version file: `https://github.com/docker/distribution/blob/master/version/version.go` - -30. Update the `MAINTAINERS` (if necessary), `AUTHORS` and `.mailmap` files. - - ``` -make AUTHORS -``` - -40. Create a signed tag. - - Distribution uses semantic versioning. Tags are of the format `vx.y.z[-rcn]` -You will need PGP installed and a PGP key which has been added to your Github account. The comment for the tag should include the release notes. - -50. Push the signed tag - -60. Create a new [release](https://github.com/docker/distribution/releases). In the case of a release candidate, tick the `pre-release` checkbox. - -70. Update the registry binary in [distribution library image repo](https://github.com/docker/distribution-library-image) by running the update script and opening a pull request. - -80. Update the official image. Add the new version in the [official images repo](https://github.com/docker-library/official-images) by appending a new version to the `registry/registry` file with the git hash pointed to by the signed tag. Update the major version to point to the latest version and the minor version to point to new patch release if necessary. -e.g. to release `2.3.1` - - `2.3.1 (new)` - - `2.3.0 -> 2.3.0` can be removed - - `2 -> 2.3.1` - - `2.3 -> 2.3.1` - -90. Build a new distribution/registry image on [Docker hub](https://hub.docker.com/u/distribution/dashboard) by adding a new automated build with the new tag and re-building the images. - diff --git a/vendor/github.com/docker/distribution/ROADMAP.md b/vendor/github.com/docker/distribution/ROADMAP.md deleted file mode 100644 index 701127afe..000000000 --- a/vendor/github.com/docker/distribution/ROADMAP.md +++ /dev/null @@ -1,267 +0,0 @@ -# Roadmap - -The Distribution Project consists of several components, some of which are -still being defined. This document defines the high-level goals of the -project, identifies the current components, and defines the release- -relationship to the Docker Platform. - -* [Distribution Goals](#distribution-goals) -* [Distribution Components](#distribution-components) -* [Project Planning](#project-planning): release-relationship to the Docker Platform. - -This road map is a living document, providing an overview of the goals and -considerations made in respect of the future of the project. - -## Distribution Goals - -- Replace the existing [docker registry](github.com/docker/docker-registry) - implementation as the primary implementation. -- Replace the existing push and pull code in the docker engine with the - distribution package. -- Define a strong data model for distributing docker images -- Provide a flexible distribution tool kit for use in the docker platform -- Unlock new distribution models - -## Distribution Components - -Components of the Distribution Project are managed via github [milestones](https://github.com/docker/distribution/milestones). Upcoming -features and bugfixes for a component will be added to the relevant milestone. If a feature or -bugfix is not part of a milestone, it is currently unscheduled for -implementation. - -* [Registry](#registry) -* [Distribution Package](#distribution-package) - -*** - -### Registry - -The new Docker registry is the main portion of the distribution repository. -Registry 2.0 is the first release of the next-generation registry. This was -primarily focused on implementing the [new registry -API](https://github.com/docker/distribution/blob/master/docs/spec/api.md), -with a focus on security and performance. - -Following from the Distribution project goals above, we have a set of goals -for registry v2 that we would like to follow in the design. New features -should be compared against these goals. - -#### Data Storage and Distribution First - -The registry's first goal is to provide a reliable, consistent storage -location for Docker images. The registry should only provide the minimal -amount of indexing required to fetch image data and no more. - -This means we should be selective in new features and API additions, including -those that may require expensive, ever growing indexes. Requests should be -servable in "constant time". - -#### Content Addressability - -All data objects used in the registry API should be content addressable. -Content identifiers should be secure and verifiable. This provides a secure, -reliable base from which to build more advanced content distribution systems. - -#### Content Agnostic - -In the past, changes to the image format would require large changes in Docker -and the Registry. By decoupling the distribution and image format, we can -allow the formats to progress without having to coordinate between the two. -This means that we should be focused on decoupling Docker from the registry -just as much as decoupling the registry from Docker. Such an approach will -allow us to unlock new distribution models that haven't been possible before. - -We can take this further by saying that the new registry should be content -agnostic. The registry provides a model of names, tags, manifests and content -addresses and that model can be used to work with content. - -#### Simplicity - -The new registry should be closer to a microservice component than its -predecessor. This means it should have a narrower API and a low number of -service dependencies. It should be easy to deploy. - -This means that other solutions should be explored before changing the API or -adding extra dependencies. If functionality is required, can it be added as an -extension or companion service. - -#### Extensibility - -The registry should provide extension points to add functionality. By keeping -the scope narrow, but providing the ability to add functionality. - -Features like search, indexing, synchronization and registry explorers fall -into this category. No such feature should be added unless we've found it -impossible to do through an extension. - -#### Active Feature Discussions - -The following are feature discussions that are currently active. - -If you don't see your favorite, unimplemented feature, feel free to contact us -via IRC or the mailing list and we can talk about adding it. The goal here is -to make sure that new features go through a rigid design process before -landing in the registry. - -##### Proxying to other Registries - -A _pull-through caching_ mode exists for the registry, but is restricted from -within the docker client to only mirror the official Docker Hub. This functionality -can be expanded when image provenance has been specified and implemented in the -distribution project. - -##### Metadata storage - -Metadata for the registry is currently stored with the manifest and layer data on -the storage backend. While this is a big win for simplicity and reliably maintaining -state, it comes with the cost of consistency and high latency. The mutable registry -metadata operations should be abstracted behind an API which will allow ACID compliant -storage systems to handle metadata. - -##### Peer to Peer transfer - -Discussion has started here: https://docs.google.com/document/d/1rYDpSpJiQWmCQy8Cuiaa3NH-Co33oK_SC9HeXYo87QA/edit - -##### Indexing, Search and Discovery - -The original registry provided some implementation of search for use with -private registries. Support has been elided from V2 since we'd like to both -decouple search functionality from the registry. The makes the registry -simpler to deploy, especially in use cases where search is not needed, and -let's us decouple the image format from the registry. - -There are explorations into using the catalog API and notification system to -build external indexes. The current line of thought is that we will define a -common search API to index and query docker images. Such a system could be run -as a companion to a registry or set of registries to power discovery. - -The main issue with search and discovery is that there are so many ways to -accomplish it. There are two aspects to this project. The first is deciding on -how it will be done, including an API definition that can work with changing -data formats. The second is the process of integrating with `docker search`. -We expect that someone attempts to address the problem with the existing tools -and propose it as a standard search API or uses it to inform a standardization -process. Once this has been explored, we integrate with the docker client. - -Please see the following for more detail: - -- https://github.com/docker/distribution/issues/206 - -##### Deletes - -> __NOTE:__ Deletes are a much asked for feature. Before requesting this -feature or participating in discussion, we ask that you read this section in -full and understand the problems behind deletes. - -While, at first glance, implementing deleting seems simple, there are a number -mitigating factors that make many solutions not ideal or even pathological in -the context of a registry. The following paragraph discuss the background and -approaches that could be applied to arrive at a solution. - -The goal of deletes in any system is to remove unused or unneeded data. Only -data requested for deletion should be removed and no other data. Removing -unintended data is worse than _not_ removing data that was requested for -removal but ideally, both are supported. Generally, according to this rule, we -err on holding data longer than needed, ensuring that it is only removed when -we can be certain that it can be removed. With the current behavior, we opt to -hold onto the data forever, ensuring that data cannot be incorrectly removed. - -To understand the problems with implementing deletes, one must understand the -data model. All registry data is stored in a filesystem layout, implemented on -a "storage driver", effectively a _virtual file system_ (VFS). The storage -system must assume that this VFS layer will be eventually consistent and has -poor read- after-write consistency, since this is the lower common denominator -among the storage drivers. This is mitigated by writing values in reverse- -dependent order, but makes wider transactional operations unsafe. - -Layered on the VFS model is a content-addressable _directed, acyclic graph_ -(DAG) made up of blobs. Manifests reference layers. Tags reference manifests. -Since the same data can be referenced by multiple manifests, we only store -data once, even if it is in different repositories. Thus, we have a set of -blobs, referenced by tags and manifests. If we want to delete a blob we need -to be certain that it is no longer referenced by another manifest or tag. When -we delete a manifest, we also can try to delete the referenced blobs. Deciding -whether or not a blob has an active reference is the crux of the problem. - -Conceptually, deleting a manifest and its resources is quite simple. Just find -all the manifests, enumerate the referenced blobs and delete the blobs not in -that set. An astute observer will recognize this as a garbage collection -problem. As with garbage collection in programming languages, this is very -simple when one always has a consistent view. When one adds parallelism and an -inconsistent view of data, it becomes very challenging. - -A simple example can demonstrate this. Let's say we are deleting a manifest -_A_ in one process. We scan the manifest and decide that all the blobs are -ready for deletion. Concurrently, we have another process accepting a new -manifest _B_ referencing one or more blobs from the manifest _A_. Manifest _B_ -is accepted and all the blobs are considered present, so the operation -proceeds. The original process then deletes the referenced blobs, assuming -they were unreferenced. The manifest _B_, which we thought had all of its data -present, can no longer be served by the registry, since the dependent data has -been deleted. - -Deleting data from the registry safely requires some way to coordinate this -operation. The following approaches are being considered: - -- _Reference Counting_ - Maintain a count of references to each blob. This is - challenging for a number of reasons: 1. maintaining a consistent consensus - of reference counts across a set of Registries and 2. Building the initial - list of reference counts for an existing registry. These challenges can be - met with a consensus protocol like Paxos or Raft in the first case and a - necessary but simple scan in the second.. -- _Lock the World GC_ - Halt all writes to the data store. Walk the data store - and find all blob references. Delete all unreferenced blobs. This approach - is very simple but requires disabling writes for a period of time while the - service reads all data. This is slow and expensive but very accurate and - effective. -- _Generational GC_ - Do something similar to above but instead of blocking - writes, writes are sent to another storage backend while reads are broadcast - to the new and old backends. GC is then performed on the read-only portion. - Because writes land in the new backend, the data in the read-only section - can be safely deleted. The main drawbacks of this approach are complexity - and coordination. -- _Centralized Oracle_ - Using a centralized, transactional database, we can - know exactly which data is referenced at any given time. This avoids - coordination problem by managing this data in a single location. We trade - off metadata scalability for simplicity and performance. This is a very good - option for most registry deployments. This would create a bottleneck for - registry metadata. However, metadata is generally not the main bottleneck - when serving images. - -Please let us know if other solutions exist that we have yet to enumerate. -Note that for any approach, implementation is a massive consideration. For -example, a mark-sweep based solution may seem simple but the amount of work in -coordination offset the extra work it might take to build a _Centralized -Oracle_. We'll accept proposals for any solution but please coordinate with us -before dropping code. - -At this time, we have traded off simplicity and ease of deployment for disk -space. Simplicity and ease of deployment tend to reduce developer involvement, -which is currently the most expensive resource in software engineering. Taking -on any solution for deletes will greatly effect these factors, trading off -very cheap disk space for a complex deployment and operational story. - -Please see the following issues for more detail: - -- https://github.com/docker/distribution/issues/422 -- https://github.com/docker/distribution/issues/461 -- https://github.com/docker/distribution/issues/462 - -### Distribution Package - -At its core, the Distribution Project is a set of Go packages that make up -Distribution Components. At this time, most of these packages make up the -Registry implementation. - -The package itself is considered unstable. If you're using it, please take care to vendor the dependent version. - -For feature additions, please see the Registry section. In the future, we may break out a -separate Roadmap for distribution-specific features that apply to more than -just the registry. - -*** - -### Project Planning - -An [Open-Source Planning Process](https://github.com/docker/distribution/wiki/Open-Source-Planning-Process) is used to define the Roadmap. [Project Pages](https://github.com/docker/distribution/wiki) define the goals for each Milestone and identify current progress. - diff --git a/vendor/github.com/docker/distribution/blobs.go b/vendor/github.com/docker/distribution/blobs.go deleted file mode 100644 index 1f91ae21e..000000000 --- a/vendor/github.com/docker/distribution/blobs.go +++ /dev/null @@ -1,257 +0,0 @@ -package distribution - -import ( - "errors" - "fmt" - "io" - "net/http" - "time" - - "github.com/docker/distribution/context" - "github.com/docker/distribution/digest" - "github.com/docker/distribution/reference" -) - -var ( - // ErrBlobExists returned when blob already exists - ErrBlobExists = errors.New("blob exists") - - // ErrBlobDigestUnsupported when blob digest is an unsupported version. - ErrBlobDigestUnsupported = errors.New("unsupported blob digest") - - // ErrBlobUnknown when blob is not found. - ErrBlobUnknown = errors.New("unknown blob") - - // ErrBlobUploadUnknown returned when upload is not found. - ErrBlobUploadUnknown = errors.New("blob upload unknown") - - // ErrBlobInvalidLength returned when the blob has an expected length on - // commit, meaning mismatched with the descriptor or an invalid value. - ErrBlobInvalidLength = errors.New("blob invalid length") -) - -// ErrBlobInvalidDigest returned when digest check fails. -type ErrBlobInvalidDigest struct { - Digest digest.Digest - Reason error -} - -func (err ErrBlobInvalidDigest) Error() string { - return fmt.Sprintf("invalid digest for referenced layer: %v, %v", - err.Digest, err.Reason) -} - -// ErrBlobMounted returned when a blob is mounted from another repository -// instead of initiating an upload session. -type ErrBlobMounted struct { - From reference.Canonical - Descriptor Descriptor -} - -func (err ErrBlobMounted) Error() string { - return fmt.Sprintf("blob mounted from: %v to: %v", - err.From, err.Descriptor) -} - -// Descriptor describes targeted content. Used in conjunction with a blob -// store, a descriptor can be used to fetch, store and target any kind of -// blob. The struct also describes the wire protocol format. Fields should -// only be added but never changed. -type Descriptor struct { - // MediaType describe the type of the content. All text based formats are - // encoded as utf-8. - MediaType string `json:"mediaType,omitempty"` - - // Size in bytes of content. - Size int64 `json:"size,omitempty"` - - // Digest uniquely identifies the content. A byte stream can be verified - // against against this digest. - Digest digest.Digest `json:"digest,omitempty"` - - // URLs contains the source URLs of this content. - URLs []string `json:"urls,omitempty"` - - // NOTE: Before adding a field here, please ensure that all - // other options have been exhausted. Much of the type relationships - // depend on the simplicity of this type. -} - -// Descriptor returns the descriptor, to make it satisfy the Describable -// interface. Note that implementations of Describable are generally objects -// which can be described, not simply descriptors; this exception is in place -// to make it more convenient to pass actual descriptors to functions that -// expect Describable objects. -func (d Descriptor) Descriptor() Descriptor { - return d -} - -// BlobStatter makes blob descriptors available by digest. The service may -// provide a descriptor of a different digest if the provided digest is not -// canonical. -type BlobStatter interface { - // Stat provides metadata about a blob identified by the digest. If the - // blob is unknown to the describer, ErrBlobUnknown will be returned. - Stat(ctx context.Context, dgst digest.Digest) (Descriptor, error) -} - -// BlobDeleter enables deleting blobs from storage. -type BlobDeleter interface { - Delete(ctx context.Context, dgst digest.Digest) error -} - -// BlobEnumerator enables iterating over blobs from storage -type BlobEnumerator interface { - Enumerate(ctx context.Context, ingester func(dgst digest.Digest) error) error -} - -// BlobDescriptorService manages metadata about a blob by digest. Most -// implementations will not expose such an interface explicitly. Such mappings -// should be maintained by interacting with the BlobIngester. Hence, this is -// left off of BlobService and BlobStore. -type BlobDescriptorService interface { - BlobStatter - - // SetDescriptor assigns the descriptor to the digest. The provided digest and - // the digest in the descriptor must map to identical content but they may - // differ on their algorithm. The descriptor must have the canonical - // digest of the content and the digest algorithm must match the - // annotators canonical algorithm. - // - // Such a facility can be used to map blobs between digest domains, with - // the restriction that the algorithm of the descriptor must match the - // canonical algorithm (ie sha256) of the annotator. - SetDescriptor(ctx context.Context, dgst digest.Digest, desc Descriptor) error - - // Clear enables descriptors to be unlinked - Clear(ctx context.Context, dgst digest.Digest) error -} - -// BlobDescriptorServiceFactory creates middleware for BlobDescriptorService. -type BlobDescriptorServiceFactory interface { - BlobAccessController(svc BlobDescriptorService) BlobDescriptorService -} - -// ReadSeekCloser is the primary reader type for blob data, combining -// io.ReadSeeker with io.Closer. -type ReadSeekCloser interface { - io.ReadSeeker - io.Closer -} - -// BlobProvider describes operations for getting blob data. -type BlobProvider interface { - // Get returns the entire blob identified by digest along with the descriptor. - Get(ctx context.Context, dgst digest.Digest) ([]byte, error) - - // Open provides a ReadSeekCloser to the blob identified by the provided - // descriptor. If the blob is not known to the service, an error will be - // returned. - Open(ctx context.Context, dgst digest.Digest) (ReadSeekCloser, error) -} - -// BlobServer can serve blobs via http. -type BlobServer interface { - // ServeBlob attempts to serve the blob, identifed by dgst, via http. The - // service may decide to redirect the client elsewhere or serve the data - // directly. - // - // This handler only issues successful responses, such as 2xx or 3xx, - // meaning it serves data or issues a redirect. If the blob is not - // available, an error will be returned and the caller may still issue a - // response. - // - // The implementation may serve the same blob from a different digest - // domain. The appropriate headers will be set for the blob, unless they - // have already been set by the caller. - ServeBlob(ctx context.Context, w http.ResponseWriter, r *http.Request, dgst digest.Digest) error -} - -// BlobIngester ingests blob data. -type BlobIngester interface { - // Put inserts the content p into the blob service, returning a descriptor - // or an error. - Put(ctx context.Context, mediaType string, p []byte) (Descriptor, error) - - // Create allocates a new blob writer to add a blob to this service. The - // returned handle can be written to and later resumed using an opaque - // identifier. With this approach, one can Close and Resume a BlobWriter - // multiple times until the BlobWriter is committed or cancelled. - Create(ctx context.Context, options ...BlobCreateOption) (BlobWriter, error) - - // Resume attempts to resume a write to a blob, identified by an id. - Resume(ctx context.Context, id string) (BlobWriter, error) -} - -// BlobCreateOption is a general extensible function argument for blob creation -// methods. A BlobIngester may choose to honor any or none of the given -// BlobCreateOptions, which can be specific to the implementation of the -// BlobIngester receiving them. -// TODO (brianbland): unify this with ManifestServiceOption in the future -type BlobCreateOption interface { - Apply(interface{}) error -} - -// CreateOptions is a collection of blob creation modifiers relevant to general -// blob storage intended to be configured by the BlobCreateOption.Apply method. -type CreateOptions struct { - Mount struct { - ShouldMount bool - From reference.Canonical - // Stat allows to pass precalculated descriptor to link and return. - // Blob access check will be skipped if set. - Stat *Descriptor - } -} - -// BlobWriter provides a handle for inserting data into a blob store. -// Instances should be obtained from BlobWriteService.Writer and -// BlobWriteService.Resume. If supported by the store, a writer can be -// recovered with the id. -type BlobWriter interface { - io.WriteCloser - io.ReaderFrom - - // Size returns the number of bytes written to this blob. - Size() int64 - - // ID returns the identifier for this writer. The ID can be used with the - // Blob service to later resume the write. - ID() string - - // StartedAt returns the time this blob write was started. - StartedAt() time.Time - - // Commit completes the blob writer process. The content is verified - // against the provided provisional descriptor, which may result in an - // error. Depending on the implementation, written data may be validated - // against the provisional descriptor fields. If MediaType is not present, - // the implementation may reject the commit or assign "application/octet- - // stream" to the blob. The returned descriptor may have a different - // digest depending on the blob store, referred to as the canonical - // descriptor. - Commit(ctx context.Context, provisional Descriptor) (canonical Descriptor, err error) - - // Cancel ends the blob write without storing any data and frees any - // associated resources. Any data written thus far will be lost. Cancel - // implementations should allow multiple calls even after a commit that - // result in a no-op. This allows use of Cancel in a defer statement, - // increasing the assurance that it is correctly called. - Cancel(ctx context.Context) error -} - -// BlobService combines the operations to access, read and write blobs. This -// can be used to describe remote blob services. -type BlobService interface { - BlobStatter - BlobProvider - BlobIngester -} - -// BlobStore represent the entire suite of blob related operations. Such an -// implementation can access, read, write, delete and serve blobs. -type BlobStore interface { - BlobService - BlobServer - BlobDeleter -} diff --git a/vendor/github.com/docker/distribution/circle.yml b/vendor/github.com/docker/distribution/circle.yml deleted file mode 100644 index 61f8be0cb..000000000 --- a/vendor/github.com/docker/distribution/circle.yml +++ /dev/null @@ -1,93 +0,0 @@ -# Pony-up! -machine: - pre: - # Install gvm - - bash < <(curl -s -S -L https://raw.githubusercontent.com/moovweb/gvm/1.0.22/binscripts/gvm-installer) - # Install codecov for coverage - - pip install --user codecov - - post: - # go - - gvm install go1.7 --prefer-binary --name=stable - - environment: - # Convenient shortcuts to "common" locations - CHECKOUT: /home/ubuntu/$CIRCLE_PROJECT_REPONAME - BASE_DIR: src/github.com/$CIRCLE_PROJECT_USERNAME/$CIRCLE_PROJECT_REPONAME - # Trick circle brainflat "no absolute path" behavior - BASE_STABLE: ../../../$HOME/.gvm/pkgsets/stable/global/$BASE_DIR - DOCKER_BUILDTAGS: "include_oss include_gcs" - # Workaround Circle parsing dumb bugs and/or YAML wonkyness - CIRCLE_PAIN: "mode: set" - - hosts: - # Not used yet - fancy: 127.0.0.1 - -dependencies: - pre: - # Copy the code to the gopath of all go versions - - > - gvm use stable && - mkdir -p "$(dirname $BASE_STABLE)" && - cp -R "$CHECKOUT" "$BASE_STABLE" - - override: - # Install dependencies for every copied clone/go version - - gvm use stable && go get github.com/tools/godep: - pwd: $BASE_STABLE - - post: - # For the stable go version, additionally install linting tools - - > - gvm use stable && - go get github.com/axw/gocov/gocov github.com/golang/lint/golint - -test: - pre: - # Output the go versions we are going to test - # - gvm use old && go version - - gvm use stable && go version - - # todo(richard): replace with a more robust vendoring solution. Removed due to a fundamental disagreement in godep philosophies. - # Ensure validation of dependencies - # - gvm use stable && if test -n "`git diff --stat=1000 master | grep -Ei \"vendor|godeps\"`"; then make dep-validate; fi: - # pwd: $BASE_STABLE - - # First thing: build everything. This will catch compile errors, and it's - # also necessary for go vet to work properly (see #807). - - gvm use stable && godep go install $(go list ./... | grep -v "/vendor/"): - pwd: $BASE_STABLE - - # FMT - - gvm use stable && make fmt: - pwd: $BASE_STABLE - - # VET - - gvm use stable && make vet: - pwd: $BASE_STABLE - - # LINT - - gvm use stable && make lint: - pwd: $BASE_STABLE - - override: - # Test stable, and report - - gvm use stable; export ROOT_PACKAGE=$(go list .); go list -tags "$DOCKER_BUILDTAGS" ./... | grep -v "/vendor/" | xargs -L 1 -I{} bash -c 'export PACKAGE={}; godep go test -tags "$DOCKER_BUILDTAGS" -test.short -coverprofile=$GOPATH/src/$PACKAGE/coverage.out -coverpkg=$(./coverpkg.sh $PACKAGE $ROOT_PACKAGE) $PACKAGE': - timeout: 1000 - pwd: $BASE_STABLE - - # Test stable with race - - gvm use stable; export ROOT_PACKAGE=$(go list .); go list -tags "$DOCKER_BUILDTAGS" ./... | grep -v "/vendor/" | grep -v "registry/handlers" | grep -v "registry/storage/driver" | xargs -L 1 -I{} bash -c 'export PACKAGE={}; godep go test -race -tags "$DOCKER_BUILDTAGS" -test.short $PACKAGE': - timeout: 1000 - pwd: $BASE_STABLE - post: - # Report to codecov - - bash <(curl -s https://codecov.io/bash): - pwd: $BASE_STABLE - - ## Notes - # Do we want these as well? - # - go get code.google.com/p/go.tools/cmd/goimports - # - test -z "$(goimports -l -w ./... | tee /dev/stderr)" - # http://labix.org/gocheck diff --git a/vendor/github.com/docker/distribution/coverpkg.sh b/vendor/github.com/docker/distribution/coverpkg.sh deleted file mode 100755 index 25d419ae8..000000000 --- a/vendor/github.com/docker/distribution/coverpkg.sh +++ /dev/null @@ -1,7 +0,0 @@ -#!/usr/bin/env bash -# Given a subpackage and the containing package, figures out which packages -# need to be passed to `go test -coverpkg`: this includes all of the -# subpackage's dependencies within the containing package, as well as the -# subpackage itself. -DEPENDENCIES="$(go list -f $'{{range $f := .Deps}}{{$f}}\n{{end}}' ${1} | grep ${2} | grep -v github.com/docker/distribution/vendor)" -echo "${1} ${DEPENDENCIES}" | xargs echo -n | tr ' ' ',' diff --git a/vendor/github.com/docker/distribution/digest/digest_test.go b/vendor/github.com/docker/distribution/digest/digest_test.go deleted file mode 100644 index afb4ebf63..000000000 --- a/vendor/github.com/docker/distribution/digest/digest_test.go +++ /dev/null @@ -1,82 +0,0 @@ -package digest - -import ( - "testing" -) - -func TestParseDigest(t *testing.T) { - for _, testcase := range []struct { - input string - err error - algorithm Algorithm - hex string - }{ - { - input: "sha256:e58fcf7418d4390dec8e8fb69d88c06ec07039d651fedd3aa72af9972e7d046b", - algorithm: "sha256", - hex: "e58fcf7418d4390dec8e8fb69d88c06ec07039d651fedd3aa72af9972e7d046b", - }, - { - input: "sha384:d3fc7881460b7e22e3d172954463dddd7866d17597e7248453c48b3e9d26d9596bf9c4a9cf8072c9d5bad76e19af801d", - algorithm: "sha384", - hex: "d3fc7881460b7e22e3d172954463dddd7866d17597e7248453c48b3e9d26d9596bf9c4a9cf8072c9d5bad76e19af801d", - }, - { - // empty hex - input: "sha256:", - err: ErrDigestInvalidFormat, - }, - { - // just hex - input: "d41d8cd98f00b204e9800998ecf8427e", - err: ErrDigestInvalidFormat, - }, - { - // not hex - input: "sha256:d41d8cd98f00b204e9800m98ecf8427e", - err: ErrDigestInvalidFormat, - }, - { - // too short - input: "sha256:abcdef0123456789", - err: ErrDigestInvalidLength, - }, - { - // too short (from different algorithm) - input: "sha512:abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789", - err: ErrDigestInvalidLength, - }, - { - input: "foo:d41d8cd98f00b204e9800998ecf8427e", - err: ErrDigestUnsupported, - }, - } { - digest, err := ParseDigest(testcase.input) - if err != testcase.err { - t.Fatalf("error differed from expected while parsing %q: %v != %v", testcase.input, err, testcase.err) - } - - if testcase.err != nil { - continue - } - - if digest.Algorithm() != testcase.algorithm { - t.Fatalf("incorrect algorithm for parsed digest: %q != %q", digest.Algorithm(), testcase.algorithm) - } - - if digest.Hex() != testcase.hex { - t.Fatalf("incorrect hex for parsed digest: %q != %q", digest.Hex(), testcase.hex) - } - - // Parse string return value and check equality - newParsed, err := ParseDigest(digest.String()) - - if err != nil { - t.Fatalf("unexpected error parsing input %q: %v", testcase.input, err) - } - - if newParsed != digest { - t.Fatalf("expected equal: %q != %q", newParsed, digest) - } - } -} diff --git a/vendor/github.com/docker/distribution/digest/digester_resumable_test.go b/vendor/github.com/docker/distribution/digest/digester_resumable_test.go deleted file mode 100644 index 6ba21c801..000000000 --- a/vendor/github.com/docker/distribution/digest/digester_resumable_test.go +++ /dev/null @@ -1,21 +0,0 @@ -// +build !noresumabledigest - -package digest - -import ( - "testing" - - "github.com/stevvooe/resumable" - _ "github.com/stevvooe/resumable/sha256" -) - -// TestResumableDetection just ensures that the resumable capability of a hash -// is exposed through the digester type, which is just a hash plus a Digest -// method. -func TestResumableDetection(t *testing.T) { - d := Canonical.New() - - if _, ok := d.Hash().(resumable.Hash); !ok { - t.Fatalf("expected digester to implement resumable.Hash: %#v, %v", d, d.Hash()) - } -} diff --git a/vendor/github.com/docker/distribution/digest/set_test.go b/vendor/github.com/docker/distribution/digest/set_test.go deleted file mode 100644 index e9dab8795..000000000 --- a/vendor/github.com/docker/distribution/digest/set_test.go +++ /dev/null @@ -1,368 +0,0 @@ -package digest - -import ( - "crypto/sha256" - "encoding/binary" - "math/rand" - "testing" -) - -func assertEqualDigests(t *testing.T, d1, d2 Digest) { - if d1 != d2 { - t.Fatalf("Digests do not match:\n\tActual: %s\n\tExpected: %s", d1, d2) - } -} - -func TestLookup(t *testing.T) { - digests := []Digest{ - "sha256:1234511111111111111111111111111111111111111111111111111111111111", - "sha256:1234111111111111111111111111111111111111111111111111111111111111", - "sha256:1234611111111111111111111111111111111111111111111111111111111111", - "sha256:5432111111111111111111111111111111111111111111111111111111111111", - "sha256:6543111111111111111111111111111111111111111111111111111111111111", - "sha256:6432111111111111111111111111111111111111111111111111111111111111", - "sha256:6542111111111111111111111111111111111111111111111111111111111111", - "sha256:6532111111111111111111111111111111111111111111111111111111111111", - } - - dset := NewSet() - for i := range digests { - if err := dset.Add(digests[i]); err != nil { - t.Fatal(err) - } - } - - dgst, err := dset.Lookup("54") - if err != nil { - t.Fatal(err) - } - assertEqualDigests(t, dgst, digests[3]) - - dgst, err = dset.Lookup("1234") - if err == nil { - t.Fatal("Expected ambiguous error looking up: 1234") - } - if err != ErrDigestAmbiguous { - t.Fatal(err) - } - - dgst, err = dset.Lookup("9876") - if err == nil { - t.Fatal("Expected ambiguous error looking up: 9876") - } - if err != ErrDigestNotFound { - t.Fatal(err) - } - - dgst, err = dset.Lookup("sha256:1234") - if err == nil { - t.Fatal("Expected ambiguous error looking up: sha256:1234") - } - if err != ErrDigestAmbiguous { - t.Fatal(err) - } - - dgst, err = dset.Lookup("sha256:12345") - if err != nil { - t.Fatal(err) - } - assertEqualDigests(t, dgst, digests[0]) - - dgst, err = dset.Lookup("sha256:12346") - if err != nil { - t.Fatal(err) - } - assertEqualDigests(t, dgst, digests[2]) - - dgst, err = dset.Lookup("12346") - if err != nil { - t.Fatal(err) - } - assertEqualDigests(t, dgst, digests[2]) - - dgst, err = dset.Lookup("12345") - if err != nil { - t.Fatal(err) - } - assertEqualDigests(t, dgst, digests[0]) -} - -func TestAddDuplication(t *testing.T) { - digests := []Digest{ - "sha256:1234111111111111111111111111111111111111111111111111111111111111", - "sha256:1234511111111111111111111111111111111111111111111111111111111111", - "sha256:1234611111111111111111111111111111111111111111111111111111111111", - "sha256:5432111111111111111111111111111111111111111111111111111111111111", - "sha256:6543111111111111111111111111111111111111111111111111111111111111", - "sha512:65431111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111", - "sha512:65421111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111", - "sha512:65321111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111", - } - - dset := NewSet() - for i := range digests { - if err := dset.Add(digests[i]); err != nil { - t.Fatal(err) - } - } - - if len(dset.entries) != 8 { - t.Fatal("Invalid dset size") - } - - if err := dset.Add(Digest("sha256:1234511111111111111111111111111111111111111111111111111111111111")); err != nil { - t.Fatal(err) - } - - if len(dset.entries) != 8 { - t.Fatal("Duplicate digest insert allowed") - } - - if err := dset.Add(Digest("sha384:123451111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111")); err != nil { - t.Fatal(err) - } - - if len(dset.entries) != 9 { - t.Fatal("Insert with different algorithm not allowed") - } -} - -func TestRemove(t *testing.T) { - digests, err := createDigests(10) - if err != nil { - t.Fatal(err) - } - - dset := NewSet() - for i := range digests { - if err := dset.Add(digests[i]); err != nil { - t.Fatal(err) - } - } - - dgst, err := dset.Lookup(digests[0].String()) - if err != nil { - t.Fatal(err) - } - if dgst != digests[0] { - t.Fatalf("Unexpected digest value:\n\tExpected: %s\n\tActual: %s", digests[0], dgst) - } - - if err := dset.Remove(digests[0]); err != nil { - t.Fatal(err) - } - - if _, err := dset.Lookup(digests[0].String()); err != ErrDigestNotFound { - t.Fatalf("Expected error %v when looking up removed digest, got %v", ErrDigestNotFound, err) - } -} - -func TestAll(t *testing.T) { - digests, err := createDigests(100) - if err != nil { - t.Fatal(err) - } - - dset := NewSet() - for i := range digests { - if err := dset.Add(digests[i]); err != nil { - t.Fatal(err) - } - } - - all := map[Digest]struct{}{} - for _, dgst := range dset.All() { - all[dgst] = struct{}{} - } - - if len(all) != len(digests) { - t.Fatalf("Unexpected number of unique digests found:\n\tExpected: %d\n\tActual: %d", len(digests), len(all)) - } - - for i, dgst := range digests { - if _, ok := all[dgst]; !ok { - t.Fatalf("Missing element at position %d: %s", i, dgst) - } - } - -} - -func assertEqualShort(t *testing.T, actual, expected string) { - if actual != expected { - t.Fatalf("Unexpected short value:\n\tExpected: %s\n\tActual: %s", expected, actual) - } -} - -func TestShortCodeTable(t *testing.T) { - digests := []Digest{ - "sha256:1234111111111111111111111111111111111111111111111111111111111111", - "sha256:1234511111111111111111111111111111111111111111111111111111111111", - "sha256:1234611111111111111111111111111111111111111111111111111111111111", - "sha256:5432111111111111111111111111111111111111111111111111111111111111", - "sha256:6543111111111111111111111111111111111111111111111111111111111111", - "sha256:6432111111111111111111111111111111111111111111111111111111111111", - "sha256:6542111111111111111111111111111111111111111111111111111111111111", - "sha256:6532111111111111111111111111111111111111111111111111111111111111", - } - - dset := NewSet() - for i := range digests { - if err := dset.Add(digests[i]); err != nil { - t.Fatal(err) - } - } - - dump := ShortCodeTable(dset, 2) - - if len(dump) < len(digests) { - t.Fatalf("Error unexpected size: %d, expecting %d", len(dump), len(digests)) - } - assertEqualShort(t, dump[digests[0]], "12341") - assertEqualShort(t, dump[digests[1]], "12345") - assertEqualShort(t, dump[digests[2]], "12346") - assertEqualShort(t, dump[digests[3]], "54") - assertEqualShort(t, dump[digests[4]], "6543") - assertEqualShort(t, dump[digests[5]], "64") - assertEqualShort(t, dump[digests[6]], "6542") - assertEqualShort(t, dump[digests[7]], "653") -} - -func createDigests(count int) ([]Digest, error) { - r := rand.New(rand.NewSource(25823)) - digests := make([]Digest, count) - for i := range digests { - h := sha256.New() - if err := binary.Write(h, binary.BigEndian, r.Int63()); err != nil { - return nil, err - } - digests[i] = NewDigest("sha256", h) - } - return digests, nil -} - -func benchAddNTable(b *testing.B, n int) { - digests, err := createDigests(n) - if err != nil { - b.Fatal(err) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - dset := &Set{entries: digestEntries(make([]*digestEntry, 0, n))} - for j := range digests { - if err = dset.Add(digests[j]); err != nil { - b.Fatal(err) - } - } - } -} - -func benchLookupNTable(b *testing.B, n int, shortLen int) { - digests, err := createDigests(n) - if err != nil { - b.Fatal(err) - } - dset := &Set{entries: digestEntries(make([]*digestEntry, 0, n))} - for i := range digests { - if err := dset.Add(digests[i]); err != nil { - b.Fatal(err) - } - } - shorts := make([]string, 0, n) - for _, short := range ShortCodeTable(dset, shortLen) { - shorts = append(shorts, short) - } - - b.ResetTimer() - for i := 0; i < b.N; i++ { - if _, err = dset.Lookup(shorts[i%n]); err != nil { - b.Fatal(err) - } - } -} - -func benchRemoveNTable(b *testing.B, n int) { - digests, err := createDigests(n) - if err != nil { - b.Fatal(err) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - dset := &Set{entries: digestEntries(make([]*digestEntry, 0, n))} - b.StopTimer() - for j := range digests { - if err = dset.Add(digests[j]); err != nil { - b.Fatal(err) - } - } - b.StartTimer() - for j := range digests { - if err = dset.Remove(digests[j]); err != nil { - b.Fatal(err) - } - } - } -} - -func benchShortCodeNTable(b *testing.B, n int, shortLen int) { - digests, err := createDigests(n) - if err != nil { - b.Fatal(err) - } - dset := &Set{entries: digestEntries(make([]*digestEntry, 0, n))} - for i := range digests { - if err := dset.Add(digests[i]); err != nil { - b.Fatal(err) - } - } - - b.ResetTimer() - for i := 0; i < b.N; i++ { - ShortCodeTable(dset, shortLen) - } -} - -func BenchmarkAdd10(b *testing.B) { - benchAddNTable(b, 10) -} - -func BenchmarkAdd100(b *testing.B) { - benchAddNTable(b, 100) -} - -func BenchmarkAdd1000(b *testing.B) { - benchAddNTable(b, 1000) -} - -func BenchmarkRemove10(b *testing.B) { - benchRemoveNTable(b, 10) -} - -func BenchmarkRemove100(b *testing.B) { - benchRemoveNTable(b, 100) -} - -func BenchmarkRemove1000(b *testing.B) { - benchRemoveNTable(b, 1000) -} - -func BenchmarkLookup10(b *testing.B) { - benchLookupNTable(b, 10, 12) -} - -func BenchmarkLookup100(b *testing.B) { - benchLookupNTable(b, 100, 12) -} - -func BenchmarkLookup1000(b *testing.B) { - benchLookupNTable(b, 1000, 12) -} - -func BenchmarkShortCode10(b *testing.B) { - benchShortCodeNTable(b, 10, 12) -} -func BenchmarkShortCode100(b *testing.B) { - benchShortCodeNTable(b, 100, 12) -} -func BenchmarkShortCode1000(b *testing.B) { - benchShortCodeNTable(b, 1000, 12) -} diff --git a/vendor/github.com/docker/distribution/digest/verifiers_test.go b/vendor/github.com/docker/distribution/digest/verifiers_test.go deleted file mode 100644 index c342d6e7c..000000000 --- a/vendor/github.com/docker/distribution/digest/verifiers_test.go +++ /dev/null @@ -1,49 +0,0 @@ -package digest - -import ( - "bytes" - "crypto/rand" - "io" - "testing" -) - -func TestDigestVerifier(t *testing.T) { - p := make([]byte, 1<<20) - rand.Read(p) - digest := FromBytes(p) - - verifier, err := NewDigestVerifier(digest) - if err != nil { - t.Fatalf("unexpected error getting digest verifier: %s", err) - } - - io.Copy(verifier, bytes.NewReader(p)) - - if !verifier.Verified() { - t.Fatalf("bytes not verified") - } -} - -// TestVerifierUnsupportedDigest ensures that unsupported digest validation is -// flowing through verifier creation. -func TestVerifierUnsupportedDigest(t *testing.T) { - unsupported := Digest("bean:0123456789abcdef") - - _, err := NewDigestVerifier(unsupported) - if err == nil { - t.Fatalf("expected error when creating verifier") - } - - if err != ErrDigestUnsupported { - t.Fatalf("incorrect error for unsupported digest: %v", err) - } -} - -// TODO(stevvooe): Add benchmarks to measure bytes/second throughput for -// DigestVerifier. -// -// The relevant benchmark for comparison can be run with the following -// commands: -// -// go test -bench . crypto/sha1 -// diff --git a/vendor/github.com/docker/distribution/doc.go b/vendor/github.com/docker/distribution/doc.go deleted file mode 100644 index bdd8cb708..000000000 --- a/vendor/github.com/docker/distribution/doc.go +++ /dev/null @@ -1,7 +0,0 @@ -// Package distribution will define the interfaces for the components of -// docker distribution. The goal is to allow users to reliably package, ship -// and store content related to docker images. -// -// This is currently a work in progress. More details are available in the -// README.md. -package distribution diff --git a/vendor/github.com/docker/distribution/errors.go b/vendor/github.com/docker/distribution/errors.go deleted file mode 100644 index c20f28113..000000000 --- a/vendor/github.com/docker/distribution/errors.go +++ /dev/null @@ -1,115 +0,0 @@ -package distribution - -import ( - "errors" - "fmt" - "strings" - - "github.com/docker/distribution/digest" -) - -// ErrAccessDenied is returned when an access to a requested resource is -// denied. -var ErrAccessDenied = errors.New("access denied") - -// ErrManifestNotModified is returned when a conditional manifest GetByTag -// returns nil due to the client indicating it has the latest version -var ErrManifestNotModified = errors.New("manifest not modified") - -// ErrUnsupported is returned when an unimplemented or unsupported action is -// performed -var ErrUnsupported = errors.New("operation unsupported") - -// ErrTagUnknown is returned if the given tag is not known by the tag service -type ErrTagUnknown struct { - Tag string -} - -func (err ErrTagUnknown) Error() string { - return fmt.Sprintf("unknown tag=%s", err.Tag) -} - -// ErrRepositoryUnknown is returned if the named repository is not known by -// the registry. -type ErrRepositoryUnknown struct { - Name string -} - -func (err ErrRepositoryUnknown) Error() string { - return fmt.Sprintf("unknown repository name=%s", err.Name) -} - -// ErrRepositoryNameInvalid should be used to denote an invalid repository -// name. Reason may set, indicating the cause of invalidity. -type ErrRepositoryNameInvalid struct { - Name string - Reason error -} - -func (err ErrRepositoryNameInvalid) Error() string { - return fmt.Sprintf("repository name %q invalid: %v", err.Name, err.Reason) -} - -// ErrManifestUnknown is returned if the manifest is not known by the -// registry. -type ErrManifestUnknown struct { - Name string - Tag string -} - -func (err ErrManifestUnknown) Error() string { - return fmt.Sprintf("unknown manifest name=%s tag=%s", err.Name, err.Tag) -} - -// ErrManifestUnknownRevision is returned when a manifest cannot be found by -// revision within a repository. -type ErrManifestUnknownRevision struct { - Name string - Revision digest.Digest -} - -func (err ErrManifestUnknownRevision) Error() string { - return fmt.Sprintf("unknown manifest name=%s revision=%s", err.Name, err.Revision) -} - -// ErrManifestUnverified is returned when the registry is unable to verify -// the manifest. -type ErrManifestUnverified struct{} - -func (ErrManifestUnverified) Error() string { - return fmt.Sprintf("unverified manifest") -} - -// ErrManifestVerification provides a type to collect errors encountered -// during manifest verification. Currently, it accepts errors of all types, -// but it may be narrowed to those involving manifest verification. -type ErrManifestVerification []error - -func (errs ErrManifestVerification) Error() string { - var parts []string - for _, err := range errs { - parts = append(parts, err.Error()) - } - - return fmt.Sprintf("errors verifying manifest: %v", strings.Join(parts, ",")) -} - -// ErrManifestBlobUnknown returned when a referenced blob cannot be found. -type ErrManifestBlobUnknown struct { - Digest digest.Digest -} - -func (err ErrManifestBlobUnknown) Error() string { - return fmt.Sprintf("unknown blob %v on manifest", err.Digest) -} - -// ErrManifestNameInvalid should be used to denote an invalid manifest -// name. Reason may set, indicating the cause of invalidity. -type ErrManifestNameInvalid struct { - Name string - Reason error -} - -func (err ErrManifestNameInvalid) Error() string { - return fmt.Sprintf("manifest name %q invalid: %v", err.Name, err.Reason) -} diff --git a/vendor/github.com/docker/distribution/manifests.go b/vendor/github.com/docker/distribution/manifests.go deleted file mode 100644 index c4fb63450..000000000 --- a/vendor/github.com/docker/distribution/manifests.go +++ /dev/null @@ -1,125 +0,0 @@ -package distribution - -import ( - "fmt" - "mime" - - "github.com/docker/distribution/context" - "github.com/docker/distribution/digest" -) - -// Manifest represents a registry object specifying a set of -// references and an optional target -type Manifest interface { - // References returns a list of objects which make up this manifest. - // A reference is anything which can be represented by a - // distribution.Descriptor. These can consist of layers, resources or other - // manifests. - // - // While no particular order is required, implementations should return - // them from highest to lowest priority. For example, one might want to - // return the base layer before the top layer. - References() []Descriptor - - // Payload provides the serialized format of the manifest, in addition to - // the mediatype. - Payload() (mediatype string, payload []byte, err error) -} - -// ManifestBuilder creates a manifest allowing one to include dependencies. -// Instances can be obtained from a version-specific manifest package. Manifest -// specific data is passed into the function which creates the builder. -type ManifestBuilder interface { - // Build creates the manifest from his builder. - Build(ctx context.Context) (Manifest, error) - - // References returns a list of objects which have been added to this - // builder. The dependencies are returned in the order they were added, - // which should be from base to head. - References() []Descriptor - - // AppendReference includes the given object in the manifest after any - // existing dependencies. If the add fails, such as when adding an - // unsupported dependency, an error may be returned. - // - // The destination of the reference is dependent on the manifest type and - // the dependency type. - AppendReference(dependency Describable) error -} - -// ManifestService describes operations on image manifests. -type ManifestService interface { - // Exists returns true if the manifest exists. - Exists(ctx context.Context, dgst digest.Digest) (bool, error) - - // Get retrieves the manifest specified by the given digest - Get(ctx context.Context, dgst digest.Digest, options ...ManifestServiceOption) (Manifest, error) - - // Put creates or updates the given manifest returning the manifest digest - Put(ctx context.Context, manifest Manifest, options ...ManifestServiceOption) (digest.Digest, error) - - // Delete removes the manifest specified by the given digest. Deleting - // a manifest that doesn't exist will return ErrManifestNotFound - Delete(ctx context.Context, dgst digest.Digest) error -} - -// ManifestEnumerator enables iterating over manifests -type ManifestEnumerator interface { - // Enumerate calls ingester for each manifest. - Enumerate(ctx context.Context, ingester func(digest.Digest) error) error -} - -// Describable is an interface for descriptors -type Describable interface { - Descriptor() Descriptor -} - -// ManifestMediaTypes returns the supported media types for manifests. -func ManifestMediaTypes() (mediaTypes []string) { - for t := range mappings { - if t != "" { - mediaTypes = append(mediaTypes, t) - } - } - return -} - -// UnmarshalFunc implements manifest unmarshalling a given MediaType -type UnmarshalFunc func([]byte) (Manifest, Descriptor, error) - -var mappings = make(map[string]UnmarshalFunc, 0) - -// UnmarshalManifest looks up manifest unmarshal functions based on -// MediaType -func UnmarshalManifest(ctHeader string, p []byte) (Manifest, Descriptor, error) { - // Need to look up by the actual media type, not the raw contents of - // the header. Strip semicolons and anything following them. - var mediatype string - if ctHeader != "" { - var err error - mediatype, _, err = mime.ParseMediaType(ctHeader) - if err != nil { - return nil, Descriptor{}, err - } - } - - unmarshalFunc, ok := mappings[mediatype] - if !ok { - unmarshalFunc, ok = mappings[""] - if !ok { - return nil, Descriptor{}, fmt.Errorf("unsupported manifest mediatype and no default available: %s", mediatype) - } - } - - return unmarshalFunc(p) -} - -// RegisterManifestSchema registers an UnmarshalFunc for a given schema type. This -// should be called from specific -func RegisterManifestSchema(mediatype string, u UnmarshalFunc) error { - if _, ok := mappings[mediatype]; ok { - return fmt.Errorf("manifest mediatype registration would overwrite existing: %s", mediatype) - } - mappings[mediatype] = u - return nil -} diff --git a/vendor/github.com/docker/distribution/reference/reference_test.go b/vendor/github.com/docker/distribution/reference/reference_test.go deleted file mode 100644 index 405c47c05..000000000 --- a/vendor/github.com/docker/distribution/reference/reference_test.go +++ /dev/null @@ -1,661 +0,0 @@ -package reference - -import ( - "encoding/json" - "strconv" - "strings" - "testing" - - "github.com/docker/distribution/digest" -) - -func TestReferenceParse(t *testing.T) { - // referenceTestcases is a unified set of testcases for - // testing the parsing of references - referenceTestcases := []struct { - // input is the repository name or name component testcase - input string - // err is the error expected from Parse, or nil - err error - // repository is the string representation for the reference - repository string - // hostname is the hostname expected in the reference - hostname string - // tag is the tag for the reference - tag string - // digest is the digest for the reference (enforces digest reference) - digest string - }{ - { - input: "test_com", - repository: "test_com", - }, - { - input: "test.com:tag", - repository: "test.com", - tag: "tag", - }, - { - input: "test.com:5000", - repository: "test.com", - tag: "5000", - }, - { - input: "test.com/repo:tag", - hostname: "test.com", - repository: "test.com/repo", - tag: "tag", - }, - { - input: "test:5000/repo", - hostname: "test:5000", - repository: "test:5000/repo", - }, - { - input: "test:5000/repo:tag", - hostname: "test:5000", - repository: "test:5000/repo", - tag: "tag", - }, - { - input: "test:5000/repo@sha256:ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", - hostname: "test:5000", - repository: "test:5000/repo", - digest: "sha256:ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", - }, - { - input: "test:5000/repo:tag@sha256:ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", - hostname: "test:5000", - repository: "test:5000/repo", - tag: "tag", - digest: "sha256:ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", - }, - { - input: "test:5000/repo", - hostname: "test:5000", - repository: "test:5000/repo", - }, - { - input: "", - err: ErrNameEmpty, - }, - { - input: ":justtag", - err: ErrReferenceInvalidFormat, - }, - { - input: "@sha256:ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", - err: ErrReferenceInvalidFormat, - }, - { - input: "repo@sha256:ffffffffffffffffffffffffffffffffff", - err: digest.ErrDigestInvalidLength, - }, - { - input: "validname@invaliddigest:ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", - err: digest.ErrDigestUnsupported, - }, - { - input: "Uppercase:tag", - err: ErrNameContainsUppercase, - }, - // FIXME "Uppercase" is incorrectly handled as a domain-name here, therefore passes. - // See https://github.com/docker/distribution/pull/1778, and https://github.com/docker/docker/pull/20175 - //{ - // input: "Uppercase/lowercase:tag", - // err: ErrNameContainsUppercase, - //}, - { - input: "test:5000/Uppercase/lowercase:tag", - err: ErrNameContainsUppercase, - }, - { - input: "lowercase:Uppercase", - repository: "lowercase", - tag: "Uppercase", - }, - { - input: strings.Repeat("a/", 128) + "a:tag", - err: ErrNameTooLong, - }, - { - input: strings.Repeat("a/", 127) + "a:tag-puts-this-over-max", - hostname: "a", - repository: strings.Repeat("a/", 127) + "a", - tag: "tag-puts-this-over-max", - }, - { - input: "aa/asdf$$^/aa", - err: ErrReferenceInvalidFormat, - }, - { - input: "sub-dom1.foo.com/bar/baz/quux", - hostname: "sub-dom1.foo.com", - repository: "sub-dom1.foo.com/bar/baz/quux", - }, - { - input: "sub-dom1.foo.com/bar/baz/quux:some-long-tag", - hostname: "sub-dom1.foo.com", - repository: "sub-dom1.foo.com/bar/baz/quux", - tag: "some-long-tag", - }, - { - input: "b.gcr.io/test.example.com/my-app:test.example.com", - hostname: "b.gcr.io", - repository: "b.gcr.io/test.example.com/my-app", - tag: "test.example.com", - }, - { - input: "xn--n3h.com/myimage:xn--n3h.com", // ☃.com in punycode - hostname: "xn--n3h.com", - repository: "xn--n3h.com/myimage", - tag: "xn--n3h.com", - }, - { - input: "xn--7o8h.com/myimage:xn--7o8h.com@sha512:ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", // 🐳.com in punycode - hostname: "xn--7o8h.com", - repository: "xn--7o8h.com/myimage", - tag: "xn--7o8h.com", - digest: "sha512:ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", - }, - { - input: "foo_bar.com:8080", - repository: "foo_bar.com", - tag: "8080", - }, - { - input: "foo/foo_bar.com:8080", - hostname: "foo", - repository: "foo/foo_bar.com", - tag: "8080", - }, - } - for _, testcase := range referenceTestcases { - failf := func(format string, v ...interface{}) { - t.Logf(strconv.Quote(testcase.input)+": "+format, v...) - t.Fail() - } - - repo, err := Parse(testcase.input) - if testcase.err != nil { - if err == nil { - failf("missing expected error: %v", testcase.err) - } else if testcase.err != err { - failf("mismatched error: got %v, expected %v", err, testcase.err) - } - continue - } else if err != nil { - failf("unexpected parse error: %v", err) - continue - } - if repo.String() != testcase.input { - failf("mismatched repo: got %q, expected %q", repo.String(), testcase.input) - } - - if named, ok := repo.(Named); ok { - if named.Name() != testcase.repository { - failf("unexpected repository: got %q, expected %q", named.Name(), testcase.repository) - } - hostname, _ := SplitHostname(named) - if hostname != testcase.hostname { - failf("unexpected hostname: got %q, expected %q", hostname, testcase.hostname) - } - } else if testcase.repository != "" || testcase.hostname != "" { - failf("expected named type, got %T", repo) - } - - tagged, ok := repo.(Tagged) - if testcase.tag != "" { - if ok { - if tagged.Tag() != testcase.tag { - failf("unexpected tag: got %q, expected %q", tagged.Tag(), testcase.tag) - } - } else { - failf("expected tagged type, got %T", repo) - } - } else if ok { - failf("unexpected tagged type") - } - - digested, ok := repo.(Digested) - if testcase.digest != "" { - if ok { - if digested.Digest().String() != testcase.digest { - failf("unexpected digest: got %q, expected %q", digested.Digest().String(), testcase.digest) - } - } else { - failf("expected digested type, got %T", repo) - } - } else if ok { - failf("unexpected digested type") - } - - } -} - -// TestWithNameFailure tests cases where WithName should fail. Cases where it -// should succeed are covered by TestSplitHostname, below. -func TestWithNameFailure(t *testing.T) { - testcases := []struct { - input string - err error - }{ - { - input: "", - err: ErrNameEmpty, - }, - { - input: ":justtag", - err: ErrReferenceInvalidFormat, - }, - { - input: "@sha256:ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", - err: ErrReferenceInvalidFormat, - }, - { - input: "validname@invaliddigest:ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", - err: ErrReferenceInvalidFormat, - }, - { - input: strings.Repeat("a/", 128) + "a:tag", - err: ErrNameTooLong, - }, - { - input: "aa/asdf$$^/aa", - err: ErrReferenceInvalidFormat, - }, - } - for _, testcase := range testcases { - failf := func(format string, v ...interface{}) { - t.Logf(strconv.Quote(testcase.input)+": "+format, v...) - t.Fail() - } - - _, err := WithName(testcase.input) - if err == nil { - failf("no error parsing name. expected: %s", testcase.err) - } - } -} - -func TestSplitHostname(t *testing.T) { - testcases := []struct { - input string - hostname string - name string - }{ - { - input: "test.com/foo", - hostname: "test.com", - name: "foo", - }, - { - input: "test_com/foo", - hostname: "", - name: "test_com/foo", - }, - { - input: "test:8080/foo", - hostname: "test:8080", - name: "foo", - }, - { - input: "test.com:8080/foo", - hostname: "test.com:8080", - name: "foo", - }, - { - input: "test-com:8080/foo", - hostname: "test-com:8080", - name: "foo", - }, - { - input: "xn--n3h.com:18080/foo", - hostname: "xn--n3h.com:18080", - name: "foo", - }, - } - for _, testcase := range testcases { - failf := func(format string, v ...interface{}) { - t.Logf(strconv.Quote(testcase.input)+": "+format, v...) - t.Fail() - } - - named, err := WithName(testcase.input) - if err != nil { - failf("error parsing name: %s", err) - } - hostname, name := SplitHostname(named) - if hostname != testcase.hostname { - failf("unexpected hostname: got %q, expected %q", hostname, testcase.hostname) - } - if name != testcase.name { - failf("unexpected name: got %q, expected %q", name, testcase.name) - } - } -} - -type serializationType struct { - Description string - Field Field -} - -func TestSerialization(t *testing.T) { - testcases := []struct { - description string - input string - name string - tag string - digest string - err error - }{ - { - description: "empty value", - err: ErrNameEmpty, - }, - { - description: "just a name", - input: "example.com:8000/named", - name: "example.com:8000/named", - }, - { - description: "name with a tag", - input: "example.com:8000/named:tagged", - name: "example.com:8000/named", - tag: "tagged", - }, - { - description: "name with digest", - input: "other.com/named@sha256:1234567890098765432112345667890098765432112345667890098765432112", - name: "other.com/named", - digest: "sha256:1234567890098765432112345667890098765432112345667890098765432112", - }, - } - for _, testcase := range testcases { - failf := func(format string, v ...interface{}) { - t.Logf(strconv.Quote(testcase.input)+": "+format, v...) - t.Fail() - } - - m := map[string]string{ - "Description": testcase.description, - "Field": testcase.input, - } - b, err := json.Marshal(m) - if err != nil { - failf("error marshalling: %v", err) - } - t := serializationType{} - - if err := json.Unmarshal(b, &t); err != nil { - if testcase.err == nil { - failf("error unmarshalling: %v", err) - } - if err != testcase.err { - failf("wrong error, expected %v, got %v", testcase.err, err) - } - - continue - } else if testcase.err != nil { - failf("expected error unmarshalling: %v", testcase.err) - } - - if t.Description != testcase.description { - failf("wrong description, expected %q, got %q", testcase.description, t.Description) - } - - ref := t.Field.Reference() - - if named, ok := ref.(Named); ok { - if named.Name() != testcase.name { - failf("unexpected repository: got %q, expected %q", named.Name(), testcase.name) - } - } else if testcase.name != "" { - failf("expected named type, got %T", ref) - } - - tagged, ok := ref.(Tagged) - if testcase.tag != "" { - if ok { - if tagged.Tag() != testcase.tag { - failf("unexpected tag: got %q, expected %q", tagged.Tag(), testcase.tag) - } - } else { - failf("expected tagged type, got %T", ref) - } - } else if ok { - failf("unexpected tagged type") - } - - digested, ok := ref.(Digested) - if testcase.digest != "" { - if ok { - if digested.Digest().String() != testcase.digest { - failf("unexpected digest: got %q, expected %q", digested.Digest().String(), testcase.digest) - } - } else { - failf("expected digested type, got %T", ref) - } - } else if ok { - failf("unexpected digested type") - } - - t = serializationType{ - Description: testcase.description, - Field: AsField(ref), - } - - b2, err := json.Marshal(t) - if err != nil { - failf("error marshing serialization type: %v", err) - } - - if string(b) != string(b2) { - failf("unexpected serialized value: expected %q, got %q", string(b), string(b2)) - } - - // Ensure t.Field is not implementing "Reference" directly, getting - // around the Reference type system - var fieldInterface interface{} = t.Field - if _, ok := fieldInterface.(Reference); ok { - failf("field should not implement Reference interface") - } - - } -} - -func TestWithTag(t *testing.T) { - testcases := []struct { - name string - digest digest.Digest - tag string - combined string - }{ - { - name: "test.com/foo", - tag: "tag", - combined: "test.com/foo:tag", - }, - { - name: "foo", - tag: "tag2", - combined: "foo:tag2", - }, - { - name: "test.com:8000/foo", - tag: "tag4", - combined: "test.com:8000/foo:tag4", - }, - { - name: "test.com:8000/foo", - tag: "TAG5", - combined: "test.com:8000/foo:TAG5", - }, - { - name: "test.com:8000/foo", - digest: "sha256:1234567890098765432112345667890098765", - tag: "TAG5", - combined: "test.com:8000/foo:TAG5@sha256:1234567890098765432112345667890098765", - }, - } - for _, testcase := range testcases { - failf := func(format string, v ...interface{}) { - t.Logf(strconv.Quote(testcase.name)+": "+format, v...) - t.Fail() - } - - named, err := WithName(testcase.name) - if err != nil { - failf("error parsing name: %s", err) - } - if testcase.digest != "" { - canonical, err := WithDigest(named, testcase.digest) - if err != nil { - failf("error adding digest") - } - named = canonical - } - - tagged, err := WithTag(named, testcase.tag) - if err != nil { - failf("WithTag failed: %s", err) - } - if tagged.String() != testcase.combined { - failf("unexpected: got %q, expected %q", tagged.String(), testcase.combined) - } - } -} - -func TestWithDigest(t *testing.T) { - testcases := []struct { - name string - digest digest.Digest - tag string - combined string - }{ - { - name: "test.com/foo", - digest: "sha256:1234567890098765432112345667890098765", - combined: "test.com/foo@sha256:1234567890098765432112345667890098765", - }, - { - name: "foo", - digest: "sha256:1234567890098765432112345667890098765", - combined: "foo@sha256:1234567890098765432112345667890098765", - }, - { - name: "test.com:8000/foo", - digest: "sha256:1234567890098765432112345667890098765", - combined: "test.com:8000/foo@sha256:1234567890098765432112345667890098765", - }, - { - name: "test.com:8000/foo", - digest: "sha256:1234567890098765432112345667890098765", - tag: "latest", - combined: "test.com:8000/foo:latest@sha256:1234567890098765432112345667890098765", - }, - } - for _, testcase := range testcases { - failf := func(format string, v ...interface{}) { - t.Logf(strconv.Quote(testcase.name)+": "+format, v...) - t.Fail() - } - - named, err := WithName(testcase.name) - if err != nil { - failf("error parsing name: %s", err) - } - if testcase.tag != "" { - tagged, err := WithTag(named, testcase.tag) - if err != nil { - failf("error adding tag") - } - named = tagged - } - digested, err := WithDigest(named, testcase.digest) - if err != nil { - failf("WithDigest failed: %s", err) - } - if digested.String() != testcase.combined { - failf("unexpected: got %q, expected %q", digested.String(), testcase.combined) - } - } -} - -func TestMatchError(t *testing.T) { - named, err := Parse("foo") - if err != nil { - t.Fatal(err) - } - _, err = Match("[-x]", named) - if err == nil { - t.Fatalf("expected an error, got nothing") - } -} - -func TestMatch(t *testing.T) { - matchCases := []struct { - reference string - pattern string - expected bool - }{ - { - reference: "foo", - pattern: "foo/**/ba[rz]", - expected: false, - }, - { - reference: "foo/any/bat", - pattern: "foo/**/ba[rz]", - expected: false, - }, - { - reference: "foo/a/bar", - pattern: "foo/**/ba[rz]", - expected: true, - }, - { - reference: "foo/b/baz", - pattern: "foo/**/ba[rz]", - expected: true, - }, - { - reference: "foo/c/baz:tag", - pattern: "foo/**/ba[rz]", - expected: true, - }, - { - reference: "foo/c/baz:tag", - pattern: "foo/*/baz:tag", - expected: true, - }, - { - reference: "foo/c/baz:tag", - pattern: "foo/c/baz:tag", - expected: true, - }, - { - reference: "example.com/foo/c/baz:tag", - pattern: "*/foo/c/baz", - expected: true, - }, - { - reference: "example.com/foo/c/baz:tag", - pattern: "example.com/foo/c/baz", - expected: true, - }, - } - for _, c := range matchCases { - named, err := Parse(c.reference) - if err != nil { - t.Fatal(err) - } - actual, err := Match(c.pattern, named) - if err != nil { - t.Fatal(err) - } - if actual != c.expected { - t.Fatalf("expected %s match %s to be %v, was %v", c.reference, c.pattern, c.expected, actual) - } - } -} diff --git a/vendor/github.com/docker/distribution/reference/regexp_test.go b/vendor/github.com/docker/distribution/reference/regexp_test.go deleted file mode 100644 index 2ec39377a..000000000 --- a/vendor/github.com/docker/distribution/reference/regexp_test.go +++ /dev/null @@ -1,489 +0,0 @@ -package reference - -import ( - "regexp" - "strings" - "testing" -) - -type regexpMatch struct { - input string - match bool - subs []string -} - -func checkRegexp(t *testing.T, r *regexp.Regexp, m regexpMatch) { - matches := r.FindStringSubmatch(m.input) - if m.match && matches != nil { - if len(matches) != (r.NumSubexp()+1) || matches[0] != m.input { - t.Fatalf("Bad match result %#v for %q", matches, m.input) - } - if len(matches) < (len(m.subs) + 1) { - t.Errorf("Expected %d sub matches, only have %d for %q", len(m.subs), len(matches)-1, m.input) - } - for i := range m.subs { - if m.subs[i] != matches[i+1] { - t.Errorf("Unexpected submatch %d: %q, expected %q for %q", i+1, matches[i+1], m.subs[i], m.input) - } - } - } else if m.match { - t.Errorf("Expected match for %q", m.input) - } else if matches != nil { - t.Errorf("Unexpected match for %q", m.input) - } -} - -func TestHostRegexp(t *testing.T) { - hostcases := []regexpMatch{ - { - input: "test.com", - match: true, - }, - { - input: "test.com:10304", - match: true, - }, - { - input: "test.com:http", - match: false, - }, - { - input: "localhost", - match: true, - }, - { - input: "localhost:8080", - match: true, - }, - { - input: "a", - match: true, - }, - { - input: "a.b", - match: true, - }, - { - input: "ab.cd.com", - match: true, - }, - { - input: "a-b.com", - match: true, - }, - { - input: "-ab.com", - match: false, - }, - { - input: "ab-.com", - match: false, - }, - { - input: "ab.c-om", - match: true, - }, - { - input: "ab.-com", - match: false, - }, - { - input: "ab.com-", - match: false, - }, - { - input: "0101.com", - match: true, // TODO(dmcgowan): valid if this should be allowed - }, - { - input: "001a.com", - match: true, - }, - { - input: "b.gbc.io:443", - match: true, - }, - { - input: "b.gbc.io", - match: true, - }, - { - input: "xn--n3h.com", // ☃.com in punycode - match: true, - }, - { - input: "Asdf.com", // uppercase character - match: true, - }, - } - r := regexp.MustCompile(`^` + hostnameRegexp.String() + `$`) - for i := range hostcases { - checkRegexp(t, r, hostcases[i]) - } -} - -func TestFullNameRegexp(t *testing.T) { - if anchoredNameRegexp.NumSubexp() != 2 { - t.Fatalf("anchored name regexp should have two submatches: %v, %v != 2", - anchoredNameRegexp, anchoredNameRegexp.NumSubexp()) - } - - testcases := []regexpMatch{ - { - input: "", - match: false, - }, - { - input: "short", - match: true, - subs: []string{"", "short"}, - }, - { - input: "simple/name", - match: true, - subs: []string{"simple", "name"}, - }, - { - input: "library/ubuntu", - match: true, - subs: []string{"library", "ubuntu"}, - }, - { - input: "docker/stevvooe/app", - match: true, - subs: []string{"docker", "stevvooe/app"}, - }, - { - input: "aa/aa/aa/aa/aa/aa/aa/aa/aa/bb/bb/bb/bb/bb/bb", - match: true, - subs: []string{"aa", "aa/aa/aa/aa/aa/aa/aa/aa/bb/bb/bb/bb/bb/bb"}, - }, - { - input: "aa/aa/bb/bb/bb", - match: true, - subs: []string{"aa", "aa/bb/bb/bb"}, - }, - { - input: "a/a/a/a", - match: true, - subs: []string{"a", "a/a/a"}, - }, - { - input: "a/a/a/a/", - match: false, - }, - { - input: "a//a/a", - match: false, - }, - { - input: "a", - match: true, - subs: []string{"", "a"}, - }, - { - input: "a/aa", - match: true, - subs: []string{"a", "aa"}, - }, - { - input: "a/aa/a", - match: true, - subs: []string{"a", "aa/a"}, - }, - { - input: "foo.com", - match: true, - subs: []string{"", "foo.com"}, - }, - { - input: "foo.com/", - match: false, - }, - { - input: "foo.com:8080/bar", - match: true, - subs: []string{"foo.com:8080", "bar"}, - }, - { - input: "foo.com:http/bar", - match: false, - }, - { - input: "foo.com/bar", - match: true, - subs: []string{"foo.com", "bar"}, - }, - { - input: "foo.com/bar/baz", - match: true, - subs: []string{"foo.com", "bar/baz"}, - }, - { - input: "localhost:8080/bar", - match: true, - subs: []string{"localhost:8080", "bar"}, - }, - { - input: "sub-dom1.foo.com/bar/baz/quux", - match: true, - subs: []string{"sub-dom1.foo.com", "bar/baz/quux"}, - }, - { - input: "blog.foo.com/bar/baz", - match: true, - subs: []string{"blog.foo.com", "bar/baz"}, - }, - { - input: "a^a", - match: false, - }, - { - input: "aa/asdf$$^/aa", - match: false, - }, - { - input: "asdf$$^/aa", - match: false, - }, - { - input: "aa-a/a", - match: true, - subs: []string{"aa-a", "a"}, - }, - { - input: strings.Repeat("a/", 128) + "a", - match: true, - subs: []string{"a", strings.Repeat("a/", 127) + "a"}, - }, - { - input: "a-/a/a/a", - match: false, - }, - { - input: "foo.com/a-/a/a", - match: false, - }, - { - input: "-foo/bar", - match: false, - }, - { - input: "foo/bar-", - match: false, - }, - { - input: "foo-/bar", - match: false, - }, - { - input: "foo/-bar", - match: false, - }, - { - input: "_foo/bar", - match: false, - }, - { - input: "foo_bar", - match: true, - subs: []string{"", "foo_bar"}, - }, - { - input: "foo_bar.com", - match: true, - subs: []string{"", "foo_bar.com"}, - }, - { - input: "foo_bar.com:8080", - match: false, - }, - { - input: "foo_bar.com:8080/app", - match: false, - }, - { - input: "foo.com/foo_bar", - match: true, - subs: []string{"foo.com", "foo_bar"}, - }, - { - input: "____/____", - match: false, - }, - { - input: "_docker/_docker", - match: false, - }, - { - input: "docker_/docker_", - match: false, - }, - { - input: "b.gcr.io/test.example.com/my-app", - match: true, - subs: []string{"b.gcr.io", "test.example.com/my-app"}, - }, - { - input: "xn--n3h.com/myimage", // ☃.com in punycode - match: true, - subs: []string{"xn--n3h.com", "myimage"}, - }, - { - input: "xn--7o8h.com/myimage", // 🐳.com in punycode - match: true, - subs: []string{"xn--7o8h.com", "myimage"}, - }, - { - input: "example.com/xn--7o8h.com/myimage", // 🐳.com in punycode - match: true, - subs: []string{"example.com", "xn--7o8h.com/myimage"}, - }, - { - input: "example.com/some_separator__underscore/myimage", - match: true, - subs: []string{"example.com", "some_separator__underscore/myimage"}, - }, - { - input: "example.com/__underscore/myimage", - match: false, - }, - { - input: "example.com/..dots/myimage", - match: false, - }, - { - input: "example.com/.dots/myimage", - match: false, - }, - { - input: "example.com/nodouble..dots/myimage", - match: false, - }, - { - input: "example.com/nodouble..dots/myimage", - match: false, - }, - { - input: "docker./docker", - match: false, - }, - { - input: ".docker/docker", - match: false, - }, - { - input: "docker-/docker", - match: false, - }, - { - input: "-docker/docker", - match: false, - }, - { - input: "do..cker/docker", - match: false, - }, - { - input: "do__cker:8080/docker", - match: false, - }, - { - input: "do__cker/docker", - match: true, - subs: []string{"", "do__cker/docker"}, - }, - { - input: "b.gcr.io/test.example.com/my-app", - match: true, - subs: []string{"b.gcr.io", "test.example.com/my-app"}, - }, - { - input: "registry.io/foo/project--id.module--name.ver---sion--name", - match: true, - subs: []string{"registry.io", "foo/project--id.module--name.ver---sion--name"}, - }, - { - input: "Asdf.com/foo/bar", // uppercase character in hostname - match: true, - }, - { - input: "Foo/FarB", // uppercase characters in remote name - match: false, - }, - } - for i := range testcases { - checkRegexp(t, anchoredNameRegexp, testcases[i]) - } -} - -func TestReferenceRegexp(t *testing.T) { - if ReferenceRegexp.NumSubexp() != 3 { - t.Fatalf("anchored name regexp should have three submatches: %v, %v != 3", - ReferenceRegexp, ReferenceRegexp.NumSubexp()) - } - - testcases := []regexpMatch{ - { - input: "registry.com:8080/myapp:tag", - match: true, - subs: []string{"registry.com:8080/myapp", "tag", ""}, - }, - { - input: "registry.com:8080/myapp@sha256:be178c0543eb17f5f3043021c9e5fcf30285e557a4fc309cce97ff9ca6182912", - match: true, - subs: []string{"registry.com:8080/myapp", "", "sha256:be178c0543eb17f5f3043021c9e5fcf30285e557a4fc309cce97ff9ca6182912"}, - }, - { - input: "registry.com:8080/myapp:tag2@sha256:be178c0543eb17f5f3043021c9e5fcf30285e557a4fc309cce97ff9ca6182912", - match: true, - subs: []string{"registry.com:8080/myapp", "tag2", "sha256:be178c0543eb17f5f3043021c9e5fcf30285e557a4fc309cce97ff9ca6182912"}, - }, - { - input: "registry.com:8080/myapp@sha256:badbadbadbad", - match: false, - }, - { - input: "registry.com:8080/myapp:invalid~tag", - match: false, - }, - { - input: "bad_hostname.com:8080/myapp:tag", - match: false, - }, - { - input:// localhost treated as name, missing tag with 8080 as tag - "localhost:8080@sha256:be178c0543eb17f5f3043021c9e5fcf30285e557a4fc309cce97ff9ca6182912", - match: true, - subs: []string{"localhost", "8080", "sha256:be178c0543eb17f5f3043021c9e5fcf30285e557a4fc309cce97ff9ca6182912"}, - }, - { - input: "localhost:8080/name@sha256:be178c0543eb17f5f3043021c9e5fcf30285e557a4fc309cce97ff9ca6182912", - match: true, - subs: []string{"localhost:8080/name", "", "sha256:be178c0543eb17f5f3043021c9e5fcf30285e557a4fc309cce97ff9ca6182912"}, - }, - { - input: "localhost:http/name@sha256:be178c0543eb17f5f3043021c9e5fcf30285e557a4fc309cce97ff9ca6182912", - match: false, - }, - { - // localhost will be treated as an image name without a host - input: "localhost@sha256:be178c0543eb17f5f3043021c9e5fcf30285e557a4fc309cce97ff9ca6182912", - match: true, - subs: []string{"localhost", "", "sha256:be178c0543eb17f5f3043021c9e5fcf30285e557a4fc309cce97ff9ca6182912"}, - }, - { - input: "registry.com:8080/myapp@bad", - match: false, - }, - { - input: "registry.com:8080/myapp@2bad", - match: false, // TODO(dmcgowan): Support this as valid - }, - } - - for i := range testcases { - checkRegexp(t, ReferenceRegexp, testcases[i]) - } - -} diff --git a/vendor/github.com/docker/distribution/registry.go b/vendor/github.com/docker/distribution/registry.go deleted file mode 100644 index 1ede31ebb..000000000 --- a/vendor/github.com/docker/distribution/registry.go +++ /dev/null @@ -1,97 +0,0 @@ -package distribution - -import ( - "github.com/docker/distribution/context" - "github.com/docker/distribution/reference" -) - -// Scope defines the set of items that match a namespace. -type Scope interface { - // Contains returns true if the name belongs to the namespace. - Contains(name string) bool -} - -type fullScope struct{} - -func (f fullScope) Contains(string) bool { - return true -} - -// GlobalScope represents the full namespace scope which contains -// all other scopes. -var GlobalScope = Scope(fullScope{}) - -// Namespace represents a collection of repositories, addressable by name. -// Generally, a namespace is backed by a set of one or more services, -// providing facilities such as registry access, trust, and indexing. -type Namespace interface { - // Scope describes the names that can be used with this Namespace. The - // global namespace will have a scope that matches all names. The scope - // effectively provides an identity for the namespace. - Scope() Scope - - // Repository should return a reference to the named repository. The - // registry may or may not have the repository but should always return a - // reference. - Repository(ctx context.Context, name reference.Named) (Repository, error) - - // Repositories fills 'repos' with a lexigraphically sorted catalog of repositories - // up to the size of 'repos' and returns the value 'n' for the number of entries - // which were filled. 'last' contains an offset in the catalog, and 'err' will be - // set to io.EOF if there are no more entries to obtain. - Repositories(ctx context.Context, repos []string, last string) (n int, err error) - - // Blobs returns a blob enumerator to access all blobs - Blobs() BlobEnumerator - - // BlobStatter returns a BlobStatter to control - BlobStatter() BlobStatter -} - -// RepositoryEnumerator describes an operation to enumerate repositories -type RepositoryEnumerator interface { - Enumerate(ctx context.Context, ingester func(string) error) error -} - -// ManifestServiceOption is a function argument for Manifest Service methods -type ManifestServiceOption interface { - Apply(ManifestService) error -} - -// WithTag allows a tag to be passed into Put -func WithTag(tag string) ManifestServiceOption { - return WithTagOption{tag} -} - -// WithTagOption holds a tag -type WithTagOption struct{ Tag string } - -// Apply conforms to the ManifestServiceOption interface -func (o WithTagOption) Apply(m ManifestService) error { - // no implementation - return nil -} - -// Repository is a named collection of manifests and layers. -type Repository interface { - // Named returns the name of the repository. - Named() reference.Named - - // Manifests returns a reference to this repository's manifest service. - // with the supplied options applied. - Manifests(ctx context.Context, options ...ManifestServiceOption) (ManifestService, error) - - // Blobs returns a reference to this repository's blob service. - Blobs(ctx context.Context) BlobStore - - // TODO(stevvooe): The above BlobStore return can probably be relaxed to - // be a BlobService for use with clients. This will allow such - // implementations to avoid implementing ServeBlob. - - // Tags returns a reference to this repositories tag service - Tags(ctx context.Context) TagService -} - -// TODO(stevvooe): Must add close methods to all these. May want to change the -// way instances are created to better reflect internal dependency -// relationships. diff --git a/vendor/github.com/docker/distribution/tags.go b/vendor/github.com/docker/distribution/tags.go deleted file mode 100644 index 503056596..000000000 --- a/vendor/github.com/docker/distribution/tags.go +++ /dev/null @@ -1,27 +0,0 @@ -package distribution - -import ( - "github.com/docker/distribution/context" -) - -// TagService provides access to information about tagged objects. -type TagService interface { - // Get retrieves the descriptor identified by the tag. Some - // implementations may differentiate between "trusted" tags and - // "untrusted" tags. If a tag is "untrusted", the mapping will be returned - // as an ErrTagUntrusted error, with the target descriptor. - Get(ctx context.Context, tag string) (Descriptor, error) - - // Tag associates the tag with the provided descriptor, updating the - // current association, if needed. - Tag(ctx context.Context, tag string, desc Descriptor) error - - // Untag removes the given tag association - Untag(ctx context.Context, tag string) error - - // All returns the set of tags managed by this tag service - All(ctx context.Context) ([]string, error) - - // Lookup returns the set of tags referencing the given digest. - Lookup(ctx context.Context, digest Descriptor) ([]string, error) -} diff --git a/vendor/github.com/emicklei/go-restful/.gitignore b/vendor/github.com/emicklei/go-restful/.gitignore deleted file mode 100644 index cece7be66..000000000 --- a/vendor/github.com/emicklei/go-restful/.gitignore +++ /dev/null @@ -1,70 +0,0 @@ -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe - -restful.html - -*.out - -tmp.prof - -go-restful.test - -examples/restful-basic-authentication - -examples/restful-encoding-filter - -examples/restful-filters - -examples/restful-hello-world - -examples/restful-resource-functions - -examples/restful-serve-static - -examples/restful-user-service - -*.DS_Store -examples/restful-user-resource - -examples/restful-multi-containers - -examples/restful-form-handling - -examples/restful-CORS-filter - -examples/restful-options-filter - -examples/restful-curly-router - -examples/restful-cpuprofiler-service - -examples/restful-pre-post-filters - -curly.prof - -examples/restful-NCSA-logging - -examples/restful-html-template - -s.html -restful-path-tail diff --git a/vendor/github.com/emicklei/go-restful/CHANGES.md b/vendor/github.com/emicklei/go-restful/CHANGES.md deleted file mode 100644 index 45bd20129..000000000 --- a/vendor/github.com/emicklei/go-restful/CHANGES.md +++ /dev/null @@ -1,159 +0,0 @@ -Change history of go-restful -= -2015-09-27 -- rename new WriteStatusAnd... to WriteHeaderAnd... for consistency - -2015-09-25 -- fixed problem with changing Header after WriteHeader (issue 235) - -2015-09-14 -- changed behavior of WriteHeader (immediate write) and WriteEntity (no status write) -- added support for custom EntityReaderWriters. - -2015-08-06 -- add support for reading entities from compressed request content -- use sync.Pool for compressors of http response and request body -- add Description to Parameter for documentation in Swagger UI - -2015-03-20 -- add configurable logging - -2015-03-18 -- if not specified, the Operation is derived from the Route function - -2015-03-17 -- expose Parameter creation functions -- make trace logger an interface -- fix OPTIONSFilter -- customize rendering of ServiceError -- JSR311 router now handles wildcards -- add Notes to Route - -2014-11-27 -- (api add) PrettyPrint per response. (as proposed in #167) - -2014-11-12 -- (api add) ApiVersion(.) for documentation in Swagger UI - -2014-11-10 -- (api change) struct fields tagged with "description" show up in Swagger UI - -2014-10-31 -- (api change) ReturnsError -> Returns -- (api add) RouteBuilder.Do(aBuilder) for DRY use of RouteBuilder -- fix swagger nested structs -- sort Swagger response messages by code - -2014-10-23 -- (api add) ReturnsError allows you to document Http codes in swagger -- fixed problem with greedy CurlyRouter -- (api add) Access-Control-Max-Age in CORS -- add tracing functionality (injectable) for debugging purposes -- support JSON parse 64bit int -- fix empty parameters for swagger -- WebServicesUrl is now optional for swagger -- fixed duplicate AccessControlAllowOrigin in CORS -- (api change) expose ServeMux in container -- (api add) added AllowedDomains in CORS -- (api add) ParameterNamed for detailed documentation - -2014-04-16 -- (api add) expose constructor of Request for testing. - -2014-06-27 -- (api add) ParameterNamed gives access to a Parameter definition and its data (for further specification). -- (api add) SetCacheReadEntity allow scontrol over whether or not the request body is being cached (default true for compatibility reasons). - -2014-07-03 -- (api add) CORS can be configured with a list of allowed domains - -2014-03-12 -- (api add) Route path parameters can use wildcard or regular expressions. (requires CurlyRouter) - -2014-02-26 -- (api add) Request now provides information about the matched Route, see method SelectedRoutePath - -2014-02-17 -- (api change) renamed parameter constants (go-lint checks) - -2014-01-10 - - (api add) support for CloseNotify, see http://golang.org/pkg/net/http/#CloseNotifier - -2014-01-07 - - (api change) Write* methods in Response now return the error or nil. - - added example of serving HTML from a Go template. - - fixed comparing Allowed headers in CORS (is now case-insensitive) - -2013-11-13 - - (api add) Response knows how many bytes are written to the response body. - -2013-10-29 - - (api add) RecoverHandler(handler RecoverHandleFunction) to change how panic recovery is handled. Default behavior is to log and return a stacktrace. This may be a security issue as it exposes sourcecode information. - -2013-10-04 - - (api add) Response knows what HTTP status has been written - - (api add) Request can have attributes (map of string->interface, also called request-scoped variables - -2013-09-12 - - (api change) Router interface simplified - - Implemented CurlyRouter, a Router that does not use|allow regular expressions in paths - -2013-08-05 - - add OPTIONS support - - add CORS support - -2013-08-27 - - fixed some reported issues (see github) - - (api change) deprecated use of WriteError; use WriteErrorString instead - -2014-04-15 - - (fix) v1.0.1 tag: fix Issue 111: WriteErrorString - -2013-08-08 - - (api add) Added implementation Container: a WebServices collection with its own http.ServeMux allowing multiple endpoints per program. Existing uses of go-restful will register their services to the DefaultContainer. - - (api add) the swagger package has be extended to have a UI per container. - - if panic is detected then a small stack trace is printed (thanks to runner-mei) - - (api add) WriteErrorString to Response - -Important API changes: - - - (api remove) package variable DoNotRecover no longer works ; use restful.DefaultContainer.DoNotRecover(true) instead. - - (api remove) package variable EnableContentEncoding no longer works ; use restful.DefaultContainer.EnableContentEncoding(true) instead. - - -2013-07-06 - - - (api add) Added support for response encoding (gzip and deflate(zlib)). This feature is disabled on default (for backwards compatibility). Use restful.EnableContentEncoding = true in your initialization to enable this feature. - -2013-06-19 - - - (improve) DoNotRecover option, moved request body closer, improved ReadEntity - -2013-06-03 - - - (api change) removed Dispatcher interface, hide PathExpression - - changed receiver names of type functions to be more idiomatic Go - -2013-06-02 - - - (optimize) Cache the RegExp compilation of Paths. - -2013-05-22 - - - (api add) Added support for request/response filter functions - -2013-05-18 - - - - (api add) Added feature to change the default Http Request Dispatch function (travis cline) - - (api change) Moved Swagger Webservice to swagger package (see example restful-user) - -[2012-11-14 .. 2013-05-18> - - - See https://github.com/emicklei/go-restful/commits - -2012-11-14 - - - Initial commit - - diff --git a/vendor/github.com/emicklei/go-restful/README.md b/vendor/github.com/emicklei/go-restful/README.md deleted file mode 100644 index 8f954c016..000000000 --- a/vendor/github.com/emicklei/go-restful/README.md +++ /dev/null @@ -1,74 +0,0 @@ -go-restful -========== - -package for building REST-style Web Services using Google Go - -REST asks developers to use HTTP methods explicitly and in a way that's consistent with the protocol definition. This basic REST design principle establishes a one-to-one mapping between create, read, update, and delete (CRUD) operations and HTTP methods. According to this mapping: - -- GET = Retrieve a representation of a resource -- POST = Create if you are sending content to the server to create a subordinate of the specified resource collection, using some server-side algorithm. -- PUT = Create if you are sending the full content of the specified resource (URI). -- PUT = Update if you are updating the full content of the specified resource. -- DELETE = Delete if you are requesting the server to delete the resource -- PATCH = Update partial content of a resource -- OPTIONS = Get information about the communication options for the request URI - -### Example - -```Go -ws := new(restful.WebService) -ws. - Path("/users"). - Consumes(restful.MIME_XML, restful.MIME_JSON). - Produces(restful.MIME_JSON, restful.MIME_XML) - -ws.Route(ws.GET("/{user-id}").To(u.findUser). - Doc("get a user"). - Param(ws.PathParameter("user-id", "identifier of the user").DataType("string")). - Writes(User{})) -... - -func (u UserResource) findUser(request *restful.Request, response *restful.Response) { - id := request.PathParameter("user-id") - ... -} -``` - -[Full API of a UserResource](https://github.com/emicklei/go-restful/tree/master/examples/restful-user-resource.go) - -### Features - -- Routes for request → function mapping with path parameter (e.g. {id}) support -- Configurable router: - - Routing algorithm after [JSR311](http://jsr311.java.net/nonav/releases/1.1/spec/spec.html) that is implemented using (but doest **not** accept) regular expressions (See RouterJSR311 which is used by default) - - Fast routing algorithm that allows static elements, regular expressions and dynamic parameters in the URL path (e.g. /meetings/{id} or /static/{subpath:*}, See CurlyRouter) -- Request API for reading structs from JSON/XML and accesing parameters (path,query,header) -- Response API for writing structs to JSON/XML and setting headers -- Filters for intercepting the request → response flow on Service or Route level -- Request-scoped variables using attributes -- Containers for WebServices on different HTTP endpoints -- Content encoding (gzip,deflate) of request and response payloads -- Automatic responses on OPTIONS (using a filter) -- Automatic CORS request handling (using a filter) -- API declaration for Swagger UI (see swagger package) -- Panic recovery to produce HTTP 500, customizable using RecoverHandler(...) -- Route errors produce HTTP 404/405/406/415 errors, customizable using ServiceErrorHandler(...) -- Configurable (trace) logging -- Customizable encoding using EntityReaderWriter registration -- Customizable gzip/deflate readers and writers using CompressorProvider registration - -### Resources - -- [Documentation on godoc.org](http://godoc.org/github.com/emicklei/go-restful) -- [Code examples](https://github.com/emicklei/go-restful/tree/master/examples) -- [Example posted on blog](http://ernestmicklei.com/2012/11/24/go-restful-first-working-example/) -- [Design explained on blog](http://ernestmicklei.com/2012/11/11/go-restful-api-design/) -- [sourcegraph](https://sourcegraph.com/github.com/emicklei/go-restful) -- [gopkg.in](https://gopkg.in/emicklei/go-restful.v1) -- [showcase: Mora - MongoDB REST Api server](https://github.com/emicklei/mora) - -[![Build Status](https://drone.io/github.com/emicklei/go-restful/status.png)](https://drone.io/github.com/emicklei/go-restful/latest) - -(c) 2012 - 2015, http://ernestmicklei.com. MIT License - -Type ```git shortlog -s``` for a full list of contributors. \ No newline at end of file diff --git a/vendor/github.com/emicklei/go-restful/Srcfile b/vendor/github.com/emicklei/go-restful/Srcfile deleted file mode 100644 index 16fd18689..000000000 --- a/vendor/github.com/emicklei/go-restful/Srcfile +++ /dev/null @@ -1 +0,0 @@ -{"SkipDirs": ["examples"]} diff --git a/vendor/github.com/emicklei/go-restful/bench_curly_test.go b/vendor/github.com/emicklei/go-restful/bench_curly_test.go deleted file mode 100644 index db6a1a752..000000000 --- a/vendor/github.com/emicklei/go-restful/bench_curly_test.go +++ /dev/null @@ -1,51 +0,0 @@ -package restful - -import ( - "fmt" - "net/http" - "net/http/httptest" - "testing" -) - -func setupCurly(container *Container) []string { - wsCount := 26 - rtCount := 26 - urisCurly := []string{} - - container.Router(CurlyRouter{}) - for i := 0; i < wsCount; i++ { - root := fmt.Sprintf("/%s/{%s}/", string(i+97), string(i+97)) - ws := new(WebService).Path(root) - for j := 0; j < rtCount; j++ { - sub := fmt.Sprintf("/%s2/{%s2}", string(j+97), string(j+97)) - ws.Route(ws.GET(sub).Consumes("application/xml").Produces("application/xml").To(echoCurly)) - } - container.Add(ws) - for _, each := range ws.Routes() { - urisCurly = append(urisCurly, "http://bench.com"+each.Path) - } - } - return urisCurly -} - -func echoCurly(req *Request, resp *Response) {} - -func BenchmarkManyCurly(b *testing.B) { - container := NewContainer() - urisCurly := setupCurly(container) - b.ResetTimer() - for t := 0; t < b.N; t++ { - for r := 0; r < 1000; r++ { - for _, each := range urisCurly { - sendNoReturnTo(each, container, t) - } - } - } -} - -func sendNoReturnTo(address string, container *Container, t int) { - httpRequest, _ := http.NewRequest("GET", address, nil) - httpRequest.Header.Set("Accept", "application/xml") - httpWriter := httptest.NewRecorder() - container.dispatch(httpWriter, httpRequest) -} diff --git a/vendor/github.com/emicklei/go-restful/bench_test.go b/vendor/github.com/emicklei/go-restful/bench_test.go deleted file mode 100644 index 3e77c2d29..000000000 --- a/vendor/github.com/emicklei/go-restful/bench_test.go +++ /dev/null @@ -1,43 +0,0 @@ -package restful - -import ( - "fmt" - "io" - "testing" -) - -var uris = []string{} - -func setup(container *Container) { - wsCount := 26 - rtCount := 26 - - for i := 0; i < wsCount; i++ { - root := fmt.Sprintf("/%s/{%s}/", string(i+97), string(i+97)) - ws := new(WebService).Path(root) - for j := 0; j < rtCount; j++ { - sub := fmt.Sprintf("/%s2/{%s2}", string(j+97), string(j+97)) - ws.Route(ws.GET(sub).To(echo)) - } - container.Add(ws) - for _, each := range ws.Routes() { - uris = append(uris, "http://bench.com"+each.Path) - } - } -} - -func echo(req *Request, resp *Response) { - io.WriteString(resp.ResponseWriter, "echo") -} - -func BenchmarkMany(b *testing.B) { - container := NewContainer() - setup(container) - b.ResetTimer() - for t := 0; t < b.N; t++ { - for _, each := range uris { - // println(each) - sendItTo(each, container) - } - } -} diff --git a/vendor/github.com/emicklei/go-restful/bench_test.sh b/vendor/github.com/emicklei/go-restful/bench_test.sh deleted file mode 100644 index 47ffbe4ac..000000000 --- a/vendor/github.com/emicklei/go-restful/bench_test.sh +++ /dev/null @@ -1,10 +0,0 @@ -#go test -run=none -file bench_test.go -test.bench . -cpuprofile=bench_test.out - -go test -c -./go-restful.test -test.run=none -test.cpuprofile=tmp.prof -test.bench=BenchmarkMany -./go-restful.test -test.run=none -test.cpuprofile=curly.prof -test.bench=BenchmarkManyCurly - -#go tool pprof go-restful.test tmp.prof -go tool pprof go-restful.test curly.prof - - diff --git a/vendor/github.com/emicklei/go-restful/compress_test.go b/vendor/github.com/emicklei/go-restful/compress_test.go deleted file mode 100644 index 84a93c3fc..000000000 --- a/vendor/github.com/emicklei/go-restful/compress_test.go +++ /dev/null @@ -1,127 +0,0 @@ -package restful - -import ( - "bytes" - "compress/gzip" - "compress/zlib" - "io" - "io/ioutil" - "net/http" - "net/http/httptest" - "testing" -) - -// go test -v -test.run TestGzip ...restful -func TestGzip(t *testing.T) { - EnableContentEncoding = true - httpRequest, _ := http.NewRequest("GET", "/test", nil) - httpRequest.Header.Set("Accept-Encoding", "gzip,deflate") - httpWriter := httptest.NewRecorder() - wanted, encoding := wantsCompressedResponse(httpRequest) - if !wanted { - t.Fatal("should accept gzip") - } - if encoding != "gzip" { - t.Fatal("expected gzip") - } - c, err := NewCompressingResponseWriter(httpWriter, encoding) - if err != nil { - t.Fatal(err.Error()) - } - c.Write([]byte("Hello World")) - c.Close() - if httpWriter.Header().Get("Content-Encoding") != "gzip" { - t.Fatal("Missing gzip header") - } - reader, err := gzip.NewReader(httpWriter.Body) - if err != nil { - t.Fatal(err.Error()) - } - data, err := ioutil.ReadAll(reader) - if err != nil { - t.Fatal(err.Error()) - } - if got, want := string(data), "Hello World"; got != want { - t.Errorf("got %v want %v", got, want) - } -} - -func TestDeflate(t *testing.T) { - EnableContentEncoding = true - httpRequest, _ := http.NewRequest("GET", "/test", nil) - httpRequest.Header.Set("Accept-Encoding", "deflate,gzip") - httpWriter := httptest.NewRecorder() - wanted, encoding := wantsCompressedResponse(httpRequest) - if !wanted { - t.Fatal("should accept deflate") - } - if encoding != "deflate" { - t.Fatal("expected deflate") - } - c, err := NewCompressingResponseWriter(httpWriter, encoding) - if err != nil { - t.Fatal(err.Error()) - } - c.Write([]byte("Hello World")) - c.Close() - if httpWriter.Header().Get("Content-Encoding") != "deflate" { - t.Fatal("Missing deflate header") - } - reader, err := zlib.NewReader(httpWriter.Body) - if err != nil { - t.Fatal(err.Error()) - } - data, err := ioutil.ReadAll(reader) - if err != nil { - t.Fatal(err.Error()) - } - if got, want := string(data), "Hello World"; got != want { - t.Errorf("got %v want %v", got, want) - } -} - -func TestGzipDecompressRequestBody(t *testing.T) { - b := new(bytes.Buffer) - w := newGzipWriter() - w.Reset(b) - io.WriteString(w, `{"msg":"hi"}`) - w.Flush() - w.Close() - - req := new(Request) - httpRequest, _ := http.NewRequest("GET", "/", bytes.NewReader(b.Bytes())) - httpRequest.Header.Set("Content-Type", "application/json") - httpRequest.Header.Set("Content-Encoding", "gzip") - req.Request = httpRequest - - doCacheReadEntityBytes = false - doc := make(map[string]interface{}) - req.ReadEntity(&doc) - - if got, want := doc["msg"], "hi"; got != want { - t.Errorf("got %v want %v", got, want) - } -} - -func TestZlibDecompressRequestBody(t *testing.T) { - b := new(bytes.Buffer) - w := newZlibWriter() - w.Reset(b) - io.WriteString(w, `{"msg":"hi"}`) - w.Flush() - w.Close() - - req := new(Request) - httpRequest, _ := http.NewRequest("GET", "/", bytes.NewReader(b.Bytes())) - httpRequest.Header.Set("Content-Type", "application/json") - httpRequest.Header.Set("Content-Encoding", "deflate") - req.Request = httpRequest - - doCacheReadEntityBytes = false - doc := make(map[string]interface{}) - req.ReadEntity(&doc) - - if got, want := doc["msg"], "hi"; got != want { - t.Errorf("got %v want %v", got, want) - } -} diff --git a/vendor/github.com/emicklei/go-restful/container_test.go b/vendor/github.com/emicklei/go-restful/container_test.go deleted file mode 100644 index dd2552c37..000000000 --- a/vendor/github.com/emicklei/go-restful/container_test.go +++ /dev/null @@ -1,61 +0,0 @@ -package restful - -import ( - "net/http" - "net/http/httptest" - "testing" -) - -// go test -v -test.run TestContainer_computeAllowedMethods ...restful -func TestContainer_computeAllowedMethods(t *testing.T) { - wc := NewContainer() - ws1 := new(WebService).Path("/users") - ws1.Route(ws1.GET("{i}").To(dummy)) - ws1.Route(ws1.POST("{i}").To(dummy)) - wc.Add(ws1) - httpRequest, _ := http.NewRequest("GET", "http://api.his.com/users/1", nil) - rreq := Request{Request: httpRequest} - m := wc.computeAllowedMethods(&rreq) - if len(m) != 2 { - t.Errorf("got %d expected 2 methods, %v", len(m), m) - } -} - -func TestContainer_HandleWithFilter(t *testing.T) { - prefilterCalled := false - postfilterCalled := false - httpHandlerCalled := false - - wc := NewContainer() - wc.Filter(func(request *Request, response *Response, chain *FilterChain) { - prefilterCalled = true - chain.ProcessFilter(request, response) - }) - wc.HandleWithFilter("/", http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - httpHandlerCalled = true - w.Write([]byte("ok")) - })) - wc.Filter(func(request *Request, response *Response, chain *FilterChain) { - postfilterCalled = true - chain.ProcessFilter(request, response) - }) - - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("GET", "/", nil) - wc.ServeHTTP(recorder, request) - if recorder.Code != http.StatusOK { - t.Errorf("unexpected code %d", recorder.Code) - } - if recorder.Body.String() != "ok" { - t.Errorf("unexpected body %s", recorder.Body.String()) - } - if !prefilterCalled { - t.Errorf("filter added before calling HandleWithFilter wasn't called") - } - if !postfilterCalled { - t.Errorf("filter added after calling HandleWithFilter wasn't called") - } - if !httpHandlerCalled { - t.Errorf("handler added by calling HandleWithFilter wasn't called") - } -} diff --git a/vendor/github.com/emicklei/go-restful/cors_filter_test.go b/vendor/github.com/emicklei/go-restful/cors_filter_test.go deleted file mode 100644 index 9b4723089..000000000 --- a/vendor/github.com/emicklei/go-restful/cors_filter_test.go +++ /dev/null @@ -1,125 +0,0 @@ -package restful - -import ( - "net/http" - "net/http/httptest" - "testing" -) - -// go test -v -test.run TestCORSFilter_Preflight ...restful -// http://www.html5rocks.com/en/tutorials/cors/#toc-handling-a-not-so-simple-request -func TestCORSFilter_Preflight(t *testing.T) { - tearDown() - ws := new(WebService) - ws.Route(ws.PUT("/cors").To(dummy)) - Add(ws) - - cors := CrossOriginResourceSharing{ - ExposeHeaders: []string{"X-Custom-Header"}, - AllowedHeaders: []string{"X-Custom-Header", "X-Additional-Header"}, - CookiesAllowed: true, - Container: DefaultContainer} - Filter(cors.Filter) - - // Preflight - httpRequest, _ := http.NewRequest("OPTIONS", "http://api.alice.com/cors", nil) - httpRequest.Method = "OPTIONS" - httpRequest.Header.Set(HEADER_Origin, "http://api.bob.com") - httpRequest.Header.Set(HEADER_AccessControlRequestMethod, "PUT") - httpRequest.Header.Set(HEADER_AccessControlRequestHeaders, "X-Custom-Header, X-Additional-Header") - - httpWriter := httptest.NewRecorder() - DefaultContainer.dispatch(httpWriter, httpRequest) - - actual := httpWriter.Header().Get(HEADER_AccessControlAllowOrigin) - if "http://api.bob.com" != actual { - t.Fatal("expected: http://api.bob.com but got:" + actual) - } - actual = httpWriter.Header().Get(HEADER_AccessControlAllowMethods) - if "PUT" != actual { - t.Fatal("expected: PUT but got:" + actual) - } - actual = httpWriter.Header().Get(HEADER_AccessControlAllowHeaders) - if "X-Custom-Header, X-Additional-Header" != actual { - t.Fatal("expected: X-Custom-Header, X-Additional-Header but got:" + actual) - } - - if !cors.isOriginAllowed("somewhere") { - t.Fatal("origin expected to be allowed") - } - cors.AllowedDomains = []string{"overthere.com"} - if cors.isOriginAllowed("somewhere") { - t.Fatal("origin [somewhere] expected NOT to be allowed") - } - if !cors.isOriginAllowed("overthere.com") { - t.Fatal("origin [overthere] expected to be allowed") - } - -} - -// go test -v -test.run TestCORSFilter_Actual ...restful -// http://www.html5rocks.com/en/tutorials/cors/#toc-handling-a-not-so-simple-request -func TestCORSFilter_Actual(t *testing.T) { - tearDown() - ws := new(WebService) - ws.Route(ws.PUT("/cors").To(dummy)) - Add(ws) - - cors := CrossOriginResourceSharing{ - ExposeHeaders: []string{"X-Custom-Header"}, - AllowedHeaders: []string{"X-Custom-Header", "X-Additional-Header"}, - CookiesAllowed: true, - Container: DefaultContainer} - Filter(cors.Filter) - - // Actual - httpRequest, _ := http.NewRequest("PUT", "http://api.alice.com/cors", nil) - httpRequest.Header.Set(HEADER_Origin, "http://api.bob.com") - httpRequest.Header.Set("X-Custom-Header", "value") - - httpWriter := httptest.NewRecorder() - DefaultContainer.dispatch(httpWriter, httpRequest) - actual := httpWriter.Header().Get(HEADER_AccessControlAllowOrigin) - if "http://api.bob.com" != actual { - t.Fatal("expected: http://api.bob.com but got:" + actual) - } - if httpWriter.Body.String() != "dummy" { - t.Fatal("expected: dummy but got:" + httpWriter.Body.String()) - } -} - -var allowedDomainInput = []struct { - domains []string - origin string - accepted bool -}{ - {[]string{}, "http://anything.com", true}, -} - -// go test -v -test.run TestCORSFilter_AllowedDomains ...restful -func TestCORSFilter_AllowedDomains(t *testing.T) { - for _, each := range allowedDomainInput { - tearDown() - ws := new(WebService) - ws.Route(ws.PUT("/cors").To(dummy)) - Add(ws) - - cors := CrossOriginResourceSharing{ - AllowedDomains: each.domains, - CookiesAllowed: true, - Container: DefaultContainer} - Filter(cors.Filter) - - httpRequest, _ := http.NewRequest("PUT", "http://api.his.com/cors", nil) - httpRequest.Header.Set(HEADER_Origin, each.origin) - httpWriter := httptest.NewRecorder() - DefaultContainer.dispatch(httpWriter, httpRequest) - actual := httpWriter.Header().Get(HEADER_AccessControlAllowOrigin) - if actual != each.origin && each.accepted { - t.Fatal("expected to be accepted") - } - if actual == each.origin && !each.accepted { - t.Fatal("did not expect to be accepted") - } - } -} diff --git a/vendor/github.com/emicklei/go-restful/coverage.sh b/vendor/github.com/emicklei/go-restful/coverage.sh deleted file mode 100644 index e27dbf1a9..000000000 --- a/vendor/github.com/emicklei/go-restful/coverage.sh +++ /dev/null @@ -1,2 +0,0 @@ -go test -coverprofile=coverage.out -go tool cover -html=coverage.out \ No newline at end of file diff --git a/vendor/github.com/emicklei/go-restful/curly_test.go b/vendor/github.com/emicklei/go-restful/curly_test.go deleted file mode 100644 index 31d66dcbd..000000000 --- a/vendor/github.com/emicklei/go-restful/curly_test.go +++ /dev/null @@ -1,231 +0,0 @@ -package restful - -import ( - "io" - "net/http" - "testing" -) - -var requestPaths = []struct { - // url with path (1) is handled by service with root (2) and remainder has value final (3) - path, root string -}{ - {"/", "/"}, - {"/p", "/p"}, - {"/p/x", "/p/{q}"}, - {"/q/x", "/q"}, - {"/p/x/", "/p/{q}"}, - {"/p/x/y", "/p/{q}"}, - {"/q/x/y", "/q"}, - {"/z/q", "/{p}/q"}, - {"/a/b/c/q", "/"}, -} - -// go test -v -test.run TestCurlyDetectWebService ...restful -func TestCurlyDetectWebService(t *testing.T) { - ws1 := new(WebService).Path("/") - ws2 := new(WebService).Path("/p") - ws3 := new(WebService).Path("/q") - ws4 := new(WebService).Path("/p/q") - ws5 := new(WebService).Path("/p/{q}") - ws7 := new(WebService).Path("/{p}/q") - var wss = []*WebService{ws1, ws2, ws3, ws4, ws5, ws7} - - for _, each := range wss { - t.Logf("path=%s,toks=%v\n", each.pathExpr.Source, each.pathExpr.tokens) - } - - router := CurlyRouter{} - - ok := true - for i, fixture := range requestPaths { - requestTokens := tokenizePath(fixture.path) - who := router.detectWebService(requestTokens, wss) - if who != nil && who.RootPath() != fixture.root { - t.Logf("[line:%v] Unexpected dispatcher, expected:%v, actual:%v", i, fixture.root, who.RootPath()) - ok = false - } - } - if !ok { - t.Fail() - } -} - -var serviceDetects = []struct { - path string - found bool - root string -}{ - {"/a/b", true, "/{p}/{q}/{r}"}, - {"/p/q", true, "/p/q"}, - {"/q/p", true, "/q"}, - {"/", true, "/"}, - {"/p/q/r", true, "/p/q"}, -} - -// go test -v -test.run Test_detectWebService ...restful -func Test_detectWebService(t *testing.T) { - router := CurlyRouter{} - ws1 := new(WebService).Path("/") - ws2 := new(WebService).Path("/p") - ws3 := new(WebService).Path("/q") - ws4 := new(WebService).Path("/p/q") - ws5 := new(WebService).Path("/p/{q}") - ws6 := new(WebService).Path("/p/{q}/") - ws7 := new(WebService).Path("/{p}/q") - ws8 := new(WebService).Path("/{p}/{q}/{r}") - var wss = []*WebService{ws8, ws7, ws6, ws5, ws4, ws3, ws2, ws1} - for _, fix := range serviceDetects { - requestPath := fix.path - requestTokens := tokenizePath(requestPath) - for _, ws := range wss { - serviceTokens := ws.pathExpr.tokens - matches, score := router.computeWebserviceScore(requestTokens, serviceTokens) - t.Logf("req=%s,toks:%v,ws=%s,toks:%v,score=%d,matches=%v", requestPath, requestTokens, ws.RootPath(), serviceTokens, score, matches) - } - best := router.detectWebService(requestTokens, wss) - if best != nil { - if fix.found { - t.Logf("best=%s", best.RootPath()) - } else { - t.Fatalf("should have found:%s", fix.root) - } - } - } -} - -var routeMatchers = []struct { - route string - path string - matches bool - paramCount int - staticCount int -}{ - // route, request-path - {"/a", "/a", true, 0, 1}, - {"/a", "/b", false, 0, 0}, - {"/a", "/b", false, 0, 0}, - {"/a/{b}/c/", "/a/2/c", true, 1, 2}, - {"/{a}/{b}/{c}/", "/a/b", false, 0, 0}, - {"/{x:*}", "/", false, 0, 0}, - {"/{x:*}", "/a", true, 1, 0}, - {"/{x:*}", "/a/b", true, 1, 0}, - {"/a/{x:*}", "/a/b", true, 1, 1}, - {"/a/{x:[A-Z][A-Z]}", "/a/ZX", true, 1, 1}, - {"/basepath/{resource:*}", "/basepath/some/other/location/test.xml", true, 1, 1}, -} - -// clear && go test -v -test.run Test_matchesRouteByPathTokens ...restful -func Test_matchesRouteByPathTokens(t *testing.T) { - router := CurlyRouter{} - for i, each := range routeMatchers { - routeToks := tokenizePath(each.route) - reqToks := tokenizePath(each.path) - matches, pCount, sCount := router.matchesRouteByPathTokens(routeToks, reqToks) - if matches != each.matches { - t.Fatalf("[%d] unexpected matches outcome route:%s, path:%s, matches:%v", i, each.route, each.path, matches) - } - if pCount != each.paramCount { - t.Fatalf("[%d] unexpected paramCount got:%d want:%d ", i, pCount, each.paramCount) - } - if sCount != each.staticCount { - t.Fatalf("[%d] unexpected staticCount got:%d want:%d ", i, sCount, each.staticCount) - } - } -} - -// clear && go test -v -test.run TestExtractParameters_Wildcard1 ...restful -func TestExtractParameters_Wildcard1(t *testing.T) { - params := doExtractParams("/fixed/{var:*}", 2, "/fixed/remainder", t) - if params["var"] != "remainder" { - t.Errorf("parameter mismatch var: %s", params["var"]) - } -} - -// clear && go test -v -test.run TestExtractParameters_Wildcard2 ...restful -func TestExtractParameters_Wildcard2(t *testing.T) { - params := doExtractParams("/fixed/{var:*}", 2, "/fixed/remain/der", t) - if params["var"] != "remain/der" { - t.Errorf("parameter mismatch var: %s", params["var"]) - } -} - -// clear && go test -v -test.run TestExtractParameters_Wildcard3 ...restful -func TestExtractParameters_Wildcard3(t *testing.T) { - params := doExtractParams("/static/{var:*}", 2, "/static/test/sub/hi.html", t) - if params["var"] != "test/sub/hi.html" { - t.Errorf("parameter mismatch var: %s", params["var"]) - } -} - -// clear && go test -v -test.run TestCurly_ISSUE_34 ...restful -func TestCurly_ISSUE_34(t *testing.T) { - ws1 := new(WebService).Path("/") - ws1.Route(ws1.GET("/{type}/{id}").To(curlyDummy)) - ws1.Route(ws1.GET("/network/{id}").To(curlyDummy)) - routes := CurlyRouter{}.selectRoutes(ws1, tokenizePath("/network/12")) - if len(routes) != 2 { - t.Fatal("expected 2 routes") - } - if routes[0].Path != "/network/{id}" { - t.Error("first is", routes[0].Path) - } -} - -// clear && go test -v -test.run TestCurly_ISSUE_34_2 ...restful -func TestCurly_ISSUE_34_2(t *testing.T) { - ws1 := new(WebService) - ws1.Route(ws1.GET("/network/{id}").To(curlyDummy)) - ws1.Route(ws1.GET("/{type}/{id}").To(curlyDummy)) - routes := CurlyRouter{}.selectRoutes(ws1, tokenizePath("/network/12")) - if len(routes) != 2 { - t.Fatal("expected 2 routes") - } - if routes[0].Path != "/network/{id}" { - t.Error("first is", routes[0].Path) - } -} - -// clear && go test -v -test.run TestCurly_JsonHtml ...restful -func TestCurly_JsonHtml(t *testing.T) { - ws1 := new(WebService) - ws1.Path("/") - ws1.Route(ws1.GET("/some.html").To(curlyDummy).Consumes("*/*").Produces("text/html")) - req, _ := http.NewRequest("GET", "/some.html", nil) - req.Header.Set("Accept", "application/json") - _, route, err := CurlyRouter{}.SelectRoute([]*WebService{ws1}, req) - if err == nil { - t.Error("error expected") - } - if route != nil { - t.Error("no route expected") - } -} - -// go test -v -test.run TestCurly_ISSUE_137 ...restful -func TestCurly_ISSUE_137(t *testing.T) { - ws1 := new(WebService) - ws1.Route(ws1.GET("/hello").To(curlyDummy)) - ws1.Path("/") - req, _ := http.NewRequest("GET", "/", nil) - _, route, _ := CurlyRouter{}.SelectRoute([]*WebService{ws1}, req) - t.Log(route) - if route != nil { - t.Error("no route expected") - } -} - -// go test -v -test.run TestCurly_ISSUE_137_2 ...restful -func TestCurly_ISSUE_137_2(t *testing.T) { - ws1 := new(WebService) - ws1.Route(ws1.GET("/hello").To(curlyDummy)) - ws1.Path("/") - req, _ := http.NewRequest("GET", "/hello/bob", nil) - _, route, _ := CurlyRouter{}.SelectRoute([]*WebService{ws1}, req) - t.Log(route) - if route != nil { - t.Errorf("no route expected, got %v", route) - } -} - -func curlyDummy(req *Request, resp *Response) { io.WriteString(resp.ResponseWriter, "curlyDummy") } diff --git a/vendor/github.com/emicklei/go-restful/doc_examples_test.go b/vendor/github.com/emicklei/go-restful/doc_examples_test.go deleted file mode 100644 index 0af636e55..000000000 --- a/vendor/github.com/emicklei/go-restful/doc_examples_test.go +++ /dev/null @@ -1,41 +0,0 @@ -package restful - -import "net/http" - -func ExampleOPTIONSFilter() { - // Install the OPTIONS filter on the default Container - Filter(OPTIONSFilter()) -} -func ExampleContainer_OPTIONSFilter() { - // Install the OPTIONS filter on a Container - myContainer := new(Container) - myContainer.Filter(myContainer.OPTIONSFilter) -} - -func ExampleContainer() { - // The Default container of go-restful uses the http.DefaultServeMux. - // You can create your own Container using restful.NewContainer() and create a new http.Server for that particular container - - ws := new(WebService) - wsContainer := NewContainer() - wsContainer.Add(ws) - server := &http.Server{Addr: ":8080", Handler: wsContainer} - server.ListenAndServe() -} - -func ExampleCrossOriginResourceSharing() { - // To install this filter on the Default Container use: - cors := CrossOriginResourceSharing{ExposeHeaders: []string{"X-My-Header"}, CookiesAllowed: false, Container: DefaultContainer} - Filter(cors.Filter) -} - -func ExampleServiceError() { - resp := new(Response) - resp.WriteEntity(NewError(http.StatusBadRequest, "Non-integer {id} path parameter")) -} - -func ExampleBoundedCachedCompressors() { - // Register a compressor provider (gzip/deflate read/write) that uses - // a bounded cache with a maximum of 20 writers and 20 readers. - SetCompressorProvider(NewBoundedCachedCompressors(20, 20)) -} diff --git a/vendor/github.com/emicklei/go-restful/entity_accessors_test.go b/vendor/github.com/emicklei/go-restful/entity_accessors_test.go deleted file mode 100644 index 943093ae0..000000000 --- a/vendor/github.com/emicklei/go-restful/entity_accessors_test.go +++ /dev/null @@ -1,69 +0,0 @@ -package restful - -import ( - "bytes" - "fmt" - "io" - "net/http" - "net/http/httptest" - "reflect" - "testing" -) - -type keyvalue struct { - readCalled bool - writeCalled bool -} - -func (kv *keyvalue) Read(req *Request, v interface{}) error { - //t := reflect.TypeOf(v) - //rv := reflect.ValueOf(v) - kv.readCalled = true - return nil -} - -func (kv *keyvalue) Write(resp *Response, status int, v interface{}) error { - t := reflect.TypeOf(v) - rv := reflect.ValueOf(v) - for ix := 0; ix < t.NumField(); ix++ { - sf := t.Field(ix) - io.WriteString(resp, sf.Name) - io.WriteString(resp, "=") - io.WriteString(resp, fmt.Sprintf("%v\n", rv.Field(ix).Interface())) - } - kv.writeCalled = true - return nil -} - -// go test -v -test.run TestKeyValueEncoding ...restful -func TestKeyValueEncoding(t *testing.T) { - type Book struct { - Title string - Author string - PublishedYear int - } - kv := new(keyvalue) - RegisterEntityAccessor("application/kv", kv) - b := Book{"Singing for Dummies", "john doe", 2015} - - // Write - httpWriter := httptest.NewRecorder() - // Accept Produces - resp := Response{httpWriter, "application/kv,*/*;q=0.8", []string{"application/kv"}, 0, 0, true, nil} - resp.WriteEntity(b) - t.Log(string(httpWriter.Body.Bytes())) - if !kv.writeCalled { - t.Error("Write never called") - } - - // Read - bodyReader := bytes.NewReader(httpWriter.Body.Bytes()) - httpRequest, _ := http.NewRequest("GET", "/test", bodyReader) - httpRequest.Header.Set("Content-Type", "application/kv; charset=UTF-8") - request := NewRequest(httpRequest) - var bb Book - request.ReadEntity(&bb) - if !kv.readCalled { - t.Error("Read never called") - } -} diff --git a/vendor/github.com/emicklei/go-restful/filter_test.go b/vendor/github.com/emicklei/go-restful/filter_test.go deleted file mode 100644 index fadfb570f..000000000 --- a/vendor/github.com/emicklei/go-restful/filter_test.go +++ /dev/null @@ -1,141 +0,0 @@ -package restful - -import ( - "io" - "net/http" - "net/http/httptest" - "testing" -) - -func setupServices(addGlobalFilter bool, addServiceFilter bool, addRouteFilter bool) { - if addGlobalFilter { - Filter(globalFilter) - } - Add(newTestService(addServiceFilter, addRouteFilter)) -} - -func tearDown() { - DefaultContainer.webServices = []*WebService{} - DefaultContainer.isRegisteredOnRoot = true // this allows for setupServices multiple times - DefaultContainer.containerFilters = []FilterFunction{} -} - -func newTestService(addServiceFilter bool, addRouteFilter bool) *WebService { - ws := new(WebService).Path("") - if addServiceFilter { - ws.Filter(serviceFilter) - } - rb := ws.GET("/foo").To(foo) - if addRouteFilter { - rb.Filter(routeFilter) - } - ws.Route(rb) - ws.Route(ws.GET("/bar").To(bar)) - return ws -} - -func foo(req *Request, resp *Response) { - io.WriteString(resp.ResponseWriter, "foo") -} - -func bar(req *Request, resp *Response) { - io.WriteString(resp.ResponseWriter, "bar") -} - -func fail(req *Request, resp *Response) { - http.Error(resp.ResponseWriter, "something failed", http.StatusInternalServerError) -} - -func globalFilter(req *Request, resp *Response, chain *FilterChain) { - io.WriteString(resp.ResponseWriter, "global-") - chain.ProcessFilter(req, resp) -} - -func serviceFilter(req *Request, resp *Response, chain *FilterChain) { - io.WriteString(resp.ResponseWriter, "service-") - chain.ProcessFilter(req, resp) -} - -func routeFilter(req *Request, resp *Response, chain *FilterChain) { - io.WriteString(resp.ResponseWriter, "route-") - chain.ProcessFilter(req, resp) -} - -func TestNoFilter(t *testing.T) { - tearDown() - setupServices(false, false, false) - actual := sendIt("http://example.com/foo") - if "foo" != actual { - t.Fatal("expected: foo but got:" + actual) - } -} - -func TestGlobalFilter(t *testing.T) { - tearDown() - setupServices(true, false, false) - actual := sendIt("http://example.com/foo") - if "global-foo" != actual { - t.Fatal("expected: global-foo but got:" + actual) - } -} - -func TestWebServiceFilter(t *testing.T) { - tearDown() - setupServices(true, true, false) - actual := sendIt("http://example.com/foo") - if "global-service-foo" != actual { - t.Fatal("expected: global-service-foo but got:" + actual) - } -} - -func TestRouteFilter(t *testing.T) { - tearDown() - setupServices(true, true, true) - actual := sendIt("http://example.com/foo") - if "global-service-route-foo" != actual { - t.Fatal("expected: global-service-route-foo but got:" + actual) - } -} - -func TestRouteFilterOnly(t *testing.T) { - tearDown() - setupServices(false, false, true) - actual := sendIt("http://example.com/foo") - if "route-foo" != actual { - t.Fatal("expected: route-foo but got:" + actual) - } -} - -func TestBar(t *testing.T) { - tearDown() - setupServices(false, true, false) - actual := sendIt("http://example.com/bar") - if "service-bar" != actual { - t.Fatal("expected: service-bar but got:" + actual) - } -} - -func TestAllFiltersBar(t *testing.T) { - tearDown() - setupServices(true, true, true) - actual := sendIt("http://example.com/bar") - if "global-service-bar" != actual { - t.Fatal("expected: global-service-bar but got:" + actual) - } -} - -func sendIt(address string) string { - httpRequest, _ := http.NewRequest("GET", address, nil) - httpRequest.Header.Set("Accept", "*/*") - httpWriter := httptest.NewRecorder() - DefaultContainer.dispatch(httpWriter, httpRequest) - return httpWriter.Body.String() -} - -func sendItTo(address string, container *Container) string { - httpRequest, _ := http.NewRequest("GET", address, nil) - httpRequest.Header.Set("Accept", "*/*") - httpWriter := httptest.NewRecorder() - container.dispatch(httpWriter, httpRequest) - return httpWriter.Body.String() -} diff --git a/vendor/github.com/emicklei/go-restful/install.sh b/vendor/github.com/emicklei/go-restful/install.sh deleted file mode 100644 index 5fe03b569..000000000 --- a/vendor/github.com/emicklei/go-restful/install.sh +++ /dev/null @@ -1,9 +0,0 @@ -cd examples - ls *.go | xargs -I {} go build -o /tmp/ignore {} - cd .. -go fmt ...swagger && \ -go test -test.v ...swagger && \ -go install ...swagger && \ -go fmt ...restful && \ -go test -test.v ...restful && \ -go install ...restful \ No newline at end of file diff --git a/vendor/github.com/emicklei/go-restful/jsr311_test.go b/vendor/github.com/emicklei/go-restful/jsr311_test.go deleted file mode 100644 index 3e79a6def..000000000 --- a/vendor/github.com/emicklei/go-restful/jsr311_test.go +++ /dev/null @@ -1,212 +0,0 @@ -package restful - -import ( - "io" - "sort" - "testing" -) - -// -// Step 1 tests -// -var paths = []struct { - // url with path (1) is handled by service with root (2) and last capturing group has value final (3) - path, root, final string -}{ - {"/", "/", "/"}, - {"/p", "/p", ""}, - {"/p/x", "/p/{q}", ""}, - {"/q/x", "/q", "/x"}, - {"/p/x/", "/p/{q}", "/"}, - {"/p/x/y", "/p/{q}", "/y"}, - {"/q/x/y", "/q", "/x/y"}, - {"/z/q", "/{p}/q", ""}, - {"/a/b/c/q", "/", "/a/b/c/q"}, -} - -func TestDetectDispatcher(t *testing.T) { - ws1 := new(WebService).Path("/") - ws2 := new(WebService).Path("/p") - ws3 := new(WebService).Path("/q") - ws4 := new(WebService).Path("/p/q") - ws5 := new(WebService).Path("/p/{q}") - ws6 := new(WebService).Path("/p/{q}/") - ws7 := new(WebService).Path("/{p}/q") - var dispatchers = []*WebService{ws1, ws2, ws3, ws4, ws5, ws6, ws7} - - wc := NewContainer() - for _, each := range dispatchers { - wc.Add(each) - } - - router := RouterJSR311{} - - ok := true - for i, fixture := range paths { - who, final, err := router.detectDispatcher(fixture.path, dispatchers) - if err != nil { - t.Logf("error in detection:%v", err) - ok = false - } - if who.RootPath() != fixture.root { - t.Logf("[line:%v] Unexpected dispatcher, expected:%v, actual:%v", i, fixture.root, who.RootPath()) - ok = false - } - if final != fixture.final { - t.Logf("[line:%v] Unexpected final, expected:%v, actual:%v", i, fixture.final, final) - ok = false - } - } - if !ok { - t.Fail() - } -} - -// -// Step 2 tests -// - -// go test -v -test.run TestISSUE_179 ...restful -func TestISSUE_179(t *testing.T) { - ws1 := new(WebService) - ws1.Route(ws1.GET("/v1/category/{param:*}").To(dummy)) - routes := RouterJSR311{}.selectRoutes(ws1, "/v1/category/sub/sub") - t.Logf("%v", routes) -} - -// go test -v -test.run TestISSUE_30 ...restful -func TestISSUE_30(t *testing.T) { - ws1 := new(WebService).Path("/users") - ws1.Route(ws1.GET("/{id}").To(dummy)) - ws1.Route(ws1.POST("/login").To(dummy)) - routes := RouterJSR311{}.selectRoutes(ws1, "/login") - if len(routes) != 2 { - t.Fatal("expected 2 routes") - } - if routes[0].Path != "/users/login" { - t.Error("first is", routes[0].Path) - t.Logf("routes:%v", routes) - } -} - -// go test -v -test.run TestISSUE_34 ...restful -func TestISSUE_34(t *testing.T) { - ws1 := new(WebService).Path("/") - ws1.Route(ws1.GET("/{type}/{id}").To(dummy)) - ws1.Route(ws1.GET("/network/{id}").To(dummy)) - routes := RouterJSR311{}.selectRoutes(ws1, "/network/12") - if len(routes) != 2 { - t.Fatal("expected 2 routes") - } - if routes[0].Path != "/network/{id}" { - t.Error("first is", routes[0].Path) - t.Logf("routes:%v", routes) - } -} - -// go test -v -test.run TestISSUE_34_2 ...restful -func TestISSUE_34_2(t *testing.T) { - ws1 := new(WebService).Path("/") - // change the registration order - ws1.Route(ws1.GET("/network/{id}").To(dummy)) - ws1.Route(ws1.GET("/{type}/{id}").To(dummy)) - routes := RouterJSR311{}.selectRoutes(ws1, "/network/12") - if len(routes) != 2 { - t.Fatal("expected 2 routes") - } - if routes[0].Path != "/network/{id}" { - t.Error("first is", routes[0].Path) - } -} - -// go test -v -test.run TestISSUE_137 ...restful -func TestISSUE_137(t *testing.T) { - ws1 := new(WebService) - ws1.Route(ws1.GET("/hello").To(dummy)) - routes := RouterJSR311{}.selectRoutes(ws1, "/") - t.Log(routes) - if len(routes) > 0 { - t.Error("no route expected") - } -} - -func TestSelectRoutesSlash(t *testing.T) { - ws1 := new(WebService).Path("/") - ws1.Route(ws1.GET("").To(dummy)) - ws1.Route(ws1.GET("/").To(dummy)) - ws1.Route(ws1.GET("/u").To(dummy)) - ws1.Route(ws1.POST("/u").To(dummy)) - ws1.Route(ws1.POST("/u/v").To(dummy)) - ws1.Route(ws1.POST("/u/{w}").To(dummy)) - ws1.Route(ws1.POST("/u/{w}/z").To(dummy)) - routes := RouterJSR311{}.selectRoutes(ws1, "/u") - checkRoutesContains(routes, "/u", t) - checkRoutesContainsNo(routes, "/u/v", t) - checkRoutesContainsNo(routes, "/", t) - checkRoutesContainsNo(routes, "/u/{w}/z", t) -} -func TestSelectRoutesU(t *testing.T) { - ws1 := new(WebService).Path("/u") - ws1.Route(ws1.GET("").To(dummy)) - ws1.Route(ws1.GET("/").To(dummy)) - ws1.Route(ws1.GET("/v").To(dummy)) - ws1.Route(ws1.POST("/{w}").To(dummy)) - ws1.Route(ws1.POST("/{w}/z").To(dummy)) // so full path = /u/{w}/z - routes := RouterJSR311{}.selectRoutes(ws1, "/v") // test against /u/v - checkRoutesContains(routes, "/u/{w}", t) -} - -func TestSelectRoutesUsers1(t *testing.T) { - ws1 := new(WebService).Path("/users") - ws1.Route(ws1.POST("").To(dummy)) - ws1.Route(ws1.POST("/").To(dummy)) - ws1.Route(ws1.PUT("/{id}").To(dummy)) - routes := RouterJSR311{}.selectRoutes(ws1, "/1") - checkRoutesContains(routes, "/users/{id}", t) -} -func checkRoutesContains(routes []Route, path string, t *testing.T) { - if !containsRoutePath(routes, path, t) { - for _, r := range routes { - t.Logf("route %v %v", r.Method, r.Path) - } - t.Fatalf("routes should include [%v]:", path) - } -} -func checkRoutesContainsNo(routes []Route, path string, t *testing.T) { - if containsRoutePath(routes, path, t) { - for _, r := range routes { - t.Logf("route %v %v", r.Method, r.Path) - } - t.Fatalf("routes should not include [%v]:", path) - } -} -func containsRoutePath(routes []Route, path string, t *testing.T) bool { - for _, each := range routes { - if each.Path == path { - return true - } - } - return false -} - -// go test -v -test.run TestSortableRouteCandidates ...restful -func TestSortableRouteCandidates(t *testing.T) { - fixture := &sortableRouteCandidates{} - r1 := routeCandidate{matchesCount: 0, literalCount: 0, nonDefaultCount: 0} - r2 := routeCandidate{matchesCount: 0, literalCount: 0, nonDefaultCount: 1} - r3 := routeCandidate{matchesCount: 0, literalCount: 1, nonDefaultCount: 1} - r4 := routeCandidate{matchesCount: 1, literalCount: 1, nonDefaultCount: 0} - r5 := routeCandidate{matchesCount: 1, literalCount: 0, nonDefaultCount: 0} - fixture.candidates = append(fixture.candidates, r5, r4, r3, r2, r1) - sort.Sort(sort.Reverse(fixture)) - first := fixture.candidates[0] - if first.matchesCount != 1 && first.literalCount != 1 && first.nonDefaultCount != 0 { - t.Fatal("expected r4") - } - last := fixture.candidates[len(fixture.candidates)-1] - if last.matchesCount != 0 && last.literalCount != 0 && last.nonDefaultCount != 0 { - t.Fatal("expected r1") - } -} - -func dummy(req *Request, resp *Response) { io.WriteString(resp.ResponseWriter, "dummy") } diff --git a/vendor/github.com/emicklei/go-restful/options_filter_test.go b/vendor/github.com/emicklei/go-restful/options_filter_test.go deleted file mode 100644 index f0fceb834..000000000 --- a/vendor/github.com/emicklei/go-restful/options_filter_test.go +++ /dev/null @@ -1,34 +0,0 @@ -package restful - -import ( - "net/http" - "net/http/httptest" - "testing" -) - -// go test -v -test.run TestOptionsFilter ...restful -func TestOptionsFilter(t *testing.T) { - tearDown() - ws := new(WebService) - ws.Route(ws.GET("/candy/{kind}").To(dummy)) - ws.Route(ws.DELETE("/candy/{kind}").To(dummy)) - ws.Route(ws.POST("/candies").To(dummy)) - Add(ws) - Filter(OPTIONSFilter()) - - httpRequest, _ := http.NewRequest("OPTIONS", "http://here.io/candy/gum", nil) - httpWriter := httptest.NewRecorder() - DefaultContainer.dispatch(httpWriter, httpRequest) - actual := httpWriter.Header().Get(HEADER_Allow) - if "GET,DELETE" != actual { - t.Fatal("expected: GET,DELETE but got:" + actual) - } - - httpRequest, _ = http.NewRequest("OPTIONS", "http://here.io/candies", nil) - httpWriter = httptest.NewRecorder() - DefaultContainer.dispatch(httpWriter, httpRequest) - actual = httpWriter.Header().Get(HEADER_Allow) - if "POST" != actual { - t.Fatal("expected: POST but got:" + actual) - } -} diff --git a/vendor/github.com/emicklei/go-restful/path_expression_test.go b/vendor/github.com/emicklei/go-restful/path_expression_test.go deleted file mode 100644 index 334fcef73..000000000 --- a/vendor/github.com/emicklei/go-restful/path_expression_test.go +++ /dev/null @@ -1,37 +0,0 @@ -package restful - -import "testing" - -var tempregexs = []struct { - template, regex string - literalCount, varCount int -}{ - {"", "^(/.*)?$", 0, 0}, - {"/a/{b}/c/", "^/a/([^/]+?)/c(/.*)?$", 2, 1}, - {"/{a}/{b}/{c-d-e}/", "^/([^/]+?)/([^/]+?)/([^/]+?)(/.*)?$", 0, 3}, - {"/{p}/abcde", "^/([^/]+?)/abcde(/.*)?$", 5, 1}, - {"/a/{b:*}", "^/a/(.*)(/.*)?$", 1, 1}, - {"/a/{b:[a-z]+}", "^/a/([a-z]+)(/.*)?$", 1, 1}, -} - -func TestTemplateToRegularExpression(t *testing.T) { - ok := true - for i, fixture := range tempregexs { - actual, lCount, vCount, _ := templateToRegularExpression(fixture.template) - if actual != fixture.regex { - t.Logf("regex mismatch, expected:%v , actual:%v, line:%v\n", fixture.regex, actual, i) // 11 = where the data starts - ok = false - } - if lCount != fixture.literalCount { - t.Logf("literal count mismatch, expected:%v , actual:%v, line:%v\n", fixture.literalCount, lCount, i) - ok = false - } - if vCount != fixture.varCount { - t.Logf("variable count mismatch, expected:%v , actual:%v, line:%v\n", fixture.varCount, vCount, i) - ok = false - } - } - if !ok { - t.Fatal("one or more expression did not match") - } -} diff --git a/vendor/github.com/emicklei/go-restful/request_test.go b/vendor/github.com/emicklei/go-restful/request_test.go deleted file mode 100644 index 72f078f92..000000000 --- a/vendor/github.com/emicklei/go-restful/request_test.go +++ /dev/null @@ -1,204 +0,0 @@ -package restful - -import ( - "encoding/json" - "net/http" - "net/url" - "strconv" - "strings" - "testing" -) - -func TestQueryParameter(t *testing.T) { - hreq := http.Request{Method: "GET"} - hreq.URL, _ = url.Parse("http://www.google.com/search?q=foo&q=bar") - rreq := Request{Request: &hreq} - if rreq.QueryParameter("q") != "foo" { - t.Errorf("q!=foo %#v", rreq) - } -} - -type Anything map[string]interface{} - -type Number struct { - ValueFloat float64 - ValueInt int64 -} - -type Sample struct { - Value string -} - -func TestReadEntityXmlCached(t *testing.T) { - SetCacheReadEntity(true) - bodyReader := strings.NewReader("42") - httpRequest, _ := http.NewRequest("GET", "/test", bodyReader) - httpRequest.Header.Set("Content-Type", "application/xml") - request := &Request{Request: httpRequest} - sam := new(Sample) - request.ReadEntity(sam) - if sam.Value != "42" { - t.Fatal("read failed") - } - if request.bodyContent == nil { - t.Fatal("no expected cached bytes found") - } -} - -func TestReadEntityXmlNonCached(t *testing.T) { - SetCacheReadEntity(false) - bodyReader := strings.NewReader("42") - httpRequest, _ := http.NewRequest("GET", "/test", bodyReader) - httpRequest.Header.Set("Content-Type", "application/xml") - request := &Request{Request: httpRequest} - sam := new(Sample) - request.ReadEntity(sam) - if sam.Value != "42" { - t.Fatal("read failed") - } - if request.bodyContent != nil { - t.Fatal("unexpected cached bytes found") - } -} - -func TestReadEntityJson(t *testing.T) { - bodyReader := strings.NewReader(`{"Value" : "42"}`) - httpRequest, _ := http.NewRequest("GET", "/test", bodyReader) - httpRequest.Header.Set("Content-Type", "application/json") - request := &Request{Request: httpRequest} - sam := new(Sample) - request.ReadEntity(sam) - if sam.Value != "42" { - t.Fatal("read failed") - } -} - -func TestReadEntityJsonCharset(t *testing.T) { - bodyReader := strings.NewReader(`{"Value" : "42"}`) - httpRequest, _ := http.NewRequest("GET", "/test", bodyReader) - httpRequest.Header.Set("Content-Type", "application/json; charset=UTF-8") - request := NewRequest(httpRequest) - sam := new(Sample) - request.ReadEntity(sam) - if sam.Value != "42" { - t.Fatal("read failed") - } -} - -func TestReadEntityJsonNumber(t *testing.T) { - SetCacheReadEntity(true) - bodyReader := strings.NewReader(`{"Value" : 4899710515899924123}`) - httpRequest, _ := http.NewRequest("GET", "/test", bodyReader) - httpRequest.Header.Set("Content-Type", "application/json") - request := &Request{Request: httpRequest} - any := make(Anything) - request.ReadEntity(&any) - number, ok := any["Value"].(json.Number) - if !ok { - t.Fatal("read failed") - } - vint, err := number.Int64() - if err != nil { - t.Fatal("convert failed") - } - if vint != 4899710515899924123 { - t.Fatal("read failed") - } - vfloat, err := number.Float64() - if err != nil { - t.Fatal("convert failed") - } - // match the default behaviour - vstring := strconv.FormatFloat(vfloat, 'e', 15, 64) - if vstring != "4.899710515899924e+18" { - t.Fatal("convert float64 failed") - } -} - -func TestReadEntityJsonNumberNonCached(t *testing.T) { - SetCacheReadEntity(false) - bodyReader := strings.NewReader(`{"Value" : 4899710515899924123}`) - httpRequest, _ := http.NewRequest("GET", "/test", bodyReader) - httpRequest.Header.Set("Content-Type", "application/json") - request := &Request{Request: httpRequest} - any := make(Anything) - request.ReadEntity(&any) - number, ok := any["Value"].(json.Number) - if !ok { - t.Fatal("read failed") - } - vint, err := number.Int64() - if err != nil { - t.Fatal("convert failed") - } - if vint != 4899710515899924123 { - t.Fatal("read failed") - } - vfloat, err := number.Float64() - if err != nil { - t.Fatal("convert failed") - } - // match the default behaviour - vstring := strconv.FormatFloat(vfloat, 'e', 15, 64) - if vstring != "4.899710515899924e+18" { - t.Fatal("convert float64 failed") - } -} - -func TestReadEntityJsonLong(t *testing.T) { - bodyReader := strings.NewReader(`{"ValueFloat" : 4899710515899924123, "ValueInt": 4899710515899924123}`) - httpRequest, _ := http.NewRequest("GET", "/test", bodyReader) - httpRequest.Header.Set("Content-Type", "application/json") - request := &Request{Request: httpRequest} - number := new(Number) - request.ReadEntity(&number) - if number.ValueInt != 4899710515899924123 { - t.Fatal("read failed") - } - // match the default behaviour - vstring := strconv.FormatFloat(number.ValueFloat, 'e', 15, 64) - if vstring != "4.899710515899924e+18" { - t.Fatal("convert float64 failed") - } -} - -func TestBodyParameter(t *testing.T) { - bodyReader := strings.NewReader(`value1=42&value2=43`) - httpRequest, _ := http.NewRequest("POST", "/test?value1=44", bodyReader) // POST and PUT body parameters take precedence over URL query string - httpRequest.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8") - request := NewRequest(httpRequest) - v1, err := request.BodyParameter("value1") - if err != nil { - t.Error(err) - } - v2, err := request.BodyParameter("value2") - if err != nil { - t.Error(err) - } - if v1 != "42" || v2 != "43" { - t.Fatal("read failed") - } -} - -func TestReadEntityUnkown(t *testing.T) { - bodyReader := strings.NewReader("?") - httpRequest, _ := http.NewRequest("GET", "/test", bodyReader) - httpRequest.Header.Set("Content-Type", "application/rubbish") - request := NewRequest(httpRequest) - sam := new(Sample) - err := request.ReadEntity(sam) - if err == nil { - t.Fatal("read should be in error") - } -} - -func TestSetAttribute(t *testing.T) { - bodyReader := strings.NewReader("?") - httpRequest, _ := http.NewRequest("GET", "/test", bodyReader) - request := NewRequest(httpRequest) - request.SetAttribute("go", "there") - there := request.Attribute("go") - if there != "there" { - t.Fatalf("missing request attribute:%v", there) - } -} diff --git a/vendor/github.com/emicklei/go-restful/response_test.go b/vendor/github.com/emicklei/go-restful/response_test.go deleted file mode 100644 index c8354f8ae..000000000 --- a/vendor/github.com/emicklei/go-restful/response_test.go +++ /dev/null @@ -1,204 +0,0 @@ -package restful - -import ( - "errors" - "net/http" - "net/http/httptest" - "strings" - "testing" -) - -func TestWriteHeader(t *testing.T) { - httpWriter := httptest.NewRecorder() - resp := Response{httpWriter, "*/*", []string{"*/*"}, 0, 0, true, nil} - resp.WriteHeader(123) - if resp.StatusCode() != 123 { - t.Errorf("Unexpected status code:%d", resp.StatusCode()) - } -} - -func TestNoWriteHeader(t *testing.T) { - httpWriter := httptest.NewRecorder() - resp := Response{httpWriter, "*/*", []string{"*/*"}, 0, 0, true, nil} - if resp.StatusCode() != http.StatusOK { - t.Errorf("Unexpected status code:%d", resp.StatusCode()) - } -} - -type food struct { - Kind string -} - -// go test -v -test.run TestMeasureContentLengthXml ...restful -func TestMeasureContentLengthXml(t *testing.T) { - httpWriter := httptest.NewRecorder() - resp := Response{httpWriter, "*/*", []string{"*/*"}, 0, 0, true, nil} - resp.WriteAsXml(food{"apple"}) - if resp.ContentLength() != 76 { - t.Errorf("Incorrect measured length:%d", resp.ContentLength()) - } -} - -// go test -v -test.run TestMeasureContentLengthJson ...restful -func TestMeasureContentLengthJson(t *testing.T) { - httpWriter := httptest.NewRecorder() - resp := Response{httpWriter, "*/*", []string{"*/*"}, 0, 0, true, nil} - resp.WriteAsJson(food{"apple"}) - if resp.ContentLength() != 22 { - t.Errorf("Incorrect measured length:%d", resp.ContentLength()) - } -} - -// go test -v -test.run TestMeasureContentLengthJsonNotPretty ...restful -func TestMeasureContentLengthJsonNotPretty(t *testing.T) { - httpWriter := httptest.NewRecorder() - resp := Response{httpWriter, "*/*", []string{"*/*"}, 0, 0, false, nil} - resp.WriteAsJson(food{"apple"}) - if resp.ContentLength() != 17 { // 16+1 using the Encoder directly yields another /n - t.Errorf("Incorrect measured length:%d", resp.ContentLength()) - } -} - -// go test -v -test.run TestMeasureContentLengthWriteErrorString ...restful -func TestMeasureContentLengthWriteErrorString(t *testing.T) { - httpWriter := httptest.NewRecorder() - resp := Response{httpWriter, "*/*", []string{"*/*"}, 0, 0, true, nil} - resp.WriteErrorString(404, "Invalid") - if resp.ContentLength() != len("Invalid") { - t.Errorf("Incorrect measured length:%d", resp.ContentLength()) - } -} - -// go test -v -test.run TestStatusIsPassedToResponse ...restful -func TestStatusIsPassedToResponse(t *testing.T) { - for _, each := range []struct { - write, read int - }{ - {write: 204, read: 204}, - {write: 304, read: 304}, - {write: 200, read: 200}, - {write: 400, read: 400}, - } { - httpWriter := httptest.NewRecorder() - resp := Response{httpWriter, "*/*", []string{"*/*"}, 0, 0, true, nil} - resp.WriteHeader(each.write) - if got, want := httpWriter.Code, each.read; got != want { - t.Errorf("got %v want %v", got, want) - } - } -} - -// go test -v -test.run TestStatusCreatedAndContentTypeJson_Issue54 ...restful -func TestStatusCreatedAndContentTypeJson_Issue54(t *testing.T) { - httpWriter := httptest.NewRecorder() - resp := Response{httpWriter, "application/json", []string{"application/json"}, 0, 0, true, nil} - resp.WriteHeader(201) - resp.WriteAsJson(food{"Juicy"}) - if httpWriter.HeaderMap.Get("Content-Type") != "application/json" { - t.Errorf("Expected content type json but got:%d", httpWriter.HeaderMap.Get("Content-Type")) - } - if httpWriter.Code != 201 { - t.Errorf("Expected status 201 but got:%d", httpWriter.Code) - } -} - -type errorOnWriteRecorder struct { - *httptest.ResponseRecorder -} - -func (e errorOnWriteRecorder) Write(bytes []byte) (int, error) { - return 0, errors.New("fail") -} - -// go test -v -test.run TestLastWriteErrorCaught ...restful -func TestLastWriteErrorCaught(t *testing.T) { - httpWriter := errorOnWriteRecorder{httptest.NewRecorder()} - resp := Response{httpWriter, "application/json", []string{"application/json"}, 0, 0, true, nil} - err := resp.WriteAsJson(food{"Juicy"}) - if err.Error() != "fail" { - t.Errorf("Unexpected error message:%v", err) - } -} - -// go test -v -test.run TestAcceptStarStar_Issue83 ...restful -func TestAcceptStarStar_Issue83(t *testing.T) { - httpWriter := httptest.NewRecorder() - // Accept Produces - resp := Response{httpWriter, "application/bogus,*/*;q=0.8", []string{"application/json"}, 0, 0, true, nil} - resp.WriteEntity(food{"Juicy"}) - ct := httpWriter.Header().Get("Content-Type") - if "application/json" != ct { - t.Errorf("Unexpected content type:%s", ct) - } -} - -// go test -v -test.run TestAcceptSkipStarStar_Issue83 ...restful -func TestAcceptSkipStarStar_Issue83(t *testing.T) { - httpWriter := httptest.NewRecorder() - // Accept Produces - resp := Response{httpWriter, " application/xml ,*/* ; q=0.8", []string{"application/json", "application/xml"}, 0, 0, true, nil} - resp.WriteEntity(food{"Juicy"}) - ct := httpWriter.Header().Get("Content-Type") - if "application/xml" != ct { - t.Errorf("Unexpected content type:%s", ct) - } -} - -// go test -v -test.run TestAcceptXmlBeforeStarStar_Issue83 ...restful -func TestAcceptXmlBeforeStarStar_Issue83(t *testing.T) { - httpWriter := httptest.NewRecorder() - // Accept Produces - resp := Response{httpWriter, "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", []string{"application/json"}, 0, 0, true, nil} - resp.WriteEntity(food{"Juicy"}) - ct := httpWriter.Header().Get("Content-Type") - if "application/json" != ct { - t.Errorf("Unexpected content type:%s", ct) - } -} - -// go test -v -test.run TestWriteHeaderNoContent_Issue124 ...restful -func TestWriteHeaderNoContent_Issue124(t *testing.T) { - httpWriter := httptest.NewRecorder() - resp := Response{httpWriter, "text/plain", []string{"text/plain"}, 0, 0, true, nil} - resp.WriteHeader(http.StatusNoContent) - if httpWriter.Code != http.StatusNoContent { - t.Errorf("got %d want %d", httpWriter.Code, http.StatusNoContent) - } -} - -// go test -v -test.run TestStatusCreatedAndContentTypeJson_Issue163 ...restful -func TestStatusCreatedAndContentTypeJson_Issue163(t *testing.T) { - httpWriter := httptest.NewRecorder() - resp := Response{httpWriter, "application/json", []string{"application/json"}, 0, 0, true, nil} - resp.WriteHeader(http.StatusNotModified) - if httpWriter.Code != http.StatusNotModified { - t.Errorf("Got %d want %d", httpWriter.Code, http.StatusNotModified) - } -} - -func TestWriteHeaderAndEntity_Issue235(t *testing.T) { - httpWriter := httptest.NewRecorder() - resp := Response{httpWriter, "application/json", []string{"application/json"}, 0, 0, true, nil} - var pong = struct { - Foo string `json:"foo"` - }{Foo: "123"} - resp.WriteHeaderAndEntity(404, pong) - if httpWriter.Code != http.StatusNotFound { - t.Errorf("got %d want %d", httpWriter.Code, http.StatusNoContent) - } - if got, want := httpWriter.Header().Get("Content-Type"), "application/json"; got != want { - t.Errorf("got %v want %v", got, want) - } - if !strings.HasPrefix(httpWriter.Body.String(), "{") { - t.Errorf("expected pong struct in json:%s", httpWriter.Body.String()) - } -} - -func TestWriteEntityNotAcceptable(t *testing.T) { - httpWriter := httptest.NewRecorder() - resp := Response{httpWriter, "application/bogus", []string{"application/json"}, 0, 0, true, nil} - resp.WriteEntity("done") - if httpWriter.Code != http.StatusNotAcceptable { - t.Errorf("got %d want %d", httpWriter.Code, http.StatusNotAcceptable) - } -} diff --git a/vendor/github.com/emicklei/go-restful/route_builder_test.go b/vendor/github.com/emicklei/go-restful/route_builder_test.go deleted file mode 100644 index 56dbe02e4..000000000 --- a/vendor/github.com/emicklei/go-restful/route_builder_test.go +++ /dev/null @@ -1,58 +0,0 @@ -package restful - -import ( - "testing" -) - -func TestRouteBuilder_PathParameter(t *testing.T) { - p := &Parameter{&ParameterData{Name: "name", Description: "desc"}} - p.AllowMultiple(true) - p.DataType("int") - p.Required(true) - values := map[string]string{"a": "b"} - p.AllowableValues(values) - p.bePath() - - b := new(RouteBuilder) - b.function = dummy - b.Param(p) - r := b.Build() - if !r.ParameterDocs[0].Data().AllowMultiple { - t.Error("AllowMultiple invalid") - } - if r.ParameterDocs[0].Data().DataType != "int" { - t.Error("dataType invalid") - } - if !r.ParameterDocs[0].Data().Required { - t.Error("required invalid") - } - if r.ParameterDocs[0].Data().Kind != PathParameterKind { - t.Error("kind invalid") - } - if r.ParameterDocs[0].Data().AllowableValues["a"] != "b" { - t.Error("allowableValues invalid") - } - if b.ParameterNamed("name") == nil { - t.Error("access to parameter failed") - } -} - -func TestRouteBuilder(t *testing.T) { - json := "application/json" - b := new(RouteBuilder) - b.To(dummy) - b.Path("/routes").Method("HEAD").Consumes(json).Produces(json) - r := b.Build() - if r.Path != "/routes" { - t.Error("path invalid") - } - if r.Produces[0] != json { - t.Error("produces invalid") - } - if r.Consumes[0] != json { - t.Error("consumes invalid") - } - if r.Operation != "dummy" { - t.Error("Operation not set") - } -} diff --git a/vendor/github.com/emicklei/go-restful/route_test.go b/vendor/github.com/emicklei/go-restful/route_test.go deleted file mode 100644 index 6a104aff8..000000000 --- a/vendor/github.com/emicklei/go-restful/route_test.go +++ /dev/null @@ -1,127 +0,0 @@ -package restful - -import ( - "testing" -) - -// accept should match produces -func TestMatchesAcceptPlainTextWhenProducePlainTextAsLast(t *testing.T) { - r := Route{Produces: []string{"application/json", "text/plain"}} - if !r.matchesAccept("text/plain") { - t.Errorf("accept should match text/plain") - } -} - -// accept should match produces -func TestMatchesAcceptStar(t *testing.T) { - r := Route{Produces: []string{"application/xml"}} - if !r.matchesAccept("*/*") { - t.Errorf("accept should match star") - } -} - -// accept should match produces -func TestMatchesAcceptIE(t *testing.T) { - r := Route{Produces: []string{"application/xml"}} - if !r.matchesAccept("text/html, application/xhtml+xml, */*") { - t.Errorf("accept should match star") - } -} - -// accept should match produces -func TestMatchesAcceptXml(t *testing.T) { - r := Route{Produces: []string{"application/xml"}} - if r.matchesAccept("application/json") { - t.Errorf("accept should not match json") - } - if !r.matchesAccept("application/xml") { - t.Errorf("accept should match xml") - } -} - -// accept should match produces -func TestMatchesAcceptAny(t *testing.T) { - r := Route{Produces: []string{"*/*"}} - if !r.matchesAccept("application/json") { - t.Errorf("accept should match json") - } - if !r.matchesAccept("application/xml") { - t.Errorf("accept should match xml") - } -} - -// content type should match consumes -func TestMatchesContentTypeXml(t *testing.T) { - r := Route{Consumes: []string{"application/xml"}} - if r.matchesContentType("application/json") { - t.Errorf("accept should not match json") - } - if !r.matchesContentType("application/xml") { - t.Errorf("accept should match xml") - } -} - -// content type should match consumes -func TestMatchesContentTypeCharsetInformation(t *testing.T) { - r := Route{Consumes: []string{"application/json"}} - if !r.matchesContentType("application/json; charset=UTF-8") { - t.Errorf("matchesContentType should ignore charset information") - } -} - -func TestMatchesPath_OneParam(t *testing.T) { - params := doExtractParams("/from/{source}", 2, "/from/here", t) - if params["source"] != "here" { - t.Errorf("parameter mismatch here") - } -} - -func TestMatchesPath_Slash(t *testing.T) { - params := doExtractParams("/", 0, "/", t) - if len(params) != 0 { - t.Errorf("expected empty parameters") - } -} - -func TestMatchesPath_SlashNonVar(t *testing.T) { - params := doExtractParams("/any", 1, "/any", t) - if len(params) != 0 { - t.Errorf("expected empty parameters") - } -} - -func TestMatchesPath_TwoVars(t *testing.T) { - params := doExtractParams("/from/{source}/to/{destination}", 4, "/from/AMS/to/NY", t) - if params["source"] != "AMS" { - t.Errorf("parameter mismatch AMS") - } -} - -func TestMatchesPath_VarOnFront(t *testing.T) { - params := doExtractParams("{what}/from/{source}/", 3, "who/from/SOS/", t) - if params["source"] != "SOS" { - t.Errorf("parameter mismatch SOS") - } -} - -func TestExtractParameters_EmptyValue(t *testing.T) { - params := doExtractParams("/fixed/{var}", 2, "/fixed/", t) - if params["var"] != "" { - t.Errorf("parameter mismatch var") - } -} - -func TestTokenizePath(t *testing.T) { - if len(tokenizePath("/")) != 0 { - t.Errorf("not empty path tokens") - } -} - -func doExtractParams(routePath string, size int, urlPath string, t *testing.T) map[string]string { - r := Route{Path: routePath} - r.postBuild() - if len(r.pathParts) != size { - t.Fatalf("len not %v %v, but %v", size, r.pathParts, len(r.pathParts)) - } - return r.extractParameters(urlPath) -} diff --git a/vendor/github.com/emicklei/go-restful/swagger/CHANGES.md b/vendor/github.com/emicklei/go-restful/swagger/CHANGES.md deleted file mode 100644 index 736f6f37c..000000000 --- a/vendor/github.com/emicklei/go-restful/swagger/CHANGES.md +++ /dev/null @@ -1,43 +0,0 @@ -Change history of swagger -= -2015-10-16 -- add type override mechanism for swagger models (MR 254, nathanejohnson) -- replace uses of wildcard in generated apidocs (issue 251) - -2015-05-25 -- (api break) changed the type of Properties in Model -- (api break) changed the type of Models in ApiDeclaration -- (api break) changed the parameter type of PostBuildDeclarationMapFunc - -2015-04-09 -- add ModelBuildable interface for customization of Model - -2015-03-17 -- preserve order of Routes per WebService in Swagger listing -- fix use of $ref and type in Swagger models -- add api version to listing - -2014-11-14 -- operation parameters are now sorted using ordering path,query,form,header,body - -2014-11-12 -- respect omitempty tag value for embedded structs -- expose ApiVersion of WebService to Swagger ApiDeclaration - -2014-05-29 -- (api add) Ability to define custom http.Handler to serve swagger-ui static files - -2014-05-04 -- (fix) include model for array element type of response - -2014-01-03 -- (fix) do not add primitive type to the Api models - -2013-11-27 -- (fix) make Swagger work for WebServices with root ("/" or "") paths - -2013-10-29 -- (api add) package variable LogInfo to customize logging function - -2013-10-15 -- upgraded to spec version 1.2 (https://github.com/wordnik/swagger-core/wiki/1.2-transition) \ No newline at end of file diff --git a/vendor/github.com/emicklei/go-restful/swagger/README.md b/vendor/github.com/emicklei/go-restful/swagger/README.md deleted file mode 100644 index 6c27c3070..000000000 --- a/vendor/github.com/emicklei/go-restful/swagger/README.md +++ /dev/null @@ -1,76 +0,0 @@ -How to use Swagger UI with go-restful -= - -Get the Swagger UI sources (version 1.2 only) - - git clone https://github.com/wordnik/swagger-ui.git - -The project contains a "dist" folder. -Its contents has all the Swagger UI files you need. - -The `index.html` has an `url` set to `http://petstore.swagger.wordnik.com/api/api-docs`. -You need to change that to match your WebService JSON endpoint e.g. `http://localhost:8080/apidocs.json` - -Now, you can install the Swagger WebService for serving the Swagger specification in JSON. - - config := swagger.Config{ - WebServices: restful.RegisteredWebServices(), - ApiPath: "/apidocs.json", - SwaggerPath: "/apidocs/", - SwaggerFilePath: "/Users/emicklei/Projects/swagger-ui/dist"} - swagger.InstallSwaggerService(config) - - -Documenting Structs --- - -Currently there are 2 ways to document your structs in the go-restful Swagger. - -###### By using struct tags -- Use tag "description" to annotate a struct field with a description to show in the UI -- Use tag "modelDescription" to annotate the struct itself with a description to show in the UI. The tag can be added in an field of the struct and in case that there are multiple definition, they will be appended with an empty line. - -###### By using the SwaggerDoc method -Here is an example with an `Address` struct and the documentation for each of the fields. The `""` is a special entry for **documenting the struct itself**. - - type Address struct { - Country string `json:"country,omitempty"` - PostCode int `json:"postcode,omitempty"` - } - - func (Address) SwaggerDoc() map[string]string { - return map[string]string{ - "": "Address doc", - "country": "Country doc", - "postcode": "PostCode doc", - } - } - -This example will generate a JSON like this - - { - "Address": { - "id": "Address", - "description": "Address doc", - "properties": { - "country": { - "type": "string", - "description": "Country doc" - }, - "postcode": { - "type": "integer", - "format": "int32", - "description": "PostCode doc" - } - } - } - } - -**Very Important Notes:** -- `SwaggerDoc()` is using a **NON-Pointer** receiver (e.g. func (Address) and not func (*Address)) -- The returned map should use as key the name of the field as defined in the JSON parameter (e.g. `"postcode"` and not `"PostCode"`) - -Notes --- -- The Nickname of an Operation is automatically set by finding the name of the function. You can override it using RouteBuilder.Operation(..) -- The WebServices field of swagger.Config can be used to control which service you want to expose and document ; you can have multiple configs and therefore multiple endpoints. diff --git a/vendor/github.com/emicklei/go-restful/swagger/model_builder_test.go b/vendor/github.com/emicklei/go-restful/swagger/model_builder_test.go deleted file mode 100644 index fa3a1a453..000000000 --- a/vendor/github.com/emicklei/go-restful/swagger/model_builder_test.go +++ /dev/null @@ -1,1142 +0,0 @@ -package swagger - -import ( - "net" - "testing" - "time" -) - -type YesNo bool - -func (y YesNo) MarshalJSON() ([]byte, error) { - if y { - return []byte("yes"), nil - } - return []byte("no"), nil -} - -// clear && go test -v -test.run TestRef_Issue190 ...swagger -func TestRef_Issue190(t *testing.T) { - type User struct { - items []string - } - testJsonFromStruct(t, User{}, `{ - "swagger.User": { - "id": "swagger.User", - "required": [ - "items" - ], - "properties": { - "items": { - "type": "array", - "items": { - "type": "string" - } - } - } - } - }`) -} - -// clear && go test -v -test.run TestCustomMarshaller_Issue96 ...swagger -func TestCustomMarshaller_Issue96(t *testing.T) { - type Vote struct { - What YesNo - } - testJsonFromStruct(t, Vote{}, `{ - "swagger.Vote": { - "id": "swagger.Vote", - "required": [ - "What" - ], - "properties": { - "What": { - "type": "string" - } - } - } - }`) -} - -// clear && go test -v -test.run TestPrimitiveTypes ...swagger -func TestPrimitiveTypes(t *testing.T) { - type Prims struct { - f float64 - t time.Time - } - testJsonFromStruct(t, Prims{}, `{ - "swagger.Prims": { - "id": "swagger.Prims", - "required": [ - "f", - "t" - ], - "properties": { - "f": { - "type": "number", - "format": "double" - }, - "t": { - "type": "string", - "format": "date-time" - } - } - } - }`) -} - -// clear && go test -v -test.run TestPrimitivePtrTypes ...swagger -func TestPrimitivePtrTypes(t *testing.T) { - type Prims struct { - f *float64 - t *time.Time - b *bool - s *string - i *int - } - testJsonFromStruct(t, Prims{}, `{ - "swagger.Prims": { - "id": "swagger.Prims", - "required": [ - "f", - "t", - "b", - "s", - "i" - ], - "properties": { - "b": { - "type": "boolean" - }, - "f": { - "type": "number", - "format": "double" - }, - "i": { - "type": "integer", - "format": "int32" - }, - "s": { - "type": "string" - }, - "t": { - "type": "string", - "format": "date-time" - } - } - } - }`) -} - -// clear && go test -v -test.run TestS1 ...swagger -func TestS1(t *testing.T) { - type S1 struct { - Id string - } - testJsonFromStruct(t, S1{}, `{ - "swagger.S1": { - "id": "swagger.S1", - "required": [ - "Id" - ], - "properties": { - "Id": { - "type": "string" - } - } - } - }`) -} - -// clear && go test -v -test.run TestS2 ...swagger -func TestS2(t *testing.T) { - type S2 struct { - Ids []string - } - testJsonFromStruct(t, S2{}, `{ - "swagger.S2": { - "id": "swagger.S2", - "required": [ - "Ids" - ], - "properties": { - "Ids": { - "type": "array", - "items": { - "type": "string" - } - } - } - } - }`) -} - -// clear && go test -v -test.run TestS3 ...swagger -func TestS3(t *testing.T) { - type NestedS3 struct { - Id string - } - type S3 struct { - Nested NestedS3 - } - testJsonFromStruct(t, S3{}, `{ - "swagger.NestedS3": { - "id": "swagger.NestedS3", - "required": [ - "Id" - ], - "properties": { - "Id": { - "type": "string" - } - } - }, - "swagger.S3": { - "id": "swagger.S3", - "required": [ - "Nested" - ], - "properties": { - "Nested": { - "$ref": "swagger.NestedS3" - } - } - } - }`) -} - -type sample struct { - id string `swagger:"required"` // TODO - items []item - rootItem item `json:"root" description:"root desc"` -} - -type item struct { - itemName string `json:"name"` -} - -// clear && go test -v -test.run TestSampleToModelAsJson ...swagger -func TestSampleToModelAsJson(t *testing.T) { - testJsonFromStruct(t, sample{items: []item{}}, `{ - "swagger.item": { - "id": "swagger.item", - "required": [ - "name" - ], - "properties": { - "name": { - "type": "string" - } - } - }, - "swagger.sample": { - "id": "swagger.sample", - "required": [ - "id", - "items", - "root" - ], - "properties": { - "id": { - "type": "string" - }, - "items": { - "type": "array", - "items": { - "$ref": "swagger.item" - } - }, - "root": { - "$ref": "swagger.item", - "description": "root desc" - } - } - } - }`) -} - -func TestJsonTags(t *testing.T) { - type X struct { - A string - B string `json:"-"` - C int `json:",string"` - D int `json:","` - } - - expected := `{ - "swagger.X": { - "id": "swagger.X", - "required": [ - "A", - "C", - "D" - ], - "properties": { - "A": { - "type": "string" - }, - "C": { - "type": "string" - }, - "D": { - "type": "integer", - "format": "int32" - } - } - } - }` - - testJsonFromStruct(t, X{}, expected) -} - -func TestJsonTagOmitempty(t *testing.T) { - type X struct { - A int `json:",omitempty"` - B int `json:"C,omitempty"` - } - - expected := `{ - "swagger.X": { - "id": "swagger.X", - "properties": { - "A": { - "type": "integer", - "format": "int32" - }, - "C": { - "type": "integer", - "format": "int32" - } - } - } - }` - - testJsonFromStruct(t, X{}, expected) -} - -func TestJsonTagName(t *testing.T) { - type X struct { - A string `json:"B"` - } - - expected := `{ - "swagger.X": { - "id": "swagger.X", - "required": [ - "B" - ], - "properties": { - "B": { - "type": "string" - } - } - } - }` - - testJsonFromStruct(t, X{}, expected) -} - -func TestAnonymousStruct(t *testing.T) { - type X struct { - A struct { - B int - } - } - - expected := `{ - "swagger.X": { - "id": "swagger.X", - "required": [ - "A" - ], - "properties": { - "A": { - "$ref": "swagger.X.A" - } - } - }, - "swagger.X.A": { - "id": "swagger.X.A", - "required": [ - "B" - ], - "properties": { - "B": { - "type": "integer", - "format": "int32" - } - } - } - }` - - testJsonFromStruct(t, X{}, expected) -} - -func TestAnonymousPtrStruct(t *testing.T) { - type X struct { - A *struct { - B int - } - } - - expected := `{ - "swagger.X": { - "id": "swagger.X", - "required": [ - "A" - ], - "properties": { - "A": { - "$ref": "swagger.X.A" - } - } - }, - "swagger.X.A": { - "id": "swagger.X.A", - "required": [ - "B" - ], - "properties": { - "B": { - "type": "integer", - "format": "int32" - } - } - } - }` - - testJsonFromStruct(t, X{}, expected) -} - -func TestAnonymousArrayStruct(t *testing.T) { - type X struct { - A []struct { - B int - } - } - - expected := `{ - "swagger.X": { - "id": "swagger.X", - "required": [ - "A" - ], - "properties": { - "A": { - "type": "array", - "items": { - "$ref": "swagger.X.A" - } - } - } - }, - "swagger.X.A": { - "id": "swagger.X.A", - "required": [ - "B" - ], - "properties": { - "B": { - "type": "integer", - "format": "int32" - } - } - } - }` - - testJsonFromStruct(t, X{}, expected) -} - -func TestAnonymousPtrArrayStruct(t *testing.T) { - type X struct { - A *[]struct { - B int - } - } - - expected := `{ - "swagger.X": { - "id": "swagger.X", - "required": [ - "A" - ], - "properties": { - "A": { - "type": "array", - "items": { - "$ref": "swagger.X.A" - } - } - } - }, - "swagger.X.A": { - "id": "swagger.X.A", - "required": [ - "B" - ], - "properties": { - "B": { - "type": "integer", - "format": "int32" - } - } - } - }` - - testJsonFromStruct(t, X{}, expected) -} - -// go test -v -test.run TestEmbeddedStruct_Issue98 ...swagger -func TestEmbeddedStruct_Issue98(t *testing.T) { - type Y struct { - A int - } - type X struct { - Y - } - testJsonFromStruct(t, X{}, `{ - "swagger.X": { - "id": "swagger.X", - "required": [ - "A" - ], - "properties": { - "A": { - "type": "integer", - "format": "int32" - } - } - } - }`) -} - -type Dataset struct { - Names []string -} - -// clear && go test -v -test.run TestIssue85 ...swagger -func TestIssue85(t *testing.T) { - anon := struct{ Datasets []Dataset }{} - testJsonFromStruct(t, anon, `{ - "struct { Datasets ||swagger.Dataset }": { - "id": "struct { Datasets ||swagger.Dataset }", - "required": [ - "Datasets" - ], - "properties": { - "Datasets": { - "type": "array", - "items": { - "$ref": "swagger.Dataset" - } - } - } - }, - "swagger.Dataset": { - "id": "swagger.Dataset", - "required": [ - "Names" - ], - "properties": { - "Names": { - "type": "array", - "items": { - "type": "string" - } - } - } - } - }`) -} - -type File struct { - History []File - HistoryPtrs []*File -} - -// go test -v -test.run TestRecursiveStructure ...swagger -func TestRecursiveStructure(t *testing.T) { - testJsonFromStruct(t, File{}, `{ - "swagger.File": { - "id": "swagger.File", - "required": [ - "History", - "HistoryPtrs" - ], - "properties": { - "History": { - "type": "array", - "items": { - "$ref": "swagger.File" - } - }, - "HistoryPtrs": { - "type": "array", - "items": { - "$ref": "swagger.File" - } - } - } - } - }`) -} - -type A1 struct { - B struct { - Id int - Comment string `json:"comment,omitempty"` - } -} - -// go test -v -test.run TestEmbeddedStructA1 ...swagger -func TestEmbeddedStructA1(t *testing.T) { - testJsonFromStruct(t, A1{}, `{ - "swagger.A1": { - "id": "swagger.A1", - "required": [ - "B" - ], - "properties": { - "B": { - "$ref": "swagger.A1.B" - } - } - }, - "swagger.A1.B": { - "id": "swagger.A1.B", - "required": [ - "Id" - ], - "properties": { - "Id": { - "type": "integer", - "format": "int32" - }, - "comment": { - "type": "string" - } - } - } - }`) -} - -type A2 struct { - C -} -type C struct { - Id int `json:"B"` - Comment string `json:"comment,omitempty"` - Secure bool `json:"secure"` -} - -// go test -v -test.run TestEmbeddedStructA2 ...swagger -func TestEmbeddedStructA2(t *testing.T) { - testJsonFromStruct(t, A2{}, `{ - "swagger.A2": { - "id": "swagger.A2", - "required": [ - "B", - "secure" - ], - "properties": { - "B": { - "type": "integer", - "format": "int32" - }, - "comment": { - "type": "string" - }, - "secure": { - "type": "boolean" - } - } - } - }`) -} - -type A3 struct { - B D -} - -type D struct { - Id int -} - -// clear && go test -v -test.run TestStructA3 ...swagger -func TestStructA3(t *testing.T) { - testJsonFromStruct(t, A3{}, `{ - "swagger.A3": { - "id": "swagger.A3", - "required": [ - "B" - ], - "properties": { - "B": { - "$ref": "swagger.D" - } - } - }, - "swagger.D": { - "id": "swagger.D", - "required": [ - "Id" - ], - "properties": { - "Id": { - "type": "integer", - "format": "int32" - } - } - } - }`) -} - -type A4 struct { - D "json:,inline" -} - -// clear && go test -v -test.run TestStructA4 ...swagger -func TestEmbeddedStructA4(t *testing.T) { - testJsonFromStruct(t, A4{}, `{ - "swagger.A4": { - "id": "swagger.A4", - "required": [ - "Id" - ], - "properties": { - "Id": { - "type": "integer", - "format": "int32" - } - } - } - }`) -} - -type A5 struct { - D `json:"d"` -} - -// clear && go test -v -test.run TestStructA5 ...swagger -func TestEmbeddedStructA5(t *testing.T) { - testJsonFromStruct(t, A5{}, `{ - "swagger.A5": { - "id": "swagger.A5", - "required": [ - "d" - ], - "properties": { - "d": { - "$ref": "swagger.D" - } - } - }, - "swagger.D": { - "id": "swagger.D", - "required": [ - "Id" - ], - "properties": { - "Id": { - "type": "integer", - "format": "int32" - } - } - } - }`) -} - -type D2 struct { - id int - D []D -} - -type A6 struct { - D2 "json:,inline" -} - -// clear && go test -v -test.run TestStructA4 ...swagger -func TestEmbeddedStructA6(t *testing.T) { - testJsonFromStruct(t, A6{}, `{ - "swagger.A6": { - "id": "swagger.A6", - "required": [ - "id", - "D" - ], - "properties": { - "D": { - "type": "array", - "items": { - "$ref": "swagger.D" - } - }, - "id": { - "type": "integer", - "format": "int32" - } - } - }, - "swagger.D": { - "id": "swagger.D", - "required": [ - "Id" - ], - "properties": { - "Id": { - "type": "integer", - "format": "int32" - } - } - } - }`) -} - -type ObjectId []byte - -type Region struct { - Id ObjectId `bson:"_id" json:"id"` - Name string `bson:"name" json:"name"` - Type string `bson:"type" json:"type"` -} - -// clear && go test -v -test.run TestRegion_Issue113 ...swagger -func TestRegion_Issue113(t *testing.T) { - testJsonFromStruct(t, []Region{}, `{ - "integer": { - "id": "integer", - "properties": {} - }, - "swagger.Region": { - "id": "swagger.Region", - "required": [ - "id", - "name", - "type" - ], - "properties": { - "id": { - "type": "array", - "items": { - "$ref": "integer" - } - }, - "name": { - "type": "string" - }, - "type": { - "type": "string" - } - } - }, - "||swagger.Region": { - "id": "||swagger.Region", - "properties": {} - } - }`) -} - -// clear && go test -v -test.run TestIssue158 ...swagger -func TestIssue158(t *testing.T) { - type Address struct { - Country string `json:"country,omitempty"` - } - - type Customer struct { - Name string `json:"name"` - Address Address `json:"address"` - } - expected := `{ - "swagger.Address": { - "id": "swagger.Address", - "properties": { - "country": { - "type": "string" - } - } - }, - "swagger.Customer": { - "id": "swagger.Customer", - "required": [ - "name", - "address" - ], - "properties": { - "address": { - "$ref": "swagger.Address" - }, - "name": { - "type": "string" - } - } - } - }` - testJsonFromStruct(t, Customer{}, expected) -} - -func TestSlices(t *testing.T) { - type Address struct { - Country string `json:"country,omitempty"` - } - expected := `{ - "swagger.Address": { - "id": "swagger.Address", - "properties": { - "country": { - "type": "string" - } - } - }, - "swagger.Customer": { - "id": "swagger.Customer", - "required": [ - "name", - "addresses" - ], - "properties": { - "addresses": { - "type": "array", - "items": { - "$ref": "swagger.Address" - } - }, - "name": { - "type": "string" - } - } - } - }` - // both slices (with pointer value and with type value) should have equal swagger representation - { - type Customer struct { - Name string `json:"name"` - Addresses []Address `json:"addresses"` - } - testJsonFromStruct(t, Customer{}, expected) - } - { - type Customer struct { - Name string `json:"name"` - Addresses []*Address `json:"addresses"` - } - testJsonFromStruct(t, Customer{}, expected) - } - -} - -type Name struct { - Value string -} - -func (n Name) PostBuildModel(m *Model) *Model { - m.Description = "titles must be upcase" - return m -} - -type TOC struct { - Titles []Name -} - -type Discography struct { - Title Name - TOC -} - -// clear && go test -v -test.run TestEmbeddedStructPull204 ...swagger -func TestEmbeddedStructPull204(t *testing.T) { - b := Discography{} - testJsonFromStruct(t, b, ` -{ - "swagger.Discography": { - "id": "swagger.Discography", - "required": [ - "Title", - "Titles" - ], - "properties": { - "Title": { - "$ref": "swagger.Name" - }, - "Titles": { - "type": "array", - "items": { - "$ref": "swagger.Name" - } - } - } - }, - "swagger.Name": { - "id": "swagger.Name", - "required": [ - "Value" - ], - "properties": { - "Value": { - "type": "string" - } - } - } - } -`) -} - -type AddressWithMethod struct { - Country string `json:"country,omitempty"` - PostCode int `json:"postcode,omitempty"` -} - -func (AddressWithMethod) SwaggerDoc() map[string]string { - return map[string]string{ - "": "Address doc", - "country": "Country doc", - "postcode": "PostCode doc", - } -} - -func TestDocInMethodSwaggerDoc(t *testing.T) { - expected := `{ - "swagger.AddressWithMethod": { - "id": "swagger.AddressWithMethod", - "description": "Address doc", - "properties": { - "country": { - "type": "string", - "description": "Country doc" - }, - "postcode": { - "type": "integer", - "format": "int32", - "description": "PostCode doc" - } - } - } - }` - testJsonFromStruct(t, AddressWithMethod{}, expected) -} - -type RefDesc struct { - f1 *int64 `description:"desc"` -} - -func TestPtrDescription(t *testing.T) { - b := RefDesc{} - expected := `{ - "swagger.RefDesc": { - "id": "swagger.RefDesc", - "required": [ - "f1" - ], - "properties": { - "f1": { - "type": "integer", - "format": "int64", - "description": "desc" - } - } - } - }` - testJsonFromStruct(t, b, expected) -} - -type A struct { - B `json:",inline"` - C1 `json:"metadata,omitempty"` -} - -type B struct { - SB string -} - -type C1 struct { - SC string -} - -func (A) SwaggerDoc() map[string]string { - return map[string]string{ - "": "A struct", - "B": "B field", // We should not get anything from this - "metadata": "C1 field", - } -} - -func (B) SwaggerDoc() map[string]string { - return map[string]string{ - "": "B struct", - "SB": "SB field", - } -} - -func (C1) SwaggerDoc() map[string]string { - return map[string]string{ - "": "C1 struct", - "SC": "SC field", - } -} - -func TestNestedStructDescription(t *testing.T) { - expected := ` -{ - "swagger.A": { - "id": "swagger.A", - "description": "A struct", - "required": [ - "SB" - ], - "properties": { - "SB": { - "type": "string", - "description": "SB field" - }, - "metadata": { - "$ref": "swagger.C1", - "description": "C1 field" - } - } - }, - "swagger.C1": { - "id": "swagger.C1", - "description": "C1 struct", - "required": [ - "SC" - ], - "properties": { - "SC": { - "type": "string", - "description": "SC field" - } - } - } - } -` - testJsonFromStruct(t, A{}, expected) -} - -// This tests a primitive with type overrides in the struct tags -type FakeInt int -type E struct { - Id FakeInt `type:"integer"` - IP net.IP `type:"string"` -} - -func TestOverridenTypeTagE1(t *testing.T) { - expected := ` -{ - "swagger.E": { - "id": "swagger.E", - "required": [ - "Id", - "IP" - ], - "properties": { - "Id": { - "type": "integer" - }, - "IP": { - "type": "string" - } - } - } - } -` - testJsonFromStruct(t, E{}, expected) -} diff --git a/vendor/github.com/emicklei/go-restful/swagger/model_list_test.go b/vendor/github.com/emicklei/go-restful/swagger/model_list_test.go deleted file mode 100644 index 9a9ab919b..000000000 --- a/vendor/github.com/emicklei/go-restful/swagger/model_list_test.go +++ /dev/null @@ -1,48 +0,0 @@ -package swagger - -import ( - "encoding/json" - "testing" -) - -func TestModelList(t *testing.T) { - m := Model{} - m.Id = "m" - l := ModelList{} - l.Put("m", m) - k, ok := l.At("m") - if !ok { - t.Error("want model back") - } - if got, want := k.Id, "m"; got != want { - t.Errorf("got %v want %v", got, want) - } -} - -func TestModelList_Marshal(t *testing.T) { - l := ModelList{} - m := Model{Id: "myid"} - l.Put("myid", m) - data, err := json.Marshal(l) - if err != nil { - t.Error(err) - } - if got, want := string(data), `{"myid":{"id":"myid","properties":{}}}`; got != want { - t.Errorf("got %v want %v", got, want) - } -} - -func TestModelList_Unmarshal(t *testing.T) { - data := `{"myid":{"id":"myid","properties":{}}}` - l := ModelList{} - if err := json.Unmarshal([]byte(data), &l); err != nil { - t.Error(err) - } - m, ok := l.At("myid") - if !ok { - t.Error("expected myid") - } - if got, want := m.Id, "myid"; got != want { - t.Errorf("got %v want %v", got, want) - } -} diff --git a/vendor/github.com/emicklei/go-restful/swagger/model_property_ext_test.go b/vendor/github.com/emicklei/go-restful/swagger/model_property_ext_test.go deleted file mode 100644 index eff0d59d3..000000000 --- a/vendor/github.com/emicklei/go-restful/swagger/model_property_ext_test.go +++ /dev/null @@ -1,60 +0,0 @@ -package swagger - -import ( - "net" - "testing" -) - -// clear && go test -v -test.run TestThatExtraTagsAreReadIntoModel ...swagger -func TestThatExtraTagsAreReadIntoModel(t *testing.T) { - type fakeint int - type Anything struct { - Name string `description:"name" modelDescription:"a test"` - Size int `minimum:"0" maximum:"10"` - Stati string `enum:"off|on" default:"on" modelDescription:"more description"` - ID string `unique:"true"` - FakeInt fakeint `type:"integer"` - IP net.IP `type:"string"` - Password string - } - m := modelsFromStruct(Anything{}) - props, _ := m.At("swagger.Anything") - p1, _ := props.Properties.At("Name") - if got, want := p1.Description, "name"; got != want { - t.Errorf("got %v want %v", got, want) - } - p2, _ := props.Properties.At("Size") - if got, want := p2.Minimum, "0"; got != want { - t.Errorf("got %v want %v", got, want) - } - if got, want := p2.Maximum, "10"; got != want { - t.Errorf("got %v want %v", got, want) - } - p3, _ := props.Properties.At("Stati") - if got, want := p3.Enum[0], "off"; got != want { - t.Errorf("got %v want %v", got, want) - } - if got, want := p3.Enum[1], "on"; got != want { - t.Errorf("got %v want %v", got, want) - } - p4, _ := props.Properties.At("ID") - if got, want := *p4.UniqueItems, true; got != want { - t.Errorf("got %v want %v", got, want) - } - p5, _ := props.Properties.At("Password") - if got, want := *p5.Type, "string"; got != want { - t.Errorf("got %v want %v", got, want) - } - p6, _ := props.Properties.At("FakeInt") - if got, want := *p6.Type, "integer"; got != want { - t.Errorf("got %v want %v", got, want) - } - p7, _ := props.Properties.At("IP") - if got, want := *p7.Type, "string"; got != want { - t.Errorf("got %v want %v", got, want) - } - - if got, want := props.Description, "a test\nmore description"; got != want { - t.Errorf("got %v want %v", got, want) - } -} diff --git a/vendor/github.com/emicklei/go-restful/swagger/model_property_list_test.go b/vendor/github.com/emicklei/go-restful/swagger/model_property_list_test.go deleted file mode 100644 index 2833ad8fd..000000000 --- a/vendor/github.com/emicklei/go-restful/swagger/model_property_list_test.go +++ /dev/null @@ -1,47 +0,0 @@ -package swagger - -import ( - "encoding/json" - "testing" -) - -func TestModelPropertyList(t *testing.T) { - l := ModelPropertyList{} - p := ModelProperty{Description: "d"} - l.Put("p", p) - q, ok := l.At("p") - if !ok { - t.Error("expected p") - } - if got, want := q.Description, "d"; got != want { - t.Errorf("got %v want %v", got, want) - } -} - -func TestModelPropertyList_Marshal(t *testing.T) { - l := ModelPropertyList{} - p := ModelProperty{Description: "d"} - l.Put("p", p) - data, err := json.Marshal(l) - if err != nil { - t.Error(err) - } - if got, want := string(data), `{"p":{"description":"d"}}`; got != want { - t.Errorf("got %v want %v", got, want) - } -} - -func TestModelPropertyList_Unmarshal(t *testing.T) { - data := `{"p":{"description":"d"}}` - l := ModelPropertyList{} - if err := json.Unmarshal([]byte(data), &l); err != nil { - t.Error(err) - } - m, ok := l.At("p") - if !ok { - t.Error("expected p") - } - if got, want := m.Description, "d"; got != want { - t.Errorf("got %v want %v", got, want) - } -} diff --git a/vendor/github.com/emicklei/go-restful/swagger/ordered_route_map_test.go b/vendor/github.com/emicklei/go-restful/swagger/ordered_route_map_test.go deleted file mode 100644 index 964e7da05..000000000 --- a/vendor/github.com/emicklei/go-restful/swagger/ordered_route_map_test.go +++ /dev/null @@ -1,29 +0,0 @@ -package swagger - -import ( - "testing" - - "github.com/emicklei/go-restful" -) - -// go test -v -test.run TestOrderedRouteMap ...swagger -func TestOrderedRouteMap(t *testing.T) { - m := newOrderedRouteMap() - r1 := restful.Route{Path: "/r1"} - r2 := restful.Route{Path: "/r2"} - m.Add("a", r1) - m.Add("b", r2) - m.Add("b", r1) - m.Add("d", r2) - m.Add("c", r2) - order := "" - m.Do(func(k string, routes []restful.Route) { - order += k - if len(routes) == 0 { - t.Fail() - } - }) - if order != "abdc" { - t.Fail() - } -} diff --git a/vendor/github.com/emicklei/go-restful/swagger/postbuild_model_test.go b/vendor/github.com/emicklei/go-restful/swagger/postbuild_model_test.go deleted file mode 100644 index 3e20d2f5b..000000000 --- a/vendor/github.com/emicklei/go-restful/swagger/postbuild_model_test.go +++ /dev/null @@ -1,42 +0,0 @@ -package swagger - -import "testing" - -type Boat struct { - Length int `json:"-"` // on default, this makes the fields not required - Weight int `json:"-"` -} - -// PostBuildModel is from swagger.ModelBuildable -func (b Boat) PostBuildModel(m *Model) *Model { - // override required - m.Required = []string{"Length", "Weight"} - - // add model property (just to test is can be added; is this a real usecase?) - extraType := "string" - m.Properties.Put("extra", ModelProperty{ - Description: "extra description", - DataTypeFields: DataTypeFields{ - Type: &extraType, - }, - }) - return m -} - -func TestCustomPostModelBuilde(t *testing.T) { - testJsonFromStruct(t, Boat{}, `{ - "swagger.Boat": { - "id": "swagger.Boat", - "required": [ - "Length", - "Weight" - ], - "properties": { - "extra": { - "type": "string", - "description": "extra description" - } - } - } -}`) -} diff --git a/vendor/github.com/emicklei/go-restful/swagger/swagger_test.go b/vendor/github.com/emicklei/go-restful/swagger/swagger_test.go deleted file mode 100644 index 78e2d43cc..000000000 --- a/vendor/github.com/emicklei/go-restful/swagger/swagger_test.go +++ /dev/null @@ -1,284 +0,0 @@ -package swagger - -import ( - "encoding/json" - "testing" - - "github.com/emicklei/go-restful" - "github.com/emicklei/go-restful/swagger/test_package" -) - -func TestInfoStruct_Issue231(t *testing.T) { - config := Config{ - Info: Info{ - Title: "Title", - Description: "Description", - TermsOfServiceUrl: "http://example.com", - Contact: "example@example.com", - License: "License", - LicenseUrl: "http://example.com/license.txt", - }, - } - sws := newSwaggerService(config) - str, err := json.MarshalIndent(sws.produceListing(), "", " ") - if err != nil { - t.Fatal(err) - } - compareJson(t, string(str), ` - { - "apiVersion": "", - "swaggerVersion": "1.2", - "apis": null, - "info": { - "title": "Title", - "description": "Description", - "termsOfServiceUrl": "http://example.com", - "contact": "example@example.com", - "license": "License", - "licenseUrl": "http://example.com/license.txt" - } - } - `) -} - -// go test -v -test.run TestThatMultiplePathsOnRootAreHandled ...swagger -func TestThatMultiplePathsOnRootAreHandled(t *testing.T) { - ws1 := new(restful.WebService) - ws1.Route(ws1.GET("/_ping").To(dummy)) - ws1.Route(ws1.GET("/version").To(dummy)) - - cfg := Config{ - WebServicesUrl: "http://here.com", - ApiPath: "/apipath", - WebServices: []*restful.WebService{ws1}, - } - sws := newSwaggerService(cfg) - decl := sws.composeDeclaration(ws1, "/") - if got, want := len(decl.Apis), 2; got != want { - t.Errorf("got %v want %v", got, want) - } -} - -func TestWriteSamples(t *testing.T) { - ws1 := new(restful.WebService) - ws1.Route(ws1.GET("/object").To(dummy).Writes(test_package.TestStruct{})) - ws1.Route(ws1.GET("/array").To(dummy).Writes([]test_package.TestStruct{})) - ws1.Route(ws1.GET("/object_and_array").To(dummy).Writes(struct{ Abc test_package.TestStruct }{})) - - cfg := Config{ - WebServicesUrl: "http://here.com", - ApiPath: "/apipath", - WebServices: []*restful.WebService{ws1}, - } - sws := newSwaggerService(cfg) - - decl := sws.composeDeclaration(ws1, "/") - - str, err := json.MarshalIndent(decl.Apis, "", " ") - if err != nil { - t.Fatal(err) - } - - compareJson(t, string(str), ` - [ - { - "path": "/object", - "description": "", - "operations": [ - { - "type": "test_package.TestStruct", - "method": "GET", - "nickname": "dummy", - "parameters": [] - } - ] - }, - { - "path": "/array", - "description": "", - "operations": [ - { - "type": "array", - "items": { - "$ref": "test_package.TestStruct" - }, - "method": "GET", - "nickname": "dummy", - "parameters": [] - } - ] - }, - { - "path": "/object_and_array", - "description": "", - "operations": [ - { - "type": "struct { Abc test_package.TestStruct }", - "method": "GET", - "nickname": "dummy", - "parameters": [] - } - ] - } - ]`) - - str, err = json.MarshalIndent(decl.Models, "", " ") - if err != nil { - t.Fatal(err) - } - compareJson(t, string(str), ` - { - "test_package.TestStruct": { - "id": "test_package.TestStruct", - "required": [ - "TestField" - ], - "properties": { - "TestField": { - "type": "string" - } - } - }, - "||test_package.TestStruct": { - "id": "||test_package.TestStruct", - "properties": {} - }, - "struct { Abc test_package.TestStruct }": { - "id": "struct { Abc test_package.TestStruct }", - "required": [ - "Abc" - ], - "properties": { - "Abc": { - "$ref": "test_package.TestStruct" - } - } - } - }`) -} - -// go test -v -test.run TestServiceToApi ...swagger -func TestServiceToApi(t *testing.T) { - ws := new(restful.WebService) - ws.Path("/tests") - ws.Consumes(restful.MIME_JSON) - ws.Produces(restful.MIME_XML) - ws.Route(ws.GET("/a").To(dummy).Writes(sample{})) - ws.Route(ws.PUT("/b").To(dummy).Writes(sample{})) - ws.Route(ws.POST("/c").To(dummy).Writes(sample{})) - ws.Route(ws.DELETE("/d").To(dummy).Writes(sample{})) - - ws.Route(ws.GET("/d").To(dummy).Writes(sample{})) - ws.Route(ws.PUT("/c").To(dummy).Writes(sample{})) - ws.Route(ws.POST("/b").To(dummy).Writes(sample{})) - ws.Route(ws.DELETE("/a").To(dummy).Writes(sample{})) - ws.ApiVersion("1.2.3") - cfg := Config{ - WebServicesUrl: "http://here.com", - ApiPath: "/apipath", - WebServices: []*restful.WebService{ws}, - PostBuildHandler: func(in *ApiDeclarationList) {}, - } - sws := newSwaggerService(cfg) - decl := sws.composeDeclaration(ws, "/tests") - // checks - if decl.ApiVersion != "1.2.3" { - t.Errorf("got %v want %v", decl.ApiVersion, "1.2.3") - } - if decl.BasePath != "http://here.com" { - t.Errorf("got %v want %v", decl.BasePath, "http://here.com") - } - if len(decl.Apis) != 4 { - t.Errorf("got %v want %v", len(decl.Apis), 4) - } - pathOrder := "" - for _, each := range decl.Apis { - pathOrder += each.Path - for _, other := range each.Operations { - pathOrder += other.Method - } - } - - if pathOrder != "/tests/aGETDELETE/tests/bPUTPOST/tests/cPOSTPUT/tests/dDELETEGET" { - t.Errorf("got %v want %v", pathOrder, "see test source") - } -} - -func dummy(i *restful.Request, o *restful.Response) {} - -// go test -v -test.run TestIssue78 ...swagger -type Response struct { - Code int - Users *[]User - Items *[]TestItem -} -type User struct { - Id, Name string -} -type TestItem struct { - Id, Name string -} - -// clear && go test -v -test.run TestComposeResponseMessages ...swagger -func TestComposeResponseMessages(t *testing.T) { - responseErrors := map[int]restful.ResponseError{} - responseErrors[400] = restful.ResponseError{Code: 400, Message: "Bad Request", Model: TestItem{}} - route := restful.Route{ResponseErrors: responseErrors} - decl := new(ApiDeclaration) - decl.Models = ModelList{} - msgs := composeResponseMessages(route, decl) - if msgs[0].ResponseModel != "swagger.TestItem" { - t.Errorf("got %s want swagger.TestItem", msgs[0].ResponseModel) - } -} - -// clear && go test -v -test.run TestComposeResponseMessageArray ...swagger -func TestComposeResponseMessageArray(t *testing.T) { - responseErrors := map[int]restful.ResponseError{} - responseErrors[400] = restful.ResponseError{Code: 400, Message: "Bad Request", Model: []TestItem{}} - route := restful.Route{ResponseErrors: responseErrors} - decl := new(ApiDeclaration) - decl.Models = ModelList{} - msgs := composeResponseMessages(route, decl) - if msgs[0].ResponseModel != "array[swagger.TestItem]" { - t.Errorf("got %s want swagger.TestItem", msgs[0].ResponseModel) - } -} - -func TestIssue78(t *testing.T) { - sws := newSwaggerService(Config{}) - models := new(ModelList) - sws.addModelFromSampleTo(&Operation{}, true, Response{Items: &[]TestItem{}}, models) - model, ok := models.At("swagger.Response") - if !ok { - t.Fatal("missing response model") - } - if "swagger.Response" != model.Id { - t.Fatal("wrong model id:" + model.Id) - } - code, ok := model.Properties.At("Code") - if !ok { - t.Fatal("missing code") - } - if "integer" != *code.Type { - t.Fatal("wrong code type:" + *code.Type) - } - items, ok := model.Properties.At("Items") - if !ok { - t.Fatal("missing items") - } - if "array" != *items.Type { - t.Fatal("wrong items type:" + *items.Type) - } - items_items := items.Items - if items_items == nil { - t.Fatal("missing items->items") - } - ref := items_items.Ref - if ref == nil { - t.Fatal("missing $ref") - } - if *ref != "swagger.TestItem" { - t.Fatal("wrong $ref:" + *ref) - } -} diff --git a/vendor/github.com/emicklei/go-restful/swagger/utils_test.go b/vendor/github.com/emicklei/go-restful/swagger/utils_test.go deleted file mode 100644 index dab871032..000000000 --- a/vendor/github.com/emicklei/go-restful/swagger/utils_test.go +++ /dev/null @@ -1,78 +0,0 @@ -package swagger - -import ( - "bytes" - "encoding/json" - "fmt" - "reflect" - "strings" - "testing" -) - -func testJsonFromStruct(t *testing.T, sample interface{}, expectedJson string) bool { - m := modelsFromStruct(sample) - data, _ := json.MarshalIndent(m, " ", " ") - return compareJson(t, string(data), expectedJson) -} - -func modelsFromStruct(sample interface{}) *ModelList { - models := new(ModelList) - builder := modelBuilder{models} - builder.addModelFrom(sample) - return models -} - -func compareJson(t *testing.T, actualJsonAsString string, expectedJsonAsString string) bool { - success := false - var actualMap map[string]interface{} - json.Unmarshal([]byte(actualJsonAsString), &actualMap) - var expectedMap map[string]interface{} - err := json.Unmarshal([]byte(expectedJsonAsString), &expectedMap) - if err != nil { - var actualArray []interface{} - json.Unmarshal([]byte(actualJsonAsString), &actualArray) - var expectedArray []interface{} - err := json.Unmarshal([]byte(expectedJsonAsString), &expectedArray) - success = reflect.DeepEqual(actualArray, expectedArray) - if err != nil { - t.Fatalf("Unparsable expected JSON: %s", err) - } - } else { - success = reflect.DeepEqual(actualMap, expectedMap) - } - if !success { - t.Log("---- expected -----") - t.Log(withLineNumbers(expectedJsonAsString)) - t.Log("---- actual -----") - t.Log(withLineNumbers(actualJsonAsString)) - t.Log("---- raw -----") - t.Log(actualJsonAsString) - t.Error("there are differences") - return false - } - return true -} - -func indexOfNonMatchingLine(actual, expected string) int { - a := strings.Split(actual, "\n") - e := strings.Split(expected, "\n") - size := len(a) - if len(e) < len(a) { - size = len(e) - } - for i := 0; i < size; i++ { - if a[i] != e[i] { - return i - } - } - return -1 -} - -func withLineNumbers(content string) string { - var buffer bytes.Buffer - lines := strings.Split(content, "\n") - for i, each := range lines { - buffer.WriteString(fmt.Sprintf("%d:%s\n", i, each)) - } - return buffer.String() -} diff --git a/vendor/github.com/emicklei/go-restful/tracer_test.go b/vendor/github.com/emicklei/go-restful/tracer_test.go deleted file mode 100644 index 60c1e9fc0..000000000 --- a/vendor/github.com/emicklei/go-restful/tracer_test.go +++ /dev/null @@ -1,18 +0,0 @@ -package restful - -import "testing" - -// Use like this: -// -// TraceLogger(testLogger{t}) -type testLogger struct { - t *testing.T -} - -func (l testLogger) Print(v ...interface{}) { - l.t.Log(v...) -} - -func (l testLogger) Printf(format string, v ...interface{}) { - l.t.Logf(format, v...) -} diff --git a/vendor/github.com/emicklei/go-restful/web_service_test.go b/vendor/github.com/emicklei/go-restful/web_service_test.go deleted file mode 100644 index 469890434..000000000 --- a/vendor/github.com/emicklei/go-restful/web_service_test.go +++ /dev/null @@ -1,254 +0,0 @@ -package restful - -import ( - "net/http" - "net/http/httptest" - "testing" -) - -const ( - pathGetFriends = "/get/{userId}/friends" -) - -func TestParameter(t *testing.T) { - p := &Parameter{&ParameterData{Name: "name", Description: "desc"}} - p.AllowMultiple(true) - p.DataType("int") - p.Required(true) - values := map[string]string{"a": "b"} - p.AllowableValues(values) - p.bePath() - - ws := new(WebService) - ws.Param(p) - if ws.pathParameters[0].Data().Name != "name" { - t.Error("path parameter (or name) invalid") - } -} -func TestWebService_CanCreateParameterKinds(t *testing.T) { - ws := new(WebService) - if ws.BodyParameter("b", "b").Kind() != BodyParameterKind { - t.Error("body parameter expected") - } - if ws.PathParameter("p", "p").Kind() != PathParameterKind { - t.Error("path parameter expected") - } - if ws.QueryParameter("q", "q").Kind() != QueryParameterKind { - t.Error("query parameter expected") - } -} - -func TestCapturePanic(t *testing.T) { - tearDown() - Add(newPanicingService()) - httpRequest, _ := http.NewRequest("GET", "http://here.com/fire", nil) - httpRequest.Header.Set("Accept", "*/*") - httpWriter := httptest.NewRecorder() - DefaultContainer.dispatch(httpWriter, httpRequest) - if 500 != httpWriter.Code { - t.Error("500 expected on fire") - } -} - -func TestCapturePanicWithEncoded(t *testing.T) { - tearDown() - Add(newPanicingService()) - DefaultContainer.EnableContentEncoding(true) - httpRequest, _ := http.NewRequest("GET", "http://here.com/fire", nil) - httpRequest.Header.Set("Accept", "*/*") - httpRequest.Header.Set("Accept-Encoding", "gzip") - httpWriter := httptest.NewRecorder() - DefaultContainer.dispatch(httpWriter, httpRequest) - if 500 != httpWriter.Code { - t.Error("500 expected on fire, got", httpWriter.Code) - } -} - -func TestNotFound(t *testing.T) { - tearDown() - httpRequest, _ := http.NewRequest("GET", "http://here.com/missing", nil) - httpRequest.Header.Set("Accept", "*/*") - httpWriter := httptest.NewRecorder() - DefaultContainer.dispatch(httpWriter, httpRequest) - if 404 != httpWriter.Code { - t.Error("404 expected on missing") - } -} - -func TestMethodNotAllowed(t *testing.T) { - tearDown() - Add(newGetOnlyService()) - httpRequest, _ := http.NewRequest("POST", "http://here.com/get", nil) - httpRequest.Header.Set("Accept", "*/*") - httpWriter := httptest.NewRecorder() - DefaultContainer.dispatch(httpWriter, httpRequest) - if 405 != httpWriter.Code { - t.Error("405 expected method not allowed") - } -} - -func TestSelectedRoutePath_Issue100(t *testing.T) { - tearDown() - Add(newSelectedRouteTestingService()) - httpRequest, _ := http.NewRequest("GET", "http://here.com/get/232452/friends", nil) - httpRequest.Header.Set("Accept", "*/*") - httpWriter := httptest.NewRecorder() - DefaultContainer.dispatch(httpWriter, httpRequest) - if http.StatusOK != httpWriter.Code { - t.Error(http.StatusOK, "expected,", httpWriter.Code, "received.") - } -} - -func TestContentType415_Issue170(t *testing.T) { - tearDown() - Add(newGetOnlyJsonOnlyService()) - httpRequest, _ := http.NewRequest("GET", "http://here.com/get", nil) - httpWriter := httptest.NewRecorder() - DefaultContainer.dispatch(httpWriter, httpRequest) - if 200 != httpWriter.Code { - t.Errorf("Expected 200, got %d", httpWriter.Code) - } -} - -func TestContentType415_POST_Issue170(t *testing.T) { - tearDown() - Add(newPostOnlyJsonOnlyService()) - httpRequest, _ := http.NewRequest("POST", "http://here.com/post", nil) - httpRequest.Header.Set("Content-Type", "application/json") - httpWriter := httptest.NewRecorder() - DefaultContainer.dispatch(httpWriter, httpRequest) - if 200 != httpWriter.Code { - t.Errorf("Expected 200, got %d", httpWriter.Code) - } -} - -// go test -v -test.run TestContentType406PlainJson ...restful -func TestContentType406PlainJson(t *testing.T) { - tearDown() - TraceLogger(testLogger{t}) - Add(newGetPlainTextOrJsonService()) - httpRequest, _ := http.NewRequest("GET", "http://here.com/get", nil) - httpRequest.Header.Set("Accept", "text/plain") - httpWriter := httptest.NewRecorder() - DefaultContainer.dispatch(httpWriter, httpRequest) - if got, want := httpWriter.Code, 200; got != want { - t.Errorf("got %v, want %v", got, want) - } -} - -func TestRemoveRoute(t *testing.T) { - tearDown() - TraceLogger(testLogger{t}) - ws := newGetPlainTextOrJsonService() - Add(ws) - httpRequest, _ := http.NewRequest("GET", "http://here.com/get", nil) - httpRequest.Header.Set("Accept", "text/plain") - httpWriter := httptest.NewRecorder() - DefaultContainer.dispatch(httpWriter, httpRequest) - if got, want := httpWriter.Code, 200; got != want { - t.Errorf("got %v, want %v", got, want) - } - - // dynamic apis are disabled, should error and do nothing - if err := ws.RemoveRoute("/get", "GET"); err == nil { - t.Error("unexpected non-error") - } - - httpWriter = httptest.NewRecorder() - DefaultContainer.dispatch(httpWriter, httpRequest) - if got, want := httpWriter.Code, 200; got != want { - t.Errorf("got %v, want %v", got, want) - } - - ws.SetDynamicRoutes(true) - if err := ws.RemoveRoute("/get", "GET"); err != nil { - t.Errorf("unexpected error %v", err) - } - - httpWriter = httptest.NewRecorder() - DefaultContainer.dispatch(httpWriter, httpRequest) - if got, want := httpWriter.Code, 404; got != want { - t.Errorf("got %v, want %v", got, want) - } -} - -// go test -v -test.run TestContentTypeOctet_Issue170 ...restful -func TestContentTypeOctet_Issue170(t *testing.T) { - tearDown() - Add(newGetConsumingOctetStreamService()) - // with content-type - httpRequest, _ := http.NewRequest("GET", "http://here.com/get", nil) - httpRequest.Header.Set("Content-Type", MIME_OCTET) - httpWriter := httptest.NewRecorder() - DefaultContainer.dispatch(httpWriter, httpRequest) - if 200 != httpWriter.Code { - t.Errorf("Expected 200, got %d", httpWriter.Code) - } - // without content-type - httpRequest, _ = http.NewRequest("GET", "http://here.com/get", nil) - httpWriter = httptest.NewRecorder() - DefaultContainer.dispatch(httpWriter, httpRequest) - if 200 != httpWriter.Code { - t.Errorf("Expected 200, got %d", httpWriter.Code) - } -} - -func newPanicingService() *WebService { - ws := new(WebService).Path("") - ws.Route(ws.GET("/fire").To(doPanic)) - return ws -} - -func newGetOnlyService() *WebService { - ws := new(WebService).Path("") - ws.Route(ws.GET("/get").To(doPanic)) - return ws -} - -func newPostOnlyJsonOnlyService() *WebService { - ws := new(WebService).Path("") - ws.Consumes("application/json") - ws.Route(ws.POST("/post").To(doNothing)) - return ws -} - -func newGetOnlyJsonOnlyService() *WebService { - ws := new(WebService).Path("") - ws.Consumes("application/json") - ws.Route(ws.GET("/get").To(doNothing)) - return ws -} - -func newGetPlainTextOrJsonService() *WebService { - ws := new(WebService).Path("") - ws.Produces("text/plain", "application/json") - ws.Route(ws.GET("/get").To(doNothing)) - return ws -} - -func newGetConsumingOctetStreamService() *WebService { - ws := new(WebService).Path("") - ws.Consumes("application/octet-stream") - ws.Route(ws.GET("/get").To(doNothing)) - return ws -} - -func newSelectedRouteTestingService() *WebService { - ws := new(WebService).Path("") - ws.Route(ws.GET(pathGetFriends).To(selectedRouteChecker)) - return ws -} - -func selectedRouteChecker(req *Request, resp *Response) { - if req.SelectedRoutePath() != pathGetFriends { - resp.InternalServerError() - } -} - -func doPanic(req *Request, resp *Response) { - println("lightning...") - panic("fire") -} - -func doNothing(req *Request, resp *Response) { -} diff --git a/vendor/github.com/ghodss/yaml/.gitignore b/vendor/github.com/ghodss/yaml/.gitignore deleted file mode 100644 index e256a31e0..000000000 --- a/vendor/github.com/ghodss/yaml/.gitignore +++ /dev/null @@ -1,20 +0,0 @@ -# OSX leaves these everywhere on SMB shares -._* - -# Eclipse files -.classpath -.project -.settings/** - -# Emacs save files -*~ - -# Vim-related files -[._]*.s[a-w][a-z] -[._]s[a-w][a-z] -*.un~ -Session.vim -.netrwhist - -# Go test binaries -*.test diff --git a/vendor/github.com/ghodss/yaml/.travis.yml b/vendor/github.com/ghodss/yaml/.travis.yml deleted file mode 100644 index 0e9d6edc0..000000000 --- a/vendor/github.com/ghodss/yaml/.travis.yml +++ /dev/null @@ -1,7 +0,0 @@ -language: go -go: - - 1.3 - - 1.4 -script: - - go test - - go build diff --git a/vendor/github.com/ghodss/yaml/README.md b/vendor/github.com/ghodss/yaml/README.md deleted file mode 100644 index 0200f75b4..000000000 --- a/vendor/github.com/ghodss/yaml/README.md +++ /dev/null @@ -1,121 +0,0 @@ -# YAML marshaling and unmarshaling support for Go - -[![Build Status](https://travis-ci.org/ghodss/yaml.svg)](https://travis-ci.org/ghodss/yaml) - -## Introduction - -A wrapper around [go-yaml](https://github.com/go-yaml/yaml) designed to enable a better way of handling YAML when marshaling to and from structs. - -In short, this library first converts YAML to JSON using go-yaml and then uses `json.Marshal` and `json.Unmarshal` to convert to or from the struct. This means that it effectively reuses the JSON struct tags as well as the custom JSON methods `MarshalJSON` and `UnmarshalJSON` unlike go-yaml. For a detailed overview of the rationale behind this method, [see this blog post](http://ghodss.com/2014/the-right-way-to-handle-yaml-in-golang/). - -## Compatibility - -This package uses [go-yaml](https://github.com/go-yaml/yaml) and therefore supports [everything go-yaml supports](https://github.com/go-yaml/yaml#compatibility). - -## Caveats - -**Caveat #1:** When using `yaml.Marshal` and `yaml.Unmarshal`, binary data should NOT be preceded with the `!!binary` YAML tag. If you do, go-yaml will convert the binary data from base64 to native binary data, which is not compatible with JSON. You can still use binary in your YAML files though - just store them without the `!!binary` tag and decode the base64 in your code (e.g. in the custom JSON methods `MarshalJSON` and `UnmarshalJSON`). This also has the benefit that your YAML and your JSON binary data will be decoded exactly the same way. As an example: - -``` -BAD: - exampleKey: !!binary gIGC - -GOOD: - exampleKey: gIGC -... and decode the base64 data in your code. -``` - -**Caveat #2:** When using `YAMLToJSON` directly, maps with keys that are maps will result in an error since this is not supported by JSON. This error will occur in `Unmarshal` as well since you can't unmarshal map keys anyways since struct fields can't be keys. - -## Installation and usage - -To install, run: - -``` -$ go get github.com/ghodss/yaml -``` - -And import using: - -``` -import "github.com/ghodss/yaml" -``` - -Usage is very similar to the JSON library: - -```go -package main - -import ( - "fmt" - - "github.com/ghodss/yaml" -) - -type Person struct { - Name string `json:"name"` // Affects YAML field names too. - Age int `json:"age"` -} - -func main() { - // Marshal a Person struct to YAML. - p := Person{"John", 30} - y, err := yaml.Marshal(p) - if err != nil { - fmt.Printf("err: %v\n", err) - return - } - fmt.Println(string(y)) - /* Output: - age: 30 - name: John - */ - - // Unmarshal the YAML back into a Person struct. - var p2 Person - err = yaml.Unmarshal(y, &p2) - if err != nil { - fmt.Printf("err: %v\n", err) - return - } - fmt.Println(p2) - /* Output: - {John 30} - */ -} -``` - -`yaml.YAMLToJSON` and `yaml.JSONToYAML` methods are also available: - -```go -package main - -import ( - "fmt" - - "github.com/ghodss/yaml" -) - -func main() { - j := []byte(`{"name": "John", "age": 30}`) - y, err := yaml.JSONToYAML(j) - if err != nil { - fmt.Printf("err: %v\n", err) - return - } - fmt.Println(string(y)) - /* Output: - name: John - age: 30 - */ - j2, err := yaml.YAMLToJSON(y) - if err != nil { - fmt.Printf("err: %v\n", err) - return - } - fmt.Println(string(j2)) - /* Output: - {"age":30,"name":"John"} - */ -} -``` diff --git a/vendor/github.com/ghodss/yaml/yaml_test.go b/vendor/github.com/ghodss/yaml/yaml_test.go deleted file mode 100644 index 505af4530..000000000 --- a/vendor/github.com/ghodss/yaml/yaml_test.go +++ /dev/null @@ -1,287 +0,0 @@ -package yaml - -import ( - "fmt" - "math" - "reflect" - "strconv" - "testing" -) - -type MarshalTest struct { - A string - B int64 - // Would like to test float64, but it's not supported in go-yaml. - // (See https://github.com/go-yaml/yaml/issues/83.) - C float32 -} - -func TestMarshal(t *testing.T) { - f32String := strconv.FormatFloat(math.MaxFloat32, 'g', -1, 32) - s := MarshalTest{"a", math.MaxInt64, math.MaxFloat32} - e := []byte(fmt.Sprintf("A: a\nB: %d\nC: %s\n", math.MaxInt64, f32String)) - - y, err := Marshal(s) - if err != nil { - t.Errorf("error marshaling YAML: %v", err) - } - - if !reflect.DeepEqual(y, e) { - t.Errorf("marshal YAML was unsuccessful, expected: %#v, got: %#v", - string(e), string(y)) - } -} - -type UnmarshalString struct { - A string - True string -} - -type UnmarshalStringMap struct { - A map[string]string -} - -type UnmarshalNestedString struct { - A NestedString -} - -type NestedString struct { - A string -} - -type UnmarshalSlice struct { - A []NestedSlice -} - -type NestedSlice struct { - B string - C *string -} - -func TestUnmarshal(t *testing.T) { - y := []byte("a: 1") - s1 := UnmarshalString{} - e1 := UnmarshalString{A: "1"} - unmarshal(t, y, &s1, &e1) - - y = []byte("a: true") - s1 = UnmarshalString{} - e1 = UnmarshalString{A: "true"} - unmarshal(t, y, &s1, &e1) - - y = []byte("true: 1") - s1 = UnmarshalString{} - e1 = UnmarshalString{True: "1"} - unmarshal(t, y, &s1, &e1) - - y = []byte("a:\n a: 1") - s2 := UnmarshalNestedString{} - e2 := UnmarshalNestedString{NestedString{"1"}} - unmarshal(t, y, &s2, &e2) - - y = []byte("a:\n - b: abc\n c: def\n - b: 123\n c: 456\n") - s3 := UnmarshalSlice{} - e3 := UnmarshalSlice{[]NestedSlice{NestedSlice{"abc", strPtr("def")}, NestedSlice{"123", strPtr("456")}}} - unmarshal(t, y, &s3, &e3) - - y = []byte("a:\n b: 1") - s4 := UnmarshalStringMap{} - e4 := UnmarshalStringMap{map[string]string{"b": "1"}} - unmarshal(t, y, &s4, &e4) - - y = []byte(` -a: - name: TestA -b: - name: TestB -`) - type NamedThing struct { - Name string `json:"name"` - } - s5 := map[string]*NamedThing{} - e5 := map[string]*NamedThing{ - "a": &NamedThing{Name: "TestA"}, - "b": &NamedThing{Name: "TestB"}, - } - unmarshal(t, y, &s5, &e5) -} - -func unmarshal(t *testing.T, y []byte, s, e interface{}) { - err := Unmarshal(y, s) - if err != nil { - t.Errorf("error unmarshaling YAML: %v", err) - } - - if !reflect.DeepEqual(s, e) { - t.Errorf("unmarshal YAML was unsuccessful, expected: %+#v, got: %+#v", - e, s) - } -} - -type Case struct { - input string - output string - // By default we test that reversing the output == input. But if there is a - // difference in the reversed output, you can optionally specify it here. - reverse *string -} - -type RunType int - -const ( - RunTypeJSONToYAML RunType = iota - RunTypeYAMLToJSON -) - -func TestJSONToYAML(t *testing.T) { - cases := []Case{ - { - `{"t":"a"}`, - "t: a\n", - nil, - }, { - `{"t":null}`, - "t: null\n", - nil, - }, - } - - runCases(t, RunTypeJSONToYAML, cases) -} - -func TestYAMLToJSON(t *testing.T) { - cases := []Case{ - { - "t: a\n", - `{"t":"a"}`, - nil, - }, { - "t: \n", - `{"t":null}`, - strPtr("t: null\n"), - }, { - "t: null\n", - `{"t":null}`, - nil, - }, { - "1: a\n", - `{"1":"a"}`, - strPtr("\"1\": a\n"), - }, { - "1000000000000000000000000000000000000: a\n", - `{"1e+36":"a"}`, - strPtr("\"1e+36\": a\n"), - }, { - "1e+36: a\n", - `{"1e+36":"a"}`, - strPtr("\"1e+36\": a\n"), - }, { - "\"1e+36\": a\n", - `{"1e+36":"a"}`, - nil, - }, { - "\"1.2\": a\n", - `{"1.2":"a"}`, - nil, - }, { - "- t: a\n", - `[{"t":"a"}]`, - nil, - }, { - "- t: a\n" + - "- t:\n" + - " b: 1\n" + - " c: 2\n", - `[{"t":"a"},{"t":{"b":1,"c":2}}]`, - nil, - }, { - `[{t: a}, {t: {b: 1, c: 2}}]`, - `[{"t":"a"},{"t":{"b":1,"c":2}}]`, - strPtr("- t: a\n" + - "- t:\n" + - " b: 1\n" + - " c: 2\n"), - }, { - "- t: \n", - `[{"t":null}]`, - strPtr("- t: null\n"), - }, { - "- t: null\n", - `[{"t":null}]`, - nil, - }, - } - - // Cases that should produce errors. - _ = []Case{ - { - "~: a", - `{"null":"a"}`, - nil, - }, { - "a: !!binary gIGC\n", - "{\"a\":\"\x80\x81\x82\"}", - nil, - }, - } - - runCases(t, RunTypeYAMLToJSON, cases) -} - -func runCases(t *testing.T, runType RunType, cases []Case) { - var f func([]byte) ([]byte, error) - var invF func([]byte) ([]byte, error) - var msg string - var invMsg string - if runType == RunTypeJSONToYAML { - f = JSONToYAML - invF = YAMLToJSON - msg = "JSON to YAML" - invMsg = "YAML back to JSON" - } else { - f = YAMLToJSON - invF = JSONToYAML - msg = "YAML to JSON" - invMsg = "JSON back to YAML" - } - - for _, c := range cases { - // Convert the string. - t.Logf("converting %s\n", c.input) - output, err := f([]byte(c.input)) - if err != nil { - t.Errorf("Failed to convert %s, input: `%s`, err: %v", msg, c.input, err) - } - - // Check it against the expected output. - if string(output) != c.output { - t.Errorf("Failed to convert %s, input: `%s`, expected `%s`, got `%s`", - msg, c.input, c.output, string(output)) - } - - // Set the string that we will compare the reversed output to. - reverse := c.input - // If a special reverse string was specified, use that instead. - if c.reverse != nil { - reverse = *c.reverse - } - - // Reverse the output. - input, err := invF(output) - if err != nil { - t.Errorf("Failed to convert %s, input: `%s`, err: %v", invMsg, string(output), err) - } - - // Check the reverse is equal to the input (or to *c.reverse). - if string(input) != reverse { - t.Errorf("Failed to convert %s, input: `%s`, expected `%s`, got `%s`", - invMsg, string(output), reverse, string(input)) - } - } - -} - -// To be able to easily fill in the *Case.reverse string above. -func strPtr(s string) *string { - return &s -} diff --git a/vendor/github.com/go-ini/ini/.gitignore b/vendor/github.com/go-ini/ini/.gitignore deleted file mode 100644 index 12411127b..000000000 --- a/vendor/github.com/go-ini/ini/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -testdata/conf_out.ini -ini.sublime-project -ini.sublime-workspace -testdata/conf_reflect.ini -.idea -/.vscode diff --git a/vendor/github.com/go-ini/ini/.travis.yml b/vendor/github.com/go-ini/ini/.travis.yml deleted file mode 100644 index 9787d4dba..000000000 --- a/vendor/github.com/go-ini/ini/.travis.yml +++ /dev/null @@ -1,13 +0,0 @@ -sudo: false -language: go -go: - - 1.5.x - - 1.6.x - - 1.7.x - - 1.8.x - - 1.9.x - -script: - - go get golang.org/x/tools/cmd/cover - - go get github.com/smartystreets/goconvey - - go test -v -cover -race diff --git a/vendor/github.com/go-ini/ini/Makefile b/vendor/github.com/go-ini/ini/Makefile deleted file mode 100644 index ac034e525..000000000 --- a/vendor/github.com/go-ini/ini/Makefile +++ /dev/null @@ -1,12 +0,0 @@ -.PHONY: build test bench vet - -build: vet bench - -test: - go test -v -cover -race - -bench: - go test -v -cover -race -test.bench=. -test.benchmem - -vet: - go vet diff --git a/vendor/github.com/go-ini/ini/README.md b/vendor/github.com/go-ini/ini/README.md deleted file mode 100644 index f4ff27cd3..000000000 --- a/vendor/github.com/go-ini/ini/README.md +++ /dev/null @@ -1,763 +0,0 @@ -INI [![Build Status](https://travis-ci.org/go-ini/ini.svg?branch=master)](https://travis-ci.org/go-ini/ini) [![Sourcegraph](https://sourcegraph.com/github.com/go-ini/ini/-/badge.svg)](https://sourcegraph.com/github.com/go-ini/ini?badge) -=== - -![](https://avatars0.githubusercontent.com/u/10216035?v=3&s=200) - -Package ini provides INI file read and write functionality in Go. - -[简体中文](README_ZH.md) - -## Feature - -- Load multiple data sources(`[]byte`, file and `io.ReadCloser`) with overwrites. -- Read with recursion values. -- Read with parent-child sections. -- Read with auto-increment key names. -- Read with multiple-line values. -- Read with tons of helper methods. -- Read and convert values to Go types. -- Read and **WRITE** comments of sections and keys. -- Manipulate sections, keys and comments with ease. -- Keep sections and keys in order as you parse and save. - -## Installation - -To use a tagged revision: - - go get gopkg.in/ini.v1 - -To use with latest changes: - - go get github.com/go-ini/ini - -Please add `-u` flag to update in the future. - -### Testing - -If you want to test on your machine, please apply `-t` flag: - - go get -t gopkg.in/ini.v1 - -Please add `-u` flag to update in the future. - -## Getting Started - -### Loading from data sources - -A **Data Source** is either raw data in type `[]byte`, a file name with type `string` or `io.ReadCloser`. You can load **as many data sources as you want**. Passing other types will simply return an error. - -```go -cfg, err := ini.Load([]byte("raw data"), "filename", ioutil.NopCloser(bytes.NewReader([]byte("some other data")))) -``` - -Or start with an empty object: - -```go -cfg := ini.Empty() -``` - -When you cannot decide how many data sources to load at the beginning, you will still be able to **Append()** them later. - -```go -err := cfg.Append("other file", []byte("other raw data")) -``` - -If you have a list of files with possibilities that some of them may not available at the time, and you don't know exactly which ones, you can use `LooseLoad` to ignore nonexistent files without returning error. - -```go -cfg, err := ini.LooseLoad("filename", "filename_404") -``` - -The cool thing is, whenever the file is available to load while you're calling `Reload` method, it will be counted as usual. - -#### Ignore cases of key name - -When you do not care about cases of section and key names, you can use `InsensitiveLoad` to force all names to be lowercased while parsing. - -```go -cfg, err := ini.InsensitiveLoad("filename") -//... - -// sec1 and sec2 are the exactly same section object -sec1, err := cfg.GetSection("Section") -sec2, err := cfg.GetSection("SecTIOn") - -// key1 and key2 are the exactly same key object -key1, err := sec1.GetKey("Key") -key2, err := sec2.GetKey("KeY") -``` - -#### MySQL-like boolean key - -MySQL's configuration allows a key without value as follows: - -```ini -[mysqld] -... -skip-host-cache -skip-name-resolve -``` - -By default, this is considered as missing value. But if you know you're going to deal with those cases, you can assign advanced load options: - -```go -cfg, err := ini.LoadSources(ini.LoadOptions{AllowBooleanKeys: true}, "my.cnf")) -``` - -The value of those keys are always `true`, and when you save to a file, it will keep in the same foramt as you read. - -To generate such keys in your program, you could use `NewBooleanKey`: - -```go -key, err := sec.NewBooleanKey("skip-host-cache") -``` - -#### Comment - -Take care that following format will be treated as comment: - -1. Line begins with `#` or `;` -2. Words after `#` or `;` -3. Words after section name (i.e words after `[some section name]`) - -If you want to save a value with `#` or `;`, please quote them with ``` ` ``` or ``` """ ```. - -Alternatively, you can use following `LoadOptions` to completely ignore inline comments: - -```go -cfg, err := ini.LoadSources(ini.LoadOptions{IgnoreInlineComment: true}, "app.ini")) -``` - -### Working with sections - -To get a section, you would need to: - -```go -section, err := cfg.GetSection("section name") -``` - -For a shortcut for default section, just give an empty string as name: - -```go -section, err := cfg.GetSection("") -``` - -When you're pretty sure the section exists, following code could make your life easier: - -```go -section := cfg.Section("section name") -``` - -What happens when the section somehow does not exist? Don't panic, it automatically creates and returns a new section to you. - -To create a new section: - -```go -err := cfg.NewSection("new section") -``` - -To get a list of sections or section names: - -```go -sections := cfg.Sections() -names := cfg.SectionStrings() -``` - -### Working with keys - -To get a key under a section: - -```go -key, err := cfg.Section("").GetKey("key name") -``` - -Same rule applies to key operations: - -```go -key := cfg.Section("").Key("key name") -``` - -To check if a key exists: - -```go -yes := cfg.Section("").HasKey("key name") -``` - -To create a new key: - -```go -err := cfg.Section("").NewKey("name", "value") -``` - -To get a list of keys or key names: - -```go -keys := cfg.Section("").Keys() -names := cfg.Section("").KeyStrings() -``` - -To get a clone hash of keys and corresponding values: - -```go -hash := cfg.Section("").KeysHash() -``` - -### Working with values - -To get a string value: - -```go -val := cfg.Section("").Key("key name").String() -``` - -To validate key value on the fly: - -```go -val := cfg.Section("").Key("key name").Validate(func(in string) string { - if len(in) == 0 { - return "default" - } - return in -}) -``` - -If you do not want any auto-transformation (such as recursive read) for the values, you can get raw value directly (this way you get much better performance): - -```go -val := cfg.Section("").Key("key name").Value() -``` - -To check if raw value exists: - -```go -yes := cfg.Section("").HasValue("test value") -``` - -To get value with types: - -```go -// For boolean values: -// true when value is: 1, t, T, TRUE, true, True, YES, yes, Yes, y, ON, on, On -// false when value is: 0, f, F, FALSE, false, False, NO, no, No, n, OFF, off, Off -v, err = cfg.Section("").Key("BOOL").Bool() -v, err = cfg.Section("").Key("FLOAT64").Float64() -v, err = cfg.Section("").Key("INT").Int() -v, err = cfg.Section("").Key("INT64").Int64() -v, err = cfg.Section("").Key("UINT").Uint() -v, err = cfg.Section("").Key("UINT64").Uint64() -v, err = cfg.Section("").Key("TIME").TimeFormat(time.RFC3339) -v, err = cfg.Section("").Key("TIME").Time() // RFC3339 - -v = cfg.Section("").Key("BOOL").MustBool() -v = cfg.Section("").Key("FLOAT64").MustFloat64() -v = cfg.Section("").Key("INT").MustInt() -v = cfg.Section("").Key("INT64").MustInt64() -v = cfg.Section("").Key("UINT").MustUint() -v = cfg.Section("").Key("UINT64").MustUint64() -v = cfg.Section("").Key("TIME").MustTimeFormat(time.RFC3339) -v = cfg.Section("").Key("TIME").MustTime() // RFC3339 - -// Methods start with Must also accept one argument for default value -// when key not found or fail to parse value to given type. -// Except method MustString, which you have to pass a default value. - -v = cfg.Section("").Key("String").MustString("default") -v = cfg.Section("").Key("BOOL").MustBool(true) -v = cfg.Section("").Key("FLOAT64").MustFloat64(1.25) -v = cfg.Section("").Key("INT").MustInt(10) -v = cfg.Section("").Key("INT64").MustInt64(99) -v = cfg.Section("").Key("UINT").MustUint(3) -v = cfg.Section("").Key("UINT64").MustUint64(6) -v = cfg.Section("").Key("TIME").MustTimeFormat(time.RFC3339, time.Now()) -v = cfg.Section("").Key("TIME").MustTime(time.Now()) // RFC3339 -``` - -What if my value is three-line long? - -```ini -[advance] -ADDRESS = """404 road, -NotFound, State, 5000 -Earth""" -``` - -Not a problem! - -```go -cfg.Section("advance").Key("ADDRESS").String() - -/* --- start --- -404 road, -NotFound, State, 5000 -Earth ------- end --- */ -``` - -That's cool, how about continuation lines? - -```ini -[advance] -two_lines = how about \ - continuation lines? -lots_of_lines = 1 \ - 2 \ - 3 \ - 4 -``` - -Piece of cake! - -```go -cfg.Section("advance").Key("two_lines").String() // how about continuation lines? -cfg.Section("advance").Key("lots_of_lines").String() // 1 2 3 4 -``` - -Well, I hate continuation lines, how do I disable that? - -```go -cfg, err := ini.LoadSources(ini.LoadOptions{ - IgnoreContinuation: true, -}, "filename") -``` - -Holy crap! - -Note that single quotes around values will be stripped: - -```ini -foo = "some value" // foo: some value -bar = 'some value' // bar: some value -``` - -Sometimes you downloaded file from [Crowdin](https://crowdin.com/) has values like the following (value is surrounded by double quotes and quotes in the value are escaped): - -```ini -create_repo="created repository %s" -``` - -How do you transform this to regular format automatically? - -```go -cfg, err := ini.LoadSources(ini.LoadOptions{UnescapeValueDoubleQuotes: true}, "en-US.ini")) -cfg.Section("").Key("create_repo").String() -// You got: created repository %s -``` - -That's all? Hmm, no. - -#### Helper methods of working with values - -To get value with given candidates: - -```go -v = cfg.Section("").Key("STRING").In("default", []string{"str", "arr", "types"}) -v = cfg.Section("").Key("FLOAT64").InFloat64(1.1, []float64{1.25, 2.5, 3.75}) -v = cfg.Section("").Key("INT").InInt(5, []int{10, 20, 30}) -v = cfg.Section("").Key("INT64").InInt64(10, []int64{10, 20, 30}) -v = cfg.Section("").Key("UINT").InUint(4, []int{3, 6, 9}) -v = cfg.Section("").Key("UINT64").InUint64(8, []int64{3, 6, 9}) -v = cfg.Section("").Key("TIME").InTimeFormat(time.RFC3339, time.Now(), []time.Time{time1, time2, time3}) -v = cfg.Section("").Key("TIME").InTime(time.Now(), []time.Time{time1, time2, time3}) // RFC3339 -``` - -Default value will be presented if value of key is not in candidates you given, and default value does not need be one of candidates. - -To validate value in a given range: - -```go -vals = cfg.Section("").Key("FLOAT64").RangeFloat64(0.0, 1.1, 2.2) -vals = cfg.Section("").Key("INT").RangeInt(0, 10, 20) -vals = cfg.Section("").Key("INT64").RangeInt64(0, 10, 20) -vals = cfg.Section("").Key("UINT").RangeUint(0, 3, 9) -vals = cfg.Section("").Key("UINT64").RangeUint64(0, 3, 9) -vals = cfg.Section("").Key("TIME").RangeTimeFormat(time.RFC3339, time.Now(), minTime, maxTime) -vals = cfg.Section("").Key("TIME").RangeTime(time.Now(), minTime, maxTime) // RFC3339 -``` - -##### Auto-split values into a slice - -To use zero value of type for invalid inputs: - -```go -// Input: 1.1, 2.2, 3.3, 4.4 -> [1.1 2.2 3.3 4.4] -// Input: how, 2.2, are, you -> [0.0 2.2 0.0 0.0] -vals = cfg.Section("").Key("STRINGS").Strings(",") -vals = cfg.Section("").Key("FLOAT64S").Float64s(",") -vals = cfg.Section("").Key("INTS").Ints(",") -vals = cfg.Section("").Key("INT64S").Int64s(",") -vals = cfg.Section("").Key("UINTS").Uints(",") -vals = cfg.Section("").Key("UINT64S").Uint64s(",") -vals = cfg.Section("").Key("TIMES").Times(",") -``` - -To exclude invalid values out of result slice: - -```go -// Input: 1.1, 2.2, 3.3, 4.4 -> [1.1 2.2 3.3 4.4] -// Input: how, 2.2, are, you -> [2.2] -vals = cfg.Section("").Key("FLOAT64S").ValidFloat64s(",") -vals = cfg.Section("").Key("INTS").ValidInts(",") -vals = cfg.Section("").Key("INT64S").ValidInt64s(",") -vals = cfg.Section("").Key("UINTS").ValidUints(",") -vals = cfg.Section("").Key("UINT64S").ValidUint64s(",") -vals = cfg.Section("").Key("TIMES").ValidTimes(",") -``` - -Or to return nothing but error when have invalid inputs: - -```go -// Input: 1.1, 2.2, 3.3, 4.4 -> [1.1 2.2 3.3 4.4] -// Input: how, 2.2, are, you -> error -vals = cfg.Section("").Key("FLOAT64S").StrictFloat64s(",") -vals = cfg.Section("").Key("INTS").StrictInts(",") -vals = cfg.Section("").Key("INT64S").StrictInt64s(",") -vals = cfg.Section("").Key("UINTS").StrictUints(",") -vals = cfg.Section("").Key("UINT64S").StrictUint64s(",") -vals = cfg.Section("").Key("TIMES").StrictTimes(",") -``` - -### Save your configuration - -Finally, it's time to save your configuration to somewhere. - -A typical way to save configuration is writing it to a file: - -```go -// ... -err = cfg.SaveTo("my.ini") -err = cfg.SaveToIndent("my.ini", "\t") -``` - -Another way to save is writing to a `io.Writer` interface: - -```go -// ... -cfg.WriteTo(writer) -cfg.WriteToIndent(writer, "\t") -``` - -By default, spaces are used to align "=" sign between key and values, to disable that: - -```go -ini.PrettyFormat = false -``` - -## Advanced Usage - -### Recursive Values - -For all value of keys, there is a special syntax `%()s`, where `` is the key name in same section or default section, and `%()s` will be replaced by corresponding value(empty string if key not found). You can use this syntax at most 99 level of recursions. - -```ini -NAME = ini - -[author] -NAME = Unknwon -GITHUB = https://github.com/%(NAME)s - -[package] -FULL_NAME = github.com/go-ini/%(NAME)s -``` - -```go -cfg.Section("author").Key("GITHUB").String() // https://github.com/Unknwon -cfg.Section("package").Key("FULL_NAME").String() // github.com/go-ini/ini -``` - -### Parent-child Sections - -You can use `.` in section name to indicate parent-child relationship between two or more sections. If the key not found in the child section, library will try again on its parent section until there is no parent section. - -```ini -NAME = ini -VERSION = v1 -IMPORT_PATH = gopkg.in/%(NAME)s.%(VERSION)s - -[package] -CLONE_URL = https://%(IMPORT_PATH)s - -[package.sub] -``` - -```go -cfg.Section("package.sub").Key("CLONE_URL").String() // https://gopkg.in/ini.v1 -``` - -#### Retrieve parent keys available to a child section - -```go -cfg.Section("package.sub").ParentKeys() // ["CLONE_URL"] -``` - -### Unparseable Sections - -Sometimes, you have sections that do not contain key-value pairs but raw content, to handle such case, you can use `LoadOptions.UnparsableSections`: - -```go -cfg, err := ini.LoadSources(ini.LoadOptions{UnparseableSections: []string{"COMMENTS"}}, `[COMMENTS] -<1> This slide has the fuel listed in the wrong units `)) - -body := cfg.Section("COMMENTS").Body() - -/* --- start --- -<1> This slide has the fuel listed in the wrong units ------- end --- */ -``` - -### Auto-increment Key Names - -If key name is `-` in data source, then it would be seen as special syntax for auto-increment key name start from 1, and every section is independent on counter. - -```ini -[features] --: Support read/write comments of keys and sections --: Support auto-increment of key names --: Support load multiple files to overwrite key values -``` - -```go -cfg.Section("features").KeyStrings() // []{"#1", "#2", "#3"} -``` - -### Map To Struct - -Want more objective way to play with INI? Cool. - -```ini -Name = Unknwon -age = 21 -Male = true -Born = 1993-01-01T20:17:05Z - -[Note] -Content = Hi is a good man! -Cities = HangZhou, Boston -``` - -```go -type Note struct { - Content string - Cities []string -} - -type Person struct { - Name string - Age int `ini:"age"` - Male bool - Born time.Time - Note - Created time.Time `ini:"-"` -} - -func main() { - cfg, err := ini.Load("path/to/ini") - // ... - p := new(Person) - err = cfg.MapTo(p) - // ... - - // Things can be simpler. - err = ini.MapTo(p, "path/to/ini") - // ... - - // Just map a section? Fine. - n := new(Note) - err = cfg.Section("Note").MapTo(n) - // ... -} -``` - -Can I have default value for field? Absolutely. - -Assign it before you map to struct. It will keep the value as it is if the key is not presented or got wrong type. - -```go -// ... -p := &Person{ - Name: "Joe", -} -// ... -``` - -It's really cool, but what's the point if you can't give me my file back from struct? - -### Reflect From Struct - -Why not? - -```go -type Embeded struct { - Dates []time.Time `delim:"|" comment:"Time data"` - Places []string `ini:"places,omitempty"` - None []int `ini:",omitempty"` -} - -type Author struct { - Name string `ini:"NAME"` - Male bool - Age int `comment:"Author's age"` - GPA float64 - NeverMind string `ini:"-"` - *Embeded `comment:"Embeded section"` -} - -func main() { - a := &Author{"Unknwon", true, 21, 2.8, "", - &Embeded{ - []time.Time{time.Now(), time.Now()}, - []string{"HangZhou", "Boston"}, - []int{}, - }} - cfg := ini.Empty() - err = ini.ReflectFrom(cfg, a) - // ... -} -``` - -So, what do I get? - -```ini -NAME = Unknwon -Male = true -; Author's age -Age = 21 -GPA = 2.8 - -; Embeded section -[Embeded] -; Time data -Dates = 2015-08-07T22:14:22+08:00|2015-08-07T22:14:22+08:00 -places = HangZhou,Boston -``` - -#### Name Mapper - -To save your time and make your code cleaner, this library supports [`NameMapper`](https://gowalker.org/gopkg.in/ini.v1#NameMapper) between struct field and actual section and key name. - -There are 2 built-in name mappers: - -- `AllCapsUnderscore`: it converts to format `ALL_CAPS_UNDERSCORE` then match section or key. -- `TitleUnderscore`: it converts to format `title_underscore` then match section or key. - -To use them: - -```go -type Info struct { - PackageName string -} - -func main() { - err = ini.MapToWithMapper(&Info{}, ini.TitleUnderscore, []byte("package_name=ini")) - // ... - - cfg, err := ini.Load([]byte("PACKAGE_NAME=ini")) - // ... - info := new(Info) - cfg.NameMapper = ini.AllCapsUnderscore - err = cfg.MapTo(info) - // ... -} -``` - -Same rules of name mapper apply to `ini.ReflectFromWithMapper` function. - -#### Value Mapper - -To expand values (e.g. from environment variables), you can use the `ValueMapper` to transform values: - -```go -type Env struct { - Foo string `ini:"foo"` -} - -func main() { - cfg, err := ini.Load([]byte("[env]\nfoo = ${MY_VAR}\n") - cfg.ValueMapper = os.ExpandEnv - // ... - env := &Env{} - err = cfg.Section("env").MapTo(env) -} -``` - -This would set the value of `env.Foo` to the value of the environment variable `MY_VAR`. - -#### Other Notes On Map/Reflect - -Any embedded struct is treated as a section by default, and there is no automatic parent-child relations in map/reflect feature: - -```go -type Child struct { - Age string -} - -type Parent struct { - Name string - Child -} - -type Config struct { - City string - Parent -} -``` - -Example configuration: - -```ini -City = Boston - -[Parent] -Name = Unknwon - -[Child] -Age = 21 -``` - -What if, yes, I'm paranoid, I want embedded struct to be in the same section. Well, all roads lead to Rome. - -```go -type Child struct { - Age string -} - -type Parent struct { - Name string - Child `ini:"Parent"` -} - -type Config struct { - City string - Parent -} -``` - -Example configuration: - -```ini -City = Boston - -[Parent] -Name = Unknwon -Age = 21 -``` - -## Getting Help - -- [API Documentation](https://gowalker.org/gopkg.in/ini.v1) -- [File An Issue](https://github.com/go-ini/ini/issues/new) - -## FAQs - -### What does `BlockMode` field do? - -By default, library lets you read and write values so we need a locker to make sure your data is safe. But in cases that you are very sure about only reading data through the library, you can set `cfg.BlockMode = false` to speed up read operations about **50-70%** faster. - -### Why another INI library? - -Many people are using my another INI library [goconfig](https://github.com/Unknwon/goconfig), so the reason for this one is I would like to make more Go style code. Also when you set `cfg.BlockMode = false`, this one is about **10-30%** faster. - -To make those changes I have to confirm API broken, so it's safer to keep it in another place and start using `gopkg.in` to version my package at this time.(PS: shorter import path) - -## License - -This project is under Apache v2 License. See the [LICENSE](LICENSE) file for the full license text. diff --git a/vendor/github.com/go-ini/ini/README_ZH.md b/vendor/github.com/go-ini/ini/README_ZH.md deleted file mode 100644 index 69aefef12..000000000 --- a/vendor/github.com/go-ini/ini/README_ZH.md +++ /dev/null @@ -1,750 +0,0 @@ -本包提供了 Go 语言中读写 INI 文件的功能。 - -## 功能特性 - -- 支持覆盖加载多个数据源(`[]byte`、文件和 `io.ReadCloser`) -- 支持递归读取键值 -- 支持读取父子分区 -- 支持读取自增键名 -- 支持读取多行的键值 -- 支持大量辅助方法 -- 支持在读取时直接转换为 Go 语言类型 -- 支持读取和 **写入** 分区和键的注释 -- 轻松操作分区、键值和注释 -- 在保存文件时分区和键值会保持原有的顺序 - -## 下载安装 - -使用一个特定版本: - - go get gopkg.in/ini.v1 - -使用最新版: - - go get github.com/go-ini/ini - -如需更新请添加 `-u` 选项。 - -### 测试安装 - -如果您想要在自己的机器上运行测试,请使用 `-t` 标记: - - go get -t gopkg.in/ini.v1 - -如需更新请添加 `-u` 选项。 - -## 开始使用 - -### 从数据源加载 - -一个 **数据源** 可以是 `[]byte` 类型的原始数据,`string` 类型的文件路径或 `io.ReadCloser`。您可以加载 **任意多个** 数据源。如果您传递其它类型的数据源,则会直接返回错误。 - -```go -cfg, err := ini.Load([]byte("raw data"), "filename", ioutil.NopCloser(bytes.NewReader([]byte("some other data")))) -``` - -或者从一个空白的文件开始: - -```go -cfg := ini.Empty() -``` - -当您在一开始无法决定需要加载哪些数据源时,仍可以使用 **Append()** 在需要的时候加载它们。 - -```go -err := cfg.Append("other file", []byte("other raw data")) -``` - -当您想要加载一系列文件,但是不能够确定其中哪些文件是不存在的,可以通过调用函数 `LooseLoad` 来忽略它们(`Load` 会因为文件不存在而返回错误): - -```go -cfg, err := ini.LooseLoad("filename", "filename_404") -``` - -更牛逼的是,当那些之前不存在的文件在重新调用 `Reload` 方法的时候突然出现了,那么它们会被正常加载。 - -#### 忽略键名的大小写 - -有时候分区和键的名称大小写混合非常烦人,这个时候就可以通过 `InsensitiveLoad` 将所有分区和键名在读取里强制转换为小写: - -```go -cfg, err := ini.InsensitiveLoad("filename") -//... - -// sec1 和 sec2 指向同一个分区对象 -sec1, err := cfg.GetSection("Section") -sec2, err := cfg.GetSection("SecTIOn") - -// key1 和 key2 指向同一个键对象 -key1, err := sec1.GetKey("Key") -key2, err := sec2.GetKey("KeY") -``` - -#### 类似 MySQL 配置中的布尔值键 - -MySQL 的配置文件中会出现没有具体值的布尔类型的键: - -```ini -[mysqld] -... -skip-host-cache -skip-name-resolve -``` - -默认情况下这被认为是缺失值而无法完成解析,但可以通过高级的加载选项对它们进行处理: - -```go -cfg, err := ini.LoadSources(ini.LoadOptions{AllowBooleanKeys: true}, "my.cnf")) -``` - -这些键的值永远为 `true`,且在保存到文件时也只会输出键名。 - -如果您想要通过程序来生成此类键,则可以使用 `NewBooleanKey`: - -```go -key, err := sec.NewBooleanKey("skip-host-cache") -``` - -#### 关于注释 - -下述几种情况的内容将被视为注释: - -1. 所有以 `#` 或 `;` 开头的行 -2. 所有在 `#` 或 `;` 之后的内容 -3. 分区标签后的文字 (即 `[分区名]` 之后的内容) - -如果你希望使用包含 `#` 或 `;` 的值,请使用 ``` ` ``` 或 ``` """ ``` 进行包覆。 - -除此之外,您还可以通过 `LoadOptions` 完全忽略行内注释: - -```go -cfg, err := ini.LoadSources(ini.LoadOptions{IgnoreInlineComment: true}, "app.ini")) -``` - -### 操作分区(Section) - -获取指定分区: - -```go -section, err := cfg.GetSection("section name") -``` - -如果您想要获取默认分区,则可以用空字符串代替分区名: - -```go -section, err := cfg.GetSection("") -``` - -当您非常确定某个分区是存在的,可以使用以下简便方法: - -```go -section := cfg.Section("section name") -``` - -如果不小心判断错了,要获取的分区其实是不存在的,那会发生什么呢?没事的,它会自动创建并返回一个对应的分区对象给您。 - -创建一个分区: - -```go -err := cfg.NewSection("new section") -``` - -获取所有分区对象或名称: - -```go -sections := cfg.Sections() -names := cfg.SectionStrings() -``` - -### 操作键(Key) - -获取某个分区下的键: - -```go -key, err := cfg.Section("").GetKey("key name") -``` - -和分区一样,您也可以直接获取键而忽略错误处理: - -```go -key := cfg.Section("").Key("key name") -``` - -判断某个键是否存在: - -```go -yes := cfg.Section("").HasKey("key name") -``` - -创建一个新的键: - -```go -err := cfg.Section("").NewKey("name", "value") -``` - -获取分区下的所有键或键名: - -```go -keys := cfg.Section("").Keys() -names := cfg.Section("").KeyStrings() -``` - -获取分区下的所有键值对的克隆: - -```go -hash := cfg.Section("").KeysHash() -``` - -### 操作键值(Value) - -获取一个类型为字符串(string)的值: - -```go -val := cfg.Section("").Key("key name").String() -``` - -获取值的同时通过自定义函数进行处理验证: - -```go -val := cfg.Section("").Key("key name").Validate(func(in string) string { - if len(in) == 0 { - return "default" - } - return in -}) -``` - -如果您不需要任何对值的自动转变功能(例如递归读取),可以直接获取原值(这种方式性能最佳): - -```go -val := cfg.Section("").Key("key name").Value() -``` - -判断某个原值是否存在: - -```go -yes := cfg.Section("").HasValue("test value") -``` - -获取其它类型的值: - -```go -// 布尔值的规则: -// true 当值为:1, t, T, TRUE, true, True, YES, yes, Yes, y, ON, on, On -// false 当值为:0, f, F, FALSE, false, False, NO, no, No, n, OFF, off, Off -v, err = cfg.Section("").Key("BOOL").Bool() -v, err = cfg.Section("").Key("FLOAT64").Float64() -v, err = cfg.Section("").Key("INT").Int() -v, err = cfg.Section("").Key("INT64").Int64() -v, err = cfg.Section("").Key("UINT").Uint() -v, err = cfg.Section("").Key("UINT64").Uint64() -v, err = cfg.Section("").Key("TIME").TimeFormat(time.RFC3339) -v, err = cfg.Section("").Key("TIME").Time() // RFC3339 - -v = cfg.Section("").Key("BOOL").MustBool() -v = cfg.Section("").Key("FLOAT64").MustFloat64() -v = cfg.Section("").Key("INT").MustInt() -v = cfg.Section("").Key("INT64").MustInt64() -v = cfg.Section("").Key("UINT").MustUint() -v = cfg.Section("").Key("UINT64").MustUint64() -v = cfg.Section("").Key("TIME").MustTimeFormat(time.RFC3339) -v = cfg.Section("").Key("TIME").MustTime() // RFC3339 - -// 由 Must 开头的方法名允许接收一个相同类型的参数来作为默认值, -// 当键不存在或者转换失败时,则会直接返回该默认值。 -// 但是,MustString 方法必须传递一个默认值。 - -v = cfg.Seciont("").Key("String").MustString("default") -v = cfg.Section("").Key("BOOL").MustBool(true) -v = cfg.Section("").Key("FLOAT64").MustFloat64(1.25) -v = cfg.Section("").Key("INT").MustInt(10) -v = cfg.Section("").Key("INT64").MustInt64(99) -v = cfg.Section("").Key("UINT").MustUint(3) -v = cfg.Section("").Key("UINT64").MustUint64(6) -v = cfg.Section("").Key("TIME").MustTimeFormat(time.RFC3339, time.Now()) -v = cfg.Section("").Key("TIME").MustTime(time.Now()) // RFC3339 -``` - -如果我的值有好多行怎么办? - -```ini -[advance] -ADDRESS = """404 road, -NotFound, State, 5000 -Earth""" -``` - -嗯哼?小 case! - -```go -cfg.Section("advance").Key("ADDRESS").String() - -/* --- start --- -404 road, -NotFound, State, 5000 -Earth ------- end --- */ -``` - -赞爆了!那要是我属于一行的内容写不下想要写到第二行怎么办? - -```ini -[advance] -two_lines = how about \ - continuation lines? -lots_of_lines = 1 \ - 2 \ - 3 \ - 4 -``` - -简直是小菜一碟! - -```go -cfg.Section("advance").Key("two_lines").String() // how about continuation lines? -cfg.Section("advance").Key("lots_of_lines").String() // 1 2 3 4 -``` - -可是我有时候觉得两行连在一起特别没劲,怎么才能不自动连接两行呢? - -```go -cfg, err := ini.LoadSources(ini.LoadOptions{ - IgnoreContinuation: true, -}, "filename") -``` - -哇靠给力啊! - -需要注意的是,值两侧的单引号会被自动剔除: - -```ini -foo = "some value" // foo: some value -bar = 'some value' // bar: some value -``` - -有时您会获得像从 [Crowdin](https://crowdin.com/) 网站下载的文件那样具有特殊格式的值(值使用双引号括起来,内部的双引号被转义): - -```ini -create_repo="创建了仓库 %s" -``` - -那么,怎么自动地将这类值进行处理呢? - -```go -cfg, err := ini.LoadSources(ini.LoadOptions{UnescapeValueDoubleQuotes: true}, "en-US.ini")) -cfg.Section("").Key("create_repo").String() -// You got: 创建了仓库 %s -``` - -这就是全部了?哈哈,当然不是。 - -#### 操作键值的辅助方法 - -获取键值时设定候选值: - -```go -v = cfg.Section("").Key("STRING").In("default", []string{"str", "arr", "types"}) -v = cfg.Section("").Key("FLOAT64").InFloat64(1.1, []float64{1.25, 2.5, 3.75}) -v = cfg.Section("").Key("INT").InInt(5, []int{10, 20, 30}) -v = cfg.Section("").Key("INT64").InInt64(10, []int64{10, 20, 30}) -v = cfg.Section("").Key("UINT").InUint(4, []int{3, 6, 9}) -v = cfg.Section("").Key("UINT64").InUint64(8, []int64{3, 6, 9}) -v = cfg.Section("").Key("TIME").InTimeFormat(time.RFC3339, time.Now(), []time.Time{time1, time2, time3}) -v = cfg.Section("").Key("TIME").InTime(time.Now(), []time.Time{time1, time2, time3}) // RFC3339 -``` - -如果获取到的值不是候选值的任意一个,则会返回默认值,而默认值不需要是候选值中的一员。 - -验证获取的值是否在指定范围内: - -```go -vals = cfg.Section("").Key("FLOAT64").RangeFloat64(0.0, 1.1, 2.2) -vals = cfg.Section("").Key("INT").RangeInt(0, 10, 20) -vals = cfg.Section("").Key("INT64").RangeInt64(0, 10, 20) -vals = cfg.Section("").Key("UINT").RangeUint(0, 3, 9) -vals = cfg.Section("").Key("UINT64").RangeUint64(0, 3, 9) -vals = cfg.Section("").Key("TIME").RangeTimeFormat(time.RFC3339, time.Now(), minTime, maxTime) -vals = cfg.Section("").Key("TIME").RangeTime(time.Now(), minTime, maxTime) // RFC3339 -``` - -##### 自动分割键值到切片(slice) - -当存在无效输入时,使用零值代替: - -```go -// Input: 1.1, 2.2, 3.3, 4.4 -> [1.1 2.2 3.3 4.4] -// Input: how, 2.2, are, you -> [0.0 2.2 0.0 0.0] -vals = cfg.Section("").Key("STRINGS").Strings(",") -vals = cfg.Section("").Key("FLOAT64S").Float64s(",") -vals = cfg.Section("").Key("INTS").Ints(",") -vals = cfg.Section("").Key("INT64S").Int64s(",") -vals = cfg.Section("").Key("UINTS").Uints(",") -vals = cfg.Section("").Key("UINT64S").Uint64s(",") -vals = cfg.Section("").Key("TIMES").Times(",") -``` - -从结果切片中剔除无效输入: - -```go -// Input: 1.1, 2.2, 3.3, 4.4 -> [1.1 2.2 3.3 4.4] -// Input: how, 2.2, are, you -> [2.2] -vals = cfg.Section("").Key("FLOAT64S").ValidFloat64s(",") -vals = cfg.Section("").Key("INTS").ValidInts(",") -vals = cfg.Section("").Key("INT64S").ValidInt64s(",") -vals = cfg.Section("").Key("UINTS").ValidUints(",") -vals = cfg.Section("").Key("UINT64S").ValidUint64s(",") -vals = cfg.Section("").Key("TIMES").ValidTimes(",") -``` - -当存在无效输入时,直接返回错误: - -```go -// Input: 1.1, 2.2, 3.3, 4.4 -> [1.1 2.2 3.3 4.4] -// Input: how, 2.2, are, you -> error -vals = cfg.Section("").Key("FLOAT64S").StrictFloat64s(",") -vals = cfg.Section("").Key("INTS").StrictInts(",") -vals = cfg.Section("").Key("INT64S").StrictInt64s(",") -vals = cfg.Section("").Key("UINTS").StrictUints(",") -vals = cfg.Section("").Key("UINT64S").StrictUint64s(",") -vals = cfg.Section("").Key("TIMES").StrictTimes(",") -``` - -### 保存配置 - -终于到了这个时刻,是时候保存一下配置了。 - -比较原始的做法是输出配置到某个文件: - -```go -// ... -err = cfg.SaveTo("my.ini") -err = cfg.SaveToIndent("my.ini", "\t") -``` - -另一个比较高级的做法是写入到任何实现 `io.Writer` 接口的对象中: - -```go -// ... -cfg.WriteTo(writer) -cfg.WriteToIndent(writer, "\t") -``` - -默认情况下,空格将被用于对齐键值之间的等号以美化输出结果,以下代码可以禁用该功能: - -```go -ini.PrettyFormat = false -``` - -## 高级用法 - -### 递归读取键值 - -在获取所有键值的过程中,特殊语法 `%()s` 会被应用,其中 `` 可以是相同分区或者默认分区下的键名。字符串 `%()s` 会被相应的键值所替代,如果指定的键不存在,则会用空字符串替代。您可以最多使用 99 层的递归嵌套。 - -```ini -NAME = ini - -[author] -NAME = Unknwon -GITHUB = https://github.com/%(NAME)s - -[package] -FULL_NAME = github.com/go-ini/%(NAME)s -``` - -```go -cfg.Section("author").Key("GITHUB").String() // https://github.com/Unknwon -cfg.Section("package").Key("FULL_NAME").String() // github.com/go-ini/ini -``` - -### 读取父子分区 - -您可以在分区名称中使用 `.` 来表示两个或多个分区之间的父子关系。如果某个键在子分区中不存在,则会去它的父分区中再次寻找,直到没有父分区为止。 - -```ini -NAME = ini -VERSION = v1 -IMPORT_PATH = gopkg.in/%(NAME)s.%(VERSION)s - -[package] -CLONE_URL = https://%(IMPORT_PATH)s - -[package.sub] -``` - -```go -cfg.Section("package.sub").Key("CLONE_URL").String() // https://gopkg.in/ini.v1 -``` - -#### 获取上级父分区下的所有键名 - -```go -cfg.Section("package.sub").ParentKeys() // ["CLONE_URL"] -``` - -### 无法解析的分区 - -如果遇到一些比较特殊的分区,它们不包含常见的键值对,而是没有固定格式的纯文本,则可以使用 `LoadOptions.UnparsableSections` 进行处理: - -```go -cfg, err := LoadSources(ini.LoadOptions{UnparseableSections: []string{"COMMENTS"}}, `[COMMENTS] -<1> This slide has the fuel listed in the wrong units `)) - -body := cfg.Section("COMMENTS").Body() - -/* --- start --- -<1> This slide has the fuel listed in the wrong units ------- end --- */ -``` - -### 读取自增键名 - -如果数据源中的键名为 `-`,则认为该键使用了自增键名的特殊语法。计数器从 1 开始,并且分区之间是相互独立的。 - -```ini -[features] --: Support read/write comments of keys and sections --: Support auto-increment of key names --: Support load multiple files to overwrite key values -``` - -```go -cfg.Section("features").KeyStrings() // []{"#1", "#2", "#3"} -``` - -### 映射到结构 - -想要使用更加面向对象的方式玩转 INI 吗?好主意。 - -```ini -Name = Unknwon -age = 21 -Male = true -Born = 1993-01-01T20:17:05Z - -[Note] -Content = Hi is a good man! -Cities = HangZhou, Boston -``` - -```go -type Note struct { - Content string - Cities []string -} - -type Person struct { - Name string - Age int `ini:"age"` - Male bool - Born time.Time - Note - Created time.Time `ini:"-"` -} - -func main() { - cfg, err := ini.Load("path/to/ini") - // ... - p := new(Person) - err = cfg.MapTo(p) - // ... - - // 一切竟可以如此的简单。 - err = ini.MapTo(p, "path/to/ini") - // ... - - // 嗯哼?只需要映射一个分区吗? - n := new(Note) - err = cfg.Section("Note").MapTo(n) - // ... -} -``` - -结构的字段怎么设置默认值呢?很简单,只要在映射之前对指定字段进行赋值就可以了。如果键未找到或者类型错误,该值不会发生改变。 - -```go -// ... -p := &Person{ - Name: "Joe", -} -// ... -``` - -这样玩 INI 真的好酷啊!然而,如果不能还给我原来的配置文件,有什么卵用? - -### 从结构反射 - -可是,我有说不能吗? - -```go -type Embeded struct { - Dates []time.Time `delim:"|" comment:"Time data"` - Places []string `ini:"places,omitempty"` - None []int `ini:",omitempty"` -} - -type Author struct { - Name string `ini:"NAME"` - Male bool - Age int `comment:"Author's age"` - GPA float64 - NeverMind string `ini:"-"` - *Embeded `comment:"Embeded section"` -} - -func main() { - a := &Author{"Unknwon", true, 21, 2.8, "", - &Embeded{ - []time.Time{time.Now(), time.Now()}, - []string{"HangZhou", "Boston"}, - []int{}, - }} - cfg := ini.Empty() - err = ini.ReflectFrom(cfg, a) - // ... -} -``` - -瞧瞧,奇迹发生了。 - -```ini -NAME = Unknwon -Male = true -; Author's age -Age = 21 -GPA = 2.8 - -; Embeded section -[Embeded] -; Time data -Dates = 2015-08-07T22:14:22+08:00|2015-08-07T22:14:22+08:00 -places = HangZhou,Boston -``` - -#### 名称映射器(Name Mapper) - -为了节省您的时间并简化代码,本库支持类型为 [`NameMapper`](https://gowalker.org/gopkg.in/ini.v1#NameMapper) 的名称映射器,该映射器负责结构字段名与分区名和键名之间的映射。 - -目前有 2 款内置的映射器: - -- `AllCapsUnderscore`:该映射器将字段名转换至格式 `ALL_CAPS_UNDERSCORE` 后再去匹配分区名和键名。 -- `TitleUnderscore`:该映射器将字段名转换至格式 `title_underscore` 后再去匹配分区名和键名。 - -使用方法: - -```go -type Info struct{ - PackageName string -} - -func main() { - err = ini.MapToWithMapper(&Info{}, ini.TitleUnderscore, []byte("package_name=ini")) - // ... - - cfg, err := ini.Load([]byte("PACKAGE_NAME=ini")) - // ... - info := new(Info) - cfg.NameMapper = ini.AllCapsUnderscore - err = cfg.MapTo(info) - // ... -} -``` - -使用函数 `ini.ReflectFromWithMapper` 时也可应用相同的规则。 - -#### 值映射器(Value Mapper) - -值映射器允许使用一个自定义函数自动展开值的具体内容,例如:运行时获取环境变量: - -```go -type Env struct { - Foo string `ini:"foo"` -} - -func main() { - cfg, err := ini.Load([]byte("[env]\nfoo = ${MY_VAR}\n") - cfg.ValueMapper = os.ExpandEnv - // ... - env := &Env{} - err = cfg.Section("env").MapTo(env) -} -``` - -本例中,`env.Foo` 将会是运行时所获取到环境变量 `MY_VAR` 的值。 - -#### 映射/反射的其它说明 - -任何嵌入的结构都会被默认认作一个不同的分区,并且不会自动产生所谓的父子分区关联: - -```go -type Child struct { - Age string -} - -type Parent struct { - Name string - Child -} - -type Config struct { - City string - Parent -} -``` - -示例配置文件: - -```ini -City = Boston - -[Parent] -Name = Unknwon - -[Child] -Age = 21 -``` - -很好,但是,我就是要嵌入结构也在同一个分区。好吧,你爹是李刚! - -```go -type Child struct { - Age string -} - -type Parent struct { - Name string - Child `ini:"Parent"` -} - -type Config struct { - City string - Parent -} -``` - -示例配置文件: - -```ini -City = Boston - -[Parent] -Name = Unknwon -Age = 21 -``` - -## 获取帮助 - -- [API 文档](https://gowalker.org/gopkg.in/ini.v1) -- [创建工单](https://github.com/go-ini/ini/issues/new) - -## 常见问题 - -### 字段 `BlockMode` 是什么? - -默认情况下,本库会在您进行读写操作时采用锁机制来确保数据时间。但在某些情况下,您非常确定只进行读操作。此时,您可以通过设置 `cfg.BlockMode = false` 来将读操作提升大约 **50-70%** 的性能。 - -### 为什么要写另一个 INI 解析库? - -许多人都在使用我的 [goconfig](https://github.com/Unknwon/goconfig) 来完成对 INI 文件的操作,但我希望使用更加 Go 风格的代码。并且当您设置 `cfg.BlockMode = false` 时,会有大约 **10-30%** 的性能提升。 - -为了做出这些改变,我必须对 API 进行破坏,所以新开一个仓库是最安全的做法。除此之外,本库直接使用 `gopkg.in` 来进行版本化发布。(其实真相是导入路径更短了) diff --git a/vendor/github.com/go-ini/ini/ini_test.go b/vendor/github.com/go-ini/ini/ini_test.go deleted file mode 100644 index 6088f404d..000000000 --- a/vendor/github.com/go-ini/ini/ini_test.go +++ /dev/null @@ -1,502 +0,0 @@ -// Copyright 2014 Unknwon -// -// Licensed under the Apache License, Version 2.0 (the "License"): you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -// License for the specific language governing permissions and limitations -// under the License. - -package ini - -import ( - "bytes" - "io/ioutil" - "strings" - "testing" - "time" - - . "github.com/smartystreets/goconvey/convey" -) - -func Test_Version(t *testing.T) { - Convey("Get version", t, func() { - So(Version(), ShouldEqual, _VERSION) - }) -} - -const _CONF_DATA = ` -; Package name -NAME = ini -; Package version -VERSION = v1 -; Package import path -IMPORT_PATH = gopkg.in/%(NAME)s.%(VERSION)s - -# Information about package author -# Bio can be written in multiple lines. -[author] -NAME = Unknwon ; Succeeding comment -E-MAIL = fake@localhost -GITHUB = https://github.com/%(NAME)s -BIO = """Gopher. -Coding addict. -Good man. -""" # Succeeding comment - -[package] -CLONE_URL = https://%(IMPORT_PATH)s - -[package.sub] -UNUSED_KEY = should be deleted - -[features] --: Support read/write comments of keys and sections --: Support auto-increment of key names --: Support load multiple files to overwrite key values - -[types] -STRING = str -BOOL = true -BOOL_FALSE = false -FLOAT64 = 1.25 -INT = 10 -TIME = 2015-01-01T20:17:05Z -DURATION = 2h45m -UINT = 3 - -[array] -STRINGS = en, zh, de -FLOAT64S = 1.1, 2.2, 3.3 -INTS = 1, 2, 3 -UINTS = 1, 2, 3 -TIMES = 2015-01-01T20:17:05Z,2015-01-01T20:17:05Z,2015-01-01T20:17:05Z - -[note] -empty_lines = next line is empty\ - -; Comment before the section -[comments] ; This is a comment for the section too -; Comment before key -key = "value" -key2 = "value2" ; This is a comment for key2 -key3 = "one", "two", "three" - -[advance] -value with quotes = "some value" -value quote2 again = 'some value' -includes comment sign = ` + "`" + "my#password" + "`" + ` -includes comment sign2 = ` + "`" + "my;password" + "`" + ` -true = 2+3=5 -"1+1=2" = true -"""6+1=7""" = true -"""` + "`" + `5+5` + "`" + `""" = 10 -` + "`" + `"6+6"` + "`" + ` = 12 -` + "`" + `7-2=4` + "`" + ` = false -ADDRESS = ` + "`" + `404 road, -NotFound, State, 50000` + "`" + ` - -two_lines = how about \ - continuation lines? -lots_of_lines = 1 \ - 2 \ - 3 \ - 4 \ -` - -func Test_Load(t *testing.T) { - Convey("Load from data sources", t, func() { - - Convey("Load with empty data", func() { - So(Empty(), ShouldNotBeNil) - }) - - Convey("Load with multiple data sources", func() { - cfg, err := Load([]byte(_CONF_DATA), "testdata/conf.ini", ioutil.NopCloser(bytes.NewReader([]byte(_CONF_DATA)))) - So(err, ShouldBeNil) - So(cfg, ShouldNotBeNil) - - f, err := Load([]byte(_CONF_DATA), "testdata/404.ini") - So(err, ShouldNotBeNil) - So(f, ShouldBeNil) - }) - - Convey("Load with io.ReadCloser", func() { - cfg, err := Load(ioutil.NopCloser(bytes.NewReader([]byte(_CONF_DATA)))) - So(err, ShouldBeNil) - So(cfg, ShouldNotBeNil) - - So(cfg.Section("").Key("NAME").String(), ShouldEqual, "ini") - }) - }) - - Convey("Bad load process", t, func() { - - Convey("Load from invalid data sources", func() { - _, err := Load(_CONF_DATA) - So(err, ShouldNotBeNil) - - f, err := Load("testdata/404.ini") - So(err, ShouldNotBeNil) - So(f, ShouldBeNil) - - _, err = Load(1) - So(err, ShouldNotBeNil) - - _, err = Load([]byte(""), 1) - So(err, ShouldNotBeNil) - }) - - Convey("Load with bad section name", func() { - _, err := Load([]byte("[]")) - So(err, ShouldNotBeNil) - - _, err = Load([]byte("[")) - So(err, ShouldNotBeNil) - }) - - Convey("Load with bad keys", func() { - _, err := Load([]byte(`"""name`)) - So(err, ShouldNotBeNil) - - _, err = Load([]byte(`"""name"""`)) - So(err, ShouldNotBeNil) - - _, err = Load([]byte(`""=1`)) - So(err, ShouldNotBeNil) - - _, err = Load([]byte(`=`)) - So(err, ShouldNotBeNil) - - _, err = Load([]byte(`name`)) - So(err, ShouldNotBeNil) - }) - - Convey("Load with bad values", func() { - _, err := Load([]byte(`name="""Unknwon`)) - So(err, ShouldNotBeNil) - }) - }) - - Convey("Get section and key insensitively", t, func() { - cfg, err := InsensitiveLoad([]byte(_CONF_DATA), "testdata/conf.ini") - So(err, ShouldBeNil) - So(cfg, ShouldNotBeNil) - - sec, err := cfg.GetSection("Author") - So(err, ShouldBeNil) - So(sec, ShouldNotBeNil) - - key, err := sec.GetKey("E-mail") - So(err, ShouldBeNil) - So(key, ShouldNotBeNil) - }) - - Convey("Load with ignoring continuation lines", t, func() { - cfg, err := LoadSources(LoadOptions{IgnoreContinuation: true}, []byte(`key1=a\b\ -key2=c\d\`)) - So(err, ShouldBeNil) - So(cfg, ShouldNotBeNil) - - So(cfg.Section("").Key("key1").String(), ShouldEqual, `a\b\`) - So(cfg.Section("").Key("key2").String(), ShouldEqual, `c\d\`) - }) - - Convey("Load with ignoring inline comments", t, func() { - cfg, err := LoadSources(LoadOptions{IgnoreInlineComment: true}, []byte(`key1=value ;comment -key2=value #comment2`)) - So(err, ShouldBeNil) - So(cfg, ShouldNotBeNil) - - So(cfg.Section("").Key("key1").String(), ShouldEqual, `value ;comment`) - So(cfg.Section("").Key("key2").String(), ShouldEqual, `value #comment2`) - - var buf bytes.Buffer - cfg.WriteTo(&buf) - So(buf.String(), ShouldEqual, `key1 = value ;comment -key2 = value #comment2 - -`) - }) - - Convey("Load with boolean type keys", t, func() { - cfg, err := LoadSources(LoadOptions{AllowBooleanKeys: true}, []byte(`key1=hello -key2 -#key3 -key4 -key5`)) - So(err, ShouldBeNil) - So(cfg, ShouldNotBeNil) - - So(strings.Join(cfg.Section("").KeyStrings(), ","), ShouldEqual, "key1,key2,key4,key5") - So(cfg.Section("").Key("key2").MustBool(false), ShouldBeTrue) - - var buf bytes.Buffer - cfg.WriteTo(&buf) - // there is always a trailing \n at the end of the section - So(buf.String(), ShouldEqual, `key1 = hello -key2 -# key3 -key4 -key5 -`) - }) -} - -func Test_File_ChildSections(t *testing.T) { - Convey("Find child sections by parent name", t, func() { - cfg, err := Load([]byte(` -[node] - -[node.biz1] - -[node.biz2] - -[node.biz3] - -[node.bizN] -`)) - So(err, ShouldBeNil) - So(cfg, ShouldNotBeNil) - - children := cfg.ChildSections("node") - names := make([]string, len(children)) - for i := range children { - names[i] = children[i].name - } - So(strings.Join(names, ","), ShouldEqual, "node.biz1,node.biz2,node.biz3,node.bizN") - }) -} - -func Test_LooseLoad(t *testing.T) { - Convey("Loose load from data sources", t, func() { - Convey("Loose load mixed with nonexistent file", func() { - cfg, err := LooseLoad("testdata/404.ini") - So(err, ShouldBeNil) - So(cfg, ShouldNotBeNil) - var fake struct { - Name string `ini:"name"` - } - So(cfg.MapTo(&fake), ShouldBeNil) - - cfg, err = LooseLoad([]byte("name=Unknwon"), "testdata/404.ini") - So(err, ShouldBeNil) - So(cfg.Section("").Key("name").String(), ShouldEqual, "Unknwon") - So(cfg.MapTo(&fake), ShouldBeNil) - So(fake.Name, ShouldEqual, "Unknwon") - }) - }) - -} - -func Test_LoadOptions_UnescapeValueDoubleQuotes(t *testing.T) { - Convey("Load with option UnescapeValueDoubleQuotes enabled", t, func() { - cfg, err := LoadSources(LoadOptions{UnescapeValueDoubleQuotes: true}, - []byte(`create_repo="创建了仓库 %s"`)) - So(err, ShouldBeNil) - So(cfg, ShouldNotBeNil) - - So(cfg.Section("").Key("create_repo").String(), ShouldEqual, `创建了仓库 %s`) - }) -} - -func Test_File_Append(t *testing.T) { - Convey("Append data sources", t, func() { - cfg, err := Load([]byte("")) - So(err, ShouldBeNil) - So(cfg, ShouldNotBeNil) - - So(cfg.Append([]byte(""), []byte("")), ShouldBeNil) - - Convey("Append bad data sources", func() { - So(cfg.Append(1), ShouldNotBeNil) - So(cfg.Append([]byte(""), 1), ShouldNotBeNil) - }) - }) -} - -func Test_File_WriteTo(t *testing.T) { - Convey("Write to somewhere", t, func() { - var buf bytes.Buffer - cfg := Empty() - cfg.WriteTo(&buf) - }) -} - -func Test_File_SaveTo_WriteTo(t *testing.T) { - Convey("Save file", t, func() { - cfg, err := Load([]byte(_CONF_DATA), "testdata/conf.ini") - So(err, ShouldBeNil) - So(cfg, ShouldNotBeNil) - - cfg.Section("").Key("NAME").Comment = "Package name" - cfg.Section("author").Comment = `Information about package author -# Bio can be written in multiple lines.` - cfg.Section("advanced").Key("val w/ pound").SetValue("my#password") - cfg.Section("advanced").Key("longest key has a colon : yes/no").SetValue("yes") - So(cfg.SaveTo("testdata/conf_out.ini"), ShouldBeNil) - - cfg.Section("author").Key("NAME").Comment = "This is author name" - - So(cfg.SaveToIndent("testdata/conf_out.ini", "\t"), ShouldBeNil) - - var buf bytes.Buffer - _, err = cfg.WriteToIndent(&buf, "\t") - So(err, ShouldBeNil) - So(buf.String(), ShouldEqual, `; Package name -NAME = ini -; Package version -VERSION = v1 -; Package import path -IMPORT_PATH = gopkg.in/%(NAME)s.%(VERSION)s - -; Information about package author -# Bio can be written in multiple lines. -[author] - ; This is author name - NAME = Unknwon - E-MAIL = u@gogs.io - GITHUB = https://github.com/%(NAME)s - # Succeeding comment - BIO = """Gopher. -Coding addict. -Good man. -""" - -[package] - CLONE_URL = https://%(IMPORT_PATH)s - -[package.sub] - UNUSED_KEY = should be deleted - -[features] - - = Support read/write comments of keys and sections - - = Support auto-increment of key names - - = Support load multiple files to overwrite key values - -[types] - STRING = str - BOOL = true - BOOL_FALSE = false - FLOAT64 = 1.25 - INT = 10 - TIME = 2015-01-01T20:17:05Z - DURATION = 2h45m - UINT = 3 - -[array] - STRINGS = en, zh, de - FLOAT64S = 1.1, 2.2, 3.3 - INTS = 1, 2, 3 - UINTS = 1, 2, 3 - TIMES = 2015-01-01T20:17:05Z,2015-01-01T20:17:05Z,2015-01-01T20:17:05Z - -[note] - empty_lines = next line is empty - -; Comment before the section -; This is a comment for the section too -[comments] - ; Comment before key - key = value - ; This is a comment for key2 - key2 = value2 - key3 = "one", "two", "three" - -[advance] - value with quotes = some value - value quote2 again = some value - includes comment sign = `+"`"+"my#password"+"`"+` - includes comment sign2 = `+"`"+"my;password"+"`"+` - true = 2+3=5 - `+"`"+`1+1=2`+"`"+` = true - `+"`"+`6+1=7`+"`"+` = true - """`+"`"+`5+5`+"`"+`""" = 10 - `+"`"+`"6+6"`+"`"+` = 12 - `+"`"+`7-2=4`+"`"+` = false - ADDRESS = """404 road, -NotFound, State, 50000""" - two_lines = how about continuation lines? - lots_of_lines = 1 2 3 4 - -[advanced] - val w/ pound = `+"`"+`my#password`+"`"+` - `+"`"+`longest key has a colon : yes/no`+"`"+` = yes - -`) - }) -} - -func Test_File_WriteTo_SectionRaw(t *testing.T) { - Convey("Write a INI with a raw section", t, func() { - var buf bytes.Buffer - cfg, err := LoadSources( - LoadOptions{ - UnparseableSections: []string{"CORE_LESSON", "COMMENTS"}, - }, - "testdata/aicc.ini") - So(err, ShouldBeNil) - So(cfg, ShouldNotBeNil) - cfg.WriteToIndent(&buf, "\t") - So(buf.String(), ShouldEqual, `[Core] - Lesson_Location = 87 - Lesson_Status = C - Score = 3 - Time = 00:02:30 - -[CORE_LESSON] -my lesson state data – 1111111111111111111000000000000000001110000 -111111111111111111100000000000111000000000 – end my lesson state data -[COMMENTS] -<1> This slide has the fuel listed in the wrong units -`) - }) -} - -// Helpers for slice tests. -func float64sEqual(values []float64, expected ...float64) { - So(values, ShouldHaveLength, len(expected)) - for i, v := range expected { - So(values[i], ShouldEqual, v) - } -} - -func intsEqual(values []int, expected ...int) { - So(values, ShouldHaveLength, len(expected)) - for i, v := range expected { - So(values[i], ShouldEqual, v) - } -} - -func int64sEqual(values []int64, expected ...int64) { - So(values, ShouldHaveLength, len(expected)) - for i, v := range expected { - So(values[i], ShouldEqual, v) - } -} - -func uintsEqual(values []uint, expected ...uint) { - So(values, ShouldHaveLength, len(expected)) - for i, v := range expected { - So(values[i], ShouldEqual, v) - } -} - -func uint64sEqual(values []uint64, expected ...uint64) { - So(values, ShouldHaveLength, len(expected)) - for i, v := range expected { - So(values[i], ShouldEqual, v) - } -} - -func timesEqual(values []time.Time, expected ...time.Time) { - So(values, ShouldHaveLength, len(expected)) - for i, v := range expected { - So(values[i].String(), ShouldEqual, v.String()) - } -} diff --git a/vendor/github.com/go-ini/ini/key_test.go b/vendor/github.com/go-ini/ini/key_test.go deleted file mode 100644 index 1281d5bf0..000000000 --- a/vendor/github.com/go-ini/ini/key_test.go +++ /dev/null @@ -1,573 +0,0 @@ -// Copyright 2014 Unknwon -// -// Licensed under the Apache License, Version 2.0 (the "License"): you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -// License for the specific language governing permissions and limitations -// under the License. - -package ini - -import ( - "bytes" - "fmt" - "strings" - "testing" - "time" - - . "github.com/smartystreets/goconvey/convey" -) - -func Test_Key(t *testing.T) { - Convey("Test getting and setting values", t, func() { - cfg, err := Load([]byte(_CONF_DATA), "testdata/conf.ini") - So(err, ShouldBeNil) - So(cfg, ShouldNotBeNil) - - Convey("Get values in default section", func() { - sec := cfg.Section("") - So(sec, ShouldNotBeNil) - So(sec.Key("NAME").Value(), ShouldEqual, "ini") - So(sec.Key("NAME").String(), ShouldEqual, "ini") - So(sec.Key("NAME").Validate(func(in string) string { - return in - }), ShouldEqual, "ini") - So(sec.Key("NAME").Comment, ShouldEqual, "; Package name") - So(sec.Key("IMPORT_PATH").String(), ShouldEqual, "gopkg.in/ini.v1") - }) - - Convey("Get values in non-default section", func() { - sec := cfg.Section("author") - So(sec, ShouldNotBeNil) - So(sec.Key("NAME").String(), ShouldEqual, "Unknwon") - So(sec.Key("GITHUB").String(), ShouldEqual, "https://github.com/Unknwon") - - sec = cfg.Section("package") - So(sec, ShouldNotBeNil) - So(sec.Key("CLONE_URL").String(), ShouldEqual, "https://gopkg.in/ini.v1") - }) - - Convey("Get auto-increment key names", func() { - keys := cfg.Section("features").Keys() - for i, k := range keys { - So(k.Name(), ShouldEqual, fmt.Sprintf("#%d", i+1)) - } - }) - - Convey("Get parent-keys that are available to the child section", func() { - parentKeys := cfg.Section("package.sub").ParentKeys() - for _, k := range parentKeys { - So(k.Name(), ShouldEqual, "CLONE_URL") - } - }) - - Convey("Get overwrite value", func() { - So(cfg.Section("author").Key("E-MAIL").String(), ShouldEqual, "u@gogs.io") - }) - - Convey("Get sections", func() { - sections := cfg.Sections() - for i, name := range []string{DEFAULT_SECTION, "author", "package", "package.sub", "features", "types", "array", "note", "comments", "advance"} { - So(sections[i].Name(), ShouldEqual, name) - } - }) - - Convey("Get parent section value", func() { - So(cfg.Section("package.sub").Key("CLONE_URL").String(), ShouldEqual, "https://gopkg.in/ini.v1") - So(cfg.Section("package.fake.sub").Key("CLONE_URL").String(), ShouldEqual, "https://gopkg.in/ini.v1") - }) - - Convey("Get multiple line value", func() { - So(cfg.Section("author").Key("BIO").String(), ShouldEqual, "Gopher.\nCoding addict.\nGood man.\n") - }) - - Convey("Get values with type", func() { - sec := cfg.Section("types") - v1, err := sec.Key("BOOL").Bool() - So(err, ShouldBeNil) - So(v1, ShouldBeTrue) - - v1, err = sec.Key("BOOL_FALSE").Bool() - So(err, ShouldBeNil) - So(v1, ShouldBeFalse) - - v2, err := sec.Key("FLOAT64").Float64() - So(err, ShouldBeNil) - So(v2, ShouldEqual, 1.25) - - v3, err := sec.Key("INT").Int() - So(err, ShouldBeNil) - So(v3, ShouldEqual, 10) - - v4, err := sec.Key("INT").Int64() - So(err, ShouldBeNil) - So(v4, ShouldEqual, 10) - - v5, err := sec.Key("UINT").Uint() - So(err, ShouldBeNil) - So(v5, ShouldEqual, 3) - - v6, err := sec.Key("UINT").Uint64() - So(err, ShouldBeNil) - So(v6, ShouldEqual, 3) - - t, err := time.Parse(time.RFC3339, "2015-01-01T20:17:05Z") - So(err, ShouldBeNil) - v7, err := sec.Key("TIME").Time() - So(err, ShouldBeNil) - So(v7.String(), ShouldEqual, t.String()) - - Convey("Must get values with type", func() { - So(sec.Key("STRING").MustString("404"), ShouldEqual, "str") - So(sec.Key("BOOL").MustBool(), ShouldBeTrue) - So(sec.Key("FLOAT64").MustFloat64(), ShouldEqual, 1.25) - So(sec.Key("INT").MustInt(), ShouldEqual, 10) - So(sec.Key("INT").MustInt64(), ShouldEqual, 10) - So(sec.Key("UINT").MustUint(), ShouldEqual, 3) - So(sec.Key("UINT").MustUint64(), ShouldEqual, 3) - So(sec.Key("TIME").MustTime().String(), ShouldEqual, t.String()) - - dur, err := time.ParseDuration("2h45m") - So(err, ShouldBeNil) - So(sec.Key("DURATION").MustDuration().Seconds(), ShouldEqual, dur.Seconds()) - - Convey("Must get values with default value", func() { - So(sec.Key("STRING_404").MustString("404"), ShouldEqual, "404") - So(sec.Key("BOOL_404").MustBool(true), ShouldBeTrue) - So(sec.Key("FLOAT64_404").MustFloat64(2.5), ShouldEqual, 2.5) - So(sec.Key("INT_404").MustInt(15), ShouldEqual, 15) - So(sec.Key("INT64_404").MustInt64(15), ShouldEqual, 15) - So(sec.Key("UINT_404").MustUint(6), ShouldEqual, 6) - So(sec.Key("UINT64_404").MustUint64(6), ShouldEqual, 6) - - t, err := time.Parse(time.RFC3339, "2014-01-01T20:17:05Z") - So(err, ShouldBeNil) - So(sec.Key("TIME_404").MustTime(t).String(), ShouldEqual, t.String()) - - So(sec.Key("DURATION_404").MustDuration(dur).Seconds(), ShouldEqual, dur.Seconds()) - - Convey("Must should set default as key value", func() { - So(sec.Key("STRING_404").String(), ShouldEqual, "404") - So(sec.Key("BOOL_404").String(), ShouldEqual, "true") - So(sec.Key("FLOAT64_404").String(), ShouldEqual, "2.5") - So(sec.Key("INT_404").String(), ShouldEqual, "15") - So(sec.Key("INT64_404").String(), ShouldEqual, "15") - So(sec.Key("UINT_404").String(), ShouldEqual, "6") - So(sec.Key("UINT64_404").String(), ShouldEqual, "6") - So(sec.Key("TIME_404").String(), ShouldEqual, "2014-01-01T20:17:05Z") - So(sec.Key("DURATION_404").String(), ShouldEqual, "2h45m0s") - }) - }) - }) - }) - - Convey("Get value with candidates", func() { - sec := cfg.Section("types") - So(sec.Key("STRING").In("", []string{"str", "arr", "types"}), ShouldEqual, "str") - So(sec.Key("FLOAT64").InFloat64(0, []float64{1.25, 2.5, 3.75}), ShouldEqual, 1.25) - So(sec.Key("INT").InInt(0, []int{10, 20, 30}), ShouldEqual, 10) - So(sec.Key("INT").InInt64(0, []int64{10, 20, 30}), ShouldEqual, 10) - So(sec.Key("UINT").InUint(0, []uint{3, 6, 9}), ShouldEqual, 3) - So(sec.Key("UINT").InUint64(0, []uint64{3, 6, 9}), ShouldEqual, 3) - - zt, err := time.Parse(time.RFC3339, "0001-01-01T01:00:00Z") - So(err, ShouldBeNil) - t, err := time.Parse(time.RFC3339, "2015-01-01T20:17:05Z") - So(err, ShouldBeNil) - So(sec.Key("TIME").InTime(zt, []time.Time{t, time.Now(), time.Now().Add(1 * time.Second)}).String(), ShouldEqual, t.String()) - - Convey("Get value with candidates and default value", func() { - So(sec.Key("STRING_404").In("str", []string{"str", "arr", "types"}), ShouldEqual, "str") - So(sec.Key("FLOAT64_404").InFloat64(1.25, []float64{1.25, 2.5, 3.75}), ShouldEqual, 1.25) - So(sec.Key("INT_404").InInt(10, []int{10, 20, 30}), ShouldEqual, 10) - So(sec.Key("INT64_404").InInt64(10, []int64{10, 20, 30}), ShouldEqual, 10) - So(sec.Key("UINT_404").InUint(3, []uint{3, 6, 9}), ShouldEqual, 3) - So(sec.Key("UINT_404").InUint64(3, []uint64{3, 6, 9}), ShouldEqual, 3) - So(sec.Key("TIME_404").InTime(t, []time.Time{time.Now(), time.Now(), time.Now().Add(1 * time.Second)}).String(), ShouldEqual, t.String()) - }) - }) - - Convey("Get values in range", func() { - sec := cfg.Section("types") - So(sec.Key("FLOAT64").RangeFloat64(0, 1, 2), ShouldEqual, 1.25) - So(sec.Key("INT").RangeInt(0, 10, 20), ShouldEqual, 10) - So(sec.Key("INT").RangeInt64(0, 10, 20), ShouldEqual, 10) - - minT, err := time.Parse(time.RFC3339, "0001-01-01T01:00:00Z") - So(err, ShouldBeNil) - midT, err := time.Parse(time.RFC3339, "2013-01-01T01:00:00Z") - So(err, ShouldBeNil) - maxT, err := time.Parse(time.RFC3339, "9999-01-01T01:00:00Z") - So(err, ShouldBeNil) - t, err := time.Parse(time.RFC3339, "2015-01-01T20:17:05Z") - So(err, ShouldBeNil) - So(sec.Key("TIME").RangeTime(t, minT, maxT).String(), ShouldEqual, t.String()) - - Convey("Get value in range with default value", func() { - So(sec.Key("FLOAT64").RangeFloat64(5, 0, 1), ShouldEqual, 5) - So(sec.Key("INT").RangeInt(7, 0, 5), ShouldEqual, 7) - So(sec.Key("INT").RangeInt64(7, 0, 5), ShouldEqual, 7) - So(sec.Key("TIME").RangeTime(t, minT, midT).String(), ShouldEqual, t.String()) - }) - }) - - Convey("Get values into slice", func() { - sec := cfg.Section("array") - So(strings.Join(sec.Key("STRINGS").Strings(","), ","), ShouldEqual, "en,zh,de") - So(len(sec.Key("STRINGS_404").Strings(",")), ShouldEqual, 0) - - vals1 := sec.Key("FLOAT64S").Float64s(",") - float64sEqual(vals1, 1.1, 2.2, 3.3) - - vals2 := sec.Key("INTS").Ints(",") - intsEqual(vals2, 1, 2, 3) - - vals3 := sec.Key("INTS").Int64s(",") - int64sEqual(vals3, 1, 2, 3) - - vals4 := sec.Key("UINTS").Uints(",") - uintsEqual(vals4, 1, 2, 3) - - vals5 := sec.Key("UINTS").Uint64s(",") - uint64sEqual(vals5, 1, 2, 3) - - t, err := time.Parse(time.RFC3339, "2015-01-01T20:17:05Z") - So(err, ShouldBeNil) - vals6 := sec.Key("TIMES").Times(",") - timesEqual(vals6, t, t, t) - }) - - Convey("Get valid values into slice", func() { - sec := cfg.Section("array") - vals1 := sec.Key("FLOAT64S").ValidFloat64s(",") - float64sEqual(vals1, 1.1, 2.2, 3.3) - - vals2 := sec.Key("INTS").ValidInts(",") - intsEqual(vals2, 1, 2, 3) - - vals3 := sec.Key("INTS").ValidInt64s(",") - int64sEqual(vals3, 1, 2, 3) - - vals4 := sec.Key("UINTS").ValidUints(",") - uintsEqual(vals4, 1, 2, 3) - - vals5 := sec.Key("UINTS").ValidUint64s(",") - uint64sEqual(vals5, 1, 2, 3) - - t, err := time.Parse(time.RFC3339, "2015-01-01T20:17:05Z") - So(err, ShouldBeNil) - vals6 := sec.Key("TIMES").ValidTimes(",") - timesEqual(vals6, t, t, t) - }) - - Convey("Get values one type into slice of another type", func() { - sec := cfg.Section("array") - vals1 := sec.Key("STRINGS").ValidFloat64s(",") - So(vals1, ShouldBeEmpty) - - vals2 := sec.Key("STRINGS").ValidInts(",") - So(vals2, ShouldBeEmpty) - - vals3 := sec.Key("STRINGS").ValidInt64s(",") - So(vals3, ShouldBeEmpty) - - vals4 := sec.Key("STRINGS").ValidUints(",") - So(vals4, ShouldBeEmpty) - - vals5 := sec.Key("STRINGS").ValidUint64s(",") - So(vals5, ShouldBeEmpty) - - vals6 := sec.Key("STRINGS").ValidTimes(",") - So(vals6, ShouldBeEmpty) - }) - - Convey("Get valid values into slice without errors", func() { - sec := cfg.Section("array") - vals1, err := sec.Key("FLOAT64S").StrictFloat64s(",") - So(err, ShouldBeNil) - float64sEqual(vals1, 1.1, 2.2, 3.3) - - vals2, err := sec.Key("INTS").StrictInts(",") - So(err, ShouldBeNil) - intsEqual(vals2, 1, 2, 3) - - vals3, err := sec.Key("INTS").StrictInt64s(",") - So(err, ShouldBeNil) - int64sEqual(vals3, 1, 2, 3) - - vals4, err := sec.Key("UINTS").StrictUints(",") - So(err, ShouldBeNil) - uintsEqual(vals4, 1, 2, 3) - - vals5, err := sec.Key("UINTS").StrictUint64s(",") - So(err, ShouldBeNil) - uint64sEqual(vals5, 1, 2, 3) - - t, err := time.Parse(time.RFC3339, "2015-01-01T20:17:05Z") - So(err, ShouldBeNil) - vals6, err := sec.Key("TIMES").StrictTimes(",") - So(err, ShouldBeNil) - timesEqual(vals6, t, t, t) - }) - - Convey("Get invalid values into slice", func() { - sec := cfg.Section("array") - vals1, err := sec.Key("STRINGS").StrictFloat64s(",") - So(vals1, ShouldBeEmpty) - So(err, ShouldNotBeNil) - - vals2, err := sec.Key("STRINGS").StrictInts(",") - So(vals2, ShouldBeEmpty) - So(err, ShouldNotBeNil) - - vals3, err := sec.Key("STRINGS").StrictInt64s(",") - So(vals3, ShouldBeEmpty) - So(err, ShouldNotBeNil) - - vals4, err := sec.Key("STRINGS").StrictUints(",") - So(vals4, ShouldBeEmpty) - So(err, ShouldNotBeNil) - - vals5, err := sec.Key("STRINGS").StrictUint64s(",") - So(vals5, ShouldBeEmpty) - So(err, ShouldNotBeNil) - - vals6, err := sec.Key("STRINGS").StrictTimes(",") - So(vals6, ShouldBeEmpty) - So(err, ShouldNotBeNil) - }) - - Convey("Get key hash", func() { - cfg.Section("").KeysHash() - }) - - Convey("Set key value", func() { - k := cfg.Section("author").Key("NAME") - k.SetValue("无闻") - So(k.String(), ShouldEqual, "无闻") - }) - - Convey("Get key strings", func() { - So(strings.Join(cfg.Section("types").KeyStrings(), ","), ShouldEqual, "STRING,BOOL,BOOL_FALSE,FLOAT64,INT,TIME,DURATION,UINT") - }) - - Convey("Delete a key", func() { - cfg.Section("package.sub").DeleteKey("UNUSED_KEY") - _, err := cfg.Section("package.sub").GetKey("UNUSED_KEY") - So(err, ShouldNotBeNil) - }) - - Convey("Has Key (backwards compatible)", func() { - sec := cfg.Section("package.sub") - haskey1 := sec.Haskey("UNUSED_KEY") - haskey2 := sec.Haskey("CLONE_URL") - haskey3 := sec.Haskey("CLONE_URL_NO") - So(haskey1, ShouldBeTrue) - So(haskey2, ShouldBeTrue) - So(haskey3, ShouldBeFalse) - }) - - Convey("Has Key", func() { - sec := cfg.Section("package.sub") - haskey1 := sec.HasKey("UNUSED_KEY") - haskey2 := sec.HasKey("CLONE_URL") - haskey3 := sec.HasKey("CLONE_URL_NO") - So(haskey1, ShouldBeTrue) - So(haskey2, ShouldBeTrue) - So(haskey3, ShouldBeFalse) - }) - - Convey("Has Value", func() { - sec := cfg.Section("author") - hasvalue1 := sec.HasValue("Unknwon") - hasvalue2 := sec.HasValue("doc") - So(hasvalue1, ShouldBeTrue) - So(hasvalue2, ShouldBeFalse) - }) - }) - - Convey("Test getting and setting bad values", t, func() { - cfg, err := Load([]byte(_CONF_DATA), "testdata/conf.ini") - So(err, ShouldBeNil) - So(cfg, ShouldNotBeNil) - - Convey("Create new key with empty name", func() { - k, err := cfg.Section("").NewKey("", "") - So(err, ShouldNotBeNil) - So(k, ShouldBeNil) - }) - - Convey("Create new section with empty name", func() { - s, err := cfg.NewSection("") - So(err, ShouldNotBeNil) - So(s, ShouldBeNil) - }) - - Convey("Create new sections with empty name", func() { - So(cfg.NewSections(""), ShouldNotBeNil) - }) - - Convey("Get section that not exists", func() { - s, err := cfg.GetSection("404") - So(err, ShouldNotBeNil) - So(s, ShouldBeNil) - - s = cfg.Section("404") - So(s, ShouldNotBeNil) - }) - }) - - Convey("Test key hash clone", t, func() { - cfg, err := Load([]byte(strings.Replace("network=tcp,addr=127.0.0.1:6379,db=4,pool_size=100,idle_timeout=180", ",", "\n", -1))) - So(err, ShouldBeNil) - for _, v := range cfg.Section("").KeysHash() { - So(len(v), ShouldBeGreaterThan, 0) - } - }) - - Convey("Key has empty value", t, func() { - _conf := `key1= -key2= ; comment` - cfg, err := Load([]byte(_conf)) - So(err, ShouldBeNil) - So(cfg.Section("").Key("key1").Value(), ShouldBeEmpty) - }) -} - -const _CONF_GIT_CONFIG = ` -[remote "origin"] - url = https://github.com/Antergone/test1.git - url = https://github.com/Antergone/test2.git -` - -func Test_Key_Shadows(t *testing.T) { - Convey("Shadows keys", t, func() { - Convey("Disable shadows", func() { - cfg, err := Load([]byte(_CONF_GIT_CONFIG)) - So(err, ShouldBeNil) - So(cfg.Section(`remote "origin"`).Key("url").String(), ShouldEqual, "https://github.com/Antergone/test2.git") - }) - - Convey("Enable shadows", func() { - cfg, err := ShadowLoad([]byte(_CONF_GIT_CONFIG)) - So(err, ShouldBeNil) - So(cfg.Section(`remote "origin"`).Key("url").String(), ShouldEqual, "https://github.com/Antergone/test1.git") - So(strings.Join(cfg.Section(`remote "origin"`).Key("url").ValueWithShadows(), " "), ShouldEqual, - "https://github.com/Antergone/test1.git https://github.com/Antergone/test2.git") - - Convey("Save with shadows", func() { - var buf bytes.Buffer - _, err := cfg.WriteTo(&buf) - So(err, ShouldBeNil) - So(buf.String(), ShouldEqual, `[remote "origin"] -url = https://github.com/Antergone/test1.git -url = https://github.com/Antergone/test2.git - -`) - }) - }) - }) -} - -func newTestFile(block bool) *File { - c, _ := Load([]byte(_CONF_DATA)) - c.BlockMode = block - return c -} - -func Benchmark_Key_Value(b *testing.B) { - c := newTestFile(true) - for i := 0; i < b.N; i++ { - c.Section("").Key("NAME").Value() - } -} - -func Benchmark_Key_Value_NonBlock(b *testing.B) { - c := newTestFile(false) - for i := 0; i < b.N; i++ { - c.Section("").Key("NAME").Value() - } -} - -func Benchmark_Key_Value_ViaSection(b *testing.B) { - c := newTestFile(true) - sec := c.Section("") - for i := 0; i < b.N; i++ { - sec.Key("NAME").Value() - } -} - -func Benchmark_Key_Value_ViaSection_NonBlock(b *testing.B) { - c := newTestFile(false) - sec := c.Section("") - for i := 0; i < b.N; i++ { - sec.Key("NAME").Value() - } -} - -func Benchmark_Key_Value_Direct(b *testing.B) { - c := newTestFile(true) - key := c.Section("").Key("NAME") - for i := 0; i < b.N; i++ { - key.Value() - } -} - -func Benchmark_Key_Value_Direct_NonBlock(b *testing.B) { - c := newTestFile(false) - key := c.Section("").Key("NAME") - for i := 0; i < b.N; i++ { - key.Value() - } -} - -func Benchmark_Key_String(b *testing.B) { - c := newTestFile(true) - for i := 0; i < b.N; i++ { - _ = c.Section("").Key("NAME").String() - } -} - -func Benchmark_Key_String_NonBlock(b *testing.B) { - c := newTestFile(false) - for i := 0; i < b.N; i++ { - _ = c.Section("").Key("NAME").String() - } -} - -func Benchmark_Key_String_ViaSection(b *testing.B) { - c := newTestFile(true) - sec := c.Section("") - for i := 0; i < b.N; i++ { - _ = sec.Key("NAME").String() - } -} - -func Benchmark_Key_String_ViaSection_NonBlock(b *testing.B) { - c := newTestFile(false) - sec := c.Section("") - for i := 0; i < b.N; i++ { - _ = sec.Key("NAME").String() - } -} - -func Benchmark_Key_SetValue(b *testing.B) { - c := newTestFile(true) - for i := 0; i < b.N; i++ { - c.Section("").Key("NAME").SetValue("10") - } -} - -func Benchmark_Key_SetValue_VisSection(b *testing.B) { - c := newTestFile(true) - sec := c.Section("") - for i := 0; i < b.N; i++ { - sec.Key("NAME").SetValue("10") - } -} diff --git a/vendor/github.com/go-ini/ini/parser_test.go b/vendor/github.com/go-ini/ini/parser_test.go deleted file mode 100644 index 05258195b..000000000 --- a/vendor/github.com/go-ini/ini/parser_test.go +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright 2016 Unknwon -// -// Licensed under the Apache License, Version 2.0 (the "License"): you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -// License for the specific language governing permissions and limitations -// under the License. - -package ini - -import ( - "testing" - - . "github.com/smartystreets/goconvey/convey" -) - -func Test_BOM(t *testing.T) { - Convey("Test handling BOM", t, func() { - Convey("UTF-8-BOM", func() { - cfg, err := Load("testdata/UTF-8-BOM.ini") - So(err, ShouldBeNil) - So(cfg, ShouldNotBeNil) - - So(cfg.Section("author").Key("E-MAIL").String(), ShouldEqual, "u@gogs.io") - }) - - Convey("UTF-16-LE-BOM", func() { - cfg, err := Load("testdata/UTF-16-LE-BOM.ini") - So(err, ShouldBeNil) - So(cfg, ShouldNotBeNil) - }) - - Convey("UTF-16-BE-BOM", func() { - }) - }) -} diff --git a/vendor/github.com/go-ini/ini/section_test.go b/vendor/github.com/go-ini/ini/section_test.go deleted file mode 100644 index 80282c197..000000000 --- a/vendor/github.com/go-ini/ini/section_test.go +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright 2014 Unknwon -// -// Licensed under the Apache License, Version 2.0 (the "License"): you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -// License for the specific language governing permissions and limitations -// under the License. - -package ini - -import ( - "strings" - "testing" - - . "github.com/smartystreets/goconvey/convey" -) - -func Test_Section(t *testing.T) { - Convey("Test CRD sections", t, func() { - cfg, err := Load([]byte(_CONF_DATA), "testdata/conf.ini") - So(err, ShouldBeNil) - So(cfg, ShouldNotBeNil) - - Convey("Get section strings", func() { - So(strings.Join(cfg.SectionStrings(), ","), ShouldEqual, "DEFAULT,author,package,package.sub,features,types,array,note,comments,advance") - }) - - Convey("Delete a section", func() { - cfg.DeleteSection("") - So(cfg.SectionStrings()[0], ShouldNotEqual, DEFAULT_SECTION) - }) - - Convey("Create new sections", func() { - cfg.NewSections("test", "test2") - _, err := cfg.GetSection("test") - So(err, ShouldBeNil) - _, err = cfg.GetSection("test2") - So(err, ShouldBeNil) - }) - }) -} - -func Test_SectionRaw(t *testing.T) { - Convey("Test section raw string", t, func() { - cfg, err := LoadSources( - LoadOptions{ - Insensitive: true, - UnparseableSections: []string{"core_lesson", "comments"}, - }, - "testdata/aicc.ini") - So(err, ShouldBeNil) - So(cfg, ShouldNotBeNil) - - Convey("Get section strings", func() { - So(strings.Join(cfg.SectionStrings(), ","), ShouldEqual, "DEFAULT,core,core_lesson,comments") - }) - - Convey("Validate non-raw section", func() { - val, err := cfg.Section("core").GetKey("lesson_status") - So(err, ShouldBeNil) - So(val.String(), ShouldEqual, "C") - }) - - Convey("Validate raw section", func() { - So(cfg.Section("core_lesson").Body(), ShouldEqual, `my lesson state data – 1111111111111111111000000000000000001110000 -111111111111111111100000000000111000000000 – end my lesson state data`) - }) - }) -} \ No newline at end of file diff --git a/vendor/github.com/go-ini/ini/struct_test.go b/vendor/github.com/go-ini/ini/struct_test.go deleted file mode 100644 index 86bb9de1f..000000000 --- a/vendor/github.com/go-ini/ini/struct_test.go +++ /dev/null @@ -1,369 +0,0 @@ -// Copyright 2014 Unknwon -// -// Licensed under the Apache License, Version 2.0 (the "License"): you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -// License for the specific language governing permissions and limitations -// under the License. - -package ini - -import ( - "bytes" - "fmt" - "strings" - "testing" - "time" - - . "github.com/smartystreets/goconvey/convey" -) - -type testNested struct { - Cities []string `delim:"|"` - Visits []time.Time - Years []int - Numbers []int64 - Ages []uint - Populations []uint64 - Coordinates []float64 - Note string - Unused int `ini:"-"` -} - -type testEmbeded struct { - GPA float64 -} - -type testStruct struct { - Name string `ini:"NAME"` - Age int - Male bool - Money float64 - Born time.Time - Time time.Duration `ini:"Duration"` - Others testNested - *testEmbeded `ini:"grade"` - Unused int `ini:"-"` - Unsigned uint - Omitted bool `ini:"omitthis,omitempty"` - Shadows []string `ini:",,allowshadow"` - ShadowInts []int `ini:"Shadows,,allowshadow"` -} - -const _CONF_DATA_STRUCT = ` -NAME = Unknwon -Age = 21 -Male = true -Money = 1.25 -Born = 1993-10-07T20:17:05Z -Duration = 2h45m -Unsigned = 3 -omitthis = true -Shadows = 1, 2 -Shadows = 3, 4 - -[Others] -Cities = HangZhou|Boston -Visits = 1993-10-07T20:17:05Z, 1993-10-07T20:17:05Z -Years = 1993,1994 -Numbers = 10010,10086 -Ages = 18,19 -Populations = 12345678,98765432 -Coordinates = 192.168,10.11 -Note = Hello world! - -[grade] -GPA = 2.8 - -[foo.bar] -Here = there -When = then -` - -type unsupport struct { - Byte byte -} - -type unsupport2 struct { - Others struct { - Cities byte - } -} - -type unsupport3 struct { - Cities byte -} - -type unsupport4 struct { - *unsupport3 `ini:"Others"` -} - -type defaultValue struct { - Name string - Age int - Male bool - Money float64 - Born time.Time - Cities []string -} - -type fooBar struct { - Here, When string -} - -const _INVALID_DATA_CONF_STRUCT = ` -Name = -Age = age -Male = 123 -Money = money -Born = nil -Cities = -` - -func Test_Struct(t *testing.T) { - Convey("Map to struct", t, func() { - Convey("Map file to struct", func() { - ts := new(testStruct) - So(MapTo(ts, []byte(_CONF_DATA_STRUCT)), ShouldBeNil) - - So(ts.Name, ShouldEqual, "Unknwon") - So(ts.Age, ShouldEqual, 21) - So(ts.Male, ShouldBeTrue) - So(ts.Money, ShouldEqual, 1.25) - So(ts.Unsigned, ShouldEqual, 3) - - t, err := time.Parse(time.RFC3339, "1993-10-07T20:17:05Z") - So(err, ShouldBeNil) - So(ts.Born.String(), ShouldEqual, t.String()) - - dur, err := time.ParseDuration("2h45m") - So(err, ShouldBeNil) - So(ts.Time.Seconds(), ShouldEqual, dur.Seconds()) - - So(strings.Join(ts.Others.Cities, ","), ShouldEqual, "HangZhou,Boston") - So(ts.Others.Visits[0].String(), ShouldEqual, t.String()) - So(fmt.Sprint(ts.Others.Years), ShouldEqual, "[1993 1994]") - So(fmt.Sprint(ts.Others.Numbers), ShouldEqual, "[10010 10086]") - So(fmt.Sprint(ts.Others.Ages), ShouldEqual, "[18 19]") - So(fmt.Sprint(ts.Others.Populations), ShouldEqual, "[12345678 98765432]") - So(fmt.Sprint(ts.Others.Coordinates), ShouldEqual, "[192.168 10.11]") - So(ts.Others.Note, ShouldEqual, "Hello world!") - So(ts.testEmbeded.GPA, ShouldEqual, 2.8) - }) - - Convey("Map section to struct", func() { - foobar := new(fooBar) - f, err := Load([]byte(_CONF_DATA_STRUCT)) - So(err, ShouldBeNil) - - So(f.Section("foo.bar").MapTo(foobar), ShouldBeNil) - So(foobar.Here, ShouldEqual, "there") - So(foobar.When, ShouldEqual, "then") - }) - - Convey("Map to non-pointer struct", func() { - cfg, err := Load([]byte(_CONF_DATA_STRUCT)) - So(err, ShouldBeNil) - So(cfg, ShouldNotBeNil) - - So(cfg.MapTo(testStruct{}), ShouldNotBeNil) - }) - - Convey("Map to unsupported type", func() { - cfg, err := Load([]byte(_CONF_DATA_STRUCT)) - So(err, ShouldBeNil) - So(cfg, ShouldNotBeNil) - - cfg.NameMapper = func(raw string) string { - if raw == "Byte" { - return "NAME" - } - return raw - } - So(cfg.MapTo(&unsupport{}), ShouldNotBeNil) - So(cfg.MapTo(&unsupport2{}), ShouldNotBeNil) - So(cfg.MapTo(&unsupport4{}), ShouldNotBeNil) - }) - - Convey("Map to omitempty field", func() { - ts := new(testStruct) - So(MapTo(ts, []byte(_CONF_DATA_STRUCT)), ShouldBeNil) - - So(ts.Omitted, ShouldEqual, true) - }) - - Convey("Map with shadows", func() { - cfg, err := LoadSources(LoadOptions{AllowShadows: true}, []byte(_CONF_DATA_STRUCT)) - So(err, ShouldBeNil) - ts := new(testStruct) - So(cfg.MapTo(ts), ShouldBeNil) - - So(strings.Join(ts.Shadows, " "), ShouldEqual, "1 2 3 4") - So(fmt.Sprintf("%v", ts.ShadowInts), ShouldEqual, "[1 2 3 4]") - }) - - Convey("Map from invalid data source", func() { - So(MapTo(&testStruct{}, "hi"), ShouldNotBeNil) - }) - - Convey("Map to wrong types and gain default values", func() { - cfg, err := Load([]byte(_INVALID_DATA_CONF_STRUCT)) - So(err, ShouldBeNil) - - t, err := time.Parse(time.RFC3339, "1993-10-07T20:17:05Z") - So(err, ShouldBeNil) - dv := &defaultValue{"Joe", 10, true, 1.25, t, []string{"HangZhou", "Boston"}} - So(cfg.MapTo(dv), ShouldBeNil) - So(dv.Name, ShouldEqual, "Joe") - So(dv.Age, ShouldEqual, 10) - So(dv.Male, ShouldBeTrue) - So(dv.Money, ShouldEqual, 1.25) - So(dv.Born.String(), ShouldEqual, t.String()) - So(strings.Join(dv.Cities, ","), ShouldEqual, "HangZhou,Boston") - }) - }) - - Convey("Map to struct in strict mode", t, func() { - cfg, err := Load([]byte(` -name=bruce -age=a30`)) - So(err, ShouldBeNil) - - type Strict struct { - Name string `ini:"name"` - Age int `ini:"age"` - } - s := new(Strict) - - So(cfg.Section("").StrictMapTo(s), ShouldNotBeNil) - }) - - Convey("Map slice in strict mode", t, func() { - cfg, err := Load([]byte(` -names=alice, bruce`)) - So(err, ShouldBeNil) - - type Strict struct { - Names []string `ini:"names"` - } - s := new(Strict) - - So(cfg.Section("").StrictMapTo(s), ShouldBeNil) - So(fmt.Sprint(s.Names), ShouldEqual, "[alice bruce]") - }) - - Convey("Reflect from struct", t, func() { - type Embeded struct { - Dates []time.Time `delim:"|" comment:"Time data"` - Places []string - Years []int - Numbers []int64 - Ages []uint - Populations []uint64 - Coordinates []float64 - None []int - } - type Author struct { - Name string `ini:"NAME"` - Male bool - Age int `comment:"Author's age"` - Height uint - GPA float64 - Date time.Time - NeverMind string `ini:"-"` - *Embeded `ini:"infos" comment:"Embeded section"` - } - - t, err := time.Parse(time.RFC3339, "1993-10-07T20:17:05Z") - So(err, ShouldBeNil) - a := &Author{"Unknwon", true, 21, 100, 2.8, t, "", - &Embeded{ - []time.Time{t, t}, - []string{"HangZhou", "Boston"}, - []int{1993, 1994}, - []int64{10010, 10086}, - []uint{18, 19}, - []uint64{12345678, 98765432}, - []float64{192.168, 10.11}, - []int{}, - }} - cfg := Empty() - So(ReflectFrom(cfg, a), ShouldBeNil) - - var buf bytes.Buffer - _, err = cfg.WriteTo(&buf) - So(err, ShouldBeNil) - So(buf.String(), ShouldEqual, `NAME = Unknwon -Male = true -; Author's age -Age = 21 -Height = 100 -GPA = 2.8 -Date = 1993-10-07T20:17:05Z - -; Embeded section -[infos] -; Time data -Dates = 1993-10-07T20:17:05Z|1993-10-07T20:17:05Z -Places = HangZhou,Boston -Years = 1993,1994 -Numbers = 10010,10086 -Ages = 18,19 -Populations = 12345678,98765432 -Coordinates = 192.168,10.11 -None = - -`) - - Convey("Reflect from non-point struct", func() { - So(ReflectFrom(cfg, Author{}), ShouldNotBeNil) - }) - - Convey("Reflect from struct with omitempty", func() { - cfg := Empty() - type SpecialStruct struct { - FirstName string `ini:"first_name"` - LastName string `ini:"last_name"` - JustOmitMe string `ini:"omitempty"` - LastLogin time.Time `ini:"last_login,omitempty"` - LastLogin2 time.Time `ini:",omitempty"` - NotEmpty int `ini:"omitempty"` - } - - So(ReflectFrom(cfg, &SpecialStruct{FirstName: "John", LastName: "Doe", NotEmpty: 9}), ShouldBeNil) - - var buf bytes.Buffer - _, err = cfg.WriteTo(&buf) - So(buf.String(), ShouldEqual, `first_name = John -last_name = Doe -omitempty = 9 - -`) - }) - }) -} - -type testMapper struct { - PackageName string -} - -func Test_NameGetter(t *testing.T) { - Convey("Test name mappers", t, func() { - So(MapToWithMapper(&testMapper{}, TitleUnderscore, []byte("packag_name=ini")), ShouldBeNil) - - cfg, err := Load([]byte("PACKAGE_NAME=ini")) - So(err, ShouldBeNil) - So(cfg, ShouldNotBeNil) - - cfg.NameMapper = AllCapsUnderscore - tg := new(testMapper) - So(cfg.MapTo(tg), ShouldBeNil) - So(tg.PackageName, ShouldEqual, "ini") - }) -} diff --git a/vendor/github.com/go-kit/kit/.gitignore b/vendor/github.com/go-kit/kit/.gitignore deleted file mode 100644 index 6062401c1..000000000 --- a/vendor/github.com/go-kit/kit/.gitignore +++ /dev/null @@ -1,45 +0,0 @@ -examples/addsvc/addsvc -examples/addsvc/client/client -examples/apigateway/apigateway -examples/profilesvc/profilesvc -examples/stringsvc1/stringsvc1 -examples/stringsvc2/stringsvc2 -examples/stringsvc3/stringsvc3 -*.coverprofile - -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test -_old* - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe - -# https://github.com/github/gitignore/blob/master/Global/Vim.gitignore -# swap -[._]*.s[a-w][a-z] -[._]s[a-w][a-z] -# session -Session.vim -# temporary -.netrwhist -*~ -# auto-generated tag files -tags - diff --git a/vendor/github.com/go-kit/kit/.travis.yml b/vendor/github.com/go-kit/kit/.travis.yml deleted file mode 100644 index f77ab8d44..000000000 --- a/vendor/github.com/go-kit/kit/.travis.yml +++ /dev/null @@ -1,17 +0,0 @@ -language: go - -env: - - COVERALLS_TOKEN=MYSkSqcsWXd6DmP6TnSeiDhtvuL4u6ndp - -before_install: - - go get github.com/mattn/goveralls - - go get github.com/modocache/gover - -script: - - go test -race -v ./... - - ./coveralls.bash - -go: - - 1.9.x - - 1.10.x - - tip diff --git a/vendor/github.com/go-kit/kit/CONTRIBUTING.md b/vendor/github.com/go-kit/kit/CONTRIBUTING.md deleted file mode 100644 index c0751f85a..000000000 --- a/vendor/github.com/go-kit/kit/CONTRIBUTING.md +++ /dev/null @@ -1,18 +0,0 @@ -# Contributing - -First, thank you for contributing! We love and encourage pull requests from everyone. - -Before submitting major changes, here are a few guidelines to follow: - -1. Check the [open issues][issues] and [pull requests][prs] for existing discussions. -1. Open an [issue][issues] first, to discuss a new feature or enhancement. -1. Write tests, and make sure the test suite passes locally and on CI. -1. Open a pull request, and reference the relevant issue(s). -1. After receiving feedback, [squash your commits][squash] and add a [great commit message][message]. -1. Have fun! - -[issues]: https://github.com/go-kit/kit/issues -[prs]: https://github.com/go-kit/kit/pulls -[squash]: http://gitready.com/advanced/2009/02/10/squashing-commits-with-rebase.html -[message]: http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html - diff --git a/vendor/github.com/go-kit/kit/README.md b/vendor/github.com/go-kit/kit/README.md deleted file mode 100644 index 6b8aaf445..000000000 --- a/vendor/github.com/go-kit/kit/README.md +++ /dev/null @@ -1,119 +0,0 @@ -# Go kit [![Circle CI](https://circleci.com/gh/go-kit/kit.svg?style=shield)](https://circleci.com/gh/go-kit/kit) [![Travis CI](https://travis-ci.org/go-kit/kit.svg?branch=master)](https://travis-ci.org/go-kit/kit) [![GoDoc](https://godoc.org/github.com/go-kit/kit?status.svg)](https://godoc.org/github.com/go-kit/kit) [![Coverage Status](https://coveralls.io/repos/go-kit/kit/badge.svg?branch=master&service=github)](https://coveralls.io/github/go-kit/kit?branch=master) [![Go Report Card](https://goreportcard.com/badge/go-kit/kit)](https://goreportcard.com/report/go-kit/kit) [![Sourcegraph](https://sourcegraph.com/github.com/go-kit/kit/-/badge.svg)](https://sourcegraph.com/github.com/go-kit/kit?badge) - -**Go kit** is a **programming toolkit** for building microservices -(or elegant monoliths) in Go. We solve common problems in distributed -systems and application architecture so you can focus on delivering -business value. - -- Website: [gokit.io](https://gokit.io) -- Mailing list: [go-kit](https://groups.google.com/forum/#!forum/go-kit) -- Slack: [gophers.slack.com](https://gophers.slack.com) **#go-kit** ([invite](https://gophersinvite.herokuapp.com/)) - -## Motivation - -Go has emerged as the language of the server, but it remains underrepresented -in so-called "modern enterprise" companies like Facebook, Twitter, Netflix, and -SoundCloud. Many of these organizations have turned to JVM-based stacks for -their business logic, owing in large part to libraries and ecosystems that -directly support their microservice architectures. - -To reach its next level of success, Go needs more than simple primitives and -idioms. It needs a comprehensive toolkit, for coherent distributed programming -in the large. Go kit is a set of packages and best practices, which provide a -comprehensive, robust, and trustable way of building microservices for -organizations of any size. - -For more details, see - [the website](https://gokit.io), - [the motivating blog post](http://peter.bourgon.org/go-kit/) and - [the video of the talk](https://www.youtube.com/watch?v=iFR_7AKkJFU). -See also the - [Go kit talk at GopherCon 2015](https://www.youtube.com/watch?v=1AjaZi4QuGo). - -## Goals - -- Operate in a heterogeneous SOA — expect to interact with mostly non-Go-kit services -- RPC as the primary messaging pattern -- Pluggable serialization and transport — not just JSON over HTTP -- Operate within existing infrastructures — no mandates for specific tools or technologies - -## Non-goals - -- Supporting messaging patterns other than RPC (for now) — e.g. MPI, pub/sub, CQRS, etc. -- Re-implementing functionality that can be provided by adapting existing software -- Having opinions on operational concerns: deployment, configuration, process supervision, orchestration, etc. - -## Contributing - -Please see [CONTRIBUTING.md](/CONTRIBUTING.md). -Thank you, [contributors](https://github.com/go-kit/kit/graphs/contributors)! - -## Dependency management - -Go kit is a library, designed to be imported into a binary package. Vendoring -is currently the best way for binary package authors to ensure reliable, -reproducible builds. Therefore, we strongly recommend our users use vendoring -for all of their dependencies, including Go kit. To avoid compatibility and -availability issues, Go kit doesn't vendor its own dependencies, and -doesn't recommend use of third-party import proxies. - -There are several tools which make vendoring easier, including - [dep](https://github.com/golang/dep), - [gb](http://getgb.io), - [glide](https://github.com/Masterminds/glide), - [gvt](https://github.com/FiloSottile/gvt), and - [govendor](https://github.com/kardianos/govendor). -In addition, Go kit uses a variety of continuous integration providers - to find and fix compatibility problems as soon as they occur. - -## Related projects - -Projects with a ★ have had particular influence on Go kit's design (or vice-versa). - -### Service frameworks - -- [gizmo](https://github.com/nytimes/gizmo), a microservice toolkit from The New York Times ★ -- [go-micro](https://github.com/myodc/go-micro), a microservices client/server library ★ -- [gotalk](https://github.com/rsms/gotalk), async peer communication protocol & library -- [Kite](https://github.com/koding/kite), a micro-service framework -- [gocircuit](https://github.com/gocircuit/circuit), dynamic cloud orchestration - -### Individual components - -- [afex/hystrix-go](https://github.com/afex/hystrix-go), client-side latency and fault tolerance library -- [armon/go-metrics](https://github.com/armon/go-metrics), library for exporting performance and runtime metrics to external metrics systems -- [codahale/lunk](https://github.com/codahale/lunk), structured logging in the style of Google's Dapper or Twitter's Zipkin -- [eapache/go-resiliency](https://github.com/eapache/go-resiliency), resiliency patterns -- [sasbury/logging](https://github.com/sasbury/logging), a tagged style of logging -- [grpc/grpc-go](https://github.com/grpc/grpc-go), HTTP/2 based RPC -- [inconshreveable/log15](https://github.com/inconshreveable/log15), simple, powerful logging for Go ★ -- [mailgun/vulcand](https://github.com/vulcand/vulcand), programmatic load balancer backed by etcd -- [mattheath/phosphor](https://github.com/mondough/phosphor), distributed system tracing -- [pivotal-golang/lager](https://github.com/pivotal-golang/lager), an opinionated logging library -- [rubyist/circuitbreaker](https://github.com/rubyist/circuitbreaker), circuit breaker library -- [sirupsen/logrus](https://github.com/sirupsen/logrus), structured, pluggable logging for Go ★ -- [sourcegraph/appdash](https://github.com/sourcegraph/appdash), application tracing system based on Google's Dapper -- [spacemonkeygo/monitor](https://github.com/spacemonkeygo/monitor), data collection, monitoring, instrumentation, and Zipkin client library -- [streadway/handy](https://github.com/streadway/handy), net/http handler filters -- [vitess/rpcplus](https://godoc.org/github.com/youtube/vitess/go/rpcplus), package rpc + context.Context -- [gdamore/mangos](https://github.com/gdamore/mangos), nanomsg implementation in pure Go - -### Web frameworks - -- [Gorilla](http://www.gorillatoolkit.org) -- [Gin](https://gin-gonic.github.io/gin/) -- [Negroni](https://github.com/codegangsta/negroni) -- [Goji](https://github.com/zenazn/goji) -- [Martini](https://github.com/go-martini/martini) -- [Beego](http://beego.me/) -- [Revel](https://revel.github.io/) (considered [harmful](https://github.com/go-kit/kit/issues/350)) - -## Additional reading - -- [Architecting for the Cloud](http://fr.slideshare.net/stonse/architecting-for-the-cloud-using-netflixoss-codemash-workshop-29852233) — Netflix -- [Dapper, a Large-Scale Distributed Systems Tracing Infrastructure](http://research.google.com/pubs/pub36356.html) — Google -- [Your Server as a Function](http://monkey.org/~marius/funsrv.pdf) (PDF) — Twitter - ---- - -Development supported by [DigitalOcean](https://digitalocean.com). diff --git a/vendor/github.com/go-kit/kit/circle.yml b/vendor/github.com/go-kit/kit/circle.yml deleted file mode 100644 index 35ace2ce8..000000000 --- a/vendor/github.com/go-kit/kit/circle.yml +++ /dev/null @@ -1,27 +0,0 @@ -machine: - pre: - - curl -sSL https://s3.amazonaws.com/circle-downloads/install-circleci-docker.sh | bash -s -- 1.10.0 - - sudo rm -rf /usr/local/go - - curl -sSL https://storage.googleapis.com/golang/go1.9.linux-amd64.tar.gz | sudo tar xz -C /usr/local - services: - - docker - -dependencies: - pre: - - sudo curl -L "https://github.com/docker/compose/releases/download/1.10.0/docker-compose-linux-x86_64" -o /usr/local/bin/docker-compose - - sudo chmod +x /usr/local/bin/docker-compose - - docker-compose -f docker-compose-integration.yml up -d --force-recreate - -test: - pre: - - mkdir -p /home/ubuntu/.go_workspace/src/github.com/go-kit - - mv /home/ubuntu/kit /home/ubuntu/.go_workspace/src/github.com/go-kit - - ln -s /home/ubuntu/.go_workspace/src/github.com/go-kit/kit /home/ubuntu/kit - - go get -t github.com/go-kit/kit/... - override: - - go test -v -race -tags integration github.com/go-kit/kit/...: - environment: - ETCD_ADDR: http://localhost:2379 - CONSUL_ADDR: localhost:8500 - ZK_ADDR: localhost:2181 - EUREKA_ADDR: http://localhost:8761/eureka diff --git a/vendor/github.com/go-kit/kit/coveralls.bash b/vendor/github.com/go-kit/kit/coveralls.bash deleted file mode 100755 index cf8fee93b..000000000 --- a/vendor/github.com/go-kit/kit/coveralls.bash +++ /dev/null @@ -1,31 +0,0 @@ -#!/usr/bin/env bash - -if ! type -P gover -then - echo gover missing: go get github.com/modocache/gover - exit 1 -fi - -if ! type -P goveralls -then - echo goveralls missing: go get github.com/mattn/goveralls - exit 1 -fi - -if [[ "$COVERALLS_TOKEN" == "" ]] -then - echo COVERALLS_TOKEN not set - exit 1 -fi - -go list ./... | grep -v '/examples/' | cut -d'/' -f 4- | while read d -do - cd $d - go test -covermode count -coverprofile coverage.coverprofile - cd - -done - -gover -goveralls -coverprofile gover.coverprofile -service travis-ci -repotoken $COVERALLS_TOKEN -find . -name '*.coverprofile' -delete - diff --git a/vendor/github.com/go-kit/kit/docker-compose-integration.yml b/vendor/github.com/go-kit/kit/docker-compose-integration.yml deleted file mode 100644 index 287d97db0..000000000 --- a/vendor/github.com/go-kit/kit/docker-compose-integration.yml +++ /dev/null @@ -1,22 +0,0 @@ -version: '2' -services: - etcd: - image: quay.io/coreos/etcd - ports: - - "2379:2379" - command: /usr/local/bin/etcd -advertise-client-urls http://0.0.0.0:2379,http://0.0.0.0:4001 -listen-client-urls "http://0.0.0.0:2379,http://0.0.0.0:4001" - consul: - image: progrium/consul - ports: - - "8500:8500" - command: -server -bootstrap - zk: - image: zookeeper - ports: - - "2181:2181" - eureka: - image: springcloud/eureka - environment: - eureka.server.responseCacheUpdateIntervalMs: 1000 - ports: - - "8761:8761" diff --git a/vendor/github.com/go-kit/kit/lint b/vendor/github.com/go-kit/kit/lint deleted file mode 100755 index 12e307273..000000000 --- a/vendor/github.com/go-kit/kit/lint +++ /dev/null @@ -1,26 +0,0 @@ -#!/usr/bin/env bash - -set -o errexit -set -o nounset -set -o pipefail - -if [ ! $(command -v gometalinter) ] -then - go get github.com/alecthomas/gometalinter - gometalinter --update --install -fi - -time gometalinter \ - --exclude='error return value not checked.*(Close|Log|Print).*\(errcheck\)$' \ - --exclude='.*_test\.go:.*error return value not checked.*\(errcheck\)$' \ - --exclude='/thrift/' \ - --exclude='/pb/' \ - --exclude='no args in Log call \(vet\)' \ - --disable=dupl \ - --disable=aligncheck \ - --disable=gotype \ - --cyclo-over=20 \ - --tests \ - --concurrency=2 \ - --deadline=300s \ - ./... diff --git a/vendor/github.com/go-kit/kit/log/README.md b/vendor/github.com/go-kit/kit/log/README.md deleted file mode 100644 index 7222f8009..000000000 --- a/vendor/github.com/go-kit/kit/log/README.md +++ /dev/null @@ -1,147 +0,0 @@ -# package log - -`package log` provides a minimal interface for structured logging in services. -It may be wrapped to encode conventions, enforce type-safety, provide leveled -logging, and so on. It can be used for both typical application log events, -and log-structured data streams. - -## Structured logging - -Structured logging is, basically, conceding to the reality that logs are -_data_, and warrant some level of schematic rigor. Using a stricter, -key/value-oriented message format for our logs, containing contextual and -semantic information, makes it much easier to get insight into the -operational activity of the systems we build. Consequently, `package log` is -of the strong belief that "[the benefits of structured logging outweigh the -minimal effort involved](https://www.thoughtworks.com/radar/techniques/structured-logging)". - -Migrating from unstructured to structured logging is probably a lot easier -than you'd expect. - -```go -// Unstructured -log.Printf("HTTP server listening on %s", addr) - -// Structured -logger.Log("transport", "HTTP", "addr", addr, "msg", "listening") -``` - -## Usage - -### Typical application logging - -```go -w := log.NewSyncWriter(os.Stderr) -logger := log.NewLogfmtLogger(w) -logger.Log("question", "what is the meaning of life?", "answer", 42) - -// Output: -// question="what is the meaning of life?" answer=42 -``` - -### Contextual Loggers - -```go -func main() { - var logger log.Logger - logger = log.NewLogfmtLogger(log.NewSyncWriter(os.Stderr)) - logger = log.With(logger, "instance_id", 123) - - logger.Log("msg", "starting") - NewWorker(log.With(logger, "component", "worker")).Run() - NewSlacker(log.With(logger, "component", "slacker")).Run() -} - -// Output: -// instance_id=123 msg=starting -// instance_id=123 component=worker msg=running -// instance_id=123 component=slacker msg=running -``` - -### Interact with stdlib logger - -Redirect stdlib logger to Go kit logger. - -```go -import ( - "os" - stdlog "log" - kitlog "github.com/go-kit/kit/log" -) - -func main() { - logger := kitlog.NewJSONLogger(kitlog.NewSyncWriter(os.Stdout)) - stdlog.SetOutput(kitlog.NewStdlibAdapter(logger)) - stdlog.Print("I sure like pie") -} - -// Output: -// {"msg":"I sure like pie","ts":"2016/01/01 12:34:56"} -``` - -Or, if, for legacy reasons, you need to pipe all of your logging through the -stdlib log package, you can redirect Go kit logger to the stdlib logger. - -```go -logger := kitlog.NewLogfmtLogger(kitlog.StdlibWriter{}) -logger.Log("legacy", true, "msg", "at least it's something") - -// Output: -// 2016/01/01 12:34:56 legacy=true msg="at least it's something" -``` - -### Timestamps and callers - -```go -var logger log.Logger -logger = log.NewLogfmtLogger(log.NewSyncWriter(os.Stderr)) -logger = log.With(logger, "ts", log.DefaultTimestampUTC, "caller", log.DefaultCaller) - -logger.Log("msg", "hello") - -// Output: -// ts=2016-01-01T12:34:56Z caller=main.go:15 msg=hello -``` - -## Supported output formats - -- [Logfmt](https://brandur.org/logfmt) ([see also](https://blog.codeship.com/logfmt-a-log-format-thats-easy-to-read-and-write)) -- JSON - -## Enhancements - -`package log` is centered on the one-method Logger interface. - -```go -type Logger interface { - Log(keyvals ...interface{}) error -} -``` - -This interface, and its supporting code like is the product of much iteration -and evaluation. For more details on the evolution of the Logger interface, -see [The Hunt for a Logger Interface](http://go-talks.appspot.com/github.com/ChrisHines/talks/structured-logging/structured-logging.slide#1), -a talk by [Chris Hines](https://github.com/ChrisHines). -Also, please see -[#63](https://github.com/go-kit/kit/issues/63), -[#76](https://github.com/go-kit/kit/pull/76), -[#131](https://github.com/go-kit/kit/issues/131), -[#157](https://github.com/go-kit/kit/pull/157), -[#164](https://github.com/go-kit/kit/issues/164), and -[#252](https://github.com/go-kit/kit/pull/252) -to review historical conversations about package log and the Logger interface. - -Value-add packages and suggestions, -like improvements to [the leveled logger](https://godoc.org/github.com/go-kit/kit/log/level), -are of course welcome. Good proposals should - -- Be composable with [contextual loggers](https://godoc.org/github.com/go-kit/kit/log#With), -- Not break the behavior of [log.Caller](https://godoc.org/github.com/go-kit/kit/log#Caller) in any wrapped contextual loggers, and -- Be friendly to packages that accept only an unadorned log.Logger. - -## Benchmarks & comparisons - -There are a few Go logging benchmarks and comparisons that include Go kit's package log. - -- [imkira/go-loggers-bench](https://github.com/imkira/go-loggers-bench) includes kit/log -- [uber-common/zap](https://github.com/uber-common/zap), a zero-alloc logging library, includes a comparison with kit/log diff --git a/vendor/github.com/go-kit/kit/log/benchmark_test.go b/vendor/github.com/go-kit/kit/log/benchmark_test.go deleted file mode 100644 index 126bfa5ae..000000000 --- a/vendor/github.com/go-kit/kit/log/benchmark_test.go +++ /dev/null @@ -1,21 +0,0 @@ -package log_test - -import ( - "testing" - - "github.com/go-kit/kit/log" -) - -func benchmarkRunner(b *testing.B, logger log.Logger, f func(log.Logger)) { - lc := log.With(logger, "common_key", "common_value") - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - f(lc) - } -} - -var ( - baseMessage = func(logger log.Logger) { logger.Log("foo_key", "foo_value") } - withMessage = func(logger log.Logger) { log.With(logger, "a", "b").Log("c", "d") } -) diff --git a/vendor/github.com/go-kit/kit/log/concurrency_test.go b/vendor/github.com/go-kit/kit/log/concurrency_test.go deleted file mode 100644 index 95a749e77..000000000 --- a/vendor/github.com/go-kit/kit/log/concurrency_test.go +++ /dev/null @@ -1,40 +0,0 @@ -package log_test - -import ( - "math" - "testing" - - "github.com/go-kit/kit/log" -) - -// These test are designed to be run with the race detector. - -func testConcurrency(t *testing.T, logger log.Logger, total int) { - n := int(math.Sqrt(float64(total))) - share := total / n - - errC := make(chan error, n) - - for i := 0; i < n; i++ { - go func() { - errC <- spam(logger, share) - }() - } - - for i := 0; i < n; i++ { - err := <-errC - if err != nil { - t.Fatalf("concurrent logging error: %v", err) - } - } -} - -func spam(logger log.Logger, count int) error { - for i := 0; i < count; i++ { - err := logger.Log("key", i) - if err != nil { - return err - } - } - return nil -} diff --git a/vendor/github.com/go-kit/kit/log/example_test.go b/vendor/github.com/go-kit/kit/log/example_test.go deleted file mode 100644 index 976677489..000000000 --- a/vendor/github.com/go-kit/kit/log/example_test.go +++ /dev/null @@ -1,137 +0,0 @@ -package log_test - -import ( - "math/rand" - "os" - "sync" - "time" - - "github.com/go-kit/kit/log" -) - -func Example_basic() { - logger := log.NewLogfmtLogger(os.Stdout) - - type Task struct { - ID int - } - - RunTask := func(task Task, logger log.Logger) { - logger.Log("taskID", task.ID, "event", "starting task") - - logger.Log("taskID", task.ID, "event", "task complete") - } - - RunTask(Task{ID: 1}, logger) - - // Output: - // taskID=1 event="starting task" - // taskID=1 event="task complete" -} - -func Example_contextual() { - logger := log.NewLogfmtLogger(os.Stdout) - - type Task struct { - ID int - Cmd string - } - - taskHelper := func(cmd string, logger log.Logger) { - // execute(cmd) - logger.Log("cmd", cmd, "dur", 42*time.Millisecond) - } - - RunTask := func(task Task, logger log.Logger) { - logger = log.With(logger, "taskID", task.ID) - logger.Log("event", "starting task") - - taskHelper(task.Cmd, logger) - - logger.Log("event", "task complete") - } - - RunTask(Task{ID: 1, Cmd: "echo Hello, world!"}, logger) - - // Output: - // taskID=1 event="starting task" - // taskID=1 cmd="echo Hello, world!" dur=42ms - // taskID=1 event="task complete" -} - -func Example_valuer() { - logger := log.NewLogfmtLogger(os.Stdout) - - count := 0 - counter := func() interface{} { - count++ - return count - } - - logger = log.With(logger, "count", log.Valuer(counter)) - - logger.Log("call", "first") - logger.Log("call", "second") - - // Output: - // count=1 call=first - // count=2 call=second -} - -func Example_debugInfo() { - logger := log.NewLogfmtLogger(os.Stdout) - - // make time predictable for this test - baseTime := time.Date(2015, time.February, 3, 10, 0, 0, 0, time.UTC) - mockTime := func() time.Time { - baseTime = baseTime.Add(time.Second) - return baseTime - } - - logger = log.With(logger, "time", log.Timestamp(mockTime), "caller", log.DefaultCaller) - - logger.Log("call", "first") - logger.Log("call", "second") - - // ... - - logger.Log("call", "third") - - // Output: - // time=2015-02-03T10:00:01Z caller=example_test.go:93 call=first - // time=2015-02-03T10:00:02Z caller=example_test.go:94 call=second - // time=2015-02-03T10:00:03Z caller=example_test.go:98 call=third -} - -func Example_syncWriter() { - w := log.NewSyncWriter(os.Stdout) - logger := log.NewLogfmtLogger(w) - - type Task struct { - ID int - } - - var wg sync.WaitGroup - - RunTask := func(task Task, logger log.Logger) { - logger.Log("taskID", task.ID, "event", "starting task") - - time.Sleep(time.Duration(rand.Intn(200)) * time.Millisecond) - - logger.Log("taskID", task.ID, "event", "task complete") - wg.Done() - } - - wg.Add(2) - - go RunTask(Task{ID: 1}, logger) - go RunTask(Task{ID: 2}, logger) - - wg.Wait() - - // Unordered output: - // taskID=1 event="starting task" - // taskID=2 event="starting task" - // taskID=1 event="task complete" - // taskID=2 event="task complete" -} diff --git a/vendor/github.com/go-kit/kit/log/json_logger_test.go b/vendor/github.com/go-kit/kit/log/json_logger_test.go deleted file mode 100644 index e3e309090..000000000 --- a/vendor/github.com/go-kit/kit/log/json_logger_test.go +++ /dev/null @@ -1,162 +0,0 @@ -package log_test - -import ( - "bytes" - "errors" - "io/ioutil" - "testing" - - "github.com/go-kit/kit/log" -) - -func TestJSONLoggerCaller(t *testing.T) { - t.Parallel() - buf := &bytes.Buffer{} - logger := log.NewJSONLogger(buf) - logger = log.With(logger, "caller", log.DefaultCaller) - - if err := logger.Log(); err != nil { - t.Fatal(err) - } - if want, have := `{"caller":"json_logger_test.go:18"}`+"\n", buf.String(); want != have { - t.Errorf("\nwant %#v\nhave %#v", want, have) - } -} - -func TestJSONLogger(t *testing.T) { - t.Parallel() - buf := &bytes.Buffer{} - logger := log.NewJSONLogger(buf) - if err := logger.Log("err", errors.New("err"), "m", map[string]int{"0": 0}, "a", []int{1, 2, 3}); err != nil { - t.Fatal(err) - } - if want, have := `{"a":[1,2,3],"err":"err","m":{"0":0}}`+"\n", buf.String(); want != have { - t.Errorf("\nwant %#v\nhave %#v", want, have) - } -} - -func TestJSONLoggerMissingValue(t *testing.T) { - t.Parallel() - buf := &bytes.Buffer{} - logger := log.NewJSONLogger(buf) - if err := logger.Log("k"); err != nil { - t.Fatal(err) - } - if want, have := `{"k":"(MISSING)"}`+"\n", buf.String(); want != have { - t.Errorf("\nwant %#v\nhave %#v", want, have) - } -} - -func TestJSONLoggerNilStringerKey(t *testing.T) { - t.Parallel() - - buf := &bytes.Buffer{} - logger := log.NewJSONLogger(buf) - if err := logger.Log((*stringer)(nil), "v"); err != nil { - t.Fatal(err) - } - if want, have := `{"NULL":"v"}`+"\n", buf.String(); want != have { - t.Errorf("\nwant %#v\nhave %#v", want, have) - } -} - -func TestJSONLoggerNilErrorValue(t *testing.T) { - t.Parallel() - - buf := &bytes.Buffer{} - logger := log.NewJSONLogger(buf) - if err := logger.Log("err", (*stringError)(nil)); err != nil { - t.Fatal(err) - } - if want, have := `{"err":null}`+"\n", buf.String(); want != have { - t.Errorf("\nwant %#v\nhave %#v", want, have) - } -} - -// aller implements json.Marshaler, encoding.TextMarshaler, and fmt.Stringer. -type aller struct{} - -func (aller) MarshalJSON() ([]byte, error) { - return []byte("\"json\""), nil -} - -func (aller) MarshalText() ([]byte, error) { - return []byte("text"), nil -} - -func (aller) String() string { - return "string" -} - -func (aller) Error() string { - return "error" -} - -// textstringer implements encoding.TextMarshaler and fmt.Stringer. -type textstringer struct{} - -func (textstringer) MarshalText() ([]byte, error) { - return []byte("text"), nil -} - -func (textstringer) String() string { - return "string" -} - -func TestJSONLoggerStringValue(t *testing.T) { - t.Parallel() - tests := []struct { - v interface{} - expected string - }{ - { - v: aller{}, - expected: `{"v":"json"}`, - }, - { - v: textstringer{}, - expected: `{"v":"text"}`, - }, - { - v: stringer("string"), - expected: `{"v":"string"}`, - }, - } - - for _, test := range tests { - buf := &bytes.Buffer{} - logger := log.NewJSONLogger(buf) - if err := logger.Log("v", test.v); err != nil { - t.Fatal(err) - } - - if want, have := test.expected+"\n", buf.String(); want != have { - t.Errorf("\nwant %#v\nhave %#v", want, have) - } - } -} - -type stringer string - -func (s stringer) String() string { - return string(s) -} - -type stringError string - -func (s stringError) Error() string { - return string(s) -} - -func BenchmarkJSONLoggerSimple(b *testing.B) { - benchmarkRunner(b, log.NewJSONLogger(ioutil.Discard), baseMessage) -} - -func BenchmarkJSONLoggerContextual(b *testing.B) { - benchmarkRunner(b, log.NewJSONLogger(ioutil.Discard), withMessage) -} - -func TestJSONLoggerConcurrency(t *testing.T) { - t.Parallel() - testConcurrency(t, log.NewJSONLogger(ioutil.Discard), 10000) -} diff --git a/vendor/github.com/go-kit/kit/log/level/benchmark_test.go b/vendor/github.com/go-kit/kit/log/level/benchmark_test.go deleted file mode 100644 index 4fca6f08f..000000000 --- a/vendor/github.com/go-kit/kit/log/level/benchmark_test.go +++ /dev/null @@ -1,72 +0,0 @@ -package level_test - -import ( - "io/ioutil" - "testing" - - "github.com/go-kit/kit/log" - "github.com/go-kit/kit/log/level" -) - -func Benchmark(b *testing.B) { - contexts := []struct { - name string - context func(log.Logger) log.Logger - }{ - {"NoContext", func(l log.Logger) log.Logger { - return l - }}, - {"TimeContext", func(l log.Logger) log.Logger { - return log.With(l, "time", log.DefaultTimestampUTC) - }}, - {"CallerContext", func(l log.Logger) log.Logger { - return log.With(l, "caller", log.DefaultCaller) - }}, - {"TimeCallerReqIDContext", func(l log.Logger) log.Logger { - return log.With(l, "time", log.DefaultTimestampUTC, "caller", log.DefaultCaller, "reqID", 29) - }}, - } - - loggers := []struct { - name string - logger log.Logger - }{ - {"Nop", log.NewNopLogger()}, - {"Logfmt", log.NewLogfmtLogger(ioutil.Discard)}, - {"JSON", log.NewJSONLogger(ioutil.Discard)}, - } - - filters := []struct { - name string - filter func(log.Logger) log.Logger - }{ - {"Baseline", func(l log.Logger) log.Logger { - return l - }}, - {"DisallowedLevel", func(l log.Logger) log.Logger { - return level.NewFilter(l, level.AllowInfo()) - }}, - {"AllowedLevel", func(l log.Logger) log.Logger { - return level.NewFilter(l, level.AllowAll()) - }}, - } - - for _, c := range contexts { - b.Run(c.name, func(b *testing.B) { - for _, f := range filters { - b.Run(f.name, func(b *testing.B) { - for _, l := range loggers { - b.Run(l.name, func(b *testing.B) { - logger := c.context(f.filter(l.logger)) - b.ResetTimer() - b.ReportAllocs() - for i := 0; i < b.N; i++ { - level.Debug(logger).Log("foo", "bar") - } - }) - } - }) - } - }) - } -} diff --git a/vendor/github.com/go-kit/kit/log/level/example_test.go b/vendor/github.com/go-kit/kit/log/level/example_test.go deleted file mode 100644 index fed52e512..000000000 --- a/vendor/github.com/go-kit/kit/log/level/example_test.go +++ /dev/null @@ -1,25 +0,0 @@ -package level_test - -import ( - "errors" - "os" - - "github.com/go-kit/kit/log" - "github.com/go-kit/kit/log/level" -) - -func Example_basic() { - // setup logger with level filter - logger := log.NewLogfmtLogger(os.Stdout) - logger = level.NewFilter(logger, level.AllowInfo()) - logger = log.With(logger, "caller", log.DefaultCaller) - - // use level helpers to log at different levels - level.Error(logger).Log("err", errors.New("bad data")) - level.Info(logger).Log("event", "data saved") - level.Debug(logger).Log("next item", 17) // filtered - - // Output: - // level=error caller=example_test.go:18 err="bad data" - // level=info caller=example_test.go:19 event="data saved" -} diff --git a/vendor/github.com/go-kit/kit/log/level/level_test.go b/vendor/github.com/go-kit/kit/log/level/level_test.go deleted file mode 100644 index e362effc4..000000000 --- a/vendor/github.com/go-kit/kit/log/level/level_test.go +++ /dev/null @@ -1,235 +0,0 @@ -package level_test - -import ( - "bytes" - "errors" - "io" - "strings" - "testing" - - "github.com/go-kit/kit/log" - "github.com/go-kit/kit/log/level" -) - -func TestVariousLevels(t *testing.T) { - testCases := []struct { - name string - allowed level.Option - want string - }{ - { - "AllowAll", - level.AllowAll(), - strings.Join([]string{ - `{"level":"debug","this is":"debug log"}`, - `{"level":"info","this is":"info log"}`, - `{"level":"warn","this is":"warn log"}`, - `{"level":"error","this is":"error log"}`, - }, "\n"), - }, - { - "AllowDebug", - level.AllowDebug(), - strings.Join([]string{ - `{"level":"debug","this is":"debug log"}`, - `{"level":"info","this is":"info log"}`, - `{"level":"warn","this is":"warn log"}`, - `{"level":"error","this is":"error log"}`, - }, "\n"), - }, - { - "AllowInfo", - level.AllowInfo(), - strings.Join([]string{ - `{"level":"info","this is":"info log"}`, - `{"level":"warn","this is":"warn log"}`, - `{"level":"error","this is":"error log"}`, - }, "\n"), - }, - { - "AllowWarn", - level.AllowWarn(), - strings.Join([]string{ - `{"level":"warn","this is":"warn log"}`, - `{"level":"error","this is":"error log"}`, - }, "\n"), - }, - { - "AllowError", - level.AllowError(), - strings.Join([]string{ - `{"level":"error","this is":"error log"}`, - }, "\n"), - }, - { - "AllowNone", - level.AllowNone(), - ``, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - var buf bytes.Buffer - logger := level.NewFilter(log.NewJSONLogger(&buf), tc.allowed) - - level.Debug(logger).Log("this is", "debug log") - level.Info(logger).Log("this is", "info log") - level.Warn(logger).Log("this is", "warn log") - level.Error(logger).Log("this is", "error log") - - if want, have := tc.want, strings.TrimSpace(buf.String()); want != have { - t.Errorf("\nwant:\n%s\nhave:\n%s", want, have) - } - }) - } -} - -func TestErrNotAllowed(t *testing.T) { - myError := errors.New("squelched!") - opts := []level.Option{ - level.AllowWarn(), - level.ErrNotAllowed(myError), - } - logger := level.NewFilter(log.NewNopLogger(), opts...) - - if want, have := myError, level.Info(logger).Log("foo", "bar"); want != have { - t.Errorf("want %#+v, have %#+v", want, have) - } - - if want, have := error(nil), level.Warn(logger).Log("foo", "bar"); want != have { - t.Errorf("want %#+v, have %#+v", want, have) - } -} - -func TestErrNoLevel(t *testing.T) { - myError := errors.New("no level specified") - - var buf bytes.Buffer - opts := []level.Option{ - level.SquelchNoLevel(true), - level.ErrNoLevel(myError), - } - logger := level.NewFilter(log.NewJSONLogger(&buf), opts...) - - if want, have := myError, logger.Log("foo", "bar"); want != have { - t.Errorf("want %v, have %v", want, have) - } - if want, have := ``, strings.TrimSpace(buf.String()); want != have { - t.Errorf("\nwant '%s'\nhave '%s'", want, have) - } -} - -func TestAllowNoLevel(t *testing.T) { - var buf bytes.Buffer - opts := []level.Option{ - level.SquelchNoLevel(false), - level.ErrNoLevel(errors.New("I should never be returned!")), - } - logger := level.NewFilter(log.NewJSONLogger(&buf), opts...) - - if want, have := error(nil), logger.Log("foo", "bar"); want != have { - t.Errorf("want %v, have %v", want, have) - } - if want, have := `{"foo":"bar"}`, strings.TrimSpace(buf.String()); want != have { - t.Errorf("\nwant '%s'\nhave '%s'", want, have) - } -} - -func TestLevelContext(t *testing.T) { - var buf bytes.Buffer - - // Wrapping the level logger with a context allows users to use - // log.DefaultCaller as per normal. - var logger log.Logger - logger = log.NewLogfmtLogger(&buf) - logger = level.NewFilter(logger, level.AllowAll()) - logger = log.With(logger, "caller", log.DefaultCaller) - - level.Info(logger).Log("foo", "bar") - if want, have := `level=info caller=level_test.go:149 foo=bar`, strings.TrimSpace(buf.String()); want != have { - t.Errorf("\nwant '%s'\nhave '%s'", want, have) - } -} - -func TestContextLevel(t *testing.T) { - var buf bytes.Buffer - - // Wrapping a context with the level logger still works, but requires users - // to specify a higher callstack depth value. - var logger log.Logger - logger = log.NewLogfmtLogger(&buf) - logger = log.With(logger, "caller", log.Caller(5)) - logger = level.NewFilter(logger, level.AllowAll()) - - level.Info(logger).Log("foo", "bar") - if want, have := `caller=level_test.go:165 level=info foo=bar`, strings.TrimSpace(buf.String()); want != have { - t.Errorf("\nwant '%s'\nhave '%s'", want, have) - } -} - -func TestLevelFormatting(t *testing.T) { - testCases := []struct { - name string - format func(io.Writer) log.Logger - output string - }{ - { - name: "logfmt", - format: log.NewLogfmtLogger, - output: `level=info foo=bar`, - }, - { - name: "JSON", - format: log.NewJSONLogger, - output: `{"foo":"bar","level":"info"}`, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - var buf bytes.Buffer - - logger := tc.format(&buf) - level.Info(logger).Log("foo", "bar") - if want, have := tc.output, strings.TrimSpace(buf.String()); want != have { - t.Errorf("\nwant: '%s'\nhave '%s'", want, have) - } - }) - } -} - -func TestInjector(t *testing.T) { - var ( - output []interface{} - logger log.Logger - ) - - logger = log.LoggerFunc(func(keyvals ...interface{}) error { - output = keyvals - return nil - }) - logger = level.NewInjector(logger, level.InfoValue()) - - logger.Log("foo", "bar") - if got, want := len(output), 4; got != want { - t.Errorf("missing level not injected: got len==%d, want len==%d", got, want) - } - if got, want := output[0], level.Key(); got != want { - t.Errorf("wrong level key: got %#v, want %#v", got, want) - } - if got, want := output[1], level.InfoValue(); got != want { - t.Errorf("wrong level value: got %#v, want %#v", got, want) - } - - level.Error(logger).Log("foo", "bar") - if got, want := len(output), 4; got != want { - t.Errorf("leveled record modified: got len==%d, want len==%d", got, want) - } - if got, want := output[0], level.Key(); got != want { - t.Errorf("wrong level key: got %#v, want %#v", got, want) - } - if got, want := output[1], level.ErrorValue(); got != want { - t.Errorf("wrong level value: got %#v, want %#v", got, want) - } -} diff --git a/vendor/github.com/go-kit/kit/log/log_test.go b/vendor/github.com/go-kit/kit/log/log_test.go deleted file mode 100644 index 1bf29727e..000000000 --- a/vendor/github.com/go-kit/kit/log/log_test.go +++ /dev/null @@ -1,191 +0,0 @@ -package log_test - -import ( - "bytes" - "fmt" - "sync" - "testing" - - "github.com/go-kit/kit/log" - "github.com/go-stack/stack" -) - -func TestContext(t *testing.T) { - t.Parallel() - buf := &bytes.Buffer{} - logger := log.NewLogfmtLogger(buf) - - kvs := []interface{}{"a", 123} - lc := log.With(logger, kvs...) - kvs[1] = 0 // With should copy its key values - - lc = log.With(lc, "b", "c") // With should stack - if err := lc.Log("msg", "message"); err != nil { - t.Fatal(err) - } - if want, have := "a=123 b=c msg=message\n", buf.String(); want != have { - t.Errorf("\nwant: %shave: %s", want, have) - } - - buf.Reset() - lc = log.WithPrefix(lc, "p", "first") - if err := lc.Log("msg", "message"); err != nil { - t.Fatal(err) - } - if want, have := "p=first a=123 b=c msg=message\n", buf.String(); want != have { - t.Errorf("\nwant: %shave: %s", want, have) - } -} - -func TestContextMissingValue(t *testing.T) { - t.Parallel() - var output []interface{} - logger := log.Logger(log.LoggerFunc(func(keyvals ...interface{}) error { - output = keyvals - return nil - })) - - log.WithPrefix(log.With(logger, "k1"), "k0").Log("k2") - if want, have := 6, len(output); want != have { - t.Errorf("want len(output) == %v, have %v", want, have) - } - for i := 1; i < 6; i += 2 { - if want, have := log.ErrMissingValue, output[i]; want != have { - t.Errorf("want output[%d] == %#v, have %#v", i, want, have) - } - } -} - -// Test that context.Log has a consistent function stack depth when binding -// Valuers, regardless of how many times With has been called. -func TestContextStackDepth(t *testing.T) { - t.Parallel() - fn := fmt.Sprintf("%n", stack.Caller(0)) - - var output []interface{} - - logger := log.Logger(log.LoggerFunc(func(keyvals ...interface{}) error { - output = keyvals - return nil - })) - - stackValuer := log.Valuer(func() interface{} { - for i, c := range stack.Trace() { - if fmt.Sprintf("%n", c) == fn { - return i - } - } - t.Fatal("Test function not found in stack trace.") - return nil - }) - - logger = log.With(logger, "stack", stackValuer) - - // Call through interface to get baseline. - logger.Log("k", "v") - want := output[1].(int) - - for len(output) < 10 { - logger.Log("k", "v") - if have := output[1]; have != want { - t.Errorf("%d Withs: have %v, want %v", len(output)/2-1, have, want) - } - - wrapped := log.With(logger) - wrapped.Log("k", "v") - if have := output[1]; have != want { - t.Errorf("%d Withs: have %v, want %v", len(output)/2-1, have, want) - } - - logger = log.With(logger, "k", "v") - } -} - -// Test that With returns a Logger safe for concurrent use. This test -// validates that the stored logging context does not get corrupted when -// multiple clients concurrently log additional keyvals. -// -// This test must be run with go test -cpu 2 (or more) to achieve its goal. -func TestWithConcurrent(t *testing.T) { - // Create some buckets to count how many events each goroutine logs. - const goroutines = 8 - counts := [goroutines]int{} - - // This logger extracts a goroutine id from the last value field and - // increments the referenced bucket. - logger := log.LoggerFunc(func(kv ...interface{}) error { - goroutine := kv[len(kv)-1].(int) - counts[goroutine]++ - return nil - }) - - // With must be careful about handling slices that can grow without - // copying the underlying array, so give it a challenge. - l := log.With(logger, make([]interface{}, 0, 2)...) - - // Start logging concurrently. Each goroutine logs its id so the logger - // can bucket the event counts. - var wg sync.WaitGroup - wg.Add(goroutines) - const n = 10000 - for i := 0; i < goroutines; i++ { - go func(idx int) { - defer wg.Done() - for j := 0; j < n; j++ { - l.Log("goroutineIdx", idx) - } - }(i) - } - wg.Wait() - - for bucket, have := range counts { - if want := n; want != have { - t.Errorf("bucket %d: want %d, have %d", bucket, want, have) // note Errorf - } - } -} - -func BenchmarkDiscard(b *testing.B) { - logger := log.NewNopLogger() - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - logger.Log("k", "v") - } -} - -func BenchmarkOneWith(b *testing.B) { - logger := log.NewNopLogger() - lc := log.With(logger, "k", "v") - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - lc.Log("k", "v") - } -} - -func BenchmarkTwoWith(b *testing.B) { - logger := log.NewNopLogger() - lc := log.With(logger, "k", "v") - for i := 1; i < 2; i++ { - lc = log.With(lc, "k", "v") - } - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - lc.Log("k", "v") - } -} - -func BenchmarkTenWith(b *testing.B) { - logger := log.NewNopLogger() - lc := log.With(logger, "k", "v") - for i := 1; i < 10; i++ { - lc = log.With(lc, "k", "v") - } - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - lc.Log("k", "v") - } -} diff --git a/vendor/github.com/go-kit/kit/log/logfmt_logger_test.go b/vendor/github.com/go-kit/kit/log/logfmt_logger_test.go deleted file mode 100644 index 91bbca15c..000000000 --- a/vendor/github.com/go-kit/kit/log/logfmt_logger_test.go +++ /dev/null @@ -1,57 +0,0 @@ -package log_test - -import ( - "bytes" - "errors" - "io/ioutil" - "testing" - - "github.com/go-kit/kit/log" - "github.com/go-logfmt/logfmt" -) - -func TestLogfmtLogger(t *testing.T) { - t.Parallel() - buf := &bytes.Buffer{} - logger := log.NewLogfmtLogger(buf) - - if err := logger.Log("hello", "world"); err != nil { - t.Fatal(err) - } - if want, have := "hello=world\n", buf.String(); want != have { - t.Errorf("want %#v, have %#v", want, have) - } - - buf.Reset() - if err := logger.Log("a", 1, "err", errors.New("error")); err != nil { - t.Fatal(err) - } - if want, have := "a=1 err=error\n", buf.String(); want != have { - t.Errorf("want %#v, have %#v", want, have) - } - - buf.Reset() - if err := logger.Log("std_map", map[int]int{1: 2}, "my_map", mymap{0: 0}); err != nil { - t.Fatal(err) - } - if want, have := "std_map=\""+logfmt.ErrUnsupportedValueType.Error()+"\" my_map=special_behavior\n", buf.String(); want != have { - t.Errorf("want %#v, have %#v", want, have) - } -} - -func BenchmarkLogfmtLoggerSimple(b *testing.B) { - benchmarkRunner(b, log.NewLogfmtLogger(ioutil.Discard), baseMessage) -} - -func BenchmarkLogfmtLoggerContextual(b *testing.B) { - benchmarkRunner(b, log.NewLogfmtLogger(ioutil.Discard), withMessage) -} - -func TestLogfmtLoggerConcurrency(t *testing.T) { - t.Parallel() - testConcurrency(t, log.NewLogfmtLogger(ioutil.Discard), 10000) -} - -type mymap map[int]int - -func (m mymap) String() string { return "special_behavior" } diff --git a/vendor/github.com/go-kit/kit/log/nop_logger_test.go b/vendor/github.com/go-kit/kit/log/nop_logger_test.go deleted file mode 100644 index 908ddd816..000000000 --- a/vendor/github.com/go-kit/kit/log/nop_logger_test.go +++ /dev/null @@ -1,26 +0,0 @@ -package log_test - -import ( - "testing" - - "github.com/go-kit/kit/log" -) - -func TestNopLogger(t *testing.T) { - t.Parallel() - logger := log.NewNopLogger() - if err := logger.Log("abc", 123); err != nil { - t.Error(err) - } - if err := log.With(logger, "def", "ghi").Log(); err != nil { - t.Error(err) - } -} - -func BenchmarkNopLoggerSimple(b *testing.B) { - benchmarkRunner(b, log.NewNopLogger(), baseMessage) -} - -func BenchmarkNopLoggerContextual(b *testing.B) { - benchmarkRunner(b, log.NewNopLogger(), withMessage) -} diff --git a/vendor/github.com/go-kit/kit/log/stdlib_test.go b/vendor/github.com/go-kit/kit/log/stdlib_test.go deleted file mode 100644 index 90ebc5fa4..000000000 --- a/vendor/github.com/go-kit/kit/log/stdlib_test.go +++ /dev/null @@ -1,205 +0,0 @@ -package log - -import ( - "bytes" - "fmt" - "log" - "testing" - "time" -) - -func TestStdlibWriter(t *testing.T) { - buf := &bytes.Buffer{} - log.SetOutput(buf) - log.SetFlags(log.LstdFlags) - logger := NewLogfmtLogger(StdlibWriter{}) - logger.Log("key", "val") - timestamp := time.Now().Format("2006/01/02 15:04:05") - if want, have := timestamp+" key=val\n", buf.String(); want != have { - t.Errorf("want %q, have %q", want, have) - } -} - -func TestStdlibAdapterUsage(t *testing.T) { - buf := &bytes.Buffer{} - logger := NewLogfmtLogger(buf) - writer := NewStdlibAdapter(logger) - stdlog := log.New(writer, "", 0) - - now := time.Now() - date := now.Format("2006/01/02") - time := now.Format("15:04:05") - - for flag, want := range map[int]string{ - 0: "msg=hello\n", - log.Ldate: "ts=" + date + " msg=hello\n", - log.Ltime: "ts=" + time + " msg=hello\n", - log.Ldate | log.Ltime: "ts=\"" + date + " " + time + "\" msg=hello\n", - log.Lshortfile: "caller=stdlib_test.go:44 msg=hello\n", - log.Lshortfile | log.Ldate: "ts=" + date + " caller=stdlib_test.go:44 msg=hello\n", - log.Lshortfile | log.Ldate | log.Ltime: "ts=\"" + date + " " + time + "\" caller=stdlib_test.go:44 msg=hello\n", - } { - buf.Reset() - stdlog.SetFlags(flag) - stdlog.Print("hello") - if have := buf.String(); want != have { - t.Errorf("flag=%d: want %#v, have %#v", flag, want, have) - } - } -} - -func TestStdLibAdapterExtraction(t *testing.T) { - buf := &bytes.Buffer{} - logger := NewLogfmtLogger(buf) - writer := NewStdlibAdapter(logger) - for input, want := range map[string]string{ - "hello": "msg=hello\n", - "2009/01/23: hello": "ts=2009/01/23 msg=hello\n", - "2009/01/23 01:23:23: hello": "ts=\"2009/01/23 01:23:23\" msg=hello\n", - "01:23:23: hello": "ts=01:23:23 msg=hello\n", - "2009/01/23 01:23:23.123123: hello": "ts=\"2009/01/23 01:23:23.123123\" msg=hello\n", - "2009/01/23 01:23:23.123123 /a/b/c/d.go:23: hello": "ts=\"2009/01/23 01:23:23.123123\" caller=/a/b/c/d.go:23 msg=hello\n", - "01:23:23.123123 /a/b/c/d.go:23: hello": "ts=01:23:23.123123 caller=/a/b/c/d.go:23 msg=hello\n", - "2009/01/23 01:23:23 /a/b/c/d.go:23: hello": "ts=\"2009/01/23 01:23:23\" caller=/a/b/c/d.go:23 msg=hello\n", - "2009/01/23 /a/b/c/d.go:23: hello": "ts=2009/01/23 caller=/a/b/c/d.go:23 msg=hello\n", - "/a/b/c/d.go:23: hello": "caller=/a/b/c/d.go:23 msg=hello\n", - } { - buf.Reset() - fmt.Fprint(writer, input) - if have := buf.String(); want != have { - t.Errorf("%q: want %#v, have %#v", input, want, have) - } - } -} - -func TestStdlibAdapterSubexps(t *testing.T) { - for input, wantMap := range map[string]map[string]string{ - "hello world": { - "date": "", - "time": "", - "file": "", - "msg": "hello world", - }, - "2009/01/23: hello world": { - "date": "2009/01/23", - "time": "", - "file": "", - "msg": "hello world", - }, - "2009/01/23 01:23:23: hello world": { - "date": "2009/01/23", - "time": "01:23:23", - "file": "", - "msg": "hello world", - }, - "01:23:23: hello world": { - "date": "", - "time": "01:23:23", - "file": "", - "msg": "hello world", - }, - "2009/01/23 01:23:23.123123: hello world": { - "date": "2009/01/23", - "time": "01:23:23.123123", - "file": "", - "msg": "hello world", - }, - "2009/01/23 01:23:23.123123 /a/b/c/d.go:23: hello world": { - "date": "2009/01/23", - "time": "01:23:23.123123", - "file": "/a/b/c/d.go:23", - "msg": "hello world", - }, - "01:23:23.123123 /a/b/c/d.go:23: hello world": { - "date": "", - "time": "01:23:23.123123", - "file": "/a/b/c/d.go:23", - "msg": "hello world", - }, - "2009/01/23 01:23:23 /a/b/c/d.go:23: hello world": { - "date": "2009/01/23", - "time": "01:23:23", - "file": "/a/b/c/d.go:23", - "msg": "hello world", - }, - "2009/01/23 /a/b/c/d.go:23: hello world": { - "date": "2009/01/23", - "time": "", - "file": "/a/b/c/d.go:23", - "msg": "hello world", - }, - "/a/b/c/d.go:23: hello world": { - "date": "", - "time": "", - "file": "/a/b/c/d.go:23", - "msg": "hello world", - }, - "2009/01/23 01:23:23.123123 C:/a/b/c/d.go:23: hello world": { - "date": "2009/01/23", - "time": "01:23:23.123123", - "file": "C:/a/b/c/d.go:23", - "msg": "hello world", - }, - "01:23:23.123123 C:/a/b/c/d.go:23: hello world": { - "date": "", - "time": "01:23:23.123123", - "file": "C:/a/b/c/d.go:23", - "msg": "hello world", - }, - "2009/01/23 01:23:23 C:/a/b/c/d.go:23: hello world": { - "date": "2009/01/23", - "time": "01:23:23", - "file": "C:/a/b/c/d.go:23", - "msg": "hello world", - }, - "2009/01/23 C:/a/b/c/d.go:23: hello world": { - "date": "2009/01/23", - "time": "", - "file": "C:/a/b/c/d.go:23", - "msg": "hello world", - }, - "C:/a/b/c/d.go:23: hello world": { - "date": "", - "time": "", - "file": "C:/a/b/c/d.go:23", - "msg": "hello world", - }, - "2009/01/23 01:23:23.123123 C:/a/b/c/d.go:23: :.;<>_#{[]}\"\\": { - "date": "2009/01/23", - "time": "01:23:23.123123", - "file": "C:/a/b/c/d.go:23", - "msg": ":.;<>_#{[]}\"\\", - }, - "01:23:23.123123 C:/a/b/c/d.go:23: :.;<>_#{[]}\"\\": { - "date": "", - "time": "01:23:23.123123", - "file": "C:/a/b/c/d.go:23", - "msg": ":.;<>_#{[]}\"\\", - }, - "2009/01/23 01:23:23 C:/a/b/c/d.go:23: :.;<>_#{[]}\"\\": { - "date": "2009/01/23", - "time": "01:23:23", - "file": "C:/a/b/c/d.go:23", - "msg": ":.;<>_#{[]}\"\\", - }, - "2009/01/23 C:/a/b/c/d.go:23: :.;<>_#{[]}\"\\": { - "date": "2009/01/23", - "time": "", - "file": "C:/a/b/c/d.go:23", - "msg": ":.;<>_#{[]}\"\\", - }, - "C:/a/b/c/d.go:23: :.;<>_#{[]}\"\\": { - "date": "", - "time": "", - "file": "C:/a/b/c/d.go:23", - "msg": ":.;<>_#{[]}\"\\", - }, - } { - haveMap := subexps([]byte(input)) - for key, want := range wantMap { - if have := haveMap[key]; want != have { - t.Errorf("%q: %q: want %q, have %q", input, key, want, have) - } - } - } -} diff --git a/vendor/github.com/go-kit/kit/log/sync_test.go b/vendor/github.com/go-kit/kit/log/sync_test.go deleted file mode 100644 index 55e6b150d..000000000 --- a/vendor/github.com/go-kit/kit/log/sync_test.go +++ /dev/null @@ -1,83 +0,0 @@ -package log_test - -import ( - "bytes" - "io" - "os" - "testing" - - "github.com/go-kit/kit/log" -) - -func TestSwapLogger(t *testing.T) { - t.Parallel() - var logger log.SwapLogger - - // Zero value does not panic or error. - err := logger.Log("k", "v") - if got, want := err, error(nil); got != want { - t.Errorf("got %v, want %v", got, want) - } - - buf := &bytes.Buffer{} - json := log.NewJSONLogger(buf) - logger.Swap(json) - - if err := logger.Log("k", "v"); err != nil { - t.Error(err) - } - if got, want := buf.String(), `{"k":"v"}`+"\n"; got != want { - t.Errorf("got %v, want %v", got, want) - } - - buf.Reset() - prefix := log.NewLogfmtLogger(buf) - logger.Swap(prefix) - - if err := logger.Log("k", "v"); err != nil { - t.Error(err) - } - if got, want := buf.String(), "k=v\n"; got != want { - t.Errorf("got %v, want %v", got, want) - } - - buf.Reset() - logger.Swap(nil) - - if err := logger.Log("k", "v"); err != nil { - t.Error(err) - } - if got, want := buf.String(), ""; got != want { - t.Errorf("got %v, want %v", got, want) - } -} - -func TestSwapLoggerConcurrency(t *testing.T) { - t.Parallel() - testConcurrency(t, &log.SwapLogger{}, 10000) -} - -func TestSyncLoggerConcurrency(t *testing.T) { - var w io.Writer - w = &bytes.Buffer{} - logger := log.NewLogfmtLogger(w) - logger = log.NewSyncLogger(logger) - testConcurrency(t, logger, 10000) -} - -func TestSyncWriterConcurrency(t *testing.T) { - var w io.Writer - w = &bytes.Buffer{} - w = log.NewSyncWriter(w) - testConcurrency(t, log.NewLogfmtLogger(w), 10000) -} - -func TestSyncWriterFd(t *testing.T) { - _, ok := log.NewSyncWriter(os.Stdout).(interface { - Fd() uintptr - }) - - if !ok { - t.Error("NewSyncWriter does not pass through Fd method") - } -} diff --git a/vendor/github.com/go-kit/kit/log/term/LICENSE b/vendor/github.com/go-kit/kit/log/term/LICENSE new file mode 100644 index 000000000..f090cb42f --- /dev/null +++ b/vendor/github.com/go-kit/kit/log/term/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Simon Eskildsen + +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/go-kit/kit/log/value_test.go b/vendor/github.com/go-kit/kit/log/value_test.go deleted file mode 100644 index 3a0c835a3..000000000 --- a/vendor/github.com/go-kit/kit/log/value_test.go +++ /dev/null @@ -1,150 +0,0 @@ -package log_test - -import ( - "encoding" - "fmt" - "reflect" - "testing" - "time" - - "github.com/go-kit/kit/log" -) - -func TestValueBinding(t *testing.T) { - t.Parallel() - var output []interface{} - - logger := log.Logger(log.LoggerFunc(func(keyvals ...interface{}) error { - output = keyvals - return nil - })) - - start := time.Date(2015, time.April, 25, 0, 0, 0, 0, time.UTC) - now := start - mocktime := func() time.Time { - now = now.Add(time.Second) - return now - } - - lc := log.With(logger, "ts", log.Timestamp(mocktime), "caller", log.DefaultCaller) - - lc.Log("foo", "bar") - timestamp, ok := output[1].(time.Time) - if !ok { - t.Fatalf("want time.Time, have %T", output[1]) - } - if want, have := start.Add(time.Second), timestamp; want != have { - t.Errorf("output[1]: want %v, have %v", want, have) - } - if want, have := "value_test.go:31", fmt.Sprint(output[3]); want != have { - t.Errorf("output[3]: want %s, have %s", want, have) - } - - // A second attempt to confirm the bindings are truly dynamic. - lc.Log("foo", "bar") - timestamp, ok = output[1].(time.Time) - if !ok { - t.Fatalf("want time.Time, have %T", output[1]) - } - if want, have := start.Add(2*time.Second), timestamp; want != have { - t.Errorf("output[1]: want %v, have %v", want, have) - } - if want, have := "value_test.go:44", fmt.Sprint(output[3]); want != have { - t.Errorf("output[3]: want %s, have %s", want, have) - } -} - -func TestValueBinding_loggingZeroKeyvals(t *testing.T) { - t.Parallel() - var output []interface{} - - logger := log.Logger(log.LoggerFunc(func(keyvals ...interface{}) error { - output = keyvals - return nil - })) - - start := time.Date(2015, time.April, 25, 0, 0, 0, 0, time.UTC) - now := start - mocktime := func() time.Time { - now = now.Add(time.Second) - return now - } - - logger = log.With(logger, "ts", log.Timestamp(mocktime)) - - logger.Log() - timestamp, ok := output[1].(time.Time) - if !ok { - t.Fatalf("want time.Time, have %T", output[1]) - } - if want, have := start.Add(time.Second), timestamp; want != have { - t.Errorf("output[1]: want %v, have %v", want, have) - } - - // A second attempt to confirm the bindings are truly dynamic. - logger.Log() - timestamp, ok = output[1].(time.Time) - if !ok { - t.Fatalf("want time.Time, have %T", output[1]) - } - if want, have := start.Add(2*time.Second), timestamp; want != have { - t.Errorf("output[1]: want %v, have %v", want, have) - } -} - -func TestTimestampFormat(t *testing.T) { - t.Parallel() - - start := time.Date(2015, time.April, 25, 0, 0, 0, 0, time.UTC) - now := start - mocktime := func() time.Time { - now = now.Add(time.Second) - return now - } - - tv := log.TimestampFormat(mocktime, time.RFC822) - - if want, have := now.Add(time.Second).Format(time.RFC822), fmt.Sprint(tv()); want != have { - t.Errorf("wrong time format: want %v, have %v", want, have) - } - - if want, have := now.Add(2*time.Second).Format(time.RFC822), fmt.Sprint(tv()); want != have { - t.Errorf("wrong time format: want %v, have %v", want, have) - } - - mustMarshal := func(v interface{}) []byte { - b, err := v.(encoding.TextMarshaler).MarshalText() - if err != nil { - t.Fatal("error marshaling text:", err) - } - return b - } - - if want, have := now.Add(3*time.Second).AppendFormat(nil, time.RFC822), mustMarshal(tv()); !reflect.DeepEqual(want, have) { - t.Errorf("wrong time format: want %s, have %s", want, have) - } - - if want, have := now.Add(4*time.Second).AppendFormat(nil, time.RFC822), mustMarshal(tv()); !reflect.DeepEqual(want, have) { - t.Errorf("wrong time format: want %s, have %s", want, have) - } -} - -func BenchmarkValueBindingTimestamp(b *testing.B) { - logger := log.NewNopLogger() - lc := log.With(logger, "ts", log.DefaultTimestamp) - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - lc.Log("k", "v") - } -} - -func BenchmarkValueBindingCaller(b *testing.B) { - logger := log.NewNopLogger() - lc := log.With(logger, "caller", log.DefaultCaller) - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - lc.Log("k", "v") - } -} diff --git a/vendor/github.com/go-kit/kit/update_deps.bash b/vendor/github.com/go-kit/kit/update_deps.bash deleted file mode 100755 index 576e8b4a5..000000000 --- a/vendor/github.com/go-kit/kit/update_deps.bash +++ /dev/null @@ -1,28 +0,0 @@ -#!/usr/bin/env bash - -# This script updates each non-stdlib, non-Go-kit dependency to its most recent -# commit. It can be invoked to aid in debugging after a dependency-related -# failure on continuous integration. - -function deps { - go list -f '{{join .Deps "\n"}}' ./... -} - -function not_stdlib { - xargs go list -f '{{if not .Standard}}{{.ImportPath}}{{end}}' -} - -function not_gokit { - grep -v 'go-kit/kit' -} - -function go_get_update { - while read d - do - echo $d - go get -u $d || echo "failed, trying again with master" && cd $GOPATH/src/$d && git checkout master && go get -u $d - done -} - -deps | not_stdlib | not_gokit | go_get_update - diff --git a/vendor/github.com/go-logfmt/logfmt/.gitignore b/vendor/github.com/go-logfmt/logfmt/.gitignore deleted file mode 100644 index 320e53e98..000000000 --- a/vendor/github.com/go-logfmt/logfmt/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -_testdata/ -_testdata2/ -logfmt-fuzz.zip -logfmt.test.exe diff --git a/vendor/github.com/go-logfmt/logfmt/.travis.yml b/vendor/github.com/go-logfmt/logfmt/.travis.yml deleted file mode 100644 index b599f654d..000000000 --- a/vendor/github.com/go-logfmt/logfmt/.travis.yml +++ /dev/null @@ -1,15 +0,0 @@ -language: go -sudo: false -go: - - 1.3 - - 1.4 - - 1.5 - - 1.6 - - tip - -before_install: - - go get github.com/mattn/goveralls - - go get golang.org/x/tools/cmd/cover - -script: - - goveralls -service=travis-ci diff --git a/vendor/github.com/go-logfmt/logfmt/README.md b/vendor/github.com/go-logfmt/logfmt/README.md deleted file mode 100644 index 3a8f10b76..000000000 --- a/vendor/github.com/go-logfmt/logfmt/README.md +++ /dev/null @@ -1,33 +0,0 @@ -[![GoDoc](https://godoc.org/github.com/go-logfmt/logfmt?status.svg)](https://godoc.org/github.com/go-logfmt/logfmt) -[![Go Report Card](https://goreportcard.com/badge/go-logfmt/logfmt)](https://goreportcard.com/report/go-logfmt/logfmt) -[![TravisCI](https://travis-ci.org/go-logfmt/logfmt.svg?branch=master)](https://travis-ci.org/go-logfmt/logfmt) -[![Coverage Status](https://coveralls.io/repos/github/go-logfmt/logfmt/badge.svg?branch=master)](https://coveralls.io/github/go-logfmt/logfmt?branch=master) - -# logfmt - -Package logfmt implements utilities to marshal and unmarshal data in the [logfmt -format](https://brandur.org/logfmt). It provides an API similar to -[encoding/json](http://golang.org/pkg/encoding/json/) and -[encoding/xml](http://golang.org/pkg/encoding/xml/). - -The logfmt format was first documented by Brandur Leach in [this -article](https://brandur.org/logfmt). The format has not been formally -standardized. The most authoritative public specification to date has been the -documentation of a Go Language [package](http://godoc.org/github.com/kr/logfmt) -written by Blake Mizerany and Keith Rarick. - -## Goals - -This project attempts to conform as closely as possible to the prior art, while -also removing ambiguity where necessary to provide well behaved encoder and -decoder implementations. - -## Non-goals - -This project does not attempt to formally standardize the logfmt format. In the -event that logfmt is standardized this project would take conforming to the -standard as a goal. - -## Versioning - -Package logfmt publishes releases via [semver](http://semver.org/) compatible Git tags prefixed with a single 'v'. diff --git a/vendor/github.com/go-logfmt/logfmt/decode-bench_test.go b/vendor/github.com/go-logfmt/logfmt/decode-bench_test.go deleted file mode 100644 index f66dc25a4..000000000 --- a/vendor/github.com/go-logfmt/logfmt/decode-bench_test.go +++ /dev/null @@ -1,75 +0,0 @@ -package logfmt - -import ( - "bufio" - "bytes" - "testing" - - kr "github.com/kr/logfmt" -) - -func BenchmarkDecodeKeyval(b *testing.B) { - const rows = 10000 - data := []byte{} - for i := 0; i < rows; i++ { - data = append(data, "a=1 b=\"bar\" ƒ=2h3s r=\"esc\\tmore stuff\" d x=sf \n"...) - } - - b.SetBytes(int64(len(data))) - b.ResetTimer() - for i := 0; i < b.N; i++ { - var ( - dec = NewDecoder(bytes.NewReader(data)) - j = 0 - ) - for dec.ScanRecord() { - for dec.ScanKeyval() { - } - j++ - } - if err := dec.Err(); err != nil { - b.Errorf("got %v, want %v", err, nil) - } - if j != rows { - b.Errorf("got %v, want %v", j, rows) - } - } -} - -func BenchmarkKRDecode(b *testing.B) { - const rows = 10000 - data := []byte{} - for i := 0; i < rows; i++ { - data = append(data, "a=1 b=\"bar\" ƒ=2h3s r=\"esc\\tmore stuff\" d x=sf \n"...) - } - - b.SetBytes(int64(len(data))) - b.ResetTimer() - for i := 0; i < b.N; i++ { - var ( - s = bufio.NewScanner(bytes.NewReader(data)) - err error - j = 0 - dh discardHandler - ) - for err == nil && s.Scan() { - err = kr.Unmarshal(s.Bytes(), &dh) - j++ - } - if err == nil { - err = s.Err() - } - if err != nil { - b.Errorf("got %v, want %v", err, nil) - } - if j != rows { - b.Errorf("got %v, want %v", j, rows) - } - } -} - -type discardHandler struct{} - -func (discardHandler) HandleLogfmt(key, val []byte) error { - return nil -} diff --git a/vendor/github.com/go-logfmt/logfmt/decode_test.go b/vendor/github.com/go-logfmt/logfmt/decode_test.go deleted file mode 100644 index 363152daf..000000000 --- a/vendor/github.com/go-logfmt/logfmt/decode_test.go +++ /dev/null @@ -1,184 +0,0 @@ -package logfmt - -import ( - "bytes" - "fmt" - "reflect" - "strings" - "testing" -) - -type kv struct { - k, v []byte -} - -func (s kv) String() string { - return fmt.Sprintf("{k:%q v:%q}", s.k, s.v) -} - -func TestDecoder_scan(t *testing.T) { - tests := []struct { - data string - want [][]kv - }{ - {"", nil}, - {"\n\n", [][]kv{nil, nil}}, - {`x= `, [][]kv{{{[]byte("x"), nil}}}}, - {`y=`, [][]kv{{{[]byte("y"), nil}}}}, - {`y`, [][]kv{{{[]byte("y"), nil}}}}, - {`y=f`, [][]kv{{{[]byte("y"), []byte("f")}}}}, - {"y=\"\\tf\"", [][]kv{{{[]byte("y"), []byte("\tf")}}}}, - {"a=1\n", [][]kv{{{[]byte("a"), []byte("1")}}}}, - { - `a=1 b="bar" ƒ=2h3s r="esc\t" d x=sf `, - [][]kv{{ - {[]byte("a"), []byte("1")}, - {[]byte("b"), []byte("bar")}, - {[]byte("ƒ"), []byte("2h3s")}, - {[]byte("r"), []byte("esc\t")}, - {[]byte("d"), nil}, - {[]byte("x"), []byte("sf")}, - }}, - }, - { - "y=f\ny=g", - [][]kv{ - {{[]byte("y"), []byte("f")}}, - {{[]byte("y"), []byte("g")}}, - }, - }, - { - "y=f \n\x1e y=g", - [][]kv{ - {{[]byte("y"), []byte("f")}}, - {{[]byte("y"), []byte("g")}}, - }, - }, - { - "y= d y=g", - [][]kv{{ - {[]byte("y"), nil}, - {[]byte("d"), nil}, - {[]byte("y"), []byte("g")}, - }}, - }, - { - "y=\"f\"\ny=g", - [][]kv{ - {{[]byte("y"), []byte("f")}}, - {{[]byte("y"), []byte("g")}}, - }, - }, - { - "y=\"f\\n\"y=g", - [][]kv{{ - {[]byte("y"), []byte("f\n")}, - {[]byte("y"), []byte("g")}, - }}, - }, - } - - for _, test := range tests { - var got [][]kv - dec := NewDecoder(strings.NewReader(test.data)) - - for dec.ScanRecord() { - var kvs []kv - for dec.ScanKeyval() { - k := dec.Key() - v := dec.Value() - if k != nil { - kvs = append(kvs, kv{k, v}) - } - } - got = append(got, kvs) - } - if err := dec.Err(); err != nil { - t.Errorf("got err: %v", err) - } - if !reflect.DeepEqual(got, test.want) { - t.Errorf("\n in: %q\n got: %+v\nwant: %+v", test.data, got, test.want) - } - } -} - -func TestDecoder_errors(t *testing.T) { - tests := []struct { - data string - want error - }{ - {"a=1\n=bar", &SyntaxError{Msg: "unexpected '='", Line: 2, Pos: 1}}, - {"a=1\n\"k\"=bar", &SyntaxError{Msg: "unexpected '\"'", Line: 2, Pos: 1}}, - {"a=1\nk\"ey=bar", &SyntaxError{Msg: "unexpected '\"'", Line: 2, Pos: 2}}, - {"a=1\nk=b\"ar", &SyntaxError{Msg: "unexpected '\"'", Line: 2, Pos: 4}}, - {"a=1\nk=b =ar", &SyntaxError{Msg: "unexpected '='", Line: 2, Pos: 5}}, - {"a==", &SyntaxError{Msg: "unexpected '='", Line: 1, Pos: 3}}, - {"a=1\nk=b=ar", &SyntaxError{Msg: "unexpected '='", Line: 2, Pos: 4}}, - {"a=\"1", &SyntaxError{Msg: "unterminated quoted value", Line: 1, Pos: 5}}, - {"a=\"1\\", &SyntaxError{Msg: "unterminated quoted value", Line: 1, Pos: 6}}, - {"a=\"\\t1", &SyntaxError{Msg: "unterminated quoted value", Line: 1, Pos: 7}}, - {"a=\"\\u1\"", &SyntaxError{Msg: "invalid quoted value", Line: 1, Pos: 8}}, - {"a\ufffd=bar", &SyntaxError{Msg: "invalid key", Line: 1, Pos: 5}}, - {"\x80=bar", &SyntaxError{Msg: "invalid key", Line: 1, Pos: 2}}, - {"\x80", &SyntaxError{Msg: "invalid key", Line: 1, Pos: 2}}, - } - - for _, test := range tests { - dec := NewDecoder(strings.NewReader(test.data)) - - for dec.ScanRecord() { - for dec.ScanKeyval() { - } - } - if got, want := dec.Err(), test.want; !reflect.DeepEqual(got, want) { - t.Errorf("got: %v, want: %v", got, want) - } - } -} - -func TestDecoder_decode_encode(t *testing.T) { - tests := []struct { - in, out string - }{ - {"", ""}, - {"\n", "\n"}, - {"\n \n", "\n\n"}, - { - "a=1\nb=2\n", - "a=1\nb=2\n", - }, - { - "a=1 b=\"bar\" ƒ=2h3s r=\"esc\\t\" d x=sf ", - "a=1 b=bar ƒ=2h3s r=\"esc\\t\" d= x=sf\n", - }, - } - - for _, test := range tests { - dec := NewDecoder(strings.NewReader(test.in)) - buf := bytes.Buffer{} - enc := NewEncoder(&buf) - - var err error - loop: - for dec.ScanRecord() && err == nil { - for dec.ScanKeyval() { - if dec.Key() == nil { - continue - } - if err = enc.EncodeKeyval(dec.Key(), dec.Value()); err != nil { - break loop - } - } - enc.EndRecord() - } - if err == nil { - err = dec.Err() - } - if err != nil { - t.Errorf("got err: %v", err) - } - if got, want := buf.String(), test.out; got != want { - t.Errorf("\n got: %q\nwant: %q", got, want) - } - } -} diff --git a/vendor/github.com/go-logfmt/logfmt/encode_internal_test.go b/vendor/github.com/go-logfmt/logfmt/encode_internal_test.go deleted file mode 100644 index 6271ce8ac..000000000 --- a/vendor/github.com/go-logfmt/logfmt/encode_internal_test.go +++ /dev/null @@ -1,233 +0,0 @@ -package logfmt - -import ( - "bytes" - "errors" - "fmt" - "reflect" - "testing" -) - -func TestSafeString(t *testing.T) { - _, ok := safeString((*stringStringer)(nil)) - if got, want := ok, false; got != want { - t.Errorf(" got %v, want %v", got, want) - } -} - -func TestSafeMarshal(t *testing.T) { - kb, err := safeMarshal((*stringMarshaler)(nil)) - if got := kb; got != nil { - t.Errorf(" got %v, want nil", got) - } - if got, want := err, error(nil); got != want { - t.Errorf(" got %v, want %v", got, want) - } -} - -func TestWriteKeyStrings(t *testing.T) { - keygen := []func(string) interface{}{ - func(s string) interface{} { return s }, - func(s string) interface{} { return stringData(s) }, - func(s string) interface{} { return stringStringer(s) }, - func(s string) interface{} { return stringMarshaler(s) }, - } - - data := []struct { - key string - want string - err error - }{ - {key: "k", want: "k"}, - {key: `\`, want: `\`}, - {key: "\n", err: ErrInvalidKey}, - {key: "\x00", err: ErrInvalidKey}, - {key: "\x10", err: ErrInvalidKey}, - {key: "\x1F", err: ErrInvalidKey}, - {key: "", err: ErrInvalidKey}, - {key: " ", err: ErrInvalidKey}, - {key: "=", err: ErrInvalidKey}, - {key: `"`, err: ErrInvalidKey}, - } - - for _, g := range keygen { - for _, d := range data { - w := &bytes.Buffer{} - key := g(d.key) - err := writeKey(w, key) - if err != d.err { - t.Errorf("%#v (%[1]T): got error: %v, want error: %v", key, err, d.err) - } - if err != nil { - continue - } - if got, want := w.String(), d.want; got != want { - t.Errorf("%#v (%[1]T): got '%s', want '%s'", key, got, want) - } - } - } -} - -func TestWriteKey(t *testing.T) { - var ( - nilPtr *int - one = 1 - ptr = &one - ) - - data := []struct { - key interface{} - want string - err error - }{ - {key: nil, err: ErrNilKey}, - {key: nilPtr, err: ErrNilKey}, - {key: (*stringStringer)(nil), err: ErrNilKey}, - {key: (*stringMarshaler)(nil), err: ErrNilKey}, - {key: (*stringerMarshaler)(nil), err: ErrNilKey}, - {key: ptr, want: "1"}, - - {key: errorMarshaler{}, err: &MarshalerError{Type: reflect.TypeOf(errorMarshaler{}), Err: errMarshaling}}, - {key: make(chan int), err: ErrUnsupportedKeyType}, - {key: []int{}, err: ErrUnsupportedKeyType}, - {key: map[int]int{}, err: ErrUnsupportedKeyType}, - {key: [2]int{}, err: ErrUnsupportedKeyType}, - {key: struct{}{}, err: ErrUnsupportedKeyType}, - {key: fmt.Sprint, err: ErrUnsupportedKeyType}, - } - - for _, d := range data { - w := &bytes.Buffer{} - err := writeKey(w, d.key) - if !reflect.DeepEqual(err, d.err) { - t.Errorf("%#v: got error: %v, want error: %v", d.key, err, d.err) - } - if err != nil { - continue - } - if got, want := w.String(), d.want; got != want { - t.Errorf("%#v: got '%s', want '%s'", d.key, got, want) - } - } -} - -func TestWriteValueStrings(t *testing.T) { - keygen := []func(string) interface{}{ - func(s string) interface{} { return s }, - func(s string) interface{} { return errors.New(s) }, - func(s string) interface{} { return stringData(s) }, - func(s string) interface{} { return stringStringer(s) }, - func(s string) interface{} { return stringMarshaler(s) }, - } - - data := []struct { - value string - want string - err error - }{ - {value: "", want: ""}, - {value: "v", want: "v"}, - {value: " ", want: `" "`}, - {value: "=", want: `"="`}, - {value: `\`, want: `\`}, - {value: `"`, want: `"\""`}, - {value: `\"`, want: `"\\\""`}, - {value: "\n", want: `"\n"`}, - {value: "\x00", want: `"\u0000"`}, - {value: "\x10", want: `"\u0010"`}, - {value: "\x1F", want: `"\u001f"`}, - {value: "µ", want: `µ`}, - } - - for _, g := range keygen { - for _, d := range data { - w := &bytes.Buffer{} - value := g(d.value) - err := writeValue(w, value) - if err != d.err { - t.Errorf("%#v (%[1]T): got error: %v, want error: %v", value, err, d.err) - } - if err != nil { - continue - } - if got, want := w.String(), d.want; got != want { - t.Errorf("%#v (%[1]T): got '%s', want '%s'", value, got, want) - } - } - } -} - -func TestWriteValue(t *testing.T) { - var ( - nilPtr *int - one = 1 - ptr = &one - ) - - data := []struct { - value interface{} - want string - err error - }{ - {value: nil, want: "null"}, - {value: nilPtr, want: "null"}, - {value: (*stringStringer)(nil), want: "null"}, - {value: (*stringMarshaler)(nil), want: "null"}, - {value: (*stringerMarshaler)(nil), want: "null"}, - {value: ptr, want: "1"}, - - {value: errorMarshaler{}, err: &MarshalerError{Type: reflect.TypeOf(errorMarshaler{}), Err: errMarshaling}}, - {value: make(chan int), err: ErrUnsupportedValueType}, - {value: []int{}, err: ErrUnsupportedValueType}, - {value: map[int]int{}, err: ErrUnsupportedValueType}, - {value: [2]int{}, err: ErrUnsupportedValueType}, - {value: struct{}{}, err: ErrUnsupportedValueType}, - {value: fmt.Sprint, err: ErrUnsupportedValueType}, - } - - for _, d := range data { - w := &bytes.Buffer{} - err := writeValue(w, d.value) - if !reflect.DeepEqual(err, d.err) { - t.Errorf("%#v: got error: %v, want error: %v", d.value, err, d.err) - } - if err != nil { - continue - } - if got, want := w.String(), d.want; got != want { - t.Errorf("%#v: got '%s', want '%s'", d.value, got, want) - } - } -} - -type stringData string - -type stringStringer string - -func (s stringStringer) String() string { - return string(s) -} - -type stringMarshaler string - -func (s stringMarshaler) MarshalText() ([]byte, error) { - return []byte(s), nil -} - -type stringerMarshaler string - -func (s stringerMarshaler) String() string { - return "String() called" -} - -func (s stringerMarshaler) MarshalText() ([]byte, error) { - return []byte(s), nil -} - -var errMarshaling = errors.New("marshal error") - -type errorMarshaler struct{} - -func (errorMarshaler) MarshalText() ([]byte, error) { - return nil, errMarshaling -} diff --git a/vendor/github.com/go-logfmt/logfmt/encode_test.go b/vendor/github.com/go-logfmt/logfmt/encode_test.go deleted file mode 100644 index ebebaae61..000000000 --- a/vendor/github.com/go-logfmt/logfmt/encode_test.go +++ /dev/null @@ -1,206 +0,0 @@ -package logfmt_test - -import ( - "bytes" - "errors" - "fmt" - "io/ioutil" - "reflect" - "testing" - "time" - - "github.com/go-logfmt/logfmt" -) - -func TestEncodeKeyval(t *testing.T) { - data := []struct { - key, value interface{} - want string - err error - }{ - {key: "k", value: "v", want: "k=v"}, - {key: "k", value: nil, want: "k=null"}, - {key: `\`, value: "v", want: `\=v`}, - {key: "k", value: "", want: "k="}, - {key: "k", value: "null", want: `k="null"`}, - {key: "k", value: "", want: `k=`}, - {key: "k", value: true, want: "k=true"}, - {key: "k", value: 1, want: "k=1"}, - {key: "k", value: 1.025, want: "k=1.025"}, - {key: "k", value: 1e-3, want: "k=0.001"}, - {key: "k", value: 3.5 + 2i, want: "k=(3.5+2i)"}, - {key: "k", value: "v v", want: `k="v v"`}, - {key: "k", value: " ", want: `k=" "`}, - {key: "k", value: `"`, want: `k="\""`}, - {key: "k", value: `=`, want: `k="="`}, - {key: "k", value: `\`, want: `k=\`}, - {key: "k", value: `=\`, want: `k="=\\"`}, - {key: "k", value: `\"`, want: `k="\\\""`}, - {key: "k", value: [2]int{2, 19}, err: logfmt.ErrUnsupportedValueType}, - {key: "k", value: []string{"e1", "e 2"}, err: logfmt.ErrUnsupportedValueType}, - {key: "k", value: structData{"a a", 9}, err: logfmt.ErrUnsupportedValueType}, - {key: "k", value: decimalMarshaler{5, 9}, want: "k=5.9"}, - {key: "k", value: (*decimalMarshaler)(nil), want: "k=null"}, - {key: "k", value: decimalStringer{5, 9}, want: "k=5.9"}, - {key: "k", value: (*decimalStringer)(nil), want: "k=null"}, - {key: "k", value: marshalerStringer{5, 9}, want: "k=5.9"}, - {key: "k", value: (*marshalerStringer)(nil), want: "k=null"}, - {key: "k", value: new(nilMarshaler), want: "k=notnilmarshaler"}, - {key: "k", value: (*nilMarshaler)(nil), want: "k=nilmarshaler"}, - {key: (*marshalerStringer)(nil), value: "v", err: logfmt.ErrNilKey}, - {key: decimalMarshaler{5, 9}, value: "v", want: "5.9=v"}, - {key: (*decimalMarshaler)(nil), value: "v", err: logfmt.ErrNilKey}, - {key: decimalStringer{5, 9}, value: "v", want: "5.9=v"}, - {key: (*decimalStringer)(nil), value: "v", err: logfmt.ErrNilKey}, - {key: marshalerStringer{5, 9}, value: "v", want: "5.9=v"}, - {key: "k", value: "\xbd", want: `k="\ufffd"`}, - {key: "k", value: "\ufffd\x00", want: `k="\ufffd\u0000"`}, - {key: "k", value: "\ufffd", want: `k="\ufffd"`}, - {key: "k", value: []byte("\ufffd\x00"), want: `k="\ufffd\u0000"`}, - {key: "k", value: []byte("\ufffd"), want: `k="\ufffd"`}, - } - - for _, d := range data { - w := &bytes.Buffer{} - enc := logfmt.NewEncoder(w) - err := enc.EncodeKeyval(d.key, d.value) - if err != d.err { - t.Errorf("%#v, %#v: got error: %v, want error: %v", d.key, d.value, err, d.err) - } - if got, want := w.String(), d.want; got != want { - t.Errorf("%#v, %#v: got '%s', want '%s'", d.key, d.value, got, want) - } - } -} - -func TestMarshalKeyvals(t *testing.T) { - one := 1 - ptr := &one - nilPtr := (*int)(nil) - - data := []struct { - in []interface{} - want []byte - err error - }{ - {in: nil, want: nil}, - {in: kv(), want: nil}, - {in: kv(nil, "v"), err: logfmt.ErrNilKey}, - {in: kv(nilPtr, "v"), err: logfmt.ErrNilKey}, - {in: kv("\ufffd"), err: logfmt.ErrInvalidKey}, - {in: kv("\xbd"), err: logfmt.ErrInvalidKey}, - {in: kv("k"), want: []byte("k=null")}, - {in: kv("k", nil), want: []byte("k=null")}, - {in: kv("k", ""), want: []byte("k=")}, - {in: kv("k", "null"), want: []byte(`k="null"`)}, - {in: kv("k", "v"), want: []byte("k=v")}, - {in: kv("k", true), want: []byte("k=true")}, - {in: kv("k", 1), want: []byte("k=1")}, - {in: kv("k", ptr), want: []byte("k=1")}, - {in: kv("k", nilPtr), want: []byte("k=null")}, - {in: kv("k", 1.025), want: []byte("k=1.025")}, - {in: kv("k", 1e-3), want: []byte("k=0.001")}, - {in: kv("k", "v v"), want: []byte(`k="v v"`)}, - {in: kv("k", `"`), want: []byte(`k="\""`)}, - {in: kv("k", `=`), want: []byte(`k="="`)}, - {in: kv("k", `\`), want: []byte(`k=\`)}, - {in: kv("k", `=\`), want: []byte(`k="=\\"`)}, - {in: kv("k", `\"`), want: []byte(`k="\\\""`)}, - {in: kv("k1", "v1", "k2", "v2"), want: []byte("k1=v1 k2=v2")}, - {in: kv("k1", "v1", "k2", [2]int{}), want: []byte("k1=v1 k2=\"unsupported value type\"")}, - {in: kv([2]int{}, "v1", "k2", "v2"), want: []byte("k2=v2")}, - {in: kv("k", time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)), want: []byte("k=2009-11-10T23:00:00Z")}, - {in: kv("k", errorMarshaler{}), want: []byte("k=\"error marshaling value of type logfmt_test.errorMarshaler: marshal error\"")}, - {in: kv("k", decimalMarshaler{5, 9}), want: []byte("k=5.9")}, - {in: kv("k", (*decimalMarshaler)(nil)), want: []byte("k=null")}, - {in: kv("k", decimalStringer{5, 9}), want: []byte("k=5.9")}, - {in: kv("k", (*decimalStringer)(nil)), want: []byte("k=null")}, - {in: kv("k", marshalerStringer{5, 9}), want: []byte("k=5.9")}, - {in: kv("k", (*marshalerStringer)(nil)), want: []byte("k=null")}, - {in: kv(one, "v"), want: []byte("1=v")}, - {in: kv(ptr, "v"), want: []byte("1=v")}, - {in: kv((*marshalerStringer)(nil), "v"), err: logfmt.ErrNilKey}, - {in: kv(decimalMarshaler{5, 9}, "v"), want: []byte("5.9=v")}, - {in: kv((*decimalMarshaler)(nil), "v"), err: logfmt.ErrNilKey}, - {in: kv(decimalStringer{5, 9}, "v"), want: []byte("5.9=v")}, - {in: kv((*decimalStringer)(nil), "v"), err: logfmt.ErrNilKey}, - {in: kv(marshalerStringer{5, 9}, "v"), want: []byte("5.9=v")}, - } - - for _, d := range data { - got, err := logfmt.MarshalKeyvals(d.in...) - if err != d.err { - t.Errorf("%#v: got error: %v, want error: %v", d.in, err, d.err) - } - if !reflect.DeepEqual(got, d.want) { - t.Errorf("%#v: got '%s', want '%s'", d.in, got, d.want) - } - } -} - -func kv(keyvals ...interface{}) []interface{} { - return keyvals -} - -type structData struct { - A string `logfmt:"fieldA"` - B int -} - -type nilMarshaler int - -func (m *nilMarshaler) MarshalText() ([]byte, error) { - if m == nil { - return []byte("nilmarshaler"), nil - } - return []byte("notnilmarshaler"), nil -} - -type decimalMarshaler struct { - a, b int -} - -func (t decimalMarshaler) MarshalText() ([]byte, error) { - buf := &bytes.Buffer{} - fmt.Fprintf(buf, "%d.%d", t.a, t.b) - return buf.Bytes(), nil -} - -type decimalStringer struct { - a, b int -} - -func (s decimalStringer) String() string { - return fmt.Sprintf("%d.%d", s.a, s.b) -} - -type marshalerStringer struct { - a, b int -} - -func (t marshalerStringer) MarshalText() ([]byte, error) { - buf := &bytes.Buffer{} - fmt.Fprintf(buf, "%d.%d", t.a, t.b) - return buf.Bytes(), nil -} - -func (t marshalerStringer) String() string { - return fmt.Sprint(t.a + t.b) -} - -var errMarshal = errors.New("marshal error") - -type errorMarshaler struct{} - -func (errorMarshaler) MarshalText() ([]byte, error) { - return nil, errMarshal -} - -func BenchmarkEncodeKeyval(b *testing.B) { - b.ReportAllocs() - enc := logfmt.NewEncoder(ioutil.Discard) - for i := 0; i < b.N; i++ { - enc.EncodeKeyval("sk", "10") - enc.EncodeKeyval("some-key", "a rather long string with spaces") - } -} diff --git a/vendor/github.com/go-logfmt/logfmt/example_test.go b/vendor/github.com/go-logfmt/logfmt/example_test.go deleted file mode 100644 index 829dbd567..000000000 --- a/vendor/github.com/go-logfmt/logfmt/example_test.go +++ /dev/null @@ -1,60 +0,0 @@ -package logfmt_test - -import ( - "errors" - "fmt" - "os" - "strings" - "time" - - "github.com/go-logfmt/logfmt" -) - -func ExampleEncoder() { - check := func(err error) { - if err != nil { - panic(err) - } - } - - e := logfmt.NewEncoder(os.Stdout) - - check(e.EncodeKeyval("id", 1)) - check(e.EncodeKeyval("dur", time.Second+time.Millisecond)) - check(e.EndRecord()) - - check(e.EncodeKeyval("id", 1)) - check(e.EncodeKeyval("path", "/path/to/file")) - check(e.EncodeKeyval("err", errors.New("file not found"))) - check(e.EndRecord()) - - // Output: - // id=1 dur=1.001s - // id=1 path=/path/to/file err="file not found" -} - -func ExampleDecoder() { - in := ` -id=1 dur=1.001s -id=1 path=/path/to/file err="file not found" -` - - d := logfmt.NewDecoder(strings.NewReader(in)) - for d.ScanRecord() { - for d.ScanKeyval() { - fmt.Printf("k: %s v: %s\n", d.Key(), d.Value()) - } - fmt.Println() - } - if d.Err() != nil { - panic(d.Err()) - } - - // Output: - // k: id v: 1 - // k: dur v: 1.001s - // - // k: id v: 1 - // k: path v: /path/to/file - // k: err v: file not found -} diff --git a/vendor/github.com/go-openapi/jsonpointer/.editorconfig b/vendor/github.com/go-openapi/jsonpointer/.editorconfig deleted file mode 100644 index 3152da69a..000000000 --- a/vendor/github.com/go-openapi/jsonpointer/.editorconfig +++ /dev/null @@ -1,26 +0,0 @@ -# top-most EditorConfig file -root = true - -# Unix-style newlines with a newline ending every file -[*] -end_of_line = lf -insert_final_newline = true -indent_style = space -indent_size = 2 -trim_trailing_whitespace = true - -# Set default charset -[*.{js,py,go,scala,rb,java,html,css,less,sass,md}] -charset = utf-8 - -# Tab indentation (no size specified) -[*.go] -indent_style = tab - -[*.md] -trim_trailing_whitespace = false - -# Matches the exact files either package.json or .travis.yml -[{package.json,.travis.yml}] -indent_style = space -indent_size = 2 diff --git a/vendor/github.com/go-openapi/jsonpointer/.gitignore b/vendor/github.com/go-openapi/jsonpointer/.gitignore deleted file mode 100644 index 769c24400..000000000 --- a/vendor/github.com/go-openapi/jsonpointer/.gitignore +++ /dev/null @@ -1 +0,0 @@ -secrets.yml diff --git a/vendor/github.com/go-openapi/jsonpointer/.travis.yml b/vendor/github.com/go-openapi/jsonpointer/.travis.yml deleted file mode 100644 index d0f383a26..000000000 --- a/vendor/github.com/go-openapi/jsonpointer/.travis.yml +++ /dev/null @@ -1,13 +0,0 @@ -language: go -go: -- 1.7 -install: -- go get -u github.com/stretchr/testify/assert -- go get -u github.com/go-openapi/swag -script: -- go test -v -race -cover -coverprofile=coverage.txt -covermode=atomic ./... -after_success: -- bash <(curl -s https://codecov.io/bash) -notifications: - slack: - secure: a5VgoiwB1G/AZqzmephPZIhEB9avMlsWSlVnM1dSAtYAwdrQHGTQxAmpOxYIoSPDhWNN5bfZmjd29++UlTwLcHSR+e0kJhH6IfDlsHj/HplNCJ9tyI0zYc7XchtdKgeMxMzBKCzgwFXGSbQGydXTliDNBo0HOzmY3cou/daMFTP60K+offcjS+3LRAYb1EroSRXZqrk1nuF/xDL3792DZUdPMiFR/L/Df6y74D6/QP4sTkTDFQitz4Wy/7jbsfj8dG6qK2zivgV6/l+w4OVjFkxVpPXogDWY10vVXNVynqxfJ7to2d1I9lNCHE2ilBCkWMIPdyJF7hjF8pKW+82yP4EzRh0vu8Xn0HT5MZpQxdRY/YMxNrWaG7SxsoEaO4q5uhgdzAqLYY3TRa7MjIK+7Ur+aqOeTXn6OKwVi0CjvZ6mIU3WUKSwiwkFZMbjRAkSb5CYwMEfGFO/z964xz83qGt6WAtBXNotqCQpTIiKtDHQeLOMfksHImCg6JLhQcWBVxamVgu0G3Pdh8Y6DyPnxraXY95+QDavbjqv7TeYT9T/FNnrkXaTTK0s4iWE5H4ACU0Qvz0wUYgfQrZv0/Hp7V17+rabUwnzYySHCy9SWX/7OV9Cfh31iMp9ZIffr76xmmThtOEqs8TrTtU6BWI3rWwvA9cXQipZTVtL0oswrGw= diff --git a/vendor/github.com/go-openapi/jsonpointer/CODE_OF_CONDUCT.md b/vendor/github.com/go-openapi/jsonpointer/CODE_OF_CONDUCT.md deleted file mode 100644 index 9322b065e..000000000 --- a/vendor/github.com/go-openapi/jsonpointer/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,74 +0,0 @@ -# Contributor Covenant Code of Conduct - -## Our Pledge - -In the interest of fostering an open and welcoming environment, we as -contributors and maintainers pledge to making participation in our project and -our community a harassment-free experience for everyone, regardless of age, body -size, disability, ethnicity, gender identity and expression, level of experience, -nationality, personal appearance, race, religion, or sexual identity and -orientation. - -## Our Standards - -Examples of behavior that contributes to creating a positive environment -include: - -* Using welcoming and inclusive language -* Being respectful of differing viewpoints and experiences -* Gracefully accepting constructive criticism -* Focusing on what is best for the community -* Showing empathy towards other community members - -Examples of unacceptable behavior by participants include: - -* The use of sexualized language or imagery and unwelcome sexual attention or -advances -* Trolling, insulting/derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or electronic - address, without explicit permission -* Other conduct which could reasonably be considered inappropriate in a - professional setting - -## Our Responsibilities - -Project maintainers are responsible for clarifying the standards of acceptable -behavior and are expected to take appropriate and fair corrective action in -response to any instances of unacceptable behavior. - -Project maintainers have the right and responsibility to remove, edit, or -reject comments, commits, code, wiki edits, issues, and other contributions -that are not aligned to this Code of Conduct, or to ban temporarily or -permanently any contributor for other behaviors that they deem inappropriate, -threatening, offensive, or harmful. - -## Scope - -This Code of Conduct applies both within project spaces and in public spaces -when an individual is representing the project or its community. Examples of -representing a project or community include using an official project e-mail -address, posting via an official social media account, or acting as an appointed -representative at an online or offline event. Representation of a project may be -further defined and clarified by project maintainers. - -## Enforcement - -Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported by contacting the project team at ivan+abuse@flanders.co.nz. All -complaints will be reviewed and investigated and will result in a response that -is deemed necessary and appropriate to the circumstances. The project team is -obligated to maintain confidentiality with regard to the reporter of an incident. -Further details of specific enforcement policies may be posted separately. - -Project maintainers who do not follow or enforce the Code of Conduct in good -faith may face temporary or permanent repercussions as determined by other -members of the project's leadership. - -## Attribution - -This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, -available at [http://contributor-covenant.org/version/1/4][version] - -[homepage]: http://contributor-covenant.org -[version]: http://contributor-covenant.org/version/1/4/ diff --git a/vendor/github.com/go-openapi/jsonpointer/README.md b/vendor/github.com/go-openapi/jsonpointer/README.md deleted file mode 100644 index 813788aff..000000000 --- a/vendor/github.com/go-openapi/jsonpointer/README.md +++ /dev/null @@ -1,15 +0,0 @@ -# gojsonpointer [![Build Status](https://travis-ci.org/go-openapi/jsonpointer.svg?branch=master)](https://travis-ci.org/go-openapi/jsonpointer) [![codecov](https://codecov.io/gh/go-openapi/jsonpointer/branch/master/graph/badge.svg)](https://codecov.io/gh/go-openapi/jsonpointer) [![Slack Status](https://slackin.goswagger.io/badge.svg)](https://slackin.goswagger.io) - -[![license](http://img.shields.io/badge/license-Apache%20v2-orange.svg)](https://raw.githubusercontent.com/go-openapi/jsonpointer/master/LICENSE) [![GoDoc](https://godoc.org/github.com/go-openapi/jsonpointer?status.svg)](http://godoc.org/github.com/go-openapi/jsonpointer) -An implementation of JSON Pointer - Go language - -## Status -Completed YES - -Tested YES - -## References -http://tools.ietf.org/html/draft-ietf-appsawg-json-pointer-07 - -### Note -The 4.Evaluation part of the previous reference, starting with 'If the currently referenced value is a JSON array, the reference token MUST contain either...' is not implemented. diff --git a/vendor/github.com/go-openapi/jsonpointer/pointer_test.go b/vendor/github.com/go-openapi/jsonpointer/pointer_test.go deleted file mode 100644 index eabd58603..000000000 --- a/vendor/github.com/go-openapi/jsonpointer/pointer_test.go +++ /dev/null @@ -1,573 +0,0 @@ -// Copyright 2013 sigu-399 ( https://github.com/sigu-399 ) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// author sigu-399 -// author-github https://github.com/sigu-399 -// author-mail sigu.399@gmail.com -// -// repository-name jsonpointer -// repository-desc An implementation of JSON Pointer - Go language -// -// description Automated tests on package. -// -// created 03-03-2013 - -package jsonpointer - -import ( - "encoding/json" - "fmt" - "strconv" - "testing" - - "github.com/stretchr/testify/assert" -) - -const ( - TestDocumentNBItems = 11 - TestNodeObjNBItems = 4 - TestDocumentString = `{ -"foo": ["bar", "baz"], -"obj": { "a":1, "b":2, "c":[3,4], "d":[ {"e":9}, {"f":[50,51]} ] }, -"": 0, -"a/b": 1, -"c%d": 2, -"e^f": 3, -"g|h": 4, -"i\\j": 5, -"k\"l": 6, -" ": 7, -"m~n": 8 -}` -) - -var testDocumentJSON interface{} - -type testStructJSON struct { - Foo []string `json:"foo"` - Obj struct { - A int `json:"a"` - B int `json:"b"` - C []int `json:"c"` - D []struct { - E int `json:"e"` - F []int `json:"f"` - } `json:"d"` - } `json:"obj"` -} - -type aliasedMap map[string]interface{} - -var testStructJSONDoc testStructJSON -var testStructJSONPtr *testStructJSON - -func init() { - json.Unmarshal([]byte(TestDocumentString), &testDocumentJSON) - json.Unmarshal([]byte(TestDocumentString), &testStructJSONDoc) - testStructJSONPtr = &testStructJSONDoc -} - -func TestEscaping(t *testing.T) { - - ins := []string{`/`, `/`, `/a~1b`, `/a~1b`, `/c%d`, `/e^f`, `/g|h`, `/i\j`, `/k"l`, `/ `, `/m~0n`} - outs := []float64{0, 0, 1, 1, 2, 3, 4, 5, 6, 7, 8} - - for i := range ins { - p, err := New(ins[i]) - if assert.NoError(t, err, "input: %v", ins[i]) { - result, _, err := p.Get(testDocumentJSON) - if assert.NoError(t, err, "input: %v", ins[i]) { - assert.Equal(t, outs[i], result, "input: %v", ins[i]) - } - } - } - -} - -func TestFullDocument(t *testing.T) { - - in := `` - - p, err := New(in) - if err != nil { - t.Errorf("New(%v) error %v", in, err.Error()) - } - - result, _, err := p.Get(testDocumentJSON) - if err != nil { - t.Errorf("Get(%v) error %v", in, err.Error()) - } - - if len(result.(map[string]interface{})) != TestDocumentNBItems { - t.Errorf("Get(%v) = %v, expect full document", in, result) - } - - result, _, err = p.get(testDocumentJSON, nil) - if err != nil { - t.Errorf("Get(%v) error %v", in, err.Error()) - } - - if len(result.(map[string]interface{})) != TestDocumentNBItems { - t.Errorf("Get(%v) = %v, expect full document", in, result) - } -} - -func TestDecodedTokens(t *testing.T) { - p, err := New("/obj/a~1b") - assert.NoError(t, err) - assert.Equal(t, []string{"obj", "a/b"}, p.DecodedTokens()) -} - -func TestIsEmpty(t *testing.T) { - p, err := New("") - assert.NoError(t, err) - assert.True(t, p.IsEmpty()) - p, err = New("/obj") - assert.NoError(t, err) - assert.False(t, p.IsEmpty()) -} - -func TestGetSingle(t *testing.T) { - in := `/obj` - - _, err := New(in) - assert.NoError(t, err) - result, _, err := GetForToken(testDocumentJSON, "obj") - assert.NoError(t, err) - assert.Len(t, result, TestNodeObjNBItems) - - result, _, err = GetForToken(testStructJSONDoc, "Obj") - assert.Error(t, err) - assert.Nil(t, result) - - result, _, err = GetForToken(testStructJSONDoc, "Obj2") - assert.Error(t, err) - assert.Nil(t, result) -} - -type pointableImpl struct { - a string -} - -func (p pointableImpl) JSONLookup(token string) (interface{}, error) { - if token == "some" { - return p.a, nil - } - return nil, fmt.Errorf("object has no field %q", token) -} - -func TestPointableInterface(t *testing.T) { - p := &pointableImpl{"hello"} - - result, _, err := GetForToken(p, "some") - assert.NoError(t, err) - assert.Equal(t, p.a, result) - - result, _, err = GetForToken(p, "something") - assert.Error(t, err) - assert.Nil(t, result) -} - -func TestGetNode(t *testing.T) { - - in := `/obj` - - p, err := New(in) - assert.NoError(t, err) - result, _, err := p.Get(testDocumentJSON) - assert.NoError(t, err) - assert.Len(t, result, TestNodeObjNBItems) - - result, _, err = p.Get(aliasedMap(testDocumentJSON.(map[string]interface{}))) - assert.NoError(t, err) - assert.Len(t, result, TestNodeObjNBItems) - - result, _, err = p.Get(testStructJSONDoc) - assert.NoError(t, err) - assert.Equal(t, testStructJSONDoc.Obj, result) - - result, _, err = p.Get(testStructJSONPtr) - assert.NoError(t, err) - assert.Equal(t, testStructJSONDoc.Obj, result) -} - -func TestArray(t *testing.T) { - - ins := []string{`/foo/0`, `/foo/0`, `/foo/1`} - outs := []string{"bar", "bar", "baz"} - - for i := range ins { - p, err := New(ins[i]) - assert.NoError(t, err) - - result, _, err := p.Get(testStructJSONDoc) - assert.NoError(t, err) - assert.Equal(t, outs[i], result) - - result, _, err = p.Get(testStructJSONPtr) - assert.NoError(t, err) - assert.Equal(t, outs[i], result) - - result, _, err = p.Get(testDocumentJSON) - assert.NoError(t, err) - assert.Equal(t, outs[i], result) - } -} - -func TestOtherThings(t *testing.T) { - _, err := New("abc") - assert.Error(t, err) - - p, err := New("") - assert.NoError(t, err) - assert.Equal(t, "", p.String()) - - p, err = New("/obj/a") - assert.Equal(t, "/obj/a", p.String()) - - s := Escape("m~n") - assert.Equal(t, "m~0n", s) - s = Escape("m/n") - assert.Equal(t, "m~1n", s) - - p, err = New("/foo/3") - assert.NoError(t, err) - _, _, err = p.Get(testDocumentJSON) - assert.Error(t, err) - - p, err = New("/foo/a") - assert.NoError(t, err) - _, _, err = p.Get(testDocumentJSON) - assert.Error(t, err) - - p, err = New("/notthere") - assert.NoError(t, err) - _, _, err = p.Get(testDocumentJSON) - assert.Error(t, err) - - p, err = New("/invalid") - assert.NoError(t, err) - _, _, err = p.Get(1234) - assert.Error(t, err) - - p, err = New("/foo/1") - assert.NoError(t, err) - expected := "hello" - bbb := testDocumentJSON.(map[string]interface{})["foo"] - bbb.([]interface{})[1] = "hello" - - v, _, err := p.Get(testDocumentJSON) - assert.NoError(t, err) - assert.Equal(t, expected, v) - - esc := Escape("a/") - assert.Equal(t, "a~1", esc) - unesc := Unescape(esc) - assert.Equal(t, "a/", unesc) - - unesc = Unescape("~01") - assert.Equal(t, "~1", unesc) - assert.Equal(t, "~0~1", Escape("~/")) - assert.Equal(t, "~/", Unescape("~0~1")) -} - -func TestObject(t *testing.T) { - - ins := []string{`/obj/a`, `/obj/b`, `/obj/c/0`, `/obj/c/1`, `/obj/c/1`, `/obj/d/1/f/0`} - outs := []float64{1, 2, 3, 4, 4, 50} - - for i := range ins { - - p, err := New(ins[i]) - assert.NoError(t, err) - - result, _, err := p.Get(testDocumentJSON) - assert.NoError(t, err) - assert.Equal(t, outs[i], result) - - result, _, err = p.Get(testStructJSONDoc) - assert.NoError(t, err) - assert.EqualValues(t, outs[i], result) - - result, _, err = p.Get(testStructJSONPtr) - assert.NoError(t, err) - assert.EqualValues(t, outs[i], result) - } -} - -type setJsonDocEle struct { - B int `json:"b"` - C int `json:"c"` -} -type setJsonDoc struct { - A []struct { - B int `json:"b"` - C int `json:"c"` - } `json:"a"` - D int `json:"d"` -} - -type settableDoc struct { - Coll settableColl - Int settableInt -} - -func (s settableDoc) MarshalJSON() ([]byte, error) { - var res struct { - A settableColl `json:"a"` - D settableInt `json:"d"` - } - res.A = s.Coll - res.D = s.Int - return json.Marshal(res) -} -func (s *settableDoc) UnmarshalJSON(data []byte) error { - var res struct { - A settableColl `json:"a"` - D settableInt `json:"d"` - } - - if err := json.Unmarshal(data, &res); err != nil { - return err - } - s.Coll = res.A - s.Int = res.D - return nil -} - -// JSONLookup implements an interface to customize json pointer lookup -func (s settableDoc) JSONLookup(token string) (interface{}, error) { - switch token { - case "a": - return &s.Coll, nil - case "d": - return &s.Int, nil - default: - return nil, fmt.Errorf("%s is not a known field", token) - } -} - -// JSONLookup implements an interface to customize json pointer lookup -func (s *settableDoc) JSONSet(token string, data interface{}) error { - switch token { - case "a": - switch dt := data.(type) { - case settableColl: - s.Coll = dt - return nil - case *settableColl: - if dt != nil { - s.Coll = *dt - } else { - s.Coll = settableColl{} - } - return nil - case []settableCollItem: - s.Coll.Items = dt - return nil - } - case "d": - switch dt := data.(type) { - case settableInt: - s.Int = dt - return nil - case int: - s.Int.Value = dt - return nil - case int8: - s.Int.Value = int(dt) - return nil - case int16: - s.Int.Value = int(dt) - return nil - case int32: - s.Int.Value = int(dt) - return nil - case int64: - s.Int.Value = int(dt) - return nil - default: - return fmt.Errorf("invalid type %T for %s", data, token) - } - } - return fmt.Errorf("%s is not a known field", token) -} - -type settableColl struct { - Items []settableCollItem -} - -func (s settableColl) MarshalJSON() ([]byte, error) { - return json.Marshal(s.Items) -} -func (s *settableColl) UnmarshalJSON(data []byte) error { - return json.Unmarshal(data, &s.Items) -} - -// JSONLookup implements an interface to customize json pointer lookup -func (s settableColl) JSONLookup(token string) (interface{}, error) { - if tok, err := strconv.Atoi(token); err == nil { - return &s.Items[tok], nil - } - return nil, fmt.Errorf("%s is not a valid index", token) -} - -// JSONLookup implements an interface to customize json pointer lookup -func (s *settableColl) JSONSet(token string, data interface{}) error { - if _, err := strconv.Atoi(token); err == nil { - _, err := SetForToken(s.Items, token, data) - return err - } - return fmt.Errorf("%s is not a valid index", token) -} - -type settableCollItem struct { - B int `json:"b"` - C int `json:"c"` -} - -type settableInt struct { - Value int -} - -func (s settableInt) MarshalJSON() ([]byte, error) { - return json.Marshal(s.Value) -} -func (s *settableInt) UnmarshalJSON(data []byte) error { - return json.Unmarshal(data, &s.Value) -} - -func TestSetNode(t *testing.T) { - - jsonText := `{"a":[{"b": 1, "c": 2}], "d": 3}` - - var jsonDocument interface{} - if assert.NoError(t, json.Unmarshal([]byte(jsonText), &jsonDocument)) { - in := "/a/0/c" - p, err := New(in) - if assert.NoError(t, err) { - - _, err = p.Set(jsonDocument, 999) - assert.NoError(t, err) - - firstNode := jsonDocument.(map[string]interface{}) - assert.Len(t, firstNode, 2) - - sliceNode := firstNode["a"].([]interface{}) - assert.Len(t, sliceNode, 1) - - changedNode := sliceNode[0].(map[string]interface{}) - chNodeVI := changedNode["c"] - if assert.IsType(t, 0, chNodeVI) { - changedNodeValue := chNodeVI.(int) - if assert.Equal(t, 999, changedNodeValue) { - assert.Len(t, sliceNode, 1) - } - } - } - - v, err := New("/a/0") - if assert.NoError(t, err) { - _, err = v.Set(jsonDocument, map[string]interface{}{"b": 3, "c": 8}) - if assert.NoError(t, err) { - firstNode := jsonDocument.(map[string]interface{}) - assert.Len(t, firstNode, 2) - - sliceNode := firstNode["a"].([]interface{}) - assert.Len(t, sliceNode, 1) - changedNode := sliceNode[0].(map[string]interface{}) - assert.Equal(t, 3, changedNode["b"]) - assert.Equal(t, 8, changedNode["c"]) - } - } - } - - var structDoc setJsonDoc - if assert.NoError(t, json.Unmarshal([]byte(jsonText), &structDoc)) { - g, err := New("/a") - if assert.NoError(t, err) { - _, err = g.Set(&structDoc, []struct { - B int `json:"b"` - C int `json:"c"` - }{{B: 4, C: 7}}) - - if assert.NoError(t, err) { - assert.Len(t, structDoc.A, 1) - changedNode := structDoc.A[0] - assert.Equal(t, 4, changedNode.B) - assert.Equal(t, 7, changedNode.C) - } - } - - v, err := New("/a/0") - if assert.NoError(t, err) { - _, err = v.Set(structDoc, struct { - B int `json:"b"` - C int `json:"c"` - }{B: 3, C: 8}) - - if assert.NoError(t, err) { - assert.Len(t, structDoc.A, 1) - changedNode := structDoc.A[0] - assert.Equal(t, 3, changedNode.B) - assert.Equal(t, 8, changedNode.C) - } - } - - p, err := New("/a/0/c") - if assert.NoError(t, err) { - _, err = p.Set(&structDoc, 999) - assert.NoError(t, err) - if assert.Len(t, structDoc.A, 1) { - assert.Equal(t, 999, structDoc.A[0].C) - } - } - } - - var setDoc settableDoc - if assert.NoError(t, json.Unmarshal([]byte(jsonText), &setDoc)) { - g, err := New("/a") - if assert.NoError(t, err) { - _, err = g.Set(&setDoc, []settableCollItem{{B: 4, C: 7}}) - - if assert.NoError(t, err) { - assert.Len(t, setDoc.Coll.Items, 1) - changedNode := setDoc.Coll.Items[0] - assert.Equal(t, 4, changedNode.B) - assert.Equal(t, 7, changedNode.C) - } - } - - v, err := New("/a/0") - if assert.NoError(t, err) { - _, err = v.Set(setDoc, settableCollItem{B: 3, C: 8}) - - if assert.NoError(t, err) { - assert.Len(t, setDoc.Coll.Items, 1) - changedNode := setDoc.Coll.Items[0] - assert.Equal(t, 3, changedNode.B) - assert.Equal(t, 8, changedNode.C) - } - } - - p, err := New("/a/0/c") - if assert.NoError(t, err) { - _, err = p.Set(setDoc, 999) - assert.NoError(t, err) - if assert.Len(t, setDoc.Coll.Items, 1) { - assert.Equal(t, 999, setDoc.Coll.Items[0].C) - } - } - } -} diff --git a/vendor/github.com/go-openapi/jsonreference/.gitignore b/vendor/github.com/go-openapi/jsonreference/.gitignore deleted file mode 100644 index 769c24400..000000000 --- a/vendor/github.com/go-openapi/jsonreference/.gitignore +++ /dev/null @@ -1 +0,0 @@ -secrets.yml diff --git a/vendor/github.com/go-openapi/jsonreference/.travis.yml b/vendor/github.com/go-openapi/jsonreference/.travis.yml deleted file mode 100644 index 5b31a1b3e..000000000 --- a/vendor/github.com/go-openapi/jsonreference/.travis.yml +++ /dev/null @@ -1,14 +0,0 @@ -language: go -go: -- 1.7 -install: -- go get -u github.com/stretchr/testify/assert -- go get -u github.com/PuerkitoBio/purell -- go get -u github.com/go-openapi/jsonpointer -script: -- go test -v -race -cover -coverprofile=coverage.txt -covermode=atomic ./... -after_success: -- bash <(curl -s https://codecov.io/bash) -notifications: - slack: - secure: OpQG/36F7DSF00HLm9WZMhyqFCYYyYTsVDObW226cWiR8PWYiNfLZiSEvIzT1Gx4dDjhigKTIqcLhG34CkL5iNXDjm9Yyo2RYhQPlK8NErNqUEXuBqn4RqYHW48VGhEhOyDd4Ei0E2FN5ZbgpvHgtpkdZ6XDi64r3Ac89isP9aPHXQTuv2Jog6b4/OKKiUTftLcTIst0p4Cp3gqOJWf1wnoj+IadWiECNVQT6zb47IYjtyw6+uV8iUjTzdKcRB6Zc6b4Dq7JAg1Zd7Jfxkql3hlKp4PNlRf9Cy7y5iA3G7MLyg3FcPX5z2kmcyPt2jOTRMBWUJ5zIQpOxizAcN8WsT3WWBL5KbuYK6k0PzujrIDLqdxGpNmjkkMfDBT9cKmZpm2FdW+oZgPFJP+oKmAo4u4KJz/vjiPTXgQlN5bmrLuRMCp+AwC5wkIohTqWZVPE2TK6ZSnMYcg/W39s+RP/9mJoyryAvPSpBOLTI+biCgaUCTOAZxNTWpMFc3tPYntc41WWkdKcooZ9JA5DwfcaVFyTGQ3YXz+HvX6G1z/gW0Q/A4dBi9mj2iE1xm7tRTT+4VQ2AXFvSEI1HJpfPgYnwAtwOD1v3Qm2EUHk9sCdtEDR4wVGEPIVn44GnwFMnGKx9JWppMPYwFu3SVDdHt+E+LOlhZUply11Aa+IVrT2KUQ= diff --git a/vendor/github.com/go-openapi/jsonreference/CODE_OF_CONDUCT.md b/vendor/github.com/go-openapi/jsonreference/CODE_OF_CONDUCT.md deleted file mode 100644 index 9322b065e..000000000 --- a/vendor/github.com/go-openapi/jsonreference/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,74 +0,0 @@ -# Contributor Covenant Code of Conduct - -## Our Pledge - -In the interest of fostering an open and welcoming environment, we as -contributors and maintainers pledge to making participation in our project and -our community a harassment-free experience for everyone, regardless of age, body -size, disability, ethnicity, gender identity and expression, level of experience, -nationality, personal appearance, race, religion, or sexual identity and -orientation. - -## Our Standards - -Examples of behavior that contributes to creating a positive environment -include: - -* Using welcoming and inclusive language -* Being respectful of differing viewpoints and experiences -* Gracefully accepting constructive criticism -* Focusing on what is best for the community -* Showing empathy towards other community members - -Examples of unacceptable behavior by participants include: - -* The use of sexualized language or imagery and unwelcome sexual attention or -advances -* Trolling, insulting/derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or electronic - address, without explicit permission -* Other conduct which could reasonably be considered inappropriate in a - professional setting - -## Our Responsibilities - -Project maintainers are responsible for clarifying the standards of acceptable -behavior and are expected to take appropriate and fair corrective action in -response to any instances of unacceptable behavior. - -Project maintainers have the right and responsibility to remove, edit, or -reject comments, commits, code, wiki edits, issues, and other contributions -that are not aligned to this Code of Conduct, or to ban temporarily or -permanently any contributor for other behaviors that they deem inappropriate, -threatening, offensive, or harmful. - -## Scope - -This Code of Conduct applies both within project spaces and in public spaces -when an individual is representing the project or its community. Examples of -representing a project or community include using an official project e-mail -address, posting via an official social media account, or acting as an appointed -representative at an online or offline event. Representation of a project may be -further defined and clarified by project maintainers. - -## Enforcement - -Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported by contacting the project team at ivan+abuse@flanders.co.nz. All -complaints will be reviewed and investigated and will result in a response that -is deemed necessary and appropriate to the circumstances. The project team is -obligated to maintain confidentiality with regard to the reporter of an incident. -Further details of specific enforcement policies may be posted separately. - -Project maintainers who do not follow or enforce the Code of Conduct in good -faith may face temporary or permanent repercussions as determined by other -members of the project's leadership. - -## Attribution - -This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, -available at [http://contributor-covenant.org/version/1/4][version] - -[homepage]: http://contributor-covenant.org -[version]: http://contributor-covenant.org/version/1/4/ diff --git a/vendor/github.com/go-openapi/jsonreference/README.md b/vendor/github.com/go-openapi/jsonreference/README.md deleted file mode 100644 index 66345f4c6..000000000 --- a/vendor/github.com/go-openapi/jsonreference/README.md +++ /dev/null @@ -1,15 +0,0 @@ -# gojsonreference [![Build Status](https://travis-ci.org/go-openapi/jsonreference.svg?branch=master)](https://travis-ci.org/go-openapi/jsonreference) [![codecov](https://codecov.io/gh/go-openapi/jsonreference/branch/master/graph/badge.svg)](https://codecov.io/gh/go-openapi/jsonreference) [![Slack Status](https://slackin.goswagger.io/badge.svg)](https://slackin.goswagger.io) - -[![license](http://img.shields.io/badge/license-Apache%20v2-orange.svg)](https://raw.githubusercontent.com/go-openapi/jsonreference/master/LICENSE) [![GoDoc](https://godoc.org/github.com/go-openapi/jsonreference?status.svg)](http://godoc.org/github.com/go-openapi/jsonreference) -An implementation of JSON Reference - Go language - -## Status -Work in progress ( 90% done ) - -## Dependencies -https://github.com/go-openapi/jsonpointer - -## References -http://tools.ietf.org/html/draft-ietf-appsawg-json-pointer-07 - -http://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03 diff --git a/vendor/github.com/go-openapi/jsonreference/reference_test.go b/vendor/github.com/go-openapi/jsonreference/reference_test.go deleted file mode 100644 index 499c634c5..000000000 --- a/vendor/github.com/go-openapi/jsonreference/reference_test.go +++ /dev/null @@ -1,420 +0,0 @@ -// Copyright 2013 sigu-399 ( https://github.com/sigu-399 ) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// author sigu-399 -// author-github https://github.com/sigu-399 -// author-mail sigu.399@gmail.com -// -// repository-name jsonreference -// repository-desc An implementation of JSON Reference - Go language -// -// description Automated tests on package. -// -// created 03-03-2013 - -package jsonreference - -import ( - "testing" - - "github.com/go-openapi/jsonpointer" - "github.com/stretchr/testify/assert" -) - -func TestIsRoot(t *testing.T) { - in := "#" - r1, err := New(in) - assert.NoError(t, err) - assert.True(t, r1.IsRoot()) - - in = "#/ok" - r1 = MustCreateRef(in) - assert.False(t, r1.IsRoot()) - - assert.Panics(t, assert.PanicTestFunc(func() { - MustCreateRef("%2") - })) -} - -func TestFull(t *testing.T) { - - in := "http://host/path/a/b/c#/f/a/b" - - r1, err := New(in) - if err != nil { - t.Errorf("New(%v) error %s", in, err.Error()) - } - - if in != r1.String() { - t.Errorf("New(%v) = %v, expect %v", in, r1.String(), in) - } - - if r1.HasFragmentOnly != false { - t.Errorf("New(%v)::HasFragmentOnly %v expect %v", in, r1.HasFragmentOnly, false) - } - - if r1.HasFullURL != true { - t.Errorf("New(%v)::HasFullURL %v expect %v", in, r1.HasFullURL, true) - } - - if r1.HasURLPathOnly != false { - t.Errorf("New(%v)::HasURLPathOnly %v expect %v", in, r1.HasURLPathOnly, false) - } - - if r1.HasFileScheme != false { - t.Errorf("New(%v)::HasFileScheme %v expect %v", in, r1.HasFileScheme, false) - } - - if r1.GetPointer().String() != "/f/a/b" { - t.Errorf("New(%v)::GetPointer() %v expect %v", in, r1.GetPointer().String(), "/f/a/b") - } -} - -func TestFullURL(t *testing.T) { - - in := "http://host/path/a/b/c" - - r1, err := New(in) - if err != nil { - t.Errorf("New(%v) error %s", in, err.Error()) - } - - if in != r1.String() { - t.Errorf("New(%v) = %v, expect %v", in, r1.String(), in) - } - - if r1.HasFragmentOnly != false { - t.Errorf("New(%v)::HasFragmentOnly %v expect %v", in, r1.HasFragmentOnly, false) - } - - if r1.HasFullURL != true { - t.Errorf("New(%v)::HasFullURL %v expect %v", in, r1.HasFullURL, true) - } - - if r1.HasURLPathOnly != false { - t.Errorf("New(%v)::HasURLPathOnly %v expect %v", in, r1.HasURLPathOnly, false) - } - - if r1.HasFileScheme != false { - t.Errorf("New(%v)::HasFileScheme %v expect %v", in, r1.HasFileScheme, false) - } - - if r1.GetPointer().String() != "" { - t.Errorf("New(%v)::GetPointer() %v expect %v", in, r1.GetPointer().String(), "") - } -} - -func TestFragmentOnly(t *testing.T) { - - in := "#/fragment/only" - - r1, err := New(in) - if err != nil { - t.Errorf("New(%v) error %s", in, err.Error()) - } - - if in != r1.String() { - t.Errorf("New(%v) = %v, expect %v", in, r1.String(), in) - } - - if r1.HasFragmentOnly != true { - t.Errorf("New(%v)::HasFragmentOnly %v expect %v", in, r1.HasFragmentOnly, true) - } - - if r1.HasFullURL != false { - t.Errorf("New(%v)::HasFullURL %v expect %v", in, r1.HasFullURL, false) - } - - if r1.HasURLPathOnly != false { - t.Errorf("New(%v)::HasURLPathOnly %v expect %v", in, r1.HasURLPathOnly, false) - } - - if r1.HasFileScheme != false { - t.Errorf("New(%v)::HasFileScheme %v expect %v", in, r1.HasFileScheme, false) - } - - if r1.GetPointer().String() != "/fragment/only" { - t.Errorf("New(%v)::GetPointer() %v expect %v", in, r1.GetPointer().String(), "/fragment/only") - } - - p, _ := jsonpointer.New(r1.referenceURL.Fragment) - r2 := Ref{referencePointer: p, HasFragmentOnly: true} - assert.Equal(t, r2.String(), in) - - r3 := Ref{referencePointer: p, HasFragmentOnly: false} - assert.Equal(t, r3.String(), in[1:]) -} - -func TestURLPathOnly(t *testing.T) { - - in := "/documents/document.json" - - r1, err := New(in) - if err != nil { - t.Errorf("New(%v) error %s", in, err.Error()) - } - - if in != r1.String() { - t.Errorf("New(%v) = %v, expect %v", in, r1.String(), in) - } - - if r1.HasFragmentOnly != false { - t.Errorf("New(%v)::HasFragmentOnly %v expect %v", in, r1.HasFragmentOnly, false) - } - - if r1.HasFullURL != false { - t.Errorf("New(%v)::HasFullURL %v expect %v", in, r1.HasFullURL, false) - } - - if r1.HasURLPathOnly != true { - t.Errorf("New(%v)::HasURLPathOnly %v expect %v", in, r1.HasURLPathOnly, true) - } - - if r1.HasFileScheme != false { - t.Errorf("New(%v)::HasFileScheme %v expect %v", in, r1.HasFileScheme, false) - } - - if r1.GetPointer().String() != "" { - t.Errorf("New(%v)::GetPointer() %v expect %v", in, r1.GetPointer().String(), "") - } -} - -func TestURLRelativePathOnly(t *testing.T) { - - in := "document.json" - - r1, err := New(in) - if err != nil { - t.Errorf("New(%v) error %s", in, err.Error()) - } - - if in != r1.String() { - t.Errorf("New(%v) = %v, expect %v", in, r1.String(), in) - } - - if r1.HasFragmentOnly != false { - t.Errorf("New(%v)::HasFragmentOnly %v expect %v", in, r1.HasFragmentOnly, false) - } - - if r1.HasFullURL != false { - t.Errorf("New(%v)::HasFullURL %v expect %v", in, r1.HasFullURL, false) - } - - if r1.HasURLPathOnly != true { - t.Errorf("New(%v)::HasURLPathOnly %v expect %v", in, r1.HasURLPathOnly, true) - } - - if r1.HasFileScheme != false { - t.Errorf("New(%v)::HasFileScheme %v expect %v", in, r1.HasFileScheme, false) - } - - if r1.GetPointer().String() != "" { - t.Errorf("New(%v)::GetPointer() %v expect %v", in, r1.GetPointer().String(), "") - } -} - -func TestInheritsInValid(t *testing.T) { - in1 := "http://www.test.com/doc.json" - in2 := "#/a/b" - - r1, _ := New(in1) - r2 := Ref{} - result, err := r1.Inherits(r2) - assert.Error(t, err) - assert.Nil(t, result) - - r1 = Ref{} - r2, _ = New(in2) - result, err = r1.Inherits(r2) - assert.NoError(t, err) - assert.Equal(t, r2, *result) -} - -func TestInheritsValid(t *testing.T) { - - in1 := "http://www.test.com/doc.json" - in2 := "#/a/b" - out := in1 + in2 - - r1, _ := New(in1) - r2, _ := New(in2) - - result, err := r1.Inherits(r2) - if err != nil { - t.Errorf("Inherits(%s,%s) error %s", r1.String(), r2.String(), err.Error()) - } - - if result.String() != out { - t.Errorf("Inherits(%s,%s) = %s, expect %s", r1.String(), r2.String(), result.String(), out) - } - - if result.GetPointer().String() != "/a/b" { - t.Errorf("result(%v)::GetPointer() %v expect %v", result.String(), result.GetPointer().String(), "/a/b") - } -} - -func TestInheritsDifferentHost(t *testing.T) { - - in1 := "http://www.test.com/doc.json" - in2 := "http://www.test2.com/doc.json#bla" - - r1, _ := New(in1) - r2, _ := New(in2) - - result, err := r1.Inherits(r2) - - if err != nil { - t.Errorf("Inherits(%s,%s) should not fail. Error: %s", r1.String(), r2.String(), err.Error()) - } - - if result.String() != in2 { - t.Errorf("Inherits(%s,%s) should be %s but is %s", in1, in2, in2, result) - } - - if result.GetPointer().String() != "" { - t.Errorf("result(%v)::GetPointer() %v expect %v", result.String(), result.GetPointer().String(), "") - } -} - -func TestFileScheme(t *testing.T) { - - in1 := "file:///Users/mac/1.json#a" - in2 := "file:///Users/mac/2.json#b" - - r1, _ := New(in1) - r2, _ := New(in2) - - if r1.HasFragmentOnly != false { - t.Errorf("New(%v)::HasFragmentOnly %v expect %v", in1, r1.HasFragmentOnly, false) - } - - if r1.HasFileScheme != true { - t.Errorf("New(%v)::HasFileScheme %v expect %v", in1, r1.HasFileScheme, true) - } - - if r1.HasFullFilePath != true { - t.Errorf("New(%v)::HasFullFilePath %v expect %v", in1, r1.HasFullFilePath, true) - } - - if r1.IsCanonical() != true { - t.Errorf("New(%v)::IsCanonical %v expect %v", in1, r1.IsCanonical, true) - } - - result, err := r1.Inherits(r2) - if err != nil { - t.Errorf("Inherits(%s,%s) should not fail. Error: %s", r1.String(), r2.String(), err.Error()) - } - if result.String() != in2 { - t.Errorf("Inherits(%s,%s) should be %s but is %s", in1, in2, in2, result) - } - - if result.GetPointer().String() != "" { - t.Errorf("result(%v)::GetPointer() %v expect %v", result.String(), result.GetPointer().String(), "") - } -} - -func TestReferenceResolution(t *testing.T) { - - // 5.4. Reference Resolution Examples - // http://tools.ietf.org/html/rfc3986#section-5.4 - - base := "http://a/b/c/d;p?q" - baseRef, err := New(base) - - if err != nil { - t.Errorf("New(%s) failed error: %s", base, err.Error()) - } - if baseRef.String() != base { - t.Errorf("New(%s) %s expected %s", base, baseRef.String(), base) - } - - checks := []string{ - // 5.4.1. Normal Examples - // http://tools.ietf.org/html/rfc3986#section-5.4.1 - - "g:h", "g:h", - "g", "http://a/b/c/g", - "./g", "http://a/b/c/g", - "g/", "http://a/b/c/g/", - "/g", "http://a/g", - "//g", "http://g", - "?y", "http://a/b/c/d;p?y", - "g?y", "http://a/b/c/g?y", - "#s", "http://a/b/c/d;p?q#s", - "g#s", "http://a/b/c/g#s", - "g?y#s", "http://a/b/c/g?y#s", - ";x", "http://a/b/c/;x", - "g;x", "http://a/b/c/g;x", - "g;x?y#s", "http://a/b/c/g;x?y#s", - "", "http://a/b/c/d;p?q", - ".", "http://a/b/c/", - "./", "http://a/b/c/", - "..", "http://a/b/", - "../", "http://a/b/", - "../g", "http://a/b/g", - "../..", "http://a/", - "../../", "http://a/", - "../../g", "http://a/g", - - // 5.4.2. Abnormal Examples - // http://tools.ietf.org/html/rfc3986#section-5.4.2 - - "../../../g", "http://a/g", - "../../../../g", "http://a/g", - - "/./g", "http://a/g", - "/../g", "http://a/g", - "g.", "http://a/b/c/g.", - ".g", "http://a/b/c/.g", - "g..", "http://a/b/c/g..", - "..g", "http://a/b/c/..g", - - "./../g", "http://a/b/g", - "./g/.", "http://a/b/c/g/", - "g/./h", "http://a/b/c/g/h", - "g/../h", "http://a/b/c/h", - "g;x=1/./y", "http://a/b/c/g;x=1/y", - "g;x=1/../y", "http://a/b/c/y", - - "g?y/./x", "http://a/b/c/g?y/./x", - "g?y/../x", "http://a/b/c/g?y/../x", - "g#s/./x", "http://a/b/c/g#s/./x", - "g#s/../x", "http://a/b/c/g#s/../x", - - "http:g", "http:g", // for strict parsers - //"http:g", "http://a/b/c/g", // for backward compatibility - - } - for i := 0; i < len(checks); i += 2 { - child := checks[i] - expected := checks[i+1] - // fmt.Printf("%d: %v -> %v\n", i/2, child, expected) - - childRef, e := New(child) - if e != nil { - t.Errorf("%d: New(%s) failed error: %s", i/2, child, e.Error()) - } - - res, e := baseRef.Inherits(childRef) - if res == nil { - t.Errorf("%d: Inherits(%s, %s) nil not expected", i/2, base, child) - } - if e != nil { - t.Errorf("%d: Inherits(%s) failed error: %s", i/2, child, e.Error()) - } - if res.String() != expected { - t.Errorf("%d: Inherits(%s, %s) %s expected %s", i/2, base, child, res.String(), expected) - } - } -} diff --git a/vendor/github.com/go-openapi/spec/.editorconfig b/vendor/github.com/go-openapi/spec/.editorconfig deleted file mode 100644 index 3152da69a..000000000 --- a/vendor/github.com/go-openapi/spec/.editorconfig +++ /dev/null @@ -1,26 +0,0 @@ -# top-most EditorConfig file -root = true - -# Unix-style newlines with a newline ending every file -[*] -end_of_line = lf -insert_final_newline = true -indent_style = space -indent_size = 2 -trim_trailing_whitespace = true - -# Set default charset -[*.{js,py,go,scala,rb,java,html,css,less,sass,md}] -charset = utf-8 - -# Tab indentation (no size specified) -[*.go] -indent_style = tab - -[*.md] -trim_trailing_whitespace = false - -# Matches the exact files either package.json or .travis.yml -[{package.json,.travis.yml}] -indent_style = space -indent_size = 2 diff --git a/vendor/github.com/go-openapi/spec/.gitignore b/vendor/github.com/go-openapi/spec/.gitignore deleted file mode 100644 index dd91ed6a0..000000000 --- a/vendor/github.com/go-openapi/spec/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -secrets.yml -coverage.out diff --git a/vendor/github.com/go-openapi/spec/.travis.yml b/vendor/github.com/go-openapi/spec/.travis.yml deleted file mode 100644 index ea80ef2a7..000000000 --- a/vendor/github.com/go-openapi/spec/.travis.yml +++ /dev/null @@ -1,16 +0,0 @@ -language: go -go: -- 1.7 -install: -- go get -u github.com/stretchr/testify -- go get -u github.com/go-openapi/swag -- go get -u gopkg.in/yaml.v2 -- go get -u github.com/go-openapi/jsonpointer -- go get -u github.com/go-openapi/jsonreference -script: -- go test -v -race -cover -coverprofile=coverage.txt -covermode=atomic ./... -after_success: -- bash <(curl -s https://codecov.io/bash) -notifications: - slack: - secure: QUWvCkBBK09GF7YtEvHHVt70JOkdlNBG0nIKu/5qc4/nW5HP8I2w0SEf/XR2je0eED1Qe3L/AfMCWwrEj+IUZc3l4v+ju8X8R3Lomhme0Eb0jd1MTMCuPcBT47YCj0M7RON7vXtbFfm1hFJ/jLe5+9FXz0hpXsR24PJc5ZIi/ogNwkaPqG4BmndzecpSh0vc2FJPZUD9LT0I09REY/vXR0oQAalLkW0asGD5taHZTUZq/kBpsNxaAFrLM23i4mUcf33M5fjLpvx5LRICrX/57XpBrDh2TooBU6Qj3CgoY0uPRYUmSNxbVx1czNzl2JtEpb5yjoxfVPQeg0BvQM00G8LJINISR+ohrjhkZmAqchDupAX+yFrxTtORa78CtnIL6z/aTNlgwwVD8kvL/1pFA/JWYmKDmz93mV/+6wubGzNSQCstzjkFA4/iZEKewKUoRIAi/fxyscP6L/rCpmY/4llZZvrnyTqVbt6URWpopUpH4rwYqreXAtJxJsfBJIeSmUIiDIOMGkCTvyTEW3fWGmGoqWtSHLoaWDyAIGb7azb+KvfpWtEcoPFWfSWU+LGee0A/YsUhBl7ADB9A0CJEuR8q4BPpKpfLwPKSiKSAXL7zDkyjExyhtgqbSl2jS+rKIHOZNL8JkCcTP2MKMVd563C5rC5FMKqu3S9m2b6380E= diff --git a/vendor/github.com/go-openapi/spec/CODE_OF_CONDUCT.md b/vendor/github.com/go-openapi/spec/CODE_OF_CONDUCT.md deleted file mode 100644 index 9322b065e..000000000 --- a/vendor/github.com/go-openapi/spec/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,74 +0,0 @@ -# Contributor Covenant Code of Conduct - -## Our Pledge - -In the interest of fostering an open and welcoming environment, we as -contributors and maintainers pledge to making participation in our project and -our community a harassment-free experience for everyone, regardless of age, body -size, disability, ethnicity, gender identity and expression, level of experience, -nationality, personal appearance, race, religion, or sexual identity and -orientation. - -## Our Standards - -Examples of behavior that contributes to creating a positive environment -include: - -* Using welcoming and inclusive language -* Being respectful of differing viewpoints and experiences -* Gracefully accepting constructive criticism -* Focusing on what is best for the community -* Showing empathy towards other community members - -Examples of unacceptable behavior by participants include: - -* The use of sexualized language or imagery and unwelcome sexual attention or -advances -* Trolling, insulting/derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or electronic - address, without explicit permission -* Other conduct which could reasonably be considered inappropriate in a - professional setting - -## Our Responsibilities - -Project maintainers are responsible for clarifying the standards of acceptable -behavior and are expected to take appropriate and fair corrective action in -response to any instances of unacceptable behavior. - -Project maintainers have the right and responsibility to remove, edit, or -reject comments, commits, code, wiki edits, issues, and other contributions -that are not aligned to this Code of Conduct, or to ban temporarily or -permanently any contributor for other behaviors that they deem inappropriate, -threatening, offensive, or harmful. - -## Scope - -This Code of Conduct applies both within project spaces and in public spaces -when an individual is representing the project or its community. Examples of -representing a project or community include using an official project e-mail -address, posting via an official social media account, or acting as an appointed -representative at an online or offline event. Representation of a project may be -further defined and clarified by project maintainers. - -## Enforcement - -Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported by contacting the project team at ivan+abuse@flanders.co.nz. All -complaints will be reviewed and investigated and will result in a response that -is deemed necessary and appropriate to the circumstances. The project team is -obligated to maintain confidentiality with regard to the reporter of an incident. -Further details of specific enforcement policies may be posted separately. - -Project maintainers who do not follow or enforce the Code of Conduct in good -faith may face temporary or permanent repercussions as determined by other -members of the project's leadership. - -## Attribution - -This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, -available at [http://contributor-covenant.org/version/1/4][version] - -[homepage]: http://contributor-covenant.org -[version]: http://contributor-covenant.org/version/1/4/ diff --git a/vendor/github.com/go-openapi/spec/README.md b/vendor/github.com/go-openapi/spec/README.md deleted file mode 100644 index 1d1622082..000000000 --- a/vendor/github.com/go-openapi/spec/README.md +++ /dev/null @@ -1,5 +0,0 @@ -# OAI object model [![Build Status](https://travis-ci.org/go-openapi/spec.svg?branch=master)](https://travis-ci.org/go-openapi/spec) [![codecov](https://codecov.io/gh/go-openapi/spec/branch/master/graph/badge.svg)](https://codecov.io/gh/go-openapi/spec) [![Slack Status](https://slackin.goswagger.io/badge.svg)](https://slackin.goswagger.io) - -[![license](http://img.shields.io/badge/license-Apache%20v2-orange.svg)](https://raw.githubusercontent.com/go-openapi/spec/master/LICENSE) [![GoDoc](https://godoc.org/github.com/go-openapi/spec?status.svg)](http://godoc.org/github.com/go-openapi/spec) - -The object model for OpenAPI specification documents diff --git a/vendor/github.com/go-openapi/spec/auth_test.go b/vendor/github.com/go-openapi/spec/auth_test.go deleted file mode 100644 index 5449fdec9..000000000 --- a/vendor/github.com/go-openapi/spec/auth_test.go +++ /dev/null @@ -1,128 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package spec - -import ( - "testing" -) - -func TestSerialization_AuthSerialization(t *testing.T) { - assertSerializeJSON(t, BasicAuth(), `{"type":"basic"}`) - - assertSerializeJSON(t, APIKeyAuth("api-key", "header"), `{"type":"apiKey","name":"api-key","in":"header"}`) - - assertSerializeJSON( - t, - OAuth2Implicit("http://foo.com/authorization"), - `{"type":"oauth2","flow":"implicit","authorizationUrl":"http://foo.com/authorization"}`) - - assertSerializeJSON( - t, - OAuth2Password("http://foo.com/token"), - `{"type":"oauth2","flow":"password","tokenUrl":"http://foo.com/token"}`) - - assertSerializeJSON(t, - OAuth2Application("http://foo.com/token"), - `{"type":"oauth2","flow":"application","tokenUrl":"http://foo.com/token"}`) - - assertSerializeJSON( - t, - OAuth2AccessToken("http://foo.com/authorization", "http://foo.com/token"), - `{"type":"oauth2","flow":"accessCode","authorizationUrl":"http://foo.com/authorization","tokenUrl":"http://foo.com/token"}`) - - auth1 := OAuth2Implicit("http://foo.com/authorization") - auth1.AddScope("email", "read your email") - assertSerializeJSON( - t, - auth1, - `{"type":"oauth2","flow":"implicit","authorizationUrl":"http://foo.com/authorization","scopes":{"email":"read your email"}}`) - - auth2 := OAuth2Password("http://foo.com/authorization") - auth2.AddScope("email", "read your email") - assertSerializeJSON( - t, - auth2, - `{"type":"oauth2","flow":"password","tokenUrl":"http://foo.com/authorization","scopes":{"email":"read your email"}}`) - - auth3 := OAuth2Application("http://foo.com/token") - auth3.AddScope("email", "read your email") - assertSerializeJSON( - t, - auth3, - `{"type":"oauth2","flow":"application","tokenUrl":"http://foo.com/token","scopes":{"email":"read your email"}}`) - - auth4 := OAuth2AccessToken("http://foo.com/authorization", "http://foo.com/token") - auth4.AddScope("email", "read your email") - assertSerializeJSON( - t, - auth4, - `{"type":"oauth2","flow":"accessCode","authorizationUrl":"http://foo.com/authorization","tokenUrl":"http://foo.com/token","scopes":{"email":"read your email"}}`) -} - -func TestSerialization_AuthDeserialization(t *testing.T) { - - assertParsesJSON(t, `{"type":"basic"}`, BasicAuth()) - - assertParsesJSON( - t, - `{"in":"header","name":"api-key","type":"apiKey"}`, - APIKeyAuth("api-key", "header")) - - assertParsesJSON( - t, - `{"authorizationUrl":"http://foo.com/authorization","flow":"implicit","type":"oauth2"}`, - OAuth2Implicit("http://foo.com/authorization")) - - assertParsesJSON( - t, - `{"flow":"password","tokenUrl":"http://foo.com/token","type":"oauth2"}`, - OAuth2Password("http://foo.com/token")) - - assertParsesJSON( - t, - `{"flow":"application","tokenUrl":"http://foo.com/token","type":"oauth2"}`, - OAuth2Application("http://foo.com/token")) - - assertParsesJSON( - t, - `{"authorizationUrl":"http://foo.com/authorization","flow":"accessCode","tokenUrl":"http://foo.com/token","type":"oauth2"}`, - OAuth2AccessToken("http://foo.com/authorization", "http://foo.com/token")) - - auth1 := OAuth2Implicit("http://foo.com/authorization") - auth1.AddScope("email", "read your email") - assertParsesJSON(t, - `{"authorizationUrl":"http://foo.com/authorization","flow":"implicit","scopes":{"email":"read your email"},"type":"oauth2"}`, - auth1) - - auth2 := OAuth2Password("http://foo.com/token") - auth2.AddScope("email", "read your email") - assertParsesJSON(t, - `{"flow":"password","scopes":{"email":"read your email"},"tokenUrl":"http://foo.com/token","type":"oauth2"}`, - auth2) - - auth3 := OAuth2Application("http://foo.com/token") - auth3.AddScope("email", "read your email") - assertParsesJSON(t, - `{"flow":"application","scopes":{"email":"read your email"},"tokenUrl":"http://foo.com/token","type":"oauth2"}`, - auth3) - - auth4 := OAuth2AccessToken("http://foo.com/authorization", "http://foo.com/token") - auth4.AddScope("email", "read your email") - assertParsesJSON( - t, - `{"authorizationUrl":"http://foo.com/authorization","flow":"accessCode","scopes":{"email":"read your email"},"tokenUrl":"http://foo.com/token","type":"oauth2"}`, - auth4) - -} diff --git a/vendor/github.com/go-openapi/spec/contact_info_test.go b/vendor/github.com/go-openapi/spec/contact_info_test.go deleted file mode 100644 index 5e644d0f0..000000000 --- a/vendor/github.com/go-openapi/spec/contact_info_test.go +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package spec - -import ( - "testing" -) - -var contactInfoJSON = `{"name":"wordnik api team","url":"http://developer.wordnik.com","email":"some@mailayada.dkdkd"}` -var contactInfoYAML = `name: wordnik api team -url: http://developer.wordnik.com -email: some@mailayada.dkdkd -` -var contactInfo = ContactInfo{ - Name: "wordnik api team", - URL: "http://developer.wordnik.com", - Email: "some@mailayada.dkdkd", -} - -func TestIntegrationContactInfo(t *testing.T) { - assertSerializeJSON(t, contactInfo, contactInfoJSON) - assertSerializeYAML(t, contactInfo, contactInfoYAML) - assertParsesJSON(t, contactInfoJSON, contactInfo) - assertParsesYAML(t, contactInfoYAML, contactInfo) -} diff --git a/vendor/github.com/go-openapi/spec/expander_test.go b/vendor/github.com/go-openapi/spec/expander_test.go deleted file mode 100644 index 09c8573cf..000000000 --- a/vendor/github.com/go-openapi/spec/expander_test.go +++ /dev/null @@ -1,1162 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package spec - -import ( - "encoding/json" - "io/ioutil" - "net/http" - "net/http/httptest" - "testing" - - "github.com/go-openapi/jsonpointer" - "github.com/go-openapi/swag" - "github.com/stretchr/testify/assert" -) - -func jsonDoc(path string) (json.RawMessage, error) { - data, err := swag.LoadFromFileOrHTTP(path) - if err != nil { - return nil, err - } - return json.RawMessage(data), nil -} - -func TestExpandsKnownRef(t *testing.T) { - schema := RefProperty("http://json-schema.org/draft-04/schema#") - if assert.NoError(t, ExpandSchema(schema, nil, nil)) { - assert.Equal(t, "Core schema meta-schema", schema.Description) - } -} - -func TestExpandResponseSchema(t *testing.T) { - fp := "./fixtures/local_expansion/spec.json" - b, err := jsonDoc(fp) - if assert.NoError(t, err) { - var spec Swagger - if err := json.Unmarshal(b, &spec); assert.NoError(t, err) { - err := ExpandSpec(&spec, &ExpandOptions{RelativeBase: fp}) - if assert.NoError(t, err) { - sch := spec.Paths.Paths["/item"].Get.Responses.StatusCodeResponses[200].Schema - if assert.NotNil(t, sch) { - assert.Empty(t, sch.Ref.String()) - assert.Contains(t, sch.Type, "object") - assert.Len(t, sch.Properties, 2) - } - } - } - } -} - -func TestSpecExpansion(t *testing.T) { - spec := new(Swagger) - // resolver, err := defaultSchemaLoader(spec, nil, nil) - // assert.NoError(t, err) - - err := ExpandSpec(spec, nil) - assert.NoError(t, err) - - specDoc, err := jsonDoc("fixtures/expansion/all-the-things.json") - assert.NoError(t, err) - - spec = new(Swagger) - err = json.Unmarshal(specDoc, spec) - assert.NoError(t, err) - - pet := spec.Definitions["pet"] - errorModel := spec.Definitions["errorModel"] - petResponse := spec.Responses["petResponse"] - petResponse.Schema = &pet - stringResponse := spec.Responses["stringResponse"] - tagParam := spec.Parameters["tag"] - idParam := spec.Parameters["idParam"] - - err = ExpandSpec(spec, nil) - assert.NoError(t, err) - - assert.Equal(t, tagParam, spec.Parameters["query"]) - assert.Equal(t, petResponse, spec.Responses["petResponse"]) - assert.Equal(t, petResponse, spec.Responses["anotherPet"]) - assert.Equal(t, pet, *spec.Responses["petResponse"].Schema) - assert.Equal(t, stringResponse, *spec.Paths.Paths["/"].Get.Responses.Default) - assert.Equal(t, petResponse, spec.Paths.Paths["/"].Get.Responses.StatusCodeResponses[200]) - assert.Equal(t, pet, *spec.Paths.Paths["/pets"].Get.Responses.StatusCodeResponses[200].Schema.Items.Schema) - assert.Equal(t, errorModel, *spec.Paths.Paths["/pets"].Get.Responses.Default.Schema) - assert.Equal(t, pet, spec.Definitions["petInput"].AllOf[0]) - assert.Equal(t, spec.Definitions["petInput"], *spec.Paths.Paths["/pets"].Post.Parameters[0].Schema) - assert.Equal(t, petResponse, spec.Paths.Paths["/pets"].Post.Responses.StatusCodeResponses[200]) - assert.Equal(t, errorModel, *spec.Paths.Paths["/pets"].Post.Responses.Default.Schema) - pi := spec.Paths.Paths["/pets/{id}"] - assert.Equal(t, idParam, pi.Get.Parameters[0]) - assert.Equal(t, petResponse, pi.Get.Responses.StatusCodeResponses[200]) - assert.Equal(t, errorModel, *pi.Get.Responses.Default.Schema) - assert.Equal(t, idParam, pi.Delete.Parameters[0]) - assert.Equal(t, errorModel, *pi.Delete.Responses.Default.Schema) -} - -func TestResponseExpansion(t *testing.T) { - specDoc, err := jsonDoc("fixtures/expansion/all-the-things.json") - assert.NoError(t, err) - - spec := new(Swagger) - err = json.Unmarshal(specDoc, spec) - assert.NoError(t, err) - - resolver, err := defaultSchemaLoader(spec, nil, nil, nil) - assert.NoError(t, err) - - resp := spec.Responses["anotherPet"] - expected := spec.Responses["petResponse"] - - err = expandResponse(&resp, resolver) - assert.NoError(t, err) - assert.Equal(t, expected, resp) - - resp2 := spec.Paths.Paths["/"].Get.Responses.Default - expected = spec.Responses["stringResponse"] - - err = expandResponse(resp2, resolver) - assert.NoError(t, err) - assert.Equal(t, expected, *resp2) - - resp = spec.Paths.Paths["/"].Get.Responses.StatusCodeResponses[200] - expected = spec.Responses["petResponse"] - - err = expandResponse(&resp, resolver) - assert.NoError(t, err) - // assert.Equal(t, expected, resp) -} - -func TestIssue3(t *testing.T) { - spec := new(Swagger) - specDoc, err := jsonDoc("fixtures/expansion/overflow.json") - assert.NoError(t, err) - - err = json.Unmarshal(specDoc, spec) - assert.NoError(t, err) - - assert.NotPanics(t, func() { - err = ExpandSpec(spec, nil) - assert.NoError(t, err) - }, "Calling expand spec with circular refs, should not panic!") -} - -func TestParameterExpansion(t *testing.T) { - paramDoc, err := jsonDoc("fixtures/expansion/params.json") - assert.NoError(t, err) - - spec := new(Swagger) - err = json.Unmarshal(paramDoc, spec) - assert.NoError(t, err) - - resolver, err := defaultSchemaLoader(spec, nil, nil, nil) - assert.NoError(t, err) - - param := spec.Parameters["query"] - expected := spec.Parameters["tag"] - - err = expandParameter(¶m, resolver) - assert.NoError(t, err) - assert.Equal(t, expected, param) - - param = spec.Paths.Paths["/cars/{id}"].Parameters[0] - expected = spec.Parameters["id"] - - err = expandParameter(¶m, resolver) - assert.NoError(t, err) - assert.Equal(t, expected, param) -} - -func TestCircularRefsExpansion(t *testing.T) { - carsDoc, err := jsonDoc("fixtures/expansion/circularRefs.json") - assert.NoError(t, err) - - spec := new(Swagger) - err = json.Unmarshal(carsDoc, spec) - assert.NoError(t, err) - - resolver, err := defaultSchemaLoader(spec, nil, nil, nil) - assert.NoError(t, err) - schema := spec.Definitions["car"] - - assert.NotPanics(t, func() { - _, err = expandSchema(schema, []string{"#/definitions/car"}, resolver) - assert.NoError(t, err) - }, "Calling expand schema with circular refs, should not panic!") -} - -func TestContinueOnErrorExpansion(t *testing.T) { - missingRefDoc, err := jsonDoc("fixtures/expansion/missingRef.json") - assert.NoError(t, err) - - testCase := struct { - Input *Swagger `json:"input"` - Expected *Swagger `json:"expected"` - }{} - err = json.Unmarshal(missingRefDoc, &testCase) - assert.NoError(t, err) - - opts := &ExpandOptions{ - ContinueOnError: true, - } - err = ExpandSpec(testCase.Input, opts) - assert.NoError(t, err) - assert.Equal(t, testCase.Input, testCase.Expected, "Should continue expanding spec when a definition can't be found.") - - doc, err := jsonDoc("fixtures/expansion/missingItemRef.json") - spec := new(Swagger) - err = json.Unmarshal(doc, spec) - assert.NoError(t, err) - - assert.NotPanics(t, func() { - err = ExpandSpec(spec, opts) - assert.NoError(t, err) - }, "Array of missing refs should not cause a panic, and continue to expand spec.") -} - -func TestIssue415(t *testing.T) { - doc, err := jsonDoc("fixtures/expansion/clickmeter.json") - assert.NoError(t, err) - - spec := new(Swagger) - err = json.Unmarshal(doc, spec) - assert.NoError(t, err) - - assert.NotPanics(t, func() { - err = ExpandSpec(spec, nil) - assert.NoError(t, err) - }, "Calling expand spec with response schemas that have circular refs, should not panic!") -} - -func TestCircularSpecExpansion(t *testing.T) { - doc, err := jsonDoc("fixtures/expansion/circularSpec.json") - assert.NoError(t, err) - - spec := new(Swagger) - err = json.Unmarshal(doc, spec) - assert.NoError(t, err) - - assert.NotPanics(t, func() { - err = ExpandSpec(spec, nil) - assert.NoError(t, err) - }, "Calling expand spec with circular refs, should not panic!") -} - -func TestItemsExpansion(t *testing.T) { - carsDoc, err := jsonDoc("fixtures/expansion/schemas2.json") - assert.NoError(t, err) - - spec := new(Swagger) - err = json.Unmarshal(carsDoc, spec) - assert.NoError(t, err) - - resolver, err := defaultSchemaLoader(spec, nil, nil, nil) - assert.NoError(t, err) - - schema := spec.Definitions["car"] - oldBrand := schema.Properties["brand"] - assert.NotEmpty(t, oldBrand.Items.Schema.Ref.String()) - assert.NotEqual(t, spec.Definitions["brand"], oldBrand) - - _, err = expandSchema(schema, []string{"#/definitions/car"}, resolver) - assert.NoError(t, err) - - newBrand := schema.Properties["brand"] - assert.Empty(t, newBrand.Items.Schema.Ref.String()) - assert.Equal(t, spec.Definitions["brand"], *newBrand.Items.Schema) - - schema = spec.Definitions["truck"] - assert.NotEmpty(t, schema.Items.Schema.Ref.String()) - - s, err := expandSchema(schema, []string{"#/definitions/truck"}, resolver) - schema = *s - assert.NoError(t, err) - assert.Empty(t, schema.Items.Schema.Ref.String()) - assert.Equal(t, spec.Definitions["car"], *schema.Items.Schema) - - sch := new(Schema) - _, err = expandSchema(*sch, []string{""}, resolver) - assert.NoError(t, err) - - schema = spec.Definitions["batch"] - s, err = expandSchema(schema, []string{"#/definitions/batch"}, resolver) - schema = *s - assert.NoError(t, err) - assert.Empty(t, schema.Items.Schema.Items.Schema.Ref.String()) - assert.Equal(t, *schema.Items.Schema.Items.Schema, spec.Definitions["brand"]) - - schema = spec.Definitions["batch2"] - s, err = expandSchema(schema, []string{"#/definitions/batch2"}, resolver) - schema = *s - assert.NoError(t, err) - assert.Empty(t, schema.Items.Schemas[0].Items.Schema.Ref.String()) - assert.Empty(t, schema.Items.Schemas[1].Items.Schema.Ref.String()) - assert.Equal(t, *schema.Items.Schemas[0].Items.Schema, spec.Definitions["brand"]) - assert.Equal(t, *schema.Items.Schemas[1].Items.Schema, spec.Definitions["tag"]) - - schema = spec.Definitions["allofBoth"] - s, err = expandSchema(schema, []string{"#/definitions/allofBoth"}, resolver) - schema = *s - assert.NoError(t, err) - assert.Empty(t, schema.AllOf[0].Items.Schema.Ref.String()) - assert.Empty(t, schema.AllOf[1].Items.Schema.Ref.String()) - assert.Equal(t, *schema.AllOf[0].Items.Schema, spec.Definitions["brand"]) - assert.Equal(t, *schema.AllOf[1].Items.Schema, spec.Definitions["tag"]) - - schema = spec.Definitions["anyofBoth"] - s, err = expandSchema(schema, []string{"#/definitions/anyofBoth"}, resolver) - schema = *s - assert.NoError(t, err) - assert.Empty(t, schema.AnyOf[0].Items.Schema.Ref.String()) - assert.Empty(t, schema.AnyOf[1].Items.Schema.Ref.String()) - assert.Equal(t, *schema.AnyOf[0].Items.Schema, spec.Definitions["brand"]) - assert.Equal(t, *schema.AnyOf[1].Items.Schema, spec.Definitions["tag"]) - - schema = spec.Definitions["oneofBoth"] - s, err = expandSchema(schema, []string{"#/definitions/oneofBoth"}, resolver) - schema = *s - assert.NoError(t, err) - assert.Empty(t, schema.OneOf[0].Items.Schema.Ref.String()) - assert.Empty(t, schema.OneOf[1].Items.Schema.Ref.String()) - assert.Equal(t, *schema.OneOf[0].Items.Schema, spec.Definitions["brand"]) - assert.Equal(t, *schema.OneOf[1].Items.Schema, spec.Definitions["tag"]) - - schema = spec.Definitions["notSomething"] - s, err = expandSchema(schema, []string{"#/definitions/notSomething"}, resolver) - schema = *s - assert.NoError(t, err) - assert.Empty(t, schema.Not.Items.Schema.Ref.String()) - assert.Equal(t, *schema.Not.Items.Schema, spec.Definitions["tag"]) - - schema = spec.Definitions["withAdditional"] - s, err = expandSchema(schema, []string{"#/definitions/withAdditional"}, resolver) - schema = *s - assert.NoError(t, err) - assert.Empty(t, schema.AdditionalProperties.Schema.Items.Schema.Ref.String()) - assert.Equal(t, *schema.AdditionalProperties.Schema.Items.Schema, spec.Definitions["tag"]) - - schema = spec.Definitions["withAdditionalItems"] - s, err = expandSchema(schema, []string{"#/definitions/withAdditionalItems"}, resolver) - schema = *s - assert.NoError(t, err) - assert.Empty(t, schema.AdditionalItems.Schema.Items.Schema.Ref.String()) - assert.Equal(t, *schema.AdditionalItems.Schema.Items.Schema, spec.Definitions["tag"]) - - schema = spec.Definitions["withPattern"] - s, err = expandSchema(schema, []string{"#/definitions/withPattern"}, resolver) - schema = *s - assert.NoError(t, err) - prop := schema.PatternProperties["^x-ab"] - assert.Empty(t, prop.Items.Schema.Ref.String()) - assert.Equal(t, *prop.Items.Schema, spec.Definitions["tag"]) - - schema = spec.Definitions["deps"] - s, err = expandSchema(schema, []string{"#/definitions/deps"}, resolver) - schema = *s - assert.NoError(t, err) - prop2 := schema.Dependencies["something"] - assert.Empty(t, prop2.Schema.Items.Schema.Ref.String()) - assert.Equal(t, *prop2.Schema.Items.Schema, spec.Definitions["tag"]) - - schema = spec.Definitions["defined"] - s, err = expandSchema(schema, []string{"#/definitions/defined"}, resolver) - schema = *s - assert.NoError(t, err) - prop = schema.Definitions["something"] - assert.Empty(t, prop.Items.Schema.Ref.String()) - assert.Equal(t, *prop.Items.Schema, spec.Definitions["tag"]) -} - -func TestSchemaExpansion(t *testing.T) { - carsDoc, err := jsonDoc("fixtures/expansion/schemas1.json") - assert.NoError(t, err) - - spec := new(Swagger) - err = json.Unmarshal(carsDoc, spec) - assert.NoError(t, err) - - resolver, err := defaultSchemaLoader(spec, nil, nil, nil) - assert.NoError(t, err) - - schema := spec.Definitions["car"] - oldBrand := schema.Properties["brand"] - assert.NotEmpty(t, oldBrand.Ref.String()) - assert.NotEqual(t, spec.Definitions["brand"], oldBrand) - - s, err := expandSchema(schema, []string{"#/definitions/car"}, resolver) - schema = *s - assert.NoError(t, err) - - newBrand := schema.Properties["brand"] - assert.Empty(t, newBrand.Ref.String()) - assert.Equal(t, spec.Definitions["brand"], newBrand) - - schema = spec.Definitions["truck"] - assert.NotEmpty(t, schema.Ref.String()) - - s, err = expandSchema(schema, []string{"#/definitions/truck"}, resolver) - schema = *s - assert.NoError(t, err) - assert.Empty(t, schema.Ref.String()) - assert.Equal(t, spec.Definitions["car"], schema) - - sch := new(Schema) - _, err = expandSchema(*sch, []string{""}, resolver) - assert.NoError(t, err) - - schema = spec.Definitions["batch"] - s, err = expandSchema(schema, []string{"#/definitions/batch"}, resolver) - schema = *s - assert.NoError(t, err) - assert.Empty(t, schema.Items.Schema.Ref.String()) - assert.Equal(t, *schema.Items.Schema, spec.Definitions["brand"]) - - schema = spec.Definitions["batch2"] - s, err = expandSchema(schema, []string{"#/definitions/batch2"}, resolver) - schema = *s - assert.NoError(t, err) - assert.Empty(t, schema.Items.Schemas[0].Ref.String()) - assert.Empty(t, schema.Items.Schemas[1].Ref.String()) - assert.Equal(t, schema.Items.Schemas[0], spec.Definitions["brand"]) - assert.Equal(t, schema.Items.Schemas[1], spec.Definitions["tag"]) - - schema = spec.Definitions["allofBoth"] - s, err = expandSchema(schema, []string{"#/definitions/allofBoth"}, resolver) - schema = *s - assert.NoError(t, err) - assert.Empty(t, schema.AllOf[0].Ref.String()) - assert.Empty(t, schema.AllOf[1].Ref.String()) - assert.Equal(t, schema.AllOf[0], spec.Definitions["brand"]) - assert.Equal(t, schema.AllOf[1], spec.Definitions["tag"]) - - schema = spec.Definitions["anyofBoth"] - s, err = expandSchema(schema, []string{"#/definitions/anyofBoth"}, resolver) - schema = *s - assert.NoError(t, err) - assert.Empty(t, schema.AnyOf[0].Ref.String()) - assert.Empty(t, schema.AnyOf[1].Ref.String()) - assert.Equal(t, schema.AnyOf[0], spec.Definitions["brand"]) - assert.Equal(t, schema.AnyOf[1], spec.Definitions["tag"]) - - schema = spec.Definitions["oneofBoth"] - s, err = expandSchema(schema, []string{"#/definitions/oneofBoth"}, resolver) - schema = *s - assert.NoError(t, err) - assert.Empty(t, schema.OneOf[0].Ref.String()) - assert.Empty(t, schema.OneOf[1].Ref.String()) - assert.Equal(t, schema.OneOf[0], spec.Definitions["brand"]) - assert.Equal(t, schema.OneOf[1], spec.Definitions["tag"]) - - schema = spec.Definitions["notSomething"] - s, err = expandSchema(schema, []string{"#/definitions/notSomething"}, resolver) - schema = *s - assert.NoError(t, err) - assert.Empty(t, schema.Not.Ref.String()) - assert.Equal(t, *schema.Not, spec.Definitions["tag"]) - - schema = spec.Definitions["withAdditional"] - s, err = expandSchema(schema, []string{"#/definitions/withAdditional"}, resolver) - schema = *s - assert.NoError(t, err) - assert.Empty(t, schema.AdditionalProperties.Schema.Ref.String()) - assert.Equal(t, *schema.AdditionalProperties.Schema, spec.Definitions["tag"]) - - schema = spec.Definitions["withAdditionalItems"] - s, err = expandSchema(schema, []string{"#/definitions/withAdditionalItems"}, resolver) - schema = *s - assert.NoError(t, err) - assert.Empty(t, schema.AdditionalItems.Schema.Ref.String()) - assert.Equal(t, *schema.AdditionalItems.Schema, spec.Definitions["tag"]) - - schema = spec.Definitions["withPattern"] - s, err = expandSchema(schema, []string{"#/definitions/withPattern"}, resolver) - schema = *s - assert.NoError(t, err) - prop := schema.PatternProperties["^x-ab"] - assert.Empty(t, prop.Ref.String()) - assert.Equal(t, prop, spec.Definitions["tag"]) - - schema = spec.Definitions["deps"] - s, err = expandSchema(schema, []string{"#/definitions/deps"}, resolver) - schema = *s - assert.NoError(t, err) - prop2 := schema.Dependencies["something"] - assert.Empty(t, prop2.Schema.Ref.String()) - assert.Equal(t, *prop2.Schema, spec.Definitions["tag"]) - - schema = spec.Definitions["defined"] - s, err = expandSchema(schema, []string{"#/definitions/defined"}, resolver) - schema = *s - assert.NoError(t, err) - prop = schema.Definitions["something"] - assert.Empty(t, prop.Ref.String()) - assert.Equal(t, prop, spec.Definitions["tag"]) - -} - -func TestDefaultResolutionCache(t *testing.T) { - - cache := initResolutionCache() - - sch, ok := cache.Get("not there") - assert.False(t, ok) - assert.Nil(t, sch) - - sch, ok = cache.Get("http://swagger.io/v2/schema.json") - assert.True(t, ok) - assert.Equal(t, swaggerSchema, sch) - - sch, ok = cache.Get("http://json-schema.org/draft-04/schema") - assert.True(t, ok) - assert.Equal(t, jsonSchema, sch) - - cache.Set("something", "here") - sch, ok = cache.Get("something") - assert.True(t, ok) - assert.Equal(t, "here", sch) -} - -func resolutionContextServer() *httptest.Server { - var servedAt string - server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { - // fmt.Println("got a request for", req.URL.String()) - if req.URL.Path == "/resolution.json" { - - b, _ := ioutil.ReadFile("fixtures/specs/resolution.json") - var ctnt map[string]interface{} - json.Unmarshal(b, &ctnt) - ctnt["id"] = servedAt - - rw.Header().Set("Content-Type", "application/json") - rw.WriteHeader(200) - bb, _ := json.Marshal(ctnt) - rw.Write(bb) - return - } - if req.URL.Path == "/resolution2.json" { - b, _ := ioutil.ReadFile("fixtures/specs/resolution2.json") - var ctnt map[string]interface{} - json.Unmarshal(b, &ctnt) - ctnt["id"] = servedAt - - rw.Header().Set("Content-Type", "application/json") - rw.WriteHeader(200) - bb, _ := json.Marshal(ctnt) - rw.Write(bb) - return - } - - if req.URL.Path == "/boolProp.json" { - rw.Header().Set("Content-Type", "application/json") - rw.WriteHeader(200) - b, _ := json.Marshal(map[string]interface{}{ - "type": "boolean", - }) - _, _ = rw.Write(b) - return - } - - if req.URL.Path == "/deeper/stringProp.json" { - rw.Header().Set("Content-Type", "application/json") - rw.WriteHeader(200) - b, _ := json.Marshal(map[string]interface{}{ - "type": "string", - }) - rw.Write(b) - return - } - - if req.URL.Path == "/deeper/arrayProp.json" { - rw.Header().Set("Content-Type", "application/json") - rw.WriteHeader(200) - b, _ := json.Marshal(map[string]interface{}{ - "type": "array", - "items": map[string]interface{}{ - "type": "file", - }, - }) - rw.Write(b) - return - } - - rw.WriteHeader(http.StatusNotFound) - })) - servedAt = server.URL - return server -} - -func TestResolveRemoteRef_RootSame(t *testing.T) { - specs := "fixtures/specs" - fileserver := http.FileServer(http.Dir(specs)) - server := httptest.NewServer(fileserver) - defer server.Close() - - rootDoc := new(Swagger) - b, err := ioutil.ReadFile("fixtures/specs/refed.json") - if assert.NoError(t, err) && assert.NoError(t, json.Unmarshal(b, rootDoc)) { - var result_0 Swagger - ref_0, _ := NewRef(server.URL + "/refed.json#") - resolver_0, _ := defaultSchemaLoader(rootDoc, nil, nil, nil) - if assert.NoError(t, resolver_0.Resolve(&ref_0, &result_0)) { - assertSpecs(t, result_0, *rootDoc) - } - - var result_1 Swagger - ref_1, _ := NewRef("./refed.json") - resolver_1, _ := defaultSchemaLoader(rootDoc, nil, &ExpandOptions{ - RelativeBase: (specs), - }, nil) - if assert.NoError(t, resolver_1.Resolve(&ref_1, &result_1)) { - assertSpecs(t, result_1, *rootDoc) - } - } -} - -func TestResolveRemoteRef_FromFragment(t *testing.T) { - specs := "fixtures/specs" - fileserver := http.FileServer(http.Dir(specs)) - server := httptest.NewServer(fileserver) - defer server.Close() - - rootDoc := new(Swagger) - b, err := ioutil.ReadFile("fixtures/specs/refed.json") - if assert.NoError(t, err) && assert.NoError(t, json.Unmarshal(b, rootDoc)) { - var tgt Schema - ref, err := NewRef(server.URL + "/refed.json#/definitions/pet") - if assert.NoError(t, err) { - resolver := &schemaLoader{root: rootDoc, cache: initResolutionCache(), loadDoc: jsonDoc} - if assert.NoError(t, resolver.Resolve(&ref, &tgt)) { - assert.Equal(t, []string{"id", "name"}, tgt.Required) - } - } - } -} - -func TestResolveRemoteRef_FromInvalidFragment(t *testing.T) { - specs := "fixtures/specs" - fileserver := http.FileServer(http.Dir(specs)) - server := httptest.NewServer(fileserver) - defer server.Close() - - rootDoc := new(Swagger) - b, err := ioutil.ReadFile("fixtures/specs/refed.json") - if assert.NoError(t, err) && assert.NoError(t, json.Unmarshal(b, rootDoc)) { - var tgt Schema - ref, err := NewRef(server.URL + "/refed.json#/definitions/NotThere") - if assert.NoError(t, err) { - resolver, _ := defaultSchemaLoader(rootDoc, nil, nil, nil) - assert.Error(t, resolver.Resolve(&ref, &tgt)) - } - } -} - -func TestResolveRemoteRef_WithResolutionContext(t *testing.T) { - server := resolutionContextServer() - defer server.Close() - - rootDoc := new(Swagger) - b, err := ioutil.ReadFile("fixtures/specs/refed.json") - if assert.NoError(t, err) && assert.NoError(t, json.Unmarshal(b, rootDoc)) { - var tgt Schema - ref, err := NewRef(server.URL + "/resolution.json#/definitions/bool") - if assert.NoError(t, err) { - resolver, _ := defaultSchemaLoader(rootDoc, nil, nil, nil) - if assert.NoError(t, resolver.Resolve(&ref, &tgt)) { - assert.Equal(t, StringOrArray([]string{"boolean"}), tgt.Type) - } - } - } -} - -func TestResolveRemoteRef_WithNestedResolutionContext(t *testing.T) { - server := resolutionContextServer() - defer server.Close() - - rootDoc := new(Swagger) - b, err := ioutil.ReadFile("fixtures/specs/refed.json") - if assert.NoError(t, err) && assert.NoError(t, json.Unmarshal(b, rootDoc)) { - var tgt Schema - ref, err := NewRef(server.URL + "/resolution.json#/items/items") - if assert.NoError(t, err) { - resolver, _ := defaultSchemaLoader(rootDoc, nil, nil, nil) - if assert.NoError(t, resolver.Resolve(&ref, &tgt)) { - assert.Equal(t, StringOrArray([]string{"string"}), tgt.Type) - } - } - } -} - -func TestResolveRemoteRef_WithNestedResolutionContextWithFragment(t *testing.T) { - server := resolutionContextServer() - defer server.Close() - - rootDoc := new(Swagger) - b, err := ioutil.ReadFile("fixtures/specs/refed.json") - if assert.NoError(t, err) && assert.NoError(t, json.Unmarshal(b, rootDoc)) { - var tgt Schema - ref, err := NewRef(server.URL + "/resolution2.json#/items/items") - if assert.NoError(t, err) { - resolver, _ := defaultSchemaLoader(rootDoc, nil, nil, nil) - if assert.NoError(t, resolver.Resolve(&ref, &tgt)) { - assert.Equal(t, StringOrArray([]string{"file"}), tgt.Type) - } - } - } -} - -func TestResolveRemoteRef_ToParameter(t *testing.T) { - specs := "fixtures/specs" - fileserver := http.FileServer(http.Dir(specs)) - server := httptest.NewServer(fileserver) - defer server.Close() - - rootDoc := new(Swagger) - b, err := ioutil.ReadFile("fixtures/specs/refed.json") - if assert.NoError(t, err) && assert.NoError(t, json.Unmarshal(b, rootDoc)) { - var tgt Parameter - ref, err := NewRef(server.URL + "/refed.json#/parameters/idParam") - if assert.NoError(t, err) { - - resolver, _ := defaultSchemaLoader(rootDoc, nil, nil, nil) - if assert.NoError(t, resolver.Resolve(&ref, &tgt)) { - assert.Equal(t, "id", tgt.Name) - assert.Equal(t, "path", tgt.In) - assert.Equal(t, "ID of pet to fetch", tgt.Description) - assert.True(t, tgt.Required) - assert.Equal(t, "integer", tgt.Type) - assert.Equal(t, "int64", tgt.Format) - } - } - } -} - -func TestResolveRemoteRef_ToPathItem(t *testing.T) { - specs := "fixtures/specs" - fileserver := http.FileServer(http.Dir(specs)) - server := httptest.NewServer(fileserver) - defer server.Close() - - rootDoc := new(Swagger) - b, err := ioutil.ReadFile("fixtures/specs/refed.json") - if assert.NoError(t, err) && assert.NoError(t, json.Unmarshal(b, rootDoc)) { - var tgt PathItem - ref, err := NewRef(server.URL + "/refed.json#/paths/" + jsonpointer.Escape("/pets/{id}")) - if assert.NoError(t, err) { - - resolver, _ := defaultSchemaLoader(rootDoc, nil, nil, nil) - if assert.NoError(t, resolver.Resolve(&ref, &tgt)) { - assert.Equal(t, rootDoc.Paths.Paths["/pets/{id}"].Get, tgt.Get) - } - } - } -} - -func TestResolveRemoteRef_ToResponse(t *testing.T) { - specs := "fixtures/specs" - fileserver := http.FileServer(http.Dir(specs)) - server := httptest.NewServer(fileserver) - defer server.Close() - - rootDoc := new(Swagger) - b, err := ioutil.ReadFile("fixtures/specs/refed.json") - if assert.NoError(t, err) && assert.NoError(t, json.Unmarshal(b, rootDoc)) { - var tgt Response - ref, err := NewRef(server.URL + "/refed.json#/responses/petResponse") - if assert.NoError(t, err) { - - resolver, _ := defaultSchemaLoader(rootDoc, nil, nil, nil) - if assert.NoError(t, resolver.Resolve(&ref, &tgt)) { - assert.Equal(t, rootDoc.Responses["petResponse"], tgt) - } - } - } -} - -func TestResolveLocalRef_SameRoot(t *testing.T) { - rootDoc := new(Swagger) - json.Unmarshal(PetStoreJSONMessage, rootDoc) - - result := new(Swagger) - ref, _ := NewRef("#") - resolver, _ := defaultSchemaLoader(rootDoc, nil, nil, nil) - err := resolver.Resolve(&ref, result) - if assert.NoError(t, err) { - assert.Equal(t, rootDoc, result) - } -} - -func TestResolveLocalRef_FromFragment(t *testing.T) { - rootDoc := new(Swagger) - json.Unmarshal(PetStoreJSONMessage, rootDoc) - - var tgt Schema - ref, err := NewRef("#/definitions/Category") - if assert.NoError(t, err) { - resolver, _ := defaultSchemaLoader(rootDoc, nil, nil, nil) - err := resolver.Resolve(&ref, &tgt) - if assert.NoError(t, err) { - assert.Equal(t, "Category", tgt.ID) - } - } -} - -func TestResolveLocalRef_FromInvalidFragment(t *testing.T) { - rootDoc := new(Swagger) - json.Unmarshal(PetStoreJSONMessage, rootDoc) - - var tgt Schema - ref, err := NewRef("#/definitions/NotThere") - if assert.NoError(t, err) { - resolver, _ := defaultSchemaLoader(rootDoc, nil, nil, nil) - err := resolver.Resolve(&ref, &tgt) - assert.Error(t, err) - } -} - -func TestResolveLocalRef_Parameter(t *testing.T) { - rootDoc := new(Swagger) - b, err := ioutil.ReadFile("fixtures/specs/refed.json") - if assert.NoError(t, err) && assert.NoError(t, json.Unmarshal(b, rootDoc)) { - var tgt Parameter - ref, err := NewRef("#/parameters/idParam") - if assert.NoError(t, err) { - resolver, _ := defaultSchemaLoader(rootDoc, nil, nil, nil) - if assert.NoError(t, resolver.Resolve(&ref, &tgt)) { - assert.Equal(t, "id", tgt.Name) - assert.Equal(t, "path", tgt.In) - assert.Equal(t, "ID of pet to fetch", tgt.Description) - assert.True(t, tgt.Required) - assert.Equal(t, "integer", tgt.Type) - assert.Equal(t, "int64", tgt.Format) - } - } - } -} - -func TestResolveLocalRef_PathItem(t *testing.T) { - rootDoc := new(Swagger) - b, err := ioutil.ReadFile("fixtures/specs/refed.json") - if assert.NoError(t, err) && assert.NoError(t, json.Unmarshal(b, rootDoc)) { - var tgt PathItem - ref, err := NewRef("#/paths/" + jsonpointer.Escape("/pets/{id}")) - if assert.NoError(t, err) { - resolver, _ := defaultSchemaLoader(rootDoc, nil, nil, nil) - if assert.NoError(t, resolver.Resolve(&ref, &tgt)) { - assert.Equal(t, rootDoc.Paths.Paths["/pets/{id}"].Get, tgt.Get) - } - } - } -} - -func TestResolveLocalRef_Response(t *testing.T) { - rootDoc := new(Swagger) - b, err := ioutil.ReadFile("fixtures/specs/refed.json") - if assert.NoError(t, err) && assert.NoError(t, json.Unmarshal(b, rootDoc)) { - var tgt Response - ref, err := NewRef("#/responses/petResponse") - if assert.NoError(t, err) { - resolver, _ := defaultSchemaLoader(rootDoc, nil, nil, nil) - if assert.NoError(t, resolver.Resolve(&ref, &tgt)) { - assert.Equal(t, rootDoc.Responses["petResponse"], tgt) - } - } - } -} - -// PetStoreJSONMessage json raw message for Petstore20 -var PetStoreJSONMessage = json.RawMessage([]byte(PetStore20)) - -// PetStore20 json doc for swagger 2.0 pet store -const PetStore20 = `{ - "swagger": "2.0", - "info": { - "version": "1.0.0", - "title": "Swagger Petstore", - "contact": { - "name": "Wordnik API Team", - "url": "http://developer.wordnik.com" - }, - "license": { - "name": "Creative Commons 4.0 International", - "url": "http://creativecommons.org/licenses/by/4.0/" - } - }, - "host": "petstore.swagger.wordnik.com", - "basePath": "/api", - "schemes": [ - "http" - ], - "paths": { - "/pets": { - "get": { - "security": [ - { - "basic": [] - } - ], - "tags": [ "Pet Operations" ], - "operationId": "getAllPets", - "parameters": [ - { - "name": "status", - "in": "query", - "description": "The status to filter by", - "type": "string" - }, - { - "name": "limit", - "in": "query", - "description": "The maximum number of results to return", - "type": "integer", - "format": "int64" - } - ], - "summary": "Finds all pets in the system", - "responses": { - "200": { - "description": "Pet response", - "schema": { - "type": "array", - "items": { - "$ref": "#/definitions/Pet" - } - } - }, - "default": { - "description": "Unexpected error", - "schema": { - "$ref": "#/definitions/Error" - } - } - } - }, - "post": { - "security": [ - { - "basic": [] - } - ], - "tags": [ "Pet Operations" ], - "operationId": "createPet", - "summary": "Creates a new pet", - "consumes": ["application/x-yaml"], - "produces": ["application/x-yaml"], - "parameters": [ - { - "name": "pet", - "in": "body", - "description": "The Pet to create", - "required": true, - "schema": { - "$ref": "#/definitions/newPet" - } - } - ], - "responses": { - "200": { - "description": "Created Pet response", - "schema": { - "$ref": "#/definitions/Pet" - } - }, - "default": { - "description": "Unexpected error", - "schema": { - "$ref": "#/definitions/Error" - } - } - } - } - }, - "/pets/{id}": { - "delete": { - "security": [ - { - "apiKey": [] - } - ], - "description": "Deletes the Pet by id", - "operationId": "deletePet", - "parameters": [ - { - "name": "id", - "in": "path", - "description": "ID of pet to delete", - "required": true, - "type": "integer", - "format": "int64" - } - ], - "responses": { - "204": { - "description": "pet deleted" - }, - "default": { - "description": "unexpected error", - "schema": { - "$ref": "#/definitions/Error" - } - } - } - }, - "get": { - "tags": [ "Pet Operations" ], - "operationId": "getPetById", - "summary": "Finds the pet by id", - "responses": { - "200": { - "description": "Pet response", - "schema": { - "$ref": "#/definitions/Pet" - } - }, - "default": { - "description": "Unexpected error", - "schema": { - "$ref": "#/definitions/Error" - } - } - } - }, - "parameters": [ - { - "name": "id", - "in": "path", - "description": "ID of pet", - "required": true, - "type": "integer", - "format": "int64" - } - ] - } - }, - "definitions": { - "Category": { - "id": "Category", - "properties": { - "id": { - "format": "int64", - "type": "integer" - }, - "name": { - "type": "string" - } - } - }, - "Pet": { - "id": "Pet", - "properties": { - "category": { - "$ref": "#/definitions/Category" - }, - "id": { - "description": "unique identifier for the pet", - "format": "int64", - "maximum": 100.0, - "minimum": 0.0, - "type": "integer" - }, - "name": { - "type": "string" - }, - "photoUrls": { - "items": { - "type": "string" - }, - "type": "array" - }, - "status": { - "description": "pet status in the store", - "enum": [ - "available", - "pending", - "sold" - ], - "type": "string" - }, - "tags": { - "items": { - "$ref": "#/definitions/Tag" - }, - "type": "array" - } - }, - "required": [ - "id", - "name" - ] - }, - "newPet": { - "anyOf": [ - { - "$ref": "#/definitions/Pet" - }, - { - "required": [ - "name" - ] - } - ] - }, - "Tag": { - "id": "Tag", - "properties": { - "id": { - "format": "int64", - "type": "integer" - }, - "name": { - "type": "string" - } - } - }, - "Error": { - "required": [ - "code", - "message" - ], - "properties": { - "code": { - "type": "integer", - "format": "int32" - }, - "message": { - "type": "string" - } - } - } - }, - "consumes": [ - "application/json", - "application/xml" - ], - "produces": [ - "application/json", - "application/xml", - "text/plain", - "text/html" - ], - "securityDefinitions": { - "basic": { - "type": "basic" - }, - "apiKey": { - "type": "apiKey", - "in": "header", - "name": "X-API-KEY" - } - } -} -` diff --git a/vendor/github.com/go-openapi/spec/external_docs_test.go b/vendor/github.com/go-openapi/spec/external_docs_test.go deleted file mode 100644 index 14c5ef156..000000000 --- a/vendor/github.com/go-openapi/spec/external_docs_test.go +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package spec - -import ( - "testing" -) - -func TestIntegrationExternalDocs(t *testing.T) { - var extDocs = ExternalDocumentation{"the name", "the url"} - const extDocsYAML = "description: the name\nurl: the url\n" - const extDocsJSON = `{"description":"the name","url":"the url"}` - assertSerializeJSON(t, extDocs, extDocsJSON) - assertSerializeYAML(t, extDocs, extDocsYAML) - assertParsesJSON(t, extDocsJSON, extDocs) - assertParsesYAML(t, extDocsYAML, extDocs) -} diff --git a/vendor/github.com/go-openapi/spec/header_test.go b/vendor/github.com/go-openapi/spec/header_test.go deleted file mode 100644 index a07d174fd..000000000 --- a/vendor/github.com/go-openapi/spec/header_test.go +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package spec - -import ( - "encoding/json" - "testing" - - "github.com/stretchr/testify/assert" -) - -func float64Ptr(f float64) *float64 { - return &f -} -func int64Ptr(f int64) *int64 { - return &f -} - -var header = Header{ - VendorExtensible: VendorExtensible{Extensions: map[string]interface{}{ - "x-framework": "swagger-go", - }}, - HeaderProps: HeaderProps{Description: "the description of this header"}, - SimpleSchema: SimpleSchema{ - Items: &Items{ - Refable: Refable{Ref: MustCreateRef("Cat")}, - }, - Type: "string", - Format: "date", - Default: "8", - }, - CommonValidations: CommonValidations{ - Maximum: float64Ptr(100), - ExclusiveMaximum: true, - ExclusiveMinimum: true, - Minimum: float64Ptr(5), - MaxLength: int64Ptr(100), - MinLength: int64Ptr(5), - Pattern: "\\w{1,5}\\w+", - MaxItems: int64Ptr(100), - MinItems: int64Ptr(5), - UniqueItems: true, - MultipleOf: float64Ptr(5), - Enum: []interface{}{"hello", "world"}, - }, -} - -var headerJSON = `{ - "items": { - "$ref": "Cat" - }, - "x-framework": "swagger-go", - "description": "the description of this header", - "maximum": 100, - "minimum": 5, - "exclusiveMaximum": true, - "exclusiveMinimum": true, - "maxLength": 100, - "minLength": 5, - "pattern": "\\w{1,5}\\w+", - "maxItems": 100, - "minItems": 5, - "uniqueItems": true, - "multipleOf": 5, - "enum": ["hello", "world"], - "type": "string", - "format": "date", - "default": "8" -}` - -func TestIntegrationHeader(t *testing.T) { - var actual Header - if assert.NoError(t, json.Unmarshal([]byte(headerJSON), &actual)) { - assert.EqualValues(t, actual, header) - } - - assertParsesJSON(t, headerJSON, header) -} diff --git a/vendor/github.com/go-openapi/spec/info_test.go b/vendor/github.com/go-openapi/spec/info_test.go deleted file mode 100644 index fc40c1630..000000000 --- a/vendor/github.com/go-openapi/spec/info_test.go +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package spec - -import ( - "encoding/json" - "testing" - - "github.com/stretchr/testify/assert" -) - -var infoJSON = `{ - "description": "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification", - "title": "Swagger Sample API", - "termsOfService": "http://helloreverb.com/terms/", - "contact": { - "name": "wordnik api team", - "url": "http://developer.wordnik.com" - }, - "license": { - "name": "Creative Commons 4.0 International", - "url": "http://creativecommons.org/licenses/by/4.0/" - }, - "version": "1.0.9-abcd", - "x-framework": "go-swagger" -}` - -var info = Info{ - InfoProps: InfoProps{ - Version: "1.0.9-abcd", - Title: "Swagger Sample API", - Description: "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification", - TermsOfService: "http://helloreverb.com/terms/", - Contact: &ContactInfo{Name: "wordnik api team", URL: "http://developer.wordnik.com"}, - License: &License{Name: "Creative Commons 4.0 International", URL: "http://creativecommons.org/licenses/by/4.0/"}, - }, - VendorExtensible: VendorExtensible{map[string]interface{}{"x-framework": "go-swagger"}}, -} - -func TestIntegrationInfo_Serialize(t *testing.T) { - b, err := json.MarshalIndent(info, "", "\t") - if assert.NoError(t, err) { - assert.Equal(t, infoJSON, string(b)) - } -} - -func TestIntegrationInfo_Deserialize(t *testing.T) { - actual := Info{} - err := json.Unmarshal([]byte(infoJSON), &actual) - if assert.NoError(t, err) { - assert.EqualValues(t, info, actual) - } -} diff --git a/vendor/github.com/go-openapi/spec/items_test.go b/vendor/github.com/go-openapi/spec/items_test.go deleted file mode 100644 index 2f9ac11b4..000000000 --- a/vendor/github.com/go-openapi/spec/items_test.go +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package spec - -import ( - "encoding/json" - "testing" - - "github.com/stretchr/testify/assert" -) - -var items = Items{ - Refable: Refable{Ref: MustCreateRef("Dog")}, - CommonValidations: CommonValidations{ - Maximum: float64Ptr(100), - ExclusiveMaximum: true, - ExclusiveMinimum: true, - Minimum: float64Ptr(5), - MaxLength: int64Ptr(100), - MinLength: int64Ptr(5), - Pattern: "\\w{1,5}\\w+", - MaxItems: int64Ptr(100), - MinItems: int64Ptr(5), - UniqueItems: true, - MultipleOf: float64Ptr(5), - Enum: []interface{}{"hello", "world"}, - }, - SimpleSchema: SimpleSchema{ - Type: "string", - Format: "date", - Items: &Items{ - Refable: Refable{Ref: MustCreateRef("Cat")}, - }, - CollectionFormat: "csv", - Default: "8", - }, -} - -var itemsJSON = `{ - "items": { - "$ref": "Cat" - }, - "$ref": "Dog", - "maximum": 100, - "minimum": 5, - "exclusiveMaximum": true, - "exclusiveMinimum": true, - "maxLength": 100, - "minLength": 5, - "pattern": "\\w{1,5}\\w+", - "maxItems": 100, - "minItems": 5, - "uniqueItems": true, - "multipleOf": 5, - "enum": ["hello", "world"], - "type": "string", - "format": "date", - "collectionFormat": "csv", - "default": "8" -}` - -func TestIntegrationItems(t *testing.T) { - var actual Items - if assert.NoError(t, json.Unmarshal([]byte(itemsJSON), &actual)) { - assert.EqualValues(t, actual, items) - } - - assertParsesJSON(t, itemsJSON, items) -} diff --git a/vendor/github.com/go-openapi/spec/license_test.go b/vendor/github.com/go-openapi/spec/license_test.go deleted file mode 100644 index 8ed51a352..000000000 --- a/vendor/github.com/go-openapi/spec/license_test.go +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package spec - -import "testing" - -func TestIntegrationLicense(t *testing.T) { - license := License{"the name", "the url"} - const licenseJSON = `{"name":"the name","url":"the url"}` - const licenseYAML = "name: the name\nurl: the url\n" - - assertSerializeJSON(t, license, licenseJSON) - assertSerializeYAML(t, license, licenseYAML) - assertParsesJSON(t, licenseJSON, license) - assertParsesYAML(t, licenseYAML, license) -} diff --git a/vendor/github.com/go-openapi/spec/operation_test.go b/vendor/github.com/go-openapi/spec/operation_test.go deleted file mode 100644 index 113bf6c06..000000000 --- a/vendor/github.com/go-openapi/spec/operation_test.go +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package spec - -import ( - "encoding/json" - "testing" - - "github.com/stretchr/testify/assert" -) - -var operation = Operation{ - VendorExtensible: VendorExtensible{ - Extensions: map[string]interface{}{ - "x-framework": "go-swagger", - }, - }, - OperationProps: OperationProps{ - Description: "operation description", - Consumes: []string{"application/json", "application/x-yaml"}, - Produces: []string{"application/json", "application/x-yaml"}, - Schemes: []string{"http", "https"}, - Tags: []string{"dogs"}, - Summary: "the summary of the operation", - ID: "sendCat", - Deprecated: true, - Security: []map[string][]string{ - map[string][]string{ - "apiKey": []string{}, - }, - }, - Parameters: []Parameter{ - Parameter{Refable: Refable{Ref: MustCreateRef("Cat")}}, - }, - Responses: &Responses{ - ResponsesProps: ResponsesProps{ - Default: &Response{ - ResponseProps: ResponseProps{ - Description: "void response", - }, - }, - }, - }, - }, -} - -var operationJSON = `{ - "description": "operation description", - "x-framework": "go-swagger", - "consumes": [ "application/json", "application/x-yaml" ], - "produces": [ "application/json", "application/x-yaml" ], - "schemes": ["http", "https"], - "tags": ["dogs"], - "summary": "the summary of the operation", - "operationId": "sendCat", - "deprecated": true, - "security": [ { "apiKey": [] } ], - "parameters": [{"$ref":"Cat"}], - "responses": { - "default": { - "description": "void response" - } - } -}` - -func TestIntegrationOperation(t *testing.T) { - var actual Operation - if assert.NoError(t, json.Unmarshal([]byte(operationJSON), &actual)) { - assert.EqualValues(t, actual, operation) - } - - assertParsesJSON(t, operationJSON, operation) -} diff --git a/vendor/github.com/go-openapi/spec/parameters_test.go b/vendor/github.com/go-openapi/spec/parameters_test.go deleted file mode 100644 index 424f66332..000000000 --- a/vendor/github.com/go-openapi/spec/parameters_test.go +++ /dev/null @@ -1,156 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package spec - -import ( - "encoding/json" - "testing" - - "github.com/stretchr/testify/assert" -) - -var parameter = Parameter{ - VendorExtensible: VendorExtensible{Extensions: map[string]interface{}{ - "x-framework": "swagger-go", - }}, - Refable: Refable{Ref: MustCreateRef("Dog")}, - CommonValidations: CommonValidations{ - Maximum: float64Ptr(100), - ExclusiveMaximum: true, - ExclusiveMinimum: true, - Minimum: float64Ptr(5), - MaxLength: int64Ptr(100), - MinLength: int64Ptr(5), - Pattern: "\\w{1,5}\\w+", - MaxItems: int64Ptr(100), - MinItems: int64Ptr(5), - UniqueItems: true, - MultipleOf: float64Ptr(5), - Enum: []interface{}{"hello", "world"}, - }, - SimpleSchema: SimpleSchema{ - Type: "string", - Format: "date", - CollectionFormat: "csv", - Items: &Items{ - Refable: Refable{Ref: MustCreateRef("Cat")}, - }, - Default: "8", - }, - ParamProps: ParamProps{ - Name: "param-name", - In: "header", - Required: true, - Schema: &Schema{SchemaProps: SchemaProps{Type: []string{"string"}}}, - Description: "the description of this parameter", - }, -} - -var parameterJSON = `{ - "items": { - "$ref": "Cat" - }, - "x-framework": "swagger-go", - "$ref": "Dog", - "description": "the description of this parameter", - "maximum": 100, - "minimum": 5, - "exclusiveMaximum": true, - "exclusiveMinimum": true, - "maxLength": 100, - "minLength": 5, - "pattern": "\\w{1,5}\\w+", - "maxItems": 100, - "minItems": 5, - "uniqueItems": true, - "multipleOf": 5, - "enum": ["hello", "world"], - "type": "string", - "format": "date", - "name": "param-name", - "in": "header", - "required": true, - "schema": { - "type": "string" - }, - "collectionFormat": "csv", - "default": "8" -}` - -func TestIntegrationParameter(t *testing.T) { - var actual Parameter - if assert.NoError(t, json.Unmarshal([]byte(parameterJSON), &actual)) { - assert.EqualValues(t, actual, parameter) - } - - assertParsesJSON(t, parameterJSON, parameter) -} - -func TestParameterSerialization(t *testing.T) { - items := &Items{ - SimpleSchema: SimpleSchema{Type: "string"}, - } - - intItems := &Items{ - SimpleSchema: SimpleSchema{Type: "int", Format: "int32"}, - } - - assertSerializeJSON(t, QueryParam("").Typed("string", ""), `{"type":"string","in":"query"}`) - - assertSerializeJSON(t, - QueryParam("").CollectionOf(items, "multi"), - `{"type":"array","items":{"type":"string"},"collectionFormat":"multi","in":"query"}`) - - assertSerializeJSON(t, PathParam("").Typed("string", ""), `{"type":"string","in":"path","required":true}`) - - assertSerializeJSON(t, - PathParam("").CollectionOf(items, "multi"), - `{"type":"array","items":{"type":"string"},"collectionFormat":"multi","in":"path","required":true}`) - - assertSerializeJSON(t, - PathParam("").CollectionOf(intItems, "multi"), - `{"type":"array","items":{"type":"int","format":"int32"},"collectionFormat":"multi","in":"path","required":true}`) - - assertSerializeJSON(t, HeaderParam("").Typed("string", ""), `{"type":"string","in":"header","required":true}`) - - assertSerializeJSON(t, - HeaderParam("").CollectionOf(items, "multi"), - `{"type":"array","items":{"type":"string"},"collectionFormat":"multi","in":"header","required":true}`) - schema := &Schema{SchemaProps: SchemaProps{ - Properties: map[string]Schema{ - "name": Schema{SchemaProps: SchemaProps{ - Type: []string{"string"}, - }}, - }, - }} - - refSchema := &Schema{ - SchemaProps: SchemaProps{Ref: MustCreateRef("Cat")}, - } - - assertSerializeJSON(t, - BodyParam("", schema), - `{"type":"object","in":"body","schema":{"properties":{"name":{"type":"string"}}}}`) - - assertSerializeJSON(t, - BodyParam("", refSchema), - `{"type":"object","in":"body","schema":{"$ref":"Cat"}}`) - - // array body param - assertSerializeJSON(t, - BodyParam("", ArrayProperty(RefProperty("Cat"))), - `{"type":"object","in":"body","schema":{"type":"array","items":{"$ref":"Cat"}}}`) - -} diff --git a/vendor/github.com/go-openapi/spec/path_item_test.go b/vendor/github.com/go-openapi/spec/path_item_test.go deleted file mode 100644 index ea77e6a9b..000000000 --- a/vendor/github.com/go-openapi/spec/path_item_test.go +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package spec - -import ( - "encoding/json" - "testing" - - "github.com/stretchr/testify/assert" -) - -var pathItem = PathItem{ - Refable: Refable{Ref: MustCreateRef("Dog")}, - VendorExtensible: VendorExtensible{ - Extensions: map[string]interface{}{ - "x-framework": "go-swagger", - }, - }, - PathItemProps: PathItemProps{ - Get: &Operation{ - OperationProps: OperationProps{Description: "get operation description"}, - }, - Put: &Operation{ - OperationProps: OperationProps{Description: "put operation description"}, - }, - Post: &Operation{ - OperationProps: OperationProps{Description: "post operation description"}, - }, - Delete: &Operation{ - OperationProps: OperationProps{Description: "delete operation description"}, - }, - Options: &Operation{ - OperationProps: OperationProps{Description: "options operation description"}, - }, - Head: &Operation{ - OperationProps: OperationProps{Description: "head operation description"}, - }, - Patch: &Operation{ - OperationProps: OperationProps{Description: "patch operation description"}, - }, - Parameters: []Parameter{ - Parameter{ - ParamProps: ParamProps{In: "path"}, - }, - }, - }, -} - -var pathItemJSON = `{ - "$ref": "Dog", - "x-framework": "go-swagger", - "get": { "description": "get operation description" }, - "put": { "description": "put operation description" }, - "post": { "description": "post operation description" }, - "delete": { "description": "delete operation description" }, - "options": { "description": "options operation description" }, - "head": { "description": "head operation description" }, - "patch": { "description": "patch operation description" }, - "parameters": [{"in":"path"}] -}` - -func TestIntegrationPathItem(t *testing.T) { - var actual PathItem - if assert.NoError(t, json.Unmarshal([]byte(pathItemJSON), &actual)) { - assert.EqualValues(t, actual, pathItem) - } - - assertParsesJSON(t, pathItemJSON, pathItem) -} diff --git a/vendor/github.com/go-openapi/spec/paths_test.go b/vendor/github.com/go-openapi/spec/paths_test.go deleted file mode 100644 index 5ccfd4a0a..000000000 --- a/vendor/github.com/go-openapi/spec/paths_test.go +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package spec - -import ( - "encoding/json" - "testing" - - "github.com/stretchr/testify/assert" -) - -var paths = Paths{ - VendorExtensible: VendorExtensible{Extensions: map[string]interface{}{"x-framework": "go-swagger"}}, - Paths: map[string]PathItem{ - "/": PathItem{ - Refable: Refable{Ref: MustCreateRef("cats")}, - }, - }, -} - -var pathsJSON = `{"x-framework":"go-swagger","/":{"$ref":"cats"}}` - -func TestIntegrationPaths(t *testing.T) { - var actual Paths - if assert.NoError(t, json.Unmarshal([]byte(pathsJSON), &actual)) { - assert.EqualValues(t, actual, paths) - } - - assertParsesJSON(t, pathsJSON, paths) - -} diff --git a/vendor/github.com/go-openapi/spec/properties_test.go b/vendor/github.com/go-openapi/spec/properties_test.go deleted file mode 100644 index 90bd32c9e..000000000 --- a/vendor/github.com/go-openapi/spec/properties_test.go +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package spec - -import ( - "testing" -) - -func TestPropertySerialization(t *testing.T) { - strProp := StringProperty() - strProp.Enum = append(strProp.Enum, "a", "b") - - prop := &Schema{SchemaProps: SchemaProps{ - Items: &SchemaOrArray{Schemas: []Schema{ - Schema{SchemaProps: SchemaProps{Type: []string{"string"}}}, - Schema{SchemaProps: SchemaProps{Type: []string{"string"}}}, - }}, - }} - - var propSerData = []struct { - Schema *Schema - JSON string - }{ - {BooleanProperty(), `{"type":"boolean"}`}, - {DateProperty(), `{"type":"string","format":"date"}`}, - {DateTimeProperty(), `{"type":"string","format":"date-time"}`}, - {Float64Property(), `{"type":"number","format":"double"}`}, - {Float32Property(), `{"type":"number","format":"float"}`}, - {Int32Property(), `{"type":"integer","format":"int32"}`}, - {Int64Property(), `{"type":"integer","format":"int64"}`}, - {MapProperty(StringProperty()), `{"type":"object","additionalProperties":{"type":"string"}}`}, - {MapProperty(Int32Property()), `{"type":"object","additionalProperties":{"type":"integer","format":"int32"}}`}, - {RefProperty("Dog"), `{"$ref":"Dog"}`}, - {StringProperty(), `{"type":"string"}`}, - {strProp, `{"type":"string","enum":["a","b"]}`}, - {ArrayProperty(StringProperty()), `{"type":"array","items":{"type":"string"}}`}, - {prop, `{"items":[{"type":"string"},{"type":"string"}]}`}, - } - - for _, v := range propSerData { - t.Log("roundtripping for", v.JSON) - assertSerializeJSON(t, v.Schema, v.JSON) - assertParsesJSON(t, v.JSON, v.Schema) - } - -} diff --git a/vendor/github.com/go-openapi/spec/response_test.go b/vendor/github.com/go-openapi/spec/response_test.go deleted file mode 100644 index 2a3ca4093..000000000 --- a/vendor/github.com/go-openapi/spec/response_test.go +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright 2017 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package spec - -import ( - "encoding/json" - "testing" - - "github.com/stretchr/testify/assert" -) - -var response = Response{ - Refable: Refable{Ref: MustCreateRef("Dog")}, - VendorExtensible: VendorExtensible{ - Extensions: map[string]interface{}{ - "x-go-name": "PutDogExists", - }, - }, - ResponseProps: ResponseProps{ - Description: "Dog exists", - Schema: &Schema{SchemaProps: SchemaProps{Type: []string{"string"}}}, - }, -} - -var responseJSON = `{ - "$ref": "Dog", - "x-go-name": "PutDogExists", - "description": "Dog exists", - "schema": { - "type": "string" - } -}` - -func TestIntegrationResponse(t *testing.T) { - var actual Response - if assert.NoError(t, json.Unmarshal([]byte(responseJSON), &actual)) { - assert.EqualValues(t, actual, response) - } - - assertParsesJSON(t, responseJSON, response) -} diff --git a/vendor/github.com/go-openapi/spec/schema_test.go b/vendor/github.com/go-openapi/spec/schema_test.go deleted file mode 100644 index 2e49fbc15..000000000 --- a/vendor/github.com/go-openapi/spec/schema_test.go +++ /dev/null @@ -1,205 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package spec - -import ( - "encoding/json" - "testing" - - "github.com/stretchr/testify/assert" -) - -var schema = Schema{ - VendorExtensible: VendorExtensible{Extensions: map[string]interface{}{"x-framework": "go-swagger"}}, - SchemaProps: SchemaProps{ - Ref: MustCreateRef("Cat"), - Type: []string{"string"}, - Format: "date", - Description: "the description of this schema", - Title: "the title", - Default: "blah", - Maximum: float64Ptr(100), - ExclusiveMaximum: true, - ExclusiveMinimum: true, - Minimum: float64Ptr(5), - MaxLength: int64Ptr(100), - MinLength: int64Ptr(5), - Pattern: "\\w{1,5}\\w+", - MaxItems: int64Ptr(100), - MinItems: int64Ptr(5), - UniqueItems: true, - MultipleOf: float64Ptr(5), - Enum: []interface{}{"hello", "world"}, - MaxProperties: int64Ptr(5), - MinProperties: int64Ptr(1), - Required: []string{"id", "name"}, - Items: &SchemaOrArray{Schema: &Schema{SchemaProps: SchemaProps{Type: []string{"string"}}}}, - AllOf: []Schema{Schema{SchemaProps: SchemaProps{Type: []string{"string"}}}}, - Properties: map[string]Schema{ - "id": Schema{SchemaProps: SchemaProps{Type: []string{"integer"}, Format: "int64"}}, - "name": Schema{SchemaProps: SchemaProps{Type: []string{"string"}}}, - }, - AdditionalProperties: &SchemaOrBool{Allows: true, Schema: &Schema{SchemaProps: SchemaProps{ - Type: []string{"integer"}, - Format: "int32", - }}}, - }, - SwaggerSchemaProps: SwaggerSchemaProps{ - Discriminator: "not this", - ReadOnly: true, - XML: &XMLObject{"sch", "io", "sw", true, true}, - ExternalDocs: &ExternalDocumentation{ - Description: "the documentation etc", - URL: "http://readthedocs.org/swagger", - }, - Example: []interface{}{ - map[string]interface{}{ - "id": 1, - "name": "a book", - }, - map[string]interface{}{ - "id": 2, - "name": "the thing", - }, - }, - }, -} - -var schemaJSON = `{ - "x-framework": "go-swagger", - "$ref": "Cat", - "description": "the description of this schema", - "maximum": 100, - "minimum": 5, - "exclusiveMaximum": true, - "exclusiveMinimum": true, - "maxLength": 100, - "minLength": 5, - "pattern": "\\w{1,5}\\w+", - "maxItems": 100, - "minItems": 5, - "uniqueItems": true, - "multipleOf": 5, - "enum": ["hello", "world"], - "type": "string", - "format": "date", - "title": "the title", - "default": "blah", - "maxProperties": 5, - "minProperties": 1, - "required": ["id", "name"], - "items": { - "type": "string" - }, - "allOf": [ - { - "type": "string" - } - ], - "properties": { - "id": { - "type": "integer", - "format": "int64" - }, - "name": { - "type": "string" - } - }, - "discriminator": "not this", - "readOnly": true, - "xml": { - "name": "sch", - "namespace": "io", - "prefix": "sw", - "wrapped": true, - "attribute": true - }, - "externalDocs": { - "description": "the documentation etc", - "url": "http://readthedocs.org/swagger" - }, - "example": [ - { - "id": 1, - "name": "a book" - }, - { - "id": 2, - "name": "the thing" - } - ], - "additionalProperties": { - "type": "integer", - "format": "int32" - } -} -` - -func TestSchema(t *testing.T) { - - expected := map[string]interface{}{} - json.Unmarshal([]byte(schemaJSON), &expected) - b, err := json.Marshal(schema) - if assert.NoError(t, err) { - var actual map[string]interface{} - json.Unmarshal(b, &actual) - assert.Equal(t, expected, actual) - } - - actual2 := Schema{} - if assert.NoError(t, json.Unmarshal([]byte(schemaJSON), &actual2)) { - assert.Equal(t, schema.Ref, actual2.Ref) - assert.Equal(t, schema.Description, actual2.Description) - assert.Equal(t, schema.Maximum, actual2.Maximum) - assert.Equal(t, schema.Minimum, actual2.Minimum) - assert.Equal(t, schema.ExclusiveMinimum, actual2.ExclusiveMinimum) - assert.Equal(t, schema.ExclusiveMaximum, actual2.ExclusiveMaximum) - assert.Equal(t, schema.MaxLength, actual2.MaxLength) - assert.Equal(t, schema.MinLength, actual2.MinLength) - assert.Equal(t, schema.Pattern, actual2.Pattern) - assert.Equal(t, schema.MaxItems, actual2.MaxItems) - assert.Equal(t, schema.MinItems, actual2.MinItems) - assert.True(t, actual2.UniqueItems) - assert.Equal(t, schema.MultipleOf, actual2.MultipleOf) - assert.Equal(t, schema.Enum, actual2.Enum) - assert.Equal(t, schema.Type, actual2.Type) - assert.Equal(t, schema.Format, actual2.Format) - assert.Equal(t, schema.Title, actual2.Title) - assert.Equal(t, schema.MaxProperties, actual2.MaxProperties) - assert.Equal(t, schema.MinProperties, actual2.MinProperties) - assert.Equal(t, schema.Required, actual2.Required) - assert.Equal(t, schema.Items, actual2.Items) - assert.Equal(t, schema.AllOf, actual2.AllOf) - assert.Equal(t, schema.Properties, actual2.Properties) - assert.Equal(t, schema.Discriminator, actual2.Discriminator) - assert.Equal(t, schema.ReadOnly, actual2.ReadOnly) - assert.Equal(t, schema.XML, actual2.XML) - assert.Equal(t, schema.ExternalDocs, actual2.ExternalDocs) - assert.Equal(t, schema.AdditionalProperties, actual2.AdditionalProperties) - assert.Equal(t, schema.Extensions, actual2.Extensions) - examples := actual2.Example.([]interface{}) - expEx := schema.Example.([]interface{}) - ex1 := examples[0].(map[string]interface{}) - ex2 := examples[1].(map[string]interface{}) - exp1 := expEx[0].(map[string]interface{}) - exp2 := expEx[1].(map[string]interface{}) - - assert.EqualValues(t, exp1["id"], ex1["id"]) - assert.Equal(t, exp1["name"], ex1["name"]) - assert.EqualValues(t, exp2["id"], ex2["id"]) - assert.Equal(t, exp2["name"], ex2["name"]) - } - -} diff --git a/vendor/github.com/go-openapi/spec/structs_test.go b/vendor/github.com/go-openapi/spec/structs_test.go deleted file mode 100644 index bfa59ee03..000000000 --- a/vendor/github.com/go-openapi/spec/structs_test.go +++ /dev/null @@ -1,110 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package spec - -import ( - "encoding/json" - "reflect" - "testing" - - "github.com/stretchr/testify/assert" - "gopkg.in/yaml.v2" -) - -func assertSerializeJSON(t testing.TB, actual interface{}, expected string) bool { - ser, err := json.Marshal(actual) - if err != nil { - return assert.Fail(t, "unable to marshal to json (%s): %#v", err, actual) - } - return assert.Equal(t, string(ser), expected) -} - -func assertParsesJSON(t testing.TB, actual string, expected interface{}) bool { - tpe := reflect.TypeOf(expected) - var pointed bool - if tpe.Kind() == reflect.Ptr { - tpe = tpe.Elem() - pointed = true - } - - parsed := reflect.New(tpe) - err := json.Unmarshal([]byte(actual), parsed.Interface()) - if err != nil { - return assert.Fail(t, "unable to unmarshal from json (%s): %s", err, actual) - } - act := parsed.Interface() - if !pointed { - act = reflect.Indirect(parsed).Interface() - } - return assert.Equal(t, act, expected) -} - -func assertSerializeYAML(t testing.TB, actual interface{}, expected string) bool { - ser, err := yaml.Marshal(actual) - if err != nil { - return assert.Fail(t, "unable to marshal to yaml (%s): %#v", err, actual) - } - return assert.Equal(t, string(ser), expected) -} - -func assertParsesYAML(t testing.TB, actual string, expected interface{}) bool { - tpe := reflect.TypeOf(expected) - var pointed bool - if tpe.Kind() == reflect.Ptr { - tpe = tpe.Elem() - pointed = true - } - parsed := reflect.New(tpe) - err := yaml.Unmarshal([]byte(actual), parsed.Interface()) - if err != nil { - return assert.Fail(t, "unable to unmarshal from yaml (%s): %s", err, actual) - } - act := parsed.Interface() - if !pointed { - act = reflect.Indirect(parsed).Interface() - } - return assert.EqualValues(t, act, expected) -} - -func TestSerialization_SerializeJSON(t *testing.T) { - assertSerializeJSON(t, []string{"hello"}, "[\"hello\"]") - assertSerializeJSON(t, []string{"hello", "world", "and", "stuff"}, "[\"hello\",\"world\",\"and\",\"stuff\"]") - assertSerializeJSON(t, StringOrArray(nil), "null") - assertSerializeJSON(t, SchemaOrArray{Schemas: []Schema{Schema{SchemaProps: SchemaProps{Type: []string{"string"}}}}}, "[{\"type\":\"string\"}]") - assertSerializeJSON(t, SchemaOrArray{ - Schemas: []Schema{ - Schema{SchemaProps: SchemaProps{Type: []string{"string"}}}, - Schema{SchemaProps: SchemaProps{Type: []string{"string"}}}, - }}, "[{\"type\":\"string\"},{\"type\":\"string\"}]") - assertSerializeJSON(t, SchemaOrArray{}, "null") -} - -func TestSerialization_DeserializeJSON(t *testing.T) { - // String - assertParsesJSON(t, "\"hello\"", StringOrArray([]string{"hello"})) - assertParsesJSON(t, "[\"hello\",\"world\",\"and\",\"stuff\"]", StringOrArray([]string{"hello", "world", "and", "stuff"})) - assertParsesJSON(t, "[\"hello\",\"world\",null,\"stuff\"]", StringOrArray([]string{"hello", "world", "", "stuff"})) - assertParsesJSON(t, "null", StringOrArray(nil)) - - // Schema - assertParsesJSON(t, "{\"type\":\"string\"}", SchemaOrArray{Schema: &Schema{SchemaProps: SchemaProps{Type: []string{"string"}}}}) - assertParsesJSON(t, "[{\"type\":\"string\"},{\"type\":\"string\"}]", &SchemaOrArray{ - Schemas: []Schema{ - Schema{SchemaProps: SchemaProps{Type: []string{"string"}}}, - Schema{SchemaProps: SchemaProps{Type: []string{"string"}}}, - }, - }) - assertParsesJSON(t, "null", SchemaOrArray{}) -} diff --git a/vendor/github.com/go-openapi/spec/swagger_test.go b/vendor/github.com/go-openapi/spec/swagger_test.go deleted file mode 100644 index f7b3d9022..000000000 --- a/vendor/github.com/go-openapi/spec/swagger_test.go +++ /dev/null @@ -1,365 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package spec - -import ( - "encoding/json" - "fmt" - "reflect" - "testing" - - "github.com/go-openapi/swag" - "github.com/stretchr/testify/assert" -) - -var spec = Swagger{ - SwaggerProps: SwaggerProps{ - ID: "http://localhost:3849/api-docs", - Swagger: "2.0", - Consumes: []string{"application/json", "application/x-yaml"}, - Produces: []string{"application/json"}, - Schemes: []string{"http", "https"}, - Info: &info, - Host: "some.api.out.there", - BasePath: "/", - Paths: &paths, - Definitions: map[string]Schema{"Category": {SchemaProps: SchemaProps{Type: []string{"string"}}}}, - Parameters: map[string]Parameter{ - "categoryParam": {ParamProps: ParamProps{Name: "category", In: "query"}, SimpleSchema: SimpleSchema{Type: "string"}}, - }, - Responses: map[string]Response{ - "EmptyAnswer": { - ResponseProps: ResponseProps{ - Description: "no data to return for this operation", - }, - }, - }, - SecurityDefinitions: map[string]*SecurityScheme{ - "internalApiKey": APIKeyAuth("api_key", "header"), - }, - Security: []map[string][]string{ - {"internalApiKey": {}}, - }, - Tags: []Tag{NewTag("pets", "", nil)}, - ExternalDocs: &ExternalDocumentation{"the name", "the url"}, - }, - VendorExtensible: VendorExtensible{map[string]interface{}{ - "x-some-extension": "vendor", - "x-schemes": []interface{}{"unix", "amqp"}, - }}, -} - -var specJSON = `{ - "id": "http://localhost:3849/api-docs", - "consumes": ["application/json", "application/x-yaml"], - "produces": ["application/json"], - "schemes": ["http", "https"], - "swagger": "2.0", - "info": { - "contact": { - "name": "wordnik api team", - "url": "http://developer.wordnik.com" - }, - "description": "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification", - "license": { - "name": "Creative Commons 4.0 International", - "url": "http://creativecommons.org/licenses/by/4.0/" - }, - "termsOfService": "http://helloreverb.com/terms/", - "title": "Swagger Sample API", - "version": "1.0.9-abcd", - "x-framework": "go-swagger" - }, - "host": "some.api.out.there", - "basePath": "/", - "paths": {"x-framework":"go-swagger","/":{"$ref":"cats"}}, - "definitions": { "Category": { "type": "string"} }, - "parameters": { - "categoryParam": { - "name": "category", - "in": "query", - "type": "string" - } - }, - "responses": { "EmptyAnswer": { "description": "no data to return for this operation" } }, - "securityDefinitions": { - "internalApiKey": { - "type": "apiKey", - "in": "header", - "name": "api_key" - } - }, - "security": [{"internalApiKey":[]}], - "tags": [{"name":"pets"}], - "externalDocs": {"description":"the name","url":"the url"}, - "x-some-extension": "vendor", - "x-schemes": ["unix","amqp"] -}` - -// -// func verifySpecSerialize(specJSON []byte, spec Swagger) { -// expected := map[string]interface{}{} -// json.Unmarshal(specJSON, &expected) -// b, err := json.MarshalIndent(spec, "", " ") -// So(err, ShouldBeNil) -// var actual map[string]interface{} -// err = json.Unmarshal(b, &actual) -// So(err, ShouldBeNil) -// compareSpecMaps(actual, expected) -// } - -func assertEquivalent(t testing.TB, actual, expected interface{}) bool { - if actual == nil || expected == nil || reflect.DeepEqual(actual, expected) { - return true - } - - actualType := reflect.TypeOf(actual) - expectedType := reflect.TypeOf(expected) - if reflect.TypeOf(actual).ConvertibleTo(expectedType) { - expectedValue := reflect.ValueOf(expected) - if swag.IsZero(expectedValue) && swag.IsZero(reflect.ValueOf(actual)) { - return true - } - - // Attempt comparison after type conversion - if reflect.DeepEqual(actual, expectedValue.Convert(actualType).Interface()) { - return true - } - } - - // Last ditch effort - if fmt.Sprintf("%#v", expected) == fmt.Sprintf("%#v", actual) { - return true - } - errFmt := "Expected: '%T(%#v)'\nActual: '%T(%#v)'\n(Should be equivalent)!" - return assert.Fail(t, errFmt, expected, expected, actual, actual) -} - -func ShouldBeEquivalentTo(actual interface{}, expecteds ...interface{}) string { - expected := expecteds[0] - if actual == nil || expected == nil { - return "" - } - - if reflect.DeepEqual(expected, actual) { - return "" - } - - actualType := reflect.TypeOf(actual) - expectedType := reflect.TypeOf(expected) - if reflect.TypeOf(actual).ConvertibleTo(expectedType) { - expectedValue := reflect.ValueOf(expected) - if swag.IsZero(expectedValue) && swag.IsZero(reflect.ValueOf(actual)) { - return "" - } - - // Attempt comparison after type conversion - if reflect.DeepEqual(actual, expectedValue.Convert(actualType).Interface()) { - return "" - } - } - - // Last ditch effort - if fmt.Sprintf("%#v", expected) == fmt.Sprintf("%#v", actual) { - return "" - } - errFmt := "Expected: '%T(%#v)'\nActual: '%T(%#v)'\n(Should be equivalent)!" - return fmt.Sprintf(errFmt, expected, expected, actual, actual) - -} - -func assertSpecMaps(t testing.TB, actual, expected map[string]interface{}) bool { - res := true - if id, ok := expected["id"]; ok { - res = assert.Equal(t, id, actual["id"]) - } - res = res && assert.Equal(t, expected["consumes"], actual["consumes"]) - res = res && assert.Equal(t, expected["produces"], actual["produces"]) - res = res && assert.Equal(t, expected["schemes"], actual["schemes"]) - res = res && assert.Equal(t, expected["swagger"], actual["swagger"]) - res = res && assert.Equal(t, expected["info"], actual["info"]) - res = res && assert.Equal(t, expected["host"], actual["host"]) - res = res && assert.Equal(t, expected["basePath"], actual["basePath"]) - res = res && assert.Equal(t, expected["paths"], actual["paths"]) - res = res && assert.Equal(t, expected["definitions"], actual["definitions"]) - res = res && assert.Equal(t, expected["responses"], actual["responses"]) - res = res && assert.Equal(t, expected["securityDefinitions"], actual["securityDefinitions"]) - res = res && assert.Equal(t, expected["tags"], actual["tags"]) - res = res && assert.Equal(t, expected["externalDocs"], actual["externalDocs"]) - res = res && assert.Equal(t, expected["x-some-extension"], actual["x-some-extension"]) - res = res && assert.Equal(t, expected["x-schemes"], actual["x-schemes"]) - - return res -} - -// -// func compareSpecMaps(actual, expected map[string]interface{}) { -// if id, ok := expected["id"]; ok { -// So(actual["id"], ShouldEqual, id) -// } -// //So(actual["$schema"], ShouldEqual, SwaggerSchemaURL) -// So(actual["consumes"], ShouldResemble, expected["consumes"]) -// So(actual["produces"], ShouldResemble, expected["produces"]) -// So(actual["schemes"], ShouldResemble, expected["schemes"]) -// So(actual["swagger"], ShouldEqual, expected["swagger"]) -// So(actual["info"], ShouldResemble, expected["info"]) -// So(actual["host"], ShouldEqual, expected["host"]) -// So(actual["basePath"], ShouldEqual, expected["basePath"]) -// So(actual["paths"], ShouldBeEquivalentTo, expected["paths"]) -// So(actual["definitions"], ShouldBeEquivalentTo, expected["definitions"]) -// So(actual["responses"], ShouldBeEquivalentTo, expected["responses"]) -// So(actual["securityDefinitions"], ShouldResemble, expected["securityDefinitions"]) -// So(actual["tags"], ShouldResemble, expected["tags"]) -// So(actual["externalDocs"], ShouldResemble, expected["externalDocs"]) -// So(actual["x-some-extension"], ShouldResemble, expected["x-some-extension"]) -// So(actual["x-schemes"], ShouldResemble, expected["x-schemes"]) -// } - -func assertSpecs(t testing.TB, actual, expected Swagger) bool { - expected.Swagger = "2.0" - return assert.Equal(t, actual, expected) -} - -// -// func compareSpecs(actual Swagger, spec Swagger) { -// spec.Swagger = "2.0" -// So(actual, ShouldBeEquivalentTo, spec) -// } - -func assertSpecJSON(t testing.TB, specJSON []byte) bool { - var expected map[string]interface{} - if !assert.NoError(t, json.Unmarshal(specJSON, &expected)) { - return false - } - - obj := Swagger{} - if !assert.NoError(t, json.Unmarshal(specJSON, &obj)) { - return false - } - - cb, err := json.MarshalIndent(obj, "", " ") - if assert.NoError(t, err) { - return false - } - var actual map[string]interface{} - if !assert.NoError(t, json.Unmarshal(cb, &actual)) { - return false - } - return assertSpecMaps(t, actual, expected) -} - -// func verifySpecJSON(specJSON []byte) { -// //Println() -// //Println("json to verify", string(specJson)) -// var expected map[string]interface{} -// err := json.Unmarshal(specJSON, &expected) -// So(err, ShouldBeNil) -// -// obj := Swagger{} -// err = json.Unmarshal(specJSON, &obj) -// So(err, ShouldBeNil) -// -// //spew.Dump(obj) -// -// cb, err := json.MarshalIndent(obj, "", " ") -// So(err, ShouldBeNil) -// //Println() -// //Println("Marshalling to json returned", string(cb)) -// -// var actual map[string]interface{} -// err = json.Unmarshal(cb, &actual) -// So(err, ShouldBeNil) -// //Println() -// //spew.Dump(expected) -// //spew.Dump(actual) -// //fmt.Printf("comparing %s\n\t%#v\nto\n\t%#+v\n", fileName, expected, actual) -// compareSpecMaps(actual, expected) -// } - -func TestSwaggerSpec_Serialize(t *testing.T) { - expected := make(map[string]interface{}) - json.Unmarshal([]byte(specJSON), &expected) - b, err := json.MarshalIndent(spec, "", " ") - if assert.NoError(t, err) { - var actual map[string]interface{} - err := json.Unmarshal(b, &actual) - if assert.NoError(t, err) { - assert.EqualValues(t, actual, expected) - } - } -} - -func TestSwaggerSpec_Deserialize(t *testing.T) { - var actual Swagger - err := json.Unmarshal([]byte(specJSON), &actual) - if assert.NoError(t, err) { - assert.EqualValues(t, actual, spec) - } -} - -func TestVendorExtensionStringSlice(t *testing.T) { - var actual Swagger - err := json.Unmarshal([]byte(specJSON), &actual) - if assert.NoError(t, err) { - schemes, ok := actual.Extensions.GetStringSlice("x-schemes") - if assert.True(t, ok) { - assert.EqualValues(t, []string{"unix", "amqp"}, schemes) - } - } -} - -func TestOptionalSwaggerProps_Serialize(t *testing.T) { - minimalJsonSpec := []byte(`{ - "swagger": "2.0", - "info": { - "version": "0.0.0", - "title": "Simple API" - }, - "paths": { - "/": { - "get": { - "responses": { - "200": { - "description": "OK" - } - } - } - } - } -}`) - - var minimalSpec Swagger - err := json.Unmarshal(minimalJsonSpec, &minimalSpec) - if assert.NoError(t, err) { - bytes, err := json.Marshal(&minimalSpec) - if assert.NoError(t, err) { - var ms map[string]interface{} - if err := json.Unmarshal(bytes, &ms); assert.NoError(t, err) { - assert.NotContains(t, ms, "consumes") - assert.NotContains(t, ms, "produces") - assert.NotContains(t, ms, "schemes") - assert.NotContains(t, ms, "host") - assert.NotContains(t, ms, "basePath") - assert.NotContains(t, ms, "definitions") - assert.NotContains(t, ms, "parameters") - assert.NotContains(t, ms, "responses") - assert.NotContains(t, ms, "securityDefinitions") - assert.NotContains(t, ms, "security") - assert.NotContains(t, ms, "tags") - assert.NotContains(t, ms, "externalDocs") - } - } - } -} diff --git a/vendor/github.com/go-openapi/spec/xml_object_test.go b/vendor/github.com/go-openapi/spec/xml_object_test.go deleted file mode 100644 index fda3b1084..000000000 --- a/vendor/github.com/go-openapi/spec/xml_object_test.go +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package spec - -import ( - "encoding/json" - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestXmlObject_Serialize(t *testing.T) { - obj1 := XMLObject{} - actual, err := json.Marshal(obj1) - if assert.NoError(t, err) { - assert.Equal(t, "{}", string(actual)) - } - - obj2 := XMLObject{ - Name: "the name", - Namespace: "the namespace", - Prefix: "the prefix", - Attribute: true, - Wrapped: true, - } - - actual, err = json.Marshal(obj2) - if assert.NoError(t, err) { - var ad map[string]interface{} - if assert.NoError(t, json.Unmarshal(actual, &ad)) { - assert.Equal(t, obj2.Name, ad["name"]) - assert.Equal(t, obj2.Namespace, ad["namespace"]) - assert.Equal(t, obj2.Prefix, ad["prefix"]) - assert.True(t, ad["attribute"].(bool)) - assert.True(t, ad["wrapped"].(bool)) - } - } -} - -func TestXmlObject_Deserialize(t *testing.T) { - expected := XMLObject{} - actual := XMLObject{} - if assert.NoError(t, json.Unmarshal([]byte("{}"), &actual)) { - assert.Equal(t, expected, actual) - } - - completed := `{"name":"the name","namespace":"the namespace","prefix":"the prefix","attribute":true,"wrapped":true}` - expected = XMLObject{"the name", "the namespace", "the prefix", true, true} - actual = XMLObject{} - if assert.NoError(t, json.Unmarshal([]byte(completed), &actual)) { - assert.Equal(t, expected, actual) - } -} diff --git a/vendor/github.com/go-openapi/swag/.editorconfig b/vendor/github.com/go-openapi/swag/.editorconfig deleted file mode 100644 index 3152da69a..000000000 --- a/vendor/github.com/go-openapi/swag/.editorconfig +++ /dev/null @@ -1,26 +0,0 @@ -# top-most EditorConfig file -root = true - -# Unix-style newlines with a newline ending every file -[*] -end_of_line = lf -insert_final_newline = true -indent_style = space -indent_size = 2 -trim_trailing_whitespace = true - -# Set default charset -[*.{js,py,go,scala,rb,java,html,css,less,sass,md}] -charset = utf-8 - -# Tab indentation (no size specified) -[*.go] -indent_style = tab - -[*.md] -trim_trailing_whitespace = false - -# Matches the exact files either package.json or .travis.yml -[{package.json,.travis.yml}] -indent_style = space -indent_size = 2 diff --git a/vendor/github.com/go-openapi/swag/.gitignore b/vendor/github.com/go-openapi/swag/.gitignore deleted file mode 100644 index 769c24400..000000000 --- a/vendor/github.com/go-openapi/swag/.gitignore +++ /dev/null @@ -1 +0,0 @@ -secrets.yml diff --git a/vendor/github.com/go-openapi/swag/.travis.yml b/vendor/github.com/go-openapi/swag/.travis.yml deleted file mode 100644 index 24c69bdf3..000000000 --- a/vendor/github.com/go-openapi/swag/.travis.yml +++ /dev/null @@ -1,14 +0,0 @@ -language: go -go: -- 1.8 -install: -- go get -u github.com/stretchr/testify -- go get -u github.com/mailru/easyjson -- go get -u gopkg.in/yaml.v2 -script: -- go test -v -race -cover -coverprofile=coverage.txt -covermode=atomic ./... -after_success: -- bash <(curl -s https://codecov.io/bash) -notifications: - slack: - secure: QUWvCkBBK09GF7YtEvHHVt70JOkdlNBG0nIKu/5qc4/nW5HP8I2w0SEf/XR2je0eED1Qe3L/AfMCWwrEj+IUZc3l4v+ju8X8R3Lomhme0Eb0jd1MTMCuPcBT47YCj0M7RON7vXtbFfm1hFJ/jLe5+9FXz0hpXsR24PJc5ZIi/ogNwkaPqG4BmndzecpSh0vc2FJPZUD9LT0I09REY/vXR0oQAalLkW0asGD5taHZTUZq/kBpsNxaAFrLM23i4mUcf33M5fjLpvx5LRICrX/57XpBrDh2TooBU6Qj3CgoY0uPRYUmSNxbVx1czNzl2JtEpb5yjoxfVPQeg0BvQM00G8LJINISR+ohrjhkZmAqchDupAX+yFrxTtORa78CtnIL6z/aTNlgwwVD8kvL/1pFA/JWYmKDmz93mV/+6wubGzNSQCstzjkFA4/iZEKewKUoRIAi/fxyscP6L/rCpmY/4llZZvrnyTqVbt6URWpopUpH4rwYqreXAtJxJsfBJIeSmUIiDIOMGkCTvyTEW3fWGmGoqWtSHLoaWDyAIGb7azb+KvfpWtEcoPFWfSWU+LGee0A/YsUhBl7ADB9A0CJEuR8q4BPpKpfLwPKSiKSAXL7zDkyjExyhtgqbSl2jS+rKIHOZNL8JkCcTP2MKMVd563C5rC5FMKqu3S9m2b6380E= diff --git a/vendor/github.com/go-openapi/swag/CODE_OF_CONDUCT.md b/vendor/github.com/go-openapi/swag/CODE_OF_CONDUCT.md deleted file mode 100644 index 9322b065e..000000000 --- a/vendor/github.com/go-openapi/swag/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,74 +0,0 @@ -# Contributor Covenant Code of Conduct - -## Our Pledge - -In the interest of fostering an open and welcoming environment, we as -contributors and maintainers pledge to making participation in our project and -our community a harassment-free experience for everyone, regardless of age, body -size, disability, ethnicity, gender identity and expression, level of experience, -nationality, personal appearance, race, religion, or sexual identity and -orientation. - -## Our Standards - -Examples of behavior that contributes to creating a positive environment -include: - -* Using welcoming and inclusive language -* Being respectful of differing viewpoints and experiences -* Gracefully accepting constructive criticism -* Focusing on what is best for the community -* Showing empathy towards other community members - -Examples of unacceptable behavior by participants include: - -* The use of sexualized language or imagery and unwelcome sexual attention or -advances -* Trolling, insulting/derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or electronic - address, without explicit permission -* Other conduct which could reasonably be considered inappropriate in a - professional setting - -## Our Responsibilities - -Project maintainers are responsible for clarifying the standards of acceptable -behavior and are expected to take appropriate and fair corrective action in -response to any instances of unacceptable behavior. - -Project maintainers have the right and responsibility to remove, edit, or -reject comments, commits, code, wiki edits, issues, and other contributions -that are not aligned to this Code of Conduct, or to ban temporarily or -permanently any contributor for other behaviors that they deem inappropriate, -threatening, offensive, or harmful. - -## Scope - -This Code of Conduct applies both within project spaces and in public spaces -when an individual is representing the project or its community. Examples of -representing a project or community include using an official project e-mail -address, posting via an official social media account, or acting as an appointed -representative at an online or offline event. Representation of a project may be -further defined and clarified by project maintainers. - -## Enforcement - -Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported by contacting the project team at ivan+abuse@flanders.co.nz. All -complaints will be reviewed and investigated and will result in a response that -is deemed necessary and appropriate to the circumstances. The project team is -obligated to maintain confidentiality with regard to the reporter of an incident. -Further details of specific enforcement policies may be posted separately. - -Project maintainers who do not follow or enforce the Code of Conduct in good -faith may face temporary or permanent repercussions as determined by other -members of the project's leadership. - -## Attribution - -This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, -available at [http://contributor-covenant.org/version/1/4][version] - -[homepage]: http://contributor-covenant.org -[version]: http://contributor-covenant.org/version/1/4/ diff --git a/vendor/github.com/go-openapi/swag/README.md b/vendor/github.com/go-openapi/swag/README.md deleted file mode 100644 index 5d43728e8..000000000 --- a/vendor/github.com/go-openapi/swag/README.md +++ /dev/null @@ -1,12 +0,0 @@ -# Swag [![Build Status](https://travis-ci.org/go-openapi/swag.svg?branch=master)](https://travis-ci.org/go-openapi/swag) [![codecov](https://codecov.io/gh/go-openapi/swag/branch/master/graph/badge.svg)](https://codecov.io/gh/go-openapi/swag) [![Slack Status](https://slackin.goswagger.io/badge.svg)](https://slackin.goswagger.io) - -[![license](http://img.shields.io/badge/license-Apache%20v2-orange.svg)](https://raw.githubusercontent.com/go-openapi/swag/master/LICENSE) [![GoDoc](https://godoc.org/github.com/go-openapi/swag?status.svg)](http://godoc.org/github.com/go-openapi/swag) - -Contains a bunch of helper functions: - -* convert between value and pointers for builtins -* convert from string to builtin -* fast json concatenation -* search in path -* load from file or http -* name manglin \ No newline at end of file diff --git a/vendor/github.com/go-openapi/swag/convert_test.go b/vendor/github.com/go-openapi/swag/convert_test.go deleted file mode 100644 index 2f0073236..000000000 --- a/vendor/github.com/go-openapi/swag/convert_test.go +++ /dev/null @@ -1,215 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package swag - -import ( - "math" - "strconv" - "testing" - - "github.com/stretchr/testify/assert" -) - -// These are really dumb tests - -func TestConvertBool(t *testing.T) { - for k := range evaluatesAsTrue { - r, err := ConvertBool(k) - if assert.NoError(t, err) { - assert.True(t, r) - } - } - for _, k := range []string{"a", "", "0", "false", "unchecked"} { - r, err := ConvertBool(k) - if assert.NoError(t, err) { - assert.False(t, r) - } - } -} - -func TestConvertFloat32(t *testing.T) { - validFloats := []float32{1.0, -1, math.MaxFloat32, math.SmallestNonzeroFloat32, 0, 5.494430303} - invalidFloats := []string{"a", strconv.FormatFloat(math.MaxFloat64, 'f', -1, 64), "true"} - - for _, f := range validFloats { - c, err := ConvertFloat32(FormatFloat32(f)) - if assert.NoError(t, err) { - assert.EqualValues(t, f, c) - } - } - for _, f := range invalidFloats { - _, err := ConvertFloat32(f) - assert.Error(t, err, "expected '"+f+"' to generate an error") - } -} - -func TestConvertFloat64(t *testing.T) { - validFloats := []float64{1.0, -1, float64(math.MaxFloat32), float64(math.SmallestNonzeroFloat32), math.MaxFloat64, math.SmallestNonzeroFloat64, 0, 5.494430303} - invalidFloats := []string{"a", "true"} - - for _, f := range validFloats { - c, err := ConvertFloat64(FormatFloat64(f)) - if assert.NoError(t, err) { - assert.EqualValues(t, f, c) - } - } - for _, f := range invalidFloats { - _, err := ConvertFloat64(f) - assert.Error(t, err, "expected '"+f+"' to generate an error") - } -} - -func TestConvertInt8(t *testing.T) { - validInts := []int8{0, 1, -1, math.MaxInt8, math.MinInt8} - invalidInts := []string{"1.233", "a", "false", strconv.Itoa(int(math.MaxInt64))} - - for _, f := range validInts { - c, err := ConvertInt8(FormatInt8(f)) - if assert.NoError(t, err) { - assert.EqualValues(t, f, c) - } - } - for _, f := range invalidInts { - _, err := ConvertInt8(f) - assert.Error(t, err, "expected '"+f+"' to generate an error") - } -} - -func TestConvertInt16(t *testing.T) { - validInts := []int16{0, 1, -1, math.MaxInt8, math.MinInt8, math.MaxInt16, math.MinInt16} - invalidInts := []string{"1.233", "a", "false", strconv.Itoa(int(math.MaxInt64))} - - for _, f := range validInts { - c, err := ConvertInt16(FormatInt16(f)) - if assert.NoError(t, err) { - assert.EqualValues(t, f, c) - } - } - for _, f := range invalidInts { - _, err := ConvertInt16(f) - assert.Error(t, err, "expected '"+f+"' to generate an error") - } -} - -func TestConvertInt32(t *testing.T) { - validInts := []int32{0, 1, -1, math.MaxInt8, math.MinInt8, math.MaxInt16, math.MinInt16, math.MinInt32, math.MaxInt32} - invalidInts := []string{"1.233", "a", "false", strconv.Itoa(int(math.MaxInt64))} - - for _, f := range validInts { - c, err := ConvertInt32(FormatInt32(f)) - if assert.NoError(t, err) { - assert.EqualValues(t, f, c) - } - } - for _, f := range invalidInts { - _, err := ConvertInt32(f) - assert.Error(t, err, "expected '"+f+"' to generate an error") - } -} - -func TestConvertInt64(t *testing.T) { - validInts := []int64{0, 1, -1, math.MaxInt8, math.MinInt8, math.MaxInt16, math.MinInt16, math.MinInt32, math.MaxInt32, math.MaxInt64, math.MinInt64} - invalidInts := []string{"1.233", "a", "false"} - - for _, f := range validInts { - c, err := ConvertInt64(FormatInt64(f)) - if assert.NoError(t, err) { - assert.EqualValues(t, f, c) - } - } - for _, f := range invalidInts { - _, err := ConvertInt64(f) - assert.Error(t, err, "expected '"+f+"' to generate an error") - } -} - -func TestConvertUint8(t *testing.T) { - validInts := []uint8{0, 1, math.MaxUint8} - invalidInts := []string{"1.233", "a", "false", strconv.FormatUint(math.MaxUint64, 10)} - - for _, f := range validInts { - c, err := ConvertUint8(FormatUint8(f)) - if assert.NoError(t, err) { - assert.EqualValues(t, f, c) - } - } - for _, f := range invalidInts { - _, err := ConvertUint8(f) - assert.Error(t, err, "expected '"+f+"' to generate an error") - } -} - -func TestConvertUint16(t *testing.T) { - validUints := []uint16{0, 1, math.MaxUint8, math.MaxUint16} - invalidUints := []string{"1.233", "a", "false", strconv.FormatUint(math.MaxUint64, 10)} - - for _, f := range validUints { - c, err := ConvertUint16(FormatUint16(f)) - if assert.NoError(t, err) { - assert.EqualValues(t, f, c) - } - } - for _, f := range invalidUints { - _, err := ConvertUint16(f) - assert.Error(t, err, "expected '"+f+"' to generate an error") - } -} - -func TestConvertUint32(t *testing.T) { - validUints := []uint32{0, 1, math.MaxUint8, math.MaxUint16, math.MaxUint32} - invalidUints := []string{"1.233", "a", "false", strconv.FormatUint(math.MaxUint64, 10)} - - for _, f := range validUints { - c, err := ConvertUint32(FormatUint32(f)) - if assert.NoError(t, err) { - assert.EqualValues(t, f, c) - } - } - for _, f := range invalidUints { - _, err := ConvertUint32(f) - assert.Error(t, err, "expected '"+f+"' to generate an error") - } -} - -func TestConvertUint64(t *testing.T) { - validUints := []uint64{0, 1, math.MaxUint8, math.MaxUint16, math.MaxUint32, math.MaxUint64} - invalidUints := []string{"1.233", "a", "false"} - - for _, f := range validUints { - c, err := ConvertUint64(FormatUint64(f)) - if assert.NoError(t, err) { - assert.EqualValues(t, f, c) - } - } - for _, f := range invalidUints { - _, err := ConvertUint64(f) - assert.Error(t, err, "expected '"+f+"' to generate an error") - } -} - -func TestIsFloat64AJSONInteger(t *testing.T) { - assert.False(t, IsFloat64AJSONInteger(math.Inf(1))) - assert.False(t, IsFloat64AJSONInteger(maxJSONFloat+1)) - - assert.False(t, IsFloat64AJSONInteger(minJSONFloat-1)) - assert.True(t, IsFloat64AJSONInteger(1.0)) - assert.True(t, IsFloat64AJSONInteger(maxJSONFloat)) - assert.True(t, IsFloat64AJSONInteger(minJSONFloat)) -} - -func TestFormatBool(t *testing.T) { - assert.Equal(t, "true", FormatBool(true)) - assert.Equal(t, "false", FormatBool(false)) -} diff --git a/vendor/github.com/go-openapi/swag/convert_types_test.go b/vendor/github.com/go-openapi/swag/convert_types_test.go deleted file mode 100644 index 978cf3a1d..000000000 --- a/vendor/github.com/go-openapi/swag/convert_types_test.go +++ /dev/null @@ -1,579 +0,0 @@ -package swag - -import ( - "testing" - "time" - - "github.com/stretchr/testify/assert" -) - -var testCasesStringSlice = [][]string{ - {"a", "b", "c", "d", "e"}, - {"a", "b", "", "", "e"}, -} - -func TestStringSlice(t *testing.T) { - for idx, in := range testCasesStringSlice { - if in == nil { - continue - } - out := StringSlice(in) - assert.Len(t, out, len(in), "Unexpected len at idx %d", idx) - for i := range out { - assert.Equal(t, in[i], *(out[i]), "Unexpected value at idx %d", idx) - } - - out2 := StringValueSlice(out) - assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx) - assert.Equal(t, in, out2, "Unexpected value at idx %d", idx) - } -} - -var testCasesStringValueSlice = [][]*string{ - {String("a"), String("b"), nil, String("c")}, -} - -func TestStringValueSlice(t *testing.T) { - for idx, in := range testCasesStringValueSlice { - if in == nil { - continue - } - out := StringValueSlice(in) - assert.Len(t, out, len(in), "Unexpected len at idx %d", idx) - for i := range out { - if in[i] == nil { - assert.Empty(t, out[i], "Unexpected value at idx %d", idx) - } else { - assert.Equal(t, *(in[i]), out[i], "Unexpected value at idx %d", idx) - } - } - - out2 := StringSlice(out) - assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx) - for i := range out2 { - if in[i] == nil { - assert.Empty(t, *(out2[i]), "Unexpected value at idx %d", idx) - } else { - assert.Equal(t, in[i], out2[i], "Unexpected value at idx %d", idx) - } - } - } -} - -var testCasesStringMap = []map[string]string{ - {"a": "1", "b": "2", "c": "3"}, -} - -func TestStringMap(t *testing.T) { - for idx, in := range testCasesStringMap { - if in == nil { - continue - } - out := StringMap(in) - assert.Len(t, out, len(in), "Unexpected len at idx %d", idx) - for i := range out { - assert.Equal(t, in[i], *(out[i]), "Unexpected value at idx %d", idx) - } - - out2 := StringValueMap(out) - assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx) - assert.Equal(t, in, out2, "Unexpected value at idx %d", idx) - } -} - -var testCasesBoolSlice = [][]bool{ - {true, true, false, false}, -} - -func TestBoolSlice(t *testing.T) { - for idx, in := range testCasesBoolSlice { - if in == nil { - continue - } - out := BoolSlice(in) - assert.Len(t, out, len(in), "Unexpected len at idx %d", idx) - for i := range out { - assert.Equal(t, in[i], *(out[i]), "Unexpected value at idx %d", idx) - } - - out2 := BoolValueSlice(out) - assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx) - assert.Equal(t, in, out2, "Unexpected value at idx %d", idx) - } -} - -var testCasesBoolValueSlice = [][]*bool{} - -func TestBoolValueSlice(t *testing.T) { - for idx, in := range testCasesBoolValueSlice { - if in == nil { - continue - } - out := BoolValueSlice(in) - assert.Len(t, out, len(in), "Unexpected len at idx %d", idx) - for i := range out { - if in[i] == nil { - assert.Empty(t, out[i], "Unexpected value at idx %d", idx) - } else { - assert.Equal(t, *(in[i]), out[i], "Unexpected value at idx %d", idx) - } - } - - out2 := BoolSlice(out) - assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx) - for i := range out2 { - if in[i] == nil { - assert.Empty(t, *(out2[i]), "Unexpected value at idx %d", idx) - } else { - assert.Equal(t, in[i], out2[i], "Unexpected value at idx %d", idx) - } - } - } -} - -var testCasesBoolMap = []map[string]bool{ - {"a": true, "b": false, "c": true}, -} - -func TestBoolMap(t *testing.T) { - for idx, in := range testCasesBoolMap { - if in == nil { - continue - } - out := BoolMap(in) - assert.Len(t, out, len(in), "Unexpected len at idx %d", idx) - for i := range out { - assert.Equal(t, in[i], *(out[i]), "Unexpected value at idx %d", idx) - } - - out2 := BoolValueMap(out) - assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx) - assert.Equal(t, in, out2, "Unexpected value at idx %d", idx) - } -} - -var testCasesIntSlice = [][]int{ - {1, 2, 3, 4}, -} - -func TestIntSlice(t *testing.T) { - for idx, in := range testCasesIntSlice { - if in == nil { - continue - } - out := IntSlice(in) - assert.Len(t, out, len(in), "Unexpected len at idx %d", idx) - for i := range out { - assert.Equal(t, in[i], *(out[i]), "Unexpected value at idx %d", idx) - } - - out2 := IntValueSlice(out) - assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx) - assert.Equal(t, in, out2, "Unexpected value at idx %d", idx) - } -} - -var testCasesIntValueSlice = [][]*int{} - -func TestIntValueSlice(t *testing.T) { - for idx, in := range testCasesIntValueSlice { - if in == nil { - continue - } - out := IntValueSlice(in) - assert.Len(t, out, len(in), "Unexpected len at idx %d", idx) - for i := range out { - if in[i] == nil { - assert.Empty(t, out[i], "Unexpected value at idx %d", idx) - } else { - assert.Equal(t, *(in[i]), out[i], "Unexpected value at idx %d", idx) - } - } - - out2 := IntSlice(out) - assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx) - for i := range out2 { - if in[i] == nil { - assert.Empty(t, *(out2[i]), "Unexpected value at idx %d", idx) - } else { - assert.Equal(t, in[i], out2[i], "Unexpected value at idx %d", idx) - } - } - } -} - -var testCasesIntMap = []map[string]int{ - {"a": 3, "b": 2, "c": 1}, -} - -func TestIntMap(t *testing.T) { - for idx, in := range testCasesIntMap { - if in == nil { - continue - } - out := IntMap(in) - assert.Len(t, out, len(in), "Unexpected len at idx %d", idx) - for i := range out { - assert.Equal(t, in[i], *(out[i]), "Unexpected value at idx %d", idx) - } - - out2 := IntValueMap(out) - assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx) - assert.Equal(t, in, out2, "Unexpected value at idx %d", idx) - } -} - -var testCasesInt64Slice = [][]int64{ - {1, 2, 3, 4}, -} - -func TestInt64Slice(t *testing.T) { - for idx, in := range testCasesInt64Slice { - if in == nil { - continue - } - out := Int64Slice(in) - assert.Len(t, out, len(in), "Unexpected len at idx %d", idx) - for i := range out { - assert.Equal(t, in[i], *(out[i]), "Unexpected value at idx %d", idx) - } - - out2 := Int64ValueSlice(out) - assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx) - assert.Equal(t, in, out2, "Unexpected value at idx %d", idx) - } -} - -var testCasesInt64ValueSlice = [][]*int64{} - -func TestInt64ValueSlice(t *testing.T) { - for idx, in := range testCasesInt64ValueSlice { - if in == nil { - continue - } - out := Int64ValueSlice(in) - assert.Len(t, out, len(in), "Unexpected len at idx %d", idx) - for i := range out { - if in[i] == nil { - assert.Empty(t, out[i], "Unexpected value at idx %d", idx) - } else { - assert.Equal(t, *(in[i]), out[i], "Unexpected value at idx %d", idx) - } - } - - out2 := Int64Slice(out) - assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx) - for i := range out2 { - if in[i] == nil { - assert.Empty(t, *(out2[i]), "Unexpected value at idx %d", idx) - } else { - assert.Equal(t, in[i], out2[i], "Unexpected value at idx %d", idx) - } - } - } -} - -var testCasesInt64Map = []map[string]int64{ - {"a": 3, "b": 2, "c": 1}, -} - -func TestInt64Map(t *testing.T) { - for idx, in := range testCasesInt64Map { - if in == nil { - continue - } - out := Int64Map(in) - assert.Len(t, out, len(in), "Unexpected len at idx %d", idx) - for i := range out { - assert.Equal(t, in[i], *(out[i]), "Unexpected value at idx %d", idx) - } - - out2 := Int64ValueMap(out) - assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx) - assert.Equal(t, in, out2, "Unexpected value at idx %d", idx) - } -} - -var testCasesFloat64Slice = [][]float64{ - {1, 2, 3, 4}, -} - -func TestFloat64Slice(t *testing.T) { - for idx, in := range testCasesFloat64Slice { - if in == nil { - continue - } - out := Float64Slice(in) - assert.Len(t, out, len(in), "Unexpected len at idx %d", idx) - for i := range out { - assert.Equal(t, in[i], *(out[i]), "Unexpected value at idx %d", idx) - } - - out2 := Float64ValueSlice(out) - assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx) - assert.Equal(t, in, out2, "Unexpected value at idx %d", idx) - } -} - -var testCasesUintSlice = [][]uint{ - {1, 2, 3, 4}, -} - -func TestUintSlice(t *testing.T) { - for idx, in := range testCasesUintSlice { - if in == nil { - continue - } - out := UintSlice(in) - assert.Len(t, out, len(in), "Unexpected len at idx %d", idx) - for i := range out { - assert.Equal(t, in[i], *(out[i]), "Unexpected value at idx %d", idx) - } - - out2 := UintValueSlice(out) - assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx) - assert.Equal(t, in, out2, "Unexpected value at idx %d", idx) - } -} - -var testCasesUintValueSlice = [][]*uint{} - -func TestUintValueSlice(t *testing.T) { - for idx, in := range testCasesUintValueSlice { - if in == nil { - continue - } - out := UintValueSlice(in) - assert.Len(t, out, len(in), "Unexpected len at idx %d", idx) - for i := range out { - if in[i] == nil { - assert.Empty(t, out[i], "Unexpected value at idx %d", idx) - } else { - assert.Equal(t, *(in[i]), out[i], "Unexpected value at idx %d", idx) - } - } - - out2 := UintSlice(out) - assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx) - for i := range out2 { - if in[i] == nil { - assert.Empty(t, *(out2[i]), "Unexpected value at idx %d", idx) - } else { - assert.Equal(t, in[i], out2[i], "Unexpected value at idx %d", idx) - } - } - } -} - -var testCasesUintMap = []map[string]uint{ - {"a": 3, "b": 2, "c": 1}, -} - -func TestUintMap(t *testing.T) { - for idx, in := range testCasesUintMap { - if in == nil { - continue - } - out := UintMap(in) - assert.Len(t, out, len(in), "Unexpected len at idx %d", idx) - for i := range out { - assert.Equal(t, in[i], *(out[i]), "Unexpected value at idx %d", idx) - } - - out2 := UintValueMap(out) - assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx) - assert.Equal(t, in, out2, "Unexpected value at idx %d", idx) - } -} - -var testCasesUint64Slice = [][]uint64{ - {1, 2, 3, 4}, -} - -func TestUint64Slice(t *testing.T) { - for idx, in := range testCasesUint64Slice { - if in == nil { - continue - } - out := Uint64Slice(in) - assert.Len(t, out, len(in), "Unexpected len at idx %d", idx) - for i := range out { - assert.Equal(t, in[i], *(out[i]), "Unexpected value at idx %d", idx) - } - - out2 := Uint64ValueSlice(out) - assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx) - assert.Equal(t, in, out2, "Unexpected value at idx %d", idx) - } -} - -var testCasesUint64ValueSlice = [][]*uint64{} - -func TestUint64ValueSlice(t *testing.T) { - for idx, in := range testCasesUint64ValueSlice { - if in == nil { - continue - } - out := Uint64ValueSlice(in) - assert.Len(t, out, len(in), "Unexpected len at idx %d", idx) - for i := range out { - if in[i] == nil { - assert.Empty(t, out[i], "Unexpected value at idx %d", idx) - } else { - assert.Equal(t, *(in[i]), out[i], "Unexpected value at idx %d", idx) - } - } - - out2 := Uint64Slice(out) - assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx) - for i := range out2 { - if in[i] == nil { - assert.Empty(t, *(out2[i]), "Unexpected value at idx %d", idx) - } else { - assert.Equal(t, in[i], out2[i], "Unexpected value at idx %d", idx) - } - } - } -} - -var testCasesUint64Map = []map[string]uint64{ - {"a": 3, "b": 2, "c": 1}, -} - -func TestUint64Map(t *testing.T) { - for idx, in := range testCasesUint64Map { - if in == nil { - continue - } - out := Uint64Map(in) - assert.Len(t, out, len(in), "Unexpected len at idx %d", idx) - for i := range out { - assert.Equal(t, in[i], *(out[i]), "Unexpected value at idx %d", idx) - } - - out2 := Uint64ValueMap(out) - assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx) - assert.Equal(t, in, out2, "Unexpected value at idx %d", idx) - } -} - -var testCasesFloat64ValueSlice = [][]*float64{} - -func TestFloat64ValueSlice(t *testing.T) { - for idx, in := range testCasesFloat64ValueSlice { - if in == nil { - continue - } - out := Float64ValueSlice(in) - assert.Len(t, out, len(in), "Unexpected len at idx %d", idx) - for i := range out { - if in[i] == nil { - assert.Empty(t, out[i], "Unexpected value at idx %d", idx) - } else { - assert.Equal(t, *(in[i]), out[i], "Unexpected value at idx %d", idx) - } - } - - out2 := Float64Slice(out) - assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx) - for i := range out2 { - if in[i] == nil { - assert.Empty(t, *(out2[i]), "Unexpected value at idx %d", idx) - } else { - assert.Equal(t, in[i], out2[i], "Unexpected value at idx %d", idx) - } - } - } -} - -var testCasesFloat64Map = []map[string]float64{ - {"a": 3, "b": 2, "c": 1}, -} - -func TestFloat64Map(t *testing.T) { - for idx, in := range testCasesFloat64Map { - if in == nil { - continue - } - out := Float64Map(in) - assert.Len(t, out, len(in), "Unexpected len at idx %d", idx) - for i := range out { - assert.Equal(t, in[i], *(out[i]), "Unexpected value at idx %d", idx) - } - - out2 := Float64ValueMap(out) - assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx) - assert.Equal(t, in, out2, "Unexpected value at idx %d", idx) - } -} - -var testCasesTimeSlice = [][]time.Time{ - {time.Now(), time.Now().AddDate(100, 0, 0)}, -} - -func TestTimeSlice(t *testing.T) { - for idx, in := range testCasesTimeSlice { - if in == nil { - continue - } - out := TimeSlice(in) - assert.Len(t, out, len(in), "Unexpected len at idx %d", idx) - for i := range out { - assert.Equal(t, in[i], *(out[i]), "Unexpected value at idx %d", idx) - } - - out2 := TimeValueSlice(out) - assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx) - assert.Equal(t, in, out2, "Unexpected value at idx %d", idx) - } -} - -var testCasesTimeValueSlice = [][]*time.Time{} - -func TestTimeValueSlice(t *testing.T) { - for idx, in := range testCasesTimeValueSlice { - if in == nil { - continue - } - out := TimeValueSlice(in) - assert.Len(t, out, len(in), "Unexpected len at idx %d", idx) - for i := range out { - if in[i] == nil { - assert.Empty(t, out[i], "Unexpected value at idx %d", idx) - } else { - assert.Equal(t, *(in[i]), out[i], "Unexpected value at idx %d", idx) - } - } - - out2 := TimeSlice(out) - assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx) - for i := range out2 { - if in[i] == nil { - assert.Empty(t, *(out2[i]), "Unexpected value at idx %d", idx) - } else { - assert.Equal(t, in[i], out2[i], "Unexpected value at idx %d", idx) - } - } - } -} - -var testCasesTimeMap = []map[string]time.Time{ - {"a": time.Now().AddDate(-100, 0, 0), "b": time.Now()}, -} - -func TestTimeMap(t *testing.T) { - for idx, in := range testCasesTimeMap { - if in == nil { - continue - } - out := TimeMap(in) - assert.Len(t, out, len(in), "Unexpected len at idx %d", idx) - for i := range out { - assert.Equal(t, in[i], *(out[i]), "Unexpected value at idx %d", idx) - } - - out2 := TimeValueMap(out) - assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx) - assert.Equal(t, in, out2, "Unexpected value at idx %d", idx) - } -} diff --git a/vendor/github.com/go-openapi/swag/json_test.go b/vendor/github.com/go-openapi/swag/json_test.go deleted file mode 100644 index a7d0d9821..000000000 --- a/vendor/github.com/go-openapi/swag/json_test.go +++ /dev/null @@ -1,163 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package swag - -import ( - "reflect" - "testing" - - "github.com/stretchr/testify/assert" -) - -type testNameStruct struct { - Name string `json:"name"` - NotTheSame int64 `json:"plain"` - Ignored string `json:"-"` -} - -func TestNameProvider(t *testing.T) { - - provider := NewNameProvider() - - var obj = testNameStruct{} - - nm, ok := provider.GetGoName(obj, "name") - assert.True(t, ok) - assert.Equal(t, "Name", nm) - - nm, ok = provider.GetGoName(obj, "plain") - assert.True(t, ok) - assert.Equal(t, "NotTheSame", nm) - - nm, ok = provider.GetGoName(obj, "doesNotExist") - assert.False(t, ok) - assert.Empty(t, nm) - - nm, ok = provider.GetGoName(obj, "ignored") - assert.False(t, ok) - assert.Empty(t, nm) - - tpe := reflect.TypeOf(obj) - nm, ok = provider.GetGoNameForType(tpe, "name") - assert.True(t, ok) - assert.Equal(t, "Name", nm) - - nm, ok = provider.GetGoNameForType(tpe, "plain") - assert.True(t, ok) - assert.Equal(t, "NotTheSame", nm) - - nm, ok = provider.GetGoNameForType(tpe, "doesNotExist") - assert.False(t, ok) - assert.Empty(t, nm) - - nm, ok = provider.GetGoNameForType(tpe, "ignored") - assert.False(t, ok) - assert.Empty(t, nm) - - ptr := &obj - nm, ok = provider.GetGoName(ptr, "name") - assert.True(t, ok) - assert.Equal(t, "Name", nm) - - nm, ok = provider.GetGoName(ptr, "plain") - assert.True(t, ok) - assert.Equal(t, "NotTheSame", nm) - - nm, ok = provider.GetGoName(ptr, "doesNotExist") - assert.False(t, ok) - assert.Empty(t, nm) - - nm, ok = provider.GetGoName(ptr, "ignored") - assert.False(t, ok) - assert.Empty(t, nm) - - nm, ok = provider.GetJSONName(obj, "Name") - assert.True(t, ok) - assert.Equal(t, "name", nm) - - nm, ok = provider.GetJSONName(obj, "NotTheSame") - assert.True(t, ok) - assert.Equal(t, "plain", nm) - - nm, ok = provider.GetJSONName(obj, "DoesNotExist") - assert.False(t, ok) - assert.Empty(t, nm) - - nm, ok = provider.GetJSONName(obj, "Ignored") - assert.False(t, ok) - assert.Empty(t, nm) - - nm, ok = provider.GetJSONNameForType(tpe, "Name") - assert.True(t, ok) - assert.Equal(t, "name", nm) - - nm, ok = provider.GetJSONNameForType(tpe, "NotTheSame") - assert.True(t, ok) - assert.Equal(t, "plain", nm) - - nm, ok = provider.GetJSONNameForType(tpe, "doesNotExist") - assert.False(t, ok) - assert.Empty(t, nm) - - nm, ok = provider.GetJSONNameForType(tpe, "Ignored") - assert.False(t, ok) - assert.Empty(t, nm) - - nm, ok = provider.GetJSONName(ptr, "Name") - assert.True(t, ok) - assert.Equal(t, "name", nm) - - nm, ok = provider.GetJSONName(ptr, "NotTheSame") - assert.True(t, ok) - assert.Equal(t, "plain", nm) - - nm, ok = provider.GetJSONName(ptr, "doesNotExist") - assert.False(t, ok) - assert.Empty(t, nm) - - nm, ok = provider.GetJSONName(ptr, "Ignored") - assert.False(t, ok) - assert.Empty(t, nm) - - nms := provider.GetJSONNames(ptr) - assert.Len(t, nms, 2) - - assert.Len(t, provider.index, 1) - -} - -func TestJSONConcatenation(t *testing.T) { - assert.Nil(t, ConcatJSON()) - assert.Equal(t, ConcatJSON([]byte(`{"id":1}`)), []byte(`{"id":1}`)) - assert.Equal(t, ConcatJSON([]byte(`{}`), []byte(`{}`)), []byte(`{}`)) - assert.Equal(t, ConcatJSON([]byte(`[]`), []byte(`[]`)), []byte(`[]`)) - assert.Equal(t, ConcatJSON([]byte(`{"id":1}`), []byte(`{"name":"Rachel"}`)), []byte(`{"id":1,"name":"Rachel"}`)) - assert.Equal(t, ConcatJSON([]byte(`[{"id":1}]`), []byte(`[{"name":"Rachel"}]`)), []byte(`[{"id":1},{"name":"Rachel"}]`)) - assert.Equal(t, ConcatJSON([]byte(`{}`), []byte(`{"name":"Rachel"}`)), []byte(`{"name":"Rachel"}`)) - assert.Equal(t, ConcatJSON([]byte(`[]`), []byte(`[{"name":"Rachel"}]`)), []byte(`[{"name":"Rachel"}]`)) - assert.Equal(t, ConcatJSON([]byte(`{"id":1}`), []byte(`{}`)), []byte(`{"id":1}`)) - assert.Equal(t, ConcatJSON([]byte(`[{"id":1}]`), []byte(`[]`)), []byte(`[{"id":1}]`)) - assert.Equal(t, ConcatJSON([]byte(`{}`), []byte(`{}`), []byte(`{}`)), []byte(`{}`)) - assert.Equal(t, ConcatJSON([]byte(`[]`), []byte(`[]`), []byte(`[]`)), []byte(`[]`)) - assert.Equal(t, ConcatJSON([]byte(`{"id":1}`), []byte(`{"name":"Rachel"}`), []byte(`{"age":32}`)), []byte(`{"id":1,"name":"Rachel","age":32}`)) - assert.Equal(t, ConcatJSON([]byte(`[{"id":1}]`), []byte(`[{"name":"Rachel"}]`), []byte(`[{"age":32}]`)), []byte(`[{"id":1},{"name":"Rachel"},{"age":32}]`)) - assert.Equal(t, ConcatJSON([]byte(`{}`), []byte(`{"name":"Rachel"}`), []byte(`{"age":32}`)), []byte(`{"name":"Rachel","age":32}`)) - assert.Equal(t, ConcatJSON([]byte(`[]`), []byte(`[{"name":"Rachel"}]`), []byte(`[{"age":32}]`)), []byte(`[{"name":"Rachel"},{"age":32}]`)) - assert.Equal(t, ConcatJSON([]byte(`{"id":1}`), []byte(`{}`), []byte(`{"age":32}`)), []byte(`{"id":1,"age":32}`)) - assert.Equal(t, ConcatJSON([]byte(`[{"id":1}]`), []byte(`[]`), []byte(`[{"age":32}]`)), []byte(`[{"id":1},{"age":32}]`)) - assert.Equal(t, ConcatJSON([]byte(`{"id":1}`), []byte(`{"name":"Rachel"}`), []byte(`{}`)), []byte(`{"id":1,"name":"Rachel"}`)) - assert.Equal(t, ConcatJSON([]byte(`[{"id":1}]`), []byte(`[{"name":"Rachel"}]`), []byte(`[]`)), []byte(`[{"id":1},{"name":"Rachel"}]`)) - -} diff --git a/vendor/github.com/go-openapi/swag/loading_test.go b/vendor/github.com/go-openapi/swag/loading_test.go deleted file mode 100644 index 7b8bdf48d..000000000 --- a/vendor/github.com/go-openapi/swag/loading_test.go +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package swag - -import ( - "net/http" - "net/http/httptest" - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestLoadFromHTTP(t *testing.T) { - - _, err := LoadFromFileOrHTTP("httx://12394:abd") - assert.Error(t, err) - - serv := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { - rw.WriteHeader(http.StatusNotFound) - })) - defer serv.Close() - - _, err = LoadFromFileOrHTTP(serv.URL) - assert.Error(t, err) - - ts2 := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { - rw.WriteHeader(http.StatusOK) - rw.Write([]byte("the content")) - })) - defer ts2.Close() - - d, err := LoadFromFileOrHTTP(ts2.URL) - assert.NoError(t, err) - assert.Equal(t, []byte("the content"), d) -} diff --git a/vendor/github.com/go-openapi/swag/net_test.go b/vendor/github.com/go-openapi/swag/net_test.go deleted file mode 100644 index 041db60a2..000000000 --- a/vendor/github.com/go-openapi/swag/net_test.go +++ /dev/null @@ -1,30 +0,0 @@ -package swag - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestSplitHostPort(t *testing.T) { - data := []struct { - Input string - Host string - Port int - Err bool - }{ - {"localhost:3933", "localhost", 3933, false}, - {"localhost:yellow", "", -1, true}, - {"localhost", "", -1, true}, - {"localhost:", "", -1, true}, - {"localhost:3933", "localhost", 3933, false}, - } - - for _, e := range data { - h, p, err := SplitHostPort(e.Input) - if (!e.Err && assert.NoError(t, err)) || (e.Err && assert.Error(t, err)) { - assert.Equal(t, e.Host, h) - assert.Equal(t, e.Port, p) - } - } -} diff --git a/vendor/github.com/go-openapi/swag/path_test.go b/vendor/github.com/go-openapi/swag/path_test.go deleted file mode 100644 index 743bba534..000000000 --- a/vendor/github.com/go-openapi/swag/path_test.go +++ /dev/null @@ -1,118 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package swag - -import ( - "io/ioutil" - "os" - "path/filepath" - "path" - "runtime" - "testing" - - "github.com/stretchr/testify/assert" -) - -func makeDirStructure(t *testing.T, tgt string) (string, string, error) { - if tgt == "" { - tgt = "pkgpaths" - } - td, err := ioutil.TempDir("", tgt) - if err != nil { - return "", "", err - } - td2, err := ioutil.TempDir("", tgt+"-2") - if err != nil { - return "", "", err - } - realPath := filepath.Join(td, "src", "foo", "bar") - if err := os.MkdirAll(realPath, os.ModePerm); err != nil { - return "", "", err - } - linkPathBase := filepath.Join(td, "src", "baz") - if err := os.MkdirAll(linkPathBase, os.ModePerm); err != nil { - return "", "", err - } - linkPath := filepath.Join(linkPathBase, "das") - if err := os.Symlink(realPath, linkPath); err != nil { - return "", "", err - } - - realPath = filepath.Join(td2, "src", "fuu", "bir") - if err := os.MkdirAll(realPath, os.ModePerm); err != nil { - return "", "", err - } - linkPathBase = filepath.Join(td2, "src", "biz") - if err := os.MkdirAll(linkPathBase, os.ModePerm); err != nil { - return "", "", err - } - linkPath = filepath.Join(linkPathBase, "dis") - if err := os.Symlink(realPath, linkPath); err != nil { - return "", "", err - } - return td, td2, nil -} - -func TestFindPackage(t *testing.T) { - pth, pth2, err := makeDirStructure(t, "") - if err != nil { - t.Fatal(err) - } - defer func() { - os.RemoveAll(pth) - os.RemoveAll(pth2) - }() - - searchPath := pth + string(filepath.ListSeparator) + pth2 - // finds package when real name mentioned - pkg := FindInSearchPath(searchPath, "foo/bar") - assert.NotEmpty(t, pkg) - assertPath(t, path.Join(pth, "src", "foo", "bar"), pkg) - // finds package when real name is mentioned in secondary - pkg = FindInSearchPath(searchPath, "fuu/bir") - assert.NotEmpty(t, pkg) - assertPath(t, path.Join(pth2, "src", "fuu", "bir"), pkg) - // finds package when symlinked - pkg = FindInSearchPath(searchPath, "baz/das") - assert.NotEmpty(t, pkg) - assertPath(t, path.Join(pth, "src", "foo", "bar"), pkg) - // finds package when symlinked in secondary - pkg = FindInSearchPath(searchPath, "biz/dis") - assert.NotEmpty(t, pkg) - assertPath(t, path.Join(pth2, "src", "fuu", "bir"), pkg) - // return empty string when nothing is found - pkg = FindInSearchPath(searchPath, "not/there") - assert.Empty(t, pkg) -} - -func assertPath(t testing.TB, expected, actual string) bool { - fp, err := filepath.EvalSymlinks(expected) - if assert.NoError(t, err) { - return assert.Equal(t, fp, actual) - } - return true -} - -func TestFullGOPATH(t *testing.T) { - os.Unsetenv(GOPATHKey) - ngp := "/some/where:/other/place" - os.Setenv(GOPATHKey, ngp) - - ogp := os.Getenv(GOPATHKey) - defer os.Setenv(GOPATHKey, ogp) - - expected := ngp + ":" + runtime.GOROOT() - assert.Equal(t, expected, FullGoSearchPath()) -} diff --git a/vendor/github.com/go-openapi/swag/util_test.go b/vendor/github.com/go-openapi/swag/util_test.go deleted file mode 100644 index 5db20b90f..000000000 --- a/vendor/github.com/go-openapi/swag/util_test.go +++ /dev/null @@ -1,277 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package swag - -import ( - "fmt" - "strings" - "testing" - "time" - - "github.com/stretchr/testify/assert" -) - -type translationSample struct { - str, out string -} - -func titleize(s string) string { return strings.ToTitle(s[:1]) + lower(s[1:]) } - -func TestToGoName(t *testing.T) { - samples := []translationSample{ - {"sample text", "SampleText"}, - {"sample-text", "SampleText"}, - {"sample_text", "SampleText"}, - {"sampleText", "SampleText"}, - {"sample 2 Text", "Sample2Text"}, - {"findThingById", "FindThingByID"}, - {"日本語sample 2 Text", "X日本語sample2Text"}, - {"日本語findThingById", "X日本語findThingByID"}, - } - - for k := range commonInitialisms { - samples = append(samples, - translationSample{"sample " + lower(k) + " text", "Sample" + k + "Text"}, - translationSample{"sample-" + lower(k) + "-text", "Sample" + k + "Text"}, - translationSample{"sample_" + lower(k) + "_text", "Sample" + k + "Text"}, - translationSample{"sample" + titleize(k) + "Text", "Sample" + k + "Text"}, - translationSample{"sample " + lower(k), "Sample" + k}, - translationSample{"sample-" + lower(k), "Sample" + k}, - translationSample{"sample_" + lower(k), "Sample" + k}, - translationSample{"sample" + titleize(k), "Sample" + k}, - translationSample{"sample " + titleize(k) + " text", "Sample" + k + "Text"}, - translationSample{"sample-" + titleize(k) + "-text", "Sample" + k + "Text"}, - translationSample{"sample_" + titleize(k) + "_text", "Sample" + k + "Text"}, - ) - } - - for _, sample := range samples { - assert.Equal(t, sample.out, ToGoName(sample.str)) - } -} - -func TestContainsStringsCI(t *testing.T) { - list := []string{"hello", "world", "and", "such"} - - assert.True(t, ContainsStringsCI(list, "hELLo")) - assert.True(t, ContainsStringsCI(list, "world")) - assert.True(t, ContainsStringsCI(list, "AND")) - assert.False(t, ContainsStringsCI(list, "nuts")) -} - -func TestSplitByFormat(t *testing.T) { - expected := []string{"one", "two", "three"} - for _, fmt := range []string{"csv", "pipes", "tsv", "ssv", "multi"} { - - var actual []string - switch fmt { - case "multi": - assert.Nil(t, SplitByFormat("", fmt)) - assert.Nil(t, SplitByFormat("blah", fmt)) - case "ssv": - actual = SplitByFormat(strings.Join(expected, " "), fmt) - assert.EqualValues(t, expected, actual) - case "pipes": - actual = SplitByFormat(strings.Join(expected, "|"), fmt) - assert.EqualValues(t, expected, actual) - case "tsv": - actual = SplitByFormat(strings.Join(expected, "\t"), fmt) - assert.EqualValues(t, expected, actual) - default: - actual = SplitByFormat(strings.Join(expected, ","), fmt) - assert.EqualValues(t, expected, actual) - } - } -} - -func TestJoinByFormat(t *testing.T) { - for _, fmt := range []string{"csv", "pipes", "tsv", "ssv", "multi"} { - - lval := []string{"one", "two", "three"} - var expected []string - switch fmt { - case "multi": - expected = lval - case "ssv": - expected = []string{strings.Join(lval, " ")} - case "pipes": - expected = []string{strings.Join(lval, "|")} - case "tsv": - expected = []string{strings.Join(lval, "\t")} - default: - expected = []string{strings.Join(lval, ",")} - } - assert.Nil(t, JoinByFormat(nil, fmt)) - assert.EqualValues(t, expected, JoinByFormat(lval, fmt)) - } -} - -func TestToFileName(t *testing.T) { - samples := []translationSample{ - {"SampleText", "sample_text"}, - {"FindThingByID", "find_thing_by_id"}, - } - - for k := range commonInitialisms { - samples = append(samples, - translationSample{"Sample" + k + "Text", "sample_" + lower(k) + "_text"}, - ) - } - - for _, sample := range samples { - assert.Equal(t, sample.out, ToFileName(sample.str)) - } -} - -func TestToCommandName(t *testing.T) { - samples := []translationSample{ - {"SampleText", "sample-text"}, - {"FindThingByID", "find-thing-by-id"}, - } - - for k := range commonInitialisms { - samples = append(samples, - translationSample{"Sample" + k + "Text", "sample-" + lower(k) + "-text"}, - ) - } - - for _, sample := range samples { - assert.Equal(t, sample.out, ToCommandName(sample.str)) - } -} - -func TestToHumanName(t *testing.T) { - samples := []translationSample{ - {"SampleText", "sample text"}, - {"FindThingByID", "find thing by ID"}, - } - - for k := range commonInitialisms { - samples = append(samples, - translationSample{"Sample" + k + "Text", "sample " + k + " text"}, - ) - } - - for _, sample := range samples { - assert.Equal(t, sample.out, ToHumanNameLower(sample.str)) - } -} - -func TestToJSONName(t *testing.T) { - samples := []translationSample{ - {"SampleText", "sampleText"}, - {"FindThingByID", "findThingById"}, - } - - for k := range commonInitialisms { - samples = append(samples, - translationSample{"Sample" + k + "Text", "sample" + titleize(k) + "Text"}, - ) - } - - for _, sample := range samples { - assert.Equal(t, sample.out, ToJSONName(sample.str)) - } -} - -type SimpleZeroes struct { - ID string - Name string -} -type ZeroesWithTime struct { - Time time.Time -} - -func TestIsZero(t *testing.T) { - var strs [5]string - var strss []string - var a int - var b int8 - var c int16 - var d int32 - var e int64 - var f uint - var g uint8 - var h uint16 - var i uint32 - var j uint64 - var k map[string]string - var l interface{} - var m *SimpleZeroes - var n string - var o SimpleZeroes - var p ZeroesWithTime - var q time.Time - data := []struct { - Data interface{} - Expected bool - }{ - {a, true}, - {b, true}, - {c, true}, - {d, true}, - {e, true}, - {f, true}, - {g, true}, - {h, true}, - {i, true}, - {j, true}, - {k, true}, - {l, true}, - {m, true}, - {n, true}, - {o, true}, - {p, true}, - {q, true}, - {strss, true}, - {strs, true}, - {"", true}, - {nil, true}, - {1, false}, - {0, true}, - {int8(1), false}, - {int8(0), true}, - {int16(1), false}, - {int16(0), true}, - {int32(1), false}, - {int32(0), true}, - {int64(1), false}, - {int64(0), true}, - {uint(1), false}, - {uint(0), true}, - {uint8(1), false}, - {uint8(0), true}, - {uint16(1), false}, - {uint16(0), true}, - {uint32(1), false}, - {uint32(0), true}, - {uint64(1), false}, - {uint64(0), true}, - {0.0, true}, - {0.1, false}, - {float32(0.0), true}, - {float32(0.1), false}, - {float64(0.0), true}, - {float64(0.1), false}, - {[...]string{}, true}, - {[...]string{"hello"}, false}, - {[]string(nil), true}, - {[]string{"a"}, false}, - } - - for _, it := range data { - assert.Equal(t, it.Expected, IsZero(it.Data), fmt.Sprintf("%#v", it.Data)) - } -} diff --git a/vendor/github.com/go-openapi/swag/yaml_test.go b/vendor/github.com/go-openapi/swag/yaml_test.go deleted file mode 100644 index ee32fab7d..000000000 --- a/vendor/github.com/go-openapi/swag/yaml_test.go +++ /dev/null @@ -1,444 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package swag - -import ( - "encoding/json" - "errors" - "net/http" - "net/http/httptest" - "testing" - - yaml "gopkg.in/yaml.v2" - - "github.com/stretchr/testify/assert" -) - -type failJSONMarhal struct { -} - -func (f failJSONMarhal) MarshalJSON() ([]byte, error) { - return nil, errors.New("expected") -} - -func TestLoadHTTPBytes(t *testing.T) { - _, err := LoadFromFileOrHTTP("httx://12394:abd") - assert.Error(t, err) - - serv := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { - rw.WriteHeader(http.StatusNotFound) - })) - defer serv.Close() - - _, err = LoadFromFileOrHTTP(serv.URL) - assert.Error(t, err) - - ts2 := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { - rw.WriteHeader(http.StatusOK) - rw.Write([]byte("the content")) - })) - defer ts2.Close() - - d, err := LoadFromFileOrHTTP(ts2.URL) - assert.NoError(t, err) - assert.Equal(t, []byte("the content"), d) -} - -func TestYAMLToJSON(t *testing.T) { - - sd := `--- -1: the int key value -name: a string value -'y': some value -` - var data yaml.MapSlice - yaml.Unmarshal([]byte(sd), &data) - - d, err := YAMLToJSON(data) - if assert.NoError(t, err) { - assert.Equal(t, `{"1":"the int key value","name":"a string value","y":"some value"}`, string(d)) - } - - data = append(data, yaml.MapItem{Key: true, Value: "the bool value"}) - d, err = YAMLToJSON(data) - assert.Error(t, err) - assert.Nil(t, d) - - data = data[:len(data)-1] - - tag := yaml.MapSlice{{Key: "name", Value: "tag name"}} - data = append(data, yaml.MapItem{Key: "tag", Value: tag}) - - d, err = YAMLToJSON(data) - assert.NoError(t, err) - assert.Equal(t, `{"1":"the int key value","name":"a string value","y":"some value","tag":{"name":"tag name"}}`, string(d)) - - tag = yaml.MapSlice{{Key: true, Value: "bool tag name"}} - data = append(data[:len(data)-1], yaml.MapItem{Key: "tag", Value: tag}) - - d, err = YAMLToJSON(data) - assert.Error(t, err) - assert.Nil(t, d) - - var lst []interface{} - lst = append(lst, "hello") - - d, err = YAMLToJSON(lst) - assert.NoError(t, err) - assert.Equal(t, []byte(`["hello"]`), []byte(d)) - - lst = append(lst, data) - - d, err = YAMLToJSON(lst) - assert.Error(t, err) - assert.Nil(t, d) - - // _, err := yamlToJSON(failJSONMarhal{}) - // assert.Error(t, err) - - _, err = BytesToYAMLDoc([]byte("- name: hello\n")) - assert.Error(t, err) - - dd, err := BytesToYAMLDoc([]byte("description: 'object created'\n")) - assert.NoError(t, err) - - d, err = YAMLToJSON(dd) - assert.NoError(t, err) - assert.Equal(t, json.RawMessage(`{"description":"object created"}`), d) -} - -func TestLoadStrategy(t *testing.T) { - - loader := func(p string) ([]byte, error) { - return []byte(yamlPetStore), nil - } - remLoader := func(p string) ([]byte, error) { - return []byte("not it"), nil - } - - ld := LoadStrategy("blah", loader, remLoader) - b, _ := ld("") - assert.Equal(t, []byte(yamlPetStore), b) - - serv := httptest.NewServer(http.HandlerFunc(yamlPestoreServer)) - defer serv.Close() - - s, err := YAMLDoc(serv.URL) - assert.NoError(t, err) - assert.NotNil(t, s) - - ts2 := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { - rw.WriteHeader(http.StatusNotFound) - rw.Write([]byte("\n")) - })) - defer ts2.Close() - _, err = YAMLDoc(ts2.URL) - assert.Error(t, err) -} - -var yamlPestoreServer = func(rw http.ResponseWriter, r *http.Request) { - rw.WriteHeader(http.StatusOK) - rw.Write([]byte(yamlPetStore)) -} - -func TestWithYKey(t *testing.T) { - doc, err := BytesToYAMLDoc([]byte(withYKey)) - if assert.NoError(t, err) { - _, err := YAMLToJSON(doc) - if assert.Error(t, err) { - doc, err := BytesToYAMLDoc([]byte(withQuotedYKey)) - if assert.NoError(t, err) { - jsond, err := YAMLToJSON(doc) - if assert.NoError(t, err) { - var yt struct { - Definitions struct { - Viewbox struct { - Properties struct { - Y struct { - Type string `json:"type"` - } `json:"y"` - } `json:"properties"` - } `json:"viewbox"` - } `json:"definitions"` - } - if assert.NoError(t, json.Unmarshal(jsond, &yt)) { - assert.Equal(t, "integer", yt.Definitions.Viewbox.Properties.Y.Type) - } - } - } - } - - } -} - -const withQuotedYKey = `consumes: -- application/json -definitions: - viewBox: - type: object - properties: - x: - type: integer - format: int16 - # y -> types don't match: expect map key string or int get: bool - "y": - type: integer - format: int16 - width: - type: integer - format: int16 - height: - type: integer - format: int16 -info: - description: Test RESTful APIs - title: Test Server - version: 1.0.0 -basePath: /api -paths: - /test: - get: - operationId: findAll - parameters: - - name: since - in: query - type: integer - format: int64 - - name: limit - in: query - type: integer - format: int32 - default: 20 - responses: - 200: - description: Array[Trigger] - schema: - type: array - items: - $ref: "#/definitions/viewBox" -produces: -- application/json -schemes: -- https -swagger: "2.0" -` - -const withYKey = `consumes: -- application/json -definitions: - viewBox: - type: object - properties: - x: - type: integer - format: int16 - # y -> types don't match: expect map key string or int get: bool - y: - type: integer - format: int16 - width: - type: integer - format: int16 - height: - type: integer - format: int16 -info: - description: Test RESTful APIs - title: Test Server - version: 1.0.0 -basePath: /api -paths: - /test: - get: - operationId: findAll - parameters: - - name: since - in: query - type: integer - format: int64 - - name: limit - in: query - type: integer - format: int32 - default: 20 - responses: - 200: - description: Array[Trigger] - schema: - type: array - items: - $ref: "#/definitions/viewBox" -produces: -- application/json -schemes: -- https -swagger: "2.0" -` - -const yamlPetStore = `swagger: '2.0' -info: - version: '1.0.0' - title: Swagger Petstore - description: A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification - termsOfService: http://helloreverb.com/terms/ - contact: - name: Swagger API team - email: foo@example.com - url: http://swagger.io - license: - name: MIT - url: http://opensource.org/licenses/MIT -host: petstore.swagger.wordnik.com -basePath: /api -schemes: - - http -consumes: - - application/json -produces: - - application/json -paths: - /pets: - get: - description: Returns all pets from the system that the user has access to - operationId: findPets - produces: - - application/json - - application/xml - - text/xml - - text/html - parameters: - - name: tags - in: query - description: tags to filter by - required: false - type: array - items: - type: string - collectionFormat: csv - - name: limit - in: query - description: maximum number of results to return - required: false - type: integer - format: int32 - responses: - '200': - description: pet response - schema: - type: array - items: - $ref: '#/definitions/pet' - default: - description: unexpected error - schema: - $ref: '#/definitions/errorModel' - post: - description: Creates a new pet in the store. Duplicates are allowed - operationId: addPet - produces: - - application/json - parameters: - - name: pet - in: body - description: Pet to add to the store - required: true - schema: - $ref: '#/definitions/newPet' - responses: - '200': - description: pet response - schema: - $ref: '#/definitions/pet' - default: - description: unexpected error - schema: - $ref: '#/definitions/errorModel' - /pets/{id}: - get: - description: Returns a user based on a single ID, if the user does not have access to the pet - operationId: findPetById - produces: - - application/json - - application/xml - - text/xml - - text/html - parameters: - - name: id - in: path - description: ID of pet to fetch - required: true - type: integer - format: int64 - responses: - '200': - description: pet response - schema: - $ref: '#/definitions/pet' - default: - description: unexpected error - schema: - $ref: '#/definitions/errorModel' - delete: - description: deletes a single pet based on the ID supplied - operationId: deletePet - parameters: - - name: id - in: path - description: ID of pet to delete - required: true - type: integer - format: int64 - responses: - '204': - description: pet deleted - default: - description: unexpected error - schema: - $ref: '#/definitions/errorModel' -definitions: - pet: - required: - - id - - name - properties: - id: - type: integer - format: int64 - name: - type: string - tag: - type: string - newPet: - allOf: - - $ref: '#/definitions/pet' - - required: - - name - properties: - id: - type: integer - format: int64 - name: - type: string - errorModel: - required: - - code - - message - properties: - code: - type: integer - format: int32 - message: - type: string -` diff --git a/vendor/github.com/go-stack/stack/.travis.yml b/vendor/github.com/go-stack/stack/.travis.yml deleted file mode 100644 index e91cc9a0a..000000000 --- a/vendor/github.com/go-stack/stack/.travis.yml +++ /dev/null @@ -1,13 +0,0 @@ -language: go -sudo: false -go: - - 1.7 - - 1.8 - - 1.9 - - tip - -before_install: - - go get github.com/mattn/goveralls - -script: - - goveralls -service=travis-ci diff --git a/vendor/github.com/go-stack/stack/README.md b/vendor/github.com/go-stack/stack/README.md deleted file mode 100644 index f11ccccaa..000000000 --- a/vendor/github.com/go-stack/stack/README.md +++ /dev/null @@ -1,38 +0,0 @@ -[![GoDoc](https://godoc.org/github.com/go-stack/stack?status.svg)](https://godoc.org/github.com/go-stack/stack) -[![Go Report Card](https://goreportcard.com/badge/go-stack/stack)](https://goreportcard.com/report/go-stack/stack) -[![TravisCI](https://travis-ci.org/go-stack/stack.svg?branch=master)](https://travis-ci.org/go-stack/stack) -[![Coverage Status](https://coveralls.io/repos/github/go-stack/stack/badge.svg?branch=master)](https://coveralls.io/github/go-stack/stack?branch=master) - -# stack - -Package stack implements utilities to capture, manipulate, and format call -stacks. It provides a simpler API than package runtime. - -The implementation takes care of the minutia and special cases of interpreting -the program counter (pc) values returned by runtime.Callers. - -## Versioning - -Package stack publishes releases via [semver](http://semver.org/) compatible Git -tags prefixed with a single 'v'. The master branch always contains the latest -release. The develop branch contains unreleased commits. - -## Formatting - -Package stack's types implement fmt.Formatter, which provides a simple and -flexible way to declaratively configure formatting when used with logging or -error tracking packages. - -```go -func DoTheThing() { - c := stack.Caller(0) - log.Print(c) // "source.go:10" - log.Printf("%+v", c) // "pkg/path/source.go:10" - log.Printf("%n", c) // "DoTheThing" - - s := stack.Trace().TrimRuntime() - log.Print(s) // "[source.go:15 caller.go:42 main.go:14]" -} -``` - -See the docs for all of the supported formatting options. diff --git a/vendor/github.com/go-stack/stack/format_test.go b/vendor/github.com/go-stack/stack/format_test.go deleted file mode 100644 index 013ad6736..000000000 --- a/vendor/github.com/go-stack/stack/format_test.go +++ /dev/null @@ -1,21 +0,0 @@ -// +build go1.2 - -package stack_test - -import ( - "fmt" - - "github.com/go-stack/stack" -) - -func Example_callFormat() { - logCaller("%+s") - logCaller("%v %[1]n()") - // Output: - // github.com/go-stack/stack/format_test.go - // format_test.go:13 Example_callFormat() -} - -func logCaller(format string) { - fmt.Printf(format+"\n", stack.Caller(1)) -} diff --git a/vendor/github.com/go-stack/stack/stack-go19_test.go b/vendor/github.com/go-stack/stack/stack-go19_test.go deleted file mode 100644 index d7aeea258..000000000 --- a/vendor/github.com/go-stack/stack/stack-go19_test.go +++ /dev/null @@ -1,67 +0,0 @@ -// +build go1.9 - -package stack_test - -import ( - "runtime" - "testing" - - "github.com/go-stack/stack" -) - -func TestCallerInlinedPanic(t *testing.T) { - t.Parallel() - - var line int - - defer func() { - if recover() != nil { - var pcs [32]uintptr - n := runtime.Callers(1, pcs[:]) - frames := runtime.CallersFrames(pcs[:n]) - // count frames to runtime.sigpanic - panicIdx := 0 - for { - f, more := frames.Next() - if f.Function == "runtime.sigpanic" { - break - } - panicIdx++ - if !more { - t.Fatal("no runtime.sigpanic entry on the stack") - } - } - - c := stack.Caller(panicIdx) - if got, want := c.Frame().Function, "runtime.sigpanic"; got != want { - t.Errorf("sigpanic frame: got name == %v, want name == %v", got, want) - } - - c1 := stack.Caller(panicIdx + 1) - if got, want := c1.Frame().Function, "github.com/go-stack/stack_test.inlinablePanic"; got != want { - t.Errorf("TestCallerInlinedPanic frame: got name == %v, want name == %v", got, want) - } - if got, want := c1.Frame().Line, line; got != want { - t.Errorf("TestCallerInlinedPanic frame: got line == %v, want line == %v", got, want) - } - } - }() - - doPanic(t, &line) - t.Fatal("failed to panic") -} - -func doPanic(t *testing.T, panicLine *int) { - _, _, line, ok := runtime.Caller(0) - *panicLine = line + 11 // adjust to match line of panic below - if !ok { - t.Fatal("runtime.Caller(0) failed") - } - inlinablePanic() -} - -func inlinablePanic() { - // Initiate a sigpanic. - var x *uintptr - _ = *x -} diff --git a/vendor/github.com/go-stack/stack/stack_test.go b/vendor/github.com/go-stack/stack/stack_test.go deleted file mode 100644 index 44f3a7de1..000000000 --- a/vendor/github.com/go-stack/stack/stack_test.go +++ /dev/null @@ -1,582 +0,0 @@ -package stack_test - -import ( - "fmt" - "io/ioutil" - "path" - "path/filepath" - "reflect" - "runtime" - "strings" - "testing" - - "github.com/go-stack/stack" -) - -func TestCaller(t *testing.T) { - t.Parallel() - - c := stack.Caller(0) - _, file, line, ok := runtime.Caller(0) - line-- - if !ok { - t.Fatal("runtime.Caller(0) failed") - } - - if got, want := c.Frame().File, file; got != want { - t.Errorf("got file == %v, want file == %v", got, want) - } - - if got, want := c.Frame().Line, line; got != want { - t.Errorf("got line == %v, want line == %v", got, want) - } -} - -func f3(f1 func() stack.Call) stack.Call { - return f2(f1) -} - -func f2(f1 func() stack.Call) stack.Call { - return f1() -} - -func TestCallerMidstackInlined(t *testing.T) { - t.Parallel() - - _, _, line, ok := runtime.Caller(0) - line -= 10 // adjust to return f1() line inside f2() - if !ok { - t.Fatal("runtime.Caller(0) failed") - } - - c := f3(func() stack.Call { - return stack.Caller(2) - }) - - if got, want := c.Frame().Line, line; got != want { - t.Errorf("got line == %v, want line == %v", got, want) - } - if got, want := c.Frame().Function, "github.com/go-stack/stack_test.f3"; got != want { - t.Errorf("got func name == %v, want func name == %v", got, want) - } -} - -func TestCallerPanic(t *testing.T) { - t.Parallel() - - var ( - line int - ok bool - ) - - defer func() { - if recover() != nil { - var pcs [32]uintptr - n := runtime.Callers(1, pcs[:]) - frames := runtime.CallersFrames(pcs[:n]) - // count frames to runtime.sigpanic - panicIdx := 0 - for { - f, more := frames.Next() - if f.Function == "runtime.sigpanic" { - break - } - panicIdx++ - if !more { - t.Fatal("no runtime.sigpanic entry on the stack") - } - } - c := stack.Caller(panicIdx) - if got, want := c.Frame().Function, "runtime.sigpanic"; got != want { - t.Errorf("sigpanic frame: got name == %v, want name == %v", got, want) - } - c1 := stack.Caller(panicIdx + 1) - if got, want := c1.Frame().Function, "github.com/go-stack/stack_test.TestCallerPanic"; got != want { - t.Errorf("TestCallerPanic frame: got name == %v, want name == %v", got, want) - } - if got, want := c1.Frame().Line, line; got != want { - t.Errorf("TestCallerPanic frame: got line == %v, want line == %v", got, want) - } - } - }() - - _, _, line, ok = runtime.Caller(0) - line += 7 // adjust to match line of panic below - if !ok { - t.Fatal("runtime.Caller(0) failed") - } - // Initiate a sigpanic. - var x *uintptr - _ = *x -} - -type tholder struct { - trace func() stack.CallStack -} - -func (th *tholder) traceLabyrinth() stack.CallStack { - for { - return th.trace() - } -} - -func TestTrace(t *testing.T) { - t.Parallel() - - _, _, line, ok := runtime.Caller(0) - if !ok { - t.Fatal("runtime.Caller(0) failed") - } - - fh := tholder{ - trace: func() stack.CallStack { - cs := stack.Trace() - return cs - }, - } - - cs := fh.traceLabyrinth() - - lines := []int{line + 7, line - 7, line + 12} - - for i, line := range lines { - if got, want := cs[i].Frame().Line, line; got != want { - t.Errorf("got line[%d] == %v, want line[%d] == %v", i, got, i, want) - } - } -} - -// Test stack handling originating from a sigpanic. -func TestTracePanic(t *testing.T) { - t.Parallel() - - var ( - line int - ok bool - ) - - defer func() { - if recover() != nil { - trace := stack.Trace() - - // find runtime.sigpanic - panicIdx := -1 - for i, c := range trace { - if c.Frame().Function == "runtime.sigpanic" { - panicIdx = i - break - } - } - if panicIdx == -1 { - t.Fatal("no runtime.sigpanic entry on the stack") - } - if got, want := trace[panicIdx].Frame().Function, "runtime.sigpanic"; got != want { - t.Errorf("sigpanic frame: got name == %v, want name == %v", got, want) - } - if got, want := trace[panicIdx+1].Frame().Function, "github.com/go-stack/stack_test.TestTracePanic"; got != want { - t.Errorf("TestTracePanic frame: got name == %v, want name == %v", got, want) - } - if got, want := trace[panicIdx+1].Frame().Line, line; got != want { - t.Errorf("TestTracePanic frame: got line == %v, want line == %v", got, want) - } - } - }() - - _, _, line, ok = runtime.Caller(0) - line += 7 // adjust to match line of panic below - if !ok { - t.Fatal("runtime.Caller(0) failed") - } - // Initiate a sigpanic. - var x *uintptr - _ = *x -} - -const importPath = "github.com/go-stack/stack" - -type testType struct{} - -func (tt testType) testMethod() (c stack.Call, file string, line int, ok bool) { - c = stack.Caller(0) - _, file, line, ok = runtime.Caller(0) - line-- - return -} - -func TestCallFormat(t *testing.T) { - t.Parallel() - - c := stack.Caller(0) - _, file, line, ok := runtime.Caller(0) - line-- - if !ok { - t.Fatal("runtime.Caller(0) failed") - } - relFile := path.Join(importPath, filepath.Base(file)) - - c2, file2, line2, ok2 := testType{}.testMethod() - if !ok2 { - t.Fatal("runtime.Caller(0) failed") - } - relFile2 := path.Join(importPath, filepath.Base(file2)) - - data := []struct { - c stack.Call - desc string - fmt string - out string - }{ - {stack.Call{}, "error", "%s", "%!s(NOFUNC)"}, - - {c, "func", "%s", path.Base(file)}, - {c, "func", "%+s", relFile}, - {c, "func", "%#s", file}, - {c, "func", "%d", fmt.Sprint(line)}, - {c, "func", "%n", "TestCallFormat"}, - {c, "func", "%+n", "github.com/go-stack/stack_test.TestCallFormat"}, - {c, "func", "%k", "stack_test"}, - {c, "func", "%+k", "github.com/go-stack/stack_test"}, - {c, "func", "%v", fmt.Sprint(path.Base(file), ":", line)}, - {c, "func", "%+v", fmt.Sprint(relFile, ":", line)}, - {c, "func", "%#v", fmt.Sprint(file, ":", line)}, - - {c2, "meth", "%s", path.Base(file2)}, - {c2, "meth", "%+s", relFile2}, - {c2, "meth", "%#s", file2}, - {c2, "meth", "%d", fmt.Sprint(line2)}, - {c2, "meth", "%n", "testType.testMethod"}, - {c2, "meth", "%+n", "github.com/go-stack/stack_test.testType.testMethod"}, - {c2, "meth", "%k", "stack_test"}, - {c2, "meth", "%+k", "github.com/go-stack/stack_test"}, - {c2, "meth", "%v", fmt.Sprint(path.Base(file2), ":", line2)}, - {c2, "meth", "%+v", fmt.Sprint(relFile2, ":", line2)}, - {c2, "meth", "%#v", fmt.Sprint(file2, ":", line2)}, - } - - for _, d := range data { - got := fmt.Sprintf(d.fmt, d.c) - if got != d.out { - t.Errorf("fmt.Sprintf(%q, Call(%s)) = %s, want %s", d.fmt, d.desc, got, d.out) - } - } -} - -func TestCallString(t *testing.T) { - t.Parallel() - - c := stack.Caller(0) - _, file, line, ok := runtime.Caller(0) - line-- - if !ok { - t.Fatal("runtime.Caller(0) failed") - } - - c2, file2, line2, ok2 := testType{}.testMethod() - if !ok2 { - t.Fatal("runtime.Caller(0) failed") - } - - data := []struct { - c stack.Call - desc string - out string - }{ - {stack.Call{}, "error", "%!v(NOFUNC)"}, - {c, "func", fmt.Sprint(path.Base(file), ":", line)}, - {c2, "meth", fmt.Sprint(path.Base(file2), ":", line2)}, - } - - for _, d := range data { - got := d.c.String() - if got != d.out { - t.Errorf("got %s, want %s", got, d.out) - } - } -} - -func TestCallMarshalText(t *testing.T) { - t.Parallel() - - c := stack.Caller(0) - _, file, line, ok := runtime.Caller(0) - line-- - if !ok { - t.Fatal("runtime.Caller(0) failed") - } - - c2, file2, line2, ok2 := testType{}.testMethod() - if !ok2 { - t.Fatal("runtime.Caller(0) failed") - } - - data := []struct { - c stack.Call - desc string - out []byte - err error - }{ - {stack.Call{}, "error", nil, stack.ErrNoFunc}, - {c, "func", []byte(fmt.Sprint(path.Base(file), ":", line)), nil}, - {c2, "meth", []byte(fmt.Sprint(path.Base(file2), ":", line2)), nil}, - } - - for _, d := range data { - text, err := d.c.MarshalText() - if got, want := err, d.err; got != want { - t.Errorf("%s: got err %v, want err %v", d.desc, got, want) - } - if got, want := text, d.out; !reflect.DeepEqual(got, want) { - t.Errorf("%s: got %s, want %s", d.desc, got, want) - } - } -} - -func TestCallStackString(t *testing.T) { - cs, line0 := getTrace(t) - _, file, line1, ok := runtime.Caller(0) - line1-- - if !ok { - t.Fatal("runtime.Caller(0) failed") - } - file = path.Base(file) - if got, want := cs.String(), fmt.Sprintf("[%s:%d %s:%d]", file, line0, file, line1); got != want { - t.Errorf("\n got %v\nwant %v", got, want) - } -} - -func TestCallStackMarshalText(t *testing.T) { - cs, line0 := getTrace(t) - _, file, line1, ok := runtime.Caller(0) - line1-- - if !ok { - t.Fatal("runtime.Caller(0) failed") - } - file = path.Base(file) - text, _ := cs.MarshalText() - if got, want := text, []byte(fmt.Sprintf("[%s:%d %s:%d]", file, line0, file, line1)); !reflect.DeepEqual(got, want) { - t.Errorf("\n got %v\nwant %v", got, want) - } -} - -func getTrace(t *testing.T) (stack.CallStack, int) { - cs := stack.Trace().TrimRuntime() - _, _, line, ok := runtime.Caller(0) - line-- - if !ok { - t.Fatal("runtime.Caller(0) failed") - } - return cs, line -} - -func TestTrimAbove(t *testing.T) { - trace := trimAbove() - if got, want := len(trace), 2; got != want { - t.Fatalf("got len(trace) == %v, want %v, trace: %n", got, want, trace) - } - if got, want := fmt.Sprintf("%n", trace[1]), "TestTrimAbove"; got != want { - t.Errorf("got %q, want %q", got, want) - } -} - -func trimAbove() stack.CallStack { - call := stack.Caller(1) - trace := stack.Trace() - return trace.TrimAbove(call) -} - -func TestTrimBelow(t *testing.T) { - trace := trimBelow() - if got, want := fmt.Sprintf("%n", trace[0]), "TestTrimBelow"; got != want { - t.Errorf("got %q, want %q", got, want) - } -} - -func trimBelow() stack.CallStack { - call := stack.Caller(1) - trace := stack.Trace() - return trace.TrimBelow(call) -} - -func TestTrimRuntime(t *testing.T) { - trace := stack.Trace().TrimRuntime() - if got, want := len(trace), 1; got != want { - t.Errorf("got len(trace) == %v, want %v, goroot: %q, trace: %#v", got, want, runtime.GOROOT(), trace) - } -} - -func BenchmarkCallVFmt(b *testing.B) { - c := stack.Caller(0) - b.ResetTimer() - for i := 0; i < b.N; i++ { - fmt.Fprint(ioutil.Discard, c) - } -} - -func BenchmarkCallPlusVFmt(b *testing.B) { - c := stack.Caller(0) - b.ResetTimer() - for i := 0; i < b.N; i++ { - fmt.Fprintf(ioutil.Discard, "%+v", c) - } -} - -func BenchmarkCallSharpVFmt(b *testing.B) { - c := stack.Caller(0) - b.ResetTimer() - for i := 0; i < b.N; i++ { - fmt.Fprintf(ioutil.Discard, "%#v", c) - } -} - -func BenchmarkCallSFmt(b *testing.B) { - c := stack.Caller(0) - b.ResetTimer() - for i := 0; i < b.N; i++ { - fmt.Fprintf(ioutil.Discard, "%s", c) - } -} - -func BenchmarkCallPlusSFmt(b *testing.B) { - c := stack.Caller(0) - b.ResetTimer() - for i := 0; i < b.N; i++ { - fmt.Fprintf(ioutil.Discard, "%+s", c) - } -} - -func BenchmarkCallSharpSFmt(b *testing.B) { - c := stack.Caller(0) - b.ResetTimer() - for i := 0; i < b.N; i++ { - fmt.Fprintf(ioutil.Discard, "%#s", c) - } -} - -func BenchmarkCallDFmt(b *testing.B) { - c := stack.Caller(0) - b.ResetTimer() - for i := 0; i < b.N; i++ { - fmt.Fprintf(ioutil.Discard, "%d", c) - } -} - -func BenchmarkCallNFmt(b *testing.B) { - c := stack.Caller(0) - b.ResetTimer() - for i := 0; i < b.N; i++ { - fmt.Fprintf(ioutil.Discard, "%n", c) - } -} - -func BenchmarkCallPlusNFmt(b *testing.B) { - c := stack.Caller(0) - b.ResetTimer() - for i := 0; i < b.N; i++ { - fmt.Fprintf(ioutil.Discard, "%+n", c) - } -} - -func BenchmarkCaller(b *testing.B) { - for i := 0; i < b.N; i++ { - stack.Caller(0) - } -} - -func BenchmarkTrace(b *testing.B) { - for i := 0; i < b.N; i++ { - stack.Trace() - } -} - -func deepStack(depth int, b *testing.B) stack.CallStack { - if depth > 0 { - return deepStack(depth-1, b) - } - b.StartTimer() - s := stack.Trace() - return s -} - -func BenchmarkTrace10(b *testing.B) { - for i := 0; i < b.N; i++ { - b.StopTimer() - deepStack(10, b) - } -} - -func BenchmarkTrace50(b *testing.B) { - b.StopTimer() - for i := 0; i < b.N; i++ { - deepStack(50, b) - } -} - -func BenchmarkTrace100(b *testing.B) { - b.StopTimer() - for i := 0; i < b.N; i++ { - deepStack(100, b) - } -} - -//////////////// -// Benchmark functions followed by formatting -//////////////// - -func BenchmarkCallerAndVFmt(b *testing.B) { - for i := 0; i < b.N; i++ { - fmt.Fprint(ioutil.Discard, stack.Caller(0)) - } -} - -func BenchmarkTraceAndVFmt(b *testing.B) { - for i := 0; i < b.N; i++ { - fmt.Fprint(ioutil.Discard, stack.Trace()) - } -} - -func BenchmarkTrace10AndVFmt(b *testing.B) { - for i := 0; i < b.N; i++ { - b.StopTimer() - fmt.Fprint(ioutil.Discard, deepStack(10, b)) - } -} - -//////////////// -// Baseline against package runtime. -//////////////// - -func BenchmarkRuntimeCaller(b *testing.B) { - for i := 0; i < b.N; i++ { - runtime.Caller(0) - } -} - -func BenchmarkRuntimeCallerAndFmt(b *testing.B) { - for i := 0; i < b.N; i++ { - _, file, line, _ := runtime.Caller(0) - const sep = "/" - if i := strings.LastIndex(file, sep); i != -1 { - file = file[i+len(sep):] - } - fmt.Fprint(ioutil.Discard, file, ":", line) - } -} - -func BenchmarkFuncForPC(b *testing.B) { - pc, _, _, _ := runtime.Caller(0) - pc-- - b.ResetTimer() - for i := 0; i < b.N; i++ { - runtime.FuncForPC(pc) - } -} - -func BenchmarkFuncFileLine(b *testing.B) { - pc, _, _, _ := runtime.Caller(0) - pc-- - fn := runtime.FuncForPC(pc) - b.ResetTimer() - for i := 0; i < b.N; i++ { - fn.FileLine(pc) - } -} diff --git a/vendor/github.com/gogo/protobuf/.gitignore b/vendor/github.com/gogo/protobuf/.gitignore deleted file mode 100644 index 76009479d..000000000 --- a/vendor/github.com/gogo/protobuf/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -._* -*.js -*.js.map diff --git a/vendor/github.com/gogo/protobuf/.mailmap b/vendor/github.com/gogo/protobuf/.mailmap deleted file mode 100644 index bc0010219..000000000 --- a/vendor/github.com/gogo/protobuf/.mailmap +++ /dev/null @@ -1,8 +0,0 @@ -Walter Schulze Walter Schulze -Walter Schulze -Walter Schulze awalterschulze -Walter Schulze awalterschulze@gmail.com -John Tuley -Anton Povarov -Denis Smirnov dennwc -DongYun Kang \ No newline at end of file diff --git a/vendor/github.com/gogo/protobuf/.travis.yml b/vendor/github.com/gogo/protobuf/.travis.yml deleted file mode 100644 index 7f69fba09..000000000 --- a/vendor/github.com/gogo/protobuf/.travis.yml +++ /dev/null @@ -1,20 +0,0 @@ -env: - - PROTOBUF_VERSION=2.6.1 - - PROTOBUF_VERSION=3.0.2 - - PROTOBUF_VERSION=3.4.0 - -before_install: - - ./install-protobuf.sh - - PATH=/home/travis/bin:$PATH protoc --version - -script: - - PATH=/home/travis/bin:$PATH make buildserverall - - echo $TRAVIS_GO_VERSION - - if [ "$TRAVIS_GO_VERSION" == 1.9 ] && [[ "$PROTOBUF_VERSION" == 3.4.0 ]]; then ! git status --porcelain | read || (git status; git diff; exit 1); fi - -language: go - -go: - - 1.8.3 - - 1.9 - diff --git a/vendor/github.com/gogo/protobuf/Makefile b/vendor/github.com/gogo/protobuf/Makefile deleted file mode 100644 index 17e329367..000000000 --- a/vendor/github.com/gogo/protobuf/Makefile +++ /dev/null @@ -1,161 +0,0 @@ -# Protocol Buffers for Go with Gadgets -# -# Copyright (c) 2013, The GoGo Authors. All rights reserved. -# http://github.com/gogo/protobuf -# -# 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. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -GO_VERSION:=$(shell go version) - -.PHONY: nuke regenerate tests clean install gofmt vet contributors - -all: clean install regenerate install tests errcheck vet - -buildserverall: clean install regenerate install tests vet js - -install: - go install ./proto - go install ./gogoproto - go install ./jsonpb - go install ./protoc-gen-gogo - go install ./protoc-gen-gofast - go install ./protoc-gen-gogofast - go install ./protoc-gen-gogofaster - go install ./protoc-gen-gogoslick - go install ./protoc-gen-gostring - go install ./protoc-min-version - go install ./protoc-gen-combo - go install ./gogoreplace - -clean: - go clean ./... - -nuke: - go clean -i ./... - -gofmt: - gofmt -l -s -w . - -regenerate: - make -C protoc-gen-gogo/descriptor regenerate - make -C protoc-gen-gogo/plugin regenerate - make -C protoc-gen-gogo/testdata regenerate - make -C gogoproto regenerate - make -C proto/testdata regenerate - make -C jsonpb/jsonpb_test_proto regenerate - make -C _conformance regenerate - make -C types regenerate - make -C test regenerate - make -C test/example regenerate - make -C test/unrecognized regenerate - make -C test/group regenerate - make -C test/unrecognizedgroup regenerate - make -C test/enumstringer regenerate - make -C test/unmarshalmerge regenerate - make -C test/moredefaults regenerate - make -C test/issue8 regenerate - make -C test/enumprefix regenerate - make -C test/enumcustomname regenerate - make -C test/packed regenerate - make -C test/protosize regenerate - make -C test/tags regenerate - make -C test/oneof regenerate - make -C test/oneof3 regenerate - make -C test/theproto3 regenerate - make -C test/mapdefaults regenerate - make -C test/mapsproto2 regenerate - make -C test/issue42order regenerate - make -C proto generate-test-pbs - make -C test/importdedup regenerate - make -C test/custombytesnonstruct regenerate - make -C test/required regenerate - make -C test/casttype regenerate - make -C test/castvalue regenerate - make -C vanity/test regenerate - make -C test/sizeunderscore regenerate - make -C test/issue34 regenerate - make -C test/empty-issue70 regenerate - make -C test/indeximport-issue72 regenerate - make -C test/fuzztests regenerate - make -C test/oneofembed regenerate - make -C test/asymetric-issue125 regenerate - make -C test/filedotname regenerate - make -C test/nopackage regenerate - make -C test/types regenerate - make -C test/proto3extension regenerate - make -C test/stdtypes regenerate - make -C test/data regenerate - make -C test/typedecl regenerate - make -C test/issue260 regenerate - make -C test/issue261 regenerate - make -C test/issue262 regenerate - make -C test/issue312 regenerate - make -C test/enumdecl regenerate - make -C test/typedecl_all regenerate - make -C test/enumdecl_all regenerate - make -C test/int64support regenerate - make -C test/issue322 regenerate - make -C test/issue330 regenerate - make gofmt - -tests: - go build ./test/enumprefix - go test ./... - (cd test/stdtypes && make test) - -vet: - go vet ./... - go tool vet --shadow . - -errcheck: - go get github.com/kisielk/errcheck - errcheck ./test/... - -drone: - sudo apt-get install protobuf-compiler - (cd $(GOPATH)/src/github.com/gogo/protobuf && make buildserverall) - -testall: - go get -u github.com/golang/protobuf/proto - make -C protoc-gen-gogo/testdata test - make -C vanity/test test - make -C test/registration test - make tests - -bench: - go get golang.org/x/tools/cmd/benchcmp - (cd test/mixbench && go build .) - ./test/mixbench/mixbench - -contributors: - git log --format='%aN <%aE>' | sort -fu > CONTRIBUTORS - -js: -ifeq (go1.9, $(findstring go1.9, $(GO_VERSION))) - go get -u github.com/gopherjs/gopherjs - gopherjs build github.com/gogo/protobuf/protoc-gen-gogo -endif - -update: - (cd protobuf && make update) diff --git a/vendor/github.com/gogo/protobuf/README b/vendor/github.com/gogo/protobuf/README deleted file mode 100644 index c82082723..000000000 --- a/vendor/github.com/gogo/protobuf/README +++ /dev/null @@ -1,257 +0,0 @@ -GoGoProtobuf http://github.com/gogo/protobuf extends -GoProtobuf http://github.com/golang/protobuf - -# Go support for Protocol Buffers - -Google's data interchange format. -Copyright 2010 The Go Authors. -https://github.com/golang/protobuf - -This package and the code it generates requires at least Go 1.4. - -This software implements Go bindings for protocol buffers. For -information about protocol buffers themselves, see - https://developers.google.com/protocol-buffers/ - -## Installation ## - -To use this software, you must: -- Install the standard C++ implementation of protocol buffers from - https://developers.google.com/protocol-buffers/ -- Of course, install the Go compiler and tools from - https://golang.org/ - See - https://golang.org/doc/install - for details or, if you are using gccgo, follow the instructions at - https://golang.org/doc/install/gccgo -- Grab the code from the repository and install the proto package. - The simplest way is to run `go get -u github.com/golang/protobuf/protoc-gen-go`. - The compiler plugin, protoc-gen-go, will be installed in $GOBIN, - defaulting to $GOPATH/bin. It must be in your $PATH for the protocol - compiler, protoc, to find it. - -This software has two parts: a 'protocol compiler plugin' that -generates Go source files that, once compiled, can access and manage -protocol buffers; and a library that implements run-time support for -encoding (marshaling), decoding (unmarshaling), and accessing protocol -buffers. - -There is support for gRPC in Go using protocol buffers. -See the note at the bottom of this file for details. - -There are no insertion points in the plugin. - -GoGoProtobuf provides extensions for protocol buffers and GoProtobuf -see http://github.com/gogo/protobuf/gogoproto/doc.go - -## Using protocol buffers with Go ## - -Once the software is installed, there are two steps to using it. -First you must compile the protocol buffer definitions and then import -them, with the support library, into your program. - -To compile the protocol buffer definition, run protoc with the --gogo_out -parameter set to the directory you want to output the Go code to. - - protoc --gogo_out=. *.proto - -The generated files will be suffixed .pb.go. See the Test code below -for an example using such a file. - -The package comment for the proto library contains text describing -the interface provided in Go for protocol buffers. Here is an edited -version. - -If you are using any gogo.proto extensions you will need to specify the -proto_path to include the descriptor.proto and gogo.proto. -gogo.proto is located in github.com/gogo/protobuf/gogoproto -This should be fine, since your import is the same. -descriptor.proto is located in either github.com/gogo/protobuf/protobuf -or code.google.com/p/protobuf/trunk/src/ -Its import is google/protobuf/descriptor.proto so it might need some help. - - protoc --gogo_out=. -I=.:github.com/gogo/protobuf/protobuf *.proto - -========== - -The proto package converts data structures to and from the -wire format of protocol buffers. It works in concert with the -Go source code generated for .proto files by the protocol compiler. - -A summary of the properties of the protocol buffer interface -for a protocol buffer variable v: - - - Names are turned from camel_case to CamelCase for export. - - There are no methods on v to set fields; just treat - them as structure fields. - - There are getters that return a field's value if set, - and return the field's default value if unset. - The getters work even if the receiver is a nil message. - - The zero value for a struct is its correct initialization state. - All desired fields must be set before marshaling. - - A Reset() method will restore a protobuf struct to its zero state. - - Non-repeated fields are pointers to the values; nil means unset. - That is, optional or required field int32 f becomes F *int32. - - Repeated fields are slices. - - Helper functions are available to aid the setting of fields. - Helpers for getting values are superseded by the - GetFoo methods and their use is deprecated. - msg.Foo = proto.String("hello") // set field - - Constants are defined to hold the default values of all fields that - have them. They have the form Default_StructName_FieldName. - Because the getter methods handle defaulted values, - direct use of these constants should be rare. - - Enums are given type names and maps from names to values. - Enum values are prefixed with the enum's type name. Enum types have - a String method, and a Enum method to assist in message construction. - - Nested groups and enums have type names prefixed with the name of - the surrounding message type. - - Extensions are given descriptor names that start with E_, - followed by an underscore-delimited list of the nested messages - that contain it (if any) followed by the CamelCased name of the - extension field itself. HasExtension, ClearExtension, GetExtension - and SetExtension are functions for manipulating extensions. - - Oneof field sets are given a single field in their message, - with distinguished wrapper types for each possible field value. - - Marshal and Unmarshal are functions to encode and decode the wire format. - -When the .proto file specifies `syntax="proto3"`, there are some differences: - - - Non-repeated fields of non-message type are values instead of pointers. - - Enum types do not get an Enum method. - -Consider file test.proto, containing - -```proto - package example; - - enum FOO { X = 17; }; - - message Test { - required string label = 1; - optional int32 type = 2 [default=77]; - repeated int64 reps = 3; - optional group OptionalGroup = 4 { - required string RequiredField = 5; - } - } -``` - -To create and play with a Test object from the example package, - -```go - package main - - import ( - "log" - - "github.com/gogo/protobuf/proto" - "path/to/example" - ) - - func main() { - test := &example.Test { - Label: proto.String("hello"), - Type: proto.Int32(17), - Reps: []int64{1, 2, 3}, - Optionalgroup: &example.Test_OptionalGroup { - RequiredField: proto.String("good bye"), - }, - } - data, err := proto.Marshal(test) - if err != nil { - log.Fatal("marshaling error: ", err) - } - newTest := &example.Test{} - err = proto.Unmarshal(data, newTest) - if err != nil { - log.Fatal("unmarshaling error: ", err) - } - // Now test and newTest contain the same data. - if test.GetLabel() != newTest.GetLabel() { - log.Fatalf("data mismatch %q != %q", test.GetLabel(), newTest.GetLabel()) - } - // etc. - } -``` - - -## Parameters ## - -To pass extra parameters to the plugin, use a comma-separated -parameter list separated from the output directory by a colon: - - - protoc --gogo_out=plugins=grpc,import_path=mypackage:. *.proto - - -- `import_prefix=xxx` - a prefix that is added onto the beginning of - all imports. Useful for things like generating protos in a - subdirectory, or regenerating vendored protobufs in-place. -- `import_path=foo/bar` - used as the package if no input files - declare `go_package`. If it contains slashes, everything up to the - rightmost slash is ignored. -- `plugins=plugin1+plugin2` - specifies the list of sub-plugins to - load. The only plugin in this repo is `grpc`. -- `Mfoo/bar.proto=quux/shme` - declares that foo/bar.proto is - associated with Go package quux/shme. This is subject to the - import_prefix parameter. - -## gRPC Support ## - -If a proto file specifies RPC services, protoc-gen-go can be instructed to -generate code compatible with gRPC (http://www.grpc.io/). To do this, pass -the `plugins` parameter to protoc-gen-go; the usual way is to insert it into -the --go_out argument to protoc: - - protoc --gogo_out=plugins=grpc:. *.proto - -## Compatibility ## - -The library and the generated code are expected to be stable over time. -However, we reserve the right to make breaking changes without notice for the -following reasons: - -- Security. A security issue in the specification or implementation may come to - light whose resolution requires breaking compatibility. We reserve the right - to address such security issues. -- Unspecified behavior. There are some aspects of the Protocol Buffers - specification that are undefined. Programs that depend on such unspecified - behavior may break in future releases. -- Specification errors or changes. If it becomes necessary to address an - inconsistency, incompleteness, or change in the Protocol Buffers - specification, resolving the issue could affect the meaning or legality of - existing programs. We reserve the right to address such issues, including - updating the implementations. -- Bugs. If the library has a bug that violates the specification, a program - that depends on the buggy behavior may break if the bug is fixed. We reserve - the right to fix such bugs. -- Adding methods or fields to generated structs. These may conflict with field - names that already exist in a schema, causing applications to break. When the - code generator encounters a field in the schema that would collide with a - generated field or method name, the code generator will append an underscore - to the generated field or method name. -- Adding, removing, or changing methods or fields in generated structs that - start with `XXX`. These parts of the generated code are exported out of - necessity, but should not be considered part of the public API. -- Adding, removing, or changing unexported symbols in generated code. - -Any breaking changes outside of these will be announced 6 months in advance to -protobuf@googlegroups.com. - -You should, whenever possible, use generated code created by the `protoc-gen-go` -tool built at the same commit as the `proto` package. The `proto` package -declares package-level constants in the form `ProtoPackageIsVersionX`. -Application code and generated code may depend on one of these constants to -ensure that compilation will fail if the available version of the proto library -is too old. Whenever we make a change to the generated code that requires newer -library support, in the same commit we will increment the version number of the -generated code and declare a new package-level constant whose name incorporates -the latest version number. Removing a compatibility constant is considered a -breaking change and would be subject to the announcement policy stated above. - -## Plugins ## - -The `protoc-gen-go/generator` package exposes a plugin interface, -which is used by the gRPC code generation. This interface is not -supported and is subject to incompatible changes without notice. diff --git a/vendor/github.com/gogo/protobuf/Readme.md b/vendor/github.com/gogo/protobuf/Readme.md deleted file mode 100644 index b8eb4d14e..000000000 --- a/vendor/github.com/gogo/protobuf/Readme.md +++ /dev/null @@ -1,122 +0,0 @@ -# Protocol Buffers for Go with Gadgets - -[![Build Status](https://travis-ci.org/gogo/protobuf.svg?branch=master)](https://travis-ci.org/gogo/protobuf) - -gogoprotobuf is a fork of golang/protobuf with extra code generation features. - -This code generation is used to achieve: - - - fast marshalling and unmarshalling - - more canonical Go structures - - goprotobuf compatibility - - less typing by optionally generating extra helper code - - peace of mind by optionally generating test and benchmark code - - other serialization formats - -Keeping track of how up to date gogoprotobuf is relative to golang/protobuf is done in this -issue - -## Users - -These projects use gogoprotobuf: - - - etcd - blog - sample proto file - - spacemonkey - blog - - badoo - sample proto file - - mesos-go - sample proto file - - heka - the switch from golang/protobuf to gogo/protobuf when it was still on code.google.com - - cockroachdb - sample proto file - - go-ipfs - sample proto file - - rkive-go - sample proto file - - dropbox - - srclib - sample proto file - - adyoulike - - cloudfoundry - sample proto file - - kubernetes - go2idl built on top of gogoprotobuf - - dgraph - release notes - benchmarks - - centrifugo - release notes - blog - - docker swarmkit - sample proto file - - nats.io - go-nats-streaming - - tidb - Communication between tidb and tikv - - protoactor-go - vanity command that also generates actors from service definitions - - containerd - vanity command with custom field names that conforms to the golang convention. - - nakama - - proteus - - carbonzipper stack - - SendGrid - -Please let us know if you are using gogoprotobuf by posting on our GoogleGroup. - -### Mentioned - - - Cloudflare - go serialization talk - Albert Strasheim - - GopherCon 2014 Writing High Performance Databases in Go by Ben Johnson - - alecthomas' go serialization benchmarks - -## Getting Started - -There are several ways to use gogoprotobuf, but for all you need to install go and protoc. -After that you can choose: - - - Speed - - More Speed and more generated code - - Most Speed and most customization - -### Installation - -To install it, you must first have Go (at least version 1.6.3) installed (see [http://golang.org/doc/install](http://golang.org/doc/install)). Go 1.8.3 and 1.9 are continuously tested. - -Next, install the standard protocol buffer implementation from [https://github.com/google/protobuf](https://github.com/google/protobuf). -Most versions from 2.3.1 should not give any problems, but 2.6.1, 3.0.2 and 3.4.0 are continuously tested. - -### Speed - -Install the protoc-gen-gofast binary - - go get github.com/gogo/protobuf/protoc-gen-gofast - -Use it to generate faster marshaling and unmarshaling go code for your protocol buffers. - - protoc --gofast_out=. myproto.proto - -This does not allow you to use any of the other gogoprotobuf [extensions](https://github.com/gogo/protobuf/blob/master/extensions.md). - -### More Speed and more generated code - -Fields without pointers cause less time in the garbage collector. -More code generation results in more convenient methods. - -Other binaries are also included: - - protoc-gen-gogofast (same as gofast, but imports gogoprotobuf) - protoc-gen-gogofaster (same as gogofast, without XXX_unrecognized, less pointer fields) - protoc-gen-gogoslick (same as gogofaster, but with generated string, gostring and equal methods) - -Installing any of these binaries is easy. Simply run: - - go get github.com/gogo/protobuf/proto - go get github.com/gogo/protobuf/{binary} - go get github.com/gogo/protobuf/gogoproto - -These binaries allow you to using gogoprotobuf [extensions](https://github.com/gogo/protobuf/blob/master/extensions.md). - -### Most Speed and most customization - -Customizing the fields of the messages to be the fields that you actually want to use removes the need to copy between the structs you use and structs you use to serialize. -gogoprotobuf also offers more serialization formats and generation of tests and even more methods. - -Please visit the [extensions](https://github.com/gogo/protobuf/blob/master/extensions.md) page for more documentation. - -Install protoc-gen-gogo: - - go get github.com/gogo/protobuf/proto - go get github.com/gogo/protobuf/jsonpb - go get github.com/gogo/protobuf/protoc-gen-gogo - go get github.com/gogo/protobuf/gogoproto - -## GRPC - -It works the same as golang/protobuf, simply specify the plugin. -Here is an example using gofast: - - protoc --gofast_out=plugins=grpc:. my.proto diff --git a/vendor/github.com/gogo/protobuf/bench.md b/vendor/github.com/gogo/protobuf/bench.md deleted file mode 100644 index 16da66ad2..000000000 --- a/vendor/github.com/gogo/protobuf/bench.md +++ /dev/null @@ -1,190 +0,0 @@ -# Benchmarks - -## How to reproduce - -For a comparison run: - - make bench - -followed by [benchcmp](http://code.google.com/p/go/source/browse/misc/benchcmp benchcmp) on the resulting files: - - $GOROOT/misc/benchcmp $GOPATH/src/github.com/gogo/protobuf/test/mixbench/marshal.txt $GOPATH/src/github.com/gogo/protobuf/test/mixbench/marshaler.txt - $GOROOT/misc/benchcmp $GOPATH/src/github.com/gogo/protobuf/test/mixbench/unmarshal.txt $GOPATH/src/github.com/gogo/protobuf/test/mixbench/unmarshaler.txt - -Benchmarks ran on Revision: 11c56be39364 - -June 2013 - -Processor 2,66 GHz Intel Core i7 - -Memory 8 GB 1067 MHz DDR3 - -## Marshaler - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
benchmarkold ns/opnew ns/opdelta
BenchmarkNidOptNativeProtoMarshal2656889-66.53%
BenchmarkNinOptNativeProtoMarshal26511015-61.71%
BenchmarkNidRepNativeProtoMarshal4266112519-70.65%
BenchmarkNinRepNativeProtoMarshal4230612354-70.80%
BenchmarkNidRepPackedNativeProtoMarshal3414811902-65.15%
BenchmarkNinRepPackedNativeProtoMarshal3337511969-64.14%
BenchmarkNidOptStructProtoMarshal71483727-47.86%
BenchmarkNinOptStructProtoMarshal69563481-49.96%
BenchmarkNidRepStructProtoMarshal4655119492-58.13%
BenchmarkNinRepStructProtoMarshal4671519043-59.24%
BenchmarkNidEmbeddedStructProtoMarshal52312050-60.81%
BenchmarkNinEmbeddedStructProtoMarshal46652000-57.13%
BenchmarkNidNestedStructProtoMarshal181106103604-42.79%
BenchmarkNinNestedStructProtoMarshal182053102069-43.93%
BenchmarkNidOptCustomProtoMarshal1209310-74.36%
BenchmarkNinOptCustomProtoMarshal1435277-80.70%
BenchmarkNidRepCustomProtoMarshal4126763-81.51%
BenchmarkNinRepCustomProtoMarshal3972769-80.64%
BenchmarkNinOptNativeUnionProtoMarshal973303-68.86%
BenchmarkNinOptStructUnionProtoMarshal1536521-66.08%
BenchmarkNinEmbeddedStructUnionProtoMarshal2327884-62.01%
BenchmarkNinNestedStructUnionProtoMarshal2070743-64.11%
BenchmarkTreeProtoMarshal1554838-46.07%
BenchmarkOrBranchProtoMarshal31562012-36.25%
BenchmarkAndBranchProtoMarshal31831996-37.29%
BenchmarkLeafProtoMarshal965606-37.20%
BenchmarkDeepTreeProtoMarshal23161283-44.60%
BenchmarkADeepBranchProtoMarshal27191492-45.13%
BenchmarkAndDeepBranchProtoMarshal46632922-37.34%
BenchmarkDeepLeafProtoMarshal18491016-45.05%
BenchmarkNilProtoMarshal43976-82.53%
BenchmarkNidOptEnumProtoMarshal514152-70.43%
BenchmarkNinOptEnumProtoMarshal550158-71.27%
BenchmarkNidRepEnumProtoMarshal647207-68.01%
BenchmarkNinRepEnumProtoMarshal662213-67.82%
BenchmarkTimerProtoMarshal934271-70.99%
BenchmarkMyExtendableProtoMarshal608185-69.57%
BenchmarkOtherExtenableProtoMarshal1112332-70.14%
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
benchmarkold MB/snew MB/sspeedup
BenchmarkNidOptNativeProtoMarshal126.86378.862.99x
BenchmarkNinOptNativeProtoMarshal114.27298.422.61x
BenchmarkNidRepNativeProtoMarshal164.25561.203.42x
BenchmarkNinRepNativeProtoMarshal166.10568.233.42x
BenchmarkNidRepPackedNativeProtoMarshal99.10283.972.87x
BenchmarkNinRepPackedNativeProtoMarshal101.30282.312.79x
BenchmarkNidOptStructProtoMarshal176.83339.071.92x
BenchmarkNinOptStructProtoMarshal163.59326.572.00x
BenchmarkNidRepStructProtoMarshal178.84427.492.39x
BenchmarkNinRepStructProtoMarshal178.70437.692.45x
BenchmarkNidEmbeddedStructProtoMarshal124.24317.562.56x
BenchmarkNinEmbeddedStructProtoMarshal132.03307.992.33x
BenchmarkNidNestedStructProtoMarshal192.91337.861.75x
BenchmarkNinNestedStructProtoMarshal192.44344.451.79x
BenchmarkNidOptCustomProtoMarshal29.77116.033.90x
BenchmarkNinOptCustomProtoMarshal22.29115.385.18x
BenchmarkNidRepCustomProtoMarshal35.14189.805.40x
BenchmarkNinRepCustomProtoMarshal36.50188.405.16x
BenchmarkNinOptNativeUnionProtoMarshal32.87105.393.21x
BenchmarkNinOptStructUnionProtoMarshal66.40195.762.95x
BenchmarkNinEmbeddedStructUnionProtoMarshal93.24245.262.63x
BenchmarkNinNestedStructUnionProtoMarshal57.49160.062.78x
BenchmarkTreeProtoMarshal137.64255.121.85x
BenchmarkOrBranchProtoMarshal137.80216.101.57x
BenchmarkAndBranchProtoMarshal136.64217.891.59x
BenchmarkLeafProtoMarshal214.48341.531.59x
BenchmarkDeepTreeProtoMarshal95.85173.031.81x
BenchmarkADeepBranchProtoMarshal82.73150.781.82x
BenchmarkAndDeepBranchProtoMarshal96.72153.981.59x
BenchmarkDeepLeafProtoMarshal117.34213.411.82x
BenchmarkNidOptEnumProtoMarshal3.8913.163.38x
BenchmarkNinOptEnumProtoMarshal1.826.303.46x
BenchmarkNidRepEnumProtoMarshal12.3638.503.11x
BenchmarkNinRepEnumProtoMarshal12.0837.533.11x
BenchmarkTimerProtoMarshal73.81253.873.44x
BenchmarkMyExtendableProtoMarshal13.1543.083.28x
BenchmarkOtherExtenableProtoMarshal24.2881.093.34x
- -## Unmarshaler - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
benchmarkold ns/opnew ns/opdelta
BenchmarkNidOptNativeProtoUnmarshal25211006-60.10%
BenchmarkNinOptNativeProtoUnmarshal25291750-30.80%
BenchmarkNidRepNativeProtoUnmarshal4906735299-28.06%
BenchmarkNinRepNativeProtoUnmarshal4799035456-26.12%
BenchmarkNidRepPackedNativeProtoUnmarshal2645623950-9.47%
BenchmarkNinRepPackedNativeProtoUnmarshal2649924037-9.29%
BenchmarkNidOptStructProtoUnmarshal68033873-43.07%
BenchmarkNinOptStructProtoUnmarshal67864154-38.79%
BenchmarkNidRepStructProtoUnmarshal5627631970-43.19%
BenchmarkNinRepStructProtoUnmarshal4875031832-34.70%
BenchmarkNidEmbeddedStructProtoUnmarshal45561973-56.69%
BenchmarkNinEmbeddedStructProtoUnmarshal44851975-55.96%
BenchmarkNidNestedStructProtoUnmarshal223395135844-39.19%
BenchmarkNinNestedStructProtoUnmarshal226446134022-40.82%
BenchmarkNidOptCustomProtoUnmarshal1859300-83.86%
BenchmarkNinOptCustomProtoUnmarshal1486402-72.95%
BenchmarkNidRepCustomProtoUnmarshal82291669-79.72%
BenchmarkNinRepCustomProtoUnmarshal82531649-80.02%
BenchmarkNinOptNativeUnionProtoUnmarshal840307-63.45%
BenchmarkNinOptStructUnionProtoUnmarshal1395639-54.19%
BenchmarkNinEmbeddedStructUnionProtoUnmarshal22971167-49.19%
BenchmarkNinNestedStructUnionProtoUnmarshal1820889-51.15%
BenchmarkTreeProtoUnmarshal1521720-52.66%
BenchmarkOrBranchProtoUnmarshal26691385-48.11%
BenchmarkAndBranchProtoUnmarshal26671420-46.76%
BenchmarkLeafProtoUnmarshal1171584-50.13%
BenchmarkDeepTreeProtoUnmarshal20651081-47.65%
BenchmarkADeepBranchProtoUnmarshal26951178-56.29%
BenchmarkAndDeepBranchProtoUnmarshal40551918-52.70%
BenchmarkDeepLeafProtoUnmarshal1758865-50.80%
BenchmarkNilProtoUnmarshal56463-88.79%
BenchmarkNidOptEnumProtoUnmarshal76273-90.34%
BenchmarkNinOptEnumProtoUnmarshal764163-78.66%
BenchmarkNidRepEnumProtoUnmarshal1078447-58.53%
BenchmarkNinRepEnumProtoUnmarshal1071479-55.28%
BenchmarkTimerProtoUnmarshal1128362-67.91%
BenchmarkMyExtendableProtoUnmarshal808217-73.14%
BenchmarkOtherExtenableProtoUnmarshal1233517-58.07%
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
benchmarkold MB/snew MB/sspeedup
BenchmarkNidOptNativeProtoUnmarshal133.67334.982.51x
BenchmarkNinOptNativeProtoUnmarshal119.77173.081.45x
BenchmarkNidRepNativeProtoUnmarshal143.23199.121.39x
BenchmarkNinRepNativeProtoUnmarshal146.07198.161.36x
BenchmarkNidRepPackedNativeProtoUnmarshal127.80141.041.10x
BenchmarkNinRepPackedNativeProtoUnmarshal127.55140.781.10x
BenchmarkNidOptStructProtoUnmarshal185.79326.311.76x
BenchmarkNinOptStructProtoUnmarshal167.68273.661.63x
BenchmarkNidRepStructProtoUnmarshal147.88260.391.76x
BenchmarkNinRepStructProtoUnmarshal171.20261.971.53x
BenchmarkNidEmbeddedStructProtoUnmarshal142.86329.422.31x
BenchmarkNinEmbeddedStructProtoUnmarshal137.33311.832.27x
BenchmarkNidNestedStructProtoUnmarshal154.97259.471.67x
BenchmarkNinNestedStructProtoUnmarshal154.32258.421.67x
BenchmarkNidOptCustomProtoUnmarshal19.36119.666.18x
BenchmarkNinOptCustomProtoUnmarshal21.5279.503.69x
BenchmarkNidRepCustomProtoUnmarshal17.6286.864.93x
BenchmarkNinRepCustomProtoUnmarshal17.5787.925.00x
BenchmarkNinOptNativeUnionProtoUnmarshal38.07104.122.73x
BenchmarkNinOptStructUnionProtoUnmarshal73.08159.542.18x
BenchmarkNinEmbeddedStructUnionProtoUnmarshal94.00185.921.98x
BenchmarkNinNestedStructUnionProtoUnmarshal65.35133.752.05x
BenchmarkTreeProtoUnmarshal141.28297.132.10x
BenchmarkOrBranchProtoUnmarshal162.56313.961.93x
BenchmarkAndBranchProtoUnmarshal163.06306.151.88x
BenchmarkLeafProtoUnmarshal176.72354.192.00x
BenchmarkDeepTreeProtoUnmarshal107.50205.301.91x
BenchmarkADeepBranchProtoUnmarshal83.48190.882.29x
BenchmarkAndDeepBranchProtoUnmarshal110.97234.602.11x
BenchmarkDeepLeafProtoUnmarshal123.40250.732.03x
BenchmarkNidOptEnumProtoUnmarshal2.6227.1610.37x
BenchmarkNinOptEnumProtoUnmarshal1.316.114.66x
BenchmarkNidRepEnumProtoUnmarshal7.4217.882.41x
BenchmarkNinRepEnumProtoUnmarshal7.4716.692.23x
BenchmarkTimerProtoUnmarshal61.12190.343.11x
BenchmarkMyExtendableProtoUnmarshal9.9036.713.71x
BenchmarkOtherExtenableProtoUnmarshal21.9052.132.38x
\ No newline at end of file diff --git a/vendor/github.com/gogo/protobuf/custom_types.md b/vendor/github.com/gogo/protobuf/custom_types.md deleted file mode 100644 index 3eed249b5..000000000 --- a/vendor/github.com/gogo/protobuf/custom_types.md +++ /dev/null @@ -1,68 +0,0 @@ -# Custom types - -Custom types is a gogo protobuf extensions that allows for using a custom -struct type to decorate the underlying structure of the protocol message. - -# How to use - -## Defining the protobuf message - -```proto -message CustomType { - optional ProtoType Field = 1 [(gogoproto.customtype) = "T"]; -} - -message ProtoType { - optional string Field = 1; -} -``` - -or alternatively you can declare the field type in the protocol message to be -`bytes`: - -```proto -message BytesCustomType { - optional bytes Field = 1 [(gogoproto.customtype) = "T"]; -} -``` - -The downside of using `bytes` is that it makes it harder to generate protobuf -code in other languages. In either case, it is the user responsibility to -ensure that the custom type marshals and unmarshals to the expected wire -format. That is, in the first example, gogo protobuf will not attempt to ensure -that the wire format of `ProtoType` and `T` are wire compatible. - -## Custom type method signatures - -The custom type must define the following methods with the given -signatures. Assuming the custom type is called `T`: - -```go -func (t T) Marshal() ([]byte, error) {} -func (t *T) MarshalTo(data []byte) (n int, err error) {} -func (t *T) Unmarshal(data []byte) error {} - -func (t T) MarshalJSON() ([]byte, error) {} -func (t *T) UnmarshalJSON(data []byte) error {} - -// only required if the compare option is set -func (t T) Compare(other T) int {} -// only required if the equal option is set -func (t T) Equal(other T) bool {} -// only required if populate option is set -func NewPopulatedT(r randyThetest) *T {} -``` - -Check [t.go](test/t.go) for a full example - -# Warnings and issues - -`Warning about customtype: It is your responsibility to test all cases of your marshaling, unmarshaling and size methods implemented for your custom type.` - -Issues with customtype include: - * A Bytes method is not allowed. - * Defining a customtype as a fake proto message is broken. - * proto.Clone is broken. - * Using a proto message as a customtype is not allowed. - * cusomtype of type map can not UnmarshalText - * customtype of type struct cannot jsonpb unmarshal diff --git a/vendor/github.com/gogo/protobuf/extensions.md b/vendor/github.com/gogo/protobuf/extensions.md deleted file mode 100644 index fcfe17af2..000000000 --- a/vendor/github.com/gogo/protobuf/extensions.md +++ /dev/null @@ -1,162 +0,0 @@ -# gogoprotobuf Extensions - -Here is an [example.proto](https://github.com/gogo/protobuf/blob/master/test/example/example.proto) which uses most of the gogoprotobuf code generation plugins. - -Please also look at the example [Makefile](https://github.com/gogo/protobuf/blob/master/test/example/Makefile) which shows how to specify the `descriptor.proto` and `gogo.proto` in your proto_path - -The documentation at [http://godoc.org/github.com/gogo/protobuf/gogoproto](http://godoc.org/github.com/gogo/protobuf/gogoproto) describes the extensions made to goprotobuf in more detail. - -Also see [http://godoc.org/github.com/gogo/protobuf/plugin/](http://godoc.org/github.com/gogo/protobuf/plugin/) for documentation of each of the extensions which have their own plugins. - -# Fast Marshalling and Unmarshalling - -Generating a `Marshal`, `MarshalTo`, `Size` (or `ProtoSize`) and `Unmarshal` method for a struct results in faster marshalling and unmarshalling than when using reflect. - -See [BenchComparison](https://github.com/gogo/protobuf/blob/master/bench.md) for a comparison between reflect and generated code used for marshalling and unmarshalling. - - - - - - - - - - - -
NameOptionTypeDescriptionDefault
marshalerMessageboolif true, a Marshal and MarshalTo method is generated for the specific messagefalse
sizerMessageboolif true, a Size method is generated for the specific messagefalse
unmarshaler Message bool if true, an Unmarshal method is generated for the specific message false
protosizerMessageboolif true, a ProtoSize method is generated for the specific messagefalse
unsafe_marshaler (deprecated) Message bool if true, a Marshal and MarshalTo method is generated. false
unsafe_unmarshaler (deprecated) Message bool if true, an Unmarshal method is generated. false
stable_marshaler Message bool if true, a Marshal and MarshalTo method is generated for the specific message, but unlike marshaler the output is guaranteed to be deterministic, at the sacrifice of some speed false
typedecl (beta) Message bool if false, type declaration of the message is excluded from the generated output. Requires the marshaler and unmarshaler to be generated. true
- -# More Canonical Go Structures - -Lots of times working with a goprotobuf struct will lead you to a place where you create another struct that is easier to work with and then have a function to copy the values between the two structs. - -You might also find that basic structs that started their life as part of an API need to be sent over the wire. With gob, you could just send it. With goprotobuf, you need to make a new struct. - -`gogoprotobuf` tries to fix these problems with the nullable, embed, customtype, customname, casttype, castkey and castvalue field extensions. - - - - - - - - - - - - - - - -
NameOptionTypeDescriptionDefault
nullable Field bool if false, a field is generated without a pointer (see warning below). true
embed Field bool if true, the field is generated as an embedded field. false
customtype Field string It works with the Marshal and Unmarshal methods, to allow you to have your own types in your struct, but marshal to bytes. For example, custom.Uuid or custom.Fixed128. For more information please refer to the CustomTypes document goprotobuf type
customname (beta) Field string Changes the generated fieldname. This is especially useful when generated methods conflict with fieldnames. goprotobuf field name
casttype (beta) Field string Changes the generated field type. It assumes that this type is castable to the original goprotobuf field type. It currently does not support maps, structs or enums. goprotobuf field type
castkey (beta) Field string Changes the generated fieldtype for a map key. All generated code assumes that this type is castable to the protocol buffer field type. Only supported on maps. goprotobuf field type
castvalue (beta) Field string Changes the generated fieldtype for a map value. All generated code assumes that this type is castable to the protocol buffer field type. Only supported on maps. goprotobuf field type
enum_customname (beta) Enum string Sets the type name of an enum. If goproto_enum_prefix is enabled, this value will be used as a prefix when generating enum values.goprotobuf enum type name. Helps with golint issues.
enumdecl (beta) Enum bool if false, type declaration of the enum is excluded from the generated output. Requires the marshaler and unmarshaler to be generated. true
enumvalue_customname (beta) Enum Value string Changes the generated enum name. Helps with golint issues.goprotobuf enum value name
stdtime Timestamp Field bool Changes the Well Known Timestamp Type to time.TimeTimestamp
stdduration Duration Field bool Changes the Well Known Duration Type to time.DurationDuration
- -`Warning about nullable: according to the Protocol Buffer specification, you should be able to tell whether a field is set or unset. With the option nullable=false this feature is lost, since your non-nullable fields will always be set.` - -# Goprotobuf Compatibility - -Gogoprotobuf is compatible with Goprotobuf, because it is compatible with protocol buffers (see the section on tests below). - -Gogoprotobuf generates the same code as goprotobuf if no extensions are used. - -The enumprefix, getters and stringer extensions can be used to remove some of the unnecessary code generated by goprotobuf. - - - - - - - - - - - -
NameOptionTypeDescriptionDefault
gogoproto_import File bool if false, the generated code imports github.com/golang/protobuf/proto instead of github.com/gogo/protobuf/proto. true
goproto_enum_prefix Enum bool if false, generates the enum constant names without the messagetype prefix true
goproto_getters Message bool if false, the message is generated without get methods, this is useful when you would rather want to use face true
goproto_stringer Message bool if false, the message is generated without the default string method, this is useful for rather using stringer true
goproto_enum_stringer (experimental) Enum bool if false, the enum is generated without the default string method, this is useful for rather using enum_stringer true
goproto_extensions_map (beta) Message bool if false, the extensions field is generated as type []byte instead of type map[int32]proto.Extension true
goproto_unrecognized (beta) Message bool if false, XXX_unrecognized field is not generated. This is useful to reduce GC pressure at the cost of losing information about unrecognized fields. true
goproto_registration (beta) File bool if true, the generated files will register all messages and types against both gogo/protobuf and golang/protobuf. This is necessary when using third-party packages which read registrations from golang/protobuf (such as the grpc-gateway). false
- -# Less Typing - -The Protocol Buffer language is very parseable and extra code can be easily generated for structures. - -Helper methods, functions and interfaces can be generated by triggering certain extensions like gostring. - - - - - - - - - - - - - -
NameOptionTypeDescriptionDefault
gostring Message bool if true, a `GoString` method is generated. This returns a string representing valid go code to reproduce the current state of the struct. false
onlyone (deprecated) Message bool if true, all fields must be nullable and only one of the fields may be set, like a union. Two methods are generated: `GetValue() interface{}` and `SetValue(v interface{}) (set bool)`. These provide easier interaction with a union. false
equal Message bool if true, an Equal method is generated false
compare Message bool if true, a Compare method is generated. This is very useful for quickly implementing sort on a list of protobuf structs false
verbose_equal Message bool if true, a verbose equal method is generated for the message. This returns an error which describes the exact element which is not equal to the exact element in the other struct. false
stringer Message bool if true, a String method is generated for the message. false
face Message bool if true, a function will be generated which can convert a structure which satisfies an interface (face) to the specified structure. This interface contains getters for each of the fields in the struct. The specified struct is also generated with the getters. This allows it to satisfy its own face. false
description (beta) Message bool if true, a Description method is generated for the message. false
populate Message bool if true, a `NewPopulated` function is generated. This is necessary for generated tests. false
enum_stringer (experimental) Enum bool if true, a String method is generated for an Enum false
- -Issues with Compare include: - * Oneof is not supported yet - * Not all Well Known Types are supported yet - * Maps are not supported - -#Peace of Mind - -Test and Benchmark generation is done with the following extensions: - - - - -
testgen Message bool if true, tests are generated for proto, json and prototext marshalling as well as for some of the other enabled plugins false
benchgen Message bool if true, benchmarks are generated for proto, json and prototext marshalling as well as for some of the other enabled plugins false
- -# More Serialization Formats - -Other serialization formats like xml and json typically use reflect to marshal and unmarshal structured data. Manipulating these structs into something other than the default Go requires editing tags. The following extensions provide ways of editing these tags for the generated protobuf structs. - - - - -
jsontag (beta) Field string if set, the json tag value between the double quotes is replaced with this string fieldname
moretags (beta) Field string if set, this string is appended to the tag string empty
- -Here is a longer explanation of jsontag and moretags - -# File Options - -Each of the boolean message and enum extensions also have a file extension: - - * `marshaler_all` - * `sizer_all` - * `protosizer_all` - * `unmarshaler_all` - * `unsafe_marshaler_all` - * `unsafe_unmarshaler_all` - * `stable_marshaler_all` - * `goproto_enum_prefix_all` - * `goproto_getters_all` - * `goproto_stringer_all` - * `goproto_enum_stringer_all` - * `goproto_extensions_map_all` - * `goproto_unrecognized_all` - * `gostring_all` - * `onlyone_all` - * `equal_all` - * `compare_all` - * `verbose_equal_all` - * `stringer_all` - * `enum_stringer_all` - * `face_all` - * `description_all` - * `populate_all` - * `testgen_all` - * `benchgen_all` - * `enumdecl_all` - * `typedecl_all` - -Each of these are the same as their Message Option counterparts, except they apply to all messages in the file. Their Message option counterparts can also be used to overwrite their effect. - -# Tests - - * The normal barrage of tests are run with: `make tests` - * A few weird tests: `make testall` - * Tests for compatibility with [golang/protobuf](https://github.com/golang/protobuf) are handled by a different project [harmonytests](https://github.com/gogo/harmonytests), since it requires goprotobuf. - * Cross version tests are made with [Travis CI](https://travis-ci.org/gogo/protobuf). - * GRPC Tests are also handled by a different project [grpctests](https://github.com/gogo/grpctests), since it depends on a lot of grpc libraries. - * Thanks to [go-fuzz](https://github.com/dvyukov/go-fuzz/) we have proper [fuzztests](https://github.com/gogo/fuzztests). - diff --git a/vendor/github.com/gogo/protobuf/gogoproto/Makefile b/vendor/github.com/gogo/protobuf/gogoproto/Makefile deleted file mode 100644 index 02f9c62c2..000000000 --- a/vendor/github.com/gogo/protobuf/gogoproto/Makefile +++ /dev/null @@ -1,37 +0,0 @@ -# Protocol Buffers for Go with Gadgets -# -# Copyright (c) 2013, The GoGo Authors. All rights reserved. -# http://github.com/gogo/protobuf -# -# 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. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -regenerate: - go install github.com/gogo/protobuf/protoc-gen-gogo - protoc --gogo_out=Mgoogle/protobuf/descriptor.proto=github.com/gogo/protobuf/protoc-gen-gogo/descriptor:. --proto_path=../../../../:../protobuf/:. *.proto - -restore: - cp gogo.pb.golden gogo.pb.go - -preserve: - cp gogo.pb.go gogo.pb.golden diff --git a/vendor/github.com/gogo/protobuf/gogoproto/doc.go b/vendor/github.com/gogo/protobuf/gogoproto/doc.go deleted file mode 100644 index 147b5ecc6..000000000 --- a/vendor/github.com/gogo/protobuf/gogoproto/doc.go +++ /dev/null @@ -1,169 +0,0 @@ -// Protocol Buffers for Go with Gadgets -// -// Copyright (c) 2013, The GoGo Authors. All rights reserved. -// http://github.com/gogo/protobuf -// -// 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. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -/* -Package gogoproto provides extensions for protocol buffers to achieve: - - - fast marshalling and unmarshalling. - - peace of mind by optionally generating test and benchmark code. - - more canonical Go structures. - - less typing by optionally generating extra helper code. - - goprotobuf compatibility - -More Canonical Go Structures - -A lot of time working with a goprotobuf struct will lead you to a place where you create another struct that is easier to work with and then have a function to copy the values between the two structs. -You might also find that basic structs that started their life as part of an API need to be sent over the wire. With gob, you could just send it. With goprotobuf, you need to make a parallel struct. -Gogoprotobuf tries to fix these problems with the nullable, embed, customtype and customname field extensions. - - - nullable, if false, a field is generated without a pointer (see warning below). - - embed, if true, the field is generated as an embedded field. - - customtype, It works with the Marshal and Unmarshal methods, to allow you to have your own types in your struct, but marshal to bytes. For example, custom.Uuid or custom.Fixed128 - - customname (beta), Changes the generated fieldname. This is especially useful when generated methods conflict with fieldnames. - - casttype (beta), Changes the generated fieldtype. All generated code assumes that this type is castable to the protocol buffer field type. It does not work for structs or enums. - - castkey (beta), Changes the generated fieldtype for a map key. All generated code assumes that this type is castable to the protocol buffer field type. Only supported on maps. - - castvalue (beta), Changes the generated fieldtype for a map value. All generated code assumes that this type is castable to the protocol buffer field type. Only supported on maps. - -Warning about nullable: According to the Protocol Buffer specification, you should be able to tell whether a field is set or unset. With the option nullable=false this feature is lost, since your non-nullable fields will always be set. It can be seen as a layer on top of Protocol Buffers, where before and after marshalling all non-nullable fields are set and they cannot be unset. - -Let us look at: - - github.com/gogo/protobuf/test/example/example.proto - -for a quicker overview. - -The following message: - - package test; - - import "github.com/gogo/protobuf/gogoproto/gogo.proto"; - - message A { - optional string Description = 1 [(gogoproto.nullable) = false]; - optional int64 Number = 2 [(gogoproto.nullable) = false]; - optional bytes Id = 3 [(gogoproto.customtype) = "github.com/gogo/protobuf/test/custom.Uuid", (gogoproto.nullable) = false]; - } - -Will generate a go struct which looks a lot like this: - - type A struct { - Description string - Number int64 - Id github_com_gogo_protobuf_test_custom.Uuid - } - -You will see there are no pointers, since all fields are non-nullable. -You will also see a custom type which marshals to a string. -Be warned it is your responsibility to test your custom types thoroughly. -You should think of every possible empty and nil case for your marshaling, unmarshaling and size methods. - -Next we will embed the message A in message B. - - message B { - optional A A = 1 [(gogoproto.nullable) = false, (gogoproto.embed) = true]; - repeated bytes G = 2 [(gogoproto.customtype) = "github.com/gogo/protobuf/test/custom.Uint128", (gogoproto.nullable) = false]; - } - -See below that A is embedded in B. - - type B struct { - A - G []github_com_gogo_protobuf_test_custom.Uint128 - } - -Also see the repeated custom type. - - type Uint128 [2]uint64 - -Next we will create a custom name for one of our fields. - - message C { - optional int64 size = 1 [(gogoproto.customname) = "MySize"]; - } - -See below that the field's name is MySize and not Size. - - type C struct { - MySize *int64 - } - -The is useful when having a protocol buffer message with a field name which conflicts with a generated method. -As an example, having a field name size and using the sizer plugin to generate a Size method will cause a go compiler error. -Using customname you can fix this error without changing the field name. -This is typically useful when working with a protocol buffer that was designed before these methods and/or the go language were avialable. - -Gogoprotobuf also has some more subtle changes, these could be changed back: - - - the generated package name for imports do not have the extra /filename.pb, - but are actually the imports specified in the .proto file. - -Gogoprotobuf also has lost some features which should be brought back with time: - - - Marshalling and unmarshalling with reflect and without the unsafe package, - this requires work in pointer_reflect.go - -Why does nullable break protocol buffer specifications: - -The protocol buffer specification states, somewhere, that you should be able to tell whether a -field is set or unset. With the option nullable=false this feature is lost, -since your non-nullable fields will always be set. It can be seen as a layer on top of -protocol buffers, where before and after marshalling all non-nullable fields are set -and they cannot be unset. - -Goprotobuf Compatibility: - -Gogoprotobuf is compatible with Goprotobuf, because it is compatible with protocol buffers. -Gogoprotobuf generates the same code as goprotobuf if no extensions are used. -The enumprefix, getters and stringer extensions can be used to remove some of the unnecessary code generated by goprotobuf: - - - gogoproto_import, if false, the generated code imports github.com/golang/protobuf/proto instead of github.com/gogo/protobuf/proto. - - goproto_enum_prefix, if false, generates the enum constant names without the messagetype prefix - - goproto_enum_stringer (experimental), if false, the enum is generated without the default string method, this is useful for rather using enum_stringer, or allowing you to write your own string method. - - goproto_getters, if false, the message is generated without get methods, this is useful when you would rather want to use face - - goproto_stringer, if false, the message is generated without the default string method, this is useful for rather using stringer, or allowing you to write your own string method. - - goproto_extensions_map (beta), if false, the extensions field is generated as type []byte instead of type map[int32]proto.Extension - - goproto_unrecognized (beta), if false, XXX_unrecognized field is not generated. This is useful in conjunction with gogoproto.nullable=false, to generate structures completely devoid of pointers and reduce GC pressure at the cost of losing information about unrecognized fields. - - goproto_registration (beta), if true, the generated files will register all messages and types against both gogo/protobuf and golang/protobuf. This is necessary when using third-party packages which read registrations from golang/protobuf (such as the grpc-gateway). - -Less Typing and Peace of Mind is explained in their specific plugin folders godoc: - - - github.com/gogo/protobuf/plugin/ - -If you do not use any of these extension the code that is generated -will be the same as if goprotobuf has generated it. - -The most complete way to see examples is to look at - - github.com/gogo/protobuf/test/thetest.proto - -Gogoprototest is a seperate project, -because we want to keep gogoprotobuf independant of goprotobuf, -but we still want to test it thoroughly. - -*/ -package gogoproto diff --git a/vendor/github.com/gogo/protobuf/gogoproto/gogo.pb.go b/vendor/github.com/gogo/protobuf/gogoproto/gogo.pb.go deleted file mode 100644 index fa88040f1..000000000 --- a/vendor/github.com/gogo/protobuf/gogoproto/gogo.pb.go +++ /dev/null @@ -1,803 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: gogo.proto - -/* -Package gogoproto is a generated protocol buffer package. - -It is generated from these files: - gogo.proto - -It has these top-level messages: -*/ -package gogoproto - -import proto "github.com/gogo/protobuf/proto" -import fmt "fmt" -import math "math" -import google_protobuf "github.com/gogo/protobuf/protoc-gen-gogo/descriptor" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package - -var E_GoprotoEnumPrefix = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.EnumOptions)(nil), - ExtensionType: (*bool)(nil), - Field: 62001, - Name: "gogoproto.goproto_enum_prefix", - Tag: "varint,62001,opt,name=goproto_enum_prefix,json=goprotoEnumPrefix", - Filename: "gogo.proto", -} - -var E_GoprotoEnumStringer = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.EnumOptions)(nil), - ExtensionType: (*bool)(nil), - Field: 62021, - Name: "gogoproto.goproto_enum_stringer", - Tag: "varint,62021,opt,name=goproto_enum_stringer,json=goprotoEnumStringer", - Filename: "gogo.proto", -} - -var E_EnumStringer = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.EnumOptions)(nil), - ExtensionType: (*bool)(nil), - Field: 62022, - Name: "gogoproto.enum_stringer", - Tag: "varint,62022,opt,name=enum_stringer,json=enumStringer", - Filename: "gogo.proto", -} - -var E_EnumCustomname = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.EnumOptions)(nil), - ExtensionType: (*string)(nil), - Field: 62023, - Name: "gogoproto.enum_customname", - Tag: "bytes,62023,opt,name=enum_customname,json=enumCustomname", - Filename: "gogo.proto", -} - -var E_Enumdecl = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.EnumOptions)(nil), - ExtensionType: (*bool)(nil), - Field: 62024, - Name: "gogoproto.enumdecl", - Tag: "varint,62024,opt,name=enumdecl", - Filename: "gogo.proto", -} - -var E_EnumvalueCustomname = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.EnumValueOptions)(nil), - ExtensionType: (*string)(nil), - Field: 66001, - Name: "gogoproto.enumvalue_customname", - Tag: "bytes,66001,opt,name=enumvalue_customname,json=enumvalueCustomname", - Filename: "gogo.proto", -} - -var E_GoprotoGettersAll = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FileOptions)(nil), - ExtensionType: (*bool)(nil), - Field: 63001, - Name: "gogoproto.goproto_getters_all", - Tag: "varint,63001,opt,name=goproto_getters_all,json=goprotoGettersAll", - Filename: "gogo.proto", -} - -var E_GoprotoEnumPrefixAll = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FileOptions)(nil), - ExtensionType: (*bool)(nil), - Field: 63002, - Name: "gogoproto.goproto_enum_prefix_all", - Tag: "varint,63002,opt,name=goproto_enum_prefix_all,json=goprotoEnumPrefixAll", - Filename: "gogo.proto", -} - -var E_GoprotoStringerAll = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FileOptions)(nil), - ExtensionType: (*bool)(nil), - Field: 63003, - Name: "gogoproto.goproto_stringer_all", - Tag: "varint,63003,opt,name=goproto_stringer_all,json=goprotoStringerAll", - Filename: "gogo.proto", -} - -var E_VerboseEqualAll = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FileOptions)(nil), - ExtensionType: (*bool)(nil), - Field: 63004, - Name: "gogoproto.verbose_equal_all", - Tag: "varint,63004,opt,name=verbose_equal_all,json=verboseEqualAll", - Filename: "gogo.proto", -} - -var E_FaceAll = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FileOptions)(nil), - ExtensionType: (*bool)(nil), - Field: 63005, - Name: "gogoproto.face_all", - Tag: "varint,63005,opt,name=face_all,json=faceAll", - Filename: "gogo.proto", -} - -var E_GostringAll = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FileOptions)(nil), - ExtensionType: (*bool)(nil), - Field: 63006, - Name: "gogoproto.gostring_all", - Tag: "varint,63006,opt,name=gostring_all,json=gostringAll", - Filename: "gogo.proto", -} - -var E_PopulateAll = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FileOptions)(nil), - ExtensionType: (*bool)(nil), - Field: 63007, - Name: "gogoproto.populate_all", - Tag: "varint,63007,opt,name=populate_all,json=populateAll", - Filename: "gogo.proto", -} - -var E_StringerAll = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FileOptions)(nil), - ExtensionType: (*bool)(nil), - Field: 63008, - Name: "gogoproto.stringer_all", - Tag: "varint,63008,opt,name=stringer_all,json=stringerAll", - Filename: "gogo.proto", -} - -var E_OnlyoneAll = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FileOptions)(nil), - ExtensionType: (*bool)(nil), - Field: 63009, - Name: "gogoproto.onlyone_all", - Tag: "varint,63009,opt,name=onlyone_all,json=onlyoneAll", - Filename: "gogo.proto", -} - -var E_EqualAll = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FileOptions)(nil), - ExtensionType: (*bool)(nil), - Field: 63013, - Name: "gogoproto.equal_all", - Tag: "varint,63013,opt,name=equal_all,json=equalAll", - Filename: "gogo.proto", -} - -var E_DescriptionAll = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FileOptions)(nil), - ExtensionType: (*bool)(nil), - Field: 63014, - Name: "gogoproto.description_all", - Tag: "varint,63014,opt,name=description_all,json=descriptionAll", - Filename: "gogo.proto", -} - -var E_TestgenAll = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FileOptions)(nil), - ExtensionType: (*bool)(nil), - Field: 63015, - Name: "gogoproto.testgen_all", - Tag: "varint,63015,opt,name=testgen_all,json=testgenAll", - Filename: "gogo.proto", -} - -var E_BenchgenAll = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FileOptions)(nil), - ExtensionType: (*bool)(nil), - Field: 63016, - Name: "gogoproto.benchgen_all", - Tag: "varint,63016,opt,name=benchgen_all,json=benchgenAll", - Filename: "gogo.proto", -} - -var E_MarshalerAll = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FileOptions)(nil), - ExtensionType: (*bool)(nil), - Field: 63017, - Name: "gogoproto.marshaler_all", - Tag: "varint,63017,opt,name=marshaler_all,json=marshalerAll", - Filename: "gogo.proto", -} - -var E_UnmarshalerAll = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FileOptions)(nil), - ExtensionType: (*bool)(nil), - Field: 63018, - Name: "gogoproto.unmarshaler_all", - Tag: "varint,63018,opt,name=unmarshaler_all,json=unmarshalerAll", - Filename: "gogo.proto", -} - -var E_StableMarshalerAll = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FileOptions)(nil), - ExtensionType: (*bool)(nil), - Field: 63019, - Name: "gogoproto.stable_marshaler_all", - Tag: "varint,63019,opt,name=stable_marshaler_all,json=stableMarshalerAll", - Filename: "gogo.proto", -} - -var E_SizerAll = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FileOptions)(nil), - ExtensionType: (*bool)(nil), - Field: 63020, - Name: "gogoproto.sizer_all", - Tag: "varint,63020,opt,name=sizer_all,json=sizerAll", - Filename: "gogo.proto", -} - -var E_GoprotoEnumStringerAll = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FileOptions)(nil), - ExtensionType: (*bool)(nil), - Field: 63021, - Name: "gogoproto.goproto_enum_stringer_all", - Tag: "varint,63021,opt,name=goproto_enum_stringer_all,json=goprotoEnumStringerAll", - Filename: "gogo.proto", -} - -var E_EnumStringerAll = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FileOptions)(nil), - ExtensionType: (*bool)(nil), - Field: 63022, - Name: "gogoproto.enum_stringer_all", - Tag: "varint,63022,opt,name=enum_stringer_all,json=enumStringerAll", - Filename: "gogo.proto", -} - -var E_UnsafeMarshalerAll = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FileOptions)(nil), - ExtensionType: (*bool)(nil), - Field: 63023, - Name: "gogoproto.unsafe_marshaler_all", - Tag: "varint,63023,opt,name=unsafe_marshaler_all,json=unsafeMarshalerAll", - Filename: "gogo.proto", -} - -var E_UnsafeUnmarshalerAll = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FileOptions)(nil), - ExtensionType: (*bool)(nil), - Field: 63024, - Name: "gogoproto.unsafe_unmarshaler_all", - Tag: "varint,63024,opt,name=unsafe_unmarshaler_all,json=unsafeUnmarshalerAll", - Filename: "gogo.proto", -} - -var E_GoprotoExtensionsMapAll = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FileOptions)(nil), - ExtensionType: (*bool)(nil), - Field: 63025, - Name: "gogoproto.goproto_extensions_map_all", - Tag: "varint,63025,opt,name=goproto_extensions_map_all,json=goprotoExtensionsMapAll", - Filename: "gogo.proto", -} - -var E_GoprotoUnrecognizedAll = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FileOptions)(nil), - ExtensionType: (*bool)(nil), - Field: 63026, - Name: "gogoproto.goproto_unrecognized_all", - Tag: "varint,63026,opt,name=goproto_unrecognized_all,json=goprotoUnrecognizedAll", - Filename: "gogo.proto", -} - -var E_GogoprotoImport = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FileOptions)(nil), - ExtensionType: (*bool)(nil), - Field: 63027, - Name: "gogoproto.gogoproto_import", - Tag: "varint,63027,opt,name=gogoproto_import,json=gogoprotoImport", - Filename: "gogo.proto", -} - -var E_ProtosizerAll = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FileOptions)(nil), - ExtensionType: (*bool)(nil), - Field: 63028, - Name: "gogoproto.protosizer_all", - Tag: "varint,63028,opt,name=protosizer_all,json=protosizerAll", - Filename: "gogo.proto", -} - -var E_CompareAll = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FileOptions)(nil), - ExtensionType: (*bool)(nil), - Field: 63029, - Name: "gogoproto.compare_all", - Tag: "varint,63029,opt,name=compare_all,json=compareAll", - Filename: "gogo.proto", -} - -var E_TypedeclAll = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FileOptions)(nil), - ExtensionType: (*bool)(nil), - Field: 63030, - Name: "gogoproto.typedecl_all", - Tag: "varint,63030,opt,name=typedecl_all,json=typedeclAll", - Filename: "gogo.proto", -} - -var E_EnumdeclAll = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FileOptions)(nil), - ExtensionType: (*bool)(nil), - Field: 63031, - Name: "gogoproto.enumdecl_all", - Tag: "varint,63031,opt,name=enumdecl_all,json=enumdeclAll", - Filename: "gogo.proto", -} - -var E_GoprotoRegistration = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FileOptions)(nil), - ExtensionType: (*bool)(nil), - Field: 63032, - Name: "gogoproto.goproto_registration", - Tag: "varint,63032,opt,name=goproto_registration,json=goprotoRegistration", - Filename: "gogo.proto", -} - -var E_GoprotoGetters = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.MessageOptions)(nil), - ExtensionType: (*bool)(nil), - Field: 64001, - Name: "gogoproto.goproto_getters", - Tag: "varint,64001,opt,name=goproto_getters,json=goprotoGetters", - Filename: "gogo.proto", -} - -var E_GoprotoStringer = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.MessageOptions)(nil), - ExtensionType: (*bool)(nil), - Field: 64003, - Name: "gogoproto.goproto_stringer", - Tag: "varint,64003,opt,name=goproto_stringer,json=goprotoStringer", - Filename: "gogo.proto", -} - -var E_VerboseEqual = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.MessageOptions)(nil), - ExtensionType: (*bool)(nil), - Field: 64004, - Name: "gogoproto.verbose_equal", - Tag: "varint,64004,opt,name=verbose_equal,json=verboseEqual", - Filename: "gogo.proto", -} - -var E_Face = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.MessageOptions)(nil), - ExtensionType: (*bool)(nil), - Field: 64005, - Name: "gogoproto.face", - Tag: "varint,64005,opt,name=face", - Filename: "gogo.proto", -} - -var E_Gostring = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.MessageOptions)(nil), - ExtensionType: (*bool)(nil), - Field: 64006, - Name: "gogoproto.gostring", - Tag: "varint,64006,opt,name=gostring", - Filename: "gogo.proto", -} - -var E_Populate = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.MessageOptions)(nil), - ExtensionType: (*bool)(nil), - Field: 64007, - Name: "gogoproto.populate", - Tag: "varint,64007,opt,name=populate", - Filename: "gogo.proto", -} - -var E_Stringer = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.MessageOptions)(nil), - ExtensionType: (*bool)(nil), - Field: 67008, - Name: "gogoproto.stringer", - Tag: "varint,67008,opt,name=stringer", - Filename: "gogo.proto", -} - -var E_Onlyone = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.MessageOptions)(nil), - ExtensionType: (*bool)(nil), - Field: 64009, - Name: "gogoproto.onlyone", - Tag: "varint,64009,opt,name=onlyone", - Filename: "gogo.proto", -} - -var E_Equal = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.MessageOptions)(nil), - ExtensionType: (*bool)(nil), - Field: 64013, - Name: "gogoproto.equal", - Tag: "varint,64013,opt,name=equal", - Filename: "gogo.proto", -} - -var E_Description = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.MessageOptions)(nil), - ExtensionType: (*bool)(nil), - Field: 64014, - Name: "gogoproto.description", - Tag: "varint,64014,opt,name=description", - Filename: "gogo.proto", -} - -var E_Testgen = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.MessageOptions)(nil), - ExtensionType: (*bool)(nil), - Field: 64015, - Name: "gogoproto.testgen", - Tag: "varint,64015,opt,name=testgen", - Filename: "gogo.proto", -} - -var E_Benchgen = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.MessageOptions)(nil), - ExtensionType: (*bool)(nil), - Field: 64016, - Name: "gogoproto.benchgen", - Tag: "varint,64016,opt,name=benchgen", - Filename: "gogo.proto", -} - -var E_Marshaler = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.MessageOptions)(nil), - ExtensionType: (*bool)(nil), - Field: 64017, - Name: "gogoproto.marshaler", - Tag: "varint,64017,opt,name=marshaler", - Filename: "gogo.proto", -} - -var E_Unmarshaler = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.MessageOptions)(nil), - ExtensionType: (*bool)(nil), - Field: 64018, - Name: "gogoproto.unmarshaler", - Tag: "varint,64018,opt,name=unmarshaler", - Filename: "gogo.proto", -} - -var E_StableMarshaler = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.MessageOptions)(nil), - ExtensionType: (*bool)(nil), - Field: 64019, - Name: "gogoproto.stable_marshaler", - Tag: "varint,64019,opt,name=stable_marshaler,json=stableMarshaler", - Filename: "gogo.proto", -} - -var E_Sizer = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.MessageOptions)(nil), - ExtensionType: (*bool)(nil), - Field: 64020, - Name: "gogoproto.sizer", - Tag: "varint,64020,opt,name=sizer", - Filename: "gogo.proto", -} - -var E_UnsafeMarshaler = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.MessageOptions)(nil), - ExtensionType: (*bool)(nil), - Field: 64023, - Name: "gogoproto.unsafe_marshaler", - Tag: "varint,64023,opt,name=unsafe_marshaler,json=unsafeMarshaler", - Filename: "gogo.proto", -} - -var E_UnsafeUnmarshaler = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.MessageOptions)(nil), - ExtensionType: (*bool)(nil), - Field: 64024, - Name: "gogoproto.unsafe_unmarshaler", - Tag: "varint,64024,opt,name=unsafe_unmarshaler,json=unsafeUnmarshaler", - Filename: "gogo.proto", -} - -var E_GoprotoExtensionsMap = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.MessageOptions)(nil), - ExtensionType: (*bool)(nil), - Field: 64025, - Name: "gogoproto.goproto_extensions_map", - Tag: "varint,64025,opt,name=goproto_extensions_map,json=goprotoExtensionsMap", - Filename: "gogo.proto", -} - -var E_GoprotoUnrecognized = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.MessageOptions)(nil), - ExtensionType: (*bool)(nil), - Field: 64026, - Name: "gogoproto.goproto_unrecognized", - Tag: "varint,64026,opt,name=goproto_unrecognized,json=goprotoUnrecognized", - Filename: "gogo.proto", -} - -var E_Protosizer = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.MessageOptions)(nil), - ExtensionType: (*bool)(nil), - Field: 64028, - Name: "gogoproto.protosizer", - Tag: "varint,64028,opt,name=protosizer", - Filename: "gogo.proto", -} - -var E_Compare = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.MessageOptions)(nil), - ExtensionType: (*bool)(nil), - Field: 64029, - Name: "gogoproto.compare", - Tag: "varint,64029,opt,name=compare", - Filename: "gogo.proto", -} - -var E_Typedecl = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.MessageOptions)(nil), - ExtensionType: (*bool)(nil), - Field: 64030, - Name: "gogoproto.typedecl", - Tag: "varint,64030,opt,name=typedecl", - Filename: "gogo.proto", -} - -var E_Nullable = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FieldOptions)(nil), - ExtensionType: (*bool)(nil), - Field: 65001, - Name: "gogoproto.nullable", - Tag: "varint,65001,opt,name=nullable", - Filename: "gogo.proto", -} - -var E_Embed = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FieldOptions)(nil), - ExtensionType: (*bool)(nil), - Field: 65002, - Name: "gogoproto.embed", - Tag: "varint,65002,opt,name=embed", - Filename: "gogo.proto", -} - -var E_Customtype = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FieldOptions)(nil), - ExtensionType: (*string)(nil), - Field: 65003, - Name: "gogoproto.customtype", - Tag: "bytes,65003,opt,name=customtype", - Filename: "gogo.proto", -} - -var E_Customname = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FieldOptions)(nil), - ExtensionType: (*string)(nil), - Field: 65004, - Name: "gogoproto.customname", - Tag: "bytes,65004,opt,name=customname", - Filename: "gogo.proto", -} - -var E_Jsontag = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FieldOptions)(nil), - ExtensionType: (*string)(nil), - Field: 65005, - Name: "gogoproto.jsontag", - Tag: "bytes,65005,opt,name=jsontag", - Filename: "gogo.proto", -} - -var E_Moretags = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FieldOptions)(nil), - ExtensionType: (*string)(nil), - Field: 65006, - Name: "gogoproto.moretags", - Tag: "bytes,65006,opt,name=moretags", - Filename: "gogo.proto", -} - -var E_Casttype = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FieldOptions)(nil), - ExtensionType: (*string)(nil), - Field: 65007, - Name: "gogoproto.casttype", - Tag: "bytes,65007,opt,name=casttype", - Filename: "gogo.proto", -} - -var E_Castkey = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FieldOptions)(nil), - ExtensionType: (*string)(nil), - Field: 65008, - Name: "gogoproto.castkey", - Tag: "bytes,65008,opt,name=castkey", - Filename: "gogo.proto", -} - -var E_Castvalue = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FieldOptions)(nil), - ExtensionType: (*string)(nil), - Field: 65009, - Name: "gogoproto.castvalue", - Tag: "bytes,65009,opt,name=castvalue", - Filename: "gogo.proto", -} - -var E_Stdtime = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FieldOptions)(nil), - ExtensionType: (*bool)(nil), - Field: 65010, - Name: "gogoproto.stdtime", - Tag: "varint,65010,opt,name=stdtime", - Filename: "gogo.proto", -} - -var E_Stdduration = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FieldOptions)(nil), - ExtensionType: (*bool)(nil), - Field: 65011, - Name: "gogoproto.stdduration", - Tag: "varint,65011,opt,name=stdduration", - Filename: "gogo.proto", -} - -func init() { - proto.RegisterExtension(E_GoprotoEnumPrefix) - proto.RegisterExtension(E_GoprotoEnumStringer) - proto.RegisterExtension(E_EnumStringer) - proto.RegisterExtension(E_EnumCustomname) - proto.RegisterExtension(E_Enumdecl) - proto.RegisterExtension(E_EnumvalueCustomname) - proto.RegisterExtension(E_GoprotoGettersAll) - proto.RegisterExtension(E_GoprotoEnumPrefixAll) - proto.RegisterExtension(E_GoprotoStringerAll) - proto.RegisterExtension(E_VerboseEqualAll) - proto.RegisterExtension(E_FaceAll) - proto.RegisterExtension(E_GostringAll) - proto.RegisterExtension(E_PopulateAll) - proto.RegisterExtension(E_StringerAll) - proto.RegisterExtension(E_OnlyoneAll) - proto.RegisterExtension(E_EqualAll) - proto.RegisterExtension(E_DescriptionAll) - proto.RegisterExtension(E_TestgenAll) - proto.RegisterExtension(E_BenchgenAll) - proto.RegisterExtension(E_MarshalerAll) - proto.RegisterExtension(E_UnmarshalerAll) - proto.RegisterExtension(E_StableMarshalerAll) - proto.RegisterExtension(E_SizerAll) - proto.RegisterExtension(E_GoprotoEnumStringerAll) - proto.RegisterExtension(E_EnumStringerAll) - proto.RegisterExtension(E_UnsafeMarshalerAll) - proto.RegisterExtension(E_UnsafeUnmarshalerAll) - proto.RegisterExtension(E_GoprotoExtensionsMapAll) - proto.RegisterExtension(E_GoprotoUnrecognizedAll) - proto.RegisterExtension(E_GogoprotoImport) - proto.RegisterExtension(E_ProtosizerAll) - proto.RegisterExtension(E_CompareAll) - proto.RegisterExtension(E_TypedeclAll) - proto.RegisterExtension(E_EnumdeclAll) - proto.RegisterExtension(E_GoprotoRegistration) - proto.RegisterExtension(E_GoprotoGetters) - proto.RegisterExtension(E_GoprotoStringer) - proto.RegisterExtension(E_VerboseEqual) - proto.RegisterExtension(E_Face) - proto.RegisterExtension(E_Gostring) - proto.RegisterExtension(E_Populate) - proto.RegisterExtension(E_Stringer) - proto.RegisterExtension(E_Onlyone) - proto.RegisterExtension(E_Equal) - proto.RegisterExtension(E_Description) - proto.RegisterExtension(E_Testgen) - proto.RegisterExtension(E_Benchgen) - proto.RegisterExtension(E_Marshaler) - proto.RegisterExtension(E_Unmarshaler) - proto.RegisterExtension(E_StableMarshaler) - proto.RegisterExtension(E_Sizer) - proto.RegisterExtension(E_UnsafeMarshaler) - proto.RegisterExtension(E_UnsafeUnmarshaler) - proto.RegisterExtension(E_GoprotoExtensionsMap) - proto.RegisterExtension(E_GoprotoUnrecognized) - proto.RegisterExtension(E_Protosizer) - proto.RegisterExtension(E_Compare) - proto.RegisterExtension(E_Typedecl) - proto.RegisterExtension(E_Nullable) - proto.RegisterExtension(E_Embed) - proto.RegisterExtension(E_Customtype) - proto.RegisterExtension(E_Customname) - proto.RegisterExtension(E_Jsontag) - proto.RegisterExtension(E_Moretags) - proto.RegisterExtension(E_Casttype) - proto.RegisterExtension(E_Castkey) - proto.RegisterExtension(E_Castvalue) - proto.RegisterExtension(E_Stdtime) - proto.RegisterExtension(E_Stdduration) -} - -func init() { proto.RegisterFile("gogo.proto", fileDescriptorGogo) } - -var fileDescriptorGogo = []byte{ - // 1201 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x98, 0xcb, 0x6f, 0x1c, 0x45, - 0x13, 0xc0, 0xf5, 0xe9, 0x73, 0x64, 0x6f, 0xf9, 0x85, 0xd7, 0xc6, 0x84, 0x08, 0x44, 0x72, 0xe3, - 0xe4, 0x9c, 0x22, 0x94, 0xb6, 0x22, 0xcb, 0xb1, 0x1c, 0x2b, 0x11, 0x06, 0x63, 0xe2, 0x00, 0xe2, - 0xb0, 0x9a, 0xdd, 0x6d, 0x4f, 0x06, 0x66, 0xa6, 0x87, 0x99, 0x9e, 0x28, 0xce, 0x0d, 0x85, 0x87, - 0x10, 0xe2, 0x8d, 0x04, 0x09, 0x49, 0x80, 0x03, 0xef, 0x67, 0x78, 0x1f, 0xb9, 0xf0, 0xb8, 0xf2, - 0x3f, 0x70, 0x01, 0xcc, 0xdb, 0x37, 0x5f, 0x50, 0xcd, 0x56, 0xcd, 0xf6, 0xac, 0x57, 0xea, 0xde, - 0xdb, 0xec, 0xba, 0x7f, 0xbf, 0xad, 0xa9, 0x9a, 0xae, 0xea, 0x31, 0x80, 0xaf, 0x7c, 0x35, 0x97, - 0xa4, 0x4a, 0xab, 0x7a, 0x0d, 0xaf, 0x8b, 0xcb, 0x03, 0x07, 0x7d, 0xa5, 0xfc, 0x50, 0x1e, 0x2e, - 0x3e, 0x35, 0xf3, 0xcd, 0xc3, 0x6d, 0x99, 0xb5, 0xd2, 0x20, 0xd1, 0x2a, 0xed, 0x2c, 0x16, 0x77, - 0xc1, 0x34, 0x2d, 0x6e, 0xc8, 0x38, 0x8f, 0x1a, 0x49, 0x2a, 0x37, 0x83, 0xf3, 0xf5, 0x5b, 0xe6, - 0x3a, 0xe4, 0x1c, 0x93, 0x73, 0xcb, 0x71, 0x1e, 0xdd, 0x9d, 0xe8, 0x40, 0xc5, 0xd9, 0xfe, 0xeb, - 0x3f, 0xff, 0xff, 0xe0, 0xff, 0x6e, 0x1f, 0x59, 0x9f, 0x22, 0x14, 0xff, 0xb6, 0x56, 0x80, 0x62, - 0x1d, 0x6e, 0xac, 0xf8, 0x32, 0x9d, 0x06, 0xb1, 0x2f, 0x53, 0x8b, 0xf1, 0x3b, 0x32, 0x4e, 0x1b, - 0xc6, 0x7b, 0x09, 0x15, 0x4b, 0x30, 0x3e, 0x88, 0xeb, 0x7b, 0x72, 0x8d, 0x49, 0x53, 0xb2, 0x02, - 0x93, 0x85, 0xa4, 0x95, 0x67, 0x5a, 0x45, 0xb1, 0x17, 0x49, 0x8b, 0xe6, 0x87, 0x42, 0x53, 0x5b, - 0x9f, 0x40, 0x6c, 0xa9, 0xa4, 0x84, 0x80, 0x11, 0xfc, 0xa6, 0x2d, 0x5b, 0xa1, 0xc5, 0xf0, 0x23, - 0x05, 0x52, 0xae, 0x17, 0x67, 0x60, 0x06, 0xaf, 0xcf, 0x79, 0x61, 0x2e, 0xcd, 0x48, 0x0e, 0xf5, - 0xf5, 0x9c, 0xc1, 0x65, 0x2c, 0xfb, 0xe9, 0xe2, 0x50, 0x11, 0xce, 0x74, 0x29, 0x30, 0x62, 0x32, - 0xaa, 0xe8, 0x4b, 0xad, 0x65, 0x9a, 0x35, 0xbc, 0xb0, 0x5f, 0x78, 0x27, 0x82, 0xb0, 0x34, 0x5e, - 0xda, 0xae, 0x56, 0x71, 0xa5, 0x43, 0x2e, 0x86, 0xa1, 0xd8, 0x80, 0x9b, 0xfa, 0x3c, 0x15, 0x0e, - 0xce, 0xcb, 0xe4, 0x9c, 0xd9, 0xf3, 0x64, 0xa0, 0x76, 0x0d, 0xf8, 0xfb, 0xb2, 0x96, 0x0e, 0xce, - 0xd7, 0xc8, 0x59, 0x27, 0x96, 0x4b, 0x8a, 0xc6, 0x53, 0x30, 0x75, 0x4e, 0xa6, 0x4d, 0x95, 0xc9, - 0x86, 0x7c, 0x24, 0xf7, 0x42, 0x07, 0xdd, 0x15, 0xd2, 0x4d, 0x12, 0xb8, 0x8c, 0x1c, 0xba, 0x8e, - 0xc2, 0xc8, 0xa6, 0xd7, 0x92, 0x0e, 0x8a, 0xab, 0xa4, 0x18, 0xc6, 0xf5, 0x88, 0x2e, 0xc2, 0x98, - 0xaf, 0x3a, 0xb7, 0xe4, 0x80, 0x5f, 0x23, 0x7c, 0x94, 0x19, 0x52, 0x24, 0x2a, 0xc9, 0x43, 0x4f, - 0xbb, 0x44, 0xf0, 0x3a, 0x2b, 0x98, 0x21, 0xc5, 0x00, 0x69, 0x7d, 0x83, 0x15, 0x99, 0x91, 0xcf, - 0x05, 0x18, 0x55, 0x71, 0xb8, 0xa5, 0x62, 0x97, 0x20, 0xde, 0x24, 0x03, 0x10, 0x82, 0x82, 0x79, - 0xa8, 0xb9, 0x16, 0xe2, 0xad, 0x6d, 0xde, 0x1e, 0x5c, 0x81, 0x15, 0x98, 0xe4, 0x06, 0x15, 0xa8, - 0xd8, 0x41, 0xf1, 0x36, 0x29, 0x26, 0x0c, 0x8c, 0x6e, 0x43, 0xcb, 0x4c, 0xfb, 0xd2, 0x45, 0xf2, - 0x0e, 0xdf, 0x06, 0x21, 0x94, 0xca, 0xa6, 0x8c, 0x5b, 0x67, 0xdd, 0x0c, 0xef, 0x72, 0x2a, 0x99, - 0x41, 0xc5, 0x12, 0x8c, 0x47, 0x5e, 0x9a, 0x9d, 0xf5, 0x42, 0xa7, 0x72, 0xbc, 0x47, 0x8e, 0xb1, - 0x12, 0xa2, 0x8c, 0xe4, 0xf1, 0x20, 0x9a, 0xf7, 0x39, 0x23, 0x06, 0x46, 0x5b, 0x2f, 0xd3, 0x5e, - 0x33, 0x94, 0x8d, 0x41, 0x6c, 0x1f, 0xf0, 0xd6, 0xeb, 0xb0, 0xab, 0xa6, 0x71, 0x1e, 0x6a, 0x59, - 0x70, 0xc1, 0x49, 0xf3, 0x21, 0x57, 0xba, 0x00, 0x10, 0x7e, 0x00, 0x6e, 0xee, 0x3b, 0x26, 0x1c, - 0x64, 0x1f, 0x91, 0x6c, 0xb6, 0xcf, 0xa8, 0xa0, 0x96, 0x30, 0xa8, 0xf2, 0x63, 0x6e, 0x09, 0xb2, - 0xc7, 0xb5, 0x06, 0x33, 0x79, 0x9c, 0x79, 0x9b, 0x83, 0x65, 0xed, 0x13, 0xce, 0x5a, 0x87, 0xad, - 0x64, 0xed, 0x34, 0xcc, 0x92, 0x71, 0xb0, 0xba, 0x7e, 0xca, 0x8d, 0xb5, 0x43, 0x6f, 0x54, 0xab, - 0xfb, 0x20, 0x1c, 0x28, 0xd3, 0x79, 0x5e, 0xcb, 0x38, 0x43, 0xa6, 0x11, 0x79, 0x89, 0x83, 0xf9, - 0x3a, 0x99, 0xb9, 0xe3, 0x2f, 0x97, 0x82, 0x55, 0x2f, 0x41, 0xf9, 0xfd, 0xb0, 0x9f, 0xe5, 0x79, - 0x9c, 0xca, 0x96, 0xf2, 0xe3, 0xe0, 0x82, 0x6c, 0x3b, 0xa8, 0x3f, 0xeb, 0x29, 0xd5, 0x86, 0x81, - 0xa3, 0xf9, 0x24, 0xdc, 0x50, 0x9e, 0x55, 0x1a, 0x41, 0x94, 0xa8, 0x54, 0x5b, 0x8c, 0x9f, 0x73, - 0xa5, 0x4a, 0xee, 0x64, 0x81, 0x89, 0x65, 0x98, 0x28, 0x3e, 0xba, 0x3e, 0x92, 0x5f, 0x90, 0x68, - 0xbc, 0x4b, 0x51, 0xe3, 0x68, 0xa9, 0x28, 0xf1, 0x52, 0x97, 0xfe, 0xf7, 0x25, 0x37, 0x0e, 0x42, - 0xa8, 0x71, 0xe8, 0xad, 0x44, 0xe2, 0xb4, 0x77, 0x30, 0x7c, 0xc5, 0x8d, 0x83, 0x19, 0x52, 0xf0, - 0x81, 0xc1, 0x41, 0xf1, 0x35, 0x2b, 0x98, 0x41, 0xc5, 0x3d, 0xdd, 0x41, 0x9b, 0x4a, 0x3f, 0xc8, - 0x74, 0xea, 0xe1, 0x6a, 0x8b, 0xea, 0x9b, 0xed, 0xea, 0x21, 0x6c, 0xdd, 0x40, 0xc5, 0x29, 0x98, - 0xec, 0x39, 0x62, 0xd4, 0x6f, 0xdb, 0x63, 0x5b, 0x95, 0x59, 0xe6, 0xf9, 0xa5, 0xf0, 0xd1, 0x1d, - 0x6a, 0x46, 0xd5, 0x13, 0x86, 0xb8, 0x13, 0xeb, 0x5e, 0x3d, 0x07, 0xd8, 0x65, 0x17, 0x77, 0xca, - 0xd2, 0x57, 0x8e, 0x01, 0xe2, 0x04, 0x8c, 0x57, 0xce, 0x00, 0x76, 0xd5, 0x63, 0xa4, 0x1a, 0x33, - 0x8f, 0x00, 0xe2, 0x08, 0x0c, 0xe1, 0x3c, 0xb7, 0xe3, 0x8f, 0x13, 0x5e, 0x2c, 0x17, 0xc7, 0x60, - 0x84, 0xe7, 0xb8, 0x1d, 0x7d, 0x82, 0xd0, 0x12, 0x41, 0x9c, 0x67, 0xb8, 0x1d, 0x7f, 0x92, 0x71, - 0x46, 0x10, 0x77, 0x4f, 0xe1, 0xb7, 0x4f, 0x0f, 0x51, 0x1f, 0xe6, 0xdc, 0xcd, 0xc3, 0x30, 0x0d, - 0x6f, 0x3b, 0xfd, 0x14, 0xfd, 0x38, 0x13, 0xe2, 0x0e, 0xd8, 0xe7, 0x98, 0xf0, 0x67, 0x08, 0xed, - 0xac, 0x17, 0x4b, 0x30, 0x6a, 0x0c, 0x6c, 0x3b, 0xfe, 0x2c, 0xe1, 0x26, 0x85, 0xa1, 0xd3, 0xc0, - 0xb6, 0x0b, 0x9e, 0xe3, 0xd0, 0x89, 0xc0, 0xb4, 0xf1, 0xac, 0xb6, 0xd3, 0xcf, 0x73, 0xd6, 0x19, - 0x11, 0x0b, 0x50, 0x2b, 0xfb, 0xaf, 0x9d, 0x7f, 0x81, 0xf8, 0x2e, 0x83, 0x19, 0x30, 0xfa, 0xbf, - 0x5d, 0xf1, 0x22, 0x67, 0xc0, 0xa0, 0x70, 0x1b, 0xf5, 0xce, 0x74, 0xbb, 0xe9, 0x25, 0xde, 0x46, - 0x3d, 0x23, 0x1d, 0xab, 0x59, 0xb4, 0x41, 0xbb, 0xe2, 0x65, 0xae, 0x66, 0xb1, 0x1e, 0xc3, 0xe8, - 0x1d, 0x92, 0x76, 0xc7, 0x2b, 0x1c, 0x46, 0xcf, 0x8c, 0x14, 0x6b, 0x50, 0xdf, 0x3b, 0x20, 0xed, - 0xbe, 0x57, 0xc9, 0x37, 0xb5, 0x67, 0x3e, 0x8a, 0xfb, 0x60, 0xb6, 0xff, 0x70, 0xb4, 0x5b, 0x2f, - 0xed, 0xf4, 0xbc, 0xce, 0x98, 0xb3, 0x51, 0x9c, 0xee, 0x76, 0x59, 0x73, 0x30, 0xda, 0xb5, 0x97, - 0x77, 0xaa, 0x8d, 0xd6, 0x9c, 0x8b, 0x62, 0x11, 0xa0, 0x3b, 0x93, 0xec, 0xae, 0x2b, 0xe4, 0x32, - 0x20, 0xdc, 0x1a, 0x34, 0x92, 0xec, 0xfc, 0x55, 0xde, 0x1a, 0x44, 0xe0, 0xd6, 0xe0, 0x69, 0x64, - 0xa7, 0xaf, 0xf1, 0xd6, 0x60, 0x44, 0xcc, 0xc3, 0x48, 0x9c, 0x87, 0x21, 0x3e, 0x5b, 0xf5, 0x5b, - 0xfb, 0x8c, 0x1b, 0x19, 0xb6, 0x19, 0xfe, 0x65, 0x97, 0x60, 0x06, 0xc4, 0x11, 0xd8, 0x27, 0xa3, - 0xa6, 0x6c, 0xdb, 0xc8, 0x5f, 0x77, 0xb9, 0x9f, 0xe0, 0x6a, 0xb1, 0x00, 0xd0, 0x79, 0x99, 0xc6, - 0x28, 0x6c, 0xec, 0x6f, 0xbb, 0x9d, 0xf7, 0x7a, 0x03, 0xe9, 0x0a, 0x8a, 0xb7, 0x71, 0x8b, 0x60, - 0xbb, 0x2a, 0x28, 0x5e, 0xc0, 0x8f, 0xc2, 0xf0, 0x43, 0x99, 0x8a, 0xb5, 0xe7, 0xdb, 0xe8, 0xdf, - 0x89, 0xe6, 0xf5, 0x98, 0xb0, 0x48, 0xa5, 0x52, 0x7b, 0x7e, 0x66, 0x63, 0xff, 0x20, 0xb6, 0x04, - 0x10, 0x6e, 0x79, 0x99, 0x76, 0xb9, 0xef, 0x3f, 0x19, 0x66, 0x00, 0x83, 0xc6, 0xeb, 0x87, 0xe5, - 0x96, 0x8d, 0xfd, 0x8b, 0x83, 0xa6, 0xf5, 0xe2, 0x18, 0xd4, 0xf0, 0xb2, 0xf8, 0x3f, 0x84, 0x0d, - 0xfe, 0x9b, 0xe0, 0x2e, 0x81, 0xbf, 0x9c, 0xe9, 0xb6, 0x0e, 0xec, 0xc9, 0xfe, 0x87, 0x2a, 0xcd, - 0xeb, 0xc5, 0x22, 0x8c, 0x66, 0xba, 0xdd, 0xce, 0xe9, 0x44, 0x63, 0xc1, 0xff, 0xdd, 0x2d, 0x5f, - 0x72, 0x4b, 0xe6, 0xf8, 0x21, 0x98, 0x6e, 0xa9, 0xa8, 0x17, 0x3c, 0x0e, 0x2b, 0x6a, 0x45, 0xad, - 0x15, 0xbb, 0xe8, 0xbf, 0x00, 0x00, 0x00, 0xff, 0xff, 0x0a, 0x9c, 0xec, 0xd8, 0x50, 0x13, 0x00, - 0x00, -} diff --git a/vendor/github.com/gogo/protobuf/gogoproto/gogo.pb.golden b/vendor/github.com/gogo/protobuf/gogoproto/gogo.pb.golden deleted file mode 100644 index f6502e4b9..000000000 --- a/vendor/github.com/gogo/protobuf/gogoproto/gogo.pb.golden +++ /dev/null @@ -1,45 +0,0 @@ -// Code generated by protoc-gen-go. -// source: gogo.proto -// DO NOT EDIT! - -package gogoproto - -import proto "github.com/gogo/protobuf/proto" -import json "encoding/json" -import math "math" -import google_protobuf "github.com/gogo/protobuf/protoc-gen-gogo/descriptor" - -// Reference proto, json, and math imports to suppress error if they are not otherwise used. -var _ = proto.Marshal -var _ = &json.SyntaxError{} -var _ = math.Inf - -var E_Nullable = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FieldOptions)(nil), - ExtensionType: (*bool)(nil), - Field: 51235, - Name: "gogoproto.nullable", - Tag: "varint,51235,opt,name=nullable", -} - -var E_Embed = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FieldOptions)(nil), - ExtensionType: (*bool)(nil), - Field: 51236, - Name: "gogoproto.embed", - Tag: "varint,51236,opt,name=embed", -} - -var E_Customtype = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FieldOptions)(nil), - ExtensionType: (*string)(nil), - Field: 51237, - Name: "gogoproto.customtype", - Tag: "bytes,51237,opt,name=customtype", -} - -func init() { - proto.RegisterExtension(E_Nullable) - proto.RegisterExtension(E_Embed) - proto.RegisterExtension(E_Customtype) -} diff --git a/vendor/github.com/gogo/protobuf/gogoproto/gogo.proto b/vendor/github.com/gogo/protobuf/gogoproto/gogo.proto deleted file mode 100644 index fbca44cd4..000000000 --- a/vendor/github.com/gogo/protobuf/gogoproto/gogo.proto +++ /dev/null @@ -1,132 +0,0 @@ -// Protocol Buffers for Go with Gadgets -// -// Copyright (c) 2013, The GoGo Authors. All rights reserved. -// http://github.com/gogo/protobuf -// -// 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. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -syntax = "proto2"; -package gogoproto; - -import "google/protobuf/descriptor.proto"; - -option java_package = "com.google.protobuf"; -option java_outer_classname = "GoGoProtos"; - -extend google.protobuf.EnumOptions { - optional bool goproto_enum_prefix = 62001; - optional bool goproto_enum_stringer = 62021; - optional bool enum_stringer = 62022; - optional string enum_customname = 62023; - optional bool enumdecl = 62024; -} - -extend google.protobuf.EnumValueOptions { - optional string enumvalue_customname = 66001; -} - -extend google.protobuf.FileOptions { - optional bool goproto_getters_all = 63001; - optional bool goproto_enum_prefix_all = 63002; - optional bool goproto_stringer_all = 63003; - optional bool verbose_equal_all = 63004; - optional bool face_all = 63005; - optional bool gostring_all = 63006; - optional bool populate_all = 63007; - optional bool stringer_all = 63008; - optional bool onlyone_all = 63009; - - optional bool equal_all = 63013; - optional bool description_all = 63014; - optional bool testgen_all = 63015; - optional bool benchgen_all = 63016; - optional bool marshaler_all = 63017; - optional bool unmarshaler_all = 63018; - optional bool stable_marshaler_all = 63019; - - optional bool sizer_all = 63020; - - optional bool goproto_enum_stringer_all = 63021; - optional bool enum_stringer_all = 63022; - - optional bool unsafe_marshaler_all = 63023; - optional bool unsafe_unmarshaler_all = 63024; - - optional bool goproto_extensions_map_all = 63025; - optional bool goproto_unrecognized_all = 63026; - optional bool gogoproto_import = 63027; - optional bool protosizer_all = 63028; - optional bool compare_all = 63029; - optional bool typedecl_all = 63030; - optional bool enumdecl_all = 63031; - - optional bool goproto_registration = 63032; -} - -extend google.protobuf.MessageOptions { - optional bool goproto_getters = 64001; - optional bool goproto_stringer = 64003; - optional bool verbose_equal = 64004; - optional bool face = 64005; - optional bool gostring = 64006; - optional bool populate = 64007; - optional bool stringer = 67008; - optional bool onlyone = 64009; - - optional bool equal = 64013; - optional bool description = 64014; - optional bool testgen = 64015; - optional bool benchgen = 64016; - optional bool marshaler = 64017; - optional bool unmarshaler = 64018; - optional bool stable_marshaler = 64019; - - optional bool sizer = 64020; - - optional bool unsafe_marshaler = 64023; - optional bool unsafe_unmarshaler = 64024; - - optional bool goproto_extensions_map = 64025; - optional bool goproto_unrecognized = 64026; - - optional bool protosizer = 64028; - optional bool compare = 64029; - - optional bool typedecl = 64030; -} - -extend google.protobuf.FieldOptions { - optional bool nullable = 65001; - optional bool embed = 65002; - optional string customtype = 65003; - optional string customname = 65004; - optional string jsontag = 65005; - optional string moretags = 65006; - optional string casttype = 65007; - optional string castkey = 65008; - optional string castvalue = 65009; - - optional bool stdtime = 65010; - optional bool stdduration = 65011; -} diff --git a/vendor/github.com/gogo/protobuf/gogoproto/helper.go b/vendor/github.com/gogo/protobuf/gogoproto/helper.go deleted file mode 100644 index 6b851c562..000000000 --- a/vendor/github.com/gogo/protobuf/gogoproto/helper.go +++ /dev/null @@ -1,357 +0,0 @@ -// Protocol Buffers for Go with Gadgets -// -// Copyright (c) 2013, The GoGo Authors. All rights reserved. -// http://github.com/gogo/protobuf -// -// 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. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package gogoproto - -import google_protobuf "github.com/gogo/protobuf/protoc-gen-gogo/descriptor" -import proto "github.com/gogo/protobuf/proto" - -func IsEmbed(field *google_protobuf.FieldDescriptorProto) bool { - return proto.GetBoolExtension(field.Options, E_Embed, false) -} - -func IsNullable(field *google_protobuf.FieldDescriptorProto) bool { - return proto.GetBoolExtension(field.Options, E_Nullable, true) -} - -func IsStdTime(field *google_protobuf.FieldDescriptorProto) bool { - return proto.GetBoolExtension(field.Options, E_Stdtime, false) -} - -func IsStdDuration(field *google_protobuf.FieldDescriptorProto) bool { - return proto.GetBoolExtension(field.Options, E_Stdduration, false) -} - -func NeedsNilCheck(proto3 bool, field *google_protobuf.FieldDescriptorProto) bool { - nullable := IsNullable(field) - if field.IsMessage() || IsCustomType(field) { - return nullable - } - if proto3 { - return false - } - return nullable || *field.Type == google_protobuf.FieldDescriptorProto_TYPE_BYTES -} - -func IsCustomType(field *google_protobuf.FieldDescriptorProto) bool { - typ := GetCustomType(field) - if len(typ) > 0 { - return true - } - return false -} - -func IsCastType(field *google_protobuf.FieldDescriptorProto) bool { - typ := GetCastType(field) - if len(typ) > 0 { - return true - } - return false -} - -func IsCastKey(field *google_protobuf.FieldDescriptorProto) bool { - typ := GetCastKey(field) - if len(typ) > 0 { - return true - } - return false -} - -func IsCastValue(field *google_protobuf.FieldDescriptorProto) bool { - typ := GetCastValue(field) - if len(typ) > 0 { - return true - } - return false -} - -func HasEnumDecl(file *google_protobuf.FileDescriptorProto, enum *google_protobuf.EnumDescriptorProto) bool { - return proto.GetBoolExtension(enum.Options, E_Enumdecl, proto.GetBoolExtension(file.Options, E_EnumdeclAll, true)) -} - -func HasTypeDecl(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool { - return proto.GetBoolExtension(message.Options, E_Typedecl, proto.GetBoolExtension(file.Options, E_TypedeclAll, true)) -} - -func GetCustomType(field *google_protobuf.FieldDescriptorProto) string { - if field == nil { - return "" - } - if field.Options != nil { - v, err := proto.GetExtension(field.Options, E_Customtype) - if err == nil && v.(*string) != nil { - return *(v.(*string)) - } - } - return "" -} - -func GetCastType(field *google_protobuf.FieldDescriptorProto) string { - if field == nil { - return "" - } - if field.Options != nil { - v, err := proto.GetExtension(field.Options, E_Casttype) - if err == nil && v.(*string) != nil { - return *(v.(*string)) - } - } - return "" -} - -func GetCastKey(field *google_protobuf.FieldDescriptorProto) string { - if field == nil { - return "" - } - if field.Options != nil { - v, err := proto.GetExtension(field.Options, E_Castkey) - if err == nil && v.(*string) != nil { - return *(v.(*string)) - } - } - return "" -} - -func GetCastValue(field *google_protobuf.FieldDescriptorProto) string { - if field == nil { - return "" - } - if field.Options != nil { - v, err := proto.GetExtension(field.Options, E_Castvalue) - if err == nil && v.(*string) != nil { - return *(v.(*string)) - } - } - return "" -} - -func IsCustomName(field *google_protobuf.FieldDescriptorProto) bool { - name := GetCustomName(field) - if len(name) > 0 { - return true - } - return false -} - -func IsEnumCustomName(field *google_protobuf.EnumDescriptorProto) bool { - name := GetEnumCustomName(field) - if len(name) > 0 { - return true - } - return false -} - -func IsEnumValueCustomName(field *google_protobuf.EnumValueDescriptorProto) bool { - name := GetEnumValueCustomName(field) - if len(name) > 0 { - return true - } - return false -} - -func GetCustomName(field *google_protobuf.FieldDescriptorProto) string { - if field == nil { - return "" - } - if field.Options != nil { - v, err := proto.GetExtension(field.Options, E_Customname) - if err == nil && v.(*string) != nil { - return *(v.(*string)) - } - } - return "" -} - -func GetEnumCustomName(field *google_protobuf.EnumDescriptorProto) string { - if field == nil { - return "" - } - if field.Options != nil { - v, err := proto.GetExtension(field.Options, E_EnumCustomname) - if err == nil && v.(*string) != nil { - return *(v.(*string)) - } - } - return "" -} - -func GetEnumValueCustomName(field *google_protobuf.EnumValueDescriptorProto) string { - if field == nil { - return "" - } - if field.Options != nil { - v, err := proto.GetExtension(field.Options, E_EnumvalueCustomname) - if err == nil && v.(*string) != nil { - return *(v.(*string)) - } - } - return "" -} - -func GetJsonTag(field *google_protobuf.FieldDescriptorProto) *string { - if field == nil { - return nil - } - if field.Options != nil { - v, err := proto.GetExtension(field.Options, E_Jsontag) - if err == nil && v.(*string) != nil { - return (v.(*string)) - } - } - return nil -} - -func GetMoreTags(field *google_protobuf.FieldDescriptorProto) *string { - if field == nil { - return nil - } - if field.Options != nil { - v, err := proto.GetExtension(field.Options, E_Moretags) - if err == nil && v.(*string) != nil { - return (v.(*string)) - } - } - return nil -} - -type EnableFunc func(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool - -func EnabledGoEnumPrefix(file *google_protobuf.FileDescriptorProto, enum *google_protobuf.EnumDescriptorProto) bool { - return proto.GetBoolExtension(enum.Options, E_GoprotoEnumPrefix, proto.GetBoolExtension(file.Options, E_GoprotoEnumPrefixAll, true)) -} - -func EnabledGoStringer(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool { - return proto.GetBoolExtension(message.Options, E_GoprotoStringer, proto.GetBoolExtension(file.Options, E_GoprotoStringerAll, true)) -} - -func HasGoGetters(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool { - return proto.GetBoolExtension(message.Options, E_GoprotoGetters, proto.GetBoolExtension(file.Options, E_GoprotoGettersAll, true)) -} - -func IsUnion(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool { - return proto.GetBoolExtension(message.Options, E_Onlyone, proto.GetBoolExtension(file.Options, E_OnlyoneAll, false)) -} - -func HasGoString(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool { - return proto.GetBoolExtension(message.Options, E_Gostring, proto.GetBoolExtension(file.Options, E_GostringAll, false)) -} - -func HasEqual(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool { - return proto.GetBoolExtension(message.Options, E_Equal, proto.GetBoolExtension(file.Options, E_EqualAll, false)) -} - -func HasVerboseEqual(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool { - return proto.GetBoolExtension(message.Options, E_VerboseEqual, proto.GetBoolExtension(file.Options, E_VerboseEqualAll, false)) -} - -func IsStringer(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool { - return proto.GetBoolExtension(message.Options, E_Stringer, proto.GetBoolExtension(file.Options, E_StringerAll, false)) -} - -func IsFace(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool { - return proto.GetBoolExtension(message.Options, E_Face, proto.GetBoolExtension(file.Options, E_FaceAll, false)) -} - -func HasDescription(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool { - return proto.GetBoolExtension(message.Options, E_Description, proto.GetBoolExtension(file.Options, E_DescriptionAll, false)) -} - -func HasPopulate(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool { - return proto.GetBoolExtension(message.Options, E_Populate, proto.GetBoolExtension(file.Options, E_PopulateAll, false)) -} - -func HasTestGen(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool { - return proto.GetBoolExtension(message.Options, E_Testgen, proto.GetBoolExtension(file.Options, E_TestgenAll, false)) -} - -func HasBenchGen(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool { - return proto.GetBoolExtension(message.Options, E_Benchgen, proto.GetBoolExtension(file.Options, E_BenchgenAll, false)) -} - -func IsMarshaler(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool { - return proto.GetBoolExtension(message.Options, E_Marshaler, proto.GetBoolExtension(file.Options, E_MarshalerAll, false)) -} - -func IsUnmarshaler(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool { - return proto.GetBoolExtension(message.Options, E_Unmarshaler, proto.GetBoolExtension(file.Options, E_UnmarshalerAll, false)) -} - -func IsStableMarshaler(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool { - return proto.GetBoolExtension(message.Options, E_StableMarshaler, proto.GetBoolExtension(file.Options, E_StableMarshalerAll, false)) -} - -func IsSizer(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool { - return proto.GetBoolExtension(message.Options, E_Sizer, proto.GetBoolExtension(file.Options, E_SizerAll, false)) -} - -func IsProtoSizer(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool { - return proto.GetBoolExtension(message.Options, E_Protosizer, proto.GetBoolExtension(file.Options, E_ProtosizerAll, false)) -} - -func IsGoEnumStringer(file *google_protobuf.FileDescriptorProto, enum *google_protobuf.EnumDescriptorProto) bool { - return proto.GetBoolExtension(enum.Options, E_GoprotoEnumStringer, proto.GetBoolExtension(file.Options, E_GoprotoEnumStringerAll, true)) -} - -func IsEnumStringer(file *google_protobuf.FileDescriptorProto, enum *google_protobuf.EnumDescriptorProto) bool { - return proto.GetBoolExtension(enum.Options, E_EnumStringer, proto.GetBoolExtension(file.Options, E_EnumStringerAll, false)) -} - -func IsUnsafeMarshaler(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool { - return proto.GetBoolExtension(message.Options, E_UnsafeMarshaler, proto.GetBoolExtension(file.Options, E_UnsafeMarshalerAll, false)) -} - -func IsUnsafeUnmarshaler(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool { - return proto.GetBoolExtension(message.Options, E_UnsafeUnmarshaler, proto.GetBoolExtension(file.Options, E_UnsafeUnmarshalerAll, false)) -} - -func HasExtensionsMap(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool { - return proto.GetBoolExtension(message.Options, E_GoprotoExtensionsMap, proto.GetBoolExtension(file.Options, E_GoprotoExtensionsMapAll, true)) -} - -func HasUnrecognized(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool { - if IsProto3(file) { - return false - } - return proto.GetBoolExtension(message.Options, E_GoprotoUnrecognized, proto.GetBoolExtension(file.Options, E_GoprotoUnrecognizedAll, true)) -} - -func IsProto3(file *google_protobuf.FileDescriptorProto) bool { - return file.GetSyntax() == "proto3" -} - -func ImportsGoGoProto(file *google_protobuf.FileDescriptorProto) bool { - return proto.GetBoolExtension(file.Options, E_GogoprotoImport, true) -} - -func HasCompare(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool { - return proto.GetBoolExtension(message.Options, E_Compare, proto.GetBoolExtension(file.Options, E_CompareAll, false)) -} - -func RegistersGolangProto(file *google_protobuf.FileDescriptorProto) bool { - return proto.GetBoolExtension(file.Options, E_GoprotoRegistration, false) -} diff --git a/vendor/github.com/gogo/protobuf/install-protobuf.sh b/vendor/github.com/gogo/protobuf/install-protobuf.sh deleted file mode 100755 index fc40642e4..000000000 --- a/vendor/github.com/gogo/protobuf/install-protobuf.sh +++ /dev/null @@ -1,32 +0,0 @@ -#!/usr/bin/env bash - -set -ex - -die() { - echo "$@" >&2 - exit 1 -} - -cd /home/travis - -case "$PROTOBUF_VERSION" in -2*) - basename=protobuf-$PROTOBUF_VERSION - wget https://github.com/google/protobuf/releases/download/v$PROTOBUF_VERSION/$basename.tar.gz - tar xzf $basename.tar.gz - cd protobuf-$PROTOBUF_VERSION - ./configure --prefix=/home/travis && make -j2 && make install - ;; -3*) - basename=protoc-$PROTOBUF_VERSION-linux-x86_64 - wget https://github.com/google/protobuf/releases/download/v$PROTOBUF_VERSION/$basename.zip - unzip $basename.zip - ;; -*) - die "unknown protobuf version: $PROTOBUF_VERSION" - ;; -esac - - - - diff --git a/vendor/github.com/gogo/protobuf/jsonpb/jsonpb_test.go b/vendor/github.com/gogo/protobuf/jsonpb/jsonpb_test.go deleted file mode 100644 index c4442704f..000000000 --- a/vendor/github.com/gogo/protobuf/jsonpb/jsonpb_test.go +++ /dev/null @@ -1,783 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2015 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package jsonpb - -import ( - "bytes" - "encoding/json" - "io" - "math" - "reflect" - "strings" - "testing" - - pb "github.com/gogo/protobuf/jsonpb/jsonpb_test_proto" - "github.com/gogo/protobuf/proto" - proto3pb "github.com/gogo/protobuf/proto/proto3_proto" - "github.com/gogo/protobuf/types" -) - -var ( - marshaler = Marshaler{} - - marshalerAllOptions = Marshaler{ - Indent: " ", - } - - simpleObject = &pb.Simple{ - OInt32: proto.Int32(-32), - OInt64: proto.Int64(-6400000000), - OUint32: proto.Uint32(32), - OUint64: proto.Uint64(6400000000), - OSint32: proto.Int32(-13), - OSint64: proto.Int64(-2600000000), - OFloat: proto.Float32(3.14), - ODouble: proto.Float64(6.02214179e23), - OBool: proto.Bool(true), - OString: proto.String("hello \"there\""), - OBytes: []byte("beep boop"), - OCastBytes: pb.Bytes("wow"), - } - - simpleObjectJSON = `{` + - `"oBool":true,` + - `"oInt32":-32,` + - `"oInt64":"-6400000000",` + - `"oUint32":32,` + - `"oUint64":"6400000000",` + - `"oSint32":-13,` + - `"oSint64":"-2600000000",` + - `"oFloat":3.14,` + - `"oDouble":6.02214179e+23,` + - `"oString":"hello \"there\"",` + - `"oBytes":"YmVlcCBib29w",` + - `"oCastBytes":"d293"` + - `}` - - simpleObjectPrettyJSON = `{ - "oBool": true, - "oInt32": -32, - "oInt64": "-6400000000", - "oUint32": 32, - "oUint64": "6400000000", - "oSint32": -13, - "oSint64": "-2600000000", - "oFloat": 3.14, - "oDouble": 6.02214179e+23, - "oString": "hello \"there\"", - "oBytes": "YmVlcCBib29w", - "oCastBytes": "d293" -}` - - repeatsObject = &pb.Repeats{ - RBool: []bool{true, false, true}, - RInt32: []int32{-3, -4, -5}, - RInt64: []int64{-123456789, -987654321}, - RUint32: []uint32{1, 2, 3}, - RUint64: []uint64{6789012345, 3456789012}, - RSint32: []int32{-1, -2, -3}, - RSint64: []int64{-6789012345, -3456789012}, - RFloat: []float32{3.14, 6.28}, - RDouble: []float64{299792458 * 1e20, 6.62606957e-34}, - RString: []string{"happy", "days"}, - RBytes: [][]byte{[]byte("skittles"), []byte("m&m's")}, - } - - repeatsObjectJSON = `{` + - `"rBool":[true,false,true],` + - `"rInt32":[-3,-4,-5],` + - `"rInt64":["-123456789","-987654321"],` + - `"rUint32":[1,2,3],` + - `"rUint64":["6789012345","3456789012"],` + - `"rSint32":[-1,-2,-3],` + - `"rSint64":["-6789012345","-3456789012"],` + - `"rFloat":[3.14,6.28],` + - `"rDouble":[2.99792458e+28,6.62606957e-34],` + - `"rString":["happy","days"],` + - `"rBytes":["c2tpdHRsZXM=","bSZtJ3M="]` + - `}` - - repeatsObjectPrettyJSON = `{ - "rBool": [ - true, - false, - true - ], - "rInt32": [ - -3, - -4, - -5 - ], - "rInt64": [ - "-123456789", - "-987654321" - ], - "rUint32": [ - 1, - 2, - 3 - ], - "rUint64": [ - "6789012345", - "3456789012" - ], - "rSint32": [ - -1, - -2, - -3 - ], - "rSint64": [ - "-6789012345", - "-3456789012" - ], - "rFloat": [ - 3.14, - 6.28 - ], - "rDouble": [ - 2.99792458e+28, - 6.62606957e-34 - ], - "rString": [ - "happy", - "days" - ], - "rBytes": [ - "c2tpdHRsZXM=", - "bSZtJ3M=" - ] -}` - - innerSimple = &pb.Simple{OInt32: proto.Int32(-32)} - innerSimple2 = &pb.Simple{OInt64: proto.Int64(25)} - innerRepeats = &pb.Repeats{RString: []string{"roses", "red"}} - innerRepeats2 = &pb.Repeats{RString: []string{"violets", "blue"}} - complexObject = &pb.Widget{ - Color: pb.Widget_GREEN.Enum(), - RColor: []pb.Widget_Color{pb.Widget_RED, pb.Widget_GREEN, pb.Widget_BLUE}, - Simple: innerSimple, - RSimple: []*pb.Simple{innerSimple, innerSimple2}, - Repeats: innerRepeats, - RRepeats: []*pb.Repeats{innerRepeats, innerRepeats2}, - } - - complexObjectJSON = `{"color":"GREEN",` + - `"rColor":["RED","GREEN","BLUE"],` + - `"simple":{"oInt32":-32},` + - `"rSimple":[{"oInt32":-32},{"oInt64":"25"}],` + - `"repeats":{"rString":["roses","red"]},` + - `"rRepeats":[{"rString":["roses","red"]},{"rString":["violets","blue"]}]` + - `}` - - complexObjectPrettyJSON = `{ - "color": "GREEN", - "rColor": [ - "RED", - "GREEN", - "BLUE" - ], - "simple": { - "oInt32": -32 - }, - "rSimple": [ - { - "oInt32": -32 - }, - { - "oInt64": "25" - } - ], - "repeats": { - "rString": [ - "roses", - "red" - ] - }, - "rRepeats": [ - { - "rString": [ - "roses", - "red" - ] - }, - { - "rString": [ - "violets", - "blue" - ] - } - ] -}` - - colorPrettyJSON = `{ - "color": 2 -}` - - colorListPrettyJSON = `{ - "color": 1000, - "rColor": [ - "RED" - ] -}` - - nummyPrettyJSON = `{ - "nummy": { - "1": 2, - "3": 4 - } -}` - - objjyPrettyJSON = `{ - "objjy": { - "1": { - "dub": 1 - } - } -}` - realNumber = &pb.Real{Value: proto.Float64(3.14159265359)} - realNumberName = "Pi" - complexNumber = &pb.Complex{Imaginary: proto.Float64(0.5772156649)} - realNumberJSON = `{` + - `"value":3.14159265359,` + - `"[jsonpb.Complex.real_extension]":{"imaginary":0.5772156649},` + - `"[jsonpb.name]":"Pi"` + - `}` - - anySimple = &pb.KnownTypes{ - An: &types.Any{ - TypeUrl: "something.example.com/jsonpb.Simple", - Value: []byte{ - // &pb.Simple{OBool:true} - 1 << 3, 1, - }, - }, - } - anySimpleJSON = `{"an":{"@type":"something.example.com/jsonpb.Simple","oBool":true}}` - anySimplePrettyJSON = `{ - "an": { - "@type": "something.example.com/jsonpb.Simple", - "oBool": true - } -}` - - anyWellKnown = &pb.KnownTypes{ - An: &types.Any{ - TypeUrl: "type.googleapis.com/google.protobuf.Duration", - Value: []byte{ - // &durpb.Duration{Seconds: 1, Nanos: 212000000 } - 1 << 3, 1, // seconds - 2 << 3, 0x80, 0xba, 0x8b, 0x65, // nanos - }, - }, - } - anyWellKnownJSON = `{"an":{"@type":"type.googleapis.com/google.protobuf.Duration","value":"1.212s"}}` - anyWellKnownPrettyJSON = `{ - "an": { - "@type": "type.googleapis.com/google.protobuf.Duration", - "value": "1.212s" - } -}` - - nonFinites = &pb.NonFinites{ - FNan: proto.Float32(float32(math.NaN())), - FPinf: proto.Float32(float32(math.Inf(1))), - FNinf: proto.Float32(float32(math.Inf(-1))), - DNan: proto.Float64(float64(math.NaN())), - DPinf: proto.Float64(float64(math.Inf(1))), - DNinf: proto.Float64(float64(math.Inf(-1))), - } - nonFinitesJSON = `{` + - `"fNan":"NaN",` + - `"fPinf":"Infinity",` + - `"fNinf":"-Infinity",` + - `"dNan":"NaN",` + - `"dPinf":"Infinity",` + - `"dNinf":"-Infinity"` + - `}` -) - -func init() { - if err := proto.SetExtension(realNumber, pb.E_Name, &realNumberName); err != nil { - panic(err) - } - if err := proto.SetExtension(realNumber, pb.E_Complex_RealExtension, complexNumber); err != nil { - panic(err) - } -} - -var marshalingTests = []struct { - desc string - marshaler Marshaler - pb proto.Message - json string -}{ - {"simple flat object", marshaler, simpleObject, simpleObjectJSON}, - {"simple pretty object", marshalerAllOptions, simpleObject, simpleObjectPrettyJSON}, - {"non-finite floats fields object", marshaler, nonFinites, nonFinitesJSON}, - {"repeated fields flat object", marshaler, repeatsObject, repeatsObjectJSON}, - {"repeated fields pretty object", marshalerAllOptions, repeatsObject, repeatsObjectPrettyJSON}, - {"nested message/enum flat object", marshaler, complexObject, complexObjectJSON}, - {"nested message/enum pretty object", marshalerAllOptions, complexObject, complexObjectPrettyJSON}, - {"enum-string flat object", Marshaler{}, - &pb.Widget{Color: pb.Widget_BLUE.Enum()}, `{"color":"BLUE"}`}, - {"enum-value pretty object", Marshaler{EnumsAsInts: true, Indent: " "}, - &pb.Widget{Color: pb.Widget_BLUE.Enum()}, colorPrettyJSON}, - {"unknown enum value object", marshalerAllOptions, - &pb.Widget{Color: pb.Widget_Color(1000).Enum(), RColor: []pb.Widget_Color{pb.Widget_RED}}, colorListPrettyJSON}, - {"repeated proto3 enum", Marshaler{}, - &proto3pb.Message{RFunny: []proto3pb.Message_Humour{ - proto3pb.Message_PUNS, - proto3pb.Message_SLAPSTICK, - }}, - `{"rFunny":["PUNS","SLAPSTICK"]}`}, - {"repeated proto3 enum as int", Marshaler{EnumsAsInts: true}, - &proto3pb.Message{RFunny: []proto3pb.Message_Humour{ - proto3pb.Message_PUNS, - proto3pb.Message_SLAPSTICK, - }}, - `{"rFunny":[1,2]}`}, - {"empty value", marshaler, &pb.Simple3{}, `{}`}, - {"empty value emitted", Marshaler{EmitDefaults: true}, &pb.Simple3{}, `{"dub":0}`}, - {"empty repeated emitted", Marshaler{EmitDefaults: true}, &pb.SimpleSlice3{}, `{"slices":[]}`}, - {"empty map emitted", Marshaler{EmitDefaults: true}, &pb.SimpleMap3{}, `{"stringy":{}}`}, - {"nested struct null", Marshaler{EmitDefaults: true}, &pb.SimpleNull3{}, `{"simple":null}`}, - {"map", marshaler, &pb.Mappy{Nummy: map[int64]int32{1: 2, 3: 4}}, `{"nummy":{"1":2,"3":4}}`}, - {"map", marshalerAllOptions, &pb.Mappy{Nummy: map[int64]int32{1: 2, 3: 4}}, nummyPrettyJSON}, - {"map", marshaler, - &pb.Mappy{Strry: map[string]string{`"one"`: "two", "three": "four"}}, - `{"strry":{"\"one\"":"two","three":"four"}}`}, - {"map", marshaler, - &pb.Mappy{Objjy: map[int32]*pb.Simple3{1: {Dub: 1}}}, `{"objjy":{"1":{"dub":1}}}`}, - {"map", marshalerAllOptions, - &pb.Mappy{Objjy: map[int32]*pb.Simple3{1: {Dub: 1}}}, objjyPrettyJSON}, - {"map", marshaler, &pb.Mappy{Buggy: map[int64]string{1234: "yup"}}, - `{"buggy":{"1234":"yup"}}`}, - {"map", marshaler, &pb.Mappy{Booly: map[bool]bool{false: true}}, `{"booly":{"false":true}}`}, - // TODO: This is broken. - //{"map", marshaler, &pb.Mappy{Enumy: map[string]pb.Numeral{"XIV": pb.Numeral_ROMAN}}, `{"enumy":{"XIV":"ROMAN"}`}, - {"map", Marshaler{EnumsAsInts: true}, &pb.Mappy{Enumy: map[string]pb.Numeral{"XIV": pb.Numeral_ROMAN}}, `{"enumy":{"XIV":2}}`}, - {"map", marshaler, &pb.Mappy{S32Booly: map[int32]bool{1: true, 3: false, 10: true, 12: false}}, `{"s32booly":{"1":true,"3":false,"10":true,"12":false}}`}, - {"map", marshaler, &pb.Mappy{S64Booly: map[int64]bool{1: true, 3: false, 10: true, 12: false}}, `{"s64booly":{"1":true,"3":false,"10":true,"12":false}}`}, - {"map", marshaler, &pb.Mappy{U32Booly: map[uint32]bool{1: true, 3: false, 10: true, 12: false}}, `{"u32booly":{"1":true,"3":false,"10":true,"12":false}}`}, - {"map", marshaler, &pb.Mappy{U64Booly: map[uint64]bool{1: true, 3: false, 10: true, 12: false}}, `{"u64booly":{"1":true,"3":false,"10":true,"12":false}}`}, - {"proto2 map", marshaler, &pb.Maps{MInt64Str: map[int64]string{213: "cat"}}, - `{"mInt64Str":{"213":"cat"}}`}, - {"proto2 map", marshaler, - &pb.Maps{MBoolSimple: map[bool]*pb.Simple{true: {OInt32: proto.Int32(1)}}}, - `{"mBoolSimple":{"true":{"oInt32":1}}}`}, - {"oneof, not set", marshaler, &pb.MsgWithOneof{}, `{}`}, - {"oneof, set", marshaler, &pb.MsgWithOneof{Union: &pb.MsgWithOneof_Title{Title: "Grand Poobah"}}, `{"title":"Grand Poobah"}`}, - {"force orig_name", Marshaler{OrigName: true}, &pb.Simple{OInt32: proto.Int32(4)}, - `{"o_int32":4}`}, - {"proto2 extension", marshaler, realNumber, realNumberJSON}, - {"Any with message", marshaler, anySimple, anySimpleJSON}, - {"Any with message and indent", marshalerAllOptions, anySimple, anySimplePrettyJSON}, - {"Any with WKT", marshaler, anyWellKnown, anyWellKnownJSON}, - {"Any with WKT and indent", marshalerAllOptions, anyWellKnown, anyWellKnownPrettyJSON}, - {"Duration", marshaler, &pb.KnownTypes{Dur: &types.Duration{Seconds: 3}}, `{"dur":"3.000s"}`}, - {"Struct", marshaler, &pb.KnownTypes{St: &types.Struct{ - Fields: map[string]*types.Value{ - "one": {Kind: &types.Value_StringValue{StringValue: "loneliest number"}}, - "two": {Kind: &types.Value_NullValue{NullValue: types.NULL_VALUE}}, - }, - }}, `{"st":{"one":"loneliest number","two":null}}`}, - {"empty ListValue", marshaler, &pb.KnownTypes{Lv: &types.ListValue{}}, `{"lv":[]}`}, - {"basic ListValue", marshaler, &pb.KnownTypes{Lv: &types.ListValue{Values: []*types.Value{ - {Kind: &types.Value_StringValue{StringValue: "x"}}, - {Kind: &types.Value_NullValue{}}, - {Kind: &types.Value_NumberValue{NumberValue: 3}}, - {Kind: &types.Value_BoolValue{BoolValue: true}}, - }}}, `{"lv":["x",null,3,true]}`}, - {"Timestamp", marshaler, &pb.KnownTypes{Ts: &types.Timestamp{Seconds: 14e8, Nanos: 21e6}}, `{"ts":"2014-05-13T16:53:20.021Z"}`}, - {"number Value", marshaler, &pb.KnownTypes{Val: &types.Value{Kind: &types.Value_NumberValue{NumberValue: 1}}}, `{"val":1}`}, - {"null Value", marshaler, &pb.KnownTypes{Val: &types.Value{Kind: &types.Value_NullValue{NullValue: types.NULL_VALUE}}}, `{"val":null}`}, - {"string number value", marshaler, &pb.KnownTypes{Val: &types.Value{Kind: &types.Value_StringValue{StringValue: "9223372036854775807"}}}, `{"val":"9223372036854775807"}`}, - {"list of lists Value", marshaler, &pb.KnownTypes{Val: &types.Value{ - Kind: &types.Value_ListValue{ListValue: &types.ListValue{ - Values: []*types.Value{ - {Kind: &types.Value_StringValue{StringValue: "x"}}, - {Kind: &types.Value_ListValue{ListValue: &types.ListValue{ - Values: []*types.Value{ - {Kind: &types.Value_ListValue{ListValue: &types.ListValue{ - Values: []*types.Value{{Kind: &types.Value_StringValue{StringValue: "y"}}}, - }}}, - {Kind: &types.Value_StringValue{StringValue: "z"}}, - }, - }}}, - }, - }}, - }}, `{"val":["x",[["y"],"z"]]}`}, - {"DoubleValue", marshaler, &pb.KnownTypes{Dbl: &types.DoubleValue{Value: 1.2}}, `{"dbl":1.2}`}, - {"FloatValue", marshaler, &pb.KnownTypes{Flt: &types.FloatValue{Value: 1.2}}, `{"flt":1.2}`}, - {"Int64Value", marshaler, &pb.KnownTypes{I64: &types.Int64Value{Value: -3}}, `{"i64":"-3"}`}, - {"UInt64Value", marshaler, &pb.KnownTypes{U64: &types.UInt64Value{Value: 3}}, `{"u64":"3"}`}, - {"Int32Value", marshaler, &pb.KnownTypes{I32: &types.Int32Value{Value: -4}}, `{"i32":-4}`}, - {"UInt32Value", marshaler, &pb.KnownTypes{U32: &types.UInt32Value{Value: 4}}, `{"u32":4}`}, - {"BoolValue", marshaler, &pb.KnownTypes{Bool: &types.BoolValue{Value: true}}, `{"bool":true}`}, - {"StringValue", marshaler, &pb.KnownTypes{Str: &types.StringValue{Value: "plush"}}, `{"str":"plush"}`}, - {"BytesValue", marshaler, &pb.KnownTypes{Bytes: &types.BytesValue{Value: []byte("wow")}}, `{"bytes":"d293"}`}, -} - -func TestMarshaling(t *testing.T) { - for _, tt := range marshalingTests { - json, err := tt.marshaler.MarshalToString(tt.pb) - if err != nil { - t.Errorf("%s: marshaling error: %v", tt.desc, err) - } else if tt.json != json { - t.Errorf("%s: got [%v] want [%v]", tt.desc, json, tt.json) - } - } -} - -func TestMarshalJSONPBMarshaler(t *testing.T) { - rawJson := `{ "foo": "bar", "baz": [0, 1, 2, 3] }` - msg := dynamicMessage{rawJson: rawJson} - str, err := new(Marshaler).MarshalToString(&msg) - if err != nil { - t.Errorf("an unexpected error occurred when marshalling JSONPBMarshaler: %v", err) - } - if str != rawJson { - t.Errorf("marshalling JSON produced incorrect output: got %s, wanted %s", str, rawJson) - } -} - -func TestMarshalAnyJSONPBMarshaler(t *testing.T) { - msg := dynamicMessage{rawJson: `{ "foo": "bar", "baz": [0, 1, 2, 3] }`} - a, err := types.MarshalAny(&msg) - if err != nil { - t.Errorf("an unexpected error occurred when marshalling to Any: %v", err) - } - str, err := new(Marshaler).MarshalToString(a) - if err != nil { - t.Errorf("an unexpected error occurred when marshalling Any to JSON: %v", err) - } - // after custom marshaling, it's round-tripped through JSON decoding/encoding already, - // so the keys are sorted, whitespace is compacted, and "@type" key has been added - expected := `{"@type":"type.googleapis.com/` + dynamicMessageName + `","baz":[0,1,2,3],"foo":"bar"}` - if str != expected { - t.Errorf("marshalling JSON produced incorrect output: got %s, wanted %s", str, expected) - } -} - -var unmarshalingTests = []struct { - desc string - unmarshaler Unmarshaler - json string - pb proto.Message -}{ - {"simple flat object", Unmarshaler{}, simpleObjectJSON, simpleObject}, - {"simple pretty object", Unmarshaler{}, simpleObjectPrettyJSON, simpleObject}, - {"repeated fields flat object", Unmarshaler{}, repeatsObjectJSON, repeatsObject}, - {"repeated fields pretty object", Unmarshaler{}, repeatsObjectPrettyJSON, repeatsObject}, - {"nested message/enum flat object", Unmarshaler{}, complexObjectJSON, complexObject}, - {"nested message/enum pretty object", Unmarshaler{}, complexObjectPrettyJSON, complexObject}, - {"enum-string object", Unmarshaler{}, `{"color":"BLUE"}`, &pb.Widget{Color: pb.Widget_BLUE.Enum()}}, - {"enum-value object", Unmarshaler{}, "{\n \"color\": 2\n}", &pb.Widget{Color: pb.Widget_BLUE.Enum()}}, - {"unknown field with allowed option", Unmarshaler{AllowUnknownFields: true}, `{"unknown": "foo"}`, new(pb.Simple)}, - {"proto3 enum string", Unmarshaler{}, `{"hilarity":"PUNS"}`, &proto3pb.Message{Hilarity: proto3pb.Message_PUNS}}, - {"proto3 enum value", Unmarshaler{}, `{"hilarity":1}`, &proto3pb.Message{Hilarity: proto3pb.Message_PUNS}}, - {"unknown enum value object", - Unmarshaler{}, - "{\n \"color\": 1000,\n \"r_color\": [\n \"RED\"\n ]\n}", - &pb.Widget{Color: pb.Widget_Color(1000).Enum(), RColor: []pb.Widget_Color{pb.Widget_RED}}}, - {"repeated proto3 enum", Unmarshaler{}, `{"rFunny":["PUNS","SLAPSTICK"]}`, - &proto3pb.Message{RFunny: []proto3pb.Message_Humour{ - proto3pb.Message_PUNS, - proto3pb.Message_SLAPSTICK, - }}}, - {"repeated proto3 enum as int", Unmarshaler{}, `{"rFunny":[1,2]}`, - &proto3pb.Message{RFunny: []proto3pb.Message_Humour{ - proto3pb.Message_PUNS, - proto3pb.Message_SLAPSTICK, - }}}, - {"repeated proto3 enum as mix of strings and ints", Unmarshaler{}, `{"rFunny":["PUNS",2]}`, - &proto3pb.Message{RFunny: []proto3pb.Message_Humour{ - proto3pb.Message_PUNS, - proto3pb.Message_SLAPSTICK, - }}}, - {"unquoted int64 object", Unmarshaler{}, `{"oInt64":-314}`, &pb.Simple{OInt64: proto.Int64(-314)}}, - {"unquoted uint64 object", Unmarshaler{}, `{"oUint64":123}`, &pb.Simple{OUint64: proto.Uint64(123)}}, - {"NaN", Unmarshaler{}, `{"oDouble":"NaN"}`, &pb.Simple{ODouble: proto.Float64(math.NaN())}}, - {"Inf", Unmarshaler{}, `{"oFloat":"Infinity"}`, &pb.Simple{OFloat: proto.Float32(float32(math.Inf(1)))}}, - {"-Inf", Unmarshaler{}, `{"oDouble":"-Infinity"}`, &pb.Simple{ODouble: proto.Float64(math.Inf(-1))}}, - {"map", Unmarshaler{}, `{"nummy":{"1":2,"3":4}}`, &pb.Mappy{Nummy: map[int64]int32{1: 2, 3: 4}}}, - {"map", Unmarshaler{}, `{"strry":{"\"one\"":"two","three":"four"}}`, &pb.Mappy{Strry: map[string]string{`"one"`: "two", "three": "four"}}}, - {"map", Unmarshaler{}, `{"objjy":{"1":{"dub":1}}}`, &pb.Mappy{Objjy: map[int32]*pb.Simple3{1: {Dub: 1}}}}, - {"proto2 extension", Unmarshaler{}, realNumberJSON, realNumber}, - // TODO does not work with go version 1.7, but works with go version 1.8 {"Any with message", Unmarshaler{}, anySimpleJSON, anySimple}, - // TODO does not work with go version 1.7, but works with go version 1.8 {"Any with message and indent", Unmarshaler{}, anySimplePrettyJSON, anySimple}, - {"Any with WKT", Unmarshaler{}, anyWellKnownJSON, anyWellKnown}, - {"Any with WKT and indent", Unmarshaler{}, anyWellKnownPrettyJSON, anyWellKnown}, - // TODO: This is broken. - //{"map", Unmarshaler{}, `{"enumy":{"XIV":"ROMAN"}`, &pb.Mappy{Enumy: map[string]pb.Numeral{"XIV": pb.Numeral_ROMAN}}}, - {"map", Unmarshaler{}, `{"enumy":{"XIV":2}}`, &pb.Mappy{Enumy: map[string]pb.Numeral{"XIV": pb.Numeral_ROMAN}}}, - {"oneof", Unmarshaler{}, `{"salary":31000}`, &pb.MsgWithOneof{Union: &pb.MsgWithOneof_Salary{Salary: 31000}}}, - {"oneof spec name", Unmarshaler{}, `{"Country":"Australia"}`, &pb.MsgWithOneof{Union: &pb.MsgWithOneof_Country{Country: "Australia"}}}, - {"oneof orig_name", Unmarshaler{}, `{"Country":"Australia"}`, &pb.MsgWithOneof{Union: &pb.MsgWithOneof_Country{Country: "Australia"}}}, - {"oneof spec name2", Unmarshaler{}, `{"homeAddress":"Australia"}`, &pb.MsgWithOneof{Union: &pb.MsgWithOneof_HomeAddress{HomeAddress: "Australia"}}}, - {"oneof orig_name2", Unmarshaler{}, `{"home_address":"Australia"}`, &pb.MsgWithOneof{Union: &pb.MsgWithOneof_HomeAddress{HomeAddress: "Australia"}}}, - {"orig_name input", Unmarshaler{}, `{"o_bool":true}`, &pb.Simple{OBool: proto.Bool(true)}}, - {"camelName input", Unmarshaler{}, `{"oBool":true}`, &pb.Simple{OBool: proto.Bool(true)}}, - {"Duration", Unmarshaler{}, `{"dur":"3.000s"}`, &pb.KnownTypes{Dur: &types.Duration{Seconds: 3}}}, - {"null Duration", Unmarshaler{}, `{"dur":null}`, &pb.KnownTypes{Dur: nil}}, - {"Timestamp", Unmarshaler{}, `{"ts":"2014-05-13T16:53:20.021Z"}`, &pb.KnownTypes{Ts: &types.Timestamp{Seconds: 14e8, Nanos: 21e6}}}, - {"PreEpochTimestamp", Unmarshaler{}, `{"ts":"1969-12-31T23:59:58.999999995Z"}`, &pb.KnownTypes{Ts: &types.Timestamp{Seconds: -2, Nanos: 999999995}}}, - {"ZeroTimeTimestamp", Unmarshaler{}, `{"ts":"0001-01-01T00:00:00Z"}`, &pb.KnownTypes{Ts: &types.Timestamp{Seconds: -62135596800, Nanos: 0}}}, - {"null Timestamp", Unmarshaler{}, `{"ts":null}`, &pb.KnownTypes{Ts: nil}}, - {"null Struct", Unmarshaler{}, `{"st": null}`, &pb.KnownTypes{St: nil}}, - {"empty Struct", Unmarshaler{}, `{"st": {}}`, &pb.KnownTypes{St: &types.Struct{}}}, - {"basic Struct", Unmarshaler{}, `{"st": {"a": "x", "b": null, "c": 3, "d": true}}`, &pb.KnownTypes{St: &types.Struct{Fields: map[string]*types.Value{ - "a": {Kind: &types.Value_StringValue{StringValue: "x"}}, - "b": {Kind: &types.Value_NullValue{}}, - "c": {Kind: &types.Value_NumberValue{NumberValue: 3}}, - "d": {Kind: &types.Value_BoolValue{BoolValue: true}}, - }}}}, - {"nested Struct", Unmarshaler{}, `{"st": {"a": {"b": 1, "c": [{"d": true}, "f"]}}}`, &pb.KnownTypes{St: &types.Struct{Fields: map[string]*types.Value{ - "a": {Kind: &types.Value_StructValue{StructValue: &types.Struct{Fields: map[string]*types.Value{ - "b": {Kind: &types.Value_NumberValue{NumberValue: 1}}, - "c": {Kind: &types.Value_ListValue{ListValue: &types.ListValue{Values: []*types.Value{ - {Kind: &types.Value_StructValue{StructValue: &types.Struct{Fields: map[string]*types.Value{"d": {Kind: &types.Value_BoolValue{BoolValue: true}}}}}}, - {Kind: &types.Value_StringValue{StringValue: "f"}}, - }}}}, - }}}}, - }}}}, - {"null ListValue", Unmarshaler{}, `{"lv": null}`, &pb.KnownTypes{Lv: nil}}, - {"empty ListValue", Unmarshaler{}, `{"lv": []}`, &pb.KnownTypes{Lv: &types.ListValue{}}}, - {"basic ListValue", Unmarshaler{}, `{"lv": ["x", null, 3, true]}`, &pb.KnownTypes{Lv: &types.ListValue{Values: []*types.Value{ - {Kind: &types.Value_StringValue{StringValue: "x"}}, - {Kind: &types.Value_NullValue{}}, - {Kind: &types.Value_NumberValue{NumberValue: 3}}, - {Kind: &types.Value_BoolValue{BoolValue: true}}, - }}}}, - {"number Value", Unmarshaler{}, `{"val":1}`, &pb.KnownTypes{Val: &types.Value{Kind: &types.Value_NumberValue{NumberValue: 1}}}}, - {"null Value", Unmarshaler{}, `{"val":null}`, &pb.KnownTypes{Val: &types.Value{Kind: &types.Value_NullValue{NullValue: types.NULL_VALUE}}}}, - {"bool Value", Unmarshaler{}, `{"val":true}`, &pb.KnownTypes{Val: &types.Value{Kind: &types.Value_BoolValue{BoolValue: true}}}}, - {"string Value", Unmarshaler{}, `{"val":"x"}`, &pb.KnownTypes{Val: &types.Value{Kind: &types.Value_StringValue{StringValue: "x"}}}}, - {"string number value", Unmarshaler{}, `{"val":"9223372036854775807"}`, &pb.KnownTypes{Val: &types.Value{Kind: &types.Value_StringValue{StringValue: "9223372036854775807"}}}}, - {"list of lists Value", Unmarshaler{}, `{"val":["x", [["y"], "z"]]}`, &pb.KnownTypes{Val: &types.Value{ - Kind: &types.Value_ListValue{ListValue: &types.ListValue{ - Values: []*types.Value{ - {Kind: &types.Value_StringValue{StringValue: "x"}}, - {Kind: &types.Value_ListValue{ListValue: &types.ListValue{ - Values: []*types.Value{ - {Kind: &types.Value_ListValue{ListValue: &types.ListValue{ - Values: []*types.Value{{Kind: &types.Value_StringValue{StringValue: "y"}}}, - }}}, - {Kind: &types.Value_StringValue{StringValue: "z"}}, - }, - }}}, - }, - }}}}}, - - {"DoubleValue", Unmarshaler{}, `{"dbl":1.2}`, &pb.KnownTypes{Dbl: &types.DoubleValue{Value: 1.2}}}, - {"FloatValue", Unmarshaler{}, `{"flt":1.2}`, &pb.KnownTypes{Flt: &types.FloatValue{Value: 1.2}}}, - {"Int64Value", Unmarshaler{}, `{"i64":"-3"}`, &pb.KnownTypes{I64: &types.Int64Value{Value: -3}}}, - {"UInt64Value", Unmarshaler{}, `{"u64":"3"}`, &pb.KnownTypes{U64: &types.UInt64Value{Value: 3}}}, - {"Int32Value", Unmarshaler{}, `{"i32":-4}`, &pb.KnownTypes{I32: &types.Int32Value{Value: -4}}}, - {"UInt32Value", Unmarshaler{}, `{"u32":4}`, &pb.KnownTypes{U32: &types.UInt32Value{Value: 4}}}, - {"BoolValue", Unmarshaler{}, `{"bool":true}`, &pb.KnownTypes{Bool: &types.BoolValue{Value: true}}}, - {"StringValue", Unmarshaler{}, `{"str":"plush"}`, &pb.KnownTypes{Str: &types.StringValue{Value: "plush"}}}, - {"BytesValue", Unmarshaler{}, `{"bytes":"d293"}`, &pb.KnownTypes{Bytes: &types.BytesValue{Value: []byte("wow")}}}, - // Ensure that `null` as a value ends up with a nil pointer instead of a [type]Value struct. - {"null DoubleValue", Unmarshaler{}, `{"dbl":null}`, &pb.KnownTypes{Dbl: nil}}, - {"null FloatValue", Unmarshaler{}, `{"flt":null}`, &pb.KnownTypes{Flt: nil}}, - {"null Int64Value", Unmarshaler{}, `{"i64":null}`, &pb.KnownTypes{I64: nil}}, - {"null UInt64Value", Unmarshaler{}, `{"u64":null}`, &pb.KnownTypes{U64: nil}}, - {"null Int32Value", Unmarshaler{}, `{"i32":null}`, &pb.KnownTypes{I32: nil}}, - {"null UInt32Value", Unmarshaler{}, `{"u32":null}`, &pb.KnownTypes{U32: nil}}, - {"null BoolValue", Unmarshaler{}, `{"bool":null}`, &pb.KnownTypes{Bool: nil}}, - {"null StringValue", Unmarshaler{}, `{"str":null}`, &pb.KnownTypes{Str: nil}}, - {"null BytesValue", Unmarshaler{}, `{"bytes":null}`, &pb.KnownTypes{Bytes: nil}}, -} - -func TestUnmarshaling(t *testing.T) { - for _, tt := range unmarshalingTests { - // Make a new instance of the type of our expected object. - p := reflect.New(reflect.TypeOf(tt.pb).Elem()).Interface().(proto.Message) - - err := tt.unmarshaler.Unmarshal(strings.NewReader(tt.json), p) - if err != nil { - t.Errorf("%s: %v", tt.desc, err) - continue - } - - // For easier diffs, compare text strings of the protos. - exp := proto.MarshalTextString(tt.pb) - act := proto.MarshalTextString(p) - if string(exp) != string(act) { - t.Errorf("%s: got [%s] want [%s]", tt.desc, act, exp) - } - } -} - -func TestUnmarshalNullArray(t *testing.T) { - var repeats pb.Repeats - if err := UnmarshalString(`{"rBool":null}`, &repeats); err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(repeats, pb.Repeats{}) { - t.Errorf("got non-nil fields in [%#v]", repeats) - } -} - -func TestUnmarshalNullObject(t *testing.T) { - var maps pb.Maps - if err := UnmarshalString(`{"mInt64Str":null}`, &maps); err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(maps, pb.Maps{}) { - t.Errorf("got non-nil fields in [%#v]", maps) - } -} - -func TestUnmarshalNext(t *testing.T) { - // We only need to check against a few, not all of them. - tests := unmarshalingTests[:5] - - // Create a buffer with many concatenated JSON objects. - var b bytes.Buffer - for _, tt := range tests { - b.WriteString(tt.json) - } - - dec := json.NewDecoder(&b) - for _, tt := range tests { - // Make a new instance of the type of our expected object. - p := reflect.New(reflect.TypeOf(tt.pb).Elem()).Interface().(proto.Message) - - err := tt.unmarshaler.UnmarshalNext(dec, p) - if err != nil { - t.Errorf("%s: %v", tt.desc, err) - continue - } - - // For easier diffs, compare text strings of the protos. - exp := proto.MarshalTextString(tt.pb) - act := proto.MarshalTextString(p) - if string(exp) != string(act) { - t.Errorf("%s: got [%s] want [%s]", tt.desc, act, exp) - } - } - - p := &pb.Simple{} - err := new(Unmarshaler).UnmarshalNext(dec, p) - if err != io.EOF { - t.Errorf("eof: got %v, expected io.EOF", err) - } -} - -var unmarshalingShouldError = []struct { - desc string - in string - pb proto.Message -}{ - {"a value", "666", new(pb.Simple)}, - {"gibberish", "{adskja123;l23=-=", new(pb.Simple)}, - {"unknown field", `{"unknown": "foo"}`, new(pb.Simple)}, - {"unknown enum name", `{"hilarity":"DAVE"}`, new(proto3pb.Message)}, -} - -func TestUnmarshalingBadInput(t *testing.T) { - for _, tt := range unmarshalingShouldError { - err := UnmarshalString(tt.in, tt.pb) - if err == nil { - t.Errorf("an error was expected when parsing %q instead of an object", tt.desc) - } - } -} - -func TestUnmarshalJSONPBUnmarshaler(t *testing.T) { - rawJson := `{ "foo": "bar", "baz": [0, 1, 2, 3] }` - var msg dynamicMessage - if err := Unmarshal(strings.NewReader(rawJson), &msg); err != nil { - t.Errorf("an unexpected error occurred when parsing into JSONPBUnmarshaler: %v", err) - } - if msg.rawJson != rawJson { - t.Errorf("message contents not set correctly after unmarshalling JSON: got %s, wanted %s", msg.rawJson, rawJson) - } -} - -func TestUnmarshalAnyJSONPBUnmarshaler(t *testing.T) { - rawJson := `{ "@type": "blah.com/` + dynamicMessageName + `", "foo": "bar", "baz": [0, 1, 2, 3] }` - var got types.Any - if err := Unmarshal(strings.NewReader(rawJson), &got); err != nil { - t.Errorf("an unexpected error occurred when parsing into JSONPBUnmarshaler: %v", err) - } - - dm := &dynamicMessage{rawJson: `{"baz":[0,1,2,3],"foo":"bar"}`} - var want types.Any - if b, err := proto.Marshal(dm); err != nil { - t.Errorf("an unexpected error occurred when marshaling message: %v", err) - } else { - want.TypeUrl = "blah.com/" + dynamicMessageName - want.Value = b - } - - if !proto.Equal(&got, &want) { - t.Errorf("message contents not set correctly after unmarshalling JSON: got %s, wanted %s", got, want) - } -} - -const ( - dynamicMessageName = "google.protobuf.jsonpb.testing.dynamicMessage" -) - -func init() { - // we register the custom type below so that we can use it in Any types - proto.RegisterType((*dynamicMessage)(nil), dynamicMessageName) -} - -// dynamicMessage implements protobuf.Message but is not a normal generated message type. -// It provides implementations of JSONPBMarshaler and JSONPBUnmarshaler for JSON support. -type dynamicMessage struct { - rawJson string `protobuf:"bytes,1,opt,name=rawJson"` -} - -func (m *dynamicMessage) Reset() { - m.rawJson = "{}" -} - -func (m *dynamicMessage) String() string { - return m.rawJson -} - -func (m *dynamicMessage) ProtoMessage() { -} - -func (m *dynamicMessage) MarshalJSONPB(jm *Marshaler) ([]byte, error) { - return []byte(m.rawJson), nil -} - -func (m *dynamicMessage) UnmarshalJSONPB(jum *Unmarshaler, js []byte) error { - m.rawJson = string(js) - return nil -} diff --git a/vendor/github.com/gogo/protobuf/proto/Makefile b/vendor/github.com/gogo/protobuf/proto/Makefile deleted file mode 100644 index 41c717573..000000000 --- a/vendor/github.com/gogo/protobuf/proto/Makefile +++ /dev/null @@ -1,43 +0,0 @@ -# Go support for Protocol Buffers - Google's data interchange format -# -# Copyright 2010 The Go Authors. All rights reserved. -# https://github.com/golang/protobuf -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following disclaimer -# in the documentation and/or other materials provided with the -# distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived from -# this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -install: - go install - -test: install generate-test-pbs - go test - - -generate-test-pbs: - make install - make -C testdata - protoc-min-version --version="3.0.0" --proto_path=.:../../../../:../protobuf --gogo_out=Mtestdata/test.proto=github.com/gogo/protobuf/proto/testdata,Mgoogle/protobuf/any.proto=github.com/gogo/protobuf/types:. proto3_proto/proto3.proto - make diff --git a/vendor/github.com/gogo/protobuf/proto/all_test.go b/vendor/github.com/gogo/protobuf/proto/all_test.go deleted file mode 100644 index b5f8709d8..000000000 --- a/vendor/github.com/gogo/protobuf/proto/all_test.go +++ /dev/null @@ -1,2278 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto_test - -import ( - "bytes" - "encoding/json" - "errors" - "fmt" - "math" - "math/rand" - "reflect" - "runtime/debug" - "strings" - "testing" - "time" - - . "github.com/gogo/protobuf/proto" - . "github.com/gogo/protobuf/proto/testdata" -) - -var globalO *Buffer - -func old() *Buffer { - if globalO == nil { - globalO = NewBuffer(nil) - } - globalO.Reset() - return globalO -} - -func equalbytes(b1, b2 []byte, t *testing.T) { - if len(b1) != len(b2) { - t.Errorf("wrong lengths: 2*%d != %d", len(b1), len(b2)) - return - } - for i := 0; i < len(b1); i++ { - if b1[i] != b2[i] { - t.Errorf("bad byte[%d]:%x %x: %s %s", i, b1[i], b2[i], b1, b2) - } - } -} - -func initGoTestField() *GoTestField { - f := new(GoTestField) - f.Label = String("label") - f.Type = String("type") - return f -} - -// These are all structurally equivalent but the tag numbers differ. -// (It's remarkable that required, optional, and repeated all have -// 8 letters.) -func initGoTest_RequiredGroup() *GoTest_RequiredGroup { - return &GoTest_RequiredGroup{ - RequiredField: String("required"), - } -} - -func initGoTest_OptionalGroup() *GoTest_OptionalGroup { - return &GoTest_OptionalGroup{ - RequiredField: String("optional"), - } -} - -func initGoTest_RepeatedGroup() *GoTest_RepeatedGroup { - return &GoTest_RepeatedGroup{ - RequiredField: String("repeated"), - } -} - -func initGoTest(setdefaults bool) *GoTest { - pb := new(GoTest) - if setdefaults { - pb.F_BoolDefaulted = Bool(Default_GoTest_F_BoolDefaulted) - pb.F_Int32Defaulted = Int32(Default_GoTest_F_Int32Defaulted) - pb.F_Int64Defaulted = Int64(Default_GoTest_F_Int64Defaulted) - pb.F_Fixed32Defaulted = Uint32(Default_GoTest_F_Fixed32Defaulted) - pb.F_Fixed64Defaulted = Uint64(Default_GoTest_F_Fixed64Defaulted) - pb.F_Uint32Defaulted = Uint32(Default_GoTest_F_Uint32Defaulted) - pb.F_Uint64Defaulted = Uint64(Default_GoTest_F_Uint64Defaulted) - pb.F_FloatDefaulted = Float32(Default_GoTest_F_FloatDefaulted) - pb.F_DoubleDefaulted = Float64(Default_GoTest_F_DoubleDefaulted) - pb.F_StringDefaulted = String(Default_GoTest_F_StringDefaulted) - pb.F_BytesDefaulted = Default_GoTest_F_BytesDefaulted - pb.F_Sint32Defaulted = Int32(Default_GoTest_F_Sint32Defaulted) - pb.F_Sint64Defaulted = Int64(Default_GoTest_F_Sint64Defaulted) - } - - pb.Kind = GoTest_TIME.Enum() - pb.RequiredField = initGoTestField() - pb.F_BoolRequired = Bool(true) - pb.F_Int32Required = Int32(3) - pb.F_Int64Required = Int64(6) - pb.F_Fixed32Required = Uint32(32) - pb.F_Fixed64Required = Uint64(64) - pb.F_Uint32Required = Uint32(3232) - pb.F_Uint64Required = Uint64(6464) - pb.F_FloatRequired = Float32(3232) - pb.F_DoubleRequired = Float64(6464) - pb.F_StringRequired = String("string") - pb.F_BytesRequired = []byte("bytes") - pb.F_Sint32Required = Int32(-32) - pb.F_Sint64Required = Int64(-64) - pb.Requiredgroup = initGoTest_RequiredGroup() - - return pb -} - -func fail(msg string, b *bytes.Buffer, s string, t *testing.T) { - data := b.Bytes() - ld := len(data) - ls := len(s) / 2 - - fmt.Printf("fail %s ld=%d ls=%d\n", msg, ld, ls) - - // find the interesting spot - n - n := ls - if ld < ls { - n = ld - } - j := 0 - for i := 0; i < n; i++ { - bs := hex(s[j])*16 + hex(s[j+1]) - j += 2 - if data[i] == bs { - continue - } - n = i - break - } - l := n - 10 - if l < 0 { - l = 0 - } - h := n + 10 - - // find the interesting spot - n - fmt.Printf("is[%d]:", l) - for i := l; i < h; i++ { - if i >= ld { - fmt.Printf(" --") - continue - } - fmt.Printf(" %.2x", data[i]) - } - fmt.Printf("\n") - - fmt.Printf("sb[%d]:", l) - for i := l; i < h; i++ { - if i >= ls { - fmt.Printf(" --") - continue - } - bs := hex(s[j])*16 + hex(s[j+1]) - j += 2 - fmt.Printf(" %.2x", bs) - } - fmt.Printf("\n") - - t.Fail() - - // t.Errorf("%s: \ngood: %s\nbad: %x", msg, s, b.Bytes()) - // Print the output in a partially-decoded format; can - // be helpful when updating the test. It produces the output - // that is pasted, with minor edits, into the argument to verify(). - // data := b.Bytes() - // nesting := 0 - // for b.Len() > 0 { - // start := len(data) - b.Len() - // var u uint64 - // u, err := DecodeVarint(b) - // if err != nil { - // fmt.Printf("decode error on varint:", err) - // return - // } - // wire := u & 0x7 - // tag := u >> 3 - // switch wire { - // case WireVarint: - // v, err := DecodeVarint(b) - // if err != nil { - // fmt.Printf("decode error on varint:", err) - // return - // } - // fmt.Printf("\t\t\"%x\" // field %d, encoding %d, value %d\n", - // data[start:len(data)-b.Len()], tag, wire, v) - // case WireFixed32: - // v, err := DecodeFixed32(b) - // if err != nil { - // fmt.Printf("decode error on fixed32:", err) - // return - // } - // fmt.Printf("\t\t\"%x\" // field %d, encoding %d, value %d\n", - // data[start:len(data)-b.Len()], tag, wire, v) - // case WireFixed64: - // v, err := DecodeFixed64(b) - // if err != nil { - // fmt.Printf("decode error on fixed64:", err) - // return - // } - // fmt.Printf("\t\t\"%x\" // field %d, encoding %d, value %d\n", - // data[start:len(data)-b.Len()], tag, wire, v) - // case WireBytes: - // nb, err := DecodeVarint(b) - // if err != nil { - // fmt.Printf("decode error on bytes:", err) - // return - // } - // after_tag := len(data) - b.Len() - // str := make([]byte, nb) - // _, err = b.Read(str) - // if err != nil { - // fmt.Printf("decode error on bytes:", err) - // return - // } - // fmt.Printf("\t\t\"%x\" \"%x\" // field %d, encoding %d (FIELD)\n", - // data[start:after_tag], str, tag, wire) - // case WireStartGroup: - // nesting++ - // fmt.Printf("\t\t\"%x\"\t\t// start group field %d level %d\n", - // data[start:len(data)-b.Len()], tag, nesting) - // case WireEndGroup: - // fmt.Printf("\t\t\"%x\"\t\t// end group field %d level %d\n", - // data[start:len(data)-b.Len()], tag, nesting) - // nesting-- - // default: - // fmt.Printf("unrecognized wire type %d\n", wire) - // return - // } - // } -} - -func hex(c uint8) uint8 { - if '0' <= c && c <= '9' { - return c - '0' - } - if 'a' <= c && c <= 'f' { - return 10 + c - 'a' - } - if 'A' <= c && c <= 'F' { - return 10 + c - 'A' - } - return 0 -} - -func equal(b []byte, s string, t *testing.T) bool { - if 2*len(b) != len(s) { - // fail(fmt.Sprintf("wrong lengths: 2*%d != %d", len(b), len(s)), b, s, t) - fmt.Printf("wrong lengths: 2*%d != %d\n", len(b), len(s)) - return false - } - for i, j := 0, 0; i < len(b); i, j = i+1, j+2 { - x := hex(s[j])*16 + hex(s[j+1]) - if b[i] != x { - // fail(fmt.Sprintf("bad byte[%d]:%x %x", i, b[i], x), b, s, t) - fmt.Printf("bad byte[%d]:%x %x", i, b[i], x) - return false - } - } - return true -} - -func overify(t *testing.T, pb *GoTest, expected string) { - o := old() - err := o.Marshal(pb) - if err != nil { - fmt.Printf("overify marshal-1 err = %v", err) - o.DebugPrint("", o.Bytes()) - t.Fatalf("expected = %s", expected) - } - if !equal(o.Bytes(), expected, t) { - o.DebugPrint("overify neq 1", o.Bytes()) - t.Fatalf("expected = %s", expected) - } - - // Now test Unmarshal by recreating the original buffer. - pbd := new(GoTest) - err = o.Unmarshal(pbd) - if err != nil { - t.Fatalf("overify unmarshal err = %v", err) - o.DebugPrint("", o.Bytes()) - t.Fatalf("string = %s", expected) - } - o.Reset() - err = o.Marshal(pbd) - if err != nil { - t.Errorf("overify marshal-2 err = %v", err) - o.DebugPrint("", o.Bytes()) - t.Fatalf("string = %s", expected) - } - if !equal(o.Bytes(), expected, t) { - o.DebugPrint("overify neq 2", o.Bytes()) - t.Fatalf("string = %s", expected) - } -} - -// Simple tests for numeric encode/decode primitives (varint, etc.) -func TestNumericPrimitives(t *testing.T) { - for i := uint64(0); i < 1e6; i += 111 { - o := old() - if o.EncodeVarint(i) != nil { - t.Error("EncodeVarint") - break - } - x, e := o.DecodeVarint() - if e != nil { - t.Fatal("DecodeVarint") - } - if x != i { - t.Fatal("varint decode fail:", i, x) - } - - o = old() - if o.EncodeFixed32(i) != nil { - t.Fatal("encFixed32") - } - x, e = o.DecodeFixed32() - if e != nil { - t.Fatal("decFixed32") - } - if x != i { - t.Fatal("fixed32 decode fail:", i, x) - } - - o = old() - if o.EncodeFixed64(i*1234567) != nil { - t.Error("encFixed64") - break - } - x, e = o.DecodeFixed64() - if e != nil { - t.Error("decFixed64") - break - } - if x != i*1234567 { - t.Error("fixed64 decode fail:", i*1234567, x) - break - } - - o = old() - i32 := int32(i - 12345) - if o.EncodeZigzag32(uint64(i32)) != nil { - t.Fatal("EncodeZigzag32") - } - x, e = o.DecodeZigzag32() - if e != nil { - t.Fatal("DecodeZigzag32") - } - if x != uint64(uint32(i32)) { - t.Fatal("zigzag32 decode fail:", i32, x) - } - - o = old() - i64 := int64(i - 12345) - if o.EncodeZigzag64(uint64(i64)) != nil { - t.Fatal("EncodeZigzag64") - } - x, e = o.DecodeZigzag64() - if e != nil { - t.Fatal("DecodeZigzag64") - } - if x != uint64(i64) { - t.Fatal("zigzag64 decode fail:", i64, x) - } - } -} - -// fakeMarshaler is a simple struct implementing Marshaler and Message interfaces. -type fakeMarshaler struct { - b []byte - err error -} - -func (f *fakeMarshaler) Marshal() ([]byte, error) { return f.b, f.err } -func (f *fakeMarshaler) String() string { return fmt.Sprintf("Bytes: %v Error: %v", f.b, f.err) } -func (f *fakeMarshaler) ProtoMessage() {} -func (f *fakeMarshaler) Reset() {} - -type msgWithFakeMarshaler struct { - M *fakeMarshaler `protobuf:"bytes,1,opt,name=fake"` -} - -func (m *msgWithFakeMarshaler) String() string { return CompactTextString(m) } -func (m *msgWithFakeMarshaler) ProtoMessage() {} -func (m *msgWithFakeMarshaler) Reset() {} - -// Simple tests for proto messages that implement the Marshaler interface. -func TestMarshalerEncoding(t *testing.T) { - tests := []struct { - name string - m Message - want []byte - errType reflect.Type - }{ - { - name: "Marshaler that fails", - m: &fakeMarshaler{ - err: errors.New("some marshal err"), - b: []byte{5, 6, 7}, - }, - // Since the Marshal method returned bytes, they should be written to the - // buffer. (For efficiency, we assume that Marshal implementations are - // always correct w.r.t. RequiredNotSetError and output.) - want: []byte{5, 6, 7}, - errType: reflect.TypeOf(errors.New("some marshal err")), - }, - { - name: "Marshaler that fails with RequiredNotSetError", - m: &msgWithFakeMarshaler{ - M: &fakeMarshaler{ - err: &RequiredNotSetError{}, - b: []byte{5, 6, 7}, - }, - }, - // Since there's an error that can be continued after, - // the buffer should be written. - want: []byte{ - 10, 3, // for &msgWithFakeMarshaler - 5, 6, 7, // for &fakeMarshaler - }, - errType: reflect.TypeOf(&RequiredNotSetError{}), - }, - { - name: "Marshaler that succeeds", - m: &fakeMarshaler{ - b: []byte{0, 1, 2, 3, 4, 127, 255}, - }, - want: []byte{0, 1, 2, 3, 4, 127, 255}, - }, - } - for _, test := range tests { - b := NewBuffer(nil) - err := b.Marshal(test.m) - if reflect.TypeOf(err) != test.errType { - t.Errorf("%s: got err %T(%v) wanted %T", test.name, err, err, test.errType) - } - if !reflect.DeepEqual(test.want, b.Bytes()) { - t.Errorf("%s: got bytes %v wanted %v", test.name, b.Bytes(), test.want) - } - if size := Size(test.m); size != len(b.Bytes()) { - t.Errorf("%s: Size(_) = %v, but marshaled to %v bytes", test.name, size, len(b.Bytes())) - } - - m, mErr := Marshal(test.m) - if !bytes.Equal(b.Bytes(), m) { - t.Errorf("%s: Marshal returned %v, but (*Buffer).Marshal wrote %v", test.name, m, b.Bytes()) - } - if !reflect.DeepEqual(err, mErr) { - t.Errorf("%s: Marshal err = %q, but (*Buffer).Marshal returned %q", - test.name, fmt.Sprint(mErr), fmt.Sprint(err)) - } - } -} - -// Simple tests for bytes -func TestBytesPrimitives(t *testing.T) { - o := old() - bytes := []byte{'n', 'o', 'w', ' ', 'i', 's', ' ', 't', 'h', 'e', ' ', 't', 'i', 'm', 'e'} - if o.EncodeRawBytes(bytes) != nil { - t.Error("EncodeRawBytes") - } - decb, e := o.DecodeRawBytes(false) - if e != nil { - t.Error("DecodeRawBytes") - } - equalbytes(bytes, decb, t) -} - -// Simple tests for strings -func TestStringPrimitives(t *testing.T) { - o := old() - s := "now is the time" - if o.EncodeStringBytes(s) != nil { - t.Error("enc_string") - } - decs, e := o.DecodeStringBytes() - if e != nil { - t.Error("dec_string") - } - if s != decs { - t.Error("string encode/decode fail:", s, decs) - } -} - -// Do we catch the "required bit not set" case? -func TestRequiredBit(t *testing.T) { - o := old() - pb := new(GoTest) - err := o.Marshal(pb) - if err == nil { - t.Error("did not catch missing required fields") - } else if strings.Index(err.Error(), "Kind") < 0 { - t.Error("wrong error type:", err) - } -} - -// Check that all fields are nil. -// Clearly silly, and a residue from a more interesting test with an earlier, -// different initialization property, but it once caught a compiler bug so -// it lives. -func checkInitialized(pb *GoTest, t *testing.T) { - if pb.F_BoolDefaulted != nil { - t.Error("New or Reset did not set boolean:", *pb.F_BoolDefaulted) - } - if pb.F_Int32Defaulted != nil { - t.Error("New or Reset did not set int32:", *pb.F_Int32Defaulted) - } - if pb.F_Int64Defaulted != nil { - t.Error("New or Reset did not set int64:", *pb.F_Int64Defaulted) - } - if pb.F_Fixed32Defaulted != nil { - t.Error("New or Reset did not set fixed32:", *pb.F_Fixed32Defaulted) - } - if pb.F_Fixed64Defaulted != nil { - t.Error("New or Reset did not set fixed64:", *pb.F_Fixed64Defaulted) - } - if pb.F_Uint32Defaulted != nil { - t.Error("New or Reset did not set uint32:", *pb.F_Uint32Defaulted) - } - if pb.F_Uint64Defaulted != nil { - t.Error("New or Reset did not set uint64:", *pb.F_Uint64Defaulted) - } - if pb.F_FloatDefaulted != nil { - t.Error("New or Reset did not set float:", *pb.F_FloatDefaulted) - } - if pb.F_DoubleDefaulted != nil { - t.Error("New or Reset did not set double:", *pb.F_DoubleDefaulted) - } - if pb.F_StringDefaulted != nil { - t.Error("New or Reset did not set string:", *pb.F_StringDefaulted) - } - if pb.F_BytesDefaulted != nil { - t.Error("New or Reset did not set bytes:", string(pb.F_BytesDefaulted)) - } - if pb.F_Sint32Defaulted != nil { - t.Error("New or Reset did not set int32:", *pb.F_Sint32Defaulted) - } - if pb.F_Sint64Defaulted != nil { - t.Error("New or Reset did not set int64:", *pb.F_Sint64Defaulted) - } -} - -// Does Reset() reset? -func TestReset(t *testing.T) { - pb := initGoTest(true) - // muck with some values - pb.F_BoolDefaulted = Bool(false) - pb.F_Int32Defaulted = Int32(237) - pb.F_Int64Defaulted = Int64(12346) - pb.F_Fixed32Defaulted = Uint32(32000) - pb.F_Fixed64Defaulted = Uint64(666) - pb.F_Uint32Defaulted = Uint32(323232) - pb.F_Uint64Defaulted = nil - pb.F_FloatDefaulted = nil - pb.F_DoubleDefaulted = Float64(0) - pb.F_StringDefaulted = String("gotcha") - pb.F_BytesDefaulted = []byte("asdfasdf") - pb.F_Sint32Defaulted = Int32(123) - pb.F_Sint64Defaulted = Int64(789) - pb.Reset() - checkInitialized(pb, t) -} - -// All required fields set, no defaults provided. -func TestEncodeDecode1(t *testing.T) { - pb := initGoTest(false) - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 0x20 - "714000000000000000"+ // field 14, encoding 1, value 0x40 - "78a019"+ // field 15, encoding 0, value 0xca0 = 3232 - "8001c032"+ // field 16, encoding 0, value 0x1940 = 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2, string "string" - "b304"+ // field 70, encoding 3, start group - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // field 70, encoding 4, end group - "aa0605"+"6279746573"+ // field 101, encoding 2, string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f") // field 103, encoding 0, 0x7f zigzag64 -} - -// All required fields set, defaults provided. -func TestEncodeDecode2(t *testing.T) { - pb := initGoTest(true) - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 32 - "714000000000000000"+ // field 14, encoding 1, value 64 - "78a019"+ // field 15, encoding 0, value 3232 - "8001c032"+ // field 16, encoding 0, value 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" - "c00201"+ // field 40, encoding 0, value 1 - "c80220"+ // field 41, encoding 0, value 32 - "d00240"+ // field 42, encoding 0, value 64 - "dd0240010000"+ // field 43, encoding 5, value 320 - "e1028002000000000000"+ // field 44, encoding 1, value 640 - "e8028019"+ // field 45, encoding 0, value 3200 - "f0028032"+ // field 46, encoding 0, value 6400 - "fd02e0659948"+ // field 47, encoding 5, value 314159.0 - "81030000000050971041"+ // field 48, encoding 1, value 271828.0 - "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n" - "b304"+ // start group field 70 level 1 - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // end group field 70 level 1 - "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 - "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose" - "90193f"+ // field 402, encoding 0, value 63 - "98197f") // field 403, encoding 0, value 127 - -} - -// All default fields set to their default value by hand -func TestEncodeDecode3(t *testing.T) { - pb := initGoTest(false) - pb.F_BoolDefaulted = Bool(true) - pb.F_Int32Defaulted = Int32(32) - pb.F_Int64Defaulted = Int64(64) - pb.F_Fixed32Defaulted = Uint32(320) - pb.F_Fixed64Defaulted = Uint64(640) - pb.F_Uint32Defaulted = Uint32(3200) - pb.F_Uint64Defaulted = Uint64(6400) - pb.F_FloatDefaulted = Float32(314159) - pb.F_DoubleDefaulted = Float64(271828) - pb.F_StringDefaulted = String("hello, \"world!\"\n") - pb.F_BytesDefaulted = []byte("Bignose") - pb.F_Sint32Defaulted = Int32(-32) - pb.F_Sint64Defaulted = Int64(-64) - - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 32 - "714000000000000000"+ // field 14, encoding 1, value 64 - "78a019"+ // field 15, encoding 0, value 3232 - "8001c032"+ // field 16, encoding 0, value 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" - "c00201"+ // field 40, encoding 0, value 1 - "c80220"+ // field 41, encoding 0, value 32 - "d00240"+ // field 42, encoding 0, value 64 - "dd0240010000"+ // field 43, encoding 5, value 320 - "e1028002000000000000"+ // field 44, encoding 1, value 640 - "e8028019"+ // field 45, encoding 0, value 3200 - "f0028032"+ // field 46, encoding 0, value 6400 - "fd02e0659948"+ // field 47, encoding 5, value 314159.0 - "81030000000050971041"+ // field 48, encoding 1, value 271828.0 - "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n" - "b304"+ // start group field 70 level 1 - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // end group field 70 level 1 - "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 - "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose" - "90193f"+ // field 402, encoding 0, value 63 - "98197f") // field 403, encoding 0, value 127 - -} - -// All required fields set, defaults provided, all non-defaulted optional fields have values. -func TestEncodeDecode4(t *testing.T) { - pb := initGoTest(true) - pb.Table = String("hello") - pb.Param = Int32(7) - pb.OptionalField = initGoTestField() - pb.F_BoolOptional = Bool(true) - pb.F_Int32Optional = Int32(32) - pb.F_Int64Optional = Int64(64) - pb.F_Fixed32Optional = Uint32(3232) - pb.F_Fixed64Optional = Uint64(6464) - pb.F_Uint32Optional = Uint32(323232) - pb.F_Uint64Optional = Uint64(646464) - pb.F_FloatOptional = Float32(32.) - pb.F_DoubleOptional = Float64(64.) - pb.F_StringOptional = String("hello") - pb.F_BytesOptional = []byte("Bignose") - pb.F_Sint32Optional = Int32(-32) - pb.F_Sint64Optional = Int64(-64) - pb.Optionalgroup = initGoTest_OptionalGroup() - - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "1205"+"68656c6c6f"+ // field 2, encoding 2, string "hello" - "1807"+ // field 3, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "320d"+"0a056c6162656c120474797065"+ // field 6, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 32 - "714000000000000000"+ // field 14, encoding 1, value 64 - "78a019"+ // field 15, encoding 0, value 3232 - "8001c032"+ // field 16, encoding 0, value 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" - "f00101"+ // field 30, encoding 0, value 1 - "f80120"+ // field 31, encoding 0, value 32 - "800240"+ // field 32, encoding 0, value 64 - "8d02a00c0000"+ // field 33, encoding 5, value 3232 - "91024019000000000000"+ // field 34, encoding 1, value 6464 - "9802a0dd13"+ // field 35, encoding 0, value 323232 - "a002c0ba27"+ // field 36, encoding 0, value 646464 - "ad0200000042"+ // field 37, encoding 5, value 32.0 - "b1020000000000005040"+ // field 38, encoding 1, value 64.0 - "ba0205"+"68656c6c6f"+ // field 39, encoding 2, string "hello" - "c00201"+ // field 40, encoding 0, value 1 - "c80220"+ // field 41, encoding 0, value 32 - "d00240"+ // field 42, encoding 0, value 64 - "dd0240010000"+ // field 43, encoding 5, value 320 - "e1028002000000000000"+ // field 44, encoding 1, value 640 - "e8028019"+ // field 45, encoding 0, value 3200 - "f0028032"+ // field 46, encoding 0, value 6400 - "fd02e0659948"+ // field 47, encoding 5, value 314159.0 - "81030000000050971041"+ // field 48, encoding 1, value 271828.0 - "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n" - "b304"+ // start group field 70 level 1 - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // end group field 70 level 1 - "d305"+ // start group field 90 level 1 - "da0508"+"6f7074696f6e616c"+ // field 91, encoding 2, string "optional" - "d405"+ // end group field 90 level 1 - "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 - "ea1207"+"4269676e6f7365"+ // field 301, encoding 2, string "Bignose" - "f0123f"+ // field 302, encoding 0, value 63 - "f8127f"+ // field 303, encoding 0, value 127 - "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose" - "90193f"+ // field 402, encoding 0, value 63 - "98197f") // field 403, encoding 0, value 127 - -} - -// All required fields set, defaults provided, all repeated fields given two values. -func TestEncodeDecode5(t *testing.T) { - pb := initGoTest(true) - pb.RepeatedField = []*GoTestField{initGoTestField(), initGoTestField()} - pb.F_BoolRepeated = []bool{false, true} - pb.F_Int32Repeated = []int32{32, 33} - pb.F_Int64Repeated = []int64{64, 65} - pb.F_Fixed32Repeated = []uint32{3232, 3333} - pb.F_Fixed64Repeated = []uint64{6464, 6565} - pb.F_Uint32Repeated = []uint32{323232, 333333} - pb.F_Uint64Repeated = []uint64{646464, 656565} - pb.F_FloatRepeated = []float32{32., 33.} - pb.F_DoubleRepeated = []float64{64., 65.} - pb.F_StringRepeated = []string{"hello", "sailor"} - pb.F_BytesRepeated = [][]byte{[]byte("big"), []byte("nose")} - pb.F_Sint32Repeated = []int32{32, -32} - pb.F_Sint64Repeated = []int64{64, -64} - pb.Repeatedgroup = []*GoTest_RepeatedGroup{initGoTest_RepeatedGroup(), initGoTest_RepeatedGroup()} - - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "2a0d"+"0a056c6162656c120474797065"+ // field 5, encoding 2 (GoTestField) - "2a0d"+"0a056c6162656c120474797065"+ // field 5, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 32 - "714000000000000000"+ // field 14, encoding 1, value 64 - "78a019"+ // field 15, encoding 0, value 3232 - "8001c032"+ // field 16, encoding 0, value 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" - "a00100"+ // field 20, encoding 0, value 0 - "a00101"+ // field 20, encoding 0, value 1 - "a80120"+ // field 21, encoding 0, value 32 - "a80121"+ // field 21, encoding 0, value 33 - "b00140"+ // field 22, encoding 0, value 64 - "b00141"+ // field 22, encoding 0, value 65 - "bd01a00c0000"+ // field 23, encoding 5, value 3232 - "bd01050d0000"+ // field 23, encoding 5, value 3333 - "c1014019000000000000"+ // field 24, encoding 1, value 6464 - "c101a519000000000000"+ // field 24, encoding 1, value 6565 - "c801a0dd13"+ // field 25, encoding 0, value 323232 - "c80195ac14"+ // field 25, encoding 0, value 333333 - "d001c0ba27"+ // field 26, encoding 0, value 646464 - "d001b58928"+ // field 26, encoding 0, value 656565 - "dd0100000042"+ // field 27, encoding 5, value 32.0 - "dd0100000442"+ // field 27, encoding 5, value 33.0 - "e1010000000000005040"+ // field 28, encoding 1, value 64.0 - "e1010000000000405040"+ // field 28, encoding 1, value 65.0 - "ea0105"+"68656c6c6f"+ // field 29, encoding 2, string "hello" - "ea0106"+"7361696c6f72"+ // field 29, encoding 2, string "sailor" - "c00201"+ // field 40, encoding 0, value 1 - "c80220"+ // field 41, encoding 0, value 32 - "d00240"+ // field 42, encoding 0, value 64 - "dd0240010000"+ // field 43, encoding 5, value 320 - "e1028002000000000000"+ // field 44, encoding 1, value 640 - "e8028019"+ // field 45, encoding 0, value 3200 - "f0028032"+ // field 46, encoding 0, value 6400 - "fd02e0659948"+ // field 47, encoding 5, value 314159.0 - "81030000000050971041"+ // field 48, encoding 1, value 271828.0 - "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n" - "b304"+ // start group field 70 level 1 - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // end group field 70 level 1 - "8305"+ // start group field 80 level 1 - "8a0508"+"7265706561746564"+ // field 81, encoding 2, string "repeated" - "8405"+ // end group field 80 level 1 - "8305"+ // start group field 80 level 1 - "8a0508"+"7265706561746564"+ // field 81, encoding 2, string "repeated" - "8405"+ // end group field 80 level 1 - "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 - "ca0c03"+"626967"+ // field 201, encoding 2, string "big" - "ca0c04"+"6e6f7365"+ // field 201, encoding 2, string "nose" - "d00c40"+ // field 202, encoding 0, value 32 - "d00c3f"+ // field 202, encoding 0, value -32 - "d80c8001"+ // field 203, encoding 0, value 64 - "d80c7f"+ // field 203, encoding 0, value -64 - "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose" - "90193f"+ // field 402, encoding 0, value 63 - "98197f") // field 403, encoding 0, value 127 - -} - -// All required fields set, all packed repeated fields given two values. -func TestEncodeDecode6(t *testing.T) { - pb := initGoTest(false) - pb.F_BoolRepeatedPacked = []bool{false, true} - pb.F_Int32RepeatedPacked = []int32{32, 33} - pb.F_Int64RepeatedPacked = []int64{64, 65} - pb.F_Fixed32RepeatedPacked = []uint32{3232, 3333} - pb.F_Fixed64RepeatedPacked = []uint64{6464, 6565} - pb.F_Uint32RepeatedPacked = []uint32{323232, 333333} - pb.F_Uint64RepeatedPacked = []uint64{646464, 656565} - pb.F_FloatRepeatedPacked = []float32{32., 33.} - pb.F_DoubleRepeatedPacked = []float64{64., 65.} - pb.F_Sint32RepeatedPacked = []int32{32, -32} - pb.F_Sint64RepeatedPacked = []int64{64, -64} - - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 32 - "714000000000000000"+ // field 14, encoding 1, value 64 - "78a019"+ // field 15, encoding 0, value 3232 - "8001c032"+ // field 16, encoding 0, value 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" - "9203020001"+ // field 50, encoding 2, 2 bytes, value 0, value 1 - "9a03022021"+ // field 51, encoding 2, 2 bytes, value 32, value 33 - "a203024041"+ // field 52, encoding 2, 2 bytes, value 64, value 65 - "aa0308"+ // field 53, encoding 2, 8 bytes - "a00c0000050d0000"+ // value 3232, value 3333 - "b20310"+ // field 54, encoding 2, 16 bytes - "4019000000000000a519000000000000"+ // value 6464, value 6565 - "ba0306"+ // field 55, encoding 2, 6 bytes - "a0dd1395ac14"+ // value 323232, value 333333 - "c20306"+ // field 56, encoding 2, 6 bytes - "c0ba27b58928"+ // value 646464, value 656565 - "ca0308"+ // field 57, encoding 2, 8 bytes - "0000004200000442"+ // value 32.0, value 33.0 - "d20310"+ // field 58, encoding 2, 16 bytes - "00000000000050400000000000405040"+ // value 64.0, value 65.0 - "b304"+ // start group field 70 level 1 - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // end group field 70 level 1 - "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 - "b21f02"+ // field 502, encoding 2, 2 bytes - "403f"+ // value 32, value -32 - "ba1f03"+ // field 503, encoding 2, 3 bytes - "80017f") // value 64, value -64 -} - -// Test that we can encode empty bytes fields. -func TestEncodeDecodeBytes1(t *testing.T) { - pb := initGoTest(false) - - // Create our bytes - pb.F_BytesRequired = []byte{} - pb.F_BytesRepeated = [][]byte{{}} - pb.F_BytesOptional = []byte{} - - d, err := Marshal(pb) - if err != nil { - t.Error(err) - } - - pbd := new(GoTest) - if err := Unmarshal(d, pbd); err != nil { - t.Error(err) - } - - if pbd.F_BytesRequired == nil || len(pbd.F_BytesRequired) != 0 { - t.Error("required empty bytes field is incorrect") - } - if pbd.F_BytesRepeated == nil || len(pbd.F_BytesRepeated) == 1 && pbd.F_BytesRepeated[0] == nil { - t.Error("repeated empty bytes field is incorrect") - } - if pbd.F_BytesOptional == nil || len(pbd.F_BytesOptional) != 0 { - t.Error("optional empty bytes field is incorrect") - } -} - -// Test that we encode nil-valued fields of a repeated bytes field correctly. -// Since entries in a repeated field cannot be nil, nil must mean empty value. -func TestEncodeDecodeBytes2(t *testing.T) { - pb := initGoTest(false) - - // Create our bytes - pb.F_BytesRepeated = [][]byte{nil} - - d, err := Marshal(pb) - if err != nil { - t.Error(err) - } - - pbd := new(GoTest) - if err := Unmarshal(d, pbd); err != nil { - t.Error(err) - } - - if len(pbd.F_BytesRepeated) != 1 || pbd.F_BytesRepeated[0] == nil { - t.Error("Unexpected value for repeated bytes field") - } -} - -// All required fields set, defaults provided, all repeated fields given two values. -func TestSkippingUnrecognizedFields(t *testing.T) { - o := old() - pb := initGoTestField() - - // Marshal it normally. - o.Marshal(pb) - - // Now new a GoSkipTest record. - skip := &GoSkipTest{ - SkipInt32: Int32(32), - SkipFixed32: Uint32(3232), - SkipFixed64: Uint64(6464), - SkipString: String("skipper"), - Skipgroup: &GoSkipTest_SkipGroup{ - GroupInt32: Int32(75), - GroupString: String("wxyz"), - }, - } - - // Marshal it into same buffer. - o.Marshal(skip) - - pbd := new(GoTestField) - o.Unmarshal(pbd) - - // The __unrecognized field should be a marshaling of GoSkipTest - skipd := new(GoSkipTest) - - o.SetBuf(pbd.XXX_unrecognized) - o.Unmarshal(skipd) - - if *skipd.SkipInt32 != *skip.SkipInt32 { - t.Error("skip int32", skipd.SkipInt32) - } - if *skipd.SkipFixed32 != *skip.SkipFixed32 { - t.Error("skip fixed32", skipd.SkipFixed32) - } - if *skipd.SkipFixed64 != *skip.SkipFixed64 { - t.Error("skip fixed64", skipd.SkipFixed64) - } - if *skipd.SkipString != *skip.SkipString { - t.Error("skip string", *skipd.SkipString) - } - if *skipd.Skipgroup.GroupInt32 != *skip.Skipgroup.GroupInt32 { - t.Error("skip group int32", skipd.Skipgroup.GroupInt32) - } - if *skipd.Skipgroup.GroupString != *skip.Skipgroup.GroupString { - t.Error("skip group string", *skipd.Skipgroup.GroupString) - } -} - -// Check that unrecognized fields of a submessage are preserved. -func TestSubmessageUnrecognizedFields(t *testing.T) { - nm := &NewMessage{ - Nested: &NewMessage_Nested{ - Name: String("Nigel"), - FoodGroup: String("carbs"), - }, - } - b, err := Marshal(nm) - if err != nil { - t.Fatalf("Marshal of NewMessage: %v", err) - } - - // Unmarshal into an OldMessage. - om := new(OldMessage) - if err = Unmarshal(b, om); err != nil { - t.Fatalf("Unmarshal to OldMessage: %v", err) - } - exp := &OldMessage{ - Nested: &OldMessage_Nested{ - Name: String("Nigel"), - // normal protocol buffer users should not do this - XXX_unrecognized: []byte("\x12\x05carbs"), - }, - } - if !Equal(om, exp) { - t.Errorf("om = %v, want %v", om, exp) - } - - // Clone the OldMessage. - om = Clone(om).(*OldMessage) - if !Equal(om, exp) { - t.Errorf("Clone(om) = %v, want %v", om, exp) - } - - // Marshal the OldMessage, then unmarshal it into an empty NewMessage. - if b, err = Marshal(om); err != nil { - t.Fatalf("Marshal of OldMessage: %v", err) - } - t.Logf("Marshal(%v) -> %q", om, b) - nm2 := new(NewMessage) - if err := Unmarshal(b, nm2); err != nil { - t.Fatalf("Unmarshal to NewMessage: %v", err) - } - if !Equal(nm, nm2) { - t.Errorf("NewMessage round-trip: %v => %v", nm, nm2) - } -} - -// Check that an int32 field can be upgraded to an int64 field. -func TestNegativeInt32(t *testing.T) { - om := &OldMessage{ - Num: Int32(-1), - } - b, err := Marshal(om) - if err != nil { - t.Fatalf("Marshal of OldMessage: %v", err) - } - - // Check the size. It should be 11 bytes; - // 1 for the field/wire type, and 10 for the negative number. - if len(b) != 11 { - t.Errorf("%v marshaled as %q, wanted 11 bytes", om, b) - } - - // Unmarshal into a NewMessage. - nm := new(NewMessage) - if err := Unmarshal(b, nm); err != nil { - t.Fatalf("Unmarshal to NewMessage: %v", err) - } - want := &NewMessage{ - Num: Int64(-1), - } - if !Equal(nm, want) { - t.Errorf("nm = %v, want %v", nm, want) - } -} - -// Check that we can grow an array (repeated field) to have many elements. -// This test doesn't depend only on our encoding; for variety, it makes sure -// we create, encode, and decode the correct contents explicitly. It's therefore -// a bit messier. -// This test also uses (and hence tests) the Marshal/Unmarshal functions -// instead of the methods. -func TestBigRepeated(t *testing.T) { - pb := initGoTest(true) - - // Create the arrays - const N = 50 // Internally the library starts much smaller. - pb.Repeatedgroup = make([]*GoTest_RepeatedGroup, N) - pb.F_Sint64Repeated = make([]int64, N) - pb.F_Sint32Repeated = make([]int32, N) - pb.F_BytesRepeated = make([][]byte, N) - pb.F_StringRepeated = make([]string, N) - pb.F_DoubleRepeated = make([]float64, N) - pb.F_FloatRepeated = make([]float32, N) - pb.F_Uint64Repeated = make([]uint64, N) - pb.F_Uint32Repeated = make([]uint32, N) - pb.F_Fixed64Repeated = make([]uint64, N) - pb.F_Fixed32Repeated = make([]uint32, N) - pb.F_Int64Repeated = make([]int64, N) - pb.F_Int32Repeated = make([]int32, N) - pb.F_BoolRepeated = make([]bool, N) - pb.RepeatedField = make([]*GoTestField, N) - - // Fill in the arrays with checkable values. - igtf := initGoTestField() - igtrg := initGoTest_RepeatedGroup() - for i := 0; i < N; i++ { - pb.Repeatedgroup[i] = igtrg - pb.F_Sint64Repeated[i] = int64(i) - pb.F_Sint32Repeated[i] = int32(i) - s := fmt.Sprint(i) - pb.F_BytesRepeated[i] = []byte(s) - pb.F_StringRepeated[i] = s - pb.F_DoubleRepeated[i] = float64(i) - pb.F_FloatRepeated[i] = float32(i) - pb.F_Uint64Repeated[i] = uint64(i) - pb.F_Uint32Repeated[i] = uint32(i) - pb.F_Fixed64Repeated[i] = uint64(i) - pb.F_Fixed32Repeated[i] = uint32(i) - pb.F_Int64Repeated[i] = int64(i) - pb.F_Int32Repeated[i] = int32(i) - pb.F_BoolRepeated[i] = i%2 == 0 - pb.RepeatedField[i] = igtf - } - - // Marshal. - buf, _ := Marshal(pb) - - // Now test Unmarshal by recreating the original buffer. - pbd := new(GoTest) - Unmarshal(buf, pbd) - - // Check the checkable values - for i := uint64(0); i < N; i++ { - if pbd.Repeatedgroup[i] == nil { // TODO: more checking? - t.Error("pbd.Repeatedgroup bad") - } - var x uint64 - x = uint64(pbd.F_Sint64Repeated[i]) - if x != i { - t.Error("pbd.F_Sint64Repeated bad", x, i) - } - x = uint64(pbd.F_Sint32Repeated[i]) - if x != i { - t.Error("pbd.F_Sint32Repeated bad", x, i) - } - s := fmt.Sprint(i) - equalbytes(pbd.F_BytesRepeated[i], []byte(s), t) - if pbd.F_StringRepeated[i] != s { - t.Error("pbd.F_Sint32Repeated bad", pbd.F_StringRepeated[i], i) - } - x = uint64(pbd.F_DoubleRepeated[i]) - if x != i { - t.Error("pbd.F_DoubleRepeated bad", x, i) - } - x = uint64(pbd.F_FloatRepeated[i]) - if x != i { - t.Error("pbd.F_FloatRepeated bad", x, i) - } - x = pbd.F_Uint64Repeated[i] - if x != i { - t.Error("pbd.F_Uint64Repeated bad", x, i) - } - x = uint64(pbd.F_Uint32Repeated[i]) - if x != i { - t.Error("pbd.F_Uint32Repeated bad", x, i) - } - x = pbd.F_Fixed64Repeated[i] - if x != i { - t.Error("pbd.F_Fixed64Repeated bad", x, i) - } - x = uint64(pbd.F_Fixed32Repeated[i]) - if x != i { - t.Error("pbd.F_Fixed32Repeated bad", x, i) - } - x = uint64(pbd.F_Int64Repeated[i]) - if x != i { - t.Error("pbd.F_Int64Repeated bad", x, i) - } - x = uint64(pbd.F_Int32Repeated[i]) - if x != i { - t.Error("pbd.F_Int32Repeated bad", x, i) - } - if pbd.F_BoolRepeated[i] != (i%2 == 0) { - t.Error("pbd.F_BoolRepeated bad", x, i) - } - if pbd.RepeatedField[i] == nil { // TODO: more checking? - t.Error("pbd.RepeatedField bad") - } - } -} - -// Verify we give a useful message when decoding to the wrong structure type. -func TestTypeMismatch(t *testing.T) { - pb1 := initGoTest(true) - - // Marshal - o := old() - o.Marshal(pb1) - - // Now Unmarshal it to the wrong type. - pb2 := initGoTestField() - err := o.Unmarshal(pb2) - if err == nil { - t.Error("expected error, got no error") - } else if !strings.Contains(err.Error(), "bad wiretype") { - t.Error("expected bad wiretype error, got", err) - } -} - -func encodeDecode(t *testing.T, in, out Message, msg string) { - buf, err := Marshal(in) - if err != nil { - t.Fatalf("failed marshaling %v: %v", msg, err) - } - if err := Unmarshal(buf, out); err != nil { - t.Fatalf("failed unmarshaling %v: %v", msg, err) - } -} - -func TestPackedNonPackedDecoderSwitching(t *testing.T) { - np, p := new(NonPackedTest), new(PackedTest) - - // non-packed -> packed - np.A = []int32{0, 1, 1, 2, 3, 5} - encodeDecode(t, np, p, "non-packed -> packed") - if !reflect.DeepEqual(np.A, p.B) { - t.Errorf("failed non-packed -> packed; np.A=%+v, p.B=%+v", np.A, p.B) - } - - // packed -> non-packed - np.Reset() - p.B = []int32{3, 1, 4, 1, 5, 9} - encodeDecode(t, p, np, "packed -> non-packed") - if !reflect.DeepEqual(p.B, np.A) { - t.Errorf("failed packed -> non-packed; p.B=%+v, np.A=%+v", p.B, np.A) - } -} - -func TestProto1RepeatedGroup(t *testing.T) { - pb := &MessageList{ - Message: []*MessageList_Message{ - { - Name: String("blah"), - Count: Int32(7), - }, - // NOTE: pb.Message[1] is a nil - nil, - }, - } - - o := old() - err := o.Marshal(pb) - if err == nil || !strings.Contains(err.Error(), "repeated field Message has nil") { - t.Fatalf("unexpected or no error when marshaling: %v", err) - } -} - -// Test that enums work. Checks for a bug introduced by making enums -// named types instead of int32: newInt32FromUint64 would crash with -// a type mismatch in reflect.PointTo. -func TestEnum(t *testing.T) { - pb := new(GoEnum) - pb.Foo = FOO_FOO1.Enum() - o := old() - if err := o.Marshal(pb); err != nil { - t.Fatal("error encoding enum:", err) - } - pb1 := new(GoEnum) - if err := o.Unmarshal(pb1); err != nil { - t.Fatal("error decoding enum:", err) - } - if *pb1.Foo != FOO_FOO1 { - t.Error("expected 7 but got ", *pb1.Foo) - } -} - -// Enum types have String methods. Check that enum fields can be printed. -// We don't care what the value actually is, just as long as it doesn't crash. -func TestPrintingNilEnumFields(t *testing.T) { - pb := new(GoEnum) - _ = fmt.Sprintf("%+v", pb) -} - -// Verify that absent required fields cause Marshal/Unmarshal to return errors. -func TestRequiredFieldEnforcement(t *testing.T) { - pb := new(GoTestField) - _, err := Marshal(pb) - if err == nil { - t.Error("marshal: expected error, got nil") - } else if _, ok := err.(*RequiredNotSetError); !ok || !strings.Contains(err.Error(), "Label") { - t.Errorf("marshal: bad error type: %v", err) - } - - // A slightly sneaky, yet valid, proto. It encodes the same required field twice, - // so simply counting the required fields is insufficient. - // field 1, encoding 2, value "hi" - buf := []byte("\x0A\x02hi\x0A\x02hi") - err = Unmarshal(buf, pb) - if err == nil { - t.Error("unmarshal: expected error, got nil") - } else if _, ok := err.(*RequiredNotSetError); !ok || !strings.Contains(err.Error(), "{Unknown}") { - t.Errorf("unmarshal: bad error type: %v", err) - } -} - -// Verify that absent required fields in groups cause Marshal/Unmarshal to return errors. -func TestRequiredFieldEnforcementGroups(t *testing.T) { - pb := &GoTestRequiredGroupField{Group: &GoTestRequiredGroupField_Group{}} - if _, err := Marshal(pb); err == nil { - t.Error("marshal: expected error, got nil") - } else if _, ok := err.(*RequiredNotSetError); !ok || !strings.Contains(err.Error(), "Group.Field") { - t.Errorf("marshal: bad error type: %v", err) - } - - buf := []byte{11, 12} - if err := Unmarshal(buf, pb); err == nil { - t.Error("unmarshal: expected error, got nil") - } else if _, ok := err.(*RequiredNotSetError); !ok || !strings.Contains(err.Error(), "Group.{Unknown}") { - t.Errorf("unmarshal: bad error type: %v", err) - } -} - -func TestTypedNilMarshal(t *testing.T) { - // A typed nil should return ErrNil and not crash. - { - var m *GoEnum - if _, err := Marshal(m); err != ErrNil { - t.Errorf("Marshal(%#v): got %v, want ErrNil", m, err) - } - } - - { - m := &Communique{Union: &Communique_Msg{Msg: nil}} - if _, err := Marshal(m); err == nil || err == ErrNil { - t.Errorf("Marshal(%#v): got %v, want errOneofHasNil", m, err) - } - } -} - -// A type that implements the Marshaler interface, but is not nillable. -type nonNillableInt uint64 - -func (nni nonNillableInt) Marshal() ([]byte, error) { - return EncodeVarint(uint64(nni)), nil -} - -type NNIMessage struct { - nni nonNillableInt -} - -func (*NNIMessage) Reset() {} -func (*NNIMessage) String() string { return "" } -func (*NNIMessage) ProtoMessage() {} - -// A type that implements the Marshaler interface and is nillable. -type nillableMessage struct { - x uint64 -} - -func (nm *nillableMessage) Marshal() ([]byte, error) { - return EncodeVarint(nm.x), nil -} - -type NMMessage struct { - nm *nillableMessage -} - -func (*NMMessage) Reset() {} -func (*NMMessage) String() string { return "" } -func (*NMMessage) ProtoMessage() {} - -// Verify a type that uses the Marshaler interface, but has a nil pointer. -func TestNilMarshaler(t *testing.T) { - // Try a struct with a Marshaler field that is nil. - // It should be directly marshable. - nmm := new(NMMessage) - if _, err := Marshal(nmm); err != nil { - t.Error("unexpected error marshaling nmm: ", err) - } - - // Try a struct with a Marshaler field that is not nillable. - nnim := new(NNIMessage) - nnim.nni = 7 - var _ Marshaler = nnim.nni // verify it is truly a Marshaler - if _, err := Marshal(nnim); err != nil { - t.Error("unexpected error marshaling nnim: ", err) - } -} - -func TestAllSetDefaults(t *testing.T) { - // Exercise SetDefaults with all scalar field types. - m := &Defaults{ - // NaN != NaN, so override that here. - F_Nan: Float32(1.7), - } - expected := &Defaults{ - F_Bool: Bool(true), - F_Int32: Int32(32), - F_Int64: Int64(64), - F_Fixed32: Uint32(320), - F_Fixed64: Uint64(640), - F_Uint32: Uint32(3200), - F_Uint64: Uint64(6400), - F_Float: Float32(314159), - F_Double: Float64(271828), - F_String: String(`hello, "world!"` + "\n"), - F_Bytes: []byte("Bignose"), - F_Sint32: Int32(-32), - F_Sint64: Int64(-64), - F_Enum: Defaults_GREEN.Enum(), - F_Pinf: Float32(float32(math.Inf(1))), - F_Ninf: Float32(float32(math.Inf(-1))), - F_Nan: Float32(1.7), - StrZero: String(""), - } - SetDefaults(m) - if !Equal(m, expected) { - t.Errorf("SetDefaults failed\n got %v\nwant %v", m, expected) - } -} - -func TestSetDefaultsWithSetField(t *testing.T) { - // Check that a set value is not overridden. - m := &Defaults{ - F_Int32: Int32(12), - } - SetDefaults(m) - if v := m.GetF_Int32(); v != 12 { - t.Errorf("m.FInt32 = %v, want 12", v) - } -} - -func TestSetDefaultsWithSubMessage(t *testing.T) { - m := &OtherMessage{ - Key: Int64(123), - Inner: &InnerMessage{ - Host: String("gopher"), - }, - } - expected := &OtherMessage{ - Key: Int64(123), - Inner: &InnerMessage{ - Host: String("gopher"), - Port: Int32(4000), - }, - } - SetDefaults(m) - if !Equal(m, expected) { - t.Errorf("\n got %v\nwant %v", m, expected) - } -} - -func TestSetDefaultsWithRepeatedSubMessage(t *testing.T) { - m := &MyMessage{ - RepInner: []*InnerMessage{{}}, - } - expected := &MyMessage{ - RepInner: []*InnerMessage{{ - Port: Int32(4000), - }}, - } - SetDefaults(m) - if !Equal(m, expected) { - t.Errorf("\n got %v\nwant %v", m, expected) - } -} - -func TestSetDefaultWithRepeatedNonMessage(t *testing.T) { - m := &MyMessage{ - Pet: []string{"turtle", "wombat"}, - } - expected := Clone(m) - SetDefaults(m) - if !Equal(m, expected) { - t.Errorf("\n got %v\nwant %v", m, expected) - } -} - -func TestMaximumTagNumber(t *testing.T) { - m := &MaxTag{ - LastField: String("natural goat essence"), - } - buf, err := Marshal(m) - if err != nil { - t.Fatalf("proto.Marshal failed: %v", err) - } - m2 := new(MaxTag) - if err := Unmarshal(buf, m2); err != nil { - t.Fatalf("proto.Unmarshal failed: %v", err) - } - if got, want := m2.GetLastField(), *m.LastField; got != want { - t.Errorf("got %q, want %q", got, want) - } -} - -func TestJSON(t *testing.T) { - m := &MyMessage{ - Count: Int32(4), - Pet: []string{"bunny", "kitty"}, - Inner: &InnerMessage{ - Host: String("cauchy"), - }, - Bikeshed: MyMessage_GREEN.Enum(), - } - const expected = `{"count":4,"pet":["bunny","kitty"],"inner":{"host":"cauchy"},"bikeshed":1}` - - b, err := json.Marshal(m) - if err != nil { - t.Fatalf("json.Marshal failed: %v", err) - } - s := string(b) - if s != expected { - t.Errorf("got %s\nwant %s", s, expected) - } - - received := new(MyMessage) - if err := json.Unmarshal(b, received); err != nil { - t.Fatalf("json.Unmarshal failed: %v", err) - } - if !Equal(received, m) { - t.Fatalf("got %s, want %s", received, m) - } - - // Test unmarshalling of JSON with symbolic enum name. - const old = `{"count":4,"pet":["bunny","kitty"],"inner":{"host":"cauchy"},"bikeshed":"GREEN"}` - received.Reset() - if err := json.Unmarshal([]byte(old), received); err != nil { - t.Fatalf("json.Unmarshal failed: %v", err) - } - if !Equal(received, m) { - t.Fatalf("got %s, want %s", received, m) - } -} - -func TestBadWireType(t *testing.T) { - b := []byte{7<<3 | 6} // field 7, wire type 6 - pb := new(OtherMessage) - if err := Unmarshal(b, pb); err == nil { - t.Errorf("Unmarshal did not fail") - } else if !strings.Contains(err.Error(), "unknown wire type") { - t.Errorf("wrong error: %v", err) - } -} - -func TestBytesWithInvalidLength(t *testing.T) { - // If a byte sequence has an invalid (negative) length, Unmarshal should not panic. - b := []byte{2<<3 | WireBytes, 0xff, 0xff, 0xff, 0xff, 0xff, 0} - Unmarshal(b, new(MyMessage)) -} - -func TestLengthOverflow(t *testing.T) { - // Overflowing a length should not panic. - b := []byte{2<<3 | WireBytes, 1, 1, 3<<3 | WireBytes, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, 0x01} - Unmarshal(b, new(MyMessage)) -} - -func TestVarintOverflow(t *testing.T) { - // Overflowing a 64-bit length should not be allowed. - b := []byte{1<<3 | WireVarint, 0x01, 3<<3 | WireBytes, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x01} - if err := Unmarshal(b, new(MyMessage)); err == nil { - t.Fatalf("Overflowed uint64 length without error") - } -} - -func TestUnmarshalFuzz(t *testing.T) { - const N = 1000 - seed := time.Now().UnixNano() - t.Logf("RNG seed is %d", seed) - rng := rand.New(rand.NewSource(seed)) - buf := make([]byte, 20) - for i := 0; i < N; i++ { - for j := range buf { - buf[j] = byte(rng.Intn(256)) - } - fuzzUnmarshal(t, buf) - } -} - -func TestMergeMessages(t *testing.T) { - pb := &MessageList{Message: []*MessageList_Message{{Name: String("x"), Count: Int32(1)}}} - data, err := Marshal(pb) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - - pb1 := new(MessageList) - if err := Unmarshal(data, pb1); err != nil { - t.Fatalf("first Unmarshal: %v", err) - } - if err := Unmarshal(data, pb1); err != nil { - t.Fatalf("second Unmarshal: %v", err) - } - if len(pb1.Message) != 1 { - t.Errorf("two Unmarshals produced %d Messages, want 1", len(pb1.Message)) - } - - pb2 := new(MessageList) - if err := UnmarshalMerge(data, pb2); err != nil { - t.Fatalf("first UnmarshalMerge: %v", err) - } - if err := UnmarshalMerge(data, pb2); err != nil { - t.Fatalf("second UnmarshalMerge: %v", err) - } - if len(pb2.Message) != 2 { - t.Errorf("two UnmarshalMerges produced %d Messages, want 2", len(pb2.Message)) - } -} - -func TestExtensionMarshalOrder(t *testing.T) { - m := &MyMessage{Count: Int(123)} - if err := SetExtension(m, E_Ext_More, &Ext{Data: String("alpha")}); err != nil { - t.Fatalf("SetExtension: %v", err) - } - if err := SetExtension(m, E_Ext_Text, String("aleph")); err != nil { - t.Fatalf("SetExtension: %v", err) - } - if err := SetExtension(m, E_Ext_Number, Int32(1)); err != nil { - t.Fatalf("SetExtension: %v", err) - } - - // Serialize m several times, and check we get the same bytes each time. - var orig []byte - for i := 0; i < 100; i++ { - b, err := Marshal(m) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - if i == 0 { - orig = b - continue - } - if !bytes.Equal(b, orig) { - t.Errorf("Bytes differ on attempt #%d", i) - } - } -} - -// Many extensions, because small maps might not iterate differently on each iteration. -var exts = []*ExtensionDesc{ - E_X201, - E_X202, - E_X203, - E_X204, - E_X205, - E_X206, - E_X207, - E_X208, - E_X209, - E_X210, - E_X211, - E_X212, - E_X213, - E_X214, - E_X215, - E_X216, - E_X217, - E_X218, - E_X219, - E_X220, - E_X221, - E_X222, - E_X223, - E_X224, - E_X225, - E_X226, - E_X227, - E_X228, - E_X229, - E_X230, - E_X231, - E_X232, - E_X233, - E_X234, - E_X235, - E_X236, - E_X237, - E_X238, - E_X239, - E_X240, - E_X241, - E_X242, - E_X243, - E_X244, - E_X245, - E_X246, - E_X247, - E_X248, - E_X249, - E_X250, -} - -func TestMessageSetMarshalOrder(t *testing.T) { - m := &MyMessageSet{} - for _, x := range exts { - if err := SetExtension(m, x, &Empty{}); err != nil { - t.Fatalf("SetExtension: %v", err) - } - } - - buf, err := Marshal(m) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - - // Serialize m several times, and check we get the same bytes each time. - for i := 0; i < 10; i++ { - b1, err := Marshal(m) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - if !bytes.Equal(b1, buf) { - t.Errorf("Bytes differ on re-Marshal #%d", i) - } - - m2 := &MyMessageSet{} - if err = Unmarshal(buf, m2); err != nil { - t.Errorf("Unmarshal: %v", err) - } - b2, err := Marshal(m2) - if err != nil { - t.Errorf("re-Marshal: %v", err) - } - if !bytes.Equal(b2, buf) { - t.Errorf("Bytes differ on round-trip #%d", i) - } - } -} - -func TestUnmarshalMergesMessages(t *testing.T) { - // If a nested message occurs twice in the input, - // the fields should be merged when decoding. - a := &OtherMessage{ - Key: Int64(123), - Inner: &InnerMessage{ - Host: String("polhode"), - Port: Int32(1234), - }, - } - aData, err := Marshal(a) - if err != nil { - t.Fatalf("Marshal(a): %v", err) - } - b := &OtherMessage{ - Weight: Float32(1.2), - Inner: &InnerMessage{ - Host: String("herpolhode"), - Connected: Bool(true), - }, - } - bData, err := Marshal(b) - if err != nil { - t.Fatalf("Marshal(b): %v", err) - } - want := &OtherMessage{ - Key: Int64(123), - Weight: Float32(1.2), - Inner: &InnerMessage{ - Host: String("herpolhode"), - Port: Int32(1234), - Connected: Bool(true), - }, - } - got := new(OtherMessage) - if err := Unmarshal(append(aData, bData...), got); err != nil { - t.Fatalf("Unmarshal: %v", err) - } - if !Equal(got, want) { - t.Errorf("\n got %v\nwant %v", got, want) - } -} - -func TestEncodingSizes(t *testing.T) { - tests := []struct { - m Message - n int - }{ - {&Defaults{F_Int32: Int32(math.MaxInt32)}, 6}, - {&Defaults{F_Int32: Int32(math.MinInt32)}, 11}, - {&Defaults{F_Uint32: Uint32(uint32(math.MaxInt32) + 1)}, 6}, - {&Defaults{F_Uint32: Uint32(math.MaxUint32)}, 6}, - } - for _, test := range tests { - b, err := Marshal(test.m) - if err != nil { - t.Errorf("Marshal(%v): %v", test.m, err) - continue - } - if len(b) != test.n { - t.Errorf("Marshal(%v) yielded %d bytes, want %d bytes", test.m, len(b), test.n) - } - } -} - -func TestRequiredNotSetError(t *testing.T) { - pb := initGoTest(false) - pb.RequiredField.Label = nil - pb.F_Int32Required = nil - pb.F_Int64Required = nil - - expected := "0807" + // field 1, encoding 0, value 7 - "2206" + "120474797065" + // field 4, encoding 2 (GoTestField) - "5001" + // field 10, encoding 0, value 1 - "6d20000000" + // field 13, encoding 5, value 0x20 - "714000000000000000" + // field 14, encoding 1, value 0x40 - "78a019" + // field 15, encoding 0, value 0xca0 = 3232 - "8001c032" + // field 16, encoding 0, value 0x1940 = 6464 - "8d0100004a45" + // field 17, encoding 5, value 3232.0 - "9101000000000040b940" + // field 18, encoding 1, value 6464.0 - "9a0106" + "737472696e67" + // field 19, encoding 2, string "string" - "b304" + // field 70, encoding 3, start group - "ba0408" + "7265717569726564" + // field 71, encoding 2, string "required" - "b404" + // field 70, encoding 4, end group - "aa0605" + "6279746573" + // field 101, encoding 2, string "bytes" - "b0063f" + // field 102, encoding 0, 0x3f zigzag32 - "b8067f" // field 103, encoding 0, 0x7f zigzag64 - - o := old() - mbytes, err := Marshal(pb) - if _, ok := err.(*RequiredNotSetError); !ok { - fmt.Printf("marshal-1 err = %v, want *RequiredNotSetError", err) - o.DebugPrint("", mbytes) - t.Fatalf("expected = %s", expected) - } - if strings.Index(err.Error(), "RequiredField.Label") < 0 { - t.Errorf("marshal-1 wrong err msg: %v", err) - } - if !equal(mbytes, expected, t) { - o.DebugPrint("neq 1", mbytes) - t.Fatalf("expected = %s", expected) - } - - // Now test Unmarshal by recreating the original buffer. - pbd := new(GoTest) - err = Unmarshal(mbytes, pbd) - if _, ok := err.(*RequiredNotSetError); !ok { - t.Fatalf("unmarshal err = %v, want *RequiredNotSetError", err) - o.DebugPrint("", mbytes) - t.Fatalf("string = %s", expected) - } - if strings.Index(err.Error(), "RequiredField.{Unknown}") < 0 { - t.Errorf("unmarshal wrong err msg: %v", err) - } - mbytes, err = Marshal(pbd) - if _, ok := err.(*RequiredNotSetError); !ok { - t.Errorf("marshal-2 err = %v, want *RequiredNotSetError", err) - o.DebugPrint("", mbytes) - t.Fatalf("string = %s", expected) - } - if strings.Index(err.Error(), "RequiredField.Label") < 0 { - t.Errorf("marshal-2 wrong err msg: %v", err) - } - if !equal(mbytes, expected, t) { - o.DebugPrint("neq 2", mbytes) - t.Fatalf("string = %s", expected) - } -} - -func fuzzUnmarshal(t *testing.T, data []byte) { - defer func() { - if e := recover(); e != nil { - t.Errorf("These bytes caused a panic: %+v", data) - t.Logf("Stack:\n%s", debug.Stack()) - t.FailNow() - } - }() - - pb := new(MyMessage) - Unmarshal(data, pb) -} - -func TestMapFieldMarshal(t *testing.T) { - m := &MessageWithMap{ - NameMapping: map[int32]string{ - 1: "Rob", - 4: "Ian", - 8: "Dave", - }, - } - b, err := Marshal(m) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - - // b should be the concatenation of these three byte sequences in some order. - parts := []string{ - "\n\a\b\x01\x12\x03Rob", - "\n\a\b\x04\x12\x03Ian", - "\n\b\b\x08\x12\x04Dave", - } - ok := false - for i := range parts { - for j := range parts { - if j == i { - continue - } - for k := range parts { - if k == i || k == j { - continue - } - try := parts[i] + parts[j] + parts[k] - if bytes.Equal(b, []byte(try)) { - ok = true - break - } - } - } - } - if !ok { - t.Fatalf("Incorrect Marshal output.\n got %q\nwant %q (or a permutation of that)", b, parts[0]+parts[1]+parts[2]) - } - t.Logf("FYI b: %q", b) - - (new(Buffer)).DebugPrint("Dump of b", b) -} - -func TestMapFieldRoundTrips(t *testing.T) { - m := &MessageWithMap{ - NameMapping: map[int32]string{ - 1: "Rob", - 4: "Ian", - 8: "Dave", - }, - MsgMapping: map[int64]*FloatingPoint{ - 0x7001: {F: Float64(2.0)}, - }, - ByteMapping: map[bool][]byte{ - false: []byte("that's not right!"), - true: []byte("aye, 'tis true!"), - }, - } - b, err := Marshal(m) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - t.Logf("FYI b: %q", b) - m2 := new(MessageWithMap) - if err := Unmarshal(b, m2); err != nil { - t.Fatalf("Unmarshal: %v", err) - } - for _, pair := range [][2]interface{}{ - {m.NameMapping, m2.NameMapping}, - {m.MsgMapping, m2.MsgMapping}, - {m.ByteMapping, m2.ByteMapping}, - } { - if !reflect.DeepEqual(pair[0], pair[1]) { - t.Errorf("Map did not survive a round trip.\ninitial: %v\n final: %v", pair[0], pair[1]) - } - } -} - -func TestMapFieldWithNil(t *testing.T) { - m1 := &MessageWithMap{ - MsgMapping: map[int64]*FloatingPoint{ - 1: nil, - }, - } - b, err := Marshal(m1) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - m2 := new(MessageWithMap) - if err := Unmarshal(b, m2); err != nil { - t.Fatalf("Unmarshal: %v, got these bytes: %v", err, b) - } - if v, ok := m2.MsgMapping[1]; !ok { - t.Error("msg_mapping[1] not present") - } else if v != nil { - t.Errorf("msg_mapping[1] not nil: %v", v) - } -} - -func TestMapFieldWithNilBytes(t *testing.T) { - m1 := &MessageWithMap{ - ByteMapping: map[bool][]byte{ - false: {}, - true: nil, - }, - } - n := Size(m1) - b, err := Marshal(m1) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - if n != len(b) { - t.Errorf("Size(m1) = %d; want len(Marshal(m1)) = %d", n, len(b)) - } - m2 := new(MessageWithMap) - if err := Unmarshal(b, m2); err != nil { - t.Fatalf("Unmarshal: %v, got these bytes: %v", err, b) - } - if v, ok := m2.ByteMapping[false]; !ok { - t.Error("byte_mapping[false] not present") - } else if len(v) != 0 { - t.Errorf("byte_mapping[false] not empty: %#v", v) - } - if v, ok := m2.ByteMapping[true]; !ok { - t.Error("byte_mapping[true] not present") - } else if len(v) != 0 { - t.Errorf("byte_mapping[true] not empty: %#v", v) - } -} - -func TestDecodeMapFieldMissingKey(t *testing.T) { - b := []byte{ - 0x0A, 0x03, // message, tag 1 (name_mapping), of length 3 bytes - // no key - 0x12, 0x01, 0x6D, // string value of length 1 byte, value "m" - } - got := &MessageWithMap{} - err := Unmarshal(b, got) - if err != nil { - t.Fatalf("failed to marshal map with missing key: %v", err) - } - want := &MessageWithMap{NameMapping: map[int32]string{0: "m"}} - if !Equal(got, want) { - t.Errorf("Unmarshaled map with no key was not as expected. got: %v, want %v", got, want) - } -} - -func TestDecodeMapFieldMissingValue(t *testing.T) { - b := []byte{ - 0x0A, 0x02, // message, tag 1 (name_mapping), of length 2 bytes - 0x08, 0x01, // varint key, value 1 - // no value - } - got := &MessageWithMap{} - err := Unmarshal(b, got) - if err != nil { - t.Fatalf("failed to marshal map with missing value: %v", err) - } - want := &MessageWithMap{NameMapping: map[int32]string{1: ""}} - if !Equal(got, want) { - t.Errorf("Unmarshaled map with no value was not as expected. got: %v, want %v", got, want) - } -} - -func TestOneof(t *testing.T) { - m := &Communique{} - b, err := Marshal(m) - if err != nil { - t.Fatalf("Marshal of empty message with oneof: %v", err) - } - if len(b) != 0 { - t.Errorf("Marshal of empty message yielded too many bytes: %v", b) - } - - m = &Communique{ - Union: &Communique_Name{Name: "Barry"}, - } - - // Round-trip. - b, err = Marshal(m) - if err != nil { - t.Fatalf("Marshal of message with oneof: %v", err) - } - if len(b) != 7 { // name tag/wire (1) + name len (1) + name (5) - t.Errorf("Incorrect marshal of message with oneof: %v", b) - } - m.Reset() - if err = Unmarshal(b, m); err != nil { - t.Fatalf("Unmarshal of message with oneof: %v", err) - } - if x, ok := m.Union.(*Communique_Name); !ok || x.Name != "Barry" { - t.Errorf("After round trip, Union = %+v", m.Union) - } - if name := m.GetName(); name != "Barry" { - t.Errorf("After round trip, GetName = %q, want %q", name, "Barry") - } - - // Let's try with a message in the oneof. - m.Union = &Communique_Msg{Msg: &Strings{StringField: String("deep deep string")}} - b, err = Marshal(m) - if err != nil { - t.Fatalf("Marshal of message with oneof set to message: %v", err) - } - if len(b) != 20 { // msg tag/wire (1) + msg len (1) + msg (1 + 1 + 16) - t.Errorf("Incorrect marshal of message with oneof set to message: %v", b) - } - m.Reset() - if err := Unmarshal(b, m); err != nil { - t.Fatalf("Unmarshal of message with oneof set to message: %v", err) - } - ss, ok := m.Union.(*Communique_Msg) - if !ok || ss.Msg.GetStringField() != "deep deep string" { - t.Errorf("After round trip with oneof set to message, Union = %+v", m.Union) - } -} - -func TestInefficientPackedBool(t *testing.T) { - // https://github.com/golang/protobuf/issues/76 - inp := []byte{ - 0x12, 0x02, // 0x12 = 2<<3|2; 2 bytes - // Usually a bool should take a single byte, - // but it is permitted to be any varint. - 0xb9, 0x30, - } - if err := Unmarshal(inp, new(MoreRepeated)); err != nil { - t.Error(err) - } -} - -// Benchmarks - -func testMsg() *GoTest { - pb := initGoTest(true) - const N = 1000 // Internally the library starts much smaller. - pb.F_Int32Repeated = make([]int32, N) - pb.F_DoubleRepeated = make([]float64, N) - for i := 0; i < N; i++ { - pb.F_Int32Repeated[i] = int32(i) - pb.F_DoubleRepeated[i] = float64(i) - } - return pb -} - -func bytesMsg() *GoTest { - pb := initGoTest(true) - buf := make([]byte, 4000) - for i := range buf { - buf[i] = byte(i) - } - pb.F_BytesDefaulted = buf - return pb -} - -func benchmarkMarshal(b *testing.B, pb Message, marshal func(Message) ([]byte, error)) { - d, _ := marshal(pb) - b.SetBytes(int64(len(d))) - b.ResetTimer() - for i := 0; i < b.N; i++ { - marshal(pb) - } -} - -func benchmarkBufferMarshal(b *testing.B, pb Message) { - p := NewBuffer(nil) - benchmarkMarshal(b, pb, func(pb0 Message) ([]byte, error) { - p.Reset() - err := p.Marshal(pb0) - return p.Bytes(), err - }) -} - -func benchmarkSize(b *testing.B, pb Message) { - benchmarkMarshal(b, pb, func(pb0 Message) ([]byte, error) { - Size(pb) - return nil, nil - }) -} - -func newOf(pb Message) Message { - in := reflect.ValueOf(pb) - if in.IsNil() { - return pb - } - return reflect.New(in.Type().Elem()).Interface().(Message) -} - -func benchmarkUnmarshal(b *testing.B, pb Message, unmarshal func([]byte, Message) error) { - d, _ := Marshal(pb) - b.SetBytes(int64(len(d))) - pbd := newOf(pb) - - b.ResetTimer() - for i := 0; i < b.N; i++ { - unmarshal(d, pbd) - } -} - -func benchmarkBufferUnmarshal(b *testing.B, pb Message) { - p := NewBuffer(nil) - benchmarkUnmarshal(b, pb, func(d []byte, pb0 Message) error { - p.SetBuf(d) - return p.Unmarshal(pb0) - }) -} - -// Benchmark{Marshal,BufferMarshal,Size,Unmarshal,BufferUnmarshal}{,Bytes} - -func BenchmarkMarshal(b *testing.B) { - benchmarkMarshal(b, testMsg(), Marshal) -} - -func BenchmarkBufferMarshal(b *testing.B) { - benchmarkBufferMarshal(b, testMsg()) -} - -func BenchmarkSize(b *testing.B) { - benchmarkSize(b, testMsg()) -} - -func BenchmarkUnmarshal(b *testing.B) { - benchmarkUnmarshal(b, testMsg(), Unmarshal) -} - -func BenchmarkBufferUnmarshal(b *testing.B) { - benchmarkBufferUnmarshal(b, testMsg()) -} - -func BenchmarkMarshalBytes(b *testing.B) { - benchmarkMarshal(b, bytesMsg(), Marshal) -} - -func BenchmarkBufferMarshalBytes(b *testing.B) { - benchmarkBufferMarshal(b, bytesMsg()) -} - -func BenchmarkSizeBytes(b *testing.B) { - benchmarkSize(b, bytesMsg()) -} - -func BenchmarkUnmarshalBytes(b *testing.B) { - benchmarkUnmarshal(b, bytesMsg(), Unmarshal) -} - -func BenchmarkBufferUnmarshalBytes(b *testing.B) { - benchmarkBufferUnmarshal(b, bytesMsg()) -} - -func BenchmarkUnmarshalUnrecognizedFields(b *testing.B) { - b.StopTimer() - pb := initGoTestField() - skip := &GoSkipTest{ - SkipInt32: Int32(32), - SkipFixed32: Uint32(3232), - SkipFixed64: Uint64(6464), - SkipString: String("skipper"), - Skipgroup: &GoSkipTest_SkipGroup{ - GroupInt32: Int32(75), - GroupString: String("wxyz"), - }, - } - - pbd := new(GoTestField) - p := NewBuffer(nil) - p.Marshal(pb) - p.Marshal(skip) - p2 := NewBuffer(nil) - - b.StartTimer() - for i := 0; i < b.N; i++ { - p2.SetBuf(p.Bytes()) - p2.Unmarshal(pbd) - } -} diff --git a/vendor/github.com/gogo/protobuf/proto/any_test.go b/vendor/github.com/gogo/protobuf/proto/any_test.go deleted file mode 100644 index f098d8287..000000000 --- a/vendor/github.com/gogo/protobuf/proto/any_test.go +++ /dev/null @@ -1,300 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2016 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto_test - -import ( - "strings" - "testing" - - "github.com/gogo/protobuf/proto" - - pb "github.com/gogo/protobuf/proto/proto3_proto" - testpb "github.com/gogo/protobuf/proto/testdata" - "github.com/gogo/protobuf/types" -) - -var ( - expandedMarshaler = proto.TextMarshaler{ExpandAny: true} - expandedCompactMarshaler = proto.TextMarshaler{Compact: true, ExpandAny: true} -) - -// anyEqual reports whether two messages which may be google.protobuf.Any or may -// contain google.protobuf.Any fields are equal. We can't use proto.Equal for -// comparison, because semantically equivalent messages may be marshaled to -// binary in different tag order. Instead, trust that TextMarshaler with -// ExpandAny option works and compare the text marshaling results. -func anyEqual(got, want proto.Message) bool { - // if messages are proto.Equal, no need to marshal. - if proto.Equal(got, want) { - return true - } - g := expandedMarshaler.Text(got) - w := expandedMarshaler.Text(want) - return g == w -} - -type golden struct { - m proto.Message - t, c string -} - -var goldenMessages = makeGolden() - -func makeGolden() []golden { - nested := &pb.Nested{Bunny: "Monty"} - nb, err := proto.Marshal(nested) - if err != nil { - panic(err) - } - m1 := &pb.Message{ - Name: "David", - ResultCount: 47, - Anything: &types.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(nested), Value: nb}, - } - m2 := &pb.Message{ - Name: "David", - ResultCount: 47, - Anything: &types.Any{TypeUrl: "http://[::1]/type.googleapis.com/" + proto.MessageName(nested), Value: nb}, - } - m3 := &pb.Message{ - Name: "David", - ResultCount: 47, - Anything: &types.Any{TypeUrl: `type.googleapis.com/"/` + proto.MessageName(nested), Value: nb}, - } - m4 := &pb.Message{ - Name: "David", - ResultCount: 47, - Anything: &types.Any{TypeUrl: "type.googleapis.com/a/path/" + proto.MessageName(nested), Value: nb}, - } - m5 := &types.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(nested), Value: nb} - - any1 := &testpb.MyMessage{Count: proto.Int32(47), Name: proto.String("David")} - proto.SetExtension(any1, testpb.E_Ext_More, &testpb.Ext{Data: proto.String("foo")}) - proto.SetExtension(any1, testpb.E_Ext_Text, proto.String("bar")) - any1b, err := proto.Marshal(any1) - if err != nil { - panic(err) - } - any2 := &testpb.MyMessage{Count: proto.Int32(42), Bikeshed: testpb.MyMessage_GREEN.Enum(), RepBytes: [][]byte{[]byte("roboto")}} - proto.SetExtension(any2, testpb.E_Ext_More, &testpb.Ext{Data: proto.String("baz")}) - any2b, err := proto.Marshal(any2) - if err != nil { - panic(err) - } - m6 := &pb.Message{ - Name: "David", - ResultCount: 47, - Anything: &types.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(any1), Value: any1b}, - ManyThings: []*types.Any{ - {TypeUrl: "type.googleapis.com/" + proto.MessageName(any2), Value: any2b}, - {TypeUrl: "type.googleapis.com/" + proto.MessageName(any1), Value: any1b}, - }, - } - - const ( - m1Golden = ` -name: "David" -result_count: 47 -anything: < - [type.googleapis.com/proto3_proto.Nested]: < - bunny: "Monty" - > -> -` - m2Golden = ` -name: "David" -result_count: 47 -anything: < - ["http://[::1]/type.googleapis.com/proto3_proto.Nested"]: < - bunny: "Monty" - > -> -` - m3Golden = ` -name: "David" -result_count: 47 -anything: < - ["type.googleapis.com/\"/proto3_proto.Nested"]: < - bunny: "Monty" - > -> -` - m4Golden = ` -name: "David" -result_count: 47 -anything: < - [type.googleapis.com/a/path/proto3_proto.Nested]: < - bunny: "Monty" - > -> -` - m5Golden = ` -[type.googleapis.com/proto3_proto.Nested]: < - bunny: "Monty" -> -` - m6Golden = ` -name: "David" -result_count: 47 -anything: < - [type.googleapis.com/testdata.MyMessage]: < - count: 47 - name: "David" - [testdata.Ext.more]: < - data: "foo" - > - [testdata.Ext.text]: "bar" - > -> -many_things: < - [type.googleapis.com/testdata.MyMessage]: < - count: 42 - bikeshed: GREEN - rep_bytes: "roboto" - [testdata.Ext.more]: < - data: "baz" - > - > -> -many_things: < - [type.googleapis.com/testdata.MyMessage]: < - count: 47 - name: "David" - [testdata.Ext.more]: < - data: "foo" - > - [testdata.Ext.text]: "bar" - > -> -` - ) - return []golden{ - {m1, strings.TrimSpace(m1Golden) + "\n", strings.TrimSpace(compact(m1Golden)) + " "}, - {m2, strings.TrimSpace(m2Golden) + "\n", strings.TrimSpace(compact(m2Golden)) + " "}, - {m3, strings.TrimSpace(m3Golden) + "\n", strings.TrimSpace(compact(m3Golden)) + " "}, - {m4, strings.TrimSpace(m4Golden) + "\n", strings.TrimSpace(compact(m4Golden)) + " "}, - {m5, strings.TrimSpace(m5Golden) + "\n", strings.TrimSpace(compact(m5Golden)) + " "}, - {m6, strings.TrimSpace(m6Golden) + "\n", strings.TrimSpace(compact(m6Golden)) + " "}, - } -} - -func TestMarshalGolden(t *testing.T) { - for _, tt := range goldenMessages { - if got, want := expandedMarshaler.Text(tt.m), tt.t; got != want { - t.Errorf("message %v: got:\n%s\nwant:\n%s", tt.m, got, want) - } - if got, want := expandedCompactMarshaler.Text(tt.m), tt.c; got != want { - t.Errorf("message %v: got:\n`%s`\nwant:\n`%s`", tt.m, got, want) - } - } -} - -func TestUnmarshalGolden(t *testing.T) { - for _, tt := range goldenMessages { - want := tt.m - got := proto.Clone(tt.m) - got.Reset() - if err := proto.UnmarshalText(tt.t, got); err != nil { - t.Errorf("failed to unmarshal\n%s\nerror: %v", tt.t, err) - } - if !anyEqual(got, want) { - t.Errorf("message:\n%s\ngot:\n%s\nwant:\n%s", tt.t, got, want) - } - got.Reset() - if err := proto.UnmarshalText(tt.c, got); err != nil { - t.Errorf("failed to unmarshal\n%s\nerror: %v", tt.c, err) - } - if !anyEqual(got, want) { - t.Errorf("message:\n%s\ngot:\n%s\nwant:\n%s", tt.c, got, want) - } - } -} - -func TestMarshalUnknownAny(t *testing.T) { - m := &pb.Message{ - Anything: &types.Any{ - TypeUrl: "foo", - Value: []byte("bar"), - }, - } - want := `anything: < - type_url: "foo" - value: "bar" -> -` - got := expandedMarshaler.Text(m) - if got != want { - t.Errorf("got\n`%s`\nwant\n`%s`", got, want) - } -} - -func TestAmbiguousAny(t *testing.T) { - pb := &types.Any{} - err := proto.UnmarshalText(` - type_url: "ttt/proto3_proto.Nested" - value: "\n\x05Monty" - `, pb) - t.Logf("result: %v (error: %v)", expandedMarshaler.Text(pb), err) - if err != nil { - t.Errorf("failed to parse ambiguous Any message: %v", err) - } -} - -func TestUnmarshalOverwriteAny(t *testing.T) { - pb := &types.Any{} - err := proto.UnmarshalText(` - [type.googleapis.com/a/path/proto3_proto.Nested]: < - bunny: "Monty" - > - [type.googleapis.com/a/path/proto3_proto.Nested]: < - bunny: "Rabbit of Caerbannog" - > - `, pb) - want := `line 7: Any message unpacked multiple times, or "type_url" already set` - if err.Error() != want { - t.Errorf("incorrect error.\nHave: %v\nWant: %v", err.Error(), want) - } -} - -func TestUnmarshalAnyMixAndMatch(t *testing.T) { - pb := &types.Any{} - err := proto.UnmarshalText(` - value: "\n\x05Monty" - [type.googleapis.com/a/path/proto3_proto.Nested]: < - bunny: "Rabbit of Caerbannog" - > - `, pb) - want := `line 5: Any message unpacked multiple times, or "value" already set` - if err.Error() != want { - t.Errorf("incorrect error.\nHave: %v\nWant: %v", err.Error(), want) - } -} diff --git a/vendor/github.com/gogo/protobuf/proto/clone_test.go b/vendor/github.com/gogo/protobuf/proto/clone_test.go deleted file mode 100644 index 1a16eb554..000000000 --- a/vendor/github.com/gogo/protobuf/proto/clone_test.go +++ /dev/null @@ -1,300 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2011 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto_test - -import ( - "testing" - - "github.com/gogo/protobuf/proto" - - proto3pb "github.com/gogo/protobuf/proto/proto3_proto" - pb "github.com/gogo/protobuf/proto/testdata" -) - -var cloneTestMessage = &pb.MyMessage{ - Count: proto.Int32(42), - Name: proto.String("Dave"), - Pet: []string{"bunny", "kitty", "horsey"}, - Inner: &pb.InnerMessage{ - Host: proto.String("niles"), - Port: proto.Int32(9099), - Connected: proto.Bool(true), - }, - Others: []*pb.OtherMessage{ - { - Value: []byte("some bytes"), - }, - }, - Somegroup: &pb.MyMessage_SomeGroup{ - GroupField: proto.Int32(6), - }, - RepBytes: [][]byte{[]byte("sham"), []byte("wow")}, -} - -func init() { - ext := &pb.Ext{ - Data: proto.String("extension"), - } - if err := proto.SetExtension(cloneTestMessage, pb.E_Ext_More, ext); err != nil { - panic("SetExtension: " + err.Error()) - } -} - -func TestClone(t *testing.T) { - m := proto.Clone(cloneTestMessage).(*pb.MyMessage) - if !proto.Equal(m, cloneTestMessage) { - t.Errorf("Clone(%v) = %v", cloneTestMessage, m) - } - - // Verify it was a deep copy. - *m.Inner.Port++ - if proto.Equal(m, cloneTestMessage) { - t.Error("Mutating clone changed the original") - } - // Byte fields and repeated fields should be copied. - if &m.Pet[0] == &cloneTestMessage.Pet[0] { - t.Error("Pet: repeated field not copied") - } - if &m.Others[0] == &cloneTestMessage.Others[0] { - t.Error("Others: repeated field not copied") - } - if &m.Others[0].Value[0] == &cloneTestMessage.Others[0].Value[0] { - t.Error("Others[0].Value: bytes field not copied") - } - if &m.RepBytes[0] == &cloneTestMessage.RepBytes[0] { - t.Error("RepBytes: repeated field not copied") - } - if &m.RepBytes[0][0] == &cloneTestMessage.RepBytes[0][0] { - t.Error("RepBytes[0]: bytes field not copied") - } -} - -func TestCloneNil(t *testing.T) { - var m *pb.MyMessage - if c := proto.Clone(m); !proto.Equal(m, c) { - t.Errorf("Clone(%v) = %v", m, c) - } -} - -var mergeTests = []struct { - src, dst, want proto.Message -}{ - { - src: &pb.MyMessage{ - Count: proto.Int32(42), - }, - dst: &pb.MyMessage{ - Name: proto.String("Dave"), - }, - want: &pb.MyMessage{ - Count: proto.Int32(42), - Name: proto.String("Dave"), - }, - }, - { - src: &pb.MyMessage{ - Inner: &pb.InnerMessage{ - Host: proto.String("hey"), - Connected: proto.Bool(true), - }, - Pet: []string{"horsey"}, - Others: []*pb.OtherMessage{ - { - Value: []byte("some bytes"), - }, - }, - }, - dst: &pb.MyMessage{ - Inner: &pb.InnerMessage{ - Host: proto.String("niles"), - Port: proto.Int32(9099), - }, - Pet: []string{"bunny", "kitty"}, - Others: []*pb.OtherMessage{ - { - Key: proto.Int64(31415926535), - }, - { - // Explicitly test a src=nil field - Inner: nil, - }, - }, - }, - want: &pb.MyMessage{ - Inner: &pb.InnerMessage{ - Host: proto.String("hey"), - Connected: proto.Bool(true), - Port: proto.Int32(9099), - }, - Pet: []string{"bunny", "kitty", "horsey"}, - Others: []*pb.OtherMessage{ - { - Key: proto.Int64(31415926535), - }, - {}, - { - Value: []byte("some bytes"), - }, - }, - }, - }, - { - src: &pb.MyMessage{ - RepBytes: [][]byte{[]byte("wow")}, - }, - dst: &pb.MyMessage{ - Somegroup: &pb.MyMessage_SomeGroup{ - GroupField: proto.Int32(6), - }, - RepBytes: [][]byte{[]byte("sham")}, - }, - want: &pb.MyMessage{ - Somegroup: &pb.MyMessage_SomeGroup{ - GroupField: proto.Int32(6), - }, - RepBytes: [][]byte{[]byte("sham"), []byte("wow")}, - }, - }, - // Check that a scalar bytes field replaces rather than appends. - { - src: &pb.OtherMessage{Value: []byte("foo")}, - dst: &pb.OtherMessage{Value: []byte("bar")}, - want: &pb.OtherMessage{Value: []byte("foo")}, - }, - { - src: &pb.MessageWithMap{ - NameMapping: map[int32]string{6: "Nigel"}, - MsgMapping: map[int64]*pb.FloatingPoint{ - 0x4001: {F: proto.Float64(2.0)}, - 0x4002: { - F: proto.Float64(2.0), - }, - }, - ByteMapping: map[bool][]byte{true: []byte("wowsa")}, - }, - dst: &pb.MessageWithMap{ - NameMapping: map[int32]string{ - 6: "Bruce", // should be overwritten - 7: "Andrew", - }, - MsgMapping: map[int64]*pb.FloatingPoint{ - 0x4002: { - F: proto.Float64(3.0), - Exact: proto.Bool(true), - }, // the entire message should be overwritten - }, - }, - want: &pb.MessageWithMap{ - NameMapping: map[int32]string{ - 6: "Nigel", - 7: "Andrew", - }, - MsgMapping: map[int64]*pb.FloatingPoint{ - 0x4001: {F: proto.Float64(2.0)}, - 0x4002: { - F: proto.Float64(2.0), - }, - }, - ByteMapping: map[bool][]byte{true: []byte("wowsa")}, - }, - }, - // proto3 shouldn't merge zero values, - // in the same way that proto2 shouldn't merge nils. - { - src: &proto3pb.Message{ - Name: "Aaron", - Data: []byte(""), // zero value, but not nil - }, - dst: &proto3pb.Message{ - HeightInCm: 176, - Data: []byte("texas!"), - }, - want: &proto3pb.Message{ - Name: "Aaron", - HeightInCm: 176, - Data: []byte("texas!"), - }, - }, - // Oneof fields should merge by assignment. - { - src: &pb.Communique{ - Union: &pb.Communique_Number{Number: 41}, - }, - dst: &pb.Communique{ - Union: &pb.Communique_Name{Name: "Bobby Tables"}, - }, - want: &pb.Communique{ - Union: &pb.Communique_Number{Number: 41}, - }, - }, - // Oneof nil is the same as not set. - { - src: &pb.Communique{}, - dst: &pb.Communique{ - Union: &pb.Communique_Name{Name: "Bobby Tables"}, - }, - want: &pb.Communique{ - Union: &pb.Communique_Name{Name: "Bobby Tables"}, - }, - }, - { - src: &proto3pb.Message{ - Terrain: map[string]*proto3pb.Nested{ - "kay_a": {Cute: true}, // replace - "kay_b": {Bunny: "rabbit"}, // insert - }, - }, - dst: &proto3pb.Message{ - Terrain: map[string]*proto3pb.Nested{ - "kay_a": {Bunny: "lost"}, // replaced - "kay_c": {Bunny: "bunny"}, // keep - }, - }, - want: &proto3pb.Message{ - Terrain: map[string]*proto3pb.Nested{ - "kay_a": {Cute: true}, - "kay_b": {Bunny: "rabbit"}, - "kay_c": {Bunny: "bunny"}, - }, - }, - }, -} - -func TestMerge(t *testing.T) { - for _, m := range mergeTests { - got := proto.Clone(m.dst) - proto.Merge(got, m.src) - if !proto.Equal(got, m.want) { - t.Errorf("Merge(%v, %v)\n got %v\nwant %v\n", m.dst, m.src, got, m.want) - } - } -} diff --git a/vendor/github.com/gogo/protobuf/proto/decode_test.go b/vendor/github.com/gogo/protobuf/proto/decode_test.go deleted file mode 100644 index 64d4decd9..000000000 --- a/vendor/github.com/gogo/protobuf/proto/decode_test.go +++ /dev/null @@ -1,262 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// +build go1.7 - -package proto_test - -import ( - "testing" - - "github.com/gogo/protobuf/proto" - tpb "github.com/gogo/protobuf/proto/proto3_proto" -) - -var ( - bytesBlackhole []byte - msgBlackhole = new(tpb.Message) -) - -// Disabled this Benchmark because it is using features (b.Run) from go1.7 and gogoprotobuf still have compatibility with go1.5 -// BenchmarkVarint32ArraySmall shows the performance on an array of small int32 fields (1 and -// 2 bytes long). -// func BenchmarkVarint32ArraySmall(b *testing.B) { -// for i := uint(1); i <= 10; i++ { -// dist := genInt32Dist([7]int{0, 3, 1}, 1<unmarshal. -} - -func TestMarshalUnmarshalRepeatedExtension(t *testing.T) { - // Add a repeated extension to the result. - tests := []struct { - name string - ext []*pb.ComplexExtension - }{ - { - "two fields", - []*pb.ComplexExtension{ - {First: proto.Int32(7)}, - {Second: proto.Int32(11)}, - }, - }, - { - "repeated field", - []*pb.ComplexExtension{ - {Third: []int32{1000}}, - {Third: []int32{2000}}, - }, - }, - { - "two fields and repeated field", - []*pb.ComplexExtension{ - {Third: []int32{1000}}, - {First: proto.Int32(9)}, - {Second: proto.Int32(21)}, - {Third: []int32{2000}}, - }, - }, - } - for _, test := range tests { - // Marshal message with a repeated extension. - msg1 := new(pb.OtherMessage) - err := proto.SetExtension(msg1, pb.E_RComplex, test.ext) - if err != nil { - t.Fatalf("[%s] Error setting extension: %v", test.name, err) - } - b, err := proto.Marshal(msg1) - if err != nil { - t.Fatalf("[%s] Error marshaling message: %v", test.name, err) - } - - // Unmarshal and read the merged proto. - msg2 := new(pb.OtherMessage) - err = proto.Unmarshal(b, msg2) - if err != nil { - t.Fatalf("[%s] Error unmarshaling message: %v", test.name, err) - } - e, err := proto.GetExtension(msg2, pb.E_RComplex) - if err != nil { - t.Fatalf("[%s] Error getting extension: %v", test.name, err) - } - ext := e.([]*pb.ComplexExtension) - if ext == nil { - t.Fatalf("[%s] Invalid extension", test.name) - } - if !reflect.DeepEqual(ext, test.ext) { - t.Errorf("[%s] Wrong value for ComplexExtension: got: %v want: %v\n", test.name, ext, test.ext) - } - } -} - -func TestUnmarshalRepeatingNonRepeatedExtension(t *testing.T) { - // We may see multiple instances of the same extension in the wire - // format. For example, the proto compiler may encode custom options in - // this way. Here, we verify that we merge the extensions together. - tests := []struct { - name string - ext []*pb.ComplexExtension - }{ - { - "two fields", - []*pb.ComplexExtension{ - {First: proto.Int32(7)}, - {Second: proto.Int32(11)}, - }, - }, - { - "repeated field", - []*pb.ComplexExtension{ - {Third: []int32{1000}}, - {Third: []int32{2000}}, - }, - }, - { - "two fields and repeated field", - []*pb.ComplexExtension{ - {Third: []int32{1000}}, - {First: proto.Int32(9)}, - {Second: proto.Int32(21)}, - {Third: []int32{2000}}, - }, - }, - } - for _, test := range tests { - var buf bytes.Buffer - var want pb.ComplexExtension - - // Generate a serialized representation of a repeated extension - // by catenating bytes together. - for i, e := range test.ext { - // Merge to create the wanted proto. - proto.Merge(&want, e) - - // serialize the message - msg := new(pb.OtherMessage) - err := proto.SetExtension(msg, pb.E_Complex, e) - if err != nil { - t.Fatalf("[%s] Error setting extension %d: %v", test.name, i, err) - } - b, err := proto.Marshal(msg) - if err != nil { - t.Fatalf("[%s] Error marshaling message %d: %v", test.name, i, err) - } - buf.Write(b) - } - - // Unmarshal and read the merged proto. - msg2 := new(pb.OtherMessage) - err := proto.Unmarshal(buf.Bytes(), msg2) - if err != nil { - t.Fatalf("[%s] Error unmarshaling message: %v", test.name, err) - } - e, err := proto.GetExtension(msg2, pb.E_Complex) - if err != nil { - t.Fatalf("[%s] Error getting extension: %v", test.name, err) - } - ext := e.(*pb.ComplexExtension) - if ext == nil { - t.Fatalf("[%s] Invalid extension", test.name) - } - if !reflect.DeepEqual(*ext, want) { - t.Errorf("[%s] Wrong value for ComplexExtension: got: %v want: %v\n", test.name, ext, want) - } - } -} - -func TestClearAllExtensions(t *testing.T) { - // unregistered extension - desc := &proto.ExtensionDesc{ - ExtendedType: (*pb.MyMessage)(nil), - ExtensionType: (*bool)(nil), - Field: 101010100, - Name: "emptyextension", - Tag: "varint,0,opt", - } - m := &pb.MyMessage{} - if proto.HasExtension(m, desc) { - t.Errorf("proto.HasExtension(%s): got true, want false", proto.MarshalTextString(m)) - } - if err := proto.SetExtension(m, desc, proto.Bool(true)); err != nil { - t.Errorf("proto.SetExtension(m, desc, true): got error %q, want nil", err) - } - if !proto.HasExtension(m, desc) { - t.Errorf("proto.HasExtension(%s): got false, want true", proto.MarshalTextString(m)) - } - proto.ClearAllExtensions(m) - if proto.HasExtension(m, desc) { - t.Errorf("proto.HasExtension(%s): got true, want false", proto.MarshalTextString(m)) - } -} - -func TestMarshalRace(t *testing.T) { - // unregistered extension - desc := &proto.ExtensionDesc{ - ExtendedType: (*pb.MyMessage)(nil), - ExtensionType: (*bool)(nil), - Field: 101010100, - Name: "emptyextension", - Tag: "varint,0,opt", - } - - m := &pb.MyMessage{Count: proto.Int32(4)} - if err := proto.SetExtension(m, desc, proto.Bool(true)); err != nil { - t.Errorf("proto.SetExtension(m, desc, true): got error %q, want nil", err) - } - - errChan := make(chan error, 3) - for n := 3; n > 0; n-- { - go func() { - _, err := proto.Marshal(m) - errChan <- err - }() - } - for i := 0; i < 3; i++ { - err := <-errChan - if err != nil { - t.Fatal(err) - } - } -} diff --git a/vendor/github.com/gogo/protobuf/proto/map_test.go b/vendor/github.com/gogo/protobuf/proto/map_test.go deleted file mode 100644 index 18b946d00..000000000 --- a/vendor/github.com/gogo/protobuf/proto/map_test.go +++ /dev/null @@ -1,46 +0,0 @@ -package proto_test - -import ( - "fmt" - "testing" - - "github.com/gogo/protobuf/proto" - ppb "github.com/gogo/protobuf/proto/proto3_proto" -) - -func marshalled() []byte { - m := &ppb.IntMaps{} - for i := 0; i < 1000; i++ { - m.Maps = append(m.Maps, &ppb.IntMap{ - Rtt: map[int32]int32{1: 2}, - }) - } - b, err := proto.Marshal(m) - if err != nil { - panic(fmt.Sprintf("Can't marshal %+v: %v", m, err)) - } - return b -} - -func BenchmarkConcurrentMapUnmarshal(b *testing.B) { - in := marshalled() - b.RunParallel(func(pb *testing.PB) { - for pb.Next() { - var out ppb.IntMaps - if err := proto.Unmarshal(in, &out); err != nil { - b.Errorf("Can't unmarshal ppb.IntMaps: %v", err) - } - } - }) -} - -func BenchmarkSequentialMapUnmarshal(b *testing.B) { - in := marshalled() - b.ResetTimer() - for i := 0; i < b.N; i++ { - var out ppb.IntMaps - if err := proto.Unmarshal(in, &out); err != nil { - b.Errorf("Can't unmarshal ppb.IntMaps: %v", err) - } - } -} diff --git a/vendor/github.com/gogo/protobuf/proto/message_set_test.go b/vendor/github.com/gogo/protobuf/proto/message_set_test.go deleted file mode 100644 index 353a3ea76..000000000 --- a/vendor/github.com/gogo/protobuf/proto/message_set_test.go +++ /dev/null @@ -1,66 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2014 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -import ( - "bytes" - "testing" -) - -func TestUnmarshalMessageSetWithDuplicate(t *testing.T) { - // Check that a repeated message set entry will be concatenated. - in := &messageSet{ - Item: []*_MessageSet_Item{ - {TypeId: Int32(12345), Message: []byte("hoo")}, - {TypeId: Int32(12345), Message: []byte("hah")}, - }, - } - b, err := Marshal(in) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - t.Logf("Marshaled bytes: %q", b) - - var extensions XXX_InternalExtensions - if err := UnmarshalMessageSet(b, &extensions); err != nil { - t.Fatalf("UnmarshalMessageSet: %v", err) - } - ext, ok := extensions.p.extensionMap[12345] - if !ok { - t.Fatalf("Didn't retrieve extension 12345; map is %v", extensions.p.extensionMap) - } - // Skip wire type/field number and length varints. - got := skipVarint(skipVarint(ext.enc)) - if want := []byte("hoohah"); !bytes.Equal(got, want) { - t.Errorf("Combined extension is %q, want %q", got, want) - } -} diff --git a/vendor/github.com/gogo/protobuf/proto/proto3_test.go b/vendor/github.com/gogo/protobuf/proto/proto3_test.go deleted file mode 100644 index 75b66c179..000000000 --- a/vendor/github.com/gogo/protobuf/proto/proto3_test.go +++ /dev/null @@ -1,135 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2014 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto_test - -import ( - "testing" - - "github.com/gogo/protobuf/proto" - pb "github.com/gogo/protobuf/proto/proto3_proto" - tpb "github.com/gogo/protobuf/proto/testdata" -) - -func TestProto3ZeroValues(t *testing.T) { - tests := []struct { - desc string - m proto.Message - }{ - {"zero message", &pb.Message{}}, - {"empty bytes field", &pb.Message{Data: []byte{}}}, - } - for _, test := range tests { - b, err := proto.Marshal(test.m) - if err != nil { - t.Errorf("%s: proto.Marshal: %v", test.desc, err) - continue - } - if len(b) > 0 { - t.Errorf("%s: Encoding is non-empty: %q", test.desc, b) - } - } -} - -func TestRoundTripProto3(t *testing.T) { - m := &pb.Message{ - Name: "David", // (2 | 1<<3): 0x0a 0x05 "David" - Hilarity: pb.Message_PUNS, // (0 | 2<<3): 0x10 0x01 - HeightInCm: 178, // (0 | 3<<3): 0x18 0xb2 0x01 - Data: []byte("roboto"), // (2 | 4<<3): 0x20 0x06 "roboto" - ResultCount: 47, // (0 | 7<<3): 0x38 0x2f - TrueScotsman: true, // (0 | 8<<3): 0x40 0x01 - Score: 8.1, // (5 | 9<<3): 0x4d <8.1> - - Key: []uint64{1, 0xdeadbeef}, - Nested: &pb.Nested{ - Bunny: "Monty", - }, - } - t.Logf(" m: %v", m) - - b, err := proto.Marshal(m) - if err != nil { - t.Fatalf("proto.Marshal: %v", err) - } - t.Logf(" b: %q", b) - - m2 := new(pb.Message) - if err := proto.Unmarshal(b, m2); err != nil { - t.Fatalf("proto.Unmarshal: %v", err) - } - t.Logf("m2: %v", m2) - - if !proto.Equal(m, m2) { - t.Errorf("proto.Equal returned false:\n m: %v\nm2: %v", m, m2) - } -} - -func TestGettersForBasicTypesExist(t *testing.T) { - var m pb.Message - if got := m.GetNested().GetBunny(); got != "" { - t.Errorf("m.GetNested().GetBunny() = %q, want empty string", got) - } - if got := m.GetNested().GetCute(); got { - t.Errorf("m.GetNested().GetCute() = %t, want false", got) - } -} - -func TestProto3SetDefaults(t *testing.T) { - in := &pb.Message{ - Terrain: map[string]*pb.Nested{ - "meadow": new(pb.Nested), - }, - Proto2Field: new(tpb.SubDefaults), - Proto2Value: map[string]*tpb.SubDefaults{ - "badlands": new(tpb.SubDefaults), - }, - } - - got := proto.Clone(in).(*pb.Message) - proto.SetDefaults(got) - - // There are no defaults in proto3. Everything should be the zero value, but - // we need to remember to set defaults for nested proto2 messages. - want := &pb.Message{ - Terrain: map[string]*pb.Nested{ - "meadow": new(pb.Nested), - }, - Proto2Field: &tpb.SubDefaults{N: proto.Int64(7)}, - Proto2Value: map[string]*tpb.SubDefaults{ - "badlands": {N: proto.Int64(7)}, - }, - } - - if !proto.Equal(got, want) { - t.Errorf("with in = %v\nproto.SetDefaults(in) =>\ngot %v\nwant %v", in, got, want) - } -} diff --git a/vendor/github.com/gogo/protobuf/proto/size2_test.go b/vendor/github.com/gogo/protobuf/proto/size2_test.go deleted file mode 100644 index a2729c39a..000000000 --- a/vendor/github.com/gogo/protobuf/proto/size2_test.go +++ /dev/null @@ -1,63 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2012 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -import ( - "testing" -) - -// This is a separate file and package from size_test.go because that one uses -// generated messages and thus may not be in package proto without having a circular -// dependency, whereas this file tests unexported details of size.go. - -func TestVarintSize(t *testing.T) { - // Check the edge cases carefully. - testCases := []struct { - n uint64 - size int - }{ - {0, 1}, - {1, 1}, - {127, 1}, - {128, 2}, - {16383, 2}, - {16384, 3}, - {1<<63 - 1, 9}, - {1 << 63, 10}, - } - for _, tc := range testCases { - size := sizeVarint(tc.n) - if size != tc.size { - t.Errorf("sizeVarint(%d) = %d, want %d", tc.n, size, tc.size) - } - } -} diff --git a/vendor/github.com/gogo/protobuf/proto/size_test.go b/vendor/github.com/gogo/protobuf/proto/size_test.go deleted file mode 100644 index 0a6c1772b..000000000 --- a/vendor/github.com/gogo/protobuf/proto/size_test.go +++ /dev/null @@ -1,164 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2012 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto_test - -import ( - "log" - "strings" - "testing" - - . "github.com/gogo/protobuf/proto" - proto3pb "github.com/gogo/protobuf/proto/proto3_proto" - pb "github.com/gogo/protobuf/proto/testdata" -) - -var messageWithExtension1 = &pb.MyMessage{Count: Int32(7)} - -// messageWithExtension2 is in equal_test.go. -var messageWithExtension3 = &pb.MyMessage{Count: Int32(8)} - -func init() { - if err := SetExtension(messageWithExtension1, pb.E_Ext_More, &pb.Ext{Data: String("Abbott")}); err != nil { - log.Panicf("SetExtension: %v", err) - } - if err := SetExtension(messageWithExtension3, pb.E_Ext_More, &pb.Ext{Data: String("Costello")}); err != nil { - log.Panicf("SetExtension: %v", err) - } - - // Force messageWithExtension3 to have the extension encoded. - Marshal(messageWithExtension3) - -} - -var SizeTests = []struct { - desc string - pb Message -}{ - {"empty", &pb.OtherMessage{}}, - // Basic types. - {"bool", &pb.Defaults{F_Bool: Bool(true)}}, - {"int32", &pb.Defaults{F_Int32: Int32(12)}}, - {"negative int32", &pb.Defaults{F_Int32: Int32(-1)}}, - {"small int64", &pb.Defaults{F_Int64: Int64(1)}}, - {"big int64", &pb.Defaults{F_Int64: Int64(1 << 20)}}, - {"negative int64", &pb.Defaults{F_Int64: Int64(-1)}}, - {"fixed32", &pb.Defaults{F_Fixed32: Uint32(71)}}, - {"fixed64", &pb.Defaults{F_Fixed64: Uint64(72)}}, - {"uint32", &pb.Defaults{F_Uint32: Uint32(123)}}, - {"uint64", &pb.Defaults{F_Uint64: Uint64(124)}}, - {"float", &pb.Defaults{F_Float: Float32(12.6)}}, - {"double", &pb.Defaults{F_Double: Float64(13.9)}}, - {"string", &pb.Defaults{F_String: String("niles")}}, - {"bytes", &pb.Defaults{F_Bytes: []byte("wowsa")}}, - {"bytes, empty", &pb.Defaults{F_Bytes: []byte{}}}, - {"sint32", &pb.Defaults{F_Sint32: Int32(65)}}, - {"sint64", &pb.Defaults{F_Sint64: Int64(67)}}, - {"enum", &pb.Defaults{F_Enum: pb.Defaults_BLUE.Enum()}}, - // Repeated. - {"empty repeated bool", &pb.MoreRepeated{Bools: []bool{}}}, - {"repeated bool", &pb.MoreRepeated{Bools: []bool{false, true, true, false}}}, - {"packed repeated bool", &pb.MoreRepeated{BoolsPacked: []bool{false, true, true, false, true, true, true}}}, - {"repeated int32", &pb.MoreRepeated{Ints: []int32{1, 12203, 1729, -1}}}, - {"repeated int32 packed", &pb.MoreRepeated{IntsPacked: []int32{1, 12203, 1729}}}, - {"repeated int64 packed", &pb.MoreRepeated{Int64SPacked: []int64{ - // Need enough large numbers to verify that the header is counting the number of bytes - // for the field, not the number of elements. - 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, - 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, - }}}, - {"repeated string", &pb.MoreRepeated{Strings: []string{"r", "ken", "gri"}}}, - {"repeated fixed", &pb.MoreRepeated{Fixeds: []uint32{1, 2, 3, 4}}}, - // Nested. - {"nested", &pb.OldMessage{Nested: &pb.OldMessage_Nested{Name: String("whatever")}}}, - {"group", &pb.GroupOld{G: &pb.GroupOld_G{X: Int32(12345)}}}, - // Other things. - {"unrecognized", &pb.MoreRepeated{XXX_unrecognized: []byte{13<<3 | 0, 4}}}, - {"extension (unencoded)", messageWithExtension1}, - {"extension (encoded)", messageWithExtension3}, - // proto3 message - {"proto3 empty", &proto3pb.Message{}}, - {"proto3 bool", &proto3pb.Message{TrueScotsman: true}}, - {"proto3 int64", &proto3pb.Message{ResultCount: 1}}, - {"proto3 uint32", &proto3pb.Message{HeightInCm: 123}}, - {"proto3 float", &proto3pb.Message{Score: 12.6}}, - {"proto3 string", &proto3pb.Message{Name: "Snezana"}}, - {"proto3 bytes", &proto3pb.Message{Data: []byte("wowsa")}}, - {"proto3 bytes, empty", &proto3pb.Message{Data: []byte{}}}, - {"proto3 enum", &proto3pb.Message{Hilarity: proto3pb.Message_PUNS}}, - {"proto3 map field with empty bytes", &proto3pb.MessageWithMap{ByteMapping: map[bool][]byte{false: {}}}}, - - {"map field", &pb.MessageWithMap{NameMapping: map[int32]string{1: "Rob", 7: "Andrew"}}}, - {"map field with message", &pb.MessageWithMap{MsgMapping: map[int64]*pb.FloatingPoint{0x7001: {F: Float64(2.0)}}}}, - {"map field with bytes", &pb.MessageWithMap{ByteMapping: map[bool][]byte{true: []byte("this time for sure")}}}, - {"map field with empty bytes", &pb.MessageWithMap{ByteMapping: map[bool][]byte{true: {}}}}, - - {"map field with big entry", &pb.MessageWithMap{NameMapping: map[int32]string{8: strings.Repeat("x", 125)}}}, - {"map field with big key and val", &pb.MessageWithMap{StrToStr: map[string]string{strings.Repeat("x", 70): strings.Repeat("y", 70)}}}, - {"map field with big numeric key", &pb.MessageWithMap{NameMapping: map[int32]string{0xf00d: "om nom nom"}}}, - - {"oneof not set", &pb.Oneof{}}, - {"oneof bool", &pb.Oneof{Union: &pb.Oneof_F_Bool{F_Bool: true}}}, - {"oneof zero int32", &pb.Oneof{Union: &pb.Oneof_F_Int32{F_Int32: 0}}}, - {"oneof big int32", &pb.Oneof{Union: &pb.Oneof_F_Int32{F_Int32: 1 << 20}}}, - {"oneof int64", &pb.Oneof{Union: &pb.Oneof_F_Int64{F_Int64: 42}}}, - {"oneof fixed32", &pb.Oneof{Union: &pb.Oneof_F_Fixed32{F_Fixed32: 43}}}, - {"oneof fixed64", &pb.Oneof{Union: &pb.Oneof_F_Fixed64{F_Fixed64: 44}}}, - {"oneof uint32", &pb.Oneof{Union: &pb.Oneof_F_Uint32{F_Uint32: 45}}}, - {"oneof uint64", &pb.Oneof{Union: &pb.Oneof_F_Uint64{F_Uint64: 46}}}, - {"oneof float", &pb.Oneof{Union: &pb.Oneof_F_Float{F_Float: 47.1}}}, - {"oneof double", &pb.Oneof{Union: &pb.Oneof_F_Double{F_Double: 48.9}}}, - {"oneof string", &pb.Oneof{Union: &pb.Oneof_F_String{F_String: "Rhythmic Fman"}}}, - {"oneof bytes", &pb.Oneof{Union: &pb.Oneof_F_Bytes{F_Bytes: []byte("let go")}}}, - {"oneof sint32", &pb.Oneof{Union: &pb.Oneof_F_Sint32{F_Sint32: 50}}}, - {"oneof sint64", &pb.Oneof{Union: &pb.Oneof_F_Sint64{F_Sint64: 51}}}, - {"oneof enum", &pb.Oneof{Union: &pb.Oneof_F_Enum{F_Enum: pb.MyMessage_BLUE}}}, - {"message for oneof", &pb.GoTestField{Label: String("k"), Type: String("v")}}, - {"oneof message", &pb.Oneof{Union: &pb.Oneof_F_Message{F_Message: &pb.GoTestField{Label: String("k"), Type: String("v")}}}}, - {"oneof group", &pb.Oneof{Union: &pb.Oneof_FGroup{FGroup: &pb.Oneof_F_Group{X: Int32(52)}}}}, - {"oneof largest tag", &pb.Oneof{Union: &pb.Oneof_F_Largest_Tag{F_Largest_Tag: 1}}}, - {"multiple oneofs", &pb.Oneof{Union: &pb.Oneof_F_Int32{F_Int32: 1}, Tormato: &pb.Oneof_Value{Value: 2}}}, -} - -func TestSize(t *testing.T) { - for _, tc := range SizeTests { - size := Size(tc.pb) - b, err := Marshal(tc.pb) - if err != nil { - t.Errorf("%v: Marshal failed: %v", tc.desc, err) - continue - } - if size != len(b) { - t.Errorf("%v: Size(%v) = %d, want %d", tc.desc, tc.pb, size, len(b)) - t.Logf("%v: bytes: %#v", tc.desc, b) - } - } -} diff --git a/vendor/github.com/gogo/protobuf/proto/text_parser_test.go b/vendor/github.com/gogo/protobuf/proto/text_parser_test.go deleted file mode 100644 index 9a3a447ce..000000000 --- a/vendor/github.com/gogo/protobuf/proto/text_parser_test.go +++ /dev/null @@ -1,673 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto_test - -import ( - "math" - "reflect" - "testing" - - . "github.com/gogo/protobuf/proto" - proto3pb "github.com/gogo/protobuf/proto/proto3_proto" - . "github.com/gogo/protobuf/proto/testdata" -) - -type UnmarshalTextTest struct { - in string - err string // if "", no error expected - out *MyMessage -} - -func buildExtStructTest(text string) UnmarshalTextTest { - msg := &MyMessage{ - Count: Int32(42), - } - SetExtension(msg, E_Ext_More, &Ext{ - Data: String("Hello, world!"), - }) - return UnmarshalTextTest{in: text, out: msg} -} - -func buildExtDataTest(text string) UnmarshalTextTest { - msg := &MyMessage{ - Count: Int32(42), - } - SetExtension(msg, E_Ext_Text, String("Hello, world!")) - SetExtension(msg, E_Ext_Number, Int32(1729)) - return UnmarshalTextTest{in: text, out: msg} -} - -func buildExtRepStringTest(text string) UnmarshalTextTest { - msg := &MyMessage{ - Count: Int32(42), - } - if err := SetExtension(msg, E_Greeting, []string{"bula", "hola"}); err != nil { - panic(err) - } - return UnmarshalTextTest{in: text, out: msg} -} - -var unMarshalTextTests = []UnmarshalTextTest{ - // Basic - { - in: " count:42\n name:\"Dave\" ", - out: &MyMessage{ - Count: Int32(42), - Name: String("Dave"), - }, - }, - - // Empty quoted string - { - in: `count:42 name:""`, - out: &MyMessage{ - Count: Int32(42), - Name: String(""), - }, - }, - - // Quoted string concatenation with double quotes - { - in: `count:42 name: "My name is "` + "\n" + `"elsewhere"`, - out: &MyMessage{ - Count: Int32(42), - Name: String("My name is elsewhere"), - }, - }, - - // Quoted string concatenation with single quotes - { - in: "count:42 name: 'My name is '\n'elsewhere'", - out: &MyMessage{ - Count: Int32(42), - Name: String("My name is elsewhere"), - }, - }, - - // Quoted string concatenations with mixed quotes - { - in: "count:42 name: 'My name is '\n\"elsewhere\"", - out: &MyMessage{ - Count: Int32(42), - Name: String("My name is elsewhere"), - }, - }, - { - in: "count:42 name: \"My name is \"\n'elsewhere'", - out: &MyMessage{ - Count: Int32(42), - Name: String("My name is elsewhere"), - }, - }, - - // Quoted string with escaped apostrophe - { - in: `count:42 name: "HOLIDAY - New Year\'s Day"`, - out: &MyMessage{ - Count: Int32(42), - Name: String("HOLIDAY - New Year's Day"), - }, - }, - - // Quoted string with single quote - { - in: `count:42 name: 'Roger "The Ramster" Ramjet'`, - out: &MyMessage{ - Count: Int32(42), - Name: String(`Roger "The Ramster" Ramjet`), - }, - }, - - // Quoted string with all the accepted special characters from the C++ test - { - in: `count:42 name: ` + "\"\\\"A string with \\' characters \\n and \\r newlines and \\t tabs and \\001 slashes \\\\ and multiple spaces\"", - out: &MyMessage{ - Count: Int32(42), - Name: String("\"A string with ' characters \n and \r newlines and \t tabs and \001 slashes \\ and multiple spaces"), - }, - }, - - // Quoted string with quoted backslash - { - in: `count:42 name: "\\'xyz"`, - out: &MyMessage{ - Count: Int32(42), - Name: String(`\'xyz`), - }, - }, - - // Quoted string with UTF-8 bytes. - { - in: "count:42 name: '\303\277\302\201\xAB'", - out: &MyMessage{ - Count: Int32(42), - Name: String("\303\277\302\201\xAB"), - }, - }, - - // Bad quoted string - { - in: `inner: < host: "\0" >` + "\n", - err: `line 1.15: invalid quoted string "\0": \0 requires 2 following digits`, - }, - - // Number too large for int64 - { - in: "count: 1 others { key: 123456789012345678901 }", - err: "line 1.23: invalid int64: 123456789012345678901", - }, - - // Number too large for int32 - { - in: "count: 1234567890123", - err: "line 1.7: invalid int32: 1234567890123", - }, - - // Number in hexadecimal - { - in: "count: 0x2beef", - out: &MyMessage{ - Count: Int32(0x2beef), - }, - }, - - // Number in octal - { - in: "count: 024601", - out: &MyMessage{ - Count: Int32(024601), - }, - }, - - // Floating point number with "f" suffix - { - in: "count: 4 others:< weight: 17.0f >", - out: &MyMessage{ - Count: Int32(4), - Others: []*OtherMessage{ - { - Weight: Float32(17), - }, - }, - }, - }, - - // Floating point positive infinity - { - in: "count: 4 bigfloat: inf", - out: &MyMessage{ - Count: Int32(4), - Bigfloat: Float64(math.Inf(1)), - }, - }, - - // Floating point negative infinity - { - in: "count: 4 bigfloat: -inf", - out: &MyMessage{ - Count: Int32(4), - Bigfloat: Float64(math.Inf(-1)), - }, - }, - - // Number too large for float32 - { - in: "others:< weight: 12345678901234567890123456789012345678901234567890 >", - err: "line 1.17: invalid float32: 12345678901234567890123456789012345678901234567890", - }, - - // Number posing as a quoted string - { - in: `inner: < host: 12 >` + "\n", - err: `line 1.15: invalid string: 12`, - }, - - // Quoted string posing as int32 - { - in: `count: "12"`, - err: `line 1.7: invalid int32: "12"`, - }, - - // Quoted string posing a float32 - { - in: `others:< weight: "17.4" >`, - err: `line 1.17: invalid float32: "17.4"`, - }, - - // Enum - { - in: `count:42 bikeshed: BLUE`, - out: &MyMessage{ - Count: Int32(42), - Bikeshed: MyMessage_BLUE.Enum(), - }, - }, - - // Repeated field - { - in: `count:42 pet: "horsey" pet:"bunny"`, - out: &MyMessage{ - Count: Int32(42), - Pet: []string{"horsey", "bunny"}, - }, - }, - - // Repeated field with list notation - { - in: `count:42 pet: ["horsey", "bunny"]`, - out: &MyMessage{ - Count: Int32(42), - Pet: []string{"horsey", "bunny"}, - }, - }, - - // Repeated message with/without colon and <>/{} - { - in: `count:42 others:{} others{} others:<> others:{}`, - out: &MyMessage{ - Count: Int32(42), - Others: []*OtherMessage{ - {}, - {}, - {}, - {}, - }, - }, - }, - - // Missing colon for inner message - { - in: `count:42 inner < host: "cauchy.syd" >`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("cauchy.syd"), - }, - }, - }, - - // Missing colon for string field - { - in: `name "Dave"`, - err: `line 1.5: expected ':', found "\"Dave\""`, - }, - - // Missing colon for int32 field - { - in: `count 42`, - err: `line 1.6: expected ':', found "42"`, - }, - - // Missing required field - { - in: `name: "Pawel"`, - err: `proto: required field "testdata.MyMessage.count" not set`, - out: &MyMessage{ - Name: String("Pawel"), - }, - }, - - // Missing required field in a required submessage - { - in: `count: 42 we_must_go_deeper < leo_finally_won_an_oscar <> >`, - err: `proto: required field "testdata.InnerMessage.host" not set`, - out: &MyMessage{ - Count: Int32(42), - WeMustGoDeeper: &RequiredInnerMessage{LeoFinallyWonAnOscar: &InnerMessage{}}, - }, - }, - - // Repeated non-repeated field - { - in: `name: "Rob" name: "Russ"`, - err: `line 1.12: non-repeated field "name" was repeated`, - }, - - // Group - { - in: `count: 17 SomeGroup { group_field: 12 }`, - out: &MyMessage{ - Count: Int32(17), - Somegroup: &MyMessage_SomeGroup{ - GroupField: Int32(12), - }, - }, - }, - - // Semicolon between fields - { - in: `count:3;name:"Calvin"`, - out: &MyMessage{ - Count: Int32(3), - Name: String("Calvin"), - }, - }, - // Comma between fields - { - in: `count:4,name:"Ezekiel"`, - out: &MyMessage{ - Count: Int32(4), - Name: String("Ezekiel"), - }, - }, - - // Boolean false - { - in: `count:42 inner { host: "example.com" connected: false }`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("example.com"), - Connected: Bool(false), - }, - }, - }, - // Boolean true - { - in: `count:42 inner { host: "example.com" connected: true }`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("example.com"), - Connected: Bool(true), - }, - }, - }, - // Boolean 0 - { - in: `count:42 inner { host: "example.com" connected: 0 }`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("example.com"), - Connected: Bool(false), - }, - }, - }, - // Boolean 1 - { - in: `count:42 inner { host: "example.com" connected: 1 }`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("example.com"), - Connected: Bool(true), - }, - }, - }, - // Boolean f - { - in: `count:42 inner { host: "example.com" connected: f }`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("example.com"), - Connected: Bool(false), - }, - }, - }, - // Boolean t - { - in: `count:42 inner { host: "example.com" connected: t }`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("example.com"), - Connected: Bool(true), - }, - }, - }, - // Boolean False - { - in: `count:42 inner { host: "example.com" connected: False }`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("example.com"), - Connected: Bool(false), - }, - }, - }, - // Boolean True - { - in: `count:42 inner { host: "example.com" connected: True }`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("example.com"), - Connected: Bool(true), - }, - }, - }, - - // Extension - buildExtStructTest(`count: 42 [testdata.Ext.more]:`), - buildExtStructTest(`count: 42 [testdata.Ext.more] {data:"Hello, world!"}`), - buildExtDataTest(`count: 42 [testdata.Ext.text]:"Hello, world!" [testdata.Ext.number]:1729`), - buildExtRepStringTest(`count: 42 [testdata.greeting]:"bula" [testdata.greeting]:"hola"`), - - // Big all-in-one - { - in: "count:42 # Meaning\n" + - `name:"Dave" ` + - `quote:"\"I didn't want to go.\"" ` + - `pet:"bunny" ` + - `pet:"kitty" ` + - `pet:"horsey" ` + - `inner:<` + - ` host:"footrest.syd" ` + - ` port:7001 ` + - ` connected:true ` + - `> ` + - `others:<` + - ` key:3735928559 ` + - ` value:"\x01A\a\f" ` + - `> ` + - `others:<` + - " weight:58.9 # Atomic weight of Co\n" + - ` inner:<` + - ` host:"lesha.mtv" ` + - ` port:8002 ` + - ` >` + - `>`, - out: &MyMessage{ - Count: Int32(42), - Name: String("Dave"), - Quote: String(`"I didn't want to go."`), - Pet: []string{"bunny", "kitty", "horsey"}, - Inner: &InnerMessage{ - Host: String("footrest.syd"), - Port: Int32(7001), - Connected: Bool(true), - }, - Others: []*OtherMessage{ - { - Key: Int64(3735928559), - Value: []byte{0x1, 'A', '\a', '\f'}, - }, - { - Weight: Float32(58.9), - Inner: &InnerMessage{ - Host: String("lesha.mtv"), - Port: Int32(8002), - }, - }, - }, - }, - }, -} - -func TestUnmarshalText(t *testing.T) { - for i, test := range unMarshalTextTests { - pb := new(MyMessage) - err := UnmarshalText(test.in, pb) - if test.err == "" { - // We don't expect failure. - if err != nil { - t.Errorf("Test %d: Unexpected error: %v", i, err) - } else if !reflect.DeepEqual(pb, test.out) { - t.Errorf("Test %d: Incorrect populated \nHave: %v\nWant: %v", - i, pb, test.out) - } - } else { - // We do expect failure. - if err == nil { - t.Errorf("Test %d: Didn't get expected error: %v", i, test.err) - } else if err.Error() != test.err { - t.Errorf("Test %d: Incorrect error.\nHave: %v\nWant: %v", - i, err.Error(), test.err) - } else if _, ok := err.(*RequiredNotSetError); ok && test.out != nil && !reflect.DeepEqual(pb, test.out) { - t.Errorf("Test %d: Incorrect populated \nHave: %v\nWant: %v", - i, pb, test.out) - } - } - } -} - -func TestUnmarshalTextCustomMessage(t *testing.T) { - msg := &textMessage{} - if err := UnmarshalText("custom", msg); err != nil { - t.Errorf("Unexpected error from custom unmarshal: %v", err) - } - if UnmarshalText("not custom", msg) == nil { - t.Errorf("Didn't get expected error from custom unmarshal") - } -} - -// Regression test; this caused a panic. -func TestRepeatedEnum(t *testing.T) { - pb := new(RepeatedEnum) - if err := UnmarshalText("color: RED", pb); err != nil { - t.Fatal(err) - } - exp := &RepeatedEnum{ - Color: []RepeatedEnum_Color{RepeatedEnum_RED}, - } - if !Equal(pb, exp) { - t.Errorf("Incorrect populated \nHave: %v\nWant: %v", pb, exp) - } -} - -func TestProto3TextParsing(t *testing.T) { - m := new(proto3pb.Message) - const in = `name: "Wallace" true_scotsman: true` - want := &proto3pb.Message{ - Name: "Wallace", - TrueScotsman: true, - } - if err := UnmarshalText(in, m); err != nil { - t.Fatal(err) - } - if !Equal(m, want) { - t.Errorf("\n got %v\nwant %v", m, want) - } -} - -func TestMapParsing(t *testing.T) { - m := new(MessageWithMap) - const in = `name_mapping: name_mapping:` + - `msg_mapping:,>` + // separating commas are okay - `msg_mapping>` + // no colon after "value" - `msg_mapping:>` + // omitted key - `msg_mapping:` + // omitted value - `byte_mapping:` + - `byte_mapping:<>` // omitted key and value - want := &MessageWithMap{ - NameMapping: map[int32]string{ - 1: "Beatles", - 1234: "Feist", - }, - MsgMapping: map[int64]*FloatingPoint{ - -4: {F: Float64(2.0)}, - -2: {F: Float64(4.0)}, - 0: {F: Float64(5.0)}, - 1: nil, - }, - ByteMapping: map[bool][]byte{ - false: nil, - true: []byte("so be it"), - }, - } - if err := UnmarshalText(in, m); err != nil { - t.Fatal(err) - } - if !Equal(m, want) { - t.Errorf("\n got %v\nwant %v", m, want) - } -} - -func TestOneofParsing(t *testing.T) { - const in = `name:"Shrek"` - m := new(Communique) - want := &Communique{Union: &Communique_Name{Name: "Shrek"}} - if err := UnmarshalText(in, m); err != nil { - t.Fatal(err) - } - if !Equal(m, want) { - t.Errorf("\n got %v\nwant %v", m, want) - } - - const inOverwrite = `name:"Shrek" number:42` - m = new(Communique) - testErr := "line 1.13: field 'number' would overwrite already parsed oneof 'Union'" - if err := UnmarshalText(inOverwrite, m); err == nil { - t.Errorf("TestOneofParsing: Didn't get expected error: %v", testErr) - } else if err.Error() != testErr { - t.Errorf("TestOneofParsing: Incorrect error.\nHave: %v\nWant: %v", - err.Error(), testErr) - } - -} - -var benchInput string - -func init() { - benchInput = "count: 4\n" - for i := 0; i < 1000; i++ { - benchInput += "pet: \"fido\"\n" - } - - // Check it is valid input. - pb := new(MyMessage) - err := UnmarshalText(benchInput, pb) - if err != nil { - panic("Bad benchmark input: " + err.Error()) - } -} - -func BenchmarkUnmarshalText(b *testing.B) { - pb := new(MyMessage) - for i := 0; i < b.N; i++ { - UnmarshalText(benchInput, pb) - } - b.SetBytes(int64(len(benchInput))) -} diff --git a/vendor/github.com/gogo/protobuf/proto/text_test.go b/vendor/github.com/gogo/protobuf/proto/text_test.go deleted file mode 100644 index 27df6cb9b..000000000 --- a/vendor/github.com/gogo/protobuf/proto/text_test.go +++ /dev/null @@ -1,474 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto_test - -import ( - "bytes" - "errors" - "io/ioutil" - "math" - "strings" - "testing" - - "github.com/gogo/protobuf/proto" - - proto3pb "github.com/gogo/protobuf/proto/proto3_proto" - pb "github.com/gogo/protobuf/proto/testdata" -) - -// textMessage implements the methods that allow it to marshal and unmarshal -// itself as text. -type textMessage struct { -} - -func (*textMessage) MarshalText() ([]byte, error) { - return []byte("custom"), nil -} - -func (*textMessage) UnmarshalText(bytes []byte) error { - if string(bytes) != "custom" { - return errors.New("expected 'custom'") - } - return nil -} - -func (*textMessage) Reset() {} -func (*textMessage) String() string { return "" } -func (*textMessage) ProtoMessage() {} - -func newTestMessage() *pb.MyMessage { - msg := &pb.MyMessage{ - Count: proto.Int32(42), - Name: proto.String("Dave"), - Quote: proto.String(`"I didn't want to go."`), - Pet: []string{"bunny", "kitty", "horsey"}, - Inner: &pb.InnerMessage{ - Host: proto.String("footrest.syd"), - Port: proto.Int32(7001), - Connected: proto.Bool(true), - }, - Others: []*pb.OtherMessage{ - { - Key: proto.Int64(0xdeadbeef), - Value: []byte{1, 65, 7, 12}, - }, - { - Weight: proto.Float32(6.022), - Inner: &pb.InnerMessage{ - Host: proto.String("lesha.mtv"), - Port: proto.Int32(8002), - }, - }, - }, - Bikeshed: pb.MyMessage_BLUE.Enum(), - Somegroup: &pb.MyMessage_SomeGroup{ - GroupField: proto.Int32(8), - }, - // One normally wouldn't do this. - // This is an undeclared tag 13, as a varint (wire type 0) with value 4. - XXX_unrecognized: []byte{13<<3 | 0, 4}, - } - ext := &pb.Ext{ - Data: proto.String("Big gobs for big rats"), - } - if err := proto.SetExtension(msg, pb.E_Ext_More, ext); err != nil { - panic(err) - } - greetings := []string{"adg", "easy", "cow"} - if err := proto.SetExtension(msg, pb.E_Greeting, greetings); err != nil { - panic(err) - } - - // Add an unknown extension. We marshal a pb.Ext, and fake the ID. - b, err := proto.Marshal(&pb.Ext{Data: proto.String("3G skiing")}) - if err != nil { - panic(err) - } - b = append(proto.EncodeVarint(201<<3|proto.WireBytes), b...) - proto.SetRawExtension(msg, 201, b) - - // Extensions can be plain fields, too, so let's test that. - b = append(proto.EncodeVarint(202<<3|proto.WireVarint), 19) - proto.SetRawExtension(msg, 202, b) - - return msg -} - -const text = `count: 42 -name: "Dave" -quote: "\"I didn't want to go.\"" -pet: "bunny" -pet: "kitty" -pet: "horsey" -inner: < - host: "footrest.syd" - port: 7001 - connected: true -> -others: < - key: 3735928559 - value: "\001A\007\014" -> -others: < - weight: 6.022 - inner: < - host: "lesha.mtv" - port: 8002 - > -> -bikeshed: BLUE -SomeGroup { - group_field: 8 -} -/* 2 unknown bytes */ -13: 4 -[testdata.Ext.more]: < - data: "Big gobs for big rats" -> -[testdata.greeting]: "adg" -[testdata.greeting]: "easy" -[testdata.greeting]: "cow" -/* 13 unknown bytes */ -201: "\t3G skiing" -/* 3 unknown bytes */ -202: 19 -` - -func TestMarshalText(t *testing.T) { - buf := new(bytes.Buffer) - if err := proto.MarshalText(buf, newTestMessage()); err != nil { - t.Fatalf("proto.MarshalText: %v", err) - } - s := buf.String() - if s != text { - t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v===\n", s, text) - } -} - -func TestMarshalTextCustomMessage(t *testing.T) { - buf := new(bytes.Buffer) - if err := proto.MarshalText(buf, &textMessage{}); err != nil { - t.Fatalf("proto.MarshalText: %v", err) - } - s := buf.String() - if s != "custom" { - t.Errorf("Got %q, expected %q", s, "custom") - } -} -func TestMarshalTextNil(t *testing.T) { - want := "" - tests := []proto.Message{nil, (*pb.MyMessage)(nil)} - for i, test := range tests { - buf := new(bytes.Buffer) - if err := proto.MarshalText(buf, test); err != nil { - t.Fatal(err) - } - if got := buf.String(); got != want { - t.Errorf("%d: got %q want %q", i, got, want) - } - } -} - -func TestMarshalTextUnknownEnum(t *testing.T) { - // The Color enum only specifies values 0-2. - m := &pb.MyMessage{Bikeshed: pb.MyMessage_Color(3).Enum()} - got := m.String() - const want = `bikeshed:3 ` - if got != want { - t.Errorf("\n got %q\nwant %q", got, want) - } -} - -func TestTextOneof(t *testing.T) { - tests := []struct { - m proto.Message - want string - }{ - // zero message - {&pb.Communique{}, ``}, - // scalar field - {&pb.Communique{Union: &pb.Communique_Number{Number: 4}}, `number:4`}, - // message field - {&pb.Communique{Union: &pb.Communique_Msg{ - Msg: &pb.Strings{StringField: proto.String("why hello!")}, - }}, `msg:`}, - // bad oneof (should not panic) - {&pb.Communique{Union: &pb.Communique_Msg{Msg: nil}}, `msg:/* nil */`}, - } - for _, test := range tests { - got := strings.TrimSpace(test.m.String()) - if got != test.want { - t.Errorf("\n got %s\nwant %s", got, test.want) - } - } -} - -func BenchmarkMarshalTextBuffered(b *testing.B) { - buf := new(bytes.Buffer) - m := newTestMessage() - for i := 0; i < b.N; i++ { - buf.Reset() - proto.MarshalText(buf, m) - } -} - -func BenchmarkMarshalTextUnbuffered(b *testing.B) { - w := ioutil.Discard - m := newTestMessage() - for i := 0; i < b.N; i++ { - proto.MarshalText(w, m) - } -} - -func compact(src string) string { - // s/[ \n]+/ /g; s/ $//; - dst := make([]byte, len(src)) - space, comment := false, false - j := 0 - for i := 0; i < len(src); i++ { - if strings.HasPrefix(src[i:], "/*") { - comment = true - i++ - continue - } - if comment && strings.HasPrefix(src[i:], "*/") { - comment = false - i++ - continue - } - if comment { - continue - } - c := src[i] - if c == ' ' || c == '\n' { - space = true - continue - } - if j > 0 && (dst[j-1] == ':' || dst[j-1] == '<' || dst[j-1] == '{') { - space = false - } - if c == '{' { - space = false - } - if space { - dst[j] = ' ' - j++ - space = false - } - dst[j] = c - j++ - } - if space { - dst[j] = ' ' - j++ - } - return string(dst[0:j]) -} - -var compactText = compact(text) - -func TestCompactText(t *testing.T) { - s := proto.CompactTextString(newTestMessage()) - if s != compactText { - t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v\n===\n", s, compactText) - } -} - -func TestStringEscaping(t *testing.T) { - testCases := []struct { - in *pb.Strings - out string - }{ - { - // Test data from C++ test (TextFormatTest.StringEscape). - // Single divergence: we don't escape apostrophes. - &pb.Strings{StringField: proto.String("\"A string with ' characters \n and \r newlines and \t tabs and \001 slashes \\ and multiple spaces")}, - "string_field: \"\\\"A string with ' characters \\n and \\r newlines and \\t tabs and \\001 slashes \\\\ and multiple spaces\"\n", - }, - { - // Test data from the same C++ test. - &pb.Strings{StringField: proto.String("\350\260\267\346\255\214")}, - "string_field: \"\\350\\260\\267\\346\\255\\214\"\n", - }, - { - // Some UTF-8. - &pb.Strings{StringField: proto.String("\x00\x01\xff\x81")}, - `string_field: "\000\001\377\201"` + "\n", - }, - } - - for i, tc := range testCases { - var buf bytes.Buffer - if err := proto.MarshalText(&buf, tc.in); err != nil { - t.Errorf("proto.MarsalText: %v", err) - continue - } - s := buf.String() - if s != tc.out { - t.Errorf("#%d: Got:\n%s\nExpected:\n%s\n", i, s, tc.out) - continue - } - - // Check round-trip. - pbStrings := new(pb.Strings) - if err := proto.UnmarshalText(s, pbStrings); err != nil { - t.Errorf("#%d: UnmarshalText: %v", i, err) - continue - } - if !proto.Equal(pbStrings, tc.in) { - t.Errorf("#%d: Round-trip failed:\nstart: %v\n end: %v", i, tc.in, pbStrings) - } - } -} - -// A limitedWriter accepts some output before it fails. -// This is a proxy for something like a nearly-full or imminently-failing disk, -// or a network connection that is about to die. -type limitedWriter struct { - b bytes.Buffer - limit int -} - -var outOfSpace = errors.New("proto: insufficient space") - -func (w *limitedWriter) Write(p []byte) (n int, err error) { - var avail = w.limit - w.b.Len() - if avail <= 0 { - return 0, outOfSpace - } - if len(p) <= avail { - return w.b.Write(p) - } - n, _ = w.b.Write(p[:avail]) - return n, outOfSpace -} - -func TestMarshalTextFailing(t *testing.T) { - // Try lots of different sizes to exercise more error code-paths. - for lim := 0; lim < len(text); lim++ { - buf := new(limitedWriter) - buf.limit = lim - err := proto.MarshalText(buf, newTestMessage()) - // We expect a certain error, but also some partial results in the buffer. - if err != outOfSpace { - t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v===\n", err, outOfSpace) - } - s := buf.b.String() - x := text[:buf.limit] - if s != x { - t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v===\n", s, x) - } - } -} - -func TestFloats(t *testing.T) { - tests := []struct { - f float64 - want string - }{ - {0, "0"}, - {4.7, "4.7"}, - {math.Inf(1), "inf"}, - {math.Inf(-1), "-inf"}, - {math.NaN(), "nan"}, - } - for _, test := range tests { - msg := &pb.FloatingPoint{F: &test.f} - got := strings.TrimSpace(msg.String()) - want := `f:` + test.want - if got != want { - t.Errorf("f=%f: got %q, want %q", test.f, got, want) - } - } -} - -func TestRepeatedNilText(t *testing.T) { - m := &pb.MessageList{ - Message: []*pb.MessageList_Message{ - nil, - { - Name: proto.String("Horse"), - }, - nil, - }, - } - want := `Message -Message { - name: "Horse" -} -Message -` - if s := proto.MarshalTextString(m); s != want { - t.Errorf(" got: %s\nwant: %s", s, want) - } -} - -func TestProto3Text(t *testing.T) { - tests := []struct { - m proto.Message - want string - }{ - // zero message - {&proto3pb.Message{}, ``}, - // zero message except for an empty byte slice - {&proto3pb.Message{Data: []byte{}}, ``}, - // trivial case - {&proto3pb.Message{Name: "Rob", HeightInCm: 175}, `name:"Rob" height_in_cm:175`}, - // empty map - {&pb.MessageWithMap{}, ``}, - // non-empty map; map format is the same as a repeated struct, - // and they are sorted by key (numerically for numeric keys). - { - &pb.MessageWithMap{NameMapping: map[int32]string{ - -1: "Negatory", - 7: "Lucky", - 1234: "Feist", - 6345789: "Otis", - }}, - `name_mapping: ` + - `name_mapping: ` + - `name_mapping: ` + - `name_mapping:`, - }, - // map with nil value; not well-defined, but we shouldn't crash - { - &pb.MessageWithMap{MsgMapping: map[int64]*pb.FloatingPoint{7: nil}}, - `msg_mapping:`, - }, - } - for _, test := range tests { - got := strings.TrimSpace(test.m.String()) - if got != test.want { - t.Errorf("\n got %s\nwant %s", got, test.want) - } - } -} diff --git a/vendor/github.com/gogo/protobuf/protoc-gen-gogo/Makefile b/vendor/github.com/gogo/protobuf/protoc-gen-gogo/Makefile deleted file mode 100644 index a42cc3717..000000000 --- a/vendor/github.com/gogo/protobuf/protoc-gen-gogo/Makefile +++ /dev/null @@ -1,33 +0,0 @@ -# Go support for Protocol Buffers - Google's data interchange format -# -# Copyright 2010 The Go Authors. All rights reserved. -# https://github.com/golang/protobuf -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following disclaimer -# in the documentation and/or other materials provided with the -# distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived from -# this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -test: - cd testdata && make test diff --git a/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/Makefile b/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/Makefile deleted file mode 100644 index 3496dc99d..000000000 --- a/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/Makefile +++ /dev/null @@ -1,36 +0,0 @@ -# Go support for Protocol Buffers - Google's data interchange format -# -# Copyright 2010 The Go Authors. All rights reserved. -# https://github.com/golang/protobuf -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following disclaimer -# in the documentation and/or other materials provided with the -# distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived from -# this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -regenerate: - go install github.com/gogo/protobuf/protoc-gen-gogo - go install github.com/gogo/protobuf/protoc-gen-gostring - protoc --gogo_out=. -I=../../protobuf/google/protobuf ../../protobuf/google/protobuf/descriptor.proto - protoc --gostring_out=. -I=../../protobuf/google/protobuf ../../protobuf/google/protobuf/descriptor.proto diff --git a/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/descriptor.go b/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/descriptor.go deleted file mode 100644 index a85bf1984..000000000 --- a/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/descriptor.go +++ /dev/null @@ -1,118 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2016 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// Package descriptor provides functions for obtaining protocol buffer -// descriptors for generated Go types. -// -// These functions cannot go in package proto because they depend on the -// generated protobuf descriptor messages, which themselves depend on proto. -package descriptor - -import ( - "bytes" - "compress/gzip" - "fmt" - "io/ioutil" - - "github.com/gogo/protobuf/proto" -) - -// extractFile extracts a FileDescriptorProto from a gzip'd buffer. -func extractFile(gz []byte) (*FileDescriptorProto, error) { - r, err := gzip.NewReader(bytes.NewReader(gz)) - if err != nil { - return nil, fmt.Errorf("failed to open gzip reader: %v", err) - } - defer r.Close() - - b, err := ioutil.ReadAll(r) - if err != nil { - return nil, fmt.Errorf("failed to uncompress descriptor: %v", err) - } - - fd := new(FileDescriptorProto) - if err := proto.Unmarshal(b, fd); err != nil { - return nil, fmt.Errorf("malformed FileDescriptorProto: %v", err) - } - - return fd, nil -} - -// Message is a proto.Message with a method to return its descriptor. -// -// Message types generated by the protocol compiler always satisfy -// the Message interface. -type Message interface { - proto.Message - Descriptor() ([]byte, []int) -} - -// ForMessage returns a FileDescriptorProto and a DescriptorProto from within it -// describing the given message. -func ForMessage(msg Message) (fd *FileDescriptorProto, md *DescriptorProto) { - gz, path := msg.Descriptor() - fd, err := extractFile(gz) - if err != nil { - panic(fmt.Sprintf("invalid FileDescriptorProto for %T: %v", msg, err)) - } - - md = fd.MessageType[path[0]] - for _, i := range path[1:] { - md = md.NestedType[i] - } - return fd, md -} - -// Is this field a scalar numeric type? -func (field *FieldDescriptorProto) IsScalar() bool { - if field.Type == nil { - return false - } - switch *field.Type { - case FieldDescriptorProto_TYPE_DOUBLE, - FieldDescriptorProto_TYPE_FLOAT, - FieldDescriptorProto_TYPE_INT64, - FieldDescriptorProto_TYPE_UINT64, - FieldDescriptorProto_TYPE_INT32, - FieldDescriptorProto_TYPE_FIXED64, - FieldDescriptorProto_TYPE_FIXED32, - FieldDescriptorProto_TYPE_BOOL, - FieldDescriptorProto_TYPE_UINT32, - FieldDescriptorProto_TYPE_ENUM, - FieldDescriptorProto_TYPE_SFIXED32, - FieldDescriptorProto_TYPE_SFIXED64, - FieldDescriptorProto_TYPE_SINT32, - FieldDescriptorProto_TYPE_SINT64: - return true - default: - return false - } -} diff --git a/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/descriptor.pb.go b/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/descriptor.pb.go deleted file mode 100644 index 82623f049..000000000 --- a/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/descriptor.pb.go +++ /dev/null @@ -1,2223 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: descriptor.proto - -/* -Package descriptor is a generated protocol buffer package. - -It is generated from these files: - descriptor.proto - -It has these top-level messages: - FileDescriptorSet - FileDescriptorProto - DescriptorProto - ExtensionRangeOptions - FieldDescriptorProto - OneofDescriptorProto - EnumDescriptorProto - EnumValueDescriptorProto - ServiceDescriptorProto - MethodDescriptorProto - FileOptions - MessageOptions - FieldOptions - OneofOptions - EnumOptions - EnumValueOptions - ServiceOptions - MethodOptions - UninterpretedOption - SourceCodeInfo - GeneratedCodeInfo -*/ -package descriptor - -import proto "github.com/gogo/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package - -type FieldDescriptorProto_Type int32 - -const ( - // 0 is reserved for errors. - // Order is weird for historical reasons. - FieldDescriptorProto_TYPE_DOUBLE FieldDescriptorProto_Type = 1 - FieldDescriptorProto_TYPE_FLOAT FieldDescriptorProto_Type = 2 - // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if - // negative values are likely. - FieldDescriptorProto_TYPE_INT64 FieldDescriptorProto_Type = 3 - FieldDescriptorProto_TYPE_UINT64 FieldDescriptorProto_Type = 4 - // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if - // negative values are likely. - FieldDescriptorProto_TYPE_INT32 FieldDescriptorProto_Type = 5 - FieldDescriptorProto_TYPE_FIXED64 FieldDescriptorProto_Type = 6 - FieldDescriptorProto_TYPE_FIXED32 FieldDescriptorProto_Type = 7 - FieldDescriptorProto_TYPE_BOOL FieldDescriptorProto_Type = 8 - FieldDescriptorProto_TYPE_STRING FieldDescriptorProto_Type = 9 - // Tag-delimited aggregate. - // Group type is deprecated and not supported in proto3. However, Proto3 - // implementations should still be able to parse the group wire format and - // treat group fields as unknown fields. - FieldDescriptorProto_TYPE_GROUP FieldDescriptorProto_Type = 10 - FieldDescriptorProto_TYPE_MESSAGE FieldDescriptorProto_Type = 11 - // New in version 2. - FieldDescriptorProto_TYPE_BYTES FieldDescriptorProto_Type = 12 - FieldDescriptorProto_TYPE_UINT32 FieldDescriptorProto_Type = 13 - FieldDescriptorProto_TYPE_ENUM FieldDescriptorProto_Type = 14 - FieldDescriptorProto_TYPE_SFIXED32 FieldDescriptorProto_Type = 15 - FieldDescriptorProto_TYPE_SFIXED64 FieldDescriptorProto_Type = 16 - FieldDescriptorProto_TYPE_SINT32 FieldDescriptorProto_Type = 17 - FieldDescriptorProto_TYPE_SINT64 FieldDescriptorProto_Type = 18 -) - -var FieldDescriptorProto_Type_name = map[int32]string{ - 1: "TYPE_DOUBLE", - 2: "TYPE_FLOAT", - 3: "TYPE_INT64", - 4: "TYPE_UINT64", - 5: "TYPE_INT32", - 6: "TYPE_FIXED64", - 7: "TYPE_FIXED32", - 8: "TYPE_BOOL", - 9: "TYPE_STRING", - 10: "TYPE_GROUP", - 11: "TYPE_MESSAGE", - 12: "TYPE_BYTES", - 13: "TYPE_UINT32", - 14: "TYPE_ENUM", - 15: "TYPE_SFIXED32", - 16: "TYPE_SFIXED64", - 17: "TYPE_SINT32", - 18: "TYPE_SINT64", -} -var FieldDescriptorProto_Type_value = map[string]int32{ - "TYPE_DOUBLE": 1, - "TYPE_FLOAT": 2, - "TYPE_INT64": 3, - "TYPE_UINT64": 4, - "TYPE_INT32": 5, - "TYPE_FIXED64": 6, - "TYPE_FIXED32": 7, - "TYPE_BOOL": 8, - "TYPE_STRING": 9, - "TYPE_GROUP": 10, - "TYPE_MESSAGE": 11, - "TYPE_BYTES": 12, - "TYPE_UINT32": 13, - "TYPE_ENUM": 14, - "TYPE_SFIXED32": 15, - "TYPE_SFIXED64": 16, - "TYPE_SINT32": 17, - "TYPE_SINT64": 18, -} - -func (x FieldDescriptorProto_Type) Enum() *FieldDescriptorProto_Type { - p := new(FieldDescriptorProto_Type) - *p = x - return p -} -func (x FieldDescriptorProto_Type) String() string { - return proto.EnumName(FieldDescriptorProto_Type_name, int32(x)) -} -func (x *FieldDescriptorProto_Type) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(FieldDescriptorProto_Type_value, data, "FieldDescriptorProto_Type") - if err != nil { - return err - } - *x = FieldDescriptorProto_Type(value) - return nil -} -func (FieldDescriptorProto_Type) EnumDescriptor() ([]byte, []int) { - return fileDescriptorDescriptor, []int{4, 0} -} - -type FieldDescriptorProto_Label int32 - -const ( - // 0 is reserved for errors - FieldDescriptorProto_LABEL_OPTIONAL FieldDescriptorProto_Label = 1 - FieldDescriptorProto_LABEL_REQUIRED FieldDescriptorProto_Label = 2 - FieldDescriptorProto_LABEL_REPEATED FieldDescriptorProto_Label = 3 -) - -var FieldDescriptorProto_Label_name = map[int32]string{ - 1: "LABEL_OPTIONAL", - 2: "LABEL_REQUIRED", - 3: "LABEL_REPEATED", -} -var FieldDescriptorProto_Label_value = map[string]int32{ - "LABEL_OPTIONAL": 1, - "LABEL_REQUIRED": 2, - "LABEL_REPEATED": 3, -} - -func (x FieldDescriptorProto_Label) Enum() *FieldDescriptorProto_Label { - p := new(FieldDescriptorProto_Label) - *p = x - return p -} -func (x FieldDescriptorProto_Label) String() string { - return proto.EnumName(FieldDescriptorProto_Label_name, int32(x)) -} -func (x *FieldDescriptorProto_Label) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(FieldDescriptorProto_Label_value, data, "FieldDescriptorProto_Label") - if err != nil { - return err - } - *x = FieldDescriptorProto_Label(value) - return nil -} -func (FieldDescriptorProto_Label) EnumDescriptor() ([]byte, []int) { - return fileDescriptorDescriptor, []int{4, 1} -} - -// Generated classes can be optimized for speed or code size. -type FileOptions_OptimizeMode int32 - -const ( - FileOptions_SPEED FileOptions_OptimizeMode = 1 - // etc. - FileOptions_CODE_SIZE FileOptions_OptimizeMode = 2 - FileOptions_LITE_RUNTIME FileOptions_OptimizeMode = 3 -) - -var FileOptions_OptimizeMode_name = map[int32]string{ - 1: "SPEED", - 2: "CODE_SIZE", - 3: "LITE_RUNTIME", -} -var FileOptions_OptimizeMode_value = map[string]int32{ - "SPEED": 1, - "CODE_SIZE": 2, - "LITE_RUNTIME": 3, -} - -func (x FileOptions_OptimizeMode) Enum() *FileOptions_OptimizeMode { - p := new(FileOptions_OptimizeMode) - *p = x - return p -} -func (x FileOptions_OptimizeMode) String() string { - return proto.EnumName(FileOptions_OptimizeMode_name, int32(x)) -} -func (x *FileOptions_OptimizeMode) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(FileOptions_OptimizeMode_value, data, "FileOptions_OptimizeMode") - if err != nil { - return err - } - *x = FileOptions_OptimizeMode(value) - return nil -} -func (FileOptions_OptimizeMode) EnumDescriptor() ([]byte, []int) { - return fileDescriptorDescriptor, []int{10, 0} -} - -type FieldOptions_CType int32 - -const ( - // Default mode. - FieldOptions_STRING FieldOptions_CType = 0 - FieldOptions_CORD FieldOptions_CType = 1 - FieldOptions_STRING_PIECE FieldOptions_CType = 2 -) - -var FieldOptions_CType_name = map[int32]string{ - 0: "STRING", - 1: "CORD", - 2: "STRING_PIECE", -} -var FieldOptions_CType_value = map[string]int32{ - "STRING": 0, - "CORD": 1, - "STRING_PIECE": 2, -} - -func (x FieldOptions_CType) Enum() *FieldOptions_CType { - p := new(FieldOptions_CType) - *p = x - return p -} -func (x FieldOptions_CType) String() string { - return proto.EnumName(FieldOptions_CType_name, int32(x)) -} -func (x *FieldOptions_CType) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(FieldOptions_CType_value, data, "FieldOptions_CType") - if err != nil { - return err - } - *x = FieldOptions_CType(value) - return nil -} -func (FieldOptions_CType) EnumDescriptor() ([]byte, []int) { - return fileDescriptorDescriptor, []int{12, 0} -} - -type FieldOptions_JSType int32 - -const ( - // Use the default type. - FieldOptions_JS_NORMAL FieldOptions_JSType = 0 - // Use JavaScript strings. - FieldOptions_JS_STRING FieldOptions_JSType = 1 - // Use JavaScript numbers. - FieldOptions_JS_NUMBER FieldOptions_JSType = 2 -) - -var FieldOptions_JSType_name = map[int32]string{ - 0: "JS_NORMAL", - 1: "JS_STRING", - 2: "JS_NUMBER", -} -var FieldOptions_JSType_value = map[string]int32{ - "JS_NORMAL": 0, - "JS_STRING": 1, - "JS_NUMBER": 2, -} - -func (x FieldOptions_JSType) Enum() *FieldOptions_JSType { - p := new(FieldOptions_JSType) - *p = x - return p -} -func (x FieldOptions_JSType) String() string { - return proto.EnumName(FieldOptions_JSType_name, int32(x)) -} -func (x *FieldOptions_JSType) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(FieldOptions_JSType_value, data, "FieldOptions_JSType") - if err != nil { - return err - } - *x = FieldOptions_JSType(value) - return nil -} -func (FieldOptions_JSType) EnumDescriptor() ([]byte, []int) { - return fileDescriptorDescriptor, []int{12, 1} -} - -// Is this method side-effect-free (or safe in HTTP parlance), or idempotent, -// or neither? HTTP based RPC implementation may choose GET verb for safe -// methods, and PUT verb for idempotent methods instead of the default POST. -type MethodOptions_IdempotencyLevel int32 - -const ( - MethodOptions_IDEMPOTENCY_UNKNOWN MethodOptions_IdempotencyLevel = 0 - MethodOptions_NO_SIDE_EFFECTS MethodOptions_IdempotencyLevel = 1 - MethodOptions_IDEMPOTENT MethodOptions_IdempotencyLevel = 2 -) - -var MethodOptions_IdempotencyLevel_name = map[int32]string{ - 0: "IDEMPOTENCY_UNKNOWN", - 1: "NO_SIDE_EFFECTS", - 2: "IDEMPOTENT", -} -var MethodOptions_IdempotencyLevel_value = map[string]int32{ - "IDEMPOTENCY_UNKNOWN": 0, - "NO_SIDE_EFFECTS": 1, - "IDEMPOTENT": 2, -} - -func (x MethodOptions_IdempotencyLevel) Enum() *MethodOptions_IdempotencyLevel { - p := new(MethodOptions_IdempotencyLevel) - *p = x - return p -} -func (x MethodOptions_IdempotencyLevel) String() string { - return proto.EnumName(MethodOptions_IdempotencyLevel_name, int32(x)) -} -func (x *MethodOptions_IdempotencyLevel) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(MethodOptions_IdempotencyLevel_value, data, "MethodOptions_IdempotencyLevel") - if err != nil { - return err - } - *x = MethodOptions_IdempotencyLevel(value) - return nil -} -func (MethodOptions_IdempotencyLevel) EnumDescriptor() ([]byte, []int) { - return fileDescriptorDescriptor, []int{17, 0} -} - -// The protocol compiler can output a FileDescriptorSet containing the .proto -// files it parses. -type FileDescriptorSet struct { - File []*FileDescriptorProto `protobuf:"bytes,1,rep,name=file" json:"file,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *FileDescriptorSet) Reset() { *m = FileDescriptorSet{} } -func (m *FileDescriptorSet) String() string { return proto.CompactTextString(m) } -func (*FileDescriptorSet) ProtoMessage() {} -func (*FileDescriptorSet) Descriptor() ([]byte, []int) { return fileDescriptorDescriptor, []int{0} } - -func (m *FileDescriptorSet) GetFile() []*FileDescriptorProto { - if m != nil { - return m.File - } - return nil -} - -// Describes a complete .proto file. -type FileDescriptorProto struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - Package *string `protobuf:"bytes,2,opt,name=package" json:"package,omitempty"` - // Names of files imported by this file. - Dependency []string `protobuf:"bytes,3,rep,name=dependency" json:"dependency,omitempty"` - // Indexes of the public imported files in the dependency list above. - PublicDependency []int32 `protobuf:"varint,10,rep,name=public_dependency,json=publicDependency" json:"public_dependency,omitempty"` - // Indexes of the weak imported files in the dependency list. - // For Google-internal migration only. Do not use. - WeakDependency []int32 `protobuf:"varint,11,rep,name=weak_dependency,json=weakDependency" json:"weak_dependency,omitempty"` - // All top-level definitions in this file. - MessageType []*DescriptorProto `protobuf:"bytes,4,rep,name=message_type,json=messageType" json:"message_type,omitempty"` - EnumType []*EnumDescriptorProto `protobuf:"bytes,5,rep,name=enum_type,json=enumType" json:"enum_type,omitempty"` - Service []*ServiceDescriptorProto `protobuf:"bytes,6,rep,name=service" json:"service,omitempty"` - Extension []*FieldDescriptorProto `protobuf:"bytes,7,rep,name=extension" json:"extension,omitempty"` - Options *FileOptions `protobuf:"bytes,8,opt,name=options" json:"options,omitempty"` - // This field contains optional information about the original source code. - // You may safely remove this entire field without harming runtime - // functionality of the descriptors -- the information is needed only by - // development tools. - SourceCodeInfo *SourceCodeInfo `protobuf:"bytes,9,opt,name=source_code_info,json=sourceCodeInfo" json:"source_code_info,omitempty"` - // The syntax of the proto file. - // The supported values are "proto2" and "proto3". - Syntax *string `protobuf:"bytes,12,opt,name=syntax" json:"syntax,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *FileDescriptorProto) Reset() { *m = FileDescriptorProto{} } -func (m *FileDescriptorProto) String() string { return proto.CompactTextString(m) } -func (*FileDescriptorProto) ProtoMessage() {} -func (*FileDescriptorProto) Descriptor() ([]byte, []int) { return fileDescriptorDescriptor, []int{1} } - -func (m *FileDescriptorProto) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *FileDescriptorProto) GetPackage() string { - if m != nil && m.Package != nil { - return *m.Package - } - return "" -} - -func (m *FileDescriptorProto) GetDependency() []string { - if m != nil { - return m.Dependency - } - return nil -} - -func (m *FileDescriptorProto) GetPublicDependency() []int32 { - if m != nil { - return m.PublicDependency - } - return nil -} - -func (m *FileDescriptorProto) GetWeakDependency() []int32 { - if m != nil { - return m.WeakDependency - } - return nil -} - -func (m *FileDescriptorProto) GetMessageType() []*DescriptorProto { - if m != nil { - return m.MessageType - } - return nil -} - -func (m *FileDescriptorProto) GetEnumType() []*EnumDescriptorProto { - if m != nil { - return m.EnumType - } - return nil -} - -func (m *FileDescriptorProto) GetService() []*ServiceDescriptorProto { - if m != nil { - return m.Service - } - return nil -} - -func (m *FileDescriptorProto) GetExtension() []*FieldDescriptorProto { - if m != nil { - return m.Extension - } - return nil -} - -func (m *FileDescriptorProto) GetOptions() *FileOptions { - if m != nil { - return m.Options - } - return nil -} - -func (m *FileDescriptorProto) GetSourceCodeInfo() *SourceCodeInfo { - if m != nil { - return m.SourceCodeInfo - } - return nil -} - -func (m *FileDescriptorProto) GetSyntax() string { - if m != nil && m.Syntax != nil { - return *m.Syntax - } - return "" -} - -// Describes a message type. -type DescriptorProto struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - Field []*FieldDescriptorProto `protobuf:"bytes,2,rep,name=field" json:"field,omitempty"` - Extension []*FieldDescriptorProto `protobuf:"bytes,6,rep,name=extension" json:"extension,omitempty"` - NestedType []*DescriptorProto `protobuf:"bytes,3,rep,name=nested_type,json=nestedType" json:"nested_type,omitempty"` - EnumType []*EnumDescriptorProto `protobuf:"bytes,4,rep,name=enum_type,json=enumType" json:"enum_type,omitempty"` - ExtensionRange []*DescriptorProto_ExtensionRange `protobuf:"bytes,5,rep,name=extension_range,json=extensionRange" json:"extension_range,omitempty"` - OneofDecl []*OneofDescriptorProto `protobuf:"bytes,8,rep,name=oneof_decl,json=oneofDecl" json:"oneof_decl,omitempty"` - Options *MessageOptions `protobuf:"bytes,7,opt,name=options" json:"options,omitempty"` - ReservedRange []*DescriptorProto_ReservedRange `protobuf:"bytes,9,rep,name=reserved_range,json=reservedRange" json:"reserved_range,omitempty"` - // Reserved field names, which may not be used by fields in the same message. - // A given name may only be reserved once. - ReservedName []string `protobuf:"bytes,10,rep,name=reserved_name,json=reservedName" json:"reserved_name,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *DescriptorProto) Reset() { *m = DescriptorProto{} } -func (m *DescriptorProto) String() string { return proto.CompactTextString(m) } -func (*DescriptorProto) ProtoMessage() {} -func (*DescriptorProto) Descriptor() ([]byte, []int) { return fileDescriptorDescriptor, []int{2} } - -func (m *DescriptorProto) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *DescriptorProto) GetField() []*FieldDescriptorProto { - if m != nil { - return m.Field - } - return nil -} - -func (m *DescriptorProto) GetExtension() []*FieldDescriptorProto { - if m != nil { - return m.Extension - } - return nil -} - -func (m *DescriptorProto) GetNestedType() []*DescriptorProto { - if m != nil { - return m.NestedType - } - return nil -} - -func (m *DescriptorProto) GetEnumType() []*EnumDescriptorProto { - if m != nil { - return m.EnumType - } - return nil -} - -func (m *DescriptorProto) GetExtensionRange() []*DescriptorProto_ExtensionRange { - if m != nil { - return m.ExtensionRange - } - return nil -} - -func (m *DescriptorProto) GetOneofDecl() []*OneofDescriptorProto { - if m != nil { - return m.OneofDecl - } - return nil -} - -func (m *DescriptorProto) GetOptions() *MessageOptions { - if m != nil { - return m.Options - } - return nil -} - -func (m *DescriptorProto) GetReservedRange() []*DescriptorProto_ReservedRange { - if m != nil { - return m.ReservedRange - } - return nil -} - -func (m *DescriptorProto) GetReservedName() []string { - if m != nil { - return m.ReservedName - } - return nil -} - -type DescriptorProto_ExtensionRange struct { - Start *int32 `protobuf:"varint,1,opt,name=start" json:"start,omitempty"` - End *int32 `protobuf:"varint,2,opt,name=end" json:"end,omitempty"` - Options *ExtensionRangeOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *DescriptorProto_ExtensionRange) Reset() { *m = DescriptorProto_ExtensionRange{} } -func (m *DescriptorProto_ExtensionRange) String() string { return proto.CompactTextString(m) } -func (*DescriptorProto_ExtensionRange) ProtoMessage() {} -func (*DescriptorProto_ExtensionRange) Descriptor() ([]byte, []int) { - return fileDescriptorDescriptor, []int{2, 0} -} - -func (m *DescriptorProto_ExtensionRange) GetStart() int32 { - if m != nil && m.Start != nil { - return *m.Start - } - return 0 -} - -func (m *DescriptorProto_ExtensionRange) GetEnd() int32 { - if m != nil && m.End != nil { - return *m.End - } - return 0 -} - -func (m *DescriptorProto_ExtensionRange) GetOptions() *ExtensionRangeOptions { - if m != nil { - return m.Options - } - return nil -} - -// Range of reserved tag numbers. Reserved tag numbers may not be used by -// fields or extension ranges in the same message. Reserved ranges may -// not overlap. -type DescriptorProto_ReservedRange struct { - Start *int32 `protobuf:"varint,1,opt,name=start" json:"start,omitempty"` - End *int32 `protobuf:"varint,2,opt,name=end" json:"end,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *DescriptorProto_ReservedRange) Reset() { *m = DescriptorProto_ReservedRange{} } -func (m *DescriptorProto_ReservedRange) String() string { return proto.CompactTextString(m) } -func (*DescriptorProto_ReservedRange) ProtoMessage() {} -func (*DescriptorProto_ReservedRange) Descriptor() ([]byte, []int) { - return fileDescriptorDescriptor, []int{2, 1} -} - -func (m *DescriptorProto_ReservedRange) GetStart() int32 { - if m != nil && m.Start != nil { - return *m.Start - } - return 0 -} - -func (m *DescriptorProto_ReservedRange) GetEnd() int32 { - if m != nil && m.End != nil { - return *m.End - } - return 0 -} - -type ExtensionRangeOptions struct { - // The parser stores options it doesn't recognize here. See above. - UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` - proto.XXX_InternalExtensions `json:"-"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *ExtensionRangeOptions) Reset() { *m = ExtensionRangeOptions{} } -func (m *ExtensionRangeOptions) String() string { return proto.CompactTextString(m) } -func (*ExtensionRangeOptions) ProtoMessage() {} -func (*ExtensionRangeOptions) Descriptor() ([]byte, []int) { return fileDescriptorDescriptor, []int{3} } - -var extRange_ExtensionRangeOptions = []proto.ExtensionRange{ - {Start: 1000, End: 536870911}, -} - -func (*ExtensionRangeOptions) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_ExtensionRangeOptions -} - -func (m *ExtensionRangeOptions) GetUninterpretedOption() []*UninterpretedOption { - if m != nil { - return m.UninterpretedOption - } - return nil -} - -// Describes a field within a message. -type FieldDescriptorProto struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - Number *int32 `protobuf:"varint,3,opt,name=number" json:"number,omitempty"` - Label *FieldDescriptorProto_Label `protobuf:"varint,4,opt,name=label,enum=google.protobuf.FieldDescriptorProto_Label" json:"label,omitempty"` - // If type_name is set, this need not be set. If both this and type_name - // are set, this must be one of TYPE_ENUM, TYPE_MESSAGE or TYPE_GROUP. - Type *FieldDescriptorProto_Type `protobuf:"varint,5,opt,name=type,enum=google.protobuf.FieldDescriptorProto_Type" json:"type,omitempty"` - // For message and enum types, this is the name of the type. If the name - // starts with a '.', it is fully-qualified. Otherwise, C++-like scoping - // rules are used to find the type (i.e. first the nested types within this - // message are searched, then within the parent, on up to the root - // namespace). - TypeName *string `protobuf:"bytes,6,opt,name=type_name,json=typeName" json:"type_name,omitempty"` - // For extensions, this is the name of the type being extended. It is - // resolved in the same manner as type_name. - Extendee *string `protobuf:"bytes,2,opt,name=extendee" json:"extendee,omitempty"` - // For numeric types, contains the original text representation of the value. - // For booleans, "true" or "false". - // For strings, contains the default text contents (not escaped in any way). - // For bytes, contains the C escaped value. All bytes >= 128 are escaped. - // TODO(kenton): Base-64 encode? - DefaultValue *string `protobuf:"bytes,7,opt,name=default_value,json=defaultValue" json:"default_value,omitempty"` - // If set, gives the index of a oneof in the containing type's oneof_decl - // list. This field is a member of that oneof. - OneofIndex *int32 `protobuf:"varint,9,opt,name=oneof_index,json=oneofIndex" json:"oneof_index,omitempty"` - // JSON name of this field. The value is set by protocol compiler. If the - // user has set a "json_name" option on this field, that option's value - // will be used. Otherwise, it's deduced from the field's name by converting - // it to camelCase. - JsonName *string `protobuf:"bytes,10,opt,name=json_name,json=jsonName" json:"json_name,omitempty"` - Options *FieldOptions `protobuf:"bytes,8,opt,name=options" json:"options,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *FieldDescriptorProto) Reset() { *m = FieldDescriptorProto{} } -func (m *FieldDescriptorProto) String() string { return proto.CompactTextString(m) } -func (*FieldDescriptorProto) ProtoMessage() {} -func (*FieldDescriptorProto) Descriptor() ([]byte, []int) { return fileDescriptorDescriptor, []int{4} } - -func (m *FieldDescriptorProto) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *FieldDescriptorProto) GetNumber() int32 { - if m != nil && m.Number != nil { - return *m.Number - } - return 0 -} - -func (m *FieldDescriptorProto) GetLabel() FieldDescriptorProto_Label { - if m != nil && m.Label != nil { - return *m.Label - } - return FieldDescriptorProto_LABEL_OPTIONAL -} - -func (m *FieldDescriptorProto) GetType() FieldDescriptorProto_Type { - if m != nil && m.Type != nil { - return *m.Type - } - return FieldDescriptorProto_TYPE_DOUBLE -} - -func (m *FieldDescriptorProto) GetTypeName() string { - if m != nil && m.TypeName != nil { - return *m.TypeName - } - return "" -} - -func (m *FieldDescriptorProto) GetExtendee() string { - if m != nil && m.Extendee != nil { - return *m.Extendee - } - return "" -} - -func (m *FieldDescriptorProto) GetDefaultValue() string { - if m != nil && m.DefaultValue != nil { - return *m.DefaultValue - } - return "" -} - -func (m *FieldDescriptorProto) GetOneofIndex() int32 { - if m != nil && m.OneofIndex != nil { - return *m.OneofIndex - } - return 0 -} - -func (m *FieldDescriptorProto) GetJsonName() string { - if m != nil && m.JsonName != nil { - return *m.JsonName - } - return "" -} - -func (m *FieldDescriptorProto) GetOptions() *FieldOptions { - if m != nil { - return m.Options - } - return nil -} - -// Describes a oneof. -type OneofDescriptorProto struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - Options *OneofOptions `protobuf:"bytes,2,opt,name=options" json:"options,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *OneofDescriptorProto) Reset() { *m = OneofDescriptorProto{} } -func (m *OneofDescriptorProto) String() string { return proto.CompactTextString(m) } -func (*OneofDescriptorProto) ProtoMessage() {} -func (*OneofDescriptorProto) Descriptor() ([]byte, []int) { return fileDescriptorDescriptor, []int{5} } - -func (m *OneofDescriptorProto) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *OneofDescriptorProto) GetOptions() *OneofOptions { - if m != nil { - return m.Options - } - return nil -} - -// Describes an enum type. -type EnumDescriptorProto struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - Value []*EnumValueDescriptorProto `protobuf:"bytes,2,rep,name=value" json:"value,omitempty"` - Options *EnumOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *EnumDescriptorProto) Reset() { *m = EnumDescriptorProto{} } -func (m *EnumDescriptorProto) String() string { return proto.CompactTextString(m) } -func (*EnumDescriptorProto) ProtoMessage() {} -func (*EnumDescriptorProto) Descriptor() ([]byte, []int) { return fileDescriptorDescriptor, []int{6} } - -func (m *EnumDescriptorProto) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *EnumDescriptorProto) GetValue() []*EnumValueDescriptorProto { - if m != nil { - return m.Value - } - return nil -} - -func (m *EnumDescriptorProto) GetOptions() *EnumOptions { - if m != nil { - return m.Options - } - return nil -} - -// Describes a value within an enum. -type EnumValueDescriptorProto struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - Number *int32 `protobuf:"varint,2,opt,name=number" json:"number,omitempty"` - Options *EnumValueOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *EnumValueDescriptorProto) Reset() { *m = EnumValueDescriptorProto{} } -func (m *EnumValueDescriptorProto) String() string { return proto.CompactTextString(m) } -func (*EnumValueDescriptorProto) ProtoMessage() {} -func (*EnumValueDescriptorProto) Descriptor() ([]byte, []int) { - return fileDescriptorDescriptor, []int{7} -} - -func (m *EnumValueDescriptorProto) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *EnumValueDescriptorProto) GetNumber() int32 { - if m != nil && m.Number != nil { - return *m.Number - } - return 0 -} - -func (m *EnumValueDescriptorProto) GetOptions() *EnumValueOptions { - if m != nil { - return m.Options - } - return nil -} - -// Describes a service. -type ServiceDescriptorProto struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - Method []*MethodDescriptorProto `protobuf:"bytes,2,rep,name=method" json:"method,omitempty"` - Options *ServiceOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *ServiceDescriptorProto) Reset() { *m = ServiceDescriptorProto{} } -func (m *ServiceDescriptorProto) String() string { return proto.CompactTextString(m) } -func (*ServiceDescriptorProto) ProtoMessage() {} -func (*ServiceDescriptorProto) Descriptor() ([]byte, []int) { return fileDescriptorDescriptor, []int{8} } - -func (m *ServiceDescriptorProto) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *ServiceDescriptorProto) GetMethod() []*MethodDescriptorProto { - if m != nil { - return m.Method - } - return nil -} - -func (m *ServiceDescriptorProto) GetOptions() *ServiceOptions { - if m != nil { - return m.Options - } - return nil -} - -// Describes a method of a service. -type MethodDescriptorProto struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - // Input and output type names. These are resolved in the same way as - // FieldDescriptorProto.type_name, but must refer to a message type. - InputType *string `protobuf:"bytes,2,opt,name=input_type,json=inputType" json:"input_type,omitempty"` - OutputType *string `protobuf:"bytes,3,opt,name=output_type,json=outputType" json:"output_type,omitempty"` - Options *MethodOptions `protobuf:"bytes,4,opt,name=options" json:"options,omitempty"` - // Identifies if client streams multiple client messages - ClientStreaming *bool `protobuf:"varint,5,opt,name=client_streaming,json=clientStreaming,def=0" json:"client_streaming,omitempty"` - // Identifies if server streams multiple server messages - ServerStreaming *bool `protobuf:"varint,6,opt,name=server_streaming,json=serverStreaming,def=0" json:"server_streaming,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *MethodDescriptorProto) Reset() { *m = MethodDescriptorProto{} } -func (m *MethodDescriptorProto) String() string { return proto.CompactTextString(m) } -func (*MethodDescriptorProto) ProtoMessage() {} -func (*MethodDescriptorProto) Descriptor() ([]byte, []int) { return fileDescriptorDescriptor, []int{9} } - -const Default_MethodDescriptorProto_ClientStreaming bool = false -const Default_MethodDescriptorProto_ServerStreaming bool = false - -func (m *MethodDescriptorProto) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *MethodDescriptorProto) GetInputType() string { - if m != nil && m.InputType != nil { - return *m.InputType - } - return "" -} - -func (m *MethodDescriptorProto) GetOutputType() string { - if m != nil && m.OutputType != nil { - return *m.OutputType - } - return "" -} - -func (m *MethodDescriptorProto) GetOptions() *MethodOptions { - if m != nil { - return m.Options - } - return nil -} - -func (m *MethodDescriptorProto) GetClientStreaming() bool { - if m != nil && m.ClientStreaming != nil { - return *m.ClientStreaming - } - return Default_MethodDescriptorProto_ClientStreaming -} - -func (m *MethodDescriptorProto) GetServerStreaming() bool { - if m != nil && m.ServerStreaming != nil { - return *m.ServerStreaming - } - return Default_MethodDescriptorProto_ServerStreaming -} - -type FileOptions struct { - // Sets the Java package where classes generated from this .proto will be - // placed. By default, the proto package is used, but this is often - // inappropriate because proto packages do not normally start with backwards - // domain names. - JavaPackage *string `protobuf:"bytes,1,opt,name=java_package,json=javaPackage" json:"java_package,omitempty"` - // If set, all the classes from the .proto file are wrapped in a single - // outer class with the given name. This applies to both Proto1 - // (equivalent to the old "--one_java_file" option) and Proto2 (where - // a .proto always translates to a single class, but you may want to - // explicitly choose the class name). - JavaOuterClassname *string `protobuf:"bytes,8,opt,name=java_outer_classname,json=javaOuterClassname" json:"java_outer_classname,omitempty"` - // If set true, then the Java code generator will generate a separate .java - // file for each top-level message, enum, and service defined in the .proto - // file. Thus, these types will *not* be nested inside the outer class - // named by java_outer_classname. However, the outer class will still be - // generated to contain the file's getDescriptor() method as well as any - // top-level extensions defined in the file. - JavaMultipleFiles *bool `protobuf:"varint,10,opt,name=java_multiple_files,json=javaMultipleFiles,def=0" json:"java_multiple_files,omitempty"` - // This option does nothing. - JavaGenerateEqualsAndHash *bool `protobuf:"varint,20,opt,name=java_generate_equals_and_hash,json=javaGenerateEqualsAndHash" json:"java_generate_equals_and_hash,omitempty"` - // If set true, then the Java2 code generator will generate code that - // throws an exception whenever an attempt is made to assign a non-UTF-8 - // byte sequence to a string field. - // Message reflection will do the same. - // However, an extension field still accepts non-UTF-8 byte sequences. - // This option has no effect on when used with the lite runtime. - JavaStringCheckUtf8 *bool `protobuf:"varint,27,opt,name=java_string_check_utf8,json=javaStringCheckUtf8,def=0" json:"java_string_check_utf8,omitempty"` - OptimizeFor *FileOptions_OptimizeMode `protobuf:"varint,9,opt,name=optimize_for,json=optimizeFor,enum=google.protobuf.FileOptions_OptimizeMode,def=1" json:"optimize_for,omitempty"` - // Sets the Go package where structs generated from this .proto will be - // placed. If omitted, the Go package will be derived from the following: - // - The basename of the package import path, if provided. - // - Otherwise, the package statement in the .proto file, if present. - // - Otherwise, the basename of the .proto file, without extension. - GoPackage *string `protobuf:"bytes,11,opt,name=go_package,json=goPackage" json:"go_package,omitempty"` - // Should generic services be generated in each language? "Generic" services - // are not specific to any particular RPC system. They are generated by the - // main code generators in each language (without additional plugins). - // Generic services were the only kind of service generation supported by - // early versions of google.protobuf. - // - // Generic services are now considered deprecated in favor of using plugins - // that generate code specific to your particular RPC system. Therefore, - // these default to false. Old code which depends on generic services should - // explicitly set them to true. - CcGenericServices *bool `protobuf:"varint,16,opt,name=cc_generic_services,json=ccGenericServices,def=0" json:"cc_generic_services,omitempty"` - JavaGenericServices *bool `protobuf:"varint,17,opt,name=java_generic_services,json=javaGenericServices,def=0" json:"java_generic_services,omitempty"` - PyGenericServices *bool `protobuf:"varint,18,opt,name=py_generic_services,json=pyGenericServices,def=0" json:"py_generic_services,omitempty"` - PhpGenericServices *bool `protobuf:"varint,19,opt,name=php_generic_services,json=phpGenericServices,def=0" json:"php_generic_services,omitempty"` - // Is this file deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for everything in the file, or it will be completely ignored; in the very - // least, this is a formalization for deprecating files. - Deprecated *bool `protobuf:"varint,23,opt,name=deprecated,def=0" json:"deprecated,omitempty"` - // Enables the use of arenas for the proto messages in this file. This applies - // only to generated classes for C++. - CcEnableArenas *bool `protobuf:"varint,31,opt,name=cc_enable_arenas,json=ccEnableArenas,def=0" json:"cc_enable_arenas,omitempty"` - // Sets the objective c class prefix which is prepended to all objective c - // generated classes from this .proto. There is no default. - ObjcClassPrefix *string `protobuf:"bytes,36,opt,name=objc_class_prefix,json=objcClassPrefix" json:"objc_class_prefix,omitempty"` - // Namespace for generated classes; defaults to the package. - CsharpNamespace *string `protobuf:"bytes,37,opt,name=csharp_namespace,json=csharpNamespace" json:"csharp_namespace,omitempty"` - // By default Swift generators will take the proto package and CamelCase it - // replacing '.' with underscore and use that to prefix the types/symbols - // defined. When this options is provided, they will use this value instead - // to prefix the types/symbols defined. - SwiftPrefix *string `protobuf:"bytes,39,opt,name=swift_prefix,json=swiftPrefix" json:"swift_prefix,omitempty"` - // Sets the php class prefix which is prepended to all php generated classes - // from this .proto. Default is empty. - PhpClassPrefix *string `protobuf:"bytes,40,opt,name=php_class_prefix,json=phpClassPrefix" json:"php_class_prefix,omitempty"` - // Use this option to change the namespace of php generated classes. Default - // is empty. When this option is empty, the package name will be used for - // determining the namespace. - PhpNamespace *string `protobuf:"bytes,41,opt,name=php_namespace,json=phpNamespace" json:"php_namespace,omitempty"` - // The parser stores options it doesn't recognize here. See above. - UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` - proto.XXX_InternalExtensions `json:"-"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *FileOptions) Reset() { *m = FileOptions{} } -func (m *FileOptions) String() string { return proto.CompactTextString(m) } -func (*FileOptions) ProtoMessage() {} -func (*FileOptions) Descriptor() ([]byte, []int) { return fileDescriptorDescriptor, []int{10} } - -var extRange_FileOptions = []proto.ExtensionRange{ - {Start: 1000, End: 536870911}, -} - -func (*FileOptions) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_FileOptions -} - -const Default_FileOptions_JavaMultipleFiles bool = false -const Default_FileOptions_JavaStringCheckUtf8 bool = false -const Default_FileOptions_OptimizeFor FileOptions_OptimizeMode = FileOptions_SPEED -const Default_FileOptions_CcGenericServices bool = false -const Default_FileOptions_JavaGenericServices bool = false -const Default_FileOptions_PyGenericServices bool = false -const Default_FileOptions_PhpGenericServices bool = false -const Default_FileOptions_Deprecated bool = false -const Default_FileOptions_CcEnableArenas bool = false - -func (m *FileOptions) GetJavaPackage() string { - if m != nil && m.JavaPackage != nil { - return *m.JavaPackage - } - return "" -} - -func (m *FileOptions) GetJavaOuterClassname() string { - if m != nil && m.JavaOuterClassname != nil { - return *m.JavaOuterClassname - } - return "" -} - -func (m *FileOptions) GetJavaMultipleFiles() bool { - if m != nil && m.JavaMultipleFiles != nil { - return *m.JavaMultipleFiles - } - return Default_FileOptions_JavaMultipleFiles -} - -func (m *FileOptions) GetJavaGenerateEqualsAndHash() bool { - if m != nil && m.JavaGenerateEqualsAndHash != nil { - return *m.JavaGenerateEqualsAndHash - } - return false -} - -func (m *FileOptions) GetJavaStringCheckUtf8() bool { - if m != nil && m.JavaStringCheckUtf8 != nil { - return *m.JavaStringCheckUtf8 - } - return Default_FileOptions_JavaStringCheckUtf8 -} - -func (m *FileOptions) GetOptimizeFor() FileOptions_OptimizeMode { - if m != nil && m.OptimizeFor != nil { - return *m.OptimizeFor - } - return Default_FileOptions_OptimizeFor -} - -func (m *FileOptions) GetGoPackage() string { - if m != nil && m.GoPackage != nil { - return *m.GoPackage - } - return "" -} - -func (m *FileOptions) GetCcGenericServices() bool { - if m != nil && m.CcGenericServices != nil { - return *m.CcGenericServices - } - return Default_FileOptions_CcGenericServices -} - -func (m *FileOptions) GetJavaGenericServices() bool { - if m != nil && m.JavaGenericServices != nil { - return *m.JavaGenericServices - } - return Default_FileOptions_JavaGenericServices -} - -func (m *FileOptions) GetPyGenericServices() bool { - if m != nil && m.PyGenericServices != nil { - return *m.PyGenericServices - } - return Default_FileOptions_PyGenericServices -} - -func (m *FileOptions) GetPhpGenericServices() bool { - if m != nil && m.PhpGenericServices != nil { - return *m.PhpGenericServices - } - return Default_FileOptions_PhpGenericServices -} - -func (m *FileOptions) GetDeprecated() bool { - if m != nil && m.Deprecated != nil { - return *m.Deprecated - } - return Default_FileOptions_Deprecated -} - -func (m *FileOptions) GetCcEnableArenas() bool { - if m != nil && m.CcEnableArenas != nil { - return *m.CcEnableArenas - } - return Default_FileOptions_CcEnableArenas -} - -func (m *FileOptions) GetObjcClassPrefix() string { - if m != nil && m.ObjcClassPrefix != nil { - return *m.ObjcClassPrefix - } - return "" -} - -func (m *FileOptions) GetCsharpNamespace() string { - if m != nil && m.CsharpNamespace != nil { - return *m.CsharpNamespace - } - return "" -} - -func (m *FileOptions) GetSwiftPrefix() string { - if m != nil && m.SwiftPrefix != nil { - return *m.SwiftPrefix - } - return "" -} - -func (m *FileOptions) GetPhpClassPrefix() string { - if m != nil && m.PhpClassPrefix != nil { - return *m.PhpClassPrefix - } - return "" -} - -func (m *FileOptions) GetPhpNamespace() string { - if m != nil && m.PhpNamespace != nil { - return *m.PhpNamespace - } - return "" -} - -func (m *FileOptions) GetUninterpretedOption() []*UninterpretedOption { - if m != nil { - return m.UninterpretedOption - } - return nil -} - -type MessageOptions struct { - // Set true to use the old proto1 MessageSet wire format for extensions. - // This is provided for backwards-compatibility with the MessageSet wire - // format. You should not use this for any other reason: It's less - // efficient, has fewer features, and is more complicated. - // - // The message must be defined exactly as follows: - // message Foo { - // option message_set_wire_format = true; - // extensions 4 to max; - // } - // Note that the message cannot have any defined fields; MessageSets only - // have extensions. - // - // All extensions of your type must be singular messages; e.g. they cannot - // be int32s, enums, or repeated messages. - // - // Because this is an option, the above two restrictions are not enforced by - // the protocol compiler. - MessageSetWireFormat *bool `protobuf:"varint,1,opt,name=message_set_wire_format,json=messageSetWireFormat,def=0" json:"message_set_wire_format,omitempty"` - // Disables the generation of the standard "descriptor()" accessor, which can - // conflict with a field of the same name. This is meant to make migration - // from proto1 easier; new code should avoid fields named "descriptor". - NoStandardDescriptorAccessor *bool `protobuf:"varint,2,opt,name=no_standard_descriptor_accessor,json=noStandardDescriptorAccessor,def=0" json:"no_standard_descriptor_accessor,omitempty"` - // Is this message deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for the message, or it will be completely ignored; in the very least, - // this is a formalization for deprecating messages. - Deprecated *bool `protobuf:"varint,3,opt,name=deprecated,def=0" json:"deprecated,omitempty"` - // Whether the message is an automatically generated map entry type for the - // maps field. - // - // For maps fields: - // map map_field = 1; - // The parsed descriptor looks like: - // message MapFieldEntry { - // option map_entry = true; - // optional KeyType key = 1; - // optional ValueType value = 2; - // } - // repeated MapFieldEntry map_field = 1; - // - // Implementations may choose not to generate the map_entry=true message, but - // use a native map in the target language to hold the keys and values. - // The reflection APIs in such implementions still need to work as - // if the field is a repeated message field. - // - // NOTE: Do not set the option in .proto files. Always use the maps syntax - // instead. The option should only be implicitly set by the proto compiler - // parser. - MapEntry *bool `protobuf:"varint,7,opt,name=map_entry,json=mapEntry" json:"map_entry,omitempty"` - // The parser stores options it doesn't recognize here. See above. - UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` - proto.XXX_InternalExtensions `json:"-"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *MessageOptions) Reset() { *m = MessageOptions{} } -func (m *MessageOptions) String() string { return proto.CompactTextString(m) } -func (*MessageOptions) ProtoMessage() {} -func (*MessageOptions) Descriptor() ([]byte, []int) { return fileDescriptorDescriptor, []int{11} } - -var extRange_MessageOptions = []proto.ExtensionRange{ - {Start: 1000, End: 536870911}, -} - -func (*MessageOptions) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_MessageOptions -} - -const Default_MessageOptions_MessageSetWireFormat bool = false -const Default_MessageOptions_NoStandardDescriptorAccessor bool = false -const Default_MessageOptions_Deprecated bool = false - -func (m *MessageOptions) GetMessageSetWireFormat() bool { - if m != nil && m.MessageSetWireFormat != nil { - return *m.MessageSetWireFormat - } - return Default_MessageOptions_MessageSetWireFormat -} - -func (m *MessageOptions) GetNoStandardDescriptorAccessor() bool { - if m != nil && m.NoStandardDescriptorAccessor != nil { - return *m.NoStandardDescriptorAccessor - } - return Default_MessageOptions_NoStandardDescriptorAccessor -} - -func (m *MessageOptions) GetDeprecated() bool { - if m != nil && m.Deprecated != nil { - return *m.Deprecated - } - return Default_MessageOptions_Deprecated -} - -func (m *MessageOptions) GetMapEntry() bool { - if m != nil && m.MapEntry != nil { - return *m.MapEntry - } - return false -} - -func (m *MessageOptions) GetUninterpretedOption() []*UninterpretedOption { - if m != nil { - return m.UninterpretedOption - } - return nil -} - -type FieldOptions struct { - // The ctype option instructs the C++ code generator to use a different - // representation of the field than it normally would. See the specific - // options below. This option is not yet implemented in the open source - // release -- sorry, we'll try to include it in a future version! - Ctype *FieldOptions_CType `protobuf:"varint,1,opt,name=ctype,enum=google.protobuf.FieldOptions_CType,def=0" json:"ctype,omitempty"` - // The packed option can be enabled for repeated primitive fields to enable - // a more efficient representation on the wire. Rather than repeatedly - // writing the tag and type for each element, the entire array is encoded as - // a single length-delimited blob. In proto3, only explicit setting it to - // false will avoid using packed encoding. - Packed *bool `protobuf:"varint,2,opt,name=packed" json:"packed,omitempty"` - // The jstype option determines the JavaScript type used for values of the - // field. The option is permitted only for 64 bit integral and fixed types - // (int64, uint64, sint64, fixed64, sfixed64). A field with jstype JS_STRING - // is represented as JavaScript string, which avoids loss of precision that - // can happen when a large value is converted to a floating point JavaScript. - // Specifying JS_NUMBER for the jstype causes the generated JavaScript code to - // use the JavaScript "number" type. The behavior of the default option - // JS_NORMAL is implementation dependent. - // - // This option is an enum to permit additional types to be added, e.g. - // goog.math.Integer. - Jstype *FieldOptions_JSType `protobuf:"varint,6,opt,name=jstype,enum=google.protobuf.FieldOptions_JSType,def=0" json:"jstype,omitempty"` - // Should this field be parsed lazily? Lazy applies only to message-type - // fields. It means that when the outer message is initially parsed, the - // inner message's contents will not be parsed but instead stored in encoded - // form. The inner message will actually be parsed when it is first accessed. - // - // This is only a hint. Implementations are free to choose whether to use - // eager or lazy parsing regardless of the value of this option. However, - // setting this option true suggests that the protocol author believes that - // using lazy parsing on this field is worth the additional bookkeeping - // overhead typically needed to implement it. - // - // This option does not affect the public interface of any generated code; - // all method signatures remain the same. Furthermore, thread-safety of the - // interface is not affected by this option; const methods remain safe to - // call from multiple threads concurrently, while non-const methods continue - // to require exclusive access. - // - // - // Note that implementations may choose not to check required fields within - // a lazy sub-message. That is, calling IsInitialized() on the outer message - // may return true even if the inner message has missing required fields. - // This is necessary because otherwise the inner message would have to be - // parsed in order to perform the check, defeating the purpose of lazy - // parsing. An implementation which chooses not to check required fields - // must be consistent about it. That is, for any particular sub-message, the - // implementation must either *always* check its required fields, or *never* - // check its required fields, regardless of whether or not the message has - // been parsed. - Lazy *bool `protobuf:"varint,5,opt,name=lazy,def=0" json:"lazy,omitempty"` - // Is this field deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for accessors, or it will be completely ignored; in the very least, this - // is a formalization for deprecating fields. - Deprecated *bool `protobuf:"varint,3,opt,name=deprecated,def=0" json:"deprecated,omitempty"` - // For Google-internal migration only. Do not use. - Weak *bool `protobuf:"varint,10,opt,name=weak,def=0" json:"weak,omitempty"` - // The parser stores options it doesn't recognize here. See above. - UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` - proto.XXX_InternalExtensions `json:"-"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *FieldOptions) Reset() { *m = FieldOptions{} } -func (m *FieldOptions) String() string { return proto.CompactTextString(m) } -func (*FieldOptions) ProtoMessage() {} -func (*FieldOptions) Descriptor() ([]byte, []int) { return fileDescriptorDescriptor, []int{12} } - -var extRange_FieldOptions = []proto.ExtensionRange{ - {Start: 1000, End: 536870911}, -} - -func (*FieldOptions) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_FieldOptions -} - -const Default_FieldOptions_Ctype FieldOptions_CType = FieldOptions_STRING -const Default_FieldOptions_Jstype FieldOptions_JSType = FieldOptions_JS_NORMAL -const Default_FieldOptions_Lazy bool = false -const Default_FieldOptions_Deprecated bool = false -const Default_FieldOptions_Weak bool = false - -func (m *FieldOptions) GetCtype() FieldOptions_CType { - if m != nil && m.Ctype != nil { - return *m.Ctype - } - return Default_FieldOptions_Ctype -} - -func (m *FieldOptions) GetPacked() bool { - if m != nil && m.Packed != nil { - return *m.Packed - } - return false -} - -func (m *FieldOptions) GetJstype() FieldOptions_JSType { - if m != nil && m.Jstype != nil { - return *m.Jstype - } - return Default_FieldOptions_Jstype -} - -func (m *FieldOptions) GetLazy() bool { - if m != nil && m.Lazy != nil { - return *m.Lazy - } - return Default_FieldOptions_Lazy -} - -func (m *FieldOptions) GetDeprecated() bool { - if m != nil && m.Deprecated != nil { - return *m.Deprecated - } - return Default_FieldOptions_Deprecated -} - -func (m *FieldOptions) GetWeak() bool { - if m != nil && m.Weak != nil { - return *m.Weak - } - return Default_FieldOptions_Weak -} - -func (m *FieldOptions) GetUninterpretedOption() []*UninterpretedOption { - if m != nil { - return m.UninterpretedOption - } - return nil -} - -type OneofOptions struct { - // The parser stores options it doesn't recognize here. See above. - UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` - proto.XXX_InternalExtensions `json:"-"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *OneofOptions) Reset() { *m = OneofOptions{} } -func (m *OneofOptions) String() string { return proto.CompactTextString(m) } -func (*OneofOptions) ProtoMessage() {} -func (*OneofOptions) Descriptor() ([]byte, []int) { return fileDescriptorDescriptor, []int{13} } - -var extRange_OneofOptions = []proto.ExtensionRange{ - {Start: 1000, End: 536870911}, -} - -func (*OneofOptions) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_OneofOptions -} - -func (m *OneofOptions) GetUninterpretedOption() []*UninterpretedOption { - if m != nil { - return m.UninterpretedOption - } - return nil -} - -type EnumOptions struct { - // Set this option to true to allow mapping different tag names to the same - // value. - AllowAlias *bool `protobuf:"varint,2,opt,name=allow_alias,json=allowAlias" json:"allow_alias,omitempty"` - // Is this enum deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for the enum, or it will be completely ignored; in the very least, this - // is a formalization for deprecating enums. - Deprecated *bool `protobuf:"varint,3,opt,name=deprecated,def=0" json:"deprecated,omitempty"` - // The parser stores options it doesn't recognize here. See above. - UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` - proto.XXX_InternalExtensions `json:"-"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *EnumOptions) Reset() { *m = EnumOptions{} } -func (m *EnumOptions) String() string { return proto.CompactTextString(m) } -func (*EnumOptions) ProtoMessage() {} -func (*EnumOptions) Descriptor() ([]byte, []int) { return fileDescriptorDescriptor, []int{14} } - -var extRange_EnumOptions = []proto.ExtensionRange{ - {Start: 1000, End: 536870911}, -} - -func (*EnumOptions) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_EnumOptions -} - -const Default_EnumOptions_Deprecated bool = false - -func (m *EnumOptions) GetAllowAlias() bool { - if m != nil && m.AllowAlias != nil { - return *m.AllowAlias - } - return false -} - -func (m *EnumOptions) GetDeprecated() bool { - if m != nil && m.Deprecated != nil { - return *m.Deprecated - } - return Default_EnumOptions_Deprecated -} - -func (m *EnumOptions) GetUninterpretedOption() []*UninterpretedOption { - if m != nil { - return m.UninterpretedOption - } - return nil -} - -type EnumValueOptions struct { - // Is this enum value deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for the enum value, or it will be completely ignored; in the very least, - // this is a formalization for deprecating enum values. - Deprecated *bool `protobuf:"varint,1,opt,name=deprecated,def=0" json:"deprecated,omitempty"` - // The parser stores options it doesn't recognize here. See above. - UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` - proto.XXX_InternalExtensions `json:"-"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *EnumValueOptions) Reset() { *m = EnumValueOptions{} } -func (m *EnumValueOptions) String() string { return proto.CompactTextString(m) } -func (*EnumValueOptions) ProtoMessage() {} -func (*EnumValueOptions) Descriptor() ([]byte, []int) { return fileDescriptorDescriptor, []int{15} } - -var extRange_EnumValueOptions = []proto.ExtensionRange{ - {Start: 1000, End: 536870911}, -} - -func (*EnumValueOptions) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_EnumValueOptions -} - -const Default_EnumValueOptions_Deprecated bool = false - -func (m *EnumValueOptions) GetDeprecated() bool { - if m != nil && m.Deprecated != nil { - return *m.Deprecated - } - return Default_EnumValueOptions_Deprecated -} - -func (m *EnumValueOptions) GetUninterpretedOption() []*UninterpretedOption { - if m != nil { - return m.UninterpretedOption - } - return nil -} - -type ServiceOptions struct { - // Is this service deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for the service, or it will be completely ignored; in the very least, - // this is a formalization for deprecating services. - Deprecated *bool `protobuf:"varint,33,opt,name=deprecated,def=0" json:"deprecated,omitempty"` - // The parser stores options it doesn't recognize here. See above. - UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` - proto.XXX_InternalExtensions `json:"-"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *ServiceOptions) Reset() { *m = ServiceOptions{} } -func (m *ServiceOptions) String() string { return proto.CompactTextString(m) } -func (*ServiceOptions) ProtoMessage() {} -func (*ServiceOptions) Descriptor() ([]byte, []int) { return fileDescriptorDescriptor, []int{16} } - -var extRange_ServiceOptions = []proto.ExtensionRange{ - {Start: 1000, End: 536870911}, -} - -func (*ServiceOptions) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_ServiceOptions -} - -const Default_ServiceOptions_Deprecated bool = false - -func (m *ServiceOptions) GetDeprecated() bool { - if m != nil && m.Deprecated != nil { - return *m.Deprecated - } - return Default_ServiceOptions_Deprecated -} - -func (m *ServiceOptions) GetUninterpretedOption() []*UninterpretedOption { - if m != nil { - return m.UninterpretedOption - } - return nil -} - -type MethodOptions struct { - // Is this method deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for the method, or it will be completely ignored; in the very least, - // this is a formalization for deprecating methods. - Deprecated *bool `protobuf:"varint,33,opt,name=deprecated,def=0" json:"deprecated,omitempty"` - IdempotencyLevel *MethodOptions_IdempotencyLevel `protobuf:"varint,34,opt,name=idempotency_level,json=idempotencyLevel,enum=google.protobuf.MethodOptions_IdempotencyLevel,def=0" json:"idempotency_level,omitempty"` - // The parser stores options it doesn't recognize here. See above. - UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` - proto.XXX_InternalExtensions `json:"-"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *MethodOptions) Reset() { *m = MethodOptions{} } -func (m *MethodOptions) String() string { return proto.CompactTextString(m) } -func (*MethodOptions) ProtoMessage() {} -func (*MethodOptions) Descriptor() ([]byte, []int) { return fileDescriptorDescriptor, []int{17} } - -var extRange_MethodOptions = []proto.ExtensionRange{ - {Start: 1000, End: 536870911}, -} - -func (*MethodOptions) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_MethodOptions -} - -const Default_MethodOptions_Deprecated bool = false -const Default_MethodOptions_IdempotencyLevel MethodOptions_IdempotencyLevel = MethodOptions_IDEMPOTENCY_UNKNOWN - -func (m *MethodOptions) GetDeprecated() bool { - if m != nil && m.Deprecated != nil { - return *m.Deprecated - } - return Default_MethodOptions_Deprecated -} - -func (m *MethodOptions) GetIdempotencyLevel() MethodOptions_IdempotencyLevel { - if m != nil && m.IdempotencyLevel != nil { - return *m.IdempotencyLevel - } - return Default_MethodOptions_IdempotencyLevel -} - -func (m *MethodOptions) GetUninterpretedOption() []*UninterpretedOption { - if m != nil { - return m.UninterpretedOption - } - return nil -} - -// A message representing a option the parser does not recognize. This only -// appears in options protos created by the compiler::Parser class. -// DescriptorPool resolves these when building Descriptor objects. Therefore, -// options protos in descriptor objects (e.g. returned by Descriptor::options(), -// or produced by Descriptor::CopyTo()) will never have UninterpretedOptions -// in them. -type UninterpretedOption struct { - Name []*UninterpretedOption_NamePart `protobuf:"bytes,2,rep,name=name" json:"name,omitempty"` - // The value of the uninterpreted option, in whatever type the tokenizer - // identified it as during parsing. Exactly one of these should be set. - IdentifierValue *string `protobuf:"bytes,3,opt,name=identifier_value,json=identifierValue" json:"identifier_value,omitempty"` - PositiveIntValue *uint64 `protobuf:"varint,4,opt,name=positive_int_value,json=positiveIntValue" json:"positive_int_value,omitempty"` - NegativeIntValue *int64 `protobuf:"varint,5,opt,name=negative_int_value,json=negativeIntValue" json:"negative_int_value,omitempty"` - DoubleValue *float64 `protobuf:"fixed64,6,opt,name=double_value,json=doubleValue" json:"double_value,omitempty"` - StringValue []byte `protobuf:"bytes,7,opt,name=string_value,json=stringValue" json:"string_value,omitempty"` - AggregateValue *string `protobuf:"bytes,8,opt,name=aggregate_value,json=aggregateValue" json:"aggregate_value,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *UninterpretedOption) Reset() { *m = UninterpretedOption{} } -func (m *UninterpretedOption) String() string { return proto.CompactTextString(m) } -func (*UninterpretedOption) ProtoMessage() {} -func (*UninterpretedOption) Descriptor() ([]byte, []int) { return fileDescriptorDescriptor, []int{18} } - -func (m *UninterpretedOption) GetName() []*UninterpretedOption_NamePart { - if m != nil { - return m.Name - } - return nil -} - -func (m *UninterpretedOption) GetIdentifierValue() string { - if m != nil && m.IdentifierValue != nil { - return *m.IdentifierValue - } - return "" -} - -func (m *UninterpretedOption) GetPositiveIntValue() uint64 { - if m != nil && m.PositiveIntValue != nil { - return *m.PositiveIntValue - } - return 0 -} - -func (m *UninterpretedOption) GetNegativeIntValue() int64 { - if m != nil && m.NegativeIntValue != nil { - return *m.NegativeIntValue - } - return 0 -} - -func (m *UninterpretedOption) GetDoubleValue() float64 { - if m != nil && m.DoubleValue != nil { - return *m.DoubleValue - } - return 0 -} - -func (m *UninterpretedOption) GetStringValue() []byte { - if m != nil { - return m.StringValue - } - return nil -} - -func (m *UninterpretedOption) GetAggregateValue() string { - if m != nil && m.AggregateValue != nil { - return *m.AggregateValue - } - return "" -} - -// The name of the uninterpreted option. Each string represents a segment in -// a dot-separated name. is_extension is true iff a segment represents an -// extension (denoted with parentheses in options specs in .proto files). -// E.g.,{ ["foo", false], ["bar.baz", true], ["qux", false] } represents -// "foo.(bar.baz).qux". -type UninterpretedOption_NamePart struct { - NamePart *string `protobuf:"bytes,1,req,name=name_part,json=namePart" json:"name_part,omitempty"` - IsExtension *bool `protobuf:"varint,2,req,name=is_extension,json=isExtension" json:"is_extension,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *UninterpretedOption_NamePart) Reset() { *m = UninterpretedOption_NamePart{} } -func (m *UninterpretedOption_NamePart) String() string { return proto.CompactTextString(m) } -func (*UninterpretedOption_NamePart) ProtoMessage() {} -func (*UninterpretedOption_NamePart) Descriptor() ([]byte, []int) { - return fileDescriptorDescriptor, []int{18, 0} -} - -func (m *UninterpretedOption_NamePart) GetNamePart() string { - if m != nil && m.NamePart != nil { - return *m.NamePart - } - return "" -} - -func (m *UninterpretedOption_NamePart) GetIsExtension() bool { - if m != nil && m.IsExtension != nil { - return *m.IsExtension - } - return false -} - -// Encapsulates information about the original source file from which a -// FileDescriptorProto was generated. -type SourceCodeInfo struct { - // A Location identifies a piece of source code in a .proto file which - // corresponds to a particular definition. This information is intended - // to be useful to IDEs, code indexers, documentation generators, and similar - // tools. - // - // For example, say we have a file like: - // message Foo { - // optional string foo = 1; - // } - // Let's look at just the field definition: - // optional string foo = 1; - // ^ ^^ ^^ ^ ^^^ - // a bc de f ghi - // We have the following locations: - // span path represents - // [a,i) [ 4, 0, 2, 0 ] The whole field definition. - // [a,b) [ 4, 0, 2, 0, 4 ] The label (optional). - // [c,d) [ 4, 0, 2, 0, 5 ] The type (string). - // [e,f) [ 4, 0, 2, 0, 1 ] The name (foo). - // [g,h) [ 4, 0, 2, 0, 3 ] The number (1). - // - // Notes: - // - A location may refer to a repeated field itself (i.e. not to any - // particular index within it). This is used whenever a set of elements are - // logically enclosed in a single code segment. For example, an entire - // extend block (possibly containing multiple extension definitions) will - // have an outer location whose path refers to the "extensions" repeated - // field without an index. - // - Multiple locations may have the same path. This happens when a single - // logical declaration is spread out across multiple places. The most - // obvious example is the "extend" block again -- there may be multiple - // extend blocks in the same scope, each of which will have the same path. - // - A location's span is not always a subset of its parent's span. For - // example, the "extendee" of an extension declaration appears at the - // beginning of the "extend" block and is shared by all extensions within - // the block. - // - Just because a location's span is a subset of some other location's span - // does not mean that it is a descendent. For example, a "group" defines - // both a type and a field in a single declaration. Thus, the locations - // corresponding to the type and field and their components will overlap. - // - Code which tries to interpret locations should probably be designed to - // ignore those that it doesn't understand, as more types of locations could - // be recorded in the future. - Location []*SourceCodeInfo_Location `protobuf:"bytes,1,rep,name=location" json:"location,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *SourceCodeInfo) Reset() { *m = SourceCodeInfo{} } -func (m *SourceCodeInfo) String() string { return proto.CompactTextString(m) } -func (*SourceCodeInfo) ProtoMessage() {} -func (*SourceCodeInfo) Descriptor() ([]byte, []int) { return fileDescriptorDescriptor, []int{19} } - -func (m *SourceCodeInfo) GetLocation() []*SourceCodeInfo_Location { - if m != nil { - return m.Location - } - return nil -} - -type SourceCodeInfo_Location struct { - // Identifies which part of the FileDescriptorProto was defined at this - // location. - // - // Each element is a field number or an index. They form a path from - // the root FileDescriptorProto to the place where the definition. For - // example, this path: - // [ 4, 3, 2, 7, 1 ] - // refers to: - // file.message_type(3) // 4, 3 - // .field(7) // 2, 7 - // .name() // 1 - // This is because FileDescriptorProto.message_type has field number 4: - // repeated DescriptorProto message_type = 4; - // and DescriptorProto.field has field number 2: - // repeated FieldDescriptorProto field = 2; - // and FieldDescriptorProto.name has field number 1: - // optional string name = 1; - // - // Thus, the above path gives the location of a field name. If we removed - // the last element: - // [ 4, 3, 2, 7 ] - // this path refers to the whole field declaration (from the beginning - // of the label to the terminating semicolon). - Path []int32 `protobuf:"varint,1,rep,packed,name=path" json:"path,omitempty"` - // Always has exactly three or four elements: start line, start column, - // end line (optional, otherwise assumed same as start line), end column. - // These are packed into a single field for efficiency. Note that line - // and column numbers are zero-based -- typically you will want to add - // 1 to each before displaying to a user. - Span []int32 `protobuf:"varint,2,rep,packed,name=span" json:"span,omitempty"` - // If this SourceCodeInfo represents a complete declaration, these are any - // comments appearing before and after the declaration which appear to be - // attached to the declaration. - // - // A series of line comments appearing on consecutive lines, with no other - // tokens appearing on those lines, will be treated as a single comment. - // - // leading_detached_comments will keep paragraphs of comments that appear - // before (but not connected to) the current element. Each paragraph, - // separated by empty lines, will be one comment element in the repeated - // field. - // - // Only the comment content is provided; comment markers (e.g. //) are - // stripped out. For block comments, leading whitespace and an asterisk - // will be stripped from the beginning of each line other than the first. - // Newlines are included in the output. - // - // Examples: - // - // optional int32 foo = 1; // Comment attached to foo. - // // Comment attached to bar. - // optional int32 bar = 2; - // - // optional string baz = 3; - // // Comment attached to baz. - // // Another line attached to baz. - // - // // Comment attached to qux. - // // - // // Another line attached to qux. - // optional double qux = 4; - // - // // Detached comment for corge. This is not leading or trailing comments - // // to qux or corge because there are blank lines separating it from - // // both. - // - // // Detached comment for corge paragraph 2. - // - // optional string corge = 5; - // /* Block comment attached - // * to corge. Leading asterisks - // * will be removed. */ - // /* Block comment attached to - // * grault. */ - // optional int32 grault = 6; - // - // // ignored detached comments. - LeadingComments *string `protobuf:"bytes,3,opt,name=leading_comments,json=leadingComments" json:"leading_comments,omitempty"` - TrailingComments *string `protobuf:"bytes,4,opt,name=trailing_comments,json=trailingComments" json:"trailing_comments,omitempty"` - LeadingDetachedComments []string `protobuf:"bytes,6,rep,name=leading_detached_comments,json=leadingDetachedComments" json:"leading_detached_comments,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *SourceCodeInfo_Location) Reset() { *m = SourceCodeInfo_Location{} } -func (m *SourceCodeInfo_Location) String() string { return proto.CompactTextString(m) } -func (*SourceCodeInfo_Location) ProtoMessage() {} -func (*SourceCodeInfo_Location) Descriptor() ([]byte, []int) { - return fileDescriptorDescriptor, []int{19, 0} -} - -func (m *SourceCodeInfo_Location) GetPath() []int32 { - if m != nil { - return m.Path - } - return nil -} - -func (m *SourceCodeInfo_Location) GetSpan() []int32 { - if m != nil { - return m.Span - } - return nil -} - -func (m *SourceCodeInfo_Location) GetLeadingComments() string { - if m != nil && m.LeadingComments != nil { - return *m.LeadingComments - } - return "" -} - -func (m *SourceCodeInfo_Location) GetTrailingComments() string { - if m != nil && m.TrailingComments != nil { - return *m.TrailingComments - } - return "" -} - -func (m *SourceCodeInfo_Location) GetLeadingDetachedComments() []string { - if m != nil { - return m.LeadingDetachedComments - } - return nil -} - -// Describes the relationship between generated code and its original source -// file. A GeneratedCodeInfo message is associated with only one generated -// source file, but may contain references to different source .proto files. -type GeneratedCodeInfo struct { - // An Annotation connects some span of text in generated code to an element - // of its generating .proto file. - Annotation []*GeneratedCodeInfo_Annotation `protobuf:"bytes,1,rep,name=annotation" json:"annotation,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GeneratedCodeInfo) Reset() { *m = GeneratedCodeInfo{} } -func (m *GeneratedCodeInfo) String() string { return proto.CompactTextString(m) } -func (*GeneratedCodeInfo) ProtoMessage() {} -func (*GeneratedCodeInfo) Descriptor() ([]byte, []int) { return fileDescriptorDescriptor, []int{20} } - -func (m *GeneratedCodeInfo) GetAnnotation() []*GeneratedCodeInfo_Annotation { - if m != nil { - return m.Annotation - } - return nil -} - -type GeneratedCodeInfo_Annotation struct { - // Identifies the element in the original source .proto file. This field - // is formatted the same as SourceCodeInfo.Location.path. - Path []int32 `protobuf:"varint,1,rep,packed,name=path" json:"path,omitempty"` - // Identifies the filesystem path to the original source .proto. - SourceFile *string `protobuf:"bytes,2,opt,name=source_file,json=sourceFile" json:"source_file,omitempty"` - // Identifies the starting offset in bytes in the generated code - // that relates to the identified object. - Begin *int32 `protobuf:"varint,3,opt,name=begin" json:"begin,omitempty"` - // Identifies the ending offset in bytes in the generated code that - // relates to the identified offset. The end offset should be one past - // the last relevant byte (so the length of the text = end - begin). - End *int32 `protobuf:"varint,4,opt,name=end" json:"end,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GeneratedCodeInfo_Annotation) Reset() { *m = GeneratedCodeInfo_Annotation{} } -func (m *GeneratedCodeInfo_Annotation) String() string { return proto.CompactTextString(m) } -func (*GeneratedCodeInfo_Annotation) ProtoMessage() {} -func (*GeneratedCodeInfo_Annotation) Descriptor() ([]byte, []int) { - return fileDescriptorDescriptor, []int{20, 0} -} - -func (m *GeneratedCodeInfo_Annotation) GetPath() []int32 { - if m != nil { - return m.Path - } - return nil -} - -func (m *GeneratedCodeInfo_Annotation) GetSourceFile() string { - if m != nil && m.SourceFile != nil { - return *m.SourceFile - } - return "" -} - -func (m *GeneratedCodeInfo_Annotation) GetBegin() int32 { - if m != nil && m.Begin != nil { - return *m.Begin - } - return 0 -} - -func (m *GeneratedCodeInfo_Annotation) GetEnd() int32 { - if m != nil && m.End != nil { - return *m.End - } - return 0 -} - -func init() { - proto.RegisterType((*FileDescriptorSet)(nil), "google.protobuf.FileDescriptorSet") - proto.RegisterType((*FileDescriptorProto)(nil), "google.protobuf.FileDescriptorProto") - proto.RegisterType((*DescriptorProto)(nil), "google.protobuf.DescriptorProto") - proto.RegisterType((*DescriptorProto_ExtensionRange)(nil), "google.protobuf.DescriptorProto.ExtensionRange") - proto.RegisterType((*DescriptorProto_ReservedRange)(nil), "google.protobuf.DescriptorProto.ReservedRange") - proto.RegisterType((*ExtensionRangeOptions)(nil), "google.protobuf.ExtensionRangeOptions") - proto.RegisterType((*FieldDescriptorProto)(nil), "google.protobuf.FieldDescriptorProto") - proto.RegisterType((*OneofDescriptorProto)(nil), "google.protobuf.OneofDescriptorProto") - proto.RegisterType((*EnumDescriptorProto)(nil), "google.protobuf.EnumDescriptorProto") - proto.RegisterType((*EnumValueDescriptorProto)(nil), "google.protobuf.EnumValueDescriptorProto") - proto.RegisterType((*ServiceDescriptorProto)(nil), "google.protobuf.ServiceDescriptorProto") - proto.RegisterType((*MethodDescriptorProto)(nil), "google.protobuf.MethodDescriptorProto") - proto.RegisterType((*FileOptions)(nil), "google.protobuf.FileOptions") - proto.RegisterType((*MessageOptions)(nil), "google.protobuf.MessageOptions") - proto.RegisterType((*FieldOptions)(nil), "google.protobuf.FieldOptions") - proto.RegisterType((*OneofOptions)(nil), "google.protobuf.OneofOptions") - proto.RegisterType((*EnumOptions)(nil), "google.protobuf.EnumOptions") - proto.RegisterType((*EnumValueOptions)(nil), "google.protobuf.EnumValueOptions") - proto.RegisterType((*ServiceOptions)(nil), "google.protobuf.ServiceOptions") - proto.RegisterType((*MethodOptions)(nil), "google.protobuf.MethodOptions") - proto.RegisterType((*UninterpretedOption)(nil), "google.protobuf.UninterpretedOption") - proto.RegisterType((*UninterpretedOption_NamePart)(nil), "google.protobuf.UninterpretedOption.NamePart") - proto.RegisterType((*SourceCodeInfo)(nil), "google.protobuf.SourceCodeInfo") - proto.RegisterType((*SourceCodeInfo_Location)(nil), "google.protobuf.SourceCodeInfo.Location") - proto.RegisterType((*GeneratedCodeInfo)(nil), "google.protobuf.GeneratedCodeInfo") - proto.RegisterType((*GeneratedCodeInfo_Annotation)(nil), "google.protobuf.GeneratedCodeInfo.Annotation") - proto.RegisterEnum("google.protobuf.FieldDescriptorProto_Type", FieldDescriptorProto_Type_name, FieldDescriptorProto_Type_value) - proto.RegisterEnum("google.protobuf.FieldDescriptorProto_Label", FieldDescriptorProto_Label_name, FieldDescriptorProto_Label_value) - proto.RegisterEnum("google.protobuf.FileOptions_OptimizeMode", FileOptions_OptimizeMode_name, FileOptions_OptimizeMode_value) - proto.RegisterEnum("google.protobuf.FieldOptions_CType", FieldOptions_CType_name, FieldOptions_CType_value) - proto.RegisterEnum("google.protobuf.FieldOptions_JSType", FieldOptions_JSType_name, FieldOptions_JSType_value) - proto.RegisterEnum("google.protobuf.MethodOptions_IdempotencyLevel", MethodOptions_IdempotencyLevel_name, MethodOptions_IdempotencyLevel_value) -} - -func init() { proto.RegisterFile("descriptor.proto", fileDescriptorDescriptor) } - -var fileDescriptorDescriptor = []byte{ - // 2451 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xc4, 0x59, 0xcd, 0x6f, 0xdb, 0xc8, - 0x15, 0x5f, 0x7d, 0x5a, 0x7a, 0x92, 0xe5, 0xf1, 0xd8, 0x9b, 0x30, 0xce, 0x66, 0xe3, 0x28, 0xc9, - 0xc6, 0x49, 0x5a, 0x65, 0xe1, 0x7c, 0xae, 0xb7, 0xd8, 0x56, 0x96, 0x18, 0xaf, 0x52, 0x59, 0x52, - 0x29, 0xb9, 0x9b, 0xec, 0x85, 0x18, 0x93, 0x23, 0x89, 0x09, 0x45, 0x72, 0x49, 0x2a, 0x89, 0x83, - 0x1e, 0x02, 0xf4, 0xd4, 0xff, 0xa0, 0x28, 0x8a, 0x1e, 0xf6, 0xb2, 0x40, 0xaf, 0x05, 0x0a, 0xb4, - 0xf7, 0x5e, 0x0b, 0xf4, 0xde, 0x43, 0x0f, 0x05, 0xda, 0x3f, 0xa3, 0x98, 0x19, 0x92, 0xa2, 0xbe, - 0x12, 0x77, 0x81, 0x64, 0x4f, 0xf6, 0xfc, 0xde, 0xef, 0xbd, 0x79, 0xf3, 0xf8, 0x66, 0xde, 0x9b, - 0x11, 0x20, 0x9d, 0x7a, 0x9a, 0x6b, 0x38, 0xbe, 0xed, 0x56, 0x1c, 0xd7, 0xf6, 0x6d, 0xbc, 0x36, - 0xb0, 0xed, 0x81, 0x49, 0xc5, 0xe8, 0x78, 0xdc, 0x2f, 0x1f, 0xc2, 0xfa, 0x43, 0xc3, 0xa4, 0xf5, - 0x88, 0xd8, 0xa5, 0x3e, 0x7e, 0x00, 0xe9, 0xbe, 0x61, 0x52, 0x29, 0xb1, 0x9d, 0xda, 0x29, 0xec, - 0x5e, 0xa9, 0xcc, 0x28, 0x55, 0xa6, 0x35, 0x3a, 0x0c, 0x56, 0xb8, 0x46, 0xf9, 0xdf, 0x69, 0xd8, - 0x58, 0x20, 0xc5, 0x18, 0xd2, 0x16, 0x19, 0x31, 0x8b, 0x89, 0x9d, 0xbc, 0xc2, 0xff, 0xc7, 0x12, - 0xac, 0x38, 0x44, 0x7b, 0x46, 0x06, 0x54, 0x4a, 0x72, 0x38, 0x1c, 0xe2, 0x8f, 0x01, 0x74, 0xea, - 0x50, 0x4b, 0xa7, 0x96, 0x76, 0x22, 0xa5, 0xb6, 0x53, 0x3b, 0x79, 0x25, 0x86, 0xe0, 0x9b, 0xb0, - 0xee, 0x8c, 0x8f, 0x4d, 0x43, 0x53, 0x63, 0x34, 0xd8, 0x4e, 0xed, 0x64, 0x14, 0x24, 0x04, 0xf5, - 0x09, 0xf9, 0x1a, 0xac, 0xbd, 0xa0, 0xe4, 0x59, 0x9c, 0x5a, 0xe0, 0xd4, 0x12, 0x83, 0x63, 0xc4, - 0x1a, 0x14, 0x47, 0xd4, 0xf3, 0xc8, 0x80, 0xaa, 0xfe, 0x89, 0x43, 0xa5, 0x34, 0x5f, 0xfd, 0xf6, - 0xdc, 0xea, 0x67, 0x57, 0x5e, 0x08, 0xb4, 0x7a, 0x27, 0x0e, 0xc5, 0x55, 0xc8, 0x53, 0x6b, 0x3c, - 0x12, 0x16, 0x32, 0x4b, 0xe2, 0x27, 0x5b, 0xe3, 0xd1, 0xac, 0x95, 0x1c, 0x53, 0x0b, 0x4c, 0xac, - 0x78, 0xd4, 0x7d, 0x6e, 0x68, 0x54, 0xca, 0x72, 0x03, 0xd7, 0xe6, 0x0c, 0x74, 0x85, 0x7c, 0xd6, - 0x46, 0xa8, 0x87, 0x6b, 0x90, 0xa7, 0x2f, 0x7d, 0x6a, 0x79, 0x86, 0x6d, 0x49, 0x2b, 0xdc, 0xc8, - 0xd5, 0x05, 0x5f, 0x91, 0x9a, 0xfa, 0xac, 0x89, 0x89, 0x1e, 0xbe, 0x07, 0x2b, 0xb6, 0xe3, 0x1b, - 0xb6, 0xe5, 0x49, 0xb9, 0xed, 0xc4, 0x4e, 0x61, 0xf7, 0xa3, 0x85, 0x89, 0xd0, 0x16, 0x1c, 0x25, - 0x24, 0xe3, 0x06, 0x20, 0xcf, 0x1e, 0xbb, 0x1a, 0x55, 0x35, 0x5b, 0xa7, 0xaa, 0x61, 0xf5, 0x6d, - 0x29, 0xcf, 0x0d, 0x5c, 0x9c, 0x5f, 0x08, 0x27, 0xd6, 0x6c, 0x9d, 0x36, 0xac, 0xbe, 0xad, 0x94, - 0xbc, 0xa9, 0x31, 0x3e, 0x03, 0x59, 0xef, 0xc4, 0xf2, 0xc9, 0x4b, 0xa9, 0xc8, 0x33, 0x24, 0x18, - 0x95, 0xff, 0x92, 0x85, 0xb5, 0xd3, 0xa4, 0xd8, 0xe7, 0x90, 0xe9, 0xb3, 0x55, 0x4a, 0xc9, 0xff, - 0x27, 0x06, 0x42, 0x67, 0x3a, 0x88, 0xd9, 0xef, 0x19, 0xc4, 0x2a, 0x14, 0x2c, 0xea, 0xf9, 0x54, - 0x17, 0x19, 0x91, 0x3a, 0x65, 0x4e, 0x81, 0x50, 0x9a, 0x4f, 0xa9, 0xf4, 0xf7, 0x4a, 0xa9, 0xc7, - 0xb0, 0x16, 0xb9, 0xa4, 0xba, 0xc4, 0x1a, 0x84, 0xb9, 0x79, 0xeb, 0x6d, 0x9e, 0x54, 0xe4, 0x50, - 0x4f, 0x61, 0x6a, 0x4a, 0x89, 0x4e, 0x8d, 0x71, 0x1d, 0xc0, 0xb6, 0xa8, 0xdd, 0x57, 0x75, 0xaa, - 0x99, 0x52, 0x6e, 0x49, 0x94, 0xda, 0x8c, 0x32, 0x17, 0x25, 0x5b, 0xa0, 0x9a, 0x89, 0x3f, 0x9b, - 0xa4, 0xda, 0xca, 0x92, 0x4c, 0x39, 0x14, 0x9b, 0x6c, 0x2e, 0xdb, 0x8e, 0xa0, 0xe4, 0x52, 0x96, - 0xf7, 0x54, 0x0f, 0x56, 0x96, 0xe7, 0x4e, 0x54, 0xde, 0xba, 0x32, 0x25, 0x50, 0x13, 0x0b, 0x5b, - 0x75, 0xe3, 0x43, 0x7c, 0x19, 0x22, 0x40, 0xe5, 0x69, 0x05, 0xfc, 0x14, 0x2a, 0x86, 0x60, 0x8b, - 0x8c, 0xe8, 0xd6, 0x2b, 0x28, 0x4d, 0x87, 0x07, 0x6f, 0x42, 0xc6, 0xf3, 0x89, 0xeb, 0xf3, 0x2c, - 0xcc, 0x28, 0x62, 0x80, 0x11, 0xa4, 0xa8, 0xa5, 0xf3, 0x53, 0x2e, 0xa3, 0xb0, 0x7f, 0xf1, 0xcf, - 0x26, 0x0b, 0x4e, 0xf1, 0x05, 0x7f, 0x32, 0xff, 0x45, 0xa7, 0x2c, 0xcf, 0xae, 0x7b, 0xeb, 0x3e, - 0xac, 0x4e, 0x2d, 0xe0, 0xb4, 0x53, 0x97, 0x7f, 0x05, 0x1f, 0x2e, 0x34, 0x8d, 0x1f, 0xc3, 0xe6, - 0xd8, 0x32, 0x2c, 0x9f, 0xba, 0x8e, 0x4b, 0x59, 0xc6, 0x8a, 0xa9, 0xa4, 0xff, 0xac, 0x2c, 0xc9, - 0xb9, 0xa3, 0x38, 0x5b, 0x58, 0x51, 0x36, 0xc6, 0xf3, 0xe0, 0x8d, 0x7c, 0xee, 0xbf, 0x2b, 0xe8, - 0xf5, 0xeb, 0xd7, 0xaf, 0x93, 0xe5, 0xdf, 0x66, 0x61, 0x73, 0xd1, 0x9e, 0x59, 0xb8, 0x7d, 0xcf, - 0x40, 0xd6, 0x1a, 0x8f, 0x8e, 0xa9, 0xcb, 0x83, 0x94, 0x51, 0x82, 0x11, 0xae, 0x42, 0xc6, 0x24, - 0xc7, 0xd4, 0x94, 0xd2, 0xdb, 0x89, 0x9d, 0xd2, 0xee, 0xcd, 0x53, 0xed, 0xca, 0x4a, 0x93, 0xa9, - 0x28, 0x42, 0x13, 0x7f, 0x01, 0xe9, 0xe0, 0x88, 0x66, 0x16, 0x6e, 0x9c, 0xce, 0x02, 0xdb, 0x4b, - 0x0a, 0xd7, 0xc3, 0xe7, 0x21, 0xcf, 0xfe, 0x8a, 0xdc, 0xc8, 0x72, 0x9f, 0x73, 0x0c, 0x60, 0x79, - 0x81, 0xb7, 0x20, 0xc7, 0xb7, 0x89, 0x4e, 0xc3, 0xd2, 0x16, 0x8d, 0x59, 0x62, 0xe9, 0xb4, 0x4f, - 0xc6, 0xa6, 0xaf, 0x3e, 0x27, 0xe6, 0x98, 0xf2, 0x84, 0xcf, 0x2b, 0xc5, 0x00, 0xfc, 0x25, 0xc3, - 0xf0, 0x45, 0x28, 0x88, 0x5d, 0x65, 0x58, 0x3a, 0x7d, 0xc9, 0x4f, 0xcf, 0x8c, 0x22, 0x36, 0x5a, - 0x83, 0x21, 0x6c, 0xfa, 0xa7, 0x9e, 0x6d, 0x85, 0xa9, 0xc9, 0xa7, 0x60, 0x00, 0x9f, 0xfe, 0xfe, - 0xec, 0xc1, 0x7d, 0x61, 0xf1, 0xf2, 0x66, 0x73, 0xaa, 0xfc, 0xe7, 0x24, 0xa4, 0xf9, 0x79, 0xb1, - 0x06, 0x85, 0xde, 0x93, 0x8e, 0xac, 0xd6, 0xdb, 0x47, 0xfb, 0x4d, 0x19, 0x25, 0x70, 0x09, 0x80, - 0x03, 0x0f, 0x9b, 0xed, 0x6a, 0x0f, 0x25, 0xa3, 0x71, 0xa3, 0xd5, 0xbb, 0x77, 0x07, 0xa5, 0x22, - 0x85, 0x23, 0x01, 0xa4, 0xe3, 0x84, 0xdb, 0xbb, 0x28, 0x83, 0x11, 0x14, 0x85, 0x81, 0xc6, 0x63, - 0xb9, 0x7e, 0xef, 0x0e, 0xca, 0x4e, 0x23, 0xb7, 0x77, 0xd1, 0x0a, 0x5e, 0x85, 0x3c, 0x47, 0xf6, - 0xdb, 0xed, 0x26, 0xca, 0x45, 0x36, 0xbb, 0x3d, 0xa5, 0xd1, 0x3a, 0x40, 0xf9, 0xc8, 0xe6, 0x81, - 0xd2, 0x3e, 0xea, 0x20, 0x88, 0x2c, 0x1c, 0xca, 0xdd, 0x6e, 0xf5, 0x40, 0x46, 0x85, 0x88, 0xb1, - 0xff, 0xa4, 0x27, 0x77, 0x51, 0x71, 0xca, 0xad, 0xdb, 0xbb, 0x68, 0x35, 0x9a, 0x42, 0x6e, 0x1d, - 0x1d, 0xa2, 0x12, 0x5e, 0x87, 0x55, 0x31, 0x45, 0xe8, 0xc4, 0xda, 0x0c, 0x74, 0xef, 0x0e, 0x42, - 0x13, 0x47, 0x84, 0x95, 0xf5, 0x29, 0xe0, 0xde, 0x1d, 0x84, 0xcb, 0x35, 0xc8, 0xf0, 0xec, 0xc2, - 0x18, 0x4a, 0xcd, 0xea, 0xbe, 0xdc, 0x54, 0xdb, 0x9d, 0x5e, 0xa3, 0xdd, 0xaa, 0x36, 0x51, 0x62, - 0x82, 0x29, 0xf2, 0x2f, 0x8e, 0x1a, 0x8a, 0x5c, 0x47, 0xc9, 0x38, 0xd6, 0x91, 0xab, 0x3d, 0xb9, - 0x8e, 0x52, 0x65, 0x0d, 0x36, 0x17, 0x9d, 0x93, 0x0b, 0x77, 0x46, 0xec, 0x13, 0x27, 0x97, 0x7c, - 0x62, 0x6e, 0x6b, 0xee, 0x13, 0x7f, 0x9b, 0x80, 0x8d, 0x05, 0xb5, 0x62, 0xe1, 0x24, 0x3f, 0x85, - 0x8c, 0x48, 0x51, 0x51, 0x3d, 0xaf, 0x2f, 0x2c, 0x3a, 0x3c, 0x61, 0xe7, 0x2a, 0x28, 0xd7, 0x8b, - 0x77, 0x10, 0xa9, 0x25, 0x1d, 0x04, 0x33, 0x31, 0xe7, 0xe4, 0xaf, 0x13, 0x20, 0x2d, 0xb3, 0xfd, - 0x96, 0x83, 0x22, 0x39, 0x75, 0x50, 0x7c, 0x3e, 0xeb, 0xc0, 0xa5, 0xe5, 0x6b, 0x98, 0xf3, 0xe2, - 0xbb, 0x04, 0x9c, 0x59, 0xdc, 0x68, 0x2d, 0xf4, 0xe1, 0x0b, 0xc8, 0x8e, 0xa8, 0x3f, 0xb4, 0xc3, - 0x66, 0xe3, 0x93, 0x05, 0x25, 0x8c, 0x89, 0x67, 0x63, 0x15, 0x68, 0xc5, 0x6b, 0x60, 0x6a, 0x59, - 0xb7, 0x24, 0xbc, 0x99, 0xf3, 0xf4, 0x37, 0x49, 0xf8, 0x70, 0xa1, 0xf1, 0x85, 0x8e, 0x5e, 0x00, - 0x30, 0x2c, 0x67, 0xec, 0x8b, 0x86, 0x42, 0x9c, 0x4f, 0x79, 0x8e, 0xf0, 0xbd, 0xcf, 0xce, 0x9e, - 0xb1, 0x1f, 0xc9, 0x53, 0x5c, 0x0e, 0x02, 0xe2, 0x84, 0x07, 0x13, 0x47, 0xd3, 0xdc, 0xd1, 0x8f, - 0x97, 0xac, 0x74, 0xae, 0x56, 0x7f, 0x0a, 0x48, 0x33, 0x0d, 0x6a, 0xf9, 0xaa, 0xe7, 0xbb, 0x94, - 0x8c, 0x0c, 0x6b, 0xc0, 0x0f, 0xe0, 0xdc, 0x5e, 0xa6, 0x4f, 0x4c, 0x8f, 0x2a, 0x6b, 0x42, 0xdc, - 0x0d, 0xa5, 0x4c, 0x83, 0xd7, 0x38, 0x37, 0xa6, 0x91, 0x9d, 0xd2, 0x10, 0xe2, 0x48, 0xa3, 0xfc, - 0xa7, 0x1c, 0x14, 0x62, 0x6d, 0x29, 0xbe, 0x04, 0xc5, 0xa7, 0xe4, 0x39, 0x51, 0xc3, 0xab, 0x86, - 0x88, 0x44, 0x81, 0x61, 0x9d, 0xe0, 0xba, 0xf1, 0x29, 0x6c, 0x72, 0x8a, 0x3d, 0xf6, 0xa9, 0xab, - 0x6a, 0x26, 0xf1, 0x3c, 0x1e, 0xb4, 0x1c, 0xa7, 0x62, 0x26, 0x6b, 0x33, 0x51, 0x2d, 0x94, 0xe0, - 0xbb, 0xb0, 0xc1, 0x35, 0x46, 0x63, 0xd3, 0x37, 0x1c, 0x93, 0xaa, 0xec, 0xf2, 0xe3, 0xf1, 0x83, - 0x38, 0xf2, 0x6c, 0x9d, 0x31, 0x0e, 0x03, 0x02, 0xf3, 0xc8, 0xc3, 0x75, 0xb8, 0xc0, 0xd5, 0x06, - 0xd4, 0xa2, 0x2e, 0xf1, 0xa9, 0x4a, 0xbf, 0x19, 0x13, 0xd3, 0x53, 0x89, 0xa5, 0xab, 0x43, 0xe2, - 0x0d, 0xa5, 0x4d, 0x66, 0x60, 0x3f, 0x29, 0x25, 0x94, 0x73, 0x8c, 0x78, 0x10, 0xf0, 0x64, 0x4e, - 0xab, 0x5a, 0xfa, 0x97, 0xc4, 0x1b, 0xe2, 0x3d, 0x38, 0xc3, 0xad, 0x78, 0xbe, 0x6b, 0x58, 0x03, - 0x55, 0x1b, 0x52, 0xed, 0x99, 0x3a, 0xf6, 0xfb, 0x0f, 0xa4, 0xf3, 0xf1, 0xf9, 0xb9, 0x87, 0x5d, - 0xce, 0xa9, 0x31, 0xca, 0x91, 0xdf, 0x7f, 0x80, 0xbb, 0x50, 0x64, 0x1f, 0x63, 0x64, 0xbc, 0xa2, - 0x6a, 0xdf, 0x76, 0x79, 0x65, 0x29, 0x2d, 0xd8, 0xd9, 0xb1, 0x08, 0x56, 0xda, 0x81, 0xc2, 0xa1, - 0xad, 0xd3, 0xbd, 0x4c, 0xb7, 0x23, 0xcb, 0x75, 0xa5, 0x10, 0x5a, 0x79, 0x68, 0xbb, 0x2c, 0xa1, - 0x06, 0x76, 0x14, 0xe0, 0x82, 0x48, 0xa8, 0x81, 0x1d, 0x86, 0xf7, 0x2e, 0x6c, 0x68, 0x9a, 0x58, - 0xb3, 0xa1, 0xa9, 0xc1, 0x15, 0xc5, 0x93, 0xd0, 0x54, 0xb0, 0x34, 0xed, 0x40, 0x10, 0x82, 0x1c, - 0xf7, 0xf0, 0x67, 0xf0, 0xe1, 0x24, 0x58, 0x71, 0xc5, 0xf5, 0xb9, 0x55, 0xce, 0xaa, 0xde, 0x85, - 0x0d, 0xe7, 0x64, 0x5e, 0x11, 0x4f, 0xcd, 0xe8, 0x9c, 0xcc, 0xaa, 0xdd, 0x87, 0x4d, 0x67, 0xe8, - 0xcc, 0xeb, 0x6d, 0xc4, 0xf5, 0xb0, 0x33, 0x74, 0x66, 0x15, 0xaf, 0xf2, 0xfb, 0xaa, 0x4b, 0x35, - 0xe2, 0x53, 0x5d, 0x3a, 0x1b, 0xa7, 0xc7, 0x04, 0xf8, 0x16, 0x20, 0x4d, 0x53, 0xa9, 0x45, 0x8e, - 0x4d, 0xaa, 0x12, 0x97, 0x5a, 0xc4, 0x93, 0x2e, 0xc6, 0xc9, 0x25, 0x4d, 0x93, 0xb9, 0xb4, 0xca, - 0x85, 0xf8, 0x06, 0xac, 0xdb, 0xc7, 0x4f, 0x35, 0x91, 0x92, 0xaa, 0xe3, 0xd2, 0xbe, 0xf1, 0x52, - 0xba, 0xc2, 0xe3, 0xbb, 0xc6, 0x04, 0x3c, 0x21, 0x3b, 0x1c, 0xc6, 0xd7, 0x01, 0x69, 0xde, 0x90, - 0xb8, 0x0e, 0xef, 0x09, 0x3c, 0x87, 0x68, 0x54, 0xba, 0x2a, 0xa8, 0x02, 0x6f, 0x85, 0x30, 0xdb, - 0x12, 0xde, 0x0b, 0xa3, 0xef, 0x87, 0x16, 0xaf, 0x89, 0x2d, 0xc1, 0xb1, 0xc0, 0xda, 0x0e, 0x20, - 0x16, 0x8a, 0xa9, 0x89, 0x77, 0x38, 0xad, 0xe4, 0x0c, 0x9d, 0xf8, 0xbc, 0x97, 0x61, 0x95, 0x31, - 0x27, 0x93, 0x5e, 0x17, 0xfd, 0x8c, 0x33, 0x8c, 0xcd, 0xf8, 0xce, 0x5a, 0xcb, 0xf2, 0x1e, 0x14, - 0xe3, 0xf9, 0x89, 0xf3, 0x20, 0x32, 0x14, 0x25, 0x58, 0xad, 0xaf, 0xb5, 0xeb, 0xac, 0x4a, 0x7f, - 0x2d, 0xa3, 0x24, 0xeb, 0x16, 0x9a, 0x8d, 0x9e, 0xac, 0x2a, 0x47, 0xad, 0x5e, 0xe3, 0x50, 0x46, - 0xa9, 0x78, 0x5b, 0xfa, 0xb7, 0x24, 0x94, 0xa6, 0x6f, 0x18, 0xf8, 0x27, 0x70, 0x36, 0x7c, 0x0e, - 0xf0, 0xa8, 0xaf, 0xbe, 0x30, 0x5c, 0xbe, 0x65, 0x46, 0x44, 0x74, 0xd8, 0xd1, 0x47, 0xdb, 0x0c, - 0x58, 0x5d, 0xea, 0x7f, 0x65, 0xb8, 0x6c, 0x43, 0x8c, 0x88, 0x8f, 0x9b, 0x70, 0xd1, 0xb2, 0x55, - 0xcf, 0x27, 0x96, 0x4e, 0x5c, 0x5d, 0x9d, 0x3c, 0xc4, 0xa8, 0x44, 0xd3, 0xa8, 0xe7, 0xd9, 0xa2, - 0x54, 0x45, 0x56, 0x3e, 0xb2, 0xec, 0x6e, 0x40, 0x9e, 0x9c, 0xe1, 0xd5, 0x80, 0x3a, 0x93, 0x60, - 0xa9, 0x65, 0x09, 0x76, 0x1e, 0xf2, 0x23, 0xe2, 0xa8, 0xd4, 0xf2, 0xdd, 0x13, 0xde, 0x57, 0xe6, - 0x94, 0xdc, 0x88, 0x38, 0x32, 0x1b, 0xbf, 0x9f, 0xf6, 0xfe, 0x9f, 0x29, 0x28, 0xc6, 0x7b, 0x4b, - 0xd6, 0xaa, 0x6b, 0xbc, 0x8e, 0x24, 0xf8, 0x49, 0x73, 0xf9, 0x8d, 0x9d, 0x68, 0xa5, 0xc6, 0x0a, - 0xcc, 0x5e, 0x56, 0x74, 0x7c, 0x8a, 0xd0, 0x64, 0xc5, 0x9d, 0x9d, 0x2d, 0x54, 0xdc, 0x62, 0x72, - 0x4a, 0x30, 0xc2, 0x07, 0x90, 0x7d, 0xea, 0x71, 0xdb, 0x59, 0x6e, 0xfb, 0xca, 0x9b, 0x6d, 0x3f, - 0xea, 0x72, 0xe3, 0xf9, 0x47, 0x5d, 0xb5, 0xd5, 0x56, 0x0e, 0xab, 0x4d, 0x25, 0x50, 0xc7, 0xe7, - 0x20, 0x6d, 0x92, 0x57, 0x27, 0xd3, 0xa5, 0x88, 0x43, 0xa7, 0x0d, 0xfc, 0x39, 0x48, 0xbf, 0xa0, - 0xe4, 0xd9, 0x74, 0x01, 0xe0, 0xd0, 0x3b, 0x4c, 0xfd, 0x5b, 0x90, 0xe1, 0xf1, 0xc2, 0x00, 0x41, - 0xc4, 0xd0, 0x07, 0x38, 0x07, 0xe9, 0x5a, 0x5b, 0x61, 0xe9, 0x8f, 0xa0, 0x28, 0x50, 0xb5, 0xd3, - 0x90, 0x6b, 0x32, 0x4a, 0x96, 0xef, 0x42, 0x56, 0x04, 0x81, 0x6d, 0x8d, 0x28, 0x0c, 0xe8, 0x83, - 0x60, 0x18, 0xd8, 0x48, 0x84, 0xd2, 0xa3, 0xc3, 0x7d, 0x59, 0x41, 0xc9, 0xf8, 0xe7, 0xf5, 0xa0, - 0x18, 0x6f, 0x2b, 0xdf, 0x4f, 0x4e, 0xfd, 0x35, 0x01, 0x85, 0x58, 0x9b, 0xc8, 0x1a, 0x14, 0x62, - 0x9a, 0xf6, 0x0b, 0x95, 0x98, 0x06, 0xf1, 0x82, 0xa4, 0x00, 0x0e, 0x55, 0x19, 0x72, 0xda, 0x8f, - 0xf6, 0x5e, 0x9c, 0xff, 0x43, 0x02, 0xd0, 0x6c, 0x8b, 0x39, 0xe3, 0x60, 0xe2, 0x07, 0x75, 0xf0, - 0xf7, 0x09, 0x28, 0x4d, 0xf7, 0x95, 0x33, 0xee, 0x5d, 0xfa, 0x41, 0xdd, 0xfb, 0x57, 0x12, 0x56, - 0xa7, 0xba, 0xc9, 0xd3, 0x7a, 0xf7, 0x0d, 0xac, 0x1b, 0x3a, 0x1d, 0x39, 0xb6, 0x4f, 0x2d, 0xed, - 0x44, 0x35, 0xe9, 0x73, 0x6a, 0x4a, 0x65, 0x7e, 0x50, 0xdc, 0x7a, 0x73, 0xbf, 0x5a, 0x69, 0x4c, - 0xf4, 0x9a, 0x4c, 0x6d, 0x6f, 0xa3, 0x51, 0x97, 0x0f, 0x3b, 0xed, 0x9e, 0xdc, 0xaa, 0x3d, 0x51, - 0x8f, 0x5a, 0x3f, 0x6f, 0xb5, 0xbf, 0x6a, 0x29, 0xc8, 0x98, 0xa1, 0xbd, 0xc3, 0xad, 0xde, 0x01, - 0x34, 0xeb, 0x14, 0x3e, 0x0b, 0x8b, 0xdc, 0x42, 0x1f, 0xe0, 0x0d, 0x58, 0x6b, 0xb5, 0xd5, 0x6e, - 0xa3, 0x2e, 0xab, 0xf2, 0xc3, 0x87, 0x72, 0xad, 0xd7, 0x15, 0x17, 0xf8, 0x88, 0xdd, 0x9b, 0xde, - 0xd4, 0xbf, 0x4b, 0xc1, 0xc6, 0x02, 0x4f, 0x70, 0x35, 0xb8, 0x3b, 0x88, 0xeb, 0xcc, 0x8f, 0x4f, - 0xe3, 0x7d, 0x85, 0x95, 0xfc, 0x0e, 0x71, 0xfd, 0xe0, 0xaa, 0x71, 0x1d, 0x58, 0x94, 0x2c, 0xdf, - 0xe8, 0x1b, 0xd4, 0x0d, 0xde, 0x3b, 0xc4, 0x85, 0x62, 0x6d, 0x82, 0x8b, 0x27, 0x8f, 0x1f, 0x01, - 0x76, 0x6c, 0xcf, 0xf0, 0x8d, 0xe7, 0x54, 0x35, 0xac, 0xf0, 0x71, 0x84, 0x5d, 0x30, 0xd2, 0x0a, - 0x0a, 0x25, 0x0d, 0xcb, 0x8f, 0xd8, 0x16, 0x1d, 0x90, 0x19, 0x36, 0x3b, 0xc0, 0x53, 0x0a, 0x0a, - 0x25, 0x11, 0xfb, 0x12, 0x14, 0x75, 0x7b, 0xcc, 0xba, 0x2e, 0xc1, 0x63, 0xf5, 0x22, 0xa1, 0x14, - 0x04, 0x16, 0x51, 0x82, 0x7e, 0x7a, 0xf2, 0x2a, 0x53, 0x54, 0x0a, 0x02, 0x13, 0x94, 0x6b, 0xb0, - 0x46, 0x06, 0x03, 0x97, 0x19, 0x0f, 0x0d, 0x89, 0x1b, 0x42, 0x29, 0x82, 0x39, 0x71, 0xeb, 0x11, - 0xe4, 0xc2, 0x38, 0xb0, 0x92, 0xcc, 0x22, 0xa1, 0x3a, 0xe2, 0x65, 0x2e, 0xb9, 0x93, 0x57, 0x72, - 0x56, 0x28, 0xbc, 0x04, 0x45, 0xc3, 0x53, 0x27, 0x8f, 0xcc, 0xc9, 0xed, 0xe4, 0x4e, 0x4e, 0x29, - 0x18, 0x5e, 0xf4, 0x40, 0x57, 0xfe, 0x2e, 0x09, 0xa5, 0xe9, 0x47, 0x72, 0x5c, 0x87, 0x9c, 0x69, - 0x6b, 0x84, 0xa7, 0x96, 0xf8, 0x85, 0x66, 0xe7, 0x2d, 0xef, 0xea, 0x95, 0x66, 0xc0, 0x57, 0x22, - 0xcd, 0xad, 0xbf, 0x27, 0x20, 0x17, 0xc2, 0xf8, 0x0c, 0xa4, 0x1d, 0xe2, 0x0f, 0xb9, 0xb9, 0xcc, - 0x7e, 0x12, 0x25, 0x14, 0x3e, 0x66, 0xb8, 0xe7, 0x10, 0x8b, 0xa7, 0x40, 0x80, 0xb3, 0x31, 0xfb, - 0xae, 0x26, 0x25, 0x3a, 0xbf, 0x7e, 0xd8, 0xa3, 0x11, 0xb5, 0x7c, 0x2f, 0xfc, 0xae, 0x01, 0x5e, - 0x0b, 0x60, 0x7c, 0x13, 0xd6, 0x7d, 0x97, 0x18, 0xe6, 0x14, 0x37, 0xcd, 0xb9, 0x28, 0x14, 0x44, - 0xe4, 0x3d, 0x38, 0x17, 0xda, 0xd5, 0xa9, 0x4f, 0xb4, 0x21, 0xd5, 0x27, 0x4a, 0x59, 0xfe, 0x02, - 0x7b, 0x36, 0x20, 0xd4, 0x03, 0x79, 0xa8, 0x5b, 0xfe, 0x47, 0x02, 0xd6, 0xc3, 0x0b, 0x93, 0x1e, - 0x05, 0xeb, 0x10, 0x80, 0x58, 0x96, 0xed, 0xc7, 0xc3, 0x35, 0x9f, 0xca, 0x73, 0x7a, 0x95, 0x6a, - 0xa4, 0xa4, 0xc4, 0x0c, 0x6c, 0x8d, 0x00, 0x26, 0x92, 0xa5, 0x61, 0xbb, 0x08, 0x85, 0xe0, 0x17, - 0x10, 0xfe, 0x33, 0x9a, 0xb8, 0x62, 0x83, 0x80, 0xd8, 0xcd, 0x0a, 0x6f, 0x42, 0xe6, 0x98, 0x0e, - 0x0c, 0x2b, 0x78, 0xd7, 0x14, 0x83, 0xf0, 0xad, 0x36, 0x1d, 0xbd, 0xd5, 0xee, 0x3f, 0x86, 0x0d, - 0xcd, 0x1e, 0xcd, 0xba, 0xbb, 0x8f, 0x66, 0xae, 0xf9, 0xde, 0x97, 0x89, 0xaf, 0x61, 0xd2, 0x62, - 0x7e, 0x9b, 0x4c, 0x1d, 0x74, 0xf6, 0xff, 0x98, 0xdc, 0x3a, 0x10, 0x7a, 0x9d, 0x70, 0x99, 0x0a, - 0xed, 0x9b, 0x54, 0x63, 0xae, 0xff, 0x2f, 0x00, 0x00, 0xff, 0xff, 0x6b, 0x03, 0xf1, 0x99, 0x1b, - 0x1c, 0x00, 0x00, -} diff --git a/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/descriptor_gostring.gen.go b/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/descriptor_gostring.gen.go deleted file mode 100644 index be534f0fa..000000000 --- a/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/descriptor_gostring.gen.go +++ /dev/null @@ -1,749 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: descriptor.proto - -/* -Package descriptor is a generated protocol buffer package. - -It is generated from these files: - descriptor.proto - -It has these top-level messages: - FileDescriptorSet - FileDescriptorProto - DescriptorProto - ExtensionRangeOptions - FieldDescriptorProto - OneofDescriptorProto - EnumDescriptorProto - EnumValueDescriptorProto - ServiceDescriptorProto - MethodDescriptorProto - FileOptions - MessageOptions - FieldOptions - OneofOptions - EnumOptions - EnumValueOptions - ServiceOptions - MethodOptions - UninterpretedOption - SourceCodeInfo - GeneratedCodeInfo -*/ -package descriptor - -import fmt "fmt" -import strings "strings" -import github_com_gogo_protobuf_proto "github.com/gogo/protobuf/proto" -import sort "sort" -import strconv "strconv" -import reflect "reflect" -import proto "github.com/gogo/protobuf/proto" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -func (this *FileDescriptorSet) GoString() string { - if this == nil { - return "nil" - } - s := make([]string, 0, 5) - s = append(s, "&descriptor.FileDescriptorSet{") - if this.File != nil { - s = append(s, "File: "+fmt.Sprintf("%#v", this.File)+",\n") - } - if this.XXX_unrecognized != nil { - s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n") - } - s = append(s, "}") - return strings.Join(s, "") -} -func (this *FileDescriptorProto) GoString() string { - if this == nil { - return "nil" - } - s := make([]string, 0, 16) - s = append(s, "&descriptor.FileDescriptorProto{") - if this.Name != nil { - s = append(s, "Name: "+valueToGoStringDescriptor(this.Name, "string")+",\n") - } - if this.Package != nil { - s = append(s, "Package: "+valueToGoStringDescriptor(this.Package, "string")+",\n") - } - if this.Dependency != nil { - s = append(s, "Dependency: "+fmt.Sprintf("%#v", this.Dependency)+",\n") - } - if this.PublicDependency != nil { - s = append(s, "PublicDependency: "+fmt.Sprintf("%#v", this.PublicDependency)+",\n") - } - if this.WeakDependency != nil { - s = append(s, "WeakDependency: "+fmt.Sprintf("%#v", this.WeakDependency)+",\n") - } - if this.MessageType != nil { - s = append(s, "MessageType: "+fmt.Sprintf("%#v", this.MessageType)+",\n") - } - if this.EnumType != nil { - s = append(s, "EnumType: "+fmt.Sprintf("%#v", this.EnumType)+",\n") - } - if this.Service != nil { - s = append(s, "Service: "+fmt.Sprintf("%#v", this.Service)+",\n") - } - if this.Extension != nil { - s = append(s, "Extension: "+fmt.Sprintf("%#v", this.Extension)+",\n") - } - if this.Options != nil { - s = append(s, "Options: "+fmt.Sprintf("%#v", this.Options)+",\n") - } - if this.SourceCodeInfo != nil { - s = append(s, "SourceCodeInfo: "+fmt.Sprintf("%#v", this.SourceCodeInfo)+",\n") - } - if this.Syntax != nil { - s = append(s, "Syntax: "+valueToGoStringDescriptor(this.Syntax, "string")+",\n") - } - if this.XXX_unrecognized != nil { - s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n") - } - s = append(s, "}") - return strings.Join(s, "") -} -func (this *DescriptorProto) GoString() string { - if this == nil { - return "nil" - } - s := make([]string, 0, 14) - s = append(s, "&descriptor.DescriptorProto{") - if this.Name != nil { - s = append(s, "Name: "+valueToGoStringDescriptor(this.Name, "string")+",\n") - } - if this.Field != nil { - s = append(s, "Field: "+fmt.Sprintf("%#v", this.Field)+",\n") - } - if this.Extension != nil { - s = append(s, "Extension: "+fmt.Sprintf("%#v", this.Extension)+",\n") - } - if this.NestedType != nil { - s = append(s, "NestedType: "+fmt.Sprintf("%#v", this.NestedType)+",\n") - } - if this.EnumType != nil { - s = append(s, "EnumType: "+fmt.Sprintf("%#v", this.EnumType)+",\n") - } - if this.ExtensionRange != nil { - s = append(s, "ExtensionRange: "+fmt.Sprintf("%#v", this.ExtensionRange)+",\n") - } - if this.OneofDecl != nil { - s = append(s, "OneofDecl: "+fmt.Sprintf("%#v", this.OneofDecl)+",\n") - } - if this.Options != nil { - s = append(s, "Options: "+fmt.Sprintf("%#v", this.Options)+",\n") - } - if this.ReservedRange != nil { - s = append(s, "ReservedRange: "+fmt.Sprintf("%#v", this.ReservedRange)+",\n") - } - if this.ReservedName != nil { - s = append(s, "ReservedName: "+fmt.Sprintf("%#v", this.ReservedName)+",\n") - } - if this.XXX_unrecognized != nil { - s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n") - } - s = append(s, "}") - return strings.Join(s, "") -} -func (this *DescriptorProto_ExtensionRange) GoString() string { - if this == nil { - return "nil" - } - s := make([]string, 0, 7) - s = append(s, "&descriptor.DescriptorProto_ExtensionRange{") - if this.Start != nil { - s = append(s, "Start: "+valueToGoStringDescriptor(this.Start, "int32")+",\n") - } - if this.End != nil { - s = append(s, "End: "+valueToGoStringDescriptor(this.End, "int32")+",\n") - } - if this.Options != nil { - s = append(s, "Options: "+fmt.Sprintf("%#v", this.Options)+",\n") - } - if this.XXX_unrecognized != nil { - s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n") - } - s = append(s, "}") - return strings.Join(s, "") -} -func (this *DescriptorProto_ReservedRange) GoString() string { - if this == nil { - return "nil" - } - s := make([]string, 0, 6) - s = append(s, "&descriptor.DescriptorProto_ReservedRange{") - if this.Start != nil { - s = append(s, "Start: "+valueToGoStringDescriptor(this.Start, "int32")+",\n") - } - if this.End != nil { - s = append(s, "End: "+valueToGoStringDescriptor(this.End, "int32")+",\n") - } - if this.XXX_unrecognized != nil { - s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n") - } - s = append(s, "}") - return strings.Join(s, "") -} -func (this *ExtensionRangeOptions) GoString() string { - if this == nil { - return "nil" - } - s := make([]string, 0, 5) - s = append(s, "&descriptor.ExtensionRangeOptions{") - if this.UninterpretedOption != nil { - s = append(s, "UninterpretedOption: "+fmt.Sprintf("%#v", this.UninterpretedOption)+",\n") - } - s = append(s, "XXX_InternalExtensions: "+extensionToGoStringDescriptor(this)+",\n") - if this.XXX_unrecognized != nil { - s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n") - } - s = append(s, "}") - return strings.Join(s, "") -} -func (this *FieldDescriptorProto) GoString() string { - if this == nil { - return "nil" - } - s := make([]string, 0, 14) - s = append(s, "&descriptor.FieldDescriptorProto{") - if this.Name != nil { - s = append(s, "Name: "+valueToGoStringDescriptor(this.Name, "string")+",\n") - } - if this.Number != nil { - s = append(s, "Number: "+valueToGoStringDescriptor(this.Number, "int32")+",\n") - } - if this.Label != nil { - s = append(s, "Label: "+valueToGoStringDescriptor(this.Label, "FieldDescriptorProto_Label")+",\n") - } - if this.Type != nil { - s = append(s, "Type: "+valueToGoStringDescriptor(this.Type, "FieldDescriptorProto_Type")+",\n") - } - if this.TypeName != nil { - s = append(s, "TypeName: "+valueToGoStringDescriptor(this.TypeName, "string")+",\n") - } - if this.Extendee != nil { - s = append(s, "Extendee: "+valueToGoStringDescriptor(this.Extendee, "string")+",\n") - } - if this.DefaultValue != nil { - s = append(s, "DefaultValue: "+valueToGoStringDescriptor(this.DefaultValue, "string")+",\n") - } - if this.OneofIndex != nil { - s = append(s, "OneofIndex: "+valueToGoStringDescriptor(this.OneofIndex, "int32")+",\n") - } - if this.JsonName != nil { - s = append(s, "JsonName: "+valueToGoStringDescriptor(this.JsonName, "string")+",\n") - } - if this.Options != nil { - s = append(s, "Options: "+fmt.Sprintf("%#v", this.Options)+",\n") - } - if this.XXX_unrecognized != nil { - s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n") - } - s = append(s, "}") - return strings.Join(s, "") -} -func (this *OneofDescriptorProto) GoString() string { - if this == nil { - return "nil" - } - s := make([]string, 0, 6) - s = append(s, "&descriptor.OneofDescriptorProto{") - if this.Name != nil { - s = append(s, "Name: "+valueToGoStringDescriptor(this.Name, "string")+",\n") - } - if this.Options != nil { - s = append(s, "Options: "+fmt.Sprintf("%#v", this.Options)+",\n") - } - if this.XXX_unrecognized != nil { - s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n") - } - s = append(s, "}") - return strings.Join(s, "") -} -func (this *EnumDescriptorProto) GoString() string { - if this == nil { - return "nil" - } - s := make([]string, 0, 7) - s = append(s, "&descriptor.EnumDescriptorProto{") - if this.Name != nil { - s = append(s, "Name: "+valueToGoStringDescriptor(this.Name, "string")+",\n") - } - if this.Value != nil { - s = append(s, "Value: "+fmt.Sprintf("%#v", this.Value)+",\n") - } - if this.Options != nil { - s = append(s, "Options: "+fmt.Sprintf("%#v", this.Options)+",\n") - } - if this.XXX_unrecognized != nil { - s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n") - } - s = append(s, "}") - return strings.Join(s, "") -} -func (this *EnumValueDescriptorProto) GoString() string { - if this == nil { - return "nil" - } - s := make([]string, 0, 7) - s = append(s, "&descriptor.EnumValueDescriptorProto{") - if this.Name != nil { - s = append(s, "Name: "+valueToGoStringDescriptor(this.Name, "string")+",\n") - } - if this.Number != nil { - s = append(s, "Number: "+valueToGoStringDescriptor(this.Number, "int32")+",\n") - } - if this.Options != nil { - s = append(s, "Options: "+fmt.Sprintf("%#v", this.Options)+",\n") - } - if this.XXX_unrecognized != nil { - s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n") - } - s = append(s, "}") - return strings.Join(s, "") -} -func (this *ServiceDescriptorProto) GoString() string { - if this == nil { - return "nil" - } - s := make([]string, 0, 7) - s = append(s, "&descriptor.ServiceDescriptorProto{") - if this.Name != nil { - s = append(s, "Name: "+valueToGoStringDescriptor(this.Name, "string")+",\n") - } - if this.Method != nil { - s = append(s, "Method: "+fmt.Sprintf("%#v", this.Method)+",\n") - } - if this.Options != nil { - s = append(s, "Options: "+fmt.Sprintf("%#v", this.Options)+",\n") - } - if this.XXX_unrecognized != nil { - s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n") - } - s = append(s, "}") - return strings.Join(s, "") -} -func (this *MethodDescriptorProto) GoString() string { - if this == nil { - return "nil" - } - s := make([]string, 0, 10) - s = append(s, "&descriptor.MethodDescriptorProto{") - if this.Name != nil { - s = append(s, "Name: "+valueToGoStringDescriptor(this.Name, "string")+",\n") - } - if this.InputType != nil { - s = append(s, "InputType: "+valueToGoStringDescriptor(this.InputType, "string")+",\n") - } - if this.OutputType != nil { - s = append(s, "OutputType: "+valueToGoStringDescriptor(this.OutputType, "string")+",\n") - } - if this.Options != nil { - s = append(s, "Options: "+fmt.Sprintf("%#v", this.Options)+",\n") - } - if this.ClientStreaming != nil { - s = append(s, "ClientStreaming: "+valueToGoStringDescriptor(this.ClientStreaming, "bool")+",\n") - } - if this.ServerStreaming != nil { - s = append(s, "ServerStreaming: "+valueToGoStringDescriptor(this.ServerStreaming, "bool")+",\n") - } - if this.XXX_unrecognized != nil { - s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n") - } - s = append(s, "}") - return strings.Join(s, "") -} -func (this *FileOptions) GoString() string { - if this == nil { - return "nil" - } - s := make([]string, 0, 23) - s = append(s, "&descriptor.FileOptions{") - if this.JavaPackage != nil { - s = append(s, "JavaPackage: "+valueToGoStringDescriptor(this.JavaPackage, "string")+",\n") - } - if this.JavaOuterClassname != nil { - s = append(s, "JavaOuterClassname: "+valueToGoStringDescriptor(this.JavaOuterClassname, "string")+",\n") - } - if this.JavaMultipleFiles != nil { - s = append(s, "JavaMultipleFiles: "+valueToGoStringDescriptor(this.JavaMultipleFiles, "bool")+",\n") - } - if this.JavaGenerateEqualsAndHash != nil { - s = append(s, "JavaGenerateEqualsAndHash: "+valueToGoStringDescriptor(this.JavaGenerateEqualsAndHash, "bool")+",\n") - } - if this.JavaStringCheckUtf8 != nil { - s = append(s, "JavaStringCheckUtf8: "+valueToGoStringDescriptor(this.JavaStringCheckUtf8, "bool")+",\n") - } - if this.OptimizeFor != nil { - s = append(s, "OptimizeFor: "+valueToGoStringDescriptor(this.OptimizeFor, "FileOptions_OptimizeMode")+",\n") - } - if this.GoPackage != nil { - s = append(s, "GoPackage: "+valueToGoStringDescriptor(this.GoPackage, "string")+",\n") - } - if this.CcGenericServices != nil { - s = append(s, "CcGenericServices: "+valueToGoStringDescriptor(this.CcGenericServices, "bool")+",\n") - } - if this.JavaGenericServices != nil { - s = append(s, "JavaGenericServices: "+valueToGoStringDescriptor(this.JavaGenericServices, "bool")+",\n") - } - if this.PyGenericServices != nil { - s = append(s, "PyGenericServices: "+valueToGoStringDescriptor(this.PyGenericServices, "bool")+",\n") - } - if this.PhpGenericServices != nil { - s = append(s, "PhpGenericServices: "+valueToGoStringDescriptor(this.PhpGenericServices, "bool")+",\n") - } - if this.Deprecated != nil { - s = append(s, "Deprecated: "+valueToGoStringDescriptor(this.Deprecated, "bool")+",\n") - } - if this.CcEnableArenas != nil { - s = append(s, "CcEnableArenas: "+valueToGoStringDescriptor(this.CcEnableArenas, "bool")+",\n") - } - if this.ObjcClassPrefix != nil { - s = append(s, "ObjcClassPrefix: "+valueToGoStringDescriptor(this.ObjcClassPrefix, "string")+",\n") - } - if this.CsharpNamespace != nil { - s = append(s, "CsharpNamespace: "+valueToGoStringDescriptor(this.CsharpNamespace, "string")+",\n") - } - if this.SwiftPrefix != nil { - s = append(s, "SwiftPrefix: "+valueToGoStringDescriptor(this.SwiftPrefix, "string")+",\n") - } - if this.PhpClassPrefix != nil { - s = append(s, "PhpClassPrefix: "+valueToGoStringDescriptor(this.PhpClassPrefix, "string")+",\n") - } - if this.PhpNamespace != nil { - s = append(s, "PhpNamespace: "+valueToGoStringDescriptor(this.PhpNamespace, "string")+",\n") - } - if this.UninterpretedOption != nil { - s = append(s, "UninterpretedOption: "+fmt.Sprintf("%#v", this.UninterpretedOption)+",\n") - } - s = append(s, "XXX_InternalExtensions: "+extensionToGoStringDescriptor(this)+",\n") - if this.XXX_unrecognized != nil { - s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n") - } - s = append(s, "}") - return strings.Join(s, "") -} -func (this *MessageOptions) GoString() string { - if this == nil { - return "nil" - } - s := make([]string, 0, 9) - s = append(s, "&descriptor.MessageOptions{") - if this.MessageSetWireFormat != nil { - s = append(s, "MessageSetWireFormat: "+valueToGoStringDescriptor(this.MessageSetWireFormat, "bool")+",\n") - } - if this.NoStandardDescriptorAccessor != nil { - s = append(s, "NoStandardDescriptorAccessor: "+valueToGoStringDescriptor(this.NoStandardDescriptorAccessor, "bool")+",\n") - } - if this.Deprecated != nil { - s = append(s, "Deprecated: "+valueToGoStringDescriptor(this.Deprecated, "bool")+",\n") - } - if this.MapEntry != nil { - s = append(s, "MapEntry: "+valueToGoStringDescriptor(this.MapEntry, "bool")+",\n") - } - if this.UninterpretedOption != nil { - s = append(s, "UninterpretedOption: "+fmt.Sprintf("%#v", this.UninterpretedOption)+",\n") - } - s = append(s, "XXX_InternalExtensions: "+extensionToGoStringDescriptor(this)+",\n") - if this.XXX_unrecognized != nil { - s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n") - } - s = append(s, "}") - return strings.Join(s, "") -} -func (this *FieldOptions) GoString() string { - if this == nil { - return "nil" - } - s := make([]string, 0, 11) - s = append(s, "&descriptor.FieldOptions{") - if this.Ctype != nil { - s = append(s, "Ctype: "+valueToGoStringDescriptor(this.Ctype, "FieldOptions_CType")+",\n") - } - if this.Packed != nil { - s = append(s, "Packed: "+valueToGoStringDescriptor(this.Packed, "bool")+",\n") - } - if this.Jstype != nil { - s = append(s, "Jstype: "+valueToGoStringDescriptor(this.Jstype, "FieldOptions_JSType")+",\n") - } - if this.Lazy != nil { - s = append(s, "Lazy: "+valueToGoStringDescriptor(this.Lazy, "bool")+",\n") - } - if this.Deprecated != nil { - s = append(s, "Deprecated: "+valueToGoStringDescriptor(this.Deprecated, "bool")+",\n") - } - if this.Weak != nil { - s = append(s, "Weak: "+valueToGoStringDescriptor(this.Weak, "bool")+",\n") - } - if this.UninterpretedOption != nil { - s = append(s, "UninterpretedOption: "+fmt.Sprintf("%#v", this.UninterpretedOption)+",\n") - } - s = append(s, "XXX_InternalExtensions: "+extensionToGoStringDescriptor(this)+",\n") - if this.XXX_unrecognized != nil { - s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n") - } - s = append(s, "}") - return strings.Join(s, "") -} -func (this *OneofOptions) GoString() string { - if this == nil { - return "nil" - } - s := make([]string, 0, 5) - s = append(s, "&descriptor.OneofOptions{") - if this.UninterpretedOption != nil { - s = append(s, "UninterpretedOption: "+fmt.Sprintf("%#v", this.UninterpretedOption)+",\n") - } - s = append(s, "XXX_InternalExtensions: "+extensionToGoStringDescriptor(this)+",\n") - if this.XXX_unrecognized != nil { - s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n") - } - s = append(s, "}") - return strings.Join(s, "") -} -func (this *EnumOptions) GoString() string { - if this == nil { - return "nil" - } - s := make([]string, 0, 7) - s = append(s, "&descriptor.EnumOptions{") - if this.AllowAlias != nil { - s = append(s, "AllowAlias: "+valueToGoStringDescriptor(this.AllowAlias, "bool")+",\n") - } - if this.Deprecated != nil { - s = append(s, "Deprecated: "+valueToGoStringDescriptor(this.Deprecated, "bool")+",\n") - } - if this.UninterpretedOption != nil { - s = append(s, "UninterpretedOption: "+fmt.Sprintf("%#v", this.UninterpretedOption)+",\n") - } - s = append(s, "XXX_InternalExtensions: "+extensionToGoStringDescriptor(this)+",\n") - if this.XXX_unrecognized != nil { - s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n") - } - s = append(s, "}") - return strings.Join(s, "") -} -func (this *EnumValueOptions) GoString() string { - if this == nil { - return "nil" - } - s := make([]string, 0, 6) - s = append(s, "&descriptor.EnumValueOptions{") - if this.Deprecated != nil { - s = append(s, "Deprecated: "+valueToGoStringDescriptor(this.Deprecated, "bool")+",\n") - } - if this.UninterpretedOption != nil { - s = append(s, "UninterpretedOption: "+fmt.Sprintf("%#v", this.UninterpretedOption)+",\n") - } - s = append(s, "XXX_InternalExtensions: "+extensionToGoStringDescriptor(this)+",\n") - if this.XXX_unrecognized != nil { - s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n") - } - s = append(s, "}") - return strings.Join(s, "") -} -func (this *ServiceOptions) GoString() string { - if this == nil { - return "nil" - } - s := make([]string, 0, 6) - s = append(s, "&descriptor.ServiceOptions{") - if this.Deprecated != nil { - s = append(s, "Deprecated: "+valueToGoStringDescriptor(this.Deprecated, "bool")+",\n") - } - if this.UninterpretedOption != nil { - s = append(s, "UninterpretedOption: "+fmt.Sprintf("%#v", this.UninterpretedOption)+",\n") - } - s = append(s, "XXX_InternalExtensions: "+extensionToGoStringDescriptor(this)+",\n") - if this.XXX_unrecognized != nil { - s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n") - } - s = append(s, "}") - return strings.Join(s, "") -} -func (this *MethodOptions) GoString() string { - if this == nil { - return "nil" - } - s := make([]string, 0, 7) - s = append(s, "&descriptor.MethodOptions{") - if this.Deprecated != nil { - s = append(s, "Deprecated: "+valueToGoStringDescriptor(this.Deprecated, "bool")+",\n") - } - if this.IdempotencyLevel != nil { - s = append(s, "IdempotencyLevel: "+valueToGoStringDescriptor(this.IdempotencyLevel, "MethodOptions_IdempotencyLevel")+",\n") - } - if this.UninterpretedOption != nil { - s = append(s, "UninterpretedOption: "+fmt.Sprintf("%#v", this.UninterpretedOption)+",\n") - } - s = append(s, "XXX_InternalExtensions: "+extensionToGoStringDescriptor(this)+",\n") - if this.XXX_unrecognized != nil { - s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n") - } - s = append(s, "}") - return strings.Join(s, "") -} -func (this *UninterpretedOption) GoString() string { - if this == nil { - return "nil" - } - s := make([]string, 0, 11) - s = append(s, "&descriptor.UninterpretedOption{") - if this.Name != nil { - s = append(s, "Name: "+fmt.Sprintf("%#v", this.Name)+",\n") - } - if this.IdentifierValue != nil { - s = append(s, "IdentifierValue: "+valueToGoStringDescriptor(this.IdentifierValue, "string")+",\n") - } - if this.PositiveIntValue != nil { - s = append(s, "PositiveIntValue: "+valueToGoStringDescriptor(this.PositiveIntValue, "uint64")+",\n") - } - if this.NegativeIntValue != nil { - s = append(s, "NegativeIntValue: "+valueToGoStringDescriptor(this.NegativeIntValue, "int64")+",\n") - } - if this.DoubleValue != nil { - s = append(s, "DoubleValue: "+valueToGoStringDescriptor(this.DoubleValue, "float64")+",\n") - } - if this.StringValue != nil { - s = append(s, "StringValue: "+valueToGoStringDescriptor(this.StringValue, "byte")+",\n") - } - if this.AggregateValue != nil { - s = append(s, "AggregateValue: "+valueToGoStringDescriptor(this.AggregateValue, "string")+",\n") - } - if this.XXX_unrecognized != nil { - s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n") - } - s = append(s, "}") - return strings.Join(s, "") -} -func (this *UninterpretedOption_NamePart) GoString() string { - if this == nil { - return "nil" - } - s := make([]string, 0, 6) - s = append(s, "&descriptor.UninterpretedOption_NamePart{") - if this.NamePart != nil { - s = append(s, "NamePart: "+valueToGoStringDescriptor(this.NamePart, "string")+",\n") - } - if this.IsExtension != nil { - s = append(s, "IsExtension: "+valueToGoStringDescriptor(this.IsExtension, "bool")+",\n") - } - if this.XXX_unrecognized != nil { - s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n") - } - s = append(s, "}") - return strings.Join(s, "") -} -func (this *SourceCodeInfo) GoString() string { - if this == nil { - return "nil" - } - s := make([]string, 0, 5) - s = append(s, "&descriptor.SourceCodeInfo{") - if this.Location != nil { - s = append(s, "Location: "+fmt.Sprintf("%#v", this.Location)+",\n") - } - if this.XXX_unrecognized != nil { - s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n") - } - s = append(s, "}") - return strings.Join(s, "") -} -func (this *SourceCodeInfo_Location) GoString() string { - if this == nil { - return "nil" - } - s := make([]string, 0, 9) - s = append(s, "&descriptor.SourceCodeInfo_Location{") - if this.Path != nil { - s = append(s, "Path: "+fmt.Sprintf("%#v", this.Path)+",\n") - } - if this.Span != nil { - s = append(s, "Span: "+fmt.Sprintf("%#v", this.Span)+",\n") - } - if this.LeadingComments != nil { - s = append(s, "LeadingComments: "+valueToGoStringDescriptor(this.LeadingComments, "string")+",\n") - } - if this.TrailingComments != nil { - s = append(s, "TrailingComments: "+valueToGoStringDescriptor(this.TrailingComments, "string")+",\n") - } - if this.LeadingDetachedComments != nil { - s = append(s, "LeadingDetachedComments: "+fmt.Sprintf("%#v", this.LeadingDetachedComments)+",\n") - } - if this.XXX_unrecognized != nil { - s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n") - } - s = append(s, "}") - return strings.Join(s, "") -} -func (this *GeneratedCodeInfo) GoString() string { - if this == nil { - return "nil" - } - s := make([]string, 0, 5) - s = append(s, "&descriptor.GeneratedCodeInfo{") - if this.Annotation != nil { - s = append(s, "Annotation: "+fmt.Sprintf("%#v", this.Annotation)+",\n") - } - if this.XXX_unrecognized != nil { - s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n") - } - s = append(s, "}") - return strings.Join(s, "") -} -func (this *GeneratedCodeInfo_Annotation) GoString() string { - if this == nil { - return "nil" - } - s := make([]string, 0, 8) - s = append(s, "&descriptor.GeneratedCodeInfo_Annotation{") - if this.Path != nil { - s = append(s, "Path: "+fmt.Sprintf("%#v", this.Path)+",\n") - } - if this.SourceFile != nil { - s = append(s, "SourceFile: "+valueToGoStringDescriptor(this.SourceFile, "string")+",\n") - } - if this.Begin != nil { - s = append(s, "Begin: "+valueToGoStringDescriptor(this.Begin, "int32")+",\n") - } - if this.End != nil { - s = append(s, "End: "+valueToGoStringDescriptor(this.End, "int32")+",\n") - } - if this.XXX_unrecognized != nil { - s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n") - } - s = append(s, "}") - return strings.Join(s, "") -} -func valueToGoStringDescriptor(v interface{}, typ string) string { - rv := reflect.ValueOf(v) - if rv.IsNil() { - return "nil" - } - pv := reflect.Indirect(rv).Interface() - return fmt.Sprintf("func(v %v) *%v { return &v } ( %#v )", typ, typ, pv) -} -func extensionToGoStringDescriptor(m github_com_gogo_protobuf_proto.Message) string { - e := github_com_gogo_protobuf_proto.GetUnsafeExtensionsMap(m) - if e == nil { - return "nil" - } - s := "proto.NewUnsafeXXX_InternalExtensions(map[int32]proto.Extension{" - keys := make([]int, 0, len(e)) - for k := range e { - keys = append(keys, int(k)) - } - sort.Ints(keys) - ss := []string{} - for _, k := range keys { - ss = append(ss, strconv.Itoa(k)+": "+e[int32(k)].GoString()) - } - s += strings.Join(ss, ",") + "})" - return s -} diff --git a/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/descriptor_test.go b/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/descriptor_test.go deleted file mode 100644 index d4248b483..000000000 --- a/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/descriptor_test.go +++ /dev/null @@ -1,31 +0,0 @@ -package descriptor_test - -import ( - "fmt" - "testing" - - tpb "github.com/gogo/protobuf/proto/testdata" - "github.com/gogo/protobuf/protoc-gen-gogo/descriptor" -) - -func TestMessage(t *testing.T) { - var msg *descriptor.DescriptorProto - fd, md := descriptor.ForMessage(msg) - if pkg, want := fd.GetPackage(), "google.protobuf"; pkg != want { - t.Errorf("descriptor.ForMessage(%T).GetPackage() = %q; want %q", msg, pkg, want) - } - if name, want := md.GetName(), "DescriptorProto"; name != want { - t.Fatalf("descriptor.ForMessage(%T).GetName() = %q; want %q", msg, name, want) - } -} - -func Example_Options() { - var msg *tpb.MyMessageSet - _, md := descriptor.ForMessage(msg) - if md.GetOptions().GetMessageSetWireFormat() { - fmt.Printf("%v uses option message_set_wire_format.\n", md.GetName()) - } - - // Output: - // MyMessageSet uses option message_set_wire_format. -} diff --git a/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/helper.go b/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/helper.go deleted file mode 100644 index e0846a357..000000000 --- a/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/helper.go +++ /dev/null @@ -1,390 +0,0 @@ -// Protocol Buffers for Go with Gadgets -// -// Copyright (c) 2013, The GoGo Authors. All rights reserved. -// http://github.com/gogo/protobuf -// -// 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. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package descriptor - -import ( - "strings" -) - -func (msg *DescriptorProto) GetMapFields() (*FieldDescriptorProto, *FieldDescriptorProto) { - if !msg.GetOptions().GetMapEntry() { - return nil, nil - } - return msg.GetField()[0], msg.GetField()[1] -} - -func dotToUnderscore(r rune) rune { - if r == '.' { - return '_' - } - return r -} - -func (field *FieldDescriptorProto) WireType() (wire int) { - switch *field.Type { - case FieldDescriptorProto_TYPE_DOUBLE: - return 1 - case FieldDescriptorProto_TYPE_FLOAT: - return 5 - case FieldDescriptorProto_TYPE_INT64: - return 0 - case FieldDescriptorProto_TYPE_UINT64: - return 0 - case FieldDescriptorProto_TYPE_INT32: - return 0 - case FieldDescriptorProto_TYPE_UINT32: - return 0 - case FieldDescriptorProto_TYPE_FIXED64: - return 1 - case FieldDescriptorProto_TYPE_FIXED32: - return 5 - case FieldDescriptorProto_TYPE_BOOL: - return 0 - case FieldDescriptorProto_TYPE_STRING: - return 2 - case FieldDescriptorProto_TYPE_GROUP: - return 2 - case FieldDescriptorProto_TYPE_MESSAGE: - return 2 - case FieldDescriptorProto_TYPE_BYTES: - return 2 - case FieldDescriptorProto_TYPE_ENUM: - return 0 - case FieldDescriptorProto_TYPE_SFIXED32: - return 5 - case FieldDescriptorProto_TYPE_SFIXED64: - return 1 - case FieldDescriptorProto_TYPE_SINT32: - return 0 - case FieldDescriptorProto_TYPE_SINT64: - return 0 - } - panic("unreachable") -} - -func (field *FieldDescriptorProto) GetKeyUint64() (x uint64) { - packed := field.IsPacked() - wireType := field.WireType() - fieldNumber := field.GetNumber() - if packed { - wireType = 2 - } - x = uint64(uint32(fieldNumber)<<3 | uint32(wireType)) - return x -} - -func (field *FieldDescriptorProto) GetKey3Uint64() (x uint64) { - packed := field.IsPacked3() - wireType := field.WireType() - fieldNumber := field.GetNumber() - if packed { - wireType = 2 - } - x = uint64(uint32(fieldNumber)<<3 | uint32(wireType)) - return x -} - -func (field *FieldDescriptorProto) GetKey() []byte { - x := field.GetKeyUint64() - i := 0 - keybuf := make([]byte, 0) - for i = 0; x > 127; i++ { - keybuf = append(keybuf, 0x80|uint8(x&0x7F)) - x >>= 7 - } - keybuf = append(keybuf, uint8(x)) - return keybuf -} - -func (field *FieldDescriptorProto) GetKey3() []byte { - x := field.GetKey3Uint64() - i := 0 - keybuf := make([]byte, 0) - for i = 0; x > 127; i++ { - keybuf = append(keybuf, 0x80|uint8(x&0x7F)) - x >>= 7 - } - keybuf = append(keybuf, uint8(x)) - return keybuf -} - -func (desc *FileDescriptorSet) GetField(packageName, messageName, fieldName string) *FieldDescriptorProto { - msg := desc.GetMessage(packageName, messageName) - if msg == nil { - return nil - } - for _, field := range msg.GetField() { - if field.GetName() == fieldName { - return field - } - } - return nil -} - -func (file *FileDescriptorProto) GetMessage(typeName string) *DescriptorProto { - for _, msg := range file.GetMessageType() { - if msg.GetName() == typeName { - return msg - } - nes := file.GetNestedMessage(msg, strings.TrimPrefix(typeName, msg.GetName()+".")) - if nes != nil { - return nes - } - } - return nil -} - -func (file *FileDescriptorProto) GetNestedMessage(msg *DescriptorProto, typeName string) *DescriptorProto { - for _, nes := range msg.GetNestedType() { - if nes.GetName() == typeName { - return nes - } - res := file.GetNestedMessage(nes, strings.TrimPrefix(typeName, nes.GetName()+".")) - if res != nil { - return res - } - } - return nil -} - -func (desc *FileDescriptorSet) GetMessage(packageName string, typeName string) *DescriptorProto { - for _, file := range desc.GetFile() { - if strings.Map(dotToUnderscore, file.GetPackage()) != strings.Map(dotToUnderscore, packageName) { - continue - } - for _, msg := range file.GetMessageType() { - if msg.GetName() == typeName { - return msg - } - } - for _, msg := range file.GetMessageType() { - for _, nes := range msg.GetNestedType() { - if nes.GetName() == typeName { - return nes - } - if msg.GetName()+"."+nes.GetName() == typeName { - return nes - } - } - } - } - return nil -} - -func (desc *FileDescriptorSet) IsProto3(packageName string, typeName string) bool { - for _, file := range desc.GetFile() { - if strings.Map(dotToUnderscore, file.GetPackage()) != strings.Map(dotToUnderscore, packageName) { - continue - } - for _, msg := range file.GetMessageType() { - if msg.GetName() == typeName { - return file.GetSyntax() == "proto3" - } - } - for _, msg := range file.GetMessageType() { - for _, nes := range msg.GetNestedType() { - if nes.GetName() == typeName { - return file.GetSyntax() == "proto3" - } - if msg.GetName()+"."+nes.GetName() == typeName { - return file.GetSyntax() == "proto3" - } - } - } - } - return false -} - -func (msg *DescriptorProto) IsExtendable() bool { - return len(msg.GetExtensionRange()) > 0 -} - -func (desc *FileDescriptorSet) FindExtension(packageName string, typeName string, fieldName string) (extPackageName string, field *FieldDescriptorProto) { - parent := desc.GetMessage(packageName, typeName) - if parent == nil { - return "", nil - } - if !parent.IsExtendable() { - return "", nil - } - extendee := "." + packageName + "." + typeName - for _, file := range desc.GetFile() { - for _, ext := range file.GetExtension() { - if strings.Map(dotToUnderscore, file.GetPackage()) == strings.Map(dotToUnderscore, packageName) { - if !(ext.GetExtendee() == typeName || ext.GetExtendee() == extendee) { - continue - } - } else { - if ext.GetExtendee() != extendee { - continue - } - } - if ext.GetName() == fieldName { - return file.GetPackage(), ext - } - } - } - return "", nil -} - -func (desc *FileDescriptorSet) FindExtensionByFieldNumber(packageName string, typeName string, fieldNum int32) (extPackageName string, field *FieldDescriptorProto) { - parent := desc.GetMessage(packageName, typeName) - if parent == nil { - return "", nil - } - if !parent.IsExtendable() { - return "", nil - } - extendee := "." + packageName + "." + typeName - for _, file := range desc.GetFile() { - for _, ext := range file.GetExtension() { - if strings.Map(dotToUnderscore, file.GetPackage()) == strings.Map(dotToUnderscore, packageName) { - if !(ext.GetExtendee() == typeName || ext.GetExtendee() == extendee) { - continue - } - } else { - if ext.GetExtendee() != extendee { - continue - } - } - if ext.GetNumber() == fieldNum { - return file.GetPackage(), ext - } - } - } - return "", nil -} - -func (desc *FileDescriptorSet) FindMessage(packageName string, typeName string, fieldName string) (msgPackageName string, msgName string) { - parent := desc.GetMessage(packageName, typeName) - if parent == nil { - return "", "" - } - field := parent.GetFieldDescriptor(fieldName) - if field == nil { - var extPackageName string - extPackageName, field = desc.FindExtension(packageName, typeName, fieldName) - if field == nil { - return "", "" - } - packageName = extPackageName - } - typeNames := strings.Split(field.GetTypeName(), ".") - if len(typeNames) == 1 { - msg := desc.GetMessage(packageName, typeName) - if msg == nil { - return "", "" - } - return packageName, msg.GetName() - } - if len(typeNames) > 2 { - for i := 1; i < len(typeNames)-1; i++ { - packageName = strings.Join(typeNames[1:len(typeNames)-i], ".") - typeName = strings.Join(typeNames[len(typeNames)-i:], ".") - msg := desc.GetMessage(packageName, typeName) - if msg != nil { - typeNames := strings.Split(msg.GetName(), ".") - if len(typeNames) == 1 { - return packageName, msg.GetName() - } - return strings.Join(typeNames[1:len(typeNames)-1], "."), typeNames[len(typeNames)-1] - } - } - } - return "", "" -} - -func (msg *DescriptorProto) GetFieldDescriptor(fieldName string) *FieldDescriptorProto { - for _, field := range msg.GetField() { - if field.GetName() == fieldName { - return field - } - } - return nil -} - -func (desc *FileDescriptorSet) GetEnum(packageName string, typeName string) *EnumDescriptorProto { - for _, file := range desc.GetFile() { - if strings.Map(dotToUnderscore, file.GetPackage()) != strings.Map(dotToUnderscore, packageName) { - continue - } - for _, enum := range file.GetEnumType() { - if enum.GetName() == typeName { - return enum - } - } - } - return nil -} - -func (f *FieldDescriptorProto) IsEnum() bool { - return *f.Type == FieldDescriptorProto_TYPE_ENUM -} - -func (f *FieldDescriptorProto) IsMessage() bool { - return *f.Type == FieldDescriptorProto_TYPE_MESSAGE -} - -func (f *FieldDescriptorProto) IsBytes() bool { - return *f.Type == FieldDescriptorProto_TYPE_BYTES -} - -func (f *FieldDescriptorProto) IsRepeated() bool { - return f.Label != nil && *f.Label == FieldDescriptorProto_LABEL_REPEATED -} - -func (f *FieldDescriptorProto) IsString() bool { - return *f.Type == FieldDescriptorProto_TYPE_STRING -} - -func (f *FieldDescriptorProto) IsBool() bool { - return *f.Type == FieldDescriptorProto_TYPE_BOOL -} - -func (f *FieldDescriptorProto) IsRequired() bool { - return f.Label != nil && *f.Label == FieldDescriptorProto_LABEL_REQUIRED -} - -func (f *FieldDescriptorProto) IsPacked() bool { - return f.Options != nil && f.GetOptions().GetPacked() -} - -func (f *FieldDescriptorProto) IsPacked3() bool { - if f.IsRepeated() && f.IsScalar() { - if f.Options == nil || f.GetOptions().Packed == nil { - return true - } - return f.Options != nil && f.GetOptions().GetPacked() - } - return false -} - -func (m *DescriptorProto) HasExtension() bool { - return len(m.ExtensionRange) > 0 -} diff --git a/vendor/github.com/gogo/protobuf/protoc-gen-gogo/doc.go b/vendor/github.com/gogo/protobuf/protoc-gen-gogo/doc.go deleted file mode 100644 index 15c7cf43c..000000000 --- a/vendor/github.com/gogo/protobuf/protoc-gen-gogo/doc.go +++ /dev/null @@ -1,51 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -/* - A plugin for the Google protocol buffer compiler to generate Go code. - Run it by building this program and putting it in your path with the name - protoc-gen-gogo - That word 'gogo' at the end becomes part of the option string set for the - protocol compiler, so once the protocol compiler (protoc) is installed - you can run - protoc --gogo_out=output_directory input_directory/file.proto - to generate Go bindings for the protocol defined by file.proto. - With that input, the output will be written to - output_directory/go_package/file.pb.go - - The generated code is documented in the package comment for - the library. - - See the README and documentation for protocol buffers to learn more: - https://developers.google.com/protocol-buffers/ - -*/ -package documentation diff --git a/vendor/github.com/gogo/protobuf/protoc-gen-gogo/main.go b/vendor/github.com/gogo/protobuf/protoc-gen-gogo/main.go deleted file mode 100644 index dd8e79503..000000000 --- a/vendor/github.com/gogo/protobuf/protoc-gen-gogo/main.go +++ /dev/null @@ -1,57 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// protoc-gen-go is a plugin for the Google protocol buffer compiler to generate -// Go code. Run it by building this program and putting it in your path with -// the name -// protoc-gen-gogo -// That word 'gogo' at the end becomes part of the option string set for the -// protocol compiler, so once the protocol compiler (protoc) is installed -// you can run -// protoc --gogo_out=output_directory input_directory/file.proto -// to generate Go bindings for the protocol defined by file.proto. -// With that input, the output will be written to -// output_directory/file.pb.go -// -// The generated code is documented in the package comment for -// the library. -// -// See the README and documentation for protocol buffers to learn more: -// https://developers.google.com/protocol-buffers/ -package main - -import ( - "github.com/gogo/protobuf/vanity/command" -) - -func main() { - command.Write(command.Generate(command.Read())) -} diff --git a/vendor/github.com/gogo/protobuf/types/Makefile b/vendor/github.com/gogo/protobuf/types/Makefile deleted file mode 100644 index c326d2578..000000000 --- a/vendor/github.com/gogo/protobuf/types/Makefile +++ /dev/null @@ -1,39 +0,0 @@ -# Protocol Buffers for Go with Gadgets -# -# Copyright (c) 2016, The GoGo Authors. All rights reserved. -# http://github.com/gogo/protobuf -# -# 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. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -regenerate: - go install github.com/gogo/protobuf/protoc-gen-gogotypes - go install github.com/gogo/protobuf/protoc-min-version - - protoc-min-version --version="3.0.0" --gogotypes_out=. -I=../protobuf/google/protobuf ../protobuf/google/protobuf/any.proto - protoc-min-version --version="3.0.0" --gogotypes_out=. -I=../protobuf/google/protobuf ../protobuf/google/protobuf/empty.proto - protoc-min-version --version="3.0.0" --gogotypes_out=. -I=../protobuf/google/protobuf ../protobuf/google/protobuf/timestamp.proto - protoc-min-version --version="3.0.0" --gogotypes_out=. -I=../protobuf/google/protobuf ../protobuf/google/protobuf/duration.proto - protoc-min-version --version="3.0.0" --gogotypes_out=. -I=../protobuf/google/protobuf ../protobuf/google/protobuf/struct.proto - protoc-min-version --version="3.0.0" --gogotypes_out=. -I=../protobuf/google/protobuf ../protobuf/google/protobuf/wrappers.proto - protoc-min-version --version="3.0.0" --gogotypes_out=. -I=../protobuf/google/protobuf ../protobuf/google/protobuf/field_mask.proto diff --git a/vendor/github.com/gogo/protobuf/types/any_test.go b/vendor/github.com/gogo/protobuf/types/any_test.go deleted file mode 100644 index 14679a244..000000000 --- a/vendor/github.com/gogo/protobuf/types/any_test.go +++ /dev/null @@ -1,112 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2016 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package types - -import ( - "testing" - - "github.com/gogo/protobuf/proto" - pb "github.com/gogo/protobuf/protoc-gen-gogo/descriptor" -) - -func TestMarshalUnmarshal(t *testing.T) { - orig := &Any{Value: []byte("test")} - - packed, err := MarshalAny(orig) - if err != nil { - t.Errorf("MarshalAny(%+v): got: _, %v exp: _, nil", orig, err) - } - - unpacked := &Any{} - err = UnmarshalAny(packed, unpacked) - if err != nil || !proto.Equal(unpacked, orig) { - t.Errorf("got: %v, %+v; want nil, %+v", err, unpacked, orig) - } -} - -func TestIs(t *testing.T) { - a, err := MarshalAny(&pb.FileDescriptorProto{}) - if err != nil { - t.Fatal(err) - } - if Is(a, &pb.DescriptorProto{}) { - t.Error("FileDescriptorProto is not a DescriptorProto, but Is says it is") - } - if !Is(a, &pb.FileDescriptorProto{}) { - t.Error("FileDescriptorProto is indeed a FileDescriptorProto, but Is says it is not") - } -} - -func TestIsDifferentUrlPrefixes(t *testing.T) { - m := &pb.FileDescriptorProto{} - a := &Any{TypeUrl: "foo/bar/" + proto.MessageName(m)} - if !Is(a, m) { - t.Errorf("message with type url %q didn't satisfy Is for type %q", a.TypeUrl, proto.MessageName(m)) - } -} - -func TestUnmarshalDynamic(t *testing.T) { - want := &pb.FileDescriptorProto{Name: proto.String("foo")} - a, err := MarshalAny(want) - if err != nil { - t.Fatal(err) - } - var got DynamicAny - if err := UnmarshalAny(a, &got); err != nil { - t.Fatal(err) - } - if !proto.Equal(got.Message, want) { - t.Errorf("invalid result from UnmarshalAny, got %q want %q", got.Message, want) - } -} - -func TestEmpty(t *testing.T) { - want := &pb.FileDescriptorProto{} - a, err := MarshalAny(want) - if err != nil { - t.Fatal(err) - } - got, err := EmptyAny(a) - if err != nil { - t.Fatal(err) - } - if !proto.Equal(got, want) { - t.Errorf("unequal empty message, got %q, want %q", got, want) - } - - // that's a valid type_url for a message which shouldn't be linked into this - // test binary. We want an error. - a.TypeUrl = "type.googleapis.com/google.protobuf.TestAny" - if _, err := EmptyAny(a); err == nil { - t.Errorf("got no error for an attempt to create a message of type %q, which shouldn't be linked in", a.TypeUrl) - } -} diff --git a/vendor/github.com/gogo/protobuf/types/duration_test.go b/vendor/github.com/gogo/protobuf/types/duration_test.go deleted file mode 100644 index 7f2bcb429..000000000 --- a/vendor/github.com/gogo/protobuf/types/duration_test.go +++ /dev/null @@ -1,120 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2016 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package types - -import ( - "math" - "testing" - "time" - - "github.com/gogo/protobuf/proto" -) - -const ( - minGoSeconds = math.MinInt64 / int64(1e9) - maxGoSeconds = math.MaxInt64 / int64(1e9) -) - -var durationTests = []struct { - proto *Duration - isValid bool - inRange bool - dur time.Duration -}{ - // The zero duration. - {&Duration{Seconds: 0, Nanos: 0}, true, true, 0}, - // Some ordinary non-zero durations. - {&Duration{Seconds: 100, Nanos: 0}, true, true, 100 * time.Second}, - {&Duration{Seconds: -100, Nanos: 0}, true, true, -100 * time.Second}, - {&Duration{Seconds: 100, Nanos: 987}, true, true, 100*time.Second + 987}, - {&Duration{Seconds: -100, Nanos: -987}, true, true, -(100*time.Second + 987)}, - // The largest duration representable in Go. - {&Duration{Seconds: maxGoSeconds, Nanos: int32(math.MaxInt64 - 1e9*maxGoSeconds)}, true, true, math.MaxInt64}, - // The smallest duration representable in Go. - {&Duration{Seconds: minGoSeconds, Nanos: int32(math.MinInt64 - 1e9*minGoSeconds)}, true, true, math.MinInt64}, - {nil, false, false, 0}, - {&Duration{Seconds: -100, Nanos: 987}, false, false, 0}, - {&Duration{Seconds: 100, Nanos: -987}, false, false, 0}, - {&Duration{Seconds: math.MinInt64, Nanos: 0}, false, false, 0}, - {&Duration{Seconds: math.MaxInt64, Nanos: 0}, false, false, 0}, - // The largest valid duration. - {&Duration{Seconds: maxSeconds, Nanos: 1e9 - 1}, true, false, 0}, - // The smallest valid duration. - {&Duration{Seconds: minSeconds, Nanos: -(1e9 - 1)}, true, false, 0}, - // The smallest invalid duration above the valid range. - {&Duration{Seconds: maxSeconds + 1, Nanos: 0}, false, false, 0}, - // The largest invalid duration below the valid range. - {&Duration{Seconds: minSeconds - 1, Nanos: -(1e9 - 1)}, false, false, 0}, - // One nanosecond past the largest duration representable in Go. - {&Duration{Seconds: maxGoSeconds, Nanos: int32(math.MaxInt64-1e9*maxGoSeconds) + 1}, true, false, 0}, - // One nanosecond past the smallest duration representable in Go. - {&Duration{Seconds: minGoSeconds, Nanos: int32(math.MinInt64-1e9*minGoSeconds) - 1}, true, false, 0}, - // One second past the largest duration representable in Go. - {&Duration{Seconds: maxGoSeconds + 1, Nanos: int32(math.MaxInt64 - 1e9*maxGoSeconds)}, true, false, 0}, - // One second past the smallest duration representable in Go. - {&Duration{Seconds: minGoSeconds - 1, Nanos: int32(math.MinInt64 - 1e9*minGoSeconds)}, true, false, 0}, -} - -func TestValidateDuration(t *testing.T) { - for _, test := range durationTests { - err := validateDuration(test.proto) - gotValid := (err == nil) - if gotValid != test.isValid { - t.Errorf("validateDuration(%v) = %t, want %t", test.proto, gotValid, test.isValid) - } - } -} - -func TestDurationFromProto(t *testing.T) { - for _, test := range durationTests { - got, err := DurationFromProto(test.proto) - gotOK := (err == nil) - wantOK := test.isValid && test.inRange - if gotOK != wantOK { - t.Errorf("DurationFromProto(%v) ok = %t, want %t", test.proto, gotOK, wantOK) - } - if err == nil && got != test.dur { - t.Errorf("DurationFromProto(%v) = %v, want %v", test.proto, got, test.dur) - } - } -} - -func TestDurationProto(t *testing.T) { - for _, test := range durationTests { - if test.isValid && test.inRange { - got := DurationProto(test.dur) - if !proto.Equal(got, test.proto) { - t.Errorf("DurationProto(%v) = %v, want %v", test.dur, got, test.proto) - } - } - } -} diff --git a/vendor/github.com/gogo/protobuf/types/timestamp_test.go b/vendor/github.com/gogo/protobuf/types/timestamp_test.go deleted file mode 100644 index 6af8631e5..000000000 --- a/vendor/github.com/gogo/protobuf/types/timestamp_test.go +++ /dev/null @@ -1,152 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2016 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package types - -import ( - "math" - "testing" - "time" - - "github.com/gogo/protobuf/proto" -) - -var tests = []struct { - ts *Timestamp - valid bool - t time.Time -}{ - // The timestamp representing the Unix epoch date. - {&Timestamp{Seconds: 0, Nanos: 0}, true, utcDate(1970, 1, 1)}, - // The smallest representable timestamp. - {&Timestamp{Seconds: math.MinInt64, Nanos: math.MinInt32}, false, - time.Unix(math.MinInt64, math.MinInt32).UTC()}, - // The smallest representable timestamp with non-negative nanos. - {&Timestamp{Seconds: math.MinInt64, Nanos: 0}, false, time.Unix(math.MinInt64, 0).UTC()}, - // The earliest valid timestamp. - {&Timestamp{Seconds: minValidSeconds, Nanos: 0}, true, utcDate(1, 1, 1)}, - //"0001-01-01T00:00:00Z"}, - // The largest representable timestamp. - {&Timestamp{Seconds: math.MaxInt64, Nanos: math.MaxInt32}, false, - time.Unix(math.MaxInt64, math.MaxInt32).UTC()}, - // The largest representable timestamp with nanos in range. - {&Timestamp{Seconds: math.MaxInt64, Nanos: 1e9 - 1}, false, - time.Unix(math.MaxInt64, 1e9-1).UTC()}, - // The largest valid timestamp. - {&Timestamp{Seconds: maxValidSeconds - 1, Nanos: 1e9 - 1}, true, - time.Date(9999, 12, 31, 23, 59, 59, 1e9-1, time.UTC)}, - // The smallest invalid timestamp that is larger than the valid range. - {&Timestamp{Seconds: maxValidSeconds, Nanos: 0}, false, time.Unix(maxValidSeconds, 0).UTC()}, - // A date before the epoch. - {&Timestamp{Seconds: -281836800, Nanos: 0}, true, utcDate(1961, 1, 26)}, - // A date after the epoch. - {&Timestamp{Seconds: 1296000000, Nanos: 0}, true, utcDate(2011, 1, 26)}, - // A date after the epoch, in the middle of the day. - {&Timestamp{Seconds: 1296012345, Nanos: 940483}, true, - time.Date(2011, 1, 26, 3, 25, 45, 940483, time.UTC)}, -} - -func TestValidateTimestamp(t *testing.T) { - for _, s := range tests { - got := validateTimestamp(s.ts) - if (got == nil) != s.valid { - t.Errorf("validateTimestamp(%v) = %v, want %v", s.ts, got, s.valid) - } - } -} - -func TestTimestampFromProto(t *testing.T) { - for _, s := range tests { - got, err := TimestampFromProto(s.ts) - if (err == nil) != s.valid { - t.Errorf("TimestampFromProto(%v) error = %v, but valid = %t", s.ts, err, s.valid) - } else if s.valid && got != s.t { - t.Errorf("TimestampFromProto(%v) = %v, want %v", s.ts, got, s.t) - } - } - // Special case: a nil TimestampFromProto is an error, but returns the 0 Unix time. - got, err := TimestampFromProto(nil) - want := time.Unix(0, 0).UTC() - if got != want { - t.Errorf("TimestampFromProto(nil) = %v, want %v", got, want) - } - if err == nil { - t.Errorf("TimestampFromProto(nil) error = nil, expected error") - } -} - -func TestTimestampProto(t *testing.T) { - for _, s := range tests { - got, err := TimestampProto(s.t) - if (err == nil) != s.valid { - t.Errorf("TimestampProto(%v) error = %v, but valid = %t", s.t, err, s.valid) - } else if s.valid && !proto.Equal(got, s.ts) { - t.Errorf("TimestampProto(%v) = %v, want %v", s.t, got, s.ts) - } - } - // No corresponding special case here: no time.Time results in a nil Timestamp. -} - -func TestTimestampString(t *testing.T) { - for _, test := range []struct { - ts *Timestamp - want string - }{ - // Not much testing needed because presumably time.Format is - // well-tested. - {&Timestamp{Seconds: 0, Nanos: 0}, "1970-01-01T00:00:00Z"}, - {&Timestamp{Seconds: minValidSeconds - 1, Nanos: 0}, "(timestamp: &types.Timestamp{Seconds: -62135596801,\nNanos: 0,\n} before 0001-01-01)"}, - } { - got := TimestampString(test.ts) - if got != test.want { - t.Errorf("TimestampString(%v) = %q, want %q", test.ts, got, test.want) - } - } -} - -func utcDate(year, month, day int) time.Time { - return time.Date(year, time.Month(month), day, 0, 0, 0, 0, time.UTC) -} - -func TestTimestampNow(t *testing.T) { - // Bracket the expected time. - before := time.Now() - ts := TimestampNow() - after := time.Now() - - tm, err := TimestampFromProto(ts) - if err != nil { - t.Errorf("between %v and %v\nTimestampNow() = %v\nwhich is invalid (%v)", before, after, ts, err) - } - if tm.Before(before) || tm.After(after) { - t.Errorf("between %v and %v\nTimestamp(TimestampNow()) = %v", before, after, tm) - } -} diff --git a/vendor/github.com/golang/glog/README b/vendor/github.com/golang/glog/README deleted file mode 100644 index 387b4eb68..000000000 --- a/vendor/github.com/golang/glog/README +++ /dev/null @@ -1,44 +0,0 @@ -glog -==== - -Leveled execution logs for Go. - -This is an efficient pure Go implementation of leveled logs in the -manner of the open source C++ package - https://github.com/google/glog - -By binding methods to booleans it is possible to use the log package -without paying the expense of evaluating the arguments to the log. -Through the -vmodule flag, the package also provides fine-grained -control over logging at the file level. - -The comment from glog.go introduces the ideas: - - Package glog implements logging analogous to the Google-internal - C++ INFO/ERROR/V setup. It provides functions Info, Warning, - Error, Fatal, plus formatting variants such as Infof. It - also provides V-style logging controlled by the -v and - -vmodule=file=2 flags. - - Basic examples: - - glog.Info("Prepare to repel boarders") - - glog.Fatalf("Initialization failed: %s", err) - - See the documentation for the V function for an explanation - of these examples: - - if glog.V(2) { - glog.Info("Starting transaction...") - } - - glog.V(2).Infoln("Processed", nItems, "elements") - - -The repository contains an open source version of the log package -used inside Google. The master copy of the source lives inside -Google, not here. The code in this repo is for export only and is not itself -under development. Feature requests will be ignored. - -Send bug reports to golang-nuts@googlegroups.com. diff --git a/vendor/github.com/golang/glog/glog_test.go b/vendor/github.com/golang/glog/glog_test.go deleted file mode 100644 index 0fb376e1f..000000000 --- a/vendor/github.com/golang/glog/glog_test.go +++ /dev/null @@ -1,415 +0,0 @@ -// Go support for leveled logs, analogous to https://code.google.com/p/google-glog/ -// -// Copyright 2013 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package glog - -import ( - "bytes" - "fmt" - stdLog "log" - "path/filepath" - "runtime" - "strconv" - "strings" - "testing" - "time" -) - -// Test that shortHostname works as advertised. -func TestShortHostname(t *testing.T) { - for hostname, expect := range map[string]string{ - "": "", - "host": "host", - "host.google.com": "host", - } { - if got := shortHostname(hostname); expect != got { - t.Errorf("shortHostname(%q): expected %q, got %q", hostname, expect, got) - } - } -} - -// flushBuffer wraps a bytes.Buffer to satisfy flushSyncWriter. -type flushBuffer struct { - bytes.Buffer -} - -func (f *flushBuffer) Flush() error { - return nil -} - -func (f *flushBuffer) Sync() error { - return nil -} - -// swap sets the log writers and returns the old array. -func (l *loggingT) swap(writers [numSeverity]flushSyncWriter) (old [numSeverity]flushSyncWriter) { - l.mu.Lock() - defer l.mu.Unlock() - old = l.file - for i, w := range writers { - logging.file[i] = w - } - return -} - -// newBuffers sets the log writers to all new byte buffers and returns the old array. -func (l *loggingT) newBuffers() [numSeverity]flushSyncWriter { - return l.swap([numSeverity]flushSyncWriter{new(flushBuffer), new(flushBuffer), new(flushBuffer), new(flushBuffer)}) -} - -// contents returns the specified log value as a string. -func contents(s severity) string { - return logging.file[s].(*flushBuffer).String() -} - -// contains reports whether the string is contained in the log. -func contains(s severity, str string, t *testing.T) bool { - return strings.Contains(contents(s), str) -} - -// setFlags configures the logging flags how the test expects them. -func setFlags() { - logging.toStderr = false -} - -// Test that Info works as advertised. -func TestInfo(t *testing.T) { - setFlags() - defer logging.swap(logging.newBuffers()) - Info("test") - if !contains(infoLog, "I", t) { - t.Errorf("Info has wrong character: %q", contents(infoLog)) - } - if !contains(infoLog, "test", t) { - t.Error("Info failed") - } -} - -func TestInfoDepth(t *testing.T) { - setFlags() - defer logging.swap(logging.newBuffers()) - - f := func() { InfoDepth(1, "depth-test1") } - - // The next three lines must stay together - _, _, wantLine, _ := runtime.Caller(0) - InfoDepth(0, "depth-test0") - f() - - msgs := strings.Split(strings.TrimSuffix(contents(infoLog), "\n"), "\n") - if len(msgs) != 2 { - t.Fatalf("Got %d lines, expected 2", len(msgs)) - } - - for i, m := range msgs { - if !strings.HasPrefix(m, "I") { - t.Errorf("InfoDepth[%d] has wrong character: %q", i, m) - } - w := fmt.Sprintf("depth-test%d", i) - if !strings.Contains(m, w) { - t.Errorf("InfoDepth[%d] missing %q: %q", i, w, m) - } - - // pull out the line number (between : and ]) - msg := m[strings.LastIndex(m, ":")+1:] - x := strings.Index(msg, "]") - if x < 0 { - t.Errorf("InfoDepth[%d]: missing ']': %q", i, m) - continue - } - line, err := strconv.Atoi(msg[:x]) - if err != nil { - t.Errorf("InfoDepth[%d]: bad line number: %q", i, m) - continue - } - wantLine++ - if wantLine != line { - t.Errorf("InfoDepth[%d]: got line %d, want %d", i, line, wantLine) - } - } -} - -func init() { - CopyStandardLogTo("INFO") -} - -// Test that CopyStandardLogTo panics on bad input. -func TestCopyStandardLogToPanic(t *testing.T) { - defer func() { - if s, ok := recover().(string); !ok || !strings.Contains(s, "LOG") { - t.Errorf(`CopyStandardLogTo("LOG") should have panicked: %v`, s) - } - }() - CopyStandardLogTo("LOG") -} - -// Test that using the standard log package logs to INFO. -func TestStandardLog(t *testing.T) { - setFlags() - defer logging.swap(logging.newBuffers()) - stdLog.Print("test") - if !contains(infoLog, "I", t) { - t.Errorf("Info has wrong character: %q", contents(infoLog)) - } - if !contains(infoLog, "test", t) { - t.Error("Info failed") - } -} - -// Test that the header has the correct format. -func TestHeader(t *testing.T) { - setFlags() - defer logging.swap(logging.newBuffers()) - defer func(previous func() time.Time) { timeNow = previous }(timeNow) - timeNow = func() time.Time { - return time.Date(2006, 1, 2, 15, 4, 5, .067890e9, time.Local) - } - pid = 1234 - Info("test") - var line int - format := "I0102 15:04:05.067890 1234 glog_test.go:%d] test\n" - n, err := fmt.Sscanf(contents(infoLog), format, &line) - if n != 1 || err != nil { - t.Errorf("log format error: %d elements, error %s:\n%s", n, err, contents(infoLog)) - } - // Scanf treats multiple spaces as equivalent to a single space, - // so check for correct space-padding also. - want := fmt.Sprintf(format, line) - if contents(infoLog) != want { - t.Errorf("log format error: got:\n\t%q\nwant:\t%q", contents(infoLog), want) - } -} - -// Test that an Error log goes to Warning and Info. -// Even in the Info log, the source character will be E, so the data should -// all be identical. -func TestError(t *testing.T) { - setFlags() - defer logging.swap(logging.newBuffers()) - Error("test") - if !contains(errorLog, "E", t) { - t.Errorf("Error has wrong character: %q", contents(errorLog)) - } - if !contains(errorLog, "test", t) { - t.Error("Error failed") - } - str := contents(errorLog) - if !contains(warningLog, str, t) { - t.Error("Warning failed") - } - if !contains(infoLog, str, t) { - t.Error("Info failed") - } -} - -// Test that a Warning log goes to Info. -// Even in the Info log, the source character will be W, so the data should -// all be identical. -func TestWarning(t *testing.T) { - setFlags() - defer logging.swap(logging.newBuffers()) - Warning("test") - if !contains(warningLog, "W", t) { - t.Errorf("Warning has wrong character: %q", contents(warningLog)) - } - if !contains(warningLog, "test", t) { - t.Error("Warning failed") - } - str := contents(warningLog) - if !contains(infoLog, str, t) { - t.Error("Info failed") - } -} - -// Test that a V log goes to Info. -func TestV(t *testing.T) { - setFlags() - defer logging.swap(logging.newBuffers()) - logging.verbosity.Set("2") - defer logging.verbosity.Set("0") - V(2).Info("test") - if !contains(infoLog, "I", t) { - t.Errorf("Info has wrong character: %q", contents(infoLog)) - } - if !contains(infoLog, "test", t) { - t.Error("Info failed") - } -} - -// Test that a vmodule enables a log in this file. -func TestVmoduleOn(t *testing.T) { - setFlags() - defer logging.swap(logging.newBuffers()) - logging.vmodule.Set("glog_test=2") - defer logging.vmodule.Set("") - if !V(1) { - t.Error("V not enabled for 1") - } - if !V(2) { - t.Error("V not enabled for 2") - } - if V(3) { - t.Error("V enabled for 3") - } - V(2).Info("test") - if !contains(infoLog, "I", t) { - t.Errorf("Info has wrong character: %q", contents(infoLog)) - } - if !contains(infoLog, "test", t) { - t.Error("Info failed") - } -} - -// Test that a vmodule of another file does not enable a log in this file. -func TestVmoduleOff(t *testing.T) { - setFlags() - defer logging.swap(logging.newBuffers()) - logging.vmodule.Set("notthisfile=2") - defer logging.vmodule.Set("") - for i := 1; i <= 3; i++ { - if V(Level(i)) { - t.Errorf("V enabled for %d", i) - } - } - V(2).Info("test") - if contents(infoLog) != "" { - t.Error("V logged incorrectly") - } -} - -// vGlobs are patterns that match/don't match this file at V=2. -var vGlobs = map[string]bool{ - // Easy to test the numeric match here. - "glog_test=1": false, // If -vmodule sets V to 1, V(2) will fail. - "glog_test=2": true, - "glog_test=3": true, // If -vmodule sets V to 1, V(3) will succeed. - // These all use 2 and check the patterns. All are true. - "*=2": true, - "?l*=2": true, - "????_*=2": true, - "??[mno]?_*t=2": true, - // These all use 2 and check the patterns. All are false. - "*x=2": false, - "m*=2": false, - "??_*=2": false, - "?[abc]?_*t=2": false, -} - -// Test that vmodule globbing works as advertised. -func testVmoduleGlob(pat string, match bool, t *testing.T) { - setFlags() - defer logging.swap(logging.newBuffers()) - defer logging.vmodule.Set("") - logging.vmodule.Set(pat) - if V(2) != Verbose(match) { - t.Errorf("incorrect match for %q: got %t expected %t", pat, V(2), match) - } -} - -// Test that a vmodule globbing works as advertised. -func TestVmoduleGlob(t *testing.T) { - for glob, match := range vGlobs { - testVmoduleGlob(glob, match, t) - } -} - -func TestRollover(t *testing.T) { - setFlags() - var err error - defer func(previous func(error)) { logExitFunc = previous }(logExitFunc) - logExitFunc = func(e error) { - err = e - } - defer func(previous uint64) { MaxSize = previous }(MaxSize) - MaxSize = 512 - - Info("x") // Be sure we have a file. - info, ok := logging.file[infoLog].(*syncBuffer) - if !ok { - t.Fatal("info wasn't created") - } - if err != nil { - t.Fatalf("info has initial error: %v", err) - } - fname0 := info.file.Name() - Info(strings.Repeat("x", int(MaxSize))) // force a rollover - if err != nil { - t.Fatalf("info has error after big write: %v", err) - } - - // Make sure the next log file gets a file name with a different - // time stamp. - // - // TODO: determine whether we need to support subsecond log - // rotation. C++ does not appear to handle this case (nor does it - // handle Daylight Savings Time properly). - time.Sleep(1 * time.Second) - - Info("x") // create a new file - if err != nil { - t.Fatalf("error after rotation: %v", err) - } - fname1 := info.file.Name() - if fname0 == fname1 { - t.Errorf("info.f.Name did not change: %v", fname0) - } - if info.nbytes >= MaxSize { - t.Errorf("file size was not reset: %d", info.nbytes) - } -} - -func TestLogBacktraceAt(t *testing.T) { - setFlags() - defer logging.swap(logging.newBuffers()) - // The peculiar style of this code simplifies line counting and maintenance of the - // tracing block below. - var infoLine string - setTraceLocation := func(file string, line int, ok bool, delta int) { - if !ok { - t.Fatal("could not get file:line") - } - _, file = filepath.Split(file) - infoLine = fmt.Sprintf("%s:%d", file, line+delta) - err := logging.traceLocation.Set(infoLine) - if err != nil { - t.Fatal("error setting log_backtrace_at: ", err) - } - } - { - // Start of tracing block. These lines know about each other's relative position. - _, file, line, ok := runtime.Caller(0) - setTraceLocation(file, line, ok, +2) // Two lines between Caller and Info calls. - Info("we want a stack trace here") - } - numAppearances := strings.Count(contents(infoLog), infoLine) - if numAppearances < 2 { - // Need 2 appearances, one in the log header and one in the trace: - // log_test.go:281: I0511 16:36:06.952398 02238 log_test.go:280] we want a stack trace here - // ... - // github.com/glog/glog_test.go:280 (0x41ba91) - // ... - // We could be more precise but that would require knowing the details - // of the traceback format, which may not be dependable. - t.Fatal("got no trace back; log is ", contents(infoLog)) - } -} - -func BenchmarkHeader(b *testing.B) { - for i := 0; i < b.N; i++ { - buf, _, _ := logging.header(infoLog, 0) - logging.putBuffer(buf) - } -} diff --git a/vendor/github.com/golang/protobuf/.gitignore b/vendor/github.com/golang/protobuf/.gitignore deleted file mode 100644 index 8f5b596b1..000000000 --- a/vendor/github.com/golang/protobuf/.gitignore +++ /dev/null @@ -1,16 +0,0 @@ -.DS_Store -*.[568ao] -*.ao -*.so -*.pyc -._* -.nfs.* -[568a].out -*~ -*.orig -core -_obj -_test -_testmain.go -protoc-gen-go/testdata/multi/*.pb.go -_conformance/_conformance diff --git a/vendor/github.com/golang/protobuf/.travis.yml b/vendor/github.com/golang/protobuf/.travis.yml deleted file mode 100644 index 93c67805b..000000000 --- a/vendor/github.com/golang/protobuf/.travis.yml +++ /dev/null @@ -1,18 +0,0 @@ -sudo: false -language: go -go: -- 1.6.x -- 1.7.x -- 1.8.x -- 1.9.x - -install: - - go get -v -d -t github.com/golang/protobuf/... - - curl -L https://github.com/google/protobuf/releases/download/v3.3.0/protoc-3.3.0-linux-x86_64.zip -o /tmp/protoc.zip - - unzip /tmp/protoc.zip -d $HOME/protoc - -env: - - PATH=$HOME/protoc/bin:$PATH - -script: - - make all test diff --git a/vendor/github.com/golang/protobuf/Make.protobuf b/vendor/github.com/golang/protobuf/Make.protobuf deleted file mode 100644 index 15071de10..000000000 --- a/vendor/github.com/golang/protobuf/Make.protobuf +++ /dev/null @@ -1,40 +0,0 @@ -# Go support for Protocol Buffers - Google's data interchange format -# -# Copyright 2010 The Go Authors. All rights reserved. -# https://github.com/golang/protobuf -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following disclaimer -# in the documentation and/or other materials provided with the -# distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived from -# this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -# Includable Makefile to add a rule for generating .pb.go files from .proto files -# (Google protocol buffer descriptions). -# Typical use if myproto.proto is a file in package mypackage in this directory: -# -# include $(GOROOT)/src/pkg/github.com/golang/protobuf/Make.protobuf - -%.pb.go: %.proto - protoc --go_out=. $< - diff --git a/vendor/github.com/golang/protobuf/Makefile b/vendor/github.com/golang/protobuf/Makefile deleted file mode 100644 index a1421d8b7..000000000 --- a/vendor/github.com/golang/protobuf/Makefile +++ /dev/null @@ -1,55 +0,0 @@ -# Go support for Protocol Buffers - Google's data interchange format -# -# Copyright 2010 The Go Authors. All rights reserved. -# https://github.com/golang/protobuf -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following disclaimer -# in the documentation and/or other materials provided with the -# distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived from -# this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - -all: install - -install: - go install ./proto ./jsonpb ./ptypes - go install ./protoc-gen-go - -test: - go test ./proto ./jsonpb ./ptypes - make -C protoc-gen-go/testdata test - -clean: - go clean ./... - -nuke: - go clean -i ./... - -regenerate: - make -C protoc-gen-go/descriptor regenerate - make -C protoc-gen-go/plugin regenerate - make -C protoc-gen-go/testdata regenerate - make -C proto/testdata regenerate - make -C jsonpb/jsonpb_test_proto regenerate - make -C _conformance regenerate diff --git a/vendor/github.com/golang/protobuf/README.md b/vendor/github.com/golang/protobuf/README.md deleted file mode 100644 index 207eb6b48..000000000 --- a/vendor/github.com/golang/protobuf/README.md +++ /dev/null @@ -1,243 +0,0 @@ -# Go support for Protocol Buffers - -[![Build Status](https://travis-ci.org/golang/protobuf.svg?branch=master)](https://travis-ci.org/golang/protobuf) - -Google's data interchange format. -Copyright 2010 The Go Authors. -https://github.com/golang/protobuf - -This package and the code it generates requires at least Go 1.4. - -This software implements Go bindings for protocol buffers. For -information about protocol buffers themselves, see - https://developers.google.com/protocol-buffers/ - -## Installation ## - -To use this software, you must: -- Install the standard C++ implementation of protocol buffers from - https://developers.google.com/protocol-buffers/ -- Of course, install the Go compiler and tools from - https://golang.org/ - See - https://golang.org/doc/install - for details or, if you are using gccgo, follow the instructions at - https://golang.org/doc/install/gccgo -- Grab the code from the repository and install the proto package. - The simplest way is to run `go get -u github.com/golang/protobuf/protoc-gen-go`. - The compiler plugin, protoc-gen-go, will be installed in $GOBIN, - defaulting to $GOPATH/bin. It must be in your $PATH for the protocol - compiler, protoc, to find it. - -This software has two parts: a 'protocol compiler plugin' that -generates Go source files that, once compiled, can access and manage -protocol buffers; and a library that implements run-time support for -encoding (marshaling), decoding (unmarshaling), and accessing protocol -buffers. - -There is support for gRPC in Go using protocol buffers. -See the note at the bottom of this file for details. - -There are no insertion points in the plugin. - - -## Using protocol buffers with Go ## - -Once the software is installed, there are two steps to using it. -First you must compile the protocol buffer definitions and then import -them, with the support library, into your program. - -To compile the protocol buffer definition, run protoc with the --go_out -parameter set to the directory you want to output the Go code to. - - protoc --go_out=. *.proto - -The generated files will be suffixed .pb.go. See the Test code below -for an example using such a file. - - -The package comment for the proto library contains text describing -the interface provided in Go for protocol buffers. Here is an edited -version. - -========== - -The proto package converts data structures to and from the -wire format of protocol buffers. It works in concert with the -Go source code generated for .proto files by the protocol compiler. - -A summary of the properties of the protocol buffer interface -for a protocol buffer variable v: - - - Names are turned from camel_case to CamelCase for export. - - There are no methods on v to set fields; just treat - them as structure fields. - - There are getters that return a field's value if set, - and return the field's default value if unset. - The getters work even if the receiver is a nil message. - - The zero value for a struct is its correct initialization state. - All desired fields must be set before marshaling. - - A Reset() method will restore a protobuf struct to its zero state. - - Non-repeated fields are pointers to the values; nil means unset. - That is, optional or required field int32 f becomes F *int32. - - Repeated fields are slices. - - Helper functions are available to aid the setting of fields. - Helpers for getting values are superseded by the - GetFoo methods and their use is deprecated. - msg.Foo = proto.String("hello") // set field - - Constants are defined to hold the default values of all fields that - have them. They have the form Default_StructName_FieldName. - Because the getter methods handle defaulted values, - direct use of these constants should be rare. - - Enums are given type names and maps from names to values. - Enum values are prefixed with the enum's type name. Enum types have - a String method, and a Enum method to assist in message construction. - - Nested groups and enums have type names prefixed with the name of - the surrounding message type. - - Extensions are given descriptor names that start with E_, - followed by an underscore-delimited list of the nested messages - that contain it (if any) followed by the CamelCased name of the - extension field itself. HasExtension, ClearExtension, GetExtension - and SetExtension are functions for manipulating extensions. - - Oneof field sets are given a single field in their message, - with distinguished wrapper types for each possible field value. - - Marshal and Unmarshal are functions to encode and decode the wire format. - -When the .proto file specifies `syntax="proto3"`, there are some differences: - - - Non-repeated fields of non-message type are values instead of pointers. - - Enum types do not get an Enum method. - -Consider file test.proto, containing - -```proto - syntax = "proto2"; - package example; - - enum FOO { X = 17; }; - - message Test { - required string label = 1; - optional int32 type = 2 [default=77]; - repeated int64 reps = 3; - optional group OptionalGroup = 4 { - required string RequiredField = 5; - } - } -``` - -To create and play with a Test object from the example package, - -```go - package main - - import ( - "log" - - "github.com/golang/protobuf/proto" - "path/to/example" - ) - - func main() { - test := &example.Test { - Label: proto.String("hello"), - Type: proto.Int32(17), - Reps: []int64{1, 2, 3}, - Optionalgroup: &example.Test_OptionalGroup { - RequiredField: proto.String("good bye"), - }, - } - data, err := proto.Marshal(test) - if err != nil { - log.Fatal("marshaling error: ", err) - } - newTest := &example.Test{} - err = proto.Unmarshal(data, newTest) - if err != nil { - log.Fatal("unmarshaling error: ", err) - } - // Now test and newTest contain the same data. - if test.GetLabel() != newTest.GetLabel() { - log.Fatalf("data mismatch %q != %q", test.GetLabel(), newTest.GetLabel()) - } - // etc. - } -``` - -## Parameters ## - -To pass extra parameters to the plugin, use a comma-separated -parameter list separated from the output directory by a colon: - - - protoc --go_out=plugins=grpc,import_path=mypackage:. *.proto - - -- `import_prefix=xxx` - a prefix that is added onto the beginning of - all imports. Useful for things like generating protos in a - subdirectory, or regenerating vendored protobufs in-place. -- `import_path=foo/bar` - used as the package if no input files - declare `go_package`. If it contains slashes, everything up to the - rightmost slash is ignored. -- `plugins=plugin1+plugin2` - specifies the list of sub-plugins to - load. The only plugin in this repo is `grpc`. -- `Mfoo/bar.proto=quux/shme` - declares that foo/bar.proto is - associated with Go package quux/shme. This is subject to the - import_prefix parameter. - -## gRPC Support ## - -If a proto file specifies RPC services, protoc-gen-go can be instructed to -generate code compatible with gRPC (http://www.grpc.io/). To do this, pass -the `plugins` parameter to protoc-gen-go; the usual way is to insert it into -the --go_out argument to protoc: - - protoc --go_out=plugins=grpc:. *.proto - -## Compatibility ## - -The library and the generated code are expected to be stable over time. -However, we reserve the right to make breaking changes without notice for the -following reasons: - -- Security. A security issue in the specification or implementation may come to - light whose resolution requires breaking compatibility. We reserve the right - to address such security issues. -- Unspecified behavior. There are some aspects of the Protocol Buffers - specification that are undefined. Programs that depend on such unspecified - behavior may break in future releases. -- Specification errors or changes. If it becomes necessary to address an - inconsistency, incompleteness, or change in the Protocol Buffers - specification, resolving the issue could affect the meaning or legality of - existing programs. We reserve the right to address such issues, including - updating the implementations. -- Bugs. If the library has a bug that violates the specification, a program - that depends on the buggy behavior may break if the bug is fixed. We reserve - the right to fix such bugs. -- Adding methods or fields to generated structs. These may conflict with field - names that already exist in a schema, causing applications to break. When the - code generator encounters a field in the schema that would collide with a - generated field or method name, the code generator will append an underscore - to the generated field or method name. -- Adding, removing, or changing methods or fields in generated structs that - start with `XXX`. These parts of the generated code are exported out of - necessity, but should not be considered part of the public API. -- Adding, removing, or changing unexported symbols in generated code. - -Any breaking changes outside of these will be announced 6 months in advance to -protobuf@googlegroups.com. - -You should, whenever possible, use generated code created by the `protoc-gen-go` -tool built at the same commit as the `proto` package. The `proto` package -declares package-level constants in the form `ProtoPackageIsVersionX`. -Application code and generated code may depend on one of these constants to -ensure that compilation will fail if the available version of the proto library -is too old. Whenever we make a change to the generated code that requires newer -library support, in the same commit we will increment the version number of the -generated code and declare a new package-level constant whose name incorporates -the latest version number. Removing a compatibility constant is considered a -breaking change and would be subject to the announcement policy stated above. - -The `protoc-gen-go/generator` package exposes a plugin interface, -which is used by the gRPC code generation. This interface is not -supported and is subject to incompatible changes without notice. diff --git a/vendor/github.com/golang/protobuf/jsonpb/jsonpb_test.go b/vendor/github.com/golang/protobuf/jsonpb/jsonpb_test.go deleted file mode 100644 index 2428d0566..000000000 --- a/vendor/github.com/golang/protobuf/jsonpb/jsonpb_test.go +++ /dev/null @@ -1,896 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2015 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package jsonpb - -import ( - "bytes" - "encoding/json" - "io" - "math" - "reflect" - "strings" - "testing" - - "github.com/golang/protobuf/proto" - - pb "github.com/golang/protobuf/jsonpb/jsonpb_test_proto" - proto3pb "github.com/golang/protobuf/proto/proto3_proto" - "github.com/golang/protobuf/ptypes" - anypb "github.com/golang/protobuf/ptypes/any" - durpb "github.com/golang/protobuf/ptypes/duration" - stpb "github.com/golang/protobuf/ptypes/struct" - tspb "github.com/golang/protobuf/ptypes/timestamp" - wpb "github.com/golang/protobuf/ptypes/wrappers" -) - -var ( - marshaler = Marshaler{} - - marshalerAllOptions = Marshaler{ - Indent: " ", - } - - simpleObject = &pb.Simple{ - OInt32: proto.Int32(-32), - OInt64: proto.Int64(-6400000000), - OUint32: proto.Uint32(32), - OUint64: proto.Uint64(6400000000), - OSint32: proto.Int32(-13), - OSint64: proto.Int64(-2600000000), - OFloat: proto.Float32(3.14), - ODouble: proto.Float64(6.02214179e23), - OBool: proto.Bool(true), - OString: proto.String("hello \"there\""), - OBytes: []byte("beep boop"), - } - - simpleObjectJSON = `{` + - `"oBool":true,` + - `"oInt32":-32,` + - `"oInt64":"-6400000000",` + - `"oUint32":32,` + - `"oUint64":"6400000000",` + - `"oSint32":-13,` + - `"oSint64":"-2600000000",` + - `"oFloat":3.14,` + - `"oDouble":6.02214179e+23,` + - `"oString":"hello \"there\"",` + - `"oBytes":"YmVlcCBib29w"` + - `}` - - simpleObjectPrettyJSON = `{ - "oBool": true, - "oInt32": -32, - "oInt64": "-6400000000", - "oUint32": 32, - "oUint64": "6400000000", - "oSint32": -13, - "oSint64": "-2600000000", - "oFloat": 3.14, - "oDouble": 6.02214179e+23, - "oString": "hello \"there\"", - "oBytes": "YmVlcCBib29w" -}` - - repeatsObject = &pb.Repeats{ - RBool: []bool{true, false, true}, - RInt32: []int32{-3, -4, -5}, - RInt64: []int64{-123456789, -987654321}, - RUint32: []uint32{1, 2, 3}, - RUint64: []uint64{6789012345, 3456789012}, - RSint32: []int32{-1, -2, -3}, - RSint64: []int64{-6789012345, -3456789012}, - RFloat: []float32{3.14, 6.28}, - RDouble: []float64{299792458 * 1e20, 6.62606957e-34}, - RString: []string{"happy", "days"}, - RBytes: [][]byte{[]byte("skittles"), []byte("m&m's")}, - } - - repeatsObjectJSON = `{` + - `"rBool":[true,false,true],` + - `"rInt32":[-3,-4,-5],` + - `"rInt64":["-123456789","-987654321"],` + - `"rUint32":[1,2,3],` + - `"rUint64":["6789012345","3456789012"],` + - `"rSint32":[-1,-2,-3],` + - `"rSint64":["-6789012345","-3456789012"],` + - `"rFloat":[3.14,6.28],` + - `"rDouble":[2.99792458e+28,6.62606957e-34],` + - `"rString":["happy","days"],` + - `"rBytes":["c2tpdHRsZXM=","bSZtJ3M="]` + - `}` - - repeatsObjectPrettyJSON = `{ - "rBool": [ - true, - false, - true - ], - "rInt32": [ - -3, - -4, - -5 - ], - "rInt64": [ - "-123456789", - "-987654321" - ], - "rUint32": [ - 1, - 2, - 3 - ], - "rUint64": [ - "6789012345", - "3456789012" - ], - "rSint32": [ - -1, - -2, - -3 - ], - "rSint64": [ - "-6789012345", - "-3456789012" - ], - "rFloat": [ - 3.14, - 6.28 - ], - "rDouble": [ - 2.99792458e+28, - 6.62606957e-34 - ], - "rString": [ - "happy", - "days" - ], - "rBytes": [ - "c2tpdHRsZXM=", - "bSZtJ3M=" - ] -}` - - innerSimple = &pb.Simple{OInt32: proto.Int32(-32)} - innerSimple2 = &pb.Simple{OInt64: proto.Int64(25)} - innerRepeats = &pb.Repeats{RString: []string{"roses", "red"}} - innerRepeats2 = &pb.Repeats{RString: []string{"violets", "blue"}} - complexObject = &pb.Widget{ - Color: pb.Widget_GREEN.Enum(), - RColor: []pb.Widget_Color{pb.Widget_RED, pb.Widget_GREEN, pb.Widget_BLUE}, - Simple: innerSimple, - RSimple: []*pb.Simple{innerSimple, innerSimple2}, - Repeats: innerRepeats, - RRepeats: []*pb.Repeats{innerRepeats, innerRepeats2}, - } - - complexObjectJSON = `{"color":"GREEN",` + - `"rColor":["RED","GREEN","BLUE"],` + - `"simple":{"oInt32":-32},` + - `"rSimple":[{"oInt32":-32},{"oInt64":"25"}],` + - `"repeats":{"rString":["roses","red"]},` + - `"rRepeats":[{"rString":["roses","red"]},{"rString":["violets","blue"]}]` + - `}` - - complexObjectPrettyJSON = `{ - "color": "GREEN", - "rColor": [ - "RED", - "GREEN", - "BLUE" - ], - "simple": { - "oInt32": -32 - }, - "rSimple": [ - { - "oInt32": -32 - }, - { - "oInt64": "25" - } - ], - "repeats": { - "rString": [ - "roses", - "red" - ] - }, - "rRepeats": [ - { - "rString": [ - "roses", - "red" - ] - }, - { - "rString": [ - "violets", - "blue" - ] - } - ] -}` - - colorPrettyJSON = `{ - "color": 2 -}` - - colorListPrettyJSON = `{ - "color": 1000, - "rColor": [ - "RED" - ] -}` - - nummyPrettyJSON = `{ - "nummy": { - "1": 2, - "3": 4 - } -}` - - objjyPrettyJSON = `{ - "objjy": { - "1": { - "dub": 1 - } - } -}` - realNumber = &pb.Real{Value: proto.Float64(3.14159265359)} - realNumberName = "Pi" - complexNumber = &pb.Complex{Imaginary: proto.Float64(0.5772156649)} - realNumberJSON = `{` + - `"value":3.14159265359,` + - `"[jsonpb.Complex.real_extension]":{"imaginary":0.5772156649},` + - `"[jsonpb.name]":"Pi"` + - `}` - - anySimple = &pb.KnownTypes{ - An: &anypb.Any{ - TypeUrl: "something.example.com/jsonpb.Simple", - Value: []byte{ - // &pb.Simple{OBool:true} - 1 << 3, 1, - }, - }, - } - anySimpleJSON = `{"an":{"@type":"something.example.com/jsonpb.Simple","oBool":true}}` - anySimplePrettyJSON = `{ - "an": { - "@type": "something.example.com/jsonpb.Simple", - "oBool": true - } -}` - - anyWellKnown = &pb.KnownTypes{ - An: &anypb.Any{ - TypeUrl: "type.googleapis.com/google.protobuf.Duration", - Value: []byte{ - // &durpb.Duration{Seconds: 1, Nanos: 212000000 } - 1 << 3, 1, // seconds - 2 << 3, 0x80, 0xba, 0x8b, 0x65, // nanos - }, - }, - } - anyWellKnownJSON = `{"an":{"@type":"type.googleapis.com/google.protobuf.Duration","value":"1.212s"}}` - anyWellKnownPrettyJSON = `{ - "an": { - "@type": "type.googleapis.com/google.protobuf.Duration", - "value": "1.212s" - } -}` - - nonFinites = &pb.NonFinites{ - FNan: proto.Float32(float32(math.NaN())), - FPinf: proto.Float32(float32(math.Inf(1))), - FNinf: proto.Float32(float32(math.Inf(-1))), - DNan: proto.Float64(float64(math.NaN())), - DPinf: proto.Float64(float64(math.Inf(1))), - DNinf: proto.Float64(float64(math.Inf(-1))), - } - nonFinitesJSON = `{` + - `"fNan":"NaN",` + - `"fPinf":"Infinity",` + - `"fNinf":"-Infinity",` + - `"dNan":"NaN",` + - `"dPinf":"Infinity",` + - `"dNinf":"-Infinity"` + - `}` -) - -func init() { - if err := proto.SetExtension(realNumber, pb.E_Name, &realNumberName); err != nil { - panic(err) - } - if err := proto.SetExtension(realNumber, pb.E_Complex_RealExtension, complexNumber); err != nil { - panic(err) - } -} - -var marshalingTests = []struct { - desc string - marshaler Marshaler - pb proto.Message - json string -}{ - {"simple flat object", marshaler, simpleObject, simpleObjectJSON}, - {"simple pretty object", marshalerAllOptions, simpleObject, simpleObjectPrettyJSON}, - {"non-finite floats fields object", marshaler, nonFinites, nonFinitesJSON}, - {"repeated fields flat object", marshaler, repeatsObject, repeatsObjectJSON}, - {"repeated fields pretty object", marshalerAllOptions, repeatsObject, repeatsObjectPrettyJSON}, - {"nested message/enum flat object", marshaler, complexObject, complexObjectJSON}, - {"nested message/enum pretty object", marshalerAllOptions, complexObject, complexObjectPrettyJSON}, - {"enum-string flat object", Marshaler{}, - &pb.Widget{Color: pb.Widget_BLUE.Enum()}, `{"color":"BLUE"}`}, - {"enum-value pretty object", Marshaler{EnumsAsInts: true, Indent: " "}, - &pb.Widget{Color: pb.Widget_BLUE.Enum()}, colorPrettyJSON}, - {"unknown enum value object", marshalerAllOptions, - &pb.Widget{Color: pb.Widget_Color(1000).Enum(), RColor: []pb.Widget_Color{pb.Widget_RED}}, colorListPrettyJSON}, - {"repeated proto3 enum", Marshaler{}, - &proto3pb.Message{RFunny: []proto3pb.Message_Humour{ - proto3pb.Message_PUNS, - proto3pb.Message_SLAPSTICK, - }}, - `{"rFunny":["PUNS","SLAPSTICK"]}`}, - {"repeated proto3 enum as int", Marshaler{EnumsAsInts: true}, - &proto3pb.Message{RFunny: []proto3pb.Message_Humour{ - proto3pb.Message_PUNS, - proto3pb.Message_SLAPSTICK, - }}, - `{"rFunny":[1,2]}`}, - {"empty value", marshaler, &pb.Simple3{}, `{}`}, - {"empty value emitted", Marshaler{EmitDefaults: true}, &pb.Simple3{}, `{"dub":0}`}, - {"empty repeated emitted", Marshaler{EmitDefaults: true}, &pb.SimpleSlice3{}, `{"slices":[]}`}, - {"empty map emitted", Marshaler{EmitDefaults: true}, &pb.SimpleMap3{}, `{"stringy":{}}`}, - {"nested struct null", Marshaler{EmitDefaults: true}, &pb.SimpleNull3{}, `{"simple":null}`}, - {"map", marshaler, &pb.Mappy{Nummy: map[int64]int32{1: 2, 3: 4}}, `{"nummy":{"1":2,"3":4}}`}, - {"map", marshalerAllOptions, &pb.Mappy{Nummy: map[int64]int32{1: 2, 3: 4}}, nummyPrettyJSON}, - {"map", marshaler, - &pb.Mappy{Strry: map[string]string{`"one"`: "two", "three": "four"}}, - `{"strry":{"\"one\"":"two","three":"four"}}`}, - {"map", marshaler, - &pb.Mappy{Objjy: map[int32]*pb.Simple3{1: {Dub: 1}}}, `{"objjy":{"1":{"dub":1}}}`}, - {"map", marshalerAllOptions, - &pb.Mappy{Objjy: map[int32]*pb.Simple3{1: {Dub: 1}}}, objjyPrettyJSON}, - {"map", marshaler, &pb.Mappy{Buggy: map[int64]string{1234: "yup"}}, - `{"buggy":{"1234":"yup"}}`}, - {"map", marshaler, &pb.Mappy{Booly: map[bool]bool{false: true}}, `{"booly":{"false":true}}`}, - // TODO: This is broken. - //{"map", marshaler, &pb.Mappy{Enumy: map[string]pb.Numeral{"XIV": pb.Numeral_ROMAN}}, `{"enumy":{"XIV":"ROMAN"}`}, - {"map", Marshaler{EnumsAsInts: true}, &pb.Mappy{Enumy: map[string]pb.Numeral{"XIV": pb.Numeral_ROMAN}}, `{"enumy":{"XIV":2}}`}, - {"map", marshaler, &pb.Mappy{S32Booly: map[int32]bool{1: true, 3: false, 10: true, 12: false}}, `{"s32booly":{"1":true,"3":false,"10":true,"12":false}}`}, - {"map", marshaler, &pb.Mappy{S64Booly: map[int64]bool{1: true, 3: false, 10: true, 12: false}}, `{"s64booly":{"1":true,"3":false,"10":true,"12":false}}`}, - {"map", marshaler, &pb.Mappy{U32Booly: map[uint32]bool{1: true, 3: false, 10: true, 12: false}}, `{"u32booly":{"1":true,"3":false,"10":true,"12":false}}`}, - {"map", marshaler, &pb.Mappy{U64Booly: map[uint64]bool{1: true, 3: false, 10: true, 12: false}}, `{"u64booly":{"1":true,"3":false,"10":true,"12":false}}`}, - {"proto2 map", marshaler, &pb.Maps{MInt64Str: map[int64]string{213: "cat"}}, - `{"mInt64Str":{"213":"cat"}}`}, - {"proto2 map", marshaler, - &pb.Maps{MBoolSimple: map[bool]*pb.Simple{true: {OInt32: proto.Int32(1)}}}, - `{"mBoolSimple":{"true":{"oInt32":1}}}`}, - {"oneof, not set", marshaler, &pb.MsgWithOneof{}, `{}`}, - {"oneof, set", marshaler, &pb.MsgWithOneof{Union: &pb.MsgWithOneof_Title{"Grand Poobah"}}, `{"title":"Grand Poobah"}`}, - {"force orig_name", Marshaler{OrigName: true}, &pb.Simple{OInt32: proto.Int32(4)}, - `{"o_int32":4}`}, - {"proto2 extension", marshaler, realNumber, realNumberJSON}, - {"Any with message", marshaler, anySimple, anySimpleJSON}, - {"Any with message and indent", marshalerAllOptions, anySimple, anySimplePrettyJSON}, - {"Any with WKT", marshaler, anyWellKnown, anyWellKnownJSON}, - {"Any with WKT and indent", marshalerAllOptions, anyWellKnown, anyWellKnownPrettyJSON}, - {"Duration", marshaler, &pb.KnownTypes{Dur: &durpb.Duration{Seconds: 3}}, `{"dur":"3.000s"}`}, - {"Struct", marshaler, &pb.KnownTypes{St: &stpb.Struct{ - Fields: map[string]*stpb.Value{ - "one": {Kind: &stpb.Value_StringValue{"loneliest number"}}, - "two": {Kind: &stpb.Value_NullValue{stpb.NullValue_NULL_VALUE}}, - }, - }}, `{"st":{"one":"loneliest number","two":null}}`}, - {"empty ListValue", marshaler, &pb.KnownTypes{Lv: &stpb.ListValue{}}, `{"lv":[]}`}, - {"basic ListValue", marshaler, &pb.KnownTypes{Lv: &stpb.ListValue{Values: []*stpb.Value{ - {Kind: &stpb.Value_StringValue{"x"}}, - {Kind: &stpb.Value_NullValue{}}, - {Kind: &stpb.Value_NumberValue{3}}, - {Kind: &stpb.Value_BoolValue{true}}, - }}}, `{"lv":["x",null,3,true]}`}, - {"Timestamp", marshaler, &pb.KnownTypes{Ts: &tspb.Timestamp{Seconds: 14e8, Nanos: 21e6}}, `{"ts":"2014-05-13T16:53:20.021Z"}`}, - {"number Value", marshaler, &pb.KnownTypes{Val: &stpb.Value{Kind: &stpb.Value_NumberValue{1}}}, `{"val":1}`}, - {"null Value", marshaler, &pb.KnownTypes{Val: &stpb.Value{Kind: &stpb.Value_NullValue{stpb.NullValue_NULL_VALUE}}}, `{"val":null}`}, - {"string number value", marshaler, &pb.KnownTypes{Val: &stpb.Value{Kind: &stpb.Value_StringValue{"9223372036854775807"}}}, `{"val":"9223372036854775807"}`}, - {"list of lists Value", marshaler, &pb.KnownTypes{Val: &stpb.Value{ - Kind: &stpb.Value_ListValue{&stpb.ListValue{ - Values: []*stpb.Value{ - {Kind: &stpb.Value_StringValue{"x"}}, - {Kind: &stpb.Value_ListValue{&stpb.ListValue{ - Values: []*stpb.Value{ - {Kind: &stpb.Value_ListValue{&stpb.ListValue{ - Values: []*stpb.Value{{Kind: &stpb.Value_StringValue{"y"}}}, - }}}, - {Kind: &stpb.Value_StringValue{"z"}}, - }, - }}}, - }, - }}, - }}, `{"val":["x",[["y"],"z"]]}`}, - - {"DoubleValue", marshaler, &pb.KnownTypes{Dbl: &wpb.DoubleValue{Value: 1.2}}, `{"dbl":1.2}`}, - {"FloatValue", marshaler, &pb.KnownTypes{Flt: &wpb.FloatValue{Value: 1.2}}, `{"flt":1.2}`}, - {"Int64Value", marshaler, &pb.KnownTypes{I64: &wpb.Int64Value{Value: -3}}, `{"i64":"-3"}`}, - {"UInt64Value", marshaler, &pb.KnownTypes{U64: &wpb.UInt64Value{Value: 3}}, `{"u64":"3"}`}, - {"Int32Value", marshaler, &pb.KnownTypes{I32: &wpb.Int32Value{Value: -4}}, `{"i32":-4}`}, - {"UInt32Value", marshaler, &pb.KnownTypes{U32: &wpb.UInt32Value{Value: 4}}, `{"u32":4}`}, - {"BoolValue", marshaler, &pb.KnownTypes{Bool: &wpb.BoolValue{Value: true}}, `{"bool":true}`}, - {"StringValue", marshaler, &pb.KnownTypes{Str: &wpb.StringValue{Value: "plush"}}, `{"str":"plush"}`}, - {"BytesValue", marshaler, &pb.KnownTypes{Bytes: &wpb.BytesValue{Value: []byte("wow")}}, `{"bytes":"d293"}`}, -} - -func TestMarshaling(t *testing.T) { - for _, tt := range marshalingTests { - json, err := tt.marshaler.MarshalToString(tt.pb) - if err != nil { - t.Errorf("%s: marshaling error: %v", tt.desc, err) - } else if tt.json != json { - t.Errorf("%s: got [%v] want [%v]", tt.desc, json, tt.json) - } - } -} - -func TestMarshalJSONPBMarshaler(t *testing.T) { - rawJson := `{ "foo": "bar", "baz": [0, 1, 2, 3] }` - msg := dynamicMessage{rawJson: rawJson} - str, err := new(Marshaler).MarshalToString(&msg) - if err != nil { - t.Errorf("an unexpected error occurred when marshalling JSONPBMarshaler: %v", err) - } - if str != rawJson { - t.Errorf("marshalling JSON produced incorrect output: got %s, wanted %s", str, rawJson) - } -} - -func TestMarshalAnyJSONPBMarshaler(t *testing.T) { - msg := dynamicMessage{rawJson: `{ "foo": "bar", "baz": [0, 1, 2, 3] }`} - a, err := ptypes.MarshalAny(&msg) - if err != nil { - t.Errorf("an unexpected error occurred when marshalling to Any: %v", err) - } - str, err := new(Marshaler).MarshalToString(a) - if err != nil { - t.Errorf("an unexpected error occurred when marshalling Any to JSON: %v", err) - } - // after custom marshaling, it's round-tripped through JSON decoding/encoding already, - // so the keys are sorted, whitespace is compacted, and "@type" key has been added - expected := `{"@type":"type.googleapis.com/` + dynamicMessageName + `","baz":[0,1,2,3],"foo":"bar"}` - if str != expected { - t.Errorf("marshalling JSON produced incorrect output: got %s, wanted %s", str, expected) - } -} - -var unmarshalingTests = []struct { - desc string - unmarshaler Unmarshaler - json string - pb proto.Message -}{ - {"simple flat object", Unmarshaler{}, simpleObjectJSON, simpleObject}, - {"simple pretty object", Unmarshaler{}, simpleObjectPrettyJSON, simpleObject}, - {"repeated fields flat object", Unmarshaler{}, repeatsObjectJSON, repeatsObject}, - {"repeated fields pretty object", Unmarshaler{}, repeatsObjectPrettyJSON, repeatsObject}, - {"nested message/enum flat object", Unmarshaler{}, complexObjectJSON, complexObject}, - {"nested message/enum pretty object", Unmarshaler{}, complexObjectPrettyJSON, complexObject}, - {"enum-string object", Unmarshaler{}, `{"color":"BLUE"}`, &pb.Widget{Color: pb.Widget_BLUE.Enum()}}, - {"enum-value object", Unmarshaler{}, "{\n \"color\": 2\n}", &pb.Widget{Color: pb.Widget_BLUE.Enum()}}, - {"unknown field with allowed option", Unmarshaler{AllowUnknownFields: true}, `{"unknown": "foo"}`, new(pb.Simple)}, - {"proto3 enum string", Unmarshaler{}, `{"hilarity":"PUNS"}`, &proto3pb.Message{Hilarity: proto3pb.Message_PUNS}}, - {"proto3 enum value", Unmarshaler{}, `{"hilarity":1}`, &proto3pb.Message{Hilarity: proto3pb.Message_PUNS}}, - {"unknown enum value object", - Unmarshaler{}, - "{\n \"color\": 1000,\n \"r_color\": [\n \"RED\"\n ]\n}", - &pb.Widget{Color: pb.Widget_Color(1000).Enum(), RColor: []pb.Widget_Color{pb.Widget_RED}}}, - {"repeated proto3 enum", Unmarshaler{}, `{"rFunny":["PUNS","SLAPSTICK"]}`, - &proto3pb.Message{RFunny: []proto3pb.Message_Humour{ - proto3pb.Message_PUNS, - proto3pb.Message_SLAPSTICK, - }}}, - {"repeated proto3 enum as int", Unmarshaler{}, `{"rFunny":[1,2]}`, - &proto3pb.Message{RFunny: []proto3pb.Message_Humour{ - proto3pb.Message_PUNS, - proto3pb.Message_SLAPSTICK, - }}}, - {"repeated proto3 enum as mix of strings and ints", Unmarshaler{}, `{"rFunny":["PUNS",2]}`, - &proto3pb.Message{RFunny: []proto3pb.Message_Humour{ - proto3pb.Message_PUNS, - proto3pb.Message_SLAPSTICK, - }}}, - {"unquoted int64 object", Unmarshaler{}, `{"oInt64":-314}`, &pb.Simple{OInt64: proto.Int64(-314)}}, - {"unquoted uint64 object", Unmarshaler{}, `{"oUint64":123}`, &pb.Simple{OUint64: proto.Uint64(123)}}, - {"NaN", Unmarshaler{}, `{"oDouble":"NaN"}`, &pb.Simple{ODouble: proto.Float64(math.NaN())}}, - {"Inf", Unmarshaler{}, `{"oFloat":"Infinity"}`, &pb.Simple{OFloat: proto.Float32(float32(math.Inf(1)))}}, - {"-Inf", Unmarshaler{}, `{"oDouble":"-Infinity"}`, &pb.Simple{ODouble: proto.Float64(math.Inf(-1))}}, - {"map", Unmarshaler{}, `{"nummy":{"1":2,"3":4}}`, &pb.Mappy{Nummy: map[int64]int32{1: 2, 3: 4}}}, - {"map", Unmarshaler{}, `{"strry":{"\"one\"":"two","three":"four"}}`, &pb.Mappy{Strry: map[string]string{`"one"`: "two", "three": "four"}}}, - {"map", Unmarshaler{}, `{"objjy":{"1":{"dub":1}}}`, &pb.Mappy{Objjy: map[int32]*pb.Simple3{1: {Dub: 1}}}}, - {"proto2 extension", Unmarshaler{}, realNumberJSON, realNumber}, - {"Any with message", Unmarshaler{}, anySimpleJSON, anySimple}, - {"Any with message and indent", Unmarshaler{}, anySimplePrettyJSON, anySimple}, - {"Any with WKT", Unmarshaler{}, anyWellKnownJSON, anyWellKnown}, - {"Any with WKT and indent", Unmarshaler{}, anyWellKnownPrettyJSON, anyWellKnown}, - // TODO: This is broken. - //{"map", Unmarshaler{}, `{"enumy":{"XIV":"ROMAN"}`, &pb.Mappy{Enumy: map[string]pb.Numeral{"XIV": pb.Numeral_ROMAN}}}, - {"map", Unmarshaler{}, `{"enumy":{"XIV":2}}`, &pb.Mappy{Enumy: map[string]pb.Numeral{"XIV": pb.Numeral_ROMAN}}}, - {"oneof", Unmarshaler{}, `{"salary":31000}`, &pb.MsgWithOneof{Union: &pb.MsgWithOneof_Salary{31000}}}, - {"oneof spec name", Unmarshaler{}, `{"Country":"Australia"}`, &pb.MsgWithOneof{Union: &pb.MsgWithOneof_Country{"Australia"}}}, - {"oneof orig_name", Unmarshaler{}, `{"Country":"Australia"}`, &pb.MsgWithOneof{Union: &pb.MsgWithOneof_Country{"Australia"}}}, - {"oneof spec name2", Unmarshaler{}, `{"homeAddress":"Australia"}`, &pb.MsgWithOneof{Union: &pb.MsgWithOneof_HomeAddress{"Australia"}}}, - {"oneof orig_name2", Unmarshaler{}, `{"home_address":"Australia"}`, &pb.MsgWithOneof{Union: &pb.MsgWithOneof_HomeAddress{"Australia"}}}, - {"orig_name input", Unmarshaler{}, `{"o_bool":true}`, &pb.Simple{OBool: proto.Bool(true)}}, - {"camelName input", Unmarshaler{}, `{"oBool":true}`, &pb.Simple{OBool: proto.Bool(true)}}, - - {"Duration", Unmarshaler{}, `{"dur":"3.000s"}`, &pb.KnownTypes{Dur: &durpb.Duration{Seconds: 3}}}, - {"null Duration", Unmarshaler{}, `{"dur":null}`, &pb.KnownTypes{Dur: nil}}, - {"Timestamp", Unmarshaler{}, `{"ts":"2014-05-13T16:53:20.021Z"}`, &pb.KnownTypes{Ts: &tspb.Timestamp{Seconds: 14e8, Nanos: 21e6}}}, - {"PreEpochTimestamp", Unmarshaler{}, `{"ts":"1969-12-31T23:59:58.999999995Z"}`, &pb.KnownTypes{Ts: &tspb.Timestamp{Seconds: -2, Nanos: 999999995}}}, - {"ZeroTimeTimestamp", Unmarshaler{}, `{"ts":"0001-01-01T00:00:00Z"}`, &pb.KnownTypes{Ts: &tspb.Timestamp{Seconds: -62135596800, Nanos: 0}}}, - {"null Timestamp", Unmarshaler{}, `{"ts":null}`, &pb.KnownTypes{Ts: nil}}, - {"null Struct", Unmarshaler{}, `{"st": null}`, &pb.KnownTypes{St: nil}}, - {"empty Struct", Unmarshaler{}, `{"st": {}}`, &pb.KnownTypes{St: &stpb.Struct{}}}, - {"basic Struct", Unmarshaler{}, `{"st": {"a": "x", "b": null, "c": 3, "d": true}}`, &pb.KnownTypes{St: &stpb.Struct{Fields: map[string]*stpb.Value{ - "a": {Kind: &stpb.Value_StringValue{"x"}}, - "b": {Kind: &stpb.Value_NullValue{}}, - "c": {Kind: &stpb.Value_NumberValue{3}}, - "d": {Kind: &stpb.Value_BoolValue{true}}, - }}}}, - {"nested Struct", Unmarshaler{}, `{"st": {"a": {"b": 1, "c": [{"d": true}, "f"]}}}`, &pb.KnownTypes{St: &stpb.Struct{Fields: map[string]*stpb.Value{ - "a": {Kind: &stpb.Value_StructValue{&stpb.Struct{Fields: map[string]*stpb.Value{ - "b": {Kind: &stpb.Value_NumberValue{1}}, - "c": {Kind: &stpb.Value_ListValue{&stpb.ListValue{Values: []*stpb.Value{ - {Kind: &stpb.Value_StructValue{&stpb.Struct{Fields: map[string]*stpb.Value{"d": {Kind: &stpb.Value_BoolValue{true}}}}}}, - {Kind: &stpb.Value_StringValue{"f"}}, - }}}}, - }}}}, - }}}}, - {"null ListValue", Unmarshaler{}, `{"lv": null}`, &pb.KnownTypes{Lv: nil}}, - {"empty ListValue", Unmarshaler{}, `{"lv": []}`, &pb.KnownTypes{Lv: &stpb.ListValue{}}}, - {"basic ListValue", Unmarshaler{}, `{"lv": ["x", null, 3, true]}`, &pb.KnownTypes{Lv: &stpb.ListValue{Values: []*stpb.Value{ - {Kind: &stpb.Value_StringValue{"x"}}, - {Kind: &stpb.Value_NullValue{}}, - {Kind: &stpb.Value_NumberValue{3}}, - {Kind: &stpb.Value_BoolValue{true}}, - }}}}, - {"number Value", Unmarshaler{}, `{"val":1}`, &pb.KnownTypes{Val: &stpb.Value{Kind: &stpb.Value_NumberValue{1}}}}, - {"null Value", Unmarshaler{}, `{"val":null}`, &pb.KnownTypes{Val: &stpb.Value{Kind: &stpb.Value_NullValue{stpb.NullValue_NULL_VALUE}}}}, - {"bool Value", Unmarshaler{}, `{"val":true}`, &pb.KnownTypes{Val: &stpb.Value{Kind: &stpb.Value_BoolValue{true}}}}, - {"string Value", Unmarshaler{}, `{"val":"x"}`, &pb.KnownTypes{Val: &stpb.Value{Kind: &stpb.Value_StringValue{"x"}}}}, - {"string number value", Unmarshaler{}, `{"val":"9223372036854775807"}`, &pb.KnownTypes{Val: &stpb.Value{Kind: &stpb.Value_StringValue{"9223372036854775807"}}}}, - {"list of lists Value", Unmarshaler{}, `{"val":["x", [["y"], "z"]]}`, &pb.KnownTypes{Val: &stpb.Value{ - Kind: &stpb.Value_ListValue{&stpb.ListValue{ - Values: []*stpb.Value{ - {Kind: &stpb.Value_StringValue{"x"}}, - {Kind: &stpb.Value_ListValue{&stpb.ListValue{ - Values: []*stpb.Value{ - {Kind: &stpb.Value_ListValue{&stpb.ListValue{ - Values: []*stpb.Value{{Kind: &stpb.Value_StringValue{"y"}}}, - }}}, - {Kind: &stpb.Value_StringValue{"z"}}, - }, - }}}, - }, - }}}}}, - - {"DoubleValue", Unmarshaler{}, `{"dbl":1.2}`, &pb.KnownTypes{Dbl: &wpb.DoubleValue{Value: 1.2}}}, - {"FloatValue", Unmarshaler{}, `{"flt":1.2}`, &pb.KnownTypes{Flt: &wpb.FloatValue{Value: 1.2}}}, - {"Int64Value", Unmarshaler{}, `{"i64":"-3"}`, &pb.KnownTypes{I64: &wpb.Int64Value{Value: -3}}}, - {"UInt64Value", Unmarshaler{}, `{"u64":"3"}`, &pb.KnownTypes{U64: &wpb.UInt64Value{Value: 3}}}, - {"Int32Value", Unmarshaler{}, `{"i32":-4}`, &pb.KnownTypes{I32: &wpb.Int32Value{Value: -4}}}, - {"UInt32Value", Unmarshaler{}, `{"u32":4}`, &pb.KnownTypes{U32: &wpb.UInt32Value{Value: 4}}}, - {"BoolValue", Unmarshaler{}, `{"bool":true}`, &pb.KnownTypes{Bool: &wpb.BoolValue{Value: true}}}, - {"StringValue", Unmarshaler{}, `{"str":"plush"}`, &pb.KnownTypes{Str: &wpb.StringValue{Value: "plush"}}}, - {"BytesValue", Unmarshaler{}, `{"bytes":"d293"}`, &pb.KnownTypes{Bytes: &wpb.BytesValue{Value: []byte("wow")}}}, - - // Ensure that `null` as a value ends up with a nil pointer instead of a [type]Value struct. - {"null DoubleValue", Unmarshaler{}, `{"dbl":null}`, &pb.KnownTypes{Dbl: nil}}, - {"null FloatValue", Unmarshaler{}, `{"flt":null}`, &pb.KnownTypes{Flt: nil}}, - {"null Int64Value", Unmarshaler{}, `{"i64":null}`, &pb.KnownTypes{I64: nil}}, - {"null UInt64Value", Unmarshaler{}, `{"u64":null}`, &pb.KnownTypes{U64: nil}}, - {"null Int32Value", Unmarshaler{}, `{"i32":null}`, &pb.KnownTypes{I32: nil}}, - {"null UInt32Value", Unmarshaler{}, `{"u32":null}`, &pb.KnownTypes{U32: nil}}, - {"null BoolValue", Unmarshaler{}, `{"bool":null}`, &pb.KnownTypes{Bool: nil}}, - {"null StringValue", Unmarshaler{}, `{"str":null}`, &pb.KnownTypes{Str: nil}}, - {"null BytesValue", Unmarshaler{}, `{"bytes":null}`, &pb.KnownTypes{Bytes: nil}}, -} - -func TestUnmarshaling(t *testing.T) { - for _, tt := range unmarshalingTests { - // Make a new instance of the type of our expected object. - p := reflect.New(reflect.TypeOf(tt.pb).Elem()).Interface().(proto.Message) - - err := tt.unmarshaler.Unmarshal(strings.NewReader(tt.json), p) - if err != nil { - t.Errorf("%s: %v", tt.desc, err) - continue - } - - // For easier diffs, compare text strings of the protos. - exp := proto.MarshalTextString(tt.pb) - act := proto.MarshalTextString(p) - if string(exp) != string(act) { - t.Errorf("%s: got [%s] want [%s]", tt.desc, act, exp) - } - } -} - -func TestUnmarshalNullArray(t *testing.T) { - var repeats pb.Repeats - if err := UnmarshalString(`{"rBool":null}`, &repeats); err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(repeats, pb.Repeats{}) { - t.Errorf("got non-nil fields in [%#v]", repeats) - } -} - -func TestUnmarshalNullObject(t *testing.T) { - var maps pb.Maps - if err := UnmarshalString(`{"mInt64Str":null}`, &maps); err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(maps, pb.Maps{}) { - t.Errorf("got non-nil fields in [%#v]", maps) - } -} - -func TestUnmarshalNext(t *testing.T) { - // We only need to check against a few, not all of them. - tests := unmarshalingTests[:5] - - // Create a buffer with many concatenated JSON objects. - var b bytes.Buffer - for _, tt := range tests { - b.WriteString(tt.json) - } - - dec := json.NewDecoder(&b) - for _, tt := range tests { - // Make a new instance of the type of our expected object. - p := reflect.New(reflect.TypeOf(tt.pb).Elem()).Interface().(proto.Message) - - err := tt.unmarshaler.UnmarshalNext(dec, p) - if err != nil { - t.Errorf("%s: %v", tt.desc, err) - continue - } - - // For easier diffs, compare text strings of the protos. - exp := proto.MarshalTextString(tt.pb) - act := proto.MarshalTextString(p) - if string(exp) != string(act) { - t.Errorf("%s: got [%s] want [%s]", tt.desc, act, exp) - } - } - - p := &pb.Simple{} - err := new(Unmarshaler).UnmarshalNext(dec, p) - if err != io.EOF { - t.Errorf("eof: got %v, expected io.EOF", err) - } -} - -var unmarshalingShouldError = []struct { - desc string - in string - pb proto.Message -}{ - {"a value", "666", new(pb.Simple)}, - {"gibberish", "{adskja123;l23=-=", new(pb.Simple)}, - {"unknown field", `{"unknown": "foo"}`, new(pb.Simple)}, - {"unknown enum name", `{"hilarity":"DAVE"}`, new(proto3pb.Message)}, -} - -func TestUnmarshalingBadInput(t *testing.T) { - for _, tt := range unmarshalingShouldError { - err := UnmarshalString(tt.in, tt.pb) - if err == nil { - t.Errorf("an error was expected when parsing %q instead of an object", tt.desc) - } - } -} - -type funcResolver func(turl string) (proto.Message, error) - -func (fn funcResolver) Resolve(turl string) (proto.Message, error) { - return fn(turl) -} - -func TestAnyWithCustomResolver(t *testing.T) { - var resolvedTypeUrls []string - resolver := funcResolver(func(turl string) (proto.Message, error) { - resolvedTypeUrls = append(resolvedTypeUrls, turl) - return new(pb.Simple), nil - }) - msg := &pb.Simple{ - OBytes: []byte{1, 2, 3, 4}, - OBool: proto.Bool(true), - OString: proto.String("foobar"), - OInt64: proto.Int64(1020304), - } - msgBytes, err := proto.Marshal(msg) - if err != nil { - t.Errorf("an unexpected error occurred when marshaling message: %v", err) - } - // make an Any with a type URL that won't resolve w/out custom resolver - any := &anypb.Any{ - TypeUrl: "https://foobar.com/some.random.MessageKind", - Value: msgBytes, - } - - m := Marshaler{AnyResolver: resolver} - js, err := m.MarshalToString(any) - if err != nil { - t.Errorf("an unexpected error occurred when marshaling any to JSON: %v", err) - } - if len(resolvedTypeUrls) != 1 { - t.Errorf("custom resolver was not invoked during marshaling") - } else if resolvedTypeUrls[0] != "https://foobar.com/some.random.MessageKind" { - t.Errorf("custom resolver was invoked with wrong URL: got %q, wanted %q", resolvedTypeUrls[0], "https://foobar.com/some.random.MessageKind") - } - wanted := `{"@type":"https://foobar.com/some.random.MessageKind","oBool":true,"oInt64":"1020304","oString":"foobar","oBytes":"AQIDBA=="}` - if js != wanted { - t.Errorf("marshalling JSON produced incorrect output: got %s, wanted %s", js, wanted) - } - - u := Unmarshaler{AnyResolver: resolver} - roundTrip := &anypb.Any{} - err = u.Unmarshal(bytes.NewReader([]byte(js)), roundTrip) - if err != nil { - t.Errorf("an unexpected error occurred when unmarshaling any from JSON: %v", err) - } - if len(resolvedTypeUrls) != 2 { - t.Errorf("custom resolver was not invoked during marshaling") - } else if resolvedTypeUrls[1] != "https://foobar.com/some.random.MessageKind" { - t.Errorf("custom resolver was invoked with wrong URL: got %q, wanted %q", resolvedTypeUrls[1], "https://foobar.com/some.random.MessageKind") - } - if !proto.Equal(any, roundTrip) { - t.Errorf("message contents not set correctly after unmarshalling JSON: got %s, wanted %s", roundTrip, any) - } -} - -func TestUnmarshalJSONPBUnmarshaler(t *testing.T) { - rawJson := `{ "foo": "bar", "baz": [0, 1, 2, 3] }` - var msg dynamicMessage - if err := Unmarshal(strings.NewReader(rawJson), &msg); err != nil { - t.Errorf("an unexpected error occurred when parsing into JSONPBUnmarshaler: %v", err) - } - if msg.rawJson != rawJson { - t.Errorf("message contents not set correctly after unmarshalling JSON: got %s, wanted %s", msg.rawJson, rawJson) - } -} - -func TestUnmarshalNullWithJSONPBUnmarshaler(t *testing.T) { - rawJson := `{"stringField":null}` - var ptrFieldMsg ptrFieldMessage - if err := Unmarshal(strings.NewReader(rawJson), &ptrFieldMsg); err != nil { - t.Errorf("unmarshal error: %v", err) - } - - want := ptrFieldMessage{StringField: &stringField{IsSet: true, StringValue: "null"}} - if !proto.Equal(&ptrFieldMsg, &want) { - t.Errorf("unmarshal result StringField: got %v, want %v", ptrFieldMsg, want) - } -} - -func TestUnmarshalAnyJSONPBUnmarshaler(t *testing.T) { - rawJson := `{ "@type": "blah.com/` + dynamicMessageName + `", "foo": "bar", "baz": [0, 1, 2, 3] }` - var got anypb.Any - if err := Unmarshal(strings.NewReader(rawJson), &got); err != nil { - t.Errorf("an unexpected error occurred when parsing into JSONPBUnmarshaler: %v", err) - } - - dm := &dynamicMessage{rawJson: `{"baz":[0,1,2,3],"foo":"bar"}`} - var want anypb.Any - if b, err := proto.Marshal(dm); err != nil { - t.Errorf("an unexpected error occurred when marshaling message: %v", err) - } else { - want.TypeUrl = "blah.com/" + dynamicMessageName - want.Value = b - } - - if !proto.Equal(&got, &want) { - t.Errorf("message contents not set correctly after unmarshalling JSON: got %s, wanted %s", got, want) - } -} - -const ( - dynamicMessageName = "google.protobuf.jsonpb.testing.dynamicMessage" -) - -func init() { - // we register the custom type below so that we can use it in Any types - proto.RegisterType((*dynamicMessage)(nil), dynamicMessageName) -} - -type ptrFieldMessage struct { - StringField *stringField `protobuf:"bytes,1,opt,name=stringField"` -} - -func (m *ptrFieldMessage) Reset() { -} - -func (m *ptrFieldMessage) String() string { - return m.StringField.StringValue -} - -func (m *ptrFieldMessage) ProtoMessage() { -} - -type stringField struct { - IsSet bool `protobuf:"varint,1,opt,name=isSet"` - StringValue string `protobuf:"bytes,2,opt,name=stringValue"` -} - -func (s *stringField) Reset() { -} - -func (s *stringField) String() string { - return s.StringValue -} - -func (s *stringField) ProtoMessage() { -} - -func (s *stringField) UnmarshalJSONPB(jum *Unmarshaler, js []byte) error { - s.IsSet = true - s.StringValue = string(js) - return nil -} - -// dynamicMessage implements protobuf.Message but is not a normal generated message type. -// It provides implementations of JSONPBMarshaler and JSONPBUnmarshaler for JSON support. -type dynamicMessage struct { - rawJson string `protobuf:"bytes,1,opt,name=rawJson"` -} - -func (m *dynamicMessage) Reset() { - m.rawJson = "{}" -} - -func (m *dynamicMessage) String() string { - return m.rawJson -} - -func (m *dynamicMessage) ProtoMessage() { -} - -func (m *dynamicMessage) MarshalJSONPB(jm *Marshaler) ([]byte, error) { - return []byte(m.rawJson), nil -} - -func (m *dynamicMessage) UnmarshalJSONPB(jum *Unmarshaler, js []byte) error { - m.rawJson = string(js) - return nil -} diff --git a/vendor/github.com/golang/protobuf/proto/Makefile b/vendor/github.com/golang/protobuf/proto/Makefile deleted file mode 100644 index e2e0651a9..000000000 --- a/vendor/github.com/golang/protobuf/proto/Makefile +++ /dev/null @@ -1,43 +0,0 @@ -# Go support for Protocol Buffers - Google's data interchange format -# -# Copyright 2010 The Go Authors. All rights reserved. -# https://github.com/golang/protobuf -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following disclaimer -# in the documentation and/or other materials provided with the -# distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived from -# this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -install: - go install - -test: install generate-test-pbs - go test - - -generate-test-pbs: - make install - make -C testdata - protoc --go_out=Mtestdata/test.proto=github.com/golang/protobuf/proto/testdata,Mgoogle/protobuf/any.proto=github.com/golang/protobuf/ptypes/any:. proto3_proto/proto3.proto - make diff --git a/vendor/github.com/golang/protobuf/proto/all_test.go b/vendor/github.com/golang/protobuf/proto/all_test.go deleted file mode 100644 index 41451a407..000000000 --- a/vendor/github.com/golang/protobuf/proto/all_test.go +++ /dev/null @@ -1,2278 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto_test - -import ( - "bytes" - "encoding/json" - "errors" - "fmt" - "math" - "math/rand" - "reflect" - "runtime/debug" - "strings" - "testing" - "time" - - . "github.com/golang/protobuf/proto" - . "github.com/golang/protobuf/proto/testdata" -) - -var globalO *Buffer - -func old() *Buffer { - if globalO == nil { - globalO = NewBuffer(nil) - } - globalO.Reset() - return globalO -} - -func equalbytes(b1, b2 []byte, t *testing.T) { - if len(b1) != len(b2) { - t.Errorf("wrong lengths: 2*%d != %d", len(b1), len(b2)) - return - } - for i := 0; i < len(b1); i++ { - if b1[i] != b2[i] { - t.Errorf("bad byte[%d]:%x %x: %s %s", i, b1[i], b2[i], b1, b2) - } - } -} - -func initGoTestField() *GoTestField { - f := new(GoTestField) - f.Label = String("label") - f.Type = String("type") - return f -} - -// These are all structurally equivalent but the tag numbers differ. -// (It's remarkable that required, optional, and repeated all have -// 8 letters.) -func initGoTest_RequiredGroup() *GoTest_RequiredGroup { - return &GoTest_RequiredGroup{ - RequiredField: String("required"), - } -} - -func initGoTest_OptionalGroup() *GoTest_OptionalGroup { - return &GoTest_OptionalGroup{ - RequiredField: String("optional"), - } -} - -func initGoTest_RepeatedGroup() *GoTest_RepeatedGroup { - return &GoTest_RepeatedGroup{ - RequiredField: String("repeated"), - } -} - -func initGoTest(setdefaults bool) *GoTest { - pb := new(GoTest) - if setdefaults { - pb.F_BoolDefaulted = Bool(Default_GoTest_F_BoolDefaulted) - pb.F_Int32Defaulted = Int32(Default_GoTest_F_Int32Defaulted) - pb.F_Int64Defaulted = Int64(Default_GoTest_F_Int64Defaulted) - pb.F_Fixed32Defaulted = Uint32(Default_GoTest_F_Fixed32Defaulted) - pb.F_Fixed64Defaulted = Uint64(Default_GoTest_F_Fixed64Defaulted) - pb.F_Uint32Defaulted = Uint32(Default_GoTest_F_Uint32Defaulted) - pb.F_Uint64Defaulted = Uint64(Default_GoTest_F_Uint64Defaulted) - pb.F_FloatDefaulted = Float32(Default_GoTest_F_FloatDefaulted) - pb.F_DoubleDefaulted = Float64(Default_GoTest_F_DoubleDefaulted) - pb.F_StringDefaulted = String(Default_GoTest_F_StringDefaulted) - pb.F_BytesDefaulted = Default_GoTest_F_BytesDefaulted - pb.F_Sint32Defaulted = Int32(Default_GoTest_F_Sint32Defaulted) - pb.F_Sint64Defaulted = Int64(Default_GoTest_F_Sint64Defaulted) - } - - pb.Kind = GoTest_TIME.Enum() - pb.RequiredField = initGoTestField() - pb.F_BoolRequired = Bool(true) - pb.F_Int32Required = Int32(3) - pb.F_Int64Required = Int64(6) - pb.F_Fixed32Required = Uint32(32) - pb.F_Fixed64Required = Uint64(64) - pb.F_Uint32Required = Uint32(3232) - pb.F_Uint64Required = Uint64(6464) - pb.F_FloatRequired = Float32(3232) - pb.F_DoubleRequired = Float64(6464) - pb.F_StringRequired = String("string") - pb.F_BytesRequired = []byte("bytes") - pb.F_Sint32Required = Int32(-32) - pb.F_Sint64Required = Int64(-64) - pb.Requiredgroup = initGoTest_RequiredGroup() - - return pb -} - -func fail(msg string, b *bytes.Buffer, s string, t *testing.T) { - data := b.Bytes() - ld := len(data) - ls := len(s) / 2 - - fmt.Printf("fail %s ld=%d ls=%d\n", msg, ld, ls) - - // find the interesting spot - n - n := ls - if ld < ls { - n = ld - } - j := 0 - for i := 0; i < n; i++ { - bs := hex(s[j])*16 + hex(s[j+1]) - j += 2 - if data[i] == bs { - continue - } - n = i - break - } - l := n - 10 - if l < 0 { - l = 0 - } - h := n + 10 - - // find the interesting spot - n - fmt.Printf("is[%d]:", l) - for i := l; i < h; i++ { - if i >= ld { - fmt.Printf(" --") - continue - } - fmt.Printf(" %.2x", data[i]) - } - fmt.Printf("\n") - - fmt.Printf("sb[%d]:", l) - for i := l; i < h; i++ { - if i >= ls { - fmt.Printf(" --") - continue - } - bs := hex(s[j])*16 + hex(s[j+1]) - j += 2 - fmt.Printf(" %.2x", bs) - } - fmt.Printf("\n") - - t.Fail() - - // t.Errorf("%s: \ngood: %s\nbad: %x", msg, s, b.Bytes()) - // Print the output in a partially-decoded format; can - // be helpful when updating the test. It produces the output - // that is pasted, with minor edits, into the argument to verify(). - // data := b.Bytes() - // nesting := 0 - // for b.Len() > 0 { - // start := len(data) - b.Len() - // var u uint64 - // u, err := DecodeVarint(b) - // if err != nil { - // fmt.Printf("decode error on varint:", err) - // return - // } - // wire := u & 0x7 - // tag := u >> 3 - // switch wire { - // case WireVarint: - // v, err := DecodeVarint(b) - // if err != nil { - // fmt.Printf("decode error on varint:", err) - // return - // } - // fmt.Printf("\t\t\"%x\" // field %d, encoding %d, value %d\n", - // data[start:len(data)-b.Len()], tag, wire, v) - // case WireFixed32: - // v, err := DecodeFixed32(b) - // if err != nil { - // fmt.Printf("decode error on fixed32:", err) - // return - // } - // fmt.Printf("\t\t\"%x\" // field %d, encoding %d, value %d\n", - // data[start:len(data)-b.Len()], tag, wire, v) - // case WireFixed64: - // v, err := DecodeFixed64(b) - // if err != nil { - // fmt.Printf("decode error on fixed64:", err) - // return - // } - // fmt.Printf("\t\t\"%x\" // field %d, encoding %d, value %d\n", - // data[start:len(data)-b.Len()], tag, wire, v) - // case WireBytes: - // nb, err := DecodeVarint(b) - // if err != nil { - // fmt.Printf("decode error on bytes:", err) - // return - // } - // after_tag := len(data) - b.Len() - // str := make([]byte, nb) - // _, err = b.Read(str) - // if err != nil { - // fmt.Printf("decode error on bytes:", err) - // return - // } - // fmt.Printf("\t\t\"%x\" \"%x\" // field %d, encoding %d (FIELD)\n", - // data[start:after_tag], str, tag, wire) - // case WireStartGroup: - // nesting++ - // fmt.Printf("\t\t\"%x\"\t\t// start group field %d level %d\n", - // data[start:len(data)-b.Len()], tag, nesting) - // case WireEndGroup: - // fmt.Printf("\t\t\"%x\"\t\t// end group field %d level %d\n", - // data[start:len(data)-b.Len()], tag, nesting) - // nesting-- - // default: - // fmt.Printf("unrecognized wire type %d\n", wire) - // return - // } - // } -} - -func hex(c uint8) uint8 { - if '0' <= c && c <= '9' { - return c - '0' - } - if 'a' <= c && c <= 'f' { - return 10 + c - 'a' - } - if 'A' <= c && c <= 'F' { - return 10 + c - 'A' - } - return 0 -} - -func equal(b []byte, s string, t *testing.T) bool { - if 2*len(b) != len(s) { - // fail(fmt.Sprintf("wrong lengths: 2*%d != %d", len(b), len(s)), b, s, t) - fmt.Printf("wrong lengths: 2*%d != %d\n", len(b), len(s)) - return false - } - for i, j := 0, 0; i < len(b); i, j = i+1, j+2 { - x := hex(s[j])*16 + hex(s[j+1]) - if b[i] != x { - // fail(fmt.Sprintf("bad byte[%d]:%x %x", i, b[i], x), b, s, t) - fmt.Printf("bad byte[%d]:%x %x", i, b[i], x) - return false - } - } - return true -} - -func overify(t *testing.T, pb *GoTest, expected string) { - o := old() - err := o.Marshal(pb) - if err != nil { - fmt.Printf("overify marshal-1 err = %v", err) - o.DebugPrint("", o.Bytes()) - t.Fatalf("expected = %s", expected) - } - if !equal(o.Bytes(), expected, t) { - o.DebugPrint("overify neq 1", o.Bytes()) - t.Fatalf("expected = %s", expected) - } - - // Now test Unmarshal by recreating the original buffer. - pbd := new(GoTest) - err = o.Unmarshal(pbd) - if err != nil { - t.Fatalf("overify unmarshal err = %v", err) - o.DebugPrint("", o.Bytes()) - t.Fatalf("string = %s", expected) - } - o.Reset() - err = o.Marshal(pbd) - if err != nil { - t.Errorf("overify marshal-2 err = %v", err) - o.DebugPrint("", o.Bytes()) - t.Fatalf("string = %s", expected) - } - if !equal(o.Bytes(), expected, t) { - o.DebugPrint("overify neq 2", o.Bytes()) - t.Fatalf("string = %s", expected) - } -} - -// Simple tests for numeric encode/decode primitives (varint, etc.) -func TestNumericPrimitives(t *testing.T) { - for i := uint64(0); i < 1e6; i += 111 { - o := old() - if o.EncodeVarint(i) != nil { - t.Error("EncodeVarint") - break - } - x, e := o.DecodeVarint() - if e != nil { - t.Fatal("DecodeVarint") - } - if x != i { - t.Fatal("varint decode fail:", i, x) - } - - o = old() - if o.EncodeFixed32(i) != nil { - t.Fatal("encFixed32") - } - x, e = o.DecodeFixed32() - if e != nil { - t.Fatal("decFixed32") - } - if x != i { - t.Fatal("fixed32 decode fail:", i, x) - } - - o = old() - if o.EncodeFixed64(i*1234567) != nil { - t.Error("encFixed64") - break - } - x, e = o.DecodeFixed64() - if e != nil { - t.Error("decFixed64") - break - } - if x != i*1234567 { - t.Error("fixed64 decode fail:", i*1234567, x) - break - } - - o = old() - i32 := int32(i - 12345) - if o.EncodeZigzag32(uint64(i32)) != nil { - t.Fatal("EncodeZigzag32") - } - x, e = o.DecodeZigzag32() - if e != nil { - t.Fatal("DecodeZigzag32") - } - if x != uint64(uint32(i32)) { - t.Fatal("zigzag32 decode fail:", i32, x) - } - - o = old() - i64 := int64(i - 12345) - if o.EncodeZigzag64(uint64(i64)) != nil { - t.Fatal("EncodeZigzag64") - } - x, e = o.DecodeZigzag64() - if e != nil { - t.Fatal("DecodeZigzag64") - } - if x != uint64(i64) { - t.Fatal("zigzag64 decode fail:", i64, x) - } - } -} - -// fakeMarshaler is a simple struct implementing Marshaler and Message interfaces. -type fakeMarshaler struct { - b []byte - err error -} - -func (f *fakeMarshaler) Marshal() ([]byte, error) { return f.b, f.err } -func (f *fakeMarshaler) String() string { return fmt.Sprintf("Bytes: %v Error: %v", f.b, f.err) } -func (f *fakeMarshaler) ProtoMessage() {} -func (f *fakeMarshaler) Reset() {} - -type msgWithFakeMarshaler struct { - M *fakeMarshaler `protobuf:"bytes,1,opt,name=fake"` -} - -func (m *msgWithFakeMarshaler) String() string { return CompactTextString(m) } -func (m *msgWithFakeMarshaler) ProtoMessage() {} -func (m *msgWithFakeMarshaler) Reset() {} - -// Simple tests for proto messages that implement the Marshaler interface. -func TestMarshalerEncoding(t *testing.T) { - tests := []struct { - name string - m Message - want []byte - errType reflect.Type - }{ - { - name: "Marshaler that fails", - m: &fakeMarshaler{ - err: errors.New("some marshal err"), - b: []byte{5, 6, 7}, - }, - // Since the Marshal method returned bytes, they should be written to the - // buffer. (For efficiency, we assume that Marshal implementations are - // always correct w.r.t. RequiredNotSetError and output.) - want: []byte{5, 6, 7}, - errType: reflect.TypeOf(errors.New("some marshal err")), - }, - { - name: "Marshaler that fails with RequiredNotSetError", - m: &msgWithFakeMarshaler{ - M: &fakeMarshaler{ - err: &RequiredNotSetError{}, - b: []byte{5, 6, 7}, - }, - }, - // Since there's an error that can be continued after, - // the buffer should be written. - want: []byte{ - 10, 3, // for &msgWithFakeMarshaler - 5, 6, 7, // for &fakeMarshaler - }, - errType: reflect.TypeOf(&RequiredNotSetError{}), - }, - { - name: "Marshaler that succeeds", - m: &fakeMarshaler{ - b: []byte{0, 1, 2, 3, 4, 127, 255}, - }, - want: []byte{0, 1, 2, 3, 4, 127, 255}, - }, - } - for _, test := range tests { - b := NewBuffer(nil) - err := b.Marshal(test.m) - if reflect.TypeOf(err) != test.errType { - t.Errorf("%s: got err %T(%v) wanted %T", test.name, err, err, test.errType) - } - if !reflect.DeepEqual(test.want, b.Bytes()) { - t.Errorf("%s: got bytes %v wanted %v", test.name, b.Bytes(), test.want) - } - if size := Size(test.m); size != len(b.Bytes()) { - t.Errorf("%s: Size(_) = %v, but marshaled to %v bytes", test.name, size, len(b.Bytes())) - } - - m, mErr := Marshal(test.m) - if !bytes.Equal(b.Bytes(), m) { - t.Errorf("%s: Marshal returned %v, but (*Buffer).Marshal wrote %v", test.name, m, b.Bytes()) - } - if !reflect.DeepEqual(err, mErr) { - t.Errorf("%s: Marshal err = %q, but (*Buffer).Marshal returned %q", - test.name, fmt.Sprint(mErr), fmt.Sprint(err)) - } - } -} - -// Simple tests for bytes -func TestBytesPrimitives(t *testing.T) { - o := old() - bytes := []byte{'n', 'o', 'w', ' ', 'i', 's', ' ', 't', 'h', 'e', ' ', 't', 'i', 'm', 'e'} - if o.EncodeRawBytes(bytes) != nil { - t.Error("EncodeRawBytes") - } - decb, e := o.DecodeRawBytes(false) - if e != nil { - t.Error("DecodeRawBytes") - } - equalbytes(bytes, decb, t) -} - -// Simple tests for strings -func TestStringPrimitives(t *testing.T) { - o := old() - s := "now is the time" - if o.EncodeStringBytes(s) != nil { - t.Error("enc_string") - } - decs, e := o.DecodeStringBytes() - if e != nil { - t.Error("dec_string") - } - if s != decs { - t.Error("string encode/decode fail:", s, decs) - } -} - -// Do we catch the "required bit not set" case? -func TestRequiredBit(t *testing.T) { - o := old() - pb := new(GoTest) - err := o.Marshal(pb) - if err == nil { - t.Error("did not catch missing required fields") - } else if strings.Index(err.Error(), "Kind") < 0 { - t.Error("wrong error type:", err) - } -} - -// Check that all fields are nil. -// Clearly silly, and a residue from a more interesting test with an earlier, -// different initialization property, but it once caught a compiler bug so -// it lives. -func checkInitialized(pb *GoTest, t *testing.T) { - if pb.F_BoolDefaulted != nil { - t.Error("New or Reset did not set boolean:", *pb.F_BoolDefaulted) - } - if pb.F_Int32Defaulted != nil { - t.Error("New or Reset did not set int32:", *pb.F_Int32Defaulted) - } - if pb.F_Int64Defaulted != nil { - t.Error("New or Reset did not set int64:", *pb.F_Int64Defaulted) - } - if pb.F_Fixed32Defaulted != nil { - t.Error("New or Reset did not set fixed32:", *pb.F_Fixed32Defaulted) - } - if pb.F_Fixed64Defaulted != nil { - t.Error("New or Reset did not set fixed64:", *pb.F_Fixed64Defaulted) - } - if pb.F_Uint32Defaulted != nil { - t.Error("New or Reset did not set uint32:", *pb.F_Uint32Defaulted) - } - if pb.F_Uint64Defaulted != nil { - t.Error("New or Reset did not set uint64:", *pb.F_Uint64Defaulted) - } - if pb.F_FloatDefaulted != nil { - t.Error("New or Reset did not set float:", *pb.F_FloatDefaulted) - } - if pb.F_DoubleDefaulted != nil { - t.Error("New or Reset did not set double:", *pb.F_DoubleDefaulted) - } - if pb.F_StringDefaulted != nil { - t.Error("New or Reset did not set string:", *pb.F_StringDefaulted) - } - if pb.F_BytesDefaulted != nil { - t.Error("New or Reset did not set bytes:", string(pb.F_BytesDefaulted)) - } - if pb.F_Sint32Defaulted != nil { - t.Error("New or Reset did not set int32:", *pb.F_Sint32Defaulted) - } - if pb.F_Sint64Defaulted != nil { - t.Error("New or Reset did not set int64:", *pb.F_Sint64Defaulted) - } -} - -// Does Reset() reset? -func TestReset(t *testing.T) { - pb := initGoTest(true) - // muck with some values - pb.F_BoolDefaulted = Bool(false) - pb.F_Int32Defaulted = Int32(237) - pb.F_Int64Defaulted = Int64(12346) - pb.F_Fixed32Defaulted = Uint32(32000) - pb.F_Fixed64Defaulted = Uint64(666) - pb.F_Uint32Defaulted = Uint32(323232) - pb.F_Uint64Defaulted = nil - pb.F_FloatDefaulted = nil - pb.F_DoubleDefaulted = Float64(0) - pb.F_StringDefaulted = String("gotcha") - pb.F_BytesDefaulted = []byte("asdfasdf") - pb.F_Sint32Defaulted = Int32(123) - pb.F_Sint64Defaulted = Int64(789) - pb.Reset() - checkInitialized(pb, t) -} - -// All required fields set, no defaults provided. -func TestEncodeDecode1(t *testing.T) { - pb := initGoTest(false) - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 0x20 - "714000000000000000"+ // field 14, encoding 1, value 0x40 - "78a019"+ // field 15, encoding 0, value 0xca0 = 3232 - "8001c032"+ // field 16, encoding 0, value 0x1940 = 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2, string "string" - "b304"+ // field 70, encoding 3, start group - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // field 70, encoding 4, end group - "aa0605"+"6279746573"+ // field 101, encoding 2, string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f") // field 103, encoding 0, 0x7f zigzag64 -} - -// All required fields set, defaults provided. -func TestEncodeDecode2(t *testing.T) { - pb := initGoTest(true) - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 32 - "714000000000000000"+ // field 14, encoding 1, value 64 - "78a019"+ // field 15, encoding 0, value 3232 - "8001c032"+ // field 16, encoding 0, value 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" - "c00201"+ // field 40, encoding 0, value 1 - "c80220"+ // field 41, encoding 0, value 32 - "d00240"+ // field 42, encoding 0, value 64 - "dd0240010000"+ // field 43, encoding 5, value 320 - "e1028002000000000000"+ // field 44, encoding 1, value 640 - "e8028019"+ // field 45, encoding 0, value 3200 - "f0028032"+ // field 46, encoding 0, value 6400 - "fd02e0659948"+ // field 47, encoding 5, value 314159.0 - "81030000000050971041"+ // field 48, encoding 1, value 271828.0 - "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n" - "b304"+ // start group field 70 level 1 - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // end group field 70 level 1 - "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 - "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose" - "90193f"+ // field 402, encoding 0, value 63 - "98197f") // field 403, encoding 0, value 127 - -} - -// All default fields set to their default value by hand -func TestEncodeDecode3(t *testing.T) { - pb := initGoTest(false) - pb.F_BoolDefaulted = Bool(true) - pb.F_Int32Defaulted = Int32(32) - pb.F_Int64Defaulted = Int64(64) - pb.F_Fixed32Defaulted = Uint32(320) - pb.F_Fixed64Defaulted = Uint64(640) - pb.F_Uint32Defaulted = Uint32(3200) - pb.F_Uint64Defaulted = Uint64(6400) - pb.F_FloatDefaulted = Float32(314159) - pb.F_DoubleDefaulted = Float64(271828) - pb.F_StringDefaulted = String("hello, \"world!\"\n") - pb.F_BytesDefaulted = []byte("Bignose") - pb.F_Sint32Defaulted = Int32(-32) - pb.F_Sint64Defaulted = Int64(-64) - - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 32 - "714000000000000000"+ // field 14, encoding 1, value 64 - "78a019"+ // field 15, encoding 0, value 3232 - "8001c032"+ // field 16, encoding 0, value 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" - "c00201"+ // field 40, encoding 0, value 1 - "c80220"+ // field 41, encoding 0, value 32 - "d00240"+ // field 42, encoding 0, value 64 - "dd0240010000"+ // field 43, encoding 5, value 320 - "e1028002000000000000"+ // field 44, encoding 1, value 640 - "e8028019"+ // field 45, encoding 0, value 3200 - "f0028032"+ // field 46, encoding 0, value 6400 - "fd02e0659948"+ // field 47, encoding 5, value 314159.0 - "81030000000050971041"+ // field 48, encoding 1, value 271828.0 - "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n" - "b304"+ // start group field 70 level 1 - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // end group field 70 level 1 - "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 - "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose" - "90193f"+ // field 402, encoding 0, value 63 - "98197f") // field 403, encoding 0, value 127 - -} - -// All required fields set, defaults provided, all non-defaulted optional fields have values. -func TestEncodeDecode4(t *testing.T) { - pb := initGoTest(true) - pb.Table = String("hello") - pb.Param = Int32(7) - pb.OptionalField = initGoTestField() - pb.F_BoolOptional = Bool(true) - pb.F_Int32Optional = Int32(32) - pb.F_Int64Optional = Int64(64) - pb.F_Fixed32Optional = Uint32(3232) - pb.F_Fixed64Optional = Uint64(6464) - pb.F_Uint32Optional = Uint32(323232) - pb.F_Uint64Optional = Uint64(646464) - pb.F_FloatOptional = Float32(32.) - pb.F_DoubleOptional = Float64(64.) - pb.F_StringOptional = String("hello") - pb.F_BytesOptional = []byte("Bignose") - pb.F_Sint32Optional = Int32(-32) - pb.F_Sint64Optional = Int64(-64) - pb.Optionalgroup = initGoTest_OptionalGroup() - - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "1205"+"68656c6c6f"+ // field 2, encoding 2, string "hello" - "1807"+ // field 3, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "320d"+"0a056c6162656c120474797065"+ // field 6, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 32 - "714000000000000000"+ // field 14, encoding 1, value 64 - "78a019"+ // field 15, encoding 0, value 3232 - "8001c032"+ // field 16, encoding 0, value 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" - "f00101"+ // field 30, encoding 0, value 1 - "f80120"+ // field 31, encoding 0, value 32 - "800240"+ // field 32, encoding 0, value 64 - "8d02a00c0000"+ // field 33, encoding 5, value 3232 - "91024019000000000000"+ // field 34, encoding 1, value 6464 - "9802a0dd13"+ // field 35, encoding 0, value 323232 - "a002c0ba27"+ // field 36, encoding 0, value 646464 - "ad0200000042"+ // field 37, encoding 5, value 32.0 - "b1020000000000005040"+ // field 38, encoding 1, value 64.0 - "ba0205"+"68656c6c6f"+ // field 39, encoding 2, string "hello" - "c00201"+ // field 40, encoding 0, value 1 - "c80220"+ // field 41, encoding 0, value 32 - "d00240"+ // field 42, encoding 0, value 64 - "dd0240010000"+ // field 43, encoding 5, value 320 - "e1028002000000000000"+ // field 44, encoding 1, value 640 - "e8028019"+ // field 45, encoding 0, value 3200 - "f0028032"+ // field 46, encoding 0, value 6400 - "fd02e0659948"+ // field 47, encoding 5, value 314159.0 - "81030000000050971041"+ // field 48, encoding 1, value 271828.0 - "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n" - "b304"+ // start group field 70 level 1 - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // end group field 70 level 1 - "d305"+ // start group field 90 level 1 - "da0508"+"6f7074696f6e616c"+ // field 91, encoding 2, string "optional" - "d405"+ // end group field 90 level 1 - "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 - "ea1207"+"4269676e6f7365"+ // field 301, encoding 2, string "Bignose" - "f0123f"+ // field 302, encoding 0, value 63 - "f8127f"+ // field 303, encoding 0, value 127 - "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose" - "90193f"+ // field 402, encoding 0, value 63 - "98197f") // field 403, encoding 0, value 127 - -} - -// All required fields set, defaults provided, all repeated fields given two values. -func TestEncodeDecode5(t *testing.T) { - pb := initGoTest(true) - pb.RepeatedField = []*GoTestField{initGoTestField(), initGoTestField()} - pb.F_BoolRepeated = []bool{false, true} - pb.F_Int32Repeated = []int32{32, 33} - pb.F_Int64Repeated = []int64{64, 65} - pb.F_Fixed32Repeated = []uint32{3232, 3333} - pb.F_Fixed64Repeated = []uint64{6464, 6565} - pb.F_Uint32Repeated = []uint32{323232, 333333} - pb.F_Uint64Repeated = []uint64{646464, 656565} - pb.F_FloatRepeated = []float32{32., 33.} - pb.F_DoubleRepeated = []float64{64., 65.} - pb.F_StringRepeated = []string{"hello", "sailor"} - pb.F_BytesRepeated = [][]byte{[]byte("big"), []byte("nose")} - pb.F_Sint32Repeated = []int32{32, -32} - pb.F_Sint64Repeated = []int64{64, -64} - pb.Repeatedgroup = []*GoTest_RepeatedGroup{initGoTest_RepeatedGroup(), initGoTest_RepeatedGroup()} - - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "2a0d"+"0a056c6162656c120474797065"+ // field 5, encoding 2 (GoTestField) - "2a0d"+"0a056c6162656c120474797065"+ // field 5, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 32 - "714000000000000000"+ // field 14, encoding 1, value 64 - "78a019"+ // field 15, encoding 0, value 3232 - "8001c032"+ // field 16, encoding 0, value 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" - "a00100"+ // field 20, encoding 0, value 0 - "a00101"+ // field 20, encoding 0, value 1 - "a80120"+ // field 21, encoding 0, value 32 - "a80121"+ // field 21, encoding 0, value 33 - "b00140"+ // field 22, encoding 0, value 64 - "b00141"+ // field 22, encoding 0, value 65 - "bd01a00c0000"+ // field 23, encoding 5, value 3232 - "bd01050d0000"+ // field 23, encoding 5, value 3333 - "c1014019000000000000"+ // field 24, encoding 1, value 6464 - "c101a519000000000000"+ // field 24, encoding 1, value 6565 - "c801a0dd13"+ // field 25, encoding 0, value 323232 - "c80195ac14"+ // field 25, encoding 0, value 333333 - "d001c0ba27"+ // field 26, encoding 0, value 646464 - "d001b58928"+ // field 26, encoding 0, value 656565 - "dd0100000042"+ // field 27, encoding 5, value 32.0 - "dd0100000442"+ // field 27, encoding 5, value 33.0 - "e1010000000000005040"+ // field 28, encoding 1, value 64.0 - "e1010000000000405040"+ // field 28, encoding 1, value 65.0 - "ea0105"+"68656c6c6f"+ // field 29, encoding 2, string "hello" - "ea0106"+"7361696c6f72"+ // field 29, encoding 2, string "sailor" - "c00201"+ // field 40, encoding 0, value 1 - "c80220"+ // field 41, encoding 0, value 32 - "d00240"+ // field 42, encoding 0, value 64 - "dd0240010000"+ // field 43, encoding 5, value 320 - "e1028002000000000000"+ // field 44, encoding 1, value 640 - "e8028019"+ // field 45, encoding 0, value 3200 - "f0028032"+ // field 46, encoding 0, value 6400 - "fd02e0659948"+ // field 47, encoding 5, value 314159.0 - "81030000000050971041"+ // field 48, encoding 1, value 271828.0 - "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n" - "b304"+ // start group field 70 level 1 - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // end group field 70 level 1 - "8305"+ // start group field 80 level 1 - "8a0508"+"7265706561746564"+ // field 81, encoding 2, string "repeated" - "8405"+ // end group field 80 level 1 - "8305"+ // start group field 80 level 1 - "8a0508"+"7265706561746564"+ // field 81, encoding 2, string "repeated" - "8405"+ // end group field 80 level 1 - "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 - "ca0c03"+"626967"+ // field 201, encoding 2, string "big" - "ca0c04"+"6e6f7365"+ // field 201, encoding 2, string "nose" - "d00c40"+ // field 202, encoding 0, value 32 - "d00c3f"+ // field 202, encoding 0, value -32 - "d80c8001"+ // field 203, encoding 0, value 64 - "d80c7f"+ // field 203, encoding 0, value -64 - "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose" - "90193f"+ // field 402, encoding 0, value 63 - "98197f") // field 403, encoding 0, value 127 - -} - -// All required fields set, all packed repeated fields given two values. -func TestEncodeDecode6(t *testing.T) { - pb := initGoTest(false) - pb.F_BoolRepeatedPacked = []bool{false, true} - pb.F_Int32RepeatedPacked = []int32{32, 33} - pb.F_Int64RepeatedPacked = []int64{64, 65} - pb.F_Fixed32RepeatedPacked = []uint32{3232, 3333} - pb.F_Fixed64RepeatedPacked = []uint64{6464, 6565} - pb.F_Uint32RepeatedPacked = []uint32{323232, 333333} - pb.F_Uint64RepeatedPacked = []uint64{646464, 656565} - pb.F_FloatRepeatedPacked = []float32{32., 33.} - pb.F_DoubleRepeatedPacked = []float64{64., 65.} - pb.F_Sint32RepeatedPacked = []int32{32, -32} - pb.F_Sint64RepeatedPacked = []int64{64, -64} - - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 32 - "714000000000000000"+ // field 14, encoding 1, value 64 - "78a019"+ // field 15, encoding 0, value 3232 - "8001c032"+ // field 16, encoding 0, value 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" - "9203020001"+ // field 50, encoding 2, 2 bytes, value 0, value 1 - "9a03022021"+ // field 51, encoding 2, 2 bytes, value 32, value 33 - "a203024041"+ // field 52, encoding 2, 2 bytes, value 64, value 65 - "aa0308"+ // field 53, encoding 2, 8 bytes - "a00c0000050d0000"+ // value 3232, value 3333 - "b20310"+ // field 54, encoding 2, 16 bytes - "4019000000000000a519000000000000"+ // value 6464, value 6565 - "ba0306"+ // field 55, encoding 2, 6 bytes - "a0dd1395ac14"+ // value 323232, value 333333 - "c20306"+ // field 56, encoding 2, 6 bytes - "c0ba27b58928"+ // value 646464, value 656565 - "ca0308"+ // field 57, encoding 2, 8 bytes - "0000004200000442"+ // value 32.0, value 33.0 - "d20310"+ // field 58, encoding 2, 16 bytes - "00000000000050400000000000405040"+ // value 64.0, value 65.0 - "b304"+ // start group field 70 level 1 - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // end group field 70 level 1 - "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 - "b21f02"+ // field 502, encoding 2, 2 bytes - "403f"+ // value 32, value -32 - "ba1f03"+ // field 503, encoding 2, 3 bytes - "80017f") // value 64, value -64 -} - -// Test that we can encode empty bytes fields. -func TestEncodeDecodeBytes1(t *testing.T) { - pb := initGoTest(false) - - // Create our bytes - pb.F_BytesRequired = []byte{} - pb.F_BytesRepeated = [][]byte{{}} - pb.F_BytesOptional = []byte{} - - d, err := Marshal(pb) - if err != nil { - t.Error(err) - } - - pbd := new(GoTest) - if err := Unmarshal(d, pbd); err != nil { - t.Error(err) - } - - if pbd.F_BytesRequired == nil || len(pbd.F_BytesRequired) != 0 { - t.Error("required empty bytes field is incorrect") - } - if pbd.F_BytesRepeated == nil || len(pbd.F_BytesRepeated) == 1 && pbd.F_BytesRepeated[0] == nil { - t.Error("repeated empty bytes field is incorrect") - } - if pbd.F_BytesOptional == nil || len(pbd.F_BytesOptional) != 0 { - t.Error("optional empty bytes field is incorrect") - } -} - -// Test that we encode nil-valued fields of a repeated bytes field correctly. -// Since entries in a repeated field cannot be nil, nil must mean empty value. -func TestEncodeDecodeBytes2(t *testing.T) { - pb := initGoTest(false) - - // Create our bytes - pb.F_BytesRepeated = [][]byte{nil} - - d, err := Marshal(pb) - if err != nil { - t.Error(err) - } - - pbd := new(GoTest) - if err := Unmarshal(d, pbd); err != nil { - t.Error(err) - } - - if len(pbd.F_BytesRepeated) != 1 || pbd.F_BytesRepeated[0] == nil { - t.Error("Unexpected value for repeated bytes field") - } -} - -// All required fields set, defaults provided, all repeated fields given two values. -func TestSkippingUnrecognizedFields(t *testing.T) { - o := old() - pb := initGoTestField() - - // Marshal it normally. - o.Marshal(pb) - - // Now new a GoSkipTest record. - skip := &GoSkipTest{ - SkipInt32: Int32(32), - SkipFixed32: Uint32(3232), - SkipFixed64: Uint64(6464), - SkipString: String("skipper"), - Skipgroup: &GoSkipTest_SkipGroup{ - GroupInt32: Int32(75), - GroupString: String("wxyz"), - }, - } - - // Marshal it into same buffer. - o.Marshal(skip) - - pbd := new(GoTestField) - o.Unmarshal(pbd) - - // The __unrecognized field should be a marshaling of GoSkipTest - skipd := new(GoSkipTest) - - o.SetBuf(pbd.XXX_unrecognized) - o.Unmarshal(skipd) - - if *skipd.SkipInt32 != *skip.SkipInt32 { - t.Error("skip int32", skipd.SkipInt32) - } - if *skipd.SkipFixed32 != *skip.SkipFixed32 { - t.Error("skip fixed32", skipd.SkipFixed32) - } - if *skipd.SkipFixed64 != *skip.SkipFixed64 { - t.Error("skip fixed64", skipd.SkipFixed64) - } - if *skipd.SkipString != *skip.SkipString { - t.Error("skip string", *skipd.SkipString) - } - if *skipd.Skipgroup.GroupInt32 != *skip.Skipgroup.GroupInt32 { - t.Error("skip group int32", skipd.Skipgroup.GroupInt32) - } - if *skipd.Skipgroup.GroupString != *skip.Skipgroup.GroupString { - t.Error("skip group string", *skipd.Skipgroup.GroupString) - } -} - -// Check that unrecognized fields of a submessage are preserved. -func TestSubmessageUnrecognizedFields(t *testing.T) { - nm := &NewMessage{ - Nested: &NewMessage_Nested{ - Name: String("Nigel"), - FoodGroup: String("carbs"), - }, - } - b, err := Marshal(nm) - if err != nil { - t.Fatalf("Marshal of NewMessage: %v", err) - } - - // Unmarshal into an OldMessage. - om := new(OldMessage) - if err := Unmarshal(b, om); err != nil { - t.Fatalf("Unmarshal to OldMessage: %v", err) - } - exp := &OldMessage{ - Nested: &OldMessage_Nested{ - Name: String("Nigel"), - // normal protocol buffer users should not do this - XXX_unrecognized: []byte("\x12\x05carbs"), - }, - } - if !Equal(om, exp) { - t.Errorf("om = %v, want %v", om, exp) - } - - // Clone the OldMessage. - om = Clone(om).(*OldMessage) - if !Equal(om, exp) { - t.Errorf("Clone(om) = %v, want %v", om, exp) - } - - // Marshal the OldMessage, then unmarshal it into an empty NewMessage. - if b, err = Marshal(om); err != nil { - t.Fatalf("Marshal of OldMessage: %v", err) - } - t.Logf("Marshal(%v) -> %q", om, b) - nm2 := new(NewMessage) - if err := Unmarshal(b, nm2); err != nil { - t.Fatalf("Unmarshal to NewMessage: %v", err) - } - if !Equal(nm, nm2) { - t.Errorf("NewMessage round-trip: %v => %v", nm, nm2) - } -} - -// Check that an int32 field can be upgraded to an int64 field. -func TestNegativeInt32(t *testing.T) { - om := &OldMessage{ - Num: Int32(-1), - } - b, err := Marshal(om) - if err != nil { - t.Fatalf("Marshal of OldMessage: %v", err) - } - - // Check the size. It should be 11 bytes; - // 1 for the field/wire type, and 10 for the negative number. - if len(b) != 11 { - t.Errorf("%v marshaled as %q, wanted 11 bytes", om, b) - } - - // Unmarshal into a NewMessage. - nm := new(NewMessage) - if err := Unmarshal(b, nm); err != nil { - t.Fatalf("Unmarshal to NewMessage: %v", err) - } - want := &NewMessage{ - Num: Int64(-1), - } - if !Equal(nm, want) { - t.Errorf("nm = %v, want %v", nm, want) - } -} - -// Check that we can grow an array (repeated field) to have many elements. -// This test doesn't depend only on our encoding; for variety, it makes sure -// we create, encode, and decode the correct contents explicitly. It's therefore -// a bit messier. -// This test also uses (and hence tests) the Marshal/Unmarshal functions -// instead of the methods. -func TestBigRepeated(t *testing.T) { - pb := initGoTest(true) - - // Create the arrays - const N = 50 // Internally the library starts much smaller. - pb.Repeatedgroup = make([]*GoTest_RepeatedGroup, N) - pb.F_Sint64Repeated = make([]int64, N) - pb.F_Sint32Repeated = make([]int32, N) - pb.F_BytesRepeated = make([][]byte, N) - pb.F_StringRepeated = make([]string, N) - pb.F_DoubleRepeated = make([]float64, N) - pb.F_FloatRepeated = make([]float32, N) - pb.F_Uint64Repeated = make([]uint64, N) - pb.F_Uint32Repeated = make([]uint32, N) - pb.F_Fixed64Repeated = make([]uint64, N) - pb.F_Fixed32Repeated = make([]uint32, N) - pb.F_Int64Repeated = make([]int64, N) - pb.F_Int32Repeated = make([]int32, N) - pb.F_BoolRepeated = make([]bool, N) - pb.RepeatedField = make([]*GoTestField, N) - - // Fill in the arrays with checkable values. - igtf := initGoTestField() - igtrg := initGoTest_RepeatedGroup() - for i := 0; i < N; i++ { - pb.Repeatedgroup[i] = igtrg - pb.F_Sint64Repeated[i] = int64(i) - pb.F_Sint32Repeated[i] = int32(i) - s := fmt.Sprint(i) - pb.F_BytesRepeated[i] = []byte(s) - pb.F_StringRepeated[i] = s - pb.F_DoubleRepeated[i] = float64(i) - pb.F_FloatRepeated[i] = float32(i) - pb.F_Uint64Repeated[i] = uint64(i) - pb.F_Uint32Repeated[i] = uint32(i) - pb.F_Fixed64Repeated[i] = uint64(i) - pb.F_Fixed32Repeated[i] = uint32(i) - pb.F_Int64Repeated[i] = int64(i) - pb.F_Int32Repeated[i] = int32(i) - pb.F_BoolRepeated[i] = i%2 == 0 - pb.RepeatedField[i] = igtf - } - - // Marshal. - buf, _ := Marshal(pb) - - // Now test Unmarshal by recreating the original buffer. - pbd := new(GoTest) - Unmarshal(buf, pbd) - - // Check the checkable values - for i := uint64(0); i < N; i++ { - if pbd.Repeatedgroup[i] == nil { // TODO: more checking? - t.Error("pbd.Repeatedgroup bad") - } - var x uint64 - x = uint64(pbd.F_Sint64Repeated[i]) - if x != i { - t.Error("pbd.F_Sint64Repeated bad", x, i) - } - x = uint64(pbd.F_Sint32Repeated[i]) - if x != i { - t.Error("pbd.F_Sint32Repeated bad", x, i) - } - s := fmt.Sprint(i) - equalbytes(pbd.F_BytesRepeated[i], []byte(s), t) - if pbd.F_StringRepeated[i] != s { - t.Error("pbd.F_Sint32Repeated bad", pbd.F_StringRepeated[i], i) - } - x = uint64(pbd.F_DoubleRepeated[i]) - if x != i { - t.Error("pbd.F_DoubleRepeated bad", x, i) - } - x = uint64(pbd.F_FloatRepeated[i]) - if x != i { - t.Error("pbd.F_FloatRepeated bad", x, i) - } - x = pbd.F_Uint64Repeated[i] - if x != i { - t.Error("pbd.F_Uint64Repeated bad", x, i) - } - x = uint64(pbd.F_Uint32Repeated[i]) - if x != i { - t.Error("pbd.F_Uint32Repeated bad", x, i) - } - x = pbd.F_Fixed64Repeated[i] - if x != i { - t.Error("pbd.F_Fixed64Repeated bad", x, i) - } - x = uint64(pbd.F_Fixed32Repeated[i]) - if x != i { - t.Error("pbd.F_Fixed32Repeated bad", x, i) - } - x = uint64(pbd.F_Int64Repeated[i]) - if x != i { - t.Error("pbd.F_Int64Repeated bad", x, i) - } - x = uint64(pbd.F_Int32Repeated[i]) - if x != i { - t.Error("pbd.F_Int32Repeated bad", x, i) - } - if pbd.F_BoolRepeated[i] != (i%2 == 0) { - t.Error("pbd.F_BoolRepeated bad", x, i) - } - if pbd.RepeatedField[i] == nil { // TODO: more checking? - t.Error("pbd.RepeatedField bad") - } - } -} - -// Verify we give a useful message when decoding to the wrong structure type. -func TestTypeMismatch(t *testing.T) { - pb1 := initGoTest(true) - - // Marshal - o := old() - o.Marshal(pb1) - - // Now Unmarshal it to the wrong type. - pb2 := initGoTestField() - err := o.Unmarshal(pb2) - if err == nil { - t.Error("expected error, got no error") - } else if !strings.Contains(err.Error(), "bad wiretype") { - t.Error("expected bad wiretype error, got", err) - } -} - -func encodeDecode(t *testing.T, in, out Message, msg string) { - buf, err := Marshal(in) - if err != nil { - t.Fatalf("failed marshaling %v: %v", msg, err) - } - if err := Unmarshal(buf, out); err != nil { - t.Fatalf("failed unmarshaling %v: %v", msg, err) - } -} - -func TestPackedNonPackedDecoderSwitching(t *testing.T) { - np, p := new(NonPackedTest), new(PackedTest) - - // non-packed -> packed - np.A = []int32{0, 1, 1, 2, 3, 5} - encodeDecode(t, np, p, "non-packed -> packed") - if !reflect.DeepEqual(np.A, p.B) { - t.Errorf("failed non-packed -> packed; np.A=%+v, p.B=%+v", np.A, p.B) - } - - // packed -> non-packed - np.Reset() - p.B = []int32{3, 1, 4, 1, 5, 9} - encodeDecode(t, p, np, "packed -> non-packed") - if !reflect.DeepEqual(p.B, np.A) { - t.Errorf("failed packed -> non-packed; p.B=%+v, np.A=%+v", p.B, np.A) - } -} - -func TestProto1RepeatedGroup(t *testing.T) { - pb := &MessageList{ - Message: []*MessageList_Message{ - { - Name: String("blah"), - Count: Int32(7), - }, - // NOTE: pb.Message[1] is a nil - nil, - }, - } - - o := old() - err := o.Marshal(pb) - if err == nil || !strings.Contains(err.Error(), "repeated field Message has nil") { - t.Fatalf("unexpected or no error when marshaling: %v", err) - } -} - -// Test that enums work. Checks for a bug introduced by making enums -// named types instead of int32: newInt32FromUint64 would crash with -// a type mismatch in reflect.PointTo. -func TestEnum(t *testing.T) { - pb := new(GoEnum) - pb.Foo = FOO_FOO1.Enum() - o := old() - if err := o.Marshal(pb); err != nil { - t.Fatal("error encoding enum:", err) - } - pb1 := new(GoEnum) - if err := o.Unmarshal(pb1); err != nil { - t.Fatal("error decoding enum:", err) - } - if *pb1.Foo != FOO_FOO1 { - t.Error("expected 7 but got ", *pb1.Foo) - } -} - -// Enum types have String methods. Check that enum fields can be printed. -// We don't care what the value actually is, just as long as it doesn't crash. -func TestPrintingNilEnumFields(t *testing.T) { - pb := new(GoEnum) - _ = fmt.Sprintf("%+v", pb) -} - -// Verify that absent required fields cause Marshal/Unmarshal to return errors. -func TestRequiredFieldEnforcement(t *testing.T) { - pb := new(GoTestField) - _, err := Marshal(pb) - if err == nil { - t.Error("marshal: expected error, got nil") - } else if _, ok := err.(*RequiredNotSetError); !ok || !strings.Contains(err.Error(), "Label") { - t.Errorf("marshal: bad error type: %v", err) - } - - // A slightly sneaky, yet valid, proto. It encodes the same required field twice, - // so simply counting the required fields is insufficient. - // field 1, encoding 2, value "hi" - buf := []byte("\x0A\x02hi\x0A\x02hi") - err = Unmarshal(buf, pb) - if err == nil { - t.Error("unmarshal: expected error, got nil") - } else if _, ok := err.(*RequiredNotSetError); !ok || !strings.Contains(err.Error(), "{Unknown}") { - t.Errorf("unmarshal: bad error type: %v", err) - } -} - -// Verify that absent required fields in groups cause Marshal/Unmarshal to return errors. -func TestRequiredFieldEnforcementGroups(t *testing.T) { - pb := &GoTestRequiredGroupField{Group: &GoTestRequiredGroupField_Group{}} - if _, err := Marshal(pb); err == nil { - t.Error("marshal: expected error, got nil") - } else if _, ok := err.(*RequiredNotSetError); !ok || !strings.Contains(err.Error(), "Group.Field") { - t.Errorf("marshal: bad error type: %v", err) - } - - buf := []byte{11, 12} - if err := Unmarshal(buf, pb); err == nil { - t.Error("unmarshal: expected error, got nil") - } else if _, ok := err.(*RequiredNotSetError); !ok || !strings.Contains(err.Error(), "Group.{Unknown}") { - t.Errorf("unmarshal: bad error type: %v", err) - } -} - -func TestTypedNilMarshal(t *testing.T) { - // A typed nil should return ErrNil and not crash. - { - var m *GoEnum - if _, err := Marshal(m); err != ErrNil { - t.Errorf("Marshal(%#v): got %v, want ErrNil", m, err) - } - } - - { - m := &Communique{Union: &Communique_Msg{nil}} - if _, err := Marshal(m); err == nil || err == ErrNil { - t.Errorf("Marshal(%#v): got %v, want errOneofHasNil", m, err) - } - } -} - -// A type that implements the Marshaler interface, but is not nillable. -type nonNillableInt uint64 - -func (nni nonNillableInt) Marshal() ([]byte, error) { - return EncodeVarint(uint64(nni)), nil -} - -type NNIMessage struct { - nni nonNillableInt -} - -func (*NNIMessage) Reset() {} -func (*NNIMessage) String() string { return "" } -func (*NNIMessage) ProtoMessage() {} - -// A type that implements the Marshaler interface and is nillable. -type nillableMessage struct { - x uint64 -} - -func (nm *nillableMessage) Marshal() ([]byte, error) { - return EncodeVarint(nm.x), nil -} - -type NMMessage struct { - nm *nillableMessage -} - -func (*NMMessage) Reset() {} -func (*NMMessage) String() string { return "" } -func (*NMMessage) ProtoMessage() {} - -// Verify a type that uses the Marshaler interface, but has a nil pointer. -func TestNilMarshaler(t *testing.T) { - // Try a struct with a Marshaler field that is nil. - // It should be directly marshable. - nmm := new(NMMessage) - if _, err := Marshal(nmm); err != nil { - t.Error("unexpected error marshaling nmm: ", err) - } - - // Try a struct with a Marshaler field that is not nillable. - nnim := new(NNIMessage) - nnim.nni = 7 - var _ Marshaler = nnim.nni // verify it is truly a Marshaler - if _, err := Marshal(nnim); err != nil { - t.Error("unexpected error marshaling nnim: ", err) - } -} - -func TestAllSetDefaults(t *testing.T) { - // Exercise SetDefaults with all scalar field types. - m := &Defaults{ - // NaN != NaN, so override that here. - F_Nan: Float32(1.7), - } - expected := &Defaults{ - F_Bool: Bool(true), - F_Int32: Int32(32), - F_Int64: Int64(64), - F_Fixed32: Uint32(320), - F_Fixed64: Uint64(640), - F_Uint32: Uint32(3200), - F_Uint64: Uint64(6400), - F_Float: Float32(314159), - F_Double: Float64(271828), - F_String: String(`hello, "world!"` + "\n"), - F_Bytes: []byte("Bignose"), - F_Sint32: Int32(-32), - F_Sint64: Int64(-64), - F_Enum: Defaults_GREEN.Enum(), - F_Pinf: Float32(float32(math.Inf(1))), - F_Ninf: Float32(float32(math.Inf(-1))), - F_Nan: Float32(1.7), - StrZero: String(""), - } - SetDefaults(m) - if !Equal(m, expected) { - t.Errorf("SetDefaults failed\n got %v\nwant %v", m, expected) - } -} - -func TestSetDefaultsWithSetField(t *testing.T) { - // Check that a set value is not overridden. - m := &Defaults{ - F_Int32: Int32(12), - } - SetDefaults(m) - if v := m.GetF_Int32(); v != 12 { - t.Errorf("m.FInt32 = %v, want 12", v) - } -} - -func TestSetDefaultsWithSubMessage(t *testing.T) { - m := &OtherMessage{ - Key: Int64(123), - Inner: &InnerMessage{ - Host: String("gopher"), - }, - } - expected := &OtherMessage{ - Key: Int64(123), - Inner: &InnerMessage{ - Host: String("gopher"), - Port: Int32(4000), - }, - } - SetDefaults(m) - if !Equal(m, expected) { - t.Errorf("\n got %v\nwant %v", m, expected) - } -} - -func TestSetDefaultsWithRepeatedSubMessage(t *testing.T) { - m := &MyMessage{ - RepInner: []*InnerMessage{{}}, - } - expected := &MyMessage{ - RepInner: []*InnerMessage{{ - Port: Int32(4000), - }}, - } - SetDefaults(m) - if !Equal(m, expected) { - t.Errorf("\n got %v\nwant %v", m, expected) - } -} - -func TestSetDefaultWithRepeatedNonMessage(t *testing.T) { - m := &MyMessage{ - Pet: []string{"turtle", "wombat"}, - } - expected := Clone(m) - SetDefaults(m) - if !Equal(m, expected) { - t.Errorf("\n got %v\nwant %v", m, expected) - } -} - -func TestMaximumTagNumber(t *testing.T) { - m := &MaxTag{ - LastField: String("natural goat essence"), - } - buf, err := Marshal(m) - if err != nil { - t.Fatalf("proto.Marshal failed: %v", err) - } - m2 := new(MaxTag) - if err := Unmarshal(buf, m2); err != nil { - t.Fatalf("proto.Unmarshal failed: %v", err) - } - if got, want := m2.GetLastField(), *m.LastField; got != want { - t.Errorf("got %q, want %q", got, want) - } -} - -func TestJSON(t *testing.T) { - m := &MyMessage{ - Count: Int32(4), - Pet: []string{"bunny", "kitty"}, - Inner: &InnerMessage{ - Host: String("cauchy"), - }, - Bikeshed: MyMessage_GREEN.Enum(), - } - const expected = `{"count":4,"pet":["bunny","kitty"],"inner":{"host":"cauchy"},"bikeshed":1}` - - b, err := json.Marshal(m) - if err != nil { - t.Fatalf("json.Marshal failed: %v", err) - } - s := string(b) - if s != expected { - t.Errorf("got %s\nwant %s", s, expected) - } - - received := new(MyMessage) - if err := json.Unmarshal(b, received); err != nil { - t.Fatalf("json.Unmarshal failed: %v", err) - } - if !Equal(received, m) { - t.Fatalf("got %s, want %s", received, m) - } - - // Test unmarshalling of JSON with symbolic enum name. - const old = `{"count":4,"pet":["bunny","kitty"],"inner":{"host":"cauchy"},"bikeshed":"GREEN"}` - received.Reset() - if err := json.Unmarshal([]byte(old), received); err != nil { - t.Fatalf("json.Unmarshal failed: %v", err) - } - if !Equal(received, m) { - t.Fatalf("got %s, want %s", received, m) - } -} - -func TestBadWireType(t *testing.T) { - b := []byte{7<<3 | 6} // field 7, wire type 6 - pb := new(OtherMessage) - if err := Unmarshal(b, pb); err == nil { - t.Errorf("Unmarshal did not fail") - } else if !strings.Contains(err.Error(), "unknown wire type") { - t.Errorf("wrong error: %v", err) - } -} - -func TestBytesWithInvalidLength(t *testing.T) { - // If a byte sequence has an invalid (negative) length, Unmarshal should not panic. - b := []byte{2<<3 | WireBytes, 0xff, 0xff, 0xff, 0xff, 0xff, 0} - Unmarshal(b, new(MyMessage)) -} - -func TestLengthOverflow(t *testing.T) { - // Overflowing a length should not panic. - b := []byte{2<<3 | WireBytes, 1, 1, 3<<3 | WireBytes, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, 0x01} - Unmarshal(b, new(MyMessage)) -} - -func TestVarintOverflow(t *testing.T) { - // Overflowing a 64-bit length should not be allowed. - b := []byte{1<<3 | WireVarint, 0x01, 3<<3 | WireBytes, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x01} - if err := Unmarshal(b, new(MyMessage)); err == nil { - t.Fatalf("Overflowed uint64 length without error") - } -} - -func TestUnmarshalFuzz(t *testing.T) { - const N = 1000 - seed := time.Now().UnixNano() - t.Logf("RNG seed is %d", seed) - rng := rand.New(rand.NewSource(seed)) - buf := make([]byte, 20) - for i := 0; i < N; i++ { - for j := range buf { - buf[j] = byte(rng.Intn(256)) - } - fuzzUnmarshal(t, buf) - } -} - -func TestMergeMessages(t *testing.T) { - pb := &MessageList{Message: []*MessageList_Message{{Name: String("x"), Count: Int32(1)}}} - data, err := Marshal(pb) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - - pb1 := new(MessageList) - if err := Unmarshal(data, pb1); err != nil { - t.Fatalf("first Unmarshal: %v", err) - } - if err := Unmarshal(data, pb1); err != nil { - t.Fatalf("second Unmarshal: %v", err) - } - if len(pb1.Message) != 1 { - t.Errorf("two Unmarshals produced %d Messages, want 1", len(pb1.Message)) - } - - pb2 := new(MessageList) - if err := UnmarshalMerge(data, pb2); err != nil { - t.Fatalf("first UnmarshalMerge: %v", err) - } - if err := UnmarshalMerge(data, pb2); err != nil { - t.Fatalf("second UnmarshalMerge: %v", err) - } - if len(pb2.Message) != 2 { - t.Errorf("two UnmarshalMerges produced %d Messages, want 2", len(pb2.Message)) - } -} - -func TestExtensionMarshalOrder(t *testing.T) { - m := &MyMessage{Count: Int(123)} - if err := SetExtension(m, E_Ext_More, &Ext{Data: String("alpha")}); err != nil { - t.Fatalf("SetExtension: %v", err) - } - if err := SetExtension(m, E_Ext_Text, String("aleph")); err != nil { - t.Fatalf("SetExtension: %v", err) - } - if err := SetExtension(m, E_Ext_Number, Int32(1)); err != nil { - t.Fatalf("SetExtension: %v", err) - } - - // Serialize m several times, and check we get the same bytes each time. - var orig []byte - for i := 0; i < 100; i++ { - b, err := Marshal(m) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - if i == 0 { - orig = b - continue - } - if !bytes.Equal(b, orig) { - t.Errorf("Bytes differ on attempt #%d", i) - } - } -} - -// Many extensions, because small maps might not iterate differently on each iteration. -var exts = []*ExtensionDesc{ - E_X201, - E_X202, - E_X203, - E_X204, - E_X205, - E_X206, - E_X207, - E_X208, - E_X209, - E_X210, - E_X211, - E_X212, - E_X213, - E_X214, - E_X215, - E_X216, - E_X217, - E_X218, - E_X219, - E_X220, - E_X221, - E_X222, - E_X223, - E_X224, - E_X225, - E_X226, - E_X227, - E_X228, - E_X229, - E_X230, - E_X231, - E_X232, - E_X233, - E_X234, - E_X235, - E_X236, - E_X237, - E_X238, - E_X239, - E_X240, - E_X241, - E_X242, - E_X243, - E_X244, - E_X245, - E_X246, - E_X247, - E_X248, - E_X249, - E_X250, -} - -func TestMessageSetMarshalOrder(t *testing.T) { - m := &MyMessageSet{} - for _, x := range exts { - if err := SetExtension(m, x, &Empty{}); err != nil { - t.Fatalf("SetExtension: %v", err) - } - } - - buf, err := Marshal(m) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - - // Serialize m several times, and check we get the same bytes each time. - for i := 0; i < 10; i++ { - b1, err := Marshal(m) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - if !bytes.Equal(b1, buf) { - t.Errorf("Bytes differ on re-Marshal #%d", i) - } - - m2 := &MyMessageSet{} - if err := Unmarshal(buf, m2); err != nil { - t.Errorf("Unmarshal: %v", err) - } - b2, err := Marshal(m2) - if err != nil { - t.Errorf("re-Marshal: %v", err) - } - if !bytes.Equal(b2, buf) { - t.Errorf("Bytes differ on round-trip #%d", i) - } - } -} - -func TestUnmarshalMergesMessages(t *testing.T) { - // If a nested message occurs twice in the input, - // the fields should be merged when decoding. - a := &OtherMessage{ - Key: Int64(123), - Inner: &InnerMessage{ - Host: String("polhode"), - Port: Int32(1234), - }, - } - aData, err := Marshal(a) - if err != nil { - t.Fatalf("Marshal(a): %v", err) - } - b := &OtherMessage{ - Weight: Float32(1.2), - Inner: &InnerMessage{ - Host: String("herpolhode"), - Connected: Bool(true), - }, - } - bData, err := Marshal(b) - if err != nil { - t.Fatalf("Marshal(b): %v", err) - } - want := &OtherMessage{ - Key: Int64(123), - Weight: Float32(1.2), - Inner: &InnerMessage{ - Host: String("herpolhode"), - Port: Int32(1234), - Connected: Bool(true), - }, - } - got := new(OtherMessage) - if err := Unmarshal(append(aData, bData...), got); err != nil { - t.Fatalf("Unmarshal: %v", err) - } - if !Equal(got, want) { - t.Errorf("\n got %v\nwant %v", got, want) - } -} - -func TestEncodingSizes(t *testing.T) { - tests := []struct { - m Message - n int - }{ - {&Defaults{F_Int32: Int32(math.MaxInt32)}, 6}, - {&Defaults{F_Int32: Int32(math.MinInt32)}, 11}, - {&Defaults{F_Uint32: Uint32(uint32(math.MaxInt32) + 1)}, 6}, - {&Defaults{F_Uint32: Uint32(math.MaxUint32)}, 6}, - } - for _, test := range tests { - b, err := Marshal(test.m) - if err != nil { - t.Errorf("Marshal(%v): %v", test.m, err) - continue - } - if len(b) != test.n { - t.Errorf("Marshal(%v) yielded %d bytes, want %d bytes", test.m, len(b), test.n) - } - } -} - -func TestRequiredNotSetError(t *testing.T) { - pb := initGoTest(false) - pb.RequiredField.Label = nil - pb.F_Int32Required = nil - pb.F_Int64Required = nil - - expected := "0807" + // field 1, encoding 0, value 7 - "2206" + "120474797065" + // field 4, encoding 2 (GoTestField) - "5001" + // field 10, encoding 0, value 1 - "6d20000000" + // field 13, encoding 5, value 0x20 - "714000000000000000" + // field 14, encoding 1, value 0x40 - "78a019" + // field 15, encoding 0, value 0xca0 = 3232 - "8001c032" + // field 16, encoding 0, value 0x1940 = 6464 - "8d0100004a45" + // field 17, encoding 5, value 3232.0 - "9101000000000040b940" + // field 18, encoding 1, value 6464.0 - "9a0106" + "737472696e67" + // field 19, encoding 2, string "string" - "b304" + // field 70, encoding 3, start group - "ba0408" + "7265717569726564" + // field 71, encoding 2, string "required" - "b404" + // field 70, encoding 4, end group - "aa0605" + "6279746573" + // field 101, encoding 2, string "bytes" - "b0063f" + // field 102, encoding 0, 0x3f zigzag32 - "b8067f" // field 103, encoding 0, 0x7f zigzag64 - - o := old() - bytes, err := Marshal(pb) - if _, ok := err.(*RequiredNotSetError); !ok { - fmt.Printf("marshal-1 err = %v, want *RequiredNotSetError", err) - o.DebugPrint("", bytes) - t.Fatalf("expected = %s", expected) - } - if strings.Index(err.Error(), "RequiredField.Label") < 0 { - t.Errorf("marshal-1 wrong err msg: %v", err) - } - if !equal(bytes, expected, t) { - o.DebugPrint("neq 1", bytes) - t.Fatalf("expected = %s", expected) - } - - // Now test Unmarshal by recreating the original buffer. - pbd := new(GoTest) - err = Unmarshal(bytes, pbd) - if _, ok := err.(*RequiredNotSetError); !ok { - t.Fatalf("unmarshal err = %v, want *RequiredNotSetError", err) - o.DebugPrint("", bytes) - t.Fatalf("string = %s", expected) - } - if strings.Index(err.Error(), "RequiredField.{Unknown}") < 0 { - t.Errorf("unmarshal wrong err msg: %v", err) - } - bytes, err = Marshal(pbd) - if _, ok := err.(*RequiredNotSetError); !ok { - t.Errorf("marshal-2 err = %v, want *RequiredNotSetError", err) - o.DebugPrint("", bytes) - t.Fatalf("string = %s", expected) - } - if strings.Index(err.Error(), "RequiredField.Label") < 0 { - t.Errorf("marshal-2 wrong err msg: %v", err) - } - if !equal(bytes, expected, t) { - o.DebugPrint("neq 2", bytes) - t.Fatalf("string = %s", expected) - } -} - -func fuzzUnmarshal(t *testing.T, data []byte) { - defer func() { - if e := recover(); e != nil { - t.Errorf("These bytes caused a panic: %+v", data) - t.Logf("Stack:\n%s", debug.Stack()) - t.FailNow() - } - }() - - pb := new(MyMessage) - Unmarshal(data, pb) -} - -func TestMapFieldMarshal(t *testing.T) { - m := &MessageWithMap{ - NameMapping: map[int32]string{ - 1: "Rob", - 4: "Ian", - 8: "Dave", - }, - } - b, err := Marshal(m) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - - // b should be the concatenation of these three byte sequences in some order. - parts := []string{ - "\n\a\b\x01\x12\x03Rob", - "\n\a\b\x04\x12\x03Ian", - "\n\b\b\x08\x12\x04Dave", - } - ok := false - for i := range parts { - for j := range parts { - if j == i { - continue - } - for k := range parts { - if k == i || k == j { - continue - } - try := parts[i] + parts[j] + parts[k] - if bytes.Equal(b, []byte(try)) { - ok = true - break - } - } - } - } - if !ok { - t.Fatalf("Incorrect Marshal output.\n got %q\nwant %q (or a permutation of that)", b, parts[0]+parts[1]+parts[2]) - } - t.Logf("FYI b: %q", b) - - (new(Buffer)).DebugPrint("Dump of b", b) -} - -func TestMapFieldRoundTrips(t *testing.T) { - m := &MessageWithMap{ - NameMapping: map[int32]string{ - 1: "Rob", - 4: "Ian", - 8: "Dave", - }, - MsgMapping: map[int64]*FloatingPoint{ - 0x7001: &FloatingPoint{F: Float64(2.0)}, - }, - ByteMapping: map[bool][]byte{ - false: []byte("that's not right!"), - true: []byte("aye, 'tis true!"), - }, - } - b, err := Marshal(m) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - t.Logf("FYI b: %q", b) - m2 := new(MessageWithMap) - if err := Unmarshal(b, m2); err != nil { - t.Fatalf("Unmarshal: %v", err) - } - for _, pair := range [][2]interface{}{ - {m.NameMapping, m2.NameMapping}, - {m.MsgMapping, m2.MsgMapping}, - {m.ByteMapping, m2.ByteMapping}, - } { - if !reflect.DeepEqual(pair[0], pair[1]) { - t.Errorf("Map did not survive a round trip.\ninitial: %v\n final: %v", pair[0], pair[1]) - } - } -} - -func TestMapFieldWithNil(t *testing.T) { - m1 := &MessageWithMap{ - MsgMapping: map[int64]*FloatingPoint{ - 1: nil, - }, - } - b, err := Marshal(m1) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - m2 := new(MessageWithMap) - if err := Unmarshal(b, m2); err != nil { - t.Fatalf("Unmarshal: %v, got these bytes: %v", err, b) - } - if v, ok := m2.MsgMapping[1]; !ok { - t.Error("msg_mapping[1] not present") - } else if v != nil { - t.Errorf("msg_mapping[1] not nil: %v", v) - } -} - -func TestMapFieldWithNilBytes(t *testing.T) { - m1 := &MessageWithMap{ - ByteMapping: map[bool][]byte{ - false: []byte{}, - true: nil, - }, - } - n := Size(m1) - b, err := Marshal(m1) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - if n != len(b) { - t.Errorf("Size(m1) = %d; want len(Marshal(m1)) = %d", n, len(b)) - } - m2 := new(MessageWithMap) - if err := Unmarshal(b, m2); err != nil { - t.Fatalf("Unmarshal: %v, got these bytes: %v", err, b) - } - if v, ok := m2.ByteMapping[false]; !ok { - t.Error("byte_mapping[false] not present") - } else if len(v) != 0 { - t.Errorf("byte_mapping[false] not empty: %#v", v) - } - if v, ok := m2.ByteMapping[true]; !ok { - t.Error("byte_mapping[true] not present") - } else if len(v) != 0 { - t.Errorf("byte_mapping[true] not empty: %#v", v) - } -} - -func TestDecodeMapFieldMissingKey(t *testing.T) { - b := []byte{ - 0x0A, 0x03, // message, tag 1 (name_mapping), of length 3 bytes - // no key - 0x12, 0x01, 0x6D, // string value of length 1 byte, value "m" - } - got := &MessageWithMap{} - err := Unmarshal(b, got) - if err != nil { - t.Fatalf("failed to marshal map with missing key: %v", err) - } - want := &MessageWithMap{NameMapping: map[int32]string{0: "m"}} - if !Equal(got, want) { - t.Errorf("Unmarshaled map with no key was not as expected. got: %v, want %v", got, want) - } -} - -func TestDecodeMapFieldMissingValue(t *testing.T) { - b := []byte{ - 0x0A, 0x02, // message, tag 1 (name_mapping), of length 2 bytes - 0x08, 0x01, // varint key, value 1 - // no value - } - got := &MessageWithMap{} - err := Unmarshal(b, got) - if err != nil { - t.Fatalf("failed to marshal map with missing value: %v", err) - } - want := &MessageWithMap{NameMapping: map[int32]string{1: ""}} - if !Equal(got, want) { - t.Errorf("Unmarshaled map with no value was not as expected. got: %v, want %v", got, want) - } -} - -func TestOneof(t *testing.T) { - m := &Communique{} - b, err := Marshal(m) - if err != nil { - t.Fatalf("Marshal of empty message with oneof: %v", err) - } - if len(b) != 0 { - t.Errorf("Marshal of empty message yielded too many bytes: %v", b) - } - - m = &Communique{ - Union: &Communique_Name{"Barry"}, - } - - // Round-trip. - b, err = Marshal(m) - if err != nil { - t.Fatalf("Marshal of message with oneof: %v", err) - } - if len(b) != 7 { // name tag/wire (1) + name len (1) + name (5) - t.Errorf("Incorrect marshal of message with oneof: %v", b) - } - m.Reset() - if err := Unmarshal(b, m); err != nil { - t.Fatalf("Unmarshal of message with oneof: %v", err) - } - if x, ok := m.Union.(*Communique_Name); !ok || x.Name != "Barry" { - t.Errorf("After round trip, Union = %+v", m.Union) - } - if name := m.GetName(); name != "Barry" { - t.Errorf("After round trip, GetName = %q, want %q", name, "Barry") - } - - // Let's try with a message in the oneof. - m.Union = &Communique_Msg{&Strings{StringField: String("deep deep string")}} - b, err = Marshal(m) - if err != nil { - t.Fatalf("Marshal of message with oneof set to message: %v", err) - } - if len(b) != 20 { // msg tag/wire (1) + msg len (1) + msg (1 + 1 + 16) - t.Errorf("Incorrect marshal of message with oneof set to message: %v", b) - } - m.Reset() - if err := Unmarshal(b, m); err != nil { - t.Fatalf("Unmarshal of message with oneof set to message: %v", err) - } - ss, ok := m.Union.(*Communique_Msg) - if !ok || ss.Msg.GetStringField() != "deep deep string" { - t.Errorf("After round trip with oneof set to message, Union = %+v", m.Union) - } -} - -func TestInefficientPackedBool(t *testing.T) { - // https://github.com/golang/protobuf/issues/76 - inp := []byte{ - 0x12, 0x02, // 0x12 = 2<<3|2; 2 bytes - // Usually a bool should take a single byte, - // but it is permitted to be any varint. - 0xb9, 0x30, - } - if err := Unmarshal(inp, new(MoreRepeated)); err != nil { - t.Error(err) - } -} - -// Benchmarks - -func testMsg() *GoTest { - pb := initGoTest(true) - const N = 1000 // Internally the library starts much smaller. - pb.F_Int32Repeated = make([]int32, N) - pb.F_DoubleRepeated = make([]float64, N) - for i := 0; i < N; i++ { - pb.F_Int32Repeated[i] = int32(i) - pb.F_DoubleRepeated[i] = float64(i) - } - return pb -} - -func bytesMsg() *GoTest { - pb := initGoTest(true) - buf := make([]byte, 4000) - for i := range buf { - buf[i] = byte(i) - } - pb.F_BytesDefaulted = buf - return pb -} - -func benchmarkMarshal(b *testing.B, pb Message, marshal func(Message) ([]byte, error)) { - d, _ := marshal(pb) - b.SetBytes(int64(len(d))) - b.ResetTimer() - for i := 0; i < b.N; i++ { - marshal(pb) - } -} - -func benchmarkBufferMarshal(b *testing.B, pb Message) { - p := NewBuffer(nil) - benchmarkMarshal(b, pb, func(pb0 Message) ([]byte, error) { - p.Reset() - err := p.Marshal(pb0) - return p.Bytes(), err - }) -} - -func benchmarkSize(b *testing.B, pb Message) { - benchmarkMarshal(b, pb, func(pb0 Message) ([]byte, error) { - Size(pb) - return nil, nil - }) -} - -func newOf(pb Message) Message { - in := reflect.ValueOf(pb) - if in.IsNil() { - return pb - } - return reflect.New(in.Type().Elem()).Interface().(Message) -} - -func benchmarkUnmarshal(b *testing.B, pb Message, unmarshal func([]byte, Message) error) { - d, _ := Marshal(pb) - b.SetBytes(int64(len(d))) - pbd := newOf(pb) - - b.ResetTimer() - for i := 0; i < b.N; i++ { - unmarshal(d, pbd) - } -} - -func benchmarkBufferUnmarshal(b *testing.B, pb Message) { - p := NewBuffer(nil) - benchmarkUnmarshal(b, pb, func(d []byte, pb0 Message) error { - p.SetBuf(d) - return p.Unmarshal(pb0) - }) -} - -// Benchmark{Marshal,BufferMarshal,Size,Unmarshal,BufferUnmarshal}{,Bytes} - -func BenchmarkMarshal(b *testing.B) { - benchmarkMarshal(b, testMsg(), Marshal) -} - -func BenchmarkBufferMarshal(b *testing.B) { - benchmarkBufferMarshal(b, testMsg()) -} - -func BenchmarkSize(b *testing.B) { - benchmarkSize(b, testMsg()) -} - -func BenchmarkUnmarshal(b *testing.B) { - benchmarkUnmarshal(b, testMsg(), Unmarshal) -} - -func BenchmarkBufferUnmarshal(b *testing.B) { - benchmarkBufferUnmarshal(b, testMsg()) -} - -func BenchmarkMarshalBytes(b *testing.B) { - benchmarkMarshal(b, bytesMsg(), Marshal) -} - -func BenchmarkBufferMarshalBytes(b *testing.B) { - benchmarkBufferMarshal(b, bytesMsg()) -} - -func BenchmarkSizeBytes(b *testing.B) { - benchmarkSize(b, bytesMsg()) -} - -func BenchmarkUnmarshalBytes(b *testing.B) { - benchmarkUnmarshal(b, bytesMsg(), Unmarshal) -} - -func BenchmarkBufferUnmarshalBytes(b *testing.B) { - benchmarkBufferUnmarshal(b, bytesMsg()) -} - -func BenchmarkUnmarshalUnrecognizedFields(b *testing.B) { - b.StopTimer() - pb := initGoTestField() - skip := &GoSkipTest{ - SkipInt32: Int32(32), - SkipFixed32: Uint32(3232), - SkipFixed64: Uint64(6464), - SkipString: String("skipper"), - Skipgroup: &GoSkipTest_SkipGroup{ - GroupInt32: Int32(75), - GroupString: String("wxyz"), - }, - } - - pbd := new(GoTestField) - p := NewBuffer(nil) - p.Marshal(pb) - p.Marshal(skip) - p2 := NewBuffer(nil) - - b.StartTimer() - for i := 0; i < b.N; i++ { - p2.SetBuf(p.Bytes()) - p2.Unmarshal(pbd) - } -} diff --git a/vendor/github.com/golang/protobuf/proto/any_test.go b/vendor/github.com/golang/protobuf/proto/any_test.go deleted file mode 100644 index 1a3c22ed4..000000000 --- a/vendor/github.com/golang/protobuf/proto/any_test.go +++ /dev/null @@ -1,300 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2016 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto_test - -import ( - "strings" - "testing" - - "github.com/golang/protobuf/proto" - - pb "github.com/golang/protobuf/proto/proto3_proto" - testpb "github.com/golang/protobuf/proto/testdata" - anypb "github.com/golang/protobuf/ptypes/any" -) - -var ( - expandedMarshaler = proto.TextMarshaler{ExpandAny: true} - expandedCompactMarshaler = proto.TextMarshaler{Compact: true, ExpandAny: true} -) - -// anyEqual reports whether two messages which may be google.protobuf.Any or may -// contain google.protobuf.Any fields are equal. We can't use proto.Equal for -// comparison, because semantically equivalent messages may be marshaled to -// binary in different tag order. Instead, trust that TextMarshaler with -// ExpandAny option works and compare the text marshaling results. -func anyEqual(got, want proto.Message) bool { - // if messages are proto.Equal, no need to marshal. - if proto.Equal(got, want) { - return true - } - g := expandedMarshaler.Text(got) - w := expandedMarshaler.Text(want) - return g == w -} - -type golden struct { - m proto.Message - t, c string -} - -var goldenMessages = makeGolden() - -func makeGolden() []golden { - nested := &pb.Nested{Bunny: "Monty"} - nb, err := proto.Marshal(nested) - if err != nil { - panic(err) - } - m1 := &pb.Message{ - Name: "David", - ResultCount: 47, - Anything: &anypb.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(nested), Value: nb}, - } - m2 := &pb.Message{ - Name: "David", - ResultCount: 47, - Anything: &anypb.Any{TypeUrl: "http://[::1]/type.googleapis.com/" + proto.MessageName(nested), Value: nb}, - } - m3 := &pb.Message{ - Name: "David", - ResultCount: 47, - Anything: &anypb.Any{TypeUrl: `type.googleapis.com/"/` + proto.MessageName(nested), Value: nb}, - } - m4 := &pb.Message{ - Name: "David", - ResultCount: 47, - Anything: &anypb.Any{TypeUrl: "type.googleapis.com/a/path/" + proto.MessageName(nested), Value: nb}, - } - m5 := &anypb.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(nested), Value: nb} - - any1 := &testpb.MyMessage{Count: proto.Int32(47), Name: proto.String("David")} - proto.SetExtension(any1, testpb.E_Ext_More, &testpb.Ext{Data: proto.String("foo")}) - proto.SetExtension(any1, testpb.E_Ext_Text, proto.String("bar")) - any1b, err := proto.Marshal(any1) - if err != nil { - panic(err) - } - any2 := &testpb.MyMessage{Count: proto.Int32(42), Bikeshed: testpb.MyMessage_GREEN.Enum(), RepBytes: [][]byte{[]byte("roboto")}} - proto.SetExtension(any2, testpb.E_Ext_More, &testpb.Ext{Data: proto.String("baz")}) - any2b, err := proto.Marshal(any2) - if err != nil { - panic(err) - } - m6 := &pb.Message{ - Name: "David", - ResultCount: 47, - Anything: &anypb.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(any1), Value: any1b}, - ManyThings: []*anypb.Any{ - &anypb.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(any2), Value: any2b}, - &anypb.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(any1), Value: any1b}, - }, - } - - const ( - m1Golden = ` -name: "David" -result_count: 47 -anything: < - [type.googleapis.com/proto3_proto.Nested]: < - bunny: "Monty" - > -> -` - m2Golden = ` -name: "David" -result_count: 47 -anything: < - ["http://[::1]/type.googleapis.com/proto3_proto.Nested"]: < - bunny: "Monty" - > -> -` - m3Golden = ` -name: "David" -result_count: 47 -anything: < - ["type.googleapis.com/\"/proto3_proto.Nested"]: < - bunny: "Monty" - > -> -` - m4Golden = ` -name: "David" -result_count: 47 -anything: < - [type.googleapis.com/a/path/proto3_proto.Nested]: < - bunny: "Monty" - > -> -` - m5Golden = ` -[type.googleapis.com/proto3_proto.Nested]: < - bunny: "Monty" -> -` - m6Golden = ` -name: "David" -result_count: 47 -anything: < - [type.googleapis.com/testdata.MyMessage]: < - count: 47 - name: "David" - [testdata.Ext.more]: < - data: "foo" - > - [testdata.Ext.text]: "bar" - > -> -many_things: < - [type.googleapis.com/testdata.MyMessage]: < - count: 42 - bikeshed: GREEN - rep_bytes: "roboto" - [testdata.Ext.more]: < - data: "baz" - > - > -> -many_things: < - [type.googleapis.com/testdata.MyMessage]: < - count: 47 - name: "David" - [testdata.Ext.more]: < - data: "foo" - > - [testdata.Ext.text]: "bar" - > -> -` - ) - return []golden{ - {m1, strings.TrimSpace(m1Golden) + "\n", strings.TrimSpace(compact(m1Golden)) + " "}, - {m2, strings.TrimSpace(m2Golden) + "\n", strings.TrimSpace(compact(m2Golden)) + " "}, - {m3, strings.TrimSpace(m3Golden) + "\n", strings.TrimSpace(compact(m3Golden)) + " "}, - {m4, strings.TrimSpace(m4Golden) + "\n", strings.TrimSpace(compact(m4Golden)) + " "}, - {m5, strings.TrimSpace(m5Golden) + "\n", strings.TrimSpace(compact(m5Golden)) + " "}, - {m6, strings.TrimSpace(m6Golden) + "\n", strings.TrimSpace(compact(m6Golden)) + " "}, - } -} - -func TestMarshalGolden(t *testing.T) { - for _, tt := range goldenMessages { - if got, want := expandedMarshaler.Text(tt.m), tt.t; got != want { - t.Errorf("message %v: got:\n%s\nwant:\n%s", tt.m, got, want) - } - if got, want := expandedCompactMarshaler.Text(tt.m), tt.c; got != want { - t.Errorf("message %v: got:\n`%s`\nwant:\n`%s`", tt.m, got, want) - } - } -} - -func TestUnmarshalGolden(t *testing.T) { - for _, tt := range goldenMessages { - want := tt.m - got := proto.Clone(tt.m) - got.Reset() - if err := proto.UnmarshalText(tt.t, got); err != nil { - t.Errorf("failed to unmarshal\n%s\nerror: %v", tt.t, err) - } - if !anyEqual(got, want) { - t.Errorf("message:\n%s\ngot:\n%s\nwant:\n%s", tt.t, got, want) - } - got.Reset() - if err := proto.UnmarshalText(tt.c, got); err != nil { - t.Errorf("failed to unmarshal\n%s\nerror: %v", tt.c, err) - } - if !anyEqual(got, want) { - t.Errorf("message:\n%s\ngot:\n%s\nwant:\n%s", tt.c, got, want) - } - } -} - -func TestMarshalUnknownAny(t *testing.T) { - m := &pb.Message{ - Anything: &anypb.Any{ - TypeUrl: "foo", - Value: []byte("bar"), - }, - } - want := `anything: < - type_url: "foo" - value: "bar" -> -` - got := expandedMarshaler.Text(m) - if got != want { - t.Errorf("got\n`%s`\nwant\n`%s`", got, want) - } -} - -func TestAmbiguousAny(t *testing.T) { - pb := &anypb.Any{} - err := proto.UnmarshalText(` - type_url: "ttt/proto3_proto.Nested" - value: "\n\x05Monty" - `, pb) - t.Logf("result: %v (error: %v)", expandedMarshaler.Text(pb), err) - if err != nil { - t.Errorf("failed to parse ambiguous Any message: %v", err) - } -} - -func TestUnmarshalOverwriteAny(t *testing.T) { - pb := &anypb.Any{} - err := proto.UnmarshalText(` - [type.googleapis.com/a/path/proto3_proto.Nested]: < - bunny: "Monty" - > - [type.googleapis.com/a/path/proto3_proto.Nested]: < - bunny: "Rabbit of Caerbannog" - > - `, pb) - want := `line 7: Any message unpacked multiple times, or "type_url" already set` - if err.Error() != want { - t.Errorf("incorrect error.\nHave: %v\nWant: %v", err.Error(), want) - } -} - -func TestUnmarshalAnyMixAndMatch(t *testing.T) { - pb := &anypb.Any{} - err := proto.UnmarshalText(` - value: "\n\x05Monty" - [type.googleapis.com/a/path/proto3_proto.Nested]: < - bunny: "Rabbit of Caerbannog" - > - `, pb) - want := `line 5: Any message unpacked multiple times, or "value" already set` - if err.Error() != want { - t.Errorf("incorrect error.\nHave: %v\nWant: %v", err.Error(), want) - } -} diff --git a/vendor/github.com/golang/protobuf/proto/clone_test.go b/vendor/github.com/golang/protobuf/proto/clone_test.go deleted file mode 100644 index f607ff49e..000000000 --- a/vendor/github.com/golang/protobuf/proto/clone_test.go +++ /dev/null @@ -1,300 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2011 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto_test - -import ( - "testing" - - "github.com/golang/protobuf/proto" - - proto3pb "github.com/golang/protobuf/proto/proto3_proto" - pb "github.com/golang/protobuf/proto/testdata" -) - -var cloneTestMessage = &pb.MyMessage{ - Count: proto.Int32(42), - Name: proto.String("Dave"), - Pet: []string{"bunny", "kitty", "horsey"}, - Inner: &pb.InnerMessage{ - Host: proto.String("niles"), - Port: proto.Int32(9099), - Connected: proto.Bool(true), - }, - Others: []*pb.OtherMessage{ - { - Value: []byte("some bytes"), - }, - }, - Somegroup: &pb.MyMessage_SomeGroup{ - GroupField: proto.Int32(6), - }, - RepBytes: [][]byte{[]byte("sham"), []byte("wow")}, -} - -func init() { - ext := &pb.Ext{ - Data: proto.String("extension"), - } - if err := proto.SetExtension(cloneTestMessage, pb.E_Ext_More, ext); err != nil { - panic("SetExtension: " + err.Error()) - } -} - -func TestClone(t *testing.T) { - m := proto.Clone(cloneTestMessage).(*pb.MyMessage) - if !proto.Equal(m, cloneTestMessage) { - t.Errorf("Clone(%v) = %v", cloneTestMessage, m) - } - - // Verify it was a deep copy. - *m.Inner.Port++ - if proto.Equal(m, cloneTestMessage) { - t.Error("Mutating clone changed the original") - } - // Byte fields and repeated fields should be copied. - if &m.Pet[0] == &cloneTestMessage.Pet[0] { - t.Error("Pet: repeated field not copied") - } - if &m.Others[0] == &cloneTestMessage.Others[0] { - t.Error("Others: repeated field not copied") - } - if &m.Others[0].Value[0] == &cloneTestMessage.Others[0].Value[0] { - t.Error("Others[0].Value: bytes field not copied") - } - if &m.RepBytes[0] == &cloneTestMessage.RepBytes[0] { - t.Error("RepBytes: repeated field not copied") - } - if &m.RepBytes[0][0] == &cloneTestMessage.RepBytes[0][0] { - t.Error("RepBytes[0]: bytes field not copied") - } -} - -func TestCloneNil(t *testing.T) { - var m *pb.MyMessage - if c := proto.Clone(m); !proto.Equal(m, c) { - t.Errorf("Clone(%v) = %v", m, c) - } -} - -var mergeTests = []struct { - src, dst, want proto.Message -}{ - { - src: &pb.MyMessage{ - Count: proto.Int32(42), - }, - dst: &pb.MyMessage{ - Name: proto.String("Dave"), - }, - want: &pb.MyMessage{ - Count: proto.Int32(42), - Name: proto.String("Dave"), - }, - }, - { - src: &pb.MyMessage{ - Inner: &pb.InnerMessage{ - Host: proto.String("hey"), - Connected: proto.Bool(true), - }, - Pet: []string{"horsey"}, - Others: []*pb.OtherMessage{ - { - Value: []byte("some bytes"), - }, - }, - }, - dst: &pb.MyMessage{ - Inner: &pb.InnerMessage{ - Host: proto.String("niles"), - Port: proto.Int32(9099), - }, - Pet: []string{"bunny", "kitty"}, - Others: []*pb.OtherMessage{ - { - Key: proto.Int64(31415926535), - }, - { - // Explicitly test a src=nil field - Inner: nil, - }, - }, - }, - want: &pb.MyMessage{ - Inner: &pb.InnerMessage{ - Host: proto.String("hey"), - Connected: proto.Bool(true), - Port: proto.Int32(9099), - }, - Pet: []string{"bunny", "kitty", "horsey"}, - Others: []*pb.OtherMessage{ - { - Key: proto.Int64(31415926535), - }, - {}, - { - Value: []byte("some bytes"), - }, - }, - }, - }, - { - src: &pb.MyMessage{ - RepBytes: [][]byte{[]byte("wow")}, - }, - dst: &pb.MyMessage{ - Somegroup: &pb.MyMessage_SomeGroup{ - GroupField: proto.Int32(6), - }, - RepBytes: [][]byte{[]byte("sham")}, - }, - want: &pb.MyMessage{ - Somegroup: &pb.MyMessage_SomeGroup{ - GroupField: proto.Int32(6), - }, - RepBytes: [][]byte{[]byte("sham"), []byte("wow")}, - }, - }, - // Check that a scalar bytes field replaces rather than appends. - { - src: &pb.OtherMessage{Value: []byte("foo")}, - dst: &pb.OtherMessage{Value: []byte("bar")}, - want: &pb.OtherMessage{Value: []byte("foo")}, - }, - { - src: &pb.MessageWithMap{ - NameMapping: map[int32]string{6: "Nigel"}, - MsgMapping: map[int64]*pb.FloatingPoint{ - 0x4001: &pb.FloatingPoint{F: proto.Float64(2.0)}, - 0x4002: &pb.FloatingPoint{ - F: proto.Float64(2.0), - }, - }, - ByteMapping: map[bool][]byte{true: []byte("wowsa")}, - }, - dst: &pb.MessageWithMap{ - NameMapping: map[int32]string{ - 6: "Bruce", // should be overwritten - 7: "Andrew", - }, - MsgMapping: map[int64]*pb.FloatingPoint{ - 0x4002: &pb.FloatingPoint{ - F: proto.Float64(3.0), - Exact: proto.Bool(true), - }, // the entire message should be overwritten - }, - }, - want: &pb.MessageWithMap{ - NameMapping: map[int32]string{ - 6: "Nigel", - 7: "Andrew", - }, - MsgMapping: map[int64]*pb.FloatingPoint{ - 0x4001: &pb.FloatingPoint{F: proto.Float64(2.0)}, - 0x4002: &pb.FloatingPoint{ - F: proto.Float64(2.0), - }, - }, - ByteMapping: map[bool][]byte{true: []byte("wowsa")}, - }, - }, - // proto3 shouldn't merge zero values, - // in the same way that proto2 shouldn't merge nils. - { - src: &proto3pb.Message{ - Name: "Aaron", - Data: []byte(""), // zero value, but not nil - }, - dst: &proto3pb.Message{ - HeightInCm: 176, - Data: []byte("texas!"), - }, - want: &proto3pb.Message{ - Name: "Aaron", - HeightInCm: 176, - Data: []byte("texas!"), - }, - }, - // Oneof fields should merge by assignment. - { - src: &pb.Communique{ - Union: &pb.Communique_Number{41}, - }, - dst: &pb.Communique{ - Union: &pb.Communique_Name{"Bobby Tables"}, - }, - want: &pb.Communique{ - Union: &pb.Communique_Number{41}, - }, - }, - // Oneof nil is the same as not set. - { - src: &pb.Communique{}, - dst: &pb.Communique{ - Union: &pb.Communique_Name{"Bobby Tables"}, - }, - want: &pb.Communique{ - Union: &pb.Communique_Name{"Bobby Tables"}, - }, - }, - { - src: &proto3pb.Message{ - Terrain: map[string]*proto3pb.Nested{ - "kay_a": &proto3pb.Nested{Cute: true}, // replace - "kay_b": &proto3pb.Nested{Bunny: "rabbit"}, // insert - }, - }, - dst: &proto3pb.Message{ - Terrain: map[string]*proto3pb.Nested{ - "kay_a": &proto3pb.Nested{Bunny: "lost"}, // replaced - "kay_c": &proto3pb.Nested{Bunny: "bunny"}, // keep - }, - }, - want: &proto3pb.Message{ - Terrain: map[string]*proto3pb.Nested{ - "kay_a": &proto3pb.Nested{Cute: true}, - "kay_b": &proto3pb.Nested{Bunny: "rabbit"}, - "kay_c": &proto3pb.Nested{Bunny: "bunny"}, - }, - }, - }, -} - -func TestMerge(t *testing.T) { - for _, m := range mergeTests { - got := proto.Clone(m.dst) - proto.Merge(got, m.src) - if !proto.Equal(got, m.want) { - t.Errorf("Merge(%v, %v)\n got %v\nwant %v\n", m.dst, m.src, got, m.want) - } - } -} diff --git a/vendor/github.com/golang/protobuf/proto/decode_test.go b/vendor/github.com/golang/protobuf/proto/decode_test.go deleted file mode 100644 index 2c4c31d12..000000000 --- a/vendor/github.com/golang/protobuf/proto/decode_test.go +++ /dev/null @@ -1,258 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// +build go1.7 - -package proto_test - -import ( - "fmt" - "testing" - - "github.com/golang/protobuf/proto" - tpb "github.com/golang/protobuf/proto/proto3_proto" -) - -var ( - bytesBlackhole []byte - msgBlackhole = new(tpb.Message) -) - -// BenchmarkVarint32ArraySmall shows the performance on an array of small int32 fields (1 and -// 2 bytes long). -func BenchmarkVarint32ArraySmall(b *testing.B) { - for i := uint(1); i <= 10; i++ { - dist := genInt32Dist([7]int{0, 3, 1}, 1<unmarshal. -} - -func TestMarshalUnmarshalRepeatedExtension(t *testing.T) { - // Add a repeated extension to the result. - tests := []struct { - name string - ext []*pb.ComplexExtension - }{ - { - "two fields", - []*pb.ComplexExtension{ - {First: proto.Int32(7)}, - {Second: proto.Int32(11)}, - }, - }, - { - "repeated field", - []*pb.ComplexExtension{ - {Third: []int32{1000}}, - {Third: []int32{2000}}, - }, - }, - { - "two fields and repeated field", - []*pb.ComplexExtension{ - {Third: []int32{1000}}, - {First: proto.Int32(9)}, - {Second: proto.Int32(21)}, - {Third: []int32{2000}}, - }, - }, - } - for _, test := range tests { - // Marshal message with a repeated extension. - msg1 := new(pb.OtherMessage) - err := proto.SetExtension(msg1, pb.E_RComplex, test.ext) - if err != nil { - t.Fatalf("[%s] Error setting extension: %v", test.name, err) - } - b, err := proto.Marshal(msg1) - if err != nil { - t.Fatalf("[%s] Error marshaling message: %v", test.name, err) - } - - // Unmarshal and read the merged proto. - msg2 := new(pb.OtherMessage) - err = proto.Unmarshal(b, msg2) - if err != nil { - t.Fatalf("[%s] Error unmarshaling message: %v", test.name, err) - } - e, err := proto.GetExtension(msg2, pb.E_RComplex) - if err != nil { - t.Fatalf("[%s] Error getting extension: %v", test.name, err) - } - ext := e.([]*pb.ComplexExtension) - if ext == nil { - t.Fatalf("[%s] Invalid extension", test.name) - } - if !reflect.DeepEqual(ext, test.ext) { - t.Errorf("[%s] Wrong value for ComplexExtension: got: %v want: %v\n", test.name, ext, test.ext) - } - } -} - -func TestUnmarshalRepeatingNonRepeatedExtension(t *testing.T) { - // We may see multiple instances of the same extension in the wire - // format. For example, the proto compiler may encode custom options in - // this way. Here, we verify that we merge the extensions together. - tests := []struct { - name string - ext []*pb.ComplexExtension - }{ - { - "two fields", - []*pb.ComplexExtension{ - {First: proto.Int32(7)}, - {Second: proto.Int32(11)}, - }, - }, - { - "repeated field", - []*pb.ComplexExtension{ - {Third: []int32{1000}}, - {Third: []int32{2000}}, - }, - }, - { - "two fields and repeated field", - []*pb.ComplexExtension{ - {Third: []int32{1000}}, - {First: proto.Int32(9)}, - {Second: proto.Int32(21)}, - {Third: []int32{2000}}, - }, - }, - } - for _, test := range tests { - var buf bytes.Buffer - var want pb.ComplexExtension - - // Generate a serialized representation of a repeated extension - // by catenating bytes together. - for i, e := range test.ext { - // Merge to create the wanted proto. - proto.Merge(&want, e) - - // serialize the message - msg := new(pb.OtherMessage) - err := proto.SetExtension(msg, pb.E_Complex, e) - if err != nil { - t.Fatalf("[%s] Error setting extension %d: %v", test.name, i, err) - } - b, err := proto.Marshal(msg) - if err != nil { - t.Fatalf("[%s] Error marshaling message %d: %v", test.name, i, err) - } - buf.Write(b) - } - - // Unmarshal and read the merged proto. - msg2 := new(pb.OtherMessage) - err := proto.Unmarshal(buf.Bytes(), msg2) - if err != nil { - t.Fatalf("[%s] Error unmarshaling message: %v", test.name, err) - } - e, err := proto.GetExtension(msg2, pb.E_Complex) - if err != nil { - t.Fatalf("[%s] Error getting extension: %v", test.name, err) - } - ext := e.(*pb.ComplexExtension) - if ext == nil { - t.Fatalf("[%s] Invalid extension", test.name) - } - if !reflect.DeepEqual(*ext, want) { - t.Errorf("[%s] Wrong value for ComplexExtension: got: %s want: %s\n", test.name, ext, want) - } - } -} - -func TestClearAllExtensions(t *testing.T) { - // unregistered extension - desc := &proto.ExtensionDesc{ - ExtendedType: (*pb.MyMessage)(nil), - ExtensionType: (*bool)(nil), - Field: 101010100, - Name: "emptyextension", - Tag: "varint,0,opt", - } - m := &pb.MyMessage{} - if proto.HasExtension(m, desc) { - t.Errorf("proto.HasExtension(%s): got true, want false", proto.MarshalTextString(m)) - } - if err := proto.SetExtension(m, desc, proto.Bool(true)); err != nil { - t.Errorf("proto.SetExtension(m, desc, true): got error %q, want nil", err) - } - if !proto.HasExtension(m, desc) { - t.Errorf("proto.HasExtension(%s): got false, want true", proto.MarshalTextString(m)) - } - proto.ClearAllExtensions(m) - if proto.HasExtension(m, desc) { - t.Errorf("proto.HasExtension(%s): got true, want false", proto.MarshalTextString(m)) - } -} - -func TestMarshalRace(t *testing.T) { - // unregistered extension - desc := &proto.ExtensionDesc{ - ExtendedType: (*pb.MyMessage)(nil), - ExtensionType: (*bool)(nil), - Field: 101010100, - Name: "emptyextension", - Tag: "varint,0,opt", - } - - m := &pb.MyMessage{Count: proto.Int32(4)} - if err := proto.SetExtension(m, desc, proto.Bool(true)); err != nil { - t.Errorf("proto.SetExtension(m, desc, true): got error %q, want nil", err) - } - - var g errgroup.Group - for n := 3; n > 0; n-- { - g.Go(func() error { - _, err := proto.Marshal(m) - return err - }) - } - if err := g.Wait(); err != nil { - t.Fatal(err) - } -} diff --git a/vendor/github.com/golang/protobuf/proto/map_test.go b/vendor/github.com/golang/protobuf/proto/map_test.go deleted file mode 100644 index 313e87924..000000000 --- a/vendor/github.com/golang/protobuf/proto/map_test.go +++ /dev/null @@ -1,46 +0,0 @@ -package proto_test - -import ( - "fmt" - "testing" - - "github.com/golang/protobuf/proto" - ppb "github.com/golang/protobuf/proto/proto3_proto" -) - -func marshalled() []byte { - m := &ppb.IntMaps{} - for i := 0; i < 1000; i++ { - m.Maps = append(m.Maps, &ppb.IntMap{ - Rtt: map[int32]int32{1: 2}, - }) - } - b, err := proto.Marshal(m) - if err != nil { - panic(fmt.Sprintf("Can't marshal %+v: %v", m, err)) - } - return b -} - -func BenchmarkConcurrentMapUnmarshal(b *testing.B) { - in := marshalled() - b.RunParallel(func(pb *testing.PB) { - for pb.Next() { - var out ppb.IntMaps - if err := proto.Unmarshal(in, &out); err != nil { - b.Errorf("Can't unmarshal ppb.IntMaps: %v", err) - } - } - }) -} - -func BenchmarkSequentialMapUnmarshal(b *testing.B) { - in := marshalled() - b.ResetTimer() - for i := 0; i < b.N; i++ { - var out ppb.IntMaps - if err := proto.Unmarshal(in, &out); err != nil { - b.Errorf("Can't unmarshal ppb.IntMaps: %v", err) - } - } -} diff --git a/vendor/github.com/golang/protobuf/proto/message_set_test.go b/vendor/github.com/golang/protobuf/proto/message_set_test.go deleted file mode 100644 index 353a3ea76..000000000 --- a/vendor/github.com/golang/protobuf/proto/message_set_test.go +++ /dev/null @@ -1,66 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2014 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -import ( - "bytes" - "testing" -) - -func TestUnmarshalMessageSetWithDuplicate(t *testing.T) { - // Check that a repeated message set entry will be concatenated. - in := &messageSet{ - Item: []*_MessageSet_Item{ - {TypeId: Int32(12345), Message: []byte("hoo")}, - {TypeId: Int32(12345), Message: []byte("hah")}, - }, - } - b, err := Marshal(in) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - t.Logf("Marshaled bytes: %q", b) - - var extensions XXX_InternalExtensions - if err := UnmarshalMessageSet(b, &extensions); err != nil { - t.Fatalf("UnmarshalMessageSet: %v", err) - } - ext, ok := extensions.p.extensionMap[12345] - if !ok { - t.Fatalf("Didn't retrieve extension 12345; map is %v", extensions.p.extensionMap) - } - // Skip wire type/field number and length varints. - got := skipVarint(skipVarint(ext.enc)) - if want := []byte("hoohah"); !bytes.Equal(got, want) { - t.Errorf("Combined extension is %q, want %q", got, want) - } -} diff --git a/vendor/github.com/golang/protobuf/proto/proto3_test.go b/vendor/github.com/golang/protobuf/proto/proto3_test.go deleted file mode 100644 index 735837f2d..000000000 --- a/vendor/github.com/golang/protobuf/proto/proto3_test.go +++ /dev/null @@ -1,135 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2014 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto_test - -import ( - "testing" - - "github.com/golang/protobuf/proto" - pb "github.com/golang/protobuf/proto/proto3_proto" - tpb "github.com/golang/protobuf/proto/testdata" -) - -func TestProto3ZeroValues(t *testing.T) { - tests := []struct { - desc string - m proto.Message - }{ - {"zero message", &pb.Message{}}, - {"empty bytes field", &pb.Message{Data: []byte{}}}, - } - for _, test := range tests { - b, err := proto.Marshal(test.m) - if err != nil { - t.Errorf("%s: proto.Marshal: %v", test.desc, err) - continue - } - if len(b) > 0 { - t.Errorf("%s: Encoding is non-empty: %q", test.desc, b) - } - } -} - -func TestRoundTripProto3(t *testing.T) { - m := &pb.Message{ - Name: "David", // (2 | 1<<3): 0x0a 0x05 "David" - Hilarity: pb.Message_PUNS, // (0 | 2<<3): 0x10 0x01 - HeightInCm: 178, // (0 | 3<<3): 0x18 0xb2 0x01 - Data: []byte("roboto"), // (2 | 4<<3): 0x20 0x06 "roboto" - ResultCount: 47, // (0 | 7<<3): 0x38 0x2f - TrueScotsman: true, // (0 | 8<<3): 0x40 0x01 - Score: 8.1, // (5 | 9<<3): 0x4d <8.1> - - Key: []uint64{1, 0xdeadbeef}, - Nested: &pb.Nested{ - Bunny: "Monty", - }, - } - t.Logf(" m: %v", m) - - b, err := proto.Marshal(m) - if err != nil { - t.Fatalf("proto.Marshal: %v", err) - } - t.Logf(" b: %q", b) - - m2 := new(pb.Message) - if err := proto.Unmarshal(b, m2); err != nil { - t.Fatalf("proto.Unmarshal: %v", err) - } - t.Logf("m2: %v", m2) - - if !proto.Equal(m, m2) { - t.Errorf("proto.Equal returned false:\n m: %v\nm2: %v", m, m2) - } -} - -func TestGettersForBasicTypesExist(t *testing.T) { - var m pb.Message - if got := m.GetNested().GetBunny(); got != "" { - t.Errorf("m.GetNested().GetBunny() = %q, want empty string", got) - } - if got := m.GetNested().GetCute(); got { - t.Errorf("m.GetNested().GetCute() = %t, want false", got) - } -} - -func TestProto3SetDefaults(t *testing.T) { - in := &pb.Message{ - Terrain: map[string]*pb.Nested{ - "meadow": new(pb.Nested), - }, - Proto2Field: new(tpb.SubDefaults), - Proto2Value: map[string]*tpb.SubDefaults{ - "badlands": new(tpb.SubDefaults), - }, - } - - got := proto.Clone(in).(*pb.Message) - proto.SetDefaults(got) - - // There are no defaults in proto3. Everything should be the zero value, but - // we need to remember to set defaults for nested proto2 messages. - want := &pb.Message{ - Terrain: map[string]*pb.Nested{ - "meadow": new(pb.Nested), - }, - Proto2Field: &tpb.SubDefaults{N: proto.Int64(7)}, - Proto2Value: map[string]*tpb.SubDefaults{ - "badlands": &tpb.SubDefaults{N: proto.Int64(7)}, - }, - } - - if !proto.Equal(got, want) { - t.Errorf("with in = %v\nproto.SetDefaults(in) =>\ngot %v\nwant %v", in, got, want) - } -} diff --git a/vendor/github.com/golang/protobuf/proto/size2_test.go b/vendor/github.com/golang/protobuf/proto/size2_test.go deleted file mode 100644 index a2729c39a..000000000 --- a/vendor/github.com/golang/protobuf/proto/size2_test.go +++ /dev/null @@ -1,63 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2012 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -import ( - "testing" -) - -// This is a separate file and package from size_test.go because that one uses -// generated messages and thus may not be in package proto without having a circular -// dependency, whereas this file tests unexported details of size.go. - -func TestVarintSize(t *testing.T) { - // Check the edge cases carefully. - testCases := []struct { - n uint64 - size int - }{ - {0, 1}, - {1, 1}, - {127, 1}, - {128, 2}, - {16383, 2}, - {16384, 3}, - {1<<63 - 1, 9}, - {1 << 63, 10}, - } - for _, tc := range testCases { - size := sizeVarint(tc.n) - if size != tc.size { - t.Errorf("sizeVarint(%d) = %d, want %d", tc.n, size, tc.size) - } - } -} diff --git a/vendor/github.com/golang/protobuf/proto/size_test.go b/vendor/github.com/golang/protobuf/proto/size_test.go deleted file mode 100644 index af1034dc7..000000000 --- a/vendor/github.com/golang/protobuf/proto/size_test.go +++ /dev/null @@ -1,164 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2012 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto_test - -import ( - "log" - "strings" - "testing" - - . "github.com/golang/protobuf/proto" - proto3pb "github.com/golang/protobuf/proto/proto3_proto" - pb "github.com/golang/protobuf/proto/testdata" -) - -var messageWithExtension1 = &pb.MyMessage{Count: Int32(7)} - -// messageWithExtension2 is in equal_test.go. -var messageWithExtension3 = &pb.MyMessage{Count: Int32(8)} - -func init() { - if err := SetExtension(messageWithExtension1, pb.E_Ext_More, &pb.Ext{Data: String("Abbott")}); err != nil { - log.Panicf("SetExtension: %v", err) - } - if err := SetExtension(messageWithExtension3, pb.E_Ext_More, &pb.Ext{Data: String("Costello")}); err != nil { - log.Panicf("SetExtension: %v", err) - } - - // Force messageWithExtension3 to have the extension encoded. - Marshal(messageWithExtension3) - -} - -var SizeTests = []struct { - desc string - pb Message -}{ - {"empty", &pb.OtherMessage{}}, - // Basic types. - {"bool", &pb.Defaults{F_Bool: Bool(true)}}, - {"int32", &pb.Defaults{F_Int32: Int32(12)}}, - {"negative int32", &pb.Defaults{F_Int32: Int32(-1)}}, - {"small int64", &pb.Defaults{F_Int64: Int64(1)}}, - {"big int64", &pb.Defaults{F_Int64: Int64(1 << 20)}}, - {"negative int64", &pb.Defaults{F_Int64: Int64(-1)}}, - {"fixed32", &pb.Defaults{F_Fixed32: Uint32(71)}}, - {"fixed64", &pb.Defaults{F_Fixed64: Uint64(72)}}, - {"uint32", &pb.Defaults{F_Uint32: Uint32(123)}}, - {"uint64", &pb.Defaults{F_Uint64: Uint64(124)}}, - {"float", &pb.Defaults{F_Float: Float32(12.6)}}, - {"double", &pb.Defaults{F_Double: Float64(13.9)}}, - {"string", &pb.Defaults{F_String: String("niles")}}, - {"bytes", &pb.Defaults{F_Bytes: []byte("wowsa")}}, - {"bytes, empty", &pb.Defaults{F_Bytes: []byte{}}}, - {"sint32", &pb.Defaults{F_Sint32: Int32(65)}}, - {"sint64", &pb.Defaults{F_Sint64: Int64(67)}}, - {"enum", &pb.Defaults{F_Enum: pb.Defaults_BLUE.Enum()}}, - // Repeated. - {"empty repeated bool", &pb.MoreRepeated{Bools: []bool{}}}, - {"repeated bool", &pb.MoreRepeated{Bools: []bool{false, true, true, false}}}, - {"packed repeated bool", &pb.MoreRepeated{BoolsPacked: []bool{false, true, true, false, true, true, true}}}, - {"repeated int32", &pb.MoreRepeated{Ints: []int32{1, 12203, 1729, -1}}}, - {"repeated int32 packed", &pb.MoreRepeated{IntsPacked: []int32{1, 12203, 1729}}}, - {"repeated int64 packed", &pb.MoreRepeated{Int64SPacked: []int64{ - // Need enough large numbers to verify that the header is counting the number of bytes - // for the field, not the number of elements. - 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, - 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, - }}}, - {"repeated string", &pb.MoreRepeated{Strings: []string{"r", "ken", "gri"}}}, - {"repeated fixed", &pb.MoreRepeated{Fixeds: []uint32{1, 2, 3, 4}}}, - // Nested. - {"nested", &pb.OldMessage{Nested: &pb.OldMessage_Nested{Name: String("whatever")}}}, - {"group", &pb.GroupOld{G: &pb.GroupOld_G{X: Int32(12345)}}}, - // Other things. - {"unrecognized", &pb.MoreRepeated{XXX_unrecognized: []byte{13<<3 | 0, 4}}}, - {"extension (unencoded)", messageWithExtension1}, - {"extension (encoded)", messageWithExtension3}, - // proto3 message - {"proto3 empty", &proto3pb.Message{}}, - {"proto3 bool", &proto3pb.Message{TrueScotsman: true}}, - {"proto3 int64", &proto3pb.Message{ResultCount: 1}}, - {"proto3 uint32", &proto3pb.Message{HeightInCm: 123}}, - {"proto3 float", &proto3pb.Message{Score: 12.6}}, - {"proto3 string", &proto3pb.Message{Name: "Snezana"}}, - {"proto3 bytes", &proto3pb.Message{Data: []byte("wowsa")}}, - {"proto3 bytes, empty", &proto3pb.Message{Data: []byte{}}}, - {"proto3 enum", &proto3pb.Message{Hilarity: proto3pb.Message_PUNS}}, - {"proto3 map field with empty bytes", &proto3pb.MessageWithMap{ByteMapping: map[bool][]byte{false: []byte{}}}}, - - {"map field", &pb.MessageWithMap{NameMapping: map[int32]string{1: "Rob", 7: "Andrew"}}}, - {"map field with message", &pb.MessageWithMap{MsgMapping: map[int64]*pb.FloatingPoint{0x7001: &pb.FloatingPoint{F: Float64(2.0)}}}}, - {"map field with bytes", &pb.MessageWithMap{ByteMapping: map[bool][]byte{true: []byte("this time for sure")}}}, - {"map field with empty bytes", &pb.MessageWithMap{ByteMapping: map[bool][]byte{true: []byte{}}}}, - - {"map field with big entry", &pb.MessageWithMap{NameMapping: map[int32]string{8: strings.Repeat("x", 125)}}}, - {"map field with big key and val", &pb.MessageWithMap{StrToStr: map[string]string{strings.Repeat("x", 70): strings.Repeat("y", 70)}}}, - {"map field with big numeric key", &pb.MessageWithMap{NameMapping: map[int32]string{0xf00d: "om nom nom"}}}, - - {"oneof not set", &pb.Oneof{}}, - {"oneof bool", &pb.Oneof{Union: &pb.Oneof_F_Bool{true}}}, - {"oneof zero int32", &pb.Oneof{Union: &pb.Oneof_F_Int32{0}}}, - {"oneof big int32", &pb.Oneof{Union: &pb.Oneof_F_Int32{1 << 20}}}, - {"oneof int64", &pb.Oneof{Union: &pb.Oneof_F_Int64{42}}}, - {"oneof fixed32", &pb.Oneof{Union: &pb.Oneof_F_Fixed32{43}}}, - {"oneof fixed64", &pb.Oneof{Union: &pb.Oneof_F_Fixed64{44}}}, - {"oneof uint32", &pb.Oneof{Union: &pb.Oneof_F_Uint32{45}}}, - {"oneof uint64", &pb.Oneof{Union: &pb.Oneof_F_Uint64{46}}}, - {"oneof float", &pb.Oneof{Union: &pb.Oneof_F_Float{47.1}}}, - {"oneof double", &pb.Oneof{Union: &pb.Oneof_F_Double{48.9}}}, - {"oneof string", &pb.Oneof{Union: &pb.Oneof_F_String{"Rhythmic Fman"}}}, - {"oneof bytes", &pb.Oneof{Union: &pb.Oneof_F_Bytes{[]byte("let go")}}}, - {"oneof sint32", &pb.Oneof{Union: &pb.Oneof_F_Sint32{50}}}, - {"oneof sint64", &pb.Oneof{Union: &pb.Oneof_F_Sint64{51}}}, - {"oneof enum", &pb.Oneof{Union: &pb.Oneof_F_Enum{pb.MyMessage_BLUE}}}, - {"message for oneof", &pb.GoTestField{Label: String("k"), Type: String("v")}}, - {"oneof message", &pb.Oneof{Union: &pb.Oneof_F_Message{&pb.GoTestField{Label: String("k"), Type: String("v")}}}}, - {"oneof group", &pb.Oneof{Union: &pb.Oneof_FGroup{&pb.Oneof_F_Group{X: Int32(52)}}}}, - {"oneof largest tag", &pb.Oneof{Union: &pb.Oneof_F_Largest_Tag{1}}}, - {"multiple oneofs", &pb.Oneof{Union: &pb.Oneof_F_Int32{1}, Tormato: &pb.Oneof_Value{2}}}, -} - -func TestSize(t *testing.T) { - for _, tc := range SizeTests { - size := Size(tc.pb) - b, err := Marshal(tc.pb) - if err != nil { - t.Errorf("%v: Marshal failed: %v", tc.desc, err) - continue - } - if size != len(b) { - t.Errorf("%v: Size(%v) = %d, want %d", tc.desc, tc.pb, size, len(b)) - t.Logf("%v: bytes: %#v", tc.desc, b) - } - } -} diff --git a/vendor/github.com/golang/protobuf/proto/text_parser_test.go b/vendor/github.com/golang/protobuf/proto/text_parser_test.go deleted file mode 100644 index 8f7cb4d27..000000000 --- a/vendor/github.com/golang/protobuf/proto/text_parser_test.go +++ /dev/null @@ -1,673 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto_test - -import ( - "math" - "reflect" - "testing" - - . "github.com/golang/protobuf/proto" - proto3pb "github.com/golang/protobuf/proto/proto3_proto" - . "github.com/golang/protobuf/proto/testdata" -) - -type UnmarshalTextTest struct { - in string - err string // if "", no error expected - out *MyMessage -} - -func buildExtStructTest(text string) UnmarshalTextTest { - msg := &MyMessage{ - Count: Int32(42), - } - SetExtension(msg, E_Ext_More, &Ext{ - Data: String("Hello, world!"), - }) - return UnmarshalTextTest{in: text, out: msg} -} - -func buildExtDataTest(text string) UnmarshalTextTest { - msg := &MyMessage{ - Count: Int32(42), - } - SetExtension(msg, E_Ext_Text, String("Hello, world!")) - SetExtension(msg, E_Ext_Number, Int32(1729)) - return UnmarshalTextTest{in: text, out: msg} -} - -func buildExtRepStringTest(text string) UnmarshalTextTest { - msg := &MyMessage{ - Count: Int32(42), - } - if err := SetExtension(msg, E_Greeting, []string{"bula", "hola"}); err != nil { - panic(err) - } - return UnmarshalTextTest{in: text, out: msg} -} - -var unMarshalTextTests = []UnmarshalTextTest{ - // Basic - { - in: " count:42\n name:\"Dave\" ", - out: &MyMessage{ - Count: Int32(42), - Name: String("Dave"), - }, - }, - - // Empty quoted string - { - in: `count:42 name:""`, - out: &MyMessage{ - Count: Int32(42), - Name: String(""), - }, - }, - - // Quoted string concatenation with double quotes - { - in: `count:42 name: "My name is "` + "\n" + `"elsewhere"`, - out: &MyMessage{ - Count: Int32(42), - Name: String("My name is elsewhere"), - }, - }, - - // Quoted string concatenation with single quotes - { - in: "count:42 name: 'My name is '\n'elsewhere'", - out: &MyMessage{ - Count: Int32(42), - Name: String("My name is elsewhere"), - }, - }, - - // Quoted string concatenations with mixed quotes - { - in: "count:42 name: 'My name is '\n\"elsewhere\"", - out: &MyMessage{ - Count: Int32(42), - Name: String("My name is elsewhere"), - }, - }, - { - in: "count:42 name: \"My name is \"\n'elsewhere'", - out: &MyMessage{ - Count: Int32(42), - Name: String("My name is elsewhere"), - }, - }, - - // Quoted string with escaped apostrophe - { - in: `count:42 name: "HOLIDAY - New Year\'s Day"`, - out: &MyMessage{ - Count: Int32(42), - Name: String("HOLIDAY - New Year's Day"), - }, - }, - - // Quoted string with single quote - { - in: `count:42 name: 'Roger "The Ramster" Ramjet'`, - out: &MyMessage{ - Count: Int32(42), - Name: String(`Roger "The Ramster" Ramjet`), - }, - }, - - // Quoted string with all the accepted special characters from the C++ test - { - in: `count:42 name: ` + "\"\\\"A string with \\' characters \\n and \\r newlines and \\t tabs and \\001 slashes \\\\ and multiple spaces\"", - out: &MyMessage{ - Count: Int32(42), - Name: String("\"A string with ' characters \n and \r newlines and \t tabs and \001 slashes \\ and multiple spaces"), - }, - }, - - // Quoted string with quoted backslash - { - in: `count:42 name: "\\'xyz"`, - out: &MyMessage{ - Count: Int32(42), - Name: String(`\'xyz`), - }, - }, - - // Quoted string with UTF-8 bytes. - { - in: "count:42 name: '\303\277\302\201\xAB'", - out: &MyMessage{ - Count: Int32(42), - Name: String("\303\277\302\201\xAB"), - }, - }, - - // Bad quoted string - { - in: `inner: < host: "\0" >` + "\n", - err: `line 1.15: invalid quoted string "\0": \0 requires 2 following digits`, - }, - - // Number too large for int64 - { - in: "count: 1 others { key: 123456789012345678901 }", - err: "line 1.23: invalid int64: 123456789012345678901", - }, - - // Number too large for int32 - { - in: "count: 1234567890123", - err: "line 1.7: invalid int32: 1234567890123", - }, - - // Number in hexadecimal - { - in: "count: 0x2beef", - out: &MyMessage{ - Count: Int32(0x2beef), - }, - }, - - // Number in octal - { - in: "count: 024601", - out: &MyMessage{ - Count: Int32(024601), - }, - }, - - // Floating point number with "f" suffix - { - in: "count: 4 others:< weight: 17.0f >", - out: &MyMessage{ - Count: Int32(4), - Others: []*OtherMessage{ - { - Weight: Float32(17), - }, - }, - }, - }, - - // Floating point positive infinity - { - in: "count: 4 bigfloat: inf", - out: &MyMessage{ - Count: Int32(4), - Bigfloat: Float64(math.Inf(1)), - }, - }, - - // Floating point negative infinity - { - in: "count: 4 bigfloat: -inf", - out: &MyMessage{ - Count: Int32(4), - Bigfloat: Float64(math.Inf(-1)), - }, - }, - - // Number too large for float32 - { - in: "others:< weight: 12345678901234567890123456789012345678901234567890 >", - err: "line 1.17: invalid float32: 12345678901234567890123456789012345678901234567890", - }, - - // Number posing as a quoted string - { - in: `inner: < host: 12 >` + "\n", - err: `line 1.15: invalid string: 12`, - }, - - // Quoted string posing as int32 - { - in: `count: "12"`, - err: `line 1.7: invalid int32: "12"`, - }, - - // Quoted string posing a float32 - { - in: `others:< weight: "17.4" >`, - err: `line 1.17: invalid float32: "17.4"`, - }, - - // Enum - { - in: `count:42 bikeshed: BLUE`, - out: &MyMessage{ - Count: Int32(42), - Bikeshed: MyMessage_BLUE.Enum(), - }, - }, - - // Repeated field - { - in: `count:42 pet: "horsey" pet:"bunny"`, - out: &MyMessage{ - Count: Int32(42), - Pet: []string{"horsey", "bunny"}, - }, - }, - - // Repeated field with list notation - { - in: `count:42 pet: ["horsey", "bunny"]`, - out: &MyMessage{ - Count: Int32(42), - Pet: []string{"horsey", "bunny"}, - }, - }, - - // Repeated message with/without colon and <>/{} - { - in: `count:42 others:{} others{} others:<> others:{}`, - out: &MyMessage{ - Count: Int32(42), - Others: []*OtherMessage{ - {}, - {}, - {}, - {}, - }, - }, - }, - - // Missing colon for inner message - { - in: `count:42 inner < host: "cauchy.syd" >`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("cauchy.syd"), - }, - }, - }, - - // Missing colon for string field - { - in: `name "Dave"`, - err: `line 1.5: expected ':', found "\"Dave\""`, - }, - - // Missing colon for int32 field - { - in: `count 42`, - err: `line 1.6: expected ':', found "42"`, - }, - - // Missing required field - { - in: `name: "Pawel"`, - err: `proto: required field "testdata.MyMessage.count" not set`, - out: &MyMessage{ - Name: String("Pawel"), - }, - }, - - // Missing required field in a required submessage - { - in: `count: 42 we_must_go_deeper < leo_finally_won_an_oscar <> >`, - err: `proto: required field "testdata.InnerMessage.host" not set`, - out: &MyMessage{ - Count: Int32(42), - WeMustGoDeeper: &RequiredInnerMessage{LeoFinallyWonAnOscar: &InnerMessage{}}, - }, - }, - - // Repeated non-repeated field - { - in: `name: "Rob" name: "Russ"`, - err: `line 1.12: non-repeated field "name" was repeated`, - }, - - // Group - { - in: `count: 17 SomeGroup { group_field: 12 }`, - out: &MyMessage{ - Count: Int32(17), - Somegroup: &MyMessage_SomeGroup{ - GroupField: Int32(12), - }, - }, - }, - - // Semicolon between fields - { - in: `count:3;name:"Calvin"`, - out: &MyMessage{ - Count: Int32(3), - Name: String("Calvin"), - }, - }, - // Comma between fields - { - in: `count:4,name:"Ezekiel"`, - out: &MyMessage{ - Count: Int32(4), - Name: String("Ezekiel"), - }, - }, - - // Boolean false - { - in: `count:42 inner { host: "example.com" connected: false }`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("example.com"), - Connected: Bool(false), - }, - }, - }, - // Boolean true - { - in: `count:42 inner { host: "example.com" connected: true }`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("example.com"), - Connected: Bool(true), - }, - }, - }, - // Boolean 0 - { - in: `count:42 inner { host: "example.com" connected: 0 }`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("example.com"), - Connected: Bool(false), - }, - }, - }, - // Boolean 1 - { - in: `count:42 inner { host: "example.com" connected: 1 }`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("example.com"), - Connected: Bool(true), - }, - }, - }, - // Boolean f - { - in: `count:42 inner { host: "example.com" connected: f }`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("example.com"), - Connected: Bool(false), - }, - }, - }, - // Boolean t - { - in: `count:42 inner { host: "example.com" connected: t }`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("example.com"), - Connected: Bool(true), - }, - }, - }, - // Boolean False - { - in: `count:42 inner { host: "example.com" connected: False }`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("example.com"), - Connected: Bool(false), - }, - }, - }, - // Boolean True - { - in: `count:42 inner { host: "example.com" connected: True }`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("example.com"), - Connected: Bool(true), - }, - }, - }, - - // Extension - buildExtStructTest(`count: 42 [testdata.Ext.more]:`), - buildExtStructTest(`count: 42 [testdata.Ext.more] {data:"Hello, world!"}`), - buildExtDataTest(`count: 42 [testdata.Ext.text]:"Hello, world!" [testdata.Ext.number]:1729`), - buildExtRepStringTest(`count: 42 [testdata.greeting]:"bula" [testdata.greeting]:"hola"`), - - // Big all-in-one - { - in: "count:42 # Meaning\n" + - `name:"Dave" ` + - `quote:"\"I didn't want to go.\"" ` + - `pet:"bunny" ` + - `pet:"kitty" ` + - `pet:"horsey" ` + - `inner:<` + - ` host:"footrest.syd" ` + - ` port:7001 ` + - ` connected:true ` + - `> ` + - `others:<` + - ` key:3735928559 ` + - ` value:"\x01A\a\f" ` + - `> ` + - `others:<` + - " weight:58.9 # Atomic weight of Co\n" + - ` inner:<` + - ` host:"lesha.mtv" ` + - ` port:8002 ` + - ` >` + - `>`, - out: &MyMessage{ - Count: Int32(42), - Name: String("Dave"), - Quote: String(`"I didn't want to go."`), - Pet: []string{"bunny", "kitty", "horsey"}, - Inner: &InnerMessage{ - Host: String("footrest.syd"), - Port: Int32(7001), - Connected: Bool(true), - }, - Others: []*OtherMessage{ - { - Key: Int64(3735928559), - Value: []byte{0x1, 'A', '\a', '\f'}, - }, - { - Weight: Float32(58.9), - Inner: &InnerMessage{ - Host: String("lesha.mtv"), - Port: Int32(8002), - }, - }, - }, - }, - }, -} - -func TestUnmarshalText(t *testing.T) { - for i, test := range unMarshalTextTests { - pb := new(MyMessage) - err := UnmarshalText(test.in, pb) - if test.err == "" { - // We don't expect failure. - if err != nil { - t.Errorf("Test %d: Unexpected error: %v", i, err) - } else if !reflect.DeepEqual(pb, test.out) { - t.Errorf("Test %d: Incorrect populated \nHave: %v\nWant: %v", - i, pb, test.out) - } - } else { - // We do expect failure. - if err == nil { - t.Errorf("Test %d: Didn't get expected error: %v", i, test.err) - } else if err.Error() != test.err { - t.Errorf("Test %d: Incorrect error.\nHave: %v\nWant: %v", - i, err.Error(), test.err) - } else if _, ok := err.(*RequiredNotSetError); ok && test.out != nil && !reflect.DeepEqual(pb, test.out) { - t.Errorf("Test %d: Incorrect populated \nHave: %v\nWant: %v", - i, pb, test.out) - } - } - } -} - -func TestUnmarshalTextCustomMessage(t *testing.T) { - msg := &textMessage{} - if err := UnmarshalText("custom", msg); err != nil { - t.Errorf("Unexpected error from custom unmarshal: %v", err) - } - if UnmarshalText("not custom", msg) == nil { - t.Errorf("Didn't get expected error from custom unmarshal") - } -} - -// Regression test; this caused a panic. -func TestRepeatedEnum(t *testing.T) { - pb := new(RepeatedEnum) - if err := UnmarshalText("color: RED", pb); err != nil { - t.Fatal(err) - } - exp := &RepeatedEnum{ - Color: []RepeatedEnum_Color{RepeatedEnum_RED}, - } - if !Equal(pb, exp) { - t.Errorf("Incorrect populated \nHave: %v\nWant: %v", pb, exp) - } -} - -func TestProto3TextParsing(t *testing.T) { - m := new(proto3pb.Message) - const in = `name: "Wallace" true_scotsman: true` - want := &proto3pb.Message{ - Name: "Wallace", - TrueScotsman: true, - } - if err := UnmarshalText(in, m); err != nil { - t.Fatal(err) - } - if !Equal(m, want) { - t.Errorf("\n got %v\nwant %v", m, want) - } -} - -func TestMapParsing(t *testing.T) { - m := new(MessageWithMap) - const in = `name_mapping: name_mapping:` + - `msg_mapping:,>` + // separating commas are okay - `msg_mapping>` + // no colon after "value" - `msg_mapping:>` + // omitted key - `msg_mapping:` + // omitted value - `byte_mapping:` + - `byte_mapping:<>` // omitted key and value - want := &MessageWithMap{ - NameMapping: map[int32]string{ - 1: "Beatles", - 1234: "Feist", - }, - MsgMapping: map[int64]*FloatingPoint{ - -4: {F: Float64(2.0)}, - -2: {F: Float64(4.0)}, - 0: {F: Float64(5.0)}, - 1: nil, - }, - ByteMapping: map[bool][]byte{ - false: nil, - true: []byte("so be it"), - }, - } - if err := UnmarshalText(in, m); err != nil { - t.Fatal(err) - } - if !Equal(m, want) { - t.Errorf("\n got %v\nwant %v", m, want) - } -} - -func TestOneofParsing(t *testing.T) { - const in = `name:"Shrek"` - m := new(Communique) - want := &Communique{Union: &Communique_Name{"Shrek"}} - if err := UnmarshalText(in, m); err != nil { - t.Fatal(err) - } - if !Equal(m, want) { - t.Errorf("\n got %v\nwant %v", m, want) - } - - const inOverwrite = `name:"Shrek" number:42` - m = new(Communique) - testErr := "line 1.13: field 'number' would overwrite already parsed oneof 'Union'" - if err := UnmarshalText(inOverwrite, m); err == nil { - t.Errorf("TestOneofParsing: Didn't get expected error: %v", testErr) - } else if err.Error() != testErr { - t.Errorf("TestOneofParsing: Incorrect error.\nHave: %v\nWant: %v", - err.Error(), testErr) - } - -} - -var benchInput string - -func init() { - benchInput = "count: 4\n" - for i := 0; i < 1000; i++ { - benchInput += "pet: \"fido\"\n" - } - - // Check it is valid input. - pb := new(MyMessage) - err := UnmarshalText(benchInput, pb) - if err != nil { - panic("Bad benchmark input: " + err.Error()) - } -} - -func BenchmarkUnmarshalText(b *testing.B) { - pb := new(MyMessage) - for i := 0; i < b.N; i++ { - UnmarshalText(benchInput, pb) - } - b.SetBytes(int64(len(benchInput))) -} diff --git a/vendor/github.com/golang/protobuf/proto/text_test.go b/vendor/github.com/golang/protobuf/proto/text_test.go deleted file mode 100644 index 3eabacac8..000000000 --- a/vendor/github.com/golang/protobuf/proto/text_test.go +++ /dev/null @@ -1,474 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto_test - -import ( - "bytes" - "errors" - "io/ioutil" - "math" - "strings" - "testing" - - "github.com/golang/protobuf/proto" - - proto3pb "github.com/golang/protobuf/proto/proto3_proto" - pb "github.com/golang/protobuf/proto/testdata" -) - -// textMessage implements the methods that allow it to marshal and unmarshal -// itself as text. -type textMessage struct { -} - -func (*textMessage) MarshalText() ([]byte, error) { - return []byte("custom"), nil -} - -func (*textMessage) UnmarshalText(bytes []byte) error { - if string(bytes) != "custom" { - return errors.New("expected 'custom'") - } - return nil -} - -func (*textMessage) Reset() {} -func (*textMessage) String() string { return "" } -func (*textMessage) ProtoMessage() {} - -func newTestMessage() *pb.MyMessage { - msg := &pb.MyMessage{ - Count: proto.Int32(42), - Name: proto.String("Dave"), - Quote: proto.String(`"I didn't want to go."`), - Pet: []string{"bunny", "kitty", "horsey"}, - Inner: &pb.InnerMessage{ - Host: proto.String("footrest.syd"), - Port: proto.Int32(7001), - Connected: proto.Bool(true), - }, - Others: []*pb.OtherMessage{ - { - Key: proto.Int64(0xdeadbeef), - Value: []byte{1, 65, 7, 12}, - }, - { - Weight: proto.Float32(6.022), - Inner: &pb.InnerMessage{ - Host: proto.String("lesha.mtv"), - Port: proto.Int32(8002), - }, - }, - }, - Bikeshed: pb.MyMessage_BLUE.Enum(), - Somegroup: &pb.MyMessage_SomeGroup{ - GroupField: proto.Int32(8), - }, - // One normally wouldn't do this. - // This is an undeclared tag 13, as a varint (wire type 0) with value 4. - XXX_unrecognized: []byte{13<<3 | 0, 4}, - } - ext := &pb.Ext{ - Data: proto.String("Big gobs for big rats"), - } - if err := proto.SetExtension(msg, pb.E_Ext_More, ext); err != nil { - panic(err) - } - greetings := []string{"adg", "easy", "cow"} - if err := proto.SetExtension(msg, pb.E_Greeting, greetings); err != nil { - panic(err) - } - - // Add an unknown extension. We marshal a pb.Ext, and fake the ID. - b, err := proto.Marshal(&pb.Ext{Data: proto.String("3G skiing")}) - if err != nil { - panic(err) - } - b = append(proto.EncodeVarint(201<<3|proto.WireBytes), b...) - proto.SetRawExtension(msg, 201, b) - - // Extensions can be plain fields, too, so let's test that. - b = append(proto.EncodeVarint(202<<3|proto.WireVarint), 19) - proto.SetRawExtension(msg, 202, b) - - return msg -} - -const text = `count: 42 -name: "Dave" -quote: "\"I didn't want to go.\"" -pet: "bunny" -pet: "kitty" -pet: "horsey" -inner: < - host: "footrest.syd" - port: 7001 - connected: true -> -others: < - key: 3735928559 - value: "\001A\007\014" -> -others: < - weight: 6.022 - inner: < - host: "lesha.mtv" - port: 8002 - > -> -bikeshed: BLUE -SomeGroup { - group_field: 8 -} -/* 2 unknown bytes */ -13: 4 -[testdata.Ext.more]: < - data: "Big gobs for big rats" -> -[testdata.greeting]: "adg" -[testdata.greeting]: "easy" -[testdata.greeting]: "cow" -/* 13 unknown bytes */ -201: "\t3G skiing" -/* 3 unknown bytes */ -202: 19 -` - -func TestMarshalText(t *testing.T) { - buf := new(bytes.Buffer) - if err := proto.MarshalText(buf, newTestMessage()); err != nil { - t.Fatalf("proto.MarshalText: %v", err) - } - s := buf.String() - if s != text { - t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v===\n", s, text) - } -} - -func TestMarshalTextCustomMessage(t *testing.T) { - buf := new(bytes.Buffer) - if err := proto.MarshalText(buf, &textMessage{}); err != nil { - t.Fatalf("proto.MarshalText: %v", err) - } - s := buf.String() - if s != "custom" { - t.Errorf("Got %q, expected %q", s, "custom") - } -} -func TestMarshalTextNil(t *testing.T) { - want := "" - tests := []proto.Message{nil, (*pb.MyMessage)(nil)} - for i, test := range tests { - buf := new(bytes.Buffer) - if err := proto.MarshalText(buf, test); err != nil { - t.Fatal(err) - } - if got := buf.String(); got != want { - t.Errorf("%d: got %q want %q", i, got, want) - } - } -} - -func TestMarshalTextUnknownEnum(t *testing.T) { - // The Color enum only specifies values 0-2. - m := &pb.MyMessage{Bikeshed: pb.MyMessage_Color(3).Enum()} - got := m.String() - const want = `bikeshed:3 ` - if got != want { - t.Errorf("\n got %q\nwant %q", got, want) - } -} - -func TestTextOneof(t *testing.T) { - tests := []struct { - m proto.Message - want string - }{ - // zero message - {&pb.Communique{}, ``}, - // scalar field - {&pb.Communique{Union: &pb.Communique_Number{4}}, `number:4`}, - // message field - {&pb.Communique{Union: &pb.Communique_Msg{ - &pb.Strings{StringField: proto.String("why hello!")}, - }}, `msg:`}, - // bad oneof (should not panic) - {&pb.Communique{Union: &pb.Communique_Msg{nil}}, `msg:/* nil */`}, - } - for _, test := range tests { - got := strings.TrimSpace(test.m.String()) - if got != test.want { - t.Errorf("\n got %s\nwant %s", got, test.want) - } - } -} - -func BenchmarkMarshalTextBuffered(b *testing.B) { - buf := new(bytes.Buffer) - m := newTestMessage() - for i := 0; i < b.N; i++ { - buf.Reset() - proto.MarshalText(buf, m) - } -} - -func BenchmarkMarshalTextUnbuffered(b *testing.B) { - w := ioutil.Discard - m := newTestMessage() - for i := 0; i < b.N; i++ { - proto.MarshalText(w, m) - } -} - -func compact(src string) string { - // s/[ \n]+/ /g; s/ $//; - dst := make([]byte, len(src)) - space, comment := false, false - j := 0 - for i := 0; i < len(src); i++ { - if strings.HasPrefix(src[i:], "/*") { - comment = true - i++ - continue - } - if comment && strings.HasPrefix(src[i:], "*/") { - comment = false - i++ - continue - } - if comment { - continue - } - c := src[i] - if c == ' ' || c == '\n' { - space = true - continue - } - if j > 0 && (dst[j-1] == ':' || dst[j-1] == '<' || dst[j-1] == '{') { - space = false - } - if c == '{' { - space = false - } - if space { - dst[j] = ' ' - j++ - space = false - } - dst[j] = c - j++ - } - if space { - dst[j] = ' ' - j++ - } - return string(dst[0:j]) -} - -var compactText = compact(text) - -func TestCompactText(t *testing.T) { - s := proto.CompactTextString(newTestMessage()) - if s != compactText { - t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v\n===\n", s, compactText) - } -} - -func TestStringEscaping(t *testing.T) { - testCases := []struct { - in *pb.Strings - out string - }{ - { - // Test data from C++ test (TextFormatTest.StringEscape). - // Single divergence: we don't escape apostrophes. - &pb.Strings{StringField: proto.String("\"A string with ' characters \n and \r newlines and \t tabs and \001 slashes \\ and multiple spaces")}, - "string_field: \"\\\"A string with ' characters \\n and \\r newlines and \\t tabs and \\001 slashes \\\\ and multiple spaces\"\n", - }, - { - // Test data from the same C++ test. - &pb.Strings{StringField: proto.String("\350\260\267\346\255\214")}, - "string_field: \"\\350\\260\\267\\346\\255\\214\"\n", - }, - { - // Some UTF-8. - &pb.Strings{StringField: proto.String("\x00\x01\xff\x81")}, - `string_field: "\000\001\377\201"` + "\n", - }, - } - - for i, tc := range testCases { - var buf bytes.Buffer - if err := proto.MarshalText(&buf, tc.in); err != nil { - t.Errorf("proto.MarsalText: %v", err) - continue - } - s := buf.String() - if s != tc.out { - t.Errorf("#%d: Got:\n%s\nExpected:\n%s\n", i, s, tc.out) - continue - } - - // Check round-trip. - pb := new(pb.Strings) - if err := proto.UnmarshalText(s, pb); err != nil { - t.Errorf("#%d: UnmarshalText: %v", i, err) - continue - } - if !proto.Equal(pb, tc.in) { - t.Errorf("#%d: Round-trip failed:\nstart: %v\n end: %v", i, tc.in, pb) - } - } -} - -// A limitedWriter accepts some output before it fails. -// This is a proxy for something like a nearly-full or imminently-failing disk, -// or a network connection that is about to die. -type limitedWriter struct { - b bytes.Buffer - limit int -} - -var outOfSpace = errors.New("proto: insufficient space") - -func (w *limitedWriter) Write(p []byte) (n int, err error) { - var avail = w.limit - w.b.Len() - if avail <= 0 { - return 0, outOfSpace - } - if len(p) <= avail { - return w.b.Write(p) - } - n, _ = w.b.Write(p[:avail]) - return n, outOfSpace -} - -func TestMarshalTextFailing(t *testing.T) { - // Try lots of different sizes to exercise more error code-paths. - for lim := 0; lim < len(text); lim++ { - buf := new(limitedWriter) - buf.limit = lim - err := proto.MarshalText(buf, newTestMessage()) - // We expect a certain error, but also some partial results in the buffer. - if err != outOfSpace { - t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v===\n", err, outOfSpace) - } - s := buf.b.String() - x := text[:buf.limit] - if s != x { - t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v===\n", s, x) - } - } -} - -func TestFloats(t *testing.T) { - tests := []struct { - f float64 - want string - }{ - {0, "0"}, - {4.7, "4.7"}, - {math.Inf(1), "inf"}, - {math.Inf(-1), "-inf"}, - {math.NaN(), "nan"}, - } - for _, test := range tests { - msg := &pb.FloatingPoint{F: &test.f} - got := strings.TrimSpace(msg.String()) - want := `f:` + test.want - if got != want { - t.Errorf("f=%f: got %q, want %q", test.f, got, want) - } - } -} - -func TestRepeatedNilText(t *testing.T) { - m := &pb.MessageList{ - Message: []*pb.MessageList_Message{ - nil, - &pb.MessageList_Message{ - Name: proto.String("Horse"), - }, - nil, - }, - } - want := `Message -Message { - name: "Horse" -} -Message -` - if s := proto.MarshalTextString(m); s != want { - t.Errorf(" got: %s\nwant: %s", s, want) - } -} - -func TestProto3Text(t *testing.T) { - tests := []struct { - m proto.Message - want string - }{ - // zero message - {&proto3pb.Message{}, ``}, - // zero message except for an empty byte slice - {&proto3pb.Message{Data: []byte{}}, ``}, - // trivial case - {&proto3pb.Message{Name: "Rob", HeightInCm: 175}, `name:"Rob" height_in_cm:175`}, - // empty map - {&pb.MessageWithMap{}, ``}, - // non-empty map; map format is the same as a repeated struct, - // and they are sorted by key (numerically for numeric keys). - { - &pb.MessageWithMap{NameMapping: map[int32]string{ - -1: "Negatory", - 7: "Lucky", - 1234: "Feist", - 6345789: "Otis", - }}, - `name_mapping: ` + - `name_mapping: ` + - `name_mapping: ` + - `name_mapping:`, - }, - // map with nil value; not well-defined, but we shouldn't crash - { - &pb.MessageWithMap{MsgMapping: map[int64]*pb.FloatingPoint{7: nil}}, - `msg_mapping:`, - }, - } - for _, test := range tests { - got := strings.TrimSpace(test.m.String()) - if got != test.want { - t.Errorf("\n got %s\nwant %s", got, test.want) - } - } -} diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/Makefile b/vendor/github.com/golang/protobuf/protoc-gen-go/Makefile deleted file mode 100644 index a42cc3717..000000000 --- a/vendor/github.com/golang/protobuf/protoc-gen-go/Makefile +++ /dev/null @@ -1,33 +0,0 @@ -# Go support for Protocol Buffers - Google's data interchange format -# -# Copyright 2010 The Go Authors. All rights reserved. -# https://github.com/golang/protobuf -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following disclaimer -# in the documentation and/or other materials provided with the -# distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived from -# this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -test: - cd testdata && make test diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/descriptor/Makefile b/vendor/github.com/golang/protobuf/protoc-gen-go/descriptor/Makefile deleted file mode 100644 index f706871a6..000000000 --- a/vendor/github.com/golang/protobuf/protoc-gen-go/descriptor/Makefile +++ /dev/null @@ -1,37 +0,0 @@ -# Go support for Protocol Buffers - Google's data interchange format -# -# Copyright 2010 The Go Authors. All rights reserved. -# https://github.com/golang/protobuf -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following disclaimer -# in the documentation and/or other materials provided with the -# distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived from -# this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -# Not stored here, but descriptor.proto is in https://github.com/google/protobuf/ -# at src/google/protobuf/descriptor.proto -regenerate: - @echo WARNING! THIS RULE IS PROBABLY NOT RIGHT FOR YOUR INSTALLATION - cp $(HOME)/src/protobuf/include/google/protobuf/descriptor.proto . - protoc --go_out=../../../../.. -I$(HOME)/src/protobuf/include $(HOME)/src/protobuf/include/google/protobuf/descriptor.proto diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.proto b/vendor/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.proto deleted file mode 100644 index 4d4fb378f..000000000 --- a/vendor/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.proto +++ /dev/null @@ -1,849 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. -// -// The messages in this file describe the definitions found in .proto files. -// A valid .proto file can be translated directly to a FileDescriptorProto -// without any other information (e.g. without reading its imports). - - -syntax = "proto2"; - -package google.protobuf; -option go_package = "github.com/golang/protobuf/protoc-gen-go/descriptor;descriptor"; -option java_package = "com.google.protobuf"; -option java_outer_classname = "DescriptorProtos"; -option csharp_namespace = "Google.Protobuf.Reflection"; -option objc_class_prefix = "GPB"; - -// descriptor.proto must be optimized for speed because reflection-based -// algorithms don't work during bootstrapping. -option optimize_for = SPEED; - -// The protocol compiler can output a FileDescriptorSet containing the .proto -// files it parses. -message FileDescriptorSet { - repeated FileDescriptorProto file = 1; -} - -// Describes a complete .proto file. -message FileDescriptorProto { - optional string name = 1; // file name, relative to root of source tree - optional string package = 2; // e.g. "foo", "foo.bar", etc. - - // Names of files imported by this file. - repeated string dependency = 3; - // Indexes of the public imported files in the dependency list above. - repeated int32 public_dependency = 10; - // Indexes of the weak imported files in the dependency list. - // For Google-internal migration only. Do not use. - repeated int32 weak_dependency = 11; - - // All top-level definitions in this file. - repeated DescriptorProto message_type = 4; - repeated EnumDescriptorProto enum_type = 5; - repeated ServiceDescriptorProto service = 6; - repeated FieldDescriptorProto extension = 7; - - optional FileOptions options = 8; - - // This field contains optional information about the original source code. - // You may safely remove this entire field without harming runtime - // functionality of the descriptors -- the information is needed only by - // development tools. - optional SourceCodeInfo source_code_info = 9; - - // The syntax of the proto file. - // The supported values are "proto2" and "proto3". - optional string syntax = 12; -} - -// Describes a message type. -message DescriptorProto { - optional string name = 1; - - repeated FieldDescriptorProto field = 2; - repeated FieldDescriptorProto extension = 6; - - repeated DescriptorProto nested_type = 3; - repeated EnumDescriptorProto enum_type = 4; - - message ExtensionRange { - optional int32 start = 1; - optional int32 end = 2; - - optional ExtensionRangeOptions options = 3; - } - repeated ExtensionRange extension_range = 5; - - repeated OneofDescriptorProto oneof_decl = 8; - - optional MessageOptions options = 7; - - // Range of reserved tag numbers. Reserved tag numbers may not be used by - // fields or extension ranges in the same message. Reserved ranges may - // not overlap. - message ReservedRange { - optional int32 start = 1; // Inclusive. - optional int32 end = 2; // Exclusive. - } - repeated ReservedRange reserved_range = 9; - // Reserved field names, which may not be used by fields in the same message. - // A given name may only be reserved once. - repeated string reserved_name = 10; -} - -message ExtensionRangeOptions { - // The parser stores options it doesn't recognize here. See above. - repeated UninterpretedOption uninterpreted_option = 999; - - // Clients can define custom options in extensions of this message. See above. - extensions 1000 to max; -} - -// Describes a field within a message. -message FieldDescriptorProto { - enum Type { - // 0 is reserved for errors. - // Order is weird for historical reasons. - TYPE_DOUBLE = 1; - TYPE_FLOAT = 2; - // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if - // negative values are likely. - TYPE_INT64 = 3; - TYPE_UINT64 = 4; - // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if - // negative values are likely. - TYPE_INT32 = 5; - TYPE_FIXED64 = 6; - TYPE_FIXED32 = 7; - TYPE_BOOL = 8; - TYPE_STRING = 9; - // Tag-delimited aggregate. - // Group type is deprecated and not supported in proto3. However, Proto3 - // implementations should still be able to parse the group wire format and - // treat group fields as unknown fields. - TYPE_GROUP = 10; - TYPE_MESSAGE = 11; // Length-delimited aggregate. - - // New in version 2. - TYPE_BYTES = 12; - TYPE_UINT32 = 13; - TYPE_ENUM = 14; - TYPE_SFIXED32 = 15; - TYPE_SFIXED64 = 16; - TYPE_SINT32 = 17; // Uses ZigZag encoding. - TYPE_SINT64 = 18; // Uses ZigZag encoding. - }; - - enum Label { - // 0 is reserved for errors - LABEL_OPTIONAL = 1; - LABEL_REQUIRED = 2; - LABEL_REPEATED = 3; - }; - - optional string name = 1; - optional int32 number = 3; - optional Label label = 4; - - // If type_name is set, this need not be set. If both this and type_name - // are set, this must be one of TYPE_ENUM, TYPE_MESSAGE or TYPE_GROUP. - optional Type type = 5; - - // For message and enum types, this is the name of the type. If the name - // starts with a '.', it is fully-qualified. Otherwise, C++-like scoping - // rules are used to find the type (i.e. first the nested types within this - // message are searched, then within the parent, on up to the root - // namespace). - optional string type_name = 6; - - // For extensions, this is the name of the type being extended. It is - // resolved in the same manner as type_name. - optional string extendee = 2; - - // For numeric types, contains the original text representation of the value. - // For booleans, "true" or "false". - // For strings, contains the default text contents (not escaped in any way). - // For bytes, contains the C escaped value. All bytes >= 128 are escaped. - // TODO(kenton): Base-64 encode? - optional string default_value = 7; - - // If set, gives the index of a oneof in the containing type's oneof_decl - // list. This field is a member of that oneof. - optional int32 oneof_index = 9; - - // JSON name of this field. The value is set by protocol compiler. If the - // user has set a "json_name" option on this field, that option's value - // will be used. Otherwise, it's deduced from the field's name by converting - // it to camelCase. - optional string json_name = 10; - - optional FieldOptions options = 8; -} - -// Describes a oneof. -message OneofDescriptorProto { - optional string name = 1; - optional OneofOptions options = 2; -} - -// Describes an enum type. -message EnumDescriptorProto { - optional string name = 1; - - repeated EnumValueDescriptorProto value = 2; - - optional EnumOptions options = 3; -} - -// Describes a value within an enum. -message EnumValueDescriptorProto { - optional string name = 1; - optional int32 number = 2; - - optional EnumValueOptions options = 3; -} - -// Describes a service. -message ServiceDescriptorProto { - optional string name = 1; - repeated MethodDescriptorProto method = 2; - - optional ServiceOptions options = 3; -} - -// Describes a method of a service. -message MethodDescriptorProto { - optional string name = 1; - - // Input and output type names. These are resolved in the same way as - // FieldDescriptorProto.type_name, but must refer to a message type. - optional string input_type = 2; - optional string output_type = 3; - - optional MethodOptions options = 4; - - // Identifies if client streams multiple client messages - optional bool client_streaming = 5 [default=false]; - // Identifies if server streams multiple server messages - optional bool server_streaming = 6 [default=false]; -} - - -// =================================================================== -// Options - -// Each of the definitions above may have "options" attached. These are -// just annotations which may cause code to be generated slightly differently -// or may contain hints for code that manipulates protocol messages. -// -// Clients may define custom options as extensions of the *Options messages. -// These extensions may not yet be known at parsing time, so the parser cannot -// store the values in them. Instead it stores them in a field in the *Options -// message called uninterpreted_option. This field must have the same name -// across all *Options messages. We then use this field to populate the -// extensions when we build a descriptor, at which point all protos have been -// parsed and so all extensions are known. -// -// Extension numbers for custom options may be chosen as follows: -// * For options which will only be used within a single application or -// organization, or for experimental options, use field numbers 50000 -// through 99999. It is up to you to ensure that you do not use the -// same number for multiple options. -// * For options which will be published and used publicly by multiple -// independent entities, e-mail protobuf-global-extension-registry@google.com -// to reserve extension numbers. Simply provide your project name (e.g. -// Objective-C plugin) and your project website (if available) -- there's no -// need to explain how you intend to use them. Usually you only need one -// extension number. You can declare multiple options with only one extension -// number by putting them in a sub-message. See the Custom Options section of -// the docs for examples: -// https://developers.google.com/protocol-buffers/docs/proto#options -// If this turns out to be popular, a web service will be set up -// to automatically assign option numbers. - - -message FileOptions { - - // Sets the Java package where classes generated from this .proto will be - // placed. By default, the proto package is used, but this is often - // inappropriate because proto packages do not normally start with backwards - // domain names. - optional string java_package = 1; - - - // If set, all the classes from the .proto file are wrapped in a single - // outer class with the given name. This applies to both Proto1 - // (equivalent to the old "--one_java_file" option) and Proto2 (where - // a .proto always translates to a single class, but you may want to - // explicitly choose the class name). - optional string java_outer_classname = 8; - - // If set true, then the Java code generator will generate a separate .java - // file for each top-level message, enum, and service defined in the .proto - // file. Thus, these types will *not* be nested inside the outer class - // named by java_outer_classname. However, the outer class will still be - // generated to contain the file's getDescriptor() method as well as any - // top-level extensions defined in the file. - optional bool java_multiple_files = 10 [default=false]; - - // This option does nothing. - optional bool java_generate_equals_and_hash = 20 [deprecated=true]; - - // If set true, then the Java2 code generator will generate code that - // throws an exception whenever an attempt is made to assign a non-UTF-8 - // byte sequence to a string field. - // Message reflection will do the same. - // However, an extension field still accepts non-UTF-8 byte sequences. - // This option has no effect on when used with the lite runtime. - optional bool java_string_check_utf8 = 27 [default=false]; - - - // Generated classes can be optimized for speed or code size. - enum OptimizeMode { - SPEED = 1; // Generate complete code for parsing, serialization, - // etc. - CODE_SIZE = 2; // Use ReflectionOps to implement these methods. - LITE_RUNTIME = 3; // Generate code using MessageLite and the lite runtime. - } - optional OptimizeMode optimize_for = 9 [default=SPEED]; - - // Sets the Go package where structs generated from this .proto will be - // placed. If omitted, the Go package will be derived from the following: - // - The basename of the package import path, if provided. - // - Otherwise, the package statement in the .proto file, if present. - // - Otherwise, the basename of the .proto file, without extension. - optional string go_package = 11; - - - - // Should generic services be generated in each language? "Generic" services - // are not specific to any particular RPC system. They are generated by the - // main code generators in each language (without additional plugins). - // Generic services were the only kind of service generation supported by - // early versions of google.protobuf. - // - // Generic services are now considered deprecated in favor of using plugins - // that generate code specific to your particular RPC system. Therefore, - // these default to false. Old code which depends on generic services should - // explicitly set them to true. - optional bool cc_generic_services = 16 [default=false]; - optional bool java_generic_services = 17 [default=false]; - optional bool py_generic_services = 18 [default=false]; - optional bool php_generic_services = 42 [default=false]; - - // Is this file deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for everything in the file, or it will be completely ignored; in the very - // least, this is a formalization for deprecating files. - optional bool deprecated = 23 [default=false]; - - // Enables the use of arenas for the proto messages in this file. This applies - // only to generated classes for C++. - optional bool cc_enable_arenas = 31 [default=false]; - - - // Sets the objective c class prefix which is prepended to all objective c - // generated classes from this .proto. There is no default. - optional string objc_class_prefix = 36; - - // Namespace for generated classes; defaults to the package. - optional string csharp_namespace = 37; - - // By default Swift generators will take the proto package and CamelCase it - // replacing '.' with underscore and use that to prefix the types/symbols - // defined. When this options is provided, they will use this value instead - // to prefix the types/symbols defined. - optional string swift_prefix = 39; - - // Sets the php class prefix which is prepended to all php generated classes - // from this .proto. Default is empty. - optional string php_class_prefix = 40; - - // Use this option to change the namespace of php generated classes. Default - // is empty. When this option is empty, the package name will be used for - // determining the namespace. - optional string php_namespace = 41; - - // The parser stores options it doesn't recognize here. See above. - repeated UninterpretedOption uninterpreted_option = 999; - - // Clients can define custom options in extensions of this message. See above. - extensions 1000 to max; - - reserved 38; -} - -message MessageOptions { - // Set true to use the old proto1 MessageSet wire format for extensions. - // This is provided for backwards-compatibility with the MessageSet wire - // format. You should not use this for any other reason: It's less - // efficient, has fewer features, and is more complicated. - // - // The message must be defined exactly as follows: - // message Foo { - // option message_set_wire_format = true; - // extensions 4 to max; - // } - // Note that the message cannot have any defined fields; MessageSets only - // have extensions. - // - // All extensions of your type must be singular messages; e.g. they cannot - // be int32s, enums, or repeated messages. - // - // Because this is an option, the above two restrictions are not enforced by - // the protocol compiler. - optional bool message_set_wire_format = 1 [default=false]; - - // Disables the generation of the standard "descriptor()" accessor, which can - // conflict with a field of the same name. This is meant to make migration - // from proto1 easier; new code should avoid fields named "descriptor". - optional bool no_standard_descriptor_accessor = 2 [default=false]; - - // Is this message deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for the message, or it will be completely ignored; in the very least, - // this is a formalization for deprecating messages. - optional bool deprecated = 3 [default=false]; - - // Whether the message is an automatically generated map entry type for the - // maps field. - // - // For maps fields: - // map map_field = 1; - // The parsed descriptor looks like: - // message MapFieldEntry { - // option map_entry = true; - // optional KeyType key = 1; - // optional ValueType value = 2; - // } - // repeated MapFieldEntry map_field = 1; - // - // Implementations may choose not to generate the map_entry=true message, but - // use a native map in the target language to hold the keys and values. - // The reflection APIs in such implementions still need to work as - // if the field is a repeated message field. - // - // NOTE: Do not set the option in .proto files. Always use the maps syntax - // instead. The option should only be implicitly set by the proto compiler - // parser. - optional bool map_entry = 7; - - reserved 8; // javalite_serializable - reserved 9; // javanano_as_lite - - // The parser stores options it doesn't recognize here. See above. - repeated UninterpretedOption uninterpreted_option = 999; - - // Clients can define custom options in extensions of this message. See above. - extensions 1000 to max; -} - -message FieldOptions { - // The ctype option instructs the C++ code generator to use a different - // representation of the field than it normally would. See the specific - // options below. This option is not yet implemented in the open source - // release -- sorry, we'll try to include it in a future version! - optional CType ctype = 1 [default = STRING]; - enum CType { - // Default mode. - STRING = 0; - - CORD = 1; - - STRING_PIECE = 2; - } - // The packed option can be enabled for repeated primitive fields to enable - // a more efficient representation on the wire. Rather than repeatedly - // writing the tag and type for each element, the entire array is encoded as - // a single length-delimited blob. In proto3, only explicit setting it to - // false will avoid using packed encoding. - optional bool packed = 2; - - // The jstype option determines the JavaScript type used for values of the - // field. The option is permitted only for 64 bit integral and fixed types - // (int64, uint64, sint64, fixed64, sfixed64). A field with jstype JS_STRING - // is represented as JavaScript string, which avoids loss of precision that - // can happen when a large value is converted to a floating point JavaScript. - // Specifying JS_NUMBER for the jstype causes the generated JavaScript code to - // use the JavaScript "number" type. The behavior of the default option - // JS_NORMAL is implementation dependent. - // - // This option is an enum to permit additional types to be added, e.g. - // goog.math.Integer. - optional JSType jstype = 6 [default = JS_NORMAL]; - enum JSType { - // Use the default type. - JS_NORMAL = 0; - - // Use JavaScript strings. - JS_STRING = 1; - - // Use JavaScript numbers. - JS_NUMBER = 2; - } - - // Should this field be parsed lazily? Lazy applies only to message-type - // fields. It means that when the outer message is initially parsed, the - // inner message's contents will not be parsed but instead stored in encoded - // form. The inner message will actually be parsed when it is first accessed. - // - // This is only a hint. Implementations are free to choose whether to use - // eager or lazy parsing regardless of the value of this option. However, - // setting this option true suggests that the protocol author believes that - // using lazy parsing on this field is worth the additional bookkeeping - // overhead typically needed to implement it. - // - // This option does not affect the public interface of any generated code; - // all method signatures remain the same. Furthermore, thread-safety of the - // interface is not affected by this option; const methods remain safe to - // call from multiple threads concurrently, while non-const methods continue - // to require exclusive access. - // - // - // Note that implementations may choose not to check required fields within - // a lazy sub-message. That is, calling IsInitialized() on the outer message - // may return true even if the inner message has missing required fields. - // This is necessary because otherwise the inner message would have to be - // parsed in order to perform the check, defeating the purpose of lazy - // parsing. An implementation which chooses not to check required fields - // must be consistent about it. That is, for any particular sub-message, the - // implementation must either *always* check its required fields, or *never* - // check its required fields, regardless of whether or not the message has - // been parsed. - optional bool lazy = 5 [default=false]; - - // Is this field deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for accessors, or it will be completely ignored; in the very least, this - // is a formalization for deprecating fields. - optional bool deprecated = 3 [default=false]; - - // For Google-internal migration only. Do not use. - optional bool weak = 10 [default=false]; - - - // The parser stores options it doesn't recognize here. See above. - repeated UninterpretedOption uninterpreted_option = 999; - - // Clients can define custom options in extensions of this message. See above. - extensions 1000 to max; - - reserved 4; // removed jtype -} - -message OneofOptions { - // The parser stores options it doesn't recognize here. See above. - repeated UninterpretedOption uninterpreted_option = 999; - - // Clients can define custom options in extensions of this message. See above. - extensions 1000 to max; -} - -message EnumOptions { - - // Set this option to true to allow mapping different tag names to the same - // value. - optional bool allow_alias = 2; - - // Is this enum deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for the enum, or it will be completely ignored; in the very least, this - // is a formalization for deprecating enums. - optional bool deprecated = 3 [default=false]; - - reserved 5; // javanano_as_lite - - // The parser stores options it doesn't recognize here. See above. - repeated UninterpretedOption uninterpreted_option = 999; - - // Clients can define custom options in extensions of this message. See above. - extensions 1000 to max; -} - -message EnumValueOptions { - // Is this enum value deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for the enum value, or it will be completely ignored; in the very least, - // this is a formalization for deprecating enum values. - optional bool deprecated = 1 [default=false]; - - // The parser stores options it doesn't recognize here. See above. - repeated UninterpretedOption uninterpreted_option = 999; - - // Clients can define custom options in extensions of this message. See above. - extensions 1000 to max; -} - -message ServiceOptions { - - // Note: Field numbers 1 through 32 are reserved for Google's internal RPC - // framework. We apologize for hoarding these numbers to ourselves, but - // we were already using them long before we decided to release Protocol - // Buffers. - - // Is this service deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for the service, or it will be completely ignored; in the very least, - // this is a formalization for deprecating services. - optional bool deprecated = 33 [default=false]; - - // The parser stores options it doesn't recognize here. See above. - repeated UninterpretedOption uninterpreted_option = 999; - - // Clients can define custom options in extensions of this message. See above. - extensions 1000 to max; -} - -message MethodOptions { - - // Note: Field numbers 1 through 32 are reserved for Google's internal RPC - // framework. We apologize for hoarding these numbers to ourselves, but - // we were already using them long before we decided to release Protocol - // Buffers. - - // Is this method deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for the method, or it will be completely ignored; in the very least, - // this is a formalization for deprecating methods. - optional bool deprecated = 33 [default=false]; - - // Is this method side-effect-free (or safe in HTTP parlance), or idempotent, - // or neither? HTTP based RPC implementation may choose GET verb for safe - // methods, and PUT verb for idempotent methods instead of the default POST. - enum IdempotencyLevel { - IDEMPOTENCY_UNKNOWN = 0; - NO_SIDE_EFFECTS = 1; // implies idempotent - IDEMPOTENT = 2; // idempotent, but may have side effects - } - optional IdempotencyLevel idempotency_level = - 34 [default=IDEMPOTENCY_UNKNOWN]; - - // The parser stores options it doesn't recognize here. See above. - repeated UninterpretedOption uninterpreted_option = 999; - - // Clients can define custom options in extensions of this message. See above. - extensions 1000 to max; -} - - -// A message representing a option the parser does not recognize. This only -// appears in options protos created by the compiler::Parser class. -// DescriptorPool resolves these when building Descriptor objects. Therefore, -// options protos in descriptor objects (e.g. returned by Descriptor::options(), -// or produced by Descriptor::CopyTo()) will never have UninterpretedOptions -// in them. -message UninterpretedOption { - // The name of the uninterpreted option. Each string represents a segment in - // a dot-separated name. is_extension is true iff a segment represents an - // extension (denoted with parentheses in options specs in .proto files). - // E.g.,{ ["foo", false], ["bar.baz", true], ["qux", false] } represents - // "foo.(bar.baz).qux". - message NamePart { - required string name_part = 1; - required bool is_extension = 2; - } - repeated NamePart name = 2; - - // The value of the uninterpreted option, in whatever type the tokenizer - // identified it as during parsing. Exactly one of these should be set. - optional string identifier_value = 3; - optional uint64 positive_int_value = 4; - optional int64 negative_int_value = 5; - optional double double_value = 6; - optional bytes string_value = 7; - optional string aggregate_value = 8; -} - -// =================================================================== -// Optional source code info - -// Encapsulates information about the original source file from which a -// FileDescriptorProto was generated. -message SourceCodeInfo { - // A Location identifies a piece of source code in a .proto file which - // corresponds to a particular definition. This information is intended - // to be useful to IDEs, code indexers, documentation generators, and similar - // tools. - // - // For example, say we have a file like: - // message Foo { - // optional string foo = 1; - // } - // Let's look at just the field definition: - // optional string foo = 1; - // ^ ^^ ^^ ^ ^^^ - // a bc de f ghi - // We have the following locations: - // span path represents - // [a,i) [ 4, 0, 2, 0 ] The whole field definition. - // [a,b) [ 4, 0, 2, 0, 4 ] The label (optional). - // [c,d) [ 4, 0, 2, 0, 5 ] The type (string). - // [e,f) [ 4, 0, 2, 0, 1 ] The name (foo). - // [g,h) [ 4, 0, 2, 0, 3 ] The number (1). - // - // Notes: - // - A location may refer to a repeated field itself (i.e. not to any - // particular index within it). This is used whenever a set of elements are - // logically enclosed in a single code segment. For example, an entire - // extend block (possibly containing multiple extension definitions) will - // have an outer location whose path refers to the "extensions" repeated - // field without an index. - // - Multiple locations may have the same path. This happens when a single - // logical declaration is spread out across multiple places. The most - // obvious example is the "extend" block again -- there may be multiple - // extend blocks in the same scope, each of which will have the same path. - // - A location's span is not always a subset of its parent's span. For - // example, the "extendee" of an extension declaration appears at the - // beginning of the "extend" block and is shared by all extensions within - // the block. - // - Just because a location's span is a subset of some other location's span - // does not mean that it is a descendent. For example, a "group" defines - // both a type and a field in a single declaration. Thus, the locations - // corresponding to the type and field and their components will overlap. - // - Code which tries to interpret locations should probably be designed to - // ignore those that it doesn't understand, as more types of locations could - // be recorded in the future. - repeated Location location = 1; - message Location { - // Identifies which part of the FileDescriptorProto was defined at this - // location. - // - // Each element is a field number or an index. They form a path from - // the root FileDescriptorProto to the place where the definition. For - // example, this path: - // [ 4, 3, 2, 7, 1 ] - // refers to: - // file.message_type(3) // 4, 3 - // .field(7) // 2, 7 - // .name() // 1 - // This is because FileDescriptorProto.message_type has field number 4: - // repeated DescriptorProto message_type = 4; - // and DescriptorProto.field has field number 2: - // repeated FieldDescriptorProto field = 2; - // and FieldDescriptorProto.name has field number 1: - // optional string name = 1; - // - // Thus, the above path gives the location of a field name. If we removed - // the last element: - // [ 4, 3, 2, 7 ] - // this path refers to the whole field declaration (from the beginning - // of the label to the terminating semicolon). - repeated int32 path = 1 [packed=true]; - - // Always has exactly three or four elements: start line, start column, - // end line (optional, otherwise assumed same as start line), end column. - // These are packed into a single field for efficiency. Note that line - // and column numbers are zero-based -- typically you will want to add - // 1 to each before displaying to a user. - repeated int32 span = 2 [packed=true]; - - // If this SourceCodeInfo represents a complete declaration, these are any - // comments appearing before and after the declaration which appear to be - // attached to the declaration. - // - // A series of line comments appearing on consecutive lines, with no other - // tokens appearing on those lines, will be treated as a single comment. - // - // leading_detached_comments will keep paragraphs of comments that appear - // before (but not connected to) the current element. Each paragraph, - // separated by empty lines, will be one comment element in the repeated - // field. - // - // Only the comment content is provided; comment markers (e.g. //) are - // stripped out. For block comments, leading whitespace and an asterisk - // will be stripped from the beginning of each line other than the first. - // Newlines are included in the output. - // - // Examples: - // - // optional int32 foo = 1; // Comment attached to foo. - // // Comment attached to bar. - // optional int32 bar = 2; - // - // optional string baz = 3; - // // Comment attached to baz. - // // Another line attached to baz. - // - // // Comment attached to qux. - // // - // // Another line attached to qux. - // optional double qux = 4; - // - // // Detached comment for corge. This is not leading or trailing comments - // // to qux or corge because there are blank lines separating it from - // // both. - // - // // Detached comment for corge paragraph 2. - // - // optional string corge = 5; - // /* Block comment attached - // * to corge. Leading asterisks - // * will be removed. */ - // /* Block comment attached to - // * grault. */ - // optional int32 grault = 6; - // - // // ignored detached comments. - optional string leading_comments = 3; - optional string trailing_comments = 4; - repeated string leading_detached_comments = 6; - } -} - -// Describes the relationship between generated code and its original source -// file. A GeneratedCodeInfo message is associated with only one generated -// source file, but may contain references to different source .proto files. -message GeneratedCodeInfo { - // An Annotation connects some span of text in generated code to an element - // of its generating .proto file. - repeated Annotation annotation = 1; - message Annotation { - // Identifies the element in the original source .proto file. This field - // is formatted the same as SourceCodeInfo.Location.path. - repeated int32 path = 1 [packed=true]; - - // Identifies the filesystem path to the original source .proto. - optional string source_file = 2; - - // Identifies the starting offset in bytes in the generated code - // that relates to the identified object. - optional int32 begin = 3; - - // Identifies the ending offset in bytes in the generated code that - // relates to the identified offset. The end offset should be one past - // the last relevant byte (so the length of the text = end - begin). - optional int32 end = 4; - } -} diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/doc.go b/vendor/github.com/golang/protobuf/protoc-gen-go/doc.go deleted file mode 100644 index 0d6055d61..000000000 --- a/vendor/github.com/golang/protobuf/protoc-gen-go/doc.go +++ /dev/null @@ -1,51 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -/* - A plugin for the Google protocol buffer compiler to generate Go code. - Run it by building this program and putting it in your path with the name - protoc-gen-go - That word 'go' at the end becomes part of the option string set for the - protocol compiler, so once the protocol compiler (protoc) is installed - you can run - protoc --go_out=output_directory input_directory/file.proto - to generate Go bindings for the protocol defined by file.proto. - With that input, the output will be written to - output_directory/file.pb.go - - The generated code is documented in the package comment for - the library. - - See the README and documentation for protocol buffers to learn more: - https://developers.google.com/protocol-buffers/ - -*/ -package documentation diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/link_grpc.go b/vendor/github.com/golang/protobuf/protoc-gen-go/link_grpc.go deleted file mode 100644 index 532a55005..000000000 --- a/vendor/github.com/golang/protobuf/protoc-gen-go/link_grpc.go +++ /dev/null @@ -1,34 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2015 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package main - -import _ "github.com/golang/protobuf/protoc-gen-go/grpc" diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/main.go b/vendor/github.com/golang/protobuf/protoc-gen-go/main.go deleted file mode 100644 index 8e2486de0..000000000 --- a/vendor/github.com/golang/protobuf/protoc-gen-go/main.go +++ /dev/null @@ -1,98 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// protoc-gen-go is a plugin for the Google protocol buffer compiler to generate -// Go code. Run it by building this program and putting it in your path with -// the name -// protoc-gen-go -// That word 'go' at the end becomes part of the option string set for the -// protocol compiler, so once the protocol compiler (protoc) is installed -// you can run -// protoc --go_out=output_directory input_directory/file.proto -// to generate Go bindings for the protocol defined by file.proto. -// With that input, the output will be written to -// output_directory/file.pb.go -// -// The generated code is documented in the package comment for -// the library. -// -// See the README and documentation for protocol buffers to learn more: -// https://developers.google.com/protocol-buffers/ -package main - -import ( - "io/ioutil" - "os" - - "github.com/golang/protobuf/proto" - "github.com/golang/protobuf/protoc-gen-go/generator" -) - -func main() { - // Begin by allocating a generator. The request and response structures are stored there - // so we can do error handling easily - the response structure contains the field to - // report failure. - g := generator.New() - - data, err := ioutil.ReadAll(os.Stdin) - if err != nil { - g.Error(err, "reading input") - } - - if err := proto.Unmarshal(data, g.Request); err != nil { - g.Error(err, "parsing input proto") - } - - if len(g.Request.FileToGenerate) == 0 { - g.Fail("no files to generate") - } - - g.CommandLineParameters(g.Request.GetParameter()) - - // Create a wrapped version of the Descriptors and EnumDescriptors that - // point to the file that defines them. - g.WrapTypes() - - g.SetPackageNames() - g.BuildTypeNameMap() - - g.GenerateAllFiles() - - // Send back the results. - data, err = proto.Marshal(g.Response) - if err != nil { - g.Error(err, "failed to marshal output proto") - } - _, err = os.Stdout.Write(data) - if err != nil { - g.Error(err, "failed to write output proto") - } -} diff --git a/vendor/github.com/golang/protobuf/ptypes/any/any.proto b/vendor/github.com/golang/protobuf/ptypes/any/any.proto deleted file mode 100644 index c74866762..000000000 --- a/vendor/github.com/golang/protobuf/ptypes/any/any.proto +++ /dev/null @@ -1,149 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -syntax = "proto3"; - -package google.protobuf; - -option csharp_namespace = "Google.Protobuf.WellKnownTypes"; -option go_package = "github.com/golang/protobuf/ptypes/any"; -option java_package = "com.google.protobuf"; -option java_outer_classname = "AnyProto"; -option java_multiple_files = true; -option objc_class_prefix = "GPB"; - -// `Any` contains an arbitrary serialized protocol buffer message along with a -// URL that describes the type of the serialized message. -// -// Protobuf library provides support to pack/unpack Any values in the form -// of utility functions or additional generated methods of the Any type. -// -// Example 1: Pack and unpack a message in C++. -// -// Foo foo = ...; -// Any any; -// any.PackFrom(foo); -// ... -// if (any.UnpackTo(&foo)) { -// ... -// } -// -// Example 2: Pack and unpack a message in Java. -// -// Foo foo = ...; -// Any any = Any.pack(foo); -// ... -// if (any.is(Foo.class)) { -// foo = any.unpack(Foo.class); -// } -// -// Example 3: Pack and unpack a message in Python. -// -// foo = Foo(...) -// any = Any() -// any.Pack(foo) -// ... -// if any.Is(Foo.DESCRIPTOR): -// any.Unpack(foo) -// ... -// -// Example 4: Pack and unpack a message in Go -// -// foo := &pb.Foo{...} -// any, err := ptypes.MarshalAny(foo) -// ... -// foo := &pb.Foo{} -// if err := ptypes.UnmarshalAny(any, foo); err != nil { -// ... -// } -// -// The pack methods provided by protobuf library will by default use -// 'type.googleapis.com/full.type.name' as the type URL and the unpack -// methods only use the fully qualified type name after the last '/' -// in the type URL, for example "foo.bar.com/x/y.z" will yield type -// name "y.z". -// -// -// JSON -// ==== -// The JSON representation of an `Any` value uses the regular -// representation of the deserialized, embedded message, with an -// additional field `@type` which contains the type URL. Example: -// -// package google.profile; -// message Person { -// string first_name = 1; -// string last_name = 2; -// } -// -// { -// "@type": "type.googleapis.com/google.profile.Person", -// "firstName": , -// "lastName": -// } -// -// If the embedded message type is well-known and has a custom JSON -// representation, that representation will be embedded adding a field -// `value` which holds the custom JSON in addition to the `@type` -// field. Example (for message [google.protobuf.Duration][]): -// -// { -// "@type": "type.googleapis.com/google.protobuf.Duration", -// "value": "1.212s" -// } -// -message Any { - // A URL/resource name whose content describes the type of the - // serialized protocol buffer message. - // - // For URLs which use the scheme `http`, `https`, or no scheme, the - // following restrictions and interpretations apply: - // - // * If no scheme is provided, `https` is assumed. - // * The last segment of the URL's path must represent the fully - // qualified name of the type (as in `path/google.protobuf.Duration`). - // The name should be in a canonical form (e.g., leading "." is - // not accepted). - // * An HTTP GET on the URL must yield a [google.protobuf.Type][] - // value in binary format, or produce an error. - // * Applications are allowed to cache lookup results based on the - // URL, or have them precompiled into a binary to avoid any - // lookup. Therefore, binary compatibility needs to be preserved - // on changes to types. (Use versioned type names to manage - // breaking changes.) - // - // Schemes other than `http`, `https` (or the empty scheme) might be - // used with implementation specific semantics. - // - string type_url = 1; - - // Must be a valid serialized protocol buffer of the above specified type. - bytes value = 2; -} diff --git a/vendor/github.com/golang/protobuf/ptypes/any_test.go b/vendor/github.com/golang/protobuf/ptypes/any_test.go deleted file mode 100644 index ed675b489..000000000 --- a/vendor/github.com/golang/protobuf/ptypes/any_test.go +++ /dev/null @@ -1,113 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2016 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package ptypes - -import ( - "testing" - - "github.com/golang/protobuf/proto" - pb "github.com/golang/protobuf/protoc-gen-go/descriptor" - "github.com/golang/protobuf/ptypes/any" -) - -func TestMarshalUnmarshal(t *testing.T) { - orig := &any.Any{Value: []byte("test")} - - packed, err := MarshalAny(orig) - if err != nil { - t.Errorf("MarshalAny(%+v): got: _, %v exp: _, nil", orig, err) - } - - unpacked := &any.Any{} - err = UnmarshalAny(packed, unpacked) - if err != nil || !proto.Equal(unpacked, orig) { - t.Errorf("got: %v, %+v; want nil, %+v", err, unpacked, orig) - } -} - -func TestIs(t *testing.T) { - a, err := MarshalAny(&pb.FileDescriptorProto{}) - if err != nil { - t.Fatal(err) - } - if Is(a, &pb.DescriptorProto{}) { - t.Error("FileDescriptorProto is not a DescriptorProto, but Is says it is") - } - if !Is(a, &pb.FileDescriptorProto{}) { - t.Error("FileDescriptorProto is indeed a FileDescriptorProto, but Is says it is not") - } -} - -func TestIsDifferentUrlPrefixes(t *testing.T) { - m := &pb.FileDescriptorProto{} - a := &any.Any{TypeUrl: "foo/bar/" + proto.MessageName(m)} - if !Is(a, m) { - t.Errorf("message with type url %q didn't satisfy Is for type %q", a.TypeUrl, proto.MessageName(m)) - } -} - -func TestUnmarshalDynamic(t *testing.T) { - want := &pb.FileDescriptorProto{Name: proto.String("foo")} - a, err := MarshalAny(want) - if err != nil { - t.Fatal(err) - } - var got DynamicAny - if err := UnmarshalAny(a, &got); err != nil { - t.Fatal(err) - } - if !proto.Equal(got.Message, want) { - t.Errorf("invalid result from UnmarshalAny, got %q want %q", got.Message, want) - } -} - -func TestEmpty(t *testing.T) { - want := &pb.FileDescriptorProto{} - a, err := MarshalAny(want) - if err != nil { - t.Fatal(err) - } - got, err := Empty(a) - if err != nil { - t.Fatal(err) - } - if !proto.Equal(got, want) { - t.Errorf("unequal empty message, got %q, want %q", got, want) - } - - // that's a valid type_url for a message which shouldn't be linked into this - // test binary. We want an error. - a.TypeUrl = "type.googleapis.com/google.protobuf.FieldMask" - if _, err := Empty(a); err == nil { - t.Errorf("got no error for an attempt to create a message of type %q, which shouldn't be linked in", a.TypeUrl) - } -} diff --git a/vendor/github.com/golang/protobuf/ptypes/duration/duration.proto b/vendor/github.com/golang/protobuf/ptypes/duration/duration.proto deleted file mode 100644 index 975fce41a..000000000 --- a/vendor/github.com/golang/protobuf/ptypes/duration/duration.proto +++ /dev/null @@ -1,117 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -syntax = "proto3"; - -package google.protobuf; - -option csharp_namespace = "Google.Protobuf.WellKnownTypes"; -option cc_enable_arenas = true; -option go_package = "github.com/golang/protobuf/ptypes/duration"; -option java_package = "com.google.protobuf"; -option java_outer_classname = "DurationProto"; -option java_multiple_files = true; -option objc_class_prefix = "GPB"; - -// A Duration represents a signed, fixed-length span of time represented -// as a count of seconds and fractions of seconds at nanosecond -// resolution. It is independent of any calendar and concepts like "day" -// or "month". It is related to Timestamp in that the difference between -// two Timestamp values is a Duration and it can be added or subtracted -// from a Timestamp. Range is approximately +-10,000 years. -// -// # Examples -// -// Example 1: Compute Duration from two Timestamps in pseudo code. -// -// Timestamp start = ...; -// Timestamp end = ...; -// Duration duration = ...; -// -// duration.seconds = end.seconds - start.seconds; -// duration.nanos = end.nanos - start.nanos; -// -// if (duration.seconds < 0 && duration.nanos > 0) { -// duration.seconds += 1; -// duration.nanos -= 1000000000; -// } else if (durations.seconds > 0 && duration.nanos < 0) { -// duration.seconds -= 1; -// duration.nanos += 1000000000; -// } -// -// Example 2: Compute Timestamp from Timestamp + Duration in pseudo code. -// -// Timestamp start = ...; -// Duration duration = ...; -// Timestamp end = ...; -// -// end.seconds = start.seconds + duration.seconds; -// end.nanos = start.nanos + duration.nanos; -// -// if (end.nanos < 0) { -// end.seconds -= 1; -// end.nanos += 1000000000; -// } else if (end.nanos >= 1000000000) { -// end.seconds += 1; -// end.nanos -= 1000000000; -// } -// -// Example 3: Compute Duration from datetime.timedelta in Python. -// -// td = datetime.timedelta(days=3, minutes=10) -// duration = Duration() -// duration.FromTimedelta(td) -// -// # JSON Mapping -// -// In JSON format, the Duration type is encoded as a string rather than an -// object, where the string ends in the suffix "s" (indicating seconds) and -// is preceded by the number of seconds, with nanoseconds expressed as -// fractional seconds. For example, 3 seconds with 0 nanoseconds should be -// encoded in JSON format as "3s", while 3 seconds and 1 nanosecond should -// be expressed in JSON format as "3.000000001s", and 3 seconds and 1 -// microsecond should be expressed in JSON format as "3.000001s". -// -// -message Duration { - - // Signed seconds of the span of time. Must be from -315,576,000,000 - // to +315,576,000,000 inclusive. Note: these bounds are computed from: - // 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years - int64 seconds = 1; - - // Signed fractions of a second at nanosecond resolution of the span - // of time. Durations less than one second are represented with a 0 - // `seconds` field and a positive or negative `nanos` field. For durations - // of one second or more, a non-zero value for the `nanos` field must be - // of the same sign as the `seconds` field. Must be from -999,999,999 - // to +999,999,999 inclusive. - int32 nanos = 2; -} diff --git a/vendor/github.com/golang/protobuf/ptypes/duration_test.go b/vendor/github.com/golang/protobuf/ptypes/duration_test.go deleted file mode 100644 index e00491a34..000000000 --- a/vendor/github.com/golang/protobuf/ptypes/duration_test.go +++ /dev/null @@ -1,121 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2016 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package ptypes - -import ( - "math" - "testing" - "time" - - "github.com/golang/protobuf/proto" - durpb "github.com/golang/protobuf/ptypes/duration" -) - -const ( - minGoSeconds = math.MinInt64 / int64(1e9) - maxGoSeconds = math.MaxInt64 / int64(1e9) -) - -var durationTests = []struct { - proto *durpb.Duration - isValid bool - inRange bool - dur time.Duration -}{ - // The zero duration. - {&durpb.Duration{Seconds: 0, Nanos: 0}, true, true, 0}, - // Some ordinary non-zero durations. - {&durpb.Duration{Seconds: 100, Nanos: 0}, true, true, 100 * time.Second}, - {&durpb.Duration{Seconds: -100, Nanos: 0}, true, true, -100 * time.Second}, - {&durpb.Duration{Seconds: 100, Nanos: 987}, true, true, 100*time.Second + 987}, - {&durpb.Duration{Seconds: -100, Nanos: -987}, true, true, -(100*time.Second + 987)}, - // The largest duration representable in Go. - {&durpb.Duration{Seconds: maxGoSeconds, Nanos: int32(math.MaxInt64 - 1e9*maxGoSeconds)}, true, true, math.MaxInt64}, - // The smallest duration representable in Go. - {&durpb.Duration{Seconds: minGoSeconds, Nanos: int32(math.MinInt64 - 1e9*minGoSeconds)}, true, true, math.MinInt64}, - {nil, false, false, 0}, - {&durpb.Duration{Seconds: -100, Nanos: 987}, false, false, 0}, - {&durpb.Duration{Seconds: 100, Nanos: -987}, false, false, 0}, - {&durpb.Duration{Seconds: math.MinInt64, Nanos: 0}, false, false, 0}, - {&durpb.Duration{Seconds: math.MaxInt64, Nanos: 0}, false, false, 0}, - // The largest valid duration. - {&durpb.Duration{Seconds: maxSeconds, Nanos: 1e9 - 1}, true, false, 0}, - // The smallest valid duration. - {&durpb.Duration{Seconds: minSeconds, Nanos: -(1e9 - 1)}, true, false, 0}, - // The smallest invalid duration above the valid range. - {&durpb.Duration{Seconds: maxSeconds + 1, Nanos: 0}, false, false, 0}, - // The largest invalid duration below the valid range. - {&durpb.Duration{Seconds: minSeconds - 1, Nanos: -(1e9 - 1)}, false, false, 0}, - // One nanosecond past the largest duration representable in Go. - {&durpb.Duration{Seconds: maxGoSeconds, Nanos: int32(math.MaxInt64-1e9*maxGoSeconds) + 1}, true, false, 0}, - // One nanosecond past the smallest duration representable in Go. - {&durpb.Duration{Seconds: minGoSeconds, Nanos: int32(math.MinInt64-1e9*minGoSeconds) - 1}, true, false, 0}, - // One second past the largest duration representable in Go. - {&durpb.Duration{Seconds: maxGoSeconds + 1, Nanos: int32(math.MaxInt64 - 1e9*maxGoSeconds)}, true, false, 0}, - // One second past the smallest duration representable in Go. - {&durpb.Duration{Seconds: minGoSeconds - 1, Nanos: int32(math.MinInt64 - 1e9*minGoSeconds)}, true, false, 0}, -} - -func TestValidateDuration(t *testing.T) { - for _, test := range durationTests { - err := validateDuration(test.proto) - gotValid := (err == nil) - if gotValid != test.isValid { - t.Errorf("validateDuration(%v) = %t, want %t", test.proto, gotValid, test.isValid) - } - } -} - -func TestDuration(t *testing.T) { - for _, test := range durationTests { - got, err := Duration(test.proto) - gotOK := (err == nil) - wantOK := test.isValid && test.inRange - if gotOK != wantOK { - t.Errorf("Duration(%v) ok = %t, want %t", test.proto, gotOK, wantOK) - } - if err == nil && got != test.dur { - t.Errorf("Duration(%v) = %v, want %v", test.proto, got, test.dur) - } - } -} - -func TestDurationProto(t *testing.T) { - for _, test := range durationTests { - if test.isValid && test.inRange { - got := DurationProto(test.dur) - if !proto.Equal(got, test.proto) { - t.Errorf("DurationProto(%v) = %v, want %v", test.dur, got, test.proto) - } - } - } -} diff --git a/vendor/github.com/golang/protobuf/ptypes/regen.sh b/vendor/github.com/golang/protobuf/ptypes/regen.sh deleted file mode 100755 index b50a9414a..000000000 --- a/vendor/github.com/golang/protobuf/ptypes/regen.sh +++ /dev/null @@ -1,43 +0,0 @@ -#!/bin/bash -e -# -# This script fetches and rebuilds the "well-known types" protocol buffers. -# To run this you will need protoc and goprotobuf installed; -# see https://github.com/golang/protobuf for instructions. -# You also need Go and Git installed. - -PKG=github.com/golang/protobuf/ptypes -UPSTREAM=https://github.com/google/protobuf -UPSTREAM_SUBDIR=src/google/protobuf -PROTO_FILES=(any duration empty struct timestamp wrappers) - -function die() { - echo 1>&2 $* - exit 1 -} - -# Sanity check that the right tools are accessible. -for tool in go git protoc protoc-gen-go; do - q=$(which $tool) || die "didn't find $tool" - echo 1>&2 "$tool: $q" -done - -tmpdir=$(mktemp -d -t regen-wkt.XXXXXX) -trap 'rm -rf $tmpdir' EXIT - -echo -n 1>&2 "finding package dir... " -pkgdir=$(go list -f '{{.Dir}}' $PKG) -echo 1>&2 $pkgdir -base=$(echo $pkgdir | sed "s,/$PKG\$,,") -echo 1>&2 "base: $base" -cd "$base" - -echo 1>&2 "fetching latest protos... " -git clone -q $UPSTREAM $tmpdir - -for file in ${PROTO_FILES[@]}; do - echo 1>&2 "* $file" - protoc --go_out=. -I$tmpdir/src $tmpdir/src/google/protobuf/$file.proto || die - cp $tmpdir/src/google/protobuf/$file.proto $PKG/$file -done - -echo 1>&2 "All OK" diff --git a/vendor/github.com/golang/protobuf/ptypes/struct/struct.proto b/vendor/github.com/golang/protobuf/ptypes/struct/struct.proto deleted file mode 100644 index 7d7808e7f..000000000 --- a/vendor/github.com/golang/protobuf/ptypes/struct/struct.proto +++ /dev/null @@ -1,96 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -syntax = "proto3"; - -package google.protobuf; - -option csharp_namespace = "Google.Protobuf.WellKnownTypes"; -option cc_enable_arenas = true; -option go_package = "github.com/golang/protobuf/ptypes/struct;structpb"; -option java_package = "com.google.protobuf"; -option java_outer_classname = "StructProto"; -option java_multiple_files = true; -option objc_class_prefix = "GPB"; - - -// `Struct` represents a structured data value, consisting of fields -// which map to dynamically typed values. In some languages, `Struct` -// might be supported by a native representation. For example, in -// scripting languages like JS a struct is represented as an -// object. The details of that representation are described together -// with the proto support for the language. -// -// The JSON representation for `Struct` is JSON object. -message Struct { - // Unordered map of dynamically typed values. - map fields = 1; -} - -// `Value` represents a dynamically typed value which can be either -// null, a number, a string, a boolean, a recursive struct value, or a -// list of values. A producer of value is expected to set one of that -// variants, absence of any variant indicates an error. -// -// The JSON representation for `Value` is JSON value. -message Value { - // The kind of value. - oneof kind { - // Represents a null value. - NullValue null_value = 1; - // Represents a double value. - double number_value = 2; - // Represents a string value. - string string_value = 3; - // Represents a boolean value. - bool bool_value = 4; - // Represents a structured value. - Struct struct_value = 5; - // Represents a repeated `Value`. - ListValue list_value = 6; - } -} - -// `NullValue` is a singleton enumeration to represent the null value for the -// `Value` type union. -// -// The JSON representation for `NullValue` is JSON `null`. -enum NullValue { - // Null value. - NULL_VALUE = 0; -} - -// `ListValue` is a wrapper around a repeated field of values. -// -// The JSON representation for `ListValue` is JSON array. -message ListValue { - // Repeated field of dynamically typed values. - repeated Value values = 1; -} diff --git a/vendor/github.com/golang/protobuf/ptypes/timestamp/timestamp.proto b/vendor/github.com/golang/protobuf/ptypes/timestamp/timestamp.proto deleted file mode 100644 index b7cbd1750..000000000 --- a/vendor/github.com/golang/protobuf/ptypes/timestamp/timestamp.proto +++ /dev/null @@ -1,133 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -syntax = "proto3"; - -package google.protobuf; - -option csharp_namespace = "Google.Protobuf.WellKnownTypes"; -option cc_enable_arenas = true; -option go_package = "github.com/golang/protobuf/ptypes/timestamp"; -option java_package = "com.google.protobuf"; -option java_outer_classname = "TimestampProto"; -option java_multiple_files = true; -option objc_class_prefix = "GPB"; - -// A Timestamp represents a point in time independent of any time zone -// or calendar, represented as seconds and fractions of seconds at -// nanosecond resolution in UTC Epoch time. It is encoded using the -// Proleptic Gregorian Calendar which extends the Gregorian calendar -// backwards to year one. It is encoded assuming all minutes are 60 -// seconds long, i.e. leap seconds are "smeared" so that no leap second -// table is needed for interpretation. Range is from -// 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. -// By restricting to that range, we ensure that we can convert to -// and from RFC 3339 date strings. -// See [https://www.ietf.org/rfc/rfc3339.txt](https://www.ietf.org/rfc/rfc3339.txt). -// -// # Examples -// -// Example 1: Compute Timestamp from POSIX `time()`. -// -// Timestamp timestamp; -// timestamp.set_seconds(time(NULL)); -// timestamp.set_nanos(0); -// -// Example 2: Compute Timestamp from POSIX `gettimeofday()`. -// -// struct timeval tv; -// gettimeofday(&tv, NULL); -// -// Timestamp timestamp; -// timestamp.set_seconds(tv.tv_sec); -// timestamp.set_nanos(tv.tv_usec * 1000); -// -// Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`. -// -// FILETIME ft; -// GetSystemTimeAsFileTime(&ft); -// UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime; -// -// // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z -// // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z. -// Timestamp timestamp; -// timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL)); -// timestamp.set_nanos((INT32) ((ticks % 10000000) * 100)); -// -// Example 4: Compute Timestamp from Java `System.currentTimeMillis()`. -// -// long millis = System.currentTimeMillis(); -// -// Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000) -// .setNanos((int) ((millis % 1000) * 1000000)).build(); -// -// -// Example 5: Compute Timestamp from current time in Python. -// -// timestamp = Timestamp() -// timestamp.GetCurrentTime() -// -// # JSON Mapping -// -// In JSON format, the Timestamp type is encoded as a string in the -// [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the -// format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z" -// where {year} is always expressed using four digits while {month}, {day}, -// {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional -// seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution), -// are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone -// is required, though only UTC (as indicated by "Z") is presently supported. -// -// For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past -// 01:30 UTC on January 15, 2017. -// -// In JavaScript, one can convert a Date object to this format using the -// standard [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString] -// method. In Python, a standard `datetime.datetime` object can be converted -// to this format using [`strftime`](https://docs.python.org/2/library/time.html#time.strftime) -// with the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one -// can use the Joda Time's [`ISODateTimeFormat.dateTime()`]( -// http://joda-time.sourceforge.net/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime()) -// to obtain a formatter capable of generating timestamps in this format. -// -// -message Timestamp { - - // Represents seconds of UTC time since Unix epoch - // 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to - // 9999-12-31T23:59:59Z inclusive. - int64 seconds = 1; - - // Non-negative fractions of a second at nanosecond resolution. Negative - // second values with fractions must still have non-negative nanos values - // that count forward in time. Must be from 0 to 999,999,999 - // inclusive. - int32 nanos = 2; -} diff --git a/vendor/github.com/golang/protobuf/ptypes/timestamp_test.go b/vendor/github.com/golang/protobuf/ptypes/timestamp_test.go deleted file mode 100644 index 6e3c969b9..000000000 --- a/vendor/github.com/golang/protobuf/ptypes/timestamp_test.go +++ /dev/null @@ -1,153 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2016 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package ptypes - -import ( - "math" - "testing" - "time" - - "github.com/golang/protobuf/proto" - tspb "github.com/golang/protobuf/ptypes/timestamp" -) - -var tests = []struct { - ts *tspb.Timestamp - valid bool - t time.Time -}{ - // The timestamp representing the Unix epoch date. - {&tspb.Timestamp{Seconds: 0, Nanos: 0}, true, utcDate(1970, 1, 1)}, - // The smallest representable timestamp. - {&tspb.Timestamp{Seconds: math.MinInt64, Nanos: math.MinInt32}, false, - time.Unix(math.MinInt64, math.MinInt32).UTC()}, - // The smallest representable timestamp with non-negative nanos. - {&tspb.Timestamp{Seconds: math.MinInt64, Nanos: 0}, false, time.Unix(math.MinInt64, 0).UTC()}, - // The earliest valid timestamp. - {&tspb.Timestamp{Seconds: minValidSeconds, Nanos: 0}, true, utcDate(1, 1, 1)}, - //"0001-01-01T00:00:00Z"}, - // The largest representable timestamp. - {&tspb.Timestamp{Seconds: math.MaxInt64, Nanos: math.MaxInt32}, false, - time.Unix(math.MaxInt64, math.MaxInt32).UTC()}, - // The largest representable timestamp with nanos in range. - {&tspb.Timestamp{Seconds: math.MaxInt64, Nanos: 1e9 - 1}, false, - time.Unix(math.MaxInt64, 1e9-1).UTC()}, - // The largest valid timestamp. - {&tspb.Timestamp{Seconds: maxValidSeconds - 1, Nanos: 1e9 - 1}, true, - time.Date(9999, 12, 31, 23, 59, 59, 1e9-1, time.UTC)}, - // The smallest invalid timestamp that is larger than the valid range. - {&tspb.Timestamp{Seconds: maxValidSeconds, Nanos: 0}, false, time.Unix(maxValidSeconds, 0).UTC()}, - // A date before the epoch. - {&tspb.Timestamp{Seconds: -281836800, Nanos: 0}, true, utcDate(1961, 1, 26)}, - // A date after the epoch. - {&tspb.Timestamp{Seconds: 1296000000, Nanos: 0}, true, utcDate(2011, 1, 26)}, - // A date after the epoch, in the middle of the day. - {&tspb.Timestamp{Seconds: 1296012345, Nanos: 940483}, true, - time.Date(2011, 1, 26, 3, 25, 45, 940483, time.UTC)}, -} - -func TestValidateTimestamp(t *testing.T) { - for _, s := range tests { - got := validateTimestamp(s.ts) - if (got == nil) != s.valid { - t.Errorf("validateTimestamp(%v) = %v, want %v", s.ts, got, s.valid) - } - } -} - -func TestTimestamp(t *testing.T) { - for _, s := range tests { - got, err := Timestamp(s.ts) - if (err == nil) != s.valid { - t.Errorf("Timestamp(%v) error = %v, but valid = %t", s.ts, err, s.valid) - } else if s.valid && got != s.t { - t.Errorf("Timestamp(%v) = %v, want %v", s.ts, got, s.t) - } - } - // Special case: a nil Timestamp is an error, but returns the 0 Unix time. - got, err := Timestamp(nil) - want := time.Unix(0, 0).UTC() - if got != want { - t.Errorf("Timestamp(nil) = %v, want %v", got, want) - } - if err == nil { - t.Errorf("Timestamp(nil) error = nil, expected error") - } -} - -func TestTimestampProto(t *testing.T) { - for _, s := range tests { - got, err := TimestampProto(s.t) - if (err == nil) != s.valid { - t.Errorf("TimestampProto(%v) error = %v, but valid = %t", s.t, err, s.valid) - } else if s.valid && !proto.Equal(got, s.ts) { - t.Errorf("TimestampProto(%v) = %v, want %v", s.t, got, s.ts) - } - } - // No corresponding special case here: no time.Time results in a nil Timestamp. -} - -func TestTimestampString(t *testing.T) { - for _, test := range []struct { - ts *tspb.Timestamp - want string - }{ - // Not much testing needed because presumably time.Format is - // well-tested. - {&tspb.Timestamp{Seconds: 0, Nanos: 0}, "1970-01-01T00:00:00Z"}, - {&tspb.Timestamp{Seconds: minValidSeconds - 1, Nanos: 0}, "(timestamp: seconds:-62135596801 before 0001-01-01)"}, - } { - got := TimestampString(test.ts) - if got != test.want { - t.Errorf("TimestampString(%v) = %q, want %q", test.ts, got, test.want) - } - } -} - -func utcDate(year, month, day int) time.Time { - return time.Date(year, time.Month(month), day, 0, 0, 0, 0, time.UTC) -} - -func TestTimestampNow(t *testing.T) { - // Bracket the expected time. - before := time.Now() - ts := TimestampNow() - after := time.Now() - - tm, err := Timestamp(ts) - if err != nil { - t.Errorf("between %v and %v\nTimestampNow() = %v\nwhich is invalid (%v)", before, after, ts, err) - } - if tm.Before(before) || tm.After(after) { - t.Errorf("between %v and %v\nTimestamp(TimestampNow()) = %v", before, after, tm) - } -} diff --git a/vendor/github.com/golang/snappy/.gitignore b/vendor/github.com/golang/snappy/.gitignore deleted file mode 100644 index 042091d9b..000000000 --- a/vendor/github.com/golang/snappy/.gitignore +++ /dev/null @@ -1,16 +0,0 @@ -cmd/snappytool/snappytool -testdata/bench - -# These explicitly listed benchmark data files are for an obsolete version of -# snappy_test.go. -testdata/alice29.txt -testdata/asyoulik.txt -testdata/fireworks.jpeg -testdata/geo.protodata -testdata/html -testdata/html_x_4 -testdata/kppkn.gtb -testdata/lcet10.txt -testdata/paper-100k.pdf -testdata/plrabn12.txt -testdata/urls.10K diff --git a/vendor/github.com/golang/snappy/README b/vendor/github.com/golang/snappy/README deleted file mode 100644 index cea12879a..000000000 --- a/vendor/github.com/golang/snappy/README +++ /dev/null @@ -1,107 +0,0 @@ -The Snappy compression format in the Go programming language. - -To download and install from source: -$ go get github.com/golang/snappy - -Unless otherwise noted, the Snappy-Go source files are distributed -under the BSD-style license found in the LICENSE file. - - - -Benchmarks. - -The golang/snappy benchmarks include compressing (Z) and decompressing (U) ten -or so files, the same set used by the C++ Snappy code (github.com/google/snappy -and note the "google", not "golang"). On an "Intel(R) Core(TM) i7-3770 CPU @ -3.40GHz", Go's GOARCH=amd64 numbers as of 2016-05-29: - -"go test -test.bench=." - -_UFlat0-8 2.19GB/s ± 0% html -_UFlat1-8 1.41GB/s ± 0% urls -_UFlat2-8 23.5GB/s ± 2% jpg -_UFlat3-8 1.91GB/s ± 0% jpg_200 -_UFlat4-8 14.0GB/s ± 1% pdf -_UFlat5-8 1.97GB/s ± 0% html4 -_UFlat6-8 814MB/s ± 0% txt1 -_UFlat7-8 785MB/s ± 0% txt2 -_UFlat8-8 857MB/s ± 0% txt3 -_UFlat9-8 719MB/s ± 1% txt4 -_UFlat10-8 2.84GB/s ± 0% pb -_UFlat11-8 1.05GB/s ± 0% gaviota - -_ZFlat0-8 1.04GB/s ± 0% html -_ZFlat1-8 534MB/s ± 0% urls -_ZFlat2-8 15.7GB/s ± 1% jpg -_ZFlat3-8 740MB/s ± 3% jpg_200 -_ZFlat4-8 9.20GB/s ± 1% pdf -_ZFlat5-8 991MB/s ± 0% html4 -_ZFlat6-8 379MB/s ± 0% txt1 -_ZFlat7-8 352MB/s ± 0% txt2 -_ZFlat8-8 396MB/s ± 1% txt3 -_ZFlat9-8 327MB/s ± 1% txt4 -_ZFlat10-8 1.33GB/s ± 1% pb -_ZFlat11-8 605MB/s ± 1% gaviota - - - -"go test -test.bench=. -tags=noasm" - -_UFlat0-8 621MB/s ± 2% html -_UFlat1-8 494MB/s ± 1% urls -_UFlat2-8 23.2GB/s ± 1% jpg -_UFlat3-8 1.12GB/s ± 1% jpg_200 -_UFlat4-8 4.35GB/s ± 1% pdf -_UFlat5-8 609MB/s ± 0% html4 -_UFlat6-8 296MB/s ± 0% txt1 -_UFlat7-8 288MB/s ± 0% txt2 -_UFlat8-8 309MB/s ± 1% txt3 -_UFlat9-8 280MB/s ± 1% txt4 -_UFlat10-8 753MB/s ± 0% pb -_UFlat11-8 400MB/s ± 0% gaviota - -_ZFlat0-8 409MB/s ± 1% html -_ZFlat1-8 250MB/s ± 1% urls -_ZFlat2-8 12.3GB/s ± 1% jpg -_ZFlat3-8 132MB/s ± 0% jpg_200 -_ZFlat4-8 2.92GB/s ± 0% pdf -_ZFlat5-8 405MB/s ± 1% html4 -_ZFlat6-8 179MB/s ± 1% txt1 -_ZFlat7-8 170MB/s ± 1% txt2 -_ZFlat8-8 189MB/s ± 1% txt3 -_ZFlat9-8 164MB/s ± 1% txt4 -_ZFlat10-8 479MB/s ± 1% pb -_ZFlat11-8 270MB/s ± 1% gaviota - - - -For comparison (Go's encoded output is byte-for-byte identical to C++'s), here -are the numbers from C++ Snappy's - -make CXXFLAGS="-O2 -DNDEBUG -g" clean snappy_unittest.log && cat snappy_unittest.log - -BM_UFlat/0 2.4GB/s html -BM_UFlat/1 1.4GB/s urls -BM_UFlat/2 21.8GB/s jpg -BM_UFlat/3 1.5GB/s jpg_200 -BM_UFlat/4 13.3GB/s pdf -BM_UFlat/5 2.1GB/s html4 -BM_UFlat/6 1.0GB/s txt1 -BM_UFlat/7 959.4MB/s txt2 -BM_UFlat/8 1.0GB/s txt3 -BM_UFlat/9 864.5MB/s txt4 -BM_UFlat/10 2.9GB/s pb -BM_UFlat/11 1.2GB/s gaviota - -BM_ZFlat/0 944.3MB/s html (22.31 %) -BM_ZFlat/1 501.6MB/s urls (47.78 %) -BM_ZFlat/2 14.3GB/s jpg (99.95 %) -BM_ZFlat/3 538.3MB/s jpg_200 (73.00 %) -BM_ZFlat/4 8.3GB/s pdf (83.30 %) -BM_ZFlat/5 903.5MB/s html4 (22.52 %) -BM_ZFlat/6 336.0MB/s txt1 (57.88 %) -BM_ZFlat/7 312.3MB/s txt2 (61.91 %) -BM_ZFlat/8 353.1MB/s txt3 (54.99 %) -BM_ZFlat/9 289.9MB/s txt4 (66.26 %) -BM_ZFlat/10 1.2GB/s pb (19.68 %) -BM_ZFlat/11 527.4MB/s gaviota (37.72 %) diff --git a/vendor/github.com/golang/snappy/golden_test.go b/vendor/github.com/golang/snappy/golden_test.go deleted file mode 100644 index e4496f92e..000000000 --- a/vendor/github.com/golang/snappy/golden_test.go +++ /dev/null @@ -1,1965 +0,0 @@ -// Copyright 2016 The Snappy-Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package snappy - -// extendMatchGoldenTestCases is the i and j arguments, and the returned value, -// for every extendMatch call issued when encoding the -// testdata/Mark.Twain-Tom.Sawyer.txt file. It is used to benchmark the -// extendMatch implementation. -// -// It was generated manually by adding some print statements to the (pure Go) -// extendMatch implementation: -// -// func extendMatch(src []byte, i, j int) int { -// i0, j0 := i, j -// for ; j < len(src) && src[i] == src[j]; i, j = i+1, j+1 { -// } -// println("{", i0, ",", j0, ",", j, "},") -// return j -// } -// -// and running "go test -test.run=EncodeGoldenInput -tags=noasm". -var extendMatchGoldenTestCases = []struct { - i, j, want int -}{ - {11, 61, 62}, - {80, 81, 82}, - {86, 87, 101}, - {85, 133, 149}, - {152, 153, 162}, - {133, 168, 193}, - {168, 207, 225}, - {81, 255, 275}, - {278, 279, 283}, - {306, 417, 417}, - {373, 428, 430}, - {389, 444, 447}, - {474, 510, 512}, - {465, 533, 533}, - {47, 547, 547}, - {307, 551, 554}, - {420, 582, 587}, - {309, 604, 604}, - {604, 625, 625}, - {538, 629, 629}, - {328, 640, 640}, - {573, 645, 645}, - {319, 657, 657}, - {30, 664, 664}, - {45, 679, 680}, - {621, 684, 684}, - {376, 700, 700}, - {33, 707, 708}, - {601, 733, 733}, - {334, 744, 745}, - {625, 758, 759}, - {382, 763, 763}, - {550, 769, 771}, - {533, 789, 789}, - {804, 813, 813}, - {342, 841, 842}, - {742, 847, 847}, - {74, 852, 852}, - {810, 864, 864}, - {758, 868, 869}, - {714, 883, 883}, - {582, 889, 891}, - {61, 934, 935}, - {894, 942, 942}, - {939, 949, 949}, - {785, 956, 957}, - {886, 978, 978}, - {792, 998, 998}, - {998, 1005, 1005}, - {572, 1032, 1032}, - {698, 1051, 1053}, - {599, 1067, 1069}, - {1056, 1079, 1079}, - {942, 1089, 1090}, - {831, 1094, 1096}, - {1088, 1100, 1103}, - {732, 1113, 1114}, - {1037, 1118, 1118}, - {872, 1128, 1130}, - {1079, 1140, 1142}, - {332, 1162, 1162}, - {207, 1168, 1186}, - {1189, 1190, 1225}, - {105, 1229, 1230}, - {79, 1256, 1257}, - {1190, 1261, 1283}, - {255, 1306, 1306}, - {1319, 1339, 1358}, - {364, 1370, 1370}, - {955, 1378, 1380}, - {122, 1403, 1403}, - {1325, 1407, 1419}, - {664, 1423, 1424}, - {941, 1461, 1463}, - {867, 1477, 1478}, - {757, 1488, 1489}, - {1140, 1499, 1499}, - {31, 1506, 1506}, - {1487, 1510, 1512}, - {1089, 1520, 1521}, - {1467, 1525, 1529}, - {1394, 1537, 1537}, - {1499, 1541, 1541}, - {367, 1558, 1558}, - {1475, 1564, 1564}, - {1525, 1568, 1571}, - {1541, 1582, 1583}, - {864, 1587, 1588}, - {704, 1597, 1597}, - {336, 1602, 1602}, - {1383, 1613, 1613}, - {1498, 1617, 1618}, - {1051, 1623, 1625}, - {401, 1643, 1645}, - {1072, 1654, 1655}, - {1067, 1667, 1669}, - {699, 1673, 1674}, - {1587, 1683, 1684}, - {920, 1696, 1696}, - {1505, 1710, 1710}, - {1550, 1723, 1723}, - {996, 1727, 1727}, - {833, 1733, 1734}, - {1638, 1739, 1740}, - {1654, 1744, 1744}, - {753, 1761, 1761}, - {1548, 1773, 1773}, - {1568, 1777, 1780}, - {1683, 1793, 1794}, - {948, 1801, 1801}, - {1666, 1805, 1808}, - {1502, 1814, 1814}, - {1696, 1822, 1822}, - {502, 1836, 1837}, - {917, 1843, 1843}, - {1733, 1854, 1855}, - {970, 1859, 1859}, - {310, 1863, 1863}, - {657, 1872, 1872}, - {1005, 1876, 1876}, - {1662, 1880, 1880}, - {904, 1892, 1892}, - {1427, 1910, 1910}, - {1772, 1929, 1930}, - {1822, 1937, 1940}, - {1858, 1949, 1950}, - {1602, 1956, 1956}, - {1150, 1962, 1962}, - {1504, 1966, 1967}, - {51, 1971, 1971}, - {1605, 1979, 1979}, - {1458, 1983, 1988}, - {1536, 2001, 2006}, - {1373, 2014, 2018}, - {1494, 2025, 2025}, - {1667, 2029, 2031}, - {1592, 2035, 2035}, - {330, 2045, 2045}, - {1376, 2053, 2053}, - {1991, 2058, 2059}, - {1635, 2065, 2065}, - {1992, 2073, 2074}, - {2014, 2080, 2081}, - {1546, 2085, 2087}, - {59, 2099, 2099}, - {1996, 2106, 2106}, - {1836, 2110, 2110}, - {2068, 2114, 2114}, - {1338, 2122, 2122}, - {1562, 2128, 2130}, - {1934, 2134, 2134}, - {2114, 2141, 2142}, - {977, 2149, 2150}, - {956, 2154, 2155}, - {1407, 2162, 2162}, - {1773, 2166, 2166}, - {883, 2171, 2171}, - {623, 2175, 2178}, - {1520, 2191, 2192}, - {1162, 2200, 2200}, - {912, 2204, 2204}, - {733, 2208, 2208}, - {1777, 2212, 2215}, - {1532, 2219, 2219}, - {718, 2223, 2225}, - {2069, 2229, 2229}, - {2207, 2245, 2246}, - {1139, 2264, 2264}, - {677, 2274, 2274}, - {2099, 2279, 2279}, - {1863, 2283, 2283}, - {1966, 2305, 2306}, - {2279, 2313, 2313}, - {1628, 2319, 2319}, - {755, 2329, 2329}, - {1461, 2334, 2334}, - {2117, 2340, 2340}, - {2313, 2349, 2349}, - {1859, 2353, 2353}, - {1048, 2362, 2362}, - {895, 2366, 2366}, - {2278, 2373, 2373}, - {1884, 2377, 2377}, - {1402, 2387, 2392}, - {700, 2398, 2398}, - {1971, 2402, 2402}, - {2009, 2419, 2419}, - {1441, 2426, 2428}, - {2208, 2432, 2432}, - {2038, 2436, 2436}, - {932, 2443, 2443}, - {1759, 2447, 2448}, - {744, 2452, 2452}, - {1875, 2458, 2458}, - {2405, 2468, 2468}, - {1596, 2472, 2473}, - {1953, 2480, 2482}, - {736, 2487, 2487}, - {1913, 2493, 2493}, - {774, 2497, 2497}, - {1484, 2506, 2508}, - {2432, 2512, 2512}, - {752, 2519, 2519}, - {2497, 2523, 2523}, - {2409, 2528, 2529}, - {2122, 2533, 2533}, - {2396, 2537, 2538}, - {2410, 2547, 2548}, - {1093, 2555, 2560}, - {551, 2564, 2565}, - {2268, 2569, 2569}, - {1362, 2580, 2580}, - {1916, 2584, 2585}, - {994, 2589, 2590}, - {1979, 2596, 2596}, - {1041, 2602, 2602}, - {2104, 2614, 2616}, - {2609, 2621, 2628}, - {2329, 2638, 2638}, - {2211, 2657, 2658}, - {2638, 2662, 2667}, - {2578, 2676, 2679}, - {2153, 2685, 2686}, - {2608, 2696, 2697}, - {598, 2712, 2712}, - {2620, 2719, 2720}, - {1888, 2724, 2728}, - {2709, 2732, 2732}, - {1365, 2739, 2739}, - {784, 2747, 2748}, - {424, 2753, 2753}, - {2204, 2759, 2759}, - {812, 2768, 2769}, - {2455, 2773, 2773}, - {1722, 2781, 2781}, - {1917, 2792, 2792}, - {2705, 2799, 2799}, - {2685, 2806, 2807}, - {2742, 2811, 2811}, - {1370, 2818, 2818}, - {2641, 2830, 2830}, - {2512, 2837, 2837}, - {2457, 2841, 2841}, - {2756, 2845, 2845}, - {2719, 2855, 2855}, - {1423, 2859, 2859}, - {2849, 2863, 2865}, - {1474, 2871, 2871}, - {1161, 2875, 2876}, - {2282, 2880, 2881}, - {2746, 2888, 2888}, - {1783, 2893, 2893}, - {2401, 2899, 2900}, - {2632, 2920, 2923}, - {2422, 2928, 2930}, - {2715, 2939, 2939}, - {2162, 2943, 2943}, - {2859, 2947, 2947}, - {1910, 2951, 2951}, - {1431, 2955, 2956}, - {1439, 2964, 2964}, - {2501, 2968, 2969}, - {2029, 2973, 2976}, - {689, 2983, 2984}, - {1658, 2988, 2988}, - {1031, 2996, 2996}, - {2149, 3001, 3002}, - {25, 3009, 3013}, - {2964, 3023, 3023}, - {953, 3027, 3028}, - {2359, 3036, 3036}, - {3023, 3049, 3049}, - {2880, 3055, 3056}, - {2973, 3076, 3077}, - {2874, 3090, 3090}, - {2871, 3094, 3094}, - {2532, 3100, 3100}, - {2938, 3107, 3108}, - {350, 3115, 3115}, - {2196, 3119, 3121}, - {1133, 3127, 3129}, - {1797, 3134, 3150}, - {3032, 3158, 3158}, - {3016, 3172, 3172}, - {2533, 3179, 3179}, - {3055, 3187, 3188}, - {1384, 3192, 3193}, - {2799, 3199, 3199}, - {2126, 3203, 3207}, - {2334, 3215, 3215}, - {2105, 3220, 3221}, - {3199, 3229, 3229}, - {2891, 3233, 3233}, - {855, 3240, 3240}, - {1852, 3253, 3256}, - {2140, 3263, 3263}, - {1682, 3268, 3270}, - {3243, 3274, 3274}, - {924, 3279, 3279}, - {2212, 3283, 3283}, - {2596, 3287, 3287}, - {2999, 3291, 3291}, - {2353, 3295, 3295}, - {2480, 3302, 3304}, - {1959, 3308, 3311}, - {3000, 3318, 3318}, - {845, 3330, 3330}, - {2283, 3334, 3334}, - {2519, 3342, 3342}, - {3325, 3346, 3348}, - {2397, 3353, 3354}, - {2763, 3358, 3358}, - {3198, 3363, 3364}, - {3211, 3368, 3372}, - {2950, 3376, 3377}, - {3245, 3388, 3391}, - {2264, 3398, 3398}, - {795, 3403, 3403}, - {3287, 3407, 3407}, - {3358, 3411, 3411}, - {3317, 3415, 3415}, - {3232, 3431, 3431}, - {2128, 3435, 3437}, - {3236, 3441, 3441}, - {3398, 3445, 3446}, - {2814, 3450, 3450}, - {3394, 3466, 3466}, - {2425, 3470, 3470}, - {3330, 3476, 3476}, - {1612, 3480, 3480}, - {1004, 3485, 3486}, - {2732, 3490, 3490}, - {1117, 3494, 3495}, - {629, 3501, 3501}, - {3087, 3514, 3514}, - {684, 3518, 3518}, - {3489, 3522, 3524}, - {1760, 3529, 3529}, - {617, 3537, 3537}, - {3431, 3541, 3541}, - {997, 3547, 3547}, - {882, 3552, 3553}, - {2419, 3558, 3558}, - {610, 3562, 3563}, - {1903, 3567, 3569}, - {3005, 3575, 3575}, - {3076, 3585, 3586}, - {3541, 3590, 3590}, - {3490, 3594, 3594}, - {1899, 3599, 3599}, - {3545, 3606, 3606}, - {3290, 3614, 3615}, - {2056, 3619, 3620}, - {3556, 3625, 3625}, - {3294, 3632, 3633}, - {637, 3643, 3644}, - {3609, 3648, 3650}, - {3175, 3658, 3658}, - {3498, 3665, 3665}, - {1597, 3669, 3669}, - {1983, 3673, 3673}, - {3215, 3682, 3682}, - {3544, 3689, 3689}, - {3694, 3698, 3698}, - {3228, 3715, 3716}, - {2594, 3720, 3722}, - {3573, 3726, 3726}, - {2479, 3732, 3735}, - {3191, 3741, 3742}, - {1113, 3746, 3747}, - {2844, 3751, 3751}, - {3445, 3756, 3757}, - {3755, 3766, 3766}, - {3421, 3775, 3780}, - {3593, 3784, 3786}, - {3263, 3796, 3796}, - {3469, 3806, 3806}, - {2602, 3815, 3815}, - {723, 3819, 3821}, - {1608, 3826, 3826}, - {3334, 3830, 3830}, - {2198, 3835, 3835}, - {2635, 3840, 3840}, - {3702, 3852, 3853}, - {3406, 3858, 3859}, - {3681, 3867, 3870}, - {3407, 3880, 3880}, - {340, 3889, 3889}, - {3772, 3893, 3893}, - {593, 3897, 3897}, - {2563, 3914, 3916}, - {2981, 3929, 3929}, - {1835, 3933, 3934}, - {3906, 3951, 3951}, - {1459, 3958, 3958}, - {3889, 3974, 3974}, - {2188, 3982, 3982}, - {3220, 3986, 3987}, - {3585, 3991, 3993}, - {3712, 3997, 4001}, - {2805, 4007, 4007}, - {1879, 4012, 4013}, - {3618, 4018, 4018}, - {1145, 4031, 4032}, - {3901, 4037, 4037}, - {2772, 4046, 4047}, - {2802, 4053, 4054}, - {3299, 4058, 4058}, - {3725, 4066, 4066}, - {2271, 4070, 4070}, - {385, 4075, 4076}, - {3624, 4089, 4090}, - {3745, 4096, 4098}, - {1563, 4102, 4102}, - {4045, 4106, 4111}, - {3696, 4115, 4119}, - {3376, 4125, 4126}, - {1880, 4130, 4130}, - {2048, 4140, 4141}, - {2724, 4149, 4149}, - {1767, 4156, 4156}, - {2601, 4164, 4164}, - {2757, 4168, 4168}, - {3974, 4172, 4172}, - {3914, 4178, 4178}, - {516, 4185, 4185}, - {1032, 4189, 4190}, - {3462, 4197, 4198}, - {3805, 4202, 4203}, - {3910, 4207, 4212}, - {3075, 4221, 4221}, - {3756, 4225, 4226}, - {1872, 4236, 4237}, - {3844, 4241, 4241}, - {3991, 4245, 4249}, - {2203, 4258, 4258}, - {3903, 4267, 4268}, - {705, 4272, 4272}, - {1896, 4276, 4276}, - {1955, 4285, 4288}, - {3746, 4302, 4303}, - {2672, 4311, 4311}, - {3969, 4317, 4317}, - {3883, 4322, 4322}, - {1920, 4339, 4340}, - {3527, 4344, 4346}, - {1160, 4358, 4358}, - {3648, 4364, 4366}, - {2711, 4387, 4387}, - {3619, 4391, 4392}, - {1944, 4396, 4396}, - {4369, 4400, 4400}, - {2736, 4404, 4407}, - {2546, 4411, 4412}, - {4390, 4422, 4422}, - {3610, 4426, 4427}, - {4058, 4431, 4431}, - {4374, 4435, 4435}, - {3463, 4445, 4446}, - {1813, 4452, 4452}, - {3669, 4456, 4456}, - {3830, 4460, 4460}, - {421, 4464, 4465}, - {1719, 4471, 4471}, - {3880, 4475, 4475}, - {1834, 4485, 4487}, - {3590, 4491, 4491}, - {442, 4496, 4497}, - {4435, 4501, 4501}, - {3814, 4509, 4509}, - {987, 4513, 4513}, - {4494, 4518, 4521}, - {3218, 4526, 4529}, - {4221, 4537, 4537}, - {2778, 4543, 4545}, - {4422, 4552, 4552}, - {4031, 4558, 4559}, - {4178, 4563, 4563}, - {3726, 4567, 4574}, - {4027, 4578, 4578}, - {4339, 4585, 4587}, - {3796, 4592, 4595}, - {543, 4600, 4613}, - {2855, 4620, 4621}, - {2795, 4627, 4627}, - {3440, 4631, 4632}, - {4279, 4636, 4639}, - {4245, 4643, 4645}, - {4516, 4649, 4650}, - {3133, 4654, 4654}, - {4042, 4658, 4659}, - {3422, 4663, 4663}, - {4046, 4667, 4668}, - {4267, 4672, 4672}, - {4004, 4676, 4677}, - {2490, 4682, 4682}, - {2451, 4697, 4697}, - {3027, 4705, 4705}, - {4028, 4717, 4717}, - {4460, 4721, 4721}, - {2471, 4725, 4727}, - {3090, 4735, 4735}, - {3192, 4739, 4740}, - {3835, 4760, 4760}, - {4540, 4764, 4764}, - {4007, 4772, 4774}, - {619, 4784, 4784}, - {3561, 4789, 4791}, - {3367, 4805, 4805}, - {4490, 4810, 4811}, - {2402, 4815, 4815}, - {3352, 4819, 4822}, - {2773, 4828, 4828}, - {4552, 4832, 4832}, - {2522, 4840, 4841}, - {316, 4847, 4852}, - {4715, 4858, 4858}, - {2959, 4862, 4862}, - {4858, 4868, 4869}, - {2134, 4873, 4873}, - {578, 4878, 4878}, - {4189, 4889, 4890}, - {2229, 4894, 4894}, - {4501, 4898, 4898}, - {2297, 4903, 4903}, - {2933, 4909, 4909}, - {3008, 4913, 4913}, - {3153, 4917, 4917}, - {4819, 4921, 4921}, - {4921, 4932, 4933}, - {4920, 4944, 4945}, - {4814, 4954, 4955}, - {576, 4966, 4966}, - {1854, 4970, 4971}, - {1374, 4975, 4976}, - {3307, 4980, 4980}, - {974, 4984, 4988}, - {4721, 4992, 4992}, - {4898, 4996, 4996}, - {4475, 5006, 5006}, - {3819, 5012, 5012}, - {1948, 5019, 5021}, - {4954, 5027, 5029}, - {3740, 5038, 5040}, - {4763, 5044, 5045}, - {1936, 5051, 5051}, - {4844, 5055, 5060}, - {4215, 5069, 5072}, - {1146, 5076, 5076}, - {3845, 5082, 5082}, - {4865, 5090, 5090}, - {4624, 5094, 5094}, - {4815, 5098, 5098}, - {5006, 5105, 5105}, - {4980, 5109, 5109}, - {4795, 5113, 5115}, - {5043, 5119, 5121}, - {4782, 5129, 5129}, - {3826, 5139, 5139}, - {3876, 5156, 5156}, - {3111, 5167, 5171}, - {1470, 5177, 5177}, - {4431, 5181, 5181}, - {546, 5189, 5189}, - {4225, 5193, 5193}, - {1672, 5199, 5201}, - {4207, 5205, 5209}, - {4220, 5216, 5217}, - {4658, 5224, 5225}, - {3295, 5235, 5235}, - {2436, 5239, 5239}, - {2349, 5246, 5246}, - {2175, 5250, 5250}, - {5180, 5257, 5258}, - {3161, 5263, 5263}, - {5105, 5272, 5272}, - {3552, 5282, 5282}, - {4944, 5299, 5300}, - {4130, 5312, 5313}, - {902, 5323, 5323}, - {913, 5327, 5327}, - {2987, 5333, 5334}, - {5150, 5344, 5344}, - {5249, 5348, 5348}, - {1965, 5358, 5359}, - {5330, 5364, 5364}, - {2012, 5373, 5377}, - {712, 5384, 5386}, - {5235, 5390, 5390}, - {5044, 5398, 5399}, - {564, 5406, 5406}, - {39, 5410, 5410}, - {4642, 5422, 5425}, - {4421, 5437, 5438}, - {2347, 5449, 5449}, - {5333, 5453, 5454}, - {4136, 5458, 5459}, - {3793, 5468, 5468}, - {2243, 5480, 5480}, - {4889, 5492, 5493}, - {4295, 5504, 5504}, - {2785, 5511, 5511}, - {2377, 5518, 5518}, - {3662, 5525, 5525}, - {5097, 5529, 5530}, - {4781, 5537, 5538}, - {4697, 5547, 5548}, - {436, 5552, 5553}, - {5542, 5558, 5558}, - {3692, 5562, 5562}, - {2696, 5568, 5569}, - {4620, 5578, 5578}, - {2898, 5590, 5590}, - {5557, 5596, 5618}, - {2797, 5623, 5625}, - {2792, 5629, 5629}, - {5243, 5633, 5633}, - {5348, 5637, 5637}, - {5547, 5643, 5643}, - {4296, 5654, 5655}, - {5568, 5662, 5662}, - {3001, 5670, 5671}, - {3794, 5679, 5679}, - {4006, 5685, 5686}, - {4969, 5690, 5692}, - {687, 5704, 5704}, - {4563, 5708, 5708}, - {1723, 5738, 5738}, - {649, 5742, 5742}, - {5163, 5748, 5755}, - {3907, 5759, 5759}, - {3074, 5764, 5764}, - {5326, 5771, 5771}, - {2951, 5776, 5776}, - {5181, 5780, 5780}, - {2614, 5785, 5788}, - {4709, 5794, 5794}, - {2784, 5799, 5799}, - {5518, 5803, 5803}, - {4155, 5812, 5815}, - {921, 5819, 5819}, - {5224, 5823, 5824}, - {2853, 5830, 5836}, - {5776, 5840, 5840}, - {2955, 5844, 5845}, - {5745, 5853, 5853}, - {3291, 5857, 5857}, - {2988, 5861, 5861}, - {2647, 5865, 5865}, - {5398, 5869, 5870}, - {1085, 5874, 5875}, - {4906, 5881, 5881}, - {802, 5886, 5886}, - {5119, 5890, 5893}, - {5802, 5899, 5900}, - {3415, 5904, 5904}, - {5629, 5908, 5908}, - {3714, 5912, 5914}, - {5558, 5921, 5921}, - {2710, 5927, 5928}, - {1094, 5932, 5934}, - {2653, 5940, 5941}, - {4735, 5954, 5954}, - {5861, 5958, 5958}, - {1040, 5971, 5971}, - {5514, 5977, 5977}, - {5048, 5981, 5982}, - {5953, 5992, 5993}, - {3751, 5997, 5997}, - {4991, 6001, 6002}, - {5885, 6006, 6007}, - {5529, 6011, 6012}, - {4974, 6019, 6020}, - {5857, 6024, 6024}, - {3483, 6032, 6032}, - {3594, 6036, 6036}, - {1997, 6040, 6040}, - {5997, 6044, 6047}, - {5197, 6051, 6051}, - {1764, 6055, 6055}, - {6050, 6059, 6059}, - {5239, 6063, 6063}, - {5049, 6067, 6067}, - {5957, 6073, 6074}, - {1022, 6078, 6078}, - {3414, 6083, 6084}, - {3809, 6090, 6090}, - {4562, 6095, 6096}, - {5878, 6104, 6104}, - {594, 6108, 6109}, - {3353, 6115, 6116}, - {4992, 6120, 6121}, - {2424, 6125, 6125}, - {4484, 6130, 6130}, - {3900, 6134, 6135}, - {5793, 6139, 6141}, - {3562, 6145, 6145}, - {1438, 6152, 6153}, - {6058, 6157, 6158}, - {4411, 6162, 6163}, - {4590, 6167, 6171}, - {4748, 6175, 6175}, - {5517, 6183, 6184}, - {6095, 6191, 6192}, - {1471, 6203, 6203}, - {2643, 6209, 6210}, - {450, 6220, 6220}, - {5266, 6226, 6226}, - {2576, 6233, 6233}, - {2607, 6239, 6240}, - {5164, 6244, 6251}, - {6054, 6255, 6255}, - {1789, 6260, 6261}, - {5250, 6265, 6265}, - {6062, 6273, 6278}, - {5990, 6282, 6282}, - {3283, 6286, 6286}, - {5436, 6290, 6290}, - {6059, 6294, 6294}, - {5668, 6298, 6300}, - {3072, 6324, 6329}, - {3132, 6338, 6339}, - {3246, 6343, 6344}, - {28, 6348, 6349}, - {1503, 6353, 6355}, - {6067, 6359, 6359}, - {3384, 6364, 6364}, - {545, 6375, 6376}, - {5803, 6380, 6380}, - {5522, 6384, 6385}, - {5908, 6389, 6389}, - {2796, 6393, 6396}, - {4831, 6403, 6404}, - {6388, 6412, 6412}, - {6005, 6417, 6420}, - {4450, 6430, 6430}, - {4050, 6435, 6435}, - {5372, 6441, 6441}, - {4378, 6447, 6447}, - {6199, 6452, 6452}, - {3026, 6456, 6456}, - {2642, 6460, 6462}, - {6392, 6470, 6470}, - {6459, 6474, 6474}, - {2829, 6487, 6488}, - {2942, 6499, 6504}, - {5069, 6508, 6511}, - {5341, 6515, 6516}, - {5853, 6521, 6525}, - {6104, 6531, 6531}, - {5759, 6535, 6538}, - {4672, 6542, 6543}, - {2443, 6550, 6550}, - {5109, 6554, 6554}, - {6494, 6558, 6560}, - {6006, 6570, 6572}, - {6424, 6576, 6580}, - {4693, 6591, 6592}, - {6439, 6596, 6597}, - {3179, 6601, 6601}, - {5299, 6606, 6607}, - {4148, 6612, 6613}, - {3774, 6617, 6617}, - {3537, 6623, 6624}, - {4975, 6628, 6629}, - {3848, 6636, 6636}, - {856, 6640, 6640}, - {5724, 6645, 6645}, - {6632, 6651, 6651}, - {4630, 6656, 6658}, - {1440, 6662, 6662}, - {4281, 6666, 6667}, - {4302, 6671, 6672}, - {2589, 6676, 6677}, - {5647, 6681, 6687}, - {6082, 6691, 6693}, - {6144, 6698, 6698}, - {6103, 6709, 6710}, - {3710, 6714, 6714}, - {4253, 6718, 6721}, - {2467, 6730, 6730}, - {4778, 6734, 6734}, - {6528, 6738, 6738}, - {4358, 6747, 6747}, - {5889, 6753, 6753}, - {5193, 6757, 6757}, - {5797, 6761, 6761}, - {3858, 6765, 6766}, - {5951, 6776, 6776}, - {6487, 6781, 6782}, - {3282, 6786, 6787}, - {4667, 6797, 6799}, - {1927, 6803, 6806}, - {6583, 6810, 6810}, - {4937, 6814, 6814}, - {6099, 6824, 6824}, - {4415, 6835, 6836}, - {6332, 6840, 6841}, - {5160, 6850, 6850}, - {4764, 6854, 6854}, - {6814, 6858, 6859}, - {3018, 6864, 6864}, - {6293, 6868, 6869}, - {6359, 6877, 6877}, - {3047, 6884, 6886}, - {5262, 6890, 6891}, - {5471, 6900, 6900}, - {3268, 6910, 6912}, - {1047, 6916, 6916}, - {5904, 6923, 6923}, - {5798, 6933, 6938}, - {4149, 6942, 6942}, - {1821, 6946, 6946}, - {3599, 6952, 6952}, - {6470, 6957, 6957}, - {5562, 6961, 6961}, - {6268, 6965, 6967}, - {6389, 6971, 6971}, - {6596, 6975, 6976}, - {6553, 6980, 6981}, - {6576, 6985, 6989}, - {1375, 6993, 6993}, - {652, 6998, 6998}, - {4876, 7002, 7003}, - {5768, 7011, 7013}, - {3973, 7017, 7017}, - {6802, 7025, 7025}, - {6955, 7034, 7036}, - {6974, 7040, 7040}, - {5944, 7044, 7044}, - {6992, 7048, 7054}, - {6872, 7059, 7059}, - {2943, 7063, 7063}, - {6923, 7067, 7067}, - {5094, 7071, 7071}, - {4873, 7075, 7075}, - {5819, 7079, 7079}, - {5945, 7085, 7085}, - {1540, 7090, 7091}, - {2090, 7095, 7095}, - {5024, 7104, 7105}, - {6900, 7109, 7109}, - {6024, 7113, 7114}, - {6000, 7118, 7120}, - {2187, 7124, 7125}, - {6760, 7129, 7130}, - {5898, 7134, 7136}, - {7032, 7144, 7144}, - {4271, 7148, 7148}, - {3706, 7152, 7152}, - {6970, 7156, 7157}, - {7088, 7161, 7163}, - {2718, 7168, 7169}, - {5674, 7175, 7175}, - {4631, 7182, 7182}, - {7070, 7188, 7189}, - {6220, 7196, 7196}, - {3458, 7201, 7202}, - {2041, 7211, 7212}, - {1454, 7216, 7216}, - {5199, 7225, 7227}, - {3529, 7234, 7234}, - {6890, 7238, 7238}, - {3815, 7242, 7243}, - {5490, 7250, 7253}, - {6554, 7257, 7263}, - {5890, 7267, 7269}, - {6877, 7273, 7273}, - {4877, 7277, 7277}, - {2502, 7285, 7285}, - {1483, 7289, 7295}, - {7210, 7304, 7308}, - {6845, 7313, 7316}, - {7219, 7320, 7320}, - {7001, 7325, 7329}, - {6853, 7333, 7334}, - {6120, 7338, 7338}, - {6606, 7342, 7343}, - {7020, 7348, 7350}, - {3509, 7354, 7354}, - {7133, 7359, 7363}, - {3434, 7371, 7374}, - {2787, 7384, 7384}, - {7044, 7388, 7388}, - {6960, 7394, 7395}, - {6676, 7399, 7400}, - {7161, 7404, 7404}, - {7285, 7417, 7418}, - {4558, 7425, 7426}, - {4828, 7430, 7430}, - {6063, 7436, 7436}, - {3597, 7442, 7442}, - {914, 7446, 7446}, - {7320, 7452, 7454}, - {7267, 7458, 7460}, - {5076, 7464, 7464}, - {7430, 7468, 7469}, - {6273, 7473, 7474}, - {7440, 7478, 7487}, - {7348, 7491, 7494}, - {1021, 7510, 7510}, - {7473, 7515, 7515}, - {2823, 7519, 7519}, - {6264, 7527, 7527}, - {7302, 7531, 7531}, - {7089, 7535, 7535}, - {7342, 7540, 7541}, - {3688, 7547, 7551}, - {3054, 7558, 7560}, - {4177, 7566, 7567}, - {6691, 7574, 7575}, - {7156, 7585, 7586}, - {7147, 7590, 7592}, - {7407, 7598, 7598}, - {7403, 7602, 7603}, - {6868, 7607, 7607}, - {6636, 7611, 7611}, - {4805, 7617, 7617}, - {5779, 7623, 7623}, - {7063, 7627, 7627}, - {5079, 7632, 7632}, - {7377, 7637, 7637}, - {7337, 7641, 7642}, - {6738, 7655, 7655}, - {7338, 7659, 7659}, - {6541, 7669, 7671}, - {595, 7675, 7675}, - {7658, 7679, 7680}, - {7647, 7685, 7686}, - {2477, 7690, 7690}, - {5823, 7694, 7694}, - {4156, 7699, 7699}, - {5931, 7703, 7706}, - {6854, 7712, 7712}, - {4931, 7718, 7718}, - {6979, 7722, 7722}, - {5085, 7727, 7727}, - {6965, 7732, 7732}, - {7201, 7736, 7737}, - {3639, 7741, 7743}, - {7534, 7749, 7749}, - {4292, 7753, 7753}, - {3427, 7759, 7763}, - {7273, 7767, 7767}, - {940, 7778, 7778}, - {4838, 7782, 7785}, - {4216, 7790, 7792}, - {922, 7800, 7801}, - {7256, 7810, 7811}, - {7789, 7815, 7819}, - {7225, 7823, 7825}, - {7531, 7829, 7829}, - {6997, 7833, 7833}, - {7757, 7837, 7838}, - {4129, 7842, 7842}, - {7333, 7848, 7849}, - {6776, 7855, 7855}, - {7527, 7859, 7859}, - {4370, 7863, 7863}, - {4512, 7868, 7868}, - {5679, 7880, 7880}, - {3162, 7884, 7885}, - {3933, 7892, 7894}, - {7804, 7899, 7902}, - {6363, 7906, 7907}, - {7848, 7911, 7912}, - {5584, 7917, 7921}, - {874, 7926, 7926}, - {3342, 7930, 7930}, - {4507, 7935, 7937}, - {3672, 7943, 7944}, - {7911, 7948, 7949}, - {6402, 7956, 7956}, - {7940, 7960, 7960}, - {7113, 7964, 7964}, - {1073, 7968, 7968}, - {7740, 7974, 7974}, - {7601, 7978, 7982}, - {6797, 7987, 7988}, - {3528, 7994, 7995}, - {5483, 7999, 7999}, - {5717, 8011, 8011}, - {5480, 8017, 8017}, - {7770, 8023, 8030}, - {2452, 8034, 8034}, - {5282, 8047, 8047}, - {7967, 8051, 8051}, - {1128, 8058, 8066}, - {6348, 8070, 8070}, - {8055, 8077, 8077}, - {7925, 8081, 8086}, - {6810, 8090, 8090}, - {5051, 8101, 8101}, - {4696, 8109, 8110}, - {5129, 8119, 8119}, - {4449, 8123, 8123}, - {7222, 8127, 8127}, - {4649, 8131, 8134}, - {7994, 8138, 8138}, - {5954, 8148, 8148}, - {475, 8152, 8153}, - {7906, 8157, 8157}, - {7458, 8164, 8166}, - {7632, 8171, 8173}, - {3874, 8177, 8183}, - {4391, 8187, 8187}, - {561, 8191, 8191}, - {2417, 8195, 8195}, - {2357, 8204, 8204}, - {2269, 8216, 8218}, - {3968, 8222, 8222}, - {2200, 8226, 8227}, - {3453, 8247, 8247}, - {2439, 8251, 8252}, - {7175, 8257, 8257}, - {976, 8262, 8264}, - {4953, 8273, 8273}, - {4219, 8278, 8278}, - {6, 8285, 8291}, - {5703, 8295, 8296}, - {5272, 8300, 8300}, - {8037, 8304, 8304}, - {8186, 8314, 8314}, - {8304, 8318, 8318}, - {8051, 8326, 8326}, - {8318, 8330, 8330}, - {2671, 8334, 8335}, - {2662, 8339, 8339}, - {8081, 8349, 8350}, - {3328, 8356, 8356}, - {2879, 8360, 8362}, - {8050, 8370, 8371}, - {8330, 8375, 8376}, - {8375, 8386, 8386}, - {4961, 8390, 8390}, - {1017, 8403, 8405}, - {3533, 8416, 8416}, - {4555, 8422, 8422}, - {6445, 8426, 8426}, - {8169, 8432, 8432}, - {990, 8436, 8436}, - {4102, 8440, 8440}, - {7398, 8444, 8446}, - {3480, 8450, 8450}, - {6324, 8462, 8462}, - {7948, 8466, 8467}, - {5950, 8471, 8471}, - {5189, 8476, 8476}, - {4026, 8490, 8490}, - {8374, 8494, 8495}, - {4682, 8501, 8501}, - {7387, 8506, 8506}, - {8164, 8510, 8515}, - {4079, 8524, 8524}, - {8360, 8529, 8531}, - {7446, 8540, 8543}, - {7971, 8547, 8548}, - {4311, 8552, 8552}, - {5204, 8556, 8557}, - {7968, 8562, 8562}, - {7847, 8571, 8573}, - {8547, 8577, 8577}, - {5320, 8581, 8581}, - {8556, 8585, 8586}, - {8504, 8590, 8590}, - {7669, 8602, 8604}, - {5874, 8608, 8609}, - {5828, 8613, 8613}, - {7998, 8617, 8617}, - {8519, 8625, 8625}, - {7250, 8637, 8637}, - {426, 8641, 8641}, - {8436, 8645, 8645}, - {5986, 8649, 8656}, - {8157, 8660, 8660}, - {7182, 8665, 8665}, - {8421, 8675, 8675}, - {8509, 8681, 8681}, - {5137, 8688, 8689}, - {8625, 8694, 8695}, - {5228, 8701, 8702}, - {6661, 8714, 8714}, - {1010, 8719, 8719}, - {6648, 8723, 8723}, - {3500, 8728, 8728}, - {2442, 8735, 8735}, - {8494, 8740, 8741}, - {8171, 8753, 8755}, - {7242, 8763, 8764}, - {4739, 8768, 8769}, - {7079, 8773, 8773}, - {8386, 8777, 8777}, - {8624, 8781, 8787}, - {661, 8791, 8794}, - {8631, 8801, 8801}, - {7753, 8805, 8805}, - {4783, 8809, 8810}, - {1673, 8814, 8815}, - {6623, 8819, 8819}, - {4404, 8823, 8823}, - {8089, 8827, 8828}, - {8773, 8832, 8832}, - {5394, 8836, 8836}, - {6231, 8841, 8843}, - {1015, 8852, 8853}, - {6873, 8857, 8857}, - {6289, 8865, 8865}, - {8577, 8869, 8869}, - {8114, 8873, 8875}, - {8534, 8883, 8883}, - {3007, 8887, 8888}, - {8827, 8892, 8893}, - {4788, 8897, 8900}, - {5698, 8906, 8907}, - {7690, 8911, 8911}, - {6643, 8919, 8919}, - {7206, 8923, 8924}, - {7866, 8929, 8931}, - {8880, 8942, 8942}, - {8630, 8951, 8952}, - {6027, 8958, 8958}, - {7749, 8966, 8967}, - {4932, 8972, 8973}, - {8892, 8980, 8981}, - {634, 9003, 9003}, - {8109, 9007, 9008}, - {8777, 9012, 9012}, - {3981, 9016, 9017}, - {5723, 9025, 9025}, - {7662, 9034, 9038}, - {8955, 9042, 9042}, - {8070, 9060, 9062}, - {8910, 9066, 9066}, - {5363, 9070, 9071}, - {7699, 9075, 9076}, - {8991, 9081, 9081}, - {6850, 9085, 9085}, - {5811, 9092, 9094}, - {9079, 9098, 9102}, - {6456, 9106, 9106}, - {2259, 9111, 9111}, - {4752, 9116, 9116}, - {9060, 9120, 9123}, - {8090, 9127, 9127}, - {5305, 9131, 9132}, - {8623, 9137, 9137}, - {7417, 9141, 9141}, - {6564, 9148, 9149}, - {9126, 9157, 9158}, - {4285, 9169, 9170}, - {8698, 9174, 9174}, - {8869, 9178, 9178}, - {2572, 9182, 9183}, - {6482, 9188, 9190}, - {9181, 9201, 9201}, - {2968, 9208, 9209}, - {2506, 9213, 9215}, - {9127, 9219, 9219}, - {7910, 9225, 9227}, - {5422, 9235, 9239}, - {8813, 9244, 9246}, - {9178, 9250, 9250}, - {8748, 9255, 9255}, - {7354, 9265, 9265}, - {7767, 9269, 9269}, - {7710, 9281, 9283}, - {8826, 9288, 9290}, - {861, 9295, 9295}, - {4482, 9301, 9301}, - {9264, 9305, 9306}, - {8805, 9310, 9310}, - {4995, 9314, 9314}, - {6730, 9318, 9318}, - {7457, 9328, 9328}, - {2547, 9335, 9336}, - {6298, 9340, 9343}, - {9305, 9353, 9354}, - {9269, 9358, 9358}, - {6338, 9370, 9370}, - {7289, 9376, 9379}, - {5780, 9383, 9383}, - {7607, 9387, 9387}, - {2065, 9392, 9392}, - {7238, 9396, 9396}, - {8856, 9400, 9400}, - {8069, 9412, 9413}, - {611, 9420, 9420}, - {7071, 9424, 9424}, - {3089, 9430, 9431}, - {7117, 9435, 9438}, - {1976, 9445, 9445}, - {6640, 9449, 9449}, - {5488, 9453, 9453}, - {8739, 9457, 9459}, - {5958, 9466, 9466}, - {7985, 9470, 9470}, - {8735, 9475, 9475}, - {5009, 9479, 9479}, - {8073, 9483, 9484}, - {2328, 9490, 9491}, - {9250, 9495, 9495}, - {4043, 9502, 9502}, - {7712, 9506, 9506}, - {9012, 9510, 9510}, - {9028, 9514, 9515}, - {2190, 9521, 9524}, - {9029, 9528, 9528}, - {9519, 9532, 9532}, - {9495, 9536, 9536}, - {8527, 9540, 9540}, - {2137, 9550, 9550}, - {8419, 9557, 9557}, - {9383, 9561, 9562}, - {8970, 9575, 9578}, - {8911, 9582, 9582}, - {7828, 9595, 9596}, - {6180, 9600, 9600}, - {8738, 9604, 9607}, - {7540, 9611, 9612}, - {9599, 9616, 9618}, - {9187, 9623, 9623}, - {9294, 9628, 9629}, - {4536, 9639, 9639}, - {3867, 9643, 9643}, - {6305, 9648, 9648}, - {1617, 9654, 9657}, - {5762, 9666, 9666}, - {8314, 9670, 9670}, - {9666, 9674, 9675}, - {9506, 9679, 9679}, - {9669, 9685, 9686}, - {9683, 9690, 9690}, - {8763, 9697, 9698}, - {7468, 9702, 9702}, - {460, 9707, 9707}, - {3115, 9712, 9712}, - {9424, 9716, 9717}, - {7359, 9721, 9724}, - {7547, 9728, 9729}, - {7151, 9733, 9738}, - {7627, 9742, 9742}, - {2822, 9747, 9747}, - {8247, 9751, 9753}, - {9550, 9758, 9758}, - {7585, 9762, 9763}, - {1002, 9767, 9767}, - {7168, 9772, 9773}, - {6941, 9777, 9780}, - {9728, 9784, 9786}, - {9770, 9792, 9796}, - {6411, 9801, 9802}, - {3689, 9806, 9808}, - {9575, 9814, 9816}, - {7025, 9820, 9821}, - {2776, 9826, 9826}, - {9806, 9830, 9830}, - {9820, 9834, 9835}, - {9800, 9839, 9847}, - {9834, 9851, 9852}, - {9829, 9856, 9862}, - {1400, 9866, 9866}, - {3197, 9870, 9871}, - {9851, 9875, 9876}, - {9742, 9883, 9884}, - {3362, 9888, 9889}, - {9883, 9893, 9893}, - {5711, 9899, 9910}, - {7806, 9915, 9915}, - {9120, 9919, 9919}, - {9715, 9925, 9934}, - {2580, 9938, 9938}, - {4907, 9942, 9944}, - {6239, 9953, 9954}, - {6961, 9963, 9963}, - {5295, 9967, 9968}, - {1915, 9972, 9973}, - {3426, 9983, 9985}, - {9875, 9994, 9995}, - {6942, 9999, 9999}, - {6621, 10005, 10005}, - {7589, 10010, 10012}, - {9286, 10020, 10020}, - {838, 10024, 10024}, - {9980, 10028, 10031}, - {9994, 10035, 10041}, - {2702, 10048, 10051}, - {2621, 10059, 10059}, - {10054, 10065, 10065}, - {8612, 10073, 10074}, - {7033, 10078, 10078}, - {916, 10082, 10082}, - {10035, 10086, 10087}, - {8613, 10097, 10097}, - {9919, 10107, 10108}, - {6133, 10114, 10115}, - {10059, 10119, 10119}, - {10065, 10126, 10127}, - {7732, 10131, 10131}, - {7155, 10135, 10136}, - {6728, 10140, 10140}, - {6162, 10144, 10145}, - {4724, 10150, 10150}, - {1665, 10154, 10154}, - {10126, 10163, 10163}, - {9783, 10168, 10168}, - {1715, 10172, 10173}, - {7152, 10177, 10182}, - {8760, 10187, 10187}, - {7829, 10191, 10191}, - {9679, 10196, 10196}, - {9369, 10201, 10201}, - {2928, 10206, 10208}, - {6951, 10214, 10217}, - {5633, 10221, 10221}, - {7199, 10225, 10225}, - {10118, 10230, 10231}, - {9999, 10235, 10236}, - {10045, 10240, 10249}, - {5565, 10256, 10256}, - {9866, 10261, 10261}, - {10163, 10268, 10268}, - {9869, 10272, 10272}, - {9789, 10276, 10283}, - {10235, 10287, 10288}, - {10214, 10298, 10299}, - {6971, 10303, 10303}, - {3346, 10307, 10307}, - {10185, 10311, 10312}, - {9993, 10318, 10320}, - {2779, 10332, 10334}, - {1726, 10338, 10338}, - {741, 10354, 10360}, - {10230, 10372, 10373}, - {10260, 10384, 10385}, - {10131, 10389, 10398}, - {6946, 10406, 10409}, - {10158, 10413, 10420}, - {10123, 10424, 10424}, - {6157, 10428, 10429}, - {4518, 10434, 10434}, - {9893, 10438, 10438}, - {9865, 10442, 10446}, - {7558, 10454, 10454}, - {10434, 10460, 10460}, - {10064, 10466, 10468}, - {2703, 10472, 10474}, - {9751, 10478, 10479}, - {6714, 10485, 10485}, - {8020, 10490, 10490}, - {10303, 10494, 10494}, - {3521, 10499, 10500}, - {9281, 10513, 10515}, - {6028, 10519, 10523}, - {9387, 10527, 10527}, - {7614, 10531, 10531}, - {3611, 10536, 10536}, - {9162, 10540, 10540}, - {10081, 10546, 10547}, - {10034, 10560, 10562}, - {6726, 10567, 10571}, - {8237, 10575, 10575}, - {10438, 10579, 10583}, - {10140, 10587, 10587}, - {5784, 10592, 10592}, - {9819, 10597, 10600}, - {10567, 10604, 10608}, - {9335, 10613, 10613}, - {8300, 10617, 10617}, - {10575, 10621, 10621}, - {9678, 10625, 10626}, - {9962, 10632, 10633}, - {10535, 10637, 10638}, - {8199, 10642, 10642}, - {10372, 10647, 10648}, - {10637, 10656, 10657}, - {10579, 10667, 10668}, - {10465, 10677, 10680}, - {6702, 10684, 10685}, - {10073, 10691, 10692}, - {4505, 10696, 10697}, - {9042, 10701, 10701}, - {6460, 10705, 10706}, - {10010, 10714, 10716}, - {10656, 10720, 10722}, - {7282, 10727, 10729}, - {2327, 10733, 10733}, - {2491, 10740, 10741}, - {10704, 10748, 10750}, - {6465, 10754, 10754}, - {10647, 10758, 10759}, - {10424, 10763, 10763}, - {10748, 10776, 10776}, - {10546, 10780, 10781}, - {10758, 10785, 10786}, - {10287, 10790, 10797}, - {10785, 10801, 10807}, - {10240, 10811, 10826}, - {9509, 10830, 10830}, - {2579, 10836, 10838}, - {9801, 10843, 10845}, - {7555, 10849, 10850}, - {10776, 10860, 10865}, - {8023, 10869, 10869}, - {10046, 10876, 10884}, - {10253, 10888, 10892}, - {9941, 10897, 10897}, - {7898, 10901, 10905}, - {6725, 10909, 10913}, - {10757, 10921, 10923}, - {10160, 10931, 10931}, - {10916, 10935, 10942}, - {10261, 10946, 10946}, - {10318, 10952, 10954}, - {5911, 10959, 10961}, - {10801, 10965, 10966}, - {10946, 10970, 10977}, - {10592, 10982, 10984}, - {9913, 10988, 10990}, - {8510, 10994, 10996}, - {9419, 11000, 11001}, - {6765, 11006, 11007}, - {10725, 11011, 11011}, - {5537, 11017, 11019}, - {9208, 11024, 11025}, - {5850, 11030, 11030}, - {9610, 11034, 11036}, - {8846, 11041, 11047}, - {9697, 11051, 11051}, - {1622, 11055, 11058}, - {2370, 11062, 11062}, - {8393, 11067, 11067}, - {9756, 11071, 11071}, - {10172, 11076, 11076}, - {27, 11081, 11081}, - {7357, 11087, 11092}, - {8151, 11104, 11106}, - {6115, 11110, 11110}, - {10667, 11114, 11115}, - {11099, 11121, 11123}, - {10705, 11127, 11127}, - {8938, 11131, 11131}, - {11114, 11135, 11136}, - {1390, 11140, 11141}, - {10964, 11146, 11148}, - {11140, 11152, 11155}, - {9813, 11159, 11166}, - {624, 11171, 11172}, - {3118, 11177, 11179}, - {11029, 11184, 11186}, - {10186, 11190, 11190}, - {10306, 11196, 11196}, - {8665, 11201, 11201}, - {7382, 11205, 11205}, - {1100, 11210, 11210}, - {2337, 11216, 11217}, - {1609, 11221, 11223}, - {5763, 11228, 11229}, - {5220, 11233, 11233}, - {11061, 11241, 11241}, - {10617, 11246, 11246}, - {11190, 11250, 11251}, - {10144, 11255, 11256}, - {11232, 11260, 11260}, - {857, 11264, 11265}, - {10994, 11269, 11271}, - {3879, 11280, 11281}, - {11184, 11287, 11289}, - {9611, 11293, 11295}, - {11250, 11299, 11299}, - {4495, 11304, 11304}, - {7574, 11308, 11309}, - {9814, 11315, 11317}, - {1713, 11321, 11324}, - {1905, 11328, 11328}, - {8745, 11335, 11340}, - {8883, 11351, 11351}, - {8119, 11358, 11358}, - {1842, 11363, 11364}, - {11237, 11368, 11368}, - {8814, 11373, 11374}, - {5684, 11378, 11378}, - {11011, 11382, 11382}, - {6520, 11389, 11389}, - {11183, 11393, 11396}, - {1790, 11404, 11404}, - {9536, 11408, 11408}, - {11298, 11418, 11419}, - {3929, 11425, 11425}, - {5588, 11429, 11429}, - {8476, 11436, 11436}, - {4096, 11440, 11442}, - {11084, 11446, 11454}, - {10603, 11458, 11463}, - {7332, 11472, 11474}, - {7611, 11483, 11486}, - {4836, 11490, 11491}, - {10024, 11495, 11495}, - {4917, 11501, 11506}, - {6486, 11510, 11512}, - {11269, 11516, 11518}, - {3603, 11522, 11525}, - {11126, 11535, 11535}, - {11418, 11539, 11541}, - {11408, 11545, 11545}, - {9021, 11549, 11552}, - {6745, 11557, 11557}, - {5118, 11561, 11564}, - {7590, 11568, 11569}, - {4426, 11573, 11578}, - {9790, 11582, 11583}, - {6447, 11587, 11587}, - {10229, 11591, 11594}, - {10457, 11598, 11598}, - {10168, 11604, 11604}, - {10543, 11608, 11608}, - {7404, 11612, 11612}, - {11127, 11616, 11616}, - {3337, 11620, 11620}, - {11501, 11624, 11628}, - {4543, 11633, 11635}, - {8449, 11642, 11642}, - {4943, 11646, 11648}, - {10526, 11652, 11654}, - {11620, 11659, 11659}, - {8927, 11664, 11669}, - {532, 11673, 11673}, - {10513, 11677, 11679}, - {10428, 11683, 11683}, - {10999, 11689, 11690}, - {9469, 11695, 11695}, - {3606, 11699, 11699}, - {9560, 11708, 11709}, - {1564, 11714, 11714}, - {10527, 11718, 11718}, - {3071, 11723, 11726}, - {11590, 11731, 11732}, - {6605, 11737, 11737}, - {11624, 11741, 11745}, - {7822, 11749, 11752}, - {5269, 11757, 11758}, - {1339, 11767, 11767}, - {1363, 11771, 11773}, - {3704, 11777, 11777}, - {10952, 11781, 11783}, - {6764, 11793, 11795}, - {8675, 11800, 11800}, - {9963, 11804, 11804}, - {11573, 11808, 11809}, - {9548, 11813, 11813}, - {11591, 11817, 11818}, - {11446, 11822, 11822}, - {9224, 11828, 11828}, - {3158, 11836, 11836}, - {10830, 11840, 11840}, - {7234, 11846, 11846}, - {11299, 11850, 11850}, - {11544, 11854, 11855}, - {11498, 11859, 11859}, - {10993, 11865, 11868}, - {9720, 11872, 11878}, - {10489, 11882, 11890}, - {11712, 11898, 11904}, - {11516, 11908, 11910}, - {11568, 11914, 11915}, - {10177, 11919, 11924}, - {11363, 11928, 11929}, - {10494, 11933, 11933}, - {9870, 11937, 11938}, - {9427, 11942, 11942}, - {11481, 11949, 11949}, - {6030, 11955, 11957}, - {11718, 11961, 11961}, - {10531, 11965, 11983}, - {5126, 11987, 11987}, - {7515, 11991, 11991}, - {10646, 11996, 11997}, - {2947, 12001, 12001}, - {9582, 12009, 12010}, - {6202, 12017, 12018}, - {11714, 12022, 12022}, - {9235, 12033, 12037}, - {9721, 12041, 12044}, - {11932, 12051, 12052}, - {12040, 12056, 12056}, - {12051, 12060, 12060}, - {11601, 12066, 12066}, - {8426, 12070, 12070}, - {4053, 12077, 12077}, - {4262, 12081, 12081}, - {9761, 12086, 12088}, - {11582, 12092, 12093}, - {10965, 12097, 12098}, - {11803, 12103, 12104}, - {11933, 12108, 12109}, - {10688, 12117, 12117}, - {12107, 12125, 12126}, - {6774, 12130, 12132}, - {6286, 12137, 12137}, - {9543, 12141, 12141}, - {12097, 12145, 12146}, - {10790, 12150, 12150}, - {10125, 12154, 12156}, - {12125, 12164, 12164}, - {12064, 12168, 12172}, - {10811, 12178, 12188}, - {12092, 12192, 12193}, - {10058, 12197, 12198}, - {11611, 12211, 12212}, - {3459, 12216, 12216}, - {10291, 12225, 12228}, - {12191, 12232, 12234}, - {12145, 12238, 12238}, - {12001, 12242, 12250}, - {3840, 12255, 12255}, - {12216, 12259, 12259}, - {674, 12272, 12272}, - {12141, 12276, 12276}, - {10766, 12280, 12280}, - {11545, 12284, 12284}, - {6496, 12290, 12290}, - {11381, 12294, 12295}, - {603, 12302, 12303}, - {12276, 12308, 12308}, - {11850, 12313, 12314}, - {565, 12319, 12319}, - {9351, 12324, 12324}, - {11822, 12328, 12328}, - {2691, 12333, 12334}, - {11840, 12338, 12338}, - {11070, 12343, 12343}, - {9510, 12347, 12347}, - {11024, 12352, 12353}, - {7173, 12359, 12359}, - {517, 12363, 12363}, - {6311, 12367, 12368}, - {11367, 12372, 12373}, - {12008, 12377, 12377}, - {11372, 12382, 12384}, - {11358, 12391, 12392}, - {11382, 12396, 12396}, - {6882, 12400, 12401}, - {11246, 12405, 12405}, - {8359, 12409, 12412}, - {10154, 12418, 12418}, - {12016, 12425, 12426}, - {8972, 12434, 12435}, - {10478, 12439, 12440}, - {12395, 12449, 12449}, - {11612, 12454, 12454}, - {12347, 12458, 12458}, - {10700, 12466, 12467}, - {3637, 12471, 12476}, - {1042, 12480, 12481}, - {6747, 12488, 12488}, - {12396, 12492, 12493}, - {9420, 12497, 12497}, - {11285, 12501, 12510}, - {4470, 12515, 12515}, - {9374, 12519, 12519}, - {11293, 12528, 12528}, - {2058, 12534, 12535}, - {6521, 12539, 12539}, - {12492, 12543, 12543}, - {3043, 12547, 12547}, - {2982, 12551, 12553}, - {11030, 12557, 12563}, - {7636, 12568, 12568}, - {9639, 12572, 12572}, - {12543, 12576, 12576}, - {5989, 12580, 12583}, - {11051, 12587, 12587}, - {1061, 12592, 12594}, - {12313, 12599, 12601}, - {11846, 12605, 12605}, - {12576, 12609, 12609}, - {11040, 12618, 12625}, - {12479, 12629, 12629}, - {6903, 12633, 12633}, - {12322, 12639, 12639}, - {12253, 12643, 12645}, - {5594, 12651, 12651}, - {12522, 12655, 12655}, - {11703, 12659, 12659}, - {1377, 12665, 12665}, - {8022, 12669, 12669}, - {12280, 12674, 12674}, - {9023, 12680, 12681}, - {12328, 12685, 12685}, - {3085, 12689, 12693}, - {4700, 12698, 12698}, - {10224, 12702, 12702}, - {8781, 12706, 12706}, - {1651, 12710, 12710}, - {12458, 12714, 12714}, - {12005, 12718, 12721}, - {11908, 12725, 12726}, - {8202, 12733, 12733}, - {11708, 12739, 12740}, - {12599, 12744, 12745}, - {12284, 12749, 12749}, - {5285, 12756, 12756}, - {12055, 12775, 12777}, - {6919, 12782, 12782}, - {12242, 12786, 12786}, - {12009, 12790, 12790}, - {9628, 12794, 12796}, - {11354, 12801, 12802}, - {10225, 12806, 12807}, - {579, 12813, 12813}, - {8935, 12817, 12822}, - {8753, 12827, 12829}, - {11006, 12835, 12835}, - {858, 12841, 12845}, - {476, 12849, 12849}, - {7667, 12854, 12854}, - {12760, 12860, 12871}, - {11677, 12875, 12877}, - {12714, 12881, 12881}, - {12731, 12885, 12890}, - {7108, 12894, 12896}, - {1165, 12900, 12900}, - {4021, 12906, 12906}, - {10829, 12910, 12911}, - {12331, 12915, 12915}, - {8887, 12919, 12921}, - {11639, 12925, 12925}, - {7964, 12929, 12929}, - {12528, 12937, 12937}, - {8148, 12941, 12941}, - {12770, 12948, 12950}, - {12609, 12954, 12954}, - {12685, 12958, 12958}, - {2803, 12962, 12962}, - {9561, 12966, 12966}, - {6671, 12972, 12973}, - {12056, 12977, 12977}, - {6380, 12981, 12981}, - {12048, 12985, 12985}, - {11961, 12989, 12993}, - {3368, 12997, 12999}, - {6634, 13004, 13004}, - {6775, 13009, 13010}, - {12136, 13014, 13019}, - {10341, 13023, 13023}, - {13002, 13027, 13027}, - {10587, 13031, 13031}, - {10307, 13035, 13035}, - {12736, 13039, 13039}, - {12744, 13043, 13044}, - {6175, 13048, 13048}, - {9702, 13053, 13054}, - {662, 13059, 13061}, - {12718, 13065, 13068}, - {12893, 13072, 13075}, - {8299, 13086, 13091}, - {12604, 13095, 13096}, - {12848, 13100, 13101}, - {12749, 13105, 13105}, - {12526, 13109, 13114}, - {9173, 13122, 13122}, - {12769, 13128, 13128}, - {13038, 13132, 13132}, - {12725, 13136, 13137}, - {12639, 13146, 13146}, - {9711, 13150, 13151}, - {12137, 13155, 13155}, - {13039, 13159, 13159}, - {4681, 13163, 13164}, - {12954, 13168, 13168}, - {13158, 13175, 13176}, - {13105, 13180, 13180}, - {10754, 13184, 13184}, - {13167, 13188, 13188}, - {12658, 13192, 13192}, - {4294, 13199, 13200}, - {11682, 13204, 13205}, - {11695, 13209, 13209}, - {11076, 13214, 13214}, - {12232, 13218, 13218}, - {9399, 13223, 13224}, - {12880, 13228, 13229}, - {13048, 13234, 13234}, - {9701, 13238, 13239}, - {13209, 13243, 13243}, - {3658, 13248, 13248}, - {3698, 13252, 13254}, - {12237, 13260, 13260}, - {8872, 13266, 13266}, - {12957, 13272, 13273}, - {1393, 13281, 13281}, - {2013, 13285, 13288}, - {4244, 13296, 13299}, - {9428, 13303, 13303}, - {12702, 13307, 13307}, - {13078, 13311, 13311}, - {6071, 13315, 13315}, - {3061, 13319, 13319}, - {2051, 13324, 13324}, - {11560, 13328, 13331}, - {6584, 13336, 13336}, - {8482, 13340, 13340}, - {5331, 13344, 13344}, - {4171, 13348, 13348}, - {8501, 13352, 13352}, - {9219, 13356, 13356}, - {9473, 13360, 13363}, - {12881, 13367, 13367}, - {13065, 13371, 13375}, - {2979, 13379, 13384}, - {1518, 13388, 13388}, - {11177, 13392, 13392}, - {9457, 13398, 13398}, - {12293, 13407, 13410}, - {3697, 13414, 13417}, - {10338, 13425, 13425}, - {13367, 13429, 13429}, - {11074, 13433, 13437}, - {4201, 13441, 13443}, - {1812, 13447, 13448}, - {13360, 13452, 13456}, - {13188, 13463, 13463}, - {9732, 13470, 13470}, - {11332, 13477, 13477}, - {9918, 13487, 13487}, - {6337, 13497, 13497}, - {13429, 13501, 13501}, - {11413, 13505, 13505}, - {4685, 13512, 13513}, - {13136, 13517, 13519}, - {7416, 13528, 13530}, - {12929, 13534, 13534}, - {11110, 13539, 13539}, - {11521, 13543, 13543}, - {12825, 13553, 13553}, - {13447, 13557, 13558}, - {12299, 13562, 13563}, - {9003, 13570, 13570}, - {12500, 13577, 13577}, - {13501, 13581, 13581}, - {9392, 13586, 13586}, - {12454, 13590, 13590}, - {6189, 13595, 13595}, - {13053, 13599, 13599}, - {11881, 13604, 13604}, - {13159, 13608, 13608}, - {4894, 13612, 13612}, - {13221, 13621, 13621}, - {8950, 13625, 13625}, - {13533, 13629, 13629}, - {9633, 13633, 13633}, - {7892, 13637, 13639}, - {13581, 13643, 13643}, - {13616, 13647, 13649}, - {12794, 13653, 13654}, - {8919, 13659, 13659}, - {9674, 13663, 13663}, - {13577, 13668, 13668}, - {12966, 13672, 13672}, - {12659, 13676, 13683}, - {6124, 13688, 13688}, - {9225, 13693, 13695}, - {11833, 13702, 13702}, - {12904, 13709, 13717}, - {13647, 13721, 13722}, - {11687, 13726, 13727}, - {12434, 13731, 13732}, - {12689, 13736, 13742}, - {13168, 13746, 13746}, - {6151, 13751, 13752}, - {11821, 13756, 13757}, - {6467, 13764, 13764}, - {5730, 13769, 13769}, - {5136, 13780, 13780}, - {724, 13784, 13785}, - {13517, 13789, 13791}, - {640, 13795, 13796}, - {7721, 13800, 13802}, - {11121, 13806, 13807}, - {5791, 13811, 13815}, - {12894, 13819, 13819}, - {11100, 13824, 13824}, - {7011, 13830, 13830}, - {7129, 13834, 13837}, - {13833, 13841, 13841}, - {11276, 13847, 13847}, - {13621, 13853, 13853}, - {13589, 13862, 13863}, - {12989, 13867, 13867}, - {12789, 13871, 13871}, - {1239, 13875, 13875}, - {4675, 13879, 13881}, - {4686, 13885, 13885}, - {707, 13889, 13889}, - {5449, 13897, 13898}, - {13867, 13902, 13903}, - {10613, 13908, 13908}, - {13789, 13912, 13914}, - {4451, 13918, 13919}, - {9200, 13924, 13924}, - {2011, 13930, 13930}, - {11433, 13934, 13936}, - {4695, 13942, 13943}, - {9435, 13948, 13951}, - {13688, 13955, 13957}, - {11694, 13961, 13962}, - {5712, 13966, 13966}, - {5991, 13970, 13972}, - {13477, 13976, 13976}, - {10213, 13987, 13987}, - {11839, 13991, 13993}, - {12272, 13997, 13997}, - {6206, 14001, 14001}, - {13179, 14006, 14007}, - {2939, 14011, 14011}, - {12972, 14016, 14017}, - {13918, 14021, 14022}, - {7436, 14026, 14027}, - {7678, 14032, 14034}, - {13586, 14040, 14040}, - {13347, 14044, 14044}, - {13109, 14048, 14051}, - {9244, 14055, 14057}, - {13315, 14061, 14061}, - {13276, 14067, 14067}, - {11435, 14073, 14074}, - {13853, 14078, 14078}, - {13452, 14082, 14082}, - {14044, 14087, 14087}, - {4440, 14091, 14095}, - {4479, 14100, 14103}, - {9395, 14107, 14109}, - {6834, 14119, 14119}, - {10458, 14123, 14124}, - {1429, 14129, 14129}, - {8443, 14135, 14135}, - {10365, 14140, 14140}, - {5267, 14145, 14145}, - {11834, 14151, 14153}, -} diff --git a/vendor/github.com/golang/snappy/snappy_test.go b/vendor/github.com/golang/snappy/snappy_test.go deleted file mode 100644 index 2712710df..000000000 --- a/vendor/github.com/golang/snappy/snappy_test.go +++ /dev/null @@ -1,1353 +0,0 @@ -// Copyright 2011 The Snappy-Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package snappy - -import ( - "bytes" - "encoding/binary" - "flag" - "fmt" - "io" - "io/ioutil" - "math/rand" - "net/http" - "os" - "os/exec" - "path/filepath" - "runtime" - "strings" - "testing" -) - -var ( - download = flag.Bool("download", false, "If true, download any missing files before running benchmarks") - testdataDir = flag.String("testdataDir", "testdata", "Directory containing the test data") - benchdataDir = flag.String("benchdataDir", "testdata/bench", "Directory containing the benchmark data") -) - -// goEncoderShouldMatchCppEncoder is whether to test that the algorithm used by -// Go's encoder matches byte-for-byte what the C++ snappy encoder produces, on -// this GOARCH. There is more than one valid encoding of any given input, and -// there is more than one good algorithm along the frontier of trading off -// throughput for output size. Nonetheless, we presume that the C++ encoder's -// algorithm is a good one and has been tested on a wide range of inputs, so -// matching that exactly should mean that the Go encoder's algorithm is also -// good, without needing to gather our own corpus of test data. -// -// The exact algorithm used by the C++ code is potentially endian dependent, as -// it puns a byte pointer to a uint32 pointer to load, hash and compare 4 bytes -// at a time. The Go implementation is endian agnostic, in that its output is -// the same (as little-endian C++ code), regardless of the CPU's endianness. -// -// Thus, when comparing Go's output to C++ output generated beforehand, such as -// the "testdata/pi.txt.rawsnappy" file generated by C++ code on a little- -// endian system, we can run that test regardless of the runtime.GOARCH value. -// -// When comparing Go's output to dynamically generated C++ output, i.e. the -// result of fork/exec'ing a C++ program, we can run that test only on -// little-endian systems, because the C++ output might be different on -// big-endian systems. The runtime package doesn't export endianness per se, -// but we can restrict this match-C++ test to common little-endian systems. -const goEncoderShouldMatchCppEncoder = runtime.GOARCH == "386" || runtime.GOARCH == "amd64" || runtime.GOARCH == "arm" - -func TestMaxEncodedLenOfMaxBlockSize(t *testing.T) { - got := maxEncodedLenOfMaxBlockSize - want := MaxEncodedLen(maxBlockSize) - if got != want { - t.Fatalf("got %d, want %d", got, want) - } -} - -func cmp(a, b []byte) error { - if bytes.Equal(a, b) { - return nil - } - if len(a) != len(b) { - return fmt.Errorf("got %d bytes, want %d", len(a), len(b)) - } - for i := range a { - if a[i] != b[i] { - return fmt.Errorf("byte #%d: got 0x%02x, want 0x%02x", i, a[i], b[i]) - } - } - return nil -} - -func roundtrip(b, ebuf, dbuf []byte) error { - d, err := Decode(dbuf, Encode(ebuf, b)) - if err != nil { - return fmt.Errorf("decoding error: %v", err) - } - if err := cmp(d, b); err != nil { - return fmt.Errorf("roundtrip mismatch: %v", err) - } - return nil -} - -func TestEmpty(t *testing.T) { - if err := roundtrip(nil, nil, nil); err != nil { - t.Fatal(err) - } -} - -func TestSmallCopy(t *testing.T) { - for _, ebuf := range [][]byte{nil, make([]byte, 20), make([]byte, 64)} { - for _, dbuf := range [][]byte{nil, make([]byte, 20), make([]byte, 64)} { - for i := 0; i < 32; i++ { - s := "aaaa" + strings.Repeat("b", i) + "aaaabbbb" - if err := roundtrip([]byte(s), ebuf, dbuf); err != nil { - t.Errorf("len(ebuf)=%d, len(dbuf)=%d, i=%d: %v", len(ebuf), len(dbuf), i, err) - } - } - } - } -} - -func TestSmallRand(t *testing.T) { - rng := rand.New(rand.NewSource(1)) - for n := 1; n < 20000; n += 23 { - b := make([]byte, n) - for i := range b { - b[i] = uint8(rng.Intn(256)) - } - if err := roundtrip(b, nil, nil); err != nil { - t.Fatal(err) - } - } -} - -func TestSmallRegular(t *testing.T) { - for n := 1; n < 20000; n += 23 { - b := make([]byte, n) - for i := range b { - b[i] = uint8(i%10 + 'a') - } - if err := roundtrip(b, nil, nil); err != nil { - t.Fatal(err) - } - } -} - -func TestInvalidVarint(t *testing.T) { - testCases := []struct { - desc string - input string - }{{ - "invalid varint, final byte has continuation bit set", - "\xff", - }, { - "invalid varint, value overflows uint64", - "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x00", - }, { - // https://github.com/google/snappy/blob/master/format_description.txt - // says that "the stream starts with the uncompressed length [as a - // varint] (up to a maximum of 2^32 - 1)". - "valid varint (as uint64), but value overflows uint32", - "\x80\x80\x80\x80\x10", - }} - - for _, tc := range testCases { - input := []byte(tc.input) - if _, err := DecodedLen(input); err != ErrCorrupt { - t.Errorf("%s: DecodedLen: got %v, want ErrCorrupt", tc.desc, err) - } - if _, err := Decode(nil, input); err != ErrCorrupt { - t.Errorf("%s: Decode: got %v, want ErrCorrupt", tc.desc, err) - } - } -} - -func TestDecode(t *testing.T) { - lit40Bytes := make([]byte, 40) - for i := range lit40Bytes { - lit40Bytes[i] = byte(i) - } - lit40 := string(lit40Bytes) - - testCases := []struct { - desc string - input string - want string - wantErr error - }{{ - `decodedLen=0; valid input`, - "\x00", - "", - nil, - }, { - `decodedLen=3; tagLiteral, 0-byte length; length=3; valid input`, - "\x03" + "\x08\xff\xff\xff", - "\xff\xff\xff", - nil, - }, { - `decodedLen=2; tagLiteral, 0-byte length; length=3; not enough dst bytes`, - "\x02" + "\x08\xff\xff\xff", - "", - ErrCorrupt, - }, { - `decodedLen=3; tagLiteral, 0-byte length; length=3; not enough src bytes`, - "\x03" + "\x08\xff\xff", - "", - ErrCorrupt, - }, { - `decodedLen=40; tagLiteral, 0-byte length; length=40; valid input`, - "\x28" + "\x9c" + lit40, - lit40, - nil, - }, { - `decodedLen=1; tagLiteral, 1-byte length; not enough length bytes`, - "\x01" + "\xf0", - "", - ErrCorrupt, - }, { - `decodedLen=3; tagLiteral, 1-byte length; length=3; valid input`, - "\x03" + "\xf0\x02\xff\xff\xff", - "\xff\xff\xff", - nil, - }, { - `decodedLen=1; tagLiteral, 2-byte length; not enough length bytes`, - "\x01" + "\xf4\x00", - "", - ErrCorrupt, - }, { - `decodedLen=3; tagLiteral, 2-byte length; length=3; valid input`, - "\x03" + "\xf4\x02\x00\xff\xff\xff", - "\xff\xff\xff", - nil, - }, { - `decodedLen=1; tagLiteral, 3-byte length; not enough length bytes`, - "\x01" + "\xf8\x00\x00", - "", - ErrCorrupt, - }, { - `decodedLen=3; tagLiteral, 3-byte length; length=3; valid input`, - "\x03" + "\xf8\x02\x00\x00\xff\xff\xff", - "\xff\xff\xff", - nil, - }, { - `decodedLen=1; tagLiteral, 4-byte length; not enough length bytes`, - "\x01" + "\xfc\x00\x00\x00", - "", - ErrCorrupt, - }, { - `decodedLen=1; tagLiteral, 4-byte length; length=3; not enough dst bytes`, - "\x01" + "\xfc\x02\x00\x00\x00\xff\xff\xff", - "", - ErrCorrupt, - }, { - `decodedLen=4; tagLiteral, 4-byte length; length=3; not enough src bytes`, - "\x04" + "\xfc\x02\x00\x00\x00\xff", - "", - ErrCorrupt, - }, { - `decodedLen=3; tagLiteral, 4-byte length; length=3; valid input`, - "\x03" + "\xfc\x02\x00\x00\x00\xff\xff\xff", - "\xff\xff\xff", - nil, - }, { - `decodedLen=4; tagCopy1, 1 extra length|offset byte; not enough extra bytes`, - "\x04" + "\x01", - "", - ErrCorrupt, - }, { - `decodedLen=4; tagCopy2, 2 extra length|offset bytes; not enough extra bytes`, - "\x04" + "\x02\x00", - "", - ErrCorrupt, - }, { - `decodedLen=4; tagCopy4, 4 extra length|offset bytes; not enough extra bytes`, - "\x04" + "\x03\x00\x00\x00", - "", - ErrCorrupt, - }, { - `decodedLen=4; tagLiteral (4 bytes "abcd"); valid input`, - "\x04" + "\x0cabcd", - "abcd", - nil, - }, { - `decodedLen=13; tagLiteral (4 bytes "abcd"); tagCopy1; length=9 offset=4; valid input`, - "\x0d" + "\x0cabcd" + "\x15\x04", - "abcdabcdabcda", - nil, - }, { - `decodedLen=8; tagLiteral (4 bytes "abcd"); tagCopy1; length=4 offset=4; valid input`, - "\x08" + "\x0cabcd" + "\x01\x04", - "abcdabcd", - nil, - }, { - `decodedLen=8; tagLiteral (4 bytes "abcd"); tagCopy1; length=4 offset=2; valid input`, - "\x08" + "\x0cabcd" + "\x01\x02", - "abcdcdcd", - nil, - }, { - `decodedLen=8; tagLiteral (4 bytes "abcd"); tagCopy1; length=4 offset=1; valid input`, - "\x08" + "\x0cabcd" + "\x01\x01", - "abcddddd", - nil, - }, { - `decodedLen=8; tagLiteral (4 bytes "abcd"); tagCopy1; length=4 offset=0; zero offset`, - "\x08" + "\x0cabcd" + "\x01\x00", - "", - ErrCorrupt, - }, { - `decodedLen=9; tagLiteral (4 bytes "abcd"); tagCopy1; length=4 offset=4; inconsistent dLen`, - "\x09" + "\x0cabcd" + "\x01\x04", - "", - ErrCorrupt, - }, { - `decodedLen=8; tagLiteral (4 bytes "abcd"); tagCopy1; length=4 offset=5; offset too large`, - "\x08" + "\x0cabcd" + "\x01\x05", - "", - ErrCorrupt, - }, { - `decodedLen=7; tagLiteral (4 bytes "abcd"); tagCopy1; length=4 offset=4; length too large`, - "\x07" + "\x0cabcd" + "\x01\x04", - "", - ErrCorrupt, - }, { - `decodedLen=6; tagLiteral (4 bytes "abcd"); tagCopy2; length=2 offset=3; valid input`, - "\x06" + "\x0cabcd" + "\x06\x03\x00", - "abcdbc", - nil, - }, { - `decodedLen=6; tagLiteral (4 bytes "abcd"); tagCopy4; length=2 offset=3; valid input`, - "\x06" + "\x0cabcd" + "\x07\x03\x00\x00\x00", - "abcdbc", - nil, - }} - - const ( - // notPresentXxx defines a range of byte values [0xa0, 0xc5) that are - // not present in either the input or the output. It is written to dBuf - // to check that Decode does not write bytes past the end of - // dBuf[:dLen]. - // - // The magic number 37 was chosen because it is prime. A more 'natural' - // number like 32 might lead to a false negative if, for example, a - // byte was incorrectly copied 4*8 bytes later. - notPresentBase = 0xa0 - notPresentLen = 37 - ) - - var dBuf [100]byte -loop: - for i, tc := range testCases { - input := []byte(tc.input) - for _, x := range input { - if notPresentBase <= x && x < notPresentBase+notPresentLen { - t.Errorf("#%d (%s): input shouldn't contain %#02x\ninput: % x", i, tc.desc, x, input) - continue loop - } - } - - dLen, n := binary.Uvarint(input) - if n <= 0 { - t.Errorf("#%d (%s): invalid varint-encoded dLen", i, tc.desc) - continue - } - if dLen > uint64(len(dBuf)) { - t.Errorf("#%d (%s): dLen %d is too large", i, tc.desc, dLen) - continue - } - - for j := range dBuf { - dBuf[j] = byte(notPresentBase + j%notPresentLen) - } - g, gotErr := Decode(dBuf[:], input) - if got := string(g); got != tc.want || gotErr != tc.wantErr { - t.Errorf("#%d (%s):\ngot %q, %v\nwant %q, %v", - i, tc.desc, got, gotErr, tc.want, tc.wantErr) - continue - } - for j, x := range dBuf { - if uint64(j) < dLen { - continue - } - if w := byte(notPresentBase + j%notPresentLen); x != w { - t.Errorf("#%d (%s): Decode overrun: dBuf[%d] was modified: got %#02x, want %#02x\ndBuf: % x", - i, tc.desc, j, x, w, dBuf) - continue loop - } - } - } -} - -func TestDecodeCopy4(t *testing.T) { - dots := strings.Repeat(".", 65536) - - input := strings.Join([]string{ - "\x89\x80\x04", // decodedLen = 65545. - "\x0cpqrs", // 4-byte literal "pqrs". - "\xf4\xff\xff" + dots, // 65536-byte literal dots. - "\x13\x04\x00\x01\x00", // tagCopy4; length=5 offset=65540. - }, "") - - gotBytes, err := Decode(nil, []byte(input)) - if err != nil { - t.Fatal(err) - } - got := string(gotBytes) - want := "pqrs" + dots + "pqrs." - if len(got) != len(want) { - t.Fatalf("got %d bytes, want %d", len(got), len(want)) - } - if got != want { - for i := 0; i < len(got); i++ { - if g, w := got[i], want[i]; g != w { - t.Fatalf("byte #%d: got %#02x, want %#02x", i, g, w) - } - } - } -} - -// TestDecodeLengthOffset tests decoding an encoding of the form literal + -// copy-length-offset + literal. For example: "abcdefghijkl" + "efghij" + "AB". -func TestDecodeLengthOffset(t *testing.T) { - const ( - prefix = "abcdefghijklmnopqr" - suffix = "ABCDEFGHIJKLMNOPQR" - - // notPresentXxx defines a range of byte values [0xa0, 0xc5) that are - // not present in either the input or the output. It is written to - // gotBuf to check that Decode does not write bytes past the end of - // gotBuf[:totalLen]. - // - // The magic number 37 was chosen because it is prime. A more 'natural' - // number like 32 might lead to a false negative if, for example, a - // byte was incorrectly copied 4*8 bytes later. - notPresentBase = 0xa0 - notPresentLen = 37 - ) - var gotBuf, wantBuf, inputBuf [128]byte - for length := 1; length <= 18; length++ { - for offset := 1; offset <= 18; offset++ { - loop: - for suffixLen := 0; suffixLen <= 18; suffixLen++ { - totalLen := len(prefix) + length + suffixLen - - inputLen := binary.PutUvarint(inputBuf[:], uint64(totalLen)) - inputBuf[inputLen] = tagLiteral + 4*byte(len(prefix)-1) - inputLen++ - inputLen += copy(inputBuf[inputLen:], prefix) - inputBuf[inputLen+0] = tagCopy2 + 4*byte(length-1) - inputBuf[inputLen+1] = byte(offset) - inputBuf[inputLen+2] = 0x00 - inputLen += 3 - if suffixLen > 0 { - inputBuf[inputLen] = tagLiteral + 4*byte(suffixLen-1) - inputLen++ - inputLen += copy(inputBuf[inputLen:], suffix[:suffixLen]) - } - input := inputBuf[:inputLen] - - for i := range gotBuf { - gotBuf[i] = byte(notPresentBase + i%notPresentLen) - } - got, err := Decode(gotBuf[:], input) - if err != nil { - t.Errorf("length=%d, offset=%d; suffixLen=%d: %v", length, offset, suffixLen, err) - continue - } - - wantLen := 0 - wantLen += copy(wantBuf[wantLen:], prefix) - for i := 0; i < length; i++ { - wantBuf[wantLen] = wantBuf[wantLen-offset] - wantLen++ - } - wantLen += copy(wantBuf[wantLen:], suffix[:suffixLen]) - want := wantBuf[:wantLen] - - for _, x := range input { - if notPresentBase <= x && x < notPresentBase+notPresentLen { - t.Errorf("length=%d, offset=%d; suffixLen=%d: input shouldn't contain %#02x\ninput: % x", - length, offset, suffixLen, x, input) - continue loop - } - } - for i, x := range gotBuf { - if i < totalLen { - continue - } - if w := byte(notPresentBase + i%notPresentLen); x != w { - t.Errorf("length=%d, offset=%d; suffixLen=%d; totalLen=%d: "+ - "Decode overrun: gotBuf[%d] was modified: got %#02x, want %#02x\ngotBuf: % x", - length, offset, suffixLen, totalLen, i, x, w, gotBuf) - continue loop - } - } - for _, x := range want { - if notPresentBase <= x && x < notPresentBase+notPresentLen { - t.Errorf("length=%d, offset=%d; suffixLen=%d: want shouldn't contain %#02x\nwant: % x", - length, offset, suffixLen, x, want) - continue loop - } - } - - if !bytes.Equal(got, want) { - t.Errorf("length=%d, offset=%d; suffixLen=%d:\ninput % x\ngot % x\nwant % x", - length, offset, suffixLen, input, got, want) - continue - } - } - } - } -} - -const ( - goldenText = "Mark.Twain-Tom.Sawyer.txt" - goldenCompressed = goldenText + ".rawsnappy" -) - -func TestDecodeGoldenInput(t *testing.T) { - tDir := filepath.FromSlash(*testdataDir) - src, err := ioutil.ReadFile(filepath.Join(tDir, goldenCompressed)) - if err != nil { - t.Fatalf("ReadFile: %v", err) - } - got, err := Decode(nil, src) - if err != nil { - t.Fatalf("Decode: %v", err) - } - want, err := ioutil.ReadFile(filepath.Join(tDir, goldenText)) - if err != nil { - t.Fatalf("ReadFile: %v", err) - } - if err := cmp(got, want); err != nil { - t.Fatal(err) - } -} - -func TestEncodeGoldenInput(t *testing.T) { - tDir := filepath.FromSlash(*testdataDir) - src, err := ioutil.ReadFile(filepath.Join(tDir, goldenText)) - if err != nil { - t.Fatalf("ReadFile: %v", err) - } - got := Encode(nil, src) - want, err := ioutil.ReadFile(filepath.Join(tDir, goldenCompressed)) - if err != nil { - t.Fatalf("ReadFile: %v", err) - } - if err := cmp(got, want); err != nil { - t.Fatal(err) - } -} - -func TestExtendMatchGoldenInput(t *testing.T) { - tDir := filepath.FromSlash(*testdataDir) - src, err := ioutil.ReadFile(filepath.Join(tDir, goldenText)) - if err != nil { - t.Fatalf("ReadFile: %v", err) - } - for i, tc := range extendMatchGoldenTestCases { - got := extendMatch(src, tc.i, tc.j) - if got != tc.want { - t.Errorf("test #%d: i, j = %5d, %5d: got %5d (= j + %6d), want %5d (= j + %6d)", - i, tc.i, tc.j, got, got-tc.j, tc.want, tc.want-tc.j) - } - } -} - -func TestExtendMatch(t *testing.T) { - // ref is a simple, reference implementation of extendMatch. - ref := func(src []byte, i, j int) int { - for ; j < len(src) && src[i] == src[j]; i, j = i+1, j+1 { - } - return j - } - - nums := []int{0, 1, 2, 7, 8, 9, 29, 30, 31, 32, 33, 34, 38, 39, 40} - for yIndex := 40; yIndex > 30; yIndex-- { - xxx := bytes.Repeat([]byte("x"), 40) - if yIndex < len(xxx) { - xxx[yIndex] = 'y' - } - for _, i := range nums { - for _, j := range nums { - if i >= j { - continue - } - got := extendMatch(xxx, i, j) - want := ref(xxx, i, j) - if got != want { - t.Errorf("yIndex=%d, i=%d, j=%d: got %d, want %d", yIndex, i, j, got, want) - } - } - } - } -} - -const snappytoolCmdName = "cmd/snappytool/snappytool" - -func skipTestSameEncodingAsCpp() (msg string) { - if !goEncoderShouldMatchCppEncoder { - return fmt.Sprintf("skipping testing that the encoding is byte-for-byte identical to C++: GOARCH=%s", runtime.GOARCH) - } - if _, err := os.Stat(snappytoolCmdName); err != nil { - return fmt.Sprintf("could not find snappytool: %v", err) - } - return "" -} - -func runTestSameEncodingAsCpp(src []byte) error { - got := Encode(nil, src) - - cmd := exec.Command(snappytoolCmdName, "-e") - cmd.Stdin = bytes.NewReader(src) - want, err := cmd.Output() - if err != nil { - return fmt.Errorf("could not run snappytool: %v", err) - } - return cmp(got, want) -} - -func TestSameEncodingAsCppShortCopies(t *testing.T) { - if msg := skipTestSameEncodingAsCpp(); msg != "" { - t.Skip(msg) - } - src := bytes.Repeat([]byte{'a'}, 20) - for i := 0; i <= len(src); i++ { - if err := runTestSameEncodingAsCpp(src[:i]); err != nil { - t.Errorf("i=%d: %v", i, err) - } - } -} - -func TestSameEncodingAsCppLongFiles(t *testing.T) { - if msg := skipTestSameEncodingAsCpp(); msg != "" { - t.Skip(msg) - } - bDir := filepath.FromSlash(*benchdataDir) - failed := false - for i, tf := range testFiles { - if err := downloadBenchmarkFiles(t, tf.filename); err != nil { - t.Fatalf("failed to download testdata: %s", err) - } - data := readFile(t, filepath.Join(bDir, tf.filename)) - if n := tf.sizeLimit; 0 < n && n < len(data) { - data = data[:n] - } - if err := runTestSameEncodingAsCpp(data); err != nil { - t.Errorf("i=%d: %v", i, err) - failed = true - } - } - if failed { - t.Errorf("was the snappytool program built against the C++ snappy library version " + - "d53de187 or later, commited on 2016-04-05? See " + - "https://github.com/google/snappy/commit/d53de18799418e113e44444252a39b12a0e4e0cc") - } -} - -// TestSlowForwardCopyOverrun tests the "expand the pattern" algorithm -// described in decode_amd64.s and its claim of a 10 byte overrun worst case. -func TestSlowForwardCopyOverrun(t *testing.T) { - const base = 100 - - for length := 1; length < 18; length++ { - for offset := 1; offset < 18; offset++ { - highWaterMark := base - d := base - l := length - o := offset - - // makeOffsetAtLeast8 - for o < 8 { - if end := d + 8; highWaterMark < end { - highWaterMark = end - } - l -= o - d += o - o += o - } - - // fixUpSlowForwardCopy - a := d - d += l - - // finishSlowForwardCopy - for l > 0 { - if end := a + 8; highWaterMark < end { - highWaterMark = end - } - a += 8 - l -= 8 - } - - dWant := base + length - overrun := highWaterMark - dWant - if d != dWant || overrun < 0 || 10 < overrun { - t.Errorf("length=%d, offset=%d: d and overrun: got (%d, %d), want (%d, something in [0, 10])", - length, offset, d, overrun, dWant) - } - } - } -} - -// TestEncodeNoiseThenRepeats encodes input for which the first half is very -// incompressible and the second half is very compressible. The encoded form's -// length should be closer to 50% of the original length than 100%. -func TestEncodeNoiseThenRepeats(t *testing.T) { - for _, origLen := range []int{256 * 1024, 2048 * 1024} { - src := make([]byte, origLen) - rng := rand.New(rand.NewSource(1)) - firstHalf, secondHalf := src[:origLen/2], src[origLen/2:] - for i := range firstHalf { - firstHalf[i] = uint8(rng.Intn(256)) - } - for i := range secondHalf { - secondHalf[i] = uint8(i >> 8) - } - dst := Encode(nil, src) - if got, want := len(dst), origLen*3/4; got >= want { - t.Errorf("origLen=%d: got %d encoded bytes, want less than %d", origLen, got, want) - } - } -} - -func TestFramingFormat(t *testing.T) { - // src is comprised of alternating 1e5-sized sequences of random - // (incompressible) bytes and repeated (compressible) bytes. 1e5 was chosen - // because it is larger than maxBlockSize (64k). - src := make([]byte, 1e6) - rng := rand.New(rand.NewSource(1)) - for i := 0; i < 10; i++ { - if i%2 == 0 { - for j := 0; j < 1e5; j++ { - src[1e5*i+j] = uint8(rng.Intn(256)) - } - } else { - for j := 0; j < 1e5; j++ { - src[1e5*i+j] = uint8(i) - } - } - } - - buf := new(bytes.Buffer) - if _, err := NewWriter(buf).Write(src); err != nil { - t.Fatalf("Write: encoding: %v", err) - } - dst, err := ioutil.ReadAll(NewReader(buf)) - if err != nil { - t.Fatalf("ReadAll: decoding: %v", err) - } - if err := cmp(dst, src); err != nil { - t.Fatal(err) - } -} - -func TestWriterGoldenOutput(t *testing.T) { - buf := new(bytes.Buffer) - w := NewBufferedWriter(buf) - defer w.Close() - w.Write([]byte("abcd")) // Not compressible. - w.Flush() - w.Write(bytes.Repeat([]byte{'A'}, 150)) // Compressible. - w.Flush() - // The next chunk is also compressible, but a naive, greedy encoding of the - // overall length 67 copy as a length 64 copy (the longest expressible as a - // tagCopy1 or tagCopy2) plus a length 3 remainder would be two 3-byte - // tagCopy2 tags (6 bytes), since the minimum length for a tagCopy1 is 4 - // bytes. Instead, we could do it shorter, in 5 bytes: a 3-byte tagCopy2 - // (of length 60) and a 2-byte tagCopy1 (of length 7). - w.Write(bytes.Repeat([]byte{'B'}, 68)) - w.Write([]byte("efC")) // Not compressible. - w.Write(bytes.Repeat([]byte{'C'}, 20)) // Compressible. - w.Write(bytes.Repeat([]byte{'B'}, 20)) // Compressible. - w.Write([]byte("g")) // Not compressible. - w.Flush() - - got := buf.String() - want := strings.Join([]string{ - magicChunk, - "\x01\x08\x00\x00", // Uncompressed chunk, 8 bytes long (including 4 byte checksum). - "\x68\x10\xe6\xb6", // Checksum. - "\x61\x62\x63\x64", // Uncompressed payload: "abcd". - "\x00\x11\x00\x00", // Compressed chunk, 17 bytes long (including 4 byte checksum). - "\x5f\xeb\xf2\x10", // Checksum. - "\x96\x01", // Compressed payload: Uncompressed length (varint encoded): 150. - "\x00\x41", // Compressed payload: tagLiteral, length=1, "A". - "\xfe\x01\x00", // Compressed payload: tagCopy2, length=64, offset=1. - "\xfe\x01\x00", // Compressed payload: tagCopy2, length=64, offset=1. - "\x52\x01\x00", // Compressed payload: tagCopy2, length=21, offset=1. - "\x00\x18\x00\x00", // Compressed chunk, 24 bytes long (including 4 byte checksum). - "\x30\x85\x69\xeb", // Checksum. - "\x70", // Compressed payload: Uncompressed length (varint encoded): 112. - "\x00\x42", // Compressed payload: tagLiteral, length=1, "B". - "\xee\x01\x00", // Compressed payload: tagCopy2, length=60, offset=1. - "\x0d\x01", // Compressed payload: tagCopy1, length=7, offset=1. - "\x08\x65\x66\x43", // Compressed payload: tagLiteral, length=3, "efC". - "\x4e\x01\x00", // Compressed payload: tagCopy2, length=20, offset=1. - "\x4e\x5a\x00", // Compressed payload: tagCopy2, length=20, offset=90. - "\x00\x67", // Compressed payload: tagLiteral, length=1, "g". - }, "") - if got != want { - t.Fatalf("\ngot: % x\nwant: % x", got, want) - } -} - -func TestEmitLiteral(t *testing.T) { - testCases := []struct { - length int - want string - }{ - {1, "\x00"}, - {2, "\x04"}, - {59, "\xe8"}, - {60, "\xec"}, - {61, "\xf0\x3c"}, - {62, "\xf0\x3d"}, - {254, "\xf0\xfd"}, - {255, "\xf0\xfe"}, - {256, "\xf0\xff"}, - {257, "\xf4\x00\x01"}, - {65534, "\xf4\xfd\xff"}, - {65535, "\xf4\xfe\xff"}, - {65536, "\xf4\xff\xff"}, - } - - dst := make([]byte, 70000) - nines := bytes.Repeat([]byte{0x99}, 65536) - for _, tc := range testCases { - lit := nines[:tc.length] - n := emitLiteral(dst, lit) - if !bytes.HasSuffix(dst[:n], lit) { - t.Errorf("length=%d: did not end with that many literal bytes", tc.length) - continue - } - got := string(dst[:n-tc.length]) - if got != tc.want { - t.Errorf("length=%d:\ngot % x\nwant % x", tc.length, got, tc.want) - continue - } - } -} - -func TestEmitCopy(t *testing.T) { - testCases := []struct { - offset int - length int - want string - }{ - {8, 04, "\x01\x08"}, - {8, 11, "\x1d\x08"}, - {8, 12, "\x2e\x08\x00"}, - {8, 13, "\x32\x08\x00"}, - {8, 59, "\xea\x08\x00"}, - {8, 60, "\xee\x08\x00"}, - {8, 61, "\xf2\x08\x00"}, - {8, 62, "\xf6\x08\x00"}, - {8, 63, "\xfa\x08\x00"}, - {8, 64, "\xfe\x08\x00"}, - {8, 65, "\xee\x08\x00\x05\x08"}, - {8, 66, "\xee\x08\x00\x09\x08"}, - {8, 67, "\xee\x08\x00\x0d\x08"}, - {8, 68, "\xfe\x08\x00\x01\x08"}, - {8, 69, "\xfe\x08\x00\x05\x08"}, - {8, 80, "\xfe\x08\x00\x3e\x08\x00"}, - - {256, 04, "\x21\x00"}, - {256, 11, "\x3d\x00"}, - {256, 12, "\x2e\x00\x01"}, - {256, 13, "\x32\x00\x01"}, - {256, 59, "\xea\x00\x01"}, - {256, 60, "\xee\x00\x01"}, - {256, 61, "\xf2\x00\x01"}, - {256, 62, "\xf6\x00\x01"}, - {256, 63, "\xfa\x00\x01"}, - {256, 64, "\xfe\x00\x01"}, - {256, 65, "\xee\x00\x01\x25\x00"}, - {256, 66, "\xee\x00\x01\x29\x00"}, - {256, 67, "\xee\x00\x01\x2d\x00"}, - {256, 68, "\xfe\x00\x01\x21\x00"}, - {256, 69, "\xfe\x00\x01\x25\x00"}, - {256, 80, "\xfe\x00\x01\x3e\x00\x01"}, - - {2048, 04, "\x0e\x00\x08"}, - {2048, 11, "\x2a\x00\x08"}, - {2048, 12, "\x2e\x00\x08"}, - {2048, 13, "\x32\x00\x08"}, - {2048, 59, "\xea\x00\x08"}, - {2048, 60, "\xee\x00\x08"}, - {2048, 61, "\xf2\x00\x08"}, - {2048, 62, "\xf6\x00\x08"}, - {2048, 63, "\xfa\x00\x08"}, - {2048, 64, "\xfe\x00\x08"}, - {2048, 65, "\xee\x00\x08\x12\x00\x08"}, - {2048, 66, "\xee\x00\x08\x16\x00\x08"}, - {2048, 67, "\xee\x00\x08\x1a\x00\x08"}, - {2048, 68, "\xfe\x00\x08\x0e\x00\x08"}, - {2048, 69, "\xfe\x00\x08\x12\x00\x08"}, - {2048, 80, "\xfe\x00\x08\x3e\x00\x08"}, - } - - dst := make([]byte, 1024) - for _, tc := range testCases { - n := emitCopy(dst, tc.offset, tc.length) - got := string(dst[:n]) - if got != tc.want { - t.Errorf("offset=%d, length=%d:\ngot % x\nwant % x", tc.offset, tc.length, got, tc.want) - } - } -} - -func TestNewBufferedWriter(t *testing.T) { - // Test all 32 possible sub-sequences of these 5 input slices. - // - // Their lengths sum to 400,000, which is over 6 times the Writer ibuf - // capacity: 6 * maxBlockSize is 393,216. - inputs := [][]byte{ - bytes.Repeat([]byte{'a'}, 40000), - bytes.Repeat([]byte{'b'}, 150000), - bytes.Repeat([]byte{'c'}, 60000), - bytes.Repeat([]byte{'d'}, 120000), - bytes.Repeat([]byte{'e'}, 30000), - } -loop: - for i := 0; i < 1< 0; { - i := copy(x, src) - x = x[i:] - } - return dst -} - -func benchWords(b *testing.B, n int, decode bool) { - // Note: the file is OS-language dependent so the resulting values are not - // directly comparable for non-US-English OS installations. - data := expand(readFile(b, "/usr/share/dict/words"), n) - if decode { - benchDecode(b, data) - } else { - benchEncode(b, data) - } -} - -func BenchmarkWordsDecode1e1(b *testing.B) { benchWords(b, 1e1, true) } -func BenchmarkWordsDecode1e2(b *testing.B) { benchWords(b, 1e2, true) } -func BenchmarkWordsDecode1e3(b *testing.B) { benchWords(b, 1e3, true) } -func BenchmarkWordsDecode1e4(b *testing.B) { benchWords(b, 1e4, true) } -func BenchmarkWordsDecode1e5(b *testing.B) { benchWords(b, 1e5, true) } -func BenchmarkWordsDecode1e6(b *testing.B) { benchWords(b, 1e6, true) } -func BenchmarkWordsEncode1e1(b *testing.B) { benchWords(b, 1e1, false) } -func BenchmarkWordsEncode1e2(b *testing.B) { benchWords(b, 1e2, false) } -func BenchmarkWordsEncode1e3(b *testing.B) { benchWords(b, 1e3, false) } -func BenchmarkWordsEncode1e4(b *testing.B) { benchWords(b, 1e4, false) } -func BenchmarkWordsEncode1e5(b *testing.B) { benchWords(b, 1e5, false) } -func BenchmarkWordsEncode1e6(b *testing.B) { benchWords(b, 1e6, false) } - -func BenchmarkRandomEncode(b *testing.B) { - rng := rand.New(rand.NewSource(1)) - data := make([]byte, 1<<20) - for i := range data { - data[i] = uint8(rng.Intn(256)) - } - benchEncode(b, data) -} - -// testFiles' values are copied directly from -// https://raw.githubusercontent.com/google/snappy/master/snappy_unittest.cc -// The label field is unused in snappy-go. -var testFiles = []struct { - label string - filename string - sizeLimit int -}{ - {"html", "html", 0}, - {"urls", "urls.10K", 0}, - {"jpg", "fireworks.jpeg", 0}, - {"jpg_200", "fireworks.jpeg", 200}, - {"pdf", "paper-100k.pdf", 0}, - {"html4", "html_x_4", 0}, - {"txt1", "alice29.txt", 0}, - {"txt2", "asyoulik.txt", 0}, - {"txt3", "lcet10.txt", 0}, - {"txt4", "plrabn12.txt", 0}, - {"pb", "geo.protodata", 0}, - {"gaviota", "kppkn.gtb", 0}, -} - -const ( - // The benchmark data files are at this canonical URL. - benchURL = "https://raw.githubusercontent.com/google/snappy/master/testdata/" -) - -func downloadBenchmarkFiles(b testing.TB, basename string) (errRet error) { - bDir := filepath.FromSlash(*benchdataDir) - filename := filepath.Join(bDir, basename) - if stat, err := os.Stat(filename); err == nil && stat.Size() != 0 { - return nil - } - - if !*download { - b.Skipf("test data not found; skipping %s without the -download flag", testOrBenchmark(b)) - } - // Download the official snappy C++ implementation reference test data - // files for benchmarking. - if err := os.MkdirAll(bDir, 0777); err != nil && !os.IsExist(err) { - return fmt.Errorf("failed to create %s: %s", bDir, err) - } - - f, err := os.Create(filename) - if err != nil { - return fmt.Errorf("failed to create %s: %s", filename, err) - } - defer f.Close() - defer func() { - if errRet != nil { - os.Remove(filename) - } - }() - url := benchURL + basename - resp, err := http.Get(url) - if err != nil { - return fmt.Errorf("failed to download %s: %s", url, err) - } - defer resp.Body.Close() - if s := resp.StatusCode; s != http.StatusOK { - return fmt.Errorf("downloading %s: HTTP status code %d (%s)", url, s, http.StatusText(s)) - } - _, err = io.Copy(f, resp.Body) - if err != nil { - return fmt.Errorf("failed to download %s to %s: %s", url, filename, err) - } - return nil -} - -func benchFile(b *testing.B, i int, decode bool) { - if err := downloadBenchmarkFiles(b, testFiles[i].filename); err != nil { - b.Fatalf("failed to download testdata: %s", err) - } - bDir := filepath.FromSlash(*benchdataDir) - data := readFile(b, filepath.Join(bDir, testFiles[i].filename)) - if n := testFiles[i].sizeLimit; 0 < n && n < len(data) { - data = data[:n] - } - if decode { - benchDecode(b, data) - } else { - benchEncode(b, data) - } -} - -// Naming convention is kept similar to what snappy's C++ implementation uses. -func Benchmark_UFlat0(b *testing.B) { benchFile(b, 0, true) } -func Benchmark_UFlat1(b *testing.B) { benchFile(b, 1, true) } -func Benchmark_UFlat2(b *testing.B) { benchFile(b, 2, true) } -func Benchmark_UFlat3(b *testing.B) { benchFile(b, 3, true) } -func Benchmark_UFlat4(b *testing.B) { benchFile(b, 4, true) } -func Benchmark_UFlat5(b *testing.B) { benchFile(b, 5, true) } -func Benchmark_UFlat6(b *testing.B) { benchFile(b, 6, true) } -func Benchmark_UFlat7(b *testing.B) { benchFile(b, 7, true) } -func Benchmark_UFlat8(b *testing.B) { benchFile(b, 8, true) } -func Benchmark_UFlat9(b *testing.B) { benchFile(b, 9, true) } -func Benchmark_UFlat10(b *testing.B) { benchFile(b, 10, true) } -func Benchmark_UFlat11(b *testing.B) { benchFile(b, 11, true) } -func Benchmark_ZFlat0(b *testing.B) { benchFile(b, 0, false) } -func Benchmark_ZFlat1(b *testing.B) { benchFile(b, 1, false) } -func Benchmark_ZFlat2(b *testing.B) { benchFile(b, 2, false) } -func Benchmark_ZFlat3(b *testing.B) { benchFile(b, 3, false) } -func Benchmark_ZFlat4(b *testing.B) { benchFile(b, 4, false) } -func Benchmark_ZFlat5(b *testing.B) { benchFile(b, 5, false) } -func Benchmark_ZFlat6(b *testing.B) { benchFile(b, 6, false) } -func Benchmark_ZFlat7(b *testing.B) { benchFile(b, 7, false) } -func Benchmark_ZFlat8(b *testing.B) { benchFile(b, 8, false) } -func Benchmark_ZFlat9(b *testing.B) { benchFile(b, 9, false) } -func Benchmark_ZFlat10(b *testing.B) { benchFile(b, 10, false) } -func Benchmark_ZFlat11(b *testing.B) { benchFile(b, 11, false) } - -func BenchmarkExtendMatch(b *testing.B) { - tDir := filepath.FromSlash(*testdataDir) - src, err := ioutil.ReadFile(filepath.Join(tDir, goldenText)) - if err != nil { - b.Fatalf("ReadFile: %v", err) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - for _, tc := range extendMatchGoldenTestCases { - extendMatch(src, tc.i, tc.j) - } - } -} diff --git a/vendor/github.com/google/gofuzz/.travis.yml b/vendor/github.com/google/gofuzz/.travis.yml deleted file mode 100644 index f8684d99f..000000000 --- a/vendor/github.com/google/gofuzz/.travis.yml +++ /dev/null @@ -1,13 +0,0 @@ -language: go - -go: - - 1.4 - - 1.3 - - 1.2 - - tip - -install: - - if ! go get code.google.com/p/go.tools/cmd/cover; then go get golang.org/x/tools/cmd/cover; fi - -script: - - go test -cover diff --git a/vendor/github.com/google/gofuzz/CONTRIBUTING.md b/vendor/github.com/google/gofuzz/CONTRIBUTING.md deleted file mode 100644 index 51cf5cd1a..000000000 --- a/vendor/github.com/google/gofuzz/CONTRIBUTING.md +++ /dev/null @@ -1,67 +0,0 @@ -# How to contribute # - -We'd love to accept your patches and contributions to this project. There are -a just a few small guidelines you need to follow. - - -## Contributor License Agreement ## - -Contributions to any Google project must be accompanied by a Contributor -License Agreement. This is not a copyright **assignment**, it simply gives -Google permission to use and redistribute your contributions as part of the -project. - - * If you are an individual writing original source code and you're sure you - own the intellectual property, then you'll need to sign an [individual - CLA][]. - - * If you work for a company that wants to allow you to contribute your work, - then you'll need to sign a [corporate CLA][]. - -You generally only need to submit a CLA once, so if you've already submitted -one (even if it was for a different project), you probably don't need to do it -again. - -[individual CLA]: https://developers.google.com/open-source/cla/individual -[corporate CLA]: https://developers.google.com/open-source/cla/corporate - - -## Submitting a patch ## - - 1. It's generally best to start by opening a new issue describing the bug or - feature you're intending to fix. Even if you think it's relatively minor, - it's helpful to know what people are working on. Mention in the initial - issue that you are planning to work on that bug or feature so that it can - be assigned to you. - - 1. Follow the normal process of [forking][] the project, and setup a new - branch to work in. It's important that each group of changes be done in - separate branches in order to ensure that a pull request only includes the - commits related to that bug or feature. - - 1. Go makes it very simple to ensure properly formatted code, so always run - `go fmt` on your code before committing it. You should also run - [golint][] over your code. As noted in the [golint readme][], it's not - strictly necessary that your code be completely "lint-free", but this will - help you find common style issues. - - 1. Any significant changes should almost always be accompanied by tests. The - project already has good test coverage, so look at some of the existing - tests if you're unsure how to go about it. [gocov][] and [gocov-html][] - are invaluable tools for seeing which parts of your code aren't being - exercised by your tests. - - 1. Do your best to have [well-formed commit messages][] for each change. - This provides consistency throughout the project, and ensures that commit - messages are able to be formatted properly by various git tools. - - 1. Finally, push the commits to your fork and submit a [pull request][]. - -[forking]: https://help.github.com/articles/fork-a-repo -[golint]: https://github.com/golang/lint -[golint readme]: https://github.com/golang/lint/blob/master/README -[gocov]: https://github.com/axw/gocov -[gocov-html]: https://github.com/matm/gocov-html -[well-formed commit messages]: http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html -[squash]: http://git-scm.com/book/en/Git-Tools-Rewriting-History#Squashing-Commits -[pull request]: https://help.github.com/articles/creating-a-pull-request diff --git a/vendor/github.com/google/gofuzz/README.md b/vendor/github.com/google/gofuzz/README.md deleted file mode 100644 index 64869af34..000000000 --- a/vendor/github.com/google/gofuzz/README.md +++ /dev/null @@ -1,71 +0,0 @@ -gofuzz -====== - -gofuzz is a library for populating go objects with random values. - -[![GoDoc](https://godoc.org/github.com/google/gofuzz?status.png)](https://godoc.org/github.com/google/gofuzz) -[![Travis](https://travis-ci.org/google/gofuzz.svg?branch=master)](https://travis-ci.org/google/gofuzz) - -This is useful for testing: - -* Do your project's objects really serialize/unserialize correctly in all cases? -* Is there an incorrectly formatted object that will cause your project to panic? - -Import with ```import "github.com/google/gofuzz"``` - -You can use it on single variables: -```go -f := fuzz.New() -var myInt int -f.Fuzz(&myInt) // myInt gets a random value. -``` - -You can use it on maps: -```go -f := fuzz.New().NilChance(0).NumElements(1, 1) -var myMap map[ComplexKeyType]string -f.Fuzz(&myMap) // myMap will have exactly one element. -``` - -Customize the chance of getting a nil pointer: -```go -f := fuzz.New().NilChance(.5) -var fancyStruct struct { - A, B, C, D *string -} -f.Fuzz(&fancyStruct) // About half the pointers should be set. -``` - -You can even customize the randomization completely if needed: -```go -type MyEnum string -const ( - A MyEnum = "A" - B MyEnum = "B" -) -type MyInfo struct { - Type MyEnum - AInfo *string - BInfo *string -} - -f := fuzz.New().NilChance(0).Funcs( - func(e *MyInfo, c fuzz.Continue) { - switch c.Intn(2) { - case 0: - e.Type = A - c.Fuzz(&e.AInfo) - case 1: - e.Type = B - c.Fuzz(&e.BInfo) - } - }, -) - -var myObject MyInfo -f.Fuzz(&myObject) // Type will correspond to whether A or B info is set. -``` - -See more examples in ```example_test.go```. - -Happy testing! diff --git a/vendor/github.com/google/gofuzz/example_test.go b/vendor/github.com/google/gofuzz/example_test.go deleted file mode 100644 index 792707a3a..000000000 --- a/vendor/github.com/google/gofuzz/example_test.go +++ /dev/null @@ -1,225 +0,0 @@ -/* -Copyright 2014 Google Inc. All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package fuzz_test - -import ( - "encoding/json" - "fmt" - "math/rand" - - "github.com/google/gofuzz" -) - -func ExampleSimple() { - type MyType struct { - A string - B string - C int - D struct { - E float64 - } - } - - f := fuzz.New() - object := MyType{} - - uniqueObjects := map[MyType]int{} - - for i := 0; i < 1000; i++ { - f.Fuzz(&object) - uniqueObjects[object]++ - } - fmt.Printf("Got %v unique objects.\n", len(uniqueObjects)) - // Output: - // Got 1000 unique objects. -} - -func ExampleCustom() { - type MyType struct { - A int - B string - } - - counter := 0 - f := fuzz.New().Funcs( - func(i *int, c fuzz.Continue) { - *i = counter - counter++ - }, - ) - object := MyType{} - - uniqueObjects := map[MyType]int{} - - for i := 0; i < 100; i++ { - f.Fuzz(&object) - if object.A != i { - fmt.Printf("Unexpected value: %#v\n", object) - } - uniqueObjects[object]++ - } - fmt.Printf("Got %v unique objects.\n", len(uniqueObjects)) - // Output: - // Got 100 unique objects. -} - -func ExampleComplex() { - type OtherType struct { - A string - B string - } - type MyType struct { - Pointer *OtherType - Map map[string]OtherType - PointerMap *map[string]OtherType - Slice []OtherType - SlicePointer []*OtherType - PointerSlicePointer *[]*OtherType - } - - f := fuzz.New().RandSource(rand.NewSource(0)).NilChance(0).NumElements(1, 1).Funcs( - func(o *OtherType, c fuzz.Continue) { - o.A = "Foo" - o.B = "Bar" - }, - func(op **OtherType, c fuzz.Continue) { - *op = &OtherType{"A", "B"} - }, - func(m map[string]OtherType, c fuzz.Continue) { - m["Works Because"] = OtherType{ - "Fuzzer", - "Preallocated", - } - }, - ) - object := MyType{} - f.Fuzz(&object) - bytes, err := json.MarshalIndent(&object, "", " ") - if err != nil { - fmt.Printf("error: %v\n", err) - } - fmt.Printf("%s\n", string(bytes)) - // Output: - // { - // "Pointer": { - // "A": "A", - // "B": "B" - // }, - // "Map": { - // "Works Because": { - // "A": "Fuzzer", - // "B": "Preallocated" - // } - // }, - // "PointerMap": { - // "Works Because": { - // "A": "Fuzzer", - // "B": "Preallocated" - // } - // }, - // "Slice": [ - // { - // "A": "Foo", - // "B": "Bar" - // } - // ], - // "SlicePointer": [ - // { - // "A": "A", - // "B": "B" - // } - // ], - // "PointerSlicePointer": [ - // { - // "A": "A", - // "B": "B" - // } - // ] - // } -} - -func ExampleMap() { - f := fuzz.New().NilChance(0).NumElements(1, 1) - var myMap map[struct{ A, B, C int }]string - f.Fuzz(&myMap) - fmt.Printf("myMap has %v element(s).\n", len(myMap)) - // Output: - // myMap has 1 element(s). -} - -func ExampleSingle() { - f := fuzz.New() - var i int - f.Fuzz(&i) - - // Technically, we'd expect this to fail one out of 2 billion attempts... - fmt.Printf("(i == 0) == %v", i == 0) - // Output: - // (i == 0) == false -} - -func ExampleEnum() { - type MyEnum string - const ( - A MyEnum = "A" - B MyEnum = "B" - ) - type MyInfo struct { - Type MyEnum - AInfo *string - BInfo *string - } - - f := fuzz.New().NilChance(0).Funcs( - func(e *MyInfo, c fuzz.Continue) { - // Note c's embedded Rand allows for direct use. - // We could also use c.RandBool() here. - switch c.Intn(2) { - case 0: - e.Type = A - c.Fuzz(&e.AInfo) - case 1: - e.Type = B - c.Fuzz(&e.BInfo) - } - }, - ) - - for i := 0; i < 100; i++ { - var myObject MyInfo - f.Fuzz(&myObject) - switch myObject.Type { - case A: - if myObject.AInfo == nil { - fmt.Println("AInfo should have been set!") - } - if myObject.BInfo != nil { - fmt.Println("BInfo should NOT have been set!") - } - case B: - if myObject.BInfo == nil { - fmt.Println("BInfo should have been set!") - } - if myObject.AInfo != nil { - fmt.Println("AInfo should NOT have been set!") - } - default: - fmt.Println("Invalid enum value!") - } - } - // Output: -} diff --git a/vendor/github.com/google/gofuzz/fuzz_test.go b/vendor/github.com/google/gofuzz/fuzz_test.go deleted file mode 100644 index 4059ea6fe..000000000 --- a/vendor/github.com/google/gofuzz/fuzz_test.go +++ /dev/null @@ -1,472 +0,0 @@ -/* -Copyright 2014 Google Inc. All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package fuzz - -import ( - "reflect" - "testing" - "time" -) - -func TestFuzz_basic(t *testing.T) { - obj := &struct { - I int - I8 int8 - I16 int16 - I32 int32 - I64 int64 - U uint - U8 uint8 - U16 uint16 - U32 uint32 - U64 uint64 - Uptr uintptr - S string - B bool - T time.Time - }{} - - failed := map[string]int{} - for i := 0; i < 10; i++ { - New().Fuzz(obj) - - if n, v := "i", obj.I; v == 0 { - failed[n] = failed[n] + 1 - } - if n, v := "i8", obj.I8; v == 0 { - failed[n] = failed[n] + 1 - } - if n, v := "i16", obj.I16; v == 0 { - failed[n] = failed[n] + 1 - } - if n, v := "i32", obj.I32; v == 0 { - failed[n] = failed[n] + 1 - } - if n, v := "i64", obj.I64; v == 0 { - failed[n] = failed[n] + 1 - } - if n, v := "u", obj.U; v == 0 { - failed[n] = failed[n] + 1 - } - if n, v := "u8", obj.U8; v == 0 { - failed[n] = failed[n] + 1 - } - if n, v := "u16", obj.U16; v == 0 { - failed[n] = failed[n] + 1 - } - if n, v := "u32", obj.U32; v == 0 { - failed[n] = failed[n] + 1 - } - if n, v := "u64", obj.U64; v == 0 { - failed[n] = failed[n] + 1 - } - if n, v := "uptr", obj.Uptr; v == 0 { - failed[n] = failed[n] + 1 - } - if n, v := "s", obj.S; v == "" { - failed[n] = failed[n] + 1 - } - if n, v := "b", obj.B; v == false { - failed[n] = failed[n] + 1 - } - if n, v := "t", obj.T; v.IsZero() { - failed[n] = failed[n] + 1 - } - } - checkFailed(t, failed) -} - -func checkFailed(t *testing.T, failed map[string]int) { - for k, v := range failed { - if v > 8 { - t.Errorf("%v seems to not be getting set, was zero value %v times", k, v) - } - } -} - -func TestFuzz_structptr(t *testing.T) { - obj := &struct { - A *struct { - S string - } - }{} - - f := New().NilChance(.5) - failed := map[string]int{} - for i := 0; i < 10; i++ { - f.Fuzz(obj) - - if n, v := "a not nil", obj.A; v == nil { - failed[n] = failed[n] + 1 - } - if n, v := "a nil", obj.A; v != nil { - failed[n] = failed[n] + 1 - } - if n, v := "as", obj.A; v == nil || v.S == "" { - failed[n] = failed[n] + 1 - } - } - checkFailed(t, failed) -} - -// tryFuzz tries fuzzing up to 20 times. Fail if check() never passes, report the highest -// stage it ever got to. -func tryFuzz(t *testing.T, f *Fuzzer, obj interface{}, check func() (stage int, passed bool)) { - maxStage := 0 - for i := 0; i < 20; i++ { - f.Fuzz(obj) - stage, passed := check() - if stage > maxStage { - maxStage = stage - } - if passed { - return - } - } - t.Errorf("Only ever got to stage %v", maxStage) -} - -func TestFuzz_structmap(t *testing.T) { - obj := &struct { - A map[struct { - S string - }]struct { - S2 string - } - B map[string]string - }{} - - tryFuzz(t, New(), obj, func() (int, bool) { - if obj.A == nil { - return 1, false - } - if len(obj.A) == 0 { - return 2, false - } - for k, v := range obj.A { - if k.S == "" { - return 3, false - } - if v.S2 == "" { - return 4, false - } - } - - if obj.B == nil { - return 5, false - } - if len(obj.B) == 0 { - return 6, false - } - for k, v := range obj.B { - if k == "" { - return 7, false - } - if v == "" { - return 8, false - } - } - return 9, true - }) -} - -func TestFuzz_structslice(t *testing.T) { - obj := &struct { - A []struct { - S string - } - B []string - }{} - - tryFuzz(t, New(), obj, func() (int, bool) { - if obj.A == nil { - return 1, false - } - if len(obj.A) == 0 { - return 2, false - } - for _, v := range obj.A { - if v.S == "" { - return 3, false - } - } - - if obj.B == nil { - return 4, false - } - if len(obj.B) == 0 { - return 5, false - } - for _, v := range obj.B { - if v == "" { - return 6, false - } - } - return 7, true - }) -} - -func TestFuzz_structarray(t *testing.T) { - obj := &struct { - A [3]struct { - S string - } - B [2]int - }{} - - tryFuzz(t, New(), obj, func() (int, bool) { - for _, v := range obj.A { - if v.S == "" { - return 1, false - } - } - - for _, v := range obj.B { - if v == 0 { - return 2, false - } - } - return 3, true - }) -} - -func TestFuzz_custom(t *testing.T) { - obj := &struct { - A string - B *string - C map[string]string - D *map[string]string - }{} - - testPhrase := "gotcalled" - testMap := map[string]string{"C": "D"} - f := New().Funcs( - func(s *string, c Continue) { - *s = testPhrase - }, - func(m map[string]string, c Continue) { - m["C"] = "D" - }, - ) - - tryFuzz(t, f, obj, func() (int, bool) { - if obj.A != testPhrase { - return 1, false - } - if obj.B == nil { - return 2, false - } - if *obj.B != testPhrase { - return 3, false - } - if e, a := testMap, obj.C; !reflect.DeepEqual(e, a) { - return 4, false - } - if obj.D == nil { - return 5, false - } - if e, a := testMap, *obj.D; !reflect.DeepEqual(e, a) { - return 6, false - } - return 7, true - }) -} - -type SelfFuzzer string - -// Implement fuzz.Interface. -func (sf *SelfFuzzer) Fuzz(c Continue) { - *sf = selfFuzzerTestPhrase -} - -const selfFuzzerTestPhrase = "was fuzzed" - -func TestFuzz_interface(t *testing.T) { - f := New() - - var obj1 SelfFuzzer - tryFuzz(t, f, &obj1, func() (int, bool) { - if obj1 != selfFuzzerTestPhrase { - return 1, false - } - return 1, true - }) - - var obj2 map[int]SelfFuzzer - tryFuzz(t, f, &obj2, func() (int, bool) { - for _, v := range obj2 { - if v != selfFuzzerTestPhrase { - return 1, false - } - } - return 1, true - }) -} - -func TestFuzz_interfaceAndFunc(t *testing.T) { - const privateTestPhrase = "private phrase" - f := New().Funcs( - // This should take precedence over SelfFuzzer.Fuzz(). - func(s *SelfFuzzer, c Continue) { - *s = privateTestPhrase - }, - ) - - var obj1 SelfFuzzer - tryFuzz(t, f, &obj1, func() (int, bool) { - if obj1 != privateTestPhrase { - return 1, false - } - return 1, true - }) - - var obj2 map[int]SelfFuzzer - tryFuzz(t, f, &obj2, func() (int, bool) { - for _, v := range obj2 { - if v != privateTestPhrase { - return 1, false - } - } - return 1, true - }) -} - -func TestFuzz_noCustom(t *testing.T) { - type Inner struct { - Str string - } - type Outer struct { - Str string - In Inner - } - - testPhrase := "gotcalled" - f := New().Funcs( - func(outer *Outer, c Continue) { - outer.Str = testPhrase - c.Fuzz(&outer.In) - }, - func(inner *Inner, c Continue) { - inner.Str = testPhrase - }, - ) - c := Continue{fc: &fuzzerContext{fuzzer: f}, Rand: f.r} - - // Fuzzer.Fuzz() - obj1 := Outer{} - f.Fuzz(&obj1) - if obj1.Str != testPhrase { - t.Errorf("expected Outer custom function to have been called") - } - if obj1.In.Str != testPhrase { - t.Errorf("expected Inner custom function to have been called") - } - - // Continue.Fuzz() - obj2 := Outer{} - c.Fuzz(&obj2) - if obj2.Str != testPhrase { - t.Errorf("expected Outer custom function to have been called") - } - if obj2.In.Str != testPhrase { - t.Errorf("expected Inner custom function to have been called") - } - - // Fuzzer.FuzzNoCustom() - obj3 := Outer{} - f.FuzzNoCustom(&obj3) - if obj3.Str == testPhrase { - t.Errorf("expected Outer custom function to not have been called") - } - if obj3.In.Str != testPhrase { - t.Errorf("expected Inner custom function to have been called") - } - - // Continue.FuzzNoCustom() - obj4 := Outer{} - c.FuzzNoCustom(&obj4) - if obj4.Str == testPhrase { - t.Errorf("expected Outer custom function to not have been called") - } - if obj4.In.Str != testPhrase { - t.Errorf("expected Inner custom function to have been called") - } -} - -func TestFuzz_NumElements(t *testing.T) { - f := New().NilChance(0).NumElements(0, 1) - obj := &struct { - A []int - }{} - - tryFuzz(t, f, obj, func() (int, bool) { - if obj.A == nil { - return 1, false - } - return 2, len(obj.A) == 0 - }) - tryFuzz(t, f, obj, func() (int, bool) { - if obj.A == nil { - return 3, false - } - return 4, len(obj.A) == 1 - }) -} - -func TestFuzz_Maxdepth(t *testing.T) { - type S struct { - S *S - } - - f := New().NilChance(0) - - f.MaxDepth(1) - for i := 0; i < 100; i++ { - obj := S{} - f.Fuzz(&obj) - - if obj.S != nil { - t.Errorf("Expected nil") - } - } - - f.MaxDepth(3) // field, ptr - for i := 0; i < 100; i++ { - obj := S{} - f.Fuzz(&obj) - - if obj.S == nil { - t.Errorf("Expected obj.S not nil") - } else if obj.S.S != nil { - t.Errorf("Expected obj.S.S nil") - } - } - - f.MaxDepth(5) // field, ptr, field, ptr - for i := 0; i < 100; i++ { - obj := S{} - f.Fuzz(&obj) - - if obj.S == nil { - t.Errorf("Expected obj.S not nil") - } else if obj.S.S == nil { - t.Errorf("Expected obj.S.S not nil") - } else if obj.S.S.S != nil { - t.Errorf("Expected obj.S.S.S nil") - } - } -} diff --git a/vendor/github.com/gophercloud/gophercloud/.gitignore b/vendor/github.com/gophercloud/gophercloud/.gitignore deleted file mode 100644 index ead84456e..000000000 --- a/vendor/github.com/gophercloud/gophercloud/.gitignore +++ /dev/null @@ -1 +0,0 @@ -**/*.swp diff --git a/vendor/github.com/gophercloud/gophercloud/.travis.yml b/vendor/github.com/gophercloud/gophercloud/.travis.yml deleted file mode 100644 index 59c419495..000000000 --- a/vendor/github.com/gophercloud/gophercloud/.travis.yml +++ /dev/null @@ -1,21 +0,0 @@ -language: go -sudo: false -install: -- go get golang.org/x/crypto/ssh -- go get -v -tags 'fixtures acceptance' ./... -- go get github.com/wadey/gocovmerge -- go get github.com/mattn/goveralls -- go get golang.org/x/tools/cmd/goimports -go: -- 1.8 -- tip -env: - global: - - secure: "xSQsAG5wlL9emjbCdxzz/hYQsSpJ/bABO1kkbwMSISVcJ3Nk0u4ywF+LS4bgeOnwPfmFvNTOqVDu3RwEvMeWXSI76t1piCPcObutb2faKLVD/hLoAS76gYX+Z8yGWGHrSB7Do5vTPj1ERe2UljdrnsSeOXzoDwFxYRaZLX4bBOB4AyoGvRniil5QXPATiA1tsWX1VMicj8a4F8X+xeESzjt1Q5Iy31e7vkptu71bhvXCaoo5QhYwT+pLR9dN0S1b7Ro0KVvkRefmr1lUOSYd2e74h6Lc34tC1h3uYZCS4h47t7v5cOXvMNxinEj2C51RvbjvZI1RLVdkuAEJD1Iz4+Ote46nXbZ//6XRZMZz/YxQ13l7ux1PFjgEB6HAapmF5Xd8PRsgeTU9LRJxpiTJ3P5QJ3leS1va8qnziM5kYipj/Rn+V8g2ad/rgkRox9LSiR9VYZD2Pe45YCb1mTKSl2aIJnV7nkOqsShY5LNB4JZSg7xIffA+9YVDktw8dJlATjZqt7WvJJ49g6A61mIUV4C15q2JPGKTkZzDiG81NtmS7hFa7k0yaE2ELgYocbcuyUcAahhxntYTC0i23nJmEHVNiZmBO3u7EgpWe4KGVfumU+lt12tIn5b3dZRBBUk3QakKKozSK1QPHGpk/AZGrhu7H6l8to6IICKWtDcyMPQ=" -before_script: -- go vet ./... -script: -- ./script/coverage -- ./script/format -after_success: -- $HOME/gopath/bin/goveralls -service=travis-ci -coverprofile=cover.out diff --git a/vendor/github.com/gophercloud/gophercloud/FAQ.md b/vendor/github.com/gophercloud/gophercloud/FAQ.md deleted file mode 100644 index 88a366a28..000000000 --- a/vendor/github.com/gophercloud/gophercloud/FAQ.md +++ /dev/null @@ -1,148 +0,0 @@ -# Tips - -## Implementing default logging and re-authentication attempts - -You can implement custom logging and/or limit re-auth attempts by creating a custom HTTP client -like the following and setting it as the provider client's HTTP Client (via the -`gophercloud.ProviderClient.HTTPClient` field): - -```go -//... - -// LogRoundTripper satisfies the http.RoundTripper interface and is used to -// customize the default Gophercloud RoundTripper to allow for logging. -type LogRoundTripper struct { - rt http.RoundTripper - numReauthAttempts int -} - -// newHTTPClient return a custom HTTP client that allows for logging relevant -// information before and after the HTTP request. -func newHTTPClient() http.Client { - return http.Client{ - Transport: &LogRoundTripper{ - rt: http.DefaultTransport, - }, - } -} - -// RoundTrip performs a round-trip HTTP request and logs relevant information about it. -func (lrt *LogRoundTripper) RoundTrip(request *http.Request) (*http.Response, error) { - glog.Infof("Request URL: %s\n", request.URL) - - response, err := lrt.rt.RoundTrip(request) - if response == nil { - return nil, err - } - - if response.StatusCode == http.StatusUnauthorized { - if lrt.numReauthAttempts == 3 { - return response, fmt.Errorf("Tried to re-authenticate 3 times with no success.") - } - lrt.numReauthAttempts++ - } - - glog.Debugf("Response Status: %s\n", response.Status) - - return response, nil -} - -endpoint := "https://127.0.0.1/auth" -pc := openstack.NewClient(endpoint) -pc.HTTPClient = newHTTPClient() - -//... -``` - - -## Implementing custom objects - -OpenStack request/response objects may differ among variable names or types. - -### Custom request objects - -To pass custom options to a request, implement the desired `OptsBuilder` interface. For -example, to pass in - -```go -type MyCreateServerOpts struct { - Name string - Size int -} -``` - -to `servers.Create`, simply implement the `servers.CreateOptsBuilder` interface: - -```go -func (o MyCreateServeropts) ToServerCreateMap() (map[string]interface{}, error) { - return map[string]interface{}{ - "name": o.Name, - "size": o.Size, - }, nil -} -``` - -create an instance of your custom options object, and pass it to `servers.Create`: - -```go -// ... -myOpts := MyCreateServerOpts{ - Name: "s1", - Size: "100", -} -server, err := servers.Create(computeClient, myOpts).Extract() -// ... -``` - -### Custom response objects - -Some OpenStack services have extensions. Extensions that are supported in Gophercloud can be -combined to create a custom object: - -```go -// ... -type MyVolume struct { - volumes.Volume - tenantattr.VolumeExt -} - -var v struct { - MyVolume `json:"volume"` -} - -err := volumes.Get(client, volID).ExtractInto(&v) -// ... -``` - -## Overriding default `UnmarshalJSON` method - -For some response objects, a field may be a custom type or may be allowed to take on -different types. In these cases, overriding the default `UnmarshalJSON` method may be -necessary. To do this, declare the JSON `struct` field tag as "-" and create an `UnmarshalJSON` -method on the type: - -```go -// ... -type MyVolume struct { - ID string `json: "id"` - TimeCreated time.Time `json: "-"` -} - -func (r *MyVolume) UnmarshalJSON(b []byte) error { - type tmp MyVolume - var s struct { - tmp - TimeCreated gophercloud.JSONRFC3339MilliNoZ `json:"created_at"` - } - err := json.Unmarshal(b, &s) - if err != nil { - return err - } - *r = Volume(s.tmp) - - r.TimeCreated = time.Time(s.CreatedAt) - - return err -} -// ... -``` diff --git a/vendor/github.com/gophercloud/gophercloud/MIGRATING.md b/vendor/github.com/gophercloud/gophercloud/MIGRATING.md deleted file mode 100644 index aa383c9cc..000000000 --- a/vendor/github.com/gophercloud/gophercloud/MIGRATING.md +++ /dev/null @@ -1,32 +0,0 @@ -# Compute - -## Floating IPs - -* `github.com/gophercloud/gophercloud/openstack/compute/v2/extensions/floatingip` is now `github.com/gophercloud/gophercloud/openstack/compute/v2/extensions/floatingips` -* `floatingips.Associate` and `floatingips.Disassociate` have been removed. -* `floatingips.DisassociateOpts` is now required to disassociate a Floating IP. - -## Security Groups - -* `secgroups.AddServerToGroup` is now `secgroups.AddServer`. -* `secgroups.RemoveServerFromGroup` is now `secgroups.RemoveServer`. - -## Servers - -* `servers.Reboot` now requires a `servers.RebootOpts` struct: - - ```golang - rebootOpts := &servers.RebootOpts{ - Type: servers.SoftReboot, - } - res := servers.Reboot(client, server.ID, rebootOpts) - ``` - -# Identity - -## V3 - -### Tokens - -* `Token.ExpiresAt` is now of type `gophercloud.JSONRFC3339Milli` instead of - `time.Time` diff --git a/vendor/github.com/gophercloud/gophercloud/README.md b/vendor/github.com/gophercloud/gophercloud/README.md deleted file mode 100644 index 60ca479de..000000000 --- a/vendor/github.com/gophercloud/gophercloud/README.md +++ /dev/null @@ -1,143 +0,0 @@ -# Gophercloud: an OpenStack SDK for Go -[![Build Status](https://travis-ci.org/gophercloud/gophercloud.svg?branch=master)](https://travis-ci.org/gophercloud/gophercloud) -[![Coverage Status](https://coveralls.io/repos/github/gophercloud/gophercloud/badge.svg?branch=master)](https://coveralls.io/github/gophercloud/gophercloud?branch=master) - -Gophercloud is an OpenStack Go SDK. - -## Useful links - -* [Reference documentation](http://godoc.org/github.com/gophercloud/gophercloud) -* [Effective Go](https://golang.org/doc/effective_go.html) - -## How to install - -Before installing, you need to ensure that your [GOPATH environment variable](https://golang.org/doc/code.html#GOPATH) -is pointing to an appropriate directory where you want to install Gophercloud: - -```bash -mkdir $HOME/go -export GOPATH=$HOME/go -``` - -To protect yourself against changes in your dependencies, we highly recommend choosing a -[dependency management solution](https://github.com/golang/go/wiki/PackageManagementTools) for -your projects, such as [godep](https://github.com/tools/godep). Once this is set up, you can install -Gophercloud as a dependency like so: - -```bash -go get github.com/gophercloud/gophercloud - -# Edit your code to import relevant packages from "github.com/gophercloud/gophercloud" - -godep save ./... -``` - -This will install all the source files you need into a `Godeps/_workspace` directory, which is -referenceable from your own source files when you use the `godep go` command. - -## Getting started - -### Credentials - -Because you'll be hitting an API, you will need to retrieve your OpenStack -credentials and either store them as environment variables or in your local Go -files. The first method is recommended because it decouples credential -information from source code, allowing you to push the latter to your version -control system without any security risk. - -You will need to retrieve the following: - -* username -* password -* a valid Keystone identity URL - -For users that have the OpenStack dashboard installed, there's a shortcut. If -you visit the `project/access_and_security` path in Horizon and click on the -"Download OpenStack RC File" button at the top right hand corner, you will -download a bash file that exports all of your access details to environment -variables. To execute the file, run `source admin-openrc.sh` and you will be -prompted for your password. - -### Authentication - -Once you have access to your credentials, you can begin plugging them into -Gophercloud. The next step is authentication, and this is handled by a base -"Provider" struct. To get one, you can either pass in your credentials -explicitly, or tell Gophercloud to use environment variables: - -```go -import ( - "github.com/gophercloud/gophercloud" - "github.com/gophercloud/gophercloud/openstack" - "github.com/gophercloud/gophercloud/openstack/utils" -) - -// Option 1: Pass in the values yourself -opts := gophercloud.AuthOptions{ - IdentityEndpoint: "https://openstack.example.com:5000/v2.0", - Username: "{username}", - Password: "{password}", -} - -// Option 2: Use a utility function to retrieve all your environment variables -opts, err := openstack.AuthOptionsFromEnv() -``` - -Once you have the `opts` variable, you can pass it in and get back a -`ProviderClient` struct: - -```go -provider, err := openstack.AuthenticatedClient(opts) -``` - -The `ProviderClient` is the top-level client that all of your OpenStack services -derive from. The provider contains all of the authentication details that allow -your Go code to access the API - such as the base URL and token ID. - -### Provision a server - -Once we have a base Provider, we inject it as a dependency into each OpenStack -service. In order to work with the Compute API, we need a Compute service -client; which can be created like so: - -```go -client, err := openstack.NewComputeV2(provider, gophercloud.EndpointOpts{ - Region: os.Getenv("OS_REGION_NAME"), -}) -``` - -We then use this `client` for any Compute API operation we want. In our case, -we want to provision a new server - so we invoke the `Create` method and pass -in the flavor ID (hardware specification) and image ID (operating system) we're -interested in: - -```go -import "github.com/gophercloud/gophercloud/openstack/compute/v2/servers" - -server, err := servers.Create(client, servers.CreateOpts{ - Name: "My new server!", - FlavorRef: "flavor_id", - ImageRef: "image_id", -}).Extract() -``` - -The above code sample creates a new server with the parameters, and embodies the -new resource in the `server` variable (a -[`servers.Server`](http://godoc.org/github.com/gophercloud/gophercloud) struct). - -## Advanced Usage - -Have a look at the [FAQ](./FAQ.md) for some tips on customizing the way Gophercloud works. - -## Backwards-Compatibility Guarantees - -None. Vendor it and write tests covering the parts you use. - -## Contributing - -See the [contributing guide](./.github/CONTRIBUTING.md). - -## Help and feedback - -If you're struggling with something or have spotted a potential bug, feel free -to submit an issue to our [bug tracker](/issues). diff --git a/vendor/github.com/gophercloud/gophercloud/STYLEGUIDE.md b/vendor/github.com/gophercloud/gophercloud/STYLEGUIDE.md deleted file mode 100644 index e7531a83d..000000000 --- a/vendor/github.com/gophercloud/gophercloud/STYLEGUIDE.md +++ /dev/null @@ -1,74 +0,0 @@ - -## On Pull Requests - -- Before you start a PR there needs to be a Github issue and a discussion about it - on that issue with a core contributor, even if it's just a 'SGTM'. - -- A PR's description must reference the issue it closes with a `For ` (e.g. For #293). - -- A PR's description must contain link(s) to the line(s) in the OpenStack - source code (on Github) that prove(s) the PR code to be valid. Links to documentation - are not good enough. The link(s) should be to a non-`master` branch. For example, - a pull request implementing the creation of a Neutron v2 subnet might put the - following link in the description: - - https://github.com/openstack/neutron/blob/stable/mitaka/neutron/api/v2/attributes.py#L749 - - From that link, a reviewer (or user) can verify the fields in the request/response - objects in the PR. - -- A PR that is in-progress should have `[wip]` in front of the PR's title. When - ready for review, remove the `[wip]` and ping a core contributor with an `@`. - -- Forcing PRs to be small can have the effect of users submitting PRs in a hierarchical chain, with - one depending on the next. If a PR depends on another one, it should have a [Pending #PRNUM] - prefix in the PR title. In addition, it will be the PR submitter's responsibility to remove the - [Pending #PRNUM] tag once the PR has been updated with the merged, dependent PR. That will - let reviewers know it is ready to review. - -- A PR should be small. Even if you intend on implementing an entire - service, a PR should only be one route of that service - (e.g. create server or get server, but not both). - -- Unless explicitly asked, do not squash commits in the middle of a review; only - append. It makes it difficult for the reviewer to see what's changed from one - review to the next. - -## On Code - -- In re design: follow as closely as is reasonable the code already in the library. - Most operations (e.g. create, delete) admit the same design. - -- Unit tests and acceptance (integration) tests must be written to cover each PR. - Tests for operations with several options (e.g. list, create) should include all - the options in the tests. This will allow users to verify an operation on their - own infrastructure and see an example of usage. - -- If in doubt, ask in-line on the PR. - -### File Structure - -- The following should be used in most cases: - - - `requests.go`: contains all the functions that make HTTP requests and the - types associated with the HTTP request (parameters for URL, body, etc) - - `results.go`: contains all the response objects and their methods - - `urls.go`: contains the endpoints to which the requests are made - -### Naming - -- For methods on a type in `results.go`, the receiver should be named `r` and the - variable into which it will be unmarshalled `s`. - -- Functions in `requests.go`, with the exception of functions that return a - `pagination.Pager`, should be named returns of the name `r`. - -- Functions in `requests.go` that accept request bodies should accept as their - last parameter an `interface` named `OptsBuilder` (eg `CreateOptsBuilder`). - This `interface` should have at the least a method named `ToMap` - (eg `ToPortCreateMap`). - -- Functions in `requests.go` that accept query strings should accept as their - last parameter an `interface` named `OptsBuilder` (eg `ListOptsBuilder`). - This `interface` should have at the least a method named `ToQuery` - (eg `ToServerListQuery`). diff --git a/vendor/github.com/gophercloud/gophercloud/openstack/compute/v2/extensions/delegate.go b/vendor/github.com/gophercloud/gophercloud/openstack/compute/v2/extensions/delegate.go deleted file mode 100644 index 00e7c3bec..000000000 --- a/vendor/github.com/gophercloud/gophercloud/openstack/compute/v2/extensions/delegate.go +++ /dev/null @@ -1,23 +0,0 @@ -package extensions - -import ( - "github.com/gophercloud/gophercloud" - common "github.com/gophercloud/gophercloud/openstack/common/extensions" - "github.com/gophercloud/gophercloud/pagination" -) - -// ExtractExtensions interprets a Page as a slice of Extensions. -func ExtractExtensions(page pagination.Page) ([]common.Extension, error) { - return common.ExtractExtensions(page) -} - -// Get retrieves information for a specific extension using its alias. -func Get(c *gophercloud.ServiceClient, alias string) common.GetResult { - return common.Get(c, alias) -} - -// List returns a Pager which allows you to iterate over the full collection of extensions. -// It does not accept query parameters. -func List(c *gophercloud.ServiceClient) pagination.Pager { - return common.List(c) -} diff --git a/vendor/github.com/gophercloud/gophercloud/openstack/compute/v2/extensions/doc.go b/vendor/github.com/gophercloud/gophercloud/openstack/compute/v2/extensions/doc.go deleted file mode 100644 index 2b447da1d..000000000 --- a/vendor/github.com/gophercloud/gophercloud/openstack/compute/v2/extensions/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -// Package extensions provides information and interaction with the -// different extensions available for the OpenStack Compute service. -package extensions diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/.gitignore b/vendor/github.com/grpc-ecosystem/grpc-gateway/.gitignore deleted file mode 100644 index eb1543328..000000000 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -_output/ -.idea diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/.travis.yml b/vendor/github.com/grpc-ecosystem/grpc-gateway/.travis.yml deleted file mode 100644 index eea6dd820..000000000 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/.travis.yml +++ /dev/null @@ -1,38 +0,0 @@ -language: go -sudo: false -go: -- 1.7.x -- 1.8.x -- 1.9.x -- master -go_import_path: github.com/grpc-ecosystem/grpc-gateway -cache: - directories: - - $HOME/local - - ${TRAVIS_BUILD_DIR}/examples/browser/node_modules -before_install: -- ./.travis/install-protoc.sh 3.1.0 -- ./.travis/install-swagger-codegen.sh 2.2.2 -- nvm install v6.1 && nvm use v6.1 && node --version -- go get github.com/golang/lint/golint -- go get github.com/dghubble/sling -- go get github.com/go-resty/resty -install: -- go get github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway -- go get github.com/grpc-ecosystem/grpc-gateway/runtime -- go get github.com/grpc-ecosystem/grpc-gateway/examples -- go get github.com/grpc-ecosystem/grpc-gateway/examples/server -before_script: -- sh -c 'cd examples/browser && npm install' -script: -- make realclean && make examples SWAGGER_CODEGEN="java -jar $HOME/local/swagger-codegen-cli.jar" -- if (go version | grep -q 1.8) && [ -z "${GATEWAY_PLUGIN_FLAGS}" ]; then test -z "$(git status --porcelain)" || (git status; git diff; exit 1); fi -- env GLOG_logtostderr=1 go test -race -v github.com/grpc-ecosystem/grpc-gateway/... -- make lint -- sh -c 'cd examples/browser && node ./node_modules/gulp/bin/gulp' -env: - global: - - "PATH=$PATH:$HOME/local/bin" - matrix: - - GATEWAY_PLUGIN_FLAGS= - - GATEWAY_PLUGIN_FLAGS=request_context=false diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/CHANGELOG.md b/vendor/github.com/grpc-ecosystem/grpc-gateway/CHANGELOG.md deleted file mode 100644 index 285589491..000000000 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/CHANGELOG.md +++ /dev/null @@ -1,215 +0,0 @@ -# Change Log - -## [1.3.1](https://github.com/grpc-ecosystem/grpc-gateway/tree/1.3.1) (2017-12-23) -**Merged pull requests:** - -- Add support for --Import\_path [\#507](https://github.com/grpc-ecosystem/grpc-gateway/pull/507) -- Fix \#504 Missing Definitions [\#505](https://github.com/grpc-ecosystem/grpc-gateway/pull/505) -- Maintain default delimiter of newline [\#497](https://github.com/grpc-ecosystem/grpc-gateway/pull/497) -- Fix gen-swagger to support more well known types [\#496](https://github.com/grpc-ecosystem/grpc-gateway/pull/496) -- Use golang/protobuf instead of gogo/protobuf [\#494](https://github.com/grpc-ecosystem/grpc-gateway/pull/494) -- Fix stream delimiters [\#488](https://github.com/grpc-ecosystem/grpc-gateway/pull/488) -- ForwardResponseStream status code errors [\#482](https://github.com/grpc-ecosystem/grpc-gateway/pull/482) -- protoc-gen-grpc-gateway: flip request\_context default to true [\#474](https://github.com/grpc-ecosystem/grpc-gateway/pull/474) -- grpc-gateway/generator: respect full package [\#462](https://github.com/grpc-ecosystem/grpc-gateway/pull/462) -- Add proto marshaller for proto-over-http [\#459](https://github.com/grpc-ecosystem/grpc-gateway/pull/459) - -## [v1.3](https://github.com/grpc-ecosystem/grpc-gateway/tree/v1.3) (2017-11-03) -## [v1.3.0](https://github.com/grpc-ecosystem/grpc-gateway/tree/v1.3.0) (2017-11-03) -**Merged pull requests:** - -- Streaming forward handler fix chunk encoding [\#479](https://github.com/grpc-ecosystem/grpc-gateway/pull/479) -- Fix logic handling primitive wrapper in URL params [\#478](https://github.com/grpc-ecosystem/grpc-gateway/pull/478) -- runtime: use r.Context\(\) [\#473](https://github.com/grpc-ecosystem/grpc-gateway/pull/473) -- Optional SourceCodeInfo [\#466](https://github.com/grpc-ecosystem/grpc-gateway/pull/466) -- Some steps to fix Travis CI [\#461](https://github.com/grpc-ecosystem/grpc-gateway/pull/461) -- fix 2 typos in Registry.SetPrefix's comment [\#455](https://github.com/grpc-ecosystem/grpc-gateway/pull/455) -- Add Handler method to pass in client [\#454](https://github.com/grpc-ecosystem/grpc-gateway/pull/454) -- Fallback to JSON name when matching URL parameter. [\#450](https://github.com/grpc-ecosystem/grpc-gateway/pull/450) -- Update DO NOT EDIT template. [\#434](https://github.com/grpc-ecosystem/grpc-gateway/pull/434) -- Memoise calls to fullyQualifiedNameToSwaggerName to speed it up for large registries [\#421](https://github.com/grpc-ecosystem/grpc-gateway/pull/421) -- Update Swagger Codegen from 2.1.6 to 2.2.2 [\#415](https://github.com/grpc-ecosystem/grpc-gateway/pull/415) -- Return codes.InvalidArgument to rather return HTTP 400 instead of HTTP 500 [\#409](https://github.com/grpc-ecosystem/grpc-gateway/pull/409) -- improve {incoming,outgoing}HeaderMatcher logic [\#408](https://github.com/grpc-ecosystem/grpc-gateway/pull/408) -- improve WKT handling in gateway and openapi output [\#404](https://github.com/grpc-ecosystem/grpc-gateway/pull/404) -- Return if runtime.AnnotateContext gave error [\#403](https://github.com/grpc-ecosystem/grpc-gateway/pull/403) -- jsonpb: update tests to reflect new jsonpb behavior [\#401](https://github.com/grpc-ecosystem/grpc-gateway/pull/401) -- Reference import grpc Status to suppress unused errors. [\#387](https://github.com/grpc-ecosystem/grpc-gateway/pull/387) -- ci: regen with current protoc-gen-go [\#385](https://github.com/grpc-ecosystem/grpc-gateway/pull/385) -- Use status package for error and introduce WithProtoErrorHandler option [\#378](https://github.com/grpc-ecosystem/grpc-gateway/pull/378) -- Return response headers from grpc server [\#374](https://github.com/grpc-ecosystem/grpc-gateway/pull/374) -- Skip unreferenced messages in definitions. [\#371](https://github.com/grpc-ecosystem/grpc-gateway/pull/371) -- Use canonical header form in default header matcher. [\#369](https://github.com/grpc-ecosystem/grpc-gateway/pull/369) -- support allow\_delete\_body for protoc-gen-grpc-gateway [\#318](https://github.com/grpc-ecosystem/grpc-gateway/pull/318) -- fixes package name override doesn't work [\#277](https://github.com/grpc-ecosystem/grpc-gateway/pull/277) -- add custom options to allow more control of swagger/openapi output [\#145](https://github.com/grpc-ecosystem/grpc-gateway/pull/145) - -## [v1.2.2](https://github.com/grpc-ecosystem/grpc-gateway/tree/v1.2.2) (2017-04-17) -**Merged pull requests:** - -- Add changelog for 1.2.2 [\#363](https://github.com/grpc-ecosystem/grpc-gateway/pull/363) -- metadata: fix properly and change to Outgoing [\#361](https://github.com/grpc-ecosystem/grpc-gateway/pull/361) - -## [v1.2.1](https://github.com/grpc-ecosystem/grpc-gateway/tree/v1.2.1) (2017-04-17) -**Merged pull requests:** - -- Add changelog for 1.2.1 [\#360](https://github.com/grpc-ecosystem/grpc-gateway/pull/360) -- bugfix: reflect upstream api change. [\#359](https://github.com/grpc-ecosystem/grpc-gateway/pull/359) - -## [v1.2.0](https://github.com/grpc-ecosystem/grpc-gateway/tree/v1.2.0) (2017-03-31) -**Merged pull requests:** - -- Add changelog for 1.2.0 [\#342](https://github.com/grpc-ecosystem/grpc-gateway/pull/342) - -## [v1.2.0.rc1](https://github.com/grpc-ecosystem/grpc-gateway/tree/v1.2.0.rc1) (2017-03-24) -**Merged pull requests:** - -- Support user configurable header forwarding & context metadata [\#336](https://github.com/grpc-ecosystem/grpc-gateway/pull/336) -- Update go\_out parameter to remove comma [\#333](https://github.com/grpc-ecosystem/grpc-gateway/pull/333) -- Update stale path in README [\#332](https://github.com/grpc-ecosystem/grpc-gateway/pull/332) -- improve documentation regarding external dependencies [\#330](https://github.com/grpc-ecosystem/grpc-gateway/pull/330) -- Return an error on invalid nested query parameters. [\#329](https://github.com/grpc-ecosystem/grpc-gateway/pull/329) -- Update upstream proto files and add google.golang.org/genproto support. [\#325](https://github.com/grpc-ecosystem/grpc-gateway/pull/325) -- Support oneof fields in query params [\#321](https://github.com/grpc-ecosystem/grpc-gateway/pull/321) -- Do not ignore the error coming from http.ListenAndServe in examples [\#319](https://github.com/grpc-ecosystem/grpc-gateway/pull/319) -- Look up enum value maps by their proto name [\#315](https://github.com/grpc-ecosystem/grpc-gateway/pull/315) -- enable parsing enums from query parameters [\#314](https://github.com/grpc-ecosystem/grpc-gateway/pull/314) -- Do not add imports from methods with no bindings. [\#312](https://github.com/grpc-ecosystem/grpc-gateway/pull/312) -- Convert the first letter of method name to upper [\#300](https://github.com/grpc-ecosystem/grpc-gateway/pull/300) -- write query parameters to swagger definition [\#297](https://github.com/grpc-ecosystem/grpc-gateway/pull/297) -- Bump swagger-client to 2.1.28 for examples/browser [\#290](https://github.com/grpc-ecosystem/grpc-gateway/pull/290) -- pin to version before es6ism [\#289](https://github.com/grpc-ecosystem/grpc-gateway/pull/289) -- Prevent lack of http bindings from generating non-building output [\#286](https://github.com/grpc-ecosystem/grpc-gateway/pull/286) -- Added support for Timestamp in URL. [\#281](https://github.com/grpc-ecosystem/grpc-gateway/pull/281) -- add plugin param 'allow\_delete\_body' [\#280](https://github.com/grpc-ecosystem/grpc-gateway/pull/280) -- Fix ruby gen command [\#275](https://github.com/grpc-ecosystem/grpc-gateway/pull/275) -- Make grpc-gateway support enum fields in path parameter [\#273](https://github.com/grpc-ecosystem/grpc-gateway/pull/273) -- remove unnecessary make\(\) [\#271](https://github.com/grpc-ecosystem/grpc-gateway/pull/271) -- preserve field order in swagger spec [\#270](https://github.com/grpc-ecosystem/grpc-gateway/pull/270) -- Merge \#228 [\#268](https://github.com/grpc-ecosystem/grpc-gateway/pull/268) -- Handle methods with no bindings more carefully [\#267](https://github.com/grpc-ecosystem/grpc-gateway/pull/267) -- describe default marshaler in README.md [\#266](https://github.com/grpc-ecosystem/grpc-gateway/pull/266) -- Add request\_context flag to utilize \(\*http.Request\).Context\(\) in handlers [\#265](https://github.com/grpc-ecosystem/grpc-gateway/pull/265) -- Regenerate examples [\#264](https://github.com/grpc-ecosystem/grpc-gateway/pull/264) -- Correct runtime.errorBody protobuf field tag [\#256](https://github.com/grpc-ecosystem/grpc-gateway/pull/256) -- Pass permanent HTTP request headers [\#252](https://github.com/grpc-ecosystem/grpc-gateway/pull/252) -- regenerate examples, fix tests for go tip [\#248](https://github.com/grpc-ecosystem/grpc-gateway/pull/248) -- Render the swagger request body properly [\#247](https://github.com/grpc-ecosystem/grpc-gateway/pull/247) -- Error output should have lowercase attribute names [\#244](https://github.com/grpc-ecosystem/grpc-gateway/pull/244) -- runtime - export prefix constants [\#236](https://github.com/grpc-ecosystem/grpc-gateway/pull/236) -- README - Add CoreOS example [\#231](https://github.com/grpc-ecosystem/grpc-gateway/pull/231) -- Docs - Add section about how HTTP maps to gRPC [\#227](https://github.com/grpc-ecosystem/grpc-gateway/pull/227) -- readme: added links to additional documentation [\#222](https://github.com/grpc-ecosystem/grpc-gateway/pull/222) -- Use a released version of protoc [\#216](https://github.com/grpc-ecosystem/grpc-gateway/pull/216) -- Add contribution guideline [\#210](https://github.com/grpc-ecosystem/grpc-gateway/pull/210) -- improve\(genswagger:template\):added support for google.protobuf.Timestamp [\#209](https://github.com/grpc-ecosystem/grpc-gateway/pull/209) -- Allowing unknown fields to be dropped instead of returning error from… [\#208](https://github.com/grpc-ecosystem/grpc-gateway/pull/208) -- Avoid Internal Server Error on zero-length input for bidi streaming [\#200](https://github.com/grpc-ecosystem/grpc-gateway/pull/200) - -## [v1.1.0](https://github.com/grpc-ecosystem/grpc-gateway/tree/v1.1.0) (2016-07-23) -**Merged pull requests:** - -- Rename packages to follow the repository transfer [\#192](https://github.com/grpc-ecosystem/grpc-gateway/pull/192) -- return err early if EOF to prevent logging in normal conditions [\#191](https://github.com/grpc-ecosystem/grpc-gateway/pull/191) -- send Trailer header on error [\#188](https://github.com/grpc-ecosystem/grpc-gateway/pull/188) -- generate swagger output for streaming endpoints with a basic note [\#183](https://github.com/grpc-ecosystem/grpc-gateway/pull/183) - -## [v1.0.0](https://github.com/grpc-ecosystem/grpc-gateway/tree/v1.0.0) (2016-06-15) -**Merged pull requests:** - -- Regenerate files with the latest protoc-gen-go [\#185](https://github.com/grpc-ecosystem/grpc-gateway/pull/185) -- Add browser examples [\#184](https://github.com/grpc-ecosystem/grpc-gateway/pull/184) -- Fix golint and go vet errors [\#182](https://github.com/grpc-ecosystem/grpc-gateway/pull/182) -- Add integration with clients generated by swagger-codegen [\#181](https://github.com/grpc-ecosystem/grpc-gateway/pull/181) -- Simplify example services [\#180](https://github.com/grpc-ecosystem/grpc-gateway/pull/180) -- Avoid errors when req.RemoteAddr is empty [\#178](https://github.com/grpc-ecosystem/grpc-gateway/pull/178) -- Feature/headers [\#176](https://github.com/grpc-ecosystem/grpc-gateway/pull/176) -- Include HTTP req.remoteAddr in gRPC ctx [\#174](https://github.com/grpc-ecosystem/grpc-gateway/pull/174) -- Update dependencies [\#171](https://github.com/grpc-ecosystem/grpc-gateway/pull/171) -- Add bidirectional streaming support by running Send\(\) and Recv\(\) concurrently [\#170](https://github.com/grpc-ecosystem/grpc-gateway/pull/170) -- make Authorization header check case-insensitive to comply with RFC 2616 4.2 [\#164](https://github.com/grpc-ecosystem/grpc-gateway/pull/164) -- jsonpb: avoid duplicating upstream's struct [\#158](https://github.com/grpc-ecosystem/grpc-gateway/pull/158) -- Generate Swagger description for service methods using proto comments. [\#156](https://github.com/grpc-ecosystem/grpc-gateway/pull/156) -- Implement gRPC timeout support for inbound HTTP headers [\#155](https://github.com/grpc-ecosystem/grpc-gateway/pull/155) -- Add more examples to marshalers [\#154](https://github.com/grpc-ecosystem/grpc-gateway/pull/154) -- custom marshaler: handle `Accept` headers correctly [\#152](https://github.com/grpc-ecosystem/grpc-gateway/pull/152) -- Simplify custom marshaler API [\#151](https://github.com/grpc-ecosystem/grpc-gateway/pull/151) -- Fix camel case path parameter handling in swagger [\#149](https://github.com/grpc-ecosystem/grpc-gateway/pull/149) -- Swagger dot in path template [\#148](https://github.com/grpc-ecosystem/grpc-gateway/pull/148) -- Support map types in swagger generator [\#147](https://github.com/grpc-ecosystem/grpc-gateway/pull/147) -- Cleanup custom marshaler [\#146](https://github.com/grpc-ecosystem/grpc-gateway/pull/146) -- Implement custom Marshaler support, add jsonpb implemention. [\#144](https://github.com/grpc-ecosystem/grpc-gateway/pull/144) -- Allow period in path URL templates when generating Swagger templates. [\#143](https://github.com/grpc-ecosystem/grpc-gateway/pull/143) -- Link to LICENSE.txt [\#142](https://github.com/grpc-ecosystem/grpc-gateway/pull/142) -- Support map types in swagger generator [\#141](https://github.com/grpc-ecosystem/grpc-gateway/pull/141) -- Conditionally stops checking if generated file are up-to-date [\#136](https://github.com/grpc-ecosystem/grpc-gateway/pull/136) -- Generate Swagger description for service methods using proto comments. [\#134](https://github.com/grpc-ecosystem/grpc-gateway/pull/134) -- Swagger definitions now have `type` set to `object`. [\#133](https://github.com/grpc-ecosystem/grpc-gateway/pull/133) -- go\_package option as go import path [\#129](https://github.com/grpc-ecosystem/grpc-gateway/pull/129) -- Fix govet errors [\#126](https://github.com/grpc-ecosystem/grpc-gateway/pull/126) -- Fix data-race in generated codes [\#125](https://github.com/grpc-ecosystem/grpc-gateway/pull/125) -- Fix \#119 - CloseNotify race with ServeHTTP [\#120](https://github.com/grpc-ecosystem/grpc-gateway/pull/120) -- Replace glog with grpclog [\#118](https://github.com/grpc-ecosystem/grpc-gateway/pull/118) -- Fix a goroutine-leak in HTTP keep-alive [\#116](https://github.com/grpc-ecosystem/grpc-gateway/pull/116) -- Fix camel case path parameter handling in swagger [\#114](https://github.com/grpc-ecosystem/grpc-gateway/pull/114) -- gofmt -s [\#112](https://github.com/grpc-ecosystem/grpc-gateway/pull/112) -- fix typo [\#111](https://github.com/grpc-ecosystem/grpc-gateway/pull/111) -- fix typo [\#110](https://github.com/grpc-ecosystem/grpc-gateway/pull/110) -- fixes missing swagger operation objects [\#109](https://github.com/grpc-ecosystem/grpc-gateway/pull/109) -- Add parser and swagger support for enum, no gengateway yet [\#108](https://github.com/grpc-ecosystem/grpc-gateway/pull/108) -- README: add protoc-gen-swagger too [\#105](https://github.com/grpc-ecosystem/grpc-gateway/pull/105) -- README: Suggest go get -u by default. [\#104](https://github.com/grpc-ecosystem/grpc-gateway/pull/104) -- Cancel context when HTTP connection is closed [\#102](https://github.com/grpc-ecosystem/grpc-gateway/pull/102) -- wait test server up [\#100](https://github.com/grpc-ecosystem/grpc-gateway/pull/100) -- Fix the swagger section of the README.md [\#98](https://github.com/grpc-ecosystem/grpc-gateway/pull/98) -- Add documentation for using Swagger [\#97](https://github.com/grpc-ecosystem/grpc-gateway/pull/97) -- Better compatibility to field names generated by protoc-gen-go [\#96](https://github.com/grpc-ecosystem/grpc-gateway/pull/96) -- Update protoc from 3.0.0-beta1 to 3.0.0-beta2 [\#95](https://github.com/grpc-ecosystem/grpc-gateway/pull/95) -- Better grpc error strings [\#94](https://github.com/grpc-ecosystem/grpc-gateway/pull/94) -- make available header and trailer metadata [\#93](https://github.com/grpc-ecosystem/grpc-gateway/pull/93) -- make grpc.DialOption configurable [\#89](https://github.com/grpc-ecosystem/grpc-gateway/pull/89) -- Add request in error handlers [\#88](https://github.com/grpc-ecosystem/grpc-gateway/pull/88) -- Improve PascalFromSnake behavior [\#85](https://github.com/grpc-ecosystem/grpc-gateway/pull/85) -- Typo grcp -\> grpc [\#81](https://github.com/grpc-ecosystem/grpc-gateway/pull/81) -- Add abstraction of code generator implementation [\#78](https://github.com/grpc-ecosystem/grpc-gateway/pull/78) -- Support multivalue of metadata [\#77](https://github.com/grpc-ecosystem/grpc-gateway/pull/77) -- Fix broken test [\#76](https://github.com/grpc-ecosystem/grpc-gateway/pull/76) -- Added missing instruction line in README [\#75](https://github.com/grpc-ecosystem/grpc-gateway/pull/75) -- Fix a complie error in generated go files [\#71](https://github.com/grpc-ecosystem/grpc-gateway/pull/71) -- Update generated .pb.go files in third\_party [\#69](https://github.com/grpc-ecosystem/grpc-gateway/pull/69) -- Add swagger support [\#68](https://github.com/grpc-ecosystem/grpc-gateway/pull/68) -- Bugfix/handling headers for `Authorization` and `Host` [\#65](https://github.com/grpc-ecosystem/grpc-gateway/pull/65) -- Fix `error` field always in chunk response [\#64](https://github.com/grpc-ecosystem/grpc-gateway/pull/64) -- Update .pb.go to latest version. [\#63](https://github.com/grpc-ecosystem/grpc-gateway/pull/63) -- Run more tests in Travis CI [\#60](https://github.com/grpc-ecosystem/grpc-gateway/pull/60) -- Added http error code and error status for responseStreamChunk error [\#59](https://github.com/grpc-ecosystem/grpc-gateway/pull/59) -- Fix parsing of verb and final path component. [\#55](https://github.com/grpc-ecosystem/grpc-gateway/pull/55) -- Add runtime.WithForwardResponseOption [\#53](https://github.com/grpc-ecosystem/grpc-gateway/pull/53) -- add grpc.WithInsecure\(\) as option for grpc.Dial call in template [\#52](https://github.com/grpc-ecosystem/grpc-gateway/pull/52) -- update .pb.go files for latest golang proto generation [\#51](https://github.com/grpc-ecosystem/grpc-gateway/pull/51) -- Fix a build error with the latest protoc-gen-go [\#50](https://github.com/grpc-ecosystem/grpc-gateway/pull/50) -- Configure Travis CI [\#49](https://github.com/grpc-ecosystem/grpc-gateway/pull/49) -- Follow a change of go package name convention in protoc-gen-go [\#48](https://github.com/grpc-ecosystem/grpc-gateway/pull/48) -- Consider tail segments after deep wildcard [\#47](https://github.com/grpc-ecosystem/grpc-gateway/pull/47) -- Fix typo in README [\#45](https://github.com/grpc-ecosystem/grpc-gateway/pull/45) -- Fix undefined variable error in generated codes [\#42](https://github.com/grpc-ecosystem/grpc-gateway/pull/42) -- Follow changes in protoc-gen-go and grpc-go [\#41](https://github.com/grpc-ecosystem/grpc-gateway/pull/41) -- Fixes \#4 [\#40](https://github.com/grpc-ecosystem/grpc-gateway/pull/40) -- fix examples to work with go1.5 [\#39](https://github.com/grpc-ecosystem/grpc-gateway/pull/39) -- rename internal to utilties for 1.5 compatibility [\#38](https://github.com/grpc-ecosystem/grpc-gateway/pull/38) -- Reflection fix of proto3 nested messages. [\#34](https://github.com/grpc-ecosystem/grpc-gateway/pull/34) -- \[Experimental\] Make the response forwarder function customizable [\#31](https://github.com/grpc-ecosystem/grpc-gateway/pull/31) -- Add f.Flush\(\) to runtime.ForwardResponseStream [\#30](https://github.com/grpc-ecosystem/grpc-gateway/pull/30) -- Format error message in JSON [\#29](https://github.com/grpc-ecosystem/grpc-gateway/pull/29) -- Update examples with HTTP header context annotation [\#28](https://github.com/grpc-ecosystem/grpc-gateway/pull/28) -- Report semantic errors in the source to protoc [\#27](https://github.com/grpc-ecosystem/grpc-gateway/pull/27) -- Add support for non-nullable nested messages. [\#21](https://github.com/grpc-ecosystem/grpc-gateway/pull/21) -- Receive GRPC metadata from HTTP headers. [\#18](https://github.com/grpc-ecosystem/grpc-gateway/pull/18) -- Implement detailed specs of google.api.http [\#14](https://github.com/grpc-ecosystem/grpc-gateway/pull/14) -- Configure travis CI [\#13](https://github.com/grpc-ecosystem/grpc-gateway/pull/13) -- Replace our own custom option with the one defined by Google [\#12](https://github.com/grpc-ecosystem/grpc-gateway/pull/12) -- Remove useless context setup [\#11](https://github.com/grpc-ecosystem/grpc-gateway/pull/11) -- Fix typo, path, missing semicolon. [\#10](https://github.com/grpc-ecosystem/grpc-gateway/pull/10) -- Use a globally unique id for the custom option [\#3](https://github.com/grpc-ecosystem/grpc-gateway/pull/3) -- implement ABitOfEverythingService [\#2](https://github.com/grpc-ecosystem/grpc-gateway/pull/2) -- support streaming API calls [\#1](https://github.com/grpc-ecosystem/grpc-gateway/pull/1) diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/CONTRIBUTING.md b/vendor/github.com/grpc-ecosystem/grpc-gateway/CONTRIBUTING.md deleted file mode 100644 index 94983bc97..000000000 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/CONTRIBUTING.md +++ /dev/null @@ -1,20 +0,0 @@ -# How to contribute - -Thank you for your contribution to grpc-gateway. -Here's the recommended process of contribution. - -1. `go get github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway` -2. `cd $GOPATH/src/github.com/grpc-ecosystem/grpc-gateway` -3. hack, hack, hack... -4. Make sure that your change follows best practices in Go - * [Effective Go](https://golang.org/doc/effective_go.html) - * [Go Code Review Comments](https://golang.org/wiki/CodeReviewComments) -5. Make sure that `make test` passes. (use swagger-codegen 2.1.6, not newer versions) -6. Sign [a Contributor License Agreement](https://cla.developers.google.com/clas) -7. Open a pull request in Github - -When you work on a larger contribution, it is also recommended that you get in touch -with us through the issue tracker. - -### Code reviews -All submissions, including submissions by project members, require review. diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/Makefile b/vendor/github.com/grpc-ecosystem/grpc-gateway/Makefile deleted file mode 100644 index c6a645e0e..000000000 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/Makefile +++ /dev/null @@ -1,154 +0,0 @@ -# This is a Makefile which maintains files automatically generated but to be -# shipped together with other files. -# You don't have to rebuild these targets by yourself unless you develop -# grpc-gateway itself. - -PKG=github.com/grpc-ecosystem/grpc-gateway -GO_PLUGIN=bin/protoc-gen-go -GO_PLUGIN_PKG=github.com/golang/protobuf/protoc-gen-go -SWAGGER_PLUGIN=bin/protoc-gen-swagger -SWAGGER_PLUGIN_SRC= utilities/doc.go \ - utilities/pattern.go \ - utilities/trie.go \ - protoc-gen-swagger/genswagger/generator.go \ - protoc-gen-swagger/genswagger/template.go \ - protoc-gen-swagger/main.go -SWAGGER_PLUGIN_PKG=$(PKG)/protoc-gen-swagger -GATEWAY_PLUGIN=bin/protoc-gen-grpc-gateway -GATEWAY_PLUGIN_PKG=$(PKG)/protoc-gen-grpc-gateway -GATEWAY_PLUGIN_SRC= utilities/doc.go \ - utilities/pattern.go \ - utilities/trie.go \ - protoc-gen-grpc-gateway \ - protoc-gen-grpc-gateway/descriptor \ - protoc-gen-grpc-gateway/descriptor/registry.go \ - protoc-gen-grpc-gateway/descriptor/services.go \ - protoc-gen-grpc-gateway/descriptor/types.go \ - protoc-gen-grpc-gateway/generator \ - protoc-gen-grpc-gateway/generator/generator.go \ - protoc-gen-grpc-gateway/gengateway \ - protoc-gen-grpc-gateway/gengateway/doc.go \ - protoc-gen-grpc-gateway/gengateway/generator.go \ - protoc-gen-grpc-gateway/gengateway/template.go \ - protoc-gen-grpc-gateway/httprule \ - protoc-gen-grpc-gateway/httprule/compile.go \ - protoc-gen-grpc-gateway/httprule/parse.go \ - protoc-gen-grpc-gateway/httprule/types.go \ - protoc-gen-grpc-gateway/main.go -GATEWAY_PLUGIN_FLAGS?= - -GOOGLEAPIS_DIR=third_party/googleapis -OUTPUT_DIR=_output - -RUNTIME_PROTO=runtime/internal/stream_chunk.proto -RUNTIME_GO=$(RUNTIME_PROTO:.proto=.pb.go) - -OPENAPIV2_PROTO=protoc-gen-swagger/options/openapiv2.proto protoc-gen-swagger/options/annotations.proto -OPENAPIV2_GO=$(OPENAPIV2_PROTO:.proto=.pb.go) - -PKGMAP=Mgoogle/protobuf/descriptor.proto=$(GO_PLUGIN_PKG)/descriptor,Mexamples/sub/message.proto=$(PKG)/examples/sub -ADDITIONAL_FLAGS= -ifneq "$(GATEWAY_PLUGIN_FLAGS)" "" - ADDITIONAL_FLAGS=,$(GATEWAY_PLUGIN_FLAGS) -endif -SWAGGER_EXAMPLES=examples/examplepb/echo_service.proto \ - examples/examplepb/a_bit_of_everything.proto -EXAMPLES=examples/examplepb/echo_service.proto \ - examples/examplepb/a_bit_of_everything.proto \ - examples/examplepb/stream.proto \ - examples/examplepb/flow_combination.proto -EXAMPLE_SVCSRCS=$(EXAMPLES:.proto=.pb.go) -EXAMPLE_GWSRCS=$(EXAMPLES:.proto=.pb.gw.go) -EXAMPLE_SWAGGERSRCS=$(EXAMPLES:.proto=.swagger.json) -EXAMPLE_DEPS=examples/sub/message.proto examples/sub2/message.proto -EXAMPLE_DEPSRCS=$(EXAMPLE_DEPS:.proto=.pb.go) - -EXAMPLE_CLIENT_DIR=examples/clients -ECHO_EXAMPLE_SPEC=examples/examplepb/echo_service.swagger.json -ECHO_EXAMPLE_SRCS=$(EXAMPLE_CLIENT_DIR)/echo/EchoServiceApi.go \ - $(EXAMPLE_CLIENT_DIR)/echo/ExamplepbSimpleMessage.go -ABE_EXAMPLE_SPEC=examples/examplepb/a_bit_of_everything.swagger.json -ABE_EXAMPLE_SRCS=$(EXAMPLE_CLIENT_DIR)/abe/ABitOfEverythingServiceApi.go \ - $(EXAMPLE_CLIENT_DIR)/abe/ABitOfEverythingNested.go \ - $(EXAMPLE_CLIENT_DIR)/abe/ExamplepbABitOfEverything.go \ - $(EXAMPLE_CLIENT_DIR)/abe/ExamplepbNumericEnum.go \ - $(EXAMPLE_CLIENT_DIR)/abe/ExamplepbIdMessage.go \ - $(EXAMPLE_CLIENT_DIR)/abe/NestedDeepEnum.go \ - $(EXAMPLE_CLIENT_DIR)/abe/ProtobufEmpty.go \ - $(EXAMPLE_CLIENT_DIR)/abe/Sub2IdMessage.go \ - $(EXAMPLE_CLIENT_DIR)/abe/SubStringMessage.go -EXAMPLE_CLIENT_SRCS=$(ECHO_EXAMPLE_SRCS) $(ABE_EXAMPLE_SRCS) -SWAGGER_CODEGEN=swagger-codegen - -PROTOC_INC_PATH=$(dir $(shell which protoc))/../include - -generate: $(RUNTIME_GO) - -.SUFFIXES: .go .proto - -$(GO_PLUGIN): - go get $(GO_PLUGIN_PKG) - go build -o $@ $(GO_PLUGIN_PKG) - -$(RUNTIME_GO): $(RUNTIME_PROTO) $(GO_PLUGIN) - protoc -I $(PROTOC_INC_PATH) --plugin=$(GO_PLUGIN) -I. --go_out=$(PKGMAP):. $(RUNTIME_PROTO) - -$(OPENAPIV2_GO): $(OPENAPIV2_PROTO) $(GO_PLUGIN) - protoc -I $(PROTOC_INC_PATH) --plugin=$(GO_PLUGIN) -I. --go_out=$(PKGMAP):$(GOPATH)/src $(OPENAPIV2_PROTO) - -$(GATEWAY_PLUGIN): $(RUNTIME_GO) $(GATEWAY_PLUGIN_SRC) - go build -o $@ $(GATEWAY_PLUGIN_PKG) - -$(SWAGGER_PLUGIN): $(SWAGGER_PLUGIN_SRC) $(OPENAPIV2_GO) - go build -o $@ $(SWAGGER_PLUGIN_PKG) - -$(EXAMPLE_SVCSRCS): $(GO_PLUGIN) $(EXAMPLES) - protoc -I $(PROTOC_INC_PATH) -I. -I$(GOOGLEAPIS_DIR) --plugin=$(GO_PLUGIN) --go_out=$(PKGMAP),plugins=grpc:. $(EXAMPLES) -$(EXAMPLE_DEPSRCS): $(GO_PLUGIN) $(EXAMPLE_DEPS) - mkdir -p $(OUTPUT_DIR) - protoc -I $(PROTOC_INC_PATH) -I. --plugin=$(GO_PLUGIN) --go_out=$(PKGMAP),plugins=grpc:$(OUTPUT_DIR) $(@:.pb.go=.proto) - cp $(OUTPUT_DIR)/$(PKG)/$@ $@ || cp $(OUTPUT_DIR)/$@ $@ -$(EXAMPLE_GWSRCS): $(GATEWAY_PLUGIN) $(EXAMPLES) - protoc -I $(PROTOC_INC_PATH) -I. -I$(GOOGLEAPIS_DIR) --plugin=$(GATEWAY_PLUGIN) --grpc-gateway_out=logtostderr=true,$(PKGMAP)$(ADDITIONAL_FLAGS):. $(EXAMPLES) -$(EXAMPLE_SWAGGERSRCS): $(SWAGGER_PLUGIN) $(SWAGGER_EXAMPLES) - protoc -I $(PROTOC_INC_PATH) -I. -I$(GOOGLEAPIS_DIR) --plugin=$(SWAGGER_PLUGIN) --swagger_out=logtostderr=true,$(PKGMAP):. $(SWAGGER_EXAMPLES) - -$(ECHO_EXAMPLE_SRCS): $(ECHO_EXAMPLE_SPEC) - $(SWAGGER_CODEGEN) generate -i $(ECHO_EXAMPLE_SPEC) \ - -l go -o examples/clients/echo --additional-properties packageName=echo - @rm -f $(EXAMPLE_CLIENT_DIR)/echo/README.md \ - $(EXAMPLE_CLIENT_DIR)/echo/git_push.sh \ - $(EXAMPLE_CLIENT_DIR)/echo/.travis.yml -$(ABE_EXAMPLE_SRCS): $(ABE_EXAMPLE_SPEC) - $(SWAGGER_CODEGEN) generate -i $(ABE_EXAMPLE_SPEC) \ - -l go -o examples/clients/abe --additional-properties packageName=abe - @rm -f $(EXAMPLE_CLIENT_DIR)/abe/README.md \ - $(EXAMPLE_CLIENT_DIR)/abe/git_push.sh \ - $(EXAMPLE_CLIENT_DIR)/abe/.travis.yml - -examples: $(EXAMPLE_SVCSRCS) $(EXAMPLE_GWSRCS) $(EXAMPLE_DEPSRCS) $(EXAMPLE_SWAGGERSRCS) $(EXAMPLE_CLIENT_SRCS) -test: examples - go test -race $(PKG)/... - -lint: - golint --set_exit_status $(PKG)/runtime - golint --set_exit_status $(PKG)/utilities/... - golint --set_exit_status $(PKG)/protoc-gen-grpc-gateway/... - golint --set_exit_status $(PKG)/protoc-gen-swagger/... - go vet $(PKG)/runtime || true - go vet $(PKG)/utilities/... - go vet $(PKG)/protoc-gen-grpc-gateway/... - go vet $(PKG)/protoc-gen-swagger/... - -clean distclean: - rm -f $(GATEWAY_PLUGIN) -realclean: distclean - rm -f $(EXAMPLE_SVCSRCS) $(EXAMPLE_DEPSRCS) - rm -f $(EXAMPLE_GWSRCS) - rm -f $(EXAMPLE_SWAGGERSRCS) - rm -f $(GO_PLUGIN) - rm -f $(SWAGGER_PLUGIN) - rm -f $(EXAMPLE_CLIENT_SRCS) - rm -f $(OPENAPIV2_GO) - -.PHONY: generate examples test lint clean distclean realclean diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/README.md b/vendor/github.com/grpc-ecosystem/grpc-gateway/README.md deleted file mode 100644 index c7396cc15..000000000 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/README.md +++ /dev/null @@ -1,245 +0,0 @@ -# grpc-gateway - -[![Build Status](https://travis-ci.org/grpc-ecosystem/grpc-gateway.svg?branch=master)](https://travis-ci.org/grpc-ecosystem/grpc-gateway) - -grpc-gateway is a plugin of [protoc](http://github.com/google/protobuf). -It reads [gRPC](http://github.com/grpc/grpc-common) service definition, -and generates a reverse-proxy server which translates a RESTful JSON API into gRPC. -This server is generated according to [custom options](https://cloud.google.com/service-management/reference/rpc/google.api#http) in your gRPC definition. - -It helps you to provide your APIs in both gRPC and RESTful style at the same time. - -![architecture introduction diagram](https://docs.google.com/drawings/d/12hp4CPqrNPFhattL_cIoJptFvlAqm5wLQ0ggqI5mkCg/pub?w=749&h=370) - -## Background -gRPC is great -- it generates API clients and server stubs in many programming languages, it is fast, easy-to-use, bandwidth-efficient and its design is combat-proven by Google. -However, you might still want to provide a traditional RESTful API as well. Reasons can range from maintaining backwards-compatibility, supporting languages or clients not well supported by gRPC to simply maintaining the aesthetics and tooling involved with a RESTful architecture. - -This project aims to provide that HTTP+JSON interface to your gRPC service. A small amount of configuration in your service to attach HTTP semantics is all that's needed to generate a reverse-proxy with this library. - -## Installation -First you need to install ProtocolBuffers 3.0.0-beta-3 or later. - -```sh -mkdir tmp -cd tmp -git clone https://github.com/google/protobuf -cd protobuf -./autogen.sh -./configure -make -make check -sudo make install -``` - -Then, `go get -u` as usual the following packages: - -```sh -go get -u github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway -go get -u github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger -go get -u github.com/golang/protobuf/protoc-gen-go -``` - -## Usage -Make sure that your `$GOPATH/bin` is in your `$PATH`. - -1. Define your service in gRPC - - your_service.proto: - ```protobuf - syntax = "proto3"; - package example; - message StringMessage { - string value = 1; - } - - service YourService { - rpc Echo(StringMessage) returns (StringMessage) {} - } - ``` -2. Add a [custom option](https://cloud.google.com/service-management/reference/rpc/google.api#http) to the .proto file - - your_service.proto: - ```diff - syntax = "proto3"; - package example; - + - +import "google/api/annotations.proto"; - + - message StringMessage { - string value = 1; - } - - service YourService { - - rpc Echo(StringMessage) returns (StringMessage) {} - + rpc Echo(StringMessage) returns (StringMessage) { - + option (google.api.http) = { - + post: "/v1/example/echo" - + body: "*" - + }; - + } - } - ``` -3. Generate gRPC stub - - ```sh - protoc -I/usr/local/include -I. \ - -I$GOPATH/src \ - -I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \ - --go_out=plugins=grpc:. \ - path/to/your_service.proto - ``` - - It will generate a stub file `path/to/your_service.pb.go`. -4. Implement your service in gRPC as usual - 1. (Optional) Generate gRPC stub in the language you want. - - e.g. - ```sh - protoc -I/usr/local/include -I. \ - -I$GOPATH/src \ - -I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \ - --ruby_out=. \ - path/to/your/service_proto - - protoc -I/usr/local/include -I. \ - -I$GOPATH/src \ - -I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \ - --plugin=protoc-gen-grpc=grpc_ruby_plugin \ - --grpc-ruby_out=. \ - path/to/your/service.proto - ``` - 2. Add the googleapis-common-protos gem (or your language equivalent) as a dependency to your project. - 3. Implement your service - -5. Generate reverse-proxy - - ```sh - protoc -I/usr/local/include -I. \ - -I$GOPATH/src \ - -I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \ - --grpc-gateway_out=logtostderr=true:. \ - path/to/your_service.proto - ``` - - It will generate a reverse proxy `path/to/your_service.pb.gw.go`. - - Note: After generating the code for each of the stubs, in order to build the code, you will want to run ```go get .``` from the directory containing the stubs. - -6. Write an entrypoint - - Now you need to write an entrypoint of the proxy server. - ```go - package main - - import ( - "flag" - "net/http" - - "github.com/golang/glog" - "golang.org/x/net/context" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "google.golang.org/grpc" - - gw "path/to/your_service_package" - ) - - var ( - echoEndpoint = flag.String("echo_endpoint", "localhost:9090", "endpoint of YourService") - ) - - func run() error { - ctx := context.Background() - ctx, cancel := context.WithCancel(ctx) - defer cancel() - - mux := runtime.NewServeMux() - opts := []grpc.DialOption{grpc.WithInsecure()} - err := gw.RegisterYourServiceHandlerFromEndpoint(ctx, mux, *echoEndpoint, opts) - if err != nil { - return err - } - - return http.ListenAndServe(":8080", mux) - } - - func main() { - flag.Parse() - defer glog.Flush() - - if err := run(); err != nil { - glog.Fatal(err) - } - } - ``` - -7. (Optional) Generate swagger definitions - - ```sh - protoc -I/usr/local/include -I. \ - -I$GOPATH/src \ - -I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \ - --swagger_out=logtostderr=true:. \ - path/to/your_service.proto - ``` - -## Parameters and flags -`protoc-gen-grpc-gateway` supports custom mapping from Protobuf `import` to Golang import path. -They are compatible to [the parameters with same names in `protoc-gen-go`](https://github.com/golang/protobuf#parameters). - -In addition we also support the `request_context` parameter in order to use the `http.Request`'s Context (only for Go 1.7 and above). -This parameter can be useful to pass request scoped context between the gateway and the gRPC service. - -`protoc-gen-grpc-gateway` also supports some more command line flags to control logging. You can give these flags together with parameters above. Run `protoc-gen-grpc-gateway --help` for more details about the flags. - -## More Examples -More examples are available under `examples` directory. -* `examplepb/echo_service.proto`, `examplepb/a_bit_of_everything.proto`: service definition - * `examplepb/echo_service.pb.go`, `examplepb/a_bit_of_everything.pb.go`: [generated] stub of the service - * `examplepb/echo_service.pb.gw.go`, `examplepb/a_bit_of_everything.pb.gw.go`: [generated] reverse proxy for the service -* `server/main.go`: service implementation -* `main.go`: entrypoint of the generated reverse proxy - -To use the same port for custom HTTP handlers (e.g. serving `swagger.json`), gRPC-gateway, and a gRPC server, see [this code example by CoreOS](https://github.com/philips/grpc-gateway-example/blob/master/cmd/serve.go) (and its accompanying [blog post](https://coreos.com/blog/gRPC-protobufs-swagger.html)) - -## Features -### Supported -* Generating JSON API handlers -* Method parameters in request body -* Method parameters in request path -* Method parameters in query string -* Enum fields in path parameter (including repeated enum fields). -* Mapping streaming APIs to newline-delimited JSON streams -* Mapping HTTP headers with `Grpc-Metadata-` prefix to gRPC metadata (prefixed with `grpcgateway-`) -* Optionally emitting API definition for [Swagger](http://swagger.io). -* Setting [gRPC timeouts](http://www.grpc.io/docs/guides/wire.html) through inbound HTTP `Grpc-Timeout` header. - -### Want to support -But not yet. -* bytes fields in path parameter. #5 -* Optionally generating the entrypoint. #8 -* `import_path` parameter - -### No plan to support -But patch is welcome. -* Method parameters in HTTP headers -* Handling trailer metadata -* Encoding request/response body in XML -* True bi-directional streaming. (Probably impossible?) - -# Mapping gRPC to HTTP - -* [How gRPC error codes map to HTTP status codes in the response](https://github.com/grpc-ecosystem/grpc-gateway/blob/master/runtime/errors.go#L15) -* HTTP request source IP is added as `X-Forwarded-For` gRPC request header -* HTTP request host is added as `X-Forwarded-Host` gRPC request header -* HTTP `Authorization` header is added as `authorization` gRPC request header -* Remaining Permanent HTTP header keys (as specified by the IANA [here](http://www.iana.org/assignments/message-headers/message-headers.xhtml) are prefixed with `grpcgateway-` and added with their values to gRPC request header -* HTTP headers that start with 'Grpc-Metadata-' are mapped to gRPC metadata (prefixed with `grpcgateway-`) -* While configurable, the default {un,}marshaling uses [jsonpb](https://godoc.org/github.com/golang/protobuf/jsonpb) with `OrigName: true`. - -# Contribution -See [CONTRIBUTING.md](http://github.com/grpc-ecosystem/grpc-gateway/blob/master/CONTRIBUTING.md). - -# License -grpc-gateway is licensed under the BSD 3-Clause License. -See [LICENSE.txt](https://github.com/grpc-ecosystem/grpc-gateway/blob/master/LICENSE.txt) for more details. diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/context_test.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/context_test.go deleted file mode 100644 index 955d6f135..000000000 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/context_test.go +++ /dev/null @@ -1,172 +0,0 @@ -package runtime_test - -import ( - "net/http" - "reflect" - "testing" - "time" - - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "golang.org/x/net/context" - "google.golang.org/grpc/metadata" -) - -const ( - emptyForwardMetaCount = 1 -) - -func TestAnnotateContext_WorksWithEmpty(t *testing.T) { - ctx := context.Background() - - request, err := http.NewRequest("GET", "http://www.example.com", nil) - if err != nil { - t.Fatalf("http.NewRequest(%q, %q, nil) failed with %v; want success", "GET", "http://www.example.com", err) - } - request.Header.Add("Some-Irrelevant-Header", "some value") - annotated, err := runtime.AnnotateContext(ctx, runtime.NewServeMux(), request) - if err != nil { - t.Errorf("runtime.AnnotateContext(ctx, %#v) failed with %v; want success", request, err) - return - } - md, ok := metadata.FromOutgoingContext(annotated) - if !ok || len(md) != emptyForwardMetaCount { - t.Errorf("Expected %d metadata items in context; got %v", emptyForwardMetaCount, md) - } -} - -func TestAnnotateContext_ForwardsGrpcMetadata(t *testing.T) { - ctx := context.Background() - request, err := http.NewRequest("GET", "http://www.example.com", nil) - if err != nil { - t.Fatalf("http.NewRequest(%q, %q, nil) failed with %v; want success", "GET", "http://www.example.com", err) - } - request.Header.Add("Some-Irrelevant-Header", "some value") - request.Header.Add("Grpc-Metadata-FooBar", "Value1") - request.Header.Add("Grpc-Metadata-Foo-BAZ", "Value2") - request.Header.Add("Grpc-Metadata-foo-bAz", "Value3") - request.Header.Add("Authorization", "Token 1234567890") - annotated, err := runtime.AnnotateContext(ctx, runtime.NewServeMux(), request) - if err != nil { - t.Errorf("runtime.AnnotateContext(ctx, %#v) failed with %v; want success", request, err) - return - } - md, ok := metadata.FromOutgoingContext(annotated) - if got, want := len(md), emptyForwardMetaCount+4; !ok || got != want { - t.Errorf("metadata items in context = %d want %d: %v", got, want, md) - } - if got, want := md["foobar"], []string{"Value1"}; !reflect.DeepEqual(got, want) { - t.Errorf(`md["grpcgateway-foobar"] = %q; want %q`, got, want) - } - if got, want := md["foo-baz"], []string{"Value2", "Value3"}; !reflect.DeepEqual(got, want) { - t.Errorf(`md["grpcgateway-foo-baz"] = %q want %q`, got, want) - } - if got, want := md["grpcgateway-authorization"], []string{"Token 1234567890"}; !reflect.DeepEqual(got, want) { - t.Errorf(`md["grpcgateway-authorization"] = %q want %q`, got, want) - } - if got, want := md["authorization"], []string{"Token 1234567890"}; !reflect.DeepEqual(got, want) { - t.Errorf(`md["authorization"] = %q want %q`, got, want) - } -} - -func TestAnnotateContext_XForwardedFor(t *testing.T) { - ctx := context.Background() - request, err := http.NewRequest("GET", "http://bar.foo.example.com", nil) - if err != nil { - t.Fatalf("http.NewRequest(%q, %q, nil) failed with %v; want success", "GET", "http://bar.foo.example.com", err) - } - request.Header.Add("X-Forwarded-For", "192.0.2.100") // client - request.RemoteAddr = "192.0.2.200:12345" // proxy - - annotated, err := runtime.AnnotateContext(ctx, runtime.NewServeMux(), request) - if err != nil { - t.Errorf("runtime.AnnotateContext(ctx, %#v) failed with %v; want success", request, err) - return - } - md, ok := metadata.FromOutgoingContext(annotated) - if !ok || len(md) != emptyForwardMetaCount+1 { - t.Errorf("Expected %d metadata items in context; got %v", emptyForwardMetaCount+1, md) - } - if got, want := md["x-forwarded-host"], []string{"bar.foo.example.com"}; !reflect.DeepEqual(got, want) { - t.Errorf(`md["host"] = %v; want %v`, got, want) - } - // Note: it must be in order client, proxy1, proxy2 - if got, want := md["x-forwarded-for"], []string{"192.0.2.100, 192.0.2.200"}; !reflect.DeepEqual(got, want) { - t.Errorf(`md["x-forwarded-for"] = %v want %v`, got, want) - } -} - -func TestAnnotateContext_SupportsTimeouts(t *testing.T) { - ctx := context.Background() - request, err := http.NewRequest("GET", "http://example.com", nil) - if err != nil { - t.Fatalf(`http.NewRequest("GET", "http://example.com", nil failed with %v; want success`, err) - } - annotated, err := runtime.AnnotateContext(ctx, runtime.NewServeMux(), request) - if err != nil { - t.Errorf("runtime.AnnotateContext(ctx, %#v) failed with %v; want success", request, err) - return - } - if _, ok := annotated.Deadline(); ok { - // no deadline by default - t.Errorf("annotated.Deadline() = _, true; want _, false") - } - - const acceptableError = 50 * time.Millisecond - runtime.DefaultContextTimeout = 10 * time.Second - annotated, err = runtime.AnnotateContext(ctx, runtime.NewServeMux(), request) - if err != nil { - t.Errorf("runtime.AnnotateContext(ctx, %#v) failed with %v; want success", request, err) - return - } - deadline, ok := annotated.Deadline() - if !ok { - t.Errorf("annotated.Deadline() = _, false; want _, true") - } - if got, want := deadline.Sub(time.Now()), runtime.DefaultContextTimeout; got-want > acceptableError || got-want < -acceptableError { - t.Errorf("deadline.Sub(time.Now()) = %v; want %v; with error %v", got, want, acceptableError) - } - - for _, spec := range []struct { - timeout string - want time.Duration - }{ - { - timeout: "17H", - want: 17 * time.Hour, - }, - { - timeout: "19M", - want: 19 * time.Minute, - }, - { - timeout: "23S", - want: 23 * time.Second, - }, - { - timeout: "1009m", - want: 1009 * time.Millisecond, - }, - { - timeout: "1000003u", - want: 1000003 * time.Microsecond, - }, - { - timeout: "100000007n", - want: 100000007 * time.Nanosecond, - }, - } { - request.Header.Set("Grpc-Timeout", spec.timeout) - annotated, err = runtime.AnnotateContext(ctx, runtime.NewServeMux(), request) - if err != nil { - t.Errorf("runtime.AnnotateContext(ctx, %#v) failed with %v; want success", request, err) - return - } - deadline, ok := annotated.Deadline() - if !ok { - t.Errorf("annotated.Deadline() = _, false; want _, true; timeout = %q", spec.timeout) - } - if got, want := deadline.Sub(time.Now()), spec.want; got-want > acceptableError || got-want < -acceptableError { - t.Errorf("deadline.Sub(time.Now()) = %v; want %v; with error %v; timeout= %q", got, want, acceptableError, spec.timeout) - } - } -} diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/errors_test.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/errors_test.go deleted file mode 100644 index ee5dfb3c0..000000000 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/errors_test.go +++ /dev/null @@ -1,57 +0,0 @@ -package runtime_test - -import ( - "encoding/json" - "fmt" - "net/http" - "net/http/httptest" - "strings" - "testing" - - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "golang.org/x/net/context" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" -) - -func TestDefaultHTTPError(t *testing.T) { - ctx := context.Background() - - for _, spec := range []struct { - err error - status int - msg string - }{ - { - err: fmt.Errorf("example error"), - status: http.StatusInternalServerError, - msg: "example error", - }, - { - err: status.Error(codes.NotFound, "no such resource"), - status: http.StatusNotFound, - msg: "no such resource", - }, - } { - w := httptest.NewRecorder() - req, _ := http.NewRequest("", "", nil) // Pass in an empty request to match the signature - runtime.DefaultHTTPError(ctx, &runtime.ServeMux{}, &runtime.JSONBuiltin{}, w, req, spec.err) - - if got, want := w.Header().Get("Content-Type"), "application/json"; got != want { - t.Errorf(`w.Header().Get("Content-Type") = %q; want %q; on spec.err=%v`, got, want, spec.err) - } - if got, want := w.Code, spec.status; got != want { - t.Errorf("w.Code = %d; want %d", got, want) - } - - body := make(map[string]interface{}) - if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil { - t.Errorf("json.Unmarshal(%q, &body) failed with %v; want success", w.Body.Bytes(), err) - continue - } - - if got, want := body["error"].(string), spec.msg; !strings.Contains(got, want) { - t.Errorf(`body["error"] = %q; want %q; on spec.err=%v`, got, want, spec.err) - } - } -} diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/handler_test.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/handler_test.go deleted file mode 100644 index 493aa5e54..000000000 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/handler_test.go +++ /dev/null @@ -1,204 +0,0 @@ -package runtime_test - -import ( - "io" - "io/ioutil" - "net/http" - "net/http/httptest" - "testing" - - "github.com/golang/protobuf/proto" - pb "github.com/grpc-ecosystem/grpc-gateway/examples/examplepb" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "golang.org/x/net/context" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" -) - -func TestForwardResponseStream(t *testing.T) { - type msg struct { - pb proto.Message - err error - } - tests := []struct { - name string - msgs []msg - statusCode int - }{{ - name: "encoding", - msgs: []msg{ - {&pb.SimpleMessage{Id: "One"}, nil}, - {&pb.SimpleMessage{Id: "Two"}, nil}, - }, - statusCode: http.StatusOK, - }, { - name: "empty", - statusCode: http.StatusOK, - }, { - name: "error", - msgs: []msg{{nil, grpc.Errorf(codes.OutOfRange, "400")}}, - statusCode: http.StatusBadRequest, - }, { - name: "stream_error", - msgs: []msg{ - {&pb.SimpleMessage{Id: "One"}, nil}, - {nil, grpc.Errorf(codes.OutOfRange, "400")}, - }, - statusCode: http.StatusOK, - }} - - newTestRecv := func(t *testing.T, msgs []msg) func() (proto.Message, error) { - var count int - return func() (proto.Message, error) { - if count == len(msgs) { - return nil, io.EOF - } else if count > len(msgs) { - t.Errorf("recv() called %d times for %d messages", count, len(msgs)) - } - count++ - msg := msgs[count-1] - return msg.pb, msg.err - } - } - ctx := runtime.NewServerMetadataContext(context.Background(), runtime.ServerMetadata{}) - marshaler := &runtime.JSONPb{} - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - recv := newTestRecv(t, tt.msgs) - req := httptest.NewRequest("GET", "http://example.com/foo", nil) - resp := httptest.NewRecorder() - - runtime.ForwardResponseStream(ctx, runtime.NewServeMux(), marshaler, resp, req, recv) - - w := resp.Result() - if w.StatusCode != tt.statusCode { - t.Errorf("StatusCode %d want %d", w.StatusCode, tt.statusCode) - } - if h := w.Header.Get("Transfer-Encoding"); h != "chunked" { - t.Errorf("ForwardResponseStream missing header chunked") - } - body, err := ioutil.ReadAll(w.Body) - if err != nil { - t.Errorf("Failed to read response body with %v", err) - } - w.Body.Close() - - var want []byte - for _, msg := range tt.msgs { - if msg.err != nil { - t.Skip("checking erorr encodings") - } - b, err := marshaler.Marshal(map[string]proto.Message{"result": msg.pb}) - if err != nil { - t.Errorf("marshaler.Marshal() failed %v", err) - } - want = append(want, b...) - want = append(want, marshaler.Delimiter()...) - } - - if string(body) != string(want) { - t.Errorf("ForwardResponseStream() = \"%s\" want \"%s\"", body, want) - } - }) - } -} - - -// A custom marshaler implementation, that doesn't implement the delimited interface -type CustomMarshaler struct { - m *runtime.JSONPb -} -func (c *CustomMarshaler) Marshal(v interface{}) ([]byte, error) { return c.m.Marshal(v) } -func (c *CustomMarshaler) Unmarshal(data []byte, v interface{}) error { return c.m.Unmarshal(data, v) } -func (c *CustomMarshaler) NewDecoder(r io.Reader) runtime.Decoder { return c.m.NewDecoder(r) } -func (c *CustomMarshaler) NewEncoder(w io.Writer) runtime.Encoder { return c.m.NewEncoder(w) } -func (c *CustomMarshaler) ContentType() string { return c.m.ContentType() } - - -func TestForwardResponseStreamCustomMarshaler(t *testing.T) { - type msg struct { - pb proto.Message - err error - } - tests := []struct { - name string - msgs []msg - statusCode int - }{{ - name: "encoding", - msgs: []msg{ - {&pb.SimpleMessage{Id: "One"}, nil}, - {&pb.SimpleMessage{Id: "Two"}, nil}, - }, - statusCode: http.StatusOK, - }, { - name: "empty", - statusCode: http.StatusOK, - }, { - name: "error", - msgs: []msg{{nil, grpc.Errorf(codes.OutOfRange, "400")}}, - statusCode: http.StatusBadRequest, - }, { - name: "stream_error", - msgs: []msg{ - {&pb.SimpleMessage{Id: "One"}, nil}, - {nil, grpc.Errorf(codes.OutOfRange, "400")}, - }, - statusCode: http.StatusOK, - }} - - newTestRecv := func(t *testing.T, msgs []msg) func() (proto.Message, error) { - var count int - return func() (proto.Message, error) { - if count == len(msgs) { - return nil, io.EOF - } else if count > len(msgs) { - t.Errorf("recv() called %d times for %d messages", count, len(msgs)) - } - count++ - msg := msgs[count-1] - return msg.pb, msg.err - } - } - ctx := runtime.NewServerMetadataContext(context.Background(), runtime.ServerMetadata{}) - marshaler := &CustomMarshaler{&runtime.JSONPb{}} - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - recv := newTestRecv(t, tt.msgs) - req := httptest.NewRequest("GET", "http://example.com/foo", nil) - resp := httptest.NewRecorder() - - runtime.ForwardResponseStream(ctx, runtime.NewServeMux(), marshaler, resp, req, recv) - - w := resp.Result() - if w.StatusCode != tt.statusCode { - t.Errorf("StatusCode %d want %d", w.StatusCode, tt.statusCode) - } - if h := w.Header.Get("Transfer-Encoding"); h != "chunked" { - t.Errorf("ForwardResponseStream missing header chunked") - } - body, err := ioutil.ReadAll(w.Body) - if err != nil { - t.Errorf("Failed to read response body with %v", err) - } - w.Body.Close() - - var want []byte - for _, msg := range tt.msgs { - if msg.err != nil { - t.Skip("checking erorr encodings") - } - b, err := marshaler.Marshal(map[string]proto.Message{"result": msg.pb}) - if err != nil { - t.Errorf("marshaler.Marshal() failed %v", err) - } - want = append(want, b...) - want = append(want, "\n"...) - } - - if string(body) != string(want) { - t.Errorf("ForwardResponseStream() = \"%s\" want \"%s\"", body, want) - } - }) - } -} diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/internal/stream_chunk.proto b/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/internal/stream_chunk.proto deleted file mode 100644 index f7fba56c3..000000000 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/internal/stream_chunk.proto +++ /dev/null @@ -1,12 +0,0 @@ -syntax = "proto3"; -package grpc.gateway.runtime; -option go_package = "internal"; - -// StreamError is a response type which is returned when -// streaming rpc returns an error. -message StreamError { - int32 grpc_code = 1; - int32 http_code = 2; - string message = 3; - string http_status = 4; -} diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/marshal_json_test.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/marshal_json_test.go deleted file mode 100644 index e6efa2910..000000000 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/marshal_json_test.go +++ /dev/null @@ -1,245 +0,0 @@ -package runtime_test - -import ( - "bytes" - "encoding/json" - "reflect" - "strings" - "testing" - - "github.com/golang/protobuf/proto" - "github.com/golang/protobuf/ptypes/empty" - structpb "github.com/golang/protobuf/ptypes/struct" - "github.com/golang/protobuf/ptypes/timestamp" - "github.com/golang/protobuf/ptypes/wrappers" - "github.com/grpc-ecosystem/grpc-gateway/examples/examplepb" - "github.com/grpc-ecosystem/grpc-gateway/runtime" -) - -func TestJSONBuiltinMarshal(t *testing.T) { - var m runtime.JSONBuiltin - msg := examplepb.SimpleMessage{ - Id: "foo", - } - - buf, err := m.Marshal(&msg) - if err != nil { - t.Errorf("m.Marshal(%v) failed with %v; want success", &msg, err) - } - - var got examplepb.SimpleMessage - if err := json.Unmarshal(buf, &got); err != nil { - t.Errorf("json.Unmarshal(%q, &got) failed with %v; want success", buf, err) - } - if want := msg; !reflect.DeepEqual(got, want) { - t.Errorf("got = %v; want %v", &got, &want) - } -} - -func TestJSONBuiltinMarshalField(t *testing.T) { - var m runtime.JSONBuiltin - for _, fixt := range builtinFieldFixtures { - buf, err := m.Marshal(fixt.data) - if err != nil { - t.Errorf("m.Marshal(%v) failed with %v; want success", fixt.data, err) - } - if got, want := string(buf), fixt.json; got != want { - t.Errorf("got = %q; want %q; data = %#v", got, want, fixt.data) - } - } -} - -func TestJSONBuiltinMarshalFieldKnownErrors(t *testing.T) { - var m runtime.JSONBuiltin - for _, fixt := range builtinKnownErrors { - buf, err := m.Marshal(fixt.data) - if err != nil { - t.Errorf("m.Marshal(%v) failed with %v; want success", fixt.data, err) - } - if got, want := string(buf), fixt.json; got == want { - t.Errorf("surprisingly got = %q; as want %q; data = %#v", got, want, fixt.data) - } - } -} - -func TestJSONBuiltinsnmarshal(t *testing.T) { - var ( - m runtime.JSONBuiltin - got examplepb.SimpleMessage - - data = []byte(`{"id": "foo"}`) - ) - if err := m.Unmarshal(data, &got); err != nil { - t.Errorf("m.Unmarshal(%q, &got) failed with %v; want success", data, err) - } - - want := examplepb.SimpleMessage{ - Id: "foo", - } - if !reflect.DeepEqual(got, want) { - t.Errorf("got = %v; want = %v", &got, &want) - } -} - -func TestJSONBuiltinUnmarshalField(t *testing.T) { - var m runtime.JSONBuiltin - for _, fixt := range builtinFieldFixtures { - dest := reflect.New(reflect.TypeOf(fixt.data)) - if err := m.Unmarshal([]byte(fixt.json), dest.Interface()); err != nil { - t.Errorf("m.Unmarshal(%q, dest) failed with %v; want success", fixt.json, err) - } - - if got, want := dest.Elem().Interface(), fixt.data; !reflect.DeepEqual(got, want) { - t.Errorf("got = %#v; want = %#v; input = %q", got, want, fixt.json) - } - } -} - -func TestJSONBuiltinUnmarshalFieldKnownErrors(t *testing.T) { - var m runtime.JSONBuiltin - for _, fixt := range builtinKnownErrors { - dest := reflect.New(reflect.TypeOf(fixt.data)) - if err := m.Unmarshal([]byte(fixt.json), dest.Interface()); err == nil { - t.Errorf("m.Unmarshal(%q, dest) succeeded; want ane error", fixt.json) - } - } -} - -func TestJSONBuiltinEncoder(t *testing.T) { - var m runtime.JSONBuiltin - msg := examplepb.SimpleMessage{ - Id: "foo", - } - - var buf bytes.Buffer - enc := m.NewEncoder(&buf) - if err := enc.Encode(&msg); err != nil { - t.Errorf("enc.Encode(%v) failed with %v; want success", &msg, err) - } - - var got examplepb.SimpleMessage - if err := json.Unmarshal(buf.Bytes(), &got); err != nil { - t.Errorf("json.Unmarshal(%q, &got) failed with %v; want success", buf.String(), err) - } - if want := msg; !reflect.DeepEqual(got, want) { - t.Errorf("got = %v; want %v", &got, &want) - } -} - -func TestJSONBuiltinEncoderFields(t *testing.T) { - var m runtime.JSONBuiltin - for _, fixt := range builtinFieldFixtures { - var buf bytes.Buffer - enc := m.NewEncoder(&buf) - if err := enc.Encode(fixt.data); err != nil { - t.Errorf("enc.Encode(%#v) failed with %v; want success", fixt.data, err) - } - - if got, want := buf.String(), fixt.json+"\n"; got != want { - t.Errorf("got = %q; want %q; data = %#v", got, want, fixt.data) - } - } -} - -func TestJSONBuiltinDecoder(t *testing.T) { - var ( - m runtime.JSONBuiltin - got examplepb.SimpleMessage - - data = `{"id": "foo"}` - ) - r := strings.NewReader(data) - dec := m.NewDecoder(r) - if err := dec.Decode(&got); err != nil { - t.Errorf("m.Unmarshal(&got) failed with %v; want success", err) - } - - want := examplepb.SimpleMessage{ - Id: "foo", - } - if !reflect.DeepEqual(got, want) { - t.Errorf("got = %v; want = %v", &got, &want) - } -} - -func TestJSONBuiltinDecoderFields(t *testing.T) { - var m runtime.JSONBuiltin - for _, fixt := range builtinFieldFixtures { - r := strings.NewReader(fixt.json) - dec := m.NewDecoder(r) - dest := reflect.New(reflect.TypeOf(fixt.data)) - if err := dec.Decode(dest.Interface()); err != nil { - t.Errorf("dec.Decode(dest) failed with %v; want success; data = %q", err, fixt.json) - } - - if got, want := dest.Elem().Interface(), fixt.data; !reflect.DeepEqual(got, want) { - t.Errorf("got = %v; want = %v; input = %q", got, want, fixt.json) - } - } -} - -var ( - builtinFieldFixtures = []struct { - data interface{} - json string - }{ - {data: "", json: `""`}, - {data: proto.String(""), json: `""`}, - {data: "foo", json: `"foo"`}, - {data: proto.String("foo"), json: `"foo"`}, - {data: int32(-1), json: "-1"}, - {data: proto.Int32(-1), json: "-1"}, - {data: int64(-1), json: "-1"}, - {data: proto.Int64(-1), json: "-1"}, - {data: uint32(123), json: "123"}, - {data: proto.Uint32(123), json: "123"}, - {data: uint64(123), json: "123"}, - {data: proto.Uint64(123), json: "123"}, - {data: float32(-1.5), json: "-1.5"}, - {data: proto.Float32(-1.5), json: "-1.5"}, - {data: float64(-1.5), json: "-1.5"}, - {data: proto.Float64(-1.5), json: "-1.5"}, - {data: true, json: "true"}, - {data: proto.Bool(true), json: "true"}, - {data: (*string)(nil), json: "null"}, - {data: new(empty.Empty), json: "{}"}, - {data: examplepb.NumericEnum_ONE, json: "1"}, - { - data: (*examplepb.NumericEnum)(proto.Int32(int32(examplepb.NumericEnum_ONE))), - json: "1", - }, - } - builtinKnownErrors = []struct { - data interface{} - json string - }{ - {data: examplepb.NumericEnum_ONE, json: "ONE"}, - { - data: (*examplepb.NumericEnum)(proto.Int32(int32(examplepb.NumericEnum_ONE))), - json: "ONE", - }, - { - data: &examplepb.ABitOfEverything_OneofString{OneofString: "abc"}, - json: `"abc"`, - }, - { - data: ×tamp.Timestamp{ - Seconds: 1462875553, - Nanos: 123000000, - }, - json: `"2016-05-10T10:19:13.123Z"`, - }, - { - data: &wrappers.Int32Value{Value: 123}, - json: "123", - }, - { - data: &structpb.Value{ - Kind: &structpb.Value_StringValue{ - StringValue: "abc", - }, - }, - json: `"abc"`, - }, - } -) diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/marshal_jsonpb_test.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/marshal_jsonpb_test.go deleted file mode 100644 index 482a45bfd..000000000 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/marshal_jsonpb_test.go +++ /dev/null @@ -1,618 +0,0 @@ -package runtime_test - -import ( - "bytes" - "reflect" - "strings" - "testing" - - "github.com/golang/protobuf/jsonpb" - "github.com/golang/protobuf/proto" - "github.com/golang/protobuf/ptypes/duration" - "github.com/golang/protobuf/ptypes/empty" - structpb "github.com/golang/protobuf/ptypes/struct" - "github.com/golang/protobuf/ptypes/timestamp" - "github.com/golang/protobuf/ptypes/wrappers" - "github.com/grpc-ecosystem/grpc-gateway/examples/examplepb" - "github.com/grpc-ecosystem/grpc-gateway/runtime" -) - -func TestJSONPbMarshal(t *testing.T) { - msg := examplepb.ABitOfEverything{ - SingleNested: &examplepb.ABitOfEverything_Nested{}, - RepeatedStringValue: []string{}, - MappedStringValue: map[string]string{}, - MappedNestedValue: map[string]*examplepb.ABitOfEverything_Nested{}, - RepeatedEnumValue: []examplepb.NumericEnum{}, - TimestampValue: ×tamp.Timestamp{}, - Uuid: "6EC2446F-7E89-4127-B3E6-5C05E6BECBA7", - Nested: []*examplepb.ABitOfEverything_Nested{ - { - Name: "foo", - Amount: 12345, - }, - }, - Uint64Value: 0xFFFFFFFFFFFFFFFF, - EnumValue: examplepb.NumericEnum_ONE, - OneofValue: &examplepb.ABitOfEverything_OneofString{ - OneofString: "bar", - }, - MapValue: map[string]examplepb.NumericEnum{ - "a": examplepb.NumericEnum_ONE, - "b": examplepb.NumericEnum_ZERO, - }, - } - - for i, spec := range []struct { - enumsAsInts, emitDefaults bool - indent string - origName bool - verifier func(json string) - }{ - { - verifier: func(json string) { - if strings.ContainsAny(json, " \t\r\n") { - t.Errorf("strings.ContainsAny(%q, %q) = true; want false", json, " \t\r\n") - } - if !strings.Contains(json, "ONE") { - t.Errorf(`strings.Contains(%q, "ONE") = false; want true`, json) - } - if want := "uint64Value"; !strings.Contains(json, want) { - t.Errorf(`strings.Contains(%q, %q) = false; want true`, json, want) - } - }, - }, - { - enumsAsInts: true, - verifier: func(json string) { - if strings.Contains(json, "ONE") { - t.Errorf(`strings.Contains(%q, "ONE") = true; want false`, json) - } - }, - }, - { - emitDefaults: true, - verifier: func(json string) { - if want := `"sfixed32Value"`; !strings.Contains(json, want) { - t.Errorf(`strings.Contains(%q, %q) = false; want true`, json, want) - } - }, - }, - { - indent: "\t\t", - verifier: func(json string) { - if want := "\t\t\"amount\":"; !strings.Contains(json, want) { - t.Errorf(`strings.Contains(%q, %q) = false; want true`, json, want) - } - }, - }, - { - origName: true, - verifier: func(json string) { - if want := "uint64_value"; !strings.Contains(json, want) { - t.Errorf(`strings.Contains(%q, %q) = false; want true`, json, want) - } - }, - }, - } { - m := runtime.JSONPb{ - EnumsAsInts: spec.enumsAsInts, - EmitDefaults: spec.emitDefaults, - Indent: spec.indent, - OrigName: spec.origName, - } - buf, err := m.Marshal(&msg) - if err != nil { - t.Errorf("m.Marshal(%v) failed with %v; want success; spec=%v", &msg, err, spec) - } - - var got examplepb.ABitOfEverything - if err := jsonpb.UnmarshalString(string(buf), &got); err != nil { - t.Errorf("jsonpb.UnmarshalString(%q, &got) failed with %v; want success; spec=%v", string(buf), err, spec) - } - if want := msg; !reflect.DeepEqual(got, want) { - t.Errorf("case %d: got = %v; want %v; spec=%v", i, &got, &want, spec) - } - if spec.verifier != nil { - spec.verifier(string(buf)) - } - } -} - -func TestJSONPbMarshalFields(t *testing.T) { - var m runtime.JSONPb - for _, spec := range []struct { - val interface{} - want string - }{} { - buf, err := m.Marshal(spec.val) - if err != nil { - t.Errorf("m.Marshal(%#v) failed with %v; want success", spec.val, err) - } - if got, want := string(buf), spec.want; got != want { - t.Errorf("m.Marshal(%#v) = %q; want %q", spec.val, got, want) - } - } - - m.EnumsAsInts = true - buf, err := m.Marshal(examplepb.NumericEnum_ONE) - if err != nil { - t.Errorf("m.Marshal(%#v) failed with %v; want success", examplepb.NumericEnum_ONE, err) - } - if got, want := string(buf), "1"; got != want { - t.Errorf("m.Marshal(%#v) = %q; want %q", examplepb.NumericEnum_ONE, got, want) - } -} - -func TestJSONPbUnmarshal(t *testing.T) { - var ( - m runtime.JSONPb - got examplepb.ABitOfEverything - ) - for i, data := range []string{ - `{ - "uuid": "6EC2446F-7E89-4127-B3E6-5C05E6BECBA7", - "nested": [ - {"name": "foo", "amount": 12345} - ], - "uint64Value": 18446744073709551615, - "enumValue": "ONE", - "oneofString": "bar", - "mapValue": { - "a": 1, - "b": 0 - } - }`, - `{ - "uuid": "6EC2446F-7E89-4127-B3E6-5C05E6BECBA7", - "nested": [ - {"name": "foo", "amount": 12345} - ], - "uint64Value": "18446744073709551615", - "enumValue": "ONE", - "oneofString": "bar", - "mapValue": { - "a": 1, - "b": 0 - } - }`, - `{ - "uuid": "6EC2446F-7E89-4127-B3E6-5C05E6BECBA7", - "nested": [ - {"name": "foo", "amount": 12345} - ], - "uint64Value": 18446744073709551615, - "enumValue": 1, - "oneofString": "bar", - "mapValue": { - "a": 1, - "b": 0 - } - }`, - } { - if err := m.Unmarshal([]byte(data), &got); err != nil { - t.Errorf("case %d: m.Unmarshal(%q, &got) failed with %v; want success", i, data, err) - } - - want := examplepb.ABitOfEverything{ - Uuid: "6EC2446F-7E89-4127-B3E6-5C05E6BECBA7", - Nested: []*examplepb.ABitOfEverything_Nested{ - { - Name: "foo", - Amount: 12345, - }, - }, - Uint64Value: 0xFFFFFFFFFFFFFFFF, - EnumValue: examplepb.NumericEnum_ONE, - OneofValue: &examplepb.ABitOfEverything_OneofString{ - OneofString: "bar", - }, - MapValue: map[string]examplepb.NumericEnum{ - "a": examplepb.NumericEnum_ONE, - "b": examplepb.NumericEnum_ZERO, - }, - } - - if !reflect.DeepEqual(got, want) { - t.Errorf("case %d: got = %v; want = %v", i, &got, &want) - } - } -} - -func TestJSONPbUnmarshalFields(t *testing.T) { - var m runtime.JSONPb - for _, fixt := range fieldFixtures { - if fixt.skipUnmarshal { - continue - } - - dest := reflect.New(reflect.TypeOf(fixt.data)) - if err := m.Unmarshal([]byte(fixt.json), dest.Interface()); err != nil { - t.Errorf("m.Unmarshal(%q, %T) failed with %v; want success", fixt.json, dest.Interface(), err) - } - if got, want := dest.Elem().Interface(), fixt.data; !reflect.DeepEqual(got, want) { - t.Errorf("dest = %#v; want %#v; input = %v", got, want, fixt.json) - } - } -} - -func TestJSONPbEncoder(t *testing.T) { - msg := examplepb.ABitOfEverything{ - SingleNested: &examplepb.ABitOfEverything_Nested{}, - RepeatedStringValue: []string{}, - MappedStringValue: map[string]string{}, - MappedNestedValue: map[string]*examplepb.ABitOfEverything_Nested{}, - RepeatedEnumValue: []examplepb.NumericEnum{}, - TimestampValue: ×tamp.Timestamp{}, - Uuid: "6EC2446F-7E89-4127-B3E6-5C05E6BECBA7", - Nested: []*examplepb.ABitOfEverything_Nested{ - { - Name: "foo", - Amount: 12345, - }, - }, - Uint64Value: 0xFFFFFFFFFFFFFFFF, - OneofValue: &examplepb.ABitOfEverything_OneofString{ - OneofString: "bar", - }, - MapValue: map[string]examplepb.NumericEnum{ - "a": examplepb.NumericEnum_ONE, - "b": examplepb.NumericEnum_ZERO, - }, - } - - for i, spec := range []struct { - enumsAsInts, emitDefaults bool - indent string - origName bool - verifier func(json string) - }{ - { - verifier: func(json string) { - if strings.ContainsAny(json, " \t\r\n") { - t.Errorf("strings.ContainsAny(%q, %q) = true; want false", json, " \t\r\n") - } - if strings.Contains(json, "ONE") { - t.Errorf(`strings.Contains(%q, "ONE") = true; want false`, json) - } - if want := "uint64Value"; !strings.Contains(json, want) { - t.Errorf(`strings.Contains(%q, %q) = false; want true`, json, want) - } - }, - }, - { - enumsAsInts: true, - verifier: func(json string) { - if strings.Contains(json, "ONE") { - t.Errorf(`strings.Contains(%q, "ONE") = true; want false`, json) - } - }, - }, - { - emitDefaults: true, - verifier: func(json string) { - if want := `"sfixed32Value"`; !strings.Contains(json, want) { - t.Errorf(`strings.Contains(%q, %q) = false; want true`, json, want) - } - }, - }, - { - indent: "\t\t", - verifier: func(json string) { - if want := "\t\t\"amount\":"; !strings.Contains(json, want) { - t.Errorf(`strings.Contains(%q, %q) = false; want true`, json, want) - } - }, - }, - { - origName: true, - verifier: func(json string) { - if want := "uint64_value"; !strings.Contains(json, want) { - t.Errorf(`strings.Contains(%q, %q) = false; want true`, json, want) - } - }, - }, - } { - m := runtime.JSONPb{ - EnumsAsInts: spec.enumsAsInts, - EmitDefaults: spec.emitDefaults, - Indent: spec.indent, - OrigName: spec.origName, - } - - var buf bytes.Buffer - enc := m.NewEncoder(&buf) - if err := enc.Encode(&msg); err != nil { - t.Errorf("enc.Encode(%v) failed with %v; want success; spec=%v", &msg, err, spec) - } - - var got examplepb.ABitOfEverything - if err := jsonpb.UnmarshalString(buf.String(), &got); err != nil { - t.Errorf("jsonpb.UnmarshalString(%q, &got) failed with %v; want success; spec=%v", buf.String(), err, spec) - } - if want := msg; !reflect.DeepEqual(got, want) { - t.Errorf("case %d: got = %v; want %v; spec=%v", i, &got, &want, spec) - } - if spec.verifier != nil { - spec.verifier(buf.String()) - } - } -} - -func TestJSONPbEncoderFields(t *testing.T) { - var m runtime.JSONPb - for _, fixt := range fieldFixtures { - var buf bytes.Buffer - enc := m.NewEncoder(&buf) - if err := enc.Encode(fixt.data); err != nil { - t.Errorf("enc.Encode(%#v) failed with %v; want success", fixt.data, err) - } - if got, want := buf.String(), fixt.json; got != want { - t.Errorf("enc.Encode(%#v) = %q; want %q", fixt.data, got, want) - } - } - - m.EnumsAsInts = true - buf, err := m.Marshal(examplepb.NumericEnum_ONE) - if err != nil { - t.Errorf("m.Marshal(%#v) failed with %v; want success", examplepb.NumericEnum_ONE, err) - } - if got, want := string(buf), "1"; got != want { - t.Errorf("m.Marshal(%#v) = %q; want %q", examplepb.NumericEnum_ONE, got, want) - } -} - -func TestJSONPbDecoder(t *testing.T) { - var ( - m runtime.JSONPb - got examplepb.ABitOfEverything - ) - for _, data := range []string{ - `{ - "uuid": "6EC2446F-7E89-4127-B3E6-5C05E6BECBA7", - "nested": [ - {"name": "foo", "amount": 12345} - ], - "uint64Value": 18446744073709551615, - "enumValue": "ONE", - "oneofString": "bar", - "mapValue": { - "a": 1, - "b": 0 - } - }`, - `{ - "uuid": "6EC2446F-7E89-4127-B3E6-5C05E6BECBA7", - "nested": [ - {"name": "foo", "amount": 12345} - ], - "uint64Value": "18446744073709551615", - "enumValue": "ONE", - "oneofString": "bar", - "mapValue": { - "a": 1, - "b": 0 - } - }`, - `{ - "uuid": "6EC2446F-7E89-4127-B3E6-5C05E6BECBA7", - "nested": [ - {"name": "foo", "amount": 12345} - ], - "uint64Value": 18446744073709551615, - "enumValue": 1, - "oneofString": "bar", - "mapValue": { - "a": 1, - "b": 0 - } - }`, - } { - r := strings.NewReader(data) - dec := m.NewDecoder(r) - if err := dec.Decode(&got); err != nil { - t.Errorf("m.Unmarshal(&got) failed with %v; want success; data=%q", err, data) - } - - want := examplepb.ABitOfEverything{ - Uuid: "6EC2446F-7E89-4127-B3E6-5C05E6BECBA7", - Nested: []*examplepb.ABitOfEverything_Nested{ - { - Name: "foo", - Amount: 12345, - }, - }, - Uint64Value: 0xFFFFFFFFFFFFFFFF, - EnumValue: examplepb.NumericEnum_ONE, - OneofValue: &examplepb.ABitOfEverything_OneofString{ - OneofString: "bar", - }, - MapValue: map[string]examplepb.NumericEnum{ - "a": examplepb.NumericEnum_ONE, - "b": examplepb.NumericEnum_ZERO, - }, - } - if !reflect.DeepEqual(got, want) { - t.Errorf("got = %v; want = %v; data = %v", &got, &want, data) - } - } -} - -func TestJSONPbDecoderFields(t *testing.T) { - var m runtime.JSONPb - for _, fixt := range fieldFixtures { - if fixt.skipUnmarshal { - continue - } - - dest := reflect.New(reflect.TypeOf(fixt.data)) - dec := m.NewDecoder(strings.NewReader(fixt.json)) - if err := dec.Decode(dest.Interface()); err != nil { - t.Errorf("dec.Decode(%T) failed with %v; want success; input = %q", dest.Interface(), err, fixt.json) - } - if got, want := dest.Elem().Interface(), fixt.data; !reflect.DeepEqual(got, want) { - t.Errorf("dest = %#v; want %#v; input = %v", got, want, fixt.json) - } - } -} - -var ( - fieldFixtures = []struct { - data interface{} - json string - skipUnmarshal bool - }{ - {data: int32(1), json: "1"}, - {data: proto.Int32(1), json: "1"}, - {data: int64(1), json: "1"}, - {data: proto.Int64(1), json: "1"}, - {data: uint32(1), json: "1"}, - {data: proto.Uint32(1), json: "1"}, - {data: uint64(1), json: "1"}, - {data: proto.Uint64(1), json: "1"}, - {data: "abc", json: `"abc"`}, - {data: proto.String("abc"), json: `"abc"`}, - {data: float32(1.5), json: "1.5"}, - {data: proto.Float32(1.5), json: "1.5"}, - {data: float64(1.5), json: "1.5"}, - {data: proto.Float64(1.5), json: "1.5"}, - {data: true, json: "true"}, - {data: false, json: "false"}, - {data: (*string)(nil), json: "null"}, - { - data: examplepb.NumericEnum_ONE, - json: `"ONE"`, - // TODO(yugui) support unmarshaling of symbolic enum - skipUnmarshal: true, - }, - { - data: (*examplepb.NumericEnum)(proto.Int32(int32(examplepb.NumericEnum_ONE))), - json: `"ONE"`, - // TODO(yugui) support unmarshaling of symbolic enum - skipUnmarshal: true, - }, - - { - data: map[string]int32{ - "foo": 1, - }, - json: `{"foo":1}`, - }, - { - data: map[string]*examplepb.SimpleMessage{ - "foo": {Id: "bar"}, - }, - json: `{"foo":{"id":"bar"}}`, - }, - { - data: map[int32]*examplepb.SimpleMessage{ - 1: {Id: "foo"}, - }, - json: `{"1":{"id":"foo"}}`, - }, - { - data: map[bool]*examplepb.SimpleMessage{ - true: {Id: "foo"}, - }, - json: `{"true":{"id":"foo"}}`, - }, - { - data: &duration.Duration{ - Seconds: 123, - Nanos: 456000000, - }, - json: `"123.456s"`, - }, - { - data: ×tamp.Timestamp{ - Seconds: 1462875553, - Nanos: 123000000, - }, - json: `"2016-05-10T10:19:13.123Z"`, - }, - { - data: new(empty.Empty), - json: "{}", - }, - - // TODO(yugui) Enable unmarshaling of the following examples - // once jsonpb supports them. - { - data: &structpb.Value{ - Kind: new(structpb.Value_NullValue), - }, - json: "null", - skipUnmarshal: true, - }, - { - data: &structpb.Value{ - Kind: &structpb.Value_NumberValue{ - NumberValue: 123.4, - }, - }, - json: "123.4", - skipUnmarshal: true, - }, - { - data: &structpb.Value{ - Kind: &structpb.Value_StringValue{ - StringValue: "abc", - }, - }, - json: `"abc"`, - skipUnmarshal: true, - }, - { - data: &structpb.Value{ - Kind: &structpb.Value_BoolValue{ - BoolValue: true, - }, - }, - json: "true", - skipUnmarshal: true, - }, - { - data: &structpb.Struct{ - Fields: map[string]*structpb.Value{ - "foo_bar": { - Kind: &structpb.Value_BoolValue{ - BoolValue: true, - }, - }, - }, - }, - json: `{"foo_bar":true}`, - skipUnmarshal: true, - }, - - { - data: &wrappers.BoolValue{Value: true}, - json: "true", - }, - { - data: &wrappers.DoubleValue{Value: 123.456}, - json: "123.456", - }, - { - data: &wrappers.FloatValue{Value: 123.456}, - json: "123.456", - }, - { - data: &wrappers.Int32Value{Value: -123}, - json: "-123", - }, - { - data: &wrappers.Int64Value{Value: -123}, - json: `"-123"`, - }, - { - data: &wrappers.UInt32Value{Value: 123}, - json: "123", - }, - { - data: &wrappers.UInt64Value{Value: 123}, - json: `"123"`, - }, - // TODO(yugui) Add other well-known types once jsonpb supports them - } -) diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/marshal_proto_test.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/marshal_proto_test.go deleted file mode 100644 index 07dac47bd..000000000 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/marshal_proto_test.go +++ /dev/null @@ -1,91 +0,0 @@ -package runtime_test - -import ( - "reflect" - "testing" - - "bytes" - "github.com/golang/protobuf/ptypes/timestamp" - "github.com/grpc-ecosystem/grpc-gateway/examples/examplepb" - "github.com/grpc-ecosystem/grpc-gateway/runtime" -) - -var message = &examplepb.ABitOfEverything{ - SingleNested: &examplepb.ABitOfEverything_Nested{}, - RepeatedStringValue: nil, - MappedStringValue: nil, - MappedNestedValue: nil, - RepeatedEnumValue: nil, - TimestampValue: ×tamp.Timestamp{}, - Uuid: "6EC2446F-7E89-4127-B3E6-5C05E6BECBA7", - Nested: []*examplepb.ABitOfEverything_Nested{ - { - Name: "foo", - Amount: 12345, - }, - }, - Uint64Value: 0xFFFFFFFFFFFFFFFF, - EnumValue: examplepb.NumericEnum_ONE, - OneofValue: &examplepb.ABitOfEverything_OneofString{ - OneofString: "bar", - }, - MapValue: map[string]examplepb.NumericEnum{ - "a": examplepb.NumericEnum_ONE, - "b": examplepb.NumericEnum_ZERO, - }, -} - -func TestProtoMarshalUnmarshal(t *testing.T) { - marshaller := runtime.ProtoMarshaller{} - - // Marshal - buffer, err := marshaller.Marshal(message) - if err != nil { - t.Fatalf("Marshalling returned error: %s", err.Error()) - } - - // Unmarshal - unmarshalled := &examplepb.ABitOfEverything{} - err = marshaller.Unmarshal(buffer, unmarshalled) - if err != nil { - t.Fatalf("Unmarshalling returned error: %s", err.Error()) - } - - if !reflect.DeepEqual(unmarshalled, message) { - t.Errorf( - "Unmarshalled didn't match original message: (original = %v) != (unmarshalled = %v)", - unmarshalled, - message, - ) - } -} - -func TestProtoEncoderDecodert(t *testing.T) { - marshaller := runtime.ProtoMarshaller{} - - var buf bytes.Buffer - - encoder := marshaller.NewEncoder(&buf) - decoder := marshaller.NewDecoder(&buf) - - // Encode - err := encoder.Encode(message) - if err != nil { - t.Fatalf("Encoding returned error: %s", err.Error()) - } - - // Decode - unencoded := &examplepb.ABitOfEverything{} - err = decoder.Decode(unencoded) - if err != nil { - t.Fatalf("Unmarshalling returned error: %s", err.Error()) - } - - if !reflect.DeepEqual(unencoded, message) { - t.Errorf( - "Unencoded didn't match original message: (original = %v) != (unencoded = %v)", - unencoded, - message, - ) - } -} diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/marshaler_registry_test.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/marshaler_registry_test.go deleted file mode 100644 index 194de6fee..000000000 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/marshaler_registry_test.go +++ /dev/null @@ -1,107 +0,0 @@ -package runtime_test - -import ( - "errors" - "io" - "net/http" - "testing" - - "github.com/grpc-ecosystem/grpc-gateway/runtime" -) - -func TestMarshalerForRequest(t *testing.T) { - r, err := http.NewRequest("GET", "http://example.com", nil) - if err != nil { - t.Fatalf(`http.NewRequest("GET", "http://example.com", nil) failed with %v; want success`, err) - } - r.Header.Set("Accept", "application/x-out") - r.Header.Set("Content-Type", "application/x-in") - - mux := runtime.NewServeMux() - - in, out := runtime.MarshalerForRequest(mux, r) - if _, ok := in.(*runtime.JSONPb); !ok { - t.Errorf("in = %#v; want a runtime.JSONPb", in) - } - if _, ok := out.(*runtime.JSONPb); !ok { - t.Errorf("out = %#v; want a runtime.JSONPb", in) - } - - var marshalers [3]dummyMarshaler - specs := []struct { - opt runtime.ServeMuxOption - - wantIn runtime.Marshaler - wantOut runtime.Marshaler - }{ - { - opt: runtime.WithMarshalerOption(runtime.MIMEWildcard, &marshalers[0]), - wantIn: &marshalers[0], - wantOut: &marshalers[0], - }, - { - opt: runtime.WithMarshalerOption("application/x-in", &marshalers[1]), - wantIn: &marshalers[1], - wantOut: &marshalers[0], - }, - { - opt: runtime.WithMarshalerOption("application/x-out", &marshalers[2]), - wantIn: &marshalers[1], - wantOut: &marshalers[2], - }, - } - for i, spec := range specs { - var opts []runtime.ServeMuxOption - for _, s := range specs[:i+1] { - opts = append(opts, s.opt) - } - mux = runtime.NewServeMux(opts...) - - in, out = runtime.MarshalerForRequest(mux, r) - if got, want := in, spec.wantIn; got != want { - t.Errorf("in = %#v; want %#v", got, want) - } - if got, want := out, spec.wantOut; got != want { - t.Errorf("out = %#v; want %#v", got, want) - } - } - - r.Header.Set("Content-Type", "application/x-another") - in, out = runtime.MarshalerForRequest(mux, r) - if got, want := in, &marshalers[1]; got != want { - t.Errorf("in = %#v; want %#v", got, want) - } - if got, want := out, &marshalers[0]; got != want { - t.Errorf("out = %#v; want %#v", got, want) - } -} - -type dummyMarshaler struct{} - -func (dummyMarshaler) ContentType() string { return "" } -func (dummyMarshaler) Marshal(interface{}) ([]byte, error) { - return nil, errors.New("not implemented") -} - -func (dummyMarshaler) Unmarshal([]byte, interface{}) error { - return errors.New("not implemented") -} - -func (dummyMarshaler) NewDecoder(r io.Reader) runtime.Decoder { - return dummyDecoder{} -} -func (dummyMarshaler) NewEncoder(w io.Writer) runtime.Encoder { - return dummyEncoder{} -} - -type dummyDecoder struct{} - -func (dummyDecoder) Decode(interface{}) error { - return errors.New("not implemented") -} - -type dummyEncoder struct{} - -func (dummyEncoder) Encode(interface{}) error { - return errors.New("not implemented") -} diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/mux_test.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/mux_test.go deleted file mode 100644 index bb90a7306..000000000 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/mux_test.go +++ /dev/null @@ -1,213 +0,0 @@ -package runtime_test - -import ( - "bytes" - "fmt" - "net/http" - "net/http/httptest" - "testing" - - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/grpc-ecosystem/grpc-gateway/utilities" -) - -func TestMuxServeHTTP(t *testing.T) { - type stubPattern struct { - method string - ops []int - pool []string - verb string - } - for _, spec := range []struct { - patterns []stubPattern - - reqMethod string - reqPath string - headers map[string]string - - respStatus int - respContent string - }{ - { - patterns: nil, - reqMethod: "GET", - reqPath: "/", - respStatus: http.StatusNotFound, - }, - { - patterns: []stubPattern{ - { - method: "GET", - ops: []int{int(utilities.OpLitPush), 0}, - pool: []string{"foo"}, - }, - }, - reqMethod: "GET", - reqPath: "/foo", - respStatus: http.StatusOK, - respContent: "GET /foo", - }, - { - patterns: []stubPattern{ - { - method: "GET", - ops: []int{int(utilities.OpLitPush), 0}, - pool: []string{"foo"}, - }, - }, - reqMethod: "GET", - reqPath: "/bar", - respStatus: http.StatusNotFound, - }, - { - patterns: []stubPattern{ - { - method: "GET", - ops: []int{int(utilities.OpLitPush), 0}, - pool: []string{"foo"}, - }, - { - method: "GET", - ops: []int{int(utilities.OpPush), 0}, - }, - }, - reqMethod: "GET", - reqPath: "/foo", - respStatus: http.StatusOK, - respContent: "GET /foo", - }, - { - patterns: []stubPattern{ - { - method: "GET", - ops: []int{int(utilities.OpLitPush), 0}, - pool: []string{"foo"}, - }, - { - method: "POST", - ops: []int{int(utilities.OpLitPush), 0}, - pool: []string{"foo"}, - }, - }, - reqMethod: "POST", - reqPath: "/foo", - respStatus: http.StatusOK, - respContent: "POST /foo", - }, - { - patterns: []stubPattern{ - { - method: "GET", - ops: []int{int(utilities.OpLitPush), 0}, - pool: []string{"foo"}, - }, - }, - reqMethod: "DELETE", - reqPath: "/foo", - respStatus: http.StatusMethodNotAllowed, - }, - { - patterns: []stubPattern{ - { - method: "GET", - ops: []int{int(utilities.OpLitPush), 0}, - pool: []string{"foo"}, - }, - }, - reqMethod: "POST", - reqPath: "/foo", - headers: map[string]string{ - "Content-Type": "application/x-www-form-urlencoded", - }, - respStatus: http.StatusOK, - respContent: "GET /foo", - }, - { - patterns: []stubPattern{ - { - method: "GET", - ops: []int{int(utilities.OpLitPush), 0}, - pool: []string{"foo"}, - }, - { - method: "POST", - ops: []int{int(utilities.OpLitPush), 0}, - pool: []string{"foo"}, - }, - }, - reqMethod: "POST", - reqPath: "/foo", - headers: map[string]string{ - "Content-Type": "application/x-www-form-urlencoded", - "X-HTTP-Method-Override": "GET", - }, - respStatus: http.StatusOK, - respContent: "GET /foo", - }, - { - patterns: []stubPattern{ - { - method: "GET", - ops: []int{int(utilities.OpLitPush), 0}, - pool: []string{"foo"}, - }, - }, - reqMethod: "POST", - reqPath: "/foo", - headers: map[string]string{ - "Content-Type": "application/json", - }, - respStatus: http.StatusMethodNotAllowed, - }, - { - patterns: []stubPattern{ - { - method: "POST", - ops: []int{int(utilities.OpLitPush), 0}, - pool: []string{"foo"}, - verb: "bar", - }, - }, - reqMethod: "POST", - reqPath: "/foo:bar", - headers: map[string]string{ - "Content-Type": "application/json", - }, - respStatus: http.StatusOK, - respContent: "POST /foo:bar", - }, - } { - mux := runtime.NewServeMux() - for _, p := range spec.patterns { - func(p stubPattern) { - pat, err := runtime.NewPattern(1, p.ops, p.pool, p.verb) - if err != nil { - t.Fatalf("runtime.NewPattern(1, %#v, %#v, %q) failed with %v; want success", p.ops, p.pool, p.verb, err) - } - mux.Handle(p.method, pat, func(w http.ResponseWriter, r *http.Request, pathParams map[string]string) { - fmt.Fprintf(w, "%s %s", p.method, pat.String()) - }) - }(p) - } - - url := fmt.Sprintf("http://host.example%s", spec.reqPath) - r, err := http.NewRequest(spec.reqMethod, url, bytes.NewReader(nil)) - if err != nil { - t.Fatalf("http.NewRequest(%q, %q, nil) failed with %v; want success", spec.reqMethod, url, err) - } - for name, value := range spec.headers { - r.Header.Set(name, value) - } - w := httptest.NewRecorder() - mux.ServeHTTP(w, r) - - if got, want := w.Code, spec.respStatus; got != want { - t.Errorf("w.Code = %d; want %d; patterns=%v; req=%v", got, want, spec.patterns, r) - } - if spec.respContent != "" { - if got, want := w.Body.String(), spec.respContent; got != want { - t.Errorf("w.Body = %q; want %q; patterns=%v; req=%v", got, want, spec.patterns, r) - } - } - } -} diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/pattern_test.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/pattern_test.go deleted file mode 100644 index 8f5a664ab..000000000 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/pattern_test.go +++ /dev/null @@ -1,590 +0,0 @@ -package runtime - -import ( - "fmt" - "reflect" - "strings" - "testing" - - "github.com/grpc-ecosystem/grpc-gateway/utilities" -) - -const ( - validVersion = 1 - anything = 0 -) - -func TestNewPattern(t *testing.T) { - for _, spec := range []struct { - ops []int - pool []string - verb string - - stackSizeWant, tailLenWant int - }{ - {}, - { - ops: []int{int(utilities.OpNop), anything}, - stackSizeWant: 0, - tailLenWant: 0, - }, - { - ops: []int{int(utilities.OpPush), anything}, - stackSizeWant: 1, - tailLenWant: 0, - }, - { - ops: []int{int(utilities.OpLitPush), 0}, - pool: []string{"abc"}, - stackSizeWant: 1, - tailLenWant: 0, - }, - { - ops: []int{int(utilities.OpPushM), anything}, - stackSizeWant: 1, - tailLenWant: 0, - }, - { - ops: []int{ - int(utilities.OpPush), anything, - int(utilities.OpConcatN), 1, - }, - stackSizeWant: 1, - tailLenWant: 0, - }, - { - ops: []int{ - int(utilities.OpPush), anything, - int(utilities.OpConcatN), 1, - int(utilities.OpCapture), 0, - }, - pool: []string{"abc"}, - stackSizeWant: 1, - tailLenWant: 0, - }, - { - ops: []int{ - int(utilities.OpPush), anything, - int(utilities.OpLitPush), 0, - int(utilities.OpLitPush), 1, - int(utilities.OpPushM), anything, - int(utilities.OpConcatN), 2, - int(utilities.OpCapture), 2, - }, - pool: []string{"lit1", "lit2", "var1"}, - stackSizeWant: 4, - tailLenWant: 0, - }, - { - ops: []int{ - int(utilities.OpPushM), anything, - int(utilities.OpConcatN), 1, - int(utilities.OpCapture), 2, - int(utilities.OpLitPush), 0, - int(utilities.OpLitPush), 1, - }, - pool: []string{"lit1", "lit2", "var1"}, - stackSizeWant: 2, - tailLenWant: 2, - }, - { - ops: []int{ - int(utilities.OpLitPush), 0, - int(utilities.OpLitPush), 1, - int(utilities.OpPushM), anything, - int(utilities.OpLitPush), 2, - int(utilities.OpConcatN), 3, - int(utilities.OpLitPush), 3, - int(utilities.OpCapture), 4, - }, - pool: []string{"lit1", "lit2", "lit3", "lit4", "var1"}, - stackSizeWant: 4, - tailLenWant: 2, - }, - { - ops: []int{int(utilities.OpLitPush), 0}, - pool: []string{"abc"}, - verb: "LOCK", - stackSizeWant: 1, - tailLenWant: 0, - }, - } { - pat, err := NewPattern(validVersion, spec.ops, spec.pool, spec.verb) - if err != nil { - t.Errorf("NewPattern(%d, %v, %q, %q) failed with %v; want success", validVersion, spec.ops, spec.pool, spec.verb, err) - continue - } - if got, want := pat.stacksize, spec.stackSizeWant; got != want { - t.Errorf("pat.stacksize = %d; want %d", got, want) - } - if got, want := pat.tailLen, spec.tailLenWant; got != want { - t.Errorf("pat.stacksize = %d; want %d", got, want) - } - } -} - -func TestNewPatternWithWrongOp(t *testing.T) { - for _, spec := range []struct { - ops []int - pool []string - verb string - }{ - { - // op code out of bound - ops: []int{-1, anything}, - }, - { - // op code out of bound - ops: []int{int(utilities.OpEnd), 0}, - }, - { - // odd number of items - ops: []int{int(utilities.OpPush)}, - }, - { - // negative index - ops: []int{int(utilities.OpLitPush), -1}, - pool: []string{"abc"}, - }, - { - // index out of bound - ops: []int{int(utilities.OpLitPush), 1}, - pool: []string{"abc"}, - }, - { - // negative # of segments - ops: []int{int(utilities.OpConcatN), -1}, - pool: []string{"abc"}, - }, - { - // negative index - ops: []int{int(utilities.OpCapture), -1}, - pool: []string{"abc"}, - }, - { - // index out of bound - ops: []int{int(utilities.OpCapture), 1}, - pool: []string{"abc"}, - }, - { - // pushM appears twice - ops: []int{ - int(utilities.OpPushM), anything, - int(utilities.OpLitPush), 0, - int(utilities.OpPushM), anything, - }, - pool: []string{"abc"}, - }, - } { - _, err := NewPattern(validVersion, spec.ops, spec.pool, spec.verb) - if err == nil { - t.Errorf("NewPattern(%d, %v, %q, %q) succeeded; want failure with %v", validVersion, spec.ops, spec.pool, spec.verb, ErrInvalidPattern) - continue - } - if err != ErrInvalidPattern { - t.Errorf("NewPattern(%d, %v, %q, %q) failed with %v; want failure with %v", validVersion, spec.ops, spec.pool, spec.verb, err, ErrInvalidPattern) - continue - } - } -} - -func TestNewPatternWithStackUnderflow(t *testing.T) { - for _, spec := range []struct { - ops []int - pool []string - verb string - }{ - { - ops: []int{int(utilities.OpConcatN), 1}, - }, - { - ops: []int{int(utilities.OpCapture), 0}, - pool: []string{"abc"}, - }, - } { - _, err := NewPattern(validVersion, spec.ops, spec.pool, spec.verb) - if err == nil { - t.Errorf("NewPattern(%d, %v, %q, %q) succeeded; want failure with %v", validVersion, spec.ops, spec.pool, spec.verb, ErrInvalidPattern) - continue - } - if err != ErrInvalidPattern { - t.Errorf("NewPattern(%d, %v, %q, %q) failed with %v; want failure with %v", validVersion, spec.ops, spec.pool, spec.verb, err, ErrInvalidPattern) - continue - } - } -} - -func TestMatch(t *testing.T) { - for _, spec := range []struct { - ops []int - pool []string - verb string - - match []string - notMatch []string - }{ - { - match: []string{""}, - notMatch: []string{"example"}, - }, - { - ops: []int{int(utilities.OpNop), anything}, - match: []string{""}, - notMatch: []string{"example", "path/to/example"}, - }, - { - ops: []int{int(utilities.OpPush), anything}, - match: []string{"abc", "def"}, - notMatch: []string{"", "abc/def"}, - }, - { - ops: []int{int(utilities.OpLitPush), 0}, - pool: []string{"v1"}, - match: []string{"v1"}, - notMatch: []string{"", "v2"}, - }, - { - ops: []int{int(utilities.OpPushM), anything}, - match: []string{"", "abc", "abc/def", "abc/def/ghi"}, - }, - { - ops: []int{ - int(utilities.OpPushM), anything, - int(utilities.OpLitPush), 0, - }, - pool: []string{"tail"}, - match: []string{"tail", "abc/tail", "abc/def/tail"}, - notMatch: []string{ - "", "abc", "abc/def", - "tail/extra", "abc/tail/extra", "abc/def/tail/extra", - }, - }, - { - ops: []int{ - int(utilities.OpLitPush), 0, - int(utilities.OpLitPush), 1, - int(utilities.OpPush), anything, - int(utilities.OpConcatN), 1, - int(utilities.OpCapture), 2, - }, - pool: []string{"v1", "bucket", "name"}, - match: []string{"v1/bucket/my-bucket", "v1/bucket/our-bucket"}, - notMatch: []string{ - "", - "v1", - "v1/bucket", - "v2/bucket/my-bucket", - "v1/pubsub/my-topic", - }, - }, - { - ops: []int{ - int(utilities.OpLitPush), 0, - int(utilities.OpLitPush), 1, - int(utilities.OpPushM), anything, - int(utilities.OpConcatN), 2, - int(utilities.OpCapture), 2, - }, - pool: []string{"v1", "o", "name"}, - match: []string{ - "v1/o", - "v1/o/my-bucket", - "v1/o/our-bucket", - "v1/o/my-bucket/dir", - "v1/o/my-bucket/dir/dir2", - "v1/o/my-bucket/dir/dir2/obj", - }, - notMatch: []string{ - "", - "v1", - "v2/o/my-bucket", - "v1/b/my-bucket", - }, - }, - { - ops: []int{ - int(utilities.OpLitPush), 0, - int(utilities.OpLitPush), 1, - int(utilities.OpPush), anything, - int(utilities.OpConcatN), 2, - int(utilities.OpCapture), 2, - int(utilities.OpLitPush), 3, - int(utilities.OpPush), anything, - int(utilities.OpConcatN), 1, - int(utilities.OpCapture), 4, - }, - pool: []string{"v2", "b", "name", "o", "oname"}, - match: []string{ - "v2/b/my-bucket/o/obj", - "v2/b/our-bucket/o/obj", - "v2/b/my-bucket/o/dir", - }, - notMatch: []string{ - "", - "v2", - "v2/b", - "v2/b/my-bucket", - "v2/b/my-bucket/o", - }, - }, - { - ops: []int{int(utilities.OpLitPush), 0}, - pool: []string{"v1"}, - verb: "LOCK", - match: []string{"v1:LOCK"}, - notMatch: []string{"v1", "LOCK"}, - }, - } { - pat, err := NewPattern(validVersion, spec.ops, spec.pool, spec.verb) - if err != nil { - t.Errorf("NewPattern(%d, %v, %q, %q) failed with %v; want success", validVersion, spec.ops, spec.pool, spec.verb, err) - continue - } - - for _, path := range spec.match { - _, err = pat.Match(segments(path)) - if err != nil { - t.Errorf("pat.Match(%q) failed with %v; want success; pattern = (%v, %q)", path, err, spec.ops, spec.pool) - } - } - - for _, path := range spec.notMatch { - _, err = pat.Match(segments(path)) - if err == nil { - t.Errorf("pat.Match(%q) succeeded; want failure with %v; pattern = (%v, %q)", path, ErrNotMatch, spec.ops, spec.pool) - continue - } - if err != ErrNotMatch { - t.Errorf("pat.Match(%q) failed with %v; want failure with %v; pattern = (%v, %q)", spec.notMatch, err, ErrNotMatch, spec.ops, spec.pool) - } - } - } -} - -func TestMatchWithBinding(t *testing.T) { - for _, spec := range []struct { - ops []int - pool []string - path string - verb string - - want map[string]string - }{ - { - want: make(map[string]string), - }, - { - ops: []int{int(utilities.OpNop), anything}, - want: make(map[string]string), - }, - { - ops: []int{int(utilities.OpPush), anything}, - path: "abc", - want: make(map[string]string), - }, - { - ops: []int{int(utilities.OpPush), anything}, - verb: "LOCK", - path: "abc:LOCK", - want: make(map[string]string), - }, - { - ops: []int{int(utilities.OpLitPush), 0}, - pool: []string{"endpoint"}, - path: "endpoint", - want: make(map[string]string), - }, - { - ops: []int{int(utilities.OpPushM), anything}, - path: "abc/def/ghi", - want: make(map[string]string), - }, - { - ops: []int{ - int(utilities.OpLitPush), 0, - int(utilities.OpLitPush), 1, - int(utilities.OpPush), anything, - int(utilities.OpConcatN), 1, - int(utilities.OpCapture), 2, - }, - pool: []string{"v1", "bucket", "name"}, - path: "v1/bucket/my-bucket", - want: map[string]string{ - "name": "my-bucket", - }, - }, - { - ops: []int{ - int(utilities.OpLitPush), 0, - int(utilities.OpLitPush), 1, - int(utilities.OpPush), anything, - int(utilities.OpConcatN), 1, - int(utilities.OpCapture), 2, - }, - pool: []string{"v1", "bucket", "name"}, - verb: "LOCK", - path: "v1/bucket/my-bucket:LOCK", - want: map[string]string{ - "name": "my-bucket", - }, - }, - { - ops: []int{ - int(utilities.OpLitPush), 0, - int(utilities.OpLitPush), 1, - int(utilities.OpPushM), anything, - int(utilities.OpConcatN), 2, - int(utilities.OpCapture), 2, - }, - pool: []string{"v1", "o", "name"}, - path: "v1/o/my-bucket/dir/dir2/obj", - want: map[string]string{ - "name": "o/my-bucket/dir/dir2/obj", - }, - }, - { - ops: []int{ - int(utilities.OpLitPush), 0, - int(utilities.OpLitPush), 1, - int(utilities.OpPushM), anything, - int(utilities.OpLitPush), 2, - int(utilities.OpConcatN), 3, - int(utilities.OpCapture), 4, - int(utilities.OpLitPush), 3, - }, - pool: []string{"v1", "o", ".ext", "tail", "name"}, - path: "v1/o/my-bucket/dir/dir2/obj/.ext/tail", - want: map[string]string{ - "name": "o/my-bucket/dir/dir2/obj/.ext", - }, - }, - { - ops: []int{ - int(utilities.OpLitPush), 0, - int(utilities.OpLitPush), 1, - int(utilities.OpPush), anything, - int(utilities.OpConcatN), 2, - int(utilities.OpCapture), 2, - int(utilities.OpLitPush), 3, - int(utilities.OpPush), anything, - int(utilities.OpConcatN), 1, - int(utilities.OpCapture), 4, - }, - pool: []string{"v2", "b", "name", "o", "oname"}, - path: "v2/b/my-bucket/o/obj", - want: map[string]string{ - "name": "b/my-bucket", - "oname": "obj", - }, - }, - } { - pat, err := NewPattern(validVersion, spec.ops, spec.pool, spec.verb) - if err != nil { - t.Errorf("NewPattern(%d, %v, %q, %q) failed with %v; want success", validVersion, spec.ops, spec.pool, spec.verb, err) - continue - } - - got, err := pat.Match(segments(spec.path)) - if err != nil { - t.Errorf("pat.Match(%q) failed with %v; want success; pattern = (%v, %q)", spec.path, err, spec.ops, spec.pool) - } - if !reflect.DeepEqual(got, spec.want) { - t.Errorf("pat.Match(%q) = %q; want %q; pattern = (%v, %q)", spec.path, got, spec.want, spec.ops, spec.pool) - } - } -} - -func segments(path string) (components []string, verb string) { - if path == "" { - return nil, "" - } - components = strings.Split(path, "/") - l := len(components) - c := components[l-1] - if idx := strings.LastIndex(c, ":"); idx >= 0 { - components[l-1], verb = c[:idx], c[idx+1:] - } - return components, verb -} - -func TestPatternString(t *testing.T) { - for _, spec := range []struct { - ops []int - pool []string - - want string - }{ - { - want: "/", - }, - { - ops: []int{int(utilities.OpNop), anything}, - want: "/", - }, - { - ops: []int{int(utilities.OpPush), anything}, - want: "/*", - }, - { - ops: []int{int(utilities.OpLitPush), 0}, - pool: []string{"endpoint"}, - want: "/endpoint", - }, - { - ops: []int{int(utilities.OpPushM), anything}, - want: "/**", - }, - { - ops: []int{ - int(utilities.OpPush), anything, - int(utilities.OpConcatN), 1, - }, - want: "/*", - }, - { - ops: []int{ - int(utilities.OpPush), anything, - int(utilities.OpConcatN), 1, - int(utilities.OpCapture), 0, - }, - pool: []string{"name"}, - want: "/{name=*}", - }, - { - ops: []int{ - int(utilities.OpLitPush), 0, - int(utilities.OpLitPush), 1, - int(utilities.OpPush), anything, - int(utilities.OpConcatN), 2, - int(utilities.OpCapture), 2, - int(utilities.OpLitPush), 3, - int(utilities.OpPushM), anything, - int(utilities.OpLitPush), 4, - int(utilities.OpConcatN), 3, - int(utilities.OpCapture), 6, - int(utilities.OpLitPush), 5, - }, - pool: []string{"v1", "buckets", "bucket_name", "objects", ".ext", "tail", "name"}, - want: "/v1/{bucket_name=buckets/*}/{name=objects/**/.ext}/tail", - }, - } { - p, err := NewPattern(validVersion, spec.ops, spec.pool, "") - if err != nil { - t.Errorf("NewPattern(%d, %v, %q, %q) failed with %v; want success", validVersion, spec.ops, spec.pool, "", err) - continue - } - if got, want := p.String(), spec.want; got != want { - t.Errorf("%#v.String() = %q; want %q", p, got, want) - } - - verb := "LOCK" - p, err = NewPattern(validVersion, spec.ops, spec.pool, verb) - if err != nil { - t.Errorf("NewPattern(%d, %v, %q, %q) failed with %v; want success", validVersion, spec.ops, spec.pool, verb, err) - continue - } - if got, want := p.String(), fmt.Sprintf("%s:%s", spec.want, verb); got != want { - t.Errorf("%#v.String() = %q; want %q", p, got, want) - } - } -} diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/query_test.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/query_test.go deleted file mode 100644 index 95a72a4af..000000000 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/query_test.go +++ /dev/null @@ -1,715 +0,0 @@ -package runtime_test - -import ( - "errors" - "fmt" - "net/url" - "reflect" - "testing" - - "time" - - "github.com/golang/protobuf/proto" - "github.com/golang/protobuf/ptypes" - "github.com/golang/protobuf/ptypes/timestamp" - "github.com/golang/protobuf/ptypes/wrappers" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/grpc-ecosystem/grpc-gateway/utilities" -) - -func TestPopulateParameters(t *testing.T) { - timeT := time.Date(2016, time.December, 15, 12, 23, 32, 49, time.UTC) - timeStr := timeT.Format(time.RFC3339Nano) - timePb, err := ptypes.TimestampProto(timeT) - if err != nil { - t.Fatalf("Couldn't setup timestamp in Protobuf format: %v", err) - } - - for _, spec := range []struct { - values url.Values - filter *utilities.DoubleArray - want proto.Message - wanterr error - }{ - { - values: url.Values{ - "float_value": {"1.5"}, - "double_value": {"2.5"}, - "int64_value": {"-1"}, - "int32_value": {"-2"}, - "uint64_value": {"3"}, - "uint32_value": {"4"}, - "bool_value": {"true"}, - "string_value": {"str"}, - "repeated_value": {"a", "b", "c"}, - "enum_value": {"1"}, - "repeated_enum": {"1", "2", "0"}, - "timestamp_value": {timeStr}, - "wrapper_float_value": {"1.5"}, - "wrapper_double_value": {"2.5"}, - "wrapper_int64_value": {"-1"}, - "wrapper_int32_value": {"-2"}, - "wrapper_u_int64_value": {"3"}, - "wrapper_u_int32_value": {"4"}, - "wrapper_bool_value": {"true"}, - "wrapper_string_value": {"str"}, - }, - filter: utilities.NewDoubleArray(nil), - want: &proto3Message{ - FloatValue: 1.5, - DoubleValue: 2.5, - Int64Value: -1, - Int32Value: -2, - Uint64Value: 3, - Uint32Value: 4, - BoolValue: true, - StringValue: "str", - RepeatedValue: []string{"a", "b", "c"}, - EnumValue: EnumValue_Y, - RepeatedEnum: []EnumValue{EnumValue_Y, EnumValue_Z, EnumValue_X}, - TimestampValue: timePb, - WrapperFloatValue: &wrappers.FloatValue{1.5}, - WrapperDoubleValue: &wrappers.DoubleValue{2.5}, - WrapperInt64Value: &wrappers.Int64Value{-1}, - WrapperInt32Value: &wrappers.Int32Value{-2}, - WrapperUInt64Value: &wrappers.UInt64Value{3}, - WrapperUInt32Value: &wrappers.UInt32Value{4}, - WrapperBoolValue: &wrappers.BoolValue{true}, - WrapperStringValue: &wrappers.StringValue{"str"}, - }, - }, - { - values: url.Values{ - "floatValue": {"1.5"}, - "doubleValue": {"2.5"}, - "int64Value": {"-1"}, - "int32Value": {"-2"}, - "uint64Value": {"3"}, - "uint32Value": {"4"}, - "boolValue": {"true"}, - "stringValue": {"str"}, - "repeatedValue": {"a", "b", "c"}, - "enumValue": {"1"}, - "repeatedEnum": {"1", "2", "0"}, - "timestampValue": {timeStr}, - "wrapperFloatValue": {"1.5"}, - "wrapperDoubleValue": {"2.5"}, - "wrapperInt64Value": {"-1"}, - "wrapperInt32Value": {"-2"}, - "wrapperUInt64Value": {"3"}, - "wrapperUInt32Value": {"4"}, - "wrapperBoolValue": {"true"}, - "wrapperStringValue": {"str"}, - }, - filter: utilities.NewDoubleArray(nil), - want: &proto3Message{ - FloatValue: 1.5, - DoubleValue: 2.5, - Int64Value: -1, - Int32Value: -2, - Uint64Value: 3, - Uint32Value: 4, - BoolValue: true, - StringValue: "str", - RepeatedValue: []string{"a", "b", "c"}, - EnumValue: EnumValue_Y, - RepeatedEnum: []EnumValue{EnumValue_Y, EnumValue_Z, EnumValue_X}, - TimestampValue: timePb, - WrapperFloatValue: &wrappers.FloatValue{1.5}, - WrapperDoubleValue: &wrappers.DoubleValue{2.5}, - WrapperInt64Value: &wrappers.Int64Value{-1}, - WrapperInt32Value: &wrappers.Int32Value{-2}, - WrapperUInt64Value: &wrappers.UInt64Value{3}, - WrapperUInt32Value: &wrappers.UInt32Value{4}, - WrapperBoolValue: &wrappers.BoolValue{true}, - WrapperStringValue: &wrappers.StringValue{"str"}, - }, - }, - { - values: url.Values{ - "enum_value": {"EnumValue_Z"}, - "repeated_enum": {"EnumValue_X", "2", "0"}, - }, - filter: utilities.NewDoubleArray(nil), - want: &proto3Message{ - EnumValue: EnumValue_Z, - RepeatedEnum: []EnumValue{EnumValue_X, EnumValue_Z, EnumValue_X}, - }, - }, - { - values: url.Values{ - "float_value": {"1.5"}, - "double_value": {"2.5"}, - "int64_value": {"-1"}, - "int32_value": {"-2"}, - "uint64_value": {"3"}, - "uint32_value": {"4"}, - "bool_value": {"true"}, - "string_value": {"str"}, - "repeated_value": {"a", "b", "c"}, - "enum_value": {"1"}, - "repeated_enum": {"1", "2", "0"}, - }, - filter: utilities.NewDoubleArray(nil), - want: &proto2Message{ - FloatValue: proto.Float32(1.5), - DoubleValue: proto.Float64(2.5), - Int64Value: proto.Int64(-1), - Int32Value: proto.Int32(-2), - Uint64Value: proto.Uint64(3), - Uint32Value: proto.Uint32(4), - BoolValue: proto.Bool(true), - StringValue: proto.String("str"), - RepeatedValue: []string{"a", "b", "c"}, - EnumValue: EnumValue_Y, - RepeatedEnum: []EnumValue{EnumValue_Y, EnumValue_Z, EnumValue_X}, - }, - }, - { - values: url.Values{ - "floatValue": {"1.5"}, - "doubleValue": {"2.5"}, - "int64Value": {"-1"}, - "int32Value": {"-2"}, - "uint64Value": {"3"}, - "uint32Value": {"4"}, - "boolValue": {"true"}, - "stringValue": {"str"}, - "repeatedValue": {"a", "b", "c"}, - "enumValue": {"1"}, - "repeatedEnum": {"1", "2", "0"}, - }, - filter: utilities.NewDoubleArray(nil), - want: &proto2Message{ - FloatValue: proto.Float32(1.5), - DoubleValue: proto.Float64(2.5), - Int64Value: proto.Int64(-1), - Int32Value: proto.Int32(-2), - Uint64Value: proto.Uint64(3), - Uint32Value: proto.Uint32(4), - BoolValue: proto.Bool(true), - StringValue: proto.String("str"), - RepeatedValue: []string{"a", "b", "c"}, - EnumValue: EnumValue_Y, - RepeatedEnum: []EnumValue{EnumValue_Y, EnumValue_Z, EnumValue_X}, - }, - }, - { - values: url.Values{ - "nested.nested.nested.repeated_value": {"a", "b", "c"}, - "nested.nested.nested.string_value": {"s"}, - "nested.nested.string_value": {"t"}, - "nested.string_value": {"u"}, - "nested_non_null.string_value": {"v"}, - }, - filter: utilities.NewDoubleArray(nil), - want: &proto3Message{ - Nested: &proto2Message{ - Nested: &proto3Message{ - Nested: &proto2Message{ - RepeatedValue: []string{"a", "b", "c"}, - StringValue: proto.String("s"), - }, - StringValue: "t", - }, - StringValue: proto.String("u"), - }, - NestedNonNull: proto2Message{ - StringValue: proto.String("v"), - }, - }, - }, - { - values: url.Values{ - "uint64_value": {"1", "2", "3", "4", "5"}, - }, - filter: utilities.NewDoubleArray(nil), - want: &proto3Message{ - Uint64Value: 1, - }, - }, - { - values: url.Values{ - "oneof_string_value": {"foobar"}, - }, - filter: utilities.NewDoubleArray(nil), - want: &proto3Message{ - OneofValue: &proto3Message_OneofStringValue{"foobar"}, - }, - }, - { - values: url.Values{ - "oneof_bool_value": {"true"}, - }, - filter: utilities.NewDoubleArray(nil), - want: &proto3Message{ - OneofValue: &proto3Message_OneofBoolValue{true}, - }, - }, - { - // Don't allow setting a oneof more than once - values: url.Values{ - "oneof_bool_value": {"true"}, - "oneof_string_value": {"foobar"}, - }, - filter: utilities.NewDoubleArray(nil), - want: &proto3Message{}, - wanterr: errors.New("field already set for oneof_value oneof"), - }, - } { - msg := proto.Clone(spec.want) - msg.Reset() - err := runtime.PopulateQueryParameters(msg, spec.values, spec.filter) - if spec.wanterr != nil { - if !reflect.DeepEqual(err, spec.wanterr) { - t.Errorf("runtime.PopulateQueryParameters(msg, %v, %v) failed with %v; want error %v", spec.values, spec.filter, err, spec.wanterr) - } - continue - } - - if err != nil { - t.Errorf("runtime.PopulateQueryParameters(msg, %v, %v) failed with %v; want success", spec.values, spec.filter, err) - continue - } - if got, want := msg, spec.want; !proto.Equal(got, want) { - t.Errorf("runtime.PopulateQueryParameters(msg, %v, %v = %v; want %v", spec.values, spec.filter, got, want) - } - } -} - -func TestPopulateParametersWithFilters(t *testing.T) { - for _, spec := range []struct { - values url.Values - filter *utilities.DoubleArray - want proto.Message - }{ - { - values: url.Values{ - "bool_value": {"true"}, - "string_value": {"str"}, - "repeated_value": {"a", "b", "c"}, - }, - filter: utilities.NewDoubleArray([][]string{ - {"bool_value"}, {"repeated_value"}, - }), - want: &proto3Message{ - StringValue: "str", - }, - }, - { - values: url.Values{ - "nested.nested.bool_value": {"true"}, - "nested.nested.string_value": {"str"}, - "nested.string_value": {"str"}, - "string_value": {"str"}, - }, - filter: utilities.NewDoubleArray([][]string{ - {"nested"}, - }), - want: &proto3Message{ - StringValue: "str", - }, - }, - { - values: url.Values{ - "nested.nested.bool_value": {"true"}, - "nested.nested.string_value": {"str"}, - "nested.string_value": {"str"}, - "string_value": {"str"}, - }, - filter: utilities.NewDoubleArray([][]string{ - {"nested", "nested"}, - }), - want: &proto3Message{ - Nested: &proto2Message{ - StringValue: proto.String("str"), - }, - StringValue: "str", - }, - }, - { - values: url.Values{ - "nested.nested.bool_value": {"true"}, - "nested.nested.string_value": {"str"}, - "nested.string_value": {"str"}, - "string_value": {"str"}, - }, - filter: utilities.NewDoubleArray([][]string{ - {"nested", "nested", "string_value"}, - }), - want: &proto3Message{ - Nested: &proto2Message{ - StringValue: proto.String("str"), - Nested: &proto3Message{ - BoolValue: true, - }, - }, - StringValue: "str", - }, - }, - } { - msg := proto.Clone(spec.want) - msg.Reset() - err := runtime.PopulateQueryParameters(msg, spec.values, spec.filter) - if err != nil { - t.Errorf("runtime.PoplateQueryParameters(msg, %v, %v) failed with %v; want success", spec.values, spec.filter, err) - continue - } - if got, want := msg, spec.want; !proto.Equal(got, want) { - t.Errorf("runtime.PopulateQueryParameters(msg, %v, %v = %v; want %v", spec.values, spec.filter, got, want) - } - } -} - -func TestPopulateQueryParametersWithInvalidNestedParameters(t *testing.T) { - for _, spec := range []struct { - msg proto.Message - values url.Values - filter *utilities.DoubleArray - }{ - { - msg: &proto3Message{}, - values: url.Values{ - "float_value.nested": {"test"}, - }, - filter: utilities.NewDoubleArray(nil), - }, - { - msg: &proto3Message{}, - values: url.Values{ - "double_value.nested": {"test"}, - }, - filter: utilities.NewDoubleArray(nil), - }, - { - msg: &proto3Message{}, - values: url.Values{ - "int64_value.nested": {"test"}, - }, - filter: utilities.NewDoubleArray(nil), - }, - { - msg: &proto3Message{}, - values: url.Values{ - "int32_value.nested": {"test"}, - }, - filter: utilities.NewDoubleArray(nil), - }, - { - msg: &proto3Message{}, - values: url.Values{ - "uint64_value.nested": {"test"}, - }, - filter: utilities.NewDoubleArray(nil), - }, - { - msg: &proto3Message{}, - values: url.Values{ - "uint32_value.nested": {"test"}, - }, - filter: utilities.NewDoubleArray(nil), - }, - { - msg: &proto3Message{}, - values: url.Values{ - "bool_value.nested": {"test"}, - }, - filter: utilities.NewDoubleArray(nil), - }, - { - msg: &proto3Message{}, - values: url.Values{ - "string_value.nested": {"test"}, - }, - filter: utilities.NewDoubleArray(nil), - }, - { - msg: &proto3Message{}, - values: url.Values{ - "repeated_value.nested": {"test"}, - }, - filter: utilities.NewDoubleArray(nil), - }, - { - msg: &proto3Message{}, - values: url.Values{ - "enum_value.nested": {"test"}, - }, - filter: utilities.NewDoubleArray(nil), - }, - { - msg: &proto3Message{}, - values: url.Values{ - "enum_value.nested": {"test"}, - }, - filter: utilities.NewDoubleArray(nil), - }, - { - msg: &proto3Message{}, - values: url.Values{ - "repeated_enum.nested": {"test"}, - }, - filter: utilities.NewDoubleArray(nil), - }, - } { - spec.msg.Reset() - err := runtime.PopulateQueryParameters(spec.msg, spec.values, spec.filter) - if err == nil { - t.Errorf("runtime.PopulateQueryParameters(msg, %v, %v) did not fail; want error", spec.values, spec.filter) - } - } -} - -type proto3Message struct { - Nested *proto2Message `protobuf:"bytes,1,opt,name=nested,json=nested" json:"nested,omitempty"` - NestedNonNull proto2Message `protobuf:"bytes,15,opt,name=nested_non_null,json=nestedNonNull" json:"nested_non_null,omitempty"` - FloatValue float32 `protobuf:"fixed32,2,opt,name=float_value,json=floatValue" json:"float_value,omitempty"` - DoubleValue float64 `protobuf:"fixed64,3,opt,name=double_value,json=doubleValue" json:"double_value,omitempty"` - Int64Value int64 `protobuf:"varint,4,opt,name=int64_value,json=int64Value" json:"int64_value,omitempty"` - Int32Value int32 `protobuf:"varint,5,opt,name=int32_value,json=int32Value" json:"int32_value,omitempty"` - Uint64Value uint64 `protobuf:"varint,6,opt,name=uint64_value,json=uint64Value" json:"uint64_value,omitempty"` - Uint32Value uint32 `protobuf:"varint,7,opt,name=uint32_value,json=uint32Value" json:"uint32_value,omitempty"` - BoolValue bool `protobuf:"varint,8,opt,name=bool_value,json=boolValue" json:"bool_value,omitempty"` - StringValue string `protobuf:"bytes,9,opt,name=string_value,json=stringValue" json:"string_value,omitempty"` - RepeatedValue []string `protobuf:"bytes,10,rep,name=repeated_value,json=repeatedValue" json:"repeated_value,omitempty"` - EnumValue EnumValue `protobuf:"varint,11,opt,name=enum_value,json=enumValue,enum=runtime_test_api.EnumValue" json:"enum_value,omitempty"` - RepeatedEnum []EnumValue `protobuf:"varint,12,rep,packed,name=repeated_enum,json=repeatedEnum,enum=runtime_test_api.EnumValue" json:"repeated_enum,omitempty"` - TimestampValue *timestamp.Timestamp `protobuf:"bytes,16,opt,name=timestamp_value,json=timestampValue" json:"timestamp_value,omitempty"` - OneofValue proto3Message_OneofValue `protobuf_oneof:"oneof_value"` - WrapperDoubleValue *wrappers.DoubleValue `protobuf:"bytes,17,opt,name=wrapper_double_value,json=wrapperDoubleValue" json:"wrapper_double_value,omitempty"` - WrapperFloatValue *wrappers.FloatValue `protobuf:"bytes,18,opt,name=wrapper_float_value,json=wrapperFloatValue" json:"wrapper_float_value,omitempty"` - WrapperInt64Value *wrappers.Int64Value `protobuf:"bytes,19,opt,name=wrapper_int64_value,json=wrapperInt64Value" json:"wrapper_int64_value,omitempty"` - WrapperInt32Value *wrappers.Int32Value `protobuf:"bytes,20,opt,name=wrapper_int32_value,json=wrapperInt32Value" json:"wrapper_int32_value,omitempty"` - WrapperUInt64Value *wrappers.UInt64Value `protobuf:"bytes,21,opt,name=wrapper_u_int64_value,json=wrapperUInt64Value" json:"wrapper_u_int64_value,omitempty"` - WrapperUInt32Value *wrappers.UInt32Value `protobuf:"bytes,22,opt,name=wrapper_u_int32_value,json=wrapperUInt32Value" json:"wrapper_u_int32_value,omitempty"` - WrapperBoolValue *wrappers.BoolValue `protobuf:"bytes,23,opt,name=wrapper_bool_value,json=wrapperBoolValue" json:"wrapper_bool_value,omitempty"` - WrapperStringValue *wrappers.StringValue `protobuf:"bytes,24,opt,name=wrapper_string_value,json=wrapperStringValue" json:"wrapper_string_value,omitempty"` -} - -func (m *proto3Message) Reset() { *m = proto3Message{} } -func (m *proto3Message) String() string { return proto.CompactTextString(m) } -func (*proto3Message) ProtoMessage() {} - -func (m *proto3Message) GetNested() *proto2Message { - if m != nil { - return m.Nested - } - return nil -} - -type proto3Message_OneofValue interface { - proto3Message_OneofValue() -} - -type proto3Message_OneofBoolValue struct { - OneofBoolValue bool `protobuf:"varint,13,opt,name=oneof_bool_value,json=oneofBoolValue,oneof"` -} -type proto3Message_OneofStringValue struct { - OneofStringValue string `protobuf:"bytes,14,opt,name=oneof_string_value,json=oneofStringValue,oneof"` -} - -func (*proto3Message_OneofBoolValue) proto3Message_OneofValue() {} -func (*proto3Message_OneofStringValue) proto3Message_OneofValue() {} - -func (m *proto3Message) GetOneofValue() proto3Message_OneofValue { - if m != nil { - return m.OneofValue - } - return nil -} - -func (m *proto3Message) GetOneofBoolValue() bool { - if x, ok := m.GetOneofValue().(*proto3Message_OneofBoolValue); ok { - return x.OneofBoolValue - } - return false -} - -func (m *proto3Message) GetOneofStringValue() string { - if x, ok := m.GetOneofValue().(*proto3Message_OneofStringValue); ok { - return x.OneofStringValue - } - return "" -} - -// XXX_OneofFuncs is for the internal use of the proto package. -func (*proto3Message) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { - return _proto3Message_OneofMarshaler, _proto3Message_OneofUnmarshaler, _proto3Message_OneofSizer, []interface{}{ - (*proto3Message_OneofBoolValue)(nil), - (*proto3Message_OneofStringValue)(nil), - } -} - -func _proto3Message_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { - m := msg.(*proto3Message) - // oneof_value - switch x := m.OneofValue.(type) { - case *proto3Message_OneofBoolValue: - t := uint64(0) - if x.OneofBoolValue { - t = 1 - } - b.EncodeVarint(13<<3 | proto.WireVarint) - b.EncodeVarint(t) - case *proto3Message_OneofStringValue: - b.EncodeVarint(14<<3 | proto.WireBytes) - b.EncodeStringBytes(x.OneofStringValue) - case nil: - default: - return fmt.Errorf("proto3Message.OneofValue has unexpected type %T", x) - } - return nil -} - -func _proto3Message_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { - m := msg.(*proto3Message) - switch tag { - case 14: // oneof_value.oneof_bool_value - if wire != proto.WireVarint { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeVarint() - m.OneofValue = &proto3Message_OneofBoolValue{x != 0} - return true, err - case 15: // oneof_value.oneof_string_value - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeStringBytes() - m.OneofValue = &proto3Message_OneofStringValue{x} - return true, err - default: - return false, nil - } -} - -func _proto3Message_OneofSizer(msg proto.Message) (n int) { - m := msg.(*proto3Message) - // oneof_value - switch x := m.OneofValue.(type) { - case *proto3Message_OneofBoolValue: - n += proto.SizeVarint(14<<3 | proto.WireVarint) - n += 1 - case *proto3Message_OneofStringValue: - n += proto.SizeVarint(15<<3 | proto.WireBytes) - n += proto.SizeVarint(uint64(len(x.OneofStringValue))) - n += len(x.OneofStringValue) - case nil: - default: - panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) - } - return n -} - -type proto2Message struct { - Nested *proto3Message `protobuf:"bytes,1,opt,name=nested,json=nested" json:"nested,omitempty"` - FloatValue *float32 `protobuf:"fixed32,2,opt,name=float_value,json=floatValue" json:"float_value,omitempty"` - DoubleValue *float64 `protobuf:"fixed64,3,opt,name=double_value,json=doubleValue" json:"double_value,omitempty"` - Int64Value *int64 `protobuf:"varint,4,opt,name=int64_value,json=int64Value" json:"int64_value,omitempty"` - Int32Value *int32 `protobuf:"varint,5,opt,name=int32_value,json=int32Value" json:"int32_value,omitempty"` - Uint64Value *uint64 `protobuf:"varint,6,opt,name=uint64_value,json=uint64Value" json:"uint64_value,omitempty"` - Uint32Value *uint32 `protobuf:"varint,7,opt,name=uint32_value,json=uint32Value" json:"uint32_value,omitempty"` - BoolValue *bool `protobuf:"varint,8,opt,name=bool_value,json=boolValue" json:"bool_value,omitempty"` - StringValue *string `protobuf:"bytes,9,opt,name=string_value,json=stringValue" json:"string_value,omitempty"` - RepeatedValue []string `protobuf:"bytes,10,rep,name=repeated_value,json=repeatedValue" json:"repeated_value,omitempty"` - EnumValue EnumValue `protobuf:"varint,11,opt,name=enum_value,json=enumValue,enum=runtime_test_api.EnumValue" json:"enum_value,omitempty"` - RepeatedEnum []EnumValue `protobuf:"varint,12,rep,packed,name=repeated_enum,json=repeatedEnum,enum=runtime_test_api.EnumValue" json:"repeated_enum,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *proto2Message) Reset() { *m = proto2Message{} } -func (m *proto2Message) String() string { return proto.CompactTextString(m) } -func (*proto2Message) ProtoMessage() {} - -func (m *proto2Message) GetNested() *proto3Message { - if m != nil { - return m.Nested - } - return nil -} - -func (m *proto2Message) GetFloatValue() float32 { - if m != nil && m.FloatValue != nil { - return *m.FloatValue - } - return 0 -} - -func (m *proto2Message) GetDoubleValue() float64 { - if m != nil && m.DoubleValue != nil { - return *m.DoubleValue - } - return 0 -} - -func (m *proto2Message) GetInt64Value() int64 { - if m != nil && m.Int64Value != nil { - return *m.Int64Value - } - return 0 -} - -func (m *proto2Message) GetInt32Value() int32 { - if m != nil && m.Int32Value != nil { - return *m.Int32Value - } - return 0 -} - -func (m *proto2Message) GetUint64Value() uint64 { - if m != nil && m.Uint64Value != nil { - return *m.Uint64Value - } - return 0 -} - -func (m *proto2Message) GetUint32Value() uint32 { - if m != nil && m.Uint32Value != nil { - return *m.Uint32Value - } - return 0 -} - -func (m *proto2Message) GetBoolValue() bool { - if m != nil && m.BoolValue != nil { - return *m.BoolValue - } - return false -} - -func (m *proto2Message) GetStringValue() string { - if m != nil && m.StringValue != nil { - return *m.StringValue - } - return "" -} - -func (m *proto2Message) GetRepeatedValue() []string { - if m != nil { - return m.RepeatedValue - } - return nil -} - -type EnumValue int32 - -const ( - EnumValue_X EnumValue = 0 - EnumValue_Y EnumValue = 1 - EnumValue_Z EnumValue = 2 -) - -var EnumValue_name = map[int32]string{ - 0: "EnumValue_X", - 1: "EnumValue_Y", - 2: "EnumValue_Z", -} -var EnumValue_value = map[string]int32{ - "EnumValue_X": 0, - "EnumValue_Y": 1, - "EnumValue_Z": 2, -} - -func init() { - proto.RegisterEnum("runtime_test_api.EnumValue", EnumValue_name, EnumValue_value) -} diff --git a/vendor/github.com/cockroachdb/cockroach/APL.txt b/vendor/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis/LICENSE similarity index 99% rename from vendor/github.com/cockroachdb/cockroach/APL.txt rename to vendor/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis/LICENSE index 829ea336d..261eeb9e9 100644 --- a/vendor/github.com/cockroachdb/cockroach/APL.txt +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis/LICENSE @@ -1,4 +1,4 @@ -Apache License + Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ @@ -178,7 +178,7 @@ Apache License APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" + boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a @@ -186,7 +186,7 @@ Apache License same "printed page" as the copyright notice for easier identification within third-party archives. - Copyright {} + Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -199,4 +199,3 @@ Apache License WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. - diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/utilities/trie_test.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/utilities/trie_test.go deleted file mode 100644 index 0178aa827..000000000 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/utilities/trie_test.go +++ /dev/null @@ -1,372 +0,0 @@ -package utilities_test - -import ( - "reflect" - "testing" - - "github.com/grpc-ecosystem/grpc-gateway/utilities" -) - -func TestMaxCommonPrefix(t *testing.T) { - for _, spec := range []struct { - da utilities.DoubleArray - tokens []string - want bool - }{ - { - da: utilities.DoubleArray{}, - tokens: nil, - want: false, - }, - { - da: utilities.DoubleArray{}, - tokens: []string{"foo"}, - want: false, - }, - { - da: utilities.DoubleArray{ - Encoding: map[string]int{ - "foo": 0, - }, - Base: []int{1, 1, 0}, - Check: []int{0, 1, 2}, - }, - tokens: nil, - want: false, - }, - { - da: utilities.DoubleArray{ - Encoding: map[string]int{ - "foo": 0, - }, - Base: []int{1, 1, 0}, - Check: []int{0, 1, 2}, - }, - tokens: []string{"foo"}, - want: true, - }, - { - da: utilities.DoubleArray{ - Encoding: map[string]int{ - "foo": 0, - }, - Base: []int{1, 1, 0}, - Check: []int{0, 1, 2}, - }, - tokens: []string{"bar"}, - want: false, - }, - { - // foo|bar - da: utilities.DoubleArray{ - Encoding: map[string]int{ - "foo": 0, - "bar": 1, - }, - Base: []int{1, 1, 2, 0, 0}, - Check: []int{0, 1, 1, 2, 3}, - // 0: ^ - // 1: ^foo - // 2: ^bar - // 3: ^foo$ - // 4: ^bar$ - }, - tokens: []string{"foo"}, - want: true, - }, - { - // foo|bar - da: utilities.DoubleArray{ - Encoding: map[string]int{ - "foo": 0, - "bar": 1, - }, - Base: []int{1, 1, 2, 0, 0}, - Check: []int{0, 1, 1, 2, 3}, - // 0: ^ - // 1: ^foo - // 2: ^bar - // 3: ^foo$ - // 4: ^bar$ - }, - tokens: []string{"bar"}, - want: true, - }, - { - // foo|bar - da: utilities.DoubleArray{ - Encoding: map[string]int{ - "foo": 0, - "bar": 1, - }, - Base: []int{1, 1, 2, 0, 0}, - Check: []int{0, 1, 1, 2, 3}, - // 0: ^ - // 1: ^foo - // 2: ^bar - // 3: ^foo$ - // 4: ^bar$ - }, - tokens: []string{"something-else"}, - want: false, - }, - { - // foo|bar - da: utilities.DoubleArray{ - Encoding: map[string]int{ - "foo": 0, - "bar": 1, - }, - Base: []int{1, 1, 2, 0, 0}, - Check: []int{0, 1, 1, 2, 3}, - // 0: ^ - // 1: ^foo - // 2: ^bar - // 3: ^foo$ - // 4: ^bar$ - }, - tokens: []string{"foo", "bar"}, - want: true, - }, - { - // foo|foo\.bar|bar - da: utilities.DoubleArray{ - Encoding: map[string]int{ - "foo": 0, - "bar": 1, - }, - Base: []int{1, 3, 1, 0, 4, 0, 0}, - Check: []int{0, 1, 1, 3, 2, 2, 5}, - // 0: ^ - // 1: ^foo - // 2: ^bar - // 3: ^bar$ - // 4: ^foo.bar - // 5: ^foo$ - // 6: ^foo.bar$ - }, - tokens: []string{"foo"}, - want: true, - }, - { - // foo|foo\.bar|bar - da: utilities.DoubleArray{ - Encoding: map[string]int{ - "foo": 0, - "bar": 1, - }, - Base: []int{1, 3, 1, 0, 4, 0, 0}, - Check: []int{0, 1, 1, 3, 2, 2, 5}, - // 0: ^ - // 1: ^foo - // 2: ^bar - // 3: ^bar$ - // 4: ^foo.bar - // 5: ^foo$ - // 6: ^foo.bar$ - }, - tokens: []string{"foo", "bar"}, - want: true, - }, - { - // foo|foo\.bar|bar - da: utilities.DoubleArray{ - Encoding: map[string]int{ - "foo": 0, - "bar": 1, - }, - Base: []int{1, 3, 1, 0, 4, 0, 0}, - Check: []int{0, 1, 1, 3, 2, 2, 5}, - // 0: ^ - // 1: ^foo - // 2: ^bar - // 3: ^bar$ - // 4: ^foo.bar - // 5: ^foo$ - // 6: ^foo.bar$ - }, - tokens: []string{"bar"}, - want: true, - }, - { - // foo|foo\.bar|bar - da: utilities.DoubleArray{ - Encoding: map[string]int{ - "foo": 0, - "bar": 1, - }, - Base: []int{1, 3, 1, 0, 4, 0, 0}, - Check: []int{0, 1, 1, 3, 2, 2, 5}, - // 0: ^ - // 1: ^foo - // 2: ^bar - // 3: ^bar$ - // 4: ^foo.bar - // 5: ^foo$ - // 6: ^foo.bar$ - }, - tokens: []string{"something-else"}, - want: false, - }, - { - // foo|foo\.bar|bar - da: utilities.DoubleArray{ - Encoding: map[string]int{ - "foo": 0, - "bar": 1, - }, - Base: []int{1, 3, 1, 0, 4, 0, 0}, - Check: []int{0, 1, 1, 3, 2, 2, 5}, - // 0: ^ - // 1: ^foo - // 2: ^bar - // 3: ^bar$ - // 4: ^foo.bar - // 5: ^foo$ - // 6: ^foo.bar$ - }, - tokens: []string{"foo", "bar", "baz"}, - want: true, - }, - } { - got := spec.da.HasCommonPrefix(spec.tokens) - if got != spec.want { - t.Errorf("%#v.HasCommonPrefix(%v) = %v; want %v", spec.da, spec.tokens, got, spec.want) - } - } -} - -func TestAdd(t *testing.T) { - for _, spec := range []struct { - tokens [][]string - want utilities.DoubleArray - }{ - { - want: utilities.DoubleArray{ - Encoding: make(map[string]int), - }, - }, - { - tokens: [][]string{{"foo"}}, - want: utilities.DoubleArray{ - Encoding: map[string]int{"foo": 0}, - Base: []int{1, 1, 0}, - Check: []int{0, 1, 2}, - // 0: ^ - // 1: ^foo - // 2: ^foo$ - }, - }, - { - tokens: [][]string{{"foo"}, {"bar"}}, - want: utilities.DoubleArray{ - Encoding: map[string]int{ - "foo": 0, - "bar": 1, - }, - Base: []int{1, 1, 2, 0, 0}, - Check: []int{0, 1, 1, 2, 3}, - // 0: ^ - // 1: ^foo - // 2: ^bar - // 3: ^foo$ - // 4: ^bar$ - }, - }, - { - tokens: [][]string{{"foo", "bar"}, {"foo", "baz"}}, - want: utilities.DoubleArray{ - Encoding: map[string]int{ - "foo": 0, - "bar": 1, - "baz": 2, - }, - Base: []int{1, 1, 1, 2, 0, 0}, - Check: []int{0, 1, 2, 2, 3, 4}, - // 0: ^ - // 1: ^foo - // 2: ^foo.bar - // 3: ^foo.baz - // 4: ^foo.bar$ - // 5: ^foo.baz$ - }, - }, - { - tokens: [][]string{{"foo", "bar"}, {"foo", "baz"}, {"qux"}}, - want: utilities.DoubleArray{ - Encoding: map[string]int{ - "foo": 0, - "bar": 1, - "baz": 2, - "qux": 3, - }, - Base: []int{1, 1, 1, 2, 3, 0, 0, 0}, - Check: []int{0, 1, 2, 2, 1, 3, 4, 5}, - // 0: ^ - // 1: ^foo - // 2: ^foo.bar - // 3: ^foo.baz - // 4: ^qux - // 5: ^foo.bar$ - // 6: ^foo.baz$ - // 7: ^qux$ - }, - }, - { - tokens: [][]string{ - {"foo", "bar"}, - {"foo", "baz", "bar"}, - {"qux", "foo"}, - }, - want: utilities.DoubleArray{ - Encoding: map[string]int{ - "foo": 0, - "bar": 1, - "baz": 2, - "qux": 3, - }, - Base: []int{1, 1, 1, 5, 8, 0, 3, 0, 5, 0}, - Check: []int{0, 1, 2, 2, 1, 3, 4, 7, 5, 9}, - // 0: ^ - // 1: ^foo - // 2: ^foo.bar - // 3: ^foo.baz - // 4: ^qux - // 5: ^foo.bar$ - // 6: ^foo.baz.bar - // 7: ^foo.baz.bar$ - // 8: ^qux.foo - // 9: ^qux.foo$ - }, - }, - } { - da := utilities.NewDoubleArray(spec.tokens) - if got, want := da.Encoding, spec.want.Encoding; !reflect.DeepEqual(got, want) { - t.Errorf("da.Encoding = %v; want %v; tokens = %#v", got, want, spec.tokens) - } - if got, want := da.Base, spec.want.Base; !compareArray(got, want) { - t.Errorf("da.Base = %v; want %v; tokens = %#v", got, want, spec.tokens) - } - if got, want := da.Check, spec.want.Check; !compareArray(got, want) { - t.Errorf("da.Check = %v; want %v; tokens = %#v", got, want, spec.tokens) - } - } -} - -func compareArray(got, want []int) bool { - var i int - for i = 0; i < len(got) && i < len(want); i++ { - if got[i] != want[i] { - return false - } - } - if i < len(want) { - return false - } - for ; i < len(got); i++ { - if got[i] != 0 { - return false - } - } - return true -} diff --git a/vendor/github.com/hashicorp/consul/.gitignore b/vendor/github.com/hashicorp/consul/.gitignore deleted file mode 100644 index b19858143..000000000 --- a/vendor/github.com/hashicorp/consul/.gitignore +++ /dev/null @@ -1,22 +0,0 @@ -*.attr -*.exe -*.log -*.old -*.swp -*.test -.DS_Store -.vagrant/ -/pkg -Thumbs.db -bin/ -exit-code -ui/.bundle -ui/.sass-cache -ui/dist/ -ui/static/application.min.js -ui/static/base.css -ui/vendor -website/.bundle -website/build/ -website/npm-debug.log -website/vendor diff --git a/vendor/github.com/hashicorp/consul/.travis.yml b/vendor/github.com/hashicorp/consul/.travis.yml deleted file mode 100644 index 45823931a..000000000 --- a/vendor/github.com/hashicorp/consul/.travis.yml +++ /dev/null @@ -1,13 +0,0 @@ -language: go - -go: - - 1.x - -branches: - only: - - master - -script: - - make test - -sudo: false diff --git a/vendor/github.com/hashicorp/consul/CHANGELOG.md b/vendor/github.com/hashicorp/consul/CHANGELOG.md deleted file mode 100644 index 306132f01..000000000 --- a/vendor/github.com/hashicorp/consul/CHANGELOG.md +++ /dev/null @@ -1,1069 +0,0 @@ - -## 0.9.3 (September 8, 2017) - -FEATURES: -* **LAN Network Segments:** (Consul Enterprise) Added a new [Network Segments](https://www.consul.io/docs/guides/segments.html) capability which allows users to configure Consul to support segmented LAN topologies with multiple, distinct gossip pools. [GH-3431] -* **WAN Join for Cloud Providers:** Added WAN support for retry join for cloud providers via go-discover, including Amazon AWS, Microsoft Azure, Google Cloud, and SoftLayer. This uses the same "provider" syntax supported for `-retry-join` via the `-retry-join-wan` configuration. [GH-3406] -* **RPC Rate Limiter:** Consul agents in client mode have a new [`limits`](https://www.consul.io/docs/agent/options.html#limits) configuration that enables a rate limit on RPC calls the agent makes to Consul servers. [GH-3140] - -IMPROVEMENTS: - -* agent: Switched to using a read lock for the agent's RPC dispatcher, which prevents RPC calls from getting serialized. [GH-3376] -* agent: When joining a cluster, Consul now skips the unique node ID constraint for Consul members running Consul older than 0.8.5. This makes it easier to upgrade to newer versions of Consul in an existing cluster with non-unique node IDs. [GH-3070] -* build: Upgraded Go version to 1.9. [GH-3428] -* server: Consul servers can re-establish quorum after all of them change their IP addresses upon a restart. [GH-1580] - -BUG FIXES: - -* agent: Fixed an issue with consul watches not triggering when ACLs are enabled. [GH-3392] -* agent: Updated memberlist library for a deadlock fix. [GH-3396] -* agent: Fixed a panic when retrieving NS or SOA records on Consul clients (non-servers). This also changed the Consul server list to come from the catalog and not the agent's local state when serving these requests, so the results are consistent across a cluster. [GH-3407] -* cli: Updated the CLI library to pull in a fix that prevents all subcommands from being shown when showing the agent's usage list; now just top-level commands are shown. [GH-3448] -* server: Fixed an issue with Consul snapshots not saving on Windows because of errors with the `fsync` syscall. [GH-3409] - -## 0.9.2 (August 9, 2017) - -BUG FIXES: - -* agent: Fixed an issue where the old `-retry-join-{ec2,azure,gce}` command line flags were not being honored. [GH-3384] -* server: Reverted the change that made unauthorized KV queries return 403 instead of 404 because it had a minor bug that affected the operation of Vault, and in addition to fixing the bug, we identified an additional case that needed to be covered. This restores the <= 0.9.0 behavior until we can get a complete fix. [GH-2637] - -## 0.9.1 (August 9, 2017) - -FEATURES: - -* **Secure ACL Token Introduction:** It's now possible to manage Consul's ACL tokens without having to place any tokens inside configuration files. This supports introduction of tokens as well as rotating. This is enabled with two new APIs: - * A new [`/v1/agent/token`](https://www.consul.io/api/agent.html#update-acl-tokens) API allows an agent's ACL tokens to be introduced without placing them into config files, and to update them without restarting the agent. See the [ACL Guide](https://www.consul.io/docs/guides/acl.html#create-an-agent-token) for an example. This was extended to ACL replication as well, along with a new [`enable_acl_replication`](https://www.consul.io/docs/agent/options.html#enable_acl_replication) config option. [GH-3324,GH-3357] - * A new [`/v1/acl/bootstrap`](https://www.consul.io/api/acl.html#bootstrap-acls) allows a cluster's first management token to be created without using the `acl_master_token` configuration. See the [ACL Guide](https://www.consul.io/docs/guides/acl.html#bootstrapping-acls) for an example. [GH-3349] -* **Metrics Viewing Endpoint:** A new [`/v1/agent/metrics`](https://www.consul.io/api/agent.html#view-metrics) API displays the current values of internally tracked metrics. [GH-3369] - -IMPROVEMENTS: - -* agent: Retry Join for Amazon AWS, Microsoft Azure, Google Cloud, and (new) SoftLayer is now handled through the https://github.com/hashicorp/go-discover library. With this all `-retry-join-{ec2,azure,gce}-*` parameters have been deprecated in favor of a unified configuration. See [`-retry-join`](https://www.consul.io/docs/agent/options.html#_retry_join) for details. [GH-3282,GH-3351] -* agent: Reports a more detailed error message if the LAN or WAN Serf instance fails to bind to an address. [GH-3312] -* agent: Added NS records and corrected SOA records to allow Consul's DNS interface to work properly with zone delegation. [GH-1301] -* agent: Added support for sending metrics with labels/tags to supported backends. [GH-3369] -* agent: Added a new `prefix_filter` option in the `telemetry` config to allow fine-grained allowing/blocking the sending of certain metrics by prefix. [GH-3369] -* cli: Added a `-child-exit-code` option to `consul lock` so that it propagates an error code of 2 if the child process exits with an error. [GH-947] -* docs: Added a new [Geo Failover Guide](https://www.consul.io/docs/guides/geo-failover.html) showing how to use prepared queries to implement geo failover policies for services. [GH-3328] -* docs: Added a new [Consul with Containers Guide](https://www.consul.io/docs/guides/consul-containers.html) showing critical aspects of operating a Consul cluster that's run inside containers. [GH-3347] -* server: Added a `RemoveEmptyTags` option to prepared query templates which will strip out any empty strings in the tags list before executing a query. This is useful when interpolating into tags in a way where the tag is optional, and where searching for an empty tag would yield no results from the query. [GH-2151] -* server: Implemented a much faster recursive delete algorithm for the KV store. It has been benchmarked to be up to 100X faster on recursive deletes that affect millions of keys. [GH-1278, GH-3313] - -BUG FIXES: - -* agent: Clean up temporary files during disk write errors when persisting services and checks. [GH-3207] -* agent: Fixed an issue where DNS and client bind address templates were not being parsed via the go-sockaddr library. [GH-3322] -* agent: Fixed status code on all KV store operations that fail due to an ACL issue. They now return a 403 status code, rather than a 404. [GH-2637] -* agent: Fixed quoting issues in script health check on Windows. [GH-1875] -* agent: Fixed an issue where `consul monitor` would exit on any empty log line. [GH-3253] -* server: Updated raft library to fix issue with machine crashes causing snapshot files to not get saved to disk [GH-3362] - -## 0.9.0 (July 20, 2017) - -BREAKING CHANGES: - -* agent: Added a new [`enable_script_checks`](https://www.consul.io/docs/agent/options.html#_enable_script_checks) configuration option that defaults to `false`, meaning that in order to allow an agent to run health checks that execute scripts, this will need to be configured and set to `true`. This provides a safer out-of-the-box configuration for Consul where operators must opt-in to allow script-based health checks. [GH-3087] -* api: Reworked `context` support in the API client to more closely match the Go standard library, and added context support to write requests in addition to read requests. [GH-3273, GH-2992] -* ui: Since the UI is now bundled with the application we no longer provide a separate UI package for downloading. [GH-3292] - -FEATURES: - -* agent: Added a new [`block_endpoints`](https://www.consul.io/docs/agent/options.html#block_endpoints) configuration option that allows blocking HTTP API endpoints by prefix. This allows operators to completely disallow access to specific endpoints on a given agent. [GH-3252] -* cli: Added a new [`consul catalog`](https://www.consul.io/docs/commands/catalog.html) command for reading datacenters, nodes, and services from the catalog. [GH-3204] -* server: (Consul Enterprise) Added a new [`consul operator area update`](https://www.consul.io/docs/commands/operator/area.html#update) command and corresponding HTTP endpoint to allow for transitioning the TLS setting of network areas at runtime. [GH-3075] -* server: (Consul Enterprise) Added a new `UpgradeVersionTag` field to the Autopilot config to allow for using the migration feature to roll out configuration or cluster changes, without having to upgrade Consul itself. - -IMPROVEMENTS: - -* agent: (Consul Enterprise) Snapshot agent rotation uses S3's pagination API, enabling retaining more than a 100 snapshots. -* agent: Removed registration of the `consul` service from the agent since it's already handled by the leader. This means that Consul servers no longer need to have an `acl_agent_token` with write access to the `consul` service if ACLs are enabled. [GH-3248] -* agent: Changed /v1/acl/clone response to 403 (from 404) when trying to clone an ACL that doesn't exist. [GH-1113] -* agent: Changed the `consul exec` ACL resolution logic to use the `acl_agent_token` if it's available. This lets operators configure an `acl_agent_token` with the required `write` privilieges to the `_rexec` prefix of the KV store without giving this to the `acl_token`, which would expose those privileges to users as well. [GH-3160] -* agent: Updated memberlist to get latest LAN gossip tuning based on the [Lifeguard paper published by Hashicorp Research](https://www.hashicorp.com/blog/making-gossip-more-robust-with-lifeguard/). [GH-3287] -* api: Added the ability to pass in a `context` as part of the `QueryOptions` during a request. This provides a way to cancel outstanding blocking queries. [GH-3195] -* api: Changed signature for "done" channels on `agent.Monitor()` and `session.RenewPeriodic` methods to make them more compatible with `context`. [GH-3271] -* docs: Added a complete end-to-end example of ACL bootstrapping in the [ACL Guide](https://www.consul.io/docs/guides/acl.html#bootstrapping-acls). [GH-3248] -* vendor: Updated golang.org/x/sys/unix to support IBM s390 platforms. [GH-3240] -* agent: rewrote Docker health checks without using the Docker client and its dependencies. [GH-3270] - -BUG FIXES: - -* agent: Fixed an issue where watch plans would take up to 10 minutes to close their connections and give up their file descriptors after reloading Consul. [GH-3018] -* agent: (Consul Enterprise) Fixed an issue with the snapshot agent where it could get stuck trying to obtain the leader lock after an extended server outage. -* agent: Fixed HTTP health checks to allow them to set the `Host` header correctly on outgoing requests. [GH-3203] -* agent: Serf snapshots can now auto recover from disk write errors without needing a restart. [GH-1744] -* agent: Fixed log redacting code to properly remove tokens from log lines with ACL tokens in the URL itself: `/v1/acl/clone/:uuid`, `/v1/acl/destroy/:uuid`, `/v1/acl/info/:uuid`. [GH-3276] -* agent: Fixed an issue in the Docker client where Docker checks would get EOF errors trying to connect to a volume-mounted Docker socket. [GH-3254] -* agent: Fixed a crash when using Azure auto discovery. [GH-3193] -* agent: Added `node` read privileges to the `acl_agent_master_token` by default so it can see all nodes, which enables it to be used with operations like `consul members`. [GH-3113] -* agent: Fixed an issue where enabling [`-disable-keyring-file`](https://www.consul.io/docs/agent/options.html#_disable_keyring_file) would cause gossip encryption to be disabled. [GH-3243] -* agent: Fixed a race condition where checks that are not associated with any existing services were allowed to persist. [GH-3297] -* agent: Stop docker checks on service deregistration and on shutdown. [GH-3265, GH-3295] -* server: Updated the Raft library to pull in a fix where servers that are very far behind in replication can get stuck in a loop trying to install snapshots. [GH-3201] -* server: Fixed a rare but serious deadlock where the Consul leader routine could get stuck with the Raft internal leader routine while waiting for the initial barrier after a leader election. [GH-3230] -* server: Added automatic cleanup of failed Raft snapshots. [GH-3258] -* server: (Consul Enterprise) Fixed an issue where networks areas would not be able to be added when the server restarts if the Raft log contained a specific sequence of adds and deletes for network areas with the same peer datacenter. -* ui: Provided a path to reset the ACL token when the current token is invalid. Previously, the UI would get stuck on the error page and it wasn't possible to get back to the settings. [GH-2370] -* ui: Removed an extra fetch of the nodes resource when loading the UI. [GH-3245] -* ui: Changed default ACL token type to "client" when creating ACLs. [GH-3246] -* ui: Display a 404 error instead of a 200 when trying to load a nonexistent node. [GH-3251] - -## 0.8.5 (June 27, 2017) - -BREAKING CHANGES: - -* agent: Parse values given to `?passing` for health endpoints. Previously Consul only checked for the existence of the querystring, not the value. That means using `?passing=false` would actually still include passing values. Consul now parses the value given to passing as a boolean. If no value is provided, the old behavior remains. This may be a breaking change for some users, but the old experience was incorrect and caused enough confusion to warrant changing it. [GH-2212, GH-3136] -* agent: The default value of [`-disable-host-node-id`](https://www.consul.io/docs/agent/options.html#_disable_host_node_id) has been changed from false to true. This means you need to opt-in to host-based node IDs and by default Consul will generate a random node ID. A high number of users struggled to deploy newer versions of Consul with host-based IDs because of various edge cases of how the host IDs work in Docker, on specially-provisioned machines, etc. so changing this from opt-out to opt-in will ease operations for many Consul users. [GH-3171] - -IMPROVEMENTS: - -* agent: Added a `-disable-keyring-file` option to prevent writing keyring data to disk. [GH-3145] -* agent: Added automatic notify to systemd on Linux after LAN join is complete, which makes it easier to order services that depend on Consul being available. [GH-2121] -* agent: The `http_api_response_headers` config has been moved into a new `http_config` struct, so the old form is still supported but is deprecated. [GH-3142] -* dns: Added support for EDNS(0) size adjustments if set in the request frame. This allows DNS responses via UDP which are larger than the standard 512 bytes max if the requesting client can support it. [GH-1980, GH-3131] -* server: Added a startup warning for servers when expecting to bootstrap with an even number of nodes. [GH-1282] -* agent: (Consul Enterprise) Added support for non rotating, statically named snapshots for S3 snapshots using the snapshot agent. - -BUG FIXES: - -* agent: Fixed a regression where configuring -1 for the port was no longer disabling the DNS server. [GH-3135] -* agent: Fix `consul leave` shutdown race. When shutting down an agent via the `consul leave` command on the command line the output would be `EOF` instead of `Graceful leave completed` [GH-2880] -* agent: Show a better error message than 'EOF' when attempting to join with the wrong gossip key. [GH-1013] -* agent: Fixed an issue where the `Method` and `Header` features of HTTP health checks were not being applied. [GH-3178] -* agent: Fixed an issue where internally-configured watches were not working because of an incorrect protocol error, and unified internal watch handling during reloads of the Consul agent. [GH-3177] -* server: Fixed an issue where the leader could return stale data duing queries as it is starting up. [GH-2644] - -## 0.8.4 (June 9, 2017) - -FEATURES: - -* agent: Added a method for [transitioning to gossip encryption on an existing cluster](https://www.consul.io/docs/agent/encryption.html#configuring-gossip-encryption-on-an-existing-cluster). [GH-3079] -* agent: Added a method for [transitioning to TLS on an existing cluster](https://www.consul.io/docs/agent/encryption.html#configuring-tls-on-an-existing-cluster). [GH-1705] -* agent: Added support for [RetryJoin on Azure](https://www.consul.io/docs/agent/options.html#retry_join_azure). [GH-2978] -* agent: (Consul Enterprise) Added [AWS server side encryption support](http://docs.aws.amazon.com/AmazonS3/latest/dev/UsingServerSideEncryption.html) for S3 snapshots using the snapshot agent. - -IMPROVEMENTS: - -* agent: Added a check which prevents advertising or setting a service to a zero address (`0.0.0.0`, `[::]`, `::`). [GH-2961] -* agent: Allow binding to any public IPv6 address with `::` [GH-2285] -* agent: Removed SCADA-related code for Atlas and deprecated all Atlas-related configuration options. [GH-3032] -* agent: Added support for custom check id and name when registering checks along with a service. [GH-3047] -* agent: Updated [go-sockaddr](https://github.com/hashicorp/go-sockaddr) library to add support for new helper functions in bind address templates (`GetPrivateIPs`, `GetPublicIPs`), new math functions, and to pick up fixes for issues with detecting addresses on multi-homed hosts. [GH-3068] -* agent: Watches now reset their index back to zero after an error, or if the index goes backwards, which allows watches to recover after a server restart with fresh state. [GH-2621] -* agent: HTTP health checks now support custom method and headers. [GH-1184, GH-2474, GH-2657, GH-3106] -* agent: Increased the graceful leave timeout from 5 to 15 seconds. [GH-3121] -* agent: Added additional logging when the agent handles signals and when it exits. [GH-3124] -* build: Added support for linux/arm64 binaries. [GH-3042] -* build: Consul now builds with Go 1.8.3. [GH-3074] -* ui: Added a sticky scroll to the KV side panel so the KV edit box always stays in place. [GH-2812] - -BUG FIXES: - -* agent: Added defensive code to prevent agents from infecting the network coordinates with `NaN` or `Inf` values, and added code to clean up in environments where this has happened. [GH-3023] -* api: Added code to always read from the body of a request so that connections will always be returned to the pool. [GH-2850] -* build: Added a vendor fix to allow compilation on Illumos. [GH-3024] -* cli: Fixed an issue where `consul exec` would return a 0 exit code, even when there were nodes that didn't respond. [GH-2757] - -## 0.8.3 (May 12, 2017) - -BUG FIXES: - -* agent: Fixed an issue where NAT-configured agents with a non-routable advertise address would refuse to make RPC connections to Consul servers. This was a regression related to GH-2822 in Consul 0.8.2. [GH-3028] - -## 0.8.2 (May 9, 2017) - -BREAKING CHANGES: - -* api: HttpClient now defaults to nil in the client config and will be generated if left blank. A NewHttpClient function has been added for creating an HttpClient with a custom Transport or TLS config. [GH-2922] - -IMPROVEMENTS: - -* agent: Added an error at agent startup time if both `-ui` and `-ui-dir` are configured together. [GH-2576] -* agent: Added the datacenter of a node to the catalog, health, and query API endpoints which contain a Node structure. [GH-2713] -* agent: Added the `ca_path`, `tls_cipher_suites`, and `tls_prefer_server_cipher_suites` options to give more flexibility around configuring TLS. [GH-2963] -* agent: Reduced the timeouts for the `-dev` server mode so that the development server starts up almost instantly. [GH-2984] -* agent: Added `verify_incoming_rpc` and `verify_incoming_https` options for more granular control over incoming TLS enforcement. [GH-2974] -* agent: Use bind address as source for outgoing connections. [GH-2822] -* api: Added the ACL replication status endpoint to the Go API client library. [GH-2947] -* cli: Added Raft protocol version to output of `operator raft list-peers` command.[GH-2929] -* ui: Added optional JSON validation when editing KV entries in the web UI. [GH-2712] -* ui: Updated ACL guide links and made guides open in a new tab. [GH-3010] - -BUG FIXES: - -* server: Fixed a panic when the tombstone garbage collector was stopped. [GH-2087] -* server: Fixed a panic in Autopilot that could occur when a node is elected but cannot complete leader establishment and steps back down. [GH-2980] -* server: Added a new peers.json format that allows outage recovery when using Raft protocol version 3 and higher. Previously, you'd have to set the Raft protocol version back to 2 in order to manually recover a cluster. See https://www.consul.io/docs/guides/outage.html#manual-recovery-using-peers-json for more details. [GH-3003] -* ui: Add and update favicons [GH-2945] - -## 0.8.1 (April 17, 2017) - -IMPROVEMENTS: - -* agent: Node IDs derived from host information are now hashed to prevent things like common server hardware from generating IDs with a common prefix across nodes. [GH-2884] -* agent: Added new `-disable-host-node-id` CLI flag and `disable_host_node_id` config option to the Consul agent to prevent it from using information from the host when generating a node ID. This will result in a random node ID, which is useful when running multiple Consul agents on the same host for testing purposes. Having this built-in eases configuring a random node ID when running in containers. [GH-2877] -* agent: Removed useless "==> Caught signal: broken pipe" logging since that often results from problems sending telemetry or broken incoming client connections; operators don't need to be alerted to these. [GH-2768] -* cli: Added TLS options for setting the client/CA certificates to use when communicating with Consul. These can be provided through environment variables or command line flags. [GH-2914] -* build: Consul is now built with Go 1.8.1. [GH-2888] -* ui: Updates Consul assets to new branding. [GH-2898] - -BUG FIXES: - -* api: Added missing Raft index fields to AgentService and Node structures. [GH-2882] -* server: Fixed an issue where flood joins would not work with IPv6 addresses. [GH-2878] -* server: Fixed an issue where electing a 0.8.x leader during an upgrade would cause a panic in older servers. [GH-2889] -* server: Fixed an issue where tracking of leadership changes could become incorrect when changes occurred very rapidly. This could manifest as a panic in Autopilot, but could have caused other issues with multiple leader management routines running simultaneously. [GH-2896] -* server: Fixed a panic when checking ACLs on a session that doesn't exist. [GH-2624] - -## 0.8.0 (April 5, 2017) - -BREAKING CHANGES: - -* **Command-Line Interface RPC Deprecation:** The RPC client interface has been removed. All CLI commands that used RPC and the `-rpc-addr` flag to communicate with Consul have been converted to use the HTTP API and the appropriate flags for it, and the `rpc` field has been removed from the port and address binding configs. You will need to remove these fields from your config files and update any scripts that passed a custom `-rpc-addr` to the following commands: `force-leave`, `info`, `join`, `keyring`, `leave`, `members`, `monitor`, `reload` - -* **Version 8 ACLs Are Now Opt-Out:** The [`acl_enforce_version_8`](https://www.consul.io/docs/agent/options.html#acl_enforce_version_8) configuration now defaults to `true` to enable [full version 8 ACL support](https://www.consul.io/docs/internals/acl.html#version_8_acls) by default. If you are upgrading an existing cluster with ACLs enabled, you will need to set this to `false` during the upgrade on **both Consul agents and Consul servers**. Version 8 ACLs were also changed so that [`acl_datacenter`](https://www.consul.io/docs/agent/options.html#acl_datacenter) must be set on agents in order to enable the agent-side enforcement of ACLs. This makes for a smoother experience in clusters where ACLs aren't enabled at all, but where the agents would have to wait to contact a Consul server before learning that. [GH-2844] - -* **Remote Exec Is Now Opt-In:** The default for [`disable_remote_exec`](https://www.consul.io/docs/agent/options.html#disable_remote_exec) was changed to "true", so now operators need to opt-in to having agents support running commands remotely via [`consul exec`](/docs/commands/exec.html). [GH-2854] - -* **Raft Protocol Compatibility:** When upgrading to Consul 0.8.0 from a version lower than 0.7.0, users will need to -set the [`-raft-protocol`](https://www.consul.io/docs/agent/options.html#_raft_protocol) option to 1 in order to maintain backwards compatibility with the old servers during the upgrade. See [Upgrading Specific Versions](https://www.consul.io/docs/upgrade-specific.html) guide for more details. - -FEATURES: - -* **Autopilot:** A set of features has been added to allow for automatic operator-friendly management of Consul servers. For more information about Autopilot, see the [Autopilot Guide](https://www.consul.io/docs/guides/autopilot.html). - - **Dead Server Cleanup:** Dead servers will periodically be cleaned up and removed from the Raft peer set, to prevent them from interfering with the quorum size and leader elections. - - **Server Health Checking:** An internal health check has been added to track the stability of servers. The thresholds of this health check are tunable as part of the [Autopilot configuration](https://www.consul.io/docs/agent/options.html#autopilot) and the status can be viewed through the [`/v1/operator/autopilot/health`](https://www.consul.io/docs/agent/http/operator.html#autopilot-health) HTTP endpoint. - - **New Server Stabilization:** When a new server is added to the cluster, there will be a waiting period where it must be healthy and stable for a certain amount of time before being promoted to a full, voting member. This threshold can be configured using the new [`server_stabilization_time`](https://www.consul.io/docs/agent/options.html#server_stabilization_time) setting. - - **Advanced Redundancy:** (Consul Enterprise) A new [`-non-voting-server`](https://www.consul.io/docs/agent/options.html#_non_voting_server) option flag has been added for Consul servers to configure a server that does not participate in the Raft quorum. This can be used to add read scalability to a cluster in cases where a high volume of reads to servers are needed, but non-voting servers can be lost without causing an outage. There's also a new [`redundancy_zone_tag`](https://www.consul.io/docs/agent/options.html#redundancy_zone_tag) configuration that allows Autopilot to manage separating servers into zones for redundancy. Only one server in each zone can be a voting member at one time. This helps when Consul servers are managed with automatic replacement with a system like a resource scheduler or auto-scaling group. Extra non-voting servers in each zone will be available as hot standbys (that help with read-scaling) that can be quickly promoted into service when the voting server in a zone fails. - - **Upgrade Orchestration:** (Consul Enterprise) Autopilot will automatically orchestrate an upgrade strategy for Consul servers where it will initially add newer versions of Consul servers as non-voters, wait for a full set of newer versioned servers to be added, and then gradually swap into service as voters and swap out older versioned servers to non-voters. This allows operators to safely bring up new servers, wait for the upgrade to be complete, and then terminate the old servers. -* **Network Areas:** (Consul Enterprise) A new capability has been added which allows operators to define network areas that join together two Consul datacenters. Unlike Consul's WAN feature, network areas use just the server RPC port for communication, and pairwise relationships can be made between arbitrary datacenters, so not all servers need to be fully connected. This allows for complex topologies among Consul datacenters like hub/spoke and more general trees. See the [Network Areas Guide](https://www.consul.io/docs/guides/areas.html) for more details. -* **WAN Soft Fail:** Request routing between servers in the WAN is now more robust by treating Serf failures as advisory but not final. This means that if there are issues between some subset of the servers in the WAN, Consul will still be able to route RPC requests as long as RPCs are actually still working. Prior to WAN Soft Fail, any datacenters having connectivity problems on the WAN would mean that all DCs might potentially stop sending RPCs to those datacenters. [GH-2801] -* **WAN Join Flooding:** A new routine was added that looks for Consul servers in the LAN and makes sure that they are joined into the WAN as well. This catches up up newly-added servers onto the WAN as soon as they join the LAN, keeping them in sync automatically. [GH-2801] -* **Validate command:** To provide consistency across our products, the `configtest` command has been deprecated and replaced with the `validate` command (to match Nomad and Terraform). The `configtest` command will be removed in Consul 0.9. [GH-2732] - -IMPROVEMENTS: - -* agent: Fixed a missing case where gossip would stop flowing to dead nodes for a short while. [GH-2722] -* agent: Changed agent to seed Go's random number generator. [GH-2722] -* agent: Serf snapshots no longer have the executable bit set on the file. [GH-2722] -* agent: Consul is now built with Go 1.8. [GH-2752] -* agent: Updated aws-sdk-go version (used for EC2 auto join) for Go 1.8 compatibility. [GH-2755] -* agent: User-supplied node IDs are now normalized to lower-case. [GH-2798] -* agent: Added checks to enforce uniqueness of agent node IDs at cluster join time and when registering with the catalog. [GH-2832] -* cli: Standardized handling of CLI options for connecting to the Consul agent. This makes sure that the same set of flags and environment variables works in all CLI commands (see https://www.consul.io/docs/commands/index.html#environment-variables). [GH-2717] -* cli: Updated go-cleanhttp library for better HTTP connection handling between CLI commands and the Consul agent (tunes reuse settings). [GH-2735] -* cli: The `operator raft` subcommand has had its two modes split into the `list-peers` and `remove-peer` subcommands. The old flags for these will continue to work for backwards compatibility, but will be removed in Consul 0.9. -* cli: Added an `-id` flag to the `operator raft remove-peer` command to allow removing a peer by ID. [GH-2847] -* dns: Allows the `.service` tag to be optional in RFC 2782 lookups. [GH-2690] -* server: Changed the internal `EnsureRegistration` RPC endpoint to prevent registering checks that aren't associated with the top-level node being registered. [GH-2846] - -BUG FIXES: - -* agent: Fixed an issue with `consul watch` not working when http was listening on a unix socket. [GH-2385] -* agent: Fixed an issue where checks and services could not sync deregister operations back to the catalog when version 8 ACL support is enabled. [GH-2818] -* agent: Fixed an issue where agents could use the ACL token registered with a service when registering checks for the same service that were registered with a different ACL token. [GH-2829] -* cli: Fixed `consul kv` commands not reading the `CONSUL_HTTP_TOKEN` environment variable. [GH-2566] -* cli: Fixed an issue where prefixing an address with a protocol (such as 'http://' or 'https://') in `-http-addr` or `CONSUL_HTTP_ADDR` would give an error. -* cli: Fixed an issue where error messages would get printed to stdout instead of stderr. [GH-2548] -* server: Fixed an issue with version 8 ACLs where servers couldn't deregister nodes from the catalog during reconciliation. [GH-2792] This fix was generalized and applied to registering nodes as well. [GH-2826] -* server: Fixed an issue where servers could temporarily roll back changes to a node's metadata or tagged addresses when making updates to the node's health checks. [GH-2826] -* server: Fixed an issue where the service name `consul` was not subject to service ACL policies with version 8 ACLs enabled. [GH-2816] - -## 0.7.5 (February 15, 2017) - -BUG FIXES: - -* server: Fixed a rare but serious issue where Consul servers could panic when performing a large delete operation followed by a specific sequence of other updates to related parts of the state store (affects KV, sessions, prepared queries, and the catalog). [GH-2724] - -## 0.7.4 (February 6, 2017) - -IMPROVEMENTS: - -* agent: Integrated gopsutil library to use built in host UUID as node ID, if available, instead of a randomly generated UUID. This makes it easier for other applications on the same host to generate the same node ID without coordinating with Consul. [GH-2697] -* agent: Added a configuration option, `tls_min_version`, for setting the minimum allowed TLS version used for the HTTP API and RPC. [GH-2699] -* agent: Added a `relay-factor` option to keyring operations to allow nodes to relay their response through N randomly-chosen other nodes in the cluster. [GH-2704] -* build: Consul is now built with Go 1.7.5. [GH-2682] -* dns: Add ability to lookup Consul agents by either their Node ID or Node Name through the node interface (e.g. DNS `(node-id|node-name).node.consul`). [GH-2702] - -BUG FIXES: - -* dns: Fixed an issue where SRV lookups for services on a node registered with non-IP addresses were missing the CNAME record in the additional section of the response. [GH-2695] - -## 0.7.3 (January 26, 2017) - -FEATURES: - -* **KV Import/Export CLI:** `consul kv export` and `consul kv import` can be used to move parts of the KV tree between disconnected consul clusters, using JSON as the intermediate representation. [GH-2633] -* **Node Metadata:** Support for assigning user-defined metadata key/value pairs to nodes has been added. This can be viewed when looking up node info, and can be used to filter the results of various catalog and health endpoints. For more information, see the [Catalog](https://www.consul.io/docs/agent/http/catalog.html), [Health](https://www.consul.io/docs/agent/http/health.html), and [Prepared Query](https://www.consul.io/docs/agent/http/query.html) endpoint documentation, as well as the [Node Meta](https://www.consul.io/docs/agent/options.html#_node_meta) section of the agent configuration. [GH-2654] -* **Node Identifiers:** Consul agents can now be configured with a unique identifier, or they will generate one at startup that will persist across agent restarts. This identifier is designed to represent a node across all time, even if the name or address of the node changes. Identifiers are currently only exposed in node-related endpoints, but they will be used in future versions of Consul to help manage Consul servers and the Raft quorum in a more robust manner, as the quorum is currently tracked via addresses, which can change. [GH-2661] -* **Improved Blocking Queries:** Consul's [blocking query](https://www.consul.io/api/index.html#blocking-queries) implementation was improved to provide a much more fine-grained mechanism for detecting changes. For example, in previous versions of Consul blocking to wait on a change to a specific service would result in a wake up if any service changed. Now, wake ups are scoped to the specific service being watched, if possible. This support has been added to all endpoints that support blocking queries, nothing new is required to take advantage of this feature. [GH-2671] -* **GCE auto-discovery:** New `-retry-join-gce` configuration options added to allow bootstrapping by automatically discovering Google Cloud instances with a given tag at startup. [GH-2570] - -IMPROVEMENTS: - -* build: Consul is now built with Go 1.7.4. [GH-2676] -* cli: `consul kv get` now has a `-base64` flag to base 64 encode the value. [GH-2631] -* cli: `consul kv put` now has a `-base64` flag for setting values which are base 64 encoded. [GH-2632] -* ui: Added a notice that JS is required when viewing the web UI with JS disabled. [GH-2636] - -BUG FIXES: - -* agent: Redacted the AWS access key and secret key ID from the /v1/agent/self output so they are not disclosed. [GH-2677] -* agent: Fixed a rare startup panic due to a Raft/Serf race condition. [GH-1899] -* cli: Fixed a panic when an empty quoted argument was given to `consul kv put`. [GH-2635] -* tests: Fixed a race condition with check mock's map usage. [GH-2578] - -## 0.7.2 (December 19, 2016) - -FEATURES: - -* **Keyring API:** A new `/v1/operator/keyring` HTTP endpoint was added that allows for performing operations such as list, install, use, and remove on the encryption keys in the gossip keyring. See the [Keyring Endpoint](https://www.consul.io/docs/agent/http/operator.html#keyring) for more details. [GH-2509] -* **Monitor API:** A new `/v1/agent/monitor` HTTP endpoint was added to allow for viewing streaming log output from the agent, similar to the `consul monitor` command. See the [Monitor Endpoint](https://www.consul.io/docs/agent/http/agent.html#agent_monitor) for more details. [GH-2511] -* **Reload API:** A new `/v1/agent/reload` HTTP endpoint was added for triggering a reload of the agent's configuration. See the [Reload Endpoint](https://www.consul.io/docs/agent/http/agent.html#agent_reload) for more details. [GH-2516] -* **Leave API:** A new `/v1/agent/leave` HTTP endpoint was added for causing an agent to gracefully shutdown and leave the cluster (previously, only `force-leave` was present in the HTTP API). See the [Leave Endpoint](https://www.consul.io/docs/agent/http/agent.html#agent_leave) for more details. [GH-2516] -* **Bind Address Templates (beta):** Consul agents now allow [go-sockaddr/template](https://godoc.org/github.com/hashicorp/go-sockaddr/template) syntax to be used for any bind address configuration (`advertise_addr`, `bind_addr`, `client_addr`, and others). This allows for easy creation of immutable images for Consul that can fetch their own address based on an interface name, network CIDR, address family from an actual RFC number, and many other possible schemes. This feature is in beta and we may tweak the template syntax before final release, but we encourage the community to try this and provide feedback. [GH-2563] -* **Complete ACL Coverage (beta):** Consul 0.8 will feature complete ACL coverage for all of Consul. To ease the transition to the new policies, a beta version of complete ACL support was added to help with testing and migration to the new features. Please see the [ACLs Internals Guide](https://www.consul.io/docs/internals/acl.html#version_8_acls) for more details. [GH-2594, GH-2592, GH-2590] - -IMPROVEMENTS: - -* agent: Defaults to `?pretty` JSON for HTTP API requests when in `-dev` mode. [GH-2518] -* agent: Updated Circonus metrics library and added new Circonus configration options for Consul for customizing check display name and tags. [GH-2555] -* agent: Added a checksum to UDP gossip messages to guard against packet corruption. [GH-2574] -* agent: Check whether a snapshot needs to be taken more often (every 5 seconds instead of 2 minutes) to keep the raft file smaller and to avoid doing huge truncations when writing lots of entries very quickly. [GH-2591] -* agent: Allow gossiping to suspected/recently dead nodes. [GH-2593] -* agent: Changed the gossip suspicion timeout to grow smoothly as the number of nodes grows. [GH-2593] -* agent: Added a deprecation notice for Atlas features to the CLI and docs. [GH-2597] -* agent: Give a better error message when the given data-dir is not a directory. [GH-2529] - -BUG FIXES: - -* agent: Fixed a panic when SIGPIPE signal was received. [GH-2404] -* api: Added missing Raft index fields to `CatalogService` structure. [GH-2366] -* api: Added missing notes field to `AgentServiceCheck` structure. [GH-2336] -* api: Changed type of `AgentServiceCheck.TLSSkipVerify` from `string` to `bool`. [GH-2530] -* api: Added new `HealthChecks.AggregatedStatus()` method that makes it easy get an overall health status from a list of checks. [GH-2544] -* api: Changed type of `KVTxnOp.Verb` from `string` to `KVOp`. [GH-2531] -* cli: Fixed an issue with the `consul kv put` command where a negative value would be interpreted as an argument to read from standard input. [GH-2526] -* ui: Fixed an issue where extra commas would be shown around service tags. [GH-2340] -* ui: Customized Bootstrap config to avoid missing font file references. [GH-2485] -* ui: Removed "Deregister" button as removing nodes from the catalog isn't a common operation and leads to lots of user confusion. [GH-2541] - -## 0.7.1 (November 10, 2016) - -BREAKING CHANGES: - -* Child process reaping support has been removed, along with the `reap` configuration option. Reaping is also done via [dumb-init](https://github.com/Yelp/dumb-init) in the [Consul Docker image](https://github.com/hashicorp/docker-consul), so removing it from Consul itself simplifies the code and eases future maintainence for Consul. If you are running Consul as PID 1 in a container you will need to arrange for a wrapper process to reap child processes. [GH-1988] -* The default for `max_stale` has been increased to a near-indefinite threshold (10 years) to allow DNS queries to continue to be served in the event of a long outage with no leader. A new telemetry counter has also been added at `consul.dns.stale_queries` to track when agents serve DNS queries that are over a certain staleness (>5 seconds). [GH-2481] -* The api package's `PreparedQuery.Delete()` method now takes `WriteOptions` instead of `QueryOptions`. [GH-2417] - -FEATURES: - -* **Key/Value Store Command Line Interface:** New `consul kv` commands were added for easy access to all basic key/value store operations. [GH-2360] -* **Snapshot/Restore:** A new /v1/snapshot HTTP endpoint and corresponding set of `consul snapshot` commands were added for easy point-in-time snapshots for disaster recovery. Snapshots include all state managed by Consul's Raft [consensus protocol](/docs/internals/consensus.html), including Key/Value Entries, Service Catalog, Prepared Queries, Sessions, and ACLs. Snapshots can be restored on the fly into a completely fresh cluster. [GH-2396] -* **AWS auto-discovery:** New `-retry-join-ec2` configuration options added to allow bootstrapping by automatically discovering AWS instances with a given tag key/value at startup. [GH-2459] - -IMPROVEMENTS: - -* api: All session options can now be set when using `api.Lock()`. [GH-2372] -* agent: Added the ability to bind Serf WAN and LAN to different interfaces than the general bind address. [GH-2007] -* agent: Added a new `tls_skip_verify` configuration option for HTTP checks. [GH-1984] -* build: Consul is now built with Go 1.7.3. [GH-2281] - -BUG FIXES: - -* agent: Fixed a Go race issue with log buffering at startup. [GH-2262] -* agent: Fixed a panic during anti-entropy sync for services and checks. [GH-2125] -* agent: Fixed an issue on Windows where "wsarecv" errors were logged when CLI commands accessed the RPC interface. [GH-2356] -* agent: Syslog initialization will now retry on errors for up to 60 seconds to avoid a race condition at system startup. [GH-1610] -* agent: Fixed a panic when both -dev and -bootstrap-expect flags were provided. [GH-2464] -* agent: Added a retry with backoff when a session fails to invalidate after expiring. [GH-2435] -* agent: Fixed an issue where Consul would fail to start because of leftover malformed check/service state files. [GH-1221] -* agent: Fixed agent crashes on macOS Sierra by upgrading Go. [GH-2407, GH-2281] -* agent: Log a warning instead of success when attempting to deregister a nonexistent service. [GH-2492] -* api: Trim leading slashes from keys/prefixes when querying KV endpoints to avoid a bug with redirects in Go 1.7 (golang/go#4800). [GH-2403] -* dns: Fixed external services that pointed to consul addresses (CNAME records) not resolving to A-records. [GH-1228] -* dns: Fixed an issue with SRV lookups where the service address was different from the node's. [GH-832] -* dns: Fixed an issue where truncated records from a recursor query were improperly reported as errors. [GH-2384] -* server: Fixed the port numbers in the sample JSON inside peers.info. [GH-2391] -* server: Squashes ACL datacenter name to lower case and checks for proper formatting at startup. [GH-2059, GH-1778, GH-2478] -* ui: Fixed an XSS issue with the display of sessions and ACLs in the web UI. [GH-2456] - -## 0.7.0 (September 14, 2016) - -BREAKING CHANGES: - -* The default behavior of `leave_on_terminate` and `skip_leave_on_interrupt` are now dependent on whether or not the agent is acting as a server or client. When Consul is started as a server the defaults for these are `false` and `true`, respectively, which means that you have to explicitly configure a server to leave the cluster. When Consul is started as a client the defaults are the opposite, which means by default, clients will leave the cluster if shutdown or interrupted. [GH-1909] [GH-2320] -* The `allow_stale` configuration for DNS queries to the Consul agent now defaults to `true`, allowing for better utilization of available Consul servers and higher throughput at the expense of weaker consistency. This is almost always an acceptable tradeoff for DNS queries, but this can be reconfigured to use the old default behavior if desired. [GH-2315] -* Output from HTTP checks is truncated to 4k when stored on the servers, similar to script check output. [GH-1952] -* Consul's Go API client will now send ACL tokens using HTTP headers instead of query parameters, requiring Consul 0.6.0 or later. [GH-2233] -* Removed support for protocol version 1, so Consul 0.7 is no longer compatible with Consul versions prior to 0.3. [GH-2259] -* The Raft peers information in `consul info` has changed format and includes information about the suffrage of a server, which will be used in future versions of Consul. [GH-2222] -* New [`translate_wan_addrs`](https://www.consul.io/docs/agent/options.html#translate_wan_addrs) behavior from [GH-2118] translates addresses in HTTP responses and could break clients that are expecting local addresses. A new `X-Consul-Translate-Addresses` header was added to allow clients to detect if translation is enabled for HTTP responses, and a "lan" tag was added to `TaggedAddresses` for clients that need the local address regardless of translation. [GH-2280] -* The behavior of the `peers.json` file is different in this version of Consul. This file won't normally be present and is used only during outage recovery. Be sure to read the updated [Outage Recovery Guide](https://www.consul.io/docs/guides/outage.html) for details. [GH-2222] -* Consul's default Raft timing is now set to work more reliably on lower-performance servers, which allows small clusters to use lower cost compute at the expense of reduced performance for failed leader detection and leader elections. You will need to configure Consul to get the same performance as before. See the new [Server Performance](https://www.consul.io/docs/guides/performance.html) guide for more details. [GH-2303] - -FEATURES: - -* **Transactional Key/Value API:** A new `/v1/txn` API was added that allows for atomic updates to and fetches from multiple entries in the key/value store inside of an atomic transaction. This includes conditional updates based on obtaining locks, and all other key/value store operations. See the [Key/Value Store Endpoint](https://www.consul.io/docs/agent/http/kv.html#txn) for more details. [GH-2028] -* **Native ACL Replication:** Added a built-in full replication capability for ACLs. Non-ACL datacenters can now replicate the complete ACL set locally to their state store and fall back to that if there's an outage. Additionally, this provides a good way to make a backup ACL datacenter, or to migrate the ACL datacenter to a different one. See the [ACL Internals Guide](https://www.consul.io/docs/internals/acl.html#replication) for more details. [GH-2237] -* **Server Connection Rebalancing:** Consul agents will now periodically reconnect to available Consul servers in order to redistribute their RPC query load. Consul clients will, by default, attempt to establish a new connection every 120s to 180s unless the size of the cluster is sufficiently large. The rate at which agents begin to query new servers is proportional to the size of the Consul cluster (servers should never receive more than 64 new connections per second per Consul server as a result of rebalancing). Clusters in stable environments who use `allow_stale` should see a more even distribution of query load across all of their Consul servers. [GH-1743] -* **Raft Updates and Consul Operator Interface:** This version of Consul upgrades to "stage one" of the v2 HashiCorp Raft library. This version offers improved handling of cluster membership changes and recovery after a loss of quorum. This version also provides a foundation for new features that will appear in future Consul versions once the remainder of the v2 library is complete. [GH-2222]
Consul's default Raft timing is now set to work more reliably on lower-performance servers, which allows small clusters to use lower cost compute at the expense of reduced performance for failed leader detection and leader elections. You will need to configure Consul to get the same performance as before. See the new [Server Performance](https://www.consul.io/docs/guides/performance.html) guide for more details. [GH-2303]
Servers will now abort bootstrapping if they detect an existing cluster with configured Raft peers. This will help prevent safe but spurious leader elections when introducing new nodes with `bootstrap_expect` enabled into an existing cluster. [GH-2319]
Added new `consul operator` command, HTTP endpoint, and associated ACL to allow Consul operators to view and update the Raft configuration. This allows a stale server to be removed from the Raft peers without requiring downtime and peers.json recovery file use. See the new [Consul Operator Command](https://www.consul.io/docs/commands/operator.html) and the [Consul Operator Endpoint](https://www.consul.io/docs/agent/http/operator.html) for details, as well as the updated [Outage Recovery Guide](https://www.consul.io/docs/guides/outage.html). [GH-2312] -* **Serf Lifeguard Updates:** Implemented a new set of feedback controls for the gossip layer that help prevent degraded nodes that can't meet the soft real-time requirements from erroneously causing `serfHealth` flapping in other, healthy nodes. This feature tunes itself automatically and requires no configuration. [GH-2101] -* **Prepared Query Near Parameter:** Prepared queries support baking in a new `Near` sorting parameter. This allows results to be sorted by network round trip time based on a static node, or based on the round trip time from the Consul agent where the request originated. This can be used to find a co-located service instance is one is available, with a transparent fallback to the next best alternate instance otherwise. [GH-2137] -* **Automatic Service Deregistration:** Added a new `deregister_critical_service_after` timeout field for health checks which will cause the service associated with that check to get deregistered if the check is critical for longer than the timeout. This is useful for cleanup of health checks registered natively by applications, or in other situations where services may not always be cleanly shutdown. [GH-679] -* **WAN Address Translation Everywhere:** Extended the [`translate_wan_addrs`](https://www.consul.io/docs/agent/options.html#translate_wan_addrs) config option to also translate node addresses in HTTP responses, making it easy to use this feature from non-DNS clients. [GH-2118] -* **RPC Retries:** Consul will now retry RPC calls that result in "no leader" errors for up to 5 seconds. This allows agents to ride out leader elections with a delayed response vs. an error. [GH-2175] -* **Circonus Telemetry Support:** Added support for Circonus as a telemetry destination. [GH-2193] - -IMPROVEMENTS: - -* agent: Reap time for failed nodes is now configurable via new `reconnect_timeout` and `reconnect_timeout_wan` config options ([use with caution](https://www.consul.io/docs/agent/options.html#reconnect_timeout)). [GH-1935] -* agent: Joins based on a DNS lookup will use TCP and attempt to join with the full list of returned addresses. [GH-2101] -* agent: Consul will now refuse to start with a helpful message if the same UNIX socket is used for more than one listening endpoint. [GH-1910] -* agent: Removed an obsolete warning message when Consul starts on Windows. [GH-1920] -* agent: Defaults bind address to 127.0.0.1 when running in `-dev` mode. [GH-1878] -* agent: Added version information to the log when Consul starts up. [GH-1404] -* agent: Added timing metrics for HTTP requests in the form of `consul.http..`. [GH-2256] -* build: Updated all vendored dependencies. [GH-2258] -* build: Consul releases are now built with Go 1.6.3. [GH-2260] -* checks: Script checks now support an optional `timeout` parameter. [GH-1762] -* checks: HTTP health checks limit saved output to 4K to avoid performance issues. [GH-1952] -* cli: Added a `-stale` mode for watchers to allow them to pull data from any Consul server, not just the leader. [GH-2045] [GH-917] -* dns: Consul agents can now limit the number of UDP answers returned via the DNS interface. The default number of UDP answers is `3`, however by adjusting the `dns_config.udp_answer_limit` configuration parameter, it is now possible to limit the results down to `1`. This tunable provides environments where RFC3484 section 6, rule 9 is enforced with an important workaround in order to preserve the desired behavior of randomized DNS results. Most modern environments will not need to adjust this setting as this RFC was made obsolete by RFC 6724\. See the [agent options](https://www.consul.io/docs/agent/options.html#udp_answer_limit) documentation for additional details for when this should be used. [GH-1712] -* dns: Consul now compresses all DNS responses by default. This prevents issues when recursing records that were originally compressed, where Consul would sometimes generate an invalid, uncompressed response that was too large. [GH-2266] -* dns: Added a new `recursor_timeout` configuration option to set the timeout for Consul's internal DNS client that's used for recursing queries to upstream DNS servers. [GH-2321] -* dns: Added a new `-dns-port` command line option so this can be set without a config file. [GH-2263] -* ui: Added a new network tomography visualization to the UI. [GH-2046] - -BUG FIXES: - -* agent: Fixed an issue where a health check's output never updates if the check status doesn't change after the Consul agent starts. [GH-1934] -* agent: External services can now be registered with ACL tokens. [GH-1738] -* agent: Fixed an issue where large events affecting many nodes could cause infinite intent rebroadcasts, leading to many log messages about intent queue overflows. [GH-1062] -* agent: Gossip encryption keys are now validated before being made persistent in the keyring, avoiding delayed feedback at runtime. [GH-1299] -* dns: Fixed an issue where DNS requests for SRV records could be incorrectly trimmed, resulting in an ADDITIONAL section that was out of sync with the ANSWER. [GH-1931] -* dns: Fixed two issues where DNS requests for SRV records on a prepared query that failed over would report the wrong domain and fail to translate addresses. [GH-2218] [GH-2220] -* server: Fixed a deadlock related to sorting the list of available datacenters by round trip time. [GH-2130] -* server: Fixed an issue with the state store's immutable radix tree that would prevent it from using cached modified objects during transactions, leading to extra copies and increased memory / GC pressure. [GH-2106] -* server: Upgraded Bolt DB to v1.2.1 to fix an issue on Windows where Consul would sometimes fail to start due to open user-mapped sections. [GH-2203] - -OTHER CHANGES: - -* build: Switched from Godep to govendor. [GH-2252] - -## 0.6.4 (March 16, 2016) - -BACKWARDS INCOMPATIBILITIES: - -* Added a new `query` ACL type to manage prepared query names, and stopped capturing - ACL tokens by default when prepared queries are created. This won't affect existing - queries and how they are executed, but this will affect how they are managed. Now - management of prepared queries can be delegated within an organization. If you use - prepared queries, you'll need to read the - [Consul 0.6.4 upgrade instructions](https://www.consul.io/docs/upgrade-specific.html) - before upgrading to this version of Consul. [GH-1748] -* Consul's Go API client now pools connections by default, and requires you to manually - opt-out of this behavior. Previously, idle connections were supported and their - lifetime was managed by a finalizer, but this wasn't reliable in certain situations. - If you reuse an API client object during the lifetime of your application, then there's - nothing to do. If you have short-lived API client objects, you may need to configure them - using the new `api.DefaultNonPooledConfig()` method to avoid leaking idle connections. [GH-1825] -* Consul's Go API client's `agent.UpdateTTL()` function was updated in a way that will - only work with Consul 0.6.4 and later. The `agent.PassTTL()`, `agent.WarnTTL()`, and - `agent.FailTTL()` functions were not affected and will continue work with older - versions of Consul. [GH-1794] - -FEATURES: - -* Added new template prepared queries which allow you to define a prefix (possibly even - an empty prefix) to apply prepared query features like datacenter failover to multiple - services with a single query definition. This makes it easy to apply a common policy to - multiple services without having to manage many prepared queries. See - [Prepared Query Templates](https://www.consul.io/docs/agent/http/query.html#templates) - for more details. [GH-1764] -* Added a new ability to translate address lookups when doing queries of nodes in - remote datacenters via DNS using a new `translate_wan_addrs` configuration - option. This allows the node to be reached within its own datacenter using its - local address, and reached from other datacenters using its WAN address, which is - useful in hybrid setups with mixed networks. [GH-1698] - -IMPROVEMENTS: - -* Added a new `disable_hostname` configuration option to control whether Consul's - runtime telemetry gets prepended with the host name. All of the telemetry - configuration has also been moved to a `telemetry` nested structure, but the old - format is currently still supported. [GH-1284] -* Consul's Go dependencies are now vendored using Godep. [GH-1714] -* Added support for `EnableTagOverride` for the catalog in the Go API client. [GH-1726] -* Consul now ships built from Go 1.6. [GH-1735] -* Added a new `/v1/agent/check/update/` API for updating TTL checks which - makes it easier to send large check output as part of a PUT body and not a query - parameter. [GH-1785]. -* Added a default set of `Accept` headers for HTTP checks. [GH-1819] -* Added support for RHEL7/Systemd in Terraform example. [GH-1629] - -BUG FIXES: - -* Updated the internal web UI (`-ui` option) to latest released build, fixing - an ACL-related issue and the broken settings icon. [GH-1619] -* Fixed an issue where blocking KV reads could miss updates and return stale data - when another key whose name is a prefix of the watched key was updated. [GH-1632] -* Fixed the redirect from `/` to `/ui` when the internal web UI (`-ui` option) is - enabled. [GH-1713] -* Updated memberlist to pull in a fix for leaking goroutines when performing TCP - fallback pings. This affected users with frequent UDP connectivity problems. [GH-1802] -* Added a fix to trim UDP DNS responses so they don't exceed 512 bytes. [GH-1813] -* Updated go-dockerclient to fix Docker health checks with Docker 1.10. [GH-1706] -* Removed fixed height display of nodes and services in UI, leading to broken displays - when a node has a lot of services. [GH-2055] - -## 0.6.3 (January 15, 2016) - -BUG FIXES: - -* Fixed an issue when running Consul as PID 1 in a Docker container where - it could consume CPU and show spurious failures for health checks, watch - handlers, and `consul exec` commands [GH-1592] - -## 0.6.2 (January 13, 2016) - -SECURITY: - -* Build against Go 1.5.3 to mitigate a security vulnerability introduced - in Go 1.5. For more information, please see https://groups.google.com/forum/#!topic/golang-dev/MEATuOi_ei4 - -This is a security-only release; other than the version number and building -against Go 1.5.3, there are no changes from 0.6.1. - -## 0.6.1 (January 6, 2016) - -BACKWARDS INCOMPATIBILITIES: - -* The new `-monitor-retry` option to `consul lock` defaults to 3. This - will cause the lock monitor to retry up to 3 times, waiting 1s between - each attempt if it gets a 500 error from the Consul servers. For the - vast majority of use cases this is desirable to prevent the lock from - being given up during a brief period of Consul unavailability. If you - want to get the previous default behavior you will need to set the - `-monitor-retry=0` option. - -IMPROVEMENTS: - -* Consul is now built with Go 1.5.2 -* Added source IP address and port information to RPC-related log error - messages and HTTP access logs [GH-1513] [GH-1448] -* API clients configured for insecure SSL now use an HTTP transport that's - set up the same way as the Go default transport [GH-1526] -* Added new per-host telemetry on DNS requests [GH-1537] -* Added support for reaping child processes which is useful when running - Consul as PID 1 in Docker containers [GH-1539] -* Added new `-ui` command line and `ui` config option that enables a built-in - Consul web UI, making deployment much simpler [GH-1543] -* Added new `-dev` command line option that creates a completely in-memory - standalone Consul server for development -* Added a Solaris build, now that dependencies have been updated to support - it [GH-1568] -* Added new `-try` option to `consul lock` to allow it to timeout with an error - if it doesn't acquire the lock [GH-1567] -* Added a new `-monitor-retry` option to `consul lock` to help ride out brief - periods of Consul unavailabily without causing the lock to be given up [GH-1567] - -BUG FIXES: - -* Fixed broken settings icon in web UI [GH-1469] -* Fixed a web UI bug where the supplied token wasn't being passed into - the internal endpoint, breaking some pages when multiple datacenters - were present [GH-1071] - -## 0.6.0 (December 3, 2015) - -BACKWARDS INCOMPATIBILITIES: - -* A KV lock acquisition operation will now allow the lock holder to - update the key's contents without giving up the lock by doing another - PUT with `?acquire=` and providing the same session that - is holding the lock. Previously, this operation would fail. - -FEATURES: - -* Service ACLs now apply to service discovery [GH-1024] -* Added event ACLs to guard firing user events [GH-1046] -* Added keyring ACLs for gossip encryption keyring operations [GH-1090] -* Added a new TCP check type that does a connect as a check [GH-1130] -* Added new "tag override" feature that lets catalog updates to a - service's tags flow down to agents [GH-1187] -* Ported in-memory database from LMDB to an immutable radix tree to improve - read throughput, reduce garbage collection pressure, and make Consul 100% - pure Go [GH-1291] -* Added support for sending telemetry to DogStatsD [GH-1293] -* Added new network tomography subsystem that estimates the network - round trip times between nodes and exposes that in raw APIs, as well - as in existing APIs (find the service node nearest node X); also - includes a new `consul rtt` command to query interactively [GH-1331] -* Consul now builds under Go 1.5.1 by default [GH-1345] -* Added built-in support for running health checks inside Docker containers - [GH-1343] -* Added prepared queries which support service health queries with rich - features such as filters for multiple tags and failover to remote datacenters - based on network coordinates; these are available via HTTP as well as the - DNS interface [GH-1389] - -BUG FIXES: - -* Fixed expired certificates in unit tests [GH-979] -* Allow services with `/` characters in the UI [GH-988] -* Added SOA/NXDOMAIN records to negative DNS responses per RFC2308 [GH-995] - [GH-1142] [GH-1195] [GH-1217] -* Token hiding in HTTP logs bug fixed [GH-1020] -* RFC6598 addresses are accepted as private IPs [GH-1050] -* Fixed reverse DNS lookups to recursor [GH-1137] -* Removes the trailing `/` added by the `consul lock` command [GH-1145] -* Fixed bad lock handler execution during shutdown [GH-1080] [GH-1158] [GH-1214] -* Added missing support for AAAA queries for nodes [GH-1222] -* Tokens passed from the CLI or API work for maint mode [GH-1230] -* Fixed service deregister/reregister flaps that could happen during - `consul reload` [GH-1235] -* Fixed the Go API client to properly distinguish between expired sessions - and sessions that don't exist [GH-1041] -* Fixed the KV section of the UI to work on Safari [GH-1321] -* Cleaned up JavaScript for built-in UI with bug fixes [GH-1338] - -IMPROVEMENTS: - -* Added sorting of `consul members` command output [GH-969] -* Updated AWS templates for RHEL6, CentOS6 [GH-992] [GH-1002] -* Advertised gossip/rpc addresses can now be configured [GH-1004] -* Failed lock acquisition handling now responds based on type of failure - [GH-1006] -* Agents now remember check state across restarts [GH-1009] -* Always run ACL tests by default in API tests [GH-1030] -* Consul now refuses to start if there are multiple private IPs [GH-1099] -* Improved efficiency of servers managing incoming connections from agents - [GH-1170] -* Added logging of the DNS client addresses in error messages [GH-1166] -* Added `-http-port` option to change the HTTP API port number [GH-1167] -* Atlas integration options are reload-able via SIGHUP [GH-1199] -* Atlas endpoint is a configurable option and CLI arg [GH-1201] -* Added `-pass-stdin` option to `consul lock` command [GH-1200] -* Enables the `/v1/internal/ui/*` endpoints, even if `-ui-dir` isn't set - [GH-1215] -* Added HTTP method to Consul's log output for better debugging [GH-1270] -* Lock holders can `?acquire=` a key again with the same session - that holds the lock to update a key's contents without releasing the - lock [GH-1291] -* Improved an O(n^2) algorithm in the agent's catalog sync code [GH-1296] -* Switched to net-rpc-msgpackrpc to reduce RPC overhead [GH-1307] -* Removed all uses of the http package's default client and transport in - Consul to avoid conflicts with other packages [GH-1310] [GH-1327] -* Added new `X-Consul-Token` HTTP header option to avoid passing tokens - in the query string [GH-1318] -* Increased session TTL max to 24 hours (use with caution, see note added - to the Session HTTP endpoint documentation) [GH-1412] -* Added support to the API client for retrying lock monitoring when Consul - is unavailable, helping prevent false indications of lost locks (eg. apps - like Vault can avoid failing over when a Consul leader election occurs) - [GH-1457] -* Added reap of receive buffer space for idle streams in the connection - pool [GH-1452] - -MISC: - -* Lots of docs fixes -* Lots of Vagrantfile cleanup -* Data migrator utility removed to eliminate cgo dependency [GH-1309] - -UPGRADE NOTES: - -* Consul will refuse to start if the data directory contains an "mdb" folder. - This folder was used in versions of Consul up to 0.5.1. Consul version 0.5.2 - included a baked-in utility to automatically upgrade the data format, but - this has been removed in Consul 0.6 to eliminate the dependency on cgo. -* New service read, event firing, and keyring ACLs may require special steps to - perform during an upgrade if ACLs are enabled and set to deny by default. -* Consul will refuse to start if there are multiple private IPs available, so - if this is the case you will need to configure Consul's advertise or bind - addresses before upgrading. - -See https://www.consul.io/docs/upgrade-specific.html for detailed upgrade -instructions. - -## 0.5.2 (May 18, 2015) - -FEATURES: - -* Include datacenter in the `members` output -* HTTP Health Check sets user agent "Consul Health Check" [GH-951] - -BUG FIXES: - -* Fixed memory leak caused by blocking query [GH-939] - -MISC: - -* Remove unused constant [GH-941] - -## 0.5.1 (May 13, 2015) - -FEATURES: - - * Ability to configure minimum session TTL. [GH-821] - * Ability to set the initial state of a health check when registering [GH-859] - * New `configtest` sub-command to verify config validity [GH-904] - * ACL enforcement is prefix based for service names [GH-905] - * ACLs support upsert for simpler restore and external generation [GH-909] - * ACL tokens can be provided per-service during registration [GH-891] - * Support for distinct LAN and WAN advertise addresses [GH-816] - * Migrating Raft log from LMDB to BoltDB [GH-857] - * `session_ttl_min` is now configurable to reduce the minimum TTL [GH-821] - * Adding `verify_server_hostname` to protect against server forging [GH-927] - -BUG FIXES: - - * Datacenter is lowercased, fixes DNS lookups [GH-761] - * Deregister all checks when service is deregistered [GH-918] - * Fixing issues with updates of persisted services [GH-910] - * Chained CNAME resolution fixes [GH-862] - * Tokens are filtered out of log messages [GH-860] - * Fixing anti-entropy issue if servers rollback Raft log [GH-850] - * Datacenter name is case insensitive for DNS lookups - * Queries for invalid datacenters do not leak sockets [GH-807] - -IMPROVEMENTS: - - * HTTP health checks more reliable, avoid KeepAlives [GH-824] - * Improved protection against a passive cluster merge - * SIGTERM is properly handled for graceful shutdown [GH-827] - * Better staggering of deferred updates to checks [GH-884] - * Configurable stats prefix [GH-902] - * Raft uses BoltDB as the backend store. [GH-857] - * API RenewPeriodic more resilient to transient errors [GH-912] - -## 0.5.0 (February 19, 2015) - -FEATURES: - - * Key rotation support for gossip layer. This allows the `encrypt` key - to be changed globally. See "keyring" command. [GH-336] - * Options to join the WAN pool on start (`start_join_wan`, `retry_join_wan`) [GH-477] - * Optional HTTPS interface [GH-478] - * Ephemeral keys via "delete" session behavior. This allows keys to be deleted when - a session is invalidated instead of having the lock released. Adds new "Behavior" - field to Session which is configurable. [GH-487] - * Reverse DNS lookups via PTR for IPv4 and IPv6 [GH-475] - * API added checks and services are persisted. This means services and - checks will survive a crash or restart. [GH-497] - * ACLs can now protect service registration. Users in blacklist mode should - allow registrations before upgrading to prevent a service disruption. [GH-506] [GH-465] - * Sessions support a heartbeat failure detector via use of TTLs. This adds a new - "TTL" field to Sessions and a `/v1/session/renew` endpoint. Heartbeats act like a - failure detector (health check), but are managed by the servers. [GH-524] [GH-172] - * Support for service specific IP addresses. This allows the service to advertise an - address that is different from the agent. [GH-229] [GH-570] - * Support KV Delete with Check-And-Set [GH-589] - * Merge `armon/consul-api` into `api` as official Go client. - * Support for distributed locks and semaphores in API client [GH-594] [GH-600] - * Support for native HTTP health checks [GH-592] - * Support for node and service maintenance modes [GH-606] - * Added new "consul maint" command to easily toggle maintenance modes [GH-625] - * Added new "consul lock" command for simple highly-available deployments. - This lets Consul manage the leader election and easily handle N+1 deployments - without the applications being Consul aware. [GH-619] - * Multiple checks can be associated with a service [GH-591] [GH-230] - -BUG FIXES: - - * Fixed X-Consul-Index calculation for KV ListKeys - * Fixed errors under extremely high read parallelism - * Fixed issue causing event watches to not fire reliably [GH-479] - * Fixed non-monotonic X-Consul-Index with key deletion [GH-577] [GH-195] - * Fixed use of default instead of custom TLD in some DNS responses [GH-582] - * Fixed memory leaks in API client when an error response is returned [GH-608] - * Fixed issues with graceful leave in single-node bootstrap cluster [GH-621] - * Fixed issue preventing node reaping [GH-371] - * Fixed gossip stability at very large scale - * Fixed string of rpc error: rpc error: ... no known leader. [GH-611] - * Fixed panic in `exec` during cancellation - * Fixed health check state reset caused by SIGHUP [GH-693] - * Fixed bug in UI when multiple datacenters exist. - -IMPROVEMENTS: - - * Support "consul exec" in foreign datacenter [GH-584] - * Improved K/V blocking query performance [GH-578] - * CLI respects CONSUL_RPC_ADDR environment variable to load parameter [GH-542] - * Added support for multiple DNS recursors [GH-448] - * Added support for defining multiple services per configuration file [GH-433] - * Added support for defining multiple checks per configuration file [GH-433] - * Allow mixing of service and check definitions in a configuration file [GH-433] - * Allow notes for checks in service definition file [GH-449] - * Random stagger for agent checks to prevent thundering herd [GH-546] - * More useful metrics are sent to statsd/statsite - * Added configuration to set custom HTTP headers (CORS) [GH-558] - * Reject invalid configurations to simplify validation [GH-576] - * Guard against accidental cluster mixing [GH-580] [GH-260] - * Added option to filter DNS results on warning [GH-595] - * Improve write throughput with raft log caching [GH-604] - * Added ability to bind RPC and HTTP listeners to UNIX sockets [GH-587] [GH-612] - * K/V HTTP endpoint returns 400 on conflicting flags [GH-634] [GH-432] - -MISC: - - * UI confirms before deleting key sub-tree [GH-520] - * More useful output in "consul version" [GH-480] - * Many documentation improvements - * Reduce log messages when quorum member is logs [GH-566] - -UPGRADE NOTES: - - * If `acl_default_policy` is "deny", ensure tokens are updated to enable - service registration to avoid a service disruption. The new ACL policy - can be submitted with 0.4 before upgrading to 0.5 where it will be - enforced. - - * Servers running 0.5.X cannot be mixed with older servers. (Any client - version is fine). There is a 15 minute upgrade window where mixed - versions are allowed before older servers will panic due to an unsupported - internal command. This is due to the new KV tombstones which are internal - to servers. - -## 0.4.1 (October 20, 2014) - -FEATURES: - - * Adding flags for `-retry-join` to attempt a join with - configurable retry behavior. [GH-395] - -BUG FIXES: - - * Fixed ACL token in UI - * Fixed ACL reloading in UI [GH-323] - * Fixed long session names in UI [GH-353] - * Fixed exit code from remote exec [GH-346] - * Fixing only a single watch being run by an agent [GH-337] - * Fixing potential race in connection multiplexing - * Fixing issue with Session ID and ACL ID generation. [GH-391] - * Fixing multiple headers for /v1/event/list endpoint [GH-361] - * Fixing graceful leave of leader causing invalid Raft peers [GH-360] - * Fixing bug with closing TLS connection on error - * Fixing issue with node reaping [GH-371] - * Fixing aggressive deadlock time [GH-389] - * Fixing syslog filter level [GH-272] - * Serf snapshot compaction works on Windows [GH-332] - * Raft snapshots work on Windows [GH-265] - * Consul service entry clean by clients now possible - * Fixing improper deserialization - -IMPROVEMENTS: - - * Use "critical" health state instead of "unknown" [GH-341] - * Consul service can be targeted for exec [GH-344] - * Provide debug logging for session invalidation [GH-390] - * Added "Deregister" button to UI [GH-364] - * Added `enable_truncate` DNS configuration flag [GH-376] - * Reduce mmap() size on 32bit systems [GH-265] - * Temporary state is cleaned after an abort [GH-338] [GH-178] - -MISC: - - * Health state "unknown" being deprecated - -## 0.4.0 (September 5, 2014) - -FEATURES: - - * Fine-grained ACL system to restrict access to KV store. Clients - use tokens which can be restricted to (read, write, deny) permissions - using longest-prefix matches. - - * Watch mechanisms added to invoke a handler when data changes in consul. - Used with the `consul watch` command, or by specifying `watches` in - an agent configuration. - - * Event system added to support custom user events. Events are fired using - the `consul event` command. They are handled using a standard watch. - - * Remote execution using `consul exec`. This allows for command execution on remote - instances mediated through Consul. - - * RFC-2782 style DNS lookups supported - - * UI improvements, including support for ACLs. - -IMPROVEMENTS: - - * DNS case-insensitivity [GH-189] - * Support for HTTP `?pretty` parameter to pretty format JSON output. - * Use $SHELL when invoking handlers. [GH-237] - * Agent takes the `-encrypt` CLI Flag [GH-245] - * New `statsd_add` config for Statsd support. [GH-247] - * New `addresses` config for providing an override to `client_addr` for - DNS, HTTP, or RPC endpoints. [GH-301] [GH-253] - * Support [Checkpoint](http://checkpoint.hashicorp.com) for security bulletins - and update announcements. - -BUG FIXES: - - * Fixed race condition in `-bootstrap-expect` [GH-254] - * Require PUT to /v1/session/destroy [GH-285] - * Fixed registration race condition [GH-300] [GH-279] - -UPGRADE NOTES: - - * ACL support should not be enabled until all server nodes are running - Consul 0.4. Mixed server versions with ACL support enabled may result in - panics. - -## 0.3.1 (July 21, 2014) - -FEATURES: - - * Improved bootstrapping process, thanks to @robxu9 - -BUG FIXES: - - * Fixed issue with service re-registration [GH-216] - * Fixed handling of `-rejoin` flag - * Restored 0.2 TLS behavior, thanks to @nelhage [GH-233] - * Fix the statsite flags, thanks to @nelhage [GH-243] - * Fixed filters on critical / non-passing checks [GH-241] - * Fixed initial log compaction crash [GH-297] - -IMPROVEMENTS: - - * UI Improvements - * Improved handling of Serf snapshot data - * Increase reliability of failure detector - * More useful logging messages - - -## 0.3.0 (June 13, 2014) - -FEATURES: - - * Better, faster, cleaner UI [GH-194] [GH-196] - * Sessions, which act as a binding layer between - nodes, checks and KV data. [GH-162] - * Key locking. KV data integrates with sessions to - enable distributed locking. [GH-162] - * DNS lookups can do stale reads and TTLs. [GH-200] - * Added new /v1/agent/self endpoint [GH-173] - * `reload` command can be used to trigger configuration - reload from the CLI [GH-142] - -IMPROVEMENTS: - - * `members` has a much cleaner output format [GH-143] - * `info` includes build version information - * Sorted results for datacneter list [GH-198] - * Switch multiplexing to yamux - * Allow multiple CA certs in ca_file [GH-174] - * Enable logging to syslog. [GH-105] - * Allow raw key value lookup [GH-150] - * Log encryption enabled [GH-151] - * Support `-rejoin` to rejoin a cluster after a previous leave. [GH-110] - * Support the "any" wildcard for v1/health/state/ [GH-152] - * Defer sync of health check output [GH-157] - * Provide output for serfHealth check [GH-176] - * Datacenter name is validated [GH-169] - * Configurable syslog facilities [GH-170] - * Pipelining replication of writes - * Raft group commits - * Increased stability of leader terms - * Prevent previously left nodes from causing re-elections - -BUG FIXES: - - * Fixed memory leak in in-memory stats system - * Fixing race between RPC and Raft init [GH-160] - * Server-local RPC is avoids network [GH-148] - * Fixing builds for older OSX [GH-147] - -MISC: - - * Fixed missing prefixes on some log messages - * Removed the `-role` filter of `members` command - * Lots of docs fixes - -## 0.2.1 (May 20, 2014) - -IMPROVEMENTS: - - * Improved the URL formatting for the key/value editor in the Web UI. - Importantly, the editor now allows editing keys with dashes in the - name. [GH-119] - * The web UI now has cancel and delete folder actions in the key/value - editor. [GH-124], [GH-122] - * Add flag to agent to write pid to a file. [GH-106] - * Time out commands if Raft exceeds command enqueue timeout - * Adding support for the `-advertise` CLI flag. [GH-156] - * Fixing potential name conflicts on the WAN gossip ring [GH-158] - * /v1/catalog/services returns an empty slice instead of null. [GH-145] - * `members` command returns exit code 2 if no results. [GH-116] - -BUG FIXES: - - * Renaming "separator" to "separator". This is the correct spelling, - but both spellings are respected for backwards compatibility. [GH-101] - * Private IP is properly found on Windows clients. - * Windows agents won't show "failed to decode" errors on every RPC - request. - * Fixed memory leak with RPC clients. [GH-149] - * Serf name conflict resolution disabled. [GH-97] - * Raft deadlock possibility fixed. [GH-141] - -MISC: - - * Updating to latest version of LMDB - * Reduced the limit of KV entries to 512KB. [GH-123]. - * Warn if any Raft log exceeds 1MB - * Lots of docs fixes - -## 0.2.0 (May 1, 2014) - -FEATURES: - - * Adding Web UI for Consul. This is enabled by providing the `-ui-dir` flag - with the path to the web directory. The UI is visited at the standard HTTP - address (Defaults to http://127.0.0.1:8500/). There is a demo - [available here](http://demo.consul.io). - * Adding new read consistency modes. `?consistent` can be used for strongly - consistent reads without caveats. `?stale` can be used for stale reads to - allow for higher throughput and read scalability. [GH-68] - * /v1/health/service/ endpoint can take an optional `?passing` flag - to filter to only nodes with passing results. [GH-57] - * The KV endpoint supports listing keys with the `?keys` query parameter, - and limited up to a separator using `?separator=`. - -IMPROVEMENTS: - - * Health check output goes into separate `Output` field instead - of overriding `Notes`. [GH-59] - * Adding a minimum check interval to prevent checks with extremely - low intervals fork bombing. [GH-64] - * Raft peer set cleared on leave. [GH-69] - * Case insensitive parsing checks. [GH-78] - * Increase limit of DB size and Raft log on 64bit systems. [GH-81] - * Output of health checks limited to 4K. [GH-83] - * More warnings if GOMAXPROCS == 1 [GH-87] - * Added runtime information to `consul info` - -BUG FIXES: - - * Fixed 404 on /v1/agent/service/deregister and - /v1/agent/check/deregister. [GH-95] - * Fixed JSON parsing for /v1/agent/check/register [GH-60] - * DNS parser can handler period in a tag name. [GH-39] - * "application/json" content-type is sent on HTTP requests. [GH-45] - * Work around for LMDB delete issue. [GH-85] - * Fixed tag gossip propagation for rapid restart. [GH-86] - -MISC: - - * More conservative timing values for Raft - * Provide a warning if attempting to commit a very large Raft entry - * Improved timeliness of registration when server is in bootstrap mode. [GH-72] - -## 0.1.0 (April 17, 2014) - - * Initial release diff --git a/vendor/github.com/hashicorp/consul/GNUmakefile b/vendor/github.com/hashicorp/consul/GNUmakefile deleted file mode 100644 index 0ad26d643..000000000 --- a/vendor/github.com/hashicorp/consul/GNUmakefile +++ /dev/null @@ -1,108 +0,0 @@ -SHELL = bash -GOTOOLS = \ - github.com/elazarl/go-bindata-assetfs/... \ - github.com/jteeuwen/go-bindata/... \ - github.com/magiconair/vendorfmt/cmd/vendorfmt \ - github.com/mitchellh/gox \ - golang.org/x/tools/cmd/cover \ - golang.org/x/tools/cmd/stringer \ - github.com/axw/gocov/gocov \ - gopkg.in/matm/v1/gocov-html - -GOTAGS ?= -GOFILES ?= $(shell go list ./... | grep -v /vendor/) -GOOS=$(shell go env GOOS) -GOARCH=$(shell go env GOARCH) - -# Get the git commit -GIT_COMMIT=$(shell git rev-parse --short HEAD) -GIT_DIRTY=$(shell test -n "`git status --porcelain`" && echo "+CHANGES" || true) -GIT_DESCRIBE=$(shell git describe --tags --always) -GIT_IMPORT=github.com/hashicorp/consul/version -GOLDFLAGS=-X $(GIT_IMPORT).GitCommit=$(GIT_COMMIT)$(GIT_DIRTY) -X $(GIT_IMPORT).GitDescribe=$(GIT_DESCRIBE) - -export GOLDFLAGS - -# all builds binaries for all targets -all: bin - -bin: tools - @mkdir -p bin/ - @GOTAGS='$(GOTAGS)' sh -c "'$(CURDIR)/scripts/build.sh'" - -# dev creates binaries for testing locally - these are put into ./bin and $GOPATH -dev: vendorfmt dev-build - -dev-build: - mkdir -p pkg/$(GOOS)_$(GOARCH)/ bin/ - go install -ldflags '$(GOLDFLAGS)' -tags '$(GOTAGS)' - cp $(GOPATH)/bin/consul bin/ - cp $(GOPATH)/bin/consul pkg/$(GOOS)_$(GOARCH) - -vendorfmt: - test -x $(GOPATH)/bin/vendorfmt || go get -u github.com/magiconair/vendorfmt/cmd/vendorfmt - vendorfmt - -# linux builds a linux package independent of the source platform -linux: - mkdir -p pkg/linux_amd64/ - GOOS=linux GOARCH=amd64 go build -ldflags '$(GOLDFLAGS)' -tags '$(GOTAGS)' -o pkg/linux_amd64/consul - -# dist builds binaries for all platforms and packages them for distribution -dist: - @GOTAGS='$(GOTAGS)' sh -c "'$(CURDIR)/scripts/dist.sh'" - -cov: - gocov test $(GOFILES) | gocov-html > /tmp/coverage.html - open /tmp/coverage.html - -test: dev-build vet - go test -tags '$(GOTAGS)' -i ./... - go test $(GOTEST_FLAGS) -tags '$(GOTAGS)' -timeout 7m -v ./... 2>&1 >test.log ; echo $$? > exit-code - @echo "Exit code: `cat exit-code`" >> test.log - @echo "----" - @grep -A5 'DATA RACE' test.log || true - @grep -A10 'panic: test timed out' test.log || true - @grep '^PASS' test.log | uniq || true - @grep -A1 -- '--- FAIL:' test.log || true - @grep '^FAIL' test.log || true - @test "$$TRAVIS" == "true" && cat test.log || true - @exit $$(cat exit-code) - -test-race: - $(MAKE) GOTEST_FLAGS=-race - -cover: - go test $(GOFILES) --cover - -format: - @echo "--> Running go fmt" - @go fmt $(GOFILES) - -vet: - @echo "--> Running go vet" - @go vet $(GOFILES); if [ $$? -eq 1 ]; then \ - echo ""; \ - echo "Vet found suspicious constructs. Please check the reported constructs"; \ - echo "and fix them if necessary before submitting the code for review."; \ - exit 1; \ - fi - -# Build the static web ui and build static assets inside a Docker container, the -# same way a release build works. This implicitly does a "make static-assets" at -# the end. -ui: - @sh -c "'$(CURDIR)/scripts/ui.sh'" - -# If you've run "make ui" manually then this will get called for you. This is -# also run as part of the release build script when it verifies that there are no -# changes to the UI assets that aren't checked in. -static-assets: - @go-bindata-assetfs -pkg agent -prefix pkg ./pkg/web_ui/... - @mv bindata_assetfs.go agent/ - $(MAKE) format - -tools: - go get -u -v $(GOTOOLS) - -.PHONY: all ci bin dev dist cov test cover format vet ui static-assets tools vendorfmt diff --git a/vendor/github.com/hashicorp/consul/ISSUE_TEMPLATE.md b/vendor/github.com/hashicorp/consul/ISSUE_TEMPLATE.md deleted file mode 100644 index 1bdc7d226..000000000 --- a/vendor/github.com/hashicorp/consul/ISSUE_TEMPLATE.md +++ /dev/null @@ -1,35 +0,0 @@ -If you have a question, please direct it to the -[consul mailing list](https://www.consul.io/community.html) if it hasn't been -addressed in either the [FAQ](https://www.consul.io/docs/faq.html) or in one -of the [Consul Guides](https://www.consul.io/docs/guides/index.html). - -When filing a bug, please include the following: - -### `consul version` for both Client and Server -Client: `[client version here]` -Server: `[server version here]` - -### `consul info` for both Client and Server -Client: -``` -[Client `consul info` here] -``` - -Server: -``` -[Server `consul info` here] -``` - -### Operating system and Environment details - -### Description of the Issue (and unexpected/desired result) - -### Reproduction steps - -### Log Fragments or Link to [gist](https://gist.github.com/) - -Include appropriate Client or Server log fragments. If the log is longer -than a few dozen lines, please include the URL to the -[gist](https://gist.github.com/). - -TIP: Use `-log-level=TRACE` on the client and server to capture the maximum log detail. diff --git a/vendor/github.com/hashicorp/consul/README.md b/vendor/github.com/hashicorp/consul/README.md deleted file mode 100644 index ed73ef872..000000000 --- a/vendor/github.com/hashicorp/consul/README.md +++ /dev/null @@ -1,70 +0,0 @@ -# Consul [![Build Status](https://travis-ci.org/hashicorp/consul.svg?branch=master)](https://travis-ci.org/hashicorp/consul) [![Join the chat at https://gitter.im/hashicorp-consul/Lobby](https://badges.gitter.im/hashicorp-consul/Lobby.svg)](https://gitter.im/hashicorp-consul/Lobby?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) - -* Website: https://www.consul.io -* Chat: [Gitter](https://gitter.im/hashicorp-consul/Lobby) -* Mailing list: [Google Groups](https://groups.google.com/group/consul-tool/) - -Consul is a tool for service discovery and configuration. Consul is -distributed, highly available, and extremely scalable. - -Consul provides several key features: - -* **Service Discovery** - Consul makes it simple for services to register - themselves and to discover other services via a DNS or HTTP interface. - External services such as SaaS providers can be registered as well. - -* **Health Checking** - Health Checking enables Consul to quickly alert - operators about any issues in a cluster. The integration with service - discovery prevents routing traffic to unhealthy hosts and enables service - level circuit breakers. - -* **Key/Value Storage** - A flexible key/value store enables storing - dynamic configuration, feature flagging, coordination, leader election and - more. The simple HTTP API makes it easy to use anywhere. - -* **Multi-Datacenter** - Consul is built to be datacenter aware, and can - support any number of regions without complex configuration. - -Consul runs on Linux, Mac OS X, FreeBSD, Solaris, and Windows. - -## Quick Start - -An extensive quick start is viewable on the Consul website: - -https://www.consul.io/intro/getting-started/install.html - -## Documentation - -Full, comprehensive documentation is viewable on the Consul website: - -https://www.consul.io/docs - -## Developing Consul - -If you wish to work on Consul itself, you'll first need [Go](https://golang.org) -installed (version 1.9+ is _required_). Make sure you have Go properly installed, -including setting up your [GOPATH](https://golang.org/doc/code.html#GOPATH). - -Next, clone this repository into `$GOPATH/src/github.com/hashicorp/consul` and -then just type `make`. In a few moments, you'll have a working `consul` executable: - -``` -$ make -... -$ bin/consul -... -``` - -*Note: `make` will build all os/architecture combinations. Set the environment variable `CONSUL_DEV=1` to build it just for your local machine's os/architecture, or use `make dev`.* - -*Note: `make` will also place a copy of the binary in the first part of your `$GOPATH`.* - -You can run tests by typing `make test`. - -If you make any changes to the code, run `make format` in order to automatically -format the code according to Go standards. - -## Vendoring - -Consul currently uses [govendor](https://github.com/kardianos/govendor) for -vendoring. diff --git a/vendor/github.com/hashicorp/consul/api/README.md b/vendor/github.com/hashicorp/consul/api/README.md deleted file mode 100644 index 7e64988f4..000000000 --- a/vendor/github.com/hashicorp/consul/api/README.md +++ /dev/null @@ -1,43 +0,0 @@ -Consul API client -================= - -This package provides the `api` package which attempts to -provide programmatic access to the full Consul API. - -Currently, all of the Consul APIs included in version 0.6.0 are supported. - -Documentation -============= - -The full documentation is available on [Godoc](https://godoc.org/github.com/hashicorp/consul/api) - -Usage -===== - -Below is an example of using the Consul client: - -```go -// Get a new client -client, err := api.NewClient(api.DefaultConfig()) -if err != nil { - panic(err) -} - -// Get a handle to the KV API -kv := client.KV() - -// PUT a new KV pair -p := &api.KVPair{Key: "foo", Value: []byte("test")} -_, err = kv.Put(p, nil) -if err != nil { - panic(err) -} - -// Lookup the pair -pair, _, err := kv.Get("foo", nil) -if err != nil { - panic(err) -} -fmt.Printf("KV: %v", pair) - -``` diff --git a/vendor/github.com/hashicorp/consul/api/acl_test.go b/vendor/github.com/hashicorp/consul/api/acl_test.go deleted file mode 100644 index 5b0e840af..000000000 --- a/vendor/github.com/hashicorp/consul/api/acl_test.go +++ /dev/null @@ -1,164 +0,0 @@ -package api - -import ( - "testing" -) - -func TestAPI_ACLBootstrap(t *testing.T) { - // TODO (slackpad) We currently can't inject the version, and the - // version in the binary depends on Git tags, so we can't reliably - // test this until we are just running an agent in-process here and - // have full control over the config. -} - -func TestAPI_ACLCreateDestroy(t *testing.T) { - t.Parallel() - c, s := makeACLClient(t) - defer s.Stop() - - acl := c.ACL() - - ae := ACLEntry{ - Name: "API test", - Type: ACLClientType, - Rules: `key "" { policy = "deny" }`, - } - - id, wm, err := acl.Create(&ae, nil) - if err != nil { - t.Fatalf("err: %v", err) - } - - if wm.RequestTime == 0 { - t.Fatalf("bad: %v", wm) - } - - if id == "" { - t.Fatalf("invalid: %v", id) - } - - ae2, _, err := acl.Info(id, nil) - if err != nil { - t.Fatalf("err: %v", err) - } - - if ae2.Name != ae.Name || ae2.Type != ae.Type || ae2.Rules != ae.Rules { - t.Fatalf("Bad: %#v", ae2) - } - - wm, err = acl.Destroy(id, nil) - if err != nil { - t.Fatalf("err: %v", err) - } - - if wm.RequestTime == 0 { - t.Fatalf("bad: %v", wm) - } -} - -func TestAPI_ACLCloneDestroy(t *testing.T) { - t.Parallel() - c, s := makeACLClient(t) - defer s.Stop() - - acl := c.ACL() - - id, wm, err := acl.Clone(c.config.Token, nil) - if err != nil { - t.Fatalf("err: %v", err) - } - - if wm.RequestTime == 0 { - t.Fatalf("bad: %v", wm) - } - - if id == "" { - t.Fatalf("invalid: %v", id) - } - - wm, err = acl.Destroy(id, nil) - if err != nil { - t.Fatalf("err: %v", err) - } - - if wm.RequestTime == 0 { - t.Fatalf("bad: %v", wm) - } -} - -func TestAPI_ACLInfo(t *testing.T) { - t.Parallel() - c, s := makeACLClient(t) - defer s.Stop() - - acl := c.ACL() - - ae, qm, err := acl.Info(c.config.Token, nil) - if err != nil { - t.Fatalf("err: %v", err) - } - - if qm.LastIndex == 0 { - t.Fatalf("bad: %v", qm) - } - if !qm.KnownLeader { - t.Fatalf("bad: %v", qm) - } - - if ae == nil || ae.ID != c.config.Token || ae.Type != ACLManagementType { - t.Fatalf("bad: %#v", ae) - } -} - -func TestAPI_ACLList(t *testing.T) { - t.Parallel() - c, s := makeACLClient(t) - defer s.Stop() - - acl := c.ACL() - - acls, qm, err := acl.List(nil) - if err != nil { - t.Fatalf("err: %v", err) - } - - if len(acls) < 2 { - t.Fatalf("bad: %v", acls) - } - - if qm.LastIndex == 0 { - t.Fatalf("bad: %v", qm) - } - if !qm.KnownLeader { - t.Fatalf("bad: %v", qm) - } -} - -func TestAPI_ACLReplication(t *testing.T) { - t.Parallel() - c, s := makeACLClient(t) - defer s.Stop() - - acl := c.ACL() - - repl, qm, err := acl.Replication(nil) - if err != nil { - t.Fatalf("err: %v", err) - } - - if repl == nil { - t.Fatalf("bad: %v", repl) - } - - if repl.Running { - t.Fatal("bad: repl should not be running") - } - - if repl.Enabled { - t.Fatal("bad: repl should not be enabled") - } - - if qm.RequestTime == 0 { - t.Fatalf("bad: %v", qm) - } -} diff --git a/vendor/github.com/hashicorp/consul/api/agent_test.go b/vendor/github.com/hashicorp/consul/api/agent_test.go deleted file mode 100644 index fda397132..000000000 --- a/vendor/github.com/hashicorp/consul/api/agent_test.go +++ /dev/null @@ -1,836 +0,0 @@ -package api - -import ( - "io/ioutil" - "strings" - "testing" - "time" - - "github.com/hashicorp/consul/testutil" - "github.com/hashicorp/serf/serf" -) - -func TestAPI_AgentSelf(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - agent := c.Agent() - - info, err := agent.Self() - if err != nil { - t.Fatalf("err: %v", err) - } - - name := info["Config"]["NodeName"] - if name == "" { - t.Fatalf("bad: %v", info) - } -} - -func TestAPI_AgentMetrics(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - agent := c.Agent() - - metrics, err := agent.Metrics() - if err != nil { - t.Fatalf("err: %v", err) - } - - if len(metrics.Gauges) < 0 { - t.Fatalf("bad: %v", metrics) - } - - if metrics.Gauges[0].Name != "consul.runtime.alloc_bytes" { - t.Fatalf("bad: %v", metrics.Gauges[0]) - } -} - -func TestAPI_AgentReload(t *testing.T) { - t.Parallel() - - // Create our initial empty config file, to be overwritten later - configFile := testutil.TempFile(t, "reload") - if _, err := configFile.Write([]byte("{}")); err != nil { - t.Fatalf("err: %s", err) - } - configFile.Close() - - c, s := makeClientWithConfig(t, nil, func(conf *testutil.TestServerConfig) { - conf.Args = []string{"-config-file", configFile.Name()} - }) - defer s.Stop() - - agent := c.Agent() - - // Update the config file with a service definition - config := `{"service":{"name":"redis", "port":1234}}` - err := ioutil.WriteFile(configFile.Name(), []byte(config), 0644) - if err != nil { - t.Fatalf("err: %v", err) - } - - if err = agent.Reload(); err != nil { - t.Fatalf("err: %v", err) - } - - services, err := agent.Services() - if err != nil { - t.Fatalf("err: %v", err) - } - - service, ok := services["redis"] - if !ok { - t.Fatalf("bad: %v", ok) - } - if service.Port != 1234 { - t.Fatalf("bad: %v", service.Port) - } -} - -func TestAPI_AgentMembersOpts(t *testing.T) { - t.Parallel() - c, s1 := makeClient(t) - _, s2 := makeClientWithConfig(t, nil, func(c *testutil.TestServerConfig) { - c.Datacenter = "dc2" - }) - defer s1.Stop() - defer s2.Stop() - - agent := c.Agent() - - s2.JoinWAN(t, s1.WANAddr) - - members, err := agent.MembersOpts(MembersOpts{WAN: true}) - if err != nil { - t.Fatalf("err: %v", err) - } - - if len(members) != 2 { - t.Fatalf("bad: %v", members) - } -} - -func TestAPI_AgentMembers(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - agent := c.Agent() - - members, err := agent.Members(false) - if err != nil { - t.Fatalf("err: %v", err) - } - - if len(members) != 1 { - t.Fatalf("bad: %v", members) - } -} - -func TestAPI_AgentServices(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - agent := c.Agent() - - reg := &AgentServiceRegistration{ - Name: "foo", - Tags: []string{"bar", "baz"}, - Port: 8000, - Check: &AgentServiceCheck{ - TTL: "15s", - }, - } - if err := agent.ServiceRegister(reg); err != nil { - t.Fatalf("err: %v", err) - } - - services, err := agent.Services() - if err != nil { - t.Fatalf("err: %v", err) - } - if _, ok := services["foo"]; !ok { - t.Fatalf("missing service: %v", services) - } - checks, err := agent.Checks() - if err != nil { - t.Fatalf("err: %v", err) - } - chk, ok := checks["service:foo"] - if !ok { - t.Fatalf("missing check: %v", checks) - } - - // Checks should default to critical - if chk.Status != HealthCritical { - t.Fatalf("Bad: %#v", chk) - } - - if err := agent.ServiceDeregister("foo"); err != nil { - t.Fatalf("err: %v", err) - } -} - -func TestAPI_AgentServices_CheckPassing(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - agent := c.Agent() - reg := &AgentServiceRegistration{ - Name: "foo", - Tags: []string{"bar", "baz"}, - Port: 8000, - Check: &AgentServiceCheck{ - TTL: "15s", - Status: HealthPassing, - }, - } - if err := agent.ServiceRegister(reg); err != nil { - t.Fatalf("err: %v", err) - } - - services, err := agent.Services() - if err != nil { - t.Fatalf("err: %v", err) - } - if _, ok := services["foo"]; !ok { - t.Fatalf("missing service: %v", services) - } - - checks, err := agent.Checks() - if err != nil { - t.Fatalf("err: %v", err) - } - chk, ok := checks["service:foo"] - if !ok { - t.Fatalf("missing check: %v", checks) - } - - if chk.Status != HealthPassing { - t.Fatalf("Bad: %#v", chk) - } - if err := agent.ServiceDeregister("foo"); err != nil { - t.Fatalf("err: %v", err) - } -} - -func TestAPI_AgentServices_CheckBadStatus(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - agent := c.Agent() - reg := &AgentServiceRegistration{ - Name: "foo", - Tags: []string{"bar", "baz"}, - Port: 8000, - Check: &AgentServiceCheck{ - TTL: "15s", - Status: "fluffy", - }, - } - if err := agent.ServiceRegister(reg); err == nil { - t.Fatalf("bad status accepted") - } -} - -func TestAPI_AgentServiceAddress(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - agent := c.Agent() - - reg1 := &AgentServiceRegistration{ - Name: "foo1", - Port: 8000, - Address: "192.168.0.42", - } - reg2 := &AgentServiceRegistration{ - Name: "foo2", - Port: 8000, - } - if err := agent.ServiceRegister(reg1); err != nil { - t.Fatalf("err: %v", err) - } - if err := agent.ServiceRegister(reg2); err != nil { - t.Fatalf("err: %v", err) - } - - services, err := agent.Services() - if err != nil { - t.Fatalf("err: %v", err) - } - - if _, ok := services["foo1"]; !ok { - t.Fatalf("missing service: %v", services) - } - if _, ok := services["foo2"]; !ok { - t.Fatalf("missing service: %v", services) - } - - if services["foo1"].Address != "192.168.0.42" { - t.Fatalf("missing Address field in service foo1: %v", services) - } - if services["foo2"].Address != "" { - t.Fatalf("missing Address field in service foo2: %v", services) - } - - if err := agent.ServiceDeregister("foo"); err != nil { - t.Fatalf("err: %v", err) - } -} - -func TestAPI_AgentEnableTagOverride(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - agent := c.Agent() - - reg1 := &AgentServiceRegistration{ - Name: "foo1", - Port: 8000, - Address: "192.168.0.42", - EnableTagOverride: true, - } - reg2 := &AgentServiceRegistration{ - Name: "foo2", - Port: 8000, - } - if err := agent.ServiceRegister(reg1); err != nil { - t.Fatalf("err: %v", err) - } - if err := agent.ServiceRegister(reg2); err != nil { - t.Fatalf("err: %v", err) - } - - services, err := agent.Services() - if err != nil { - t.Fatalf("err: %v", err) - } - - if _, ok := services["foo1"]; !ok { - t.Fatalf("missing service: %v", services) - } - if services["foo1"].EnableTagOverride != true { - t.Fatalf("tag override not set on service foo1: %v", services) - } - if _, ok := services["foo2"]; !ok { - t.Fatalf("missing service: %v", services) - } - if services["foo2"].EnableTagOverride != false { - t.Fatalf("tag override set on service foo2: %v", services) - } -} - -func TestAPI_AgentServices_MultipleChecks(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - agent := c.Agent() - - reg := &AgentServiceRegistration{ - Name: "foo", - Tags: []string{"bar", "baz"}, - Port: 8000, - Checks: AgentServiceChecks{ - &AgentServiceCheck{ - TTL: "15s", - }, - &AgentServiceCheck{ - TTL: "30s", - }, - }, - } - if err := agent.ServiceRegister(reg); err != nil { - t.Fatalf("err: %v", err) - } - - services, err := agent.Services() - if err != nil { - t.Fatalf("err: %v", err) - } - if _, ok := services["foo"]; !ok { - t.Fatalf("missing service: %v", services) - } - - checks, err := agent.Checks() - if err != nil { - t.Fatalf("err: %v", err) - } - if _, ok := checks["service:foo:1"]; !ok { - t.Fatalf("missing check: %v", checks) - } - if _, ok := checks["service:foo:2"]; !ok { - t.Fatalf("missing check: %v", checks) - } -} - -func TestAPI_AgentSetTTLStatus(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - agent := c.Agent() - - reg := &AgentServiceRegistration{ - Name: "foo", - Check: &AgentServiceCheck{ - TTL: "15s", - }, - } - if err := agent.ServiceRegister(reg); err != nil { - t.Fatalf("err: %v", err) - } - - verify := func(status, output string) { - checks, err := agent.Checks() - if err != nil { - t.Fatalf("err: %v", err) - } - chk, ok := checks["service:foo"] - if !ok { - t.Fatalf("missing check: %v", checks) - } - if chk.Status != status { - t.Fatalf("Bad: %#v", chk) - } - if chk.Output != output { - t.Fatalf("Bad: %#v", chk) - } - } - - if err := agent.WarnTTL("service:foo", "foo"); err != nil { - t.Fatalf("err: %v", err) - } - verify(HealthWarning, "foo") - - if err := agent.PassTTL("service:foo", "bar"); err != nil { - t.Fatalf("err: %v", err) - } - verify(HealthPassing, "bar") - - if err := agent.FailTTL("service:foo", "baz"); err != nil { - t.Fatalf("err: %v", err) - } - verify(HealthCritical, "baz") - - if err := agent.UpdateTTL("service:foo", "foo", "warn"); err != nil { - t.Fatalf("err: %v", err) - } - verify(HealthWarning, "foo") - - if err := agent.UpdateTTL("service:foo", "bar", "pass"); err != nil { - t.Fatalf("err: %v", err) - } - verify(HealthPassing, "bar") - - if err := agent.UpdateTTL("service:foo", "baz", "fail"); err != nil { - t.Fatalf("err: %v", err) - } - verify(HealthCritical, "baz") - - if err := agent.UpdateTTL("service:foo", "foo", HealthWarning); err != nil { - t.Fatalf("err: %v", err) - } - verify(HealthWarning, "foo") - - if err := agent.UpdateTTL("service:foo", "bar", HealthPassing); err != nil { - t.Fatalf("err: %v", err) - } - verify(HealthPassing, "bar") - - if err := agent.UpdateTTL("service:foo", "baz", HealthCritical); err != nil { - t.Fatalf("err: %v", err) - } - verify(HealthCritical, "baz") - - if err := agent.ServiceDeregister("foo"); err != nil { - t.Fatalf("err: %v", err) - } -} - -func TestAPI_AgentChecks(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - agent := c.Agent() - - reg := &AgentCheckRegistration{ - Name: "foo", - } - reg.TTL = "15s" - if err := agent.CheckRegister(reg); err != nil { - t.Fatalf("err: %v", err) - } - - checks, err := agent.Checks() - if err != nil { - t.Fatalf("err: %v", err) - } - chk, ok := checks["foo"] - if !ok { - t.Fatalf("missing check: %v", checks) - } - if chk.Status != HealthCritical { - t.Fatalf("check not critical: %v", chk) - } - - if err := agent.CheckDeregister("foo"); err != nil { - t.Fatalf("err: %v", err) - } -} - -func TestAPI_AgentCheckStartPassing(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - agent := c.Agent() - - reg := &AgentCheckRegistration{ - Name: "foo", - AgentServiceCheck: AgentServiceCheck{ - Status: HealthPassing, - }, - } - reg.TTL = "15s" - if err := agent.CheckRegister(reg); err != nil { - t.Fatalf("err: %v", err) - } - - checks, err := agent.Checks() - if err != nil { - t.Fatalf("err: %v", err) - } - chk, ok := checks["foo"] - if !ok { - t.Fatalf("missing check: %v", checks) - } - if chk.Status != HealthPassing { - t.Fatalf("check not passing: %v", chk) - } - - if err := agent.CheckDeregister("foo"); err != nil { - t.Fatalf("err: %v", err) - } -} - -func TestAPI_AgentChecks_serviceBound(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - agent := c.Agent() - - // First register a service - serviceReg := &AgentServiceRegistration{ - Name: "redis", - } - if err := agent.ServiceRegister(serviceReg); err != nil { - t.Fatalf("err: %v", err) - } - - // Register a check bound to the service - reg := &AgentCheckRegistration{ - Name: "redischeck", - ServiceID: "redis", - } - reg.TTL = "15s" - reg.DeregisterCriticalServiceAfter = "nope" - err := agent.CheckRegister(reg) - if err == nil || !strings.Contains(err.Error(), "invalid duration") { - t.Fatalf("err: %v", err) - } - - reg.DeregisterCriticalServiceAfter = "90m" - if err := agent.CheckRegister(reg); err != nil { - t.Fatalf("err: %v", err) - } - - checks, err := agent.Checks() - if err != nil { - t.Fatalf("err: %v", err) - } - - check, ok := checks["redischeck"] - if !ok { - t.Fatalf("missing check: %v", checks) - } - if check.ServiceID != "redis" { - t.Fatalf("missing service association for check: %v", check) - } -} - -func TestAPI_AgentChecks_Docker(t *testing.T) { - t.Parallel() - c, s := makeClientWithConfig(t, nil, func(c *testutil.TestServerConfig) { - c.EnableScriptChecks = true - }) - defer s.Stop() - - agent := c.Agent() - - // First register a service - serviceReg := &AgentServiceRegistration{ - Name: "redis", - } - if err := agent.ServiceRegister(serviceReg); err != nil { - t.Fatalf("err: %v", err) - } - - // Register a check bound to the service - reg := &AgentCheckRegistration{ - Name: "redischeck", - ServiceID: "redis", - AgentServiceCheck: AgentServiceCheck{ - DockerContainerID: "f972c95ebf0e", - Script: "/bin/true", - Shell: "/bin/bash", - Interval: "10s", - }, - } - if err := agent.CheckRegister(reg); err != nil { - t.Fatalf("err: %v", err) - } - - checks, err := agent.Checks() - if err != nil { - t.Fatalf("err: %v", err) - } - - check, ok := checks["redischeck"] - if !ok { - t.Fatalf("missing check: %v", checks) - } - if check.ServiceID != "redis" { - t.Fatalf("missing service association for check: %v", check) - } -} - -func TestAPI_AgentJoin(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - agent := c.Agent() - - info, err := agent.Self() - if err != nil { - t.Fatalf("err: %v", err) - } - - // Join ourself - addr := info["Config"]["AdvertiseAddr"].(string) - err = agent.Join(addr, false) - if err != nil { - t.Fatalf("err: %v", err) - } -} - -func TestAPI_AgentLeave(t *testing.T) { - t.Parallel() - c1, s1 := makeClient(t) - defer s1.Stop() - - c2, s2 := makeClientWithConfig(t, nil, func(conf *testutil.TestServerConfig) { - conf.Server = false - conf.Bootstrap = false - }) - defer s2.Stop() - - if err := c2.Agent().Join(s1.LANAddr, false); err != nil { - t.Fatalf("err: %v", err) - } - - // We sometimes see an EOF response to this one, depending on timing. - err := c2.Agent().Leave() - if err != nil && !strings.Contains(err.Error(), "EOF") { - t.Fatalf("err: %v", err) - } - - // Make sure the second agent's status is 'Left' - members, err := c1.Agent().Members(false) - if err != nil { - t.Fatalf("err: %v", err) - } - member := members[0] - if member.Name == s1.Config.NodeName { - member = members[1] - } - if member.Status != int(serf.StatusLeft) { - t.Fatalf("bad: %v", *member) - } -} - -func TestAPI_AgentForceLeave(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - agent := c.Agent() - - // Eject somebody - err := agent.ForceLeave("foo") - if err != nil { - t.Fatalf("err: %v", err) - } -} - -func TestAPI_AgentMonitor(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - agent := c.Agent() - - logCh, err := agent.Monitor("info", nil, nil) - if err != nil { - t.Fatalf("err: %v", err) - } - - // Wait for the first log message and validate it - select { - case log := <-logCh: - if !strings.Contains(log, "[INFO]") { - t.Fatalf("bad: %q", log) - } - case <-time.After(10 * time.Second): - t.Fatalf("failed to get a log message") - } -} - -func TestAPI_ServiceMaintenance(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - agent := c.Agent() - - // First register a service - serviceReg := &AgentServiceRegistration{ - Name: "redis", - } - if err := agent.ServiceRegister(serviceReg); err != nil { - t.Fatalf("err: %v", err) - } - - // Enable maintenance mode - if err := agent.EnableServiceMaintenance("redis", "broken"); err != nil { - t.Fatalf("err: %s", err) - } - - // Ensure a critical check was added - checks, err := agent.Checks() - if err != nil { - t.Fatalf("err: %v", err) - } - found := false - for _, check := range checks { - if strings.Contains(check.CheckID, "maintenance") { - found = true - if check.Status != HealthCritical || check.Notes != "broken" { - t.Fatalf("bad: %#v", checks) - } - } - } - if !found { - t.Fatalf("bad: %#v", checks) - } - - // Disable maintenance mode - if err := agent.DisableServiceMaintenance("redis"); err != nil { - t.Fatalf("err: %s", err) - } - - // Ensure the critical health check was removed - checks, err = agent.Checks() - if err != nil { - t.Fatalf("err: %s", err) - } - for _, check := range checks { - if strings.Contains(check.CheckID, "maintenance") { - t.Fatalf("should have removed health check") - } - } -} - -func TestAPI_NodeMaintenance(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - agent := c.Agent() - - // Enable maintenance mode - if err := agent.EnableNodeMaintenance("broken"); err != nil { - t.Fatalf("err: %s", err) - } - - // Check that a critical check was added - checks, err := agent.Checks() - if err != nil { - t.Fatalf("err: %s", err) - } - found := false - for _, check := range checks { - if strings.Contains(check.CheckID, "maintenance") { - found = true - if check.Status != HealthCritical || check.Notes != "broken" { - t.Fatalf("bad: %#v", checks) - } - } - } - if !found { - t.Fatalf("bad: %#v", checks) - } - - // Disable maintenance mode - if err := agent.DisableNodeMaintenance(); err != nil { - t.Fatalf("err: %s", err) - } - - // Ensure the check was removed - checks, err = agent.Checks() - if err != nil { - t.Fatalf("err: %s", err) - } - for _, check := range checks { - if strings.Contains(check.CheckID, "maintenance") { - t.Fatalf("should have removed health check") - } - } -} - -func TestAPI_AgentUpdateToken(t *testing.T) { - t.Parallel() - c, s := makeACLClient(t) - defer s.Stop() - - agent := c.Agent() - - if _, err := agent.UpdateACLToken("root", nil); err != nil { - t.Fatalf("err: %v", err) - } - - if _, err := agent.UpdateACLAgentToken("root", nil); err != nil { - t.Fatalf("err: %v", err) - } - - if _, err := agent.UpdateACLAgentMasterToken("root", nil); err != nil { - t.Fatalf("err: %v", err) - } - - if _, err := agent.UpdateACLReplicationToken("root", nil); err != nil { - t.Fatalf("err: %v", err) - } -} diff --git a/vendor/github.com/hashicorp/consul/api/api_test.go b/vendor/github.com/hashicorp/consul/api/api_test.go deleted file mode 100644 index 341956c4f..000000000 --- a/vendor/github.com/hashicorp/consul/api/api_test.go +++ /dev/null @@ -1,537 +0,0 @@ -package api - -import ( - crand "crypto/rand" - "crypto/tls" - "fmt" - "net/http" - "os" - "path/filepath" - "reflect" - "runtime" - "strings" - "testing" - "time" - - "github.com/hashicorp/consul/testutil" -) - -type configCallback func(c *Config) - -func makeClient(t *testing.T) (*Client, *testutil.TestServer) { - return makeClientWithConfig(t, nil, nil) -} - -func makeACLClient(t *testing.T) (*Client, *testutil.TestServer) { - return makeClientWithConfig(t, func(clientConfig *Config) { - clientConfig.Token = "root" - }, func(serverConfig *testutil.TestServerConfig) { - serverConfig.ACLMasterToken = "root" - serverConfig.ACLDatacenter = "dc1" - serverConfig.ACLDefaultPolicy = "deny" - }) -} - -func makeClientWithConfig( - t *testing.T, - cb1 configCallback, - cb2 testutil.ServerConfigCallback) (*Client, *testutil.TestServer) { - - // Make client config - conf := DefaultConfig() - if cb1 != nil { - cb1(conf) - } - // Create server - server, err := testutil.NewTestServerConfigT(t, cb2) - if err != nil { - t.Fatal(err) - } - conf.Address = server.HTTPAddr - - // Create client - client, err := NewClient(conf) - if err != nil { - t.Fatalf("err: %v", err) - } - - return client, server -} - -func testKey() string { - buf := make([]byte, 16) - if _, err := crand.Read(buf); err != nil { - panic(fmt.Errorf("Failed to read random bytes: %v", err)) - } - - return fmt.Sprintf("%08x-%04x-%04x-%04x-%12x", - buf[0:4], - buf[4:6], - buf[6:8], - buf[8:10], - buf[10:16]) -} - -func TestAPI_DefaultConfig_env(t *testing.T) { - t.Parallel() - addr := "1.2.3.4:5678" - token := "abcd1234" - auth := "username:password" - - os.Setenv(HTTPAddrEnvName, addr) - defer os.Setenv(HTTPAddrEnvName, "") - os.Setenv(HTTPTokenEnvName, token) - defer os.Setenv(HTTPTokenEnvName, "") - os.Setenv(HTTPAuthEnvName, auth) - defer os.Setenv(HTTPAuthEnvName, "") - os.Setenv(HTTPSSLEnvName, "1") - defer os.Setenv(HTTPSSLEnvName, "") - os.Setenv(HTTPCAFile, "ca.pem") - defer os.Setenv(HTTPCAFile, "") - os.Setenv(HTTPCAPath, "certs/") - defer os.Setenv(HTTPCAPath, "") - os.Setenv(HTTPClientCert, "client.crt") - defer os.Setenv(HTTPClientCert, "") - os.Setenv(HTTPClientKey, "client.key") - defer os.Setenv(HTTPClientKey, "") - os.Setenv(HTTPTLSServerName, "consul.test") - defer os.Setenv(HTTPTLSServerName, "") - os.Setenv(HTTPSSLVerifyEnvName, "0") - defer os.Setenv(HTTPSSLVerifyEnvName, "") - - for i, config := range []*Config{DefaultConfig(), DefaultNonPooledConfig()} { - if config.Address != addr { - t.Errorf("expected %q to be %q", config.Address, addr) - } - if config.Token != token { - t.Errorf("expected %q to be %q", config.Token, token) - } - if config.HttpAuth == nil { - t.Fatalf("expected HttpAuth to be enabled") - } - if config.HttpAuth.Username != "username" { - t.Errorf("expected %q to be %q", config.HttpAuth.Username, "username") - } - if config.HttpAuth.Password != "password" { - t.Errorf("expected %q to be %q", config.HttpAuth.Password, "password") - } - if config.Scheme != "https" { - t.Errorf("expected %q to be %q", config.Scheme, "https") - } - if config.TLSConfig.CAFile != "ca.pem" { - t.Errorf("expected %q to be %q", config.TLSConfig.CAFile, "ca.pem") - } - if config.TLSConfig.CAPath != "certs/" { - t.Errorf("expected %q to be %q", config.TLSConfig.CAPath, "certs/") - } - if config.TLSConfig.CertFile != "client.crt" { - t.Errorf("expected %q to be %q", config.TLSConfig.CertFile, "client.crt") - } - if config.TLSConfig.KeyFile != "client.key" { - t.Errorf("expected %q to be %q", config.TLSConfig.KeyFile, "client.key") - } - if config.TLSConfig.Address != "consul.test" { - t.Errorf("expected %q to be %q", config.TLSConfig.Address, "consul.test") - } - if !config.TLSConfig.InsecureSkipVerify { - t.Errorf("expected SSL verification to be off") - } - - // Use keep alives as a check for whether pooling is on or off. - if pooled := i == 0; pooled { - if config.Transport.DisableKeepAlives != false { - t.Errorf("expected keep alives to be enabled") - } - } else { - if config.Transport.DisableKeepAlives != true { - t.Errorf("expected keep alives to be disabled") - } - } - } -} - -func TestAPI_SetupTLSConfig(t *testing.T) { - // A default config should result in a clean default client config. - tlsConfig := &TLSConfig{} - cc, err := SetupTLSConfig(tlsConfig) - if err != nil { - t.Fatalf("err: %v", err) - } - expected := &tls.Config{RootCAs: cc.RootCAs} - if !reflect.DeepEqual(cc, expected) { - t.Fatalf("bad: \n%v, \n%v", cc, expected) - } - - // Try some address variations with and without ports. - tlsConfig.Address = "127.0.0.1" - cc, err = SetupTLSConfig(tlsConfig) - if err != nil { - t.Fatalf("err: %v", err) - } - expected.ServerName = "127.0.0.1" - if !reflect.DeepEqual(cc, expected) { - t.Fatalf("bad: %v", cc) - } - - tlsConfig.Address = "127.0.0.1:80" - cc, err = SetupTLSConfig(tlsConfig) - if err != nil { - t.Fatalf("err: %v", err) - } - expected.ServerName = "127.0.0.1" - if !reflect.DeepEqual(cc, expected) { - t.Fatalf("bad: %v", cc) - } - - tlsConfig.Address = "demo.consul.io:80" - cc, err = SetupTLSConfig(tlsConfig) - if err != nil { - t.Fatalf("err: %v", err) - } - expected.ServerName = "demo.consul.io" - if !reflect.DeepEqual(cc, expected) { - t.Fatalf("bad: %v", cc) - } - - tlsConfig.Address = "[2001:db8:a0b:12f0::1]" - cc, err = SetupTLSConfig(tlsConfig) - if err != nil { - t.Fatalf("err: %v", err) - } - expected.ServerName = "[2001:db8:a0b:12f0::1]" - if !reflect.DeepEqual(cc, expected) { - t.Fatalf("bad: %v", cc) - } - - tlsConfig.Address = "[2001:db8:a0b:12f0::1]:80" - cc, err = SetupTLSConfig(tlsConfig) - if err != nil { - t.Fatalf("err: %v", err) - } - expected.ServerName = "2001:db8:a0b:12f0::1" - if !reflect.DeepEqual(cc, expected) { - t.Fatalf("bad: %v", cc) - } - - // Skip verification. - tlsConfig.InsecureSkipVerify = true - cc, err = SetupTLSConfig(tlsConfig) - if err != nil { - t.Fatalf("err: %v", err) - } - expected.InsecureSkipVerify = true - if !reflect.DeepEqual(cc, expected) { - t.Fatalf("bad: %v", cc) - } - - // Make a new config that hits all the file parsers. - tlsConfig = &TLSConfig{ - CertFile: "../test/hostname/Alice.crt", - KeyFile: "../test/hostname/Alice.key", - CAFile: "../test/hostname/CertAuth.crt", - } - cc, err = SetupTLSConfig(tlsConfig) - if err != nil { - t.Fatalf("err: %v", err) - } - if len(cc.Certificates) != 1 { - t.Fatalf("missing certificate: %v", cc.Certificates) - } - if cc.RootCAs == nil { - t.Fatalf("didn't load root CAs") - } - - // Use a directory to load the certs instead - cc, err = SetupTLSConfig(&TLSConfig{ - CAPath: "../test/ca_path", - }) - if err != nil { - t.Fatalf("err: %v", err) - } - if len(cc.RootCAs.Subjects()) != 2 { - t.Fatalf("didn't load root CAs") - } -} - -func TestAPI_ClientTLSOptions(t *testing.T) { - t.Parallel() - // Start a server that verifies incoming HTTPS connections - _, srvVerify := makeClientWithConfig(t, nil, func(conf *testutil.TestServerConfig) { - conf.CAFile = "../test/client_certs/rootca.crt" - conf.CertFile = "../test/client_certs/server.crt" - conf.KeyFile = "../test/client_certs/server.key" - conf.VerifyIncomingHTTPS = true - }) - defer srvVerify.Stop() - - // Start a server without VerifyIncomingHTTPS - _, srvNoVerify := makeClientWithConfig(t, nil, func(conf *testutil.TestServerConfig) { - conf.CAFile = "../test/client_certs/rootca.crt" - conf.CertFile = "../test/client_certs/server.crt" - conf.KeyFile = "../test/client_certs/server.key" - conf.VerifyIncomingHTTPS = false - }) - defer srvNoVerify.Stop() - - // Client without a cert - t.Run("client without cert, validation", func(t *testing.T) { - client, err := NewClient(&Config{ - Address: srvVerify.HTTPSAddr, - Scheme: "https", - TLSConfig: TLSConfig{ - Address: "consul.test", - CAFile: "../test/client_certs/rootca.crt", - }, - }) - if err != nil { - t.Fatal(err) - } - - // Should fail - _, err = client.Agent().Self() - if err == nil || !strings.Contains(err.Error(), "bad certificate") { - t.Fatal(err) - } - }) - - // Client with a valid cert - t.Run("client with cert, validation", func(t *testing.T) { - client, err := NewClient(&Config{ - Address: srvVerify.HTTPSAddr, - Scheme: "https", - TLSConfig: TLSConfig{ - Address: "consul.test", - CAFile: "../test/client_certs/rootca.crt", - CertFile: "../test/client_certs/client.crt", - KeyFile: "../test/client_certs/client.key", - }, - }) - if err != nil { - t.Fatal(err) - } - - // Should succeed - _, err = client.Agent().Self() - if err != nil { - t.Fatal(err) - } - }) - - // Client without a cert - t.Run("client without cert, no validation", func(t *testing.T) { - client, err := NewClient(&Config{ - Address: srvNoVerify.HTTPSAddr, - Scheme: "https", - TLSConfig: TLSConfig{ - Address: "consul.test", - CAFile: "../test/client_certs/rootca.crt", - }, - }) - if err != nil { - t.Fatal(err) - } - - // Should succeed - _, err = client.Agent().Self() - if err != nil { - t.Fatal(err) - } - }) - - // Client with a valid cert - t.Run("client with cert, no validation", func(t *testing.T) { - client, err := NewClient(&Config{ - Address: srvNoVerify.HTTPSAddr, - Scheme: "https", - TLSConfig: TLSConfig{ - Address: "consul.test", - CAFile: "../test/client_certs/rootca.crt", - CertFile: "../test/client_certs/client.crt", - KeyFile: "../test/client_certs/client.key", - }, - }) - if err != nil { - t.Fatal(err) - } - - // Should succeed - _, err = client.Agent().Self() - if err != nil { - t.Fatal(err) - } - }) -} - -func TestAPI_SetQueryOptions(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - r := c.newRequest("GET", "/v1/kv/foo") - q := &QueryOptions{ - Datacenter: "foo", - AllowStale: true, - RequireConsistent: true, - WaitIndex: 1000, - WaitTime: 100 * time.Second, - Token: "12345", - Near: "nodex", - } - r.setQueryOptions(q) - - if r.params.Get("dc") != "foo" { - t.Fatalf("bad: %v", r.params) - } - if _, ok := r.params["stale"]; !ok { - t.Fatalf("bad: %v", r.params) - } - if _, ok := r.params["consistent"]; !ok { - t.Fatalf("bad: %v", r.params) - } - if r.params.Get("index") != "1000" { - t.Fatalf("bad: %v", r.params) - } - if r.params.Get("wait") != "100000ms" { - t.Fatalf("bad: %v", r.params) - } - if r.header.Get("X-Consul-Token") != "12345" { - t.Fatalf("bad: %v", r.header) - } - if r.params.Get("near") != "nodex" { - t.Fatalf("bad: %v", r.params) - } -} - -func TestAPI_SetWriteOptions(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - r := c.newRequest("GET", "/v1/kv/foo") - q := &WriteOptions{ - Datacenter: "foo", - Token: "23456", - } - r.setWriteOptions(q) - - if r.params.Get("dc") != "foo" { - t.Fatalf("bad: %v", r.params) - } - if r.header.Get("X-Consul-Token") != "23456" { - t.Fatalf("bad: %v", r.header) - } -} - -func TestAPI_RequestToHTTP(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - r := c.newRequest("DELETE", "/v1/kv/foo") - q := &QueryOptions{ - Datacenter: "foo", - } - r.setQueryOptions(q) - req, err := r.toHTTP() - if err != nil { - t.Fatalf("err: %v", err) - } - - if req.Method != "DELETE" { - t.Fatalf("bad: %v", req) - } - if req.URL.RequestURI() != "/v1/kv/foo?dc=foo" { - t.Fatalf("bad: %v", req) - } -} - -func TestAPI_ParseQueryMeta(t *testing.T) { - t.Parallel() - resp := &http.Response{ - Header: make(map[string][]string), - } - resp.Header.Set("X-Consul-Index", "12345") - resp.Header.Set("X-Consul-LastContact", "80") - resp.Header.Set("X-Consul-KnownLeader", "true") - resp.Header.Set("X-Consul-Translate-Addresses", "true") - - qm := &QueryMeta{} - if err := parseQueryMeta(resp, qm); err != nil { - t.Fatalf("err: %v", err) - } - - if qm.LastIndex != 12345 { - t.Fatalf("Bad: %v", qm) - } - if qm.LastContact != 80*time.Millisecond { - t.Fatalf("Bad: %v", qm) - } - if !qm.KnownLeader { - t.Fatalf("Bad: %v", qm) - } - if !qm.AddressTranslationEnabled { - t.Fatalf("Bad: %v", qm) - } -} - -func TestAPI_UnixSocket(t *testing.T) { - t.Parallel() - if runtime.GOOS == "windows" { - t.SkipNow() - } - - tempDir := testutil.TempDir(t, "consul") - defer os.RemoveAll(tempDir) - socket := filepath.Join(tempDir, "test.sock") - - c, s := makeClientWithConfig(t, func(c *Config) { - c.Address = "unix://" + socket - }, func(c *testutil.TestServerConfig) { - c.Addresses = &testutil.TestAddressConfig{ - HTTP: "unix://" + socket, - } - }) - defer s.Stop() - - agent := c.Agent() - - info, err := agent.Self() - if err != nil { - t.Fatalf("err: %s", err) - } - if info["Config"]["NodeName"] == "" { - t.Fatalf("bad: %v", info) - } -} - -func TestAPI_durToMsec(t *testing.T) { - if ms := durToMsec(0); ms != "0ms" { - t.Fatalf("bad: %s", ms) - } - - if ms := durToMsec(time.Millisecond); ms != "1ms" { - t.Fatalf("bad: %s", ms) - } - - if ms := durToMsec(time.Microsecond); ms != "1ms" { - t.Fatalf("bad: %s", ms) - } - - if ms := durToMsec(5 * time.Millisecond); ms != "5ms" { - t.Fatalf("bad: %s", ms) - } -} - -func TestAPI_IsServerError(t *testing.T) { - if IsServerError(nil) { - t.Fatalf("should not be a server error") - } - - if IsServerError(fmt.Errorf("not the error you are looking for")) { - t.Fatalf("should not be a server error") - } - - if !IsServerError(fmt.Errorf(serverError)) { - t.Fatalf("should be a server error") - } -} diff --git a/vendor/github.com/hashicorp/consul/api/catalog_test.go b/vendor/github.com/hashicorp/consul/api/catalog_test.go deleted file mode 100644 index 57cf5acdc..000000000 --- a/vendor/github.com/hashicorp/consul/api/catalog_test.go +++ /dev/null @@ -1,476 +0,0 @@ -package api - -import ( - "testing" - - "github.com/hashicorp/consul/testutil" - "github.com/hashicorp/consul/testutil/retry" - "github.com/pascaldekloe/goe/verify" -) - -func TestAPI_CatalogDatacenters(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - catalog := c.Catalog() - retry.Run(t, func(r *retry.R) { - datacenters, err := catalog.Datacenters() - if err != nil { - r.Fatal(err) - } - if len(datacenters) < 1 { - r.Fatal("got 0 datacenters want at least one") - } - }) -} - -func TestAPI_CatalogNodes(t *testing.T) { - c, s := makeClient(t) - defer s.Stop() - - catalog := c.Catalog() - retry.RunWith(retry.ThreeTimes(), t, func(r *retry.R) { - nodes, meta, err := catalog.Nodes(nil) - if err != nil { - r.Fatal(err) - } - if meta.LastIndex == 0 { - r.Fatal("got last index 0 want > 0") - } - want := []*Node{ - { - ID: s.Config.NodeID, - Node: s.Config.NodeName, - Address: "127.0.0.1", - Datacenter: "dc1", - TaggedAddresses: map[string]string{ - "lan": "127.0.0.1", - "wan": "127.0.0.1", - }, - Meta: map[string]string{ - "consul-network-segment": "", - }, - CreateIndex: meta.LastIndex - 1, - ModifyIndex: meta.LastIndex, - }, - } - if !verify.Values(r, "", nodes, want) { - r.FailNow() - } - }) -} - -func TestAPI_CatalogNodes_MetaFilter(t *testing.T) { - meta := map[string]string{"somekey": "somevalue"} - c, s := makeClientWithConfig(t, nil, func(conf *testutil.TestServerConfig) { - conf.NodeMeta = meta - }) - defer s.Stop() - - catalog := c.Catalog() - // Make sure we get the node back when filtering by its metadata - retry.Run(t, func(r *retry.R) { - nodes, meta, err := catalog.Nodes(&QueryOptions{NodeMeta: meta}) - if err != nil { - r.Fatal(err) - } - - if meta.LastIndex == 0 { - r.Fatalf("Bad: %v", meta) - } - - if len(nodes) == 0 { - r.Fatalf("Bad: %v", nodes) - } - - if _, ok := nodes[0].TaggedAddresses["wan"]; !ok { - r.Fatalf("Bad: %v", nodes[0]) - } - - if v, ok := nodes[0].Meta["somekey"]; !ok || v != "somevalue" { - r.Fatalf("Bad: %v", nodes[0].Meta) - } - - if nodes[0].Datacenter != "dc1" { - r.Fatalf("Bad datacenter: %v", nodes[0]) - } - }) - - retry.Run(t, func(r *retry.R) { - // Get nothing back when we use an invalid filter - nodes, meta, err := catalog.Nodes(&QueryOptions{NodeMeta: map[string]string{"nope": "nope"}}) - if err != nil { - r.Fatal(err) - } - - if meta.LastIndex == 0 { - r.Fatalf("Bad: %v", meta) - } - - if len(nodes) != 0 { - r.Fatalf("Bad: %v", nodes) - } - }) -} - -func TestAPI_CatalogServices(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - catalog := c.Catalog() - retry.Run(t, func(r *retry.R) { - services, meta, err := catalog.Services(nil) - if err != nil { - r.Fatal(err) - } - - if meta.LastIndex == 0 { - r.Fatalf("Bad: %v", meta) - } - - if len(services) == 0 { - r.Fatalf("Bad: %v", services) - } - }) -} - -func TestAPI_CatalogServices_NodeMetaFilter(t *testing.T) { - meta := map[string]string{"somekey": "somevalue"} - c, s := makeClientWithConfig(t, nil, func(conf *testutil.TestServerConfig) { - conf.NodeMeta = meta - }) - defer s.Stop() - - catalog := c.Catalog() - // Make sure we get the service back when filtering by the node's metadata - retry.Run(t, func(r *retry.R) { - services, meta, err := catalog.Services(&QueryOptions{NodeMeta: meta}) - if err != nil { - r.Fatal(err) - } - - if meta.LastIndex == 0 { - r.Fatalf("Bad: %v", meta) - } - - if len(services) == 0 { - r.Fatalf("Bad: %v", services) - } - }) - - retry.Run(t, func(r *retry.R) { - // Get nothing back when using an invalid filter - services, meta, err := catalog.Services(&QueryOptions{NodeMeta: map[string]string{"nope": "nope"}}) - if err != nil { - r.Fatal(err) - } - - if meta.LastIndex == 0 { - r.Fatalf("Bad: %v", meta) - } - - if len(services) != 0 { - r.Fatalf("Bad: %v", services) - } - }) -} - -func TestAPI_CatalogService(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - catalog := c.Catalog() - retry.Run(t, func(r *retry.R) { - services, meta, err := catalog.Service("consul", "", nil) - if err != nil { - r.Fatal(err) - } - - if meta.LastIndex == 0 { - r.Fatalf("Bad: %v", meta) - } - - if len(services) == 0 { - r.Fatalf("Bad: %v", services) - } - - if services[0].Datacenter != "dc1" { - r.Fatalf("Bad datacenter: %v", services[0]) - } - }) -} - -func TestAPI_CatalogService_NodeMetaFilter(t *testing.T) { - t.Parallel() - meta := map[string]string{"somekey": "somevalue"} - c, s := makeClientWithConfig(t, nil, func(conf *testutil.TestServerConfig) { - conf.NodeMeta = meta - }) - defer s.Stop() - - catalog := c.Catalog() - retry.Run(t, func(r *retry.R) { - services, meta, err := catalog.Service("consul", "", &QueryOptions{NodeMeta: meta}) - if err != nil { - r.Fatal(err) - } - - if meta.LastIndex == 0 { - r.Fatalf("Bad: %v", meta) - } - - if len(services) == 0 { - r.Fatalf("Bad: %v", services) - } - - if services[0].Datacenter != "dc1" { - r.Fatalf("Bad datacenter: %v", services[0]) - } - }) -} - -func TestAPI_CatalogNode(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - catalog := c.Catalog() - name, _ := c.Agent().NodeName() - retry.Run(t, func(r *retry.R) { - info, meta, err := catalog.Node(name, nil) - if err != nil { - r.Fatal(err) - } - - if meta.LastIndex == 0 { - r.Fatalf("Bad: %v", meta) - } - - if len(info.Services) == 0 { - r.Fatalf("Bad: %v", info) - } - - if _, ok := info.Node.TaggedAddresses["wan"]; !ok { - r.Fatalf("Bad: %v", info) - } - - if info.Node.Datacenter != "dc1" { - r.Fatalf("Bad datacenter: %v", info) - } - }) -} - -func TestAPI_CatalogRegistration(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - catalog := c.Catalog() - - service := &AgentService{ - ID: "redis1", - Service: "redis", - Tags: []string{"master", "v1"}, - Port: 8000, - } - - check := &AgentCheck{ - Node: "foobar", - CheckID: "service:redis1", - Name: "Redis health check", - Notes: "Script based health check", - Status: HealthPassing, - ServiceID: "redis1", - } - - reg := &CatalogRegistration{ - Datacenter: "dc1", - Node: "foobar", - Address: "192.168.10.10", - NodeMeta: map[string]string{"somekey": "somevalue"}, - Service: service, - Check: check, - } - retry.Run(t, func(r *retry.R) { - if _, err := catalog.Register(reg, nil); err != nil { - r.Fatal(err) - } - - node, _, err := catalog.Node("foobar", nil) - if err != nil { - r.Fatal(err) - } - - if _, ok := node.Services["redis1"]; !ok { - r.Fatal("missing service: redis1") - } - - health, _, err := c.Health().Node("foobar", nil) - if err != nil { - r.Fatal(err) - } - - if health[0].CheckID != "service:redis1" { - r.Fatal("missing checkid service:redis1") - } - - if v, ok := node.Node.Meta["somekey"]; !ok || v != "somevalue" { - r.Fatal("missing node meta pair somekey:somevalue") - } - }) - - // Test catalog deregistration of the previously registered service - dereg := &CatalogDeregistration{ - Datacenter: "dc1", - Node: "foobar", - Address: "192.168.10.10", - ServiceID: "redis1", - } - - if _, err := catalog.Deregister(dereg, nil); err != nil { - t.Fatalf("err: %v", err) - } - - retry.Run(t, func(r *retry.R) { - node, _, err := catalog.Node("foobar", nil) - if err != nil { - r.Fatal(err) - } - - if _, ok := node.Services["redis1"]; ok { - r.Fatal("ServiceID:redis1 is not deregistered") - } - }) - - // Test deregistration of the previously registered check - dereg = &CatalogDeregistration{ - Datacenter: "dc1", - Node: "foobar", - Address: "192.168.10.10", - CheckID: "service:redis1", - } - - if _, err := catalog.Deregister(dereg, nil); err != nil { - t.Fatalf("err: %v", err) - } - - retry.Run(t, func(r *retry.R) { - health, _, err := c.Health().Node("foobar", nil) - if err != nil { - r.Fatal(err) - } - - if len(health) != 0 { - r.Fatal("CheckID:service:redis1 is not deregistered") - } - }) - - // Test node deregistration of the previously registered node - dereg = &CatalogDeregistration{ - Datacenter: "dc1", - Node: "foobar", - Address: "192.168.10.10", - } - - if _, err := catalog.Deregister(dereg, nil); err != nil { - t.Fatalf("err: %v", err) - } - - retry.Run(t, func(r *retry.R) { - node, _, err := catalog.Node("foobar", nil) - if err != nil { - r.Fatal(err) - } - - if node != nil { - r.Fatalf("node is not deregistered: %v", node) - } - }) -} - -func TestAPI_CatalogEnableTagOverride(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - catalog := c.Catalog() - - service := &AgentService{ - ID: "redis1", - Service: "redis", - Tags: []string{"master", "v1"}, - Port: 8000, - } - - reg := &CatalogRegistration{ - Datacenter: "dc1", - Node: "foobar", - Address: "192.168.10.10", - Service: service, - } - - retry.Run(t, func(r *retry.R) { - if _, err := catalog.Register(reg, nil); err != nil { - r.Fatal(err) - } - - node, _, err := catalog.Node("foobar", nil) - if err != nil { - r.Fatal(err) - } - - if _, ok := node.Services["redis1"]; !ok { - r.Fatal("missing service: redis1") - } - if node.Services["redis1"].EnableTagOverride != false { - r.Fatal("tag override set") - } - - services, _, err := catalog.Service("redis", "", nil) - if err != nil { - r.Fatal(err) - } - - if len(services) < 1 || services[0].ServiceName != "redis" { - r.Fatal("missing service: redis") - } - if services[0].ServiceEnableTagOverride != false { - r.Fatal("tag override set") - } - }) - - service.EnableTagOverride = true - - retry.Run(t, func(r *retry.R) { - if _, err := catalog.Register(reg, nil); err != nil { - r.Fatal(err) - } - - node, _, err := catalog.Node("foobar", nil) - if err != nil { - r.Fatal(err) - } - - if _, ok := node.Services["redis1"]; !ok { - r.Fatal("missing service: redis1") - } - if node.Services["redis1"].EnableTagOverride != true { - r.Fatal("tag override not set") - } - - services, _, err := catalog.Service("redis", "", nil) - if err != nil { - r.Fatal(err) - } - - if len(services) < 1 || services[0].ServiceName != "redis" { - r.Fatal("missing service: redis") - } - if services[0].ServiceEnableTagOverride != true { - r.Fatal("tag override not set") - } - }) -} diff --git a/vendor/github.com/hashicorp/consul/api/coordinate_test.go b/vendor/github.com/hashicorp/consul/api/coordinate_test.go deleted file mode 100644 index f41756b57..000000000 --- a/vendor/github.com/hashicorp/consul/api/coordinate_test.go +++ /dev/null @@ -1,44 +0,0 @@ -package api - -import ( - "testing" - - "github.com/hashicorp/consul/testutil/retry" -) - -func TestAPI_CoordinateDatacenters(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - coordinate := c.Coordinate() - retry.Run(t, func(r *retry.R) { - datacenters, err := coordinate.Datacenters() - if err != nil { - r.Fatal(err) - } - - if len(datacenters) == 0 { - r.Fatalf("Bad: %v", datacenters) - } - }) -} - -func TestAPI_CoordinateNodes(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - coordinate := c.Coordinate() - retry.Run(t, func(r *retry.R) { - _, _, err := coordinate.Nodes(nil) - if err != nil { - r.Fatal(err) - } - - // There's not a good way to populate coordinates without - // waiting for them to calculate and update, so the best - // we can do is call the endpoint and make sure we don't - // get an error. - }) -} diff --git a/vendor/github.com/hashicorp/consul/api/event_test.go b/vendor/github.com/hashicorp/consul/api/event_test.go deleted file mode 100644 index 1459590e0..000000000 --- a/vendor/github.com/hashicorp/consul/api/event_test.go +++ /dev/null @@ -1,50 +0,0 @@ -package api - -import ( - "testing" - - "github.com/hashicorp/consul/testutil/retry" -) - -func TestAPI_EventFireList(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - event := c.Event() - - params := &UserEvent{Name: "foo"} - id, meta, err := event.Fire(params, nil) - if err != nil { - t.Fatalf("err: %v", err) - } - - if meta.RequestTime == 0 { - t.Fatalf("bad: %v", meta) - } - - if id == "" { - t.Fatalf("invalid: %v", id) - } - - var events []*UserEvent - var qm *QueryMeta - - retry.Run(t, func(r *retry.R) { - events, qm, err = event.List("", nil) - if err != nil { - r.Fatalf("err: %v", err) - } - if len(events) <= 0 { - r.Fatal(err) - } - }) - - if events[len(events)-1].ID != id { - t.Fatalf("bad: %#v", events) - } - - if qm.LastIndex != event.IDToIndex(id) { - t.Fatalf("Bad: %#v", qm) - } -} diff --git a/vendor/github.com/hashicorp/consul/api/health_test.go b/vendor/github.com/hashicorp/consul/api/health_test.go deleted file mode 100644 index 9cbb55e21..000000000 --- a/vendor/github.com/hashicorp/consul/api/health_test.go +++ /dev/null @@ -1,354 +0,0 @@ -package api - -import ( - "fmt" - "testing" - - "github.com/hashicorp/consul/testutil" - "github.com/hashicorp/consul/testutil/retry" - "github.com/pascaldekloe/goe/verify" -) - -func TestAPI_HealthNode(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - agent := c.Agent() - health := c.Health() - - info, err := agent.Self() - if err != nil { - t.Fatalf("err: %v", err) - } - name := info["Config"]["NodeName"].(string) - retry.Run(t, func(r *retry.R) { - checks, meta, err := health.Node(name, nil) - if err != nil { - r.Fatal(err) - } - if meta.LastIndex == 0 { - r.Fatalf("bad: %v", meta) - } - if len(checks) == 0 { - r.Fatalf("bad: %v", checks) - } - }) -} - -func TestAPI_HealthChecks_AggregatedStatus(t *testing.T) { - t.Parallel() - - cases := []struct { - name string - checks HealthChecks - exp string - }{ - { - "empty", - nil, - HealthPassing, - }, - { - "passing", - HealthChecks{ - &HealthCheck{ - Status: HealthPassing, - }, - }, - HealthPassing, - }, - { - "warning", - HealthChecks{ - &HealthCheck{ - Status: HealthWarning, - }, - }, - HealthWarning, - }, - { - "critical", - HealthChecks{ - &HealthCheck{ - Status: HealthCritical, - }, - }, - HealthCritical, - }, - { - "node_maintenance", - HealthChecks{ - &HealthCheck{ - CheckID: NodeMaint, - }, - }, - HealthMaint, - }, - { - "service_maintenance", - HealthChecks{ - &HealthCheck{ - CheckID: ServiceMaintPrefix + "service", - }, - }, - HealthMaint, - }, - { - "unknown", - HealthChecks{ - &HealthCheck{ - Status: "nope-nope-noper", - }, - }, - "", - }, - { - "maintenance_over_critical", - HealthChecks{ - &HealthCheck{ - CheckID: NodeMaint, - }, - &HealthCheck{ - Status: HealthCritical, - }, - }, - HealthMaint, - }, - { - "critical_over_warning", - HealthChecks{ - &HealthCheck{ - Status: HealthCritical, - }, - &HealthCheck{ - Status: HealthWarning, - }, - }, - HealthCritical, - }, - { - "warning_over_passing", - HealthChecks{ - &HealthCheck{ - Status: HealthWarning, - }, - &HealthCheck{ - Status: HealthPassing, - }, - }, - HealthWarning, - }, - { - "lots", - HealthChecks{ - &HealthCheck{ - Status: HealthPassing, - }, - &HealthCheck{ - Status: HealthPassing, - }, - &HealthCheck{ - Status: HealthPassing, - }, - &HealthCheck{ - Status: HealthWarning, - }, - }, - HealthWarning, - }, - } - - for i, tc := range cases { - t.Run(fmt.Sprintf("%d_%s", i, tc.name), func(t *testing.T) { - act := tc.checks.AggregatedStatus() - if tc.exp != act { - t.Errorf("\nexp: %#v\nact: %#v", tc.exp, act) - } - }) - } -} - -func TestAPI_HealthChecks(t *testing.T) { - t.Parallel() - c, s := makeClientWithConfig(t, nil, func(conf *testutil.TestServerConfig) { - conf.NodeName = "node123" - }) - defer s.Stop() - - agent := c.Agent() - health := c.Health() - - // Make a service with a check - reg := &AgentServiceRegistration{ - Name: "foo", - Tags: []string{"bar"}, - Check: &AgentServiceCheck{ - TTL: "15s", - }, - } - if err := agent.ServiceRegister(reg); err != nil { - t.Fatalf("err: %v", err) - } - defer agent.ServiceDeregister("foo") - - retry.Run(t, func(r *retry.R) { - checks := HealthChecks{ - &HealthCheck{ - Node: "node123", - CheckID: "service:foo", - Name: "Service 'foo' check", - Status: "critical", - ServiceID: "foo", - ServiceName: "foo", - ServiceTags: []string{"bar"}, - }, - } - - out, meta, err := health.Checks("foo", nil) - if err != nil { - r.Fatal(err) - } - if meta.LastIndex == 0 { - r.Fatalf("bad: %v", meta) - } - if got, want := out, checks; !verify.Values(t, "checks", got, want) { - r.Fatal("health.Checks failed") - } - }) -} - -func TestAPI_HealthChecks_NodeMetaFilter(t *testing.T) { - t.Parallel() - meta := map[string]string{"somekey": "somevalue"} - c, s := makeClientWithConfig(t, nil, func(conf *testutil.TestServerConfig) { - conf.NodeMeta = meta - }) - defer s.Stop() - - agent := c.Agent() - health := c.Health() - - // Make a service with a check - reg := &AgentServiceRegistration{ - Name: "foo", - Check: &AgentServiceCheck{ - TTL: "15s", - }, - } - if err := agent.ServiceRegister(reg); err != nil { - t.Fatalf("err: %v", err) - } - defer agent.ServiceDeregister("foo") - - retry.Run(t, func(r *retry.R) { - checks, meta, err := health.Checks("foo", &QueryOptions{NodeMeta: meta}) - if err != nil { - r.Fatal(err) - } - if meta.LastIndex == 0 { - r.Fatalf("bad: %v", meta) - } - if len(checks) == 0 { - r.Fatalf("Bad: %v", checks) - } - }) -} - -func TestAPI_HealthService(t *testing.T) { - c, s := makeClient(t) - defer s.Stop() - - health := c.Health() - retry.Run(t, func(r *retry.R) { - // consul service should always exist... - checks, meta, err := health.Service("consul", "", true, nil) - if err != nil { - r.Fatal(err) - } - if meta.LastIndex == 0 { - r.Fatalf("bad: %v", meta) - } - if len(checks) == 0 { - r.Fatalf("Bad: %v", checks) - } - if _, ok := checks[0].Node.TaggedAddresses["wan"]; !ok { - r.Fatalf("Bad: %v", checks[0].Node) - } - if checks[0].Node.Datacenter != "dc1" { - r.Fatalf("Bad datacenter: %v", checks[0].Node) - } - }) -} - -func TestAPI_HealthService_NodeMetaFilter(t *testing.T) { - meta := map[string]string{"somekey": "somevalue"} - c, s := makeClientWithConfig(t, nil, func(conf *testutil.TestServerConfig) { - conf.NodeMeta = meta - }) - defer s.Stop() - - health := c.Health() - retry.Run(t, func(r *retry.R) { - // consul service should always exist... - checks, meta, err := health.Service("consul", "", true, &QueryOptions{NodeMeta: meta}) - if err != nil { - r.Fatal(err) - } - if meta.LastIndex == 0 { - r.Fatalf("bad: %v", meta) - } - if len(checks) == 0 { - r.Fatalf("Bad: %v", checks) - } - if _, ok := checks[0].Node.TaggedAddresses["wan"]; !ok { - r.Fatalf("Bad: %v", checks[0].Node) - } - if checks[0].Node.Datacenter != "dc1" { - r.Fatalf("Bad datacenter: %v", checks[0].Node) - } - }) -} - -func TestAPI_HealthState(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - health := c.Health() - retry.Run(t, func(r *retry.R) { - checks, meta, err := health.State("any", nil) - if err != nil { - r.Fatal(err) - } - if meta.LastIndex == 0 { - r.Fatalf("bad: %v", meta) - } - if len(checks) == 0 { - r.Fatalf("Bad: %v", checks) - } - }) -} - -func TestAPI_HealthState_NodeMetaFilter(t *testing.T) { - t.Parallel() - meta := map[string]string{"somekey": "somevalue"} - c, s := makeClientWithConfig(t, nil, func(conf *testutil.TestServerConfig) { - conf.NodeMeta = meta - }) - defer s.Stop() - - health := c.Health() - retry.Run(t, func(r *retry.R) { - checks, meta, err := health.State("any", &QueryOptions{NodeMeta: meta}) - if err != nil { - r.Fatal(err) - } - if meta.LastIndex == 0 { - r.Fatalf("bad: %v", meta) - } - if len(checks) == 0 { - r.Fatalf("Bad: %v", checks) - } - }) -} diff --git a/vendor/github.com/hashicorp/consul/api/kv_test.go b/vendor/github.com/hashicorp/consul/api/kv_test.go deleted file mode 100644 index 1ca6cd794..000000000 --- a/vendor/github.com/hashicorp/consul/api/kv_test.go +++ /dev/null @@ -1,574 +0,0 @@ -package api - -import ( - "bytes" - "path" - "strings" - "testing" - "time" -) - -func TestAPI_ClientPutGetDelete(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - kv := c.KV() - - // Get a get without a key - key := testKey() - pair, _, err := kv.Get(key, nil) - if err != nil { - t.Fatalf("err: %v", err) - } - if pair != nil { - t.Fatalf("unexpected value: %#v", pair) - } - - value := []byte("test") - - // Put a key that begins with a '/', this should fail - invalidKey := "/test" - p := &KVPair{Key: invalidKey, Flags: 42, Value: value} - if _, err := kv.Put(p, nil); err == nil { - t.Fatalf("Invalid key not detected: %s", invalidKey) - } - - // Put the key - p = &KVPair{Key: key, Flags: 42, Value: value} - if _, err := kv.Put(p, nil); err != nil { - t.Fatalf("err: %v", err) - } - - // Get should work - pair, meta, err := kv.Get(key, nil) - if err != nil { - t.Fatalf("err: %v", err) - } - if pair == nil { - t.Fatalf("expected value: %#v", pair) - } - if !bytes.Equal(pair.Value, value) { - t.Fatalf("unexpected value: %#v", pair) - } - if pair.Flags != 42 { - t.Fatalf("unexpected value: %#v", pair) - } - if meta.LastIndex == 0 { - t.Fatalf("unexpected value: %#v", meta) - } - - // Delete - if _, err := kv.Delete(key, nil); err != nil { - t.Fatalf("err: %v", err) - } - - // Get should fail - pair, _, err = kv.Get(key, nil) - if err != nil { - t.Fatalf("err: %v", err) - } - if pair != nil { - t.Fatalf("unexpected value: %#v", pair) - } -} - -func TestAPI_ClientList_DeleteRecurse(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - kv := c.KV() - - // Generate some test keys - prefix := testKey() - var keys []string - for i := 0; i < 100; i++ { - keys = append(keys, path.Join(prefix, testKey())) - } - - // Set values - value := []byte("test") - for _, key := range keys { - p := &KVPair{Key: key, Value: value} - if _, err := kv.Put(p, nil); err != nil { - t.Fatalf("err: %v", err) - } - } - - // List the values - pairs, meta, err := kv.List(prefix, nil) - if err != nil { - t.Fatalf("err: %v", err) - } - if len(pairs) != len(keys) { - t.Fatalf("got %d keys", len(pairs)) - } - for _, pair := range pairs { - if !bytes.Equal(pair.Value, value) { - t.Fatalf("unexpected value: %#v", pair) - } - } - if meta.LastIndex == 0 { - t.Fatalf("unexpected value: %#v", meta) - } - - // Delete all - if _, err := kv.DeleteTree(prefix, nil); err != nil { - t.Fatalf("err: %v", err) - } - - // List the values - pairs, _, err = kv.List(prefix, nil) - if err != nil { - t.Fatalf("err: %v", err) - } - if len(pairs) != 0 { - t.Fatalf("got %d keys", len(pairs)) - } -} - -func TestAPI_ClientDeleteCAS(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - kv := c.KV() - - // Put the key - key := testKey() - value := []byte("test") - p := &KVPair{Key: key, Value: value} - if work, _, err := kv.CAS(p, nil); err != nil { - t.Fatalf("err: %v", err) - } else if !work { - t.Fatalf("CAS failure") - } - - // Get should work - pair, meta, err := kv.Get(key, nil) - if err != nil { - t.Fatalf("err: %v", err) - } - if pair == nil { - t.Fatalf("expected value: %#v", pair) - } - if meta.LastIndex == 0 { - t.Fatalf("unexpected value: %#v", meta) - } - - // CAS update with bad index - p.ModifyIndex = 1 - if work, _, err := kv.DeleteCAS(p, nil); err != nil { - t.Fatalf("err: %v", err) - } else if work { - t.Fatalf("unexpected CAS") - } - - // CAS update with valid index - p.ModifyIndex = meta.LastIndex - if work, _, err := kv.DeleteCAS(p, nil); err != nil { - t.Fatalf("err: %v", err) - } else if !work { - t.Fatalf("unexpected CAS failure") - } -} - -func TestAPI_ClientCAS(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - kv := c.KV() - - // Put the key - key := testKey() - value := []byte("test") - p := &KVPair{Key: key, Value: value} - if work, _, err := kv.CAS(p, nil); err != nil { - t.Fatalf("err: %v", err) - } else if !work { - t.Fatalf("CAS failure") - } - - // Get should work - pair, meta, err := kv.Get(key, nil) - if err != nil { - t.Fatalf("err: %v", err) - } - if pair == nil { - t.Fatalf("expected value: %#v", pair) - } - if meta.LastIndex == 0 { - t.Fatalf("unexpected value: %#v", meta) - } - - // CAS update with bad index - newVal := []byte("foo") - p.Value = newVal - p.ModifyIndex = 1 - if work, _, err := kv.CAS(p, nil); err != nil { - t.Fatalf("err: %v", err) - } else if work { - t.Fatalf("unexpected CAS") - } - - // CAS update with valid index - p.ModifyIndex = meta.LastIndex - if work, _, err := kv.CAS(p, nil); err != nil { - t.Fatalf("err: %v", err) - } else if !work { - t.Fatalf("unexpected CAS failure") - } -} - -func TestAPI_ClientWatchGet(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - kv := c.KV() - - // Get a get without a key - key := testKey() - pair, meta, err := kv.Get(key, nil) - if err != nil { - t.Fatalf("err: %v", err) - } - if pair != nil { - t.Fatalf("unexpected value: %#v", pair) - } - if meta.LastIndex == 0 { - t.Fatalf("unexpected value: %#v", meta) - } - - // Put the key - value := []byte("test") - doneCh := make(chan struct{}) - go func() { - kv := c.KV() - - time.Sleep(100 * time.Millisecond) - p := &KVPair{Key: key, Flags: 42, Value: value} - if _, err := kv.Put(p, nil); err != nil { - t.Fatalf("err: %v", err) - } - doneCh <- struct{}{} - }() - - // Get should work - options := &QueryOptions{WaitIndex: meta.LastIndex} - pair, meta2, err := kv.Get(key, options) - if err != nil { - t.Fatalf("err: %v", err) - } - if pair == nil { - t.Fatalf("expected value: %#v", pair) - } - if !bytes.Equal(pair.Value, value) { - t.Fatalf("unexpected value: %#v", pair) - } - if pair.Flags != 42 { - t.Fatalf("unexpected value: %#v", pair) - } - if meta2.LastIndex <= meta.LastIndex { - t.Fatalf("unexpected value: %#v", meta2) - } - - // Block until put finishes to avoid a race between it and deferred s.Stop() - <-doneCh -} - -func TestAPI_ClientWatchList(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - kv := c.KV() - - // Get a get without a key - prefix := testKey() - key := path.Join(prefix, testKey()) - pairs, meta, err := kv.List(prefix, nil) - if err != nil { - t.Fatalf("err: %v", err) - } - if len(pairs) != 0 { - t.Fatalf("unexpected value: %#v", pairs) - } - if meta.LastIndex == 0 { - t.Fatalf("unexpected value: %#v", meta) - } - - // Put the key - value := []byte("test") - doneCh := make(chan struct{}) - go func() { - kv := c.KV() - - time.Sleep(100 * time.Millisecond) - p := &KVPair{Key: key, Flags: 42, Value: value} - if _, err := kv.Put(p, nil); err != nil { - t.Fatalf("err: %v", err) - } - doneCh <- struct{}{} - }() - - // Get should work - options := &QueryOptions{WaitIndex: meta.LastIndex} - pairs, meta2, err := kv.List(prefix, options) - if err != nil { - t.Fatalf("err: %v", err) - } - if len(pairs) != 1 { - t.Fatalf("expected value: %#v", pairs) - } - if !bytes.Equal(pairs[0].Value, value) { - t.Fatalf("unexpected value: %#v", pairs) - } - if pairs[0].Flags != 42 { - t.Fatalf("unexpected value: %#v", pairs) - } - if meta2.LastIndex <= meta.LastIndex { - t.Fatalf("unexpected value: %#v", meta2) - } - - // Block until put finishes to avoid a race between it and deferred s.Stop() - <-doneCh -} - -func TestAPI_ClientKeys_DeleteRecurse(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - kv := c.KV() - - // Generate some test keys - prefix := testKey() - var keys []string - for i := 0; i < 100; i++ { - keys = append(keys, path.Join(prefix, testKey())) - } - - // Set values - value := []byte("test") - for _, key := range keys { - p := &KVPair{Key: key, Value: value} - if _, err := kv.Put(p, nil); err != nil { - t.Fatalf("err: %v", err) - } - } - - // List the values - out, meta, err := kv.Keys(prefix, "", nil) - if err != nil { - t.Fatalf("err: %v", err) - } - if len(out) != len(keys) { - t.Fatalf("got %d keys", len(out)) - } - if meta.LastIndex == 0 { - t.Fatalf("unexpected value: %#v", meta) - } - - // Delete all - if _, err := kv.DeleteTree(prefix, nil); err != nil { - t.Fatalf("err: %v", err) - } - - // List the values - out, _, err = kv.Keys(prefix, "", nil) - if err != nil { - t.Fatalf("err: %v", err) - } - if len(out) != 0 { - t.Fatalf("got %d keys", len(out)) - } -} - -func TestAPI_ClientAcquireRelease(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - session := c.Session() - kv := c.KV() - - // Make a session - id, _, err := session.CreateNoChecks(nil, nil) - if err != nil { - t.Fatalf("err: %v", err) - } - defer session.Destroy(id, nil) - - // Acquire the key - key := testKey() - value := []byte("test") - p := &KVPair{Key: key, Value: value, Session: id} - if work, _, err := kv.Acquire(p, nil); err != nil { - t.Fatalf("err: %v", err) - } else if !work { - t.Fatalf("Lock failure") - } - - // Get should work - pair, meta, err := kv.Get(key, nil) - if err != nil { - t.Fatalf("err: %v", err) - } - if pair == nil { - t.Fatalf("expected value: %#v", pair) - } - if pair.LockIndex != 1 { - t.Fatalf("Expected lock: %v", pair) - } - if pair.Session != id { - t.Fatalf("Expected lock: %v", pair) - } - if meta.LastIndex == 0 { - t.Fatalf("unexpected value: %#v", meta) - } - - // Release - if work, _, err := kv.Release(p, nil); err != nil { - t.Fatalf("err: %v", err) - } else if !work { - t.Fatalf("Release fail") - } - - // Get should work - pair, meta, err = kv.Get(key, nil) - if err != nil { - t.Fatalf("err: %v", err) - } - if pair == nil { - t.Fatalf("expected value: %#v", pair) - } - if pair.LockIndex != 1 { - t.Fatalf("Expected lock: %v", pair) - } - if pair.Session != "" { - t.Fatalf("Expected unlock: %v", pair) - } - if meta.LastIndex == 0 { - t.Fatalf("unexpected value: %#v", meta) - } -} - -func TestAPI_ClientTxn(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - session := c.Session() - kv := c.KV() - - // Make a session. - id, _, err := session.CreateNoChecks(nil, nil) - if err != nil { - t.Fatalf("err: %v", err) - } - defer session.Destroy(id, nil) - - // Acquire and get the key via a transaction, but don't supply a valid - // session. - key := testKey() - value := []byte("test") - txn := KVTxnOps{ - &KVTxnOp{ - Verb: KVLock, - Key: key, - Value: value, - }, - &KVTxnOp{ - Verb: KVGet, - Key: key, - }, - } - ok, ret, _, err := kv.Txn(txn, nil) - if err != nil { - t.Fatalf("err: %v", err) - } else if ok { - t.Fatalf("transaction should have failed") - } - - if ret == nil || len(ret.Errors) != 2 || len(ret.Results) != 0 { - t.Fatalf("bad: %v", ret) - } - if ret.Errors[0].OpIndex != 0 || - !strings.Contains(ret.Errors[0].What, "missing session") || - !strings.Contains(ret.Errors[1].What, "doesn't exist") { - t.Fatalf("bad: %v", ret.Errors[0]) - } - - // Now poke in a real session and try again. - txn[0].Session = id - ok, ret, _, err = kv.Txn(txn, nil) - if err != nil { - t.Fatalf("err: %v", err) - } else if !ok { - t.Fatalf("transaction failure") - } - - if ret == nil || len(ret.Errors) != 0 || len(ret.Results) != 2 { - t.Fatalf("bad: %v", ret) - } - for i, result := range ret.Results { - var expected []byte - if i == 1 { - expected = value - } - - if result.Key != key || - !bytes.Equal(result.Value, expected) || - result.Session != id || - result.LockIndex != 1 { - t.Fatalf("bad: %v", result) - } - } - - // Run a read-only transaction. - txn = KVTxnOps{ - &KVTxnOp{ - Verb: KVGet, - Key: key, - }, - } - ok, ret, _, err = kv.Txn(txn, nil) - if err != nil { - t.Fatalf("err: %v", err) - } else if !ok { - t.Fatalf("transaction failure") - } - - if ret == nil || len(ret.Errors) != 0 || len(ret.Results) != 1 { - t.Fatalf("bad: %v", ret) - } - for _, result := range ret.Results { - if result.Key != key || - !bytes.Equal(result.Value, value) || - result.Session != id || - result.LockIndex != 1 { - t.Fatalf("bad: %v", result) - } - } - - // Sanity check using the regular GET API. - pair, meta, err := kv.Get(key, nil) - if err != nil { - t.Fatalf("err: %v", err) - } - if pair == nil { - t.Fatalf("expected value: %#v", pair) - } - if pair.LockIndex != 1 { - t.Fatalf("Expected lock: %v", pair) - } - if pair.Session != id { - t.Fatalf("Expected lock: %v", pair) - } - if meta.LastIndex == 0 { - t.Fatalf("unexpected value: %#v", meta) - } -} diff --git a/vendor/github.com/hashicorp/consul/api/lock_test.go b/vendor/github.com/hashicorp/consul/api/lock_test.go deleted file mode 100644 index 560209874..000000000 --- a/vendor/github.com/hashicorp/consul/api/lock_test.go +++ /dev/null @@ -1,560 +0,0 @@ -package api - -import ( - "log" - "net/http" - "net/http/httptest" - "net/http/httputil" - "strings" - "sync" - "testing" - "time" -) - -func TestAPI_LockLockUnlock(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - lock, err := c.LockKey("test/lock") - if err != nil { - t.Fatalf("err: %v", err) - } - - // Initial unlock should fail - err = lock.Unlock() - if err != ErrLockNotHeld { - t.Fatalf("err: %v", err) - } - - // Should work - leaderCh, err := lock.Lock(nil) - if err != nil { - t.Fatalf("err: %v", err) - } - if leaderCh == nil { - t.Fatalf("not leader") - } - - // Double lock should fail - _, err = lock.Lock(nil) - if err != ErrLockHeld { - t.Fatalf("err: %v", err) - } - - // Should be leader - select { - case <-leaderCh: - t.Fatalf("should be leader") - default: - } - - // Initial unlock should work - err = lock.Unlock() - if err != nil { - t.Fatalf("err: %v", err) - } - - // Double unlock should fail - err = lock.Unlock() - if err != ErrLockNotHeld { - t.Fatalf("err: %v", err) - } - - // Should lose leadership - select { - case <-leaderCh: - case <-time.After(time.Second): - t.Fatalf("should not be leader") - } -} - -func TestAPI_LockForceInvalidate(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - lock, err := c.LockKey("test/lock") - if err != nil { - t.Fatalf("err: %v", err) - } - - // Should work - leaderCh, err := lock.Lock(nil) - if err != nil { - t.Fatalf("err: %v", err) - } - if leaderCh == nil { - t.Fatalf("not leader") - } - defer lock.Unlock() - - go func() { - // Nuke the session, simulator an operator invalidation - // or a health check failure - session := c.Session() - session.Destroy(lock.lockSession, nil) - }() - - // Should loose leadership - select { - case <-leaderCh: - case <-time.After(time.Second): - t.Fatalf("should not be leader") - } -} - -func TestAPI_LockDeleteKey(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - // This uncovered some issues around special-case handling of low index - // numbers where it would work with a low number but fail for higher - // ones, so we loop this a bit to sweep the index up out of that - // territory. - for i := 0; i < 10; i++ { - func() { - lock, err := c.LockKey("test/lock") - if err != nil { - t.Fatalf("err: %v", err) - } - - // Should work - leaderCh, err := lock.Lock(nil) - if err != nil { - t.Fatalf("err: %v", err) - } - if leaderCh == nil { - t.Fatalf("not leader") - } - defer lock.Unlock() - - go func() { - // Nuke the key, simulate an operator intervention - kv := c.KV() - kv.Delete("test/lock", nil) - }() - - // Should loose leadership - select { - case <-leaderCh: - case <-time.After(10 * time.Second): - t.Fatalf("should not be leader") - } - }() - } -} - -func TestAPI_LockContend(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - wg := &sync.WaitGroup{} - acquired := make([]bool, 3) - for idx := range acquired { - wg.Add(1) - go func(idx int) { - defer wg.Done() - lock, err := c.LockKey("test/lock") - if err != nil { - t.Fatalf("err: %v", err) - } - - // Should work eventually, will contend - leaderCh, err := lock.Lock(nil) - if err != nil { - t.Fatalf("err: %v", err) - } - if leaderCh == nil { - t.Fatalf("not leader") - } - defer lock.Unlock() - log.Printf("Contender %d acquired", idx) - - // Set acquired and then leave - acquired[idx] = true - }(idx) - } - - // Wait for termination - doneCh := make(chan struct{}) - go func() { - wg.Wait() - close(doneCh) - }() - - // Wait for everybody to get a turn - select { - case <-doneCh: - case <-time.After(3 * DefaultLockRetryTime): - t.Fatalf("timeout") - } - - for idx, did := range acquired { - if !did { - t.Fatalf("contender %d never acquired", idx) - } - } -} - -func TestAPI_LockDestroy(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - lock, err := c.LockKey("test/lock") - if err != nil { - t.Fatalf("err: %v", err) - } - - // Should work - leaderCh, err := lock.Lock(nil) - if err != nil { - t.Fatalf("err: %v", err) - } - if leaderCh == nil { - t.Fatalf("not leader") - } - - // Destroy should fail - if err := lock.Destroy(); err != ErrLockHeld { - t.Fatalf("err: %v", err) - } - - // Should be able to release - err = lock.Unlock() - if err != nil { - t.Fatalf("err: %v", err) - } - - // Acquire with a different lock - l2, err := c.LockKey("test/lock") - if err != nil { - t.Fatalf("err: %v", err) - } - - // Should work - leaderCh, err = l2.Lock(nil) - if err != nil { - t.Fatalf("err: %v", err) - } - if leaderCh == nil { - t.Fatalf("not leader") - } - - // Destroy should still fail - if err := lock.Destroy(); err != ErrLockInUse { - t.Fatalf("err: %v", err) - } - - // Should release - err = l2.Unlock() - if err != nil { - t.Fatalf("err: %v", err) - } - - // Destroy should work - err = lock.Destroy() - if err != nil { - t.Fatalf("err: %v", err) - } - - // Double destroy should work - err = l2.Destroy() - if err != nil { - t.Fatalf("err: %v", err) - } -} - -func TestAPI_LockConflict(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - sema, err := c.SemaphorePrefix("test/lock/", 2) - if err != nil { - t.Fatalf("err: %v", err) - } - - // Should work - lockCh, err := sema.Acquire(nil) - if err != nil { - t.Fatalf("err: %v", err) - } - if lockCh == nil { - t.Fatalf("not hold") - } - defer sema.Release() - - lock, err := c.LockKey("test/lock/.lock") - if err != nil { - t.Fatalf("err: %v", err) - } - - // Should conflict with semaphore - _, err = lock.Lock(nil) - if err != ErrLockConflict { - t.Fatalf("err: %v", err) - } - - // Should conflict with semaphore - err = lock.Destroy() - if err != ErrLockConflict { - t.Fatalf("err: %v", err) - } -} - -func TestAPI_LockReclaimLock(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - session, _, err := c.Session().Create(&SessionEntry{}, nil) - if err != nil { - t.Fatalf("err: %v", err) - } - - lock, err := c.LockOpts(&LockOptions{Key: "test/lock", Session: session}) - if err != nil { - t.Fatalf("err: %v", err) - } - - // Should work - leaderCh, err := lock.Lock(nil) - if err != nil { - t.Fatalf("err: %v", err) - } - if leaderCh == nil { - t.Fatalf("not leader") - } - defer lock.Unlock() - - l2, err := c.LockOpts(&LockOptions{Key: "test/lock", Session: session}) - if err != nil { - t.Fatalf("err: %v", err) - } - - reclaimed := make(chan (<-chan struct{}), 1) - go func() { - l2Ch, err := l2.Lock(nil) - if err != nil { - t.Fatalf("not locked: %v", err) - } - reclaimed <- l2Ch - }() - - // Should reclaim the lock - var leader2Ch <-chan struct{} - - select { - case leader2Ch = <-reclaimed: - case <-time.After(time.Second): - t.Fatalf("should have locked") - } - - // unlock should work - err = l2.Unlock() - if err != nil { - t.Fatalf("err: %v", err) - } - - //Both locks should see the unlock - select { - case <-leader2Ch: - case <-time.After(time.Second): - t.Fatalf("should not be leader") - } - - select { - case <-leaderCh: - case <-time.After(time.Second): - t.Fatalf("should not be leader") - } -} - -func TestAPI_LockMonitorRetry(t *testing.T) { - t.Parallel() - raw, s := makeClient(t) - defer s.Stop() - - // Set up a server that always responds with 500 errors. - failer := func(w http.ResponseWriter, req *http.Request) { - w.WriteHeader(500) - } - outage := httptest.NewServer(http.HandlerFunc(failer)) - defer outage.Close() - - // Set up a reverse proxy that will send some requests to the - // 500 server and pass everything else through to the real Consul - // server. - var mutex sync.Mutex - errors := 0 - director := func(req *http.Request) { - mutex.Lock() - defer mutex.Unlock() - - req.URL.Scheme = "http" - if errors > 0 && req.Method == "GET" && strings.Contains(req.URL.Path, "/v1/kv/test/lock") { - req.URL.Host = outage.URL[7:] // Strip off "http://". - errors-- - } else { - req.URL.Host = raw.config.Address - } - } - proxy := httptest.NewServer(&httputil.ReverseProxy{Director: director}) - defer proxy.Close() - - // Make another client that points at the proxy instead of the real - // Consul server. - config := raw.config - config.Address = proxy.URL[7:] // Strip off "http://". - c, err := NewClient(&config) - if err != nil { - t.Fatalf("err: %v", err) - } - - // Set up a lock with retries enabled. - opts := &LockOptions{ - Key: "test/lock", - SessionTTL: "60s", - MonitorRetries: 3, - } - lock, err := c.LockOpts(opts) - if err != nil { - t.Fatalf("err: %v", err) - } - - // Make sure the default got set. - if lock.opts.MonitorRetryTime != DefaultMonitorRetryTime { - t.Fatalf("bad: %d", lock.opts.MonitorRetryTime) - } - - // Now set a custom time for the test. - opts.MonitorRetryTime = 250 * time.Millisecond - lock, err = c.LockOpts(opts) - if err != nil { - t.Fatalf("err: %v", err) - } - if lock.opts.MonitorRetryTime != 250*time.Millisecond { - t.Fatalf("bad: %d", lock.opts.MonitorRetryTime) - } - - // Should get the lock. - leaderCh, err := lock.Lock(nil) - if err != nil { - t.Fatalf("err: %v", err) - } - if leaderCh == nil { - t.Fatalf("not leader") - } - - // Poke the key using the raw client to force the monitor to wake up - // and check the lock again. This time we will return errors for some - // of the responses. - mutex.Lock() - errors = 2 - mutex.Unlock() - pair, _, err := raw.KV().Get("test/lock", &QueryOptions{}) - if err != nil { - t.Fatalf("err: %v", err) - } - if _, err := raw.KV().Put(pair, &WriteOptions{}); err != nil { - t.Fatalf("err: %v", err) - } - time.Sleep(5 * opts.MonitorRetryTime) - - // Should still be the leader. - select { - case <-leaderCh: - t.Fatalf("should be leader") - default: - } - - // Now return an overwhelming number of errors. - mutex.Lock() - errors = 10 - mutex.Unlock() - if _, err := raw.KV().Put(pair, &WriteOptions{}); err != nil { - t.Fatalf("err: %v", err) - } - time.Sleep(5 * opts.MonitorRetryTime) - - // Should lose leadership. - select { - case <-leaderCh: - case <-time.After(time.Second): - t.Fatalf("should not be leader") - } -} - -func TestAPI_LockOneShot(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - // Set up a lock as a one-shot. - opts := &LockOptions{ - Key: "test/lock", - LockTryOnce: true, - } - lock, err := c.LockOpts(opts) - if err != nil { - t.Fatalf("err: %v", err) - } - - // Make sure the default got set. - if lock.opts.LockWaitTime != DefaultLockWaitTime { - t.Fatalf("bad: %d", lock.opts.LockWaitTime) - } - - // Now set a custom time for the test. - opts.LockWaitTime = 250 * time.Millisecond - lock, err = c.LockOpts(opts) - if err != nil { - t.Fatalf("err: %v", err) - } - if lock.opts.LockWaitTime != 250*time.Millisecond { - t.Fatalf("bad: %d", lock.opts.LockWaitTime) - } - - // Should get the lock. - ch, err := lock.Lock(nil) - if err != nil { - t.Fatalf("err: %v", err) - } - if ch == nil { - t.Fatalf("not leader") - } - - // Now try with another session. - contender, err := c.LockOpts(opts) - if err != nil { - t.Fatalf("err: %v", err) - } - start := time.Now() - ch, err = contender.Lock(nil) - if err != nil { - t.Fatalf("err: %v", err) - } - if ch != nil { - t.Fatalf("should not be leader") - } - diff := time.Now().Sub(start) - if diff < contender.opts.LockWaitTime || diff > 2*contender.opts.LockWaitTime { - t.Fatalf("time out of bounds: %9.6f", diff.Seconds()) - } - - // Unlock and then make sure the contender can get it. - if err := lock.Unlock(); err != nil { - t.Fatalf("err: %v", err) - } - ch, err = contender.Lock(nil) - if err != nil { - t.Fatalf("err: %v", err) - } - if ch == nil { - t.Fatalf("should be leader") - } -} diff --git a/vendor/github.com/hashicorp/consul/api/operator_autopilot_test.go b/vendor/github.com/hashicorp/consul/api/operator_autopilot_test.go deleted file mode 100644 index 9b84b9b4e..000000000 --- a/vendor/github.com/hashicorp/consul/api/operator_autopilot_test.go +++ /dev/null @@ -1,104 +0,0 @@ -package api - -import ( - "testing" - - "github.com/hashicorp/consul/testutil" - "github.com/hashicorp/consul/testutil/retry" -) - -func TestAPI_OperatorAutopilotGetSetConfiguration(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - operator := c.Operator() - config, err := operator.AutopilotGetConfiguration(nil) - if err != nil { - t.Fatalf("err: %v", err) - } - if !config.CleanupDeadServers { - t.Fatalf("bad: %v", config) - } - - // Change a config setting - newConf := &AutopilotConfiguration{CleanupDeadServers: false} - if err := operator.AutopilotSetConfiguration(newConf, nil); err != nil { - t.Fatalf("err: %v", err) - } - - config, err = operator.AutopilotGetConfiguration(nil) - if err != nil { - t.Fatalf("err: %v", err) - } - if config.CleanupDeadServers { - t.Fatalf("bad: %v", config) - } -} - -func TestAPI_OperatorAutopilotCASConfiguration(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - operator := c.Operator() - config, err := operator.AutopilotGetConfiguration(nil) - if err != nil { - t.Fatalf("err: %v", err) - } - if !config.CleanupDeadServers { - t.Fatalf("bad: %v", config) - } - - // Pass an invalid ModifyIndex - { - newConf := &AutopilotConfiguration{ - CleanupDeadServers: false, - ModifyIndex: config.ModifyIndex - 1, - } - resp, err := operator.AutopilotCASConfiguration(newConf, nil) - if err != nil { - t.Fatalf("err: %v", err) - } - if resp { - t.Fatalf("bad: %v", resp) - } - } - - // Pass a valid ModifyIndex - { - newConf := &AutopilotConfiguration{ - CleanupDeadServers: false, - ModifyIndex: config.ModifyIndex, - } - resp, err := operator.AutopilotCASConfiguration(newConf, nil) - if err != nil { - t.Fatalf("err: %v", err) - } - if !resp { - t.Fatalf("bad: %v", resp) - } - } -} - -func TestAPI_OperatorAutopilotServerHealth(t *testing.T) { - t.Parallel() - c, s := makeClientWithConfig(t, nil, func(c *testutil.TestServerConfig) { - c.RaftProtocol = 3 - }) - defer s.Stop() - - operator := c.Operator() - retry.Run(t, func(r *retry.R) { - out, err := operator.AutopilotServerHealth(nil) - if err != nil { - r.Fatalf("err: %v", err) - } - - if len(out.Servers) != 1 || - !out.Servers[0].Healthy || - out.Servers[0].Name != s.Config.NodeName { - r.Fatalf("bad: %v", out) - } - }) -} diff --git a/vendor/github.com/hashicorp/consul/api/operator_keyring_test.go b/vendor/github.com/hashicorp/consul/api/operator_keyring_test.go deleted file mode 100644 index e877170fe..000000000 --- a/vendor/github.com/hashicorp/consul/api/operator_keyring_test.go +++ /dev/null @@ -1,73 +0,0 @@ -package api - -import ( - "testing" - - "github.com/hashicorp/consul/testutil" -) - -func TestAPI_OperatorKeyringInstallListPutRemove(t *testing.T) { - oldKey := "d8wu8CSUrqgtjVsvcBPmhQ==" - newKey := "qxycTi/SsePj/TZzCBmNXw==" - t.Parallel() - c, s := makeClientWithConfig(t, nil, func(c *testutil.TestServerConfig) { - c.Encrypt = oldKey - }) - defer s.Stop() - - operator := c.Operator() - if err := operator.KeyringInstall(newKey, nil); err != nil { - t.Fatalf("err: %v", err) - } - - listResponses, err := operator.KeyringList(nil) - if err != nil { - t.Fatalf("err %v", err) - } - - // Make sure the new key is installed - if len(listResponses) != 2 { - t.Fatalf("bad: %v", len(listResponses)) - } - for _, response := range listResponses { - if len(response.Keys) != 2 { - t.Fatalf("bad: %v", len(response.Keys)) - } - if _, ok := response.Keys[oldKey]; !ok { - t.Fatalf("bad: %v", ok) - } - if _, ok := response.Keys[newKey]; !ok { - t.Fatalf("bad: %v", ok) - } - } - - // Switch the primary to the new key - if err := operator.KeyringUse(newKey, nil); err != nil { - t.Fatalf("err: %v", err) - } - - if err := operator.KeyringRemove(oldKey, nil); err != nil { - t.Fatalf("err: %v", err) - } - - listResponses, err = operator.KeyringList(nil) - if err != nil { - t.Fatalf("err %v", err) - } - - // Make sure the old key is removed - if len(listResponses) != 2 { - t.Fatalf("bad: %v", len(listResponses)) - } - for _, response := range listResponses { - if len(response.Keys) != 1 { - t.Fatalf("bad: %v", len(response.Keys)) - } - if _, ok := response.Keys[oldKey]; ok { - t.Fatalf("bad: %v", ok) - } - if _, ok := response.Keys[newKey]; !ok { - t.Fatalf("bad: %v", ok) - } - } -} diff --git a/vendor/github.com/hashicorp/consul/api/operator_raft_test.go b/vendor/github.com/hashicorp/consul/api/operator_raft_test.go deleted file mode 100644 index a6eada42c..000000000 --- a/vendor/github.com/hashicorp/consul/api/operator_raft_test.go +++ /dev/null @@ -1,38 +0,0 @@ -package api - -import ( - "strings" - "testing" -) - -func TestAPI_OperatorRaftGetConfiguration(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - operator := c.Operator() - out, err := operator.RaftGetConfiguration(nil) - if err != nil { - t.Fatalf("err: %v", err) - } - if len(out.Servers) != 1 || - !out.Servers[0].Leader || - !out.Servers[0].Voter { - t.Fatalf("bad: %v", out) - } -} - -func TestAPI_OperatorRaftRemovePeerByAddress(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - // If we get this error, it proves we sent the address all the way - // through. - operator := c.Operator() - err := operator.RaftRemovePeerByAddress("nope", nil) - if err == nil || !strings.Contains(err.Error(), - "address \"nope\" was not found in the Raft configuration") { - t.Fatalf("err: %v", err) - } -} diff --git a/vendor/github.com/hashicorp/consul/api/prepared_query_test.go b/vendor/github.com/hashicorp/consul/api/prepared_query_test.go deleted file mode 100644 index f06218001..000000000 --- a/vendor/github.com/hashicorp/consul/api/prepared_query_test.go +++ /dev/null @@ -1,133 +0,0 @@ -package api - -import ( - "reflect" - "testing" - - "github.com/hashicorp/consul/testutil/retry" -) - -func TestAPI_PreparedQuery(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - // Set up a node and a service. - reg := &CatalogRegistration{ - Datacenter: "dc1", - Node: "foobar", - Address: "192.168.10.10", - TaggedAddresses: map[string]string{ - "wan": "127.0.0.1", - }, - NodeMeta: map[string]string{"somekey": "somevalue"}, - Service: &AgentService{ - ID: "redis1", - Service: "redis", - Tags: []string{"master", "v1"}, - Port: 8000, - }, - } - - catalog := c.Catalog() - retry.Run(t, func(r *retry.R) { - if _, err := catalog.Register(reg, nil); err != nil { - r.Fatal(err) - } - if _, _, err := catalog.Node("foobar", nil); err != nil { - r.Fatal(err) - } - }) - - // Create a simple prepared query. - def := &PreparedQueryDefinition{ - Name: "test", - Service: ServiceQuery{ - Service: "redis", - NodeMeta: map[string]string{"somekey": "somevalue"}, - }, - } - - query := c.PreparedQuery() - var err error - def.ID, _, err = query.Create(def, nil) - if err != nil { - t.Fatalf("err: %s", err) - } - - // Read it back. - defs, _, err := query.Get(def.ID, nil) - if err != nil { - t.Fatalf("err: %s", err) - } - if len(defs) != 1 || !reflect.DeepEqual(defs[0], def) { - t.Fatalf("bad: %v", defs) - } - - // List them all. - defs, _, err = query.List(nil) - if err != nil { - t.Fatalf("err: %s", err) - } - if len(defs) != 1 || !reflect.DeepEqual(defs[0], def) { - t.Fatalf("bad: %v", defs) - } - - // Make an update. - def.Name = "my-query" - _, err = query.Update(def, nil) - if err != nil { - t.Fatalf("err: %s", err) - } - - // Read it back again to verify the update worked. - defs, _, err = query.Get(def.ID, nil) - if err != nil { - t.Fatalf("err: %s", err) - } - if len(defs) != 1 || !reflect.DeepEqual(defs[0], def) { - t.Fatalf("bad: %v", defs) - } - - // Execute by ID. - results, _, err := query.Execute(def.ID, nil) - if err != nil { - t.Fatalf("err: %s", err) - } - if len(results.Nodes) != 1 || results.Nodes[0].Node.Node != "foobar" { - t.Fatalf("bad: %v", results) - } - if wan, ok := results.Nodes[0].Node.TaggedAddresses["wan"]; !ok || wan != "127.0.0.1" { - t.Fatalf("bad: %v", results) - } - - // Execute by name. - results, _, err = query.Execute("my-query", nil) - if err != nil { - t.Fatalf("err: %s", err) - } - if len(results.Nodes) != 1 || results.Nodes[0].Node.Node != "foobar" { - t.Fatalf("bad: %v", results) - } - if wan, ok := results.Nodes[0].Node.TaggedAddresses["wan"]; !ok || wan != "127.0.0.1" { - t.Fatalf("bad: %v", results) - } - if results.Nodes[0].Node.Datacenter != "dc1" { - t.Fatalf("bad datacenter: %v", results) - } - - // Delete it. - _, err = query.Delete(def.ID, nil) - if err != nil { - t.Fatalf("err: %s", err) - } - - // Make sure there are no longer any queries. - defs, _, err = query.List(nil) - if err != nil { - t.Fatalf("err: %s", err) - } - if len(defs) != 0 { - t.Fatalf("bad: %v", defs) - } -} diff --git a/vendor/github.com/hashicorp/consul/api/semaphore_test.go b/vendor/github.com/hashicorp/consul/api/semaphore_test.go deleted file mode 100644 index 598be024c..000000000 --- a/vendor/github.com/hashicorp/consul/api/semaphore_test.go +++ /dev/null @@ -1,518 +0,0 @@ -package api - -import ( - "log" - "net/http" - "net/http/httptest" - "net/http/httputil" - "strings" - "sync" - "testing" - "time" -) - -func TestAPI_SemaphoreAcquireRelease(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - sema, err := c.SemaphorePrefix("test/semaphore", 2) - if err != nil { - t.Fatalf("err: %v", err) - } - - // Initial release should fail - err = sema.Release() - if err != ErrSemaphoreNotHeld { - t.Fatalf("err: %v", err) - } - - // Should work - lockCh, err := sema.Acquire(nil) - if err != nil { - t.Fatalf("err: %v", err) - } - if lockCh == nil { - t.Fatalf("not hold") - } - - // Double lock should fail - _, err = sema.Acquire(nil) - if err != ErrSemaphoreHeld { - t.Fatalf("err: %v", err) - } - - // Should be held - select { - case <-lockCh: - t.Fatalf("should be held") - default: - } - - // Initial release should work - err = sema.Release() - if err != nil { - t.Fatalf("err: %v", err) - } - - // Double unlock should fail - err = sema.Release() - if err != ErrSemaphoreNotHeld { - t.Fatalf("err: %v", err) - } - - // Should lose resource - select { - case <-lockCh: - case <-time.After(time.Second): - t.Fatalf("should not be held") - } -} - -func TestAPI_SemaphoreForceInvalidate(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - sema, err := c.SemaphorePrefix("test/semaphore", 2) - if err != nil { - t.Fatalf("err: %v", err) - } - - // Should work - lockCh, err := sema.Acquire(nil) - if err != nil { - t.Fatalf("err: %v", err) - } - if lockCh == nil { - t.Fatalf("not acquired") - } - defer sema.Release() - - go func() { - // Nuke the session, simulator an operator invalidation - // or a health check failure - session := c.Session() - session.Destroy(sema.lockSession, nil) - }() - - // Should loose slot - select { - case <-lockCh: - case <-time.After(time.Second): - t.Fatalf("should not be locked") - } -} - -func TestAPI_SemaphoreDeleteKey(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - sema, err := c.SemaphorePrefix("test/semaphore", 2) - if err != nil { - t.Fatalf("err: %v", err) - } - - // Should work - lockCh, err := sema.Acquire(nil) - if err != nil { - t.Fatalf("err: %v", err) - } - if lockCh == nil { - t.Fatalf("not locked") - } - defer sema.Release() - - go func() { - // Nuke the key, simulate an operator intervention - kv := c.KV() - kv.DeleteTree("test/semaphore", nil) - }() - - // Should loose leadership - select { - case <-lockCh: - case <-time.After(time.Second): - t.Fatalf("should not be locked") - } -} - -func TestAPI_SemaphoreContend(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - wg := &sync.WaitGroup{} - acquired := make([]bool, 4) - for idx := range acquired { - wg.Add(1) - go func(idx int) { - defer wg.Done() - sema, err := c.SemaphorePrefix("test/semaphore", 2) - if err != nil { - t.Fatalf("err: %v", err) - } - - // Should work eventually, will contend - lockCh, err := sema.Acquire(nil) - if err != nil { - t.Fatalf("err: %v", err) - } - if lockCh == nil { - t.Fatalf("not locked") - } - defer sema.Release() - log.Printf("Contender %d acquired", idx) - - // Set acquired and then leave - acquired[idx] = true - }(idx) - } - - // Wait for termination - doneCh := make(chan struct{}) - go func() { - wg.Wait() - close(doneCh) - }() - - // Wait for everybody to get a turn - select { - case <-doneCh: - case <-time.After(3 * DefaultLockRetryTime): - t.Fatalf("timeout") - } - - for idx, did := range acquired { - if !did { - t.Fatalf("contender %d never acquired", idx) - } - } -} - -func TestAPI_SemaphoreBadLimit(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - sema, err := c.SemaphorePrefix("test/semaphore", 0) - if err == nil { - t.Fatalf("should error") - } - - sema, err = c.SemaphorePrefix("test/semaphore", 1) - if err != nil { - t.Fatalf("err: %v", err) - } - - _, err = sema.Acquire(nil) - if err != nil { - t.Fatalf("err: %v", err) - } - - sema2, err := c.SemaphorePrefix("test/semaphore", 2) - if err != nil { - t.Fatalf("err: %v", err) - } - - _, err = sema2.Acquire(nil) - if err.Error() != "semaphore limit conflict (lock: 1, local: 2)" { - t.Fatalf("err: %v", err) - } -} - -func TestAPI_SemaphoreDestroy(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - sema, err := c.SemaphorePrefix("test/semaphore", 2) - if err != nil { - t.Fatalf("err: %v", err) - } - - sema2, err := c.SemaphorePrefix("test/semaphore", 2) - if err != nil { - t.Fatalf("err: %v", err) - } - - _, err = sema.Acquire(nil) - if err != nil { - t.Fatalf("err: %v", err) - } - - _, err = sema2.Acquire(nil) - if err != nil { - t.Fatalf("err: %v", err) - } - - // Destroy should fail, still held - if err := sema.Destroy(); err != ErrSemaphoreHeld { - t.Fatalf("err: %v", err) - } - - err = sema.Release() - if err != nil { - t.Fatalf("err: %v", err) - } - - // Destroy should fail, still in use - if err := sema.Destroy(); err != ErrSemaphoreInUse { - t.Fatalf("err: %v", err) - } - - err = sema2.Release() - if err != nil { - t.Fatalf("err: %v", err) - } - - // Destroy should work - if err := sema.Destroy(); err != nil { - t.Fatalf("err: %v", err) - } - - // Destroy should work - if err := sema2.Destroy(); err != nil { - t.Fatalf("err: %v", err) - } -} - -func TestAPI_SemaphoreConflict(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - lock, err := c.LockKey("test/sema/.lock") - if err != nil { - t.Fatalf("err: %v", err) - } - - // Should work - leaderCh, err := lock.Lock(nil) - if err != nil { - t.Fatalf("err: %v", err) - } - if leaderCh == nil { - t.Fatalf("not leader") - } - defer lock.Unlock() - - sema, err := c.SemaphorePrefix("test/sema/", 2) - if err != nil { - t.Fatalf("err: %v", err) - } - - // Should conflict with lock - _, err = sema.Acquire(nil) - if err != ErrSemaphoreConflict { - t.Fatalf("err: %v", err) - } - - // Should conflict with lock - err = sema.Destroy() - if err != ErrSemaphoreConflict { - t.Fatalf("err: %v", err) - } -} - -func TestAPI_SemaphoreMonitorRetry(t *testing.T) { - t.Parallel() - raw, s := makeClient(t) - defer s.Stop() - - // Set up a server that always responds with 500 errors. - failer := func(w http.ResponseWriter, req *http.Request) { - w.WriteHeader(500) - } - outage := httptest.NewServer(http.HandlerFunc(failer)) - defer outage.Close() - - // Set up a reverse proxy that will send some requests to the - // 500 server and pass everything else through to the real Consul - // server. - var mutex sync.Mutex - errors := 0 - director := func(req *http.Request) { - mutex.Lock() - defer mutex.Unlock() - - req.URL.Scheme = "http" - if errors > 0 && req.Method == "GET" && strings.Contains(req.URL.Path, "/v1/kv/test/sema/.lock") { - req.URL.Host = outage.URL[7:] // Strip off "http://". - errors-- - } else { - req.URL.Host = raw.config.Address - } - } - proxy := httptest.NewServer(&httputil.ReverseProxy{Director: director}) - defer proxy.Close() - - // Make another client that points at the proxy instead of the real - // Consul server. - config := raw.config - config.Address = proxy.URL[7:] // Strip off "http://". - c, err := NewClient(&config) - if err != nil { - t.Fatalf("err: %v", err) - } - - // Set up a lock with retries enabled. - opts := &SemaphoreOptions{ - Prefix: "test/sema/.lock", - Limit: 2, - SessionTTL: "60s", - MonitorRetries: 3, - } - sema, err := c.SemaphoreOpts(opts) - if err != nil { - t.Fatalf("err: %v", err) - } - - // Make sure the default got set. - if sema.opts.MonitorRetryTime != DefaultMonitorRetryTime { - t.Fatalf("bad: %d", sema.opts.MonitorRetryTime) - } - - // Now set a custom time for the test. - opts.MonitorRetryTime = 250 * time.Millisecond - sema, err = c.SemaphoreOpts(opts) - if err != nil { - t.Fatalf("err: %v", err) - } - if sema.opts.MonitorRetryTime != 250*time.Millisecond { - t.Fatalf("bad: %d", sema.opts.MonitorRetryTime) - } - - // Should get the lock. - ch, err := sema.Acquire(nil) - if err != nil { - t.Fatalf("err: %v", err) - } - if ch == nil { - t.Fatalf("didn't acquire") - } - - // Take the semaphore using the raw client to force the monitor to wake - // up and check the lock again. This time we will return errors for some - // of the responses. - mutex.Lock() - errors = 2 - mutex.Unlock() - another, err := raw.SemaphoreOpts(opts) - if err != nil { - t.Fatalf("err: %v", err) - } - if _, err := another.Acquire(nil); err != nil { - t.Fatalf("err: %v", err) - } - time.Sleep(5 * opts.MonitorRetryTime) - - // Should still have the semaphore. - select { - case <-ch: - t.Fatalf("lost the semaphore") - default: - } - - // Now return an overwhelming number of errors, using the raw client to - // poke the key and get the monitor to run again. - mutex.Lock() - errors = 10 - mutex.Unlock() - if err := another.Release(); err != nil { - t.Fatalf("err: %v", err) - } - time.Sleep(5 * opts.MonitorRetryTime) - - // Should lose the semaphore. - select { - case <-ch: - case <-time.After(time.Second): - t.Fatalf("should not have the semaphore") - } -} - -func TestAPI_SemaphoreOneShot(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - // Set up a semaphore as a one-shot. - opts := &SemaphoreOptions{ - Prefix: "test/sema/.lock", - Limit: 2, - SemaphoreTryOnce: true, - } - sema, err := c.SemaphoreOpts(opts) - if err != nil { - t.Fatalf("err: %v", err) - } - - // Make sure the default got set. - if sema.opts.SemaphoreWaitTime != DefaultSemaphoreWaitTime { - t.Fatalf("bad: %d", sema.opts.SemaphoreWaitTime) - } - - // Now set a custom time for the test. - opts.SemaphoreWaitTime = 250 * time.Millisecond - sema, err = c.SemaphoreOpts(opts) - if err != nil { - t.Fatalf("err: %v", err) - } - if sema.opts.SemaphoreWaitTime != 250*time.Millisecond { - t.Fatalf("bad: %d", sema.opts.SemaphoreWaitTime) - } - - // Should acquire the semaphore. - ch, err := sema.Acquire(nil) - if err != nil { - t.Fatalf("err: %v", err) - } - if ch == nil { - t.Fatalf("should have acquired the semaphore") - } - - // Try with another session. - another, err := c.SemaphoreOpts(opts) - if err != nil { - t.Fatalf("err: %v", err) - } - ch, err = another.Acquire(nil) - if err != nil { - t.Fatalf("err: %v", err) - } - if ch == nil { - t.Fatalf("should have acquired the semaphore") - } - - // Try with a third one that shouldn't get it. - contender, err := c.SemaphoreOpts(opts) - if err != nil { - t.Fatalf("err: %v", err) - } - start := time.Now() - ch, err = contender.Acquire(nil) - if err != nil { - t.Fatalf("err: %v", err) - } - if ch != nil { - t.Fatalf("should not have acquired the semaphore") - } - diff := time.Now().Sub(start) - if diff < contender.opts.SemaphoreWaitTime { - t.Fatalf("time out of bounds: %9.6f", diff.Seconds()) - } - - // Give up a slot and make sure the third one can get it. - if err := another.Release(); err != nil { - t.Fatalf("err: %v", err) - } - ch, err = contender.Acquire(nil) - if err != nil { - t.Fatalf("err: %v", err) - } - if ch == nil { - t.Fatalf("should have acquired the semaphore") - } -} diff --git a/vendor/github.com/hashicorp/consul/api/session_test.go b/vendor/github.com/hashicorp/consul/api/session_test.go deleted file mode 100644 index 0039bb2e3..000000000 --- a/vendor/github.com/hashicorp/consul/api/session_test.go +++ /dev/null @@ -1,392 +0,0 @@ -package api - -import ( - "context" - "strings" - "testing" - "time" -) - -func TestAPI_SessionCreateDestroy(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - session := c.Session() - - id, meta, err := session.Create(nil, nil) - if err != nil { - t.Fatalf("err: %v", err) - } - - if meta.RequestTime == 0 { - t.Fatalf("bad: %v", meta) - } - - if id == "" { - t.Fatalf("invalid: %v", id) - } - - meta, err = session.Destroy(id, nil) - if err != nil { - t.Fatalf("err: %v", err) - } - - if meta.RequestTime == 0 { - t.Fatalf("bad: %v", meta) - } -} - -func TestAPI_SessionCreateRenewDestroy(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - session := c.Session() - - se := &SessionEntry{ - TTL: "10s", - } - - id, meta, err := session.Create(se, nil) - if err != nil { - t.Fatalf("err: %v", err) - } - defer session.Destroy(id, nil) - - if meta.RequestTime == 0 { - t.Fatalf("bad: %v", meta) - } - - if id == "" { - t.Fatalf("invalid: %v", id) - } - - if meta.RequestTime == 0 { - t.Fatalf("bad: %v", meta) - } - - renew, meta, err := session.Renew(id, nil) - - if err != nil { - t.Fatalf("err: %v", err) - } - if meta.RequestTime == 0 { - t.Fatalf("bad: %v", meta) - } - - if renew == nil { - t.Fatalf("should get session") - } - - if renew.ID != id { - t.Fatalf("should have matching id") - } - - if renew.TTL != "10s" { - t.Fatalf("should get session with TTL") - } -} - -func TestAPI_SessionCreateRenewDestroyRenew(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - session := c.Session() - - entry := &SessionEntry{ - Behavior: SessionBehaviorDelete, - TTL: "500s", // disable ttl - } - - id, meta, err := session.Create(entry, nil) - if err != nil { - t.Fatalf("err: %v", err) - } - - if meta.RequestTime == 0 { - t.Fatalf("bad: %v", meta) - } - - if id == "" { - t.Fatalf("invalid: %v", id) - } - - // Extend right after create. Everything should be fine. - entry, _, err = session.Renew(id, nil) - if err != nil { - t.Fatalf("err: %v", err) - } - if entry == nil { - t.Fatal("session unexpectedly vanished") - } - - // Simulate TTL loss by manually destroying the session. - meta, err = session.Destroy(id, nil) - if err != nil { - t.Fatalf("err: %v", err) - } - - if meta.RequestTime == 0 { - t.Fatalf("bad: %v", meta) - } - - // Extend right after delete. The 404 should proxy as a nil. - entry, _, err = session.Renew(id, nil) - if err != nil { - t.Fatalf("err: %v", err) - } - if entry != nil { - t.Fatal("session still exists") - } -} - -func TestAPI_SessionCreateDestroyRenewPeriodic(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - session := c.Session() - - entry := &SessionEntry{ - Behavior: SessionBehaviorDelete, - TTL: "500s", // disable ttl - } - - id, meta, err := session.Create(entry, nil) - if err != nil { - t.Fatalf("err: %v", err) - } - - if meta.RequestTime == 0 { - t.Fatalf("bad: %v", meta) - } - - if id == "" { - t.Fatalf("invalid: %v", id) - } - - // This only tests Create/Destroy/RenewPeriodic to avoid the more - // difficult case of testing all of the timing code. - - // Simulate TTL loss by manually destroying the session. - meta, err = session.Destroy(id, nil) - if err != nil { - t.Fatalf("err: %v", err) - } - - if meta.RequestTime == 0 { - t.Fatalf("bad: %v", meta) - } - - // Extend right after delete. The 404 should terminate the loop quickly and return ErrSessionExpired. - errCh := make(chan error, 1) - doneCh := make(chan struct{}) - go func() { errCh <- session.RenewPeriodic("1s", id, nil, doneCh) }() - defer close(doneCh) - - select { - case <-time.After(1 * time.Second): - t.Fatal("timedout: missing session did not terminate renewal loop") - case err = <-errCh: - if err != ErrSessionExpired { - t.Fatalf("err: %v", err) - } - } -} - -func TestAPI_SessionRenewPeriodic_Cancel(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - session := c.Session() - entry := &SessionEntry{ - Behavior: SessionBehaviorDelete, - TTL: "500s", // disable ttl - } - - t.Run("done channel", func(t *testing.T) { - id, _, err := session.Create(entry, nil) - if err != nil { - t.Fatalf("err: %v", err) - } - - errCh := make(chan error, 1) - doneCh := make(chan struct{}) - go func() { errCh <- session.RenewPeriodic("1s", id, nil, doneCh) }() - - close(doneCh) - - select { - case <-time.After(1 * time.Second): - t.Fatal("renewal loop didn't terminate") - case err = <-errCh: - if err != nil { - t.Fatalf("err: %v", err) - } - } - - sess, _, err := session.Info(id, nil) - if err != nil { - t.Fatalf("err: %v", err) - } - if sess != nil { - t.Fatalf("session was not expired") - } - }) - - t.Run("context", func(t *testing.T) { - id, _, err := session.Create(entry, nil) - if err != nil { - t.Fatalf("err: %v", err) - } - - ctx, cancel := context.WithCancel(context.Background()) - wo := new(WriteOptions).WithContext(ctx) - - errCh := make(chan error, 1) - go func() { errCh <- session.RenewPeriodic("1s", id, wo, nil) }() - - cancel() - - select { - case <-time.After(1 * time.Second): - t.Fatal("renewal loop didn't terminate") - case err = <-errCh: - if err == nil || !strings.Contains(err.Error(), "context canceled") { - t.Fatalf("err: %v", err) - } - } - - // See comment in session.go for why the session isn't removed - // in this case. - sess, _, err := session.Info(id, nil) - if err != nil { - t.Fatalf("err: %v", err) - } - if sess == nil { - t.Fatalf("session should not be expired") - } - }) -} - -func TestAPI_SessionInfo(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - session := c.Session() - - id, _, err := session.Create(nil, nil) - if err != nil { - t.Fatalf("err: %v", err) - } - defer session.Destroy(id, nil) - - info, qm, err := session.Info(id, nil) - if err != nil { - t.Fatalf("err: %v", err) - } - - if qm.LastIndex == 0 { - t.Fatalf("bad: %v", qm) - } - if !qm.KnownLeader { - t.Fatalf("bad: %v", qm) - } - - if info == nil { - t.Fatalf("should get session") - } - if info.CreateIndex == 0 { - t.Fatalf("bad: %v", info) - } - if info.ID != id { - t.Fatalf("bad: %v", info) - } - if info.Name != "" { - t.Fatalf("bad: %v", info) - } - if info.Node == "" { - t.Fatalf("bad: %v", info) - } - if len(info.Checks) == 0 { - t.Fatalf("bad: %v", info) - } - if info.LockDelay == 0 { - t.Fatalf("bad: %v", info) - } - if info.Behavior != "release" { - t.Fatalf("bad: %v", info) - } - if info.TTL != "" { - t.Fatalf("bad: %v", info) - } -} - -func TestAPI_SessionNode(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - session := c.Session() - - id, _, err := session.Create(nil, nil) - if err != nil { - t.Fatalf("err: %v", err) - } - defer session.Destroy(id, nil) - - info, qm, err := session.Info(id, nil) - if err != nil { - t.Fatalf("err: %v", err) - } - - sessions, qm, err := session.Node(info.Node, nil) - if err != nil { - t.Fatalf("err: %v", err) - } - - if len(sessions) != 1 { - t.Fatalf("bad: %v", sessions) - } - - if qm.LastIndex == 0 { - t.Fatalf("bad: %v", qm) - } - if !qm.KnownLeader { - t.Fatalf("bad: %v", qm) - } -} - -func TestAPI_SessionList(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - session := c.Session() - - id, _, err := session.Create(nil, nil) - if err != nil { - t.Fatalf("err: %v", err) - } - defer session.Destroy(id, nil) - - sessions, qm, err := session.List(nil) - if err != nil { - t.Fatalf("err: %v", err) - } - - if len(sessions) != 1 { - t.Fatalf("bad: %v", sessions) - } - - if qm.LastIndex == 0 { - t.Fatalf("bad: %v", qm) - } - if !qm.KnownLeader { - t.Fatalf("bad: %v", qm) - } -} diff --git a/vendor/github.com/hashicorp/consul/api/snapshot_test.go b/vendor/github.com/hashicorp/consul/api/snapshot_test.go deleted file mode 100644 index ba371d4e4..000000000 --- a/vendor/github.com/hashicorp/consul/api/snapshot_test.go +++ /dev/null @@ -1,134 +0,0 @@ -package api - -import ( - "bytes" - "strings" - "testing" -) - -func TestAPI_Snapshot(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - // Place an initial key into the store. - kv := c.KV() - key := &KVPair{Key: testKey(), Value: []byte("hello")} - if _, err := kv.Put(key, nil); err != nil { - t.Fatalf("err: %v", err) - } - - // Make sure it reads back. - pair, _, err := kv.Get(key.Key, nil) - if err != nil { - t.Fatalf("err: %v", err) - } - if pair == nil { - t.Fatalf("expected value: %#v", pair) - } - if !bytes.Equal(pair.Value, []byte("hello")) { - t.Fatalf("unexpected value: %#v", pair) - } - - // Take a snapshot. - snapshot := c.Snapshot() - snap, qm, err := snapshot.Save(nil) - if err != nil { - t.Fatalf("err: %v", err) - } - defer snap.Close() - - // Sanity check th query metadata. - if qm.LastIndex == 0 || !qm.KnownLeader || - qm.RequestTime == 0 { - t.Fatalf("bad: %v", qm) - } - - // Overwrite the key's value. - key.Value = []byte("goodbye") - if _, err := kv.Put(key, nil); err != nil { - t.Fatalf("err: %v", err) - } - - // Read the key back and look for the new value. - pair, _, err = kv.Get(key.Key, nil) - if err != nil { - t.Fatalf("err: %v", err) - } - if pair == nil { - t.Fatalf("expected value: %#v", pair) - } - if !bytes.Equal(pair.Value, []byte("goodbye")) { - t.Fatalf("unexpected value: %#v", pair) - } - - // Restore the snapshot. - if err := snapshot.Restore(nil, snap); err != nil { - t.Fatalf("err: %v", err) - } - - // Read the key back and look for the original value. - pair, _, err = kv.Get(key.Key, nil) - if err != nil { - t.Fatalf("err: %v", err) - } - if pair == nil { - t.Fatalf("expected value: %#v", pair) - } - if !bytes.Equal(pair.Value, []byte("hello")) { - t.Fatalf("unexpected value: %#v", pair) - } -} - -func TestAPI_Snapshot_Options(t *testing.T) { - t.Parallel() - c, s := makeACLClient(t) - defer s.Stop() - - // Try to take a snapshot with a bad token. - snapshot := c.Snapshot() - _, _, err := snapshot.Save(&QueryOptions{Token: "anonymous"}) - if err == nil || !strings.Contains(err.Error(), "Permission denied") { - t.Fatalf("err: %v", err) - } - - // Now try an unknown DC. - _, _, err = snapshot.Save(&QueryOptions{Datacenter: "nope"}) - if err == nil || !strings.Contains(err.Error(), "No path to datacenter") { - t.Fatalf("err: %v", err) - } - - // This should work with a valid token. - snap, _, err := snapshot.Save(&QueryOptions{Token: "root"}) - if err != nil { - t.Fatalf("err: %v", err) - } - defer snap.Close() - - // This should work with a stale snapshot. This doesn't have good feedback - // that the stale option was sent, but it makes sure nothing bad happens. - snap, _, err = snapshot.Save(&QueryOptions{Token: "root", AllowStale: true}) - if err != nil { - t.Fatalf("err: %v", err) - } - defer snap.Close() - - // Try to restore a snapshot with a bad token. - null := bytes.NewReader([]byte("")) - err = snapshot.Restore(&WriteOptions{Token: "anonymous"}, null) - if err == nil || !strings.Contains(err.Error(), "Permission denied") { - t.Fatalf("err: %v", err) - } - - // Now try an unknown DC. - null = bytes.NewReader([]byte("")) - err = snapshot.Restore(&WriteOptions{Datacenter: "nope"}, null) - if err == nil || !strings.Contains(err.Error(), "No path to datacenter") { - t.Fatalf("err: %v", err) - } - - // This should work. - if err := snapshot.Restore(&WriteOptions{Token: "root"}, snap); err != nil { - t.Fatalf("err: %v", err) - } -} diff --git a/vendor/github.com/hashicorp/consul/api/status_test.go b/vendor/github.com/hashicorp/consul/api/status_test.go deleted file mode 100644 index f1ad3bf42..000000000 --- a/vendor/github.com/hashicorp/consul/api/status_test.go +++ /dev/null @@ -1,37 +0,0 @@ -package api - -import ( - "testing" -) - -func TestAPI_StatusLeader(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - status := c.Status() - - leader, err := status.Leader() - if err != nil { - t.Fatalf("err: %v", err) - } - if leader == "" { - t.Fatalf("Expected leader") - } -} - -func TestAPI_StatusPeers(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - status := c.Status() - - peers, err := status.Peers() - if err != nil { - t.Fatalf("err: %v", err) - } - if len(peers) == 0 { - t.Fatalf("Expected peers ") - } -} diff --git a/vendor/github.com/hashicorp/consul/main.go b/vendor/github.com/hashicorp/consul/main.go deleted file mode 100644 index 8678c8bdf..000000000 --- a/vendor/github.com/hashicorp/consul/main.go +++ /dev/null @@ -1,57 +0,0 @@ -package main - -import ( - "fmt" - "io/ioutil" - "log" - "os" - - "github.com/hashicorp/consul/command" - "github.com/hashicorp/consul/lib" - "github.com/mitchellh/cli" -) - -func init() { - lib.SeedMathRand() -} - -func main() { - os.Exit(realMain()) -} - -func realMain() int { - log.SetOutput(ioutil.Discard) - - args := os.Args[1:] - for _, arg := range args { - if arg == "--" { - break - } - - if arg == "-v" || arg == "--version" { - args = []string{"version"} - break - } - } - - var cmds []string - for c := range command.Commands { - if c != "configtest" { - cmds = append(cmds, c) - } - } - - cli := &cli.CLI{ - Args: args, - Commands: command.Commands, - HelpFunc: cli.FilteredHelpFunc(cmds, cli.BasicHelpFunc("consul")), - } - - exitCode, err := cli.Run() - if err != nil { - fmt.Fprintf(os.Stderr, "Error executing CLI: %s\n", err.Error()) - return 1 - } - - return exitCode -} diff --git a/vendor/github.com/hashicorp/consul/main_test.go b/vendor/github.com/hashicorp/consul/main_test.go deleted file mode 100644 index 06ab7d0f9..000000000 --- a/vendor/github.com/hashicorp/consul/main_test.go +++ /dev/null @@ -1 +0,0 @@ -package main diff --git a/vendor/github.com/hashicorp/consul/website/LICENSE.md b/vendor/github.com/hashicorp/consul/website/LICENSE.md new file mode 100644 index 000000000..3189f43a6 --- /dev/null +++ b/vendor/github.com/hashicorp/consul/website/LICENSE.md @@ -0,0 +1,10 @@ +# Proprietary License + +This license is temporary while a more official one is drafted. However, +this should make it clear: + +The text contents of this website are MPL 2.0 licensed. + +The design contents of this website are proprietary and may not be reproduced +or reused in any way other than to run the website locally. The license for +the design is owned solely by HashiCorp, Inc. diff --git a/vendor/github.com/hashicorp/go-cleanhttp/README.md b/vendor/github.com/hashicorp/go-cleanhttp/README.md deleted file mode 100644 index 036e5313f..000000000 --- a/vendor/github.com/hashicorp/go-cleanhttp/README.md +++ /dev/null @@ -1,30 +0,0 @@ -# cleanhttp - -Functions for accessing "clean" Go http.Client values - -------------- - -The Go standard library contains a default `http.Client` called -`http.DefaultClient`. It is a common idiom in Go code to start with -`http.DefaultClient` and tweak it as necessary, and in fact, this is -encouraged; from the `http` package documentation: - -> The Client's Transport typically has internal state (cached TCP connections), -so Clients should be reused instead of created as needed. Clients are safe for -concurrent use by multiple goroutines. - -Unfortunately, this is a shared value, and it is not uncommon for libraries to -assume that they are free to modify it at will. With enough dependencies, it -can be very easy to encounter strange problems and race conditions due to -manipulation of this shared value across libraries and goroutines (clients are -safe for concurrent use, but writing values to the client struct itself is not -protected). - -Making things worse is the fact that a bare `http.Client` will use a default -`http.Transport` called `http.DefaultTransport`, which is another global value -that behaves the same way. So it is not simply enough to replace -`http.DefaultClient` with `&http.Client{}`. - -This repository provides some simple functions to get a "clean" `http.Client` --- one that uses the same default values as the Go standard library, but -returns a client that does not share any state with other clients. diff --git a/vendor/github.com/hashicorp/go-cleanhttp/handlers_test.go b/vendor/github.com/hashicorp/go-cleanhttp/handlers_test.go deleted file mode 100644 index 95ef8124b..000000000 --- a/vendor/github.com/hashicorp/go-cleanhttp/handlers_test.go +++ /dev/null @@ -1,72 +0,0 @@ -package cleanhttp - -import ( - "fmt" - "net/http" - "net/http/httptest" - "testing" -) - -func TestPrintablePathCheckHandler(t *testing.T) { - getTestHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - fmt.Fprintln(w, "Hello, client") - }) - - cases := map[string]struct { - path string - expectCode int - input *HandlerInput - }{ - "valid nil input": { - path: "/valid", - expectCode: http.StatusOK, - input: nil, - }, - - "valid empty error status": { - path: "/valid", - expectCode: http.StatusOK, - input: &HandlerInput{}, - }, - - "invalid newline": { - path: "/invalid\n", - expectCode: http.StatusBadRequest, - }, - - "invalid carriage return": { - path: "/invalid\r", - expectCode: http.StatusBadRequest, - }, - - "invalid null": { - path: "/invalid\x00", - expectCode: http.StatusBadRequest, - }, - - "invalid alternate status": { - path: "/invalid\n", - expectCode: http.StatusInternalServerError, - input: &HandlerInput{ - ErrStatus: http.StatusInternalServerError, - }, - }, - } - - for name, tc := range cases { - t.Run(name, func(t *testing.T) { - // Create test HTTP server - ts := httptest.NewServer(PrintablePathCheckHandler(getTestHandler, tc.input)) - defer ts.Close() - - res, err := http.Get(ts.URL + tc.path) - if err != nil { - t.Fatal(err) - } - - if tc.expectCode != res.StatusCode { - t.Fatalf("expected %d, got :%d", tc.expectCode, res.StatusCode) - } - }) - } -} diff --git a/vendor/github.com/hashicorp/go-rootcerts/.travis.yml b/vendor/github.com/hashicorp/go-rootcerts/.travis.yml deleted file mode 100644 index 80e1de44e..000000000 --- a/vendor/github.com/hashicorp/go-rootcerts/.travis.yml +++ /dev/null @@ -1,12 +0,0 @@ -sudo: false - -language: go - -go: - - 1.6 - -branches: - only: - - master - -script: make test diff --git a/vendor/github.com/hashicorp/go-rootcerts/Makefile b/vendor/github.com/hashicorp/go-rootcerts/Makefile deleted file mode 100644 index c3989e789..000000000 --- a/vendor/github.com/hashicorp/go-rootcerts/Makefile +++ /dev/null @@ -1,8 +0,0 @@ -TEST?=./... - -test: - go test $(TEST) $(TESTARGS) -timeout=3s -parallel=4 - go vet $(TEST) - go test $(TEST) -race - -.PHONY: test diff --git a/vendor/github.com/hashicorp/go-rootcerts/README.md b/vendor/github.com/hashicorp/go-rootcerts/README.md deleted file mode 100644 index f5abffc29..000000000 --- a/vendor/github.com/hashicorp/go-rootcerts/README.md +++ /dev/null @@ -1,43 +0,0 @@ -# rootcerts - -Functions for loading root certificates for TLS connections. - ------ - -Go's standard library `crypto/tls` provides a common mechanism for configuring -TLS connections in `tls.Config`. The `RootCAs` field on this struct is a pool -of certificates for the client to use as a trust store when verifying server -certificates. - -This library contains utility functions for loading certificates destined for -that field, as well as one other important thing: - -When the `RootCAs` field is `nil`, the standard library attempts to load the -host's root CA set. This behavior is OS-specific, and the Darwin -implementation contains [a bug that prevents trusted certificates from the -System and Login keychains from being loaded][1]. This library contains -Darwin-specific behavior that works around that bug. - -[1]: https://github.com/golang/go/issues/14514 - -## Example Usage - -Here's a snippet demonstrating how this library is meant to be used: - -```go -func httpClient() (*http.Client, error) - tlsConfig := &tls.Config{} - err := rootcerts.ConfigureTLS(tlsConfig, &rootcerts.Config{ - CAFile: os.Getenv("MYAPP_CAFILE"), - CAPath: os.Getenv("MYAPP_CAPATH"), - }) - if err != nil { - return nil, err - } - c := cleanhttp.DefaultClient() - t := cleanhttp.DefaultTransport() - t.TLSClientConfig = tlsConfig - c.Transport = t - return c, nil -} -``` diff --git a/vendor/github.com/hashicorp/go-rootcerts/rootcerts_darwin_test.go b/vendor/github.com/hashicorp/go-rootcerts/rootcerts_darwin_test.go deleted file mode 100644 index 2129c156d..000000000 --- a/vendor/github.com/hashicorp/go-rootcerts/rootcerts_darwin_test.go +++ /dev/null @@ -1,17 +0,0 @@ -package rootcerts - -import "testing" - -func TestSystemCAsOnDarwin(t *testing.T) { - _, err := LoadSystemCAs() - if err != nil { - t.Fatalf("Got error: %s", err) - } -} - -func TestCertKeychains(t *testing.T) { - keychains := certKeychains() - if len(keychains) != 3 { - t.Fatalf("Expected 3 keychains, got %#v", keychains) - } -} diff --git a/vendor/github.com/hashicorp/go-rootcerts/rootcerts_test.go b/vendor/github.com/hashicorp/go-rootcerts/rootcerts_test.go deleted file mode 100644 index 963438588..000000000 --- a/vendor/github.com/hashicorp/go-rootcerts/rootcerts_test.go +++ /dev/null @@ -1,52 +0,0 @@ -package rootcerts - -import ( - "path/filepath" - "testing" -) - -const fixturesDir = "./test-fixtures" - -func TestConfigureTLSHandlesNil(t *testing.T) { - err := ConfigureTLS(nil, nil) - if err != nil { - t.Fatalf("err: %s", err) - } -} - -func TestLoadCACertsHandlesNil(t *testing.T) { - _, err := LoadCACerts(nil) - if err != nil { - t.Fatalf("err: %s", err) - } -} - -func TestLoadCACertsFromFile(t *testing.T) { - path := testFixture("cafile", "cacert.pem") - _, err := LoadCACerts(&Config{CAFile: path}) - if err != nil { - t.Fatalf("err: %s", err) - } -} - -func TestLoadCACertsFromDir(t *testing.T) { - path := testFixture("capath") - _, err := LoadCACerts(&Config{CAPath: path}) - if err != nil { - t.Fatalf("err: %s", err) - } -} - -func TestLoadCACertsFromDirWithSymlinks(t *testing.T) { - path := testFixture("capath-with-symlinks") - _, err := LoadCACerts(&Config{CAPath: path}) - if err != nil { - t.Fatalf("err: %s", err) - } -} - -func testFixture(n ...string) string { - parts := []string{fixturesDir} - parts = append(parts, n...) - return filepath.Join(parts...) -} diff --git a/vendor/github.com/hashicorp/go-rootcerts/test-fixtures/capath-with-symlinks/securetrust.pem b/vendor/github.com/hashicorp/go-rootcerts/test-fixtures/capath-with-symlinks/securetrust.pem new file mode 120000 index 000000000..dda0574d7 --- /dev/null +++ b/vendor/github.com/hashicorp/go-rootcerts/test-fixtures/capath-with-symlinks/securetrust.pem @@ -0,0 +1 @@ +../capath/securetrust.pem \ No newline at end of file diff --git a/vendor/github.com/hashicorp/go-rootcerts/test-fixtures/capath-with-symlinks/thawte.pem b/vendor/github.com/hashicorp/go-rootcerts/test-fixtures/capath-with-symlinks/thawte.pem new file mode 120000 index 000000000..37ed4f01a --- /dev/null +++ b/vendor/github.com/hashicorp/go-rootcerts/test-fixtures/capath-with-symlinks/thawte.pem @@ -0,0 +1 @@ +../capath/thawte.pem \ No newline at end of file diff --git a/vendor/github.com/hashicorp/serf/.gitignore b/vendor/github.com/hashicorp/serf/.gitignore deleted file mode 100644 index 5a2c683c3..000000000 --- a/vendor/github.com/hashicorp/serf/.gitignore +++ /dev/null @@ -1,32 +0,0 @@ -# Platform -.DS_Store - -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -/bin/ -/pkg/ - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe -*.test - -# Website -website/build/ -website/.bundle -website/vendor -.vagrant diff --git a/vendor/github.com/hashicorp/serf/.travis.yml b/vendor/github.com/hashicorp/serf/.travis.yml deleted file mode 100644 index 4cf0a8873..000000000 --- a/vendor/github.com/hashicorp/serf/.travis.yml +++ /dev/null @@ -1,15 +0,0 @@ -language: go - -go: - - 1.7.5 - -branches: - only: - - master - -install: - - make bin - - make get-tools - -script: - - make test diff --git a/vendor/github.com/hashicorp/serf/CHANGELOG.md b/vendor/github.com/hashicorp/serf/CHANGELOG.md deleted file mode 100644 index af3f1672b..000000000 --- a/vendor/github.com/hashicorp/serf/CHANGELOG.md +++ /dev/null @@ -1,398 +0,0 @@ -## 0.8.1 (February 6, 2017) - -IMPROVEMENTS: - - * agent: Added support for relaying query responses through N other nodes for redundancy. [GH-439] - * agent: Added the ability to tune the broadcast timeout, which might be necessary in very large clusters that experience very large, simultaneous changes to the cluster. [GH-412] - * agent: Added a checksum to UDP gossip messages to guard against packet corruption. [GH-432] - * agent: Added a short window where gossip will still flow to dead nodes so that they can more quickly refute. [GH-440] - * build: Serf now builds with Go 1.7.5. [GH-443] - -## 0.8 (September 14, 2016) - -FEATURES: - - * **Lifeguard Updates:** Implemented a new set of feedback controls for the gossip layer that help prevent degraded nodes that can't meet the soft real-time requirements from erroneously causing flapping in other, healthy nodes. This feature tunes itself automatically and requires no configuration. [GH-394] - -IMRPOVEMENTS: - - * Modified management of intents to be per-node to avoid intent queue overflow errors in large clusters. [GH-402] - * Joins based on a DNS lookup will use TCP and attempt to join with the full list of returned addresses. [GH-387] - * Serf's Go dependencies are now vendored using govendor. [GH-383] - * Updated all of Serf's dependencies. [GH-387] [GH-401] - * Moved dist build into a Docker container. [GH-409] - -BUG FIXES: - - * Updated memberlist to pull in a fix for leaking goroutines when performing TCP fallback pings. This affected users with frequent UDP connectivity problems. [GH-381] - -## 0.7 (December 21, 2015) - -FEATURES: - - * Added new network tomography subsystem that computes network coordinates for - nodes in the cluster which can be used to estimate network round trip times - between any two nodes; exposes new `GetCoordinate` API as as well as a - a new `serf rtt` command to query RTT interactively - -IMPROVEMENTS: - - * Added support for configuring query request size and query response size [GH-346] - * Syslog messages are now filtered by the configured log-level - * New `statsd_addr` for sending metrics via UDP to statsd - * Added support for sending telemetry to statsite - * `serf info` command now displays event handlers [GH-312] - * Added a `MemberLeave` message to the `EventCh` for a force-leave so higher- - level applications can handle the leave event - * Lots of documentation updates - -BUG FIXES: - - * Fixed updating cached protocol version of a node when an update event - fires [GH-335] - * Fixed a bug where an empty remote state message would cause a crash in - `MergeRemoteState` - -## 0.6.4 (Febuary 12, 2015) - -IMPROVEMENTS: - - * Added merge delegate to Serf library to support application - specific logic in cluster merging. - * `SERF_RPC_AUTH` environment variable can be used in place of CLI flags. - * Display if encryption is enabled in Serf stats - * Improved `join` behavior when using DNS resolution - -BUG FIXES: - - * Fixed snapshot file compaction on Windows - * Fixed device binding on Windows - * Fixed bug with empty keyring - * Fixed parsing of ports in some cases - * Fixing stability issues under high churn - -MISC: - -* Increased user event size limit to 512 bytes (previously 256) - -## 0.6.3 (July 10, 2014) - -IMPROVEMENTS: - -* Added `statsite_addr` configuration to stream to statsite - -BUG FIXES: - -* Fixed issue with mDNS flooding when using IPv4 and IPv6 -* Fixed issue with reloading event handlers - -MISC: - -* Improved failure detection reliability under load -* Reduced fsync() use in snapshot file -* Improved snapshot file performance -* Additional logging to help debug flapping - -## 0.6.2 (June 16, 2014) - -IMPROVEMENTS: - -* Added `syslog_facility` configuration to set facility - -BUG FIXES: - -* Fixed memory leak in in-memory stats system -* Fixed issue that would cause syslog to deadlock - -MISC: - -* Fixed missing prefixes on some log messages -* Docs fixes - -## 0.6.1 (May 29, 2014) - -BUG FIXES: - -* On Windows, a "failed to decode request header" error will no - longer be shown on every RPC request. - -* Avoiding holding a lock which can cause monitor/stream commands to - fail when an event handler is blocking - -* Fixing conflict response decoding errors - -IMPROVEMENTS: - -* Improved agent CLI usage documentation - -* Warn if an event handler is slow, potentially blocking other events - -## 0.6.0 (May 8, 2014) - -FEATURES: - - * Support for key rotation when using encryption. This adds a new - `serf keys` command, and a `-keyring-file` configuration. Thanks - to @ryanuber. - - * New `-tags-file` can be specified to persist changes to tags made - via the RPC interface. Thanks to @ryanuber. - - * New `serf info` command to provide operator debugging information, - and to get info about the local node. - - * Adding `-retry-join` flag to agent which enables retrying the join - until success or `-retry-max` attempts have been made. - -IMPROVEMENTS: - - * New `-rejoin` flag can be used along with a snapshot file to - automatically rejoin a cluster. - - * Agent uses circular buffer to invoke handlers, guards against unbounded - output lengths. - - * Adding support for logging to syslog - - * The SERF_RPC_ADDR environment variable can be used instead of the - `-rpc-addr` flags. Thanks to @lalyos [GH-209]. - - * `serf query` can now output the results in a JSON format. - - * Unknown configuration directives generate an error [GH-186]. - Thanks to @vincentbernat. - -BUG FIXES: - - * Fixing environmental variables with invalid characters. [GH-200]. - Thanks to @arschles. - - * Fixing issue with tag changes with hard restart before - failure detection. - - * Fixing issue with reconnect when using dynamic ports. - -MISC: - - * Improved logging of various error messages - - * Improved debian packaging. Thanks to @vincentbernat. - -## 0.5.0 (March 12, 2014) - -FEATURES: - - * New `query` command provides a request/response mechanism to do realtime - queries across the cluster. [GH-139] - - * Automatic conflict resolution. Serf will detect name conflicts, and use an - internal query to determine which node is in the minority and perform a shutdown. - [GH-167] [GH-119] - - * New `reachability` command can be used to help diagnose network and configuration - issues. - - * Added `member-reap` event to get notified of when Serf removes a failed or left - node from the cluster. The reap interval is controlled by `reconnect_timeout` and - `tombstone_timeout` respectively. [GH-172] - -IMPROVEMENTS: - - * New Recipes section on the site to share Serf tips. Thanks to @ryanuber. [GH-177] - - * `members` command has new `-name` filter flag. Thanks to @ryanuber [GH-164] - - * New RPC command "members-filtered" to move filtering logic to the agent. - Thanks to @ryanuber. [GH-149] - - * `reconnect_interval` and `reconnect_timeout` can be provided to configure - agent behavior for attempting to reconnect to failed nodes. [GH-155] - - * `tombstone_interval` can be provided to configure the reap time for nodes - that have gracefully left. [GH_172] - - * Agent can be provided `rpc_auth` config to require that RPC is authenticated. - All commands can take a `-rpc-auth` flag now. [GH-148] - -BUG FIXES: - - * Fixed config folder in Upstart script. Thanks to @llchen223. [GH-174] - - * Event handlers are correctly invoked when BusyBox is the shell. [GH-156] - - * Event handlers were not being invoked with the correct SERF_TAG_* values - if tags were changed using the `tags` command. [GH-169] - -MISC: - - * Support for protocol version 1 (Serf 0.2) has been removed. Serf 0.5 cannot - join a cluster that has members running version 0.2. - -## 0.4.5 (February 25, 2014) - -FEATURES: - - * New `tags` command is available to dynamically update tags without - reloading the agent. Thanks to @ryanuber. [GH-126] - -IMPROVEMENTS: - - * Upstart receipe logs output thanks to @breerly [GH-128] - - * `members` can filter on any tag thanks to @hmrm [GH-124] - - * Added vagrant demo to make a simple cluster - - * `members` now columnizes the output thanks to @ryanuber [GH-138] - - * Agent passes its own environment variables through thanks to @mcroydon [GH-142] - - * `-iface` flag can be used to bind to interfaces [GH-145] - -BUG FIXES: - - * -config-dir would cause protocol to be set to 0 if there are no - configuration files in the directory [GH-129] - - * Event handlers can filter on 'member-update' - - * User event handler appends new line, this was being omitted - -## 0.4.1 (February 3, 2014) - -IMPROVEMENTS: - - * mDNS service uses the advertise address instead of bind address - -## 0.4.0 (January 31, 2014) - -FEATURES: - - * Static `role` has been replaced with dynamic tags. Each agent can have - multiple key/value tags associated using `-tag`. Tags can be updated using - a SIGHUP and are advertised to the cluster, causing the `member-update` event - to be triggered. [GH-111] [GH-98] - - * Serf can automatically discover peers uing mDNS when provided the `-discover` - flag. In network environments supporting multicast, no explicit join is needed - to find peers. [GH-53] - - * Serf collects telemetry information and simple runtime profiling. Stats can - be dumped to stderr by sending a `USR1` signal to Serf. Windows users must use - the `BREAK` signal instead. [GH-103] - - * `advertise` flag can be used to set an advertise address different - from the bind address. Used for NAT traversal. Thanks to @benagricola [GH-93] - - * `members` command now takes `-format` flag to specify either text or JSON - output. Fixed by @ryanuber [GH-97] - -IMPROVEMENTS: - - * User payload always appends a newline when invoking a shell script - - * Severity of "Potential blocking operation" reduced to debug to prevent - spurious messages on slow or busy machines. - -BUG FIXES: - - * If an agent is restarted with the same bind address but new name, it - will not respond to the old name, causing the old name to enter the - `failed` state, instead of having duplicate entries in the `alive` state. - - * `leave_on_interrupt` set to false when not specified, if - any config file is provided. This flag is deprecated for - `skip_leave_on_interrupt` instead. [GH-94] - -MISC: - - * `-role` configuration has been deprecated in favor of `-tag role=foo`. - The flag is still supported but will generate warnings. - - * Support for protocol version 0 (Serf 0.1) has been removed. Serf 0.4 cannot - join a cluster that has members running version 0.1. - -## 0.3.0 (December 5, 2013) - -FEATURES: - - * Dynamic port support, cluster wide consistent config not necessary - * Snapshots to automaticaly rejoin cluster after failure and prevent replays [GH-84] [GH-71] - * Adding `profile` config to agent, to support WAN, LAN, and Local modes - * MsgPack over TCP RPC protocol which can be used to control Serf, send events, and - receive events with low latency. - * New `leave` CLI command and RPC endpoint to control graceful leaves - * Signal handling is controlable, graceful leave behavior on SIGINT/SIGTERM - can be specified - * SIGHUP can be used to reload configuration - -IMPROVEMENTS: - - * Event handler provides lamport time of user events via SERF_USER_LTIME [GH-68] - * Memberlist encryption overhead has been reduced - * Filter output of `members` using regular expressions on role and status - * `replay_on_join` parameter to control replay with `start_join` - * `monitor` works even if the client is behind a NAT - * Serf generates warning if binding to public IP without encryption - -BUG FIXES: - - * Prevent unbounded transmit queues [GH-78] - * IPv6 addresses can be bound to [GH-72] - * Serf join won't hang on a slow/dead node [GH-70] - * Serf Leave won't block Shutdown [GH-1] - -## 0.2.1 (November 6, 2013) - -BUG FIXES: - - * Member role and address not updated on re-join [GH-58] - -## 0.2.0 (November 1, 2013) - -FEATURES: - - * Protocol versioning features so that upgrades can be done safely. - See the website on upgrading Serf for more info. - * Can now configure Serf with files or directories of files by specifying - the `-config-file` and/or `-config-dir` flags to the agent. - * New command `serf force-leave` can be used to force a "failed" node - to the "left" state. - * Serf now supports message encryption and verification so that it can - be used on untrusted networks [GH-25] - * The `-join` flag on `serf agent` can be used to join a cluster when - starting an agent. [GH-42] - -IMPROVEMENTS: - - * Random staggering of periodic routines to avoid cluster-wide - synchronization - * Push/Pull timer automatically slows down as cluster grows to avoid - congestion - * Messages are compressed to reduce bandwidth utilization - * `serf members` now provides node roles in output - * Joining a cluster will no longer replay all the old events by default, - but it can using the `-replay` flag. - * User events are coalesced by default, meaning duplicate events (by name) - within a short period of time are merged. [GH-8] - -BUG FIXES: - - * Event handlers work on Windows now by executing commands through - `cmd /C` [GH-37] - * Nodes that previously left and rejoin won't get stuck in 'leaving' state. - [GH-18] - * Fixing alignment issues on i386 for atomic operations [GH-20] - * "trace" log level works [GH-31] - -## 0.1.1 (October 23, 2013) - -BUG FIXES: - - * Default node name is outputted when "serf agent" is called with no args. - * Remove node from reap list after join so a fast re-join doesn't lose the - member. - -## 0.1.0 (October 23, 2013) - -* Initial release diff --git a/vendor/github.com/hashicorp/serf/GNUmakefile b/vendor/github.com/hashicorp/serf/GNUmakefile deleted file mode 100644 index a938fd839..000000000 --- a/vendor/github.com/hashicorp/serf/GNUmakefile +++ /dev/null @@ -1,64 +0,0 @@ -GOTOOLS = github.com/mitchellh/gox github.com/kardianos/govendor -VERSION = $(shell awk -F\" '/^const Version/ { print $$2; exit }' cmd/serf/version.go) -GITSHA:=$(shell git rev-parse HEAD) -GITBRANCH:=$(shell git symbolic-ref --short HEAD 2>/dev/null) - -default:: test - -# bin generates the releasable binaries -bin:: tools - @sh -c "'$(CURDIR)/scripts/build.sh'" - -# cov generates the coverage output -cov:: tools - gocov test ./... | gocov-html > /tmp/coverage.html - open /tmp/coverage.html - -# dev creates binaries for testing locally - these are put into ./bin and -# $GOPATH -dev:: - @SERF_DEV=1 sh -c "'$(CURDIR)/scripts/build.sh'" - -# dist creates the binaries for distibution -dist:: - @sh -c "'$(CURDIR)/scripts/dist.sh' $(VERSION)" - -get-tools:: - go get -u -v $(GOTOOLS) - -# subnet sets up the require subnet for testing on darwin (osx) - you must run -# this before running other tests if you are on osx. -subnet:: - @sh -c "'$(CURDIR)/scripts/setup_test_subnet.sh'" - -# test runs the test suite -test:: subnet tools - @go list ./... | grep -v -E '^github.com/hashicorp/serf/(vendor|cmd/serf/vendor)' | xargs -n1 go test $(TESTARGS) - -# testrace runs the race checker -testrace:: subnet - go test -race `govendor list -no-status +local` $(TESTARGS) - -tools:: - @which gox 2>/dev/null ; if [ $$? -eq 1 ]; then \ - $(MAKE) get-tools; \ - fi - -# updatedeps installs all the dependencies needed to test, build, and run -updatedeps:: tools - govendor list -no-status +vendor | xargs -n1 go get -u - govendor update +vendor - -vet:: tools - @echo "--> Running go tool vet $(VETARGS) ." - @govendor list -no-status +local \ - | cut -d '/' -f 4- \ - | xargs -n1 \ - go tool vet $(VETARGS) ;\ - if [ $$? -ne 0 ]; then \ - echo ""; \ - echo "Vet found suspicious constructs. Please check the reported constructs"; \ - echo "and fix them if necessary before submitting the code for reviewal."; \ - fi - -.PHONY: default bin cov dev dist get-tools subnet test testrace tools updatedeps vet diff --git a/vendor/github.com/hashicorp/serf/README.md b/vendor/github.com/hashicorp/serf/README.md deleted file mode 100644 index 0e8e0b7d2..000000000 --- a/vendor/github.com/hashicorp/serf/README.md +++ /dev/null @@ -1,121 +0,0 @@ -# Serf [![Build Status](https://travis-ci.org/hashicorp/serf.png)](https://travis-ci.org/hashicorp/serf) [![Join the chat at https://gitter.im/hashicorp-serf/Lobby](https://badges.gitter.im/hashicorp-serf/Lobby.svg)](https://gitter.im/hashicorp-serf/Lobby?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) - -* Website: https://www.serf.io -* Chat: [Gitter](https://gitter.im/hashicorp-serf/Lobby) -* Mailing list: [Google Groups](https://groups.google.com/group/serfdom/) - -Serf is a decentralized solution for service discovery and orchestration -that is lightweight, highly available, and fault tolerant. - -Serf runs on Linux, Mac OS X, and Windows. An efficient and lightweight gossip -protocol is used to communicate with other nodes. Serf can detect node failures -and notify the rest of the cluster. An event system is built on top of -Serf, letting you use Serf's gossip protocol to propagate events such -as deploys, configuration changes, etc. Serf is completely masterless -with no single point of failure. - -Here are some example use cases of Serf, though there are many others: - -* Discovering web servers and automatically adding them to a load balancer -* Organizing many memcached or redis nodes into a cluster, perhaps with - something like [twemproxy](https://github.com/twitter/twemproxy) or - maybe just configuring an application with the address of all the - nodes -* Triggering web deploys using the event system built on top of Serf -* Propagating changes to configuration to relevant nodes. -* Updating DNS records to reflect cluster changes as they occur. -* Much, much more. - -## Quick Start - -First, [download a pre-built Serf binary](https://www.serf.io/downloads.html) -for your operating system, [compile Serf yourself](#developing-serf), or install -using `go get -u github.com/hashicorp/serf/cmd/serf`. - -Next, let's start a couple Serf agents. Agents run until they're told to quit -and handle the communication of maintenance tasks of Serf. In a real Serf -setup, each node in your system will run one or more Serf agents (it can -run multiple agents if you're running multiple cluster types. e.g. web -servers vs. memcached servers). - -Start each Serf agent in a separate terminal session so that we can see -the output of each. Start the first agent: - -``` -$ serf agent -node=foo -bind=127.0.0.1:5000 -rpc-addr=127.0.0.1:7373 -... -``` - -Start the second agent in another terminal session (while the first is still -running): - -``` -$ serf agent -node=bar -bind=127.0.0.1:5001 -rpc-addr=127.0.0.1:7374 -... -``` - -At this point two Serf agents are running independently but are still -unaware of each other. Let's now tell the first agent to join an existing -cluster (the second agent). When starting a Serf agent, you must join an -existing cluster by specifying at least one existing member. After this, -Serf gossips and the remainder of the cluster becomes aware of the join. -Run the following commands in a third terminal session. - -``` -$ serf join 127.0.0.1:5001 -... -``` - -If you're watching your terminals, you should see both Serf agents -become aware of the join. You can prove it by running `serf members` -to see the members of the Serf cluster: - -``` -$ serf members -foo 127.0.0.1:5000 alive -bar 127.0.0.1:5001 alive -... -``` - -At this point, you can ctrl-C or force kill either Serf agent, and they'll -update their membership lists appropriately. If you ctrl-C a Serf agent, -it will gracefully leave by notifying the cluster of its intent to leave. -If you force kill an agent, it will eventually (usually within seconds) -be detected by another member of the cluster which will notify the -cluster of the node failure. - -## Documentation - -Full, comprehensive documentation is viewable on the Serf website: - -https://www.serf.io/docs - -## Developing Serf - -If you wish to work on Serf itself, you'll first need [Go](https://golang.org) -installed (version 1.7+ is _required_). Make sure you have Go properly -[installed](https://golang.org/doc/install), -including setting up your [GOPATH](https://golang.org/doc/code.html#GOPATH). - -Next, clone this repository into `$GOPATH/src/github.com/hashicorp/serf` and -then just type `make`. In a few moments, you'll have a working `serf` executable: - -``` -$ make -... -$ bin/serf -... -``` - -*NOTE: `make` will also place a copy of the executable under `$GOPATH/bin/`* - -Serf is first and foremost a library with a command-line interface, `serf`. The -Serf library is independent of the command line agent, `serf`. The `serf` -binary is located under `cmd/serf` and can be installed stand alone by issuing -the command `go get -u github.com/hashicorp/serf/cmd/serf`. Applications using -the Serf library should only need to include `github.com/hashicorp/serf`. - -Tests can be run by typing `make test`. - -If you make any changes to the code, run `make format` in order to automatically -format the code according to Go [standards](https://golang.org/doc/effective_go.html#formatting). diff --git a/vendor/github.com/hashicorp/serf/coordinate/client_test.go b/vendor/github.com/hashicorp/serf/coordinate/client_test.go deleted file mode 100644 index ae7d58c0d..000000000 --- a/vendor/github.com/hashicorp/serf/coordinate/client_test.go +++ /dev/null @@ -1,109 +0,0 @@ -package coordinate - -import ( - "reflect" - "strings" - "testing" - "time" -) - -func TestClient_NewClient(t *testing.T) { - config := DefaultConfig() - - config.Dimensionality = 0 - client, err := NewClient(config) - if err == nil || !strings.Contains(err.Error(), "dimensionality") { - t.Fatal(err) - } - - config.Dimensionality = 7 - client, err = NewClient(config) - if err != nil { - t.Fatal(err) - } - - origin := NewCoordinate(config) - if !reflect.DeepEqual(client.GetCoordinate(), origin) { - t.Fatalf("fresh client should be located at the origin") - } -} - -func TestClient_Update(t *testing.T) { - config := DefaultConfig() - config.Dimensionality = 3 - - client, err := NewClient(config) - if err != nil { - t.Fatal(err) - } - - // Make sure the Euclidean part of our coordinate is what we expect. - c := client.GetCoordinate() - verifyEqualVectors(t, c.Vec, []float64{0.0, 0.0, 0.0}) - - // Place a node right above the client and observe an RTT longer than the - // client expects, given its distance. - other := NewCoordinate(config) - other.Vec[2] = 0.001 - rtt := time.Duration(2.0 * other.Vec[2] * secondsToNanoseconds) - c = client.Update("node", other, rtt) - - // The client should have scooted down to get away from it. - if !(c.Vec[2] < 0.0) { - t.Fatalf("client z coordinate %9.6f should be < 0.0", c.Vec[2]) - } - - // Set the coordinate to a known state. - c.Vec[2] = 99.0 - client.SetCoordinate(c) - c = client.GetCoordinate() - verifyEqualFloats(t, c.Vec[2], 99.0) -} - -func TestClient_DistanceTo(t *testing.T) { - config := DefaultConfig() - config.Dimensionality = 3 - config.HeightMin = 0 - - client, err := NewClient(config) - if err != nil { - t.Fatal(err) - } - - // Fiddle a raw coordinate to put it a specific number of seconds away. - other := NewCoordinate(config) - other.Vec[2] = 12.345 - expected := time.Duration(other.Vec[2] * secondsToNanoseconds) - dist := client.DistanceTo(other) - if dist != expected { - t.Fatalf("distance doesn't match %9.6f != %9.6f", dist.Seconds(), expected.Seconds()) - } -} - -func TestClient_latencyFilter(t *testing.T) { - config := DefaultConfig() - config.LatencyFilterSize = 3 - - client, err := NewClient(config) - if err != nil { - t.Fatal(err) - } - - // Make sure we get the median, and that things age properly. - verifyEqualFloats(t, client.latencyFilter("alice", 0.201), 0.201) - verifyEqualFloats(t, client.latencyFilter("alice", 0.200), 0.201) - verifyEqualFloats(t, client.latencyFilter("alice", 0.207), 0.201) - - // This glitch will get median-ed out and never seen by Vivaldi. - verifyEqualFloats(t, client.latencyFilter("alice", 1.9), 0.207) - verifyEqualFloats(t, client.latencyFilter("alice", 0.203), 0.207) - verifyEqualFloats(t, client.latencyFilter("alice", 0.199), 0.203) - verifyEqualFloats(t, client.latencyFilter("alice", 0.211), 0.203) - - // Make sure different nodes are not coupled. - verifyEqualFloats(t, client.latencyFilter("bob", 0.310), 0.310) - - // Make sure we don't leak coordinates for nodes that leave. - client.ForgetNode("alice") - verifyEqualFloats(t, client.latencyFilter("alice", 0.888), 0.888) -} diff --git a/vendor/github.com/hashicorp/serf/coordinate/coordinate_test.go b/vendor/github.com/hashicorp/serf/coordinate/coordinate_test.go deleted file mode 100644 index 17f68ac51..000000000 --- a/vendor/github.com/hashicorp/serf/coordinate/coordinate_test.go +++ /dev/null @@ -1,260 +0,0 @@ -package coordinate - -import ( - "math" - "reflect" - "testing" - "time" -) - -// verifyDimensionPanic will run the supplied func and make sure it panics with -// the expected error type. -func verifyDimensionPanic(t *testing.T, f func()) { - defer func() { - if r := recover(); r != nil { - if _, ok := r.(DimensionalityConflictError); !ok { - t.Fatalf("panic isn't the right type") - } - } else { - t.Fatalf("didn't get expected panic") - } - }() - f() -} - -func TestCoordinate_NewCoordinate(t *testing.T) { - config := DefaultConfig() - c := NewCoordinate(config) - if uint(len(c.Vec)) != config.Dimensionality { - t.Fatalf("dimensionality not set correctly %d != %d", - len(c.Vec), config.Dimensionality) - } -} - -func TestCoordinate_Clone(t *testing.T) { - c := NewCoordinate(DefaultConfig()) - c.Vec[0], c.Vec[1], c.Vec[2] = 1.0, 2.0, 3.0 - c.Error = 5.0 - c.Adjustment = 10.0 - c.Height = 4.2 - - other := c.Clone() - if !reflect.DeepEqual(c, other) { - t.Fatalf("coordinate clone didn't make a proper copy") - } - - other.Vec[0] = c.Vec[0] + 0.5 - if reflect.DeepEqual(c, other) { - t.Fatalf("cloned coordinate is still pointing at its ancestor") - } -} - -func TestCoordinate_IsCompatibleWith(t *testing.T) { - config := DefaultConfig() - - config.Dimensionality = 3 - c1 := NewCoordinate(config) - c2 := NewCoordinate(config) - - config.Dimensionality = 2 - alien := NewCoordinate(config) - - if !c1.IsCompatibleWith(c1) || !c2.IsCompatibleWith(c2) || - !alien.IsCompatibleWith(alien) { - t.Fatalf("coordinates should be compatible with themselves") - } - - if !c1.IsCompatibleWith(c2) || !c2.IsCompatibleWith(c1) { - t.Fatalf("coordinates should be compatible with each other") - } - - if c1.IsCompatibleWith(alien) || c2.IsCompatibleWith(alien) || - alien.IsCompatibleWith(c1) || alien.IsCompatibleWith(c2) { - t.Fatalf("alien should not be compatible with the other coordinates") - } -} - -func TestCoordinate_ApplyForce(t *testing.T) { - config := DefaultConfig() - config.Dimensionality = 3 - config.HeightMin = 0 - - origin := NewCoordinate(config) - - // This proves that we normalize, get the direction right, and apply the - // force multiplier correctly. - above := NewCoordinate(config) - above.Vec = []float64{0.0, 0.0, 2.9} - c := origin.ApplyForce(config, 5.3, above) - verifyEqualVectors(t, c.Vec, []float64{0.0, 0.0, -5.3}) - - // Scoot a point not starting at the origin to make sure there's nothing - // special there. - right := NewCoordinate(config) - right.Vec = []float64{3.4, 0.0, -5.3} - c = c.ApplyForce(config, 2.0, right) - verifyEqualVectors(t, c.Vec, []float64{-2.0, 0.0, -5.3}) - - // If the points are right on top of each other, then we should end up - // in a random direction, one unit away. This makes sure the unit vector - // build up doesn't divide by zero. - c = origin.ApplyForce(config, 1.0, origin) - verifyEqualFloats(t, origin.DistanceTo(c).Seconds(), 1.0) - - // Enable a minimum height and make sure that gets factored in properly. - config.HeightMin = 10.0e-6 - origin = NewCoordinate(config) - c = origin.ApplyForce(config, 5.3, above) - verifyEqualVectors(t, c.Vec, []float64{0.0, 0.0, -5.3}) - verifyEqualFloats(t, c.Height, config.HeightMin+5.3*config.HeightMin/2.9) - - // Make sure the height minimum is enforced. - c = origin.ApplyForce(config, -5.3, above) - verifyEqualVectors(t, c.Vec, []float64{0.0, 0.0, 5.3}) - verifyEqualFloats(t, c.Height, config.HeightMin) - - // Shenanigans should get called if the dimensions don't match. - bad := c.Clone() - bad.Vec = make([]float64, len(bad.Vec)+1) - verifyDimensionPanic(t, func() { c.ApplyForce(config, 1.0, bad) }) -} - -func TestCoordinate_DistanceTo(t *testing.T) { - config := DefaultConfig() - config.Dimensionality = 3 - config.HeightMin = 0 - - c1, c2 := NewCoordinate(config), NewCoordinate(config) - c1.Vec = []float64{-0.5, 1.3, 2.4} - c2.Vec = []float64{1.2, -2.3, 3.4} - - verifyEqualFloats(t, c1.DistanceTo(c1).Seconds(), 0.0) - verifyEqualFloats(t, c1.DistanceTo(c2).Seconds(), c2.DistanceTo(c1).Seconds()) - verifyEqualFloats(t, c1.DistanceTo(c2).Seconds(), 4.104875150354758) - - // Make sure negative adjustment factors are ignored. - c1.Adjustment = -1.0e6 - verifyEqualFloats(t, c1.DistanceTo(c2).Seconds(), 4.104875150354758) - - // Make sure positive adjustment factors affect the distance. - c1.Adjustment = 0.1 - c2.Adjustment = 0.2 - verifyEqualFloats(t, c1.DistanceTo(c2).Seconds(), 4.104875150354758+0.3) - - // Make sure the heights affect the distance. - c1.Height = 0.7 - c2.Height = 0.1 - verifyEqualFloats(t, c1.DistanceTo(c2).Seconds(), 4.104875150354758+0.3+0.8) - - // Shenanigans should get called if the dimensions don't match. - bad := c1.Clone() - bad.Vec = make([]float64, len(bad.Vec)+1) - verifyDimensionPanic(t, func() { _ = c1.DistanceTo(bad) }) -} - -// dist is a self-contained example that appears in documentation. -func dist(a *Coordinate, b *Coordinate) time.Duration { - // Coordinates will always have the same dimensionality, so this is - // just a sanity check. - if len(a.Vec) != len(b.Vec) { - panic("dimensions aren't compatible") - } - - // Calculate the Euclidean distance plus the heights. - sumsq := 0.0 - for i := 0; i < len(a.Vec); i++ { - diff := a.Vec[i] - b.Vec[i] - sumsq += diff * diff - } - rtt := math.Sqrt(sumsq) + a.Height + b.Height - - // Apply the adjustment components, guarding against negatives. - adjusted := rtt + a.Adjustment + b.Adjustment - if adjusted > 0.0 { - rtt = adjusted - } - - // Go's times are natively nanoseconds, so we convert from seconds. - const secondsToNanoseconds = 1.0e9 - return time.Duration(rtt * secondsToNanoseconds) -} - -func TestCoordinate_dist_Example(t *testing.T) { - config := DefaultConfig() - c1, c2 := NewCoordinate(config), NewCoordinate(config) - c1.Vec = []float64{-0.5, 1.3, 2.4} - c2.Vec = []float64{1.2, -2.3, 3.4} - c1.Adjustment = 0.1 - c2.Adjustment = 0.2 - c1.Height = 0.7 - c2.Height = 0.1 - verifyEqualFloats(t, c1.DistanceTo(c2).Seconds(), dist(c1, c2).Seconds()) -} - -func TestCoordinate_rawDistanceTo(t *testing.T) { - config := DefaultConfig() - config.Dimensionality = 3 - config.HeightMin = 0 - - c1, c2 := NewCoordinate(config), NewCoordinate(config) - c1.Vec = []float64{-0.5, 1.3, 2.4} - c2.Vec = []float64{1.2, -2.3, 3.4} - - verifyEqualFloats(t, c1.rawDistanceTo(c1), 0.0) - verifyEqualFloats(t, c1.rawDistanceTo(c2), c2.rawDistanceTo(c1)) - verifyEqualFloats(t, c1.rawDistanceTo(c2), 4.104875150354758) - - // Make sure that the adjustment doesn't factor into the raw - // distance. - c1.Adjustment = 1.0e6 - verifyEqualFloats(t, c1.rawDistanceTo(c2), 4.104875150354758) - - // Make sure the heights affect the distance. - c1.Height = 0.7 - c2.Height = 0.1 - verifyEqualFloats(t, c1.rawDistanceTo(c2), 4.104875150354758+0.8) -} - -func TestCoordinate_add(t *testing.T) { - vec1 := []float64{1.0, -3.0, 3.0} - vec2 := []float64{-4.0, 5.0, 6.0} - verifyEqualVectors(t, add(vec1, vec2), []float64{-3.0, 2.0, 9.0}) - - zero := []float64{0.0, 0.0, 0.0} - verifyEqualVectors(t, add(vec1, zero), vec1) -} - -func TestCoordinate_diff(t *testing.T) { - vec1 := []float64{1.0, -3.0, 3.0} - vec2 := []float64{-4.0, 5.0, 6.0} - verifyEqualVectors(t, diff(vec1, vec2), []float64{5.0, -8.0, -3.0}) - - zero := []float64{0.0, 0.0, 0.0} - verifyEqualVectors(t, diff(vec1, zero), vec1) -} - -func TestCoordinate_magnitude(t *testing.T) { - zero := []float64{0.0, 0.0, 0.0} - verifyEqualFloats(t, magnitude(zero), 0.0) - - vec := []float64{1.0, -2.0, 3.0} - verifyEqualFloats(t, magnitude(vec), 3.7416573867739413) -} - -func TestCoordinate_unitVectorAt(t *testing.T) { - vec1 := []float64{1.0, 2.0, 3.0} - vec2 := []float64{0.5, 0.6, 0.7} - u, mag := unitVectorAt(vec1, vec2) - verifyEqualVectors(t, u, []float64{0.18257418583505536, 0.511207720338155, 0.8398412548412546}) - verifyEqualFloats(t, magnitude(u), 1.0) - verifyEqualFloats(t, mag, magnitude(diff(vec1, vec2))) - - // If we give positions that are equal we should get a random unit vector - // returned to us, rather than a divide by zero. - u, mag = unitVectorAt(vec1, vec1) - verifyEqualFloats(t, magnitude(u), 1.0) - verifyEqualFloats(t, mag, 0.0) - - // We can't hit the final clause without heroics so I manually forced it - // there to verify it works. -} diff --git a/vendor/github.com/hashicorp/serf/coordinate/performance_test.go b/vendor/github.com/hashicorp/serf/coordinate/performance_test.go deleted file mode 100644 index fc676e20f..000000000 --- a/vendor/github.com/hashicorp/serf/coordinate/performance_test.go +++ /dev/null @@ -1,182 +0,0 @@ -package coordinate - -import ( - "math" - "testing" - "time" -) - -func TestPerformance_Line(t *testing.T) { - const spacing = 10 * time.Millisecond - const nodes, cycles = 10, 1000 - config := DefaultConfig() - clients, err := GenerateClients(nodes, config) - if err != nil { - t.Fatal(err) - } - truth := GenerateLine(nodes, spacing) - Simulate(clients, truth, cycles) - stats := Evaluate(clients, truth) - if stats.ErrorAvg > 0.0018 || stats.ErrorMax > 0.0092 { - t.Fatalf("performance stats are out of spec: %v", stats) - } -} - -func TestPerformance_Grid(t *testing.T) { - const spacing = 10 * time.Millisecond - const nodes, cycles = 25, 1000 - config := DefaultConfig() - clients, err := GenerateClients(nodes, config) - if err != nil { - t.Fatal(err) - } - truth := GenerateGrid(nodes, spacing) - Simulate(clients, truth, cycles) - stats := Evaluate(clients, truth) - if stats.ErrorAvg > 0.0015 || stats.ErrorMax > 0.022 { - t.Fatalf("performance stats are out of spec: %v", stats) - } -} - -func TestPerformance_Split(t *testing.T) { - const lan, wan = 1 * time.Millisecond, 10 * time.Millisecond - const nodes, cycles = 25, 1000 - config := DefaultConfig() - clients, err := GenerateClients(nodes, config) - if err != nil { - t.Fatal(err) - } - truth := GenerateSplit(nodes, lan, wan) - Simulate(clients, truth, cycles) - stats := Evaluate(clients, truth) - if stats.ErrorAvg > 0.000060 || stats.ErrorMax > 0.00048 { - t.Fatalf("performance stats are out of spec: %v", stats) - } -} - -func TestPerformance_Height(t *testing.T) { - const radius = 100 * time.Millisecond - const nodes, cycles = 25, 1000 - - // Constrain us to two dimensions so that we can just exactly represent - // the circle. - config := DefaultConfig() - config.Dimensionality = 2 - clients, err := GenerateClients(nodes, config) - if err != nil { - t.Fatal(err) - } - - // Generate truth where the first coordinate is in the "middle" because - // it's equidistant from all the nodes, but it will have an extra radius - // added to the distance, so it should come out above all the others. - truth := GenerateCircle(nodes, radius) - Simulate(clients, truth, cycles) - - // Make sure the height looks reasonable with the regular nodes all in a - // plane, and the center node up above. - for i, _ := range clients { - coord := clients[i].GetCoordinate() - if i == 0 { - if coord.Height < 0.97*radius.Seconds() { - t.Fatalf("height is out of spec: %9.6f", coord.Height) - } - } else { - if coord.Height > 0.03*radius.Seconds() { - t.Fatalf("height is out of spec: %9.6f", coord.Height) - } - } - } - stats := Evaluate(clients, truth) - if stats.ErrorAvg > 0.0025 || stats.ErrorMax > 0.064 { - t.Fatalf("performance stats are out of spec: %v", stats) - } -} - -func TestPerformance_Drift(t *testing.T) { - const dist = 500 * time.Millisecond - const nodes = 4 - config := DefaultConfig() - config.Dimensionality = 2 - clients, err := GenerateClients(nodes, config) - if err != nil { - t.Fatal(err) - } - - // Do some icky surgery on the clients to put them into a square, up in - // the first quadrant. - clients[0].coord.Vec = []float64{0.0, 0.0} - clients[1].coord.Vec = []float64{0.0, dist.Seconds()} - clients[2].coord.Vec = []float64{dist.Seconds(), dist.Seconds()} - clients[3].coord.Vec = []float64{dist.Seconds(), dist.Seconds()} - - // Make a corresponding truth matrix. The nodes are laid out like this - // so the distances are all equal, except for the diagonal: - // - // (1) <- dist -> (2) - // - // | <- dist | - // | | - // | dist -> | - // - // (0) <- dist -> (3) - // - truth := make([][]time.Duration, nodes) - for i := range truth { - truth[i] = make([]time.Duration, nodes) - } - for i := 0; i < nodes; i++ { - for j := i + 1; j < nodes; j++ { - rtt := dist - if (i%2 == 0) && (j%2 == 0) { - rtt = time.Duration(math.Sqrt2 * float64(rtt)) - } - truth[i][j], truth[j][i] = rtt, rtt - } - } - - calcCenterError := func() float64 { - min, max := clients[0].GetCoordinate(), clients[0].GetCoordinate() - for i := 1; i < nodes; i++ { - coord := clients[i].GetCoordinate() - for j, v := range coord.Vec { - min.Vec[j] = math.Min(min.Vec[j], v) - max.Vec[j] = math.Max(max.Vec[j], v) - } - } - - mid := make([]float64, config.Dimensionality) - for i, _ := range mid { - mid[i] = min.Vec[i] + (max.Vec[i]-min.Vec[i])/2 - } - return magnitude(mid) - } - - // Let the simulation run for a while to stabilize, then snap a baseline - // for the center error. - Simulate(clients, truth, 1000) - baseline := calcCenterError() - - // Now run for a bunch more cycles and see if gravity pulls the center - // in the right direction. - Simulate(clients, truth, 10000) - if error := calcCenterError(); error > 0.8*baseline { - t.Fatalf("drift performance out of spec: %9.6f -> %9.6f", baseline, error) - } -} - -func TestPerformance_Random(t *testing.T) { - const mean, deviation = 100 * time.Millisecond, 10 * time.Millisecond - const nodes, cycles = 25, 1000 - config := DefaultConfig() - clients, err := GenerateClients(nodes, config) - if err != nil { - t.Fatal(err) - } - truth := GenerateRandom(nodes, mean, deviation) - Simulate(clients, truth, cycles) - stats := Evaluate(clients, truth) - if stats.ErrorAvg > 0.075 || stats.ErrorMax > 0.33 { - t.Fatalf("performance stats are out of spec: %v", stats) - } -} diff --git a/vendor/github.com/hashicorp/serf/coordinate/util_test.go b/vendor/github.com/hashicorp/serf/coordinate/util_test.go deleted file mode 100644 index 116e94933..000000000 --- a/vendor/github.com/hashicorp/serf/coordinate/util_test.go +++ /dev/null @@ -1,27 +0,0 @@ -package coordinate - -import ( - "math" - "testing" -) - -// verifyEqualFloats will compare f1 and f2 and fail if they are not -// "equal" within a threshold. -func verifyEqualFloats(t *testing.T, f1 float64, f2 float64) { - const zeroThreshold = 1.0e-6 - if math.Abs(f1-f2) > zeroThreshold { - t.Fatalf("equal assertion fail, %9.6f != %9.6f", f1, f2) - } -} - -// verifyEqualVectors will compare vec1 and vec2 and fail if they are not -// "equal" within a threshold. -func verifyEqualVectors(t *testing.T, vec1 []float64, vec2 []float64) { - if len(vec1) != len(vec2) { - t.Fatalf("vector length mismatch, %d != %d", len(vec1), len(vec2)) - } - - for i, _ := range vec1 { - verifyEqualFloats(t, vec1[i], vec2[i]) - } -} diff --git a/vendor/github.com/hashicorp/serf/ops-misc/debian/copyright b/vendor/github.com/hashicorp/serf/ops-misc/debian/copyright new file mode 100644 index 000000000..21a1a1b53 --- /dev/null +++ b/vendor/github.com/hashicorp/serf/ops-misc/debian/copyright @@ -0,0 +1,2 @@ +Name: serf +Copyright: Hashicorp 2013 diff --git a/vendor/github.com/hashicorp/serf/website/source/LICENSE b/vendor/github.com/hashicorp/serf/website/source/LICENSE new file mode 100644 index 000000000..36c29d7f7 --- /dev/null +++ b/vendor/github.com/hashicorp/serf/website/source/LICENSE @@ -0,0 +1,10 @@ +# Proprietary License + +This license is temporary while a more official one is drafted. However, +this should make it clear: + +* The text contents of this website are MPL 2.0 licensed. + +* The design contents of this website are proprietary and may not be reproduced + or reused in any way other than to run the Serf website locally. The license + for the design is owned solely by HashiCorp, Inc. diff --git a/vendor/github.com/jessevdk/go-flags/.travis.yml b/vendor/github.com/jessevdk/go-flags/.travis.yml deleted file mode 100644 index e7c4be056..000000000 --- a/vendor/github.com/jessevdk/go-flags/.travis.yml +++ /dev/null @@ -1,38 +0,0 @@ -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/github.com/jessevdk/go-flags/README.md b/vendor/github.com/jessevdk/go-flags/README.md deleted file mode 100644 index 9378b760b..000000000 --- a/vendor/github.com/jessevdk/go-flags/README.md +++ /dev/null @@ -1,135 +0,0 @@ -go-flags: a go library for parsing command line arguments -========================================================= - -[![GoDoc](https://godoc.org/github.com/jessevdk/go-flags?status.png)](https://godoc.org/github.com/jessevdk/go-flags) [![Build Status](https://travis-ci.org/jessevdk/go-flags.svg?branch=master)](https://travis-ci.org/jessevdk/go-flags) [![Coverage Status](https://img.shields.io/coveralls/jessevdk/go-flags.svg)](https://coveralls.io/r/jessevdk/go-flags?branch=master) - -This library provides similar functionality to the builtin flag library of -go, but provides much more functionality and nicer formatting. From the -documentation: - -Package flags provides an extensive command line option parser. -The flags package is similar in functionality to the go builtin flag package -but provides more options and uses reflection to provide a convenient and -succinct way of specifying command line options. - -Supported features: -* Options with short names (-v) -* Options with long names (--verbose) -* Options with and without arguments (bool v.s. other type) -* Options with optional arguments and default values -* Multiple option groups each containing a set of options -* Generate and print well-formatted help message -* Passing remaining command line arguments after -- (optional) -* Ignoring unknown command line options (optional) -* Supports -I/usr/include -I=/usr/include -I /usr/include option argument specification -* Supports multiple short options -aux -* Supports all primitive go types (string, int{8..64}, uint{8..64}, float) -* Supports same option multiple times (can store in slice or last option counts) -* Supports maps -* Supports function callbacks -* Supports namespaces for (nested) option groups - -The flags package uses structs, reflection and struct field tags -to allow users to specify command line options. This results in very simple -and concise specification of your application options. For example: - -```go -type Options struct { - Verbose []bool `short:"v" long:"verbose" description:"Show verbose debug information"` -} -``` - -This specifies one option with a short name -v and a long name --verbose. -When either -v or --verbose is found on the command line, a 'true' value -will be appended to the Verbose field. e.g. when specifying -vvv, the -resulting value of Verbose will be {[true, true, true]}. - -Example: --------- -```go -var opts struct { - // Slice of bool will append 'true' each time the option - // is encountered (can be set multiple times, like -vvv) - Verbose []bool `short:"v" long:"verbose" description:"Show verbose debug information"` - - // Example of automatic marshalling to desired type (uint) - Offset uint `long:"offset" description:"Offset"` - - // Example of a callback, called each time the option is found. - Call func(string) `short:"c" description:"Call phone number"` - - // Example of a required flag - Name string `short:"n" long:"name" description:"A name" required:"true"` - - // Example of a value name - File string `short:"f" long:"file" description:"A file" value-name:"FILE"` - - // Example of a pointer - Ptr *int `short:"p" description:"A pointer to an integer"` - - // Example of a slice of strings - StringSlice []string `short:"s" description:"A slice of strings"` - - // Example of a slice of pointers - PtrSlice []*string `long:"ptrslice" description:"A slice of pointers to string"` - - // Example of a map - IntMap map[string]int `long:"intmap" description:"A map from string to int"` -} - -// Callback which will invoke callto: to call a number. -// Note that this works just on OS X (and probably only with -// Skype) but it shows the idea. -opts.Call = func(num string) { - cmd := exec.Command("open", "callto:"+num) - cmd.Start() - cmd.Process.Release() -} - -// Make some fake arguments to parse. -args := []string{ - "-vv", - "--offset=5", - "-n", "Me", - "-p", "3", - "-s", "hello", - "-s", "world", - "--ptrslice", "hello", - "--ptrslice", "world", - "--intmap", "a:1", - "--intmap", "b:5", - "arg1", - "arg2", - "arg3", -} - -// Parse flags from `args'. Note that here we use flags.ParseArgs for -// the sake of making a working example. Normally, you would simply use -// flags.Parse(&opts) which uses os.Args -args, err := flags.ParseArgs(&opts, args) - -if err != nil { - panic(err) - os.Exit(1) -} - -fmt.Printf("Verbosity: %v\n", opts.Verbose) -fmt.Printf("Offset: %d\n", opts.Offset) -fmt.Printf("Name: %s\n", opts.Name) -fmt.Printf("Ptr: %d\n", *opts.Ptr) -fmt.Printf("StringSlice: %v\n", opts.StringSlice) -fmt.Printf("PtrSlice: [%v %v]\n", *opts.PtrSlice[0], *opts.PtrSlice[1]) -fmt.Printf("IntMap: [a:%v b:%v]\n", opts.IntMap["a"], opts.IntMap["b"]) -fmt.Printf("Remaining args: %s\n", strings.Join(args, " ")) - -// Output: Verbosity: [true true] -// Offset: 5 -// Name: Me -// Ptr: 3 -// StringSlice: [hello world] -// PtrSlice: [hello world] -// IntMap: [a:1 b:5] -// Remaining args: arg1 arg2 arg3 -``` - -More information can be found in the godocs: diff --git a/vendor/github.com/jessevdk/go-flags/arg_test.go b/vendor/github.com/jessevdk/go-flags/arg_test.go deleted file mode 100644 index c7c0a612e..000000000 --- a/vendor/github.com/jessevdk/go-flags/arg_test.go +++ /dev/null @@ -1,163 +0,0 @@ -package flags - -import ( - "testing" -) - -func TestPositional(t *testing.T) { - var opts = struct { - Value bool `short:"v"` - - Positional struct { - Command int - Filename string - Rest []string - } `positional-args:"yes" required:"yes"` - }{} - - p := NewParser(&opts, Default) - ret, err := p.ParseArgs([]string{"10", "arg_test.go", "a", "b"}) - - if err != nil { - t.Fatalf("Unexpected error: %v", err) - return - } - - if opts.Positional.Command != 10 { - t.Fatalf("Expected opts.Positional.Command to be 10, but got %v", opts.Positional.Command) - } - - if opts.Positional.Filename != "arg_test.go" { - t.Fatalf("Expected opts.Positional.Filename to be \"arg_test.go\", but got %v", opts.Positional.Filename) - } - - assertStringArray(t, opts.Positional.Rest, []string{"a", "b"}) - assertStringArray(t, ret, []string{}) -} - -func TestPositionalRequired(t *testing.T) { - var opts = struct { - Value bool `short:"v"` - - Positional struct { - Command int - Filename string - Rest []string - } `positional-args:"yes" required:"yes"` - }{} - - p := NewParser(&opts, None) - _, err := p.ParseArgs([]string{"10"}) - - assertError(t, err, ErrRequired, "the required argument `Filename` was not provided") -} - -func TestPositionalRequiredRest1Fail(t *testing.T) { - var opts = struct { - Value bool `short:"v"` - - Positional struct { - Rest []string `required:"yes"` - } `positional-args:"yes"` - }{} - - p := NewParser(&opts, None) - _, err := p.ParseArgs([]string{}) - - assertError(t, err, ErrRequired, "the required argument `Rest (at least 1 argument)` was not provided") -} - -func TestPositionalRequiredRest1Pass(t *testing.T) { - var opts = struct { - Value bool `short:"v"` - - Positional struct { - Rest []string `required:"yes"` - } `positional-args:"yes"` - }{} - - p := NewParser(&opts, None) - _, err := p.ParseArgs([]string{"rest1"}) - - if err != nil { - t.Fatalf("Unexpected error: %v", err) - return - } - - if len(opts.Positional.Rest) != 1 { - t.Fatalf("Expected 1 positional rest argument") - } - - assertString(t, opts.Positional.Rest[0], "rest1") -} - -func TestPositionalRequiredRest2Fail(t *testing.T) { - var opts = struct { - Value bool `short:"v"` - - Positional struct { - Rest []string `required:"2"` - } `positional-args:"yes"` - }{} - - p := NewParser(&opts, None) - _, err := p.ParseArgs([]string{"rest1"}) - - assertError(t, err, ErrRequired, "the required argument `Rest (at least 2 arguments, but got only 1)` was not provided") -} - -func TestPositionalRequiredRest2Pass(t *testing.T) { - var opts = struct { - Value bool `short:"v"` - - Positional struct { - Rest []string `required:"2"` - } `positional-args:"yes"` - }{} - - p := NewParser(&opts, None) - _, err := p.ParseArgs([]string{"rest1", "rest2", "rest3"}) - - if err != nil { - t.Fatalf("Unexpected error: %v", err) - return - } - - if len(opts.Positional.Rest) != 3 { - t.Fatalf("Expected 3 positional rest argument") - } - - assertString(t, opts.Positional.Rest[0], "rest1") - assertString(t, opts.Positional.Rest[1], "rest2") - assertString(t, opts.Positional.Rest[2], "rest3") -} - -func TestPositionalRequiredRestRangeFail(t *testing.T) { - var opts = struct { - Value bool `short:"v"` - - Positional struct { - Rest []string `required:"1-2"` - } `positional-args:"yes"` - }{} - - p := NewParser(&opts, None) - _, err := p.ParseArgs([]string{"rest1", "rest2", "rest3"}) - - assertError(t, err, ErrRequired, "the required argument `Rest (at most 2 arguments, but got 3)` was not provided") -} - -func TestPositionalRequiredRestRangeEmptyFail(t *testing.T) { - var opts = struct { - Value bool `short:"v"` - - Positional struct { - Rest []string `required:"0-0"` - } `positional-args:"yes"` - }{} - - p := NewParser(&opts, None) - _, err := p.ParseArgs([]string{"some", "thing"}) - - assertError(t, err, ErrRequired, "the required argument `Rest (zero arguments)` was not provided") -} diff --git a/vendor/github.com/jessevdk/go-flags/assert_test.go b/vendor/github.com/jessevdk/go-flags/assert_test.go deleted file mode 100644 index 8e06636b6..000000000 --- a/vendor/github.com/jessevdk/go-flags/assert_test.go +++ /dev/null @@ -1,177 +0,0 @@ -package flags - -import ( - "fmt" - "io" - "io/ioutil" - "os" - "os/exec" - "path" - "runtime" - "testing" -) - -func assertCallerInfo() (string, int) { - ptr := make([]uintptr, 15) - n := runtime.Callers(1, ptr) - - if n == 0 { - return "", 0 - } - - mef := runtime.FuncForPC(ptr[0]) - mefile, meline := mef.FileLine(ptr[0]) - - for i := 2; i < n; i++ { - f := runtime.FuncForPC(ptr[i]) - file, line := f.FileLine(ptr[i]) - - if file != mefile { - return file, line - } - } - - return mefile, meline -} - -func assertErrorf(t *testing.T, format string, args ...interface{}) { - msg := fmt.Sprintf(format, args...) - - file, line := assertCallerInfo() - - t.Errorf("%s:%d: %s", path.Base(file), line, msg) -} - -func assertFatalf(t *testing.T, format string, args ...interface{}) { - msg := fmt.Sprintf(format, args...) - - file, line := assertCallerInfo() - - t.Fatalf("%s:%d: %s", path.Base(file), line, msg) -} - -func assertString(t *testing.T, a string, b string) { - if a != b { - assertErrorf(t, "Expected %#v, but got %#v", b, a) - } -} - -func assertStringArray(t *testing.T, a []string, b []string) { - if len(a) != len(b) { - assertErrorf(t, "Expected %#v, but got %#v", b, a) - return - } - - for i, v := range a { - if b[i] != v { - assertErrorf(t, "Expected %#v, but got %#v", b, a) - return - } - } -} - -func assertBoolArray(t *testing.T, a []bool, b []bool) { - if len(a) != len(b) { - assertErrorf(t, "Expected %#v, but got %#v", b, a) - return - } - - for i, v := range a { - if b[i] != v { - assertErrorf(t, "Expected %#v, but got %#v", b, a) - return - } - } -} - -func assertParserSuccess(t *testing.T, data interface{}, args ...string) (*Parser, []string) { - parser := NewParser(data, Default&^PrintErrors) - ret, err := parser.ParseArgs(args) - - if err != nil { - t.Fatalf("Unexpected parse error: %s", err) - return nil, nil - } - - return parser, ret -} - -func assertParseSuccess(t *testing.T, data interface{}, args ...string) []string { - _, ret := assertParserSuccess(t, data, args...) - return ret -} - -func assertError(t *testing.T, err error, typ ErrorType, msg string) { - if err == nil { - assertFatalf(t, "Expected error: %s", msg) - return - } - - if e, ok := err.(*Error); !ok { - assertFatalf(t, "Expected Error type, but got %#v", err) - } else { - if e.Type != typ { - assertErrorf(t, "Expected error type {%s}, but got {%s}", typ, e.Type) - } - - if e.Message != msg { - assertErrorf(t, "Expected error message %#v, but got %#v", msg, e.Message) - } - } -} - -func assertParseFail(t *testing.T, typ ErrorType, msg string, data interface{}, args ...string) []string { - parser := NewParser(data, Default&^PrintErrors) - ret, err := parser.ParseArgs(args) - - assertError(t, err, typ, msg) - return ret -} - -func diff(a, b string) (string, error) { - atmp, err := ioutil.TempFile("", "help-diff") - - if err != nil { - return "", err - } - - btmp, err := ioutil.TempFile("", "help-diff") - - if err != nil { - return "", err - } - - if _, err := io.WriteString(atmp, a); err != nil { - return "", err - } - - if _, err := io.WriteString(btmp, b); err != nil { - return "", err - } - - ret, err := exec.Command("diff", "-u", "-d", "--label", "got", atmp.Name(), "--label", "expected", btmp.Name()).Output() - - os.Remove(atmp.Name()) - os.Remove(btmp.Name()) - - if err.Error() == "exit status 1" { - return string(ret), nil - } - - return string(ret), err -} - -func assertDiff(t *testing.T, actual, expected, msg string) { - if actual == expected { - return - } - - ret, err := diff(actual, expected) - - if err != nil { - assertErrorf(t, "Unexpected diff error: %s", err) - assertErrorf(t, "Unexpected %s, expected:\n\n%s\n\nbut got\n\n%s", msg, expected, actual) - } else { - assertErrorf(t, "Unexpected %s:\n\n%s", msg, ret) - } -} diff --git a/vendor/github.com/jessevdk/go-flags/check_crosscompile.sh b/vendor/github.com/jessevdk/go-flags/check_crosscompile.sh deleted file mode 100755 index c494f6119..000000000 --- a/vendor/github.com/jessevdk/go-flags/check_crosscompile.sh +++ /dev/null @@ -1,16 +0,0 @@ -#!/bin/bash - -set -e - -echo '# linux arm7' -GOARM=7 GOARCH=arm GOOS=linux go build -echo '# linux arm5' -GOARM=5 GOARCH=arm GOOS=linux go build -echo '# windows 386' -GOARCH=386 GOOS=windows go build -echo '# windows amd64' -GOARCH=amd64 GOOS=windows go build -echo '# darwin' -GOARCH=amd64 GOOS=darwin go build -echo '# freebsd' -GOARCH=amd64 GOOS=freebsd go build diff --git a/vendor/github.com/jessevdk/go-flags/command_test.go b/vendor/github.com/jessevdk/go-flags/command_test.go deleted file mode 100644 index dc04b66c6..000000000 --- a/vendor/github.com/jessevdk/go-flags/command_test.go +++ /dev/null @@ -1,582 +0,0 @@ -package flags - -import ( - "fmt" - "testing" -) - -func TestCommandInline(t *testing.T) { - var opts = struct { - Value bool `short:"v"` - - Command struct { - G bool `short:"g"` - } `command:"cmd"` - }{} - - p, ret := assertParserSuccess(t, &opts, "-v", "cmd", "-g") - - assertStringArray(t, ret, []string{}) - - if p.Active == nil { - t.Errorf("Expected active command") - } - - if !opts.Value { - t.Errorf("Expected Value to be true") - } - - if !opts.Command.G { - t.Errorf("Expected Command.G to be true") - } - - if p.Command.Find("cmd") != p.Active { - t.Errorf("Expected to find command `cmd' to be active") - } -} - -func TestCommandInlineMulti(t *testing.T) { - var opts = struct { - Value bool `short:"v"` - - C1 struct { - } `command:"c1"` - - C2 struct { - G bool `short:"g"` - } `command:"c2"` - }{} - - p, ret := assertParserSuccess(t, &opts, "-v", "c2", "-g") - - assertStringArray(t, ret, []string{}) - - if p.Active == nil { - t.Errorf("Expected active command") - } - - if !opts.Value { - t.Errorf("Expected Value to be true") - } - - if !opts.C2.G { - t.Errorf("Expected C2.G to be true") - } - - if p.Command.Find("c1") == nil { - t.Errorf("Expected to find command `c1'") - } - - if c2 := p.Command.Find("c2"); c2 == nil { - t.Errorf("Expected to find command `c2'") - } else if c2 != p.Active { - t.Errorf("Expected to find command `c2' to be active") - } -} - -func TestCommandFlagOrder1(t *testing.T) { - var opts = struct { - Value bool `short:"v"` - - Command struct { - G bool `short:"g"` - } `command:"cmd"` - }{} - - assertParseFail(t, ErrUnknownFlag, "unknown flag `g'", &opts, "-v", "-g", "cmd") -} - -func TestCommandFlagOrder2(t *testing.T) { - var opts = struct { - Value bool `short:"v"` - - Command struct { - G bool `short:"g"` - } `command:"cmd"` - }{} - - assertParseSuccess(t, &opts, "cmd", "-v", "-g") - - if !opts.Value { - t.Errorf("Expected Value to be true") - } - - if !opts.Command.G { - t.Errorf("Expected Command.G to be true") - } -} - -func TestCommandFlagOrderSub(t *testing.T) { - var opts = struct { - Value bool `short:"v"` - - Command struct { - G bool `short:"g"` - - SubCommand struct { - B bool `short:"b"` - } `command:"sub"` - } `command:"cmd"` - }{} - - assertParseSuccess(t, &opts, "cmd", "sub", "-v", "-g", "-b") - - if !opts.Value { - t.Errorf("Expected Value to be true") - } - - if !opts.Command.G { - t.Errorf("Expected Command.G to be true") - } - - if !opts.Command.SubCommand.B { - t.Errorf("Expected Command.SubCommand.B to be true") - } -} - -func TestCommandFlagOverride1(t *testing.T) { - var opts = struct { - Value bool `short:"v"` - - Command struct { - Value bool `short:"v"` - } `command:"cmd"` - }{} - - assertParseSuccess(t, &opts, "-v", "cmd") - - if !opts.Value { - t.Errorf("Expected Value to be true") - } - - if opts.Command.Value { - t.Errorf("Expected Command.Value to be false") - } -} - -func TestCommandFlagOverride2(t *testing.T) { - var opts = struct { - Value bool `short:"v"` - - Command struct { - Value bool `short:"v"` - } `command:"cmd"` - }{} - - assertParseSuccess(t, &opts, "cmd", "-v") - - if opts.Value { - t.Errorf("Expected Value to be false") - } - - if !opts.Command.Value { - t.Errorf("Expected Command.Value to be true") - } -} - -func TestCommandFlagOverrideSub(t *testing.T) { - var opts = struct { - Value bool `short:"v"` - - Command struct { - Value bool `short:"v"` - - SubCommand struct { - Value bool `short:"v"` - } `command:"sub"` - } `command:"cmd"` - }{} - - assertParseSuccess(t, &opts, "cmd", "sub", "-v") - - if opts.Value { - t.Errorf("Expected Value to be false") - } - - if opts.Command.Value { - t.Errorf("Expected Command.Value to be false") - } - - if !opts.Command.SubCommand.Value { - t.Errorf("Expected Command.Value to be true") - } -} - -func TestCommandFlagOverrideSub2(t *testing.T) { - var opts = struct { - Value bool `short:"v"` - - Command struct { - Value bool `short:"v"` - - SubCommand struct { - G bool `short:"g"` - } `command:"sub"` - } `command:"cmd"` - }{} - - assertParseSuccess(t, &opts, "cmd", "sub", "-v") - - if opts.Value { - t.Errorf("Expected Value to be false") - } - - if !opts.Command.Value { - t.Errorf("Expected Command.Value to be true") - } -} - -func TestCommandEstimate(t *testing.T) { - var opts = struct { - Value bool `short:"v"` - - Cmd1 struct { - } `command:"remove"` - - Cmd2 struct { - } `command:"add"` - }{} - - p := NewParser(&opts, None) - _, err := p.ParseArgs([]string{}) - - assertError(t, err, ErrCommandRequired, "Please specify one command of: add or remove") -} - -func TestCommandEstimate2(t *testing.T) { - var opts = struct { - Value bool `short:"v"` - - Cmd1 struct { - } `command:"remove"` - - Cmd2 struct { - } `command:"add"` - }{} - - p := NewParser(&opts, None) - _, err := p.ParseArgs([]string{"rmive"}) - - assertError(t, err, ErrUnknownCommand, "Unknown command `rmive', did you mean `remove'?") -} - -type testCommand struct { - G bool `short:"g"` - Executed bool - EArgs []string -} - -func (c *testCommand) Execute(args []string) error { - c.Executed = true - c.EArgs = args - - return nil -} - -func TestCommandExecute(t *testing.T) { - var opts = struct { - Value bool `short:"v"` - - Command testCommand `command:"cmd"` - }{} - - assertParseSuccess(t, &opts, "-v", "cmd", "-g", "a", "b") - - if !opts.Value { - t.Errorf("Expected Value to be true") - } - - if !opts.Command.Executed { - t.Errorf("Did not execute command") - } - - if !opts.Command.G { - t.Errorf("Expected Command.C to be true") - } - - assertStringArray(t, opts.Command.EArgs, []string{"a", "b"}) -} - -func TestCommandClosest(t *testing.T) { - var opts = struct { - Value bool `short:"v"` - - Cmd1 struct { - } `command:"remove"` - - Cmd2 struct { - } `command:"add"` - }{} - - args := assertParseFail(t, ErrUnknownCommand, "Unknown command `addd', did you mean `add'?", &opts, "-v", "addd") - - assertStringArray(t, args, []string{"addd"}) -} - -func TestCommandAdd(t *testing.T) { - var opts = struct { - Value bool `short:"v"` - }{} - - var cmd = struct { - G bool `short:"g"` - }{} - - p := NewParser(&opts, Default) - c, err := p.AddCommand("cmd", "", "", &cmd) - - if err != nil { - t.Fatalf("Unexpected error: %v", err) - return - } - - ret, err := p.ParseArgs([]string{"-v", "cmd", "-g", "rest"}) - - if err != nil { - t.Fatalf("Unexpected error: %v", err) - return - } - - assertStringArray(t, ret, []string{"rest"}) - - if !opts.Value { - t.Errorf("Expected Value to be true") - } - - if !cmd.G { - t.Errorf("Expected Command.G to be true") - } - - if p.Command.Find("cmd") != c { - t.Errorf("Expected to find command `cmd'") - } - - if p.Commands()[0] != c { - t.Errorf("Expected command %#v, but got %#v", c, p.Commands()[0]) - } - - if c.Options()[0].ShortName != 'g' { - t.Errorf("Expected short name `g' but got %v", c.Options()[0].ShortName) - } -} - -func TestCommandNestedInline(t *testing.T) { - var opts = struct { - Value bool `short:"v"` - - Command struct { - G bool `short:"g"` - - Nested struct { - N string `long:"n"` - } `command:"nested"` - } `command:"cmd"` - }{} - - p, ret := assertParserSuccess(t, &opts, "-v", "cmd", "-g", "nested", "--n", "n", "rest") - - assertStringArray(t, ret, []string{"rest"}) - - if !opts.Value { - t.Errorf("Expected Value to be true") - } - - if !opts.Command.G { - t.Errorf("Expected Command.G to be true") - } - - assertString(t, opts.Command.Nested.N, "n") - - if c := p.Command.Find("cmd"); c == nil { - t.Errorf("Expected to find command `cmd'") - } else { - if c != p.Active { - t.Errorf("Expected `cmd' to be the active parser command") - } - - if nested := c.Find("nested"); nested == nil { - t.Errorf("Expected to find command `nested'") - } else if nested != c.Active { - t.Errorf("Expected to find command `nested' to be the active `cmd' command") - } - } -} - -func TestRequiredOnCommand(t *testing.T) { - var opts = struct { - Value bool `short:"v" required:"true"` - - Command struct { - G bool `short:"g"` - } `command:"cmd"` - }{} - - assertParseFail(t, ErrRequired, fmt.Sprintf("the required flag `%cv' was not specified", defaultShortOptDelimiter), &opts, "cmd") -} - -func TestRequiredAllOnCommand(t *testing.T) { - var opts = struct { - Value bool `short:"v" required:"true"` - Missing bool `long:"missing" required:"true"` - - Command struct { - G bool `short:"g"` - } `command:"cmd"` - }{} - - assertParseFail(t, ErrRequired, fmt.Sprintf("the required flags `%smissing' and `%cv' were not specified", defaultLongOptDelimiter, defaultShortOptDelimiter), &opts, "cmd") -} - -func TestDefaultOnCommand(t *testing.T) { - var opts = struct { - Command struct { - G string `short:"g" default:"value"` - } `command:"cmd"` - }{} - - assertParseSuccess(t, &opts, "cmd") - - if opts.Command.G != "value" { - t.Errorf("Expected G to be \"value\"") - } -} - -func TestAfterNonCommand(t *testing.T) { - var opts = struct { - Value bool `short:"v"` - - Cmd1 struct { - } `command:"remove"` - - Cmd2 struct { - } `command:"add"` - }{} - - assertParseFail(t, ErrUnknownCommand, "Unknown command `nocmd'. Please specify one command of: add or remove", &opts, "nocmd", "remove") -} - -func TestSubcommandsOptional(t *testing.T) { - var opts = struct { - Value bool `short:"v"` - - Cmd1 struct { - } `command:"remove"` - - Cmd2 struct { - } `command:"add"` - }{} - - p := NewParser(&opts, None) - p.SubcommandsOptional = true - - _, err := p.ParseArgs([]string{"-v"}) - - if err != nil { - t.Fatalf("Unexpected error: %v", err) - return - } - - if !opts.Value { - t.Errorf("Expected Value to be true") - } -} - -func TestSubcommandsOptionalAfterNonCommand(t *testing.T) { - var opts = struct { - Value bool `short:"v"` - - Cmd1 struct { - } `command:"remove"` - - Cmd2 struct { - } `command:"add"` - }{} - - p := NewParser(&opts, None) - p.SubcommandsOptional = true - - retargs, err := p.ParseArgs([]string{"nocmd", "remove"}) - - if err != nil { - t.Fatalf("Unexpected error: %v", err) - return - } - - assertStringArray(t, retargs, []string{"nocmd", "remove"}) -} - -func TestCommandAlias(t *testing.T) { - var opts = struct { - Command struct { - G string `short:"g" default:"value"` - } `command:"cmd" alias:"cm"` - }{} - - assertParseSuccess(t, &opts, "cm") - - if opts.Command.G != "value" { - t.Errorf("Expected G to be \"value\"") - } -} - -func TestSubCommandFindOptionByLongFlag(t *testing.T) { - var opts struct { - Testing bool `long:"testing" description:"Testing"` - } - - var cmd struct { - Other bool `long:"other" description:"Other"` - } - - p := NewParser(&opts, Default) - c, _ := p.AddCommand("command", "Short", "Long", &cmd) - - opt := c.FindOptionByLongName("other") - - if opt == nil { - t.Errorf("Expected option, but found none") - } - - assertString(t, opt.LongName, "other") - - opt = c.FindOptionByLongName("testing") - - if opt == nil { - t.Errorf("Expected option, but found none") - } - - assertString(t, opt.LongName, "testing") -} - -func TestSubCommandFindOptionByShortFlag(t *testing.T) { - var opts struct { - Testing bool `short:"t" description:"Testing"` - } - - var cmd struct { - Other bool `short:"o" description:"Other"` - } - - p := NewParser(&opts, Default) - c, _ := p.AddCommand("command", "Short", "Long", &cmd) - - opt := c.FindOptionByShortName('o') - - if opt == nil { - t.Errorf("Expected option, but found none") - } - - if opt.ShortName != 'o' { - t.Errorf("Expected 'o', but got %v", opt.ShortName) - } - - opt = c.FindOptionByShortName('t') - - if opt == nil { - t.Errorf("Expected option, but found none") - } - - if opt.ShortName != 't' { - t.Errorf("Expected 'o', but got %v", opt.ShortName) - } -} diff --git a/vendor/github.com/jessevdk/go-flags/completion_test.go b/vendor/github.com/jessevdk/go-flags/completion_test.go deleted file mode 100644 index 26f70e424..000000000 --- a/vendor/github.com/jessevdk/go-flags/completion_test.go +++ /dev/null @@ -1,315 +0,0 @@ -package flags - -import ( - "bytes" - "io" - "os" - "path" - "path/filepath" - "reflect" - "runtime" - "strings" - "testing" -) - -type TestComplete struct { -} - -func (t *TestComplete) Complete(match string) []Completion { - options := []string{ - "hello world", - "hello universe", - "hello multiverse", - } - - ret := make([]Completion, 0, len(options)) - - for _, o := range options { - if strings.HasPrefix(o, match) { - ret = append(ret, Completion{ - Item: o, - }) - } - } - - return ret -} - -var completionTestOptions struct { - Verbose bool `short:"v" long:"verbose" description:"Verbose messages"` - Debug bool `short:"d" long:"debug" description:"Enable debug"` - Info bool `short:"i" description:"Display info"` - Version bool `long:"version" description:"Show version"` - Required bool `long:"required" required:"true" description:"This is required"` - Hidden bool `long:"hidden" hidden:"true" description:"This is hidden"` - - AddCommand struct { - Positional struct { - Filename Filename - } `positional-args:"yes"` - } `command:"add" description:"add an item"` - - AddMultiCommand struct { - Positional struct { - Filename []Filename - } `positional-args:"yes"` - Extra []Filename `short:"f"` - } `command:"add-multi" description:"add multiple items"` - - AddMultiCommandFlag struct { - Files []Filename `short:"f"` - } `command:"add-multi-flag" description:"add multiple items via flags"` - - RemoveCommand struct { - Other bool `short:"o"` - File Filename `short:"f" long:"filename"` - } `command:"rm" description:"remove an item"` - - RenameCommand struct { - Completed TestComplete `short:"c" long:"completed"` - } `command:"rename" description:"rename an item"` -} - -type completionTest struct { - Args []string - Completed []string - ShowDescriptions bool -} - -var completionTests []completionTest - -func init() { - _, sourcefile, _, _ := runtime.Caller(0) - completionTestSourcedir := filepath.Join(filepath.SplitList(path.Dir(sourcefile))...) - - completionTestFilename := []string{filepath.Join(completionTestSourcedir, "completion.go"), filepath.Join(completionTestSourcedir, "completion_test.go")} - - completionTests = []completionTest{ - { - // Short names - []string{"-"}, - []string{"--debug", "--required", "--verbose", "--version", "-i"}, - false, - }, - - { - // Short names full - []string{"-i"}, - []string{"-i"}, - false, - }, - - { - // Short names concatenated - []string{"-dv"}, - []string{"-dv"}, - false, - }, - - { - // Long names - []string{"--"}, - []string{"--debug", "--required", "--verbose", "--version"}, - false, - }, - - { - // Long names with descriptions - []string{"--"}, - []string{ - "--debug # Enable debug", - "--required # This is required", - "--verbose # Verbose messages", - "--version # Show version", - }, - true, - }, - - { - // Long names partial - []string{"--ver"}, - []string{"--verbose", "--version"}, - false, - }, - - { - // Commands - []string{""}, - []string{"add", "add-multi", "add-multi-flag", "rename", "rm"}, - false, - }, - - { - // Commands with descriptions - []string{""}, - []string{ - "add # add an item", - "add-multi # add multiple items", - "add-multi-flag # add multiple items via flags", - "rename # rename an item", - "rm # remove an item", - }, - true, - }, - - { - // Commands partial - []string{"r"}, - []string{"rename", "rm"}, - false, - }, - - { - // Positional filename - []string{"add", filepath.Join(completionTestSourcedir, "completion")}, - completionTestFilename, - false, - }, - - { - // Multiple positional filename (1 arg) - []string{"add-multi", filepath.Join(completionTestSourcedir, "completion")}, - completionTestFilename, - false, - }, - { - // Multiple positional filename (2 args) - []string{"add-multi", filepath.Join(completionTestSourcedir, "completion.go"), filepath.Join(completionTestSourcedir, "completion")}, - completionTestFilename, - false, - }, - { - // Multiple positional filename (3 args) - []string{"add-multi", filepath.Join(completionTestSourcedir, "completion.go"), filepath.Join(completionTestSourcedir, "completion.go"), filepath.Join(completionTestSourcedir, "completion")}, - completionTestFilename, - false, - }, - - { - // Flag filename - []string{"rm", "-f", path.Join(completionTestSourcedir, "completion")}, - completionTestFilename, - false, - }, - - { - // Flag short concat last filename - []string{"rm", "-of", path.Join(completionTestSourcedir, "completion")}, - completionTestFilename, - false, - }, - - { - // Flag concat filename - []string{"rm", "-f" + path.Join(completionTestSourcedir, "completion")}, - []string{"-f" + completionTestFilename[0], "-f" + completionTestFilename[1]}, - false, - }, - - { - // Flag equal concat filename - []string{"rm", "-f=" + path.Join(completionTestSourcedir, "completion")}, - []string{"-f=" + completionTestFilename[0], "-f=" + completionTestFilename[1]}, - false, - }, - - { - // Flag concat long filename - []string{"rm", "--filename=" + path.Join(completionTestSourcedir, "completion")}, - []string{"--filename=" + completionTestFilename[0], "--filename=" + completionTestFilename[1]}, - false, - }, - - { - // Flag long filename - []string{"rm", "--filename", path.Join(completionTestSourcedir, "completion")}, - completionTestFilename, - false, - }, - - { - // Custom completed - []string{"rename", "-c", "hello un"}, - []string{"hello universe"}, - false, - }, - { - // Multiple flag filename - []string{"add-multi-flag", "-f", filepath.Join(completionTestSourcedir, "completion")}, - completionTestFilename, - false, - }, - } -} - -func TestCompletion(t *testing.T) { - p := NewParser(&completionTestOptions, Default) - c := &completion{parser: p} - - for _, test := range completionTests { - if test.ShowDescriptions { - continue - } - - ret := c.complete(test.Args) - items := make([]string, len(ret)) - - for i, v := range ret { - items[i] = v.Item - } - - if !reflect.DeepEqual(items, test.Completed) { - t.Errorf("Args: %#v, %#v\n Expected: %#v\n Got: %#v", test.Args, test.ShowDescriptions, test.Completed, items) - } - } -} - -func TestParserCompletion(t *testing.T) { - for _, test := range completionTests { - if test.ShowDescriptions { - os.Setenv("GO_FLAGS_COMPLETION", "verbose") - } else { - os.Setenv("GO_FLAGS_COMPLETION", "1") - } - - tmp := os.Stdout - - r, w, _ := os.Pipe() - os.Stdout = w - - out := make(chan string) - - go func() { - var buf bytes.Buffer - - io.Copy(&buf, r) - - out <- buf.String() - }() - - p := NewParser(&completionTestOptions, None) - - p.CompletionHandler = func(items []Completion) { - comp := &completion{parser: p} - comp.print(items, test.ShowDescriptions) - } - - _, err := p.ParseArgs(test.Args) - - w.Close() - - os.Stdout = tmp - - if err != nil { - t.Fatalf("Unexpected error: %s", err) - } - - got := strings.Split(strings.Trim(<-out, "\n"), "\n") - - if !reflect.DeepEqual(got, test.Completed) { - t.Errorf("Expected: %#v\nGot: %#v", test.Completed, got) - } - } - - os.Setenv("GO_FLAGS_COMPLETION", "") -} diff --git a/vendor/github.com/jessevdk/go-flags/convert_test.go b/vendor/github.com/jessevdk/go-flags/convert_test.go deleted file mode 100644 index ef131dc8d..000000000 --- a/vendor/github.com/jessevdk/go-flags/convert_test.go +++ /dev/null @@ -1,159 +0,0 @@ -package flags - -import ( - "testing" - "time" -) - -func expectConvert(t *testing.T, o *Option, expected string) { - s, err := convertToString(o.value, o.tag) - - if err != nil { - t.Errorf("Unexpected error: %v", err) - return - } - - assertString(t, s, expected) -} - -func TestConvertToString(t *testing.T) { - d, _ := time.ParseDuration("1h2m4s") - - var opts = struct { - String string `long:"string"` - - Int int `long:"int"` - Int8 int8 `long:"int8"` - Int16 int16 `long:"int16"` - Int32 int32 `long:"int32"` - Int64 int64 `long:"int64"` - - Uint uint `long:"uint"` - Uint8 uint8 `long:"uint8"` - Uint16 uint16 `long:"uint16"` - Uint32 uint32 `long:"uint32"` - Uint64 uint64 `long:"uint64"` - - Float32 float32 `long:"float32"` - Float64 float64 `long:"float64"` - - Duration time.Duration `long:"duration"` - - Bool bool `long:"bool"` - - IntSlice []int `long:"int-slice"` - IntFloatMap map[int]float64 `long:"int-float-map"` - - PtrBool *bool `long:"ptr-bool"` - Interface interface{} `long:"interface"` - - Int32Base int32 `long:"int32-base" base:"16"` - Uint32Base uint32 `long:"uint32-base" base:"16"` - }{ - "string", - - -2, - -1, - 0, - 1, - 2, - - 1, - 2, - 3, - 4, - 5, - - 1.2, - -3.4, - - d, - true, - - []int{-3, 4, -2}, - map[int]float64{-2: 4.5}, - - new(bool), - float32(5.2), - - -5823, - 4232, - } - - p := NewNamedParser("test", Default) - grp, _ := p.AddGroup("test group", "", &opts) - - expects := []string{ - "string", - "-2", - "-1", - "0", - "1", - "2", - - "1", - "2", - "3", - "4", - "5", - - "1.2", - "-3.4", - - "1h2m4s", - "true", - - "[-3, 4, -2]", - "{-2:4.5}", - - "false", - "5.2", - - "-16bf", - "1088", - } - - for i, v := range grp.Options() { - expectConvert(t, v, expects[i]) - } -} - -func TestConvertToStringInvalidIntBase(t *testing.T) { - var opts = struct { - Int int `long:"int" base:"no"` - }{ - 2, - } - - p := NewNamedParser("test", Default) - grp, _ := p.AddGroup("test group", "", &opts) - o := grp.Options()[0] - - _, err := convertToString(o.value, o.tag) - - if err != nil { - err = newErrorf(ErrMarshal, "%v", err) - } - - assertError(t, err, ErrMarshal, "strconv.ParseInt: parsing \"no\": invalid syntax") -} - -func TestConvertToStringInvalidUintBase(t *testing.T) { - var opts = struct { - Uint uint `long:"uint" base:"no"` - }{ - 2, - } - - p := NewNamedParser("test", Default) - grp, _ := p.AddGroup("test group", "", &opts) - o := grp.Options()[0] - - _, err := convertToString(o.value, o.tag) - - if err != nil { - err = newErrorf(ErrMarshal, "%v", err) - } - - assertError(t, err, ErrMarshal, "strconv.ParseInt: parsing \"no\": invalid syntax") -} diff --git a/vendor/github.com/jessevdk/go-flags/example_test.go b/vendor/github.com/jessevdk/go-flags/example_test.go deleted file mode 100644 index 4321ed8e9..000000000 --- a/vendor/github.com/jessevdk/go-flags/example_test.go +++ /dev/null @@ -1,110 +0,0 @@ -// Example of use of the flags package. -package flags - -import ( - "fmt" - "os/exec" -) - -func Example() { - var opts struct { - // Slice of bool will append 'true' each time the option - // is encountered (can be set multiple times, like -vvv) - Verbose []bool `short:"v" long:"verbose" description:"Show verbose debug information"` - - // Example of automatic marshalling to desired type (uint) - Offset uint `long:"offset" description:"Offset"` - - // Example of a callback, called each time the option is found. - Call func(string) `short:"c" description:"Call phone number"` - - // Example of a required flag - Name string `short:"n" long:"name" description:"A name" required:"true"` - - // Example of a value name - File string `short:"f" long:"file" description:"A file" value-name:"FILE"` - - // Example of a pointer - Ptr *int `short:"p" description:"A pointer to an integer"` - - // Example of a slice of strings - StringSlice []string `short:"s" description:"A slice of strings"` - - // Example of a slice of pointers - PtrSlice []*string `long:"ptrslice" description:"A slice of pointers to string"` - - // Example of a map - IntMap map[string]int `long:"intmap" description:"A map from string to int"` - - // Example of a filename (useful for completion) - Filename Filename `long:"filename" description:"A filename"` - - // Example of positional arguments - Args struct { - ID string - Num int - Rest []string - } `positional-args:"yes" required:"yes"` - } - - // Callback which will invoke callto: to call a number. - // Note that this works just on OS X (and probably only with - // Skype) but it shows the idea. - opts.Call = func(num string) { - cmd := exec.Command("open", "callto:"+num) - cmd.Start() - cmd.Process.Release() - } - - // Make some fake arguments to parse. - args := []string{ - "-vv", - "--offset=5", - "-n", "Me", - "-p", "3", - "-s", "hello", - "-s", "world", - "--ptrslice", "hello", - "--ptrslice", "world", - "--intmap", "a:1", - "--intmap", "b:5", - "--filename", "hello.go", - "id", - "10", - "remaining1", - "remaining2", - } - - // Parse flags from `args'. Note that here we use flags.ParseArgs for - // the sake of making a working example. Normally, you would simply use - // flags.Parse(&opts) which uses os.Args - _, err := ParseArgs(&opts, args) - - if err != nil { - panic(err) - } - - fmt.Printf("Verbosity: %v\n", opts.Verbose) - fmt.Printf("Offset: %d\n", opts.Offset) - fmt.Printf("Name: %s\n", opts.Name) - fmt.Printf("Ptr: %d\n", *opts.Ptr) - fmt.Printf("StringSlice: %v\n", opts.StringSlice) - fmt.Printf("PtrSlice: [%v %v]\n", *opts.PtrSlice[0], *opts.PtrSlice[1]) - fmt.Printf("IntMap: [a:%v b:%v]\n", opts.IntMap["a"], opts.IntMap["b"]) - fmt.Printf("Filename: %v\n", opts.Filename) - fmt.Printf("Args.ID: %s\n", opts.Args.ID) - fmt.Printf("Args.Num: %d\n", opts.Args.Num) - fmt.Printf("Args.Rest: %v\n", opts.Args.Rest) - - // Output: Verbosity: [true true] - // Offset: 5 - // Name: Me - // Ptr: 3 - // StringSlice: [hello world] - // PtrSlice: [hello world] - // IntMap: [a:1 b:5] - // Filename: hello.go - // Args.ID: id - // Args.Num: 10 - // Args.Rest: [remaining1 remaining2] -} diff --git a/vendor/github.com/jessevdk/go-flags/group_test.go b/vendor/github.com/jessevdk/go-flags/group_test.go deleted file mode 100644 index 18cd6c173..000000000 --- a/vendor/github.com/jessevdk/go-flags/group_test.go +++ /dev/null @@ -1,255 +0,0 @@ -package flags - -import ( - "testing" -) - -func TestGroupInline(t *testing.T) { - var opts = struct { - Value bool `short:"v"` - - Group struct { - G bool `short:"g"` - } `group:"Grouped Options"` - }{} - - p, ret := assertParserSuccess(t, &opts, "-v", "-g") - - assertStringArray(t, ret, []string{}) - - if !opts.Value { - t.Errorf("Expected Value to be true") - } - - if !opts.Group.G { - t.Errorf("Expected Group.G to be true") - } - - if p.Command.Group.Find("Grouped Options") == nil { - t.Errorf("Expected to find group `Grouped Options'") - } -} - -func TestGroupAdd(t *testing.T) { - var opts = struct { - Value bool `short:"v"` - }{} - - var grp = struct { - G bool `short:"g"` - }{} - - p := NewParser(&opts, Default) - g, err := p.AddGroup("Grouped Options", "", &grp) - - if err != nil { - t.Fatalf("Unexpected error: %v", err) - return - } - - ret, err := p.ParseArgs([]string{"-v", "-g", "rest"}) - - if err != nil { - t.Fatalf("Unexpected error: %v", err) - return - } - - assertStringArray(t, ret, []string{"rest"}) - - if !opts.Value { - t.Errorf("Expected Value to be true") - } - - if !grp.G { - t.Errorf("Expected Group.G to be true") - } - - if p.Command.Group.Find("Grouped Options") != g { - t.Errorf("Expected to find group `Grouped Options'") - } - - if p.Groups()[1] != g { - t.Errorf("Expected group %#v, but got %#v", g, p.Groups()[0]) - } - - if g.Options()[0].ShortName != 'g' { - t.Errorf("Expected short name `g' but got %v", g.Options()[0].ShortName) - } -} - -func TestGroupNestedInline(t *testing.T) { - var opts = struct { - Value bool `short:"v"` - - Group struct { - G bool `short:"g"` - - Nested struct { - N string `long:"n"` - } `group:"Nested Options"` - } `group:"Grouped Options"` - }{} - - p, ret := assertParserSuccess(t, &opts, "-v", "-g", "--n", "n", "rest") - - assertStringArray(t, ret, []string{"rest"}) - - if !opts.Value { - t.Errorf("Expected Value to be true") - } - - if !opts.Group.G { - t.Errorf("Expected Group.G to be true") - } - - assertString(t, opts.Group.Nested.N, "n") - - if p.Command.Group.Find("Grouped Options") == nil { - t.Errorf("Expected to find group `Grouped Options'") - } - - if p.Command.Group.Find("Nested Options") == nil { - t.Errorf("Expected to find group `Nested Options'") - } -} - -func TestGroupNestedInlineNamespace(t *testing.T) { - var opts = struct { - Opt string `long:"opt"` - - Group struct { - Opt string `long:"opt"` - Group struct { - Opt string `long:"opt"` - } `group:"Subsubgroup" namespace:"sap"` - } `group:"Subgroup" namespace:"sip"` - }{} - - p, ret := assertParserSuccess(t, &opts, "--opt", "a", "--sip.opt", "b", "--sip.sap.opt", "c", "rest") - - assertStringArray(t, ret, []string{"rest"}) - - assertString(t, opts.Opt, "a") - assertString(t, opts.Group.Opt, "b") - assertString(t, opts.Group.Group.Opt, "c") - - for _, name := range []string{"Subgroup", "Subsubgroup"} { - if p.Command.Group.Find(name) == nil { - t.Errorf("Expected to find group '%s'", name) - } - } -} - -func TestDuplicateShortFlags(t *testing.T) { - var opts struct { - Verbose []bool `short:"v" long:"verbose" description:"Show verbose debug information"` - Variables []string `short:"v" long:"variable" description:"Set a variable value."` - } - - args := []string{ - "--verbose", - "-v", "123", - "-v", "456", - } - - _, err := ParseArgs(&opts, args) - - if err == nil { - t.Errorf("Expected an error with type ErrDuplicatedFlag") - } else { - err2 := err.(*Error) - if err2.Type != ErrDuplicatedFlag { - t.Errorf("Expected an error with type ErrDuplicatedFlag") - } - } -} - -func TestDuplicateLongFlags(t *testing.T) { - var opts struct { - Test1 []bool `short:"a" long:"testing" description:"Test 1"` - Test2 []string `short:"b" long:"testing" description:"Test 2."` - } - - args := []string{ - "--testing", - } - - _, err := ParseArgs(&opts, args) - - if err == nil { - t.Errorf("Expected an error with type ErrDuplicatedFlag") - } else { - err2 := err.(*Error) - if err2.Type != ErrDuplicatedFlag { - t.Errorf("Expected an error with type ErrDuplicatedFlag") - } - } -} - -func TestFindOptionByLongFlag(t *testing.T) { - var opts struct { - Testing bool `long:"testing" description:"Testing"` - } - - p := NewParser(&opts, Default) - opt := p.FindOptionByLongName("testing") - - if opt == nil { - t.Errorf("Expected option, but found none") - } - - assertString(t, opt.LongName, "testing") -} - -func TestFindOptionByShortFlag(t *testing.T) { - var opts struct { - Testing bool `short:"t" description:"Testing"` - } - - p := NewParser(&opts, Default) - opt := p.FindOptionByShortName('t') - - if opt == nil { - t.Errorf("Expected option, but found none") - } - - if opt.ShortName != 't' { - t.Errorf("Expected 't', but got %v", opt.ShortName) - } -} - -func TestFindOptionByLongFlagInSubGroup(t *testing.T) { - var opts struct { - Group struct { - Testing bool `long:"testing" description:"Testing"` - } `group:"sub-group"` - } - - p := NewParser(&opts, Default) - opt := p.FindOptionByLongName("testing") - - if opt == nil { - t.Errorf("Expected option, but found none") - } - - assertString(t, opt.LongName, "testing") -} - -func TestFindOptionByShortFlagInSubGroup(t *testing.T) { - var opts struct { - Group struct { - Testing bool `short:"t" description:"Testing"` - } `group:"sub-group"` - } - - p := NewParser(&opts, Default) - opt := p.FindOptionByShortName('t') - - if opt == nil { - t.Errorf("Expected option, but found none") - } - - if opt.ShortName != 't' { - t.Errorf("Expected 't', but got %v", opt.ShortName) - } -} diff --git a/vendor/github.com/jessevdk/go-flags/help_test.go b/vendor/github.com/jessevdk/go-flags/help_test.go deleted file mode 100644 index bb7664057..000000000 --- a/vendor/github.com/jessevdk/go-flags/help_test.go +++ /dev/null @@ -1,538 +0,0 @@ -package flags - -import ( - "bufio" - "bytes" - "fmt" - "os" - "runtime" - "strings" - "testing" - "time" -) - -type helpOptions struct { - Verbose []bool `short:"v" long:"verbose" description:"Show verbose debug information" ini-name:"verbose"` - Call func(string) `short:"c" description:"Call phone number" ini-name:"call"` - PtrSlice []*string `long:"ptrslice" description:"A slice of pointers to string"` - EmptyDescription bool `long:"empty-description"` - - Default string `long:"default" default:"Some\nvalue" description:"Test default value"` - DefaultArray []string `long:"default-array" default:"Some value" default:"Other\tvalue" description:"Test default array value"` - DefaultMap map[string]string `long:"default-map" default:"some:value" default:"another:value" description:"Testdefault map value"` - EnvDefault1 string `long:"env-default1" default:"Some value" env:"ENV_DEFAULT" description:"Test env-default1 value"` - EnvDefault2 string `long:"env-default2" env:"ENV_DEFAULT" description:"Test env-default2 value"` - OptionWithArgName string `long:"opt-with-arg-name" value-name:"something" description:"Option with named argument"` - OptionWithChoices string `long:"opt-with-choices" value-name:"choice" choice:"dog" choice:"cat" description:"Option with choices"` - Hidden string `long:"hidden" description:"Hidden option" hidden:"yes"` - - OnlyIni string `ini-name:"only-ini" description:"Option only available in ini"` - - Other struct { - StringSlice []string `short:"s" default:"some" default:"value" description:"A slice of strings"` - IntMap map[string]int `long:"intmap" default:"a:1" description:"A map from string to int" ini-name:"int-map"` - } `group:"Other Options"` - - HiddenGroup struct { - InsideHiddenGroup string `long:"inside-hidden-group" description:"Inside hidden group"` - } `group:"Hidden group" hidden:"yes"` - - Group struct { - Opt string `long:"opt" description:"This is a subgroup option"` - HiddenInsideGroup string `long:"hidden-inside-group" description:"Hidden inside group" hidden:"yes"` - NotHiddenInsideGroup string `long:"not-hidden-inside-group" description:"Not hidden inside group" hidden:"false"` - - Group struct { - Opt string `long:"opt" description:"This is a subsubgroup option"` - } `group:"Subsubgroup" namespace:"sap"` - } `group:"Subgroup" namespace:"sip"` - - Command struct { - ExtraVerbose []bool `long:"extra-verbose" description:"Use for extra verbosity"` - } `command:"command" alias:"cm" alias:"cmd" description:"A command"` - - HiddenCommand struct { - ExtraVerbose []bool `long:"extra-verbose" description:"Use for extra verbosity"` - } `command:"hidden-command" description:"A hidden command" hidden:"yes"` - - Args struct { - Filename string `positional-arg-name:"filename" description:"A filename with a long description to trigger line wrapping"` - Number int `positional-arg-name:"num" description:"A number"` - HiddenInHelp float32 `positional-arg-name:"hidden-in-help" required:"yes"` - } `positional-args:"yes"` -} - -func TestHelp(t *testing.T) { - oldEnv := EnvSnapshot() - defer oldEnv.Restore() - os.Setenv("ENV_DEFAULT", "env-def") - - var opts helpOptions - p := NewNamedParser("TestHelp", HelpFlag) - p.AddGroup("Application Options", "The application options", &opts) - - _, err := p.ParseArgs([]string{"--help"}) - - if err == nil { - t.Fatalf("Expected help error") - } - - if e, ok := err.(*Error); !ok { - t.Fatalf("Expected flags.Error, but got %T", err) - } else { - if e.Type != ErrHelp { - t.Errorf("Expected flags.ErrHelp type, but got %s", e.Type) - } - - var expected string - - if runtime.GOOS == "windows" { - expected = `Usage: - TestHelp [OPTIONS] [filename] [num] [hidden-in-help] - -Application Options: - /v, /verbose Show verbose debug information - /c: Call phone number - /ptrslice: A slice of pointers to string - /empty-description - /default: Test default value (default: - "Some\nvalue") - /default-array: Test default array value (default: - Some value, "Other\tvalue") - /default-map: Testdefault map value (default: - some:value, another:value) - /env-default1: Test env-default1 value (default: - Some value) [%ENV_DEFAULT%] - /env-default2: Test env-default2 value - [%ENV_DEFAULT%] - /opt-with-arg-name:something Option with named argument - /opt-with-choices:choice[dog|cat] Option with choices - -Other Options: - /s: A slice of strings (default: some, - value) - /intmap: A map from string to int (default: - a:1) - -Subgroup: - /sip.opt: This is a subgroup option - /sip.not-hidden-inside-group: Not hidden inside group - -Subsubgroup: - /sip.sap.opt: This is a subsubgroup option - -Help Options: - /? Show this help message - /h, /help Show this help message - -Arguments: - filename: A filename with a long description - to trigger line wrapping - num: A number - -Available commands: - command A command (aliases: cm, cmd) -` - } else { - expected = `Usage: - TestHelp [OPTIONS] [filename] [num] [hidden-in-help] - -Application Options: - -v, --verbose Show verbose debug information - -c= Call phone number - --ptrslice= A slice of pointers to string - --empty-description - --default= Test default value (default: - "Some\nvalue") - --default-array= Test default array value (default: - Some value, "Other\tvalue") - --default-map= Testdefault map value (default: - some:value, another:value) - --env-default1= Test env-default1 value (default: - Some value) [$ENV_DEFAULT] - --env-default2= Test env-default2 value - [$ENV_DEFAULT] - --opt-with-arg-name=something Option with named argument - --opt-with-choices=choice[dog|cat] Option with choices - -Other Options: - -s= A slice of strings (default: some, - value) - --intmap= A map from string to int (default: - a:1) - -Subgroup: - --sip.opt= This is a subgroup option - --sip.not-hidden-inside-group= Not hidden inside group - -Subsubgroup: - --sip.sap.opt= This is a subsubgroup option - -Help Options: - -h, --help Show this help message - -Arguments: - filename: A filename with a long description - to trigger line wrapping - num: A number - -Available commands: - command A command (aliases: cm, cmd) -` - } - - assertDiff(t, e.Message, expected, "help message") - } -} - -func TestMan(t *testing.T) { - oldEnv := EnvSnapshot() - defer oldEnv.Restore() - os.Setenv("ENV_DEFAULT", "env-def") - - var opts helpOptions - p := NewNamedParser("TestMan", HelpFlag) - p.ShortDescription = "Test manpage generation" - p.LongDescription = "This is a somewhat `longer' description of what this does" - p.AddGroup("Application Options", "The application options", &opts) - - p.Commands()[0].LongDescription = "Longer `command' description" - - var buf bytes.Buffer - p.WriteManPage(&buf) - - got := buf.String() - - tt := time.Now() - - var envDefaultName string - - if runtime.GOOS == "windows" { - envDefaultName = "%ENV_DEFAULT%" - } else { - envDefaultName = "$ENV_DEFAULT" - } - - expected := fmt.Sprintf(`.TH TestMan 1 "%s" -.SH NAME -TestMan \- Test manpage generation -.SH SYNOPSIS -\fBTestMan\fP [OPTIONS] -.SH DESCRIPTION -This is a somewhat \fBlonger\fP description of what this does -.SH OPTIONS -.SS Application Options -The application options -.TP -\fB\fB\-v\fR, \fB\-\-verbose\fR\fP -Show verbose debug information -.TP -\fB\fB\-c\fR\fP -Call phone number -.TP -\fB\fB\-\-ptrslice\fR\fP -A slice of pointers to string -.TP -\fB\fB\-\-empty-description\fR\fP -.TP -\fB\fB\-\-default\fR \fP -Test default value -.TP -\fB\fB\-\-default-array\fR \fP -Test default array value -.TP -\fB\fB\-\-default-map\fR \fP -Testdefault map value -.TP -\fB\fB\-\-env-default1\fR \fP -Test env-default1 value -.TP -\fB\fB\-\-env-default2\fR \fP -Test env-default2 value -.TP -\fB\fB\-\-opt-with-arg-name\fR \fIsomething\fR\fP -Option with named argument -.TP -\fB\fB\-\-opt-with-choices\fR \fIchoice\fR\fP -Option with choices -.SS Other Options -.TP -\fB\fB\-s\fR \fP -A slice of strings -.TP -\fB\fB\-\-intmap\fR \fP -A map from string to int -.SS Subgroup -.TP -\fB\fB\-\-sip.opt\fR\fP -This is a subgroup option -.TP -\fB\fB\-\-sip.not-hidden-inside-group\fR\fP -Not hidden inside group -.SS Subsubgroup -.TP -\fB\fB\-\-sip.sap.opt\fR\fP -This is a subsubgroup option -.SH COMMANDS -.SS command -A command - -Longer \fBcommand\fP description - -\fBUsage\fP: TestMan [OPTIONS] command [command-OPTIONS] -.TP - -\fBAliases\fP: cm, cmd - -.TP -\fB\fB\-\-extra-verbose\fR\fP -Use for extra verbosity -`, tt.Format("2 January 2006"), envDefaultName) - - assertDiff(t, got, expected, "man page") -} - -type helpCommandNoOptions struct { - Command struct { - } `command:"command" description:"A command"` -} - -func TestHelpCommand(t *testing.T) { - oldEnv := EnvSnapshot() - defer oldEnv.Restore() - os.Setenv("ENV_DEFAULT", "env-def") - - var opts helpCommandNoOptions - p := NewNamedParser("TestHelpCommand", HelpFlag) - p.AddGroup("Application Options", "The application options", &opts) - - _, err := p.ParseArgs([]string{"command", "--help"}) - - if err == nil { - t.Fatalf("Expected help error") - } - - if e, ok := err.(*Error); !ok { - t.Fatalf("Expected flags.Error, but got %T", err) - } else { - if e.Type != ErrHelp { - t.Errorf("Expected flags.ErrHelp type, but got %s", e.Type) - } - - var expected string - - if runtime.GOOS == "windows" { - expected = `Usage: - TestHelpCommand [OPTIONS] command - -Help Options: - /? Show this help message - /h, /help Show this help message -` - } else { - expected = `Usage: - TestHelpCommand [OPTIONS] command - -Help Options: - -h, --help Show this help message -` - } - - assertDiff(t, e.Message, expected, "help message") - } -} - -func TestHelpDefaults(t *testing.T) { - var expected string - - if runtime.GOOS == "windows" { - expected = `Usage: - TestHelpDefaults [OPTIONS] - -Application Options: - /with-default: With default (default: default-value) - /without-default: Without default - /with-programmatic-default: With programmatic default (default: - default-value) - -Help Options: - /? Show this help message - /h, /help Show this help message -` - } else { - expected = `Usage: - TestHelpDefaults [OPTIONS] - -Application Options: - --with-default= With default (default: default-value) - --without-default= Without default - --with-programmatic-default= With programmatic default (default: - default-value) - -Help Options: - -h, --help Show this help message -` - } - - tests := []struct { - Args []string - Output string - }{ - { - Args: []string{"-h"}, - Output: expected, - }, - { - Args: []string{"--with-default", "other-value", "--with-programmatic-default", "other-value", "-h"}, - Output: expected, - }, - } - - for _, test := range tests { - var opts struct { - WithDefault string `long:"with-default" default:"default-value" description:"With default"` - WithoutDefault string `long:"without-default" description:"Without default"` - WithProgrammaticDefault string `long:"with-programmatic-default" description:"With programmatic default"` - } - - opts.WithProgrammaticDefault = "default-value" - - p := NewNamedParser("TestHelpDefaults", HelpFlag) - p.AddGroup("Application Options", "The application options", &opts) - - _, err := p.ParseArgs(test.Args) - - if err == nil { - t.Fatalf("Expected help error") - } - - if e, ok := err.(*Error); !ok { - t.Fatalf("Expected flags.Error, but got %T", err) - } else { - if e.Type != ErrHelp { - t.Errorf("Expected flags.ErrHelp type, but got %s", e.Type) - } - - assertDiff(t, e.Message, test.Output, "help message") - } - } -} - -func TestHelpRestArgs(t *testing.T) { - opts := struct { - Verbose bool `short:"v"` - }{} - - p := NewNamedParser("TestHelpDefaults", HelpFlag) - p.AddGroup("Application Options", "The application options", &opts) - - retargs, err := p.ParseArgs([]string{"-h", "-v", "rest"}) - - if err == nil { - t.Fatalf("Expected help error") - } - - assertStringArray(t, retargs, []string{"-v", "rest"}) -} - -func TestWrapText(t *testing.T) { - s := "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." - - got := wrapText(s, 60, " ") - expected := `Lorem ipsum dolor sit amet, consectetur adipisicing elit, - sed do eiusmod tempor incididunt ut labore et dolore magna - aliqua. Ut enim ad minim veniam, quis nostrud exercitation - ullamco laboris nisi ut aliquip ex ea commodo consequat. - Duis aute irure dolor in reprehenderit in voluptate velit - esse cillum dolore eu fugiat nulla pariatur. Excepteur sint - occaecat cupidatat non proident, sunt in culpa qui officia - deserunt mollit anim id est laborum.` - - assertDiff(t, got, expected, "wrapped text") -} - -func TestWrapParagraph(t *testing.T) { - s := "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\n\n" - s += "Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.\n\n" - s += "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.\n\n" - s += "Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\n" - - got := wrapText(s, 60, " ") - expected := `Lorem ipsum dolor sit amet, consectetur adipisicing elit, - sed do eiusmod tempor incididunt ut labore et dolore magna - aliqua. - - Ut enim ad minim veniam, quis nostrud exercitation ullamco - laboris nisi ut aliquip ex ea commodo consequat. - - Duis aute irure dolor in reprehenderit in voluptate velit - esse cillum dolore eu fugiat nulla pariatur. - - Excepteur sint occaecat cupidatat non proident, sunt in - culpa qui officia deserunt mollit anim id est laborum. -` - - assertDiff(t, got, expected, "wrapped paragraph") -} - -func TestHelpDefaultMask(t *testing.T) { - var tests = []struct { - opts interface{} - present string - }{ - { - opts: &struct { - Value string `short:"v" default:"123" description:"V"` - }{}, - present: "V (default: 123)\n", - }, - { - opts: &struct { - Value string `short:"v" default:"123" default-mask:"abc" description:"V"` - }{}, - present: "V (default: abc)\n", - }, - { - opts: &struct { - Value string `short:"v" default:"123" default-mask:"-" description:"V"` - }{}, - present: "V\n", - }, - { - opts: &struct { - Value string `short:"v" description:"V"` - }{Value: "123"}, - present: "V (default: 123)\n", - }, - { - opts: &struct { - Value string `short:"v" default-mask:"abc" description:"V"` - }{Value: "123"}, - present: "V (default: abc)\n", - }, - { - opts: &struct { - Value string `short:"v" default-mask:"-" description:"V"` - }{Value: "123"}, - present: "V\n", - }, - } - - for _, test := range tests { - p := NewParser(test.opts, HelpFlag) - _, err := p.ParseArgs([]string{"-h"}) - if flagsErr, ok := err.(*Error); ok && flagsErr.Type == ErrHelp { - err = nil - } - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - h := &bytes.Buffer{} - w := bufio.NewWriter(h) - p.writeHelpOption(w, p.FindOptionByShortName('v'), p.getAlignmentInfo()) - w.Flush() - if strings.Index(h.String(), test.present) < 0 { - t.Errorf("Not present %q\n%s", test.present, h.String()) - } - } -} diff --git a/vendor/github.com/jessevdk/go-flags/ini_test.go b/vendor/github.com/jessevdk/go-flags/ini_test.go deleted file mode 100644 index ad4852e8a..000000000 --- a/vendor/github.com/jessevdk/go-flags/ini_test.go +++ /dev/null @@ -1,1053 +0,0 @@ -package flags - -import ( - "bytes" - "fmt" - "io/ioutil" - "os" - "reflect" - "strings" - "testing" -) - -func TestWriteIni(t *testing.T) { - oldEnv := EnvSnapshot() - defer oldEnv.Restore() - os.Setenv("ENV_DEFAULT", "env-def") - - var tests = []struct { - args []string - options IniOptions - expected string - }{ - { - []string{"-vv", "--intmap=a:2", "--intmap", "b:3", "filename", "0", "3.14", "command"}, - IniDefault, - `[Application Options] -; Show verbose debug information -verbose = true -verbose = true - -; Test env-default1 value -EnvDefault1 = env-def - -; Test env-default2 value -EnvDefault2 = env-def - -[Other Options] -; A map from string to int -int-map = a:2 -int-map = b:3 - -`, - }, - { - []string{"-vv", "--intmap=a:2", "--intmap", "b:3", "filename", "0", "3.14", "command"}, - IniDefault | IniIncludeDefaults, - `[Application Options] -; Show verbose debug information -verbose = true -verbose = true - -; A slice of pointers to string -; PtrSlice = - -EmptyDescription = false - -; Test default value -Default = "Some\nvalue" - -; Test default array value -DefaultArray = Some value -DefaultArray = "Other\tvalue" - -; Testdefault map value -DefaultMap = another:value -DefaultMap = some:value - -; Test env-default1 value -EnvDefault1 = env-def - -; Test env-default2 value -EnvDefault2 = env-def - -; Option with named argument -OptionWithArgName = - -; Option with choices -OptionWithChoices = - -; Option only available in ini -only-ini = - -[Other Options] -; A slice of strings -StringSlice = some -StringSlice = value - -; A map from string to int -int-map = a:2 -int-map = b:3 - -[Subgroup] -; This is a subgroup option -Opt = - -; Not hidden inside group -NotHiddenInsideGroup = - -[Subsubgroup] -; This is a subsubgroup option -Opt = - -[command] -; Use for extra verbosity -; ExtraVerbose = - -`, - }, - { - []string{"filename", "0", "3.14", "command"}, - IniDefault | IniIncludeDefaults | IniCommentDefaults, - `[Application Options] -; Show verbose debug information -; verbose = - -; A slice of pointers to string -; PtrSlice = - -; EmptyDescription = false - -; Test default value -; Default = "Some\nvalue" - -; Test default array value -; DefaultArray = Some value -; DefaultArray = "Other\tvalue" - -; Testdefault map value -; DefaultMap = another:value -; DefaultMap = some:value - -; Test env-default1 value -EnvDefault1 = env-def - -; Test env-default2 value -EnvDefault2 = env-def - -; Option with named argument -; OptionWithArgName = - -; Option with choices -; OptionWithChoices = - -; Option only available in ini -; only-ini = - -[Other Options] -; A slice of strings -; StringSlice = some -; StringSlice = value - -; A map from string to int -; int-map = a:1 - -[Subgroup] -; This is a subgroup option -; Opt = - -; Not hidden inside group -; NotHiddenInsideGroup = - -[Subsubgroup] -; This is a subsubgroup option -; Opt = - -[command] -; Use for extra verbosity -; ExtraVerbose = - -`, - }, - { - []string{"--default=New value", "--default-array=New value", "--default-map=new:value", "filename", "0", "3.14", "command"}, - IniDefault | IniIncludeDefaults | IniCommentDefaults, - `[Application Options] -; Show verbose debug information -; verbose = - -; A slice of pointers to string -; PtrSlice = - -; EmptyDescription = false - -; Test default value -Default = New value - -; Test default array value -DefaultArray = New value - -; Testdefault map value -DefaultMap = new:value - -; Test env-default1 value -EnvDefault1 = env-def - -; Test env-default2 value -EnvDefault2 = env-def - -; Option with named argument -; OptionWithArgName = - -; Option with choices -; OptionWithChoices = - -; Option only available in ini -; only-ini = - -[Other Options] -; A slice of strings -; StringSlice = some -; StringSlice = value - -; A map from string to int -; int-map = a:1 - -[Subgroup] -; This is a subgroup option -; Opt = - -; Not hidden inside group -; NotHiddenInsideGroup = - -[Subsubgroup] -; This is a subsubgroup option -; Opt = - -[command] -; Use for extra verbosity -; ExtraVerbose = - -`, - }, - } - - for _, test := range tests { - var opts helpOptions - - p := NewNamedParser("TestIni", Default) - p.AddGroup("Application Options", "The application options", &opts) - - _, err := p.ParseArgs(test.args) - - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - - inip := NewIniParser(p) - - var b bytes.Buffer - inip.Write(&b, test.options) - - got := b.String() - expected := test.expected - - msg := fmt.Sprintf("with arguments %+v and ini options %b", test.args, test.options) - assertDiff(t, got, expected, msg) - } -} - -func TestReadIni_flagEquivalent(t *testing.T) { - type options struct { - Opt1 bool `long:"opt1"` - - Group1 struct { - Opt2 bool `long:"opt2"` - } `group:"group1"` - - Group2 struct { - Opt3 bool `long:"opt3"` - } `group:"group2" namespace:"ns1"` - - Cmd1 struct { - Opt4 bool `long:"opt4"` - Opt5 bool `long:"foo.opt5"` - - Group1 struct { - Opt6 bool `long:"opt6"` - Opt7 bool `long:"foo.opt7"` - } `group:"group1"` - - Group2 struct { - Opt8 bool `long:"opt8"` - } `group:"group2" namespace:"ns1"` - } `command:"cmd1"` - } - - a := ` -opt1=true - -[group1] -opt2=true - -[group2] -ns1.opt3=true - -[cmd1] -opt4=true -foo.opt5=true - -[cmd1.group1] -opt6=true -foo.opt7=true - -[cmd1.group2] -ns1.opt8=true -` - b := ` -opt1=true -opt2=true -ns1.opt3=true - -[cmd1] -opt4=true -foo.opt5=true -opt6=true -foo.opt7=true -ns1.opt8=true -` - - parse := func(readIni string) (opts options, writeIni string) { - p := NewNamedParser("TestIni", Default) - p.AddGroup("Application Options", "The application options", &opts) - - inip := NewIniParser(p) - err := inip.Parse(strings.NewReader(readIni)) - - if err != nil { - t.Fatalf("Unexpected error: %s\n\nFile:\n%s", err, readIni) - } - - var b bytes.Buffer - inip.Write(&b, Default) - - return opts, b.String() - } - - aOpt, aIni := parse(a) - bOpt, bIni := parse(b) - - assertDiff(t, aIni, bIni, "") - if !reflect.DeepEqual(aOpt, bOpt) { - t.Errorf("not equal") - } -} - -func TestReadIni(t *testing.T) { - var opts helpOptions - - p := NewNamedParser("TestIni", Default) - p.AddGroup("Application Options", "The application options", &opts) - - inip := NewIniParser(p) - - inic := ` -; Show verbose debug information -verbose = true -verbose = true - -DefaultMap = another:"value\n1" -DefaultMap = some:value 2 - -[Application Options] -; A slice of pointers to string -; PtrSlice = - -; Test default value -Default = "New\nvalue" - -; Test env-default1 value -EnvDefault1 = New value - -[Other Options] -# A slice of strings -StringSlice = "some\nvalue" -StringSlice = another value - -; A map from string to int -int-map = a:2 -int-map = b:3 - -` - - b := strings.NewReader(inic) - err := inip.Parse(b) - - if err != nil { - t.Fatalf("Unexpected error: %s", err) - } - - assertBoolArray(t, opts.Verbose, []bool{true, true}) - - if v := map[string]string{"another": "value\n1", "some": "value 2"}; !reflect.DeepEqual(opts.DefaultMap, v) { - t.Fatalf("Expected %#v for DefaultMap but got %#v", v, opts.DefaultMap) - } - - assertString(t, opts.Default, "New\nvalue") - - assertString(t, opts.EnvDefault1, "New value") - - assertStringArray(t, opts.Other.StringSlice, []string{"some\nvalue", "another value"}) - - if v, ok := opts.Other.IntMap["a"]; !ok { - t.Errorf("Expected \"a\" in Other.IntMap") - } else if v != 2 { - t.Errorf("Expected Other.IntMap[\"a\"] = 2, but got %v", v) - } - - if v, ok := opts.Other.IntMap["b"]; !ok { - t.Errorf("Expected \"b\" in Other.IntMap") - } else if v != 3 { - t.Errorf("Expected Other.IntMap[\"b\"] = 3, but got %v", v) - } -} - -func TestReadAndWriteIni(t *testing.T) { - var tests = []struct { - options IniOptions - read string - write string - }{ - { - IniIncludeComments, - `[Application Options] -; Show verbose debug information -verbose = true -verbose = true - -; Test default value -Default = "quote me" - -; Test default array value -DefaultArray = 1 -DefaultArray = "2" -DefaultArray = 3 - -; Testdefault map value -; DefaultMap = - -; Test env-default1 value -EnvDefault1 = env-def - -; Test env-default2 value -EnvDefault2 = env-def - -[Other Options] -; A slice of strings -; StringSlice = - -; A map from string to int -int-map = a:2 -int-map = b:"3" - -`, - `[Application Options] -; Show verbose debug information -verbose = true -verbose = true - -; Test default value -Default = "quote me" - -; Test default array value -DefaultArray = 1 -DefaultArray = 2 -DefaultArray = 3 - -; Testdefault map value -; DefaultMap = - -; Test env-default1 value -EnvDefault1 = env-def - -; Test env-default2 value -EnvDefault2 = env-def - -[Other Options] -; A slice of strings -; StringSlice = - -; A map from string to int -int-map = a:2 -int-map = b:3 - -`, - }, - { - IniIncludeComments, - `[Application Options] -; Show verbose debug information -verbose = true -verbose = true - -; Test default value -Default = "quote me" - -; Test default array value -DefaultArray = "1" -DefaultArray = "2" -DefaultArray = "3" - -; Testdefault map value -; DefaultMap = - -; Test env-default1 value -EnvDefault1 = env-def - -; Test env-default2 value -EnvDefault2 = env-def - -[Other Options] -; A slice of strings -; StringSlice = - -; A map from string to int -int-map = a:"2" -int-map = b:"3" - -`, - `[Application Options] -; Show verbose debug information -verbose = true -verbose = true - -; Test default value -Default = "quote me" - -; Test default array value -DefaultArray = "1" -DefaultArray = "2" -DefaultArray = "3" - -; Testdefault map value -; DefaultMap = - -; Test env-default1 value -EnvDefault1 = env-def - -; Test env-default2 value -EnvDefault2 = env-def - -[Other Options] -; A slice of strings -; StringSlice = - -; A map from string to int -int-map = a:"2" -int-map = b:"3" - -`, - }, - } - - for _, test := range tests { - var opts helpOptions - - p := NewNamedParser("TestIni", Default) - p.AddGroup("Application Options", "The application options", &opts) - - inip := NewIniParser(p) - - read := strings.NewReader(test.read) - err := inip.Parse(read) - if err != nil { - t.Fatalf("Unexpected error: %s", err) - } - - var write bytes.Buffer - inip.Write(&write, test.options) - - got := write.String() - - msg := fmt.Sprintf("with ini options %b", test.options) - assertDiff(t, got, test.write, msg) - } -} - -func TestReadIniWrongQuoting(t *testing.T) { - var tests = []struct { - iniFile string - lineNumber uint - }{ - { - iniFile: `Default = "New\nvalue`, - lineNumber: 1, - }, - { - iniFile: `StringSlice = "New\nvalue`, - lineNumber: 1, - }, - { - iniFile: `StringSlice = "New\nvalue" - StringSlice = "Second\nvalue`, - lineNumber: 2, - }, - { - iniFile: `DefaultMap = some:"value`, - lineNumber: 1, - }, - { - iniFile: `DefaultMap = some:value - DefaultMap = another:"value`, - lineNumber: 2, - }, - } - - for _, test := range tests { - var opts helpOptions - - p := NewNamedParser("TestIni", Default) - p.AddGroup("Application Options", "The application options", &opts) - - inip := NewIniParser(p) - - inic := test.iniFile - - b := strings.NewReader(inic) - err := inip.Parse(b) - - if err == nil { - t.Fatalf("Expect error") - } - - iniError := err.(*IniError) - - if iniError.LineNumber != test.lineNumber { - t.Fatalf("Expect error on line %d", test.lineNumber) - } - } -} - -func TestIniCommands(t *testing.T) { - var opts struct { - Value string `short:"v" long:"value"` - - Add struct { - Name int `short:"n" long:"name" ini-name:"AliasName"` - - Other struct { - O string `short:"o" long:"other"` - } `group:"Other Options"` - } `command:"add"` - } - - p := NewNamedParser("TestIni", Default) - p.AddGroup("Application Options", "The application options", &opts) - - inip := NewIniParser(p) - - inic := `[Application Options] -value = some value - -[add] -AliasName = 5 - -[add.Other Options] -other = subgroup - -` - - b := strings.NewReader(inic) - err := inip.Parse(b) - - if err != nil { - t.Fatalf("Unexpected error: %s", err) - } - - assertString(t, opts.Value, "some value") - - if opts.Add.Name != 5 { - t.Errorf("Expected opts.Add.Name to be 5, but got %v", opts.Add.Name) - } - - assertString(t, opts.Add.Other.O, "subgroup") - - // Test writing it back - buf := &bytes.Buffer{} - - inip.Write(buf, IniDefault) - - assertDiff(t, buf.String(), inic, "ini contents") -} - -func TestIniNoIni(t *testing.T) { - var opts struct { - NoValue string `short:"n" long:"novalue" no-ini:"yes"` - Value string `short:"v" long:"value"` - } - - p := NewNamedParser("TestIni", Default) - p.AddGroup("Application Options", "The application options", &opts) - - inip := NewIniParser(p) - - // read INI - inic := `[Application Options] -novalue = some value -value = some other value -` - - b := strings.NewReader(inic) - err := inip.Parse(b) - - if err == nil { - t.Fatalf("Expected error") - } - - iniError := err.(*IniError) - - if v := uint(2); iniError.LineNumber != v { - t.Errorf("Expected opts.Add.Name to be %d, but got %d", v, iniError.LineNumber) - } - - if v := "unknown option: novalue"; iniError.Message != v { - t.Errorf("Expected opts.Add.Name to be %s, but got %s", v, iniError.Message) - } - - // write INI - opts.NoValue = "some value" - opts.Value = "some other value" - - file, err := ioutil.TempFile("", "") - if err != nil { - t.Fatalf("Cannot create temporary file: %s", err) - } - defer os.Remove(file.Name()) - - err = inip.WriteFile(file.Name(), IniIncludeDefaults) - if err != nil { - t.Fatalf("Could not write ini file: %s", err) - } - - found, err := ioutil.ReadFile(file.Name()) - if err != nil { - t.Fatalf("Could not read written ini file: %s", err) - } - - expected := "[Application Options]\nValue = some other value\n\n" - - assertDiff(t, string(found), expected, "ini content") -} - -func TestIniParse(t *testing.T) { - file, err := ioutil.TempFile("", "") - if err != nil { - t.Fatalf("Cannot create temporary file: %s", err) - } - defer os.Remove(file.Name()) - - _, err = file.WriteString("value = 123") - if err != nil { - t.Fatalf("Cannot write to temporary file: %s", err) - } - - file.Close() - - var opts struct { - Value int `long:"value"` - } - - err = IniParse(file.Name(), &opts) - if err != nil { - t.Fatalf("Could not parse ini: %s", err) - } - - if opts.Value != 123 { - t.Fatalf("Expected Value to be \"123\" but was \"%d\"", opts.Value) - } -} - -func TestIniCliOverrides(t *testing.T) { - file, err := ioutil.TempFile("", "") - - if err != nil { - t.Fatalf("Cannot create temporary file: %s", err) - } - - defer os.Remove(file.Name()) - - _, err = file.WriteString("values = 123\n") - _, err = file.WriteString("values = 456\n") - - if err != nil { - t.Fatalf("Cannot write to temporary file: %s", err) - } - - file.Close() - - var opts struct { - Values []int `long:"values"` - } - - p := NewParser(&opts, Default) - err = NewIniParser(p).ParseFile(file.Name()) - - if err != nil { - t.Fatalf("Could not parse ini: %s", err) - } - - _, err = p.ParseArgs([]string{"--values", "111", "--values", "222"}) - - if err != nil { - t.Fatalf("Failed to parse arguments: %s", err) - } - - if len(opts.Values) != 2 { - t.Fatalf("Expected Values to contain two elements, but got %d", len(opts.Values)) - } - - if opts.Values[0] != 111 { - t.Fatalf("Expected Values[0] to be 111, but got '%d'", opts.Values[0]) - } - - if opts.Values[1] != 222 { - t.Fatalf("Expected Values[1] to be 222, but got '%d'", opts.Values[1]) - } -} - -func TestIniOverrides(t *testing.T) { - file, err := ioutil.TempFile("", "") - - if err != nil { - t.Fatalf("Cannot create temporary file: %s", err) - } - - defer os.Remove(file.Name()) - - _, err = file.WriteString("value-with-default = \"ini-value\"\n") - _, err = file.WriteString("value-with-default-override-cli = \"ini-value\"\n") - - if err != nil { - t.Fatalf("Cannot write to temporary file: %s", err) - } - - file.Close() - - var opts struct { - ValueWithDefault string `long:"value-with-default" default:"value"` - ValueWithDefaultOverrideCli string `long:"value-with-default-override-cli" default:"value"` - } - - p := NewParser(&opts, Default) - err = NewIniParser(p).ParseFile(file.Name()) - - if err != nil { - t.Fatalf("Could not parse ini: %s", err) - } - - _, err = p.ParseArgs([]string{"--value-with-default-override-cli", "cli-value"}) - - if err != nil { - t.Fatalf("Failed to parse arguments: %s", err) - } - - assertString(t, opts.ValueWithDefault, "ini-value") - assertString(t, opts.ValueWithDefaultOverrideCli, "cli-value") -} - -func TestIniRequired(t *testing.T) { - var opts struct { - Required string `short:"r" required:"yes" description:"required"` - Config func(s string) error `long:"config" default:"no-ini-file" no-ini:"true"` - } - - p := NewParser(&opts, Default) - - opts.Config = func(s string) error { - inip := NewIniParser(p) - inip.ParseAsDefaults = true - return inip.Parse(strings.NewReader("Required = ini-value\n")) - } - - _, err := p.ParseArgs([]string{"-r", "cli-value"}) - - if err != nil { - t.Fatalf("Failed to parse arguments: %s", err) - } - - assertString(t, opts.Required, "cli-value") -} - -func TestWriteFile(t *testing.T) { - file, err := ioutil.TempFile("", "") - if err != nil { - t.Fatalf("Cannot create temporary file: %s", err) - } - defer os.Remove(file.Name()) - - var opts struct { - Value int `long:"value"` - } - - opts.Value = 123 - - p := NewParser(&opts, Default) - ini := NewIniParser(p) - - err = ini.WriteFile(file.Name(), IniIncludeDefaults) - if err != nil { - t.Fatalf("Could not write ini file: %s", err) - } - - found, err := ioutil.ReadFile(file.Name()) - if err != nil { - t.Fatalf("Could not read written ini file: %s", err) - } - - expected := "[Application Options]\nValue = 123\n\n" - - assertDiff(t, string(found), expected, "ini content") -} - -func TestOverwriteRequiredOptions(t *testing.T) { - var tests = []struct { - args []string - expected []string - }{ - { - args: []string{"--value", "from CLI"}, - expected: []string{ - "from CLI", - "from default", - }, - }, - { - args: []string{"--value", "from CLI", "--default", "from CLI"}, - expected: []string{ - "from CLI", - "from CLI", - }, - }, - { - args: []string{"--config", "no file name"}, - expected: []string{ - "from INI", - "from INI", - }, - }, - { - args: []string{"--value", "from CLI before", "--default", "from CLI before", "--config", "no file name"}, - expected: []string{ - "from INI", - "from INI", - }, - }, - { - args: []string{"--value", "from CLI before", "--default", "from CLI before", "--config", "no file name", "--value", "from CLI after", "--default", "from CLI after"}, - expected: []string{ - "from CLI after", - "from CLI after", - }, - }, - } - - for _, test := range tests { - var opts struct { - Config func(s string) error `long:"config" no-ini:"true"` - Value string `long:"value" required:"true"` - Default string `long:"default" required:"true" default:"from default"` - } - - p := NewParser(&opts, Default) - - opts.Config = func(s string) error { - ini := NewIniParser(p) - - return ini.Parse(bytes.NewBufferString("value = from INI\ndefault = from INI")) - } - - _, err := p.ParseArgs(test.args) - if err != nil { - t.Fatalf("Unexpected error %s with args %+v", err, test.args) - } - - if opts.Value != test.expected[0] { - t.Fatalf("Expected Value to be \"%s\" but was \"%s\" with args %+v", test.expected[0], opts.Value, test.args) - } - - if opts.Default != test.expected[1] { - t.Fatalf("Expected Default to be \"%s\" but was \"%s\" with args %+v", test.expected[1], opts.Default, test.args) - } - } -} - -func TestIniOverwriteOptions(t *testing.T) { - var tests = []struct { - args []string - expected string - toggled bool - }{ - { - args: []string{}, - expected: "from default", - }, - { - args: []string{"--value", "from CLI"}, - expected: "from CLI", - }, - { - args: []string{"--config", "no file name"}, - expected: "from INI", - toggled: true, - }, - { - args: []string{"--value", "from CLI before", "--config", "no file name"}, - expected: "from CLI before", - toggled: true, - }, - { - args: []string{"--config", "no file name", "--value", "from CLI after"}, - expected: "from CLI after", - toggled: true, - }, - { - args: []string{"--toggle"}, - toggled: true, - expected: "from default", - }, - } - - for _, test := range tests { - var opts struct { - Config string `long:"config" no-ini:"true"` - Value string `long:"value" default:"from default"` - Toggle bool `long:"toggle"` - } - - p := NewParser(&opts, Default) - - _, err := p.ParseArgs(test.args) - if err != nil { - t.Fatalf("Unexpected error %s with args %+v", err, test.args) - } - - if opts.Config != "" { - inip := NewIniParser(p) - inip.ParseAsDefaults = true - - err = inip.Parse(bytes.NewBufferString("value = from INI\ntoggle = true")) - if err != nil { - t.Fatalf("Unexpected error %s with args %+v", err, test.args) - } - } - - if opts.Value != test.expected { - t.Fatalf("Expected Value to be \"%s\" but was \"%s\" with args %+v", test.expected, opts.Value, test.args) - } - - if opts.Toggle != test.toggled { - t.Fatalf("Expected Toggle to be \"%v\" but was \"%v\" with args %+v", test.toggled, opts.Toggle, test.args) - } - - } -} diff --git a/vendor/github.com/jessevdk/go-flags/long_test.go b/vendor/github.com/jessevdk/go-flags/long_test.go deleted file mode 100644 index 02fc8c701..000000000 --- a/vendor/github.com/jessevdk/go-flags/long_test.go +++ /dev/null @@ -1,85 +0,0 @@ -package flags - -import ( - "testing" -) - -func TestLong(t *testing.T) { - var opts = struct { - Value bool `long:"value"` - }{} - - ret := assertParseSuccess(t, &opts, "--value") - - assertStringArray(t, ret, []string{}) - - if !opts.Value { - t.Errorf("Expected Value to be true") - } -} - -func TestLongArg(t *testing.T) { - var opts = struct { - Value string `long:"value"` - }{} - - ret := assertParseSuccess(t, &opts, "--value", "value") - - assertStringArray(t, ret, []string{}) - assertString(t, opts.Value, "value") -} - -func TestLongArgEqual(t *testing.T) { - var opts = struct { - Value string `long:"value"` - }{} - - ret := assertParseSuccess(t, &opts, "--value=value") - - assertStringArray(t, ret, []string{}) - assertString(t, opts.Value, "value") -} - -func TestLongDefault(t *testing.T) { - var opts = struct { - Value string `long:"value" default:"value"` - }{} - - ret := assertParseSuccess(t, &opts) - - assertStringArray(t, ret, []string{}) - assertString(t, opts.Value, "value") -} - -func TestLongOptional(t *testing.T) { - var opts = struct { - Value string `long:"value" optional:"yes" optional-value:"value"` - }{} - - ret := assertParseSuccess(t, &opts, "--value") - - assertStringArray(t, ret, []string{}) - assertString(t, opts.Value, "value") -} - -func TestLongOptionalArg(t *testing.T) { - var opts = struct { - Value string `long:"value" optional:"yes" optional-value:"value"` - }{} - - ret := assertParseSuccess(t, &opts, "--value", "no") - - assertStringArray(t, ret, []string{"no"}) - assertString(t, opts.Value, "value") -} - -func TestLongOptionalArgEqual(t *testing.T) { - var opts = struct { - Value string `long:"value" optional:"yes" optional-value:"value"` - }{} - - ret := assertParseSuccess(t, &opts, "--value=value", "no") - - assertStringArray(t, ret, []string{"no"}) - assertString(t, opts.Value, "value") -} diff --git a/vendor/github.com/jessevdk/go-flags/marshal_test.go b/vendor/github.com/jessevdk/go-flags/marshal_test.go deleted file mode 100644 index 4cfe86568..000000000 --- a/vendor/github.com/jessevdk/go-flags/marshal_test.go +++ /dev/null @@ -1,119 +0,0 @@ -package flags - -import ( - "fmt" - "testing" -) - -type marshalled string - -func (m *marshalled) UnmarshalFlag(value string) error { - if value == "yes" { - *m = "true" - } else if value == "no" { - *m = "false" - } else { - return fmt.Errorf("`%s' is not a valid value, please specify `yes' or `no'", value) - } - - return nil -} - -func (m marshalled) MarshalFlag() (string, error) { - if m == "true" { - return "yes", nil - } - - return "no", nil -} - -type marshalledError bool - -func (m marshalledError) MarshalFlag() (string, error) { - return "", newErrorf(ErrMarshal, "Failed to marshal") -} - -func TestUnmarshal(t *testing.T) { - var opts = struct { - Value marshalled `short:"v"` - }{} - - ret := assertParseSuccess(t, &opts, "-v=yes") - - assertStringArray(t, ret, []string{}) - - if opts.Value != "true" { - t.Errorf("Expected Value to be \"true\"") - } -} - -func TestUnmarshalDefault(t *testing.T) { - var opts = struct { - Value marshalled `short:"v" default:"yes"` - }{} - - ret := assertParseSuccess(t, &opts) - - assertStringArray(t, ret, []string{}) - - if opts.Value != "true" { - t.Errorf("Expected Value to be \"true\"") - } -} - -func TestUnmarshalOptional(t *testing.T) { - var opts = struct { - Value marshalled `short:"v" optional:"yes" optional-value:"yes"` - }{} - - ret := assertParseSuccess(t, &opts, "-v") - - assertStringArray(t, ret, []string{}) - - if opts.Value != "true" { - t.Errorf("Expected Value to be \"true\"") - } -} - -func TestUnmarshalError(t *testing.T) { - var opts = struct { - Value marshalled `short:"v"` - }{} - - assertParseFail(t, ErrMarshal, fmt.Sprintf("invalid argument for flag `%cv' (expected flags.marshalled): `invalid' is not a valid value, please specify `yes' or `no'", defaultShortOptDelimiter), &opts, "-vinvalid") -} - -func TestUnmarshalPositionalError(t *testing.T) { - var opts = struct { - Args struct { - Value marshalled - } `positional-args:"yes"` - }{} - - parser := NewParser(&opts, Default&^PrintErrors) - _, err := parser.ParseArgs([]string{"invalid"}) - - msg := "`invalid' is not a valid value, please specify `yes' or `no'" - - if err == nil { - assertFatalf(t, "Expected error: %s", msg) - return - } - - if err.Error() != msg { - assertErrorf(t, "Expected error message %#v, but got %#v", msg, err.Error()) - } -} - -func TestMarshalError(t *testing.T) { - var opts = struct { - Value marshalledError `short:"v"` - }{} - - p := NewParser(&opts, Default) - o := p.Command.Groups()[0].Options()[0] - - _, err := convertToString(o.value, o.tag) - - assertError(t, err, ErrMarshal, "Failed to marshal") -} diff --git a/vendor/github.com/jessevdk/go-flags/options_test.go b/vendor/github.com/jessevdk/go-flags/options_test.go deleted file mode 100644 index b0fe9f456..000000000 --- a/vendor/github.com/jessevdk/go-flags/options_test.go +++ /dev/null @@ -1,45 +0,0 @@ -package flags - -import ( - "testing" -) - -func TestPassDoubleDash(t *testing.T) { - var opts = struct { - Value bool `short:"v"` - }{} - - p := NewParser(&opts, PassDoubleDash) - ret, err := p.ParseArgs([]string{"-v", "--", "-v", "-g"}) - - if err != nil { - t.Fatalf("Unexpected error: %v", err) - return - } - - if !opts.Value { - t.Errorf("Expected Value to be true") - } - - assertStringArray(t, ret, []string{"-v", "-g"}) -} - -func TestPassAfterNonOption(t *testing.T) { - var opts = struct { - Value bool `short:"v"` - }{} - - p := NewParser(&opts, PassAfterNonOption) - ret, err := p.ParseArgs([]string{"-v", "arg", "-v", "-g"}) - - if err != nil { - t.Fatalf("Unexpected error: %v", err) - return - } - - if !opts.Value { - t.Errorf("Expected Value to be true") - } - - assertStringArray(t, ret, []string{"arg", "-v", "-g"}) -} diff --git a/vendor/github.com/jessevdk/go-flags/parser_test.go b/vendor/github.com/jessevdk/go-flags/parser_test.go deleted file mode 100644 index 374f21cc5..000000000 --- a/vendor/github.com/jessevdk/go-flags/parser_test.go +++ /dev/null @@ -1,612 +0,0 @@ -package flags - -import ( - "fmt" - "os" - "reflect" - "runtime" - "strconv" - "strings" - "testing" - "time" -) - -type defaultOptions struct { - Int int `long:"i"` - IntDefault int `long:"id" default:"1"` - - Float64 float64 `long:"f"` - Float64Default float64 `long:"fd" default:"-3.14"` - - NumericFlag bool `short:"3"` - - String string `long:"str"` - StringDefault string `long:"strd" default:"abc"` - StringNotUnquoted string `long:"strnot" unquote:"false"` - - Time time.Duration `long:"t"` - TimeDefault time.Duration `long:"td" default:"1m"` - - Map map[string]int `long:"m"` - MapDefault map[string]int `long:"md" default:"a:1"` - - Slice []int `long:"s"` - SliceDefault []int `long:"sd" default:"1" default:"2"` -} - -func TestDefaults(t *testing.T) { - var tests = []struct { - msg string - args []string - expected defaultOptions - }{ - { - msg: "no arguments, expecting default values", - args: []string{}, - expected: defaultOptions{ - Int: 0, - IntDefault: 1, - - Float64: 0.0, - Float64Default: -3.14, - - NumericFlag: false, - - String: "", - StringDefault: "abc", - - Time: 0, - TimeDefault: time.Minute, - - Map: map[string]int{}, - MapDefault: map[string]int{"a": 1}, - - Slice: []int{}, - SliceDefault: []int{1, 2}, - }, - }, - { - msg: "non-zero value arguments, expecting overwritten arguments", - args: []string{"--i=3", "--id=3", "--f=-2.71", "--fd=2.71", "-3", "--str=def", "--strd=def", "--t=3ms", "--td=3ms", "--m=c:3", "--md=c:3", "--s=3", "--sd=3"}, - expected: defaultOptions{ - Int: 3, - IntDefault: 3, - - Float64: -2.71, - Float64Default: 2.71, - - NumericFlag: true, - - String: "def", - StringDefault: "def", - - Time: 3 * time.Millisecond, - TimeDefault: 3 * time.Millisecond, - - Map: map[string]int{"c": 3}, - MapDefault: map[string]int{"c": 3}, - - Slice: []int{3}, - SliceDefault: []int{3}, - }, - }, - { - msg: "zero value arguments, expecting overwritten arguments", - args: []string{"--i=0", "--id=0", "--f=0", "--fd=0", "--str", "", "--strd=\"\"", "--t=0ms", "--td=0s", "--m=:0", "--md=:0", "--s=0", "--sd=0"}, - expected: defaultOptions{ - Int: 0, - IntDefault: 0, - - Float64: 0, - Float64Default: 0, - - String: "", - StringDefault: "", - - Time: 0, - TimeDefault: 0, - - Map: map[string]int{"": 0}, - MapDefault: map[string]int{"": 0}, - - Slice: []int{0}, - SliceDefault: []int{0}, - }, - }, - } - - for _, test := range tests { - var opts defaultOptions - - _, err := ParseArgs(&opts, test.args) - if err != nil { - t.Fatalf("%s:\nUnexpected error: %v", test.msg, err) - } - - if opts.Slice == nil { - opts.Slice = []int{} - } - - if !reflect.DeepEqual(opts, test.expected) { - t.Errorf("%s:\nUnexpected options with arguments %+v\nexpected\n%+v\nbut got\n%+v\n", test.msg, test.args, test.expected, opts) - } - } -} - -func TestNoDefaultsForBools(t *testing.T) { - var opts struct { - DefaultBool bool `short:"d" default:"true"` - } - - if runtime.GOOS == "windows" { - assertParseFail(t, ErrInvalidTag, "boolean flag `/d' may not have default values, they always default to `false' and can only be turned on", &opts) - } else { - assertParseFail(t, ErrInvalidTag, "boolean flag `-d' may not have default values, they always default to `false' and can only be turned on", &opts) - } -} - -func TestUnquoting(t *testing.T) { - var tests = []struct { - arg string - err error - value string - }{ - { - arg: "\"abc", - err: strconv.ErrSyntax, - value: "", - }, - { - arg: "\"\"abc\"", - err: strconv.ErrSyntax, - value: "", - }, - { - arg: "\"abc\"", - err: nil, - value: "abc", - }, - { - arg: "\"\\\"abc\\\"\"", - err: nil, - value: "\"abc\"", - }, - { - arg: "\"\\\"abc\"", - err: nil, - value: "\"abc", - }, - } - - for _, test := range tests { - var opts defaultOptions - - for _, delimiter := range []bool{false, true} { - p := NewParser(&opts, None) - - var err error - if delimiter { - _, err = p.ParseArgs([]string{"--str=" + test.arg, "--strnot=" + test.arg}) - } else { - _, err = p.ParseArgs([]string{"--str", test.arg, "--strnot", test.arg}) - } - - if test.err == nil { - if err != nil { - t.Fatalf("Expected no error but got: %v", err) - } - - if test.value != opts.String { - t.Fatalf("Expected String to be %q but got %q", test.value, opts.String) - } - if q := strconv.Quote(test.value); q != opts.StringNotUnquoted { - t.Fatalf("Expected StringDefault to be %q but got %q", q, opts.StringNotUnquoted) - } - } else { - if err == nil { - t.Fatalf("Expected error") - } else if e, ok := err.(*Error); ok { - if strings.HasPrefix(e.Message, test.err.Error()) { - t.Fatalf("Expected error message to end with %q but got %v", test.err.Error(), e.Message) - } - } - } - } - } -} - -// EnvRestorer keeps a copy of a set of env variables and can restore the env from them -type EnvRestorer struct { - env map[string]string -} - -func (r *EnvRestorer) Restore() { - os.Clearenv() - - for k, v := range r.env { - os.Setenv(k, v) - } -} - -// EnvSnapshot returns a snapshot of the currently set env variables -func EnvSnapshot() *EnvRestorer { - r := EnvRestorer{make(map[string]string)} - - for _, kv := range os.Environ() { - parts := strings.SplitN(kv, "=", 2) - - if len(parts) != 2 { - panic("got a weird env variable: " + kv) - } - - r.env[parts[0]] = parts[1] - } - - return &r -} - -type envDefaultOptions struct { - Int int `long:"i" default:"1" env:"TEST_I"` - Time time.Duration `long:"t" default:"1m" env:"TEST_T"` - Map map[string]int `long:"m" default:"a:1" env:"TEST_M" env-delim:";"` - Slice []int `long:"s" default:"1" default:"2" env:"TEST_S" env-delim:","` -} - -func TestEnvDefaults(t *testing.T) { - var tests = []struct { - msg string - args []string - expected envDefaultOptions - env map[string]string - }{ - { - msg: "no arguments, no env, expecting default values", - args: []string{}, - expected: envDefaultOptions{ - Int: 1, - Time: time.Minute, - Map: map[string]int{"a": 1}, - Slice: []int{1, 2}, - }, - }, - { - msg: "no arguments, env defaults, expecting env default values", - args: []string{}, - expected: envDefaultOptions{ - Int: 2, - Time: 2 * time.Minute, - Map: map[string]int{"a": 2, "b": 3}, - Slice: []int{4, 5, 6}, - }, - env: map[string]string{ - "TEST_I": "2", - "TEST_T": "2m", - "TEST_M": "a:2;b:3", - "TEST_S": "4,5,6", - }, - }, - { - msg: "non-zero value arguments, expecting overwritten arguments", - args: []string{"--i=3", "--t=3ms", "--m=c:3", "--s=3"}, - expected: envDefaultOptions{ - Int: 3, - Time: 3 * time.Millisecond, - Map: map[string]int{"c": 3}, - Slice: []int{3}, - }, - env: map[string]string{ - "TEST_I": "2", - "TEST_T": "2m", - "TEST_M": "a:2;b:3", - "TEST_S": "4,5,6", - }, - }, - { - msg: "zero value arguments, expecting overwritten arguments", - args: []string{"--i=0", "--t=0ms", "--m=:0", "--s=0"}, - expected: envDefaultOptions{ - Int: 0, - Time: 0, - Map: map[string]int{"": 0}, - Slice: []int{0}, - }, - env: map[string]string{ - "TEST_I": "2", - "TEST_T": "2m", - "TEST_M": "a:2;b:3", - "TEST_S": "4,5,6", - }, - }, - } - - oldEnv := EnvSnapshot() - defer oldEnv.Restore() - - for _, test := range tests { - var opts envDefaultOptions - oldEnv.Restore() - for envKey, envValue := range test.env { - os.Setenv(envKey, envValue) - } - _, err := ParseArgs(&opts, test.args) - if err != nil { - t.Fatalf("%s:\nUnexpected error: %v", test.msg, err) - } - - if opts.Slice == nil { - opts.Slice = []int{} - } - - if !reflect.DeepEqual(opts, test.expected) { - t.Errorf("%s:\nUnexpected options with arguments %+v\nexpected\n%+v\nbut got\n%+v\n", test.msg, test.args, test.expected, opts) - } - } -} - -func TestOptionAsArgument(t *testing.T) { - var tests = []struct { - args []string - expectError bool - errType ErrorType - errMsg string - rest []string - }{ - { - // short option must not be accepted as argument - args: []string{"--string-slice", "foobar", "--string-slice", "-o"}, - expectError: true, - errType: ErrExpectedArgument, - errMsg: "expected argument for flag `" + defaultLongOptDelimiter + "string-slice', but got option `-o'", - }, - { - // long option must not be accepted as argument - args: []string{"--string-slice", "foobar", "--string-slice", "--other-option"}, - expectError: true, - errType: ErrExpectedArgument, - errMsg: "expected argument for flag `" + defaultLongOptDelimiter + "string-slice', but got option `--other-option'", - }, - { - // long option must not be accepted as argument - args: []string{"--string-slice", "--"}, - expectError: true, - errType: ErrExpectedArgument, - errMsg: "expected argument for flag `" + defaultLongOptDelimiter + "string-slice', but got double dash `--'", - }, - { - // quoted and appended option should be accepted as argument (even if it looks like an option) - args: []string{"--string-slice", "foobar", "--string-slice=\"--other-option\""}, - }, - { - // Accept any single character arguments including '-' - args: []string{"--string-slice", "-"}, - }, - { - // Do not accept arguments which start with '-' even if the next character is a digit - args: []string{"--string-slice", "-3.14"}, - expectError: true, - errType: ErrExpectedArgument, - errMsg: "expected argument for flag `" + defaultLongOptDelimiter + "string-slice', but got option `-3.14'", - }, - { - // Do not accept arguments which start with '-' if the next character is not a digit - args: []string{"--string-slice", "-character"}, - expectError: true, - errType: ErrExpectedArgument, - errMsg: "expected argument for flag `" + defaultLongOptDelimiter + "string-slice', but got option `-character'", - }, - { - args: []string{"-o", "-", "-"}, - rest: []string{"-", "-"}, - }, - { - // Accept arguments which start with '-' if the next character is a digit, for number options only - args: []string{"--int-slice", "-3"}, - }, - { - // Accept arguments which start with '-' if the next character is a digit, for number options only - args: []string{"--int16", "-3"}, - }, - { - // Accept arguments which start with '-' if the next character is a digit, for number options only - args: []string{"--float32", "-3.2"}, - }, - { - // Accept arguments which start with '-' if the next character is a digit, for number options only - args: []string{"--float32ptr", "-3.2"}, - }, - } - - var opts struct { - StringSlice []string `long:"string-slice"` - IntSlice []int `long:"int-slice"` - Int16 int16 `long:"int16"` - Float32 float32 `long:"float32"` - Float32Ptr *float32 `long:"float32ptr"` - OtherOption bool `long:"other-option" short:"o"` - } - - for _, test := range tests { - if test.expectError { - assertParseFail(t, test.errType, test.errMsg, &opts, test.args...) - } else { - args := assertParseSuccess(t, &opts, test.args...) - - assertStringArray(t, args, test.rest) - } - } -} - -func TestUnknownFlagHandler(t *testing.T) { - - var opts struct { - Flag1 string `long:"flag1"` - Flag2 string `long:"flag2"` - } - - p := NewParser(&opts, None) - - var unknownFlag1 string - var unknownFlag2 bool - var unknownFlag3 string - - // Set up a callback to intercept unknown options during parsing - p.UnknownOptionHandler = func(option string, arg SplitArgument, args []string) ([]string, error) { - if option == "unknownFlag1" { - if argValue, ok := arg.Value(); ok { - unknownFlag1 = argValue - return args, nil - } - // consume a value from remaining args list - unknownFlag1 = args[0] - return args[1:], nil - } else if option == "unknownFlag2" { - // treat this one as a bool switch, don't consume any args - unknownFlag2 = true - return args, nil - } else if option == "unknownFlag3" { - if argValue, ok := arg.Value(); ok { - unknownFlag3 = argValue - return args, nil - } - // consume a value from remaining args list - unknownFlag3 = args[0] - return args[1:], nil - } - - return args, fmt.Errorf("Unknown flag: %v", option) - } - - // Parse args containing some unknown flags, verify that - // our callback can handle all of them - _, err := p.ParseArgs([]string{"--flag1=stuff", "--unknownFlag1", "blah", "--unknownFlag2", "--unknownFlag3=baz", "--flag2=foo"}) - - if err != nil { - assertErrorf(t, "Parser returned unexpected error %v", err) - } - - assertString(t, opts.Flag1, "stuff") - assertString(t, opts.Flag2, "foo") - assertString(t, unknownFlag1, "blah") - assertString(t, unknownFlag3, "baz") - - if !unknownFlag2 { - assertErrorf(t, "Flag should have been set by unknown handler, but had value: %v", unknownFlag2) - } - - // Parse args with unknown flags that callback doesn't handle, verify it returns error - _, err = p.ParseArgs([]string{"--flag1=stuff", "--unknownFlagX", "blah", "--flag2=foo"}) - - if err == nil { - assertErrorf(t, "Parser should have returned error, but returned nil") - } -} - -func TestChoices(t *testing.T) { - var opts struct { - Choice string `long:"choose" choice:"v1" choice:"v2"` - } - - assertParseFail(t, ErrInvalidChoice, "Invalid value `invalid' for option `"+defaultLongOptDelimiter+"choose'. Allowed values are: v1 or v2", &opts, "--choose", "invalid") - assertParseSuccess(t, &opts, "--choose", "v2") - assertString(t, opts.Choice, "v2") -} - -func TestEmbedded(t *testing.T) { - type embedded struct { - V bool `short:"v"` - } - var opts struct { - embedded - } - - assertParseSuccess(t, &opts, "-v") - - if !opts.V { - t.Errorf("Expected V to be true") - } -} - -type command struct { -} - -func (c *command) Execute(args []string) error { - return nil -} - -func TestCommandHandlerNoCommand(t *testing.T) { - var opts = struct { - Value bool `short:"v"` - }{} - - parser := NewParser(&opts, Default&^PrintErrors) - - var executedCommand Commander - var executedArgs []string - - executed := false - - parser.CommandHandler = func(command Commander, args []string) error { - executed = true - - executedCommand = command - executedArgs = args - - return nil - } - - _, err := parser.ParseArgs([]string{"arg1", "arg2"}) - - if err != nil { - t.Fatalf("Unexpected parse error: %s", err) - } - - if !executed { - t.Errorf("Expected command handler to be executed") - } - - if executedCommand != nil { - t.Errorf("Did not exect an executed command") - } - - assertStringArray(t, executedArgs, []string{"arg1", "arg2"}) -} - -func TestCommandHandler(t *testing.T) { - var opts = struct { - Value bool `short:"v"` - - Command command `command:"cmd"` - }{} - - parser := NewParser(&opts, Default&^PrintErrors) - - var executedCommand Commander - var executedArgs []string - - executed := false - - parser.CommandHandler = func(command Commander, args []string) error { - executed = true - - executedCommand = command - executedArgs = args - - return nil - } - - _, err := parser.ParseArgs([]string{"cmd", "arg1", "arg2"}) - - if err != nil { - t.Fatalf("Unexpected parse error: %s", err) - } - - if !executed { - t.Errorf("Expected command handler to be executed") - } - - if executedCommand == nil { - t.Errorf("Expected command handler to be executed") - } - - assertStringArray(t, executedArgs, []string{"arg1", "arg2"}) -} diff --git a/vendor/github.com/jessevdk/go-flags/pointer_test.go b/vendor/github.com/jessevdk/go-flags/pointer_test.go deleted file mode 100644 index dc779c78e..000000000 --- a/vendor/github.com/jessevdk/go-flags/pointer_test.go +++ /dev/null @@ -1,164 +0,0 @@ -package flags - -import ( - "testing" -) - -func TestPointerBool(t *testing.T) { - var opts = struct { - Value *bool `short:"v"` - }{} - - ret := assertParseSuccess(t, &opts, "-v") - - assertStringArray(t, ret, []string{}) - - if !*opts.Value { - t.Errorf("Expected Value to be true") - } -} - -func TestPointerString(t *testing.T) { - var opts = struct { - Value *string `short:"v"` - }{} - - ret := assertParseSuccess(t, &opts, "-v", "value") - - assertStringArray(t, ret, []string{}) - assertString(t, *opts.Value, "value") -} - -func TestPointerSlice(t *testing.T) { - var opts = struct { - Value *[]string `short:"v"` - }{} - - ret := assertParseSuccess(t, &opts, "-v", "value1", "-v", "value2") - - assertStringArray(t, ret, []string{}) - assertStringArray(t, *opts.Value, []string{"value1", "value2"}) -} - -func TestPointerMap(t *testing.T) { - var opts = struct { - Value *map[string]int `short:"v"` - }{} - - ret := assertParseSuccess(t, &opts, "-v", "k1:2", "-v", "k2:-5") - - assertStringArray(t, ret, []string{}) - - if v, ok := (*opts.Value)["k1"]; !ok { - t.Errorf("Expected key \"k1\" to exist") - } else if v != 2 { - t.Errorf("Expected \"k1\" to be 2, but got %#v", v) - } - - if v, ok := (*opts.Value)["k2"]; !ok { - t.Errorf("Expected key \"k2\" to exist") - } else if v != -5 { - t.Errorf("Expected \"k2\" to be -5, but got %#v", v) - } -} - -type marshalledString string - -func (m *marshalledString) UnmarshalFlag(value string) error { - *m = marshalledString(value) - return nil -} - -func (m marshalledString) MarshalFlag() (string, error) { - return string(m), nil -} - -func TestPointerStringMarshalled(t *testing.T) { - var opts = struct { - Value *marshalledString `short:"v"` - }{} - - ret := assertParseSuccess(t, &opts, "-v", "value") - - assertStringArray(t, ret, []string{}) - - if opts.Value == nil { - t.Error("Expected value not to be nil") - return - } - - assertString(t, string(*opts.Value), "value") -} - -type marshalledStruct struct { - Value string -} - -func (m *marshalledStruct) UnmarshalFlag(value string) error { - m.Value = value - return nil -} - -func (m marshalledStruct) MarshalFlag() (string, error) { - return m.Value, nil -} - -func TestPointerStructMarshalled(t *testing.T) { - var opts = struct { - Value *marshalledStruct `short:"v"` - }{} - - ret := assertParseSuccess(t, &opts, "-v", "value") - - assertStringArray(t, ret, []string{}) - - if opts.Value == nil { - t.Error("Expected value not to be nil") - return - } - - assertString(t, opts.Value.Value, "value") -} - -type PointerGroup struct { - Value bool `short:"v"` -} - -func TestPointerGroup(t *testing.T) { - var opts = struct { - Group *PointerGroup `group:"Group Options"` - }{} - - ret := assertParseSuccess(t, &opts, "-v") - - assertStringArray(t, ret, []string{}) - - if !opts.Group.Value { - t.Errorf("Expected Group.Value to be true") - } -} - -func TestDoNotChangeNonTaggedFields(t *testing.T) { - var opts struct { - A struct { - Pointer *int - } - B *struct { - Pointer *int - } - } - - ret := assertParseSuccess(t, &opts) - - assertStringArray(t, ret, []string{}) - - if opts.A.Pointer != nil { - t.Error("Expected A.Pointer to be nil") - } - if opts.B != nil { - t.Error("Expected B to be nil") - } - if opts.B != nil && opts.B.Pointer != nil { - t.Error("Expected B.Pointer to be nil") - } -} diff --git a/vendor/github.com/jessevdk/go-flags/short_test.go b/vendor/github.com/jessevdk/go-flags/short_test.go deleted file mode 100644 index 5f4106b01..000000000 --- a/vendor/github.com/jessevdk/go-flags/short_test.go +++ /dev/null @@ -1,234 +0,0 @@ -package flags - -import ( - "fmt" - "testing" -) - -func TestShort(t *testing.T) { - var opts = struct { - Value bool `short:"v"` - }{} - - ret := assertParseSuccess(t, &opts, "-v") - - assertStringArray(t, ret, []string{}) - - if !opts.Value { - t.Errorf("Expected Value to be true") - } -} - -func TestShortTooLong(t *testing.T) { - var opts = struct { - Value bool `short:"vv"` - }{} - - assertParseFail(t, ErrShortNameTooLong, "short names can only be 1 character long, not `vv'", &opts) -} - -func TestShortRequired(t *testing.T) { - var opts = struct { - Value bool `short:"v" required:"true"` - }{} - - assertParseFail(t, ErrRequired, fmt.Sprintf("the required flag `%cv' was not specified", defaultShortOptDelimiter), &opts) -} - -func TestShortRequiredFalsy1(t *testing.T) { - var opts = struct { - Value bool `short:"v" required:"false"` - }{} - - assertParseSuccess(t, &opts) -} - -func TestShortRequiredFalsy2(t *testing.T) { - var opts = struct { - Value bool `short:"v" required:"no"` - }{} - - assertParseSuccess(t, &opts) -} - -func TestShortMultiConcat(t *testing.T) { - var opts = struct { - V bool `short:"v"` - O bool `short:"o"` - F bool `short:"f"` - }{} - - ret := assertParseSuccess(t, &opts, "-vo", "-f") - - assertStringArray(t, ret, []string{}) - - if !opts.V { - t.Errorf("Expected V to be true") - } - - if !opts.O { - t.Errorf("Expected O to be true") - } - - if !opts.F { - t.Errorf("Expected F to be true") - } -} - -func TestShortMultiRequiredConcat(t *testing.T) { - var opts = struct { - V bool `short:"v" required:"true"` - O bool `short:"o" required:"true"` - F bool `short:"f" required:"true"` - }{} - - ret := assertParseSuccess(t, &opts, "-vo", "-f") - - assertStringArray(t, ret, []string{}) - - if !opts.V { - t.Errorf("Expected V to be true") - } - - if !opts.O { - t.Errorf("Expected O to be true") - } - - if !opts.F { - t.Errorf("Expected F to be true") - } -} - -func TestShortMultiSlice(t *testing.T) { - var opts = struct { - Values []bool `short:"v"` - }{} - - ret := assertParseSuccess(t, &opts, "-v", "-v") - - assertStringArray(t, ret, []string{}) - assertBoolArray(t, opts.Values, []bool{true, true}) -} - -func TestShortMultiSliceConcat(t *testing.T) { - var opts = struct { - Values []bool `short:"v"` - }{} - - ret := assertParseSuccess(t, &opts, "-vvv") - - assertStringArray(t, ret, []string{}) - assertBoolArray(t, opts.Values, []bool{true, true, true}) -} - -func TestShortWithEqualArg(t *testing.T) { - var opts = struct { - Value string `short:"v"` - }{} - - ret := assertParseSuccess(t, &opts, "-v=value") - - assertStringArray(t, ret, []string{}) - assertString(t, opts.Value, "value") -} - -func TestShortWithArg(t *testing.T) { - var opts = struct { - Value string `short:"v"` - }{} - - ret := assertParseSuccess(t, &opts, "-vvalue") - - assertStringArray(t, ret, []string{}) - assertString(t, opts.Value, "value") -} - -func TestShortArg(t *testing.T) { - var opts = struct { - Value string `short:"v"` - }{} - - ret := assertParseSuccess(t, &opts, "-v", "value") - - assertStringArray(t, ret, []string{}) - assertString(t, opts.Value, "value") -} - -func TestShortMultiWithEqualArg(t *testing.T) { - var opts = struct { - F []bool `short:"f"` - Value string `short:"v"` - }{} - - assertParseFail(t, ErrExpectedArgument, fmt.Sprintf("expected argument for flag `%cv'", defaultShortOptDelimiter), &opts, "-ffv=value") -} - -func TestShortMultiArg(t *testing.T) { - var opts = struct { - F []bool `short:"f"` - Value string `short:"v"` - }{} - - ret := assertParseSuccess(t, &opts, "-ffv", "value") - - assertStringArray(t, ret, []string{}) - assertBoolArray(t, opts.F, []bool{true, true}) - assertString(t, opts.Value, "value") -} - -func TestShortMultiArgConcatFail(t *testing.T) { - var opts = struct { - F []bool `short:"f"` - Value string `short:"v"` - }{} - - assertParseFail(t, ErrExpectedArgument, fmt.Sprintf("expected argument for flag `%cv'", defaultShortOptDelimiter), &opts, "-ffvvalue") -} - -func TestShortMultiArgConcat(t *testing.T) { - var opts = struct { - F []bool `short:"f"` - Value string `short:"v"` - }{} - - ret := assertParseSuccess(t, &opts, "-vff") - - assertStringArray(t, ret, []string{}) - assertString(t, opts.Value, "ff") -} - -func TestShortOptional(t *testing.T) { - var opts = struct { - F []bool `short:"f"` - Value string `short:"v" optional:"yes" optional-value:"value"` - }{} - - ret := assertParseSuccess(t, &opts, "-fv", "f") - - assertStringArray(t, ret, []string{"f"}) - assertString(t, opts.Value, "value") -} - -func TestShortOptionalFalsy1(t *testing.T) { - var opts = struct { - F []bool `short:"f"` - Value string `short:"v" optional:"false" optional-value:"value"` - }{} - - ret := assertParseSuccess(t, &opts, "-fv", "f") - - assertStringArray(t, ret, []string{}) - assertString(t, opts.Value, "f") -} - -func TestShortOptionalFalsy2(t *testing.T) { - var opts = struct { - F []bool `short:"f"` - Value string `short:"v" optional:"no" optional-value:"value"` - }{} - - ret := assertParseSuccess(t, &opts, "-fv", "f") - - assertStringArray(t, ret, []string{}) - assertString(t, opts.Value, "f") -} diff --git a/vendor/github.com/jessevdk/go-flags/tag_test.go b/vendor/github.com/jessevdk/go-flags/tag_test.go deleted file mode 100644 index 9daa7401b..000000000 --- a/vendor/github.com/jessevdk/go-flags/tag_test.go +++ /dev/null @@ -1,38 +0,0 @@ -package flags - -import ( - "testing" -) - -func TestTagMissingColon(t *testing.T) { - var opts = struct { - Value bool `short` - }{} - - assertParseFail(t, ErrTag, "expected `:' after key name, but got end of tag (in `short`)", &opts, "") -} - -func TestTagMissingValue(t *testing.T) { - var opts = struct { - Value bool `short:` - }{} - - assertParseFail(t, ErrTag, "expected `\"' to start tag value at end of tag (in `short:`)", &opts, "") -} - -func TestTagMissingQuote(t *testing.T) { - var opts = struct { - Value bool `short:"v` - }{} - - assertParseFail(t, ErrTag, "expected end of tag value `\"' at end of tag (in `short:\"v`)", &opts, "") -} - -func TestTagNewline(t *testing.T) { - var opts = struct { - Value bool `long:"verbose" description:"verbose -something"` - }{} - - assertParseFail(t, ErrTag, "unexpected newline in tag value `description' (in `long:\"verbose\" description:\"verbose\nsomething\"`)", &opts, "") -} diff --git a/vendor/github.com/jessevdk/go-flags/unknown_test.go b/vendor/github.com/jessevdk/go-flags/unknown_test.go deleted file mode 100644 index 858be4588..000000000 --- a/vendor/github.com/jessevdk/go-flags/unknown_test.go +++ /dev/null @@ -1,66 +0,0 @@ -package flags - -import ( - "testing" -) - -func TestUnknownFlags(t *testing.T) { - var opts = struct { - Verbose []bool `short:"v" long:"verbose" description:"Verbose output"` - }{} - - args := []string{ - "-f", - } - - p := NewParser(&opts, 0) - args, err := p.ParseArgs(args) - - if err == nil { - t.Fatal("Expected error for unknown argument") - } -} - -func TestIgnoreUnknownFlags(t *testing.T) { - var opts = struct { - Verbose []bool `short:"v" long:"verbose" description:"Verbose output"` - }{} - - args := []string{ - "hello", - "world", - "-v", - "--foo=bar", - "--verbose", - "-f", - } - - p := NewParser(&opts, IgnoreUnknown) - args, err := p.ParseArgs(args) - - if err != nil { - t.Fatal(err) - } - - exargs := []string{ - "hello", - "world", - "--foo=bar", - "-f", - } - - issame := (len(args) == len(exargs)) - - if issame { - for i := 0; i < len(args); i++ { - if args[i] != exargs[i] { - issame = false - break - } - } - } - - if !issame { - t.Fatalf("Expected %v but got %v", exargs, args) - } -} diff --git a/vendor/github.com/jmespath/go-jmespath/.gitignore b/vendor/github.com/jmespath/go-jmespath/.gitignore deleted file mode 100644 index 531fcc11c..000000000 --- a/vendor/github.com/jmespath/go-jmespath/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -jpgo -jmespath-fuzz.zip -cpu.out -go-jmespath.test diff --git a/vendor/github.com/jmespath/go-jmespath/.travis.yml b/vendor/github.com/jmespath/go-jmespath/.travis.yml deleted file mode 100644 index 1f9807757..000000000 --- a/vendor/github.com/jmespath/go-jmespath/.travis.yml +++ /dev/null @@ -1,9 +0,0 @@ -language: go - -sudo: false - -go: - - 1.4 - -install: go get -v -t ./... -script: make test diff --git a/vendor/github.com/jmespath/go-jmespath/Makefile b/vendor/github.com/jmespath/go-jmespath/Makefile deleted file mode 100644 index a828d2848..000000000 --- a/vendor/github.com/jmespath/go-jmespath/Makefile +++ /dev/null @@ -1,44 +0,0 @@ - -CMD = jpgo - -help: - @echo "Please use \`make ' where is one of" - @echo " test to run all the tests" - @echo " build to build the library and jp executable" - @echo " generate to run codegen" - - -generate: - go generate ./... - -build: - rm -f $(CMD) - go build ./... - rm -f cmd/$(CMD)/$(CMD) && cd cmd/$(CMD)/ && go build ./... - mv cmd/$(CMD)/$(CMD) . - -test: - go test -v ./... - -check: - go vet ./... - @echo "golint ./..." - @lint=`golint ./...`; \ - lint=`echo "$$lint" | grep -v "astnodetype_string.go" | grep -v "toktype_string.go"`; \ - echo "$$lint"; \ - if [ "$$lint" != "" ]; then exit 1; fi - -htmlc: - go test -coverprofile="/tmp/jpcov" && go tool cover -html="/tmp/jpcov" && unlink /tmp/jpcov - -buildfuzz: - go-fuzz-build github.com/jmespath/go-jmespath/fuzz - -fuzz: buildfuzz - go-fuzz -bin=./jmespath-fuzz.zip -workdir=fuzz/testdata - -bench: - go test -bench . -cpuprofile cpu.out - -pprof-cpu: - go tool pprof ./go-jmespath.test ./cpu.out diff --git a/vendor/github.com/jmespath/go-jmespath/README.md b/vendor/github.com/jmespath/go-jmespath/README.md deleted file mode 100644 index 187ef676d..000000000 --- a/vendor/github.com/jmespath/go-jmespath/README.md +++ /dev/null @@ -1,7 +0,0 @@ -# go-jmespath - A JMESPath implementation in Go - -[![Build Status](https://img.shields.io/travis/jmespath/go-jmespath.svg)](https://travis-ci.org/jmespath/go-jmespath) - - - -See http://jmespath.org for more info. diff --git a/vendor/github.com/jmespath/go-jmespath/api_test.go b/vendor/github.com/jmespath/go-jmespath/api_test.go deleted file mode 100644 index b0b106d3d..000000000 --- a/vendor/github.com/jmespath/go-jmespath/api_test.go +++ /dev/null @@ -1,32 +0,0 @@ -package jmespath - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestValidPrecompiledExpressionSearches(t *testing.T) { - assert := assert.New(t) - data := make(map[string]interface{}) - data["foo"] = "bar" - precompiled, err := Compile("foo") - assert.Nil(err) - result, err := precompiled.Search(data) - assert.Nil(err) - assert.Equal("bar", result) -} - -func TestInvalidPrecompileErrors(t *testing.T) { - assert := assert.New(t) - _, err := Compile("not a valid expression") - assert.NotNil(err) -} - -func TestInvalidMustCompilePanics(t *testing.T) { - defer func() { - r := recover() - assert.NotNil(t, r) - }() - MustCompile("not a valid expression") -} diff --git a/vendor/github.com/jmespath/go-jmespath/compliance_test.go b/vendor/github.com/jmespath/go-jmespath/compliance_test.go deleted file mode 100644 index 4ee9c959d..000000000 --- a/vendor/github.com/jmespath/go-jmespath/compliance_test.go +++ /dev/null @@ -1,123 +0,0 @@ -package jmespath - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "os" - "path/filepath" - "testing" - - "github.com/stretchr/testify/assert" -) - -type TestSuite struct { - Given interface{} - TestCases []TestCase `json:"cases"` - Comment string -} -type TestCase struct { - Comment string - Expression string - Result interface{} - Error string -} - -var whiteListed = []string{ - "compliance/basic.json", - "compliance/current.json", - "compliance/escape.json", - "compliance/filters.json", - "compliance/functions.json", - "compliance/identifiers.json", - "compliance/indices.json", - "compliance/literal.json", - "compliance/multiselect.json", - "compliance/ormatch.json", - "compliance/pipe.json", - "compliance/slice.json", - "compliance/syntax.json", - "compliance/unicode.json", - "compliance/wildcard.json", - "compliance/boolean.json", -} - -func allowed(path string) bool { - for _, el := range whiteListed { - if el == path { - return true - } - } - return false -} - -func TestCompliance(t *testing.T) { - assert := assert.New(t) - - var complianceFiles []string - err := filepath.Walk("compliance", func(path string, _ os.FileInfo, _ error) error { - //if strings.HasSuffix(path, ".json") { - if allowed(path) { - complianceFiles = append(complianceFiles, path) - } - return nil - }) - if assert.Nil(err) { - for _, filename := range complianceFiles { - runComplianceTest(assert, filename) - } - } -} - -func runComplianceTest(assert *assert.Assertions, filename string) { - var testSuites []TestSuite - data, err := ioutil.ReadFile(filename) - if assert.Nil(err) { - err := json.Unmarshal(data, &testSuites) - if assert.Nil(err) { - for _, testsuite := range testSuites { - runTestSuite(assert, testsuite, filename) - } - } - } -} - -func runTestSuite(assert *assert.Assertions, testsuite TestSuite, filename string) { - for _, testcase := range testsuite.TestCases { - if testcase.Error != "" { - // This is a test case that verifies we error out properly. - runSyntaxTestCase(assert, testsuite.Given, testcase, filename) - } else { - runTestCase(assert, testsuite.Given, testcase, filename) - } - } -} - -func runSyntaxTestCase(assert *assert.Assertions, given interface{}, testcase TestCase, filename string) { - // Anything with an .Error means that we expect that JMESPath should return - // an error when we try to evaluate the expression. - _, err := Search(testcase.Expression, given) - assert.NotNil(err, fmt.Sprintf("Expression: %s", testcase.Expression)) -} - -func runTestCase(assert *assert.Assertions, given interface{}, testcase TestCase, filename string) { - lexer := NewLexer() - var err error - _, err = lexer.tokenize(testcase.Expression) - if err != nil { - errMsg := fmt.Sprintf("(%s) Could not lex expression: %s -- %s", filename, testcase.Expression, err.Error()) - assert.Fail(errMsg) - return - } - parser := NewParser() - _, err = parser.Parse(testcase.Expression) - if err != nil { - errMsg := fmt.Sprintf("(%s) Could not parse expression: %s -- %s", filename, testcase.Expression, err.Error()) - assert.Fail(errMsg) - return - } - actual, err := Search(testcase.Expression, given) - if assert.Nil(err, fmt.Sprintf("Expression: %s", testcase.Expression)) { - assert.Equal(testcase.Result, actual, fmt.Sprintf("Expression: %s", testcase.Expression)) - } -} diff --git a/vendor/github.com/jmespath/go-jmespath/interpreter_test.go b/vendor/github.com/jmespath/go-jmespath/interpreter_test.go deleted file mode 100644 index 11c6d0aa0..000000000 --- a/vendor/github.com/jmespath/go-jmespath/interpreter_test.go +++ /dev/null @@ -1,221 +0,0 @@ -package jmespath - -import ( - "encoding/json" - "testing" - - "github.com/stretchr/testify/assert" -) - -type scalars struct { - Foo string - Bar string -} - -type sliceType struct { - A string - B []scalars - C []*scalars -} - -type benchmarkStruct struct { - Fooasdfasdfasdfasdf string -} - -type benchmarkNested struct { - Fooasdfasdfasdfasdf nestedA -} - -type nestedA struct { - Fooasdfasdfasdfasdf nestedB -} - -type nestedB struct { - Fooasdfasdfasdfasdf nestedC -} - -type nestedC struct { - Fooasdfasdfasdfasdf string -} - -type nestedSlice struct { - A []sliceType -} - -func TestCanSupportEmptyInterface(t *testing.T) { - assert := assert.New(t) - data := make(map[string]interface{}) - data["foo"] = "bar" - result, err := Search("foo", data) - assert.Nil(err) - assert.Equal("bar", result) -} - -func TestCanSupportUserDefinedStructsValue(t *testing.T) { - assert := assert.New(t) - s := scalars{Foo: "one", Bar: "bar"} - result, err := Search("Foo", s) - assert.Nil(err) - assert.Equal("one", result) -} - -func TestCanSupportUserDefinedStructsRef(t *testing.T) { - assert := assert.New(t) - s := scalars{Foo: "one", Bar: "bar"} - result, err := Search("Foo", &s) - assert.Nil(err) - assert.Equal("one", result) -} - -func TestCanSupportStructWithSliceAll(t *testing.T) { - assert := assert.New(t) - data := sliceType{A: "foo", B: []scalars{{"f1", "b1"}, {"correct", "b2"}}} - result, err := Search("B[].Foo", data) - assert.Nil(err) - assert.Equal([]interface{}{"f1", "correct"}, result) -} - -func TestCanSupportStructWithSlicingExpression(t *testing.T) { - assert := assert.New(t) - data := sliceType{A: "foo", B: []scalars{{"f1", "b1"}, {"correct", "b2"}}} - result, err := Search("B[:].Foo", data) - assert.Nil(err) - assert.Equal([]interface{}{"f1", "correct"}, result) -} - -func TestCanSupportStructWithFilterProjection(t *testing.T) { - assert := assert.New(t) - data := sliceType{A: "foo", B: []scalars{{"f1", "b1"}, {"correct", "b2"}}} - result, err := Search("B[? `true` ].Foo", data) - assert.Nil(err) - assert.Equal([]interface{}{"f1", "correct"}, result) -} - -func TestCanSupportStructWithSlice(t *testing.T) { - assert := assert.New(t) - data := sliceType{A: "foo", B: []scalars{{"f1", "b1"}, {"correct", "b2"}}} - result, err := Search("B[-1].Foo", data) - assert.Nil(err) - assert.Equal("correct", result) -} - -func TestCanSupportStructWithOrExpressions(t *testing.T) { - assert := assert.New(t) - data := sliceType{A: "foo", C: nil} - result, err := Search("C || A", data) - assert.Nil(err) - assert.Equal("foo", result) -} - -func TestCanSupportStructWithSlicePointer(t *testing.T) { - assert := assert.New(t) - data := sliceType{A: "foo", C: []*scalars{{"f1", "b1"}, {"correct", "b2"}}} - result, err := Search("C[-1].Foo", data) - assert.Nil(err) - assert.Equal("correct", result) -} - -func TestWillAutomaticallyCapitalizeFieldNames(t *testing.T) { - assert := assert.New(t) - s := scalars{Foo: "one", Bar: "bar"} - // Note that there's a lower cased "foo" instead of "Foo", - // but it should still correspond to the Foo field in the - // scalars struct - result, err := Search("foo", &s) - assert.Nil(err) - assert.Equal("one", result) -} - -func TestCanSupportStructWithSliceLowerCased(t *testing.T) { - assert := assert.New(t) - data := sliceType{A: "foo", B: []scalars{{"f1", "b1"}, {"correct", "b2"}}} - result, err := Search("b[-1].foo", data) - assert.Nil(err) - assert.Equal("correct", result) -} - -func TestCanSupportStructWithNestedPointers(t *testing.T) { - assert := assert.New(t) - data := struct{ A *struct{ B int } }{} - result, err := Search("A.B", data) - assert.Nil(err) - assert.Nil(result) -} - -func TestCanSupportFlattenNestedSlice(t *testing.T) { - assert := assert.New(t) - data := nestedSlice{A: []sliceType{ - {B: []scalars{{Foo: "f1a"}, {Foo: "f1b"}}}, - {B: []scalars{{Foo: "f2a"}, {Foo: "f2b"}}}, - }} - result, err := Search("A[].B[].Foo", data) - assert.Nil(err) - assert.Equal([]interface{}{"f1a", "f1b", "f2a", "f2b"}, result) -} - -func TestCanSupportFlattenNestedEmptySlice(t *testing.T) { - assert := assert.New(t) - data := nestedSlice{A: []sliceType{ - {}, {B: []scalars{{Foo: "a"}}}, - }} - result, err := Search("A[].B[].Foo", data) - assert.Nil(err) - assert.Equal([]interface{}{"a"}, result) -} - -func TestCanSupportProjectionsWithStructs(t *testing.T) { - assert := assert.New(t) - data := nestedSlice{A: []sliceType{ - {A: "first"}, {A: "second"}, {A: "third"}, - }} - result, err := Search("A[*].A", data) - assert.Nil(err) - assert.Equal([]interface{}{"first", "second", "third"}, result) -} - -func TestCanSupportSliceOfStructsWithFunctions(t *testing.T) { - assert := assert.New(t) - data := []scalars{scalars{"a1", "b1"}, scalars{"a2", "b2"}} - result, err := Search("length(@)", data) - assert.Nil(err) - assert.Equal(result.(float64), 2.0) -} - -func BenchmarkInterpretSingleFieldStruct(b *testing.B) { - intr := newInterpreter() - parser := NewParser() - ast, _ := parser.Parse("fooasdfasdfasdfasdf") - data := benchmarkStruct{"foobarbazqux"} - for i := 0; i < b.N; i++ { - intr.Execute(ast, &data) - } -} - -func BenchmarkInterpretNestedStruct(b *testing.B) { - intr := newInterpreter() - parser := NewParser() - ast, _ := parser.Parse("fooasdfasdfasdfasdf.fooasdfasdfasdfasdf.fooasdfasdfasdfasdf.fooasdfasdfasdfasdf") - data := benchmarkNested{ - nestedA{ - nestedB{ - nestedC{"foobarbazqux"}, - }, - }, - } - for i := 0; i < b.N; i++ { - intr.Execute(ast, &data) - } -} - -func BenchmarkInterpretNestedMaps(b *testing.B) { - jsonData := []byte(`{"fooasdfasdfasdfasdf": {"fooasdfasdfasdfasdf": {"fooasdfasdfasdfasdf": {"fooasdfasdfasdfasdf": "foobarbazqux"}}}}`) - var data interface{} - json.Unmarshal(jsonData, &data) - - intr := newInterpreter() - parser := NewParser() - ast, _ := parser.Parse("fooasdfasdfasdfasdf.fooasdfasdfasdfasdf.fooasdfasdfasdfasdf.fooasdfasdfasdfasdf") - for i := 0; i < b.N; i++ { - intr.Execute(ast, data) - } -} diff --git a/vendor/github.com/jmespath/go-jmespath/lexer_test.go b/vendor/github.com/jmespath/go-jmespath/lexer_test.go deleted file mode 100644 index d13a042da..000000000 --- a/vendor/github.com/jmespath/go-jmespath/lexer_test.go +++ /dev/null @@ -1,161 +0,0 @@ -package jmespath - -import ( - "fmt" - "testing" - - "github.com/stretchr/testify/assert" -) - -var lexingTests = []struct { - expression string - expected []token -}{ - {"*", []token{{tStar, "*", 0, 1}}}, - {".", []token{{tDot, ".", 0, 1}}}, - {"[?", []token{{tFilter, "[?", 0, 2}}}, - {"[]", []token{{tFlatten, "[]", 0, 2}}}, - {"(", []token{{tLparen, "(", 0, 1}}}, - {")", []token{{tRparen, ")", 0, 1}}}, - {"[", []token{{tLbracket, "[", 0, 1}}}, - {"]", []token{{tRbracket, "]", 0, 1}}}, - {"{", []token{{tLbrace, "{", 0, 1}}}, - {"}", []token{{tRbrace, "}", 0, 1}}}, - {"||", []token{{tOr, "||", 0, 2}}}, - {"|", []token{{tPipe, "|", 0, 1}}}, - {"29", []token{{tNumber, "29", 0, 2}}}, - {"2", []token{{tNumber, "2", 0, 1}}}, - {"0", []token{{tNumber, "0", 0, 1}}}, - {"-20", []token{{tNumber, "-20", 0, 3}}}, - {"foo", []token{{tUnquotedIdentifier, "foo", 0, 3}}}, - {`"bar"`, []token{{tQuotedIdentifier, "bar", 0, 3}}}, - // Escaping the delimiter - {`"bar\"baz"`, []token{{tQuotedIdentifier, `bar"baz`, 0, 7}}}, - {",", []token{{tComma, ",", 0, 1}}}, - {":", []token{{tColon, ":", 0, 1}}}, - {"<", []token{{tLT, "<", 0, 1}}}, - {"<=", []token{{tLTE, "<=", 0, 2}}}, - {">", []token{{tGT, ">", 0, 1}}}, - {">=", []token{{tGTE, ">=", 0, 2}}}, - {"==", []token{{tEQ, "==", 0, 2}}}, - {"!=", []token{{tNE, "!=", 0, 2}}}, - {"`[0, 1, 2]`", []token{{tJSONLiteral, "[0, 1, 2]", 1, 9}}}, - {"'foo'", []token{{tStringLiteral, "foo", 1, 3}}}, - {"'a'", []token{{tStringLiteral, "a", 1, 1}}}, - {`'foo\'bar'`, []token{{tStringLiteral, "foo'bar", 1, 7}}}, - {"@", []token{{tCurrent, "@", 0, 1}}}, - {"&", []token{{tExpref, "&", 0, 1}}}, - // Quoted identifier unicode escape sequences - {`"\u2713"`, []token{{tQuotedIdentifier, "✓", 0, 3}}}, - {`"\\"`, []token{{tQuotedIdentifier, `\`, 0, 1}}}, - {"`\"foo\"`", []token{{tJSONLiteral, "\"foo\"", 1, 5}}}, - // Combinations of tokens. - {"foo.bar", []token{ - {tUnquotedIdentifier, "foo", 0, 3}, - {tDot, ".", 3, 1}, - {tUnquotedIdentifier, "bar", 4, 3}, - }}, - {"foo[0]", []token{ - {tUnquotedIdentifier, "foo", 0, 3}, - {tLbracket, "[", 3, 1}, - {tNumber, "0", 4, 1}, - {tRbracket, "]", 5, 1}, - }}, - {"foo[?a= any.val.Len() { + return newInvalidAny(path) + } + return Wrap(any.val.Index(firstPath).Interface()) + case int32: + if '*' == firstPath { + mappedAll := make([]Any, 0) + for i := 0; i < any.val.Len(); i++ { + mapped := Wrap(any.val.Index(i).Interface()).Get(path[1:]...) + if mapped.ValueType() != InvalidValue { + mappedAll = append(mappedAll, mapped) + } + } + return wrapArray(mappedAll) + } + return newInvalidAny(path) + default: + return newInvalidAny(path) + } +} + +func (any *arrayAny) Size() int { + return any.val.Len() +} + +func (any *arrayAny) WriteTo(stream *Stream) { + stream.WriteVal(any.val) +} + +func (any *arrayAny) GetInterface() interface{} { + return any.val.Interface() +} diff --git a/vendor/github.com/json-iterator/go/any_bool.go b/vendor/github.com/json-iterator/go/any_bool.go new file mode 100644 index 000000000..9452324af --- /dev/null +++ b/vendor/github.com/json-iterator/go/any_bool.go @@ -0,0 +1,137 @@ +package jsoniter + +type trueAny struct { + baseAny +} + +func (any *trueAny) LastError() error { + return nil +} + +func (any *trueAny) ToBool() bool { + return true +} + +func (any *trueAny) ToInt() int { + return 1 +} + +func (any *trueAny) ToInt32() int32 { + return 1 +} + +func (any *trueAny) ToInt64() int64 { + return 1 +} + +func (any *trueAny) ToUint() uint { + return 1 +} + +func (any *trueAny) ToUint32() uint32 { + return 1 +} + +func (any *trueAny) ToUint64() uint64 { + return 1 +} + +func (any *trueAny) ToFloat32() float32 { + return 1 +} + +func (any *trueAny) ToFloat64() float64 { + return 1 +} + +func (any *trueAny) ToString() string { + return "true" +} + +func (any *trueAny) WriteTo(stream *Stream) { + stream.WriteTrue() +} + +func (any *trueAny) Parse() *Iterator { + return nil +} + +func (any *trueAny) GetInterface() interface{} { + return true +} + +func (any *trueAny) ValueType() ValueType { + return BoolValue +} + +func (any *trueAny) MustBeValid() Any { + return any +} + +type falseAny struct { + baseAny +} + +func (any *falseAny) LastError() error { + return nil +} + +func (any *falseAny) ToBool() bool { + return false +} + +func (any *falseAny) ToInt() int { + return 0 +} + +func (any *falseAny) ToInt32() int32 { + return 0 +} + +func (any *falseAny) ToInt64() int64 { + return 0 +} + +func (any *falseAny) ToUint() uint { + return 0 +} + +func (any *falseAny) ToUint32() uint32 { + return 0 +} + +func (any *falseAny) ToUint64() uint64 { + return 0 +} + +func (any *falseAny) ToFloat32() float32 { + return 0 +} + +func (any *falseAny) ToFloat64() float64 { + return 0 +} + +func (any *falseAny) ToString() string { + return "false" +} + +func (any *falseAny) WriteTo(stream *Stream) { + stream.WriteFalse() +} + +func (any *falseAny) Parse() *Iterator { + return nil +} + +func (any *falseAny) GetInterface() interface{} { + return false +} + +func (any *falseAny) ValueType() ValueType { + return BoolValue +} + +func (any *falseAny) MustBeValid() Any { + return any +} diff --git a/vendor/github.com/json-iterator/go/any_float.go b/vendor/github.com/json-iterator/go/any_float.go new file mode 100644 index 000000000..35fdb0949 --- /dev/null +++ b/vendor/github.com/json-iterator/go/any_float.go @@ -0,0 +1,83 @@ +package jsoniter + +import ( + "strconv" +) + +type floatAny struct { + baseAny + val float64 +} + +func (any *floatAny) Parse() *Iterator { + return nil +} + +func (any *floatAny) ValueType() ValueType { + return NumberValue +} + +func (any *floatAny) MustBeValid() Any { + return any +} + +func (any *floatAny) LastError() error { + return nil +} + +func (any *floatAny) ToBool() bool { + return any.ToFloat64() != 0 +} + +func (any *floatAny) ToInt() int { + return int(any.val) +} + +func (any *floatAny) ToInt32() int32 { + return int32(any.val) +} + +func (any *floatAny) ToInt64() int64 { + return int64(any.val) +} + +func (any *floatAny) ToUint() uint { + if any.val > 0 { + return uint(any.val) + } + return 0 +} + +func (any *floatAny) ToUint32() uint32 { + if any.val > 0 { + return uint32(any.val) + } + return 0 +} + +func (any *floatAny) ToUint64() uint64 { + if any.val > 0 { + return uint64(any.val) + } + return 0 +} + +func (any *floatAny) ToFloat32() float32 { + return float32(any.val) +} + +func (any *floatAny) ToFloat64() float64 { + return any.val +} + +func (any *floatAny) ToString() string { + return strconv.FormatFloat(any.val, 'E', -1, 64) +} + +func (any *floatAny) WriteTo(stream *Stream) { + stream.WriteFloat64(any.val) +} + +func (any *floatAny) GetInterface() interface{} { + return any.val +} diff --git a/vendor/github.com/json-iterator/go/any_int32.go b/vendor/github.com/json-iterator/go/any_int32.go new file mode 100644 index 000000000..1b56f3991 --- /dev/null +++ b/vendor/github.com/json-iterator/go/any_int32.go @@ -0,0 +1,74 @@ +package jsoniter + +import ( + "strconv" +) + +type int32Any struct { + baseAny + val int32 +} + +func (any *int32Any) LastError() error { + return nil +} + +func (any *int32Any) ValueType() ValueType { + return NumberValue +} + +func (any *int32Any) MustBeValid() Any { + return any +} + +func (any *int32Any) ToBool() bool { + return any.val != 0 +} + +func (any *int32Any) ToInt() int { + return int(any.val) +} + +func (any *int32Any) ToInt32() int32 { + return any.val +} + +func (any *int32Any) ToInt64() int64 { + return int64(any.val) +} + +func (any *int32Any) ToUint() uint { + return uint(any.val) +} + +func (any *int32Any) ToUint32() uint32 { + return uint32(any.val) +} + +func (any *int32Any) ToUint64() uint64 { + return uint64(any.val) +} + +func (any *int32Any) ToFloat32() float32 { + return float32(any.val) +} + +func (any *int32Any) ToFloat64() float64 { + return float64(any.val) +} + +func (any *int32Any) ToString() string { + return strconv.FormatInt(int64(any.val), 10) +} + +func (any *int32Any) WriteTo(stream *Stream) { + stream.WriteInt32(any.val) +} + +func (any *int32Any) Parse() *Iterator { + return nil +} + +func (any *int32Any) GetInterface() interface{} { + return any.val +} diff --git a/vendor/github.com/json-iterator/go/any_int64.go b/vendor/github.com/json-iterator/go/any_int64.go new file mode 100644 index 000000000..c440d72b6 --- /dev/null +++ b/vendor/github.com/json-iterator/go/any_int64.go @@ -0,0 +1,74 @@ +package jsoniter + +import ( + "strconv" +) + +type int64Any struct { + baseAny + val int64 +} + +func (any *int64Any) LastError() error { + return nil +} + +func (any *int64Any) ValueType() ValueType { + return NumberValue +} + +func (any *int64Any) MustBeValid() Any { + return any +} + +func (any *int64Any) ToBool() bool { + return any.val != 0 +} + +func (any *int64Any) ToInt() int { + return int(any.val) +} + +func (any *int64Any) ToInt32() int32 { + return int32(any.val) +} + +func (any *int64Any) ToInt64() int64 { + return any.val +} + +func (any *int64Any) ToUint() uint { + return uint(any.val) +} + +func (any *int64Any) ToUint32() uint32 { + return uint32(any.val) +} + +func (any *int64Any) ToUint64() uint64 { + return uint64(any.val) +} + +func (any *int64Any) ToFloat32() float32 { + return float32(any.val) +} + +func (any *int64Any) ToFloat64() float64 { + return float64(any.val) +} + +func (any *int64Any) ToString() string { + return strconv.FormatInt(any.val, 10) +} + +func (any *int64Any) WriteTo(stream *Stream) { + stream.WriteInt64(any.val) +} + +func (any *int64Any) Parse() *Iterator { + return nil +} + +func (any *int64Any) GetInterface() interface{} { + return any.val +} diff --git a/vendor/github.com/json-iterator/go/any_invalid.go b/vendor/github.com/json-iterator/go/any_invalid.go new file mode 100644 index 000000000..1d859eac3 --- /dev/null +++ b/vendor/github.com/json-iterator/go/any_invalid.go @@ -0,0 +1,82 @@ +package jsoniter + +import "fmt" + +type invalidAny struct { + baseAny + err error +} + +func newInvalidAny(path []interface{}) *invalidAny { + return &invalidAny{baseAny{}, fmt.Errorf("%v not found", path)} +} + +func (any *invalidAny) LastError() error { + return any.err +} + +func (any *invalidAny) ValueType() ValueType { + return InvalidValue +} + +func (any *invalidAny) MustBeValid() Any { + panic(any.err) +} + +func (any *invalidAny) ToBool() bool { + return false +} + +func (any *invalidAny) ToInt() int { + return 0 +} + +func (any *invalidAny) ToInt32() int32 { + return 0 +} + +func (any *invalidAny) ToInt64() int64 { + return 0 +} + +func (any *invalidAny) ToUint() uint { + return 0 +} + +func (any *invalidAny) ToUint32() uint32 { + return 0 +} + +func (any *invalidAny) ToUint64() uint64 { + return 0 +} + +func (any *invalidAny) ToFloat32() float32 { + return 0 +} + +func (any *invalidAny) ToFloat64() float64 { + return 0 +} + +func (any *invalidAny) ToString() string { + return "" +} + +func (any *invalidAny) WriteTo(stream *Stream) { +} + +func (any *invalidAny) Get(path ...interface{}) Any { + if any.err == nil { + return &invalidAny{baseAny{}, fmt.Errorf("get %v from invalid", path)} + } + return &invalidAny{baseAny{}, fmt.Errorf("%v, get %v from invalid", any.err, path)} +} + +func (any *invalidAny) Parse() *Iterator { + return nil +} + +func (any *invalidAny) GetInterface() interface{} { + return nil +} diff --git a/vendor/github.com/json-iterator/go/any_nil.go b/vendor/github.com/json-iterator/go/any_nil.go new file mode 100644 index 000000000..d04cb54c1 --- /dev/null +++ b/vendor/github.com/json-iterator/go/any_nil.go @@ -0,0 +1,69 @@ +package jsoniter + +type nilAny struct { + baseAny +} + +func (any *nilAny) LastError() error { + return nil +} + +func (any *nilAny) ValueType() ValueType { + return NilValue +} + +func (any *nilAny) MustBeValid() Any { + return any +} + +func (any *nilAny) ToBool() bool { + return false +} + +func (any *nilAny) ToInt() int { + return 0 +} + +func (any *nilAny) ToInt32() int32 { + return 0 +} + +func (any *nilAny) ToInt64() int64 { + return 0 +} + +func (any *nilAny) ToUint() uint { + return 0 +} + +func (any *nilAny) ToUint32() uint32 { + return 0 +} + +func (any *nilAny) ToUint64() uint64 { + return 0 +} + +func (any *nilAny) ToFloat32() float32 { + return 0 +} + +func (any *nilAny) ToFloat64() float64 { + return 0 +} + +func (any *nilAny) ToString() string { + return "" +} + +func (any *nilAny) WriteTo(stream *Stream) { + stream.WriteNil() +} + +func (any *nilAny) Parse() *Iterator { + return nil +} + +func (any *nilAny) GetInterface() interface{} { + return nil +} diff --git a/vendor/github.com/json-iterator/go/any_number.go b/vendor/github.com/json-iterator/go/any_number.go new file mode 100644 index 000000000..9d1e901a6 --- /dev/null +++ b/vendor/github.com/json-iterator/go/any_number.go @@ -0,0 +1,123 @@ +package jsoniter + +import ( + "io" + "unsafe" +) + +type numberLazyAny struct { + baseAny + cfg *frozenConfig + buf []byte + err error +} + +func (any *numberLazyAny) ValueType() ValueType { + return NumberValue +} + +func (any *numberLazyAny) MustBeValid() Any { + return any +} + +func (any *numberLazyAny) LastError() error { + return any.err +} + +func (any *numberLazyAny) ToBool() bool { + return any.ToFloat64() != 0 +} + +func (any *numberLazyAny) ToInt() int { + iter := any.cfg.BorrowIterator(any.buf) + defer any.cfg.ReturnIterator(iter) + val := iter.ReadInt() + if iter.Error != nil && iter.Error != io.EOF { + any.err = iter.Error + } + return val +} + +func (any *numberLazyAny) ToInt32() int32 { + iter := any.cfg.BorrowIterator(any.buf) + defer any.cfg.ReturnIterator(iter) + val := iter.ReadInt32() + if iter.Error != nil && iter.Error != io.EOF { + any.err = iter.Error + } + return val +} + +func (any *numberLazyAny) ToInt64() int64 { + iter := any.cfg.BorrowIterator(any.buf) + defer any.cfg.ReturnIterator(iter) + val := iter.ReadInt64() + if iter.Error != nil && iter.Error != io.EOF { + any.err = iter.Error + } + return val +} + +func (any *numberLazyAny) ToUint() uint { + iter := any.cfg.BorrowIterator(any.buf) + defer any.cfg.ReturnIterator(iter) + val := iter.ReadUint() + if iter.Error != nil && iter.Error != io.EOF { + any.err = iter.Error + } + return val +} + +func (any *numberLazyAny) ToUint32() uint32 { + iter := any.cfg.BorrowIterator(any.buf) + defer any.cfg.ReturnIterator(iter) + val := iter.ReadUint32() + if iter.Error != nil && iter.Error != io.EOF { + any.err = iter.Error + } + return val +} + +func (any *numberLazyAny) ToUint64() uint64 { + iter := any.cfg.BorrowIterator(any.buf) + defer any.cfg.ReturnIterator(iter) + val := iter.ReadUint64() + if iter.Error != nil && iter.Error != io.EOF { + any.err = iter.Error + } + return val +} + +func (any *numberLazyAny) ToFloat32() float32 { + iter := any.cfg.BorrowIterator(any.buf) + defer any.cfg.ReturnIterator(iter) + val := iter.ReadFloat32() + if iter.Error != nil && iter.Error != io.EOF { + any.err = iter.Error + } + return val +} + +func (any *numberLazyAny) ToFloat64() float64 { + iter := any.cfg.BorrowIterator(any.buf) + defer any.cfg.ReturnIterator(iter) + val := iter.ReadFloat64() + if iter.Error != nil && iter.Error != io.EOF { + any.err = iter.Error + } + return val +} + +func (any *numberLazyAny) ToString() string { + return *(*string)(unsafe.Pointer(&any.buf)) +} + +func (any *numberLazyAny) WriteTo(stream *Stream) { + stream.Write(any.buf) +} + +func (any *numberLazyAny) GetInterface() interface{} { + iter := any.cfg.BorrowIterator(any.buf) + defer any.cfg.ReturnIterator(iter) + return iter.Read() +} diff --git a/vendor/github.com/json-iterator/go/any_object.go b/vendor/github.com/json-iterator/go/any_object.go new file mode 100644 index 000000000..c44ef5c98 --- /dev/null +++ b/vendor/github.com/json-iterator/go/any_object.go @@ -0,0 +1,374 @@ +package jsoniter + +import ( + "reflect" + "unsafe" +) + +type objectLazyAny struct { + baseAny + cfg *frozenConfig + buf []byte + err error +} + +func (any *objectLazyAny) ValueType() ValueType { + return ObjectValue +} + +func (any *objectLazyAny) MustBeValid() Any { + return any +} + +func (any *objectLazyAny) LastError() error { + return any.err +} + +func (any *objectLazyAny) ToBool() bool { + return true +} + +func (any *objectLazyAny) ToInt() int { + return 0 +} + +func (any *objectLazyAny) ToInt32() int32 { + return 0 +} + +func (any *objectLazyAny) ToInt64() int64 { + return 0 +} + +func (any *objectLazyAny) ToUint() uint { + return 0 +} + +func (any *objectLazyAny) ToUint32() uint32 { + return 0 +} + +func (any *objectLazyAny) ToUint64() uint64 { + return 0 +} + +func (any *objectLazyAny) ToFloat32() float32 { + return 0 +} + +func (any *objectLazyAny) ToFloat64() float64 { + return 0 +} + +func (any *objectLazyAny) ToString() string { + return *(*string)(unsafe.Pointer(&any.buf)) +} + +func (any *objectLazyAny) ToVal(obj interface{}) { + iter := any.cfg.BorrowIterator(any.buf) + defer any.cfg.ReturnIterator(iter) + iter.ReadVal(obj) +} + +func (any *objectLazyAny) Get(path ...interface{}) Any { + if len(path) == 0 { + return any + } + switch firstPath := path[0].(type) { + case string: + iter := any.cfg.BorrowIterator(any.buf) + defer any.cfg.ReturnIterator(iter) + valueBytes := locateObjectField(iter, firstPath) + if valueBytes == nil { + return newInvalidAny(path) + } + iter.ResetBytes(valueBytes) + return locatePath(iter, path[1:]) + case int32: + if '*' == firstPath { + mappedAll := map[string]Any{} + iter := any.cfg.BorrowIterator(any.buf) + defer any.cfg.ReturnIterator(iter) + iter.ReadMapCB(func(iter *Iterator, field string) bool { + mapped := locatePath(iter, path[1:]) + if mapped.ValueType() != InvalidValue { + mappedAll[field] = mapped + } + return true + }) + return wrapMap(mappedAll) + } + return newInvalidAny(path) + default: + return newInvalidAny(path) + } +} + +func (any *objectLazyAny) Keys() []string { + keys := []string{} + iter := any.cfg.BorrowIterator(any.buf) + defer any.cfg.ReturnIterator(iter) + iter.ReadMapCB(func(iter *Iterator, field string) bool { + iter.Skip() + keys = append(keys, field) + return true + }) + return keys +} + +func (any *objectLazyAny) Size() int { + size := 0 + iter := any.cfg.BorrowIterator(any.buf) + defer any.cfg.ReturnIterator(iter) + iter.ReadObjectCB(func(iter *Iterator, field string) bool { + iter.Skip() + size++ + return true + }) + return size +} + +func (any *objectLazyAny) WriteTo(stream *Stream) { + stream.Write(any.buf) +} + +func (any *objectLazyAny) GetInterface() interface{} { + iter := any.cfg.BorrowIterator(any.buf) + defer any.cfg.ReturnIterator(iter) + return iter.Read() +} + +type objectAny struct { + baseAny + err error + val reflect.Value +} + +func wrapStruct(val interface{}) *objectAny { + return &objectAny{baseAny{}, nil, reflect.ValueOf(val)} +} + +func (any *objectAny) ValueType() ValueType { + return ObjectValue +} + +func (any *objectAny) MustBeValid() Any { + return any +} + +func (any *objectAny) Parse() *Iterator { + return nil +} + +func (any *objectAny) LastError() error { + return any.err +} + +func (any *objectAny) ToBool() bool { + return any.val.NumField() != 0 +} + +func (any *objectAny) ToInt() int { + return 0 +} + +func (any *objectAny) ToInt32() int32 { + return 0 +} + +func (any *objectAny) ToInt64() int64 { + return 0 +} + +func (any *objectAny) ToUint() uint { + return 0 +} + +func (any *objectAny) ToUint32() uint32 { + return 0 +} + +func (any *objectAny) ToUint64() uint64 { + return 0 +} + +func (any *objectAny) ToFloat32() float32 { + return 0 +} + +func (any *objectAny) ToFloat64() float64 { + return 0 +} + +func (any *objectAny) ToString() string { + str, err := MarshalToString(any.val.Interface()) + any.err = err + return str +} + +func (any *objectAny) Get(path ...interface{}) Any { + if len(path) == 0 { + return any + } + switch firstPath := path[0].(type) { + case string: + field := any.val.FieldByName(firstPath) + if !field.IsValid() { + return newInvalidAny(path) + } + return Wrap(field.Interface()) + case int32: + if '*' == firstPath { + mappedAll := map[string]Any{} + for i := 0; i < any.val.NumField(); i++ { + field := any.val.Field(i) + if field.CanInterface() { + mapped := Wrap(field.Interface()).Get(path[1:]...) + if mapped.ValueType() != InvalidValue { + mappedAll[any.val.Type().Field(i).Name] = mapped + } + } + } + return wrapMap(mappedAll) + } + return newInvalidAny(path) + default: + return newInvalidAny(path) + } +} + +func (any *objectAny) Keys() []string { + keys := make([]string, 0, any.val.NumField()) + for i := 0; i < any.val.NumField(); i++ { + keys = append(keys, any.val.Type().Field(i).Name) + } + return keys +} + +func (any *objectAny) Size() int { + return any.val.NumField() +} + +func (any *objectAny) WriteTo(stream *Stream) { + stream.WriteVal(any.val) +} + +func (any *objectAny) GetInterface() interface{} { + return any.val.Interface() +} + +type mapAny struct { + baseAny + err error + val reflect.Value +} + +func wrapMap(val interface{}) *mapAny { + return &mapAny{baseAny{}, nil, reflect.ValueOf(val)} +} + +func (any *mapAny) ValueType() ValueType { + return ObjectValue +} + +func (any *mapAny) MustBeValid() Any { + return any +} + +func (any *mapAny) Parse() *Iterator { + return nil +} + +func (any *mapAny) LastError() error { + return any.err +} + +func (any *mapAny) ToBool() bool { + return true +} + +func (any *mapAny) ToInt() int { + return 0 +} + +func (any *mapAny) ToInt32() int32 { + return 0 +} + +func (any *mapAny) ToInt64() int64 { + return 0 +} + +func (any *mapAny) ToUint() uint { + return 0 +} + +func (any *mapAny) ToUint32() uint32 { + return 0 +} + +func (any *mapAny) ToUint64() uint64 { + return 0 +} + +func (any *mapAny) ToFloat32() float32 { + return 0 +} + +func (any *mapAny) ToFloat64() float64 { + return 0 +} + +func (any *mapAny) ToString() string { + str, err := MarshalToString(any.val.Interface()) + any.err = err + return str +} + +func (any *mapAny) Get(path ...interface{}) Any { + if len(path) == 0 { + return any + } + switch firstPath := path[0].(type) { + case int32: + if '*' == firstPath { + mappedAll := map[string]Any{} + for _, key := range any.val.MapKeys() { + keyAsStr := key.String() + element := Wrap(any.val.MapIndex(key).Interface()) + mapped := element.Get(path[1:]...) + if mapped.ValueType() != InvalidValue { + mappedAll[keyAsStr] = mapped + } + } + return wrapMap(mappedAll) + } + return newInvalidAny(path) + default: + value := any.val.MapIndex(reflect.ValueOf(firstPath)) + if !value.IsValid() { + return newInvalidAny(path) + } + return Wrap(value.Interface()) + } +} + +func (any *mapAny) Keys() []string { + keys := make([]string, 0, any.val.Len()) + for _, key := range any.val.MapKeys() { + keys = append(keys, key.String()) + } + return keys +} + +func (any *mapAny) Size() int { + return any.val.Len() +} + +func (any *mapAny) WriteTo(stream *Stream) { + stream.WriteVal(any.val) +} + +func (any *mapAny) GetInterface() interface{} { + return any.val.Interface() +} diff --git a/vendor/github.com/json-iterator/go/any_str.go b/vendor/github.com/json-iterator/go/any_str.go new file mode 100644 index 000000000..a4b93c78c --- /dev/null +++ b/vendor/github.com/json-iterator/go/any_str.go @@ -0,0 +1,166 @@ +package jsoniter + +import ( + "fmt" + "strconv" +) + +type stringAny struct { + baseAny + val string +} + +func (any *stringAny) Get(path ...interface{}) Any { + if len(path) == 0 { + return any + } + return &invalidAny{baseAny{}, fmt.Errorf("GetIndex %v from simple value", path)} +} + +func (any *stringAny) Parse() *Iterator { + return nil +} + +func (any *stringAny) ValueType() ValueType { + return StringValue +} + +func (any *stringAny) MustBeValid() Any { + return any +} + +func (any *stringAny) LastError() error { + return nil +} + +func (any *stringAny) ToBool() bool { + str := any.ToString() + if str == "0" { + return false + } + for _, c := range str { + switch c { + case ' ', '\n', '\r', '\t': + default: + return true + } + } + return false +} + +func (any *stringAny) ToInt() int { + return int(any.ToInt64()) + +} + +func (any *stringAny) ToInt32() int32 { + return int32(any.ToInt64()) +} + +func (any *stringAny) ToInt64() int64 { + if any.val == "" { + return 0 + } + + flag := 1 + startPos := 0 + endPos := 0 + if any.val[0] == '+' || any.val[0] == '-' { + startPos = 1 + } + + if any.val[0] == '-' { + flag = -1 + } + + for i := startPos; i < len(any.val); i++ { + if any.val[i] >= '0' && any.val[i] <= '9' { + endPos = i + 1 + } else { + break + } + } + parsed, _ := strconv.ParseInt(any.val[startPos:endPos], 10, 64) + return int64(flag) * parsed +} + +func (any *stringAny) ToUint() uint { + return uint(any.ToUint64()) +} + +func (any *stringAny) ToUint32() uint32 { + return uint32(any.ToUint64()) +} + +func (any *stringAny) ToUint64() uint64 { + if any.val == "" { + return 0 + } + + startPos := 0 + endPos := 0 + + if any.val[0] == '-' { + return 0 + } + if any.val[0] == '+' { + startPos = 1 + } + + for i := startPos; i < len(any.val); i++ { + if any.val[i] >= '0' && any.val[i] <= '9' { + endPos = i + 1 + } else { + break + } + } + parsed, _ := strconv.ParseUint(any.val[startPos:endPos], 10, 64) + return parsed +} + +func (any *stringAny) ToFloat32() float32 { + return float32(any.ToFloat64()) +} + +func (any *stringAny) ToFloat64() float64 { + if len(any.val) == 0 { + return 0 + } + + // first char invalid + if any.val[0] != '+' && any.val[0] != '-' && (any.val[0] > '9' || any.val[0] < '0') { + return 0 + } + + // extract valid num expression from string + // eg 123true => 123, -12.12xxa => -12.12 + endPos := 1 + for i := 1; i < len(any.val); i++ { + if any.val[i] == '.' || any.val[i] == 'e' || any.val[i] == 'E' || any.val[i] == '+' || any.val[i] == '-' { + endPos = i + 1 + continue + } + + // end position is the first char which is not digit + if any.val[i] >= '0' && any.val[i] <= '9' { + endPos = i + 1 + } else { + endPos = i + break + } + } + parsed, _ := strconv.ParseFloat(any.val[:endPos], 64) + return parsed +} + +func (any *stringAny) ToString() string { + return any.val +} + +func (any *stringAny) WriteTo(stream *Stream) { + stream.WriteString(any.val) +} + +func (any *stringAny) GetInterface() interface{} { + return any.val +} diff --git a/vendor/github.com/json-iterator/go/any_uint32.go b/vendor/github.com/json-iterator/go/any_uint32.go new file mode 100644 index 000000000..656bbd33d --- /dev/null +++ b/vendor/github.com/json-iterator/go/any_uint32.go @@ -0,0 +1,74 @@ +package jsoniter + +import ( + "strconv" +) + +type uint32Any struct { + baseAny + val uint32 +} + +func (any *uint32Any) LastError() error { + return nil +} + +func (any *uint32Any) ValueType() ValueType { + return NumberValue +} + +func (any *uint32Any) MustBeValid() Any { + return any +} + +func (any *uint32Any) ToBool() bool { + return any.val != 0 +} + +func (any *uint32Any) ToInt() int { + return int(any.val) +} + +func (any *uint32Any) ToInt32() int32 { + return int32(any.val) +} + +func (any *uint32Any) ToInt64() int64 { + return int64(any.val) +} + +func (any *uint32Any) ToUint() uint { + return uint(any.val) +} + +func (any *uint32Any) ToUint32() uint32 { + return any.val +} + +func (any *uint32Any) ToUint64() uint64 { + return uint64(any.val) +} + +func (any *uint32Any) ToFloat32() float32 { + return float32(any.val) +} + +func (any *uint32Any) ToFloat64() float64 { + return float64(any.val) +} + +func (any *uint32Any) ToString() string { + return strconv.FormatInt(int64(any.val), 10) +} + +func (any *uint32Any) WriteTo(stream *Stream) { + stream.WriteUint32(any.val) +} + +func (any *uint32Any) Parse() *Iterator { + return nil +} + +func (any *uint32Any) GetInterface() interface{} { + return any.val +} diff --git a/vendor/github.com/json-iterator/go/any_uint64.go b/vendor/github.com/json-iterator/go/any_uint64.go new file mode 100644 index 000000000..7df2fce33 --- /dev/null +++ b/vendor/github.com/json-iterator/go/any_uint64.go @@ -0,0 +1,74 @@ +package jsoniter + +import ( + "strconv" +) + +type uint64Any struct { + baseAny + val uint64 +} + +func (any *uint64Any) LastError() error { + return nil +} + +func (any *uint64Any) ValueType() ValueType { + return NumberValue +} + +func (any *uint64Any) MustBeValid() Any { + return any +} + +func (any *uint64Any) ToBool() bool { + return any.val != 0 +} + +func (any *uint64Any) ToInt() int { + return int(any.val) +} + +func (any *uint64Any) ToInt32() int32 { + return int32(any.val) +} + +func (any *uint64Any) ToInt64() int64 { + return int64(any.val) +} + +func (any *uint64Any) ToUint() uint { + return uint(any.val) +} + +func (any *uint64Any) ToUint32() uint32 { + return uint32(any.val) +} + +func (any *uint64Any) ToUint64() uint64 { + return any.val +} + +func (any *uint64Any) ToFloat32() float32 { + return float32(any.val) +} + +func (any *uint64Any) ToFloat64() float64 { + return float64(any.val) +} + +func (any *uint64Any) ToString() string { + return strconv.FormatUint(any.val, 10) +} + +func (any *uint64Any) WriteTo(stream *Stream) { + stream.WriteUint64(any.val) +} + +func (any *uint64Any) Parse() *Iterator { + return nil +} + +func (any *uint64Any) GetInterface() interface{} { + return any.val +} diff --git a/vendor/github.com/json-iterator/go/config.go b/vendor/github.com/json-iterator/go/config.go new file mode 100644 index 000000000..8c58fcba5 --- /dev/null +++ b/vendor/github.com/json-iterator/go/config.go @@ -0,0 +1,375 @@ +package jsoniter + +import ( + "encoding/json" + "io" + "reflect" + "sync" + "unsafe" + + "github.com/modern-go/concurrent" + "github.com/modern-go/reflect2" +) + +// Config customize how the API should behave. +// The API is created from Config by Froze. +type Config struct { + IndentionStep int + MarshalFloatWith6Digits bool + EscapeHTML bool + SortMapKeys bool + UseNumber bool + DisallowUnknownFields bool + TagKey string + OnlyTaggedField bool + ValidateJsonRawMessage bool + ObjectFieldMustBeSimpleString bool + CaseSensitive bool +} + +// API the public interface of this package. +// Primary Marshal and Unmarshal. +type API interface { + IteratorPool + StreamPool + MarshalToString(v interface{}) (string, error) + Marshal(v interface{}) ([]byte, error) + MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) + UnmarshalFromString(str string, v interface{}) error + Unmarshal(data []byte, v interface{}) error + Get(data []byte, path ...interface{}) Any + NewEncoder(writer io.Writer) *Encoder + NewDecoder(reader io.Reader) *Decoder + Valid(data []byte) bool + RegisterExtension(extension Extension) + DecoderOf(typ reflect2.Type) ValDecoder + EncoderOf(typ reflect2.Type) ValEncoder +} + +// ConfigDefault the default API +var ConfigDefault = Config{ + EscapeHTML: true, +}.Froze() + +// ConfigCompatibleWithStandardLibrary tries to be 100% compatible with standard library behavior +var ConfigCompatibleWithStandardLibrary = Config{ + EscapeHTML: true, + SortMapKeys: true, + ValidateJsonRawMessage: true, +}.Froze() + +// ConfigFastest marshals float with only 6 digits precision +var ConfigFastest = Config{ + EscapeHTML: false, + MarshalFloatWith6Digits: true, // will lose precession + ObjectFieldMustBeSimpleString: true, // do not unescape object field +}.Froze() + +type frozenConfig struct { + configBeforeFrozen Config + sortMapKeys bool + indentionStep int + objectFieldMustBeSimpleString bool + onlyTaggedField bool + disallowUnknownFields bool + decoderCache *concurrent.Map + encoderCache *concurrent.Map + encoderExtension Extension + decoderExtension Extension + extraExtensions []Extension + streamPool *sync.Pool + iteratorPool *sync.Pool + caseSensitive bool +} + +func (cfg *frozenConfig) initCache() { + cfg.decoderCache = concurrent.NewMap() + cfg.encoderCache = concurrent.NewMap() +} + +func (cfg *frozenConfig) addDecoderToCache(cacheKey uintptr, decoder ValDecoder) { + cfg.decoderCache.Store(cacheKey, decoder) +} + +func (cfg *frozenConfig) addEncoderToCache(cacheKey uintptr, encoder ValEncoder) { + cfg.encoderCache.Store(cacheKey, encoder) +} + +func (cfg *frozenConfig) getDecoderFromCache(cacheKey uintptr) ValDecoder { + decoder, found := cfg.decoderCache.Load(cacheKey) + if found { + return decoder.(ValDecoder) + } + return nil +} + +func (cfg *frozenConfig) getEncoderFromCache(cacheKey uintptr) ValEncoder { + encoder, found := cfg.encoderCache.Load(cacheKey) + if found { + return encoder.(ValEncoder) + } + return nil +} + +var cfgCache = concurrent.NewMap() + +func getFrozenConfigFromCache(cfg Config) *frozenConfig { + obj, found := cfgCache.Load(cfg) + if found { + return obj.(*frozenConfig) + } + return nil +} + +func addFrozenConfigToCache(cfg Config, frozenConfig *frozenConfig) { + cfgCache.Store(cfg, frozenConfig) +} + +// Froze forge API from config +func (cfg Config) Froze() API { + api := &frozenConfig{ + sortMapKeys: cfg.SortMapKeys, + indentionStep: cfg.IndentionStep, + objectFieldMustBeSimpleString: cfg.ObjectFieldMustBeSimpleString, + onlyTaggedField: cfg.OnlyTaggedField, + disallowUnknownFields: cfg.DisallowUnknownFields, + caseSensitive: cfg.CaseSensitive, + } + api.streamPool = &sync.Pool{ + New: func() interface{} { + return NewStream(api, nil, 512) + }, + } + api.iteratorPool = &sync.Pool{ + New: func() interface{} { + return NewIterator(api) + }, + } + api.initCache() + encoderExtension := EncoderExtension{} + decoderExtension := DecoderExtension{} + if cfg.MarshalFloatWith6Digits { + api.marshalFloatWith6Digits(encoderExtension) + } + if cfg.EscapeHTML { + api.escapeHTML(encoderExtension) + } + if cfg.UseNumber { + api.useNumber(decoderExtension) + } + if cfg.ValidateJsonRawMessage { + api.validateJsonRawMessage(encoderExtension) + } + api.encoderExtension = encoderExtension + api.decoderExtension = decoderExtension + api.configBeforeFrozen = cfg + return api +} + +func (cfg Config) frozeWithCacheReuse(extraExtensions []Extension) *frozenConfig { + api := getFrozenConfigFromCache(cfg) + if api != nil { + return api + } + api = cfg.Froze().(*frozenConfig) + for _, extension := range extraExtensions { + api.RegisterExtension(extension) + } + addFrozenConfigToCache(cfg, api) + return api +} + +func (cfg *frozenConfig) validateJsonRawMessage(extension EncoderExtension) { + encoder := &funcEncoder{func(ptr unsafe.Pointer, stream *Stream) { + rawMessage := *(*json.RawMessage)(ptr) + iter := cfg.BorrowIterator([]byte(rawMessage)) + iter.Read() + if iter.Error != nil { + stream.WriteRaw("null") + } else { + cfg.ReturnIterator(iter) + stream.WriteRaw(string(rawMessage)) + } + }, func(ptr unsafe.Pointer) bool { + return len(*((*json.RawMessage)(ptr))) == 0 + }} + extension[reflect2.TypeOfPtr((*json.RawMessage)(nil)).Elem()] = encoder + extension[reflect2.TypeOfPtr((*RawMessage)(nil)).Elem()] = encoder +} + +func (cfg *frozenConfig) useNumber(extension DecoderExtension) { + extension[reflect2.TypeOfPtr((*interface{})(nil)).Elem()] = &funcDecoder{func(ptr unsafe.Pointer, iter *Iterator) { + exitingValue := *((*interface{})(ptr)) + if exitingValue != nil && reflect.TypeOf(exitingValue).Kind() == reflect.Ptr { + iter.ReadVal(exitingValue) + return + } + if iter.WhatIsNext() == NumberValue { + *((*interface{})(ptr)) = json.Number(iter.readNumberAsString()) + } else { + *((*interface{})(ptr)) = iter.Read() + } + }} +} +func (cfg *frozenConfig) getTagKey() string { + tagKey := cfg.configBeforeFrozen.TagKey + if tagKey == "" { + return "json" + } + return tagKey +} + +func (cfg *frozenConfig) RegisterExtension(extension Extension) { + cfg.extraExtensions = append(cfg.extraExtensions, extension) + copied := cfg.configBeforeFrozen + cfg.configBeforeFrozen = copied +} + +type lossyFloat32Encoder struct { +} + +func (encoder *lossyFloat32Encoder) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteFloat32Lossy(*((*float32)(ptr))) +} + +func (encoder *lossyFloat32Encoder) IsEmpty(ptr unsafe.Pointer) bool { + return *((*float32)(ptr)) == 0 +} + +type lossyFloat64Encoder struct { +} + +func (encoder *lossyFloat64Encoder) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteFloat64Lossy(*((*float64)(ptr))) +} + +func (encoder *lossyFloat64Encoder) IsEmpty(ptr unsafe.Pointer) bool { + return *((*float64)(ptr)) == 0 +} + +// EnableLossyFloatMarshalling keeps 10**(-6) precision +// for float variables for better performance. +func (cfg *frozenConfig) marshalFloatWith6Digits(extension EncoderExtension) { + // for better performance + extension[reflect2.TypeOfPtr((*float32)(nil)).Elem()] = &lossyFloat32Encoder{} + extension[reflect2.TypeOfPtr((*float64)(nil)).Elem()] = &lossyFloat64Encoder{} +} + +type htmlEscapedStringEncoder struct { +} + +func (encoder *htmlEscapedStringEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + str := *((*string)(ptr)) + stream.WriteStringWithHTMLEscaped(str) +} + +func (encoder *htmlEscapedStringEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return *((*string)(ptr)) == "" +} + +func (cfg *frozenConfig) escapeHTML(encoderExtension EncoderExtension) { + encoderExtension[reflect2.TypeOfPtr((*string)(nil)).Elem()] = &htmlEscapedStringEncoder{} +} + +func (cfg *frozenConfig) cleanDecoders() { + typeDecoders = map[string]ValDecoder{} + fieldDecoders = map[string]ValDecoder{} + *cfg = *(cfg.configBeforeFrozen.Froze().(*frozenConfig)) +} + +func (cfg *frozenConfig) cleanEncoders() { + typeEncoders = map[string]ValEncoder{} + fieldEncoders = map[string]ValEncoder{} + *cfg = *(cfg.configBeforeFrozen.Froze().(*frozenConfig)) +} + +func (cfg *frozenConfig) MarshalToString(v interface{}) (string, error) { + stream := cfg.BorrowStream(nil) + defer cfg.ReturnStream(stream) + stream.WriteVal(v) + if stream.Error != nil { + return "", stream.Error + } + return string(stream.Buffer()), nil +} + +func (cfg *frozenConfig) Marshal(v interface{}) ([]byte, error) { + stream := cfg.BorrowStream(nil) + defer cfg.ReturnStream(stream) + stream.WriteVal(v) + if stream.Error != nil { + return nil, stream.Error + } + result := stream.Buffer() + copied := make([]byte, len(result)) + copy(copied, result) + return copied, nil +} + +func (cfg *frozenConfig) MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) { + if prefix != "" { + panic("prefix is not supported") + } + for _, r := range indent { + if r != ' ' { + panic("indent can only be space") + } + } + newCfg := cfg.configBeforeFrozen + newCfg.IndentionStep = len(indent) + return newCfg.frozeWithCacheReuse(cfg.extraExtensions).Marshal(v) +} + +func (cfg *frozenConfig) UnmarshalFromString(str string, v interface{}) error { + data := []byte(str) + iter := cfg.BorrowIterator(data) + defer cfg.ReturnIterator(iter) + iter.ReadVal(v) + c := iter.nextToken() + if c == 0 { + if iter.Error == io.EOF { + return nil + } + return iter.Error + } + iter.ReportError("Unmarshal", "there are bytes left after unmarshal") + return iter.Error +} + +func (cfg *frozenConfig) Get(data []byte, path ...interface{}) Any { + iter := cfg.BorrowIterator(data) + defer cfg.ReturnIterator(iter) + return locatePath(iter, path) +} + +func (cfg *frozenConfig) Unmarshal(data []byte, v interface{}) error { + iter := cfg.BorrowIterator(data) + defer cfg.ReturnIterator(iter) + iter.ReadVal(v) + c := iter.nextToken() + if c == 0 { + if iter.Error == io.EOF { + return nil + } + return iter.Error + } + iter.ReportError("Unmarshal", "there are bytes left after unmarshal") + return iter.Error +} + +func (cfg *frozenConfig) NewEncoder(writer io.Writer) *Encoder { + stream := NewStream(cfg, writer, 512) + return &Encoder{stream} +} + +func (cfg *frozenConfig) NewDecoder(reader io.Reader) *Decoder { + iter := Parse(cfg, reader, 512) + return &Decoder{iter} +} + +func (cfg *frozenConfig) Valid(data []byte) bool { + iter := cfg.BorrowIterator(data) + defer cfg.ReturnIterator(iter) + iter.Skip() + return iter.Error == nil +} diff --git a/vendor/github.com/json-iterator/go/iter.go b/vendor/github.com/json-iterator/go/iter.go new file mode 100644 index 000000000..95ae54fbf --- /dev/null +++ b/vendor/github.com/json-iterator/go/iter.go @@ -0,0 +1,322 @@ +package jsoniter + +import ( + "encoding/json" + "fmt" + "io" +) + +// ValueType the type for JSON element +type ValueType int + +const ( + // InvalidValue invalid JSON element + InvalidValue ValueType = iota + // StringValue JSON element "string" + StringValue + // NumberValue JSON element 100 or 0.10 + NumberValue + // NilValue JSON element null + NilValue + // BoolValue JSON element true or false + BoolValue + // ArrayValue JSON element [] + ArrayValue + // ObjectValue JSON element {} + ObjectValue +) + +var hexDigits []byte +var valueTypes []ValueType + +func init() { + hexDigits = make([]byte, 256) + for i := 0; i < len(hexDigits); i++ { + hexDigits[i] = 255 + } + for i := '0'; i <= '9'; i++ { + hexDigits[i] = byte(i - '0') + } + for i := 'a'; i <= 'f'; i++ { + hexDigits[i] = byte((i - 'a') + 10) + } + for i := 'A'; i <= 'F'; i++ { + hexDigits[i] = byte((i - 'A') + 10) + } + valueTypes = make([]ValueType, 256) + for i := 0; i < len(valueTypes); i++ { + valueTypes[i] = InvalidValue + } + valueTypes['"'] = StringValue + valueTypes['-'] = NumberValue + valueTypes['0'] = NumberValue + valueTypes['1'] = NumberValue + valueTypes['2'] = NumberValue + valueTypes['3'] = NumberValue + valueTypes['4'] = NumberValue + valueTypes['5'] = NumberValue + valueTypes['6'] = NumberValue + valueTypes['7'] = NumberValue + valueTypes['8'] = NumberValue + valueTypes['9'] = NumberValue + valueTypes['t'] = BoolValue + valueTypes['f'] = BoolValue + valueTypes['n'] = NilValue + valueTypes['['] = ArrayValue + valueTypes['{'] = ObjectValue +} + +// Iterator is a io.Reader like object, with JSON specific read functions. +// Error is not returned as return value, but stored as Error member on this iterator instance. +type Iterator struct { + cfg *frozenConfig + reader io.Reader + buf []byte + head int + tail int + captureStartedAt int + captured []byte + Error error + Attachment interface{} // open for customized decoder +} + +// NewIterator creates an empty Iterator instance +func NewIterator(cfg API) *Iterator { + return &Iterator{ + cfg: cfg.(*frozenConfig), + reader: nil, + buf: nil, + head: 0, + tail: 0, + } +} + +// Parse creates an Iterator instance from io.Reader +func Parse(cfg API, reader io.Reader, bufSize int) *Iterator { + return &Iterator{ + cfg: cfg.(*frozenConfig), + reader: reader, + buf: make([]byte, bufSize), + head: 0, + tail: 0, + } +} + +// ParseBytes creates an Iterator instance from byte array +func ParseBytes(cfg API, input []byte) *Iterator { + return &Iterator{ + cfg: cfg.(*frozenConfig), + reader: nil, + buf: input, + head: 0, + tail: len(input), + } +} + +// ParseString creates an Iterator instance from string +func ParseString(cfg API, input string) *Iterator { + return ParseBytes(cfg, []byte(input)) +} + +// Pool returns a pool can provide more iterator with same configuration +func (iter *Iterator) Pool() IteratorPool { + return iter.cfg +} + +// Reset reuse iterator instance by specifying another reader +func (iter *Iterator) Reset(reader io.Reader) *Iterator { + iter.reader = reader + iter.head = 0 + iter.tail = 0 + return iter +} + +// ResetBytes reuse iterator instance by specifying another byte array as input +func (iter *Iterator) ResetBytes(input []byte) *Iterator { + iter.reader = nil + iter.buf = input + iter.head = 0 + iter.tail = len(input) + return iter +} + +// WhatIsNext gets ValueType of relatively next json element +func (iter *Iterator) WhatIsNext() ValueType { + valueType := valueTypes[iter.nextToken()] + iter.unreadByte() + return valueType +} + +func (iter *Iterator) skipWhitespacesWithoutLoadMore() bool { + for i := iter.head; i < iter.tail; i++ { + c := iter.buf[i] + switch c { + case ' ', '\n', '\t', '\r': + continue + } + iter.head = i + return false + } + return true +} + +func (iter *Iterator) isObjectEnd() bool { + c := iter.nextToken() + if c == ',' { + return false + } + if c == '}' { + return true + } + iter.ReportError("isObjectEnd", "object ended prematurely, unexpected char "+string([]byte{c})) + return true +} + +func (iter *Iterator) nextToken() byte { + // a variation of skip whitespaces, returning the next non-whitespace token + for { + for i := iter.head; i < iter.tail; i++ { + c := iter.buf[i] + switch c { + case ' ', '\n', '\t', '\r': + continue + } + iter.head = i + 1 + return c + } + if !iter.loadMore() { + return 0 + } + } +} + +// ReportError record a error in iterator instance with current position. +func (iter *Iterator) ReportError(operation string, msg string) { + if iter.Error != nil { + if iter.Error != io.EOF { + return + } + } + peekStart := iter.head - 10 + if peekStart < 0 { + peekStart = 0 + } + peekEnd := iter.head + 10 + if peekEnd > iter.tail { + peekEnd = iter.tail + } + parsing := string(iter.buf[peekStart:peekEnd]) + contextStart := iter.head - 50 + if contextStart < 0 { + contextStart = 0 + } + contextEnd := iter.head + 50 + if contextEnd > iter.tail { + contextEnd = iter.tail + } + context := string(iter.buf[contextStart:contextEnd]) + iter.Error = fmt.Errorf("%s: %s, error found in #%v byte of ...|%s|..., bigger context ...|%s|...", + operation, msg, iter.head-peekStart, parsing, context) +} + +// CurrentBuffer gets current buffer as string for debugging purpose +func (iter *Iterator) CurrentBuffer() string { + peekStart := iter.head - 10 + if peekStart < 0 { + peekStart = 0 + } + return fmt.Sprintf("parsing #%v byte, around ...|%s|..., whole buffer ...|%s|...", iter.head, + string(iter.buf[peekStart:iter.head]), string(iter.buf[0:iter.tail])) +} + +func (iter *Iterator) readByte() (ret byte) { + if iter.head == iter.tail { + if iter.loadMore() { + ret = iter.buf[iter.head] + iter.head++ + return ret + } + return 0 + } + ret = iter.buf[iter.head] + iter.head++ + return ret +} + +func (iter *Iterator) loadMore() bool { + if iter.reader == nil { + if iter.Error == nil { + iter.head = iter.tail + iter.Error = io.EOF + } + return false + } + if iter.captured != nil { + iter.captured = append(iter.captured, + iter.buf[iter.captureStartedAt:iter.tail]...) + iter.captureStartedAt = 0 + } + for { + n, err := iter.reader.Read(iter.buf) + if n == 0 { + if err != nil { + if iter.Error == nil { + iter.Error = err + } + return false + } + } else { + iter.head = 0 + iter.tail = n + return true + } + } +} + +func (iter *Iterator) unreadByte() { + if iter.Error != nil { + return + } + iter.head-- + return +} + +// Read read the next JSON element as generic interface{}. +func (iter *Iterator) Read() interface{} { + valueType := iter.WhatIsNext() + switch valueType { + case StringValue: + return iter.ReadString() + case NumberValue: + if iter.cfg.configBeforeFrozen.UseNumber { + return json.Number(iter.readNumberAsString()) + } + return iter.ReadFloat64() + case NilValue: + iter.skipFourBytes('n', 'u', 'l', 'l') + return nil + case BoolValue: + return iter.ReadBool() + case ArrayValue: + arr := []interface{}{} + iter.ReadArrayCB(func(iter *Iterator) bool { + var elem interface{} + iter.ReadVal(&elem) + arr = append(arr, elem) + return true + }) + return arr + case ObjectValue: + obj := map[string]interface{}{} + iter.ReadMapCB(func(Iter *Iterator, field string) bool { + var elem interface{} + iter.ReadVal(&elem) + obj[field] = elem + return true + }) + return obj + default: + iter.ReportError("Read", fmt.Sprintf("unexpected value type: %v", valueType)) + return nil + } +} diff --git a/vendor/github.com/json-iterator/go/iter_array.go b/vendor/github.com/json-iterator/go/iter_array.go new file mode 100644 index 000000000..6188cb457 --- /dev/null +++ b/vendor/github.com/json-iterator/go/iter_array.go @@ -0,0 +1,58 @@ +package jsoniter + +// ReadArray read array element, tells if the array has more element to read. +func (iter *Iterator) ReadArray() (ret bool) { + c := iter.nextToken() + switch c { + case 'n': + iter.skipThreeBytes('u', 'l', 'l') + return false // null + case '[': + c = iter.nextToken() + if c != ']' { + iter.unreadByte() + return true + } + return false + case ']': + return false + case ',': + return true + default: + iter.ReportError("ReadArray", "expect [ or , or ] or n, but found "+string([]byte{c})) + return + } +} + +// ReadArrayCB read array with callback +func (iter *Iterator) ReadArrayCB(callback func(*Iterator) bool) (ret bool) { + c := iter.nextToken() + if c == '[' { + c = iter.nextToken() + if c != ']' { + iter.unreadByte() + if !callback(iter) { + return false + } + c = iter.nextToken() + for c == ',' { + if !callback(iter) { + return false + } + c = iter.nextToken() + } + if c != ']' { + iter.ReportError("ReadArrayCB", "expect ] in the end, but found "+string([]byte{c})) + return false + } + return true + } + return true + } + if c == 'n' { + iter.skipThreeBytes('u', 'l', 'l') + return true // null + } + iter.ReportError("ReadArrayCB", "expect [ or n, but found "+string([]byte{c})) + return false +} diff --git a/vendor/github.com/json-iterator/go/iter_float.go b/vendor/github.com/json-iterator/go/iter_float.go new file mode 100644 index 000000000..4f883c095 --- /dev/null +++ b/vendor/github.com/json-iterator/go/iter_float.go @@ -0,0 +1,347 @@ +package jsoniter + +import ( + "encoding/json" + "io" + "math/big" + "strconv" + "strings" + "unsafe" +) + +var floatDigits []int8 + +const invalidCharForNumber = int8(-1) +const endOfNumber = int8(-2) +const dotInNumber = int8(-3) + +func init() { + floatDigits = make([]int8, 256) + for i := 0; i < len(floatDigits); i++ { + floatDigits[i] = invalidCharForNumber + } + for i := int8('0'); i <= int8('9'); i++ { + floatDigits[i] = i - int8('0') + } + floatDigits[','] = endOfNumber + floatDigits[']'] = endOfNumber + floatDigits['}'] = endOfNumber + floatDigits[' '] = endOfNumber + floatDigits['\t'] = endOfNumber + floatDigits['\n'] = endOfNumber + floatDigits['.'] = dotInNumber +} + +// ReadBigFloat read big.Float +func (iter *Iterator) ReadBigFloat() (ret *big.Float) { + str := iter.readNumberAsString() + if iter.Error != nil && iter.Error != io.EOF { + return nil + } + prec := 64 + if len(str) > prec { + prec = len(str) + } + val, _, err := big.ParseFloat(str, 10, uint(prec), big.ToZero) + if err != nil { + iter.Error = err + return nil + } + return val +} + +// ReadBigInt read big.Int +func (iter *Iterator) ReadBigInt() (ret *big.Int) { + str := iter.readNumberAsString() + if iter.Error != nil && iter.Error != io.EOF { + return nil + } + ret = big.NewInt(0) + var success bool + ret, success = ret.SetString(str, 10) + if !success { + iter.ReportError("ReadBigInt", "invalid big int") + return nil + } + return ret +} + +//ReadFloat32 read float32 +func (iter *Iterator) ReadFloat32() (ret float32) { + c := iter.nextToken() + if c == '-' { + return -iter.readPositiveFloat32() + } + iter.unreadByte() + return iter.readPositiveFloat32() +} + +func (iter *Iterator) readPositiveFloat32() (ret float32) { + value := uint64(0) + c := byte(' ') + i := iter.head + // first char + if i == iter.tail { + return iter.readFloat32SlowPath() + } + c = iter.buf[i] + i++ + ind := floatDigits[c] + switch ind { + case invalidCharForNumber: + return iter.readFloat32SlowPath() + case endOfNumber: + iter.ReportError("readFloat32", "empty number") + return + case dotInNumber: + iter.ReportError("readFloat32", "leading dot is invalid") + return + case 0: + if i == iter.tail { + return iter.readFloat32SlowPath() + } + c = iter.buf[i] + switch c { + case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': + iter.ReportError("readFloat32", "leading zero is invalid") + return + } + } + value = uint64(ind) + // chars before dot +non_decimal_loop: + for ; i < iter.tail; i++ { + c = iter.buf[i] + ind := floatDigits[c] + switch ind { + case invalidCharForNumber: + return iter.readFloat32SlowPath() + case endOfNumber: + iter.head = i + return float32(value) + case dotInNumber: + break non_decimal_loop + } + if value > uint64SafeToMultiple10 { + return iter.readFloat32SlowPath() + } + value = (value << 3) + (value << 1) + uint64(ind) // value = value * 10 + ind; + } + // chars after dot + if c == '.' { + i++ + decimalPlaces := 0 + if i == iter.tail { + return iter.readFloat32SlowPath() + } + for ; i < iter.tail; i++ { + c = iter.buf[i] + ind := floatDigits[c] + switch ind { + case endOfNumber: + if decimalPlaces > 0 && decimalPlaces < len(pow10) { + iter.head = i + return float32(float64(value) / float64(pow10[decimalPlaces])) + } + // too many decimal places + return iter.readFloat32SlowPath() + case invalidCharForNumber: + fallthrough + case dotInNumber: + return iter.readFloat32SlowPath() + } + decimalPlaces++ + if value > uint64SafeToMultiple10 { + return iter.readFloat32SlowPath() + } + value = (value << 3) + (value << 1) + uint64(ind) + } + } + return iter.readFloat32SlowPath() +} + +func (iter *Iterator) readNumberAsString() (ret string) { + strBuf := [16]byte{} + str := strBuf[0:0] +load_loop: + for { + for i := iter.head; i < iter.tail; i++ { + c := iter.buf[i] + switch c { + case '+', '-', '.', 'e', 'E', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': + str = append(str, c) + continue + default: + iter.head = i + break load_loop + } + } + if !iter.loadMore() { + break + } + } + if iter.Error != nil && iter.Error != io.EOF { + return + } + if len(str) == 0 { + iter.ReportError("readNumberAsString", "invalid number") + } + return *(*string)(unsafe.Pointer(&str)) +} + +func (iter *Iterator) readFloat32SlowPath() (ret float32) { + str := iter.readNumberAsString() + if iter.Error != nil && iter.Error != io.EOF { + return + } + errMsg := validateFloat(str) + if errMsg != "" { + iter.ReportError("readFloat32SlowPath", errMsg) + return + } + val, err := strconv.ParseFloat(str, 32) + if err != nil { + iter.Error = err + return + } + return float32(val) +} + +// ReadFloat64 read float64 +func (iter *Iterator) ReadFloat64() (ret float64) { + c := iter.nextToken() + if c == '-' { + return -iter.readPositiveFloat64() + } + iter.unreadByte() + return iter.readPositiveFloat64() +} + +func (iter *Iterator) readPositiveFloat64() (ret float64) { + value := uint64(0) + c := byte(' ') + i := iter.head + // first char + if i == iter.tail { + return iter.readFloat64SlowPath() + } + c = iter.buf[i] + i++ + ind := floatDigits[c] + switch ind { + case invalidCharForNumber: + return iter.readFloat64SlowPath() + case endOfNumber: + iter.ReportError("readFloat64", "empty number") + return + case dotInNumber: + iter.ReportError("readFloat64", "leading dot is invalid") + return + case 0: + if i == iter.tail { + return iter.readFloat64SlowPath() + } + c = iter.buf[i] + switch c { + case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': + iter.ReportError("readFloat64", "leading zero is invalid") + return + } + } + value = uint64(ind) + // chars before dot +non_decimal_loop: + for ; i < iter.tail; i++ { + c = iter.buf[i] + ind := floatDigits[c] + switch ind { + case invalidCharForNumber: + return iter.readFloat64SlowPath() + case endOfNumber: + iter.head = i + return float64(value) + case dotInNumber: + break non_decimal_loop + } + if value > uint64SafeToMultiple10 { + return iter.readFloat64SlowPath() + } + value = (value << 3) + (value << 1) + uint64(ind) // value = value * 10 + ind; + } + // chars after dot + if c == '.' { + i++ + decimalPlaces := 0 + if i == iter.tail { + return iter.readFloat64SlowPath() + } + for ; i < iter.tail; i++ { + c = iter.buf[i] + ind := floatDigits[c] + switch ind { + case endOfNumber: + if decimalPlaces > 0 && decimalPlaces < len(pow10) { + iter.head = i + return float64(value) / float64(pow10[decimalPlaces]) + } + // too many decimal places + return iter.readFloat64SlowPath() + case invalidCharForNumber: + fallthrough + case dotInNumber: + return iter.readFloat64SlowPath() + } + decimalPlaces++ + if value > uint64SafeToMultiple10 { + return iter.readFloat64SlowPath() + } + value = (value << 3) + (value << 1) + uint64(ind) + } + } + return iter.readFloat64SlowPath() +} + +func (iter *Iterator) readFloat64SlowPath() (ret float64) { + str := iter.readNumberAsString() + if iter.Error != nil && iter.Error != io.EOF { + return + } + errMsg := validateFloat(str) + if errMsg != "" { + iter.ReportError("readFloat64SlowPath", errMsg) + return + } + val, err := strconv.ParseFloat(str, 64) + if err != nil { + iter.Error = err + return + } + return val +} + +func validateFloat(str string) string { + // strconv.ParseFloat is not validating `1.` or `1.e1` + if len(str) == 0 { + return "empty number" + } + if str[0] == '-' { + return "-- is not valid" + } + dotPos := strings.IndexByte(str, '.') + if dotPos != -1 { + if dotPos == len(str)-1 { + return "dot can not be last character" + } + switch str[dotPos+1] { + case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': + default: + return "missing digit after dot" + } + } + return "" +} + +// ReadNumber read json.Number +func (iter *Iterator) ReadNumber() (ret json.Number) { + return json.Number(iter.readNumberAsString()) +} diff --git a/vendor/github.com/json-iterator/go/iter_int.go b/vendor/github.com/json-iterator/go/iter_int.go new file mode 100644 index 000000000..214232035 --- /dev/null +++ b/vendor/github.com/json-iterator/go/iter_int.go @@ -0,0 +1,345 @@ +package jsoniter + +import ( + "math" + "strconv" +) + +var intDigits []int8 + +const uint32SafeToMultiply10 = uint32(0xffffffff)/10 - 1 +const uint64SafeToMultiple10 = uint64(0xffffffffffffffff)/10 - 1 + +func init() { + intDigits = make([]int8, 256) + for i := 0; i < len(intDigits); i++ { + intDigits[i] = invalidCharForNumber + } + for i := int8('0'); i <= int8('9'); i++ { + intDigits[i] = i - int8('0') + } +} + +// ReadUint read uint +func (iter *Iterator) ReadUint() uint { + if strconv.IntSize == 32 { + return uint(iter.ReadUint32()) + } + return uint(iter.ReadUint64()) +} + +// ReadInt read int +func (iter *Iterator) ReadInt() int { + if strconv.IntSize == 32 { + return int(iter.ReadInt32()) + } + return int(iter.ReadInt64()) +} + +// ReadInt8 read int8 +func (iter *Iterator) ReadInt8() (ret int8) { + c := iter.nextToken() + if c == '-' { + val := iter.readUint32(iter.readByte()) + if val > math.MaxInt8+1 { + iter.ReportError("ReadInt8", "overflow: "+strconv.FormatInt(int64(val), 10)) + return + } + return -int8(val) + } + val := iter.readUint32(c) + if val > math.MaxInt8 { + iter.ReportError("ReadInt8", "overflow: "+strconv.FormatInt(int64(val), 10)) + return + } + return int8(val) +} + +// ReadUint8 read uint8 +func (iter *Iterator) ReadUint8() (ret uint8) { + val := iter.readUint32(iter.nextToken()) + if val > math.MaxUint8 { + iter.ReportError("ReadUint8", "overflow: "+strconv.FormatInt(int64(val), 10)) + return + } + return uint8(val) +} + +// ReadInt16 read int16 +func (iter *Iterator) ReadInt16() (ret int16) { + c := iter.nextToken() + if c == '-' { + val := iter.readUint32(iter.readByte()) + if val > math.MaxInt16+1 { + iter.ReportError("ReadInt16", "overflow: "+strconv.FormatInt(int64(val), 10)) + return + } + return -int16(val) + } + val := iter.readUint32(c) + if val > math.MaxInt16 { + iter.ReportError("ReadInt16", "overflow: "+strconv.FormatInt(int64(val), 10)) + return + } + return int16(val) +} + +// ReadUint16 read uint16 +func (iter *Iterator) ReadUint16() (ret uint16) { + val := iter.readUint32(iter.nextToken()) + if val > math.MaxUint16 { + iter.ReportError("ReadUint16", "overflow: "+strconv.FormatInt(int64(val), 10)) + return + } + return uint16(val) +} + +// ReadInt32 read int32 +func (iter *Iterator) ReadInt32() (ret int32) { + c := iter.nextToken() + if c == '-' { + val := iter.readUint32(iter.readByte()) + if val > math.MaxInt32+1 { + iter.ReportError("ReadInt32", "overflow: "+strconv.FormatInt(int64(val), 10)) + return + } + return -int32(val) + } + val := iter.readUint32(c) + if val > math.MaxInt32 { + iter.ReportError("ReadInt32", "overflow: "+strconv.FormatInt(int64(val), 10)) + return + } + return int32(val) +} + +// ReadUint32 read uint32 +func (iter *Iterator) ReadUint32() (ret uint32) { + return iter.readUint32(iter.nextToken()) +} + +func (iter *Iterator) readUint32(c byte) (ret uint32) { + ind := intDigits[c] + if ind == 0 { + iter.assertInteger() + return 0 // single zero + } + if ind == invalidCharForNumber { + iter.ReportError("readUint32", "unexpected character: "+string([]byte{byte(ind)})) + return + } + value := uint32(ind) + if iter.tail-iter.head > 10 { + i := iter.head + ind2 := intDigits[iter.buf[i]] + if ind2 == invalidCharForNumber { + iter.head = i + iter.assertInteger() + return value + } + i++ + ind3 := intDigits[iter.buf[i]] + if ind3 == invalidCharForNumber { + iter.head = i + iter.assertInteger() + return value*10 + uint32(ind2) + } + //iter.head = i + 1 + //value = value * 100 + uint32(ind2) * 10 + uint32(ind3) + i++ + ind4 := intDigits[iter.buf[i]] + if ind4 == invalidCharForNumber { + iter.head = i + iter.assertInteger() + return value*100 + uint32(ind2)*10 + uint32(ind3) + } + i++ + ind5 := intDigits[iter.buf[i]] + if ind5 == invalidCharForNumber { + iter.head = i + iter.assertInteger() + return value*1000 + uint32(ind2)*100 + uint32(ind3)*10 + uint32(ind4) + } + i++ + ind6 := intDigits[iter.buf[i]] + if ind6 == invalidCharForNumber { + iter.head = i + iter.assertInteger() + return value*10000 + uint32(ind2)*1000 + uint32(ind3)*100 + uint32(ind4)*10 + uint32(ind5) + } + i++ + ind7 := intDigits[iter.buf[i]] + if ind7 == invalidCharForNumber { + iter.head = i + iter.assertInteger() + return value*100000 + uint32(ind2)*10000 + uint32(ind3)*1000 + uint32(ind4)*100 + uint32(ind5)*10 + uint32(ind6) + } + i++ + ind8 := intDigits[iter.buf[i]] + if ind8 == invalidCharForNumber { + iter.head = i + iter.assertInteger() + return value*1000000 + uint32(ind2)*100000 + uint32(ind3)*10000 + uint32(ind4)*1000 + uint32(ind5)*100 + uint32(ind6)*10 + uint32(ind7) + } + i++ + ind9 := intDigits[iter.buf[i]] + value = value*10000000 + uint32(ind2)*1000000 + uint32(ind3)*100000 + uint32(ind4)*10000 + uint32(ind5)*1000 + uint32(ind6)*100 + uint32(ind7)*10 + uint32(ind8) + iter.head = i + if ind9 == invalidCharForNumber { + iter.assertInteger() + return value + } + } + for { + for i := iter.head; i < iter.tail; i++ { + ind = intDigits[iter.buf[i]] + if ind == invalidCharForNumber { + iter.head = i + iter.assertInteger() + return value + } + if value > uint32SafeToMultiply10 { + value2 := (value << 3) + (value << 1) + uint32(ind) + if value2 < value { + iter.ReportError("readUint32", "overflow") + return + } + value = value2 + continue + } + value = (value << 3) + (value << 1) + uint32(ind) + } + if !iter.loadMore() { + iter.assertInteger() + return value + } + } +} + +// ReadInt64 read int64 +func (iter *Iterator) ReadInt64() (ret int64) { + c := iter.nextToken() + if c == '-' { + val := iter.readUint64(iter.readByte()) + if val > math.MaxInt64+1 { + iter.ReportError("ReadInt64", "overflow: "+strconv.FormatUint(uint64(val), 10)) + return + } + return -int64(val) + } + val := iter.readUint64(c) + if val > math.MaxInt64 { + iter.ReportError("ReadInt64", "overflow: "+strconv.FormatUint(uint64(val), 10)) + return + } + return int64(val) +} + +// ReadUint64 read uint64 +func (iter *Iterator) ReadUint64() uint64 { + return iter.readUint64(iter.nextToken()) +} + +func (iter *Iterator) readUint64(c byte) (ret uint64) { + ind := intDigits[c] + if ind == 0 { + iter.assertInteger() + return 0 // single zero + } + if ind == invalidCharForNumber { + iter.ReportError("readUint64", "unexpected character: "+string([]byte{byte(ind)})) + return + } + value := uint64(ind) + if iter.tail-iter.head > 10 { + i := iter.head + ind2 := intDigits[iter.buf[i]] + if ind2 == invalidCharForNumber { + iter.head = i + iter.assertInteger() + return value + } + i++ + ind3 := intDigits[iter.buf[i]] + if ind3 == invalidCharForNumber { + iter.head = i + iter.assertInteger() + return value*10 + uint64(ind2) + } + //iter.head = i + 1 + //value = value * 100 + uint32(ind2) * 10 + uint32(ind3) + i++ + ind4 := intDigits[iter.buf[i]] + if ind4 == invalidCharForNumber { + iter.head = i + iter.assertInteger() + return value*100 + uint64(ind2)*10 + uint64(ind3) + } + i++ + ind5 := intDigits[iter.buf[i]] + if ind5 == invalidCharForNumber { + iter.head = i + iter.assertInteger() + return value*1000 + uint64(ind2)*100 + uint64(ind3)*10 + uint64(ind4) + } + i++ + ind6 := intDigits[iter.buf[i]] + if ind6 == invalidCharForNumber { + iter.head = i + iter.assertInteger() + return value*10000 + uint64(ind2)*1000 + uint64(ind3)*100 + uint64(ind4)*10 + uint64(ind5) + } + i++ + ind7 := intDigits[iter.buf[i]] + if ind7 == invalidCharForNumber { + iter.head = i + iter.assertInteger() + return value*100000 + uint64(ind2)*10000 + uint64(ind3)*1000 + uint64(ind4)*100 + uint64(ind5)*10 + uint64(ind6) + } + i++ + ind8 := intDigits[iter.buf[i]] + if ind8 == invalidCharForNumber { + iter.head = i + iter.assertInteger() + return value*1000000 + uint64(ind2)*100000 + uint64(ind3)*10000 + uint64(ind4)*1000 + uint64(ind5)*100 + uint64(ind6)*10 + uint64(ind7) + } + i++ + ind9 := intDigits[iter.buf[i]] + value = value*10000000 + uint64(ind2)*1000000 + uint64(ind3)*100000 + uint64(ind4)*10000 + uint64(ind5)*1000 + uint64(ind6)*100 + uint64(ind7)*10 + uint64(ind8) + iter.head = i + if ind9 == invalidCharForNumber { + iter.assertInteger() + return value + } + } + for { + for i := iter.head; i < iter.tail; i++ { + ind = intDigits[iter.buf[i]] + if ind == invalidCharForNumber { + iter.head = i + iter.assertInteger() + return value + } + if value > uint64SafeToMultiple10 { + value2 := (value << 3) + (value << 1) + uint64(ind) + if value2 < value { + iter.ReportError("readUint64", "overflow") + return + } + value = value2 + continue + } + value = (value << 3) + (value << 1) + uint64(ind) + } + if !iter.loadMore() { + iter.assertInteger() + return value + } + } +} + +func (iter *Iterator) assertInteger() { + if iter.head < len(iter.buf) && iter.buf[iter.head] == '.' { + iter.ReportError("assertInteger", "can not decode float as int") + } +} diff --git a/vendor/github.com/json-iterator/go/iter_object.go b/vendor/github.com/json-iterator/go/iter_object.go new file mode 100644 index 000000000..1c5757671 --- /dev/null +++ b/vendor/github.com/json-iterator/go/iter_object.go @@ -0,0 +1,251 @@ +package jsoniter + +import ( + "fmt" + "strings" +) + +// ReadObject read one field from object. +// If object ended, returns empty string. +// Otherwise, returns the field name. +func (iter *Iterator) ReadObject() (ret string) { + c := iter.nextToken() + switch c { + case 'n': + iter.skipThreeBytes('u', 'l', 'l') + return "" // null + case '{': + c = iter.nextToken() + if c == '"' { + iter.unreadByte() + field := iter.ReadString() + c = iter.nextToken() + if c != ':' { + iter.ReportError("ReadObject", "expect : after object field, but found "+string([]byte{c})) + } + return field + } + if c == '}' { + return "" // end of object + } + iter.ReportError("ReadObject", `expect " after {, but found `+string([]byte{c})) + return + case ',': + field := iter.ReadString() + c = iter.nextToken() + if c != ':' { + iter.ReportError("ReadObject", "expect : after object field, but found "+string([]byte{c})) + } + return field + case '}': + return "" // end of object + default: + iter.ReportError("ReadObject", fmt.Sprintf(`expect { or , or } or n, but found %s`, string([]byte{c}))) + return + } +} + +// CaseInsensitive +func (iter *Iterator) readFieldHash() int64 { + hash := int64(0x811c9dc5) + c := iter.nextToken() + if c != '"' { + iter.ReportError("readFieldHash", `expect ", but found `+string([]byte{c})) + return 0 + } + for { + for i := iter.head; i < iter.tail; i++ { + // require ascii string and no escape + b := iter.buf[i] + if b == '\\' { + iter.head = i + for _, b := range iter.readStringSlowPath() { + if 'A' <= b && b <= 'Z' && !iter.cfg.caseSensitive { + b += 'a' - 'A' + } + hash ^= int64(b) + hash *= 0x1000193 + } + c = iter.nextToken() + if c != ':' { + iter.ReportError("readFieldHash", `expect :, but found `+string([]byte{c})) + return 0 + } + return hash + } + if b == '"' { + iter.head = i + 1 + c = iter.nextToken() + if c != ':' { + iter.ReportError("readFieldHash", `expect :, but found `+string([]byte{c})) + return 0 + } + return hash + } + if 'A' <= b && b <= 'Z' && !iter.cfg.caseSensitive { + b += 'a' - 'A' + } + hash ^= int64(b) + hash *= 0x1000193 + } + if !iter.loadMore() { + iter.ReportError("readFieldHash", `incomplete field name`) + return 0 + } + } +} + +func calcHash(str string, caseSensitive bool) int64 { + if !caseSensitive { + str = strings.ToLower(str) + } + hash := int64(0x811c9dc5) + for _, b := range []byte(str) { + hash ^= int64(b) + hash *= 0x1000193 + } + return int64(hash) +} + +// ReadObjectCB read object with callback, the key is ascii only and field name not copied +func (iter *Iterator) ReadObjectCB(callback func(*Iterator, string) bool) bool { + c := iter.nextToken() + var field string + if c == '{' { + c = iter.nextToken() + if c == '"' { + iter.unreadByte() + field = iter.ReadString() + c = iter.nextToken() + if c != ':' { + iter.ReportError("ReadObject", "expect : after object field, but found "+string([]byte{c})) + } + if !callback(iter, field) { + return false + } + c = iter.nextToken() + for c == ',' { + field = iter.ReadString() + c = iter.nextToken() + if c != ':' { + iter.ReportError("ReadObject", "expect : after object field, but found "+string([]byte{c})) + } + if !callback(iter, field) { + return false + } + c = iter.nextToken() + } + if c != '}' { + iter.ReportError("ReadObjectCB", `object not ended with }`) + return false + } + return true + } + if c == '}' { + return true + } + iter.ReportError("ReadObjectCB", `expect " after }, but found `+string([]byte{c})) + return false + } + if c == 'n' { + iter.skipThreeBytes('u', 'l', 'l') + return true // null + } + iter.ReportError("ReadObjectCB", `expect { or n, but found `+string([]byte{c})) + return false +} + +// ReadMapCB read map with callback, the key can be any string +func (iter *Iterator) ReadMapCB(callback func(*Iterator, string) bool) bool { + c := iter.nextToken() + if c == '{' { + c = iter.nextToken() + if c == '"' { + iter.unreadByte() + field := iter.ReadString() + if iter.nextToken() != ':' { + iter.ReportError("ReadMapCB", "expect : after object field, but found "+string([]byte{c})) + return false + } + if !callback(iter, field) { + return false + } + c = iter.nextToken() + for c == ',' { + field = iter.ReadString() + if iter.nextToken() != ':' { + iter.ReportError("ReadMapCB", "expect : after object field, but found "+string([]byte{c})) + return false + } + if !callback(iter, field) { + return false + } + c = iter.nextToken() + } + if c != '}' { + iter.ReportError("ReadMapCB", `object not ended with }`) + return false + } + return true + } + if c == '}' { + return true + } + iter.ReportError("ReadMapCB", `expect " after }, but found `+string([]byte{c})) + return false + } + if c == 'n' { + iter.skipThreeBytes('u', 'l', 'l') + return true // null + } + iter.ReportError("ReadMapCB", `expect { or n, but found `+string([]byte{c})) + return false +} + +func (iter *Iterator) readObjectStart() bool { + c := iter.nextToken() + if c == '{' { + c = iter.nextToken() + if c == '}' { + return false + } + iter.unreadByte() + return true + } else if c == 'n' { + iter.skipThreeBytes('u', 'l', 'l') + return false + } + iter.ReportError("readObjectStart", "expect { or n, but found "+string([]byte{c})) + return false +} + +func (iter *Iterator) readObjectFieldAsBytes() (ret []byte) { + str := iter.ReadStringAsSlice() + if iter.skipWhitespacesWithoutLoadMore() { + if ret == nil { + ret = make([]byte, len(str)) + copy(ret, str) + } + if !iter.loadMore() { + return + } + } + if iter.buf[iter.head] != ':' { + iter.ReportError("readObjectFieldAsBytes", "expect : after object field, but found "+string([]byte{iter.buf[iter.head]})) + return + } + iter.head++ + if iter.skipWhitespacesWithoutLoadMore() { + if ret == nil { + ret = make([]byte, len(str)) + copy(ret, str) + } + if !iter.loadMore() { + return + } + } + if ret == nil { + return str + } + return ret +} diff --git a/vendor/github.com/json-iterator/go/iter_skip.go b/vendor/github.com/json-iterator/go/iter_skip.go new file mode 100644 index 000000000..f58beb913 --- /dev/null +++ b/vendor/github.com/json-iterator/go/iter_skip.go @@ -0,0 +1,129 @@ +package jsoniter + +import "fmt" + +// ReadNil reads a json object as nil and +// returns whether it's a nil or not +func (iter *Iterator) ReadNil() (ret bool) { + c := iter.nextToken() + if c == 'n' { + iter.skipThreeBytes('u', 'l', 'l') // null + return true + } + iter.unreadByte() + return false +} + +// ReadBool reads a json object as BoolValue +func (iter *Iterator) ReadBool() (ret bool) { + c := iter.nextToken() + if c == 't' { + iter.skipThreeBytes('r', 'u', 'e') + return true + } + if c == 'f' { + iter.skipFourBytes('a', 'l', 's', 'e') + return false + } + iter.ReportError("ReadBool", "expect t or f, but found "+string([]byte{c})) + return +} + +// SkipAndReturnBytes skip next JSON element, and return its content as []byte. +// The []byte can be kept, it is a copy of data. +func (iter *Iterator) SkipAndReturnBytes() []byte { + iter.startCapture(iter.head) + iter.Skip() + return iter.stopCapture() +} + +type captureBuffer struct { + startedAt int + captured []byte +} + +func (iter *Iterator) startCapture(captureStartedAt int) { + if iter.captured != nil { + panic("already in capture mode") + } + iter.captureStartedAt = captureStartedAt + iter.captured = make([]byte, 0, 32) +} + +func (iter *Iterator) stopCapture() []byte { + if iter.captured == nil { + panic("not in capture mode") + } + captured := iter.captured + remaining := iter.buf[iter.captureStartedAt:iter.head] + iter.captureStartedAt = -1 + iter.captured = nil + if len(captured) == 0 { + copied := make([]byte, len(remaining)) + copy(copied, remaining) + return copied + } + captured = append(captured, remaining...) + return captured +} + +// Skip skips a json object and positions to relatively the next json object +func (iter *Iterator) Skip() { + c := iter.nextToken() + switch c { + case '"': + iter.skipString() + case 'n': + iter.skipThreeBytes('u', 'l', 'l') // null + case 't': + iter.skipThreeBytes('r', 'u', 'e') // true + case 'f': + iter.skipFourBytes('a', 'l', 's', 'e') // false + case '0': + iter.unreadByte() + iter.ReadFloat32() + case '-', '1', '2', '3', '4', '5', '6', '7', '8', '9': + iter.skipNumber() + case '[': + iter.skipArray() + case '{': + iter.skipObject() + default: + iter.ReportError("Skip", fmt.Sprintf("do not know how to skip: %v", c)) + return + } +} + +func (iter *Iterator) skipFourBytes(b1, b2, b3, b4 byte) { + if iter.readByte() != b1 { + iter.ReportError("skipFourBytes", fmt.Sprintf("expect %s", string([]byte{b1, b2, b3, b4}))) + return + } + if iter.readByte() != b2 { + iter.ReportError("skipFourBytes", fmt.Sprintf("expect %s", string([]byte{b1, b2, b3, b4}))) + return + } + if iter.readByte() != b3 { + iter.ReportError("skipFourBytes", fmt.Sprintf("expect %s", string([]byte{b1, b2, b3, b4}))) + return + } + if iter.readByte() != b4 { + iter.ReportError("skipFourBytes", fmt.Sprintf("expect %s", string([]byte{b1, b2, b3, b4}))) + return + } +} + +func (iter *Iterator) skipThreeBytes(b1, b2, b3 byte) { + if iter.readByte() != b1 { + iter.ReportError("skipThreeBytes", fmt.Sprintf("expect %s", string([]byte{b1, b2, b3}))) + return + } + if iter.readByte() != b2 { + iter.ReportError("skipThreeBytes", fmt.Sprintf("expect %s", string([]byte{b1, b2, b3}))) + return + } + if iter.readByte() != b3 { + iter.ReportError("skipThreeBytes", fmt.Sprintf("expect %s", string([]byte{b1, b2, b3}))) + return + } +} diff --git a/vendor/github.com/json-iterator/go/iter_skip_sloppy.go b/vendor/github.com/json-iterator/go/iter_skip_sloppy.go new file mode 100644 index 000000000..8fcdc3b69 --- /dev/null +++ b/vendor/github.com/json-iterator/go/iter_skip_sloppy.go @@ -0,0 +1,144 @@ +//+build jsoniter_sloppy + +package jsoniter + +// sloppy but faster implementation, do not validate the input json + +func (iter *Iterator) skipNumber() { + for { + for i := iter.head; i < iter.tail; i++ { + c := iter.buf[i] + switch c { + case ' ', '\n', '\r', '\t', ',', '}', ']': + iter.head = i + return + } + } + if !iter.loadMore() { + return + } + } +} + +func (iter *Iterator) skipArray() { + level := 1 + for { + for i := iter.head; i < iter.tail; i++ { + switch iter.buf[i] { + case '"': // If inside string, skip it + iter.head = i + 1 + iter.skipString() + i = iter.head - 1 // it will be i++ soon + case '[': // If open symbol, increase level + level++ + case ']': // If close symbol, increase level + level-- + + // If we have returned to the original level, we're done + if level == 0 { + iter.head = i + 1 + return + } + } + } + if !iter.loadMore() { + iter.ReportError("skipObject", "incomplete array") + return + } + } +} + +func (iter *Iterator) skipObject() { + level := 1 + for { + for i := iter.head; i < iter.tail; i++ { + switch iter.buf[i] { + case '"': // If inside string, skip it + iter.head = i + 1 + iter.skipString() + i = iter.head - 1 // it will be i++ soon + case '{': // If open symbol, increase level + level++ + case '}': // If close symbol, increase level + level-- + + // If we have returned to the original level, we're done + if level == 0 { + iter.head = i + 1 + return + } + } + } + if !iter.loadMore() { + iter.ReportError("skipObject", "incomplete object") + return + } + } +} + +func (iter *Iterator) skipString() { + for { + end, escaped := iter.findStringEnd() + if end == -1 { + if !iter.loadMore() { + iter.ReportError("skipString", "incomplete string") + return + } + if escaped { + iter.head = 1 // skip the first char as last char read is \ + } + } else { + iter.head = end + return + } + } +} + +// adapted from: https://github.com/buger/jsonparser/blob/master/parser.go +// Tries to find the end of string +// Support if string contains escaped quote symbols. +func (iter *Iterator) findStringEnd() (int, bool) { + escaped := false + for i := iter.head; i < iter.tail; i++ { + c := iter.buf[i] + if c == '"' { + if !escaped { + return i + 1, false + } + j := i - 1 + for { + if j < iter.head || iter.buf[j] != '\\' { + // even number of backslashes + // either end of buffer, or " found + return i + 1, true + } + j-- + if j < iter.head || iter.buf[j] != '\\' { + // odd number of backslashes + // it is \" or \\\" + break + } + j-- + } + } else if c == '\\' { + escaped = true + } + } + j := iter.tail - 1 + for { + if j < iter.head || iter.buf[j] != '\\' { + // even number of backslashes + // either end of buffer, or " found + return -1, false // do not end with \ + } + j-- + if j < iter.head || iter.buf[j] != '\\' { + // odd number of backslashes + // it is \" or \\\" + break + } + j-- + + } + return -1, true // end with \ +} diff --git a/vendor/github.com/json-iterator/go/iter_skip_strict.go b/vendor/github.com/json-iterator/go/iter_skip_strict.go new file mode 100644 index 000000000..f67bc2e83 --- /dev/null +++ b/vendor/github.com/json-iterator/go/iter_skip_strict.go @@ -0,0 +1,89 @@ +//+build !jsoniter_sloppy + +package jsoniter + +import "fmt" + +func (iter *Iterator) skipNumber() { + if !iter.trySkipNumber() { + iter.unreadByte() + iter.ReadFloat32() + } +} + +func (iter *Iterator) trySkipNumber() bool { + dotFound := false + for i := iter.head; i < iter.tail; i++ { + c := iter.buf[i] + switch c { + case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': + case '.': + if dotFound { + iter.ReportError("validateNumber", `more than one dot found in number`) + return true // already failed + } + if i+1 == iter.tail { + return false + } + c = iter.buf[i+1] + switch c { + case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': + default: + iter.ReportError("validateNumber", `missing digit after dot`) + return true // already failed + } + dotFound = true + default: + switch c { + case ',', ']', '}', ' ', '\t', '\n', '\r': + if iter.head == i { + return false // if - without following digits + } + iter.head = i + return true // must be valid + } + return false // may be invalid + } + } + return false +} + +func (iter *Iterator) skipString() { + if !iter.trySkipString() { + iter.unreadByte() + iter.ReadString() + } +} + +func (iter *Iterator) trySkipString() bool { + for i := iter.head; i < iter.tail; i++ { + c := iter.buf[i] + if c == '"' { + iter.head = i + 1 + return true // valid + } else if c == '\\' { + return false + } else if c < ' ' { + iter.ReportError("trySkipString", + fmt.Sprintf(`invalid control character found: %d`, c)) + return true // already failed + } + } + return false +} + +func (iter *Iterator) skipObject() { + iter.unreadByte() + iter.ReadObjectCB(func(iter *Iterator, field string) bool { + iter.Skip() + return true + }) +} + +func (iter *Iterator) skipArray() { + iter.unreadByte() + iter.ReadArrayCB(func(iter *Iterator) bool { + iter.Skip() + return true + }) +} diff --git a/vendor/github.com/json-iterator/go/iter_str.go b/vendor/github.com/json-iterator/go/iter_str.go new file mode 100644 index 000000000..adc487ea8 --- /dev/null +++ b/vendor/github.com/json-iterator/go/iter_str.go @@ -0,0 +1,215 @@ +package jsoniter + +import ( + "fmt" + "unicode/utf16" +) + +// ReadString read string from iterator +func (iter *Iterator) ReadString() (ret string) { + c := iter.nextToken() + if c == '"' { + for i := iter.head; i < iter.tail; i++ { + c := iter.buf[i] + if c == '"' { + ret = string(iter.buf[iter.head:i]) + iter.head = i + 1 + return ret + } else if c == '\\' { + break + } else if c < ' ' { + iter.ReportError("ReadString", + fmt.Sprintf(`invalid control character found: %d`, c)) + return + } + } + return iter.readStringSlowPath() + } else if c == 'n' { + iter.skipThreeBytes('u', 'l', 'l') + return "" + } + iter.ReportError("ReadString", `expects " or n, but found `+string([]byte{c})) + return +} + +func (iter *Iterator) readStringSlowPath() (ret string) { + var str []byte + var c byte + for iter.Error == nil { + c = iter.readByte() + if c == '"' { + return string(str) + } + if c == '\\' { + c = iter.readByte() + str = iter.readEscapedChar(c, str) + } else { + str = append(str, c) + } + } + iter.ReportError("readStringSlowPath", "unexpected end of input") + return +} + +func (iter *Iterator) readEscapedChar(c byte, str []byte) []byte { + switch c { + case 'u': + r := iter.readU4() + if utf16.IsSurrogate(r) { + c = iter.readByte() + if iter.Error != nil { + return nil + } + if c != '\\' { + iter.unreadByte() + str = appendRune(str, r) + return str + } + c = iter.readByte() + if iter.Error != nil { + return nil + } + if c != 'u' { + str = appendRune(str, r) + return iter.readEscapedChar(c, str) + } + r2 := iter.readU4() + if iter.Error != nil { + return nil + } + combined := utf16.DecodeRune(r, r2) + if combined == '\uFFFD' { + str = appendRune(str, r) + str = appendRune(str, r2) + } else { + str = appendRune(str, combined) + } + } else { + str = appendRune(str, r) + } + case '"': + str = append(str, '"') + case '\\': + str = append(str, '\\') + case '/': + str = append(str, '/') + case 'b': + str = append(str, '\b') + case 'f': + str = append(str, '\f') + case 'n': + str = append(str, '\n') + case 'r': + str = append(str, '\r') + case 't': + str = append(str, '\t') + default: + iter.ReportError("readEscapedChar", + `invalid escape char after \`) + return nil + } + return str +} + +// ReadStringAsSlice read string from iterator without copying into string form. +// The []byte can not be kept, as it will change after next iterator call. +func (iter *Iterator) ReadStringAsSlice() (ret []byte) { + c := iter.nextToken() + if c == '"' { + for i := iter.head; i < iter.tail; i++ { + // require ascii string and no escape + // for: field name, base64, number + if iter.buf[i] == '"' { + // fast path: reuse the underlying buffer + ret = iter.buf[iter.head:i] + iter.head = i + 1 + return ret + } + } + readLen := iter.tail - iter.head + copied := make([]byte, readLen, readLen*2) + copy(copied, iter.buf[iter.head:iter.tail]) + iter.head = iter.tail + for iter.Error == nil { + c := iter.readByte() + if c == '"' { + return copied + } + copied = append(copied, c) + } + return copied + } + iter.ReportError("ReadStringAsSlice", `expects " or n, but found `+string([]byte{c})) + return +} + +func (iter *Iterator) readU4() (ret rune) { + for i := 0; i < 4; i++ { + c := iter.readByte() + if iter.Error != nil { + return + } + if c >= '0' && c <= '9' { + ret = ret*16 + rune(c-'0') + } else if c >= 'a' && c <= 'f' { + ret = ret*16 + rune(c-'a'+10) + } else if c >= 'A' && c <= 'F' { + ret = ret*16 + rune(c-'A'+10) + } else { + iter.ReportError("readU4", "expects 0~9 or a~f, but found "+string([]byte{c})) + return + } + } + return ret +} + +const ( + t1 = 0x00 // 0000 0000 + tx = 0x80 // 1000 0000 + t2 = 0xC0 // 1100 0000 + t3 = 0xE0 // 1110 0000 + t4 = 0xF0 // 1111 0000 + t5 = 0xF8 // 1111 1000 + + maskx = 0x3F // 0011 1111 + mask2 = 0x1F // 0001 1111 + mask3 = 0x0F // 0000 1111 + mask4 = 0x07 // 0000 0111 + + rune1Max = 1<<7 - 1 + rune2Max = 1<<11 - 1 + rune3Max = 1<<16 - 1 + + surrogateMin = 0xD800 + surrogateMax = 0xDFFF + + maxRune = '\U0010FFFF' // Maximum valid Unicode code point. + runeError = '\uFFFD' // the "error" Rune or "Unicode replacement character" +) + +func appendRune(p []byte, r rune) []byte { + // Negative values are erroneous. Making it unsigned addresses the problem. + switch i := uint32(r); { + case i <= rune1Max: + p = append(p, byte(r)) + return p + case i <= rune2Max: + p = append(p, t2|byte(r>>6)) + p = append(p, tx|byte(r)&maskx) + return p + case i > maxRune, surrogateMin <= i && i <= surrogateMax: + r = runeError + fallthrough + case i <= rune3Max: + p = append(p, t3|byte(r>>12)) + p = append(p, tx|byte(r>>6)&maskx) + p = append(p, tx|byte(r)&maskx) + return p + default: + p = append(p, t4|byte(r>>18)) + p = append(p, tx|byte(r>>12)&maskx) + p = append(p, tx|byte(r>>6)&maskx) + p = append(p, tx|byte(r)&maskx) + return p + } +} diff --git a/vendor/github.com/json-iterator/go/jsoniter.go b/vendor/github.com/json-iterator/go/jsoniter.go new file mode 100644 index 000000000..c2934f916 --- /dev/null +++ b/vendor/github.com/json-iterator/go/jsoniter.go @@ -0,0 +1,18 @@ +// Package jsoniter implements encoding and decoding of JSON as defined in +// RFC 4627 and provides interfaces with identical syntax of standard lib encoding/json. +// Converting from encoding/json to jsoniter is no more than replacing the package with jsoniter +// and variable type declarations (if any). +// jsoniter interfaces gives 100% compatibility with code using standard lib. +// +// "JSON and Go" +// (https://golang.org/doc/articles/json_and_go.html) +// gives a description of how Marshal/Unmarshal operate +// between arbitrary or predefined json objects and bytes, +// and it applies to jsoniter.Marshal/Unmarshal as well. +// +// Besides, jsoniter.Iterator provides a different set of interfaces +// iterating given bytes/string/reader +// and yielding parsed elements one by one. +// This set of interfaces reads input as required and gives +// better performance. +package jsoniter diff --git a/vendor/github.com/json-iterator/go/pool.go b/vendor/github.com/json-iterator/go/pool.go new file mode 100644 index 000000000..e2389b56c --- /dev/null +++ b/vendor/github.com/json-iterator/go/pool.go @@ -0,0 +1,42 @@ +package jsoniter + +import ( + "io" +) + +// IteratorPool a thread safe pool of iterators with same configuration +type IteratorPool interface { + BorrowIterator(data []byte) *Iterator + ReturnIterator(iter *Iterator) +} + +// StreamPool a thread safe pool of streams with same configuration +type StreamPool interface { + BorrowStream(writer io.Writer) *Stream + ReturnStream(stream *Stream) +} + +func (cfg *frozenConfig) BorrowStream(writer io.Writer) *Stream { + stream := cfg.streamPool.Get().(*Stream) + stream.Reset(writer) + return stream +} + +func (cfg *frozenConfig) ReturnStream(stream *Stream) { + stream.out = nil + stream.Error = nil + stream.Attachment = nil + cfg.streamPool.Put(stream) +} + +func (cfg *frozenConfig) BorrowIterator(data []byte) *Iterator { + iter := cfg.iteratorPool.Get().(*Iterator) + iter.ResetBytes(data) + return iter +} + +func (cfg *frozenConfig) ReturnIterator(iter *Iterator) { + iter.Error = nil + iter.Attachment = nil + cfg.iteratorPool.Put(iter) +} diff --git a/vendor/github.com/json-iterator/go/reflect.go b/vendor/github.com/json-iterator/go/reflect.go new file mode 100644 index 000000000..4459e203f --- /dev/null +++ b/vendor/github.com/json-iterator/go/reflect.go @@ -0,0 +1,332 @@ +package jsoniter + +import ( + "fmt" + "reflect" + "unsafe" + + "github.com/modern-go/reflect2" +) + +// ValDecoder is an internal type registered to cache as needed. +// Don't confuse jsoniter.ValDecoder with json.Decoder. +// For json.Decoder's adapter, refer to jsoniter.AdapterDecoder(todo link). +// +// Reflection on type to create decoders, which is then cached +// Reflection on value is avoided as we can, as the reflect.Value itself will allocate, with following exceptions +// 1. create instance of new value, for example *int will need a int to be allocated +// 2. append to slice, if the existing cap is not enough, allocate will be done using Reflect.New +// 3. assignment to map, both key and value will be reflect.Value +// For a simple struct binding, it will be reflect.Value free and allocation free +type ValDecoder interface { + Decode(ptr unsafe.Pointer, iter *Iterator) +} + +// ValEncoder is an internal type registered to cache as needed. +// Don't confuse jsoniter.ValEncoder with json.Encoder. +// For json.Encoder's adapter, refer to jsoniter.AdapterEncoder(todo godoc link). +type ValEncoder interface { + IsEmpty(ptr unsafe.Pointer) bool + Encode(ptr unsafe.Pointer, stream *Stream) +} + +type checkIsEmpty interface { + IsEmpty(ptr unsafe.Pointer) bool +} + +type ctx struct { + *frozenConfig + prefix string + encoders map[reflect2.Type]ValEncoder + decoders map[reflect2.Type]ValDecoder +} + +func (b *ctx) caseSensitive() bool { + if b.frozenConfig == nil { + // default is case-insensitive + return false + } + return b.frozenConfig.caseSensitive +} + +func (b *ctx) append(prefix string) *ctx { + return &ctx{ + frozenConfig: b.frozenConfig, + prefix: b.prefix + " " + prefix, + encoders: b.encoders, + decoders: b.decoders, + } +} + +// ReadVal copy the underlying JSON into go interface, same as json.Unmarshal +func (iter *Iterator) ReadVal(obj interface{}) { + cacheKey := reflect2.RTypeOf(obj) + decoder := iter.cfg.getDecoderFromCache(cacheKey) + if decoder == nil { + typ := reflect2.TypeOf(obj) + if typ.Kind() != reflect.Ptr { + iter.ReportError("ReadVal", "can only unmarshal into pointer") + return + } + decoder = iter.cfg.DecoderOf(typ) + } + ptr := reflect2.PtrOf(obj) + if ptr == nil { + iter.ReportError("ReadVal", "can not read into nil pointer") + return + } + decoder.Decode(ptr, iter) +} + +// WriteVal copy the go interface into underlying JSON, same as json.Marshal +func (stream *Stream) WriteVal(val interface{}) { + if nil == val { + stream.WriteNil() + return + } + cacheKey := reflect2.RTypeOf(val) + encoder := stream.cfg.getEncoderFromCache(cacheKey) + if encoder == nil { + typ := reflect2.TypeOf(val) + encoder = stream.cfg.EncoderOf(typ) + } + encoder.Encode(reflect2.PtrOf(val), stream) +} + +func (cfg *frozenConfig) DecoderOf(typ reflect2.Type) ValDecoder { + cacheKey := typ.RType() + decoder := cfg.getDecoderFromCache(cacheKey) + if decoder != nil { + return decoder + } + ctx := &ctx{ + frozenConfig: cfg, + prefix: "", + decoders: map[reflect2.Type]ValDecoder{}, + encoders: map[reflect2.Type]ValEncoder{}, + } + ptrType := typ.(*reflect2.UnsafePtrType) + decoder = decoderOfType(ctx, ptrType.Elem()) + cfg.addDecoderToCache(cacheKey, decoder) + return decoder +} + +func decoderOfType(ctx *ctx, typ reflect2.Type) ValDecoder { + decoder := getTypeDecoderFromExtension(ctx, typ) + if decoder != nil { + return decoder + } + decoder = createDecoderOfType(ctx, typ) + for _, extension := range extensions { + decoder = extension.DecorateDecoder(typ, decoder) + } + decoder = ctx.decoderExtension.DecorateDecoder(typ, decoder) + for _, extension := range ctx.extraExtensions { + decoder = extension.DecorateDecoder(typ, decoder) + } + return decoder +} + +func createDecoderOfType(ctx *ctx, typ reflect2.Type) ValDecoder { + decoder := ctx.decoders[typ] + if decoder != nil { + return decoder + } + placeholder := &placeholderDecoder{} + ctx.decoders[typ] = placeholder + decoder = _createDecoderOfType(ctx, typ) + placeholder.decoder = decoder + return decoder +} + +func _createDecoderOfType(ctx *ctx, typ reflect2.Type) ValDecoder { + decoder := createDecoderOfJsonRawMessage(ctx, typ) + if decoder != nil { + return decoder + } + decoder = createDecoderOfJsonNumber(ctx, typ) + if decoder != nil { + return decoder + } + decoder = createDecoderOfMarshaler(ctx, typ) + if decoder != nil { + return decoder + } + decoder = createDecoderOfAny(ctx, typ) + if decoder != nil { + return decoder + } + decoder = createDecoderOfNative(ctx, typ) + if decoder != nil { + return decoder + } + switch typ.Kind() { + case reflect.Interface: + ifaceType, isIFace := typ.(*reflect2.UnsafeIFaceType) + if isIFace { + return &ifaceDecoder{valType: ifaceType} + } + return &efaceDecoder{} + case reflect.Struct: + return decoderOfStruct(ctx, typ) + case reflect.Array: + return decoderOfArray(ctx, typ) + case reflect.Slice: + return decoderOfSlice(ctx, typ) + case reflect.Map: + return decoderOfMap(ctx, typ) + case reflect.Ptr: + return decoderOfOptional(ctx, typ) + default: + return &lazyErrorDecoder{err: fmt.Errorf("%s%s is unsupported type", ctx.prefix, typ.String())} + } +} + +func (cfg *frozenConfig) EncoderOf(typ reflect2.Type) ValEncoder { + cacheKey := typ.RType() + encoder := cfg.getEncoderFromCache(cacheKey) + if encoder != nil { + return encoder + } + ctx := &ctx{ + frozenConfig: cfg, + prefix: "", + decoders: map[reflect2.Type]ValDecoder{}, + encoders: map[reflect2.Type]ValEncoder{}, + } + encoder = encoderOfType(ctx, typ) + if typ.LikePtr() { + encoder = &onePtrEncoder{encoder} + } + cfg.addEncoderToCache(cacheKey, encoder) + return encoder +} + +type onePtrEncoder struct { + encoder ValEncoder +} + +func (encoder *onePtrEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return encoder.encoder.IsEmpty(unsafe.Pointer(&ptr)) +} + +func (encoder *onePtrEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + encoder.encoder.Encode(unsafe.Pointer(&ptr), stream) +} + +func encoderOfType(ctx *ctx, typ reflect2.Type) ValEncoder { + encoder := getTypeEncoderFromExtension(ctx, typ) + if encoder != nil { + return encoder + } + encoder = createEncoderOfType(ctx, typ) + for _, extension := range extensions { + encoder = extension.DecorateEncoder(typ, encoder) + } + encoder = ctx.encoderExtension.DecorateEncoder(typ, encoder) + for _, extension := range ctx.extraExtensions { + encoder = extension.DecorateEncoder(typ, encoder) + } + return encoder +} + +func createEncoderOfType(ctx *ctx, typ reflect2.Type) ValEncoder { + encoder := ctx.encoders[typ] + if encoder != nil { + return encoder + } + placeholder := &placeholderEncoder{} + ctx.encoders[typ] = placeholder + encoder = _createEncoderOfType(ctx, typ) + placeholder.encoder = encoder + return encoder +} +func _createEncoderOfType(ctx *ctx, typ reflect2.Type) ValEncoder { + encoder := createEncoderOfJsonRawMessage(ctx, typ) + if encoder != nil { + return encoder + } + encoder = createEncoderOfJsonNumber(ctx, typ) + if encoder != nil { + return encoder + } + encoder = createEncoderOfMarshaler(ctx, typ) + if encoder != nil { + return encoder + } + encoder = createEncoderOfAny(ctx, typ) + if encoder != nil { + return encoder + } + encoder = createEncoderOfNative(ctx, typ) + if encoder != nil { + return encoder + } + kind := typ.Kind() + switch kind { + case reflect.Interface: + return &dynamicEncoder{typ} + case reflect.Struct: + return encoderOfStruct(ctx, typ) + case reflect.Array: + return encoderOfArray(ctx, typ) + case reflect.Slice: + return encoderOfSlice(ctx, typ) + case reflect.Map: + return encoderOfMap(ctx, typ) + case reflect.Ptr: + return encoderOfOptional(ctx, typ) + default: + return &lazyErrorEncoder{err: fmt.Errorf("%s%s is unsupported type", ctx.prefix, typ.String())} + } +} + +type lazyErrorDecoder struct { + err error +} + +func (decoder *lazyErrorDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + if iter.WhatIsNext() != NilValue { + if iter.Error == nil { + iter.Error = decoder.err + } + } else { + iter.Skip() + } +} + +type lazyErrorEncoder struct { + err error +} + +func (encoder *lazyErrorEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + if ptr == nil { + stream.WriteNil() + } else if stream.Error == nil { + stream.Error = encoder.err + } +} + +func (encoder *lazyErrorEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return false +} + +type placeholderDecoder struct { + decoder ValDecoder +} + +func (decoder *placeholderDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + decoder.decoder.Decode(ptr, iter) +} + +type placeholderEncoder struct { + encoder ValEncoder +} + +func (encoder *placeholderEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + encoder.encoder.Encode(ptr, stream) +} + +func (encoder *placeholderEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return encoder.encoder.IsEmpty(ptr) +} diff --git a/vendor/github.com/json-iterator/go/reflect_array.go b/vendor/github.com/json-iterator/go/reflect_array.go new file mode 100644 index 000000000..13a0b7b08 --- /dev/null +++ b/vendor/github.com/json-iterator/go/reflect_array.go @@ -0,0 +1,104 @@ +package jsoniter + +import ( + "fmt" + "github.com/modern-go/reflect2" + "io" + "unsafe" +) + +func decoderOfArray(ctx *ctx, typ reflect2.Type) ValDecoder { + arrayType := typ.(*reflect2.UnsafeArrayType) + decoder := decoderOfType(ctx.append("[arrayElem]"), arrayType.Elem()) + return &arrayDecoder{arrayType, decoder} +} + +func encoderOfArray(ctx *ctx, typ reflect2.Type) ValEncoder { + arrayType := typ.(*reflect2.UnsafeArrayType) + if arrayType.Len() == 0 { + return emptyArrayEncoder{} + } + encoder := encoderOfType(ctx.append("[arrayElem]"), arrayType.Elem()) + return &arrayEncoder{arrayType, encoder} +} + +type emptyArrayEncoder struct{} + +func (encoder emptyArrayEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteEmptyArray() +} + +func (encoder emptyArrayEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return true +} + +type arrayEncoder struct { + arrayType *reflect2.UnsafeArrayType + elemEncoder ValEncoder +} + +func (encoder *arrayEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteArrayStart() + elemPtr := unsafe.Pointer(ptr) + encoder.elemEncoder.Encode(elemPtr, stream) + for i := 1; i < encoder.arrayType.Len(); i++ { + stream.WriteMore() + elemPtr = encoder.arrayType.UnsafeGetIndex(ptr, i) + encoder.elemEncoder.Encode(elemPtr, stream) + } + stream.WriteArrayEnd() + if stream.Error != nil && stream.Error != io.EOF { + stream.Error = fmt.Errorf("%v: %s", encoder.arrayType, stream.Error.Error()) + } +} + +func (encoder *arrayEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return false +} + +type arrayDecoder struct { + arrayType *reflect2.UnsafeArrayType + elemDecoder ValDecoder +} + +func (decoder *arrayDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + decoder.doDecode(ptr, iter) + if iter.Error != nil && iter.Error != io.EOF { + iter.Error = fmt.Errorf("%v: %s", decoder.arrayType, iter.Error.Error()) + } +} + +func (decoder *arrayDecoder) doDecode(ptr unsafe.Pointer, iter *Iterator) { + c := iter.nextToken() + arrayType := decoder.arrayType + if c == 'n' { + iter.skipThreeBytes('u', 'l', 'l') + return + } + if c != '[' { + iter.ReportError("decode array", "expect [ or n, but found "+string([]byte{c})) + return + } + c = iter.nextToken() + if c == ']' { + return + } + iter.unreadByte() + elemPtr := arrayType.UnsafeGetIndex(ptr, 0) + decoder.elemDecoder.Decode(elemPtr, iter) + length := 1 + for c = iter.nextToken(); c == ','; c = iter.nextToken() { + if length >= arrayType.Len() { + iter.Skip() + continue + } + idx := length + length += 1 + elemPtr = arrayType.UnsafeGetIndex(ptr, idx) + decoder.elemDecoder.Decode(elemPtr, iter) + } + if c != ']' { + iter.ReportError("decode array", "expect ], but found "+string([]byte{c})) + return + } +} diff --git a/vendor/github.com/json-iterator/go/reflect_dynamic.go b/vendor/github.com/json-iterator/go/reflect_dynamic.go new file mode 100644 index 000000000..8b6bc8b43 --- /dev/null +++ b/vendor/github.com/json-iterator/go/reflect_dynamic.go @@ -0,0 +1,70 @@ +package jsoniter + +import ( + "github.com/modern-go/reflect2" + "reflect" + "unsafe" +) + +type dynamicEncoder struct { + valType reflect2.Type +} + +func (encoder *dynamicEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + obj := encoder.valType.UnsafeIndirect(ptr) + stream.WriteVal(obj) +} + +func (encoder *dynamicEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return encoder.valType.UnsafeIndirect(ptr) == nil +} + +type efaceDecoder struct { +} + +func (decoder *efaceDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + pObj := (*interface{})(ptr) + obj := *pObj + if obj == nil { + *pObj = iter.Read() + return + } + typ := reflect2.TypeOf(obj) + if typ.Kind() != reflect.Ptr { + *pObj = iter.Read() + return + } + ptrType := typ.(*reflect2.UnsafePtrType) + ptrElemType := ptrType.Elem() + if iter.WhatIsNext() == NilValue { + if ptrElemType.Kind() != reflect.Ptr { + iter.skipFourBytes('n', 'u', 'l', 'l') + *pObj = nil + return + } + } + if reflect2.IsNil(obj) { + obj := ptrElemType.New() + iter.ReadVal(obj) + *pObj = obj + return + } + iter.ReadVal(obj) +} + +type ifaceDecoder struct { + valType *reflect2.UnsafeIFaceType +} + +func (decoder *ifaceDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + if iter.ReadNil() { + decoder.valType.UnsafeSet(ptr, decoder.valType.UnsafeNew()) + return + } + obj := decoder.valType.UnsafeIndirect(ptr) + if reflect2.IsNil(obj) { + iter.ReportError("decode non empty interface", "can not unmarshal into nil") + return + } + iter.ReadVal(obj) +} diff --git a/vendor/github.com/json-iterator/go/reflect_extension.go b/vendor/github.com/json-iterator/go/reflect_extension.go new file mode 100644 index 000000000..04f68756b --- /dev/null +++ b/vendor/github.com/json-iterator/go/reflect_extension.go @@ -0,0 +1,483 @@ +package jsoniter + +import ( + "fmt" + "github.com/modern-go/reflect2" + "reflect" + "sort" + "strings" + "unicode" + "unsafe" +) + +var typeDecoders = map[string]ValDecoder{} +var fieldDecoders = map[string]ValDecoder{} +var typeEncoders = map[string]ValEncoder{} +var fieldEncoders = map[string]ValEncoder{} +var extensions = []Extension{} + +// StructDescriptor describe how should we encode/decode the struct +type StructDescriptor struct { + Type reflect2.Type + Fields []*Binding +} + +// GetField get one field from the descriptor by its name. +// Can not use map here to keep field orders. +func (structDescriptor *StructDescriptor) GetField(fieldName string) *Binding { + for _, binding := range structDescriptor.Fields { + if binding.Field.Name() == fieldName { + return binding + } + } + return nil +} + +// Binding describe how should we encode/decode the struct field +type Binding struct { + levels []int + Field reflect2.StructField + FromNames []string + ToNames []string + Encoder ValEncoder + Decoder ValDecoder +} + +// Extension the one for all SPI. Customize encoding/decoding by specifying alternate encoder/decoder. +// Can also rename fields by UpdateStructDescriptor. +type Extension interface { + UpdateStructDescriptor(structDescriptor *StructDescriptor) + CreateMapKeyDecoder(typ reflect2.Type) ValDecoder + CreateMapKeyEncoder(typ reflect2.Type) ValEncoder + CreateDecoder(typ reflect2.Type) ValDecoder + CreateEncoder(typ reflect2.Type) ValEncoder + DecorateDecoder(typ reflect2.Type, decoder ValDecoder) ValDecoder + DecorateEncoder(typ reflect2.Type, encoder ValEncoder) ValEncoder +} + +// DummyExtension embed this type get dummy implementation for all methods of Extension +type DummyExtension struct { +} + +// UpdateStructDescriptor No-op +func (extension *DummyExtension) UpdateStructDescriptor(structDescriptor *StructDescriptor) { +} + +// CreateMapKeyDecoder No-op +func (extension *DummyExtension) CreateMapKeyDecoder(typ reflect2.Type) ValDecoder { + return nil +} + +// CreateMapKeyEncoder No-op +func (extension *DummyExtension) CreateMapKeyEncoder(typ reflect2.Type) ValEncoder { + return nil +} + +// CreateDecoder No-op +func (extension *DummyExtension) CreateDecoder(typ reflect2.Type) ValDecoder { + return nil +} + +// CreateEncoder No-op +func (extension *DummyExtension) CreateEncoder(typ reflect2.Type) ValEncoder { + return nil +} + +// DecorateDecoder No-op +func (extension *DummyExtension) DecorateDecoder(typ reflect2.Type, decoder ValDecoder) ValDecoder { + return decoder +} + +// DecorateEncoder No-op +func (extension *DummyExtension) DecorateEncoder(typ reflect2.Type, encoder ValEncoder) ValEncoder { + return encoder +} + +type EncoderExtension map[reflect2.Type]ValEncoder + +// UpdateStructDescriptor No-op +func (extension EncoderExtension) UpdateStructDescriptor(structDescriptor *StructDescriptor) { +} + +// CreateDecoder No-op +func (extension EncoderExtension) CreateDecoder(typ reflect2.Type) ValDecoder { + return nil +} + +// CreateEncoder get encoder from map +func (extension EncoderExtension) CreateEncoder(typ reflect2.Type) ValEncoder { + return extension[typ] +} + +// CreateMapKeyDecoder No-op +func (extension EncoderExtension) CreateMapKeyDecoder(typ reflect2.Type) ValDecoder { + return nil +} + +// CreateMapKeyEncoder No-op +func (extension EncoderExtension) CreateMapKeyEncoder(typ reflect2.Type) ValEncoder { + return nil +} + +// DecorateDecoder No-op +func (extension EncoderExtension) DecorateDecoder(typ reflect2.Type, decoder ValDecoder) ValDecoder { + return decoder +} + +// DecorateEncoder No-op +func (extension EncoderExtension) DecorateEncoder(typ reflect2.Type, encoder ValEncoder) ValEncoder { + return encoder +} + +type DecoderExtension map[reflect2.Type]ValDecoder + +// UpdateStructDescriptor No-op +func (extension DecoderExtension) UpdateStructDescriptor(structDescriptor *StructDescriptor) { +} + +// CreateMapKeyDecoder No-op +func (extension DecoderExtension) CreateMapKeyDecoder(typ reflect2.Type) ValDecoder { + return nil +} + +// CreateMapKeyEncoder No-op +func (extension DecoderExtension) CreateMapKeyEncoder(typ reflect2.Type) ValEncoder { + return nil +} + +// CreateDecoder get decoder from map +func (extension DecoderExtension) CreateDecoder(typ reflect2.Type) ValDecoder { + return extension[typ] +} + +// CreateEncoder No-op +func (extension DecoderExtension) CreateEncoder(typ reflect2.Type) ValEncoder { + return nil +} + +// DecorateDecoder No-op +func (extension DecoderExtension) DecorateDecoder(typ reflect2.Type, decoder ValDecoder) ValDecoder { + return decoder +} + +// DecorateEncoder No-op +func (extension DecoderExtension) DecorateEncoder(typ reflect2.Type, encoder ValEncoder) ValEncoder { + return encoder +} + +type funcDecoder struct { + fun DecoderFunc +} + +func (decoder *funcDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + decoder.fun(ptr, iter) +} + +type funcEncoder struct { + fun EncoderFunc + isEmptyFunc func(ptr unsafe.Pointer) bool +} + +func (encoder *funcEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + encoder.fun(ptr, stream) +} + +func (encoder *funcEncoder) IsEmpty(ptr unsafe.Pointer) bool { + if encoder.isEmptyFunc == nil { + return false + } + return encoder.isEmptyFunc(ptr) +} + +// DecoderFunc the function form of TypeDecoder +type DecoderFunc func(ptr unsafe.Pointer, iter *Iterator) + +// EncoderFunc the function form of TypeEncoder +type EncoderFunc func(ptr unsafe.Pointer, stream *Stream) + +// RegisterTypeDecoderFunc register TypeDecoder for a type with function +func RegisterTypeDecoderFunc(typ string, fun DecoderFunc) { + typeDecoders[typ] = &funcDecoder{fun} +} + +// RegisterTypeDecoder register TypeDecoder for a typ +func RegisterTypeDecoder(typ string, decoder ValDecoder) { + typeDecoders[typ] = decoder +} + +// RegisterFieldDecoderFunc register TypeDecoder for a struct field with function +func RegisterFieldDecoderFunc(typ string, field string, fun DecoderFunc) { + RegisterFieldDecoder(typ, field, &funcDecoder{fun}) +} + +// RegisterFieldDecoder register TypeDecoder for a struct field +func RegisterFieldDecoder(typ string, field string, decoder ValDecoder) { + fieldDecoders[fmt.Sprintf("%s/%s", typ, field)] = decoder +} + +// RegisterTypeEncoderFunc register TypeEncoder for a type with encode/isEmpty function +func RegisterTypeEncoderFunc(typ string, fun EncoderFunc, isEmptyFunc func(unsafe.Pointer) bool) { + typeEncoders[typ] = &funcEncoder{fun, isEmptyFunc} +} + +// RegisterTypeEncoder register TypeEncoder for a type +func RegisterTypeEncoder(typ string, encoder ValEncoder) { + typeEncoders[typ] = encoder +} + +// RegisterFieldEncoderFunc register TypeEncoder for a struct field with encode/isEmpty function +func RegisterFieldEncoderFunc(typ string, field string, fun EncoderFunc, isEmptyFunc func(unsafe.Pointer) bool) { + RegisterFieldEncoder(typ, field, &funcEncoder{fun, isEmptyFunc}) +} + +// RegisterFieldEncoder register TypeEncoder for a struct field +func RegisterFieldEncoder(typ string, field string, encoder ValEncoder) { + fieldEncoders[fmt.Sprintf("%s/%s", typ, field)] = encoder +} + +// RegisterExtension register extension +func RegisterExtension(extension Extension) { + extensions = append(extensions, extension) +} + +func getTypeDecoderFromExtension(ctx *ctx, typ reflect2.Type) ValDecoder { + decoder := _getTypeDecoderFromExtension(ctx, typ) + if decoder != nil { + for _, extension := range extensions { + decoder = extension.DecorateDecoder(typ, decoder) + } + decoder = ctx.decoderExtension.DecorateDecoder(typ, decoder) + for _, extension := range ctx.extraExtensions { + decoder = extension.DecorateDecoder(typ, decoder) + } + } + return decoder +} +func _getTypeDecoderFromExtension(ctx *ctx, typ reflect2.Type) ValDecoder { + for _, extension := range extensions { + decoder := extension.CreateDecoder(typ) + if decoder != nil { + return decoder + } + } + decoder := ctx.decoderExtension.CreateDecoder(typ) + if decoder != nil { + return decoder + } + for _, extension := range ctx.extraExtensions { + decoder := extension.CreateDecoder(typ) + if decoder != nil { + return decoder + } + } + typeName := typ.String() + decoder = typeDecoders[typeName] + if decoder != nil { + return decoder + } + if typ.Kind() == reflect.Ptr { + ptrType := typ.(*reflect2.UnsafePtrType) + decoder := typeDecoders[ptrType.Elem().String()] + if decoder != nil { + return &OptionalDecoder{ptrType.Elem(), decoder} + } + } + return nil +} + +func getTypeEncoderFromExtension(ctx *ctx, typ reflect2.Type) ValEncoder { + encoder := _getTypeEncoderFromExtension(ctx, typ) + if encoder != nil { + for _, extension := range extensions { + encoder = extension.DecorateEncoder(typ, encoder) + } + encoder = ctx.encoderExtension.DecorateEncoder(typ, encoder) + for _, extension := range ctx.extraExtensions { + encoder = extension.DecorateEncoder(typ, encoder) + } + } + return encoder +} + +func _getTypeEncoderFromExtension(ctx *ctx, typ reflect2.Type) ValEncoder { + for _, extension := range extensions { + encoder := extension.CreateEncoder(typ) + if encoder != nil { + return encoder + } + } + encoder := ctx.encoderExtension.CreateEncoder(typ) + if encoder != nil { + return encoder + } + for _, extension := range ctx.extraExtensions { + encoder := extension.CreateEncoder(typ) + if encoder != nil { + return encoder + } + } + typeName := typ.String() + encoder = typeEncoders[typeName] + if encoder != nil { + return encoder + } + if typ.Kind() == reflect.Ptr { + typePtr := typ.(*reflect2.UnsafePtrType) + encoder := typeEncoders[typePtr.Elem().String()] + if encoder != nil { + return &OptionalEncoder{encoder} + } + } + return nil +} + +func describeStruct(ctx *ctx, typ reflect2.Type) *StructDescriptor { + structType := typ.(*reflect2.UnsafeStructType) + embeddedBindings := []*Binding{} + bindings := []*Binding{} + for i := 0; i < structType.NumField(); i++ { + field := structType.Field(i) + tag, hastag := field.Tag().Lookup(ctx.getTagKey()) + if ctx.onlyTaggedField && !hastag { + continue + } + tagParts := strings.Split(tag, ",") + if tag == "-" { + continue + } + if field.Anonymous() && (tag == "" || tagParts[0] == "") { + if field.Type().Kind() == reflect.Struct { + structDescriptor := describeStruct(ctx, field.Type()) + for _, binding := range structDescriptor.Fields { + binding.levels = append([]int{i}, binding.levels...) + omitempty := binding.Encoder.(*structFieldEncoder).omitempty + binding.Encoder = &structFieldEncoder{field, binding.Encoder, omitempty} + binding.Decoder = &structFieldDecoder{field, binding.Decoder} + embeddedBindings = append(embeddedBindings, binding) + } + continue + } else if field.Type().Kind() == reflect.Ptr { + ptrType := field.Type().(*reflect2.UnsafePtrType) + if ptrType.Elem().Kind() == reflect.Struct { + structDescriptor := describeStruct(ctx, ptrType.Elem()) + for _, binding := range structDescriptor.Fields { + binding.levels = append([]int{i}, binding.levels...) + omitempty := binding.Encoder.(*structFieldEncoder).omitempty + binding.Encoder = &dereferenceEncoder{binding.Encoder} + binding.Encoder = &structFieldEncoder{field, binding.Encoder, omitempty} + binding.Decoder = &dereferenceDecoder{ptrType.Elem(), binding.Decoder} + binding.Decoder = &structFieldDecoder{field, binding.Decoder} + embeddedBindings = append(embeddedBindings, binding) + } + continue + } + } + } + fieldNames := calcFieldNames(field.Name(), tagParts[0], tag) + fieldCacheKey := fmt.Sprintf("%s/%s", typ.String(), field.Name()) + decoder := fieldDecoders[fieldCacheKey] + if decoder == nil { + decoder = decoderOfType(ctx.append(field.Name()), field.Type()) + } + encoder := fieldEncoders[fieldCacheKey] + if encoder == nil { + encoder = encoderOfType(ctx.append(field.Name()), field.Type()) + } + binding := &Binding{ + Field: field, + FromNames: fieldNames, + ToNames: fieldNames, + Decoder: decoder, + Encoder: encoder, + } + binding.levels = []int{i} + bindings = append(bindings, binding) + } + return createStructDescriptor(ctx, typ, bindings, embeddedBindings) +} +func createStructDescriptor(ctx *ctx, typ reflect2.Type, bindings []*Binding, embeddedBindings []*Binding) *StructDescriptor { + structDescriptor := &StructDescriptor{ + Type: typ, + Fields: bindings, + } + for _, extension := range extensions { + extension.UpdateStructDescriptor(structDescriptor) + } + ctx.encoderExtension.UpdateStructDescriptor(structDescriptor) + ctx.decoderExtension.UpdateStructDescriptor(structDescriptor) + for _, extension := range ctx.extraExtensions { + extension.UpdateStructDescriptor(structDescriptor) + } + processTags(structDescriptor, ctx.frozenConfig) + // merge normal & embedded bindings & sort with original order + allBindings := sortableBindings(append(embeddedBindings, structDescriptor.Fields...)) + sort.Sort(allBindings) + structDescriptor.Fields = allBindings + return structDescriptor +} + +type sortableBindings []*Binding + +func (bindings sortableBindings) Len() int { + return len(bindings) +} + +func (bindings sortableBindings) Less(i, j int) bool { + left := bindings[i].levels + right := bindings[j].levels + k := 0 + for { + if left[k] < right[k] { + return true + } else if left[k] > right[k] { + return false + } + k++ + } +} + +func (bindings sortableBindings) Swap(i, j int) { + bindings[i], bindings[j] = bindings[j], bindings[i] +} + +func processTags(structDescriptor *StructDescriptor, cfg *frozenConfig) { + for _, binding := range structDescriptor.Fields { + shouldOmitEmpty := false + tagParts := strings.Split(binding.Field.Tag().Get(cfg.getTagKey()), ",") + for _, tagPart := range tagParts[1:] { + if tagPart == "omitempty" { + shouldOmitEmpty = true + } else if tagPart == "string" { + if binding.Field.Type().Kind() == reflect.String { + binding.Decoder = &stringModeStringDecoder{binding.Decoder, cfg} + binding.Encoder = &stringModeStringEncoder{binding.Encoder, cfg} + } else { + binding.Decoder = &stringModeNumberDecoder{binding.Decoder} + binding.Encoder = &stringModeNumberEncoder{binding.Encoder} + } + } + } + binding.Decoder = &structFieldDecoder{binding.Field, binding.Decoder} + binding.Encoder = &structFieldEncoder{binding.Field, binding.Encoder, shouldOmitEmpty} + } +} + +func calcFieldNames(originalFieldName string, tagProvidedFieldName string, wholeTag string) []string { + // ignore? + if wholeTag == "-" { + return []string{} + } + // rename? + var fieldNames []string + if tagProvidedFieldName == "" { + fieldNames = []string{originalFieldName} + } else { + fieldNames = []string{tagProvidedFieldName} + } + // private? + isNotExported := unicode.IsLower(rune(originalFieldName[0])) + if isNotExported { + fieldNames = []string{} + } + return fieldNames +} diff --git a/vendor/github.com/json-iterator/go/reflect_json_number.go b/vendor/github.com/json-iterator/go/reflect_json_number.go new file mode 100644 index 000000000..98d45c1ec --- /dev/null +++ b/vendor/github.com/json-iterator/go/reflect_json_number.go @@ -0,0 +1,112 @@ +package jsoniter + +import ( + "encoding/json" + "github.com/modern-go/reflect2" + "strconv" + "unsafe" +) + +type Number string + +// String returns the literal text of the number. +func (n Number) String() string { return string(n) } + +// Float64 returns the number as a float64. +func (n Number) Float64() (float64, error) { + return strconv.ParseFloat(string(n), 64) +} + +// Int64 returns the number as an int64. +func (n Number) Int64() (int64, error) { + return strconv.ParseInt(string(n), 10, 64) +} + +func CastJsonNumber(val interface{}) (string, bool) { + switch typedVal := val.(type) { + case json.Number: + return string(typedVal), true + case Number: + return string(typedVal), true + } + return "", false +} + +var jsonNumberType = reflect2.TypeOfPtr((*json.Number)(nil)).Elem() +var jsoniterNumberType = reflect2.TypeOfPtr((*Number)(nil)).Elem() + +func createDecoderOfJsonNumber(ctx *ctx, typ reflect2.Type) ValDecoder { + if typ.AssignableTo(jsonNumberType) { + return &jsonNumberCodec{} + } + if typ.AssignableTo(jsoniterNumberType) { + return &jsoniterNumberCodec{} + } + return nil +} + +func createEncoderOfJsonNumber(ctx *ctx, typ reflect2.Type) ValEncoder { + if typ.AssignableTo(jsonNumberType) { + return &jsonNumberCodec{} + } + if typ.AssignableTo(jsoniterNumberType) { + return &jsoniterNumberCodec{} + } + return nil +} + +type jsonNumberCodec struct { +} + +func (codec *jsonNumberCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { + switch iter.WhatIsNext() { + case StringValue: + *((*json.Number)(ptr)) = json.Number(iter.ReadString()) + case NilValue: + iter.skipFourBytes('n', 'u', 'l', 'l') + *((*json.Number)(ptr)) = "" + default: + *((*json.Number)(ptr)) = json.Number([]byte(iter.readNumberAsString())) + } +} + +func (codec *jsonNumberCodec) Encode(ptr unsafe.Pointer, stream *Stream) { + number := *((*json.Number)(ptr)) + if len(number) == 0 { + stream.writeByte('0') + } else { + stream.WriteRaw(string(number)) + } +} + +func (codec *jsonNumberCodec) IsEmpty(ptr unsafe.Pointer) bool { + return len(*((*json.Number)(ptr))) == 0 +} + +type jsoniterNumberCodec struct { +} + +func (codec *jsoniterNumberCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { + switch iter.WhatIsNext() { + case StringValue: + *((*Number)(ptr)) = Number(iter.ReadString()) + case NilValue: + iter.skipFourBytes('n', 'u', 'l', 'l') + *((*Number)(ptr)) = "" + default: + *((*Number)(ptr)) = Number([]byte(iter.readNumberAsString())) + } +} + +func (codec *jsoniterNumberCodec) Encode(ptr unsafe.Pointer, stream *Stream) { + number := *((*Number)(ptr)) + if len(number) == 0 { + stream.writeByte('0') + } else { + stream.WriteRaw(string(number)) + } +} + +func (codec *jsoniterNumberCodec) IsEmpty(ptr unsafe.Pointer) bool { + return len(*((*Number)(ptr))) == 0 +} diff --git a/vendor/github.com/json-iterator/go/reflect_json_raw_message.go b/vendor/github.com/json-iterator/go/reflect_json_raw_message.go new file mode 100644 index 000000000..f2619936c --- /dev/null +++ b/vendor/github.com/json-iterator/go/reflect_json_raw_message.go @@ -0,0 +1,60 @@ +package jsoniter + +import ( + "encoding/json" + "github.com/modern-go/reflect2" + "unsafe" +) + +var jsonRawMessageType = reflect2.TypeOfPtr((*json.RawMessage)(nil)).Elem() +var jsoniterRawMessageType = reflect2.TypeOfPtr((*RawMessage)(nil)).Elem() + +func createEncoderOfJsonRawMessage(ctx *ctx, typ reflect2.Type) ValEncoder { + if typ == jsonRawMessageType { + return &jsonRawMessageCodec{} + } + if typ == jsoniterRawMessageType { + return &jsoniterRawMessageCodec{} + } + return nil +} + +func createDecoderOfJsonRawMessage(ctx *ctx, typ reflect2.Type) ValDecoder { + if typ == jsonRawMessageType { + return &jsonRawMessageCodec{} + } + if typ == jsoniterRawMessageType { + return &jsoniterRawMessageCodec{} + } + return nil +} + +type jsonRawMessageCodec struct { +} + +func (codec *jsonRawMessageCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { + *((*json.RawMessage)(ptr)) = json.RawMessage(iter.SkipAndReturnBytes()) +} + +func (codec *jsonRawMessageCodec) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteRaw(string(*((*json.RawMessage)(ptr)))) +} + +func (codec *jsonRawMessageCodec) IsEmpty(ptr unsafe.Pointer) bool { + return len(*((*json.RawMessage)(ptr))) == 0 +} + +type jsoniterRawMessageCodec struct { +} + +func (codec *jsoniterRawMessageCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { + *((*RawMessage)(ptr)) = RawMessage(iter.SkipAndReturnBytes()) +} + +func (codec *jsoniterRawMessageCodec) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteRaw(string(*((*RawMessage)(ptr)))) +} + +func (codec *jsoniterRawMessageCodec) IsEmpty(ptr unsafe.Pointer) bool { + return len(*((*RawMessage)(ptr))) == 0 +} diff --git a/vendor/github.com/json-iterator/go/reflect_map.go b/vendor/github.com/json-iterator/go/reflect_map.go new file mode 100644 index 000000000..7f66a88b0 --- /dev/null +++ b/vendor/github.com/json-iterator/go/reflect_map.go @@ -0,0 +1,326 @@ +package jsoniter + +import ( + "fmt" + "github.com/modern-go/reflect2" + "io" + "reflect" + "sort" + "unsafe" +) + +func decoderOfMap(ctx *ctx, typ reflect2.Type) ValDecoder { + mapType := typ.(*reflect2.UnsafeMapType) + keyDecoder := decoderOfMapKey(ctx.append("[mapKey]"), mapType.Key()) + elemDecoder := decoderOfType(ctx.append("[mapElem]"), mapType.Elem()) + return &mapDecoder{ + mapType: mapType, + keyType: mapType.Key(), + elemType: mapType.Elem(), + keyDecoder: keyDecoder, + elemDecoder: elemDecoder, + } +} + +func encoderOfMap(ctx *ctx, typ reflect2.Type) ValEncoder { + mapType := typ.(*reflect2.UnsafeMapType) + if ctx.sortMapKeys { + return &sortKeysMapEncoder{ + mapType: mapType, + keyEncoder: encoderOfMapKey(ctx.append("[mapKey]"), mapType.Key()), + elemEncoder: encoderOfType(ctx.append("[mapElem]"), mapType.Elem()), + } + } + return &mapEncoder{ + mapType: mapType, + keyEncoder: encoderOfMapKey(ctx.append("[mapKey]"), mapType.Key()), + elemEncoder: encoderOfType(ctx.append("[mapElem]"), mapType.Elem()), + } +} + +func decoderOfMapKey(ctx *ctx, typ reflect2.Type) ValDecoder { + decoder := ctx.decoderExtension.CreateMapKeyDecoder(typ) + if decoder != nil { + return decoder + } + for _, extension := range ctx.extraExtensions { + decoder := extension.CreateMapKeyDecoder(typ) + if decoder != nil { + return decoder + } + } + switch typ.Kind() { + case reflect.String: + return decoderOfType(ctx, reflect2.DefaultTypeOfKind(reflect.String)) + case reflect.Bool, + reflect.Uint8, reflect.Int8, + reflect.Uint16, reflect.Int16, + reflect.Uint32, reflect.Int32, + reflect.Uint64, reflect.Int64, + reflect.Uint, reflect.Int, + reflect.Float32, reflect.Float64, + reflect.Uintptr: + typ = reflect2.DefaultTypeOfKind(typ.Kind()) + return &numericMapKeyDecoder{decoderOfType(ctx, typ)} + default: + ptrType := reflect2.PtrTo(typ) + if ptrType.Implements(textMarshalerType) { + return &referenceDecoder{ + &textUnmarshalerDecoder{ + valType: ptrType, + }, + } + } + if typ.Implements(textMarshalerType) { + return &textUnmarshalerDecoder{ + valType: typ, + } + } + return &lazyErrorDecoder{err: fmt.Errorf("unsupported map key type: %v", typ)} + } +} + +func encoderOfMapKey(ctx *ctx, typ reflect2.Type) ValEncoder { + encoder := ctx.encoderExtension.CreateMapKeyEncoder(typ) + if encoder != nil { + return encoder + } + for _, extension := range ctx.extraExtensions { + encoder := extension.CreateMapKeyEncoder(typ) + if encoder != nil { + return encoder + } + } + switch typ.Kind() { + case reflect.String: + return encoderOfType(ctx, reflect2.DefaultTypeOfKind(reflect.String)) + case reflect.Bool, + reflect.Uint8, reflect.Int8, + reflect.Uint16, reflect.Int16, + reflect.Uint32, reflect.Int32, + reflect.Uint64, reflect.Int64, + reflect.Uint, reflect.Int, + reflect.Float32, reflect.Float64, + reflect.Uintptr: + typ = reflect2.DefaultTypeOfKind(typ.Kind()) + return &numericMapKeyEncoder{encoderOfType(ctx, typ)} + default: + if typ == textMarshalerType { + return &directTextMarshalerEncoder{ + stringEncoder: ctx.EncoderOf(reflect2.TypeOf("")), + } + } + if typ.Implements(textMarshalerType) { + return &textMarshalerEncoder{ + valType: typ, + stringEncoder: ctx.EncoderOf(reflect2.TypeOf("")), + } + } + if typ.Kind() == reflect.Interface { + return &dynamicMapKeyEncoder{ctx, typ} + } + return &lazyErrorEncoder{err: fmt.Errorf("unsupported map key type: %v", typ)} + } +} + +type mapDecoder struct { + mapType *reflect2.UnsafeMapType + keyType reflect2.Type + elemType reflect2.Type + keyDecoder ValDecoder + elemDecoder ValDecoder +} + +func (decoder *mapDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + mapType := decoder.mapType + c := iter.nextToken() + if c == 'n' { + iter.skipThreeBytes('u', 'l', 'l') + *(*unsafe.Pointer)(ptr) = nil + mapType.UnsafeSet(ptr, mapType.UnsafeNew()) + return + } + if mapType.UnsafeIsNil(ptr) { + mapType.UnsafeSet(ptr, mapType.UnsafeMakeMap(0)) + } + if c != '{' { + iter.ReportError("ReadMapCB", `expect { or n, but found `+string([]byte{c})) + return + } + c = iter.nextToken() + if c == '}' { + return + } + if c != '"' { + iter.ReportError("ReadMapCB", `expect " after }, but found `+string([]byte{c})) + return + } + iter.unreadByte() + key := decoder.keyType.UnsafeNew() + decoder.keyDecoder.Decode(key, iter) + c = iter.nextToken() + if c != ':' { + iter.ReportError("ReadMapCB", "expect : after object field, but found "+string([]byte{c})) + return + } + elem := decoder.elemType.UnsafeNew() + decoder.elemDecoder.Decode(elem, iter) + decoder.mapType.UnsafeSetIndex(ptr, key, elem) + for c = iter.nextToken(); c == ','; c = iter.nextToken() { + key := decoder.keyType.UnsafeNew() + decoder.keyDecoder.Decode(key, iter) + c = iter.nextToken() + if c != ':' { + iter.ReportError("ReadMapCB", "expect : after object field, but found "+string([]byte{c})) + return + } + elem := decoder.elemType.UnsafeNew() + decoder.elemDecoder.Decode(elem, iter) + decoder.mapType.UnsafeSetIndex(ptr, key, elem) + } + if c != '}' { + iter.ReportError("ReadMapCB", `expect }, but found `+string([]byte{c})) + } +} + +type numericMapKeyDecoder struct { + decoder ValDecoder +} + +func (decoder *numericMapKeyDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + c := iter.nextToken() + if c != '"' { + iter.ReportError("ReadMapCB", `expect ", but found `+string([]byte{c})) + return + } + decoder.decoder.Decode(ptr, iter) + c = iter.nextToken() + if c != '"' { + iter.ReportError("ReadMapCB", `expect ", but found `+string([]byte{c})) + return + } +} + +type numericMapKeyEncoder struct { + encoder ValEncoder +} + +func (encoder *numericMapKeyEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.writeByte('"') + encoder.encoder.Encode(ptr, stream) + stream.writeByte('"') +} + +func (encoder *numericMapKeyEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return false +} + +type dynamicMapKeyEncoder struct { + ctx *ctx + valType reflect2.Type +} + +func (encoder *dynamicMapKeyEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + obj := encoder.valType.UnsafeIndirect(ptr) + encoderOfMapKey(encoder.ctx, reflect2.TypeOf(obj)).Encode(reflect2.PtrOf(obj), stream) +} + +func (encoder *dynamicMapKeyEncoder) IsEmpty(ptr unsafe.Pointer) bool { + obj := encoder.valType.UnsafeIndirect(ptr) + return encoderOfMapKey(encoder.ctx, reflect2.TypeOf(obj)).IsEmpty(reflect2.PtrOf(obj)) +} + +type mapEncoder struct { + mapType *reflect2.UnsafeMapType + keyEncoder ValEncoder + elemEncoder ValEncoder +} + +func (encoder *mapEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteObjectStart() + iter := encoder.mapType.UnsafeIterate(ptr) + for i := 0; iter.HasNext(); i++ { + if i != 0 { + stream.WriteMore() + } + key, elem := iter.UnsafeNext() + encoder.keyEncoder.Encode(key, stream) + if stream.indention > 0 { + stream.writeTwoBytes(byte(':'), byte(' ')) + } else { + stream.writeByte(':') + } + encoder.elemEncoder.Encode(elem, stream) + } + stream.WriteObjectEnd() +} + +func (encoder *mapEncoder) IsEmpty(ptr unsafe.Pointer) bool { + iter := encoder.mapType.UnsafeIterate(ptr) + return !iter.HasNext() +} + +type sortKeysMapEncoder struct { + mapType *reflect2.UnsafeMapType + keyEncoder ValEncoder + elemEncoder ValEncoder +} + +func (encoder *sortKeysMapEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + if *(*unsafe.Pointer)(ptr) == nil { + stream.WriteNil() + return + } + stream.WriteObjectStart() + mapIter := encoder.mapType.UnsafeIterate(ptr) + subStream := stream.cfg.BorrowStream(nil) + subIter := stream.cfg.BorrowIterator(nil) + keyValues := encodedKeyValues{} + for mapIter.HasNext() { + subStream.buf = make([]byte, 0, 64) + key, elem := mapIter.UnsafeNext() + encoder.keyEncoder.Encode(key, subStream) + if subStream.Error != nil && subStream.Error != io.EOF && stream.Error == nil { + stream.Error = subStream.Error + } + encodedKey := subStream.Buffer() + subIter.ResetBytes(encodedKey) + decodedKey := subIter.ReadString() + if stream.indention > 0 { + subStream.writeTwoBytes(byte(':'), byte(' ')) + } else { + subStream.writeByte(':') + } + encoder.elemEncoder.Encode(elem, subStream) + keyValues = append(keyValues, encodedKV{ + key: decodedKey, + keyValue: subStream.Buffer(), + }) + } + sort.Sort(keyValues) + for i, keyValue := range keyValues { + if i != 0 { + stream.WriteMore() + } + stream.Write(keyValue.keyValue) + } + stream.WriteObjectEnd() + stream.cfg.ReturnStream(subStream) + stream.cfg.ReturnIterator(subIter) +} + +func (encoder *sortKeysMapEncoder) IsEmpty(ptr unsafe.Pointer) bool { + iter := encoder.mapType.UnsafeIterate(ptr) + return !iter.HasNext() +} + +type encodedKeyValues []encodedKV + +type encodedKV struct { + key string + keyValue []byte +} + +func (sv encodedKeyValues) Len() int { return len(sv) } +func (sv encodedKeyValues) Swap(i, j int) { sv[i], sv[j] = sv[j], sv[i] } +func (sv encodedKeyValues) Less(i, j int) bool { return sv[i].key < sv[j].key } diff --git a/vendor/github.com/json-iterator/go/reflect_marshaler.go b/vendor/github.com/json-iterator/go/reflect_marshaler.go new file mode 100644 index 000000000..58ac959ad --- /dev/null +++ b/vendor/github.com/json-iterator/go/reflect_marshaler.go @@ -0,0 +1,218 @@ +package jsoniter + +import ( + "encoding" + "encoding/json" + "github.com/modern-go/reflect2" + "unsafe" +) + +var marshalerType = reflect2.TypeOfPtr((*json.Marshaler)(nil)).Elem() +var unmarshalerType = reflect2.TypeOfPtr((*json.Unmarshaler)(nil)).Elem() +var textMarshalerType = reflect2.TypeOfPtr((*encoding.TextMarshaler)(nil)).Elem() +var textUnmarshalerType = reflect2.TypeOfPtr((*encoding.TextUnmarshaler)(nil)).Elem() + +func createDecoderOfMarshaler(ctx *ctx, typ reflect2.Type) ValDecoder { + ptrType := reflect2.PtrTo(typ) + if ptrType.Implements(unmarshalerType) { + return &referenceDecoder{ + &unmarshalerDecoder{ptrType}, + } + } + if ptrType.Implements(textUnmarshalerType) { + return &referenceDecoder{ + &textUnmarshalerDecoder{ptrType}, + } + } + return nil +} + +func createEncoderOfMarshaler(ctx *ctx, typ reflect2.Type) ValEncoder { + if typ == marshalerType { + checkIsEmpty := createCheckIsEmpty(ctx, typ) + var encoder ValEncoder = &directMarshalerEncoder{ + checkIsEmpty: checkIsEmpty, + } + return encoder + } + if typ.Implements(marshalerType) { + checkIsEmpty := createCheckIsEmpty(ctx, typ) + var encoder ValEncoder = &marshalerEncoder{ + valType: typ, + checkIsEmpty: checkIsEmpty, + } + return encoder + } + ptrType := reflect2.PtrTo(typ) + if ctx.prefix != "" && ptrType.Implements(marshalerType) { + checkIsEmpty := createCheckIsEmpty(ctx, ptrType) + var encoder ValEncoder = &marshalerEncoder{ + valType: ptrType, + checkIsEmpty: checkIsEmpty, + } + return &referenceEncoder{encoder} + } + if typ == textMarshalerType { + checkIsEmpty := createCheckIsEmpty(ctx, typ) + var encoder ValEncoder = &directTextMarshalerEncoder{ + checkIsEmpty: checkIsEmpty, + stringEncoder: ctx.EncoderOf(reflect2.TypeOf("")), + } + return encoder + } + if typ.Implements(textMarshalerType) { + checkIsEmpty := createCheckIsEmpty(ctx, typ) + var encoder ValEncoder = &textMarshalerEncoder{ + valType: typ, + stringEncoder: ctx.EncoderOf(reflect2.TypeOf("")), + checkIsEmpty: checkIsEmpty, + } + return encoder + } + // if prefix is empty, the type is the root type + if ctx.prefix != "" && ptrType.Implements(textMarshalerType) { + checkIsEmpty := createCheckIsEmpty(ctx, ptrType) + var encoder ValEncoder = &textMarshalerEncoder{ + valType: ptrType, + stringEncoder: ctx.EncoderOf(reflect2.TypeOf("")), + checkIsEmpty: checkIsEmpty, + } + return &referenceEncoder{encoder} + } + return nil +} + +type marshalerEncoder struct { + checkIsEmpty checkIsEmpty + valType reflect2.Type +} + +func (encoder *marshalerEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + obj := encoder.valType.UnsafeIndirect(ptr) + if encoder.valType.IsNullable() && reflect2.IsNil(obj) { + stream.WriteNil() + return + } + marshaler := obj.(json.Marshaler) + bytes, err := marshaler.MarshalJSON() + if err != nil { + stream.Error = err + } else { + stream.Write(bytes) + } +} + +func (encoder *marshalerEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return encoder.checkIsEmpty.IsEmpty(ptr) +} + +type directMarshalerEncoder struct { + checkIsEmpty checkIsEmpty +} + +func (encoder *directMarshalerEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + marshaler := *(*json.Marshaler)(ptr) + if marshaler == nil { + stream.WriteNil() + return + } + bytes, err := marshaler.MarshalJSON() + if err != nil { + stream.Error = err + } else { + stream.Write(bytes) + } +} + +func (encoder *directMarshalerEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return encoder.checkIsEmpty.IsEmpty(ptr) +} + +type textMarshalerEncoder struct { + valType reflect2.Type + stringEncoder ValEncoder + checkIsEmpty checkIsEmpty +} + +func (encoder *textMarshalerEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + obj := encoder.valType.UnsafeIndirect(ptr) + if encoder.valType.IsNullable() && reflect2.IsNil(obj) { + stream.WriteNil() + return + } + marshaler := (obj).(encoding.TextMarshaler) + bytes, err := marshaler.MarshalText() + if err != nil { + stream.Error = err + } else { + str := string(bytes) + encoder.stringEncoder.Encode(unsafe.Pointer(&str), stream) + } +} + +func (encoder *textMarshalerEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return encoder.checkIsEmpty.IsEmpty(ptr) +} + +type directTextMarshalerEncoder struct { + stringEncoder ValEncoder + checkIsEmpty checkIsEmpty +} + +func (encoder *directTextMarshalerEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + marshaler := *(*encoding.TextMarshaler)(ptr) + if marshaler == nil { + stream.WriteNil() + return + } + bytes, err := marshaler.MarshalText() + if err != nil { + stream.Error = err + } else { + str := string(bytes) + encoder.stringEncoder.Encode(unsafe.Pointer(&str), stream) + } +} + +func (encoder *directTextMarshalerEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return encoder.checkIsEmpty.IsEmpty(ptr) +} + +type unmarshalerDecoder struct { + valType reflect2.Type +} + +func (decoder *unmarshalerDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + valType := decoder.valType + obj := valType.UnsafeIndirect(ptr) + unmarshaler := obj.(json.Unmarshaler) + iter.nextToken() + iter.unreadByte() // skip spaces + bytes := iter.SkipAndReturnBytes() + err := unmarshaler.UnmarshalJSON(bytes) + if err != nil { + iter.ReportError("unmarshalerDecoder", err.Error()) + } +} + +type textUnmarshalerDecoder struct { + valType reflect2.Type +} + +func (decoder *textUnmarshalerDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + valType := decoder.valType + obj := valType.UnsafeIndirect(ptr) + if reflect2.IsNil(obj) { + ptrType := valType.(*reflect2.UnsafePtrType) + elemType := ptrType.Elem() + elem := elemType.UnsafeNew() + ptrType.UnsafeSet(ptr, unsafe.Pointer(&elem)) + obj = valType.UnsafeIndirect(ptr) + } + unmarshaler := (obj).(encoding.TextUnmarshaler) + str := iter.ReadString() + err := unmarshaler.UnmarshalText([]byte(str)) + if err != nil { + iter.ReportError("textUnmarshalerDecoder", err.Error()) + } +} diff --git a/vendor/github.com/json-iterator/go/reflect_native.go b/vendor/github.com/json-iterator/go/reflect_native.go new file mode 100644 index 000000000..9042eb0cb --- /dev/null +++ b/vendor/github.com/json-iterator/go/reflect_native.go @@ -0,0 +1,451 @@ +package jsoniter + +import ( + "encoding/base64" + "reflect" + "strconv" + "unsafe" + + "github.com/modern-go/reflect2" +) + +const ptrSize = 32 << uintptr(^uintptr(0)>>63) + +func createEncoderOfNative(ctx *ctx, typ reflect2.Type) ValEncoder { + if typ.Kind() == reflect.Slice && typ.(reflect2.SliceType).Elem().Kind() == reflect.Uint8 { + sliceDecoder := decoderOfSlice(ctx, typ) + return &base64Codec{sliceDecoder: sliceDecoder} + } + typeName := typ.String() + kind := typ.Kind() + switch kind { + case reflect.String: + if typeName != "string" { + return encoderOfType(ctx, reflect2.TypeOfPtr((*string)(nil)).Elem()) + } + return &stringCodec{} + case reflect.Int: + if typeName != "int" { + return encoderOfType(ctx, reflect2.TypeOfPtr((*int)(nil)).Elem()) + } + if strconv.IntSize == 32 { + return &int32Codec{} + } + return &int64Codec{} + case reflect.Int8: + if typeName != "int8" { + return encoderOfType(ctx, reflect2.TypeOfPtr((*int8)(nil)).Elem()) + } + return &int8Codec{} + case reflect.Int16: + if typeName != "int16" { + return encoderOfType(ctx, reflect2.TypeOfPtr((*int16)(nil)).Elem()) + } + return &int16Codec{} + case reflect.Int32: + if typeName != "int32" { + return encoderOfType(ctx, reflect2.TypeOfPtr((*int32)(nil)).Elem()) + } + return &int32Codec{} + case reflect.Int64: + if typeName != "int64" { + return encoderOfType(ctx, reflect2.TypeOfPtr((*int64)(nil)).Elem()) + } + return &int64Codec{} + case reflect.Uint: + if typeName != "uint" { + return encoderOfType(ctx, reflect2.TypeOfPtr((*uint)(nil)).Elem()) + } + if strconv.IntSize == 32 { + return &uint32Codec{} + } + return &uint64Codec{} + case reflect.Uint8: + if typeName != "uint8" { + return encoderOfType(ctx, reflect2.TypeOfPtr((*uint8)(nil)).Elem()) + } + return &uint8Codec{} + case reflect.Uint16: + if typeName != "uint16" { + return encoderOfType(ctx, reflect2.TypeOfPtr((*uint16)(nil)).Elem()) + } + return &uint16Codec{} + case reflect.Uint32: + if typeName != "uint32" { + return encoderOfType(ctx, reflect2.TypeOfPtr((*uint32)(nil)).Elem()) + } + return &uint32Codec{} + case reflect.Uintptr: + if typeName != "uintptr" { + return encoderOfType(ctx, reflect2.TypeOfPtr((*uintptr)(nil)).Elem()) + } + if ptrSize == 32 { + return &uint32Codec{} + } + return &uint64Codec{} + case reflect.Uint64: + if typeName != "uint64" { + return encoderOfType(ctx, reflect2.TypeOfPtr((*uint64)(nil)).Elem()) + } + return &uint64Codec{} + case reflect.Float32: + if typeName != "float32" { + return encoderOfType(ctx, reflect2.TypeOfPtr((*float32)(nil)).Elem()) + } + return &float32Codec{} + case reflect.Float64: + if typeName != "float64" { + return encoderOfType(ctx, reflect2.TypeOfPtr((*float64)(nil)).Elem()) + } + return &float64Codec{} + case reflect.Bool: + if typeName != "bool" { + return encoderOfType(ctx, reflect2.TypeOfPtr((*bool)(nil)).Elem()) + } + return &boolCodec{} + } + return nil +} + +func createDecoderOfNative(ctx *ctx, typ reflect2.Type) ValDecoder { + if typ.Kind() == reflect.Slice && typ.(reflect2.SliceType).Elem().Kind() == reflect.Uint8 { + sliceDecoder := decoderOfSlice(ctx, typ) + return &base64Codec{sliceDecoder: sliceDecoder} + } + typeName := typ.String() + switch typ.Kind() { + case reflect.String: + if typeName != "string" { + return decoderOfType(ctx, reflect2.TypeOfPtr((*string)(nil)).Elem()) + } + return &stringCodec{} + case reflect.Int: + if typeName != "int" { + return decoderOfType(ctx, reflect2.TypeOfPtr((*int)(nil)).Elem()) + } + if strconv.IntSize == 32 { + return &int32Codec{} + } + return &int64Codec{} + case reflect.Int8: + if typeName != "int8" { + return decoderOfType(ctx, reflect2.TypeOfPtr((*int8)(nil)).Elem()) + } + return &int8Codec{} + case reflect.Int16: + if typeName != "int16" { + return decoderOfType(ctx, reflect2.TypeOfPtr((*int16)(nil)).Elem()) + } + return &int16Codec{} + case reflect.Int32: + if typeName != "int32" { + return decoderOfType(ctx, reflect2.TypeOfPtr((*int32)(nil)).Elem()) + } + return &int32Codec{} + case reflect.Int64: + if typeName != "int64" { + return decoderOfType(ctx, reflect2.TypeOfPtr((*int64)(nil)).Elem()) + } + return &int64Codec{} + case reflect.Uint: + if typeName != "uint" { + return decoderOfType(ctx, reflect2.TypeOfPtr((*uint)(nil)).Elem()) + } + if strconv.IntSize == 32 { + return &uint32Codec{} + } + return &uint64Codec{} + case reflect.Uint8: + if typeName != "uint8" { + return decoderOfType(ctx, reflect2.TypeOfPtr((*uint8)(nil)).Elem()) + } + return &uint8Codec{} + case reflect.Uint16: + if typeName != "uint16" { + return decoderOfType(ctx, reflect2.TypeOfPtr((*uint16)(nil)).Elem()) + } + return &uint16Codec{} + case reflect.Uint32: + if typeName != "uint32" { + return decoderOfType(ctx, reflect2.TypeOfPtr((*uint32)(nil)).Elem()) + } + return &uint32Codec{} + case reflect.Uintptr: + if typeName != "uintptr" { + return decoderOfType(ctx, reflect2.TypeOfPtr((*uintptr)(nil)).Elem()) + } + if ptrSize == 32 { + return &uint32Codec{} + } + return &uint64Codec{} + case reflect.Uint64: + if typeName != "uint64" { + return decoderOfType(ctx, reflect2.TypeOfPtr((*uint64)(nil)).Elem()) + } + return &uint64Codec{} + case reflect.Float32: + if typeName != "float32" { + return decoderOfType(ctx, reflect2.TypeOfPtr((*float32)(nil)).Elem()) + } + return &float32Codec{} + case reflect.Float64: + if typeName != "float64" { + return decoderOfType(ctx, reflect2.TypeOfPtr((*float64)(nil)).Elem()) + } + return &float64Codec{} + case reflect.Bool: + if typeName != "bool" { + return decoderOfType(ctx, reflect2.TypeOfPtr((*bool)(nil)).Elem()) + } + return &boolCodec{} + } + return nil +} + +type stringCodec struct { +} + +func (codec *stringCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { + *((*string)(ptr)) = iter.ReadString() +} + +func (codec *stringCodec) Encode(ptr unsafe.Pointer, stream *Stream) { + str := *((*string)(ptr)) + stream.WriteString(str) +} + +func (codec *stringCodec) IsEmpty(ptr unsafe.Pointer) bool { + return *((*string)(ptr)) == "" +} + +type int8Codec struct { +} + +func (codec *int8Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.ReadNil() { + *((*int8)(ptr)) = iter.ReadInt8() + } +} + +func (codec *int8Codec) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteInt8(*((*int8)(ptr))) +} + +func (codec *int8Codec) IsEmpty(ptr unsafe.Pointer) bool { + return *((*int8)(ptr)) == 0 +} + +type int16Codec struct { +} + +func (codec *int16Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.ReadNil() { + *((*int16)(ptr)) = iter.ReadInt16() + } +} + +func (codec *int16Codec) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteInt16(*((*int16)(ptr))) +} + +func (codec *int16Codec) IsEmpty(ptr unsafe.Pointer) bool { + return *((*int16)(ptr)) == 0 +} + +type int32Codec struct { +} + +func (codec *int32Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.ReadNil() { + *((*int32)(ptr)) = iter.ReadInt32() + } +} + +func (codec *int32Codec) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteInt32(*((*int32)(ptr))) +} + +func (codec *int32Codec) IsEmpty(ptr unsafe.Pointer) bool { + return *((*int32)(ptr)) == 0 +} + +type int64Codec struct { +} + +func (codec *int64Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.ReadNil() { + *((*int64)(ptr)) = iter.ReadInt64() + } +} + +func (codec *int64Codec) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteInt64(*((*int64)(ptr))) +} + +func (codec *int64Codec) IsEmpty(ptr unsafe.Pointer) bool { + return *((*int64)(ptr)) == 0 +} + +type uint8Codec struct { +} + +func (codec *uint8Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.ReadNil() { + *((*uint8)(ptr)) = iter.ReadUint8() + } +} + +func (codec *uint8Codec) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteUint8(*((*uint8)(ptr))) +} + +func (codec *uint8Codec) IsEmpty(ptr unsafe.Pointer) bool { + return *((*uint8)(ptr)) == 0 +} + +type uint16Codec struct { +} + +func (codec *uint16Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.ReadNil() { + *((*uint16)(ptr)) = iter.ReadUint16() + } +} + +func (codec *uint16Codec) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteUint16(*((*uint16)(ptr))) +} + +func (codec *uint16Codec) IsEmpty(ptr unsafe.Pointer) bool { + return *((*uint16)(ptr)) == 0 +} + +type uint32Codec struct { +} + +func (codec *uint32Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.ReadNil() { + *((*uint32)(ptr)) = iter.ReadUint32() + } +} + +func (codec *uint32Codec) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteUint32(*((*uint32)(ptr))) +} + +func (codec *uint32Codec) IsEmpty(ptr unsafe.Pointer) bool { + return *((*uint32)(ptr)) == 0 +} + +type uint64Codec struct { +} + +func (codec *uint64Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.ReadNil() { + *((*uint64)(ptr)) = iter.ReadUint64() + } +} + +func (codec *uint64Codec) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteUint64(*((*uint64)(ptr))) +} + +func (codec *uint64Codec) IsEmpty(ptr unsafe.Pointer) bool { + return *((*uint64)(ptr)) == 0 +} + +type float32Codec struct { +} + +func (codec *float32Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.ReadNil() { + *((*float32)(ptr)) = iter.ReadFloat32() + } +} + +func (codec *float32Codec) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteFloat32(*((*float32)(ptr))) +} + +func (codec *float32Codec) IsEmpty(ptr unsafe.Pointer) bool { + return *((*float32)(ptr)) == 0 +} + +type float64Codec struct { +} + +func (codec *float64Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.ReadNil() { + *((*float64)(ptr)) = iter.ReadFloat64() + } +} + +func (codec *float64Codec) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteFloat64(*((*float64)(ptr))) +} + +func (codec *float64Codec) IsEmpty(ptr unsafe.Pointer) bool { + return *((*float64)(ptr)) == 0 +} + +type boolCodec struct { +} + +func (codec *boolCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.ReadNil() { + *((*bool)(ptr)) = iter.ReadBool() + } +} + +func (codec *boolCodec) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteBool(*((*bool)(ptr))) +} + +func (codec *boolCodec) IsEmpty(ptr unsafe.Pointer) bool { + return !(*((*bool)(ptr))) +} + +type base64Codec struct { + sliceType *reflect2.UnsafeSliceType + sliceDecoder ValDecoder +} + +func (codec *base64Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { + if iter.ReadNil() { + codec.sliceType.UnsafeSetNil(ptr) + return + } + switch iter.WhatIsNext() { + case StringValue: + src := iter.ReadString() + dst, err := base64.StdEncoding.DecodeString(src) + if err != nil { + iter.ReportError("decode base64", err.Error()) + } else { + codec.sliceType.UnsafeSet(ptr, unsafe.Pointer(&dst)) + } + case ArrayValue: + codec.sliceDecoder.Decode(ptr, iter) + default: + iter.ReportError("base64Codec", "invalid input") + } +} + +func (codec *base64Codec) Encode(ptr unsafe.Pointer, stream *Stream) { + src := *((*[]byte)(ptr)) + if len(src) == 0 { + stream.WriteNil() + return + } + encoding := base64.StdEncoding + stream.writeByte('"') + size := encoding.EncodedLen(len(src)) + buf := make([]byte, size) + encoding.Encode(buf, src) + stream.buf = append(stream.buf, buf...) + stream.writeByte('"') +} + +func (codec *base64Codec) IsEmpty(ptr unsafe.Pointer) bool { + return len(*((*[]byte)(ptr))) == 0 +} diff --git a/vendor/github.com/json-iterator/go/reflect_optional.go b/vendor/github.com/json-iterator/go/reflect_optional.go new file mode 100644 index 000000000..43ec71d6d --- /dev/null +++ b/vendor/github.com/json-iterator/go/reflect_optional.go @@ -0,0 +1,133 @@ +package jsoniter + +import ( + "github.com/modern-go/reflect2" + "reflect" + "unsafe" +) + +func decoderOfOptional(ctx *ctx, typ reflect2.Type) ValDecoder { + ptrType := typ.(*reflect2.UnsafePtrType) + elemType := ptrType.Elem() + decoder := decoderOfType(ctx, elemType) + if ctx.prefix == "" && elemType.Kind() == reflect.Ptr { + return &dereferenceDecoder{elemType, decoder} + } + return &OptionalDecoder{elemType, decoder} +} + +func encoderOfOptional(ctx *ctx, typ reflect2.Type) ValEncoder { + ptrType := typ.(*reflect2.UnsafePtrType) + elemType := ptrType.Elem() + elemEncoder := encoderOfType(ctx, elemType) + encoder := &OptionalEncoder{elemEncoder} + return encoder +} + +type OptionalDecoder struct { + ValueType reflect2.Type + ValueDecoder ValDecoder +} + +func (decoder *OptionalDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + if iter.ReadNil() { + *((*unsafe.Pointer)(ptr)) = nil + } else { + if *((*unsafe.Pointer)(ptr)) == nil { + //pointer to null, we have to allocate memory to hold the value + newPtr := decoder.ValueType.UnsafeNew() + decoder.ValueDecoder.Decode(newPtr, iter) + *((*unsafe.Pointer)(ptr)) = newPtr + } else { + //reuse existing instance + decoder.ValueDecoder.Decode(*((*unsafe.Pointer)(ptr)), iter) + } + } +} + +type dereferenceDecoder struct { + // only to deference a pointer + valueType reflect2.Type + valueDecoder ValDecoder +} + +func (decoder *dereferenceDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + if *((*unsafe.Pointer)(ptr)) == nil { + //pointer to null, we have to allocate memory to hold the value + newPtr := decoder.valueType.UnsafeNew() + decoder.valueDecoder.Decode(newPtr, iter) + *((*unsafe.Pointer)(ptr)) = newPtr + } else { + //reuse existing instance + decoder.valueDecoder.Decode(*((*unsafe.Pointer)(ptr)), iter) + } +} + +type OptionalEncoder struct { + ValueEncoder ValEncoder +} + +func (encoder *OptionalEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + if *((*unsafe.Pointer)(ptr)) == nil { + stream.WriteNil() + } else { + encoder.ValueEncoder.Encode(*((*unsafe.Pointer)(ptr)), stream) + } +} + +func (encoder *OptionalEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return *((*unsafe.Pointer)(ptr)) == nil +} + +type dereferenceEncoder struct { + ValueEncoder ValEncoder +} + +func (encoder *dereferenceEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + if *((*unsafe.Pointer)(ptr)) == nil { + stream.WriteNil() + } else { + encoder.ValueEncoder.Encode(*((*unsafe.Pointer)(ptr)), stream) + } +} + +func (encoder *dereferenceEncoder) IsEmpty(ptr unsafe.Pointer) bool { + dePtr := *((*unsafe.Pointer)(ptr)) + if dePtr == nil { + return true + } + return encoder.ValueEncoder.IsEmpty(dePtr) +} + +func (encoder *dereferenceEncoder) IsEmbeddedPtrNil(ptr unsafe.Pointer) bool { + deReferenced := *((*unsafe.Pointer)(ptr)) + if deReferenced == nil { + return true + } + isEmbeddedPtrNil, converted := encoder.ValueEncoder.(IsEmbeddedPtrNil) + if !converted { + return false + } + fieldPtr := unsafe.Pointer(deReferenced) + return isEmbeddedPtrNil.IsEmbeddedPtrNil(fieldPtr) +} + +type referenceEncoder struct { + encoder ValEncoder +} + +func (encoder *referenceEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + encoder.encoder.Encode(unsafe.Pointer(&ptr), stream) +} + +func (encoder *referenceEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return encoder.encoder.IsEmpty(unsafe.Pointer(&ptr)) +} + +type referenceDecoder struct { + decoder ValDecoder +} + +func (decoder *referenceDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + decoder.decoder.Decode(unsafe.Pointer(&ptr), iter) +} diff --git a/vendor/github.com/json-iterator/go/reflect_slice.go b/vendor/github.com/json-iterator/go/reflect_slice.go new file mode 100644 index 000000000..9441d79df --- /dev/null +++ b/vendor/github.com/json-iterator/go/reflect_slice.go @@ -0,0 +1,99 @@ +package jsoniter + +import ( + "fmt" + "github.com/modern-go/reflect2" + "io" + "unsafe" +) + +func decoderOfSlice(ctx *ctx, typ reflect2.Type) ValDecoder { + sliceType := typ.(*reflect2.UnsafeSliceType) + decoder := decoderOfType(ctx.append("[sliceElem]"), sliceType.Elem()) + return &sliceDecoder{sliceType, decoder} +} + +func encoderOfSlice(ctx *ctx, typ reflect2.Type) ValEncoder { + sliceType := typ.(*reflect2.UnsafeSliceType) + encoder := encoderOfType(ctx.append("[sliceElem]"), sliceType.Elem()) + return &sliceEncoder{sliceType, encoder} +} + +type sliceEncoder struct { + sliceType *reflect2.UnsafeSliceType + elemEncoder ValEncoder +} + +func (encoder *sliceEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + if encoder.sliceType.UnsafeIsNil(ptr) { + stream.WriteNil() + return + } + length := encoder.sliceType.UnsafeLengthOf(ptr) + if length == 0 { + stream.WriteEmptyArray() + return + } + stream.WriteArrayStart() + encoder.elemEncoder.Encode(encoder.sliceType.UnsafeGetIndex(ptr, 0), stream) + for i := 1; i < length; i++ { + stream.WriteMore() + elemPtr := encoder.sliceType.UnsafeGetIndex(ptr, i) + encoder.elemEncoder.Encode(elemPtr, stream) + } + stream.WriteArrayEnd() + if stream.Error != nil && stream.Error != io.EOF { + stream.Error = fmt.Errorf("%v: %s", encoder.sliceType, stream.Error.Error()) + } +} + +func (encoder *sliceEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return encoder.sliceType.UnsafeLengthOf(ptr) == 0 +} + +type sliceDecoder struct { + sliceType *reflect2.UnsafeSliceType + elemDecoder ValDecoder +} + +func (decoder *sliceDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + decoder.doDecode(ptr, iter) + if iter.Error != nil && iter.Error != io.EOF { + iter.Error = fmt.Errorf("%v: %s", decoder.sliceType, iter.Error.Error()) + } +} + +func (decoder *sliceDecoder) doDecode(ptr unsafe.Pointer, iter *Iterator) { + c := iter.nextToken() + sliceType := decoder.sliceType + if c == 'n' { + iter.skipThreeBytes('u', 'l', 'l') + sliceType.UnsafeSetNil(ptr) + return + } + if c != '[' { + iter.ReportError("decode slice", "expect [ or n, but found "+string([]byte{c})) + return + } + c = iter.nextToken() + if c == ']' { + sliceType.UnsafeSet(ptr, sliceType.UnsafeMakeSlice(0, 0)) + return + } + iter.unreadByte() + sliceType.UnsafeGrow(ptr, 1) + elemPtr := sliceType.UnsafeGetIndex(ptr, 0) + decoder.elemDecoder.Decode(elemPtr, iter) + length := 1 + for c = iter.nextToken(); c == ','; c = iter.nextToken() { + idx := length + length += 1 + sliceType.UnsafeGrow(ptr, length) + elemPtr = sliceType.UnsafeGetIndex(ptr, idx) + decoder.elemDecoder.Decode(elemPtr, iter) + } + if c != ']' { + iter.ReportError("decode slice", "expect ], but found "+string([]byte{c})) + return + } +} diff --git a/vendor/github.com/json-iterator/go/reflect_struct_decoder.go b/vendor/github.com/json-iterator/go/reflect_struct_decoder.go new file mode 100644 index 000000000..355d2d116 --- /dev/null +++ b/vendor/github.com/json-iterator/go/reflect_struct_decoder.go @@ -0,0 +1,1048 @@ +package jsoniter + +import ( + "fmt" + "io" + "strings" + "unsafe" + + "github.com/modern-go/reflect2" +) + +func decoderOfStruct(ctx *ctx, typ reflect2.Type) ValDecoder { + bindings := map[string]*Binding{} + structDescriptor := describeStruct(ctx, typ) + for _, binding := range structDescriptor.Fields { + for _, fromName := range binding.FromNames { + old := bindings[fromName] + if old == nil { + bindings[fromName] = binding + continue + } + ignoreOld, ignoreNew := resolveConflictBinding(ctx.frozenConfig, old, binding) + if ignoreOld { + delete(bindings, fromName) + } + if !ignoreNew { + bindings[fromName] = binding + } + } + } + fields := map[string]*structFieldDecoder{} + for k, binding := range bindings { + fields[k] = binding.Decoder.(*structFieldDecoder) + } + + if !ctx.caseSensitive() { + for k, binding := range bindings { + if _, found := fields[strings.ToLower(k)]; !found { + fields[strings.ToLower(k)] = binding.Decoder.(*structFieldDecoder) + } + } + } + + return createStructDecoder(ctx, typ, fields) +} + +func createStructDecoder(ctx *ctx, typ reflect2.Type, fields map[string]*structFieldDecoder) ValDecoder { + if ctx.disallowUnknownFields { + return &generalStructDecoder{typ: typ, fields: fields, disallowUnknownFields: true} + } + knownHash := map[int64]struct{}{ + 0: {}, + } + + switch len(fields) { + case 0: + return &skipObjectDecoder{typ} + case 1: + for fieldName, fieldDecoder := range fields { + fieldHash := calcHash(fieldName, ctx.caseSensitive()) + _, known := knownHash[fieldHash] + if known { + return &generalStructDecoder{typ, fields, false} + } + knownHash[fieldHash] = struct{}{} + return &oneFieldStructDecoder{typ, fieldHash, fieldDecoder} + } + case 2: + var fieldHash1 int64 + var fieldHash2 int64 + var fieldDecoder1 *structFieldDecoder + var fieldDecoder2 *structFieldDecoder + for fieldName, fieldDecoder := range fields { + fieldHash := calcHash(fieldName, ctx.caseSensitive()) + _, known := knownHash[fieldHash] + if known { + return &generalStructDecoder{typ, fields, false} + } + knownHash[fieldHash] = struct{}{} + if fieldHash1 == 0 { + fieldHash1 = fieldHash + fieldDecoder1 = fieldDecoder + } else { + fieldHash2 = fieldHash + fieldDecoder2 = fieldDecoder + } + } + return &twoFieldsStructDecoder{typ, fieldHash1, fieldDecoder1, fieldHash2, fieldDecoder2} + case 3: + var fieldName1 int64 + var fieldName2 int64 + var fieldName3 int64 + var fieldDecoder1 *structFieldDecoder + var fieldDecoder2 *structFieldDecoder + var fieldDecoder3 *structFieldDecoder + for fieldName, fieldDecoder := range fields { + fieldHash := calcHash(fieldName, ctx.caseSensitive()) + _, known := knownHash[fieldHash] + if known { + return &generalStructDecoder{typ, fields, false} + } + knownHash[fieldHash] = struct{}{} + if fieldName1 == 0 { + fieldName1 = fieldHash + fieldDecoder1 = fieldDecoder + } else if fieldName2 == 0 { + fieldName2 = fieldHash + fieldDecoder2 = fieldDecoder + } else { + fieldName3 = fieldHash + fieldDecoder3 = fieldDecoder + } + } + return &threeFieldsStructDecoder{typ, + fieldName1, fieldDecoder1, + fieldName2, fieldDecoder2, + fieldName3, fieldDecoder3} + case 4: + var fieldName1 int64 + var fieldName2 int64 + var fieldName3 int64 + var fieldName4 int64 + var fieldDecoder1 *structFieldDecoder + var fieldDecoder2 *structFieldDecoder + var fieldDecoder3 *structFieldDecoder + var fieldDecoder4 *structFieldDecoder + for fieldName, fieldDecoder := range fields { + fieldHash := calcHash(fieldName, ctx.caseSensitive()) + _, known := knownHash[fieldHash] + if known { + return &generalStructDecoder{typ, fields, false} + } + knownHash[fieldHash] = struct{}{} + if fieldName1 == 0 { + fieldName1 = fieldHash + fieldDecoder1 = fieldDecoder + } else if fieldName2 == 0 { + fieldName2 = fieldHash + fieldDecoder2 = fieldDecoder + } else if fieldName3 == 0 { + fieldName3 = fieldHash + fieldDecoder3 = fieldDecoder + } else { + fieldName4 = fieldHash + fieldDecoder4 = fieldDecoder + } + } + return &fourFieldsStructDecoder{typ, + fieldName1, fieldDecoder1, + fieldName2, fieldDecoder2, + fieldName3, fieldDecoder3, + fieldName4, fieldDecoder4} + case 5: + var fieldName1 int64 + var fieldName2 int64 + var fieldName3 int64 + var fieldName4 int64 + var fieldName5 int64 + var fieldDecoder1 *structFieldDecoder + var fieldDecoder2 *structFieldDecoder + var fieldDecoder3 *structFieldDecoder + var fieldDecoder4 *structFieldDecoder + var fieldDecoder5 *structFieldDecoder + for fieldName, fieldDecoder := range fields { + fieldHash := calcHash(fieldName, ctx.caseSensitive()) + _, known := knownHash[fieldHash] + if known { + return &generalStructDecoder{typ, fields, false} + } + knownHash[fieldHash] = struct{}{} + if fieldName1 == 0 { + fieldName1 = fieldHash + fieldDecoder1 = fieldDecoder + } else if fieldName2 == 0 { + fieldName2 = fieldHash + fieldDecoder2 = fieldDecoder + } else if fieldName3 == 0 { + fieldName3 = fieldHash + fieldDecoder3 = fieldDecoder + } else if fieldName4 == 0 { + fieldName4 = fieldHash + fieldDecoder4 = fieldDecoder + } else { + fieldName5 = fieldHash + fieldDecoder5 = fieldDecoder + } + } + return &fiveFieldsStructDecoder{typ, + fieldName1, fieldDecoder1, + fieldName2, fieldDecoder2, + fieldName3, fieldDecoder3, + fieldName4, fieldDecoder4, + fieldName5, fieldDecoder5} + case 6: + var fieldName1 int64 + var fieldName2 int64 + var fieldName3 int64 + var fieldName4 int64 + var fieldName5 int64 + var fieldName6 int64 + var fieldDecoder1 *structFieldDecoder + var fieldDecoder2 *structFieldDecoder + var fieldDecoder3 *structFieldDecoder + var fieldDecoder4 *structFieldDecoder + var fieldDecoder5 *structFieldDecoder + var fieldDecoder6 *structFieldDecoder + for fieldName, fieldDecoder := range fields { + fieldHash := calcHash(fieldName, ctx.caseSensitive()) + _, known := knownHash[fieldHash] + if known { + return &generalStructDecoder{typ, fields, false} + } + knownHash[fieldHash] = struct{}{} + if fieldName1 == 0 { + fieldName1 = fieldHash + fieldDecoder1 = fieldDecoder + } else if fieldName2 == 0 { + fieldName2 = fieldHash + fieldDecoder2 = fieldDecoder + } else if fieldName3 == 0 { + fieldName3 = fieldHash + fieldDecoder3 = fieldDecoder + } else if fieldName4 == 0 { + fieldName4 = fieldHash + fieldDecoder4 = fieldDecoder + } else if fieldName5 == 0 { + fieldName5 = fieldHash + fieldDecoder5 = fieldDecoder + } else { + fieldName6 = fieldHash + fieldDecoder6 = fieldDecoder + } + } + return &sixFieldsStructDecoder{typ, + fieldName1, fieldDecoder1, + fieldName2, fieldDecoder2, + fieldName3, fieldDecoder3, + fieldName4, fieldDecoder4, + fieldName5, fieldDecoder5, + fieldName6, fieldDecoder6} + case 7: + var fieldName1 int64 + var fieldName2 int64 + var fieldName3 int64 + var fieldName4 int64 + var fieldName5 int64 + var fieldName6 int64 + var fieldName7 int64 + var fieldDecoder1 *structFieldDecoder + var fieldDecoder2 *structFieldDecoder + var fieldDecoder3 *structFieldDecoder + var fieldDecoder4 *structFieldDecoder + var fieldDecoder5 *structFieldDecoder + var fieldDecoder6 *structFieldDecoder + var fieldDecoder7 *structFieldDecoder + for fieldName, fieldDecoder := range fields { + fieldHash := calcHash(fieldName, ctx.caseSensitive()) + _, known := knownHash[fieldHash] + if known { + return &generalStructDecoder{typ, fields, false} + } + knownHash[fieldHash] = struct{}{} + if fieldName1 == 0 { + fieldName1 = fieldHash + fieldDecoder1 = fieldDecoder + } else if fieldName2 == 0 { + fieldName2 = fieldHash + fieldDecoder2 = fieldDecoder + } else if fieldName3 == 0 { + fieldName3 = fieldHash + fieldDecoder3 = fieldDecoder + } else if fieldName4 == 0 { + fieldName4 = fieldHash + fieldDecoder4 = fieldDecoder + } else if fieldName5 == 0 { + fieldName5 = fieldHash + fieldDecoder5 = fieldDecoder + } else if fieldName6 == 0 { + fieldName6 = fieldHash + fieldDecoder6 = fieldDecoder + } else { + fieldName7 = fieldHash + fieldDecoder7 = fieldDecoder + } + } + return &sevenFieldsStructDecoder{typ, + fieldName1, fieldDecoder1, + fieldName2, fieldDecoder2, + fieldName3, fieldDecoder3, + fieldName4, fieldDecoder4, + fieldName5, fieldDecoder5, + fieldName6, fieldDecoder6, + fieldName7, fieldDecoder7} + case 8: + var fieldName1 int64 + var fieldName2 int64 + var fieldName3 int64 + var fieldName4 int64 + var fieldName5 int64 + var fieldName6 int64 + var fieldName7 int64 + var fieldName8 int64 + var fieldDecoder1 *structFieldDecoder + var fieldDecoder2 *structFieldDecoder + var fieldDecoder3 *structFieldDecoder + var fieldDecoder4 *structFieldDecoder + var fieldDecoder5 *structFieldDecoder + var fieldDecoder6 *structFieldDecoder + var fieldDecoder7 *structFieldDecoder + var fieldDecoder8 *structFieldDecoder + for fieldName, fieldDecoder := range fields { + fieldHash := calcHash(fieldName, ctx.caseSensitive()) + _, known := knownHash[fieldHash] + if known { + return &generalStructDecoder{typ, fields, false} + } + knownHash[fieldHash] = struct{}{} + if fieldName1 == 0 { + fieldName1 = fieldHash + fieldDecoder1 = fieldDecoder + } else if fieldName2 == 0 { + fieldName2 = fieldHash + fieldDecoder2 = fieldDecoder + } else if fieldName3 == 0 { + fieldName3 = fieldHash + fieldDecoder3 = fieldDecoder + } else if fieldName4 == 0 { + fieldName4 = fieldHash + fieldDecoder4 = fieldDecoder + } else if fieldName5 == 0 { + fieldName5 = fieldHash + fieldDecoder5 = fieldDecoder + } else if fieldName6 == 0 { + fieldName6 = fieldHash + fieldDecoder6 = fieldDecoder + } else if fieldName7 == 0 { + fieldName7 = fieldHash + fieldDecoder7 = fieldDecoder + } else { + fieldName8 = fieldHash + fieldDecoder8 = fieldDecoder + } + } + return &eightFieldsStructDecoder{typ, + fieldName1, fieldDecoder1, + fieldName2, fieldDecoder2, + fieldName3, fieldDecoder3, + fieldName4, fieldDecoder4, + fieldName5, fieldDecoder5, + fieldName6, fieldDecoder6, + fieldName7, fieldDecoder7, + fieldName8, fieldDecoder8} + case 9: + var fieldName1 int64 + var fieldName2 int64 + var fieldName3 int64 + var fieldName4 int64 + var fieldName5 int64 + var fieldName6 int64 + var fieldName7 int64 + var fieldName8 int64 + var fieldName9 int64 + var fieldDecoder1 *structFieldDecoder + var fieldDecoder2 *structFieldDecoder + var fieldDecoder3 *structFieldDecoder + var fieldDecoder4 *structFieldDecoder + var fieldDecoder5 *structFieldDecoder + var fieldDecoder6 *structFieldDecoder + var fieldDecoder7 *structFieldDecoder + var fieldDecoder8 *structFieldDecoder + var fieldDecoder9 *structFieldDecoder + for fieldName, fieldDecoder := range fields { + fieldHash := calcHash(fieldName, ctx.caseSensitive()) + _, known := knownHash[fieldHash] + if known { + return &generalStructDecoder{typ, fields, false} + } + knownHash[fieldHash] = struct{}{} + if fieldName1 == 0 { + fieldName1 = fieldHash + fieldDecoder1 = fieldDecoder + } else if fieldName2 == 0 { + fieldName2 = fieldHash + fieldDecoder2 = fieldDecoder + } else if fieldName3 == 0 { + fieldName3 = fieldHash + fieldDecoder3 = fieldDecoder + } else if fieldName4 == 0 { + fieldName4 = fieldHash + fieldDecoder4 = fieldDecoder + } else if fieldName5 == 0 { + fieldName5 = fieldHash + fieldDecoder5 = fieldDecoder + } else if fieldName6 == 0 { + fieldName6 = fieldHash + fieldDecoder6 = fieldDecoder + } else if fieldName7 == 0 { + fieldName7 = fieldHash + fieldDecoder7 = fieldDecoder + } else if fieldName8 == 0 { + fieldName8 = fieldHash + fieldDecoder8 = fieldDecoder + } else { + fieldName9 = fieldHash + fieldDecoder9 = fieldDecoder + } + } + return &nineFieldsStructDecoder{typ, + fieldName1, fieldDecoder1, + fieldName2, fieldDecoder2, + fieldName3, fieldDecoder3, + fieldName4, fieldDecoder4, + fieldName5, fieldDecoder5, + fieldName6, fieldDecoder6, + fieldName7, fieldDecoder7, + fieldName8, fieldDecoder8, + fieldName9, fieldDecoder9} + case 10: + var fieldName1 int64 + var fieldName2 int64 + var fieldName3 int64 + var fieldName4 int64 + var fieldName5 int64 + var fieldName6 int64 + var fieldName7 int64 + var fieldName8 int64 + var fieldName9 int64 + var fieldName10 int64 + var fieldDecoder1 *structFieldDecoder + var fieldDecoder2 *structFieldDecoder + var fieldDecoder3 *structFieldDecoder + var fieldDecoder4 *structFieldDecoder + var fieldDecoder5 *structFieldDecoder + var fieldDecoder6 *structFieldDecoder + var fieldDecoder7 *structFieldDecoder + var fieldDecoder8 *structFieldDecoder + var fieldDecoder9 *structFieldDecoder + var fieldDecoder10 *structFieldDecoder + for fieldName, fieldDecoder := range fields { + fieldHash := calcHash(fieldName, ctx.caseSensitive()) + _, known := knownHash[fieldHash] + if known { + return &generalStructDecoder{typ, fields, false} + } + knownHash[fieldHash] = struct{}{} + if fieldName1 == 0 { + fieldName1 = fieldHash + fieldDecoder1 = fieldDecoder + } else if fieldName2 == 0 { + fieldName2 = fieldHash + fieldDecoder2 = fieldDecoder + } else if fieldName3 == 0 { + fieldName3 = fieldHash + fieldDecoder3 = fieldDecoder + } else if fieldName4 == 0 { + fieldName4 = fieldHash + fieldDecoder4 = fieldDecoder + } else if fieldName5 == 0 { + fieldName5 = fieldHash + fieldDecoder5 = fieldDecoder + } else if fieldName6 == 0 { + fieldName6 = fieldHash + fieldDecoder6 = fieldDecoder + } else if fieldName7 == 0 { + fieldName7 = fieldHash + fieldDecoder7 = fieldDecoder + } else if fieldName8 == 0 { + fieldName8 = fieldHash + fieldDecoder8 = fieldDecoder + } else if fieldName9 == 0 { + fieldName9 = fieldHash + fieldDecoder9 = fieldDecoder + } else { + fieldName10 = fieldHash + fieldDecoder10 = fieldDecoder + } + } + return &tenFieldsStructDecoder{typ, + fieldName1, fieldDecoder1, + fieldName2, fieldDecoder2, + fieldName3, fieldDecoder3, + fieldName4, fieldDecoder4, + fieldName5, fieldDecoder5, + fieldName6, fieldDecoder6, + fieldName7, fieldDecoder7, + fieldName8, fieldDecoder8, + fieldName9, fieldDecoder9, + fieldName10, fieldDecoder10} + } + return &generalStructDecoder{typ, fields, false} +} + +type generalStructDecoder struct { + typ reflect2.Type + fields map[string]*structFieldDecoder + disallowUnknownFields bool +} + +func (decoder *generalStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.readObjectStart() { + return + } + var c byte + for c = ','; c == ','; c = iter.nextToken() { + decoder.decodeOneField(ptr, iter) + } + if iter.Error != nil && iter.Error != io.EOF { + iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) + } + if c != '}' { + iter.ReportError("struct Decode", `expect }, but found `+string([]byte{c})) + } +} + +func (decoder *generalStructDecoder) decodeOneField(ptr unsafe.Pointer, iter *Iterator) { + var field string + var fieldDecoder *structFieldDecoder + if iter.cfg.objectFieldMustBeSimpleString { + fieldBytes := iter.ReadStringAsSlice() + field = *(*string)(unsafe.Pointer(&fieldBytes)) + fieldDecoder = decoder.fields[field] + if fieldDecoder == nil && !iter.cfg.caseSensitive { + fieldDecoder = decoder.fields[strings.ToLower(field)] + } + } else { + field = iter.ReadString() + fieldDecoder = decoder.fields[field] + if fieldDecoder == nil && !iter.cfg.caseSensitive { + fieldDecoder = decoder.fields[strings.ToLower(field)] + } + } + if fieldDecoder == nil { + msg := "found unknown field: " + field + if decoder.disallowUnknownFields { + iter.ReportError("ReadObject", msg) + } + c := iter.nextToken() + if c != ':' { + iter.ReportError("ReadObject", "expect : after object field, but found "+string([]byte{c})) + } + iter.Skip() + return + } + c := iter.nextToken() + if c != ':' { + iter.ReportError("ReadObject", "expect : after object field, but found "+string([]byte{c})) + } + fieldDecoder.Decode(ptr, iter) +} + +type skipObjectDecoder struct { + typ reflect2.Type +} + +func (decoder *skipObjectDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + valueType := iter.WhatIsNext() + if valueType != ObjectValue && valueType != NilValue { + iter.ReportError("skipObjectDecoder", "expect object or null") + return + } + iter.Skip() +} + +type oneFieldStructDecoder struct { + typ reflect2.Type + fieldHash int64 + fieldDecoder *structFieldDecoder +} + +func (decoder *oneFieldStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.readObjectStart() { + return + } + for { + if iter.readFieldHash() == decoder.fieldHash { + decoder.fieldDecoder.Decode(ptr, iter) + } else { + iter.Skip() + } + if iter.isObjectEnd() { + break + } + } + if iter.Error != nil && iter.Error != io.EOF { + iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) + } +} + +type twoFieldsStructDecoder struct { + typ reflect2.Type + fieldHash1 int64 + fieldDecoder1 *structFieldDecoder + fieldHash2 int64 + fieldDecoder2 *structFieldDecoder +} + +func (decoder *twoFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.readObjectStart() { + return + } + for { + switch iter.readFieldHash() { + case decoder.fieldHash1: + decoder.fieldDecoder1.Decode(ptr, iter) + case decoder.fieldHash2: + decoder.fieldDecoder2.Decode(ptr, iter) + default: + iter.Skip() + } + if iter.isObjectEnd() { + break + } + } + if iter.Error != nil && iter.Error != io.EOF { + iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) + } +} + +type threeFieldsStructDecoder struct { + typ reflect2.Type + fieldHash1 int64 + fieldDecoder1 *structFieldDecoder + fieldHash2 int64 + fieldDecoder2 *structFieldDecoder + fieldHash3 int64 + fieldDecoder3 *structFieldDecoder +} + +func (decoder *threeFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.readObjectStart() { + return + } + for { + switch iter.readFieldHash() { + case decoder.fieldHash1: + decoder.fieldDecoder1.Decode(ptr, iter) + case decoder.fieldHash2: + decoder.fieldDecoder2.Decode(ptr, iter) + case decoder.fieldHash3: + decoder.fieldDecoder3.Decode(ptr, iter) + default: + iter.Skip() + } + if iter.isObjectEnd() { + break + } + } + if iter.Error != nil && iter.Error != io.EOF { + iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) + } +} + +type fourFieldsStructDecoder struct { + typ reflect2.Type + fieldHash1 int64 + fieldDecoder1 *structFieldDecoder + fieldHash2 int64 + fieldDecoder2 *structFieldDecoder + fieldHash3 int64 + fieldDecoder3 *structFieldDecoder + fieldHash4 int64 + fieldDecoder4 *structFieldDecoder +} + +func (decoder *fourFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.readObjectStart() { + return + } + for { + switch iter.readFieldHash() { + case decoder.fieldHash1: + decoder.fieldDecoder1.Decode(ptr, iter) + case decoder.fieldHash2: + decoder.fieldDecoder2.Decode(ptr, iter) + case decoder.fieldHash3: + decoder.fieldDecoder3.Decode(ptr, iter) + case decoder.fieldHash4: + decoder.fieldDecoder4.Decode(ptr, iter) + default: + iter.Skip() + } + if iter.isObjectEnd() { + break + } + } + if iter.Error != nil && iter.Error != io.EOF { + iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) + } +} + +type fiveFieldsStructDecoder struct { + typ reflect2.Type + fieldHash1 int64 + fieldDecoder1 *structFieldDecoder + fieldHash2 int64 + fieldDecoder2 *structFieldDecoder + fieldHash3 int64 + fieldDecoder3 *structFieldDecoder + fieldHash4 int64 + fieldDecoder4 *structFieldDecoder + fieldHash5 int64 + fieldDecoder5 *structFieldDecoder +} + +func (decoder *fiveFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.readObjectStart() { + return + } + for { + switch iter.readFieldHash() { + case decoder.fieldHash1: + decoder.fieldDecoder1.Decode(ptr, iter) + case decoder.fieldHash2: + decoder.fieldDecoder2.Decode(ptr, iter) + case decoder.fieldHash3: + decoder.fieldDecoder3.Decode(ptr, iter) + case decoder.fieldHash4: + decoder.fieldDecoder4.Decode(ptr, iter) + case decoder.fieldHash5: + decoder.fieldDecoder5.Decode(ptr, iter) + default: + iter.Skip() + } + if iter.isObjectEnd() { + break + } + } + if iter.Error != nil && iter.Error != io.EOF { + iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) + } +} + +type sixFieldsStructDecoder struct { + typ reflect2.Type + fieldHash1 int64 + fieldDecoder1 *structFieldDecoder + fieldHash2 int64 + fieldDecoder2 *structFieldDecoder + fieldHash3 int64 + fieldDecoder3 *structFieldDecoder + fieldHash4 int64 + fieldDecoder4 *structFieldDecoder + fieldHash5 int64 + fieldDecoder5 *structFieldDecoder + fieldHash6 int64 + fieldDecoder6 *structFieldDecoder +} + +func (decoder *sixFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.readObjectStart() { + return + } + for { + switch iter.readFieldHash() { + case decoder.fieldHash1: + decoder.fieldDecoder1.Decode(ptr, iter) + case decoder.fieldHash2: + decoder.fieldDecoder2.Decode(ptr, iter) + case decoder.fieldHash3: + decoder.fieldDecoder3.Decode(ptr, iter) + case decoder.fieldHash4: + decoder.fieldDecoder4.Decode(ptr, iter) + case decoder.fieldHash5: + decoder.fieldDecoder5.Decode(ptr, iter) + case decoder.fieldHash6: + decoder.fieldDecoder6.Decode(ptr, iter) + default: + iter.Skip() + } + if iter.isObjectEnd() { + break + } + } + if iter.Error != nil && iter.Error != io.EOF { + iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) + } +} + +type sevenFieldsStructDecoder struct { + typ reflect2.Type + fieldHash1 int64 + fieldDecoder1 *structFieldDecoder + fieldHash2 int64 + fieldDecoder2 *structFieldDecoder + fieldHash3 int64 + fieldDecoder3 *structFieldDecoder + fieldHash4 int64 + fieldDecoder4 *structFieldDecoder + fieldHash5 int64 + fieldDecoder5 *structFieldDecoder + fieldHash6 int64 + fieldDecoder6 *structFieldDecoder + fieldHash7 int64 + fieldDecoder7 *structFieldDecoder +} + +func (decoder *sevenFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.readObjectStart() { + return + } + for { + switch iter.readFieldHash() { + case decoder.fieldHash1: + decoder.fieldDecoder1.Decode(ptr, iter) + case decoder.fieldHash2: + decoder.fieldDecoder2.Decode(ptr, iter) + case decoder.fieldHash3: + decoder.fieldDecoder3.Decode(ptr, iter) + case decoder.fieldHash4: + decoder.fieldDecoder4.Decode(ptr, iter) + case decoder.fieldHash5: + decoder.fieldDecoder5.Decode(ptr, iter) + case decoder.fieldHash6: + decoder.fieldDecoder6.Decode(ptr, iter) + case decoder.fieldHash7: + decoder.fieldDecoder7.Decode(ptr, iter) + default: + iter.Skip() + } + if iter.isObjectEnd() { + break + } + } + if iter.Error != nil && iter.Error != io.EOF { + iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) + } +} + +type eightFieldsStructDecoder struct { + typ reflect2.Type + fieldHash1 int64 + fieldDecoder1 *structFieldDecoder + fieldHash2 int64 + fieldDecoder2 *structFieldDecoder + fieldHash3 int64 + fieldDecoder3 *structFieldDecoder + fieldHash4 int64 + fieldDecoder4 *structFieldDecoder + fieldHash5 int64 + fieldDecoder5 *structFieldDecoder + fieldHash6 int64 + fieldDecoder6 *structFieldDecoder + fieldHash7 int64 + fieldDecoder7 *structFieldDecoder + fieldHash8 int64 + fieldDecoder8 *structFieldDecoder +} + +func (decoder *eightFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.readObjectStart() { + return + } + for { + switch iter.readFieldHash() { + case decoder.fieldHash1: + decoder.fieldDecoder1.Decode(ptr, iter) + case decoder.fieldHash2: + decoder.fieldDecoder2.Decode(ptr, iter) + case decoder.fieldHash3: + decoder.fieldDecoder3.Decode(ptr, iter) + case decoder.fieldHash4: + decoder.fieldDecoder4.Decode(ptr, iter) + case decoder.fieldHash5: + decoder.fieldDecoder5.Decode(ptr, iter) + case decoder.fieldHash6: + decoder.fieldDecoder6.Decode(ptr, iter) + case decoder.fieldHash7: + decoder.fieldDecoder7.Decode(ptr, iter) + case decoder.fieldHash8: + decoder.fieldDecoder8.Decode(ptr, iter) + default: + iter.Skip() + } + if iter.isObjectEnd() { + break + } + } + if iter.Error != nil && iter.Error != io.EOF { + iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) + } +} + +type nineFieldsStructDecoder struct { + typ reflect2.Type + fieldHash1 int64 + fieldDecoder1 *structFieldDecoder + fieldHash2 int64 + fieldDecoder2 *structFieldDecoder + fieldHash3 int64 + fieldDecoder3 *structFieldDecoder + fieldHash4 int64 + fieldDecoder4 *structFieldDecoder + fieldHash5 int64 + fieldDecoder5 *structFieldDecoder + fieldHash6 int64 + fieldDecoder6 *structFieldDecoder + fieldHash7 int64 + fieldDecoder7 *structFieldDecoder + fieldHash8 int64 + fieldDecoder8 *structFieldDecoder + fieldHash9 int64 + fieldDecoder9 *structFieldDecoder +} + +func (decoder *nineFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.readObjectStart() { + return + } + for { + switch iter.readFieldHash() { + case decoder.fieldHash1: + decoder.fieldDecoder1.Decode(ptr, iter) + case decoder.fieldHash2: + decoder.fieldDecoder2.Decode(ptr, iter) + case decoder.fieldHash3: + decoder.fieldDecoder3.Decode(ptr, iter) + case decoder.fieldHash4: + decoder.fieldDecoder4.Decode(ptr, iter) + case decoder.fieldHash5: + decoder.fieldDecoder5.Decode(ptr, iter) + case decoder.fieldHash6: + decoder.fieldDecoder6.Decode(ptr, iter) + case decoder.fieldHash7: + decoder.fieldDecoder7.Decode(ptr, iter) + case decoder.fieldHash8: + decoder.fieldDecoder8.Decode(ptr, iter) + case decoder.fieldHash9: + decoder.fieldDecoder9.Decode(ptr, iter) + default: + iter.Skip() + } + if iter.isObjectEnd() { + break + } + } + if iter.Error != nil && iter.Error != io.EOF { + iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) + } +} + +type tenFieldsStructDecoder struct { + typ reflect2.Type + fieldHash1 int64 + fieldDecoder1 *structFieldDecoder + fieldHash2 int64 + fieldDecoder2 *structFieldDecoder + fieldHash3 int64 + fieldDecoder3 *structFieldDecoder + fieldHash4 int64 + fieldDecoder4 *structFieldDecoder + fieldHash5 int64 + fieldDecoder5 *structFieldDecoder + fieldHash6 int64 + fieldDecoder6 *structFieldDecoder + fieldHash7 int64 + fieldDecoder7 *structFieldDecoder + fieldHash8 int64 + fieldDecoder8 *structFieldDecoder + fieldHash9 int64 + fieldDecoder9 *structFieldDecoder + fieldHash10 int64 + fieldDecoder10 *structFieldDecoder +} + +func (decoder *tenFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.readObjectStart() { + return + } + for { + switch iter.readFieldHash() { + case decoder.fieldHash1: + decoder.fieldDecoder1.Decode(ptr, iter) + case decoder.fieldHash2: + decoder.fieldDecoder2.Decode(ptr, iter) + case decoder.fieldHash3: + decoder.fieldDecoder3.Decode(ptr, iter) + case decoder.fieldHash4: + decoder.fieldDecoder4.Decode(ptr, iter) + case decoder.fieldHash5: + decoder.fieldDecoder5.Decode(ptr, iter) + case decoder.fieldHash6: + decoder.fieldDecoder6.Decode(ptr, iter) + case decoder.fieldHash7: + decoder.fieldDecoder7.Decode(ptr, iter) + case decoder.fieldHash8: + decoder.fieldDecoder8.Decode(ptr, iter) + case decoder.fieldHash9: + decoder.fieldDecoder9.Decode(ptr, iter) + case decoder.fieldHash10: + decoder.fieldDecoder10.Decode(ptr, iter) + default: + iter.Skip() + } + if iter.isObjectEnd() { + break + } + } + if iter.Error != nil && iter.Error != io.EOF { + iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) + } +} + +type structFieldDecoder struct { + field reflect2.StructField + fieldDecoder ValDecoder +} + +func (decoder *structFieldDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + fieldPtr := decoder.field.UnsafeGet(ptr) + decoder.fieldDecoder.Decode(fieldPtr, iter) + if iter.Error != nil && iter.Error != io.EOF { + iter.Error = fmt.Errorf("%s: %s", decoder.field.Name(), iter.Error.Error()) + } +} + +type stringModeStringDecoder struct { + elemDecoder ValDecoder + cfg *frozenConfig +} + +func (decoder *stringModeStringDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + decoder.elemDecoder.Decode(ptr, iter) + str := *((*string)(ptr)) + tempIter := decoder.cfg.BorrowIterator([]byte(str)) + defer decoder.cfg.ReturnIterator(tempIter) + *((*string)(ptr)) = tempIter.ReadString() +} + +type stringModeNumberDecoder struct { + elemDecoder ValDecoder +} + +func (decoder *stringModeNumberDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + c := iter.nextToken() + if c != '"' { + iter.ReportError("stringModeNumberDecoder", `expect ", but found `+string([]byte{c})) + return + } + decoder.elemDecoder.Decode(ptr, iter) + if iter.Error != nil { + return + } + c = iter.readByte() + if c != '"' { + iter.ReportError("stringModeNumberDecoder", `expect ", but found `+string([]byte{c})) + return + } +} diff --git a/vendor/github.com/json-iterator/go/reflect_struct_encoder.go b/vendor/github.com/json-iterator/go/reflect_struct_encoder.go new file mode 100644 index 000000000..d0759cf64 --- /dev/null +++ b/vendor/github.com/json-iterator/go/reflect_struct_encoder.go @@ -0,0 +1,210 @@ +package jsoniter + +import ( + "fmt" + "github.com/modern-go/reflect2" + "io" + "reflect" + "unsafe" +) + +func encoderOfStruct(ctx *ctx, typ reflect2.Type) ValEncoder { + type bindingTo struct { + binding *Binding + toName string + ignored bool + } + orderedBindings := []*bindingTo{} + structDescriptor := describeStruct(ctx, typ) + for _, binding := range structDescriptor.Fields { + for _, toName := range binding.ToNames { + new := &bindingTo{ + binding: binding, + toName: toName, + } + for _, old := range orderedBindings { + if old.toName != toName { + continue + } + old.ignored, new.ignored = resolveConflictBinding(ctx.frozenConfig, old.binding, new.binding) + } + orderedBindings = append(orderedBindings, new) + } + } + if len(orderedBindings) == 0 { + return &emptyStructEncoder{} + } + finalOrderedFields := []structFieldTo{} + for _, bindingTo := range orderedBindings { + if !bindingTo.ignored { + finalOrderedFields = append(finalOrderedFields, structFieldTo{ + encoder: bindingTo.binding.Encoder.(*structFieldEncoder), + toName: bindingTo.toName, + }) + } + } + return &structEncoder{typ, finalOrderedFields} +} + +func createCheckIsEmpty(ctx *ctx, typ reflect2.Type) checkIsEmpty { + encoder := createEncoderOfNative(ctx, typ) + if encoder != nil { + return encoder + } + kind := typ.Kind() + switch kind { + case reflect.Interface: + return &dynamicEncoder{typ} + case reflect.Struct: + return &structEncoder{typ: typ} + case reflect.Array: + return &arrayEncoder{} + case reflect.Slice: + return &sliceEncoder{} + case reflect.Map: + return encoderOfMap(ctx, typ) + case reflect.Ptr: + return &OptionalEncoder{} + default: + return &lazyErrorEncoder{err: fmt.Errorf("unsupported type: %v", typ)} + } +} + +func resolveConflictBinding(cfg *frozenConfig, old, new *Binding) (ignoreOld, ignoreNew bool) { + newTagged := new.Field.Tag().Get(cfg.getTagKey()) != "" + oldTagged := old.Field.Tag().Get(cfg.getTagKey()) != "" + if newTagged { + if oldTagged { + if len(old.levels) > len(new.levels) { + return true, false + } else if len(new.levels) > len(old.levels) { + return false, true + } else { + return true, true + } + } else { + return true, false + } + } else { + if oldTagged { + return true, false + } + if len(old.levels) > len(new.levels) { + return true, false + } else if len(new.levels) > len(old.levels) { + return false, true + } else { + return true, true + } + } +} + +type structFieldEncoder struct { + field reflect2.StructField + fieldEncoder ValEncoder + omitempty bool +} + +func (encoder *structFieldEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + fieldPtr := encoder.field.UnsafeGet(ptr) + encoder.fieldEncoder.Encode(fieldPtr, stream) + if stream.Error != nil && stream.Error != io.EOF { + stream.Error = fmt.Errorf("%s: %s", encoder.field.Name(), stream.Error.Error()) + } +} + +func (encoder *structFieldEncoder) IsEmpty(ptr unsafe.Pointer) bool { + fieldPtr := encoder.field.UnsafeGet(ptr) + return encoder.fieldEncoder.IsEmpty(fieldPtr) +} + +func (encoder *structFieldEncoder) IsEmbeddedPtrNil(ptr unsafe.Pointer) bool { + isEmbeddedPtrNil, converted := encoder.fieldEncoder.(IsEmbeddedPtrNil) + if !converted { + return false + } + fieldPtr := encoder.field.UnsafeGet(ptr) + return isEmbeddedPtrNil.IsEmbeddedPtrNil(fieldPtr) +} + +type IsEmbeddedPtrNil interface { + IsEmbeddedPtrNil(ptr unsafe.Pointer) bool +} + +type structEncoder struct { + typ reflect2.Type + fields []structFieldTo +} + +type structFieldTo struct { + encoder *structFieldEncoder + toName string +} + +func (encoder *structEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteObjectStart() + isNotFirst := false + for _, field := range encoder.fields { + if field.encoder.omitempty && field.encoder.IsEmpty(ptr) { + continue + } + if field.encoder.IsEmbeddedPtrNil(ptr) { + continue + } + if isNotFirst { + stream.WriteMore() + } + stream.WriteObjectField(field.toName) + field.encoder.Encode(ptr, stream) + isNotFirst = true + } + stream.WriteObjectEnd() + if stream.Error != nil && stream.Error != io.EOF { + stream.Error = fmt.Errorf("%v.%s", encoder.typ, stream.Error.Error()) + } +} + +func (encoder *structEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return false +} + +type emptyStructEncoder struct { +} + +func (encoder *emptyStructEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteEmptyObject() +} + +func (encoder *emptyStructEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return false +} + +type stringModeNumberEncoder struct { + elemEncoder ValEncoder +} + +func (encoder *stringModeNumberEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.writeByte('"') + encoder.elemEncoder.Encode(ptr, stream) + stream.writeByte('"') +} + +func (encoder *stringModeNumberEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return encoder.elemEncoder.IsEmpty(ptr) +} + +type stringModeStringEncoder struct { + elemEncoder ValEncoder + cfg *frozenConfig +} + +func (encoder *stringModeStringEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + tempStream := encoder.cfg.BorrowStream(nil) + defer encoder.cfg.ReturnStream(tempStream) + encoder.elemEncoder.Encode(ptr, tempStream) + stream.WriteString(string(tempStream.Buffer())) +} + +func (encoder *stringModeStringEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return encoder.elemEncoder.IsEmpty(ptr) +} diff --git a/vendor/github.com/json-iterator/go/stream.go b/vendor/github.com/json-iterator/go/stream.go new file mode 100644 index 000000000..17662fded --- /dev/null +++ b/vendor/github.com/json-iterator/go/stream.go @@ -0,0 +1,211 @@ +package jsoniter + +import ( + "io" +) + +// stream is a io.Writer like object, with JSON specific write functions. +// Error is not returned as return value, but stored as Error member on this stream instance. +type Stream struct { + cfg *frozenConfig + out io.Writer + buf []byte + Error error + indention int + Attachment interface{} // open for customized encoder +} + +// NewStream create new stream instance. +// cfg can be jsoniter.ConfigDefault. +// out can be nil if write to internal buffer. +// bufSize is the initial size for the internal buffer in bytes. +func NewStream(cfg API, out io.Writer, bufSize int) *Stream { + return &Stream{ + cfg: cfg.(*frozenConfig), + out: out, + buf: make([]byte, 0, bufSize), + Error: nil, + indention: 0, + } +} + +// Pool returns a pool can provide more stream with same configuration +func (stream *Stream) Pool() StreamPool { + return stream.cfg +} + +// Reset reuse this stream instance by assign a new writer +func (stream *Stream) Reset(out io.Writer) { + stream.out = out + stream.buf = stream.buf[:0] +} + +// Available returns how many bytes are unused in the buffer. +func (stream *Stream) Available() int { + return cap(stream.buf) - len(stream.buf) +} + +// Buffered returns the number of bytes that have been written into the current buffer. +func (stream *Stream) Buffered() int { + return len(stream.buf) +} + +// Buffer if writer is nil, use this method to take the result +func (stream *Stream) Buffer() []byte { + return stream.buf +} + +// SetBuffer allows to append to the internal buffer directly +func (stream *Stream) SetBuffer(buf []byte) { + stream.buf = buf +} + +// Write writes the contents of p into the buffer. +// It returns the number of bytes written. +// If nn < len(p), it also returns an error explaining +// why the write is short. +func (stream *Stream) Write(p []byte) (nn int, err error) { + stream.buf = append(stream.buf, p...) + if stream.out != nil { + nn, err = stream.out.Write(stream.buf) + stream.buf = stream.buf[nn:] + return + } + return len(p), nil +} + +// WriteByte writes a single byte. +func (stream *Stream) writeByte(c byte) { + stream.buf = append(stream.buf, c) +} + +func (stream *Stream) writeTwoBytes(c1 byte, c2 byte) { + stream.buf = append(stream.buf, c1, c2) +} + +func (stream *Stream) writeThreeBytes(c1 byte, c2 byte, c3 byte) { + stream.buf = append(stream.buf, c1, c2, c3) +} + +func (stream *Stream) writeFourBytes(c1 byte, c2 byte, c3 byte, c4 byte) { + stream.buf = append(stream.buf, c1, c2, c3, c4) +} + +func (stream *Stream) writeFiveBytes(c1 byte, c2 byte, c3 byte, c4 byte, c5 byte) { + stream.buf = append(stream.buf, c1, c2, c3, c4, c5) +} + +// Flush writes any buffered data to the underlying io.Writer. +func (stream *Stream) Flush() error { + if stream.out == nil { + return nil + } + if stream.Error != nil { + return stream.Error + } + n, err := stream.out.Write(stream.buf) + if err != nil { + if stream.Error == nil { + stream.Error = err + } + return err + } + stream.buf = stream.buf[n:] + return nil +} + +// WriteRaw write string out without quotes, just like []byte +func (stream *Stream) WriteRaw(s string) { + stream.buf = append(stream.buf, s...) +} + +// WriteNil write null to stream +func (stream *Stream) WriteNil() { + stream.writeFourBytes('n', 'u', 'l', 'l') +} + +// WriteTrue write true to stream +func (stream *Stream) WriteTrue() { + stream.writeFourBytes('t', 'r', 'u', 'e') +} + +// WriteFalse write false to stream +func (stream *Stream) WriteFalse() { + stream.writeFiveBytes('f', 'a', 'l', 's', 'e') +} + +// WriteBool write true or false into stream +func (stream *Stream) WriteBool(val bool) { + if val { + stream.WriteTrue() + } else { + stream.WriteFalse() + } +} + +// WriteObjectStart write { with possible indention +func (stream *Stream) WriteObjectStart() { + stream.indention += stream.cfg.indentionStep + stream.writeByte('{') + stream.writeIndention(0) +} + +// WriteObjectField write "field": with possible indention +func (stream *Stream) WriteObjectField(field string) { + stream.WriteString(field) + if stream.indention > 0 { + stream.writeTwoBytes(':', ' ') + } else { + stream.writeByte(':') + } +} + +// WriteObjectEnd write } with possible indention +func (stream *Stream) WriteObjectEnd() { + stream.writeIndention(stream.cfg.indentionStep) + stream.indention -= stream.cfg.indentionStep + stream.writeByte('}') +} + +// WriteEmptyObject write {} +func (stream *Stream) WriteEmptyObject() { + stream.writeByte('{') + stream.writeByte('}') +} + +// WriteMore write , with possible indention +func (stream *Stream) WriteMore() { + stream.writeByte(',') + stream.writeIndention(0) + stream.Flush() +} + +// WriteArrayStart write [ with possible indention +func (stream *Stream) WriteArrayStart() { + stream.indention += stream.cfg.indentionStep + stream.writeByte('[') + stream.writeIndention(0) +} + +// WriteEmptyArray write [] +func (stream *Stream) WriteEmptyArray() { + stream.writeTwoBytes('[', ']') +} + +// WriteArrayEnd write ] with possible indention +func (stream *Stream) WriteArrayEnd() { + stream.writeIndention(stream.cfg.indentionStep) + stream.indention -= stream.cfg.indentionStep + stream.writeByte(']') +} + +func (stream *Stream) writeIndention(delta int) { + if stream.indention == 0 { + return + } + stream.writeByte('\n') + toWrite := stream.indention - delta + for i := 0; i < toWrite; i++ { + stream.buf = append(stream.buf, ' ') + } +} diff --git a/vendor/github.com/json-iterator/go/stream_float.go b/vendor/github.com/json-iterator/go/stream_float.go new file mode 100644 index 000000000..f318d2c59 --- /dev/null +++ b/vendor/github.com/json-iterator/go/stream_float.go @@ -0,0 +1,94 @@ +package jsoniter + +import ( + "math" + "strconv" +) + +var pow10 []uint64 + +func init() { + pow10 = []uint64{1, 10, 100, 1000, 10000, 100000, 1000000} +} + +// WriteFloat32 write float32 to stream +func (stream *Stream) WriteFloat32(val float32) { + abs := math.Abs(float64(val)) + fmt := byte('f') + // Note: Must use float32 comparisons for underlying float32 value to get precise cutoffs right. + if abs != 0 { + if float32(abs) < 1e-6 || float32(abs) >= 1e21 { + fmt = 'e' + } + } + stream.buf = strconv.AppendFloat(stream.buf, float64(val), fmt, -1, 32) +} + +// WriteFloat32Lossy write float32 to stream with ONLY 6 digits precision although much much faster +func (stream *Stream) WriteFloat32Lossy(val float32) { + if val < 0 { + stream.writeByte('-') + val = -val + } + if val > 0x4ffffff { + stream.WriteFloat32(val) + return + } + precision := 6 + exp := uint64(1000000) // 6 + lval := uint64(float64(val)*float64(exp) + 0.5) + stream.WriteUint64(lval / exp) + fval := lval % exp + if fval == 0 { + return + } + stream.writeByte('.') + for p := precision - 1; p > 0 && fval < pow10[p]; p-- { + stream.writeByte('0') + } + stream.WriteUint64(fval) + for stream.buf[len(stream.buf)-1] == '0' { + stream.buf = stream.buf[:len(stream.buf)-1] + } +} + +// WriteFloat64 write float64 to stream +func (stream *Stream) WriteFloat64(val float64) { + abs := math.Abs(val) + fmt := byte('f') + // Note: Must use float32 comparisons for underlying float32 value to get precise cutoffs right. + if abs != 0 { + if abs < 1e-6 || abs >= 1e21 { + fmt = 'e' + } + } + stream.buf = strconv.AppendFloat(stream.buf, float64(val), fmt, -1, 64) +} + +// WriteFloat64Lossy write float64 to stream with ONLY 6 digits precision although much much faster +func (stream *Stream) WriteFloat64Lossy(val float64) { + if val < 0 { + stream.writeByte('-') + val = -val + } + if val > 0x4ffffff { + stream.WriteFloat64(val) + return + } + precision := 6 + exp := uint64(1000000) // 6 + lval := uint64(val*float64(exp) + 0.5) + stream.WriteUint64(lval / exp) + fval := lval % exp + if fval == 0 { + return + } + stream.writeByte('.') + for p := precision - 1; p > 0 && fval < pow10[p]; p-- { + stream.writeByte('0') + } + stream.WriteUint64(fval) + for stream.buf[len(stream.buf)-1] == '0' { + stream.buf = stream.buf[:len(stream.buf)-1] + } +} diff --git a/vendor/github.com/json-iterator/go/stream_int.go b/vendor/github.com/json-iterator/go/stream_int.go new file mode 100644 index 000000000..d1059ee4c --- /dev/null +++ b/vendor/github.com/json-iterator/go/stream_int.go @@ -0,0 +1,190 @@ +package jsoniter + +var digits []uint32 + +func init() { + digits = make([]uint32, 1000) + for i := uint32(0); i < 1000; i++ { + digits[i] = (((i / 100) + '0') << 16) + ((((i / 10) % 10) + '0') << 8) + i%10 + '0' + if i < 10 { + digits[i] += 2 << 24 + } else if i < 100 { + digits[i] += 1 << 24 + } + } +} + +func writeFirstBuf(space []byte, v uint32) []byte { + start := v >> 24 + if start == 0 { + space = append(space, byte(v>>16), byte(v>>8)) + } else if start == 1 { + space = append(space, byte(v>>8)) + } + space = append(space, byte(v)) + return space +} + +func writeBuf(buf []byte, v uint32) []byte { + return append(buf, byte(v>>16), byte(v>>8), byte(v)) +} + +// WriteUint8 write uint8 to stream +func (stream *Stream) WriteUint8(val uint8) { + stream.buf = writeFirstBuf(stream.buf, digits[val]) +} + +// WriteInt8 write int8 to stream +func (stream *Stream) WriteInt8(nval int8) { + var val uint8 + if nval < 0 { + val = uint8(-nval) + stream.buf = append(stream.buf, '-') + } else { + val = uint8(nval) + } + stream.buf = writeFirstBuf(stream.buf, digits[val]) +} + +// WriteUint16 write uint16 to stream +func (stream *Stream) WriteUint16(val uint16) { + q1 := val / 1000 + if q1 == 0 { + stream.buf = writeFirstBuf(stream.buf, digits[val]) + return + } + r1 := val - q1*1000 + stream.buf = writeFirstBuf(stream.buf, digits[q1]) + stream.buf = writeBuf(stream.buf, digits[r1]) + return +} + +// WriteInt16 write int16 to stream +func (stream *Stream) WriteInt16(nval int16) { + var val uint16 + if nval < 0 { + val = uint16(-nval) + stream.buf = append(stream.buf, '-') + } else { + val = uint16(nval) + } + stream.WriteUint16(val) +} + +// WriteUint32 write uint32 to stream +func (stream *Stream) WriteUint32(val uint32) { + q1 := val / 1000 + if q1 == 0 { + stream.buf = writeFirstBuf(stream.buf, digits[val]) + return + } + r1 := val - q1*1000 + q2 := q1 / 1000 + if q2 == 0 { + stream.buf = writeFirstBuf(stream.buf, digits[q1]) + stream.buf = writeBuf(stream.buf, digits[r1]) + return + } + r2 := q1 - q2*1000 + q3 := q2 / 1000 + if q3 == 0 { + stream.buf = writeFirstBuf(stream.buf, digits[q2]) + } else { + r3 := q2 - q3*1000 + stream.buf = append(stream.buf, byte(q3+'0')) + stream.buf = writeBuf(stream.buf, digits[r3]) + } + stream.buf = writeBuf(stream.buf, digits[r2]) + stream.buf = writeBuf(stream.buf, digits[r1]) +} + +// WriteInt32 write int32 to stream +func (stream *Stream) WriteInt32(nval int32) { + var val uint32 + if nval < 0 { + val = uint32(-nval) + stream.buf = append(stream.buf, '-') + } else { + val = uint32(nval) + } + stream.WriteUint32(val) +} + +// WriteUint64 write uint64 to stream +func (stream *Stream) WriteUint64(val uint64) { + q1 := val / 1000 + if q1 == 0 { + stream.buf = writeFirstBuf(stream.buf, digits[val]) + return + } + r1 := val - q1*1000 + q2 := q1 / 1000 + if q2 == 0 { + stream.buf = writeFirstBuf(stream.buf, digits[q1]) + stream.buf = writeBuf(stream.buf, digits[r1]) + return + } + r2 := q1 - q2*1000 + q3 := q2 / 1000 + if q3 == 0 { + stream.buf = writeFirstBuf(stream.buf, digits[q2]) + stream.buf = writeBuf(stream.buf, digits[r2]) + stream.buf = writeBuf(stream.buf, digits[r1]) + return + } + r3 := q2 - q3*1000 + q4 := q3 / 1000 + if q4 == 0 { + stream.buf = writeFirstBuf(stream.buf, digits[q3]) + stream.buf = writeBuf(stream.buf, digits[r3]) + stream.buf = writeBuf(stream.buf, digits[r2]) + stream.buf = writeBuf(stream.buf, digits[r1]) + return + } + r4 := q3 - q4*1000 + q5 := q4 / 1000 + if q5 == 0 { + stream.buf = writeFirstBuf(stream.buf, digits[q4]) + stream.buf = writeBuf(stream.buf, digits[r4]) + stream.buf = writeBuf(stream.buf, digits[r3]) + stream.buf = writeBuf(stream.buf, digits[r2]) + stream.buf = writeBuf(stream.buf, digits[r1]) + return + } + r5 := q4 - q5*1000 + q6 := q5 / 1000 + if q6 == 0 { + stream.buf = writeFirstBuf(stream.buf, digits[q5]) + } else { + stream.buf = writeFirstBuf(stream.buf, digits[q6]) + r6 := q5 - q6*1000 + stream.buf = writeBuf(stream.buf, digits[r6]) + } + stream.buf = writeBuf(stream.buf, digits[r5]) + stream.buf = writeBuf(stream.buf, digits[r4]) + stream.buf = writeBuf(stream.buf, digits[r3]) + stream.buf = writeBuf(stream.buf, digits[r2]) + stream.buf = writeBuf(stream.buf, digits[r1]) +} + +// WriteInt64 write int64 to stream +func (stream *Stream) WriteInt64(nval int64) { + var val uint64 + if nval < 0 { + val = uint64(-nval) + stream.buf = append(stream.buf, '-') + } else { + val = uint64(nval) + } + stream.WriteUint64(val) +} + +// WriteInt write int to stream +func (stream *Stream) WriteInt(val int) { + stream.WriteInt64(int64(val)) +} + +// WriteUint write uint to stream +func (stream *Stream) WriteUint(val uint) { + stream.WriteUint64(uint64(val)) +} diff --git a/vendor/github.com/json-iterator/go/stream_str.go b/vendor/github.com/json-iterator/go/stream_str.go new file mode 100644 index 000000000..54c2ba0b3 --- /dev/null +++ b/vendor/github.com/json-iterator/go/stream_str.go @@ -0,0 +1,372 @@ +package jsoniter + +import ( + "unicode/utf8" +) + +// htmlSafeSet holds the value true if the ASCII character with the given +// array position can be safely represented inside a JSON string, embedded +// inside of HTML