From e3d1222dd7ae8b64334ebb2cc617e3f356f771a3 Mon Sep 17 00:00:00 2001 From: Jeff Mitchell Date: Tue, 22 Sep 2015 11:44:21 -0400 Subject: [PATCH] Update deps --- Godeps/Godeps.json | 98 +- .../armon/go-metrics/datadog/dogstatsd.go | 109 + .../armon/go-metrics/inmem_signal_test.go | 46 - .../github.com/armon/go-metrics/inmem_test.go | 104 - .../armon/go-metrics/metrics_test.go | 262 - .../github.com/armon/go-metrics/sink_test.go | 120 - .../github.com/armon/go-metrics/start_test.go | 110 - .../armon/go-metrics/statsd_test.go | 105 - .../armon/go-metrics/statsite_test.go | 101 - .../github.com/armon/go-radix/radix_test.go | 319 - .../aws/aws-sdk-go/aws/awserr/types.go | 2 +- .../aws/aws-sdk-go/aws/awsutil/copy_test.go | 201 - .../aws-sdk-go/aws/awsutil/path_value_test.go | 68 - .../github.com/aws/aws-sdk-go/aws/config.go | 18 +- .../aws/aws-sdk-go/aws/config_test.go | 80 - .../aws/aws-sdk-go/aws/convert_types_test.go | 437 -- .../handlers.go} | 76 +- .../aws/corehandlers/param_validator.go | 144 + .../aws/credentials/chain_provider_test.go | 73 - .../aws/credentials/credentials_test.go | 62 - .../ec2rolecreds/ec2_role_provider_test.go | 161 - .../aws/credentials/env_provider_test.go | 70 - .../shared_credentials_provider_test.go | 90 - .../aws/credentials/static_provider_test.go | 34 - .../stscreds/assume_role_provider.go | 4 + .../stscreds/assume_role_provider_test.go | 59 - .../aws/aws-sdk-go/aws/defaults/defaults.go | 3 +- .../aws/aws-sdk-go/aws/ec2metadata/api.go | 6 +- .../aws-sdk-go/aws/ec2metadata/api_test.go | 100 - .../aws/aws-sdk-go/aws/ec2metadata/service.go | 20 +- .../github.com/aws/aws-sdk-go/aws/errors.go | 17 + .../aws/{service => request}/handlers.go | 53 +- .../aws/{service => request}/request.go | 33 +- .../aws/aws-sdk-go/aws/request/retryer.go | 71 + .../aws-sdk-go/aws/service/default_retryer.go | 51 + .../aws/service/handler_functions_test.go | 106 - .../aws-sdk-go/aws/service/handlers_test.go | 33 - .../aws-sdk-go/aws/service/param_validator.go | 89 - .../aws/service/param_validator_test.go | 85 - .../aws/service/request_pagination_test.go | 307 - .../aws-sdk-go/aws/service/request_test.go | 226 - .../aws/aws-sdk-go/aws/service/service.go | 137 +- .../aws/service/serviceinfo/service_info.go | 15 + .../aws/aws-sdk-go/aws/types_test.go | 56 - .../github.com/aws/aws-sdk-go/aws/version.go | 2 +- .../internal/endpoints/endpoints_test.go | 28 - .../internal/protocol/ec2query/build.go | 4 +- .../internal/protocol/ec2query/build_test.go | 862 --- .../internal/protocol/ec2query/unmarshal.go | 8 +- .../protocol/ec2query/unmarshal_test.go | 818 -- .../internal/protocol/query/build.go | 4 +- .../internal/protocol/query/build_test.go | 1484 ---- .../internal/protocol/query/unmarshal.go | 6 +- .../protocol/query/unmarshal_error.go | 4 +- .../internal/protocol/query/unmarshal_test.go | 1420 ---- .../internal/protocol/rest/build.go | 16 +- .../internal/protocol/rest/unmarshal.go | 16 +- .../internal/protocol/restxml/build_test.go | 2719 ------- .../internal/protocol/restxml/restxml.go | 16 +- .../protocol/restxml/unmarshal_test.go | 1312 ---- .../internal/signer/v4/functional_test.go | 43 - .../aws/aws-sdk-go/internal/signer/v4/v4.go | 4 +- .../aws-sdk-go/internal/signer/v4/v4_test.go | 246 - .../aws/aws-sdk-go/service/ec2/api.go | 1072 +-- .../aws-sdk-go/service/ec2/customizations.go | 6 +- .../service/ec2/customizations_test.go | 36 - .../service/ec2/ec2iface/interface.go | 366 +- .../service/ec2/ec2iface/interface_test.go | 15 - .../aws-sdk-go/service/ec2/examples_test.go | 6619 ----------------- .../aws/aws-sdk-go/service/ec2/service.go | 16 +- .../aws/aws-sdk-go/service/iam/api.go | 2256 ++++-- .../aws-sdk-go/service/iam/examples_test.go | 3099 -------- .../service/iam/iamiface/interface.go | 236 +- .../service/iam/iamiface/interface_test.go | 15 - .../aws/aws-sdk-go/service/iam/service.go | 20 +- .../aws/aws-sdk-go/service/s3/api.go | 619 +- .../aws-sdk-go/service/s3/bucket_location.go | 10 +- .../service/s3/bucket_location_test.go | 76 - .../aws/aws-sdk-go/service/s3/content_md5.go | 4 +- .../aws-sdk-go/service/s3/customizations.go | 9 +- .../service/s3/customizations_test.go | 91 - .../aws-sdk-go/service/s3/examples_test.go | 1928 ----- .../service/s3/host_style_bucket.go | 14 +- .../service/s3/host_style_bucket_test.go | 61 - .../service/s3/s3iface/interface.go | 118 +- .../service/s3/s3iface/interface_test.go | 15 - .../service/s3/s3manager/download.go | 3 +- .../service/s3/s3manager/download_test.go | 141 - .../aws-sdk-go/service/s3/s3manager/upload.go | 3 +- .../service/s3/s3manager/upload_test.go | 463 -- .../aws/aws-sdk-go/service/s3/service.go | 16 +- .../aws/aws-sdk-go/service/s3/sse.go | 6 +- .../aws/aws-sdk-go/service/s3/sse_test.go | 81 - .../aws-sdk-go/service/s3/statusok_error.go | 36 + .../aws-sdk-go/service/s3/unmarshal_error.go | 13 +- .../service/s3/unmarshal_error_test.go | 54 - .../coreos/go-etcd/etcd/add_child_test.go | 73 - .../coreos/go-etcd/etcd/client_test.go | 108 - .../go-etcd/etcd/compare_and_delete_test.go | 46 - .../go-etcd/etcd/compare_and_swap_test.go | 57 - .../coreos/go-etcd/etcd/debug_test.go | 28 - .../coreos/go-etcd/etcd/delete_test.go | 81 - .../coreos/go-etcd/etcd/get_test.go | 131 - .../coreos/go-etcd/etcd/member_test.go | 71 - .../coreos/go-etcd/etcd/requests_test.go | 22 - .../coreos/go-etcd/etcd/response.generated.go | 1662 +++-- .../coreos/go-etcd/etcd/response_test.go | 75 - .../coreos/go-etcd/etcd/set_curl_chan_test.go | 42 - .../go-etcd/etcd/set_update_create_test.go | 241 - .../coreos/go-etcd/etcd/watch_test.go | 119 - .../github.com/dgrijalva/jwt-go/.travis.yml | 2 + .../src/github.com/dgrijalva/jwt-go/README.md | 6 + .../github.com/dgrijalva/jwt-go/ecdsa_test.go | 100 - .../dgrijalva/jwt-go/example_test.go | 52 - .../github.com/dgrijalva/jwt-go/hmac_test.go | 91 - .../github.com/dgrijalva/jwt-go/jwt_test.go | 187 - .../dgrijalva/jwt-go/rsa_pss_test.go | 96 - .../github.com/dgrijalva/jwt-go/rsa_test.go | 174 - .../duo_api_golang/authapi/authapi_test.go | 497 -- .../duosecurity/duo_api_golang/duo_test.go | 156 - .../github.com/fatih/structs/field_test.go | 324 - .../fatih/structs/structs_example_test.go | 351 - .../github.com/fatih/structs/structs_test.go | 898 --- .../src/github.com/fatih/structs/tags_test.go | 46 - .../src/github.com/go-ldap/ldap/dn_test.go | 70 - .../github.com/go-ldap/ldap/example_test.go | 305 - .../github.com/go-ldap/ldap/filter_test.go | 96 - .../src/github.com/go-ldap/ldap/ldap_test.go | 247 - .../github.com/go-sql-driver/mysql/README.md | 2 +- .../go-sql-driver/mysql/benchmark_test.go | 246 - .../go-sql-driver/mysql/driver_test.go | 1681 ----- .../go-sql-driver/mysql/errors_test.go | 42 - .../go-sql-driver/mysql/utils_test.go | 346 - .../src/github.com/gocql/gocql/.travis.yml | 6 +- .../src/github.com/gocql/gocql/AUTHORS | 1 + .../src/github.com/gocql/gocql/README.md | 8 +- .../github.com/gocql/gocql/cass1batch_test.go | 60 - .../github.com/gocql/gocql/cassandra_test.go | 2060 ----- .../src/github.com/gocql/gocql/cluster.go | 2 +- .../github.com/gocql/gocql/compressor_test.go | 40 - .../src/github.com/gocql/gocql/conn.go | 21 +- .../src/github.com/gocql/gocql/conn_test.go | 817 -- .../github.com/gocql/gocql/connectionpool.go | 2 +- .../src/github.com/gocql/gocql/errors.go | 48 +- .../src/github.com/gocql/gocql/errors_test.go | 29 - .../src/github.com/gocql/gocql/frame.go | 192 +- .../src/github.com/gocql/gocql/frame_test.go | 98 - .../src/github.com/gocql/gocql/helpers.go | 4 +- .../src/github.com/gocql/gocql/integration.sh | 4 + .../src/github.com/gocql/gocql/lru/lru.go | 123 + .../src/github.com/gocql/gocql/marshal.go | 82 +- .../github.com/gocql/gocql/marshal_test.go | 862 --- .../src/github.com/gocql/gocql/metadata.go | 70 +- .../github.com/gocql/gocql/metadata_test.go | 815 -- .../src/github.com/gocql/gocql/murmur.go | 139 + .../gocql/gocql/murmur_appengine.go | 137 + .../github.com/gocql/gocql/policies_test.go | 125 - .../src/github.com/gocql/gocql/session.go | 55 +- .../github.com/gocql/gocql/session_test.go | 255 - .../src/github.com/gocql/gocql/stress_test.go | 40 - .../gocql/gocql/testdata/pki/.keystore | 3 - .../gocql/gocql/testdata/pki/.truststore | 3 - .../gocql/gocql/testdata/pki/ca.crt | 20 - .../gocql/gocql/testdata/pki/ca.key | 30 - .../gocql/gocql/testdata/pki/cassandra.crt | 83 - .../gocql/gocql/testdata/pki/cassandra.key | 27 - .../gocql/gocql/testdata/pki/gocql.crt | 83 - .../gocql/gocql/testdata/pki/gocql.key | 27 - .../src/github.com/gocql/gocql/token.go | 133 - .../src/github.com/gocql/gocql/token_test.go | 474 -- .../github.com/gocql/gocql/topology_test.go | 51 - .../src/github.com/gocql/gocql/tuple_test.go | 51 - .../src/github.com/gocql/gocql/udt_test.go | 254 - .../src/github.com/gocql/gocql/uuid_test.go | 197 - .../src/github.com/gocql/gocql/wiki_test.go | 274 - .../github.com/golang/snappy/snappy_test.go | 377 - .../go-github/github/activity_events.go | 4 +- .../go-github/github/activity_events_test.go | 305 - .../github/activity_notifications.go | 1 + .../github/activity_notifications_test.go | 203 - .../go-github/github/activity_star_test.go | 170 - .../github/activity_watching_test.go | 177 - .../go-github/github/gists_comments_test.go | 155 - .../google/go-github/github/gists_test.go | 411 - .../google/go-github/github/git_blobs_test.go | 92 - .../go-github/github/git_commits_test.go | 82 - .../google/go-github/github/git_refs_test.go | 280 - .../google/go-github/github/git_tags_test.go | 68 - .../google/go-github/github/git_trees_test.go | 189 - .../google/go-github/github/github.go | 2 +- .../google/go-github/github/github_test.go | 679 -- .../google/go-github/github/gitignore_test.go | 58 - .../go-github/github/issues_assignees_test.go | 98 - .../go-github/github/issues_comments_test.go | 184 - .../go-github/github/issues_events_test.go | 86 - .../go-github/github/issues_labels_test.go | 313 - .../go-github/github/issues_milestones.go | 6 +- .../github/issues_milestones_test.go | 157 - .../google/go-github/github/issues_test.go | 242 - .../google/go-github/github/licenses_test.go | 64 - .../google/go-github/github/misc_test.go | 170 - .../go-github/github/orgs_hooks_test.go | 134 - .../go-github/github/orgs_members_test.go | 356 - .../go-github/github/orgs_teams_test.go | 506 -- .../google/go-github/github/orgs_test.go | 120 - .../google/go-github/github/pulls_comments.go | 19 +- .../go-github/github/pulls_comments_test.go | 189 - .../google/go-github/github/pulls_test.go | 365 - .../github/repos_collaborators_test.go | 135 - .../go-github/github/repos_comments_test.go | 180 - .../go-github/github/repos_commits_test.go | 191 - .../go-github/github/repos_contents_test.go | 304 - .../github/repos_deployments_test.go | 87 - .../go-github/github/repos_forks_test.go | 73 - .../go-github/github/repos_hooks_test.go | 187 - .../go-github/github/repos_keys_test.go | 153 - .../go-github/github/repos_merging_test.go | 47 - .../go-github/github/repos_pages_test.go | 73 - .../go-github/github/repos_releases_test.go | 277 - .../go-github/github/repos_stats_test.go | 210 - .../go-github/github/repos_statuses_test.go | 96 - .../google/go-github/github/repos_test.go | 409 - .../google/go-github/github/search_test.go | 196 - .../google/go-github/github/strings_test.go | 137 - .../google/go-github/github/timestamp_test.go | 181 - .../google/go-github/github/users.go | 2 +- .../github/users_administration_test.go | 71 - .../go-github/github/users_emails_test.go | 94 - .../go-github/github/users_followers_test.go | 222 - .../go-github/github/users_keys_test.go | 124 - .../google/go-github/github/users_test.go | 150 - .../go-querystring/query/encode_test.go | 286 - .../hashicorp/consul/api/acl_test.go | 128 - .../hashicorp/consul/api/agent_test.go | 524 -- .../github.com/hashicorp/consul/api/api.go | 2 +- .../hashicorp/consul/api/api_test.go | 252 - .../hashicorp/consul/api/catalog_test.go | 279 - .../hashicorp/consul/api/event_test.go | 49 - .../github.com/hashicorp/consul/api/health.go | 2 +- .../hashicorp/consul/api/health_test.go | 125 - .../src/github.com/hashicorp/consul/api/kv.go | 2 +- .../hashicorp/consul/api/kv_test.go | 447 -- .../hashicorp/consul/api/lock_test.go | 363 - .../hashicorp/consul/api/semaphore.go | 4 +- .../hashicorp/consul/api/semaphore_test.go | 313 - .../hashicorp/consul/api/session.go | 2 +- .../hashicorp/consul/api/session_test.go | 205 - .../hashicorp/consul/api/status_test.go | 37 - .../hashicorp/errwrap/errwrap_test.go | 94 - .../hashicorp/go-multierror/append.go | 15 +- .../hashicorp/go-multierror/append_test.go | 45 - .../hashicorp/go-multierror/flatten_test.go | 48 - .../hashicorp/go-multierror/format_test.go | 23 - .../go-multierror/multierror_test.go | 70 - .../hashicorp/go-multierror/prefix.go | 37 + .../hashicorp/golang-lru/lru_test.go | 157 - .../github.com/hashicorp/hcl/decoder_test.go | 481 -- .../github.com/hashicorp/hcl/hcl/hcl_test.go | 4 - .../src/github.com/hashicorp/hcl/hcl/lex.go | 23 +- .../github.com/hashicorp/hcl/hcl/lex_test.go | 95 - .../src/github.com/hashicorp/hcl/hcl/parse.y | 10 +- .../hashicorp/hcl/hcl/parse_test.go | 75 - .../src/github.com/hashicorp/hcl/hcl/y.go | 399 +- .../src/github.com/hashicorp/hcl/hcl_test.go | 19 - .../hashicorp/hcl/json/json_test.go | 4 - .../github.com/hashicorp/hcl/json/lex_test.go | 78 - .../hashicorp/hcl/json/parse_test.go | 43 - .../src/github.com/hashicorp/hcl/json/y.go | 273 +- .../src/github.com/hashicorp/hcl/lex_test.go | 37 - .../logutils/level_benchmark_test.go | 37 - .../hashicorp/logutils/level_test.go | 94 - .../github.com/kardianos/osext/osext_test.go | 203 - .../src/github.com/lib/pq/bench_test.go | 435 -- .../src/github.com/lib/pq/conn_test.go | 1306 ---- .../src/github.com/lib/pq/copy_test.go | 462 -- .../src/github.com/lib/pq/encode_test.go | 719 -- .../github.com/lib/pq/hstore/hstore_test.go | 148 - .../src/github.com/lib/pq/notify_test.go | 574 -- .../src/github.com/lib/pq/ssl_test.go | 226 - .../src/github.com/lib/pq/url_test.go | 54 - .../src/github.com/mitchellh/cli/cli_test.go | 252 - .../mitchellh/cli/command_mock_test.go | 9 - .../mitchellh/cli/ui_colored_test.go | 74 - .../mitchellh/cli/ui_concurrent_test.go | 9 - .../github.com/mitchellh/cli/ui_mock_test.go | 9 - .../src/github.com/mitchellh/cli/ui_test.go | 162 - .../mitchellh/cli/ui_writer_test.go | 24 - .../copystructure/copier_time_test.go | 17 - .../copystructure_examples_test.go | 22 - .../copystructure/copystructure_test.go | 175 - .../mitchellh/go-homedir/homedir.go | 36 +- .../mitchellh/go-homedir/homedir_test.go | 98 - .../mapstructure/decode_hooks_test.go | 229 - .../mapstructure_benchmark_test.go | 279 - .../mapstructure/mapstructure_bugs_test.go | 47 - .../mapstructure_examples_test.go | 203 - .../mapstructure/mapstructure_test.go | 999 --- .../mitchellh/reflectwalk/reflectwalk_test.go | 377 - .../github.com/ryanuber/columnize/README.md | 2 + .../ryanuber/columnize/columnize.go | 24 +- .../ryanuber/columnize/columnize_test.go | 224 - .../samuel/go-zookeeper/zk/cluster_test.go | 166 - .../samuel/go-zookeeper/zk/constants_test.go | 24 - .../samuel/go-zookeeper/zk/flw_test.go | 367 - .../samuel/go-zookeeper/zk/lock_test.go | 94 - .../samuel/go-zookeeper/zk/structs_test.go | 71 - .../samuel/go-zookeeper/zk/util_test.go | 17 - .../samuel/go-zookeeper/zk/zk_test.go | 518 -- .../src/github.com/ugorji/go/codec/binc.go | 10 +- .../github.com/ugorji/go/codec/cbor_test.go | 205 - .../github.com/ugorji/go/codec/codec_test.go | 1117 --- .../ugorji/go/codec/codecgen/gen.go | 22 +- .../ugorji/go/codec/codecgen_test.go | 22 - .../src/github.com/ugorji/go/codec/decode.go | 228 +- .../src/github.com/ugorji/go/codec/encode.go | 266 +- .../ugorji/go/codec/fast-path.generated.go | 6477 +++------------- .../ugorji/go/codec/fast-path.go.tmpl | 57 +- .../ugorji/go/codec/gen-dec-array.go.tmpl | 3 - .../ugorji/go/codec/gen-dec-map.go.tmpl | 6 +- .../ugorji/go/codec/gen-helper.generated.go | 113 + .../ugorji/go/codec/gen-helper.go.tmpl | 101 +- .../ugorji/go/codec/gen.generated.go | 9 +- .../src/github.com/ugorji/go/codec/gen.go | 501 +- .../src/github.com/ugorji/go/codec/helper.go | 62 +- .../github.com/ugorji/go/codec/helper_test.go | 155 - .../src/github.com/ugorji/go/codec/json.go | 242 +- .../src/github.com/ugorji/go/codec/msgpack.go | 14 +- .../src/github.com/ugorji/go/codec/noop.go | 45 +- .../github.com/ugorji/go/codec/prebuild.sh | 4 +- .../src/github.com/ugorji/go/codec/py_test.go | 29 - .../src/github.com/ugorji/go/codec/test.py | 5 +- .../src/github.com/ugorji/go/codec/tests.sh | 55 + .../github.com/ugorji/go/codec/values_test.go | 203 - .../vaughan0/go-ini/ini_linux_test.go | 43 - .../github.com/vaughan0/go-ini/ini_test.go | 89 - .../golang.org/x/crypto/bcrypt/bcrypt_test.go | 226 - .../x/crypto/blowfish/blowfish_test.go | 274 - .../golang.org/x/crypto/cast5/cast5_test.go | 106 - .../x/crypto/curve25519/curve25519_test.go | 29 - .../x/crypto/openpgp/armor/armor_test.go | 95 - .../x/crypto/openpgp/canonical_text_test.go | 52 - .../x/crypto/openpgp/clearsign/clearsign.go | 22 +- .../openpgp/clearsign/clearsign_test.go | 187 - .../x/crypto/openpgp/elgamal/elgamal_test.go | 49 - .../golang.org/x/crypto/openpgp/keys_test.go | 370 - .../crypto/openpgp/packet/compressed_test.go | 41 - .../openpgp/packet/encrypted_key_test.go | 146 - .../x/crypto/openpgp/packet/ocfb_test.go | 46 - .../x/crypto/openpgp/packet/opaque_test.go | 67 - .../x/crypto/openpgp/packet/packet_test.go | 255 - .../crypto/openpgp/packet/private_key_test.go | 69 - .../crypto/openpgp/packet/public_key_test.go | 202 - .../openpgp/packet/public_key_v3_test.go | 82 - .../x/crypto/openpgp/packet/signature_test.go | 42 - .../openpgp/packet/signature_v3_test.go | 92 - .../packet/symmetric_key_encrypted_test.go | 102 - .../packet/symmetrically_encrypted_test.go | 123 - .../openpgp/packet/userattribute_test.go | 109 - .../x/crypto/openpgp/packet/userid_test.go | 87 - .../src/golang.org/x/crypto/openpgp/read.go | 78 +- .../golang.org/x/crypto/openpgp/read_test.go | 493 -- .../x/crypto/openpgp/s2k/s2k_test.go | 137 - .../golang.org/x/crypto/openpgp/write_test.go | 259 - .../x/crypto/ssh/agent/client_test.go | 287 - .../x/crypto/ssh/agent/server_test.go | 77 - .../x/crypto/ssh/agent/testdata_test.go | 64 - .../golang.org/x/crypto/ssh/benchmark_test.go | 122 - .../golang.org/x/crypto/ssh/buffer_test.go | 87 - .../src/golang.org/x/crypto/ssh/certs_test.go | 216 - .../golang.org/x/crypto/ssh/cipher_test.go | 127 - .../x/crypto/ssh/client_auth_test.go | 393 - .../golang.org/x/crypto/ssh/client_test.go | 39 - .../src/golang.org/x/crypto/ssh/common.go | 62 +- .../golang.org/x/crypto/ssh/example_test.go | 211 - .../src/golang.org/x/crypto/ssh/handshake.go | 6 +- .../golang.org/x/crypto/ssh/handshake_test.go | 415 -- .../src/golang.org/x/crypto/ssh/kex_test.go | 50 - .../src/golang.org/x/crypto/ssh/keys.go | 22 +- .../src/golang.org/x/crypto/ssh/keys_test.go | 306 - .../golang.org/x/crypto/ssh/mempipe_test.go | 110 - .../golang.org/x/crypto/ssh/messages_test.go | 254 - .../src/golang.org/x/crypto/ssh/mux_test.go | 525 -- .../golang.org/x/crypto/ssh/session_test.go | 774 -- .../src/golang.org/x/crypto/ssh/tcpip_test.go | 20 - .../x/crypto/ssh/terminal/terminal_test.go | 269 - .../x/crypto/ssh/test/agent_unix_test.go | 59 - .../golang.org/x/crypto/ssh/test/cert_test.go | 47 - .../x/crypto/ssh/test/forward_unix_test.go | 160 - .../x/crypto/ssh/test/session_test.go | 340 - .../x/crypto/ssh/test/tcpip_test.go | 46 - .../x/crypto/ssh/test/test_unix_test.go | 261 - .../x/crypto/ssh/test/testdata_test.go | 64 - .../golang.org/x/crypto/ssh/testdata/doc.go | 8 - .../golang.org/x/crypto/ssh/testdata/keys.go | 43 - .../golang.org/x/crypto/ssh/testdata_test.go | 63 - .../golang.org/x/crypto/ssh/transport_test.go | 109 - .../golang.org/x/net/context/context_test.go | 575 -- .../x/net/context/ctxhttp/ctxhttp_test.go | 72 - .../x/net/context/withtimeout_test.go | 26 - .../x/oauth2/bitbucket/bitbucket.go | 16 + .../golang.org/x/oauth2/client_appengine.go | 2 +- .../clientcredentials_test.go | 96 - .../src/golang.org/x/oauth2/example_test.go | 45 - .../golang.org/x/oauth2/google/appengine.go | 3 + .../x/oauth2/google/appengine_hook.go | 2 +- .../x/oauth2/google/appenginevm_hook.go | 14 + .../src/golang.org/x/oauth2/google/default.go | 5 +- .../x/oauth2/google/example_test.go | 150 - .../golang.org/x/oauth2/google/google_test.go | 67 - .../src/golang.org/x/oauth2/google/jwt.go | 6 +- .../golang.org/x/oauth2/google/sdk_test.go | 46 - .../oauth2/google/testdata/gcloud/credentials | 122 - .../oauth2/google/testdata/gcloud/properties | 2 - .../x/oauth2/internal/oauth2_test.go | 62 - .../x/oauth2/internal/token_test.go | 28 - .../src/golang.org/x/oauth2/jws/jws.go | 25 +- .../golang.org/x/oauth2/jwt/example_test.go | 31 - .../src/golang.org/x/oauth2/jwt/jwt.go | 6 + .../src/golang.org/x/oauth2/jwt/jwt_test.go | 134 - .../src/golang.org/x/oauth2/oauth2_test.go | 422 -- .../src/golang.org/x/oauth2/token_test.go | 50 - .../src/golang.org/x/oauth2/transport_test.go | 86 - .../src/gopkg.in/asn1-ber.v1/ber_test.go | 158 - Godeps/_workspace/src/gopkg.in/inf.v0/LICENSE | 33 +- .../src/gopkg.in/inf.v0/benchmark_test.go | 210 - .../src/gopkg.in/inf.v0/dec_go1_2_test.go | 33 - .../src/gopkg.in/inf.v0/dec_internal_test.go | 40 - .../src/gopkg.in/inf.v0/dec_test.go | 379 - .../src/gopkg.in/inf.v0/example_test.go | 62 - .../gopkg.in/inf.v0/rounder_example_test.go | 72 - .../src/gopkg.in/inf.v0/rounder_test.go | 109 - 431 files changed, 8448 insertions(+), 85463 deletions(-) create mode 100644 Godeps/_workspace/src/github.com/armon/go-metrics/datadog/dogstatsd.go delete mode 100644 Godeps/_workspace/src/github.com/armon/go-metrics/inmem_signal_test.go delete mode 100644 Godeps/_workspace/src/github.com/armon/go-metrics/inmem_test.go delete mode 100644 Godeps/_workspace/src/github.com/armon/go-metrics/metrics_test.go delete mode 100644 Godeps/_workspace/src/github.com/armon/go-metrics/sink_test.go delete mode 100644 Godeps/_workspace/src/github.com/armon/go-metrics/start_test.go delete mode 100644 Godeps/_workspace/src/github.com/armon/go-metrics/statsd_test.go delete mode 100644 Godeps/_workspace/src/github.com/armon/go-metrics/statsite_test.go delete mode 100644 Godeps/_workspace/src/github.com/armon/go-radix/radix_test.go delete mode 100644 Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/awsutil/copy_test.go delete mode 100644 Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/awsutil/path_value_test.go delete mode 100644 Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/config_test.go delete mode 100644 Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/convert_types_test.go rename Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/{service/handler_functions.go => corehandlers/handlers.go} (70%) create mode 100644 Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/corehandlers/param_validator.go delete mode 100644 Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/chain_provider_test.go delete mode 100644 Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/credentials_test.go delete mode 100644 Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds/ec2_role_provider_test.go delete mode 100644 Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/env_provider_test.go delete mode 100644 Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/shared_credentials_provider_test.go delete mode 100644 Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/static_provider_test.go delete mode 100644 Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/stscreds/assume_role_provider_test.go delete mode 100644 Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/ec2metadata/api_test.go create mode 100644 Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/errors.go rename Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/{service => request}/handlers.go (57%) rename Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/{service => request}/request.go (88%) create mode 100644 Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/request/retryer.go create mode 100644 Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/service/default_retryer.go delete mode 100644 Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/service/handler_functions_test.go delete mode 100644 Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/service/handlers_test.go delete mode 100644 Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/service/param_validator.go delete mode 100644 Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/service/param_validator_test.go delete mode 100644 Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/service/request_pagination_test.go delete mode 100644 Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/service/request_test.go create mode 100644 Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/service/serviceinfo/service_info.go delete mode 100644 Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/types_test.go delete mode 100644 Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/endpoints/endpoints_test.go delete mode 100644 Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/ec2query/build_test.go delete mode 100644 Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/ec2query/unmarshal_test.go delete mode 100644 Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/query/build_test.go delete mode 100644 Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/query/unmarshal_test.go delete mode 100644 Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/restxml/build_test.go delete mode 100644 Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/restxml/unmarshal_test.go delete mode 100644 Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/signer/v4/functional_test.go delete mode 100644 Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/signer/v4/v4_test.go delete mode 100644 Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/ec2/customizations_test.go delete mode 100644 Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/ec2/ec2iface/interface_test.go delete mode 100644 Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/ec2/examples_test.go delete mode 100644 Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/iam/examples_test.go delete mode 100644 Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/iam/iamiface/interface_test.go delete mode 100644 Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/bucket_location_test.go delete mode 100644 Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/customizations_test.go delete mode 100644 Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/examples_test.go delete mode 100644 Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/host_style_bucket_test.go delete mode 100644 Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/s3iface/interface_test.go delete mode 100644 Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/s3manager/download_test.go delete mode 100644 Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/s3manager/upload_test.go delete mode 100644 Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/sse_test.go create mode 100644 Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/statusok_error.go delete mode 100644 Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/unmarshal_error_test.go delete mode 100644 Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/add_child_test.go delete mode 100644 Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/client_test.go delete mode 100644 Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/compare_and_delete_test.go delete mode 100644 Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/compare_and_swap_test.go delete mode 100644 Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/debug_test.go delete mode 100644 Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/delete_test.go delete mode 100644 Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/get_test.go delete mode 100644 Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/member_test.go delete mode 100644 Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/response_test.go delete mode 100644 Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/set_curl_chan_test.go delete mode 100644 Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/set_update_create_test.go delete mode 100644 Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/watch_test.go delete mode 100644 Godeps/_workspace/src/github.com/dgrijalva/jwt-go/ecdsa_test.go delete mode 100644 Godeps/_workspace/src/github.com/dgrijalva/jwt-go/example_test.go delete mode 100644 Godeps/_workspace/src/github.com/dgrijalva/jwt-go/hmac_test.go delete mode 100644 Godeps/_workspace/src/github.com/dgrijalva/jwt-go/jwt_test.go delete mode 100644 Godeps/_workspace/src/github.com/dgrijalva/jwt-go/rsa_pss_test.go delete mode 100644 Godeps/_workspace/src/github.com/dgrijalva/jwt-go/rsa_test.go delete mode 100644 Godeps/_workspace/src/github.com/duosecurity/duo_api_golang/authapi/authapi_test.go delete mode 100644 Godeps/_workspace/src/github.com/duosecurity/duo_api_golang/duo_test.go delete mode 100644 Godeps/_workspace/src/github.com/fatih/structs/field_test.go delete mode 100644 Godeps/_workspace/src/github.com/fatih/structs/structs_example_test.go delete mode 100644 Godeps/_workspace/src/github.com/fatih/structs/structs_test.go delete mode 100644 Godeps/_workspace/src/github.com/fatih/structs/tags_test.go delete mode 100644 Godeps/_workspace/src/github.com/go-ldap/ldap/dn_test.go delete mode 100644 Godeps/_workspace/src/github.com/go-ldap/ldap/example_test.go delete mode 100644 Godeps/_workspace/src/github.com/go-ldap/ldap/filter_test.go delete mode 100644 Godeps/_workspace/src/github.com/go-ldap/ldap/ldap_test.go delete mode 100644 Godeps/_workspace/src/github.com/go-sql-driver/mysql/benchmark_test.go delete mode 100644 Godeps/_workspace/src/github.com/go-sql-driver/mysql/driver_test.go delete mode 100644 Godeps/_workspace/src/github.com/go-sql-driver/mysql/errors_test.go delete mode 100644 Godeps/_workspace/src/github.com/go-sql-driver/mysql/utils_test.go delete mode 100644 Godeps/_workspace/src/github.com/gocql/gocql/cass1batch_test.go delete mode 100644 Godeps/_workspace/src/github.com/gocql/gocql/cassandra_test.go delete mode 100644 Godeps/_workspace/src/github.com/gocql/gocql/compressor_test.go delete mode 100644 Godeps/_workspace/src/github.com/gocql/gocql/conn_test.go delete mode 100644 Godeps/_workspace/src/github.com/gocql/gocql/errors_test.go delete mode 100644 Godeps/_workspace/src/github.com/gocql/gocql/frame_test.go create mode 100644 Godeps/_workspace/src/github.com/gocql/gocql/lru/lru.go delete mode 100644 Godeps/_workspace/src/github.com/gocql/gocql/marshal_test.go delete mode 100644 Godeps/_workspace/src/github.com/gocql/gocql/metadata_test.go create mode 100644 Godeps/_workspace/src/github.com/gocql/gocql/murmur.go create mode 100644 Godeps/_workspace/src/github.com/gocql/gocql/murmur_appengine.go delete mode 100644 Godeps/_workspace/src/github.com/gocql/gocql/policies_test.go delete mode 100644 Godeps/_workspace/src/github.com/gocql/gocql/session_test.go delete mode 100644 Godeps/_workspace/src/github.com/gocql/gocql/stress_test.go delete mode 100644 Godeps/_workspace/src/github.com/gocql/gocql/testdata/pki/.keystore delete mode 100644 Godeps/_workspace/src/github.com/gocql/gocql/testdata/pki/.truststore delete mode 100644 Godeps/_workspace/src/github.com/gocql/gocql/testdata/pki/ca.crt delete mode 100644 Godeps/_workspace/src/github.com/gocql/gocql/testdata/pki/ca.key delete mode 100644 Godeps/_workspace/src/github.com/gocql/gocql/testdata/pki/cassandra.crt delete mode 100644 Godeps/_workspace/src/github.com/gocql/gocql/testdata/pki/cassandra.key delete mode 100644 Godeps/_workspace/src/github.com/gocql/gocql/testdata/pki/gocql.crt delete mode 100644 Godeps/_workspace/src/github.com/gocql/gocql/testdata/pki/gocql.key delete mode 100644 Godeps/_workspace/src/github.com/gocql/gocql/token_test.go delete mode 100644 Godeps/_workspace/src/github.com/gocql/gocql/topology_test.go delete mode 100644 Godeps/_workspace/src/github.com/gocql/gocql/tuple_test.go delete mode 100644 Godeps/_workspace/src/github.com/gocql/gocql/udt_test.go delete mode 100644 Godeps/_workspace/src/github.com/gocql/gocql/uuid_test.go delete mode 100644 Godeps/_workspace/src/github.com/gocql/gocql/wiki_test.go delete mode 100644 Godeps/_workspace/src/github.com/golang/snappy/snappy_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/go-github/github/activity_events_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/go-github/github/activity_notifications_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/go-github/github/activity_star_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/go-github/github/activity_watching_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/go-github/github/gists_comments_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/go-github/github/gists_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/go-github/github/git_blobs_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/go-github/github/git_commits_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/go-github/github/git_refs_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/go-github/github/git_tags_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/go-github/github/git_trees_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/go-github/github/github_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/go-github/github/gitignore_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/go-github/github/issues_assignees_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/go-github/github/issues_comments_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/go-github/github/issues_events_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/go-github/github/issues_labels_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/go-github/github/issues_milestones_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/go-github/github/issues_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/go-github/github/licenses_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/go-github/github/misc_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/go-github/github/orgs_hooks_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/go-github/github/orgs_members_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/go-github/github/orgs_teams_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/go-github/github/orgs_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/go-github/github/pulls_comments_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/go-github/github/pulls_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/go-github/github/repos_collaborators_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/go-github/github/repos_comments_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/go-github/github/repos_commits_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/go-github/github/repos_contents_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/go-github/github/repos_deployments_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/go-github/github/repos_forks_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/go-github/github/repos_hooks_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/go-github/github/repos_keys_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/go-github/github/repos_merging_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/go-github/github/repos_pages_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/go-github/github/repos_releases_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/go-github/github/repos_stats_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/go-github/github/repos_statuses_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/go-github/github/repos_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/go-github/github/search_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/go-github/github/strings_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/go-github/github/timestamp_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/go-github/github/users_administration_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/go-github/github/users_emails_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/go-github/github/users_followers_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/go-github/github/users_keys_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/go-github/github/users_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/go-querystring/query/encode_test.go delete mode 100644 Godeps/_workspace/src/github.com/hashicorp/consul/api/acl_test.go delete mode 100644 Godeps/_workspace/src/github.com/hashicorp/consul/api/agent_test.go delete mode 100644 Godeps/_workspace/src/github.com/hashicorp/consul/api/api_test.go delete mode 100644 Godeps/_workspace/src/github.com/hashicorp/consul/api/catalog_test.go delete mode 100644 Godeps/_workspace/src/github.com/hashicorp/consul/api/event_test.go delete mode 100644 Godeps/_workspace/src/github.com/hashicorp/consul/api/health_test.go delete mode 100644 Godeps/_workspace/src/github.com/hashicorp/consul/api/kv_test.go delete mode 100644 Godeps/_workspace/src/github.com/hashicorp/consul/api/lock_test.go delete mode 100644 Godeps/_workspace/src/github.com/hashicorp/consul/api/semaphore_test.go delete mode 100644 Godeps/_workspace/src/github.com/hashicorp/consul/api/session_test.go delete mode 100644 Godeps/_workspace/src/github.com/hashicorp/consul/api/status_test.go delete mode 100644 Godeps/_workspace/src/github.com/hashicorp/errwrap/errwrap_test.go delete mode 100644 Godeps/_workspace/src/github.com/hashicorp/go-multierror/append_test.go delete mode 100644 Godeps/_workspace/src/github.com/hashicorp/go-multierror/flatten_test.go delete mode 100644 Godeps/_workspace/src/github.com/hashicorp/go-multierror/format_test.go delete mode 100644 Godeps/_workspace/src/github.com/hashicorp/go-multierror/multierror_test.go create mode 100644 Godeps/_workspace/src/github.com/hashicorp/go-multierror/prefix.go delete mode 100644 Godeps/_workspace/src/github.com/hashicorp/golang-lru/lru_test.go delete mode 100644 Godeps/_workspace/src/github.com/hashicorp/hcl/decoder_test.go delete mode 100644 Godeps/_workspace/src/github.com/hashicorp/hcl/hcl/hcl_test.go delete mode 100644 Godeps/_workspace/src/github.com/hashicorp/hcl/hcl/lex_test.go delete mode 100644 Godeps/_workspace/src/github.com/hashicorp/hcl/hcl/parse_test.go delete mode 100644 Godeps/_workspace/src/github.com/hashicorp/hcl/hcl_test.go delete mode 100644 Godeps/_workspace/src/github.com/hashicorp/hcl/json/json_test.go delete mode 100644 Godeps/_workspace/src/github.com/hashicorp/hcl/json/lex_test.go delete mode 100644 Godeps/_workspace/src/github.com/hashicorp/hcl/json/parse_test.go delete mode 100644 Godeps/_workspace/src/github.com/hashicorp/hcl/lex_test.go delete mode 100644 Godeps/_workspace/src/github.com/hashicorp/logutils/level_benchmark_test.go delete mode 100644 Godeps/_workspace/src/github.com/hashicorp/logutils/level_test.go delete mode 100644 Godeps/_workspace/src/github.com/kardianos/osext/osext_test.go delete mode 100644 Godeps/_workspace/src/github.com/lib/pq/bench_test.go delete mode 100644 Godeps/_workspace/src/github.com/lib/pq/conn_test.go delete mode 100644 Godeps/_workspace/src/github.com/lib/pq/copy_test.go delete mode 100644 Godeps/_workspace/src/github.com/lib/pq/encode_test.go delete mode 100644 Godeps/_workspace/src/github.com/lib/pq/hstore/hstore_test.go delete mode 100644 Godeps/_workspace/src/github.com/lib/pq/notify_test.go delete mode 100644 Godeps/_workspace/src/github.com/lib/pq/ssl_test.go delete mode 100644 Godeps/_workspace/src/github.com/lib/pq/url_test.go delete mode 100644 Godeps/_workspace/src/github.com/mitchellh/cli/cli_test.go delete mode 100644 Godeps/_workspace/src/github.com/mitchellh/cli/command_mock_test.go delete mode 100644 Godeps/_workspace/src/github.com/mitchellh/cli/ui_colored_test.go delete mode 100644 Godeps/_workspace/src/github.com/mitchellh/cli/ui_concurrent_test.go delete mode 100644 Godeps/_workspace/src/github.com/mitchellh/cli/ui_mock_test.go delete mode 100644 Godeps/_workspace/src/github.com/mitchellh/cli/ui_test.go delete mode 100644 Godeps/_workspace/src/github.com/mitchellh/cli/ui_writer_test.go delete mode 100644 Godeps/_workspace/src/github.com/mitchellh/copystructure/copier_time_test.go delete mode 100644 Godeps/_workspace/src/github.com/mitchellh/copystructure/copystructure_examples_test.go delete mode 100644 Godeps/_workspace/src/github.com/mitchellh/copystructure/copystructure_test.go delete mode 100644 Godeps/_workspace/src/github.com/mitchellh/go-homedir/homedir_test.go delete mode 100644 Godeps/_workspace/src/github.com/mitchellh/mapstructure/decode_hooks_test.go delete mode 100644 Godeps/_workspace/src/github.com/mitchellh/mapstructure/mapstructure_benchmark_test.go delete mode 100644 Godeps/_workspace/src/github.com/mitchellh/mapstructure/mapstructure_bugs_test.go delete mode 100644 Godeps/_workspace/src/github.com/mitchellh/mapstructure/mapstructure_examples_test.go delete mode 100644 Godeps/_workspace/src/github.com/mitchellh/mapstructure/mapstructure_test.go delete mode 100644 Godeps/_workspace/src/github.com/mitchellh/reflectwalk/reflectwalk_test.go delete mode 100644 Godeps/_workspace/src/github.com/ryanuber/columnize/columnize_test.go delete mode 100644 Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/cluster_test.go delete mode 100644 Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/constants_test.go delete mode 100644 Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/flw_test.go delete mode 100644 Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/lock_test.go delete mode 100644 Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/structs_test.go delete mode 100644 Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/util_test.go delete mode 100644 Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/zk_test.go delete mode 100644 Godeps/_workspace/src/github.com/ugorji/go/codec/cbor_test.go delete mode 100644 Godeps/_workspace/src/github.com/ugorji/go/codec/codec_test.go delete mode 100644 Godeps/_workspace/src/github.com/ugorji/go/codec/codecgen_test.go delete mode 100644 Godeps/_workspace/src/github.com/ugorji/go/codec/helper_test.go delete mode 100644 Godeps/_workspace/src/github.com/ugorji/go/codec/py_test.go create mode 100644 Godeps/_workspace/src/github.com/ugorji/go/codec/tests.sh delete mode 100644 Godeps/_workspace/src/github.com/ugorji/go/codec/values_test.go delete mode 100644 Godeps/_workspace/src/github.com/vaughan0/go-ini/ini_linux_test.go delete mode 100644 Godeps/_workspace/src/github.com/vaughan0/go-ini/ini_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/bcrypt/bcrypt_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/blowfish/blowfish_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/cast5/cast5_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/curve25519/curve25519_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/openpgp/armor/armor_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/openpgp/canonical_text_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/openpgp/clearsign/clearsign_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/openpgp/elgamal/elgamal_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/openpgp/keys_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/openpgp/packet/compressed_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/openpgp/packet/encrypted_key_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/openpgp/packet/ocfb_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/openpgp/packet/opaque_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/openpgp/packet/packet_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/openpgp/packet/private_key_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/openpgp/packet/public_key_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/openpgp/packet/public_key_v3_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/openpgp/packet/signature_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/openpgp/packet/signature_v3_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/openpgp/packet/symmetric_key_encrypted_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/openpgp/packet/symmetrically_encrypted_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/openpgp/packet/userattribute_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/openpgp/packet/userid_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/openpgp/read_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/openpgp/s2k/s2k_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/openpgp/write_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/ssh/agent/client_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/ssh/agent/server_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/ssh/agent/testdata_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/ssh/benchmark_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/ssh/buffer_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/ssh/certs_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/ssh/cipher_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/ssh/client_auth_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/ssh/client_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/ssh/example_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/ssh/handshake_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/ssh/kex_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/ssh/keys_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/ssh/mempipe_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/ssh/messages_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/ssh/mux_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/ssh/session_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/ssh/tcpip_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/ssh/terminal/terminal_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/ssh/test/agent_unix_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/ssh/test/cert_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/ssh/test/forward_unix_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/ssh/test/session_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/ssh/test/tcpip_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/ssh/test/test_unix_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/ssh/test/testdata_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/ssh/testdata/doc.go delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/ssh/testdata/keys.go delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/ssh/testdata_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/ssh/transport_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/net/context/context_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/net/context/ctxhttp/ctxhttp_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/net/context/withtimeout_test.go create mode 100644 Godeps/_workspace/src/golang.org/x/oauth2/bitbucket/bitbucket.go delete mode 100644 Godeps/_workspace/src/golang.org/x/oauth2/clientcredentials/clientcredentials_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/oauth2/example_test.go create mode 100644 Godeps/_workspace/src/golang.org/x/oauth2/google/appenginevm_hook.go delete mode 100644 Godeps/_workspace/src/golang.org/x/oauth2/google/example_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/oauth2/google/google_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/oauth2/google/sdk_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/oauth2/google/testdata/gcloud/credentials delete mode 100644 Godeps/_workspace/src/golang.org/x/oauth2/google/testdata/gcloud/properties delete mode 100644 Godeps/_workspace/src/golang.org/x/oauth2/internal/oauth2_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/oauth2/internal/token_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/oauth2/jwt/example_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/oauth2/jwt/jwt_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/oauth2/oauth2_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/oauth2/token_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/oauth2/transport_test.go delete mode 100644 Godeps/_workspace/src/gopkg.in/asn1-ber.v1/ber_test.go delete mode 100644 Godeps/_workspace/src/gopkg.in/inf.v0/benchmark_test.go delete mode 100644 Godeps/_workspace/src/gopkg.in/inf.v0/dec_go1_2_test.go delete mode 100644 Godeps/_workspace/src/gopkg.in/inf.v0/dec_internal_test.go delete mode 100644 Godeps/_workspace/src/gopkg.in/inf.v0/dec_test.go delete mode 100644 Godeps/_workspace/src/gopkg.in/inf.v0/example_test.go delete mode 100644 Godeps/_workspace/src/gopkg.in/inf.v0/rounder_example_test.go delete mode 100644 Godeps/_workspace/src/gopkg.in/inf.v0/rounder_test.go diff --git a/Godeps/Godeps.json b/Godeps/Godeps.json index 3afaa09e3..c880b13a7 100644 --- a/Godeps/Godeps.json +++ b/Godeps/Godeps.json @@ -7,7 +7,7 @@ "Deps": [ { "ImportPath": "github.com/armon/go-metrics", - "Rev": "b2d95e5291cdbc26997d1301a5e467ecbb240e25" + "Rev": "6c5fa0d8f48f4661c9ba8709799c88d425ad20f0" }, { "ImportPath": "github.com/armon/go-radix", @@ -15,68 +15,68 @@ }, { "ImportPath": "github.com/aws/aws-sdk-go/aws", - "Comment": "v0.9.0rc1-13-g87dbf7e", - "Rev": "87dbf7e29df163bd17d9cea9a03cb75eb8b76d29" + "Comment": "v0.9.9-3-g7553d52", + "Rev": "7553d5227962c0f226768d0435881e99ec0cab35" }, { "ImportPath": "github.com/aws/aws-sdk-go/internal/endpoints", - "Comment": "v0.9.0rc1-13-g87dbf7e", - "Rev": "87dbf7e29df163bd17d9cea9a03cb75eb8b76d29" + "Comment": "v0.9.9-3-g7553d52", + "Rev": "7553d5227962c0f226768d0435881e99ec0cab35" }, { "ImportPath": "github.com/aws/aws-sdk-go/internal/protocol/ec2query", - "Comment": "v0.9.0rc1-13-g87dbf7e", - "Rev": "87dbf7e29df163bd17d9cea9a03cb75eb8b76d29" + "Comment": "v0.9.9-3-g7553d52", + "Rev": "7553d5227962c0f226768d0435881e99ec0cab35" }, { "ImportPath": "github.com/aws/aws-sdk-go/internal/protocol/query", - "Comment": "v0.9.0rc1-13-g87dbf7e", - "Rev": "87dbf7e29df163bd17d9cea9a03cb75eb8b76d29" + "Comment": "v0.9.9-3-g7553d52", + "Rev": "7553d5227962c0f226768d0435881e99ec0cab35" }, { "ImportPath": "github.com/aws/aws-sdk-go/internal/protocol/rest", - "Comment": "v0.9.0rc1-13-g87dbf7e", - "Rev": "87dbf7e29df163bd17d9cea9a03cb75eb8b76d29" + "Comment": "v0.9.9-3-g7553d52", + "Rev": "7553d5227962c0f226768d0435881e99ec0cab35" }, { "ImportPath": "github.com/aws/aws-sdk-go/internal/protocol/restxml", - "Comment": "v0.9.0rc1-13-g87dbf7e", - "Rev": "87dbf7e29df163bd17d9cea9a03cb75eb8b76d29" + "Comment": "v0.9.9-3-g7553d52", + "Rev": "7553d5227962c0f226768d0435881e99ec0cab35" }, { "ImportPath": "github.com/aws/aws-sdk-go/internal/protocol/xml/xmlutil", - "Comment": "v0.9.0rc1-13-g87dbf7e", - "Rev": "87dbf7e29df163bd17d9cea9a03cb75eb8b76d29" + "Comment": "v0.9.9-3-g7553d52", + "Rev": "7553d5227962c0f226768d0435881e99ec0cab35" }, { "ImportPath": "github.com/aws/aws-sdk-go/internal/signer/v4", - "Comment": "v0.9.0rc1-13-g87dbf7e", - "Rev": "87dbf7e29df163bd17d9cea9a03cb75eb8b76d29" + "Comment": "v0.9.9-3-g7553d52", + "Rev": "7553d5227962c0f226768d0435881e99ec0cab35" }, { "ImportPath": "github.com/aws/aws-sdk-go/service/ec2", - "Comment": "v0.9.0rc1-13-g87dbf7e", - "Rev": "87dbf7e29df163bd17d9cea9a03cb75eb8b76d29" + "Comment": "v0.9.9-3-g7553d52", + "Rev": "7553d5227962c0f226768d0435881e99ec0cab35" }, { "ImportPath": "github.com/aws/aws-sdk-go/service/iam", - "Comment": "v0.9.0rc1-13-g87dbf7e", - "Rev": "87dbf7e29df163bd17d9cea9a03cb75eb8b76d29" + "Comment": "v0.9.9-3-g7553d52", + "Rev": "7553d5227962c0f226768d0435881e99ec0cab35" }, { "ImportPath": "github.com/aws/aws-sdk-go/service/s3", - "Comment": "v0.9.0rc1-13-g87dbf7e", - "Rev": "87dbf7e29df163bd17d9cea9a03cb75eb8b76d29" + "Comment": "v0.9.9-3-g7553d52", + "Rev": "7553d5227962c0f226768d0435881e99ec0cab35" }, { "ImportPath": "github.com/coreos/go-etcd/etcd", - "Comment": "v2.0.0-28-g126041e", - "Rev": "126041ef7b24a28359a12f8bf7f6a7db6756113d" + "Comment": "v2.0.0-34-gde3514f", + "Rev": "de3514f25635bbfb024fdaf2a8d5f67378492675" }, { "ImportPath": "github.com/dgrijalva/jwt-go", - "Comment": "v2.3.0-1-g9fe8afe", - "Rev": "9fe8afe96d32468fba230b8b22acea86251f0506" + "Comment": "v2.3.0-4-gc1da563", + "Rev": "c1da56349675b292d3200463e2c88b9aa5e02391" }, { "ImportPath": "github.com/duosecurity/duo_api_golang", @@ -93,13 +93,13 @@ }, { "ImportPath": "github.com/go-sql-driver/mysql", - "Comment": "v1.2-118-g3dd7008", - "Rev": "3dd7008ac1529aca1bcd8a9db75228a71ba23cac" + "Comment": "v1.2-119-g527bcd5", + "Rev": "527bcd55aab2e53314f1a150922560174b493034" }, { "ImportPath": "github.com/gocql/gocql", - "Comment": "1st_gen_framing-225-g9d122d6", - "Rev": "9d122d6ceec00b4b73bfb70de5587cdee7078d17" + "Comment": "1st_gen_framing-268-g2641ef0", + "Rev": "2641ef08fabdc0182465a14a4f23f1521acb2834" }, { "ImportPath": "github.com/golang/snappy", @@ -107,7 +107,7 @@ }, { "ImportPath": "github.com/google/go-github/github", - "Rev": "7277108aa3e8823e0e028f6c74aea2f4ce4a1b5a" + "Rev": "0d67682ce830f252a1d56215f39b71199036361d" }, { "ImportPath": "github.com/google/go-querystring/query", @@ -115,8 +115,8 @@ }, { "ImportPath": "github.com/hashicorp/consul/api", - "Comment": "v0.5.2-216-g134db62", - "Rev": "134db6293762848681fc9244343bbd19f61d8149" + "Comment": "v0.5.2-313-gde08067", + "Rev": "de080672fee9e6104572eeea89eccdca135bb918" }, { "ImportPath": "github.com/hashicorp/errwrap", @@ -124,7 +124,7 @@ }, { "ImportPath": "github.com/hashicorp/go-multierror", - "Rev": "56912fb08d85084aa318edcf2bba735b97cf35c5" + "Rev": "d30f09973e19c1dfcd120b2d9c4f168e68d6b5d5" }, { "ImportPath": "github.com/hashicorp/go-syslog", @@ -136,7 +136,7 @@ }, { "ImportPath": "github.com/hashicorp/hcl", - "Rev": "54864211433d45cb780682431585b3e573b49e4a" + "Rev": "4de51957ef8d4aba6e285ddfc587633bbfc7c0e8" }, { "ImportPath": "github.com/hashicorp/logutils", @@ -161,7 +161,7 @@ }, { "ImportPath": "github.com/mitchellh/go-homedir", - "Rev": "1f6da4a72e57d4e7edd4a7295a585e0a3999a2d4" + "Rev": "df55a15e5ce646808815381b3db47a8c66ea62f4" }, { "ImportPath": "github.com/mitchellh/mapstructure", @@ -173,8 +173,8 @@ }, { "ImportPath": "github.com/ryanuber/columnize", - "Comment": "v2.0.1-6-g44cb478", - "Rev": "44cb4788b2ec3c3d158dd3d1b50aba7d66f4b59a" + "Comment": "v2.0.1-8-g983d3a5", + "Rev": "983d3a5fab1bf04d1b412465d2d9f8430e2e917e" }, { "ImportPath": "github.com/samuel/go-zookeeper/zk", @@ -182,7 +182,7 @@ }, { "ImportPath": "github.com/ugorji/go/codec", - "Rev": "5abd4e96a45c386928ed2ca2a7ef63e2533e18ec" + "Rev": "1d5269ed4e89d423d40362a0914e1c99adb13cc8" }, { "ImportPath": "github.com/vaughan0/go-ini", @@ -190,35 +190,35 @@ }, { "ImportPath": "golang.org/x/crypto/bcrypt", - "Rev": "81bf7719a6b7ce9b665598222362b50122dfc13b" + "Rev": "aedad9a179ec1ea11b7064c57cbc6dc30d7724ec" }, { "ImportPath": "golang.org/x/crypto/blowfish", - "Rev": "81bf7719a6b7ce9b665598222362b50122dfc13b" + "Rev": "aedad9a179ec1ea11b7064c57cbc6dc30d7724ec" }, { "ImportPath": "golang.org/x/crypto/cast5", - "Rev": "81bf7719a6b7ce9b665598222362b50122dfc13b" + "Rev": "aedad9a179ec1ea11b7064c57cbc6dc30d7724ec" }, { "ImportPath": "golang.org/x/crypto/curve25519", - "Rev": "81bf7719a6b7ce9b665598222362b50122dfc13b" + "Rev": "aedad9a179ec1ea11b7064c57cbc6dc30d7724ec" }, { "ImportPath": "golang.org/x/crypto/openpgp", - "Rev": "81bf7719a6b7ce9b665598222362b50122dfc13b" + "Rev": "aedad9a179ec1ea11b7064c57cbc6dc30d7724ec" }, { "ImportPath": "golang.org/x/crypto/ssh", - "Rev": "81bf7719a6b7ce9b665598222362b50122dfc13b" + "Rev": "aedad9a179ec1ea11b7064c57cbc6dc30d7724ec" }, { "ImportPath": "golang.org/x/net/context", - "Rev": "66f0418ca41253f8d1a024eb9754e9441a8e79b9" + "Rev": "db8e4de5b2d6653f66aea53094624468caad15d2" }, { "ImportPath": "golang.org/x/oauth2", - "Rev": "397fe7649477ff2e8ced8fc0b2696f781e53745a" + "Rev": "82de3fe653a61c1b0174fba87c5f1ca06226ed51" }, { "ImportPath": "gopkg.in/asn1-ber.v1", @@ -227,7 +227,7 @@ }, { "ImportPath": "gopkg.in/inf.v0", - "Rev": "c85f1217d51339c0fa3a498cc8b2075de695dae6" + "Rev": "3887ee99ecf07df5b447e9b00d9c0b2adaa9f3e4" } ] } diff --git a/Godeps/_workspace/src/github.com/armon/go-metrics/datadog/dogstatsd.go b/Godeps/_workspace/src/github.com/armon/go-metrics/datadog/dogstatsd.go new file mode 100644 index 000000000..d217cb83b --- /dev/null +++ b/Godeps/_workspace/src/github.com/armon/go-metrics/datadog/dogstatsd.go @@ -0,0 +1,109 @@ +package datadog + +import ( + "fmt" + "strings" + + "github.com/DataDog/datadog-go/statsd" +) + +// DogStatsdSink provides a MetricSink that can be used +// with a dogstatsd server. It utilizes the Dogstatsd client at github.com/DataDog/datadog-go/statsd +type DogStatsdSink struct { + client *statsd.Client + hostName string + propagateHostname bool +} + +// NewDogStatsdSink is used to create a new DogStatsdSink with sane defaults +func NewDogStatsdSink(addr string, hostName string) (*DogStatsdSink, error) { + client, err := statsd.New(addr) + if err != nil { + return nil, err + } + sink := &DogStatsdSink{ + client: client, + hostName: hostName, + propagateHostname: false, + } + return sink, nil +} + +// SetTags sets common tags on the Dogstatsd Client that will be sent +// along with all dogstatsd packets. +// Ref: http://docs.datadoghq.com/guides/dogstatsd/#tags +func (s *DogStatsdSink) SetTags(tags []string) { + s.client.Tags = tags +} + +// EnableHostnamePropagation forces a Dogstatsd `host` tag with the value specified by `s.HostName` +// Since the go-metrics package has its own mechanism for attaching a hostname to metrics, +// setting the `propagateHostname` flag ensures that `s.HostName` overrides the host tag naively set by the DogStatsd server +func (s *DogStatsdSink) EnableHostNamePropagation() { + s.propagateHostname = true +} + +func (s *DogStatsdSink) flattenKey(parts []string) string { + joined := strings.Join(parts, ".") + return strings.Map(func(r rune) rune { + switch r { + case ':': + fallthrough + case ' ': + return '_' + default: + return r + } + }, joined) +} + +func (s *DogStatsdSink) parseKey(key []string) ([]string, []string) { + // Since DogStatsd supports dimensionality via tags on metric keys, this sink's approach is to splice the hostname out of the key in favor of a `host` tag + // The `host` tag is either forced here, or set downstream by the DogStatsd server + + var tags []string + hostName := s.hostName + + //Splice the hostname out of the key + for i, el := range key { + if el == hostName { + key = append(key[:i], key[i+1:]...) + } + } + + if s.propagateHostname { + tags = append(tags, fmt.Sprintf("host:%s", hostName)) + } + return key, tags +} + +// Implementation of methods in the MetricSink interface + +func (s *DogStatsdSink) SetGauge(key []string, val float32) { + key, tags := s.parseKey(key) + flatKey := s.flattenKey(key) + + rate := 1.0 + s.client.Gauge(flatKey, float64(val), tags, rate) +} + +func (s *DogStatsdSink) IncrCounter(key []string, val float32) { + key, tags := s.parseKey(key) + flatKey := s.flattenKey(key) + + rate := 1.0 + s.client.Count(flatKey, int64(val), tags, rate) +} + +// EmitKey is not implemented since DogStatsd does not provide a metric type that holds an +// arbitrary number of values +func (s *DogStatsdSink) EmitKey(key []string, val float32) { +} + +func (s *DogStatsdSink) AddSample(key []string, val float32) { + key, tags := s.parseKey(key) + flatKey := s.flattenKey(key) + + rate := 1.0 + s.client.TimeInMilliseconds(flatKey, float64(val), tags, rate) +} diff --git a/Godeps/_workspace/src/github.com/armon/go-metrics/inmem_signal_test.go b/Godeps/_workspace/src/github.com/armon/go-metrics/inmem_signal_test.go deleted file mode 100644 index 9bbca5f25..000000000 --- a/Godeps/_workspace/src/github.com/armon/go-metrics/inmem_signal_test.go +++ /dev/null @@ -1,46 +0,0 @@ -package metrics - -import ( - "bytes" - "os" - "strings" - "syscall" - "testing" - "time" -) - -func TestInmemSignal(t *testing.T) { - buf := bytes.NewBuffer(nil) - inm := NewInmemSink(10*time.Millisecond, 50*time.Millisecond) - sig := NewInmemSignal(inm, syscall.SIGUSR1, buf) - defer sig.Stop() - - inm.SetGauge([]string{"foo"}, 42) - inm.EmitKey([]string{"bar"}, 42) - inm.IncrCounter([]string{"baz"}, 42) - inm.AddSample([]string{"wow"}, 42) - - // Wait for period to end - time.Sleep(15 * time.Millisecond) - - // Send signal! - syscall.Kill(os.Getpid(), syscall.SIGUSR1) - - // Wait for flush - time.Sleep(10 * time.Millisecond) - - // Check the output - out := string(buf.Bytes()) - if !strings.Contains(out, "[G] 'foo': 42") { - t.Fatalf("bad: %v", out) - } - if !strings.Contains(out, "[P] 'bar': 42") { - t.Fatalf("bad: %v", out) - } - if !strings.Contains(out, "[C] 'baz': Count: 1 Sum: 42") { - t.Fatalf("bad: %v", out) - } - if !strings.Contains(out, "[S] 'wow': Count: 1 Sum: 42") { - t.Fatalf("bad: %v", out) - } -} diff --git a/Godeps/_workspace/src/github.com/armon/go-metrics/inmem_test.go b/Godeps/_workspace/src/github.com/armon/go-metrics/inmem_test.go deleted file mode 100644 index 228a2fc1a..000000000 --- a/Godeps/_workspace/src/github.com/armon/go-metrics/inmem_test.go +++ /dev/null @@ -1,104 +0,0 @@ -package metrics - -import ( - "math" - "testing" - "time" -) - -func TestInmemSink(t *testing.T) { - inm := NewInmemSink(10*time.Millisecond, 50*time.Millisecond) - - data := inm.Data() - if len(data) != 1 { - t.Fatalf("bad: %v", data) - } - - // Add data points - inm.SetGauge([]string{"foo", "bar"}, 42) - inm.EmitKey([]string{"foo", "bar"}, 42) - inm.IncrCounter([]string{"foo", "bar"}, 20) - inm.IncrCounter([]string{"foo", "bar"}, 22) - inm.AddSample([]string{"foo", "bar"}, 20) - inm.AddSample([]string{"foo", "bar"}, 22) - - data = inm.Data() - if len(data) != 1 { - t.Fatalf("bad: %v", data) - } - - intvM := data[0] - intvM.RLock() - - if time.Now().Sub(intvM.Interval) > 10*time.Millisecond { - t.Fatalf("interval too old") - } - if intvM.Gauges["foo.bar"] != 42 { - t.Fatalf("bad val: %v", intvM.Gauges) - } - if intvM.Points["foo.bar"][0] != 42 { - t.Fatalf("bad val: %v", intvM.Points) - } - - agg := intvM.Counters["foo.bar"] - if agg.Count != 2 { - t.Fatalf("bad val: %v", agg) - } - if agg.Sum != 42 { - t.Fatalf("bad val: %v", agg) - } - if agg.SumSq != 884 { - t.Fatalf("bad val: %v", agg) - } - if agg.Min != 20 { - t.Fatalf("bad val: %v", agg) - } - if agg.Max != 22 { - t.Fatalf("bad val: %v", agg) - } - if agg.Mean() != 21 { - t.Fatalf("bad val: %v", agg) - } - if agg.Stddev() != math.Sqrt(2) { - t.Fatalf("bad val: %v", agg) - } - - if agg.LastUpdated.IsZero() { - t.Fatalf("agg.LastUpdated is not set: %v", agg) - } - - diff := time.Now().Sub(agg.LastUpdated).Seconds() - if diff > 1 { - t.Fatalf("time diff too great: %f", diff) - } - - if agg = intvM.Samples["foo.bar"]; agg == nil { - t.Fatalf("missing sample") - } - - intvM.RUnlock() - - for i := 1; i < 10; i++ { - time.Sleep(10 * time.Millisecond) - inm.SetGauge([]string{"foo", "bar"}, 42) - data = inm.Data() - if len(data) != min(i+1, 5) { - t.Fatalf("bad: %v", data) - } - } - - // Should not exceed 5 intervals! - time.Sleep(10 * time.Millisecond) - inm.SetGauge([]string{"foo", "bar"}, 42) - data = inm.Data() - if len(data) != 5 { - t.Fatalf("bad: %v", data) - } -} - -func min(a, b int) int { - if a < b { - return a - } - return b -} diff --git a/Godeps/_workspace/src/github.com/armon/go-metrics/metrics_test.go b/Godeps/_workspace/src/github.com/armon/go-metrics/metrics_test.go deleted file mode 100644 index c7baf22bf..000000000 --- a/Godeps/_workspace/src/github.com/armon/go-metrics/metrics_test.go +++ /dev/null @@ -1,262 +0,0 @@ -package metrics - -import ( - "reflect" - "runtime" - "testing" - "time" -) - -func mockMetric() (*MockSink, *Metrics) { - m := &MockSink{} - met := &Metrics{sink: m} - return m, met -} - -func TestMetrics_SetGauge(t *testing.T) { - m, met := mockMetric() - met.SetGauge([]string{"key"}, float32(1)) - if m.keys[0][0] != "key" { - t.Fatalf("") - } - if m.vals[0] != 1 { - t.Fatalf("") - } - - m, met = mockMetric() - met.HostName = "test" - met.EnableHostname = true - met.SetGauge([]string{"key"}, float32(1)) - if m.keys[0][0] != "test" || m.keys[0][1] != "key" { - t.Fatalf("") - } - if m.vals[0] != 1 { - t.Fatalf("") - } - - m, met = mockMetric() - met.EnableTypePrefix = true - met.SetGauge([]string{"key"}, float32(1)) - if m.keys[0][0] != "gauge" || m.keys[0][1] != "key" { - t.Fatalf("") - } - if m.vals[0] != 1 { - t.Fatalf("") - } - - m, met = mockMetric() - met.ServiceName = "service" - met.SetGauge([]string{"key"}, float32(1)) - if m.keys[0][0] != "service" || m.keys[0][1] != "key" { - t.Fatalf("") - } - if m.vals[0] != 1 { - t.Fatalf("") - } -} - -func TestMetrics_EmitKey(t *testing.T) { - m, met := mockMetric() - met.EmitKey([]string{"key"}, float32(1)) - if m.keys[0][0] != "key" { - t.Fatalf("") - } - if m.vals[0] != 1 { - t.Fatalf("") - } - - m, met = mockMetric() - met.EnableTypePrefix = true - met.EmitKey([]string{"key"}, float32(1)) - if m.keys[0][0] != "kv" || m.keys[0][1] != "key" { - t.Fatalf("") - } - if m.vals[0] != 1 { - t.Fatalf("") - } - - m, met = mockMetric() - met.ServiceName = "service" - met.EmitKey([]string{"key"}, float32(1)) - if m.keys[0][0] != "service" || m.keys[0][1] != "key" { - t.Fatalf("") - } - if m.vals[0] != 1 { - t.Fatalf("") - } -} - -func TestMetrics_IncrCounter(t *testing.T) { - m, met := mockMetric() - met.IncrCounter([]string{"key"}, float32(1)) - if m.keys[0][0] != "key" { - t.Fatalf("") - } - if m.vals[0] != 1 { - t.Fatalf("") - } - - m, met = mockMetric() - met.EnableTypePrefix = true - met.IncrCounter([]string{"key"}, float32(1)) - if m.keys[0][0] != "counter" || m.keys[0][1] != "key" { - t.Fatalf("") - } - if m.vals[0] != 1 { - t.Fatalf("") - } - - m, met = mockMetric() - met.ServiceName = "service" - met.IncrCounter([]string{"key"}, float32(1)) - if m.keys[0][0] != "service" || m.keys[0][1] != "key" { - t.Fatalf("") - } - if m.vals[0] != 1 { - t.Fatalf("") - } -} - -func TestMetrics_AddSample(t *testing.T) { - m, met := mockMetric() - met.AddSample([]string{"key"}, float32(1)) - if m.keys[0][0] != "key" { - t.Fatalf("") - } - if m.vals[0] != 1 { - t.Fatalf("") - } - - m, met = mockMetric() - met.EnableTypePrefix = true - met.AddSample([]string{"key"}, float32(1)) - if m.keys[0][0] != "sample" || m.keys[0][1] != "key" { - t.Fatalf("") - } - if m.vals[0] != 1 { - t.Fatalf("") - } - - m, met = mockMetric() - met.ServiceName = "service" - met.AddSample([]string{"key"}, float32(1)) - if m.keys[0][0] != "service" || m.keys[0][1] != "key" { - t.Fatalf("") - } - if m.vals[0] != 1 { - t.Fatalf("") - } -} - -func TestMetrics_MeasureSince(t *testing.T) { - m, met := mockMetric() - met.TimerGranularity = time.Millisecond - n := time.Now() - met.MeasureSince([]string{"key"}, n) - if m.keys[0][0] != "key" { - t.Fatalf("") - } - if m.vals[0] > 0.1 { - t.Fatalf("") - } - - m, met = mockMetric() - met.TimerGranularity = time.Millisecond - met.EnableTypePrefix = true - met.MeasureSince([]string{"key"}, n) - if m.keys[0][0] != "timer" || m.keys[0][1] != "key" { - t.Fatalf("") - } - if m.vals[0] > 0.1 { - t.Fatalf("") - } - - m, met = mockMetric() - met.TimerGranularity = time.Millisecond - met.ServiceName = "service" - met.MeasureSince([]string{"key"}, n) - if m.keys[0][0] != "service" || m.keys[0][1] != "key" { - t.Fatalf("") - } - if m.vals[0] > 0.1 { - t.Fatalf("") - } -} - -func TestMetrics_EmitRuntimeStats(t *testing.T) { - runtime.GC() - m, met := mockMetric() - met.emitRuntimeStats() - - if m.keys[0][0] != "runtime" || m.keys[0][1] != "num_goroutines" { - t.Fatalf("bad key %v", m.keys) - } - if m.vals[0] <= 1 { - t.Fatalf("bad val: %v", m.vals) - } - - if m.keys[1][0] != "runtime" || m.keys[1][1] != "alloc_bytes" { - t.Fatalf("bad key %v", m.keys) - } - if m.vals[1] <= 40000 { - t.Fatalf("bad val: %v", m.vals) - } - - if m.keys[2][0] != "runtime" || m.keys[2][1] != "sys_bytes" { - t.Fatalf("bad key %v", m.keys) - } - if m.vals[2] <= 100000 { - t.Fatalf("bad val: %v", m.vals) - } - - if m.keys[3][0] != "runtime" || m.keys[3][1] != "malloc_count" { - t.Fatalf("bad key %v", m.keys) - } - if m.vals[3] <= 100 { - t.Fatalf("bad val: %v", m.vals) - } - - if m.keys[4][0] != "runtime" || m.keys[4][1] != "free_count" { - t.Fatalf("bad key %v", m.keys) - } - if m.vals[4] <= 100 { - t.Fatalf("bad val: %v", m.vals) - } - - if m.keys[5][0] != "runtime" || m.keys[5][1] != "heap_objects" { - t.Fatalf("bad key %v", m.keys) - } - if m.vals[5] <= 100 { - t.Fatalf("bad val: %v", m.vals) - } - - if m.keys[6][0] != "runtime" || m.keys[6][1] != "total_gc_pause_ns" { - t.Fatalf("bad key %v", m.keys) - } - if m.vals[6] <= 100000 { - t.Fatalf("bad val: %v", m.vals) - } - - if m.keys[7][0] != "runtime" || m.keys[7][1] != "total_gc_runs" { - t.Fatalf("bad key %v", m.keys) - } - if m.vals[7] <= 1 { - t.Fatalf("bad val: %v", m.vals) - } - - if m.keys[8][0] != "runtime" || m.keys[8][1] != "gc_pause_ns" { - t.Fatalf("bad key %v", m.keys) - } - if m.vals[8] <= 1000 { - t.Fatalf("bad val: %v", m.vals) - } -} - -func TestInsert(t *testing.T) { - k := []string{"hi", "bob"} - exp := []string{"hi", "there", "bob"} - out := insert(1, "there", k) - if !reflect.DeepEqual(exp, out) { - t.Fatalf("bad insert %v %v", exp, out) - } -} diff --git a/Godeps/_workspace/src/github.com/armon/go-metrics/sink_test.go b/Godeps/_workspace/src/github.com/armon/go-metrics/sink_test.go deleted file mode 100644 index 15c5d771a..000000000 --- a/Godeps/_workspace/src/github.com/armon/go-metrics/sink_test.go +++ /dev/null @@ -1,120 +0,0 @@ -package metrics - -import ( - "reflect" - "testing" -) - -type MockSink struct { - keys [][]string - vals []float32 -} - -func (m *MockSink) SetGauge(key []string, val float32) { - m.keys = append(m.keys, key) - m.vals = append(m.vals, val) -} -func (m *MockSink) EmitKey(key []string, val float32) { - m.keys = append(m.keys, key) - m.vals = append(m.vals, val) -} -func (m *MockSink) IncrCounter(key []string, val float32) { - m.keys = append(m.keys, key) - m.vals = append(m.vals, val) -} -func (m *MockSink) AddSample(key []string, val float32) { - m.keys = append(m.keys, key) - m.vals = append(m.vals, val) -} - -func TestFanoutSink_Gauge(t *testing.T) { - m1 := &MockSink{} - m2 := &MockSink{} - fh := &FanoutSink{m1, m2} - - k := []string{"test"} - v := float32(42.0) - fh.SetGauge(k, v) - - if !reflect.DeepEqual(m1.keys[0], k) { - t.Fatalf("key not equal") - } - if !reflect.DeepEqual(m2.keys[0], k) { - t.Fatalf("key not equal") - } - if !reflect.DeepEqual(m1.vals[0], v) { - t.Fatalf("val not equal") - } - if !reflect.DeepEqual(m2.vals[0], v) { - t.Fatalf("val not equal") - } -} - -func TestFanoutSink_Key(t *testing.T) { - m1 := &MockSink{} - m2 := &MockSink{} - fh := &FanoutSink{m1, m2} - - k := []string{"test"} - v := float32(42.0) - fh.EmitKey(k, v) - - if !reflect.DeepEqual(m1.keys[0], k) { - t.Fatalf("key not equal") - } - if !reflect.DeepEqual(m2.keys[0], k) { - t.Fatalf("key not equal") - } - if !reflect.DeepEqual(m1.vals[0], v) { - t.Fatalf("val not equal") - } - if !reflect.DeepEqual(m2.vals[0], v) { - t.Fatalf("val not equal") - } -} - -func TestFanoutSink_Counter(t *testing.T) { - m1 := &MockSink{} - m2 := &MockSink{} - fh := &FanoutSink{m1, m2} - - k := []string{"test"} - v := float32(42.0) - fh.IncrCounter(k, v) - - if !reflect.DeepEqual(m1.keys[0], k) { - t.Fatalf("key not equal") - } - if !reflect.DeepEqual(m2.keys[0], k) { - t.Fatalf("key not equal") - } - if !reflect.DeepEqual(m1.vals[0], v) { - t.Fatalf("val not equal") - } - if !reflect.DeepEqual(m2.vals[0], v) { - t.Fatalf("val not equal") - } -} - -func TestFanoutSink_Sample(t *testing.T) { - m1 := &MockSink{} - m2 := &MockSink{} - fh := &FanoutSink{m1, m2} - - k := []string{"test"} - v := float32(42.0) - fh.AddSample(k, v) - - if !reflect.DeepEqual(m1.keys[0], k) { - t.Fatalf("key not equal") - } - if !reflect.DeepEqual(m2.keys[0], k) { - t.Fatalf("key not equal") - } - if !reflect.DeepEqual(m1.vals[0], v) { - t.Fatalf("val not equal") - } - if !reflect.DeepEqual(m2.vals[0], v) { - t.Fatalf("val not equal") - } -} diff --git a/Godeps/_workspace/src/github.com/armon/go-metrics/start_test.go b/Godeps/_workspace/src/github.com/armon/go-metrics/start_test.go deleted file mode 100644 index 8b3210c15..000000000 --- a/Godeps/_workspace/src/github.com/armon/go-metrics/start_test.go +++ /dev/null @@ -1,110 +0,0 @@ -package metrics - -import ( - "reflect" - "testing" - "time" -) - -func TestDefaultConfig(t *testing.T) { - conf := DefaultConfig("service") - if conf.ServiceName != "service" { - t.Fatalf("Bad name") - } - if conf.HostName == "" { - t.Fatalf("missing hostname") - } - if !conf.EnableHostname || !conf.EnableRuntimeMetrics { - t.Fatalf("expect true") - } - if conf.EnableTypePrefix { - t.Fatalf("expect false") - } - if conf.TimerGranularity != time.Millisecond { - t.Fatalf("bad granularity") - } - if conf.ProfileInterval != time.Second { - t.Fatalf("bad interval") - } -} - -func Test_GlobalMetrics_SetGauge(t *testing.T) { - m := &MockSink{} - globalMetrics = &Metrics{sink: m} - - k := []string{"test"} - v := float32(42.0) - SetGauge(k, v) - - if !reflect.DeepEqual(m.keys[0], k) { - t.Fatalf("key not equal") - } - if !reflect.DeepEqual(m.vals[0], v) { - t.Fatalf("val not equal") - } -} - -func Test_GlobalMetrics_EmitKey(t *testing.T) { - m := &MockSink{} - globalMetrics = &Metrics{sink: m} - - k := []string{"test"} - v := float32(42.0) - EmitKey(k, v) - - if !reflect.DeepEqual(m.keys[0], k) { - t.Fatalf("key not equal") - } - if !reflect.DeepEqual(m.vals[0], v) { - t.Fatalf("val not equal") - } -} - -func Test_GlobalMetrics_IncrCounter(t *testing.T) { - m := &MockSink{} - globalMetrics = &Metrics{sink: m} - - k := []string{"test"} - v := float32(42.0) - IncrCounter(k, v) - - if !reflect.DeepEqual(m.keys[0], k) { - t.Fatalf("key not equal") - } - if !reflect.DeepEqual(m.vals[0], v) { - t.Fatalf("val not equal") - } -} - -func Test_GlobalMetrics_AddSample(t *testing.T) { - m := &MockSink{} - globalMetrics = &Metrics{sink: m} - - k := []string{"test"} - v := float32(42.0) - AddSample(k, v) - - if !reflect.DeepEqual(m.keys[0], k) { - t.Fatalf("key not equal") - } - if !reflect.DeepEqual(m.vals[0], v) { - t.Fatalf("val not equal") - } -} - -func Test_GlobalMetrics_MeasureSince(t *testing.T) { - m := &MockSink{} - globalMetrics = &Metrics{sink: m} - globalMetrics.TimerGranularity = time.Millisecond - - k := []string{"test"} - now := time.Now() - MeasureSince(k, now) - - if !reflect.DeepEqual(m.keys[0], k) { - t.Fatalf("key not equal") - } - if m.vals[0] > 0.1 { - t.Fatalf("val too large %v", m.vals[0]) - } -} diff --git a/Godeps/_workspace/src/github.com/armon/go-metrics/statsd_test.go b/Godeps/_workspace/src/github.com/armon/go-metrics/statsd_test.go deleted file mode 100644 index 622eb5d3a..000000000 --- a/Godeps/_workspace/src/github.com/armon/go-metrics/statsd_test.go +++ /dev/null @@ -1,105 +0,0 @@ -package metrics - -import ( - "bufio" - "bytes" - "net" - "testing" - "time" -) - -func TestStatsd_Flatten(t *testing.T) { - s := &StatsdSink{} - flat := s.flattenKey([]string{"a", "b", "c", "d"}) - if flat != "a.b.c.d" { - t.Fatalf("Bad flat") - } -} - -func TestStatsd_PushFullQueue(t *testing.T) { - q := make(chan string, 1) - q <- "full" - - s := &StatsdSink{metricQueue: q} - s.pushMetric("omit") - - out := <-q - if out != "full" { - t.Fatalf("bad val %v", out) - } - - select { - case v := <-q: - t.Fatalf("bad val %v", v) - default: - } -} - -func TestStatsd_Conn(t *testing.T) { - addr := "127.0.0.1:7524" - done := make(chan bool) - go func() { - list, err := net.ListenUDP("udp", &net.UDPAddr{IP: net.ParseIP("127.0.0.1"), Port: 7524}) - if err != nil { - panic(err) - } - defer list.Close() - buf := make([]byte, 1500) - n, err := list.Read(buf) - if err != nil { - panic(err) - } - buf = buf[:n] - reader := bufio.NewReader(bytes.NewReader(buf)) - - line, err := reader.ReadString('\n') - if err != nil { - t.Fatalf("unexpected err %s", err) - } - if line != "gauge.val:1.000000|g\n" { - t.Fatalf("bad line %s", line) - } - - line, err = reader.ReadString('\n') - if err != nil { - t.Fatalf("unexpected err %s", err) - } - if line != "key.other:2.000000|kv\n" { - t.Fatalf("bad line %s", line) - } - - line, err = reader.ReadString('\n') - if err != nil { - t.Fatalf("unexpected err %s", err) - } - if line != "counter.me:3.000000|c\n" { - t.Fatalf("bad line %s", line) - } - - line, err = reader.ReadString('\n') - if err != nil { - t.Fatalf("unexpected err %s", err) - } - if line != "sample.slow_thingy:4.000000|ms\n" { - t.Fatalf("bad line %s", line) - } - - done <- true - }() - s, err := NewStatsdSink(addr) - if err != nil { - t.Fatalf("bad error") - } - - s.SetGauge([]string{"gauge", "val"}, float32(1)) - s.EmitKey([]string{"key", "other"}, float32(2)) - s.IncrCounter([]string{"counter", "me"}, float32(3)) - s.AddSample([]string{"sample", "slow thingy"}, float32(4)) - - select { - case <-done: - s.Shutdown() - case <-time.After(3 * time.Second): - t.Fatalf("timeout") - } -} diff --git a/Godeps/_workspace/src/github.com/armon/go-metrics/statsite_test.go b/Godeps/_workspace/src/github.com/armon/go-metrics/statsite_test.go deleted file mode 100644 index d9c744f41..000000000 --- a/Godeps/_workspace/src/github.com/armon/go-metrics/statsite_test.go +++ /dev/null @@ -1,101 +0,0 @@ -package metrics - -import ( - "bufio" - "net" - "testing" - "time" -) - -func acceptConn(addr string) net.Conn { - ln, _ := net.Listen("tcp", addr) - conn, _ := ln.Accept() - return conn -} - -func TestStatsite_Flatten(t *testing.T) { - s := &StatsiteSink{} - flat := s.flattenKey([]string{"a", "b", "c", "d"}) - if flat != "a.b.c.d" { - t.Fatalf("Bad flat") - } -} - -func TestStatsite_PushFullQueue(t *testing.T) { - q := make(chan string, 1) - q <- "full" - - s := &StatsiteSink{metricQueue: q} - s.pushMetric("omit") - - out := <-q - if out != "full" { - t.Fatalf("bad val %v", out) - } - - select { - case v := <-q: - t.Fatalf("bad val %v", v) - default: - } -} - -func TestStatsite_Conn(t *testing.T) { - addr := "localhost:7523" - done := make(chan bool) - go func() { - conn := acceptConn(addr) - reader := bufio.NewReader(conn) - - line, err := reader.ReadString('\n') - if err != nil { - t.Fatalf("unexpected err %s", err) - } - if line != "gauge.val:1.000000|g\n" { - t.Fatalf("bad line %s", line) - } - - line, err = reader.ReadString('\n') - if err != nil { - t.Fatalf("unexpected err %s", err) - } - if line != "key.other:2.000000|kv\n" { - t.Fatalf("bad line %s", line) - } - - line, err = reader.ReadString('\n') - if err != nil { - t.Fatalf("unexpected err %s", err) - } - if line != "counter.me:3.000000|c\n" { - t.Fatalf("bad line %s", line) - } - - line, err = reader.ReadString('\n') - if err != nil { - t.Fatalf("unexpected err %s", err) - } - if line != "sample.slow_thingy:4.000000|ms\n" { - t.Fatalf("bad line %s", line) - } - - conn.Close() - done <- true - }() - s, err := NewStatsiteSink(addr) - if err != nil { - t.Fatalf("bad error") - } - - s.SetGauge([]string{"gauge", "val"}, float32(1)) - s.EmitKey([]string{"key", "other"}, float32(2)) - s.IncrCounter([]string{"counter", "me"}, float32(3)) - s.AddSample([]string{"sample", "slow thingy"}, float32(4)) - - select { - case <-done: - s.Shutdown() - case <-time.After(3 * time.Second): - t.Fatalf("timeout") - } -} diff --git a/Godeps/_workspace/src/github.com/armon/go-radix/radix_test.go b/Godeps/_workspace/src/github.com/armon/go-radix/radix_test.go deleted file mode 100644 index 23b415566..000000000 --- a/Godeps/_workspace/src/github.com/armon/go-radix/radix_test.go +++ /dev/null @@ -1,319 +0,0 @@ -package radix - -import ( - crand "crypto/rand" - "fmt" - "reflect" - "sort" - "testing" -) - -func TestRadix(t *testing.T) { - var min, max string - inp := make(map[string]interface{}) - for i := 0; i < 1000; i++ { - gen := generateUUID() - inp[gen] = i - if gen < min || i == 0 { - min = gen - } - if gen > max || i == 0 { - max = gen - } - } - - r := NewFromMap(inp) - if r.Len() != len(inp) { - t.Fatalf("bad length: %v %v", r.Len(), len(inp)) - } - - r.Walk(func(k string, v interface{}) bool { - println(k) - return false - }) - - for k, v := range inp { - out, ok := r.Get(k) - if !ok { - t.Fatalf("missing key: %v", k) - } - if out != v { - t.Fatalf("value mis-match: %v %v", out, v) - } - } - - // Check min and max - outMin, _, _ := r.Minimum() - if outMin != min { - t.Fatalf("bad minimum: %v %v", outMin, min) - } - outMax, _, _ := r.Maximum() - if outMax != max { - t.Fatalf("bad maximum: %v %v", outMax, max) - } - - for k, v := range inp { - out, ok := r.Delete(k) - if !ok { - t.Fatalf("missing key: %v", k) - } - if out != v { - t.Fatalf("value mis-match: %v %v", out, v) - } - } - if r.Len() != 0 { - t.Fatalf("bad length: %v", r.Len()) - } -} - -func TestRoot(t *testing.T) { - r := New() - _, ok := r.Delete("") - if ok { - t.Fatalf("bad") - } - _, ok = r.Insert("", true) - if ok { - t.Fatalf("bad") - } - val, ok := r.Get("") - if !ok || val != true { - t.Fatalf("bad: %v", val) - } - val, ok = r.Delete("") - if !ok || val != true { - t.Fatalf("bad: %v", val) - } -} - -func TestDelete(t *testing.T) { - - r := New() - - s := []string{"", "A", "AB"} - - for _, ss := range s { - r.Insert(ss, true) - } - - for _, ss := range s { - _, ok := r.Delete(ss) - if !ok { - t.Fatalf("bad %q", ss) - } - } -} - -func TestLongestPrefix(t *testing.T) { - r := New() - - keys := []string{ - "", - "foo", - "foobar", - "foobarbaz", - "foobarbazzip", - "foozip", - } - for _, k := range keys { - r.Insert(k, nil) - } - if r.Len() != len(keys) { - t.Fatalf("bad len: %v %v", r.Len(), len(keys)) - } - - type exp struct { - inp string - out string - } - cases := []exp{ - {"a", ""}, - {"abc", ""}, - {"fo", ""}, - {"foo", "foo"}, - {"foob", "foo"}, - {"foobar", "foobar"}, - {"foobarba", "foobar"}, - {"foobarbaz", "foobarbaz"}, - {"foobarbazzi", "foobarbaz"}, - {"foobarbazzip", "foobarbazzip"}, - {"foozi", "foo"}, - {"foozip", "foozip"}, - {"foozipzap", "foozip"}, - } - for _, test := range cases { - m, _, ok := r.LongestPrefix(test.inp) - if !ok { - t.Fatalf("no match: %v", test) - } - if m != test.out { - t.Fatalf("mis-match: %v %v", m, test) - } - } -} - -func TestWalkPrefix(t *testing.T) { - r := New() - - keys := []string{ - "foobar", - "foo/bar/baz", - "foo/baz/bar", - "foo/zip/zap", - "zipzap", - } - for _, k := range keys { - r.Insert(k, nil) - } - if r.Len() != len(keys) { - t.Fatalf("bad len: %v %v", r.Len(), len(keys)) - } - - type exp struct { - inp string - out []string - } - cases := []exp{ - exp{ - "f", - []string{"foobar", "foo/bar/baz", "foo/baz/bar", "foo/zip/zap"}, - }, - exp{ - "foo", - []string{"foobar", "foo/bar/baz", "foo/baz/bar", "foo/zip/zap"}, - }, - exp{ - "foob", - []string{"foobar"}, - }, - exp{ - "foo/", - []string{"foo/bar/baz", "foo/baz/bar", "foo/zip/zap"}, - }, - exp{ - "foo/b", - []string{"foo/bar/baz", "foo/baz/bar"}, - }, - exp{ - "foo/ba", - []string{"foo/bar/baz", "foo/baz/bar"}, - }, - exp{ - "foo/bar", - []string{"foo/bar/baz"}, - }, - exp{ - "foo/bar/baz", - []string{"foo/bar/baz"}, - }, - exp{ - "foo/bar/bazoo", - []string{}, - }, - exp{ - "z", - []string{"zipzap"}, - }, - } - - for _, test := range cases { - out := []string{} - fn := func(s string, v interface{}) bool { - out = append(out, s) - return false - } - r.WalkPrefix(test.inp, fn) - sort.Strings(out) - sort.Strings(test.out) - if !reflect.DeepEqual(out, test.out) { - t.Fatalf("mis-match: %v %v", out, test.out) - } - } -} - -func TestWalkPath(t *testing.T) { - r := New() - - keys := []string{ - "foo", - "foo/bar", - "foo/bar/baz", - "foo/baz/bar", - "foo/zip/zap", - "zipzap", - } - for _, k := range keys { - r.Insert(k, nil) - } - if r.Len() != len(keys) { - t.Fatalf("bad len: %v %v", r.Len(), len(keys)) - } - - type exp struct { - inp string - out []string - } - cases := []exp{ - exp{ - "f", - []string{}, - }, - exp{ - "foo", - []string{"foo"}, - }, - exp{ - "foo/", - []string{"foo"}, - }, - exp{ - "foo/ba", - []string{"foo"}, - }, - exp{ - "foo/bar", - []string{"foo", "foo/bar"}, - }, - exp{ - "foo/bar/baz", - []string{"foo", "foo/bar", "foo/bar/baz"}, - }, - exp{ - "foo/bar/bazoo", - []string{"foo", "foo/bar", "foo/bar/baz"}, - }, - exp{ - "z", - []string{}, - }, - } - - for _, test := range cases { - out := []string{} - fn := func(s string, v interface{}) bool { - out = append(out, s) - return false - } - r.WalkPath(test.inp, fn) - sort.Strings(out) - sort.Strings(test.out) - if !reflect.DeepEqual(out, test.out) { - t.Fatalf("mis-match: %v %v", out, test.out) - } - } -} - -// generateUUID is used to generate a random UUID -func generateUUID() 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]) -} diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/awserr/types.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/awserr/types.go index 418fc4c14..003a6e806 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/awserr/types.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/awserr/types.go @@ -113,7 +113,7 @@ func newRequestError(err Error, statusCode int, requestID string) *requestError // Error returns the string representation of the error. // Satisfies the error interface. func (r requestError) Error() string { - extra := fmt.Sprintf("status code: %d, request id: [%s]", + extra := fmt.Sprintf("status code: %d, request id: %s", r.statusCode, r.requestID) return SprintError(r.Code(), r.Message(), extra, r.OrigErr()) } diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/awsutil/copy_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/awsutil/copy_test.go deleted file mode 100644 index 4f26241a2..000000000 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/awsutil/copy_test.go +++ /dev/null @@ -1,201 +0,0 @@ -package awsutil_test - -import ( - "bytes" - "fmt" - "io" - "io/ioutil" - "testing" - - "github.com/aws/aws-sdk-go/aws/awsutil" - "github.com/stretchr/testify/assert" -) - -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 TestCopy(t *testing.T) { - type Foo struct { - A int - B []*string - C map[string]*int - } - - // Create the initial value - str1 := "hello" - str2 := "bye bye" - int1 := 1 - int2 := 2 - f1 := &Foo{ - A: 1, - B: []*string{&str1, &str2}, - C: map[string]*int{ - "A": &int1, - "B": &int2, - }, - } - - // Do the copy - var f2 Foo - awsutil.Copy(&f2, f1) - - // Values are equal - assert.Equal(t, f2.A, f1.A) - assert.Equal(t, f2.B, f1.B) - assert.Equal(t, f2.C, f1.C) - - // But pointers are not! - str3 := "nothello" - int3 := 57 - f2.A = 100 - f2.B[0] = &str3 - f2.C["B"] = &int3 - assert.NotEqual(t, f2.A, f1.A) - assert.NotEqual(t, f2.B, f1.B) - assert.NotEqual(t, f2.C, f1.C) -} - -func TestCopyIgnoreNilMembers(t *testing.T) { - type Foo struct { - A *string - B []string - C map[string]string - } - - f := &Foo{} - assert.Nil(t, f.A) - assert.Nil(t, f.B) - assert.Nil(t, f.C) - - var f2 Foo - awsutil.Copy(&f2, f) - assert.Nil(t, f2.A) - assert.Nil(t, f2.B) - assert.Nil(t, f2.C) - - fcopy := awsutil.CopyOf(f) - f3 := fcopy.(*Foo) - assert.Nil(t, f3.A) - assert.Nil(t, f3.B) - assert.Nil(t, f3.C) -} - -func TestCopyPrimitive(t *testing.T) { - str := "hello" - var s string - awsutil.Copy(&s, &str) - assert.Equal(t, "hello", s) -} - -func TestCopyNil(t *testing.T) { - var s string - awsutil.Copy(&s, nil) - assert.Equal(t, "", s) -} - -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) - assert.NoError(t, err) - assert.Equal(t, []byte("hello world"), b) - - // empty bytes because this is not a deep copy - b, err = ioutil.ReadAll(buf) - assert.NoError(t, err) - assert.Equal(t, []byte(""), b) -} - -func TestCopyDifferentStructs(t *testing.T) { - type SrcFoo struct { - A int - B []*string - C map[string]*int - SrcUnique string - SameNameDiffType int - } - type DstFoo struct { - A int - B []*string - C map[string]*int - DstUnique int - SameNameDiffType string - } - - // 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, - } - - // Do the copy - var f2 DstFoo - awsutil.Copy(&f2, f1) - - // Values are equal - assert.Equal(t, f2.A, f1.A) - assert.Equal(t, f2.B, f1.B) - assert.Equal(t, f2.C, f1.C) - assert.Equal(t, "unique", f1.SrcUnique) - assert.Equal(t, 1, f1.SameNameDiffType) - assert.Equal(t, 0, f2.DstUnique) - assert.Equal(t, "", f2.SameNameDiffType) -} - -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/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/awsutil/path_value_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/awsutil/path_value_test.go deleted file mode 100644 index 0da6b06fd..000000000 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/awsutil/path_value_test.go +++ /dev/null @@ -1,68 +0,0 @@ -package awsutil_test - -import ( - "testing" - - "github.com/aws/aws-sdk-go/aws/awsutil" - "github.com/stretchr/testify/assert" -) - -type Struct struct { - A []Struct - z []Struct - B *Struct - D *Struct - C 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", -} - -func TestValueAtPathSuccess(t *testing.T) { - assert.Equal(t, []interface{}{"initial"}, awsutil.ValuesAtPath(data, "C")) - assert.Equal(t, []interface{}{"value1"}, awsutil.ValuesAtPath(data, "A[0].C")) - assert.Equal(t, []interface{}{"value2"}, awsutil.ValuesAtPath(data, "A[1].C")) - assert.Equal(t, []interface{}{"value3"}, awsutil.ValuesAtPath(data, "A[2].C")) - assert.Equal(t, []interface{}{"value3"}, awsutil.ValuesAtAnyPath(data, "a[2].c")) - assert.Equal(t, []interface{}{"value3"}, awsutil.ValuesAtPath(data, "A[-1].C")) - assert.Equal(t, []interface{}{"value1", "value2", "value3"}, awsutil.ValuesAtPath(data, "A[].C")) - assert.Equal(t, []interface{}{"terminal"}, awsutil.ValuesAtPath(data, "B . B . C")) - assert.Equal(t, []interface{}{"terminal", "terminal2"}, awsutil.ValuesAtPath(data, "B.*.C")) - assert.Equal(t, []interface{}{"initial"}, awsutil.ValuesAtPath(data, "A.D.X || C")) -} - -func TestValueAtPathFailure(t *testing.T) { - assert.Equal(t, []interface{}(nil), awsutil.ValuesAtPath(data, "C.x")) - assert.Equal(t, []interface{}(nil), awsutil.ValuesAtPath(data, ".x")) - assert.Equal(t, []interface{}{}, awsutil.ValuesAtPath(data, "X.Y.Z")) - assert.Equal(t, []interface{}{}, awsutil.ValuesAtPath(data, "A[100].C")) - assert.Equal(t, []interface{}{}, awsutil.ValuesAtPath(data, "A[3].C")) - assert.Equal(t, []interface{}{}, awsutil.ValuesAtPath(data, "B.B.C.Z")) - assert.Equal(t, []interface{}(nil), awsutil.ValuesAtPath(data, "z[-1].C")) - assert.Equal(t, []interface{}{}, awsutil.ValuesAtPath(nil, "A.B.C")) - assert.Equal(t, []interface{}{}, awsutil.ValuesAtPath(Struct{}, "A")) -} - -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") - assert.Equal(t, "test1", s.C) - assert.Equal(t, "test2", s.B.B.C) - assert.Equal(t, "test3", s.B.D.C) - - awsutil.SetValueAtPath(&s, "B.*.C", "test0") - assert.Equal(t, "test0", s.B.B.C) - assert.Equal(t, "test0", s.B.D.C) - - var s2 Struct - awsutil.SetValueAtAnyPath(&s2, "b.b.c", "test0") - assert.Equal(t, "test0", s2.B.B.C) - awsutil.SetValueAtAnyPath(&s2, "A", []Struct{{}}) - assert.Equal(t, []Struct{{}}, s2.A) -} diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/config.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/config.go index 3b342e18e..a72f70222 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/config.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/config.go @@ -2,6 +2,7 @@ package aws import ( "net/http" + "time" "github.com/aws/aws-sdk-go/aws/credentials" ) @@ -11,10 +12,10 @@ import ( const DefaultRetries = -1 // A Config provides service configuration for service clients. By default, -// all clients will use the {DefaultConfig} structure. +// all clients will use the {defaults.DefaultConfig} structure. type Config struct { // The credentials object to use when signing requests. Defaults to - // {DefaultChainCredentials}. + // {defaults.DefaultChainCredentials}. Credentials *credentials.Credentials // An optional endpoint URL (hostname only or fully qualified URI) @@ -73,6 +74,8 @@ type Config struct { // @see http://docs.aws.amazon.com/AmazonS3/latest/dev/VirtualHosting.html // Amazon S3: Virtual Hosting of Buckets S3ForcePathStyle *bool + + SleepDelay func(time.Duration) } // NewConfig returns a new Config pointer that can be chained with builder methods to @@ -161,6 +164,13 @@ func (c *Config) WithS3ForcePathStyle(force bool) *Config { return c } +// WithSleepDelay overrides the function used to sleep while waiting for the +// next retry. Defaults to time.Sleep. +func (c *Config) WithSleepDelay(fn func(time.Duration)) *Config { + c.SleepDelay = fn + return c +} + // Merge returns a new Config with the other Config's attribute values merged into // this Config. If the other Config's attribute is nil it will not be merged into // the new Config to be returned. @@ -215,6 +225,10 @@ func (c Config) Merge(other *Config) *Config { dst.S3ForcePathStyle = other.S3ForcePathStyle } + if other.SleepDelay != nil { + dst.SleepDelay = other.SleepDelay + } + return &dst } diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/config_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/config_test.go deleted file mode 100644 index c4320ca1e..000000000 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/config_test.go +++ /dev/null @@ -1,80 +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(DefaultRetries), - 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) - } -} - -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.Merge(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/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/convert_types_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/convert_types_test.go deleted file mode 100644 index df7a3e5d2..000000000 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/convert_types_test.go +++ /dev/null @@ -1,437 +0,0 @@ -package aws - -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 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/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/service/handler_functions.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/corehandlers/handlers.go similarity index 70% rename from Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/service/handler_functions.go rename to Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/corehandlers/handlers.go index 8afce7523..2fcb391a2 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/service/handler_functions.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/corehandlers/handlers.go @@ -1,4 +1,4 @@ -package service +package corehandlers import ( "bytes" @@ -9,16 +9,12 @@ import ( "net/url" "regexp" "strconv" - "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" + "github.com/aws/aws-sdk-go/aws/request" ) -var sleepDelay = func(delay time.Duration) { - time.Sleep(delay) -} - // Interface for matching types which also have a Len method. type lener interface { Len() int @@ -27,7 +23,7 @@ type lener interface { // BuildContentLength builds the content length of a request based on the body, // or will use the HTTPRequest.Header's "Content-Length" if defined. If unable // to determine request body length and no "Content-Length" was specified it will panic. -func BuildContentLength(r *Request) { +var BuildContentLengthHandler = request.NamedHandler{"core.BuildContentLengthHandler", func(r *request.Request) { if slength := r.HTTPRequest.Header.Get("Content-Length"); slength != "" { length, _ := strconv.ParseInt(slength, 10, 64) r.HTTPRequest.ContentLength = length @@ -41,27 +37,27 @@ func BuildContentLength(r *Request) { case lener: length = int64(body.Len()) case io.Seeker: - r.bodyStart, _ = body.Seek(0, 1) + r.BodyStart, _ = body.Seek(0, 1) end, _ := body.Seek(0, 2) - body.Seek(r.bodyStart, 0) // make sure to seek back to original location - length = end - r.bodyStart + body.Seek(r.BodyStart, 0) // make sure to seek back to original location + length = end - r.BodyStart default: panic("Cannot get length of body, must provide `ContentLength`") } r.HTTPRequest.ContentLength = length r.HTTPRequest.Header.Set("Content-Length", fmt.Sprintf("%d", length)) -} +}} // UserAgentHandler is a request handler for injecting User agent into requests. -func UserAgentHandler(r *Request) { +var UserAgentHandler = request.NamedHandler{"core.UserAgentHandler", func(r *request.Request) { r.HTTPRequest.Header.Set("User-Agent", aws.SDKName+"/"+aws.SDKVersion) -} +}} -var reStatusCode = regexp.MustCompile(`^(\d+)`) +var reStatusCode = regexp.MustCompile(`^(\d{3})`) // SendHandler is a request handler to send service request using HTTP client. -func SendHandler(r *Request) { +var SendHandler = request.NamedHandler{"core.SendHandler", func(r *request.Request) { var err error r.HTTPResponse, err = r.Service.Config.HTTPClient.Do(r.HTTPRequest) if err != nil { @@ -69,8 +65,8 @@ func SendHandler(r *Request) { // response. e.g. 301 without location header comes back as string // error and r.HTTPResponse is nil. Other url redirect errors will // comeback in a similar method. - if e, ok := err.(*url.Error); ok { - if s := reStatusCode.FindStringSubmatch(e.Error()); s != nil { + if e, ok := err.(*url.Error); ok && e.Err != nil { + if s := reStatusCode.FindStringSubmatch(e.Err.Error()); s != nil { code, _ := strconv.ParseInt(s[1], 10, 64) r.HTTPResponse = &http.Response{ StatusCode: int(code), @@ -93,66 +89,48 @@ func SendHandler(r *Request) { r.Error = awserr.New("RequestError", "send request failed", err) r.Retryable = aws.Bool(true) // network errors are retryable } -} +}} // ValidateResponseHandler is a request handler to validate service response. -func ValidateResponseHandler(r *Request) { +var ValidateResponseHandler = request.NamedHandler{"core.ValidateResponseHandler", func(r *request.Request) { if r.HTTPResponse.StatusCode == 0 || r.HTTPResponse.StatusCode >= 300 { // this may be replaced by an UnmarshalError handler r.Error = awserr.New("UnknownError", "unknown error", nil) } -} +}} // AfterRetryHandler performs final checks to determine if the request should // be retried and how long to delay. -func AfterRetryHandler(r *Request) { +var AfterRetryHandler = request.NamedHandler{"core.AfterRetryHandler", func(r *request.Request) { // If one of the other handlers already set the retry state // we don't want to override it based on the service's state if r.Retryable == nil { - r.Retryable = aws.Bool(r.Service.ShouldRetry(r)) + r.Retryable = aws.Bool(r.ShouldRetry(r)) } if r.WillRetry() { - r.RetryDelay = r.Service.RetryRules(r) - sleepDelay(r.RetryDelay) + r.RetryDelay = r.RetryRules(r) + r.Service.Config.SleepDelay(r.RetryDelay) // when the expired token exception occurs the credentials // need to be expired locally so that the next request to // get credentials will trigger a credentials refresh. - if r.Error != nil { - if err, ok := r.Error.(awserr.Error); ok { - if isCodeExpiredCreds(err.Code()) { - r.Config.Credentials.Expire() - } - } + if r.IsErrorExpired() { + r.Service.Config.Credentials.Expire() } r.RetryCount++ r.Error = nil } -} - -var ( - // ErrMissingRegion is an error that is returned if region configuration is - // not found. - // - // @readonly - ErrMissingRegion error = awserr.New("MissingRegion", "could not find region configuration", nil) - - // ErrMissingEndpoint is an error that is returned if an endpoint cannot be - // resolved for a service. - // - // @readonly - ErrMissingEndpoint error = awserr.New("MissingEndpoint", "'Endpoint' configuration is required for this service", nil) -) +}} // ValidateEndpointHandler is a request handler to validate a request had the // appropriate Region and Endpoint set. Will set r.Error if the endpoint or // region is not valid. -func ValidateEndpointHandler(r *Request) { +var ValidateEndpointHandler = request.NamedHandler{"core.ValidateEndpointHandler", func(r *request.Request) { if r.Service.SigningRegion == "" && aws.StringValue(r.Service.Config.Region) == "" { - r.Error = ErrMissingRegion + r.Error = aws.ErrMissingRegion } else if r.Service.Endpoint == "" { - r.Error = ErrMissingEndpoint + r.Error = aws.ErrMissingEndpoint } -} +}} diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/corehandlers/param_validator.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/corehandlers/param_validator.go new file mode 100644 index 000000000..a22197734 --- /dev/null +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/corehandlers/param_validator.go @@ -0,0 +1,144 @@ +package corehandlers + +import ( + "fmt" + "reflect" + "strconv" + "strings" + + "github.com/aws/aws-sdk-go/aws/awserr" + "github.com/aws/aws-sdk-go/aws/request" +) + +// ValidateParameters is a request handler to validate the input parameters. +// Validating parameters only has meaning if done prior to the request being sent. +var ValidateParametersHandler = request.NamedHandler{"core.ValidateParametersHandler", func(r *request.Request) { + if r.ParamsFilled() { + v := validator{errors: []string{}} + v.validateAny(reflect.ValueOf(r.Params), "") + + if count := len(v.errors); count > 0 { + format := "%d validation errors:\n- %s" + msg := fmt.Sprintf(format, count, strings.Join(v.errors, "\n- ")) + r.Error = awserr.New("InvalidParameter", msg, nil) + } + } +}} + +// A validator validates values. Collects validations errors which occurs. +type validator struct { + errors []string +} + +// validateAny will validate any struct, slice or map type. All validations +// are also performed recursively for nested types. +func (v *validator) validateAny(value reflect.Value, path string) { + value = reflect.Indirect(value) + if !value.IsValid() { + return + } + + switch value.Kind() { + case reflect.Struct: + v.validateStruct(value, path) + case reflect.Slice: + for i := 0; i < value.Len(); i++ { + v.validateAny(value.Index(i), path+fmt.Sprintf("[%d]", i)) + } + case reflect.Map: + for _, n := range value.MapKeys() { + v.validateAny(value.MapIndex(n), path+fmt.Sprintf("[%q]", n.String())) + } + } +} + +// validateStruct will validate the struct value's fields. If the structure has +// nested types those types will be validated also. +func (v *validator) validateStruct(value reflect.Value, path string) { + prefix := "." + if path == "" { + prefix = "" + } + + for i := 0; i < value.Type().NumField(); i++ { + f := value.Type().Field(i) + if strings.ToLower(f.Name[0:1]) == f.Name[0:1] { + continue + } + fvalue := value.FieldByName(f.Name) + + err := validateField(f, fvalue, validateFieldRequired, validateFieldMin) + if err != nil { + v.errors = append(v.errors, fmt.Sprintf("%s: %s", err.Error(), path+prefix+f.Name)) + continue + } + + v.validateAny(fvalue, path+prefix+f.Name) + } +} + +type validatorFunc func(f reflect.StructField, fvalue reflect.Value) error + +func validateField(f reflect.StructField, fvalue reflect.Value, funcs ...validatorFunc) error { + for _, fn := range funcs { + if err := fn(f, fvalue); err != nil { + return err + } + } + return nil +} + +// Validates that a field has a valid value provided for required fields. +func validateFieldRequired(f reflect.StructField, fvalue reflect.Value) error { + if f.Tag.Get("required") == "" { + return nil + } + + switch fvalue.Kind() { + case reflect.Ptr, reflect.Slice, reflect.Map: + if fvalue.IsNil() { + return fmt.Errorf("missing required parameter") + } + default: + if !fvalue.IsValid() { + return fmt.Errorf("missing required parameter") + } + } + return nil +} + +// Validates that if a value is provided for a field, that value must be at +// least a minimum length. +func validateFieldMin(f reflect.StructField, fvalue reflect.Value) error { + minStr := f.Tag.Get("min") + if minStr == "" { + return nil + } + min, _ := strconv.ParseInt(minStr, 10, 64) + + kind := fvalue.Kind() + if kind == reflect.Ptr { + if fvalue.IsNil() { + return nil + } + fvalue = fvalue.Elem() + } + + switch fvalue.Kind() { + case reflect.String: + if int64(fvalue.Len()) < min { + return fmt.Errorf("field too short, minimum length %d", min) + } + case reflect.Slice, reflect.Map: + if fvalue.IsNil() { + return nil + } + if int64(fvalue.Len()) < min { + return fmt.Errorf("field too short, minimum length %d", min) + } + + // TODO min can also apply to number minimum value. + + } + return nil +} diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/chain_provider_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/chain_provider_test.go deleted file mode 100644 index 4fba22f29..000000000 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/chain_provider_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" -) - -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) { - p := &ChainProvider{ - Providers: []Provider{ - &stubProvider{err: awserr.New("FirstError", "first provider error", nil)}, - &stubProvider{err: awserr.New("SecondError", "second provider error", nil)}, - }, - } - - assert.True(t, p.IsExpired(), "Expect expired with no providers") - _, err := p.Retrieve() - assert.Equal(t, ErrNoValidProvidersFoundInChain, err, "Expect no providers error returned") -} diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/credentials_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/credentials_test.go deleted file mode 100644 index 99c2b4774..000000000 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/credentials_test.go +++ /dev/null @@ -1,62 +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 - 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") -} diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds/ec2_role_provider_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds/ec2_role_provider_test.go deleted file mode 100644 index cd0cbc97e..000000000 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds/ec2_role_provider_test.go +++ /dev/null @@ -1,161 +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" -) - -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(&ec2metadata.Config{Endpoint: aws.String(server.URL + "/latest")}), - } - - 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 TestEC2RoleProviderFailAssume(t *testing.T) { - server := initTestServer("2014-12-16T01:51:37Z", true) - defer server.Close() - - p := &ec2rolecreds.EC2RoleProvider{ - Client: ec2metadata.New(&ec2metadata.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(&ec2metadata.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") - - 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(&ec2metadata.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") - - 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 BenchmarkEC2RoleProvider(b *testing.B) { - server := initTestServer("2014-12-16T01:51:37Z", false) - defer server.Close() - - p := &ec2rolecreds.EC2RoleProvider{ - Client: ec2metadata.New(&ec2metadata.Config{Endpoint: aws.String(server.URL + "/latest")}), - } - _, err := p.Retrieve() - if err != nil { - b.Fatal(err) - } - - b.ResetTimer() - b.RunParallel(func(pb *testing.PB) { - for pb.Next() { - _, err := p.Retrieve() - if err != nil { - b.Fatal(err) - } - } - }) -} diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/env_provider_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/env_provider_test.go deleted file mode 100644 index 53f6ce256..000000000 --- a/Godeps/_workspace/src/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/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/shared_credentials_provider_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/shared_credentials_provider_test.go deleted file mode 100644 index 768e63fb9..000000000 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/shared_credentials_provider_test.go +++ /dev/null @@ -1,90 +0,0 @@ -package credentials - -import ( - "github.com/stretchr/testify/assert" - "os" - "testing" -) - -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_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 BenchmarkSharedCredentialsProvider(b *testing.B) { - os.Clearenv() - - p := SharedCredentialsProvider{Filename: "example.ini", Profile: ""} - _, err := p.Retrieve() - if err != nil { - b.Fatal(err) - } - - b.ResetTimer() - b.RunParallel(func(pb *testing.PB) { - for pb.Next() { - _, err := p.Retrieve() - if err != nil { - b.Fatal(err) - } - } - }) -} diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/static_provider_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/static_provider_test.go deleted file mode 100644 index ea0123696..000000000 --- a/Godeps/_workspace/src/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/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/stscreds/assume_role_provider.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/stscreds/assume_role_provider.go index b71a74f53..7a4459f80 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/stscreds/assume_role_provider.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/stscreds/assume_role_provider.go @@ -54,6 +54,9 @@ type AssumeRoleProvider struct { // Expiry duration of the STS credentials. Defaults to 15 minutes if not set. Duration time.Duration + // Optional ExternalID to pass along, defaults to nil if not set. + ExternalID *string + // ExpiryWindow will allow the credentials to trigger refreshing prior to // the credentials actually expiring. This is beneficial so race conditions // with expiring credentials do not cause request to fail unexpectedly @@ -104,6 +107,7 @@ func (p *AssumeRoleProvider) Retrieve() (credentials.Value, error) { DurationSeconds: aws.Int64(int64(p.Duration / time.Second)), RoleArn: aws.String(p.RoleARN), RoleSessionName: aws.String(p.RoleSessionName), + ExternalId: p.ExternalID, }) if err != nil { diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/stscreds/assume_role_provider_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/stscreds/assume_role_provider_test.go deleted file mode 100644 index f5b97c005..000000000 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/stscreds/assume_role_provider_test.go +++ /dev/null @@ -1,59 +0,0 @@ -package stscreds - -import ( - "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 { -} - -func (s *stubSTS) AssumeRole(input *sts.AssumeRoleInput) (*sts.AssumeRoleOutput, error) { - 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 BenchmarkAssumeRoleProvider(b *testing.B) { - stub := &stubSTS{} - p := &AssumeRoleProvider{ - Client: stub, - RoleARN: "roleARN", - } - - b.ResetTimer() - b.RunParallel(func(pb *testing.PB) { - for pb.Next() { - _, err := p.Retrieve() - if err != nil { - b.Fatal(err) - } - } - }) -} diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/defaults/defaults.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/defaults/defaults.go index b24f14bff..2f161b57f 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/defaults/defaults.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/defaults/defaults.go @@ -35,4 +35,5 @@ var DefaultConfig = aws.NewConfig(). WithHTTPClient(http.DefaultClient). WithMaxRetries(aws.DefaultRetries). WithLogger(aws.NewDefaultLogger()). - WithLogLevel(aws.LogOff) + WithLogLevel(aws.LogOff). + WithSleepDelay(time.Sleep) diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/ec2metadata/api.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/ec2metadata/api.go index 896abe218..9d784b6e6 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/ec2metadata/api.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/ec2metadata/api.go @@ -3,19 +3,19 @@ package ec2metadata import ( "path" - "github.com/aws/aws-sdk-go/aws/service" + "github.com/aws/aws-sdk-go/aws/request" ) // GetMetadata uses the path provided to request func (c *Client) GetMetadata(p string) (string, error) { - op := &service.Operation{ + op := &request.Operation{ Name: "GetMetadata", HTTPMethod: "GET", HTTPPath: path.Join("/", "meta-data", p), } output := &metadataOutput{} - req := service.NewRequest(c.Service, op, nil, output) + req := request.New(c.Service.ServiceInfo, c.Service.Handlers, c.Service.Retryer, op, nil, output) return output.Content, req.Send() } diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/ec2metadata/api_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/ec2metadata/api_test.go deleted file mode 100644 index a371cf065..000000000 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/ec2metadata/api_test.go +++ /dev/null @@ -1,100 +0,0 @@ -package ec2metadata_test - -import ( - "bytes" - "io/ioutil" - "net/http" - "net/http/httptest" - "path" - "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/ec2metadata" - "github.com/aws/aws-sdk-go/aws/service" -) - -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(&ec2metadata.Config{}) - op := &service.Operation{ - Name: "GetMetadata", - HTTPMethod: "GET", - HTTPPath: path.Join("/", "meta-data", "testpath"), - } - - req := service.NewRequest(c.Service, op, nil, nil) - assert.Equal(t, "http://169.254.169.254/latest", req.Endpoint) - assert.Equal(t, "http://169.254.169.254/latest/meta-data/testpath", req.HTTPRequest.URL.String()) -} - -func TestGetMetadata(t *testing.T) { - server := initTestServer( - "/latest/meta-data/some/path", - "success", // real response includes suffix - ) - defer server.Close() - c := ec2metadata.New(&ec2metadata.Config{Endpoint: aws.String(server.URL + "/latest")}) - - resp, err := c.GetMetadata("some/path") - - assert.NoError(t, err) - assert.Equal(t, "success", resp) -} - -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(&ec2metadata.Config{Endpoint: aws.String(server.URL + "/latest")}) - - region, err := c.Region() - - assert.NoError(t, err) - assert.Equal(t, "us-west-2", region) -} - -func TestMetadataAvailable(t *testing.T) { - server := initTestServer( - "/latest/meta-data/instance-id", - "instance-id", - ) - defer server.Close() - c := ec2metadata.New(&ec2metadata.Config{Endpoint: aws.String(server.URL + "/latest")}) - - available := c.Available() - - assert.True(t, available) -} - -func TestMetadataNotAvailable(t *testing.T) { - c := ec2metadata.New(nil) - c.Handlers.Send.Clear() - c.Handlers.Send.PushBack(func(r *service.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 - }) - - available := c.Available() - - assert.False(t, available) -} diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/ec2metadata/service.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/ec2metadata/service.go index cbf067dd4..d230df6f9 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/ec2metadata/service.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/ec2metadata/service.go @@ -7,7 +7,9 @@ import ( "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/aws/request" "github.com/aws/aws-sdk-go/aws/service" + "github.com/aws/aws-sdk-go/aws/service/serviceinfo" ) // DefaultRetries states the default number of times the service client will @@ -56,10 +58,12 @@ type Client struct { // with the defaults package and credentials EC2 Role Provider. func New(config *Config) *Client { service := &service.Service{ - Config: copyConfig(config), - ServiceName: "Client", - Endpoint: "http://169.254.169.254/latest", - APIVersion: "latest", + ServiceInfo: serviceinfo.ServiceInfo{ + Config: copyConfig(config), + ServiceName: "Client", + Endpoint: "http://169.254.169.254/latest", + APIVersion: "latest", + }, } service.Initialize() service.Handlers.Unmarshal.PushBack(unmarshalHandler) @@ -103,7 +107,7 @@ type metadataOutput struct { Content string } -func unmarshalHandler(r *service.Request) { +func unmarshalHandler(r *request.Request) { defer r.HTTPResponse.Body.Close() b, err := ioutil.ReadAll(r.HTTPResponse.Body) if err != nil { @@ -114,7 +118,7 @@ func unmarshalHandler(r *service.Request) { data.Content = string(b) } -func unmarshalError(r *service.Request) { +func unmarshalError(r *request.Request) { defer r.HTTPResponse.Body.Close() _, err := ioutil.ReadAll(r.HTTPResponse.Body) if err != nil { @@ -124,8 +128,8 @@ func unmarshalError(r *service.Request) { // TODO extract the error... } -func validateEndpointHandler(r *service.Request) { +func validateEndpointHandler(r *request.Request) { if r.Service.Endpoint == "" { - r.Error = service.ErrMissingEndpoint + r.Error = aws.ErrMissingEndpoint } } diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/errors.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/errors.go new file mode 100644 index 000000000..db2f481b0 --- /dev/null +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/errors.go @@ -0,0 +1,17 @@ +package aws + +import "github.com/aws/aws-sdk-go/aws/awserr" + +var ( + // ErrMissingRegion is an error that is returned if region configuration is + // not found. + // + // @readonly + ErrMissingRegion error = awserr.New("MissingRegion", "could not find region configuration", nil) + + // ErrMissingEndpoint is an error that is returned if an endpoint cannot be + // resolved for a service. + // + // @readonly + ErrMissingEndpoint error = awserr.New("MissingEndpoint", "'Endpoint' configuration is required for this service", nil) +) diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/service/handlers.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/request/handlers.go similarity index 57% rename from Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/service/handlers.go rename to Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/request/handlers.go index 3f125e5a8..85bc122e7 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/service/handlers.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/request/handlers.go @@ -1,4 +1,4 @@ -package service +package request // A Handlers provides a collection of request handlers for various // stages of handling requests. @@ -15,8 +15,8 @@ type Handlers struct { AfterRetry HandlerList } -// copy returns of this handler's lists. -func (h *Handlers) copy() Handlers { +// Copy returns of this handler's lists. +func (h *Handlers) Copy() Handlers { return Handlers{ Validate: h.Validate.copy(), Build: h.Build.copy(), @@ -47,19 +47,25 @@ func (h *Handlers) Clear() { // A HandlerList manages zero or more handlers in a list. type HandlerList struct { - list []func(*Request) + list []NamedHandler +} + +// A NamedHandler is a struct that contains a name and function callback. +type NamedHandler struct { + Name string + Fn func(*Request) } // copy creates a copy of the handler list. func (l *HandlerList) copy() HandlerList { var n HandlerList - n.list = append([]func(*Request){}, l.list...) + n.list = append([]NamedHandler{}, l.list...) return n } // Clear clears the handler list. func (l *HandlerList) Clear() { - l.list = []func(*Request){} + l.list = []NamedHandler{} } // Len returns the number of handlers in the list. @@ -67,19 +73,40 @@ func (l *HandlerList) Len() int { return len(l.list) } -// PushBack pushes handlers f to the back of the handler list. -func (l *HandlerList) PushBack(f ...func(*Request)) { - l.list = append(l.list, f...) +// PushBack pushes handler f to the back of the handler list. +func (l *HandlerList) PushBack(f func(*Request)) { + l.list = append(l.list, NamedHandler{"__anonymous", f}) } -// PushFront pushes handlers f to the front of the handler list. -func (l *HandlerList) PushFront(f ...func(*Request)) { - l.list = append(f, l.list...) +// PushFront pushes handler f to the front of the handler list. +func (l *HandlerList) PushFront(f func(*Request)) { + l.list = append([]NamedHandler{{"__anonymous", f}}, l.list...) +} + +// PushBackNamed pushes named handler f to the back of the handler list. +func (l *HandlerList) PushBackNamed(n NamedHandler) { + l.list = append(l.list, n) +} + +// PushFrontNamed pushes named handler f to the front of the handler list. +func (l *HandlerList) PushFrontNamed(n NamedHandler) { + l.list = append([]NamedHandler{n}, l.list...) +} + +// Remove removes a NamedHandler n +func (l *HandlerList) Remove(n NamedHandler) { + newlist := []NamedHandler{} + for _, m := range l.list { + if m.Name != n.Name { + newlist = append(newlist, m) + } + } + l.list = newlist } // Run executes all handlers in the list with a given request object. func (l *HandlerList) Run(r *Request) { for _, f := range l.list { - f(r) + f.Fn(r) } } diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/service/request.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/request/request.go similarity index 88% rename from Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/service/request.go rename to Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/request/request.go index 24b9c99dc..70c28b883 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/service/request.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/request/request.go @@ -1,4 +1,4 @@ -package service +package request import ( "bytes" @@ -13,11 +13,13 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awsutil" + "github.com/aws/aws-sdk-go/aws/service/serviceinfo" ) // A Request is the service request to be made. type Request struct { - *Service + Retryer + Service serviceinfo.ServiceInfo Handlers Handlers Time time.Time ExpireTime time.Duration @@ -25,7 +27,7 @@ type Request struct { HTTPRequest *http.Request HTTPResponse *http.Response Body io.ReadSeeker - bodyStart int64 // offset from beginning of Body that the request body starts + BodyStart int64 // offset from beginning of Body that the request body starts Params interface{} Error error Data interface{} @@ -53,13 +55,13 @@ type Paginator struct { TruncationToken string } -// NewRequest returns a new Request pointer for the service API +// New returns a new Request pointer for the service API // operation and parameters. // // Params is any value of input parameters to be the request payload. // Data is pointer value to an object which the request's response // payload will be deserialized to. -func NewRequest(service *Service, operation *Operation, params interface{}, data interface{}) *Request { +func New(service serviceinfo.ServiceInfo, handlers Handlers, retryer Retryer, operation *Operation, params interface{}, data interface{}) *Request { method := operation.HTTPMethod if method == "" { method = "POST" @@ -73,8 +75,9 @@ func NewRequest(service *Service, operation *Operation, params interface{}, data httpReq.URL, _ = url.Parse(service.Endpoint + p) r := &Request{ + Retryer: retryer, Service: service, - Handlers: service.Handlers.copy(), + Handlers: handlers.Copy(), Time: time.Now(), ExpireTime: 0, Operation: operation, @@ -91,7 +94,7 @@ func NewRequest(service *Service, operation *Operation, params interface{}, data // WillRetry returns if the request's can be retried. func (r *Request) WillRetry() bool { - return r.Error != nil && aws.BoolValue(r.Retryable) && r.RetryCount < r.Service.MaxRetries() + return r.Error != nil && aws.BoolValue(r.Retryable) && r.RetryCount < r.MaxRetries() } // ParamsFilled returns if the request's parameters have been populated @@ -137,7 +140,7 @@ func (r *Request) Presign(expireTime time.Duration) (string, error) { } func debugLogReqError(r *Request, stage string, retrying bool, err error) { - if !r.Config.LogLevel.Matches(aws.LogDebugWithRequestErrors) { + if !r.Service.Config.LogLevel.Matches(aws.LogDebugWithRequestErrors) { return } @@ -146,8 +149,8 @@ func debugLogReqError(r *Request, stage string, retrying bool, err error) { retryStr = "will retry" } - r.Config.Logger.Log(fmt.Sprintf("DEBUG: %s %s/%s failed, %s, error %v", - stage, r.ServiceName, r.Operation.Name, retryStr, err)) + r.Service.Config.Logger.Log(fmt.Sprintf("DEBUG: %s %s/%s failed, %s, error %v", + stage, r.Service.ServiceName, r.Operation.Name, retryStr, err)) } // Build will build the request's object so it can be signed and sent @@ -202,14 +205,14 @@ func (r *Request) Send() error { } if aws.BoolValue(r.Retryable) { - if r.Config.LogLevel.Matches(aws.LogDebugWithRequestRetries) { - r.Config.Logger.Log(fmt.Sprintf("DEBUG: Retrying Request %s/%s, attempt %d", - r.ServiceName, r.Operation.Name, r.RetryCount)) + if r.Service.Config.LogLevel.Matches(aws.LogDebugWithRequestRetries) { + r.Service.Config.Logger.Log(fmt.Sprintf("DEBUG: Retrying Request %s/%s, attempt %d", + r.Service.ServiceName, r.Operation.Name, r.RetryCount)) } // Re-seek the body back to the original point in for a retry so that // send will send the body's contents again in the upcoming request. - r.Body.Seek(r.bodyStart, 0) + r.Body.Seek(r.BodyStart, 0) r.HTTPRequest.Body = ioutil.NopCloser(r.Body) } r.Retryable = nil @@ -312,7 +315,7 @@ func (r *Request) NextPage() *Request { } data := reflect.New(reflect.TypeOf(r.Data).Elem()).Interface() - nr := NewRequest(r.Service, r.Operation, awsutil.CopyOf(r.Params), data) + nr := New(r.Service, r.Handlers, r.Retryer, r.Operation, awsutil.CopyOf(r.Params), data) for i, intok := range nr.Operation.InputTokens { awsutil.SetValueAtAnyPath(nr.Params, intok, tokens[i]) } diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/request/retryer.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/request/retryer.go new file mode 100644 index 000000000..f03b0c659 --- /dev/null +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/request/retryer.go @@ -0,0 +1,71 @@ +package request + +import ( + "time" + + "github.com/aws/aws-sdk-go/aws/awserr" +) + +// Retryer is an interface to control retry logic for a given service. +// The default implementation used by most services is the service.DefaultRetryer +// structure, which contains basic retry logic using exponential backoff. +type Retryer interface { + RetryRules(*Request) time.Duration + ShouldRetry(*Request) bool + MaxRetries() uint +} + +// retryableCodes is a collection of service response codes which are retry-able +// without any further action. +var retryableCodes = map[string]struct{}{ + "RequestError": {}, + "ProvisionedThroughputExceededException": {}, + "Throttling": {}, + "ThrottlingException": {}, + "RequestLimitExceeded": {}, + "RequestThrottled": {}, +} + +// credsExpiredCodes is a collection of error codes which signify the credentials +// need to be refreshed. Expired tokens require refreshing of credentials, and +// resigning before the request can be retried. +var credsExpiredCodes = map[string]struct{}{ + "ExpiredToken": {}, + "ExpiredTokenException": {}, + "RequestExpired": {}, // EC2 Only +} + +func isCodeRetryable(code string) bool { + if _, ok := retryableCodes[code]; ok { + return true + } + + return isCodeExpiredCreds(code) +} + +func isCodeExpiredCreds(code string) bool { + _, ok := credsExpiredCodes[code] + return ok +} + +// IsErrorRetryable returns whether the error is retryable, based on its Code. +// Returns false if the request has no Error set. +func (r *Request) IsErrorRetryable() bool { + if r.Error != nil { + if err, ok := r.Error.(awserr.Error); ok { + return isCodeRetryable(err.Code()) + } + } + return false +} + +// IsErrorExpired returns whether the error code is a credential expiry error. +// Returns false if the request has no Error set. +func (r *Request) IsErrorExpired() bool { + if r.Error != nil { + if err, ok := r.Error.(awserr.Error); ok { + return isCodeExpiredCreds(err.Code()) + } + } + return false +} diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/service/default_retryer.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/service/default_retryer.go new file mode 100644 index 000000000..e642d16b7 --- /dev/null +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/service/default_retryer.go @@ -0,0 +1,51 @@ +package service + +import ( + "math" + "math/rand" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/request" +) + +// DefaultRetryer implements basic retry logic using exponential backoff for +// most services. If you want to implement custom retry logic, implement the +// request.Retryer interface or create a structure type that composes this +// struct and override the specific methods. For example, to override only +// the MaxRetries method: +// +// type retryer struct { +// service.DefaultRetryer +// } +// +// // This implementation always has 100 max retries +// func (d retryer) MaxRetries() uint { return 100 } +type DefaultRetryer struct { + *Service +} + +// MaxRetries returns the number of maximum returns the service will use to make +// an individual API request. +func (d DefaultRetryer) MaxRetries() uint { + if aws.IntValue(d.Service.Config.MaxRetries) < 0 { + return d.DefaultMaxRetries + } + return uint(aws.IntValue(d.Service.Config.MaxRetries)) +} + +var seededRand = rand.New(rand.NewSource(time.Now().UnixNano())) + +// RetryRules returns the delay duration before retrying this request again +func (d DefaultRetryer) RetryRules(r *request.Request) time.Duration { + delay := int(math.Pow(2, float64(r.RetryCount))) * (seededRand.Intn(30) + 30) + return time.Duration(delay) * time.Millisecond +} + +// ShouldRetry returns if the request should be retried. +func (d DefaultRetryer) ShouldRetry(r *request.Request) bool { + if r.HTTPResponse.StatusCode >= 500 { + return true + } + return r.IsErrorRetryable() +} diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/service/handler_functions_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/service/handler_functions_test.go deleted file mode 100644 index 418da7b7c..000000000 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/service/handler_functions_test.go +++ /dev/null @@ -1,106 +0,0 @@ -package service - -import ( - "fmt" - "net/http" - "os" - "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/credentials" -) - -func TestValidateEndpointHandler(t *testing.T) { - os.Clearenv() - svc := NewService(aws.NewConfig().WithRegion("us-west-2")) - svc.Handlers.Clear() - svc.Handlers.Validate.PushBack(ValidateEndpointHandler) - - req := NewRequest(svc, &Operation{Name: "Operation"}, nil, nil) - err := req.Build() - - assert.NoError(t, err) -} - -func TestValidateEndpointHandlerErrorRegion(t *testing.T) { - os.Clearenv() - svc := NewService(nil) - svc.Handlers.Clear() - svc.Handlers.Validate.PushBack(ValidateEndpointHandler) - - req := NewRequest(svc, &Operation{Name: "Operation"}, nil, nil) - err := req.Build() - - assert.Error(t, err) - assert.Equal(t, ErrMissingRegion, err) -} - -type mockCredsProvider struct { - expired bool - retrieveCalled bool -} - -func (m *mockCredsProvider) Retrieve() (credentials.Value, error) { - m.retrieveCalled = true - return credentials.Value{}, nil -} - -func (m *mockCredsProvider) IsExpired() bool { - return m.expired -} - -func TestAfterRetryRefreshCreds(t *testing.T) { - os.Clearenv() - credProvider := &mockCredsProvider{} - svc := NewService(&aws.Config{Credentials: credentials.NewCredentials(credProvider), MaxRetries: aws.Int(1)}) - - svc.Handlers.Clear() - svc.Handlers.ValidateResponse.PushBack(func(r *Request) { - r.Error = awserr.New("UnknownError", "", nil) - r.HTTPResponse = &http.Response{StatusCode: 400} - }) - svc.Handlers.UnmarshalError.PushBack(func(r *Request) { - r.Error = awserr.New("ExpiredTokenException", "", nil) - }) - svc.Handlers.AfterRetry.PushBack(func(r *Request) { - AfterRetryHandler(r) - }) - - assert.True(t, svc.Config.Credentials.IsExpired(), "Expect to start out expired") - assert.False(t, credProvider.retrieveCalled) - - req := NewRequest(svc, &Operation{Name: "Operation"}, nil, nil) - req.Send() - - assert.True(t, svc.Config.Credentials.IsExpired()) - assert.False(t, credProvider.retrieveCalled) - - _, err := svc.Config.Credentials.Get() - assert.NoError(t, err) - assert.True(t, credProvider.retrieveCalled) -} - -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 := NewService(&aws.Config{ - HTTPClient: &http.Client{ - Transport: &testSendHandlerTransport{}, - }, - }) - svc.Handlers.Clear() - svc.Handlers.Send.PushBack(SendHandler) - r := NewRequest(svc, &Operation{Name: "Operation"}, nil, nil) - - r.Send() - - assert.Error(t, r.Error) - assert.NotNil(t, r.HTTPResponse) -} diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/service/handlers_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/service/handlers_test.go deleted file mode 100644 index d129269f0..000000000 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/service/handlers_test.go +++ /dev/null @@ -1,33 +0,0 @@ -package service - -import ( - "testing" - - "github.com/stretchr/testify/assert" - - "github.com/aws/aws-sdk-go/aws" -) - -func TestHandlerList(t *testing.T) { - s := "" - r := &Request{} - l := HandlerList{} - l.PushBack(func(r *Request) { - s += "a" - r.Data = s - }) - l.Run(r) - assert.Equal(t, "a", s) - assert.Equal(t, "a", r.Data) -} - -func TestMultipleHandlers(t *testing.T) { - r := &Request{} - l := HandlerList{} - l.PushBack(func(r *Request) { r.Data = nil }) - l.PushFront(func(r *Request) { r.Data = aws.Bool(true) }) - l.Run(r) - if r.Data != nil { - t.Error("Expected handler to execute") - } -} diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/service/param_validator.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/service/param_validator.go deleted file mode 100644 index 76c67d029..000000000 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/service/param_validator.go +++ /dev/null @@ -1,89 +0,0 @@ -package service - -import ( - "fmt" - "reflect" - "strings" - - "github.com/aws/aws-sdk-go/aws/awserr" -) - -// ValidateParameters is a request handler to validate the input parameters. -// Validating parameters only has meaning if done prior to the request being sent. -func ValidateParameters(r *Request) { - if r.ParamsFilled() { - v := validator{errors: []string{}} - v.validateAny(reflect.ValueOf(r.Params), "") - - if count := len(v.errors); count > 0 { - format := "%d validation errors:\n- %s" - msg := fmt.Sprintf(format, count, strings.Join(v.errors, "\n- ")) - r.Error = awserr.New("InvalidParameter", msg, nil) - } - } -} - -// A validator validates values. Collects validations errors which occurs. -type validator struct { - errors []string -} - -// validateAny will validate any struct, slice or map type. All validations -// are also performed recursively for nested types. -func (v *validator) validateAny(value reflect.Value, path string) { - value = reflect.Indirect(value) - if !value.IsValid() { - return - } - - switch value.Kind() { - case reflect.Struct: - v.validateStruct(value, path) - case reflect.Slice: - for i := 0; i < value.Len(); i++ { - v.validateAny(value.Index(i), path+fmt.Sprintf("[%d]", i)) - } - case reflect.Map: - for _, n := range value.MapKeys() { - v.validateAny(value.MapIndex(n), path+fmt.Sprintf("[%q]", n.String())) - } - } -} - -// validateStruct will validate the struct value's fields. If the structure has -// nested types those types will be validated also. -func (v *validator) validateStruct(value reflect.Value, path string) { - prefix := "." - if path == "" { - prefix = "" - } - - for i := 0; i < value.Type().NumField(); i++ { - f := value.Type().Field(i) - if strings.ToLower(f.Name[0:1]) == f.Name[0:1] { - continue - } - fvalue := value.FieldByName(f.Name) - - notset := false - if f.Tag.Get("required") != "" { - switch fvalue.Kind() { - case reflect.Ptr, reflect.Slice, reflect.Map: - if fvalue.IsNil() { - notset = true - } - default: - if !fvalue.IsValid() { - notset = true - } - } - } - - if notset { - msg := "missing required parameter: " + path + prefix + f.Name - v.errors = append(v.errors, msg) - } else { - v.validateAny(fvalue, path+prefix+f.Name) - } - } -} diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/service/param_validator_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/service/param_validator_test.go deleted file mode 100644 index 514f844af..000000000 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/service/param_validator_test.go +++ /dev/null @@ -1,85 +0,0 @@ -package service - -import ( - "testing" - - "github.com/stretchr/testify/assert" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" -) - -var testSvc = func() *Service { - s := &Service{ - Config: &aws.Config{}, - ServiceName: "mock-service", - APIVersion: "2015-01-01", - } - return s -}() - -type StructShape struct { - RequiredList []*ConditionalStructShape `required:"true"` - RequiredMap map[string]*ConditionalStructShape `required:"true"` - RequiredBool *bool `required:"true"` - OptionalStruct *ConditionalStructShape - - hiddenParameter *string - - metadataStructureShape -} - -type metadataStructureShape struct { - SDKShapeTraits bool -} - -type ConditionalStructShape struct { - Name *string `required:"true"` - SDKShapeTraits bool -} - -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 := NewRequest(testSvc, &Operation{}, input, nil) - ValidateParameters(req) - assert.NoError(t, req.Error) -} - -func TestMissingRequiredParameters(t *testing.T) { - input := &StructShape{} - req := NewRequest(testSvc, &Operation{}, input, nil) - ValidateParameters(req) - - assert.Error(t, req.Error) - assert.Equal(t, "InvalidParameter", req.Error.(awserr.Error).Code()) - assert.Equal(t, "3 validation errors:\n- missing required parameter: RequiredList\n- missing required parameter: RequiredMap\n- missing required parameter: RequiredBool", req.Error.(awserr.Error).Message()) -} - -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 := NewRequest(testSvc, &Operation{}, input, nil) - ValidateParameters(req) - - assert.Error(t, req.Error) - assert.Equal(t, "InvalidParameter", req.Error.(awserr.Error).Code()) - assert.Equal(t, "3 validation errors:\n- missing required parameter: RequiredList[0].Name\n- missing required parameter: RequiredMap[\"key2\"].Name\n- missing required parameter: OptionalStruct.Name", req.Error.(awserr.Error).Message()) - -} diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/service/request_pagination_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/service/request_pagination_test.go deleted file mode 100644 index a236960fa..000000000 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/service/request_pagination_test.go +++ /dev/null @@ -1,307 +0,0 @@ -package service_test - -import ( - "testing" - - "github.com/stretchr/testify/assert" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/service" - "github.com/aws/aws-sdk-go/internal/test/unit" - "github.com/aws/aws-sdk-go/service/dynamodb" - "github.com/aws/aws-sdk-go/service/s3" -) - -var _ = unit.Imported - -// Use DynamoDB methods for simplicity -func TestPagination(t *testing.T) { - db := dynamodb.New(nil) - 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 *service.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 *service.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(nil) - 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 *service.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 *service.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(nil) - 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 *service.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(nil) - client.Handlers.Send.Clear() // mock sending - client.Handlers.Unmarshal.Clear() - client.Handlers.UnmarshalMeta.Clear() - client.Handlers.ValidateResponse.Clear() - client.Handlers.Unmarshal.PushBack(func(r *service.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) { - count := 0 - client := s3.New(nil) - - reqNum := &count - 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 *service.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 - count = 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) - -} - -// 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(nil) - 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 *service.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 *service.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/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/service/request_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/service/request_test.go deleted file mode 100644 index a07353dcb..000000000 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/service/request_test.go +++ /dev/null @@ -1,226 +0,0 @@ -package service - -import ( - "bytes" - "encoding/json" - "fmt" - "io" - "io/ioutil" - "net/http" - "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/stretchr/testify/assert" -) - -type testData struct { - Data string -} - -func body(str string) io.ReadCloser { - return ioutil.NopCloser(bytes.NewReader([]byte(str))) -} - -func unmarshal(req *Request) { - defer req.HTTPResponse.Body.Close() - if req.Data != nil { - json.NewDecoder(req.HTTPResponse.Body).Decode(req.Data) - } - return -} - -func unmarshalError(req *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 := NewService(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) { - r.HTTPResponse = &reqs[reqNum] - reqNum++ - }) - out := &testData{} - r := NewRequest(s, &Operation{Name: "Operation"}, nil, out) - err := r.Send() - assert.Nil(t, err) - assert.Equal(t, 2, int(r.RetryCount)) - assert.Equal(t, "valid", out.Data) -} - -// 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 := NewService(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) { - r.HTTPResponse = &reqs[reqNum] - reqNum++ - }) - out := &testData{} - r := NewRequest(s, &Operation{Name: "Operation"}, nil, out) - err := r.Send() - assert.Nil(t, err) - assert.Equal(t, 2, int(r.RetryCount)) - assert.Equal(t, "valid", out.Data) -} - -// 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 := NewService(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) { - r.HTTPResponse = &http.Response{StatusCode: 401, Body: body(`{"__type":"SignatureDoesNotMatch","message":"Signature does not match."}`)} - }) - out := &testData{} - r := NewRequest(s, &Operation{Name: "Operation"}, nil, out) - err := r.Send() - assert.NotNil(t, err) - if e, ok := err.(awserr.RequestFailure); ok { - assert.Equal(t, 401, e.StatusCode()) - } else { - assert.Fail(t, "Expected error to be a service failure") - } - assert.Equal(t, "SignatureDoesNotMatch", err.(awserr.Error).Code()) - assert.Equal(t, "Signature does not match.", err.(awserr.Error).Message()) - assert.Equal(t, 0, int(r.RetryCount)) -} - -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 := NewService(aws.NewConfig().WithMaxRetries(aws.DefaultRetries)) - 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) { - r.HTTPResponse = &reqs[reqNum] - reqNum++ - }) - r := NewRequest(s, &Operation{Name: "Operation"}, nil, nil) - err := r.Send() - assert.NotNil(t, err) - if e, ok := err.(awserr.RequestFailure); ok { - assert.Equal(t, 500, e.StatusCode()) - } else { - assert.Fail(t, "Expected error to be a service failure") - } - assert.Equal(t, "UnknownError", err.(awserr.Error).Code()) - assert.Equal(t, "An error occurred.", err.(awserr.Error).Message()) - assert.Equal(t, 3, int(r.RetryCount)) - - 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 - assert.True(t, min <= v && v <= max, - "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 := NewService(&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) { - credExpiredAfterRetry = r.Config.Credentials.IsExpired() - }) - - s.Handlers.Sign.Clear() - s.Handlers.Sign.PushBack(func(r *Request) { - r.Config.Credentials.Get() - }) - s.Handlers.Send.Clear() // mock sending - s.Handlers.Send.PushBack(func(r *Request) { - r.HTTPResponse = &reqs[reqNum] - reqNum++ - }) - out := &testData{} - r := NewRequest(s, &Operation{Name: "Operation"}, nil, out) - err := r.Send() - assert.Nil(t, err) - - assert.False(t, credExpiredBeforeRetry, "Expect valid creds before retry check") - assert.True(t, credExpiredAfterRetry, "Expect expired creds after retry check") - assert.False(t, s.Config.Credentials.IsExpired(), "Expect valid creds after cred expired recovery") - - assert.Equal(t, 1, int(r.RetryCount)) - assert.Equal(t, "valid", out.Data) -} diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/service/service.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/service/service.go index 900c51744..7205212e1 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/service/service.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/service/service.go @@ -3,40 +3,32 @@ package service import ( "fmt" "io/ioutil" - "math" - "math/rand" "net/http" "net/http/httputil" "regexp" "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/request" + "github.com/aws/aws-sdk-go/aws/service/serviceinfo" "github.com/aws/aws-sdk-go/internal/endpoints" ) // A Service implements the base service request and response handling // used by all services. type Service struct { - Config *aws.Config - Handlers Handlers - ServiceName string - APIVersion string - Endpoint string - SigningName string - SigningRegion string - JSONVersion string - TargetPrefix string - RetryRules func(*Request) time.Duration - ShouldRetry func(*Request) bool + serviceinfo.ServiceInfo + request.Retryer DefaultMaxRetries uint + Handlers request.Handlers } var schemeRE = regexp.MustCompile("^([^:]+)://") -// NewService will return a pointer to a new Server object initialized. -func NewService(config *aws.Config) *Service { - svc := &Service{Config: config} +// New will return a pointer to a new Server object initialized. +func New(config *aws.Config) *Service { + svc := &Service{ServiceInfo: serviceinfo.ServiceInfo{Config: config}} svc.Initialize() return svc } @@ -49,28 +41,29 @@ func (s *Service) Initialize() { if s.Config.HTTPClient == nil { s.Config.HTTPClient = http.DefaultClient } - - if s.RetryRules == nil { - s.RetryRules = retryRules - } - - if s.ShouldRetry == nil { - s.ShouldRetry = shouldRetry + if s.Config.SleepDelay == nil { + s.Config.SleepDelay = time.Sleep } + s.Retryer = DefaultRetryer{s} s.DefaultMaxRetries = 3 - s.Handlers.Validate.PushBack(ValidateEndpointHandler) - s.Handlers.Build.PushBack(UserAgentHandler) - s.Handlers.Sign.PushBack(BuildContentLength) - s.Handlers.Send.PushBack(SendHandler) - s.Handlers.AfterRetry.PushBack(AfterRetryHandler) - s.Handlers.ValidateResponse.PushBack(ValidateResponseHandler) + s.Handlers.Validate.PushBackNamed(corehandlers.ValidateEndpointHandler) + s.Handlers.Build.PushBackNamed(corehandlers.UserAgentHandler) + s.Handlers.Sign.PushBackNamed(corehandlers.BuildContentLengthHandler) + s.Handlers.Send.PushBackNamed(corehandlers.SendHandler) + s.Handlers.AfterRetry.PushBackNamed(corehandlers.AfterRetryHandler) + s.Handlers.ValidateResponse.PushBackNamed(corehandlers.ValidateResponseHandler) + if !aws.BoolValue(s.Config.DisableParamValidation) { + s.Handlers.Validate.PushBackNamed(corehandlers.ValidateParametersHandler) + } s.AddDebugHandlers() s.buildEndpoint() +} - if !aws.BoolValue(s.Config.DisableParamValidation) { - s.Handlers.Validate.PushBack(ValidateParameters) - } +// NewRequest returns a new Request pointer for the service API +// operation and parameters. +func (s *Service) NewRequest(operation *request.Operation, params interface{}, data interface{}) *request.Request { + return request.New(s.ServiceInfo, s.Handlers, s.Retryer, operation, params, data) } // buildEndpoint builds the endpoint values the service will use to make requests with. @@ -107,19 +100,19 @@ const logReqMsg = `DEBUG: Request %s/%s Details: %s -----------------------------------------------------` -func logRequest(r *Request) { - logBody := r.Config.LogLevel.Matches(aws.LogDebugWithHTTPBody) +func logRequest(r *request.Request) { + logBody := r.Service.Config.LogLevel.Matches(aws.LogDebugWithHTTPBody) dumpedBody, _ := httputil.DumpRequestOut(r.HTTPRequest, logBody) if logBody { // Reset the request body because dumpRequest will re-wrap the r.HTTPRequest's // Body as a NoOpCloser and will not be reset after read by the HTTP // client reader. - r.Body.Seek(r.bodyStart, 0) + r.Body.Seek(r.BodyStart, 0) r.HTTPRequest.Body = ioutil.NopCloser(r.Body) } - r.Config.Logger.Log(fmt.Sprintf(logReqMsg, r.ServiceName, r.Operation.Name, string(dumpedBody))) + r.Service.Config.Logger.Log(fmt.Sprintf(logReqMsg, r.Service.ServiceName, r.Operation.Name, string(dumpedBody))) } const logRespMsg = `DEBUG: Response %s/%s Details: @@ -127,78 +120,14 @@ const logRespMsg = `DEBUG: Response %s/%s Details: %s -----------------------------------------------------` -func logResponse(r *Request) { +func logResponse(r *request.Request) { var msg = "no reponse data" if r.HTTPResponse != nil { - logBody := r.Config.LogLevel.Matches(aws.LogDebugWithHTTPBody) + logBody := r.Service.Config.LogLevel.Matches(aws.LogDebugWithHTTPBody) dumpedBody, _ := httputil.DumpResponse(r.HTTPResponse, logBody) msg = string(dumpedBody) } else if r.Error != nil { msg = r.Error.Error() } - r.Config.Logger.Log(fmt.Sprintf(logRespMsg, r.ServiceName, r.Operation.Name, msg)) -} - -// MaxRetries returns the number of maximum returns the service will use to make -// an individual API request. -func (s *Service) MaxRetries() uint { - if aws.IntValue(s.Config.MaxRetries) < 0 { - return s.DefaultMaxRetries - } - return uint(aws.IntValue(s.Config.MaxRetries)) -} - -var seededRand = rand.New(rand.NewSource(time.Now().UnixNano())) - -// retryRules returns the delay duration before retrying this request again -func retryRules(r *Request) time.Duration { - - delay := int(math.Pow(2, float64(r.RetryCount))) * (seededRand.Intn(30) + 30) - return time.Duration(delay) * time.Millisecond -} - -// retryableCodes is a collection of service response codes which are retry-able -// without any further action. -var retryableCodes = map[string]struct{}{ - "RequestError": {}, - "ProvisionedThroughputExceededException": {}, - "Throttling": {}, - "ThrottlingException": {}, - "RequestLimitExceeded": {}, - "RequestThrottled": {}, -} - -// credsExpiredCodes is a collection of error codes which signify the credentials -// need to be refreshed. Expired tokens require refreshing of credentials, and -// resigning before the request can be retried. -var credsExpiredCodes = map[string]struct{}{ - "ExpiredToken": {}, - "ExpiredTokenException": {}, - "RequestExpired": {}, // EC2 Only -} - -func isCodeRetryable(code string) bool { - if _, ok := retryableCodes[code]; ok { - return true - } - - return isCodeExpiredCreds(code) -} - -func isCodeExpiredCreds(code string) bool { - _, ok := credsExpiredCodes[code] - return ok -} - -// shouldRetry returns if the request should be retried. -func shouldRetry(r *Request) bool { - if r.HTTPResponse.StatusCode >= 500 { - return true - } - if r.Error != nil { - if err, ok := r.Error.(awserr.Error); ok { - return isCodeRetryable(err.Code()) - } - } - return false + r.Service.Config.Logger.Log(fmt.Sprintf(logRespMsg, r.Service.ServiceName, r.Operation.Name, msg)) } diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/service/serviceinfo/service_info.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/service/serviceinfo/service_info.go new file mode 100644 index 000000000..a920e96a9 --- /dev/null +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/service/serviceinfo/service_info.go @@ -0,0 +1,15 @@ +package serviceinfo + +import "github.com/aws/aws-sdk-go/aws" + +// ServiceInfo wraps immutable data from the service.Service structure. +type ServiceInfo struct { + Config *aws.Config + ServiceName string + APIVersion string + Endpoint string + SigningName string + SigningRegion string + JSONVersion string + TargetPrefix string +} diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/types_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/types_test.go deleted file mode 100644 index a4ed20e7d..000000000 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/types_test.go +++ /dev/null @@ -1,56 +0,0 @@ -package aws - -import ( - "math/rand" - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestWriteAtBuffer(t *testing.T) { - b := &WriteAtBuffer{} - - n, err := b.WriteAt([]byte{1}, 0) - assert.NoError(t, err) - assert.Equal(t, 1, n) - - n, err = b.WriteAt([]byte{1, 1, 1}, 5) - assert.NoError(t, err) - assert.Equal(t, 3, n) - - n, err = b.WriteAt([]byte{2}, 1) - assert.NoError(t, err) - assert.Equal(t, 1, n) - - n, err = b.WriteAt([]byte{3}, 2) - assert.NoError(t, err) - assert.Equal(t, 1, n) - - assert.Equal(t, []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 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/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/version.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/version.go index f1439e0b9..f89f1e112 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/version.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/version.go @@ -5,4 +5,4 @@ package aws const SDKName = "aws-sdk-go" // SDKVersion is the version of this SDK -const SDKVersion = "0.9.0rc1" +const SDKVersion = "0.9.9" diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/endpoints/endpoints_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/endpoints/endpoints_test.go deleted file mode 100644 index 8af65879d..000000000 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/endpoints/endpoints_test.go +++ /dev/null @@ -1,28 +0,0 @@ -package endpoints - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestGlobalEndpoints(t *testing.T) { - region := "mock-region-1" - svcs := []string{"cloudfront", "iam", "importexport", "route53", "sts"} - - for _, name := range svcs { - ep, sr := EndpointForRegion(name, region) - assert.Equal(t, name+".amazonaws.com", ep) - assert.Equal(t, "us-east-1", sr) - } -} - -func TestServicesInCN(t *testing.T) { - region := "cn-north-1" - svcs := []string{"cloudfront", "iam", "importexport", "route53", "sts", "s3"} - - for _, name := range svcs { - ep, _ := EndpointForRegion(name, region) - assert.Equal(t, name+"."+region+".amazonaws.com.cn", ep) - } -} diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/ec2query/build.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/ec2query/build.go index d5a195ebc..fabe9b3c3 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/ec2query/build.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/ec2query/build.go @@ -7,12 +7,12 @@ import ( "net/url" "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/service" + "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/internal/protocol/query/queryutil" ) // Build builds a request for the EC2 protocol. -func Build(r *service.Request) { +func Build(r *request.Request) { body := url.Values{ "Action": {r.Operation.Name}, "Version": {r.Service.APIVersion}, diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/ec2query/build_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/ec2query/build_test.go deleted file mode 100644 index 073ea5461..000000000 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/ec2query/build_test.go +++ /dev/null @@ -1,862 +0,0 @@ -package ec2query_test - -import ( - "bytes" - "encoding/json" - "encoding/xml" - "io" - "io/ioutil" - "net/http" - "net/url" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/defaults" - "github.com/aws/aws-sdk-go/aws/service" - "github.com/aws/aws-sdk-go/internal/protocol/ec2query" - "github.com/aws/aws-sdk-go/internal/protocol/xml/xmlutil" - "github.com/aws/aws-sdk-go/internal/signer/v4" - "github.com/aws/aws-sdk-go/internal/util" - "github.com/stretchr/testify/assert" -) - -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 - -type InputService1ProtocolTest struct { - *service.Service -} - -// New returns a new InputService1ProtocolTest client. -func NewInputService1ProtocolTest(config *aws.Config) *InputService1ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "inputservice1protocoltest", - APIVersion: "2014-01-01", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(ec2query.Build) - service.Handlers.Unmarshal.PushBack(ec2query.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(ec2query.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(ec2query.UnmarshalError) - - return &InputService1ProtocolTest{service} -} - -// newRequest creates a new request for a InputService1ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService1ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opInputService1TestCaseOperation1 = "OperationName" - -// InputService1TestCaseOperation1Request generates a request for the InputService1TestCaseOperation1 operation. -func (c *InputService1ProtocolTest) InputService1TestCaseOperation1Request(input *InputService1TestShapeInputShape) (req *service.Request, output *InputService1TestShapeInputService1TestCaseOperation1Output) { - op := &service.Operation{ - Name: opInputService1TestCaseOperation1, - } - - if input == nil { - input = &InputService1TestShapeInputShape{} - } - - req = c.newRequest(op, input, output) - output = &InputService1TestShapeInputService1TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService1ProtocolTest) InputService1TestCaseOperation1(input *InputService1TestShapeInputShape) (*InputService1TestShapeInputService1TestCaseOperation1Output, error) { - req, out := c.InputService1TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type InputService1TestShapeInputService1TestCaseOperation1Output struct { - metadataInputService1TestShapeInputService1TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataInputService1TestShapeInputService1TestCaseOperation1Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService1TestShapeInputShape struct { - Bar *string `type:"string"` - - Foo *string `type:"string"` - - metadataInputService1TestShapeInputShape `json:"-" xml:"-"` -} - -type metadataInputService1TestShapeInputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService2ProtocolTest struct { - *service.Service -} - -// New returns a new InputService2ProtocolTest client. -func NewInputService2ProtocolTest(config *aws.Config) *InputService2ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "inputservice2protocoltest", - APIVersion: "2014-01-01", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(ec2query.Build) - service.Handlers.Unmarshal.PushBack(ec2query.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(ec2query.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(ec2query.UnmarshalError) - - return &InputService2ProtocolTest{service} -} - -// newRequest creates a new request for a InputService2ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService2ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opInputService2TestCaseOperation1 = "OperationName" - -// InputService2TestCaseOperation1Request generates a request for the InputService2TestCaseOperation1 operation. -func (c *InputService2ProtocolTest) InputService2TestCaseOperation1Request(input *InputService2TestShapeInputShape) (req *service.Request, output *InputService2TestShapeInputService2TestCaseOperation1Output) { - op := &service.Operation{ - Name: opInputService2TestCaseOperation1, - } - - if input == nil { - input = &InputService2TestShapeInputShape{} - } - - req = c.newRequest(op, input, output) - output = &InputService2TestShapeInputService2TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService2ProtocolTest) InputService2TestCaseOperation1(input *InputService2TestShapeInputShape) (*InputService2TestShapeInputService2TestCaseOperation1Output, error) { - req, out := c.InputService2TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type InputService2TestShapeInputService2TestCaseOperation1Output struct { - metadataInputService2TestShapeInputService2TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataInputService2TestShapeInputService2TestCaseOperation1Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService2TestShapeInputShape struct { - Bar *string `locationName:"barLocationName" type:"string"` - - Foo *string `type:"string"` - - Yuck *string `locationName:"yuckLocationName" queryName:"yuckQueryName" type:"string"` - - metadataInputService2TestShapeInputShape `json:"-" xml:"-"` -} - -type metadataInputService2TestShapeInputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService3ProtocolTest struct { - *service.Service -} - -// New returns a new InputService3ProtocolTest client. -func NewInputService3ProtocolTest(config *aws.Config) *InputService3ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "inputservice3protocoltest", - APIVersion: "2014-01-01", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(ec2query.Build) - service.Handlers.Unmarshal.PushBack(ec2query.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(ec2query.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(ec2query.UnmarshalError) - - return &InputService3ProtocolTest{service} -} - -// newRequest creates a new request for a InputService3ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService3ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opInputService3TestCaseOperation1 = "OperationName" - -// InputService3TestCaseOperation1Request generates a request for the InputService3TestCaseOperation1 operation. -func (c *InputService3ProtocolTest) InputService3TestCaseOperation1Request(input *InputService3TestShapeInputShape) (req *service.Request, output *InputService3TestShapeInputService3TestCaseOperation1Output) { - op := &service.Operation{ - Name: opInputService3TestCaseOperation1, - } - - if input == nil { - input = &InputService3TestShapeInputShape{} - } - - req = c.newRequest(op, input, output) - output = &InputService3TestShapeInputService3TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService3ProtocolTest) InputService3TestCaseOperation1(input *InputService3TestShapeInputShape) (*InputService3TestShapeInputService3TestCaseOperation1Output, error) { - req, out := c.InputService3TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type InputService3TestShapeInputService3TestCaseOperation1Output struct { - metadataInputService3TestShapeInputService3TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataInputService3TestShapeInputService3TestCaseOperation1Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService3TestShapeInputShape struct { - StructArg *InputService3TestShapeStructType `locationName:"Struct" type:"structure"` - - metadataInputService3TestShapeInputShape `json:"-" xml:"-"` -} - -type metadataInputService3TestShapeInputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService3TestShapeStructType struct { - ScalarArg *string `locationName:"Scalar" type:"string"` - - metadataInputService3TestShapeStructType `json:"-" xml:"-"` -} - -type metadataInputService3TestShapeStructType struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService4ProtocolTest struct { - *service.Service -} - -// New returns a new InputService4ProtocolTest client. -func NewInputService4ProtocolTest(config *aws.Config) *InputService4ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "inputservice4protocoltest", - APIVersion: "2014-01-01", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(ec2query.Build) - service.Handlers.Unmarshal.PushBack(ec2query.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(ec2query.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(ec2query.UnmarshalError) - - return &InputService4ProtocolTest{service} -} - -// newRequest creates a new request for a InputService4ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService4ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opInputService4TestCaseOperation1 = "OperationName" - -// InputService4TestCaseOperation1Request generates a request for the InputService4TestCaseOperation1 operation. -func (c *InputService4ProtocolTest) InputService4TestCaseOperation1Request(input *InputService4TestShapeInputShape) (req *service.Request, output *InputService4TestShapeInputService4TestCaseOperation1Output) { - op := &service.Operation{ - Name: opInputService4TestCaseOperation1, - } - - if input == nil { - input = &InputService4TestShapeInputShape{} - } - - req = c.newRequest(op, input, output) - output = &InputService4TestShapeInputService4TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService4ProtocolTest) InputService4TestCaseOperation1(input *InputService4TestShapeInputShape) (*InputService4TestShapeInputService4TestCaseOperation1Output, error) { - req, out := c.InputService4TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type InputService4TestShapeInputService4TestCaseOperation1Output struct { - metadataInputService4TestShapeInputService4TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataInputService4TestShapeInputService4TestCaseOperation1Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService4TestShapeInputShape struct { - ListArg []*string `type:"list"` - - metadataInputService4TestShapeInputShape `json:"-" xml:"-"` -} - -type metadataInputService4TestShapeInputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService5ProtocolTest struct { - *service.Service -} - -// New returns a new InputService5ProtocolTest client. -func NewInputService5ProtocolTest(config *aws.Config) *InputService5ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "inputservice5protocoltest", - APIVersion: "2014-01-01", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(ec2query.Build) - service.Handlers.Unmarshal.PushBack(ec2query.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(ec2query.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(ec2query.UnmarshalError) - - return &InputService5ProtocolTest{service} -} - -// newRequest creates a new request for a InputService5ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService5ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opInputService5TestCaseOperation1 = "OperationName" - -// InputService5TestCaseOperation1Request generates a request for the InputService5TestCaseOperation1 operation. -func (c *InputService5ProtocolTest) InputService5TestCaseOperation1Request(input *InputService5TestShapeInputShape) (req *service.Request, output *InputService5TestShapeInputService5TestCaseOperation1Output) { - op := &service.Operation{ - Name: opInputService5TestCaseOperation1, - } - - if input == nil { - input = &InputService5TestShapeInputShape{} - } - - req = c.newRequest(op, input, output) - output = &InputService5TestShapeInputService5TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService5ProtocolTest) InputService5TestCaseOperation1(input *InputService5TestShapeInputShape) (*InputService5TestShapeInputService5TestCaseOperation1Output, error) { - req, out := c.InputService5TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type InputService5TestShapeInputService5TestCaseOperation1Output struct { - metadataInputService5TestShapeInputService5TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataInputService5TestShapeInputService5TestCaseOperation1Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService5TestShapeInputShape struct { - ListArg []*string `locationName:"ListMemberName" locationNameList:"item" type:"list"` - - metadataInputService5TestShapeInputShape `json:"-" xml:"-"` -} - -type metadataInputService5TestShapeInputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService6ProtocolTest struct { - *service.Service -} - -// New returns a new InputService6ProtocolTest client. -func NewInputService6ProtocolTest(config *aws.Config) *InputService6ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "inputservice6protocoltest", - APIVersion: "2014-01-01", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(ec2query.Build) - service.Handlers.Unmarshal.PushBack(ec2query.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(ec2query.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(ec2query.UnmarshalError) - - return &InputService6ProtocolTest{service} -} - -// newRequest creates a new request for a InputService6ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService6ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opInputService6TestCaseOperation1 = "OperationName" - -// InputService6TestCaseOperation1Request generates a request for the InputService6TestCaseOperation1 operation. -func (c *InputService6ProtocolTest) InputService6TestCaseOperation1Request(input *InputService6TestShapeInputShape) (req *service.Request, output *InputService6TestShapeInputService6TestCaseOperation1Output) { - op := &service.Operation{ - Name: opInputService6TestCaseOperation1, - } - - if input == nil { - input = &InputService6TestShapeInputShape{} - } - - req = c.newRequest(op, input, output) - output = &InputService6TestShapeInputService6TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService6ProtocolTest) InputService6TestCaseOperation1(input *InputService6TestShapeInputShape) (*InputService6TestShapeInputService6TestCaseOperation1Output, error) { - req, out := c.InputService6TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type InputService6TestShapeInputService6TestCaseOperation1Output struct { - metadataInputService6TestShapeInputService6TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataInputService6TestShapeInputService6TestCaseOperation1Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService6TestShapeInputShape struct { - ListArg []*string `locationName:"ListMemberName" queryName:"ListQueryName" locationNameList:"item" type:"list"` - - metadataInputService6TestShapeInputShape `json:"-" xml:"-"` -} - -type metadataInputService6TestShapeInputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService7ProtocolTest struct { - *service.Service -} - -// New returns a new InputService7ProtocolTest client. -func NewInputService7ProtocolTest(config *aws.Config) *InputService7ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "inputservice7protocoltest", - APIVersion: "2014-01-01", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(ec2query.Build) - service.Handlers.Unmarshal.PushBack(ec2query.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(ec2query.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(ec2query.UnmarshalError) - - return &InputService7ProtocolTest{service} -} - -// newRequest creates a new request for a InputService7ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService7ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opInputService7TestCaseOperation1 = "OperationName" - -// InputService7TestCaseOperation1Request generates a request for the InputService7TestCaseOperation1 operation. -func (c *InputService7ProtocolTest) InputService7TestCaseOperation1Request(input *InputService7TestShapeInputShape) (req *service.Request, output *InputService7TestShapeInputService7TestCaseOperation1Output) { - op := &service.Operation{ - Name: opInputService7TestCaseOperation1, - } - - if input == nil { - input = &InputService7TestShapeInputShape{} - } - - req = c.newRequest(op, input, output) - output = &InputService7TestShapeInputService7TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService7ProtocolTest) InputService7TestCaseOperation1(input *InputService7TestShapeInputShape) (*InputService7TestShapeInputService7TestCaseOperation1Output, error) { - req, out := c.InputService7TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type InputService7TestShapeInputService7TestCaseOperation1Output struct { - metadataInputService7TestShapeInputService7TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataInputService7TestShapeInputService7TestCaseOperation1Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService7TestShapeInputShape struct { - BlobArg []byte `type:"blob"` - - metadataInputService7TestShapeInputShape `json:"-" xml:"-"` -} - -type metadataInputService7TestShapeInputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService8ProtocolTest struct { - *service.Service -} - -// New returns a new InputService8ProtocolTest client. -func NewInputService8ProtocolTest(config *aws.Config) *InputService8ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "inputservice8protocoltest", - APIVersion: "2014-01-01", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(ec2query.Build) - service.Handlers.Unmarshal.PushBack(ec2query.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(ec2query.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(ec2query.UnmarshalError) - - return &InputService8ProtocolTest{service} -} - -// newRequest creates a new request for a InputService8ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService8ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opInputService8TestCaseOperation1 = "OperationName" - -// InputService8TestCaseOperation1Request generates a request for the InputService8TestCaseOperation1 operation. -func (c *InputService8ProtocolTest) InputService8TestCaseOperation1Request(input *InputService8TestShapeInputShape) (req *service.Request, output *InputService8TestShapeInputService8TestCaseOperation1Output) { - op := &service.Operation{ - Name: opInputService8TestCaseOperation1, - } - - if input == nil { - input = &InputService8TestShapeInputShape{} - } - - req = c.newRequest(op, input, output) - output = &InputService8TestShapeInputService8TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService8ProtocolTest) InputService8TestCaseOperation1(input *InputService8TestShapeInputShape) (*InputService8TestShapeInputService8TestCaseOperation1Output, error) { - req, out := c.InputService8TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type InputService8TestShapeInputService8TestCaseOperation1Output struct { - metadataInputService8TestShapeInputService8TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataInputService8TestShapeInputService8TestCaseOperation1Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService8TestShapeInputShape struct { - TimeArg *time.Time `type:"timestamp" timestampFormat:"iso8601"` - - metadataInputService8TestShapeInputShape `json:"-" xml:"-"` -} - -type metadataInputService8TestShapeInputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -// -// Tests begin here -// - -func TestInputService1ProtocolTestScalarMembersCase1(t *testing.T) { - svc := NewInputService1ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService1TestShapeInputShape{ - Bar: aws.String("val2"), - Foo: aws.String("val1"), - } - req, _ := svc.InputService1TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - ec2query.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body, _ := ioutil.ReadAll(r.Body) - assert.Equal(t, util.Trim(`Action=OperationName&Bar=val2&Foo=val1&Version=2014-01-01`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService2ProtocolTestStructureWithLocationNameAndQueryNameAppliedToMembersCase1(t *testing.T) { - svc := NewInputService2ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService2TestShapeInputShape{ - Bar: aws.String("val2"), - Foo: aws.String("val1"), - Yuck: aws.String("val3"), - } - req, _ := svc.InputService2TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - ec2query.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body, _ := ioutil.ReadAll(r.Body) - assert.Equal(t, util.Trim(`Action=OperationName&BarLocationName=val2&Foo=val1&Version=2014-01-01&yuckQueryName=val3`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService3ProtocolTestNestedStructureMembersCase1(t *testing.T) { - svc := NewInputService3ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService3TestShapeInputShape{ - StructArg: &InputService3TestShapeStructType{ - ScalarArg: aws.String("foo"), - }, - } - req, _ := svc.InputService3TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - ec2query.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body, _ := ioutil.ReadAll(r.Body) - assert.Equal(t, util.Trim(`Action=OperationName&Struct.Scalar=foo&Version=2014-01-01`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService4ProtocolTestListTypesCase1(t *testing.T) { - svc := NewInputService4ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService4TestShapeInputShape{ - ListArg: []*string{ - aws.String("foo"), - aws.String("bar"), - aws.String("baz"), - }, - } - req, _ := svc.InputService4TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - ec2query.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body, _ := ioutil.ReadAll(r.Body) - assert.Equal(t, util.Trim(`Action=OperationName&ListArg.1=foo&ListArg.2=bar&ListArg.3=baz&Version=2014-01-01`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService5ProtocolTestListWithLocationNameAppliedToMemberCase1(t *testing.T) { - svc := NewInputService5ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService5TestShapeInputShape{ - ListArg: []*string{ - aws.String("a"), - aws.String("b"), - aws.String("c"), - }, - } - req, _ := svc.InputService5TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - ec2query.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body, _ := ioutil.ReadAll(r.Body) - assert.Equal(t, util.Trim(`Action=OperationName&ListMemberName.1=a&ListMemberName.2=b&ListMemberName.3=c&Version=2014-01-01`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService6ProtocolTestListWithLocationNameAndQueryNameCase1(t *testing.T) { - svc := NewInputService6ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService6TestShapeInputShape{ - ListArg: []*string{ - aws.String("a"), - aws.String("b"), - aws.String("c"), - }, - } - req, _ := svc.InputService6TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - ec2query.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body, _ := ioutil.ReadAll(r.Body) - assert.Equal(t, util.Trim(`Action=OperationName&ListQueryName.1=a&ListQueryName.2=b&ListQueryName.3=c&Version=2014-01-01`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService7ProtocolTestBase64EncodedBlobsCase1(t *testing.T) { - svc := NewInputService7ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService7TestShapeInputShape{ - BlobArg: []byte("foo"), - } - req, _ := svc.InputService7TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - ec2query.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body, _ := ioutil.ReadAll(r.Body) - assert.Equal(t, util.Trim(`Action=OperationName&BlobArg=Zm9v&Version=2014-01-01`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService8ProtocolTestTimestampValuesCase1(t *testing.T) { - svc := NewInputService8ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService8TestShapeInputShape{ - TimeArg: aws.Time(time.Unix(1422172800, 0)), - } - req, _ := svc.InputService8TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - ec2query.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body, _ := ioutil.ReadAll(r.Body) - assert.Equal(t, util.Trim(`Action=OperationName&TimeArg=2015-01-25T08%3A00%3A00Z&Version=2014-01-01`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/", r.URL.String()) - - // assert headers - -} diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/ec2query/unmarshal.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/ec2query/unmarshal.go index 4b17f0889..bb0f01588 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/ec2query/unmarshal.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/ec2query/unmarshal.go @@ -7,12 +7,12 @@ import ( "io" "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/service" + "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/internal/protocol/xml/xmlutil" ) // Unmarshal unmarshals a response body for the EC2 protocol. -func Unmarshal(r *service.Request) { +func Unmarshal(r *request.Request) { defer r.HTTPResponse.Body.Close() if r.DataFilled() { decoder := xml.NewDecoder(r.HTTPResponse.Body) @@ -25,7 +25,7 @@ func Unmarshal(r *service.Request) { } // UnmarshalMeta unmarshals response headers for the EC2 protocol. -func UnmarshalMeta(r *service.Request) { +func UnmarshalMeta(r *request.Request) { // TODO implement unmarshaling of request IDs } @@ -37,7 +37,7 @@ type xmlErrorResponse struct { } // UnmarshalError unmarshals a response error for the EC2 protocol. -func UnmarshalError(r *service.Request) { +func UnmarshalError(r *request.Request) { defer r.HTTPResponse.Body.Close() resp := &xmlErrorResponse{} diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/ec2query/unmarshal_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/ec2query/unmarshal_test.go deleted file mode 100644 index cc54480b4..000000000 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/ec2query/unmarshal_test.go +++ /dev/null @@ -1,818 +0,0 @@ -package ec2query_test - -import ( - "bytes" - "encoding/json" - "encoding/xml" - "io" - "io/ioutil" - "net/http" - "net/url" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/defaults" - "github.com/aws/aws-sdk-go/aws/service" - "github.com/aws/aws-sdk-go/internal/protocol/ec2query" - "github.com/aws/aws-sdk-go/internal/protocol/xml/xmlutil" - "github.com/aws/aws-sdk-go/internal/signer/v4" - "github.com/aws/aws-sdk-go/internal/util" - "github.com/stretchr/testify/assert" -) - -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 - -type OutputService1ProtocolTest struct { - *service.Service -} - -// New returns a new OutputService1ProtocolTest client. -func NewOutputService1ProtocolTest(config *aws.Config) *OutputService1ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "outputservice1protocoltest", - APIVersion: "", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(ec2query.Build) - service.Handlers.Unmarshal.PushBack(ec2query.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(ec2query.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(ec2query.UnmarshalError) - - return &OutputService1ProtocolTest{service} -} - -// newRequest creates a new request for a OutputService1ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService1ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opOutputService1TestCaseOperation1 = "OperationName" - -// OutputService1TestCaseOperation1Request generates a request for the OutputService1TestCaseOperation1 operation. -func (c *OutputService1ProtocolTest) OutputService1TestCaseOperation1Request(input *OutputService1TestShapeOutputService1TestCaseOperation1Input) (req *service.Request, output *OutputService1TestShapeOutputShape) { - op := &service.Operation{ - Name: opOutputService1TestCaseOperation1, - } - - if input == nil { - input = &OutputService1TestShapeOutputService1TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &OutputService1TestShapeOutputShape{} - req.Data = output - return -} - -func (c *OutputService1ProtocolTest) OutputService1TestCaseOperation1(input *OutputService1TestShapeOutputService1TestCaseOperation1Input) (*OutputService1TestShapeOutputShape, error) { - req, out := c.OutputService1TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type OutputService1TestShapeOutputService1TestCaseOperation1Input struct { - metadataOutputService1TestShapeOutputService1TestCaseOperation1Input `json:"-" xml:"-"` -} - -type metadataOutputService1TestShapeOutputService1TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService1TestShapeOutputShape struct { - 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"` - - metadataOutputService1TestShapeOutputShape `json:"-" xml:"-"` -} - -type metadataOutputService1TestShapeOutputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService2ProtocolTest struct { - *service.Service -} - -// New returns a new OutputService2ProtocolTest client. -func NewOutputService2ProtocolTest(config *aws.Config) *OutputService2ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "outputservice2protocoltest", - APIVersion: "", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(ec2query.Build) - service.Handlers.Unmarshal.PushBack(ec2query.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(ec2query.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(ec2query.UnmarshalError) - - return &OutputService2ProtocolTest{service} -} - -// newRequest creates a new request for a OutputService2ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService2ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opOutputService2TestCaseOperation1 = "OperationName" - -// OutputService2TestCaseOperation1Request generates a request for the OutputService2TestCaseOperation1 operation. -func (c *OutputService2ProtocolTest) OutputService2TestCaseOperation1Request(input *OutputService2TestShapeOutputService2TestCaseOperation1Input) (req *service.Request, output *OutputService2TestShapeOutputShape) { - op := &service.Operation{ - Name: opOutputService2TestCaseOperation1, - } - - if input == nil { - input = &OutputService2TestShapeOutputService2TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &OutputService2TestShapeOutputShape{} - req.Data = output - return -} - -func (c *OutputService2ProtocolTest) OutputService2TestCaseOperation1(input *OutputService2TestShapeOutputService2TestCaseOperation1Input) (*OutputService2TestShapeOutputShape, error) { - req, out := c.OutputService2TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type OutputService2TestShapeOutputService2TestCaseOperation1Input struct { - metadataOutputService2TestShapeOutputService2TestCaseOperation1Input `json:"-" xml:"-"` -} - -type metadataOutputService2TestShapeOutputService2TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService2TestShapeOutputShape struct { - Blob []byte `type:"blob"` - - metadataOutputService2TestShapeOutputShape `json:"-" xml:"-"` -} - -type metadataOutputService2TestShapeOutputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService3ProtocolTest struct { - *service.Service -} - -// New returns a new OutputService3ProtocolTest client. -func NewOutputService3ProtocolTest(config *aws.Config) *OutputService3ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "outputservice3protocoltest", - APIVersion: "", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(ec2query.Build) - service.Handlers.Unmarshal.PushBack(ec2query.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(ec2query.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(ec2query.UnmarshalError) - - return &OutputService3ProtocolTest{service} -} - -// newRequest creates a new request for a OutputService3ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService3ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opOutputService3TestCaseOperation1 = "OperationName" - -// OutputService3TestCaseOperation1Request generates a request for the OutputService3TestCaseOperation1 operation. -func (c *OutputService3ProtocolTest) OutputService3TestCaseOperation1Request(input *OutputService3TestShapeOutputService3TestCaseOperation1Input) (req *service.Request, output *OutputService3TestShapeOutputShape) { - op := &service.Operation{ - Name: opOutputService3TestCaseOperation1, - } - - if input == nil { - input = &OutputService3TestShapeOutputService3TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &OutputService3TestShapeOutputShape{} - req.Data = output - return -} - -func (c *OutputService3ProtocolTest) OutputService3TestCaseOperation1(input *OutputService3TestShapeOutputService3TestCaseOperation1Input) (*OutputService3TestShapeOutputShape, error) { - req, out := c.OutputService3TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type OutputService3TestShapeOutputService3TestCaseOperation1Input struct { - metadataOutputService3TestShapeOutputService3TestCaseOperation1Input `json:"-" xml:"-"` -} - -type metadataOutputService3TestShapeOutputService3TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService3TestShapeOutputShape struct { - ListMember []*string `type:"list"` - - metadataOutputService3TestShapeOutputShape `json:"-" xml:"-"` -} - -type metadataOutputService3TestShapeOutputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService4ProtocolTest struct { - *service.Service -} - -// New returns a new OutputService4ProtocolTest client. -func NewOutputService4ProtocolTest(config *aws.Config) *OutputService4ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "outputservice4protocoltest", - APIVersion: "", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(ec2query.Build) - service.Handlers.Unmarshal.PushBack(ec2query.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(ec2query.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(ec2query.UnmarshalError) - - return &OutputService4ProtocolTest{service} -} - -// newRequest creates a new request for a OutputService4ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService4ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opOutputService4TestCaseOperation1 = "OperationName" - -// OutputService4TestCaseOperation1Request generates a request for the OutputService4TestCaseOperation1 operation. -func (c *OutputService4ProtocolTest) OutputService4TestCaseOperation1Request(input *OutputService4TestShapeOutputService4TestCaseOperation1Input) (req *service.Request, output *OutputService4TestShapeOutputShape) { - op := &service.Operation{ - Name: opOutputService4TestCaseOperation1, - } - - if input == nil { - input = &OutputService4TestShapeOutputService4TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &OutputService4TestShapeOutputShape{} - req.Data = output - return -} - -func (c *OutputService4ProtocolTest) OutputService4TestCaseOperation1(input *OutputService4TestShapeOutputService4TestCaseOperation1Input) (*OutputService4TestShapeOutputShape, error) { - req, out := c.OutputService4TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type OutputService4TestShapeOutputService4TestCaseOperation1Input struct { - metadataOutputService4TestShapeOutputService4TestCaseOperation1Input `json:"-" xml:"-"` -} - -type metadataOutputService4TestShapeOutputService4TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService4TestShapeOutputShape struct { - ListMember []*string `locationNameList:"item" type:"list"` - - metadataOutputService4TestShapeOutputShape `json:"-" xml:"-"` -} - -type metadataOutputService4TestShapeOutputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService5ProtocolTest struct { - *service.Service -} - -// New returns a new OutputService5ProtocolTest client. -func NewOutputService5ProtocolTest(config *aws.Config) *OutputService5ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "outputservice5protocoltest", - APIVersion: "", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(ec2query.Build) - service.Handlers.Unmarshal.PushBack(ec2query.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(ec2query.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(ec2query.UnmarshalError) - - return &OutputService5ProtocolTest{service} -} - -// newRequest creates a new request for a OutputService5ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService5ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opOutputService5TestCaseOperation1 = "OperationName" - -// OutputService5TestCaseOperation1Request generates a request for the OutputService5TestCaseOperation1 operation. -func (c *OutputService5ProtocolTest) OutputService5TestCaseOperation1Request(input *OutputService5TestShapeOutputService5TestCaseOperation1Input) (req *service.Request, output *OutputService5TestShapeOutputShape) { - op := &service.Operation{ - Name: opOutputService5TestCaseOperation1, - } - - if input == nil { - input = &OutputService5TestShapeOutputService5TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &OutputService5TestShapeOutputShape{} - req.Data = output - return -} - -func (c *OutputService5ProtocolTest) OutputService5TestCaseOperation1(input *OutputService5TestShapeOutputService5TestCaseOperation1Input) (*OutputService5TestShapeOutputShape, error) { - req, out := c.OutputService5TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type OutputService5TestShapeOutputService5TestCaseOperation1Input struct { - metadataOutputService5TestShapeOutputService5TestCaseOperation1Input `json:"-" xml:"-"` -} - -type metadataOutputService5TestShapeOutputService5TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService5TestShapeOutputShape struct { - ListMember []*string `type:"list" flattened:"true"` - - metadataOutputService5TestShapeOutputShape `json:"-" xml:"-"` -} - -type metadataOutputService5TestShapeOutputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService6ProtocolTest struct { - *service.Service -} - -// New returns a new OutputService6ProtocolTest client. -func NewOutputService6ProtocolTest(config *aws.Config) *OutputService6ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "outputservice6protocoltest", - APIVersion: "", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(ec2query.Build) - service.Handlers.Unmarshal.PushBack(ec2query.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(ec2query.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(ec2query.UnmarshalError) - - return &OutputService6ProtocolTest{service} -} - -// newRequest creates a new request for a OutputService6ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService6ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opOutputService6TestCaseOperation1 = "OperationName" - -// OutputService6TestCaseOperation1Request generates a request for the OutputService6TestCaseOperation1 operation. -func (c *OutputService6ProtocolTest) OutputService6TestCaseOperation1Request(input *OutputService6TestShapeOutputService6TestCaseOperation1Input) (req *service.Request, output *OutputService6TestShapeOutputShape) { - op := &service.Operation{ - Name: opOutputService6TestCaseOperation1, - } - - if input == nil { - input = &OutputService6TestShapeOutputService6TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &OutputService6TestShapeOutputShape{} - req.Data = output - return -} - -func (c *OutputService6ProtocolTest) OutputService6TestCaseOperation1(input *OutputService6TestShapeOutputService6TestCaseOperation1Input) (*OutputService6TestShapeOutputShape, error) { - req, out := c.OutputService6TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type OutputService6TestShapeOutputService6TestCaseOperation1Input struct { - metadataOutputService6TestShapeOutputService6TestCaseOperation1Input `json:"-" xml:"-"` -} - -type metadataOutputService6TestShapeOutputService6TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService6TestShapeOutputShape struct { - Map map[string]*OutputService6TestShapeStructureType `type:"map"` - - metadataOutputService6TestShapeOutputShape `json:"-" xml:"-"` -} - -type metadataOutputService6TestShapeOutputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService6TestShapeStructureType struct { - Foo *string `locationName:"foo" type:"string"` - - metadataOutputService6TestShapeStructureType `json:"-" xml:"-"` -} - -type metadataOutputService6TestShapeStructureType struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService7ProtocolTest struct { - *service.Service -} - -// New returns a new OutputService7ProtocolTest client. -func NewOutputService7ProtocolTest(config *aws.Config) *OutputService7ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "outputservice7protocoltest", - APIVersion: "", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(ec2query.Build) - service.Handlers.Unmarshal.PushBack(ec2query.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(ec2query.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(ec2query.UnmarshalError) - - return &OutputService7ProtocolTest{service} -} - -// newRequest creates a new request for a OutputService7ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService7ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opOutputService7TestCaseOperation1 = "OperationName" - -// OutputService7TestCaseOperation1Request generates a request for the OutputService7TestCaseOperation1 operation. -func (c *OutputService7ProtocolTest) OutputService7TestCaseOperation1Request(input *OutputService7TestShapeOutputService7TestCaseOperation1Input) (req *service.Request, output *OutputService7TestShapeOutputShape) { - op := &service.Operation{ - Name: opOutputService7TestCaseOperation1, - } - - if input == nil { - input = &OutputService7TestShapeOutputService7TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &OutputService7TestShapeOutputShape{} - req.Data = output - return -} - -func (c *OutputService7ProtocolTest) OutputService7TestCaseOperation1(input *OutputService7TestShapeOutputService7TestCaseOperation1Input) (*OutputService7TestShapeOutputShape, error) { - req, out := c.OutputService7TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type OutputService7TestShapeOutputService7TestCaseOperation1Input struct { - metadataOutputService7TestShapeOutputService7TestCaseOperation1Input `json:"-" xml:"-"` -} - -type metadataOutputService7TestShapeOutputService7TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService7TestShapeOutputShape struct { - Map map[string]*string `type:"map" flattened:"true"` - - metadataOutputService7TestShapeOutputShape `json:"-" xml:"-"` -} - -type metadataOutputService7TestShapeOutputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService8ProtocolTest struct { - *service.Service -} - -// New returns a new OutputService8ProtocolTest client. -func NewOutputService8ProtocolTest(config *aws.Config) *OutputService8ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "outputservice8protocoltest", - APIVersion: "", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(ec2query.Build) - service.Handlers.Unmarshal.PushBack(ec2query.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(ec2query.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(ec2query.UnmarshalError) - - return &OutputService8ProtocolTest{service} -} - -// newRequest creates a new request for a OutputService8ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService8ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opOutputService8TestCaseOperation1 = "OperationName" - -// OutputService8TestCaseOperation1Request generates a request for the OutputService8TestCaseOperation1 operation. -func (c *OutputService8ProtocolTest) OutputService8TestCaseOperation1Request(input *OutputService8TestShapeOutputService8TestCaseOperation1Input) (req *service.Request, output *OutputService8TestShapeOutputShape) { - op := &service.Operation{ - Name: opOutputService8TestCaseOperation1, - } - - if input == nil { - input = &OutputService8TestShapeOutputService8TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &OutputService8TestShapeOutputShape{} - req.Data = output - return -} - -func (c *OutputService8ProtocolTest) OutputService8TestCaseOperation1(input *OutputService8TestShapeOutputService8TestCaseOperation1Input) (*OutputService8TestShapeOutputShape, error) { - req, out := c.OutputService8TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type OutputService8TestShapeOutputService8TestCaseOperation1Input struct { - metadataOutputService8TestShapeOutputService8TestCaseOperation1Input `json:"-" xml:"-"` -} - -type metadataOutputService8TestShapeOutputService8TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService8TestShapeOutputShape struct { - Map map[string]*string `locationNameKey:"foo" locationNameValue:"bar" type:"map" flattened:"true"` - - metadataOutputService8TestShapeOutputShape `json:"-" xml:"-"` -} - -type metadataOutputService8TestShapeOutputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -// -// Tests begin here -// - -func TestOutputService1ProtocolTestScalarMembersCase1(t *testing.T) { - svc := NewOutputService1ProtocolTest(nil) - - 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) - assert.NoError(t, req.Error) - - // assert response - assert.NotNil(t, out) // ensure out variable is used - assert.Equal(t, "a", *out.Char) - assert.Equal(t, 1.3, *out.Double) - assert.Equal(t, false, *out.FalseBool) - assert.Equal(t, 1.2, *out.Float) - assert.Equal(t, int64(200), *out.Long) - assert.Equal(t, int64(123), *out.Num) - assert.Equal(t, "myname", *out.Str) - assert.Equal(t, true, *out.TrueBool) - -} - -func TestOutputService2ProtocolTestBlobCase1(t *testing.T) { - svc := NewOutputService2ProtocolTest(nil) - - 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) - assert.NoError(t, req.Error) - - // assert response - assert.NotNil(t, out) // ensure out variable is used - assert.Equal(t, "value", string(out.Blob)) - -} - -func TestOutputService3ProtocolTestListsCase1(t *testing.T) { - svc := NewOutputService3ProtocolTest(nil) - - 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) - assert.NoError(t, req.Error) - - // assert response - assert.NotNil(t, out) // ensure out variable is used - assert.Equal(t, "abc", *out.ListMember[0]) - assert.Equal(t, "123", *out.ListMember[1]) - -} - -func TestOutputService4ProtocolTestListWithCustomMemberNameCase1(t *testing.T) { - svc := NewOutputService4ProtocolTest(nil) - - 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) - assert.NoError(t, req.Error) - - // assert response - assert.NotNil(t, out) // ensure out variable is used - assert.Equal(t, "abc", *out.ListMember[0]) - assert.Equal(t, "123", *out.ListMember[1]) - -} - -func TestOutputService5ProtocolTestFlattenedListCase1(t *testing.T) { - svc := NewOutputService5ProtocolTest(nil) - - 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) - assert.NoError(t, req.Error) - - // assert response - assert.NotNil(t, out) // ensure out variable is used - assert.Equal(t, "abc", *out.ListMember[0]) - assert.Equal(t, "123", *out.ListMember[1]) - -} - -func TestOutputService6ProtocolTestNormalMapCase1(t *testing.T) { - svc := NewOutputService6ProtocolTest(nil) - - 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) - assert.NoError(t, req.Error) - - // assert response - assert.NotNil(t, out) // ensure out variable is used - assert.Equal(t, "bam", *out.Map["baz"].Foo) - assert.Equal(t, "bar", *out.Map["qux"].Foo) - -} - -func TestOutputService7ProtocolTestFlattenedMapCase1(t *testing.T) { - svc := NewOutputService7ProtocolTest(nil) - - 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) - assert.NoError(t, req.Error) - - // assert response - assert.NotNil(t, out) // ensure out variable is used - assert.Equal(t, "bam", *out.Map["baz"]) - assert.Equal(t, "bar", *out.Map["qux"]) - -} - -func TestOutputService8ProtocolTestNamedMapCase1(t *testing.T) { - svc := NewOutputService8ProtocolTest(nil) - - 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) - assert.NoError(t, req.Error) - - // assert response - assert.NotNil(t, out) // ensure out variable is used - assert.Equal(t, "bam", *out.Map["baz"]) - assert.Equal(t, "bar", *out.Map["qux"]) - -} diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/query/build.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/query/build.go index 5608e6dc9..83ed8758e 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/query/build.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/query/build.go @@ -7,12 +7,12 @@ import ( "net/url" "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/service" + "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/internal/protocol/query/queryutil" ) // Build builds a request for an AWS Query service. -func Build(r *service.Request) { +func Build(r *request.Request) { body := url.Values{ "Action": {r.Operation.Name}, "Version": {r.Service.APIVersion}, diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/query/build_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/query/build_test.go deleted file mode 100644 index c0ec2219d..000000000 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/query/build_test.go +++ /dev/null @@ -1,1484 +0,0 @@ -package query_test - -import ( - "bytes" - "encoding/json" - "encoding/xml" - "io" - "io/ioutil" - "net/http" - "net/url" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/defaults" - "github.com/aws/aws-sdk-go/aws/service" - "github.com/aws/aws-sdk-go/internal/protocol/query" - "github.com/aws/aws-sdk-go/internal/protocol/xml/xmlutil" - "github.com/aws/aws-sdk-go/internal/signer/v4" - "github.com/aws/aws-sdk-go/internal/util" - "github.com/stretchr/testify/assert" -) - -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 - -type InputService1ProtocolTest struct { - *service.Service -} - -// New returns a new InputService1ProtocolTest client. -func NewInputService1ProtocolTest(config *aws.Config) *InputService1ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "inputservice1protocoltest", - APIVersion: "2014-01-01", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(query.Build) - service.Handlers.Unmarshal.PushBack(query.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(query.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(query.UnmarshalError) - - return &InputService1ProtocolTest{service} -} - -// newRequest creates a new request for a InputService1ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService1ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opInputService1TestCaseOperation1 = "OperationName" - -// InputService1TestCaseOperation1Request generates a request for the InputService1TestCaseOperation1 operation. -func (c *InputService1ProtocolTest) InputService1TestCaseOperation1Request(input *InputService1TestShapeInputShape) (req *service.Request, output *InputService1TestShapeInputService1TestCaseOperation1Output) { - op := &service.Operation{ - Name: opInputService1TestCaseOperation1, - } - - if input == nil { - input = &InputService1TestShapeInputShape{} - } - - req = c.newRequest(op, input, output) - output = &InputService1TestShapeInputService1TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService1ProtocolTest) InputService1TestCaseOperation1(input *InputService1TestShapeInputShape) (*InputService1TestShapeInputService1TestCaseOperation1Output, error) { - req, out := c.InputService1TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type InputService1TestShapeInputService1TestCaseOperation1Output struct { - metadataInputService1TestShapeInputService1TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataInputService1TestShapeInputService1TestCaseOperation1Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService1TestShapeInputShape struct { - Bar *string `type:"string"` - - Foo *string `type:"string"` - - metadataInputService1TestShapeInputShape `json:"-" xml:"-"` -} - -type metadataInputService1TestShapeInputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService2ProtocolTest struct { - *service.Service -} - -// New returns a new InputService2ProtocolTest client. -func NewInputService2ProtocolTest(config *aws.Config) *InputService2ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "inputservice2protocoltest", - APIVersion: "2014-01-01", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(query.Build) - service.Handlers.Unmarshal.PushBack(query.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(query.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(query.UnmarshalError) - - return &InputService2ProtocolTest{service} -} - -// newRequest creates a new request for a InputService2ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService2ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opInputService2TestCaseOperation1 = "OperationName" - -// InputService2TestCaseOperation1Request generates a request for the InputService2TestCaseOperation1 operation. -func (c *InputService2ProtocolTest) InputService2TestCaseOperation1Request(input *InputService2TestShapeInputShape) (req *service.Request, output *InputService2TestShapeInputService2TestCaseOperation1Output) { - op := &service.Operation{ - Name: opInputService2TestCaseOperation1, - } - - if input == nil { - input = &InputService2TestShapeInputShape{} - } - - req = c.newRequest(op, input, output) - output = &InputService2TestShapeInputService2TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService2ProtocolTest) InputService2TestCaseOperation1(input *InputService2TestShapeInputShape) (*InputService2TestShapeInputService2TestCaseOperation1Output, error) { - req, out := c.InputService2TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type InputService2TestShapeInputService2TestCaseOperation1Output struct { - metadataInputService2TestShapeInputService2TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataInputService2TestShapeInputService2TestCaseOperation1Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService2TestShapeInputShape struct { - StructArg *InputService2TestShapeStructType `type:"structure"` - - metadataInputService2TestShapeInputShape `json:"-" xml:"-"` -} - -type metadataInputService2TestShapeInputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService2TestShapeStructType struct { - ScalarArg *string `type:"string"` - - metadataInputService2TestShapeStructType `json:"-" xml:"-"` -} - -type metadataInputService2TestShapeStructType struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService3ProtocolTest struct { - *service.Service -} - -// New returns a new InputService3ProtocolTest client. -func NewInputService3ProtocolTest(config *aws.Config) *InputService3ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "inputservice3protocoltest", - APIVersion: "2014-01-01", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(query.Build) - service.Handlers.Unmarshal.PushBack(query.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(query.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(query.UnmarshalError) - - return &InputService3ProtocolTest{service} -} - -// newRequest creates a new request for a InputService3ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService3ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opInputService3TestCaseOperation1 = "OperationName" - -// InputService3TestCaseOperation1Request generates a request for the InputService3TestCaseOperation1 operation. -func (c *InputService3ProtocolTest) InputService3TestCaseOperation1Request(input *InputService3TestShapeInputShape) (req *service.Request, output *InputService3TestShapeInputService3TestCaseOperation1Output) { - op := &service.Operation{ - Name: opInputService3TestCaseOperation1, - } - - if input == nil { - input = &InputService3TestShapeInputShape{} - } - - req = c.newRequest(op, input, output) - output = &InputService3TestShapeInputService3TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService3ProtocolTest) InputService3TestCaseOperation1(input *InputService3TestShapeInputShape) (*InputService3TestShapeInputService3TestCaseOperation1Output, error) { - req, out := c.InputService3TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -const opInputService3TestCaseOperation2 = "OperationName" - -// InputService3TestCaseOperation2Request generates a request for the InputService3TestCaseOperation2 operation. -func (c *InputService3ProtocolTest) InputService3TestCaseOperation2Request(input *InputService3TestShapeInputShape) (req *service.Request, output *InputService3TestShapeInputService3TestCaseOperation2Output) { - op := &service.Operation{ - Name: opInputService3TestCaseOperation2, - } - - if input == nil { - input = &InputService3TestShapeInputShape{} - } - - req = c.newRequest(op, input, output) - output = &InputService3TestShapeInputService3TestCaseOperation2Output{} - req.Data = output - return -} - -func (c *InputService3ProtocolTest) InputService3TestCaseOperation2(input *InputService3TestShapeInputShape) (*InputService3TestShapeInputService3TestCaseOperation2Output, error) { - req, out := c.InputService3TestCaseOperation2Request(input) - err := req.Send() - return out, err -} - -type InputService3TestShapeInputService3TestCaseOperation1Output struct { - metadataInputService3TestShapeInputService3TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataInputService3TestShapeInputService3TestCaseOperation1Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService3TestShapeInputService3TestCaseOperation2Output struct { - metadataInputService3TestShapeInputService3TestCaseOperation2Output `json:"-" xml:"-"` -} - -type metadataInputService3TestShapeInputService3TestCaseOperation2Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService3TestShapeInputShape struct { - ListArg []*string `type:"list"` - - metadataInputService3TestShapeInputShape `json:"-" xml:"-"` -} - -type metadataInputService3TestShapeInputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService4ProtocolTest struct { - *service.Service -} - -// New returns a new InputService4ProtocolTest client. -func NewInputService4ProtocolTest(config *aws.Config) *InputService4ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "inputservice4protocoltest", - APIVersion: "2014-01-01", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(query.Build) - service.Handlers.Unmarshal.PushBack(query.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(query.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(query.UnmarshalError) - - return &InputService4ProtocolTest{service} -} - -// newRequest creates a new request for a InputService4ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService4ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opInputService4TestCaseOperation1 = "OperationName" - -// InputService4TestCaseOperation1Request generates a request for the InputService4TestCaseOperation1 operation. -func (c *InputService4ProtocolTest) InputService4TestCaseOperation1Request(input *InputService4TestShapeInputShape) (req *service.Request, output *InputService4TestShapeInputService4TestCaseOperation1Output) { - op := &service.Operation{ - Name: opInputService4TestCaseOperation1, - } - - if input == nil { - input = &InputService4TestShapeInputShape{} - } - - req = c.newRequest(op, input, output) - output = &InputService4TestShapeInputService4TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService4ProtocolTest) InputService4TestCaseOperation1(input *InputService4TestShapeInputShape) (*InputService4TestShapeInputService4TestCaseOperation1Output, error) { - req, out := c.InputService4TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -const opInputService4TestCaseOperation2 = "OperationName" - -// InputService4TestCaseOperation2Request generates a request for the InputService4TestCaseOperation2 operation. -func (c *InputService4ProtocolTest) InputService4TestCaseOperation2Request(input *InputService4TestShapeInputShape) (req *service.Request, output *InputService4TestShapeInputService4TestCaseOperation2Output) { - op := &service.Operation{ - Name: opInputService4TestCaseOperation2, - } - - if input == nil { - input = &InputService4TestShapeInputShape{} - } - - req = c.newRequest(op, input, output) - output = &InputService4TestShapeInputService4TestCaseOperation2Output{} - req.Data = output - return -} - -func (c *InputService4ProtocolTest) InputService4TestCaseOperation2(input *InputService4TestShapeInputShape) (*InputService4TestShapeInputService4TestCaseOperation2Output, error) { - req, out := c.InputService4TestCaseOperation2Request(input) - err := req.Send() - return out, err -} - -type InputService4TestShapeInputService4TestCaseOperation1Output struct { - metadataInputService4TestShapeInputService4TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataInputService4TestShapeInputService4TestCaseOperation1Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService4TestShapeInputService4TestCaseOperation2Output struct { - metadataInputService4TestShapeInputService4TestCaseOperation2Output `json:"-" xml:"-"` -} - -type metadataInputService4TestShapeInputService4TestCaseOperation2Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService4TestShapeInputShape struct { - ListArg []*string `type:"list" flattened:"true"` - - ScalarArg *string `type:"string"` - - metadataInputService4TestShapeInputShape `json:"-" xml:"-"` -} - -type metadataInputService4TestShapeInputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService5ProtocolTest struct { - *service.Service -} - -// New returns a new InputService5ProtocolTest client. -func NewInputService5ProtocolTest(config *aws.Config) *InputService5ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "inputservice5protocoltest", - APIVersion: "2014-01-01", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(query.Build) - service.Handlers.Unmarshal.PushBack(query.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(query.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(query.UnmarshalError) - - return &InputService5ProtocolTest{service} -} - -// newRequest creates a new request for a InputService5ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService5ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opInputService5TestCaseOperation1 = "OperationName" - -// InputService5TestCaseOperation1Request generates a request for the InputService5TestCaseOperation1 operation. -func (c *InputService5ProtocolTest) InputService5TestCaseOperation1Request(input *InputService5TestShapeInputShape) (req *service.Request, output *InputService5TestShapeInputService5TestCaseOperation1Output) { - op := &service.Operation{ - Name: opInputService5TestCaseOperation1, - } - - if input == nil { - input = &InputService5TestShapeInputShape{} - } - - req = c.newRequest(op, input, output) - output = &InputService5TestShapeInputService5TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService5ProtocolTest) InputService5TestCaseOperation1(input *InputService5TestShapeInputShape) (*InputService5TestShapeInputService5TestCaseOperation1Output, error) { - req, out := c.InputService5TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -const opInputService5TestCaseOperation2 = "OperationName" - -// InputService5TestCaseOperation2Request generates a request for the InputService5TestCaseOperation2 operation. -func (c *InputService5ProtocolTest) InputService5TestCaseOperation2Request(input *InputService5TestShapeInputShape) (req *service.Request, output *InputService5TestShapeInputService5TestCaseOperation2Output) { - op := &service.Operation{ - Name: opInputService5TestCaseOperation2, - } - - if input == nil { - input = &InputService5TestShapeInputShape{} - } - - req = c.newRequest(op, input, output) - output = &InputService5TestShapeInputService5TestCaseOperation2Output{} - req.Data = output - return -} - -func (c *InputService5ProtocolTest) InputService5TestCaseOperation2(input *InputService5TestShapeInputShape) (*InputService5TestShapeInputService5TestCaseOperation2Output, error) { - req, out := c.InputService5TestCaseOperation2Request(input) - err := req.Send() - return out, err -} - -type InputService5TestShapeInputService5TestCaseOperation1Output struct { - metadataInputService5TestShapeInputService5TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataInputService5TestShapeInputService5TestCaseOperation1Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService5TestShapeInputService5TestCaseOperation2Output struct { - metadataInputService5TestShapeInputService5TestCaseOperation2Output `json:"-" xml:"-"` -} - -type metadataInputService5TestShapeInputService5TestCaseOperation2Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService5TestShapeInputShape struct { - MapArg map[string]*string `type:"map"` - - metadataInputService5TestShapeInputShape `json:"-" xml:"-"` -} - -type metadataInputService5TestShapeInputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService6ProtocolTest struct { - *service.Service -} - -// New returns a new InputService6ProtocolTest client. -func NewInputService6ProtocolTest(config *aws.Config) *InputService6ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "inputservice6protocoltest", - APIVersion: "2014-01-01", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(query.Build) - service.Handlers.Unmarshal.PushBack(query.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(query.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(query.UnmarshalError) - - return &InputService6ProtocolTest{service} -} - -// newRequest creates a new request for a InputService6ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService6ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opInputService6TestCaseOperation1 = "OperationName" - -// InputService6TestCaseOperation1Request generates a request for the InputService6TestCaseOperation1 operation. -func (c *InputService6ProtocolTest) InputService6TestCaseOperation1Request(input *InputService6TestShapeInputShape) (req *service.Request, output *InputService6TestShapeInputService6TestCaseOperation1Output) { - op := &service.Operation{ - Name: opInputService6TestCaseOperation1, - } - - if input == nil { - input = &InputService6TestShapeInputShape{} - } - - req = c.newRequest(op, input, output) - output = &InputService6TestShapeInputService6TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService6ProtocolTest) InputService6TestCaseOperation1(input *InputService6TestShapeInputShape) (*InputService6TestShapeInputService6TestCaseOperation1Output, error) { - req, out := c.InputService6TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type InputService6TestShapeInputService6TestCaseOperation1Output struct { - metadataInputService6TestShapeInputService6TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataInputService6TestShapeInputService6TestCaseOperation1Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService6TestShapeInputShape struct { - MapArg map[string]*string `locationNameKey:"TheKey" locationNameValue:"TheValue" type:"map"` - - metadataInputService6TestShapeInputShape `json:"-" xml:"-"` -} - -type metadataInputService6TestShapeInputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService7ProtocolTest struct { - *service.Service -} - -// New returns a new InputService7ProtocolTest client. -func NewInputService7ProtocolTest(config *aws.Config) *InputService7ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "inputservice7protocoltest", - APIVersion: "2014-01-01", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(query.Build) - service.Handlers.Unmarshal.PushBack(query.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(query.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(query.UnmarshalError) - - return &InputService7ProtocolTest{service} -} - -// newRequest creates a new request for a InputService7ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService7ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opInputService7TestCaseOperation1 = "OperationName" - -// InputService7TestCaseOperation1Request generates a request for the InputService7TestCaseOperation1 operation. -func (c *InputService7ProtocolTest) InputService7TestCaseOperation1Request(input *InputService7TestShapeInputShape) (req *service.Request, output *InputService7TestShapeInputService7TestCaseOperation1Output) { - op := &service.Operation{ - Name: opInputService7TestCaseOperation1, - } - - if input == nil { - input = &InputService7TestShapeInputShape{} - } - - req = c.newRequest(op, input, output) - output = &InputService7TestShapeInputService7TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService7ProtocolTest) InputService7TestCaseOperation1(input *InputService7TestShapeInputShape) (*InputService7TestShapeInputService7TestCaseOperation1Output, error) { - req, out := c.InputService7TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type InputService7TestShapeInputService7TestCaseOperation1Output struct { - metadataInputService7TestShapeInputService7TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataInputService7TestShapeInputService7TestCaseOperation1Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService7TestShapeInputShape struct { - BlobArg []byte `type:"blob"` - - metadataInputService7TestShapeInputShape `json:"-" xml:"-"` -} - -type metadataInputService7TestShapeInputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService8ProtocolTest struct { - *service.Service -} - -// New returns a new InputService8ProtocolTest client. -func NewInputService8ProtocolTest(config *aws.Config) *InputService8ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "inputservice8protocoltest", - APIVersion: "2014-01-01", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(query.Build) - service.Handlers.Unmarshal.PushBack(query.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(query.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(query.UnmarshalError) - - return &InputService8ProtocolTest{service} -} - -// newRequest creates a new request for a InputService8ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService8ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opInputService8TestCaseOperation1 = "OperationName" - -// InputService8TestCaseOperation1Request generates a request for the InputService8TestCaseOperation1 operation. -func (c *InputService8ProtocolTest) InputService8TestCaseOperation1Request(input *InputService8TestShapeInputShape) (req *service.Request, output *InputService8TestShapeInputService8TestCaseOperation1Output) { - op := &service.Operation{ - Name: opInputService8TestCaseOperation1, - } - - if input == nil { - input = &InputService8TestShapeInputShape{} - } - - req = c.newRequest(op, input, output) - output = &InputService8TestShapeInputService8TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService8ProtocolTest) InputService8TestCaseOperation1(input *InputService8TestShapeInputShape) (*InputService8TestShapeInputService8TestCaseOperation1Output, error) { - req, out := c.InputService8TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type InputService8TestShapeInputService8TestCaseOperation1Output struct { - metadataInputService8TestShapeInputService8TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataInputService8TestShapeInputService8TestCaseOperation1Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService8TestShapeInputShape struct { - TimeArg *time.Time `type:"timestamp" timestampFormat:"iso8601"` - - metadataInputService8TestShapeInputShape `json:"-" xml:"-"` -} - -type metadataInputService8TestShapeInputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService9ProtocolTest struct { - *service.Service -} - -// New returns a new InputService9ProtocolTest client. -func NewInputService9ProtocolTest(config *aws.Config) *InputService9ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "inputservice9protocoltest", - APIVersion: "2014-01-01", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(query.Build) - service.Handlers.Unmarshal.PushBack(query.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(query.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(query.UnmarshalError) - - return &InputService9ProtocolTest{service} -} - -// newRequest creates a new request for a InputService9ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService9ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opInputService9TestCaseOperation1 = "OperationName" - -// InputService9TestCaseOperation1Request generates a request for the InputService9TestCaseOperation1 operation. -func (c *InputService9ProtocolTest) InputService9TestCaseOperation1Request(input *InputService9TestShapeInputShape) (req *service.Request, output *InputService9TestShapeInputService9TestCaseOperation1Output) { - op := &service.Operation{ - Name: opInputService9TestCaseOperation1, - } - - if input == nil { - input = &InputService9TestShapeInputShape{} - } - - req = c.newRequest(op, input, output) - output = &InputService9TestShapeInputService9TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService9ProtocolTest) InputService9TestCaseOperation1(input *InputService9TestShapeInputShape) (*InputService9TestShapeInputService9TestCaseOperation1Output, error) { - req, out := c.InputService9TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -const opInputService9TestCaseOperation2 = "OperationName" - -// InputService9TestCaseOperation2Request generates a request for the InputService9TestCaseOperation2 operation. -func (c *InputService9ProtocolTest) InputService9TestCaseOperation2Request(input *InputService9TestShapeInputShape) (req *service.Request, output *InputService9TestShapeInputService9TestCaseOperation2Output) { - op := &service.Operation{ - Name: opInputService9TestCaseOperation2, - } - - if input == nil { - input = &InputService9TestShapeInputShape{} - } - - req = c.newRequest(op, input, output) - output = &InputService9TestShapeInputService9TestCaseOperation2Output{} - req.Data = output - return -} - -func (c *InputService9ProtocolTest) InputService9TestCaseOperation2(input *InputService9TestShapeInputShape) (*InputService9TestShapeInputService9TestCaseOperation2Output, error) { - req, out := c.InputService9TestCaseOperation2Request(input) - err := req.Send() - return out, err -} - -const opInputService9TestCaseOperation3 = "OperationName" - -// InputService9TestCaseOperation3Request generates a request for the InputService9TestCaseOperation3 operation. -func (c *InputService9ProtocolTest) InputService9TestCaseOperation3Request(input *InputService9TestShapeInputShape) (req *service.Request, output *InputService9TestShapeInputService9TestCaseOperation3Output) { - op := &service.Operation{ - Name: opInputService9TestCaseOperation3, - } - - if input == nil { - input = &InputService9TestShapeInputShape{} - } - - req = c.newRequest(op, input, output) - output = &InputService9TestShapeInputService9TestCaseOperation3Output{} - req.Data = output - return -} - -func (c *InputService9ProtocolTest) InputService9TestCaseOperation3(input *InputService9TestShapeInputShape) (*InputService9TestShapeInputService9TestCaseOperation3Output, error) { - req, out := c.InputService9TestCaseOperation3Request(input) - err := req.Send() - return out, err -} - -const opInputService9TestCaseOperation4 = "OperationName" - -// InputService9TestCaseOperation4Request generates a request for the InputService9TestCaseOperation4 operation. -func (c *InputService9ProtocolTest) InputService9TestCaseOperation4Request(input *InputService9TestShapeInputShape) (req *service.Request, output *InputService9TestShapeInputService9TestCaseOperation4Output) { - op := &service.Operation{ - Name: opInputService9TestCaseOperation4, - } - - if input == nil { - input = &InputService9TestShapeInputShape{} - } - - req = c.newRequest(op, input, output) - output = &InputService9TestShapeInputService9TestCaseOperation4Output{} - req.Data = output - return -} - -func (c *InputService9ProtocolTest) InputService9TestCaseOperation4(input *InputService9TestShapeInputShape) (*InputService9TestShapeInputService9TestCaseOperation4Output, error) { - req, out := c.InputService9TestCaseOperation4Request(input) - err := req.Send() - return out, err -} - -const opInputService9TestCaseOperation5 = "OperationName" - -// InputService9TestCaseOperation5Request generates a request for the InputService9TestCaseOperation5 operation. -func (c *InputService9ProtocolTest) InputService9TestCaseOperation5Request(input *InputService9TestShapeInputShape) (req *service.Request, output *InputService9TestShapeInputService9TestCaseOperation5Output) { - op := &service.Operation{ - Name: opInputService9TestCaseOperation5, - } - - if input == nil { - input = &InputService9TestShapeInputShape{} - } - - req = c.newRequest(op, input, output) - output = &InputService9TestShapeInputService9TestCaseOperation5Output{} - req.Data = output - return -} - -func (c *InputService9ProtocolTest) InputService9TestCaseOperation5(input *InputService9TestShapeInputShape) (*InputService9TestShapeInputService9TestCaseOperation5Output, error) { - req, out := c.InputService9TestCaseOperation5Request(input) - err := req.Send() - return out, err -} - -const opInputService9TestCaseOperation6 = "OperationName" - -// InputService9TestCaseOperation6Request generates a request for the InputService9TestCaseOperation6 operation. -func (c *InputService9ProtocolTest) InputService9TestCaseOperation6Request(input *InputService9TestShapeInputShape) (req *service.Request, output *InputService9TestShapeInputService9TestCaseOperation6Output) { - op := &service.Operation{ - Name: opInputService9TestCaseOperation6, - } - - if input == nil { - input = &InputService9TestShapeInputShape{} - } - - req = c.newRequest(op, input, output) - output = &InputService9TestShapeInputService9TestCaseOperation6Output{} - req.Data = output - return -} - -func (c *InputService9ProtocolTest) InputService9TestCaseOperation6(input *InputService9TestShapeInputShape) (*InputService9TestShapeInputService9TestCaseOperation6Output, error) { - req, out := c.InputService9TestCaseOperation6Request(input) - err := req.Send() - return out, err -} - -type InputService9TestShapeInputService9TestCaseOperation1Output struct { - metadataInputService9TestShapeInputService9TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataInputService9TestShapeInputService9TestCaseOperation1Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService9TestShapeInputService9TestCaseOperation2Output struct { - metadataInputService9TestShapeInputService9TestCaseOperation2Output `json:"-" xml:"-"` -} - -type metadataInputService9TestShapeInputService9TestCaseOperation2Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService9TestShapeInputService9TestCaseOperation3Output struct { - metadataInputService9TestShapeInputService9TestCaseOperation3Output `json:"-" xml:"-"` -} - -type metadataInputService9TestShapeInputService9TestCaseOperation3Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService9TestShapeInputService9TestCaseOperation4Output struct { - metadataInputService9TestShapeInputService9TestCaseOperation4Output `json:"-" xml:"-"` -} - -type metadataInputService9TestShapeInputService9TestCaseOperation4Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService9TestShapeInputService9TestCaseOperation5Output struct { - metadataInputService9TestShapeInputService9TestCaseOperation5Output `json:"-" xml:"-"` -} - -type metadataInputService9TestShapeInputService9TestCaseOperation5Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService9TestShapeInputService9TestCaseOperation6Output struct { - metadataInputService9TestShapeInputService9TestCaseOperation6Output `json:"-" xml:"-"` -} - -type metadataInputService9TestShapeInputService9TestCaseOperation6Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService9TestShapeInputShape struct { - RecursiveStruct *InputService9TestShapeRecursiveStructType `type:"structure"` - - metadataInputService9TestShapeInputShape `json:"-" xml:"-"` -} - -type metadataInputService9TestShapeInputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService9TestShapeRecursiveStructType struct { - NoRecurse *string `type:"string"` - - RecursiveList []*InputService9TestShapeRecursiveStructType `type:"list"` - - RecursiveMap map[string]*InputService9TestShapeRecursiveStructType `type:"map"` - - RecursiveStruct *InputService9TestShapeRecursiveStructType `type:"structure"` - - metadataInputService9TestShapeRecursiveStructType `json:"-" xml:"-"` -} - -type metadataInputService9TestShapeRecursiveStructType struct { - SDKShapeTraits bool `type:"structure"` -} - -// -// Tests begin here -// - -func TestInputService1ProtocolTestScalarMembersCase1(t *testing.T) { - svc := NewInputService1ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService1TestShapeInputShape{ - Bar: aws.String("val2"), - Foo: aws.String("val1"), - } - req, _ := svc.InputService1TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body, _ := ioutil.ReadAll(r.Body) - assert.Equal(t, util.Trim(`Action=OperationName&Bar=val2&Foo=val1&Version=2014-01-01`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService2ProtocolTestNestedStructureMembersCase1(t *testing.T) { - svc := NewInputService2ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService2TestShapeInputShape{ - StructArg: &InputService2TestShapeStructType{ - ScalarArg: aws.String("foo"), - }, - } - req, _ := svc.InputService2TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body, _ := ioutil.ReadAll(r.Body) - assert.Equal(t, util.Trim(`Action=OperationName&StructArg.ScalarArg=foo&Version=2014-01-01`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService3ProtocolTestListTypesCase1(t *testing.T) { - svc := NewInputService3ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService3TestShapeInputShape{ - ListArg: []*string{ - aws.String("foo"), - aws.String("bar"), - aws.String("baz"), - }, - } - req, _ := svc.InputService3TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body, _ := ioutil.ReadAll(r.Body) - assert.Equal(t, util.Trim(`Action=OperationName&ListArg.member.1=foo&ListArg.member.2=bar&ListArg.member.3=baz&Version=2014-01-01`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService3ProtocolTestListTypesCase2(t *testing.T) { - svc := NewInputService3ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService3TestShapeInputShape{ - ListArg: []*string{}, - } - req, _ := svc.InputService3TestCaseOperation2Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body, _ := ioutil.ReadAll(r.Body) - assert.Equal(t, util.Trim(`Action=OperationName&ListArg=&Version=2014-01-01`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService4ProtocolTestFlattenedListCase1(t *testing.T) { - svc := NewInputService4ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService4TestShapeInputShape{ - 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) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body, _ := ioutil.ReadAll(r.Body) - assert.Equal(t, util.Trim(`Action=OperationName&ListArg.1=a&ListArg.2=b&ListArg.3=c&ScalarArg=foo&Version=2014-01-01`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService4ProtocolTestFlattenedListCase2(t *testing.T) { - svc := NewInputService4ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService4TestShapeInputShape{ - ListArg: []*string{}, - ScalarArg: aws.String("foo"), - } - req, _ := svc.InputService4TestCaseOperation2Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body, _ := ioutil.ReadAll(r.Body) - assert.Equal(t, util.Trim(`Action=OperationName&ListArg=&ScalarArg=foo&Version=2014-01-01`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService5ProtocolTestSerializeMapTypeCase1(t *testing.T) { - svc := NewInputService5ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService5TestShapeInputShape{ - MapArg: map[string]*string{ - "key1": aws.String("val1"), - "key2": aws.String("val2"), - }, - } - req, _ := svc.InputService5TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body, _ := ioutil.ReadAll(r.Body) - assert.Equal(t, util.Trim(`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 - assert.Equal(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService5ProtocolTestSerializeMapTypeCase2(t *testing.T) { - svc := NewInputService5ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService5TestShapeInputShape{ - MapArg: map[string]*string{}, - } - req, _ := svc.InputService5TestCaseOperation2Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body, _ := ioutil.ReadAll(r.Body) - assert.Equal(t, util.Trim(`Action=OperationName&MapArg=&Version=2014-01-01`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService6ProtocolTestSerializeMapTypeWithLocationNameCase1(t *testing.T) { - svc := NewInputService6ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService6TestShapeInputShape{ - MapArg: map[string]*string{ - "key1": aws.String("val1"), - "key2": aws.String("val2"), - }, - } - req, _ := svc.InputService6TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body, _ := ioutil.ReadAll(r.Body) - assert.Equal(t, util.Trim(`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 - assert.Equal(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService7ProtocolTestBase64EncodedBlobsCase1(t *testing.T) { - svc := NewInputService7ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService7TestShapeInputShape{ - BlobArg: []byte("foo"), - } - req, _ := svc.InputService7TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body, _ := ioutil.ReadAll(r.Body) - assert.Equal(t, util.Trim(`Action=OperationName&BlobArg=Zm9v&Version=2014-01-01`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService8ProtocolTestTimestampValuesCase1(t *testing.T) { - svc := NewInputService8ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService8TestShapeInputShape{ - TimeArg: aws.Time(time.Unix(1422172800, 0)), - } - req, _ := svc.InputService8TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body, _ := ioutil.ReadAll(r.Body) - assert.Equal(t, util.Trim(`Action=OperationName&TimeArg=2015-01-25T08%3A00%3A00Z&Version=2014-01-01`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService9ProtocolTestRecursiveShapesCase1(t *testing.T) { - svc := NewInputService9ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService9TestShapeInputShape{ - RecursiveStruct: &InputService9TestShapeRecursiveStructType{ - NoRecurse: aws.String("foo"), - }, - } - req, _ := svc.InputService9TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body, _ := ioutil.ReadAll(r.Body) - assert.Equal(t, util.Trim(`Action=OperationName&RecursiveStruct.NoRecurse=foo&Version=2014-01-01`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService9ProtocolTestRecursiveShapesCase2(t *testing.T) { - svc := NewInputService9ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService9TestShapeInputShape{ - RecursiveStruct: &InputService9TestShapeRecursiveStructType{ - RecursiveStruct: &InputService9TestShapeRecursiveStructType{ - NoRecurse: aws.String("foo"), - }, - }, - } - req, _ := svc.InputService9TestCaseOperation2Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body, _ := ioutil.ReadAll(r.Body) - assert.Equal(t, util.Trim(`Action=OperationName&RecursiveStruct.RecursiveStruct.NoRecurse=foo&Version=2014-01-01`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService9ProtocolTestRecursiveShapesCase3(t *testing.T) { - svc := NewInputService9ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService9TestShapeInputShape{ - RecursiveStruct: &InputService9TestShapeRecursiveStructType{ - RecursiveStruct: &InputService9TestShapeRecursiveStructType{ - RecursiveStruct: &InputService9TestShapeRecursiveStructType{ - RecursiveStruct: &InputService9TestShapeRecursiveStructType{ - NoRecurse: aws.String("foo"), - }, - }, - }, - }, - } - req, _ := svc.InputService9TestCaseOperation3Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body, _ := ioutil.ReadAll(r.Body) - assert.Equal(t, util.Trim(`Action=OperationName&RecursiveStruct.RecursiveStruct.RecursiveStruct.RecursiveStruct.NoRecurse=foo&Version=2014-01-01`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService9ProtocolTestRecursiveShapesCase4(t *testing.T) { - svc := NewInputService9ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService9TestShapeInputShape{ - RecursiveStruct: &InputService9TestShapeRecursiveStructType{ - RecursiveList: []*InputService9TestShapeRecursiveStructType{ - { - NoRecurse: aws.String("foo"), - }, - { - NoRecurse: aws.String("bar"), - }, - }, - }, - } - req, _ := svc.InputService9TestCaseOperation4Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body, _ := ioutil.ReadAll(r.Body) - assert.Equal(t, util.Trim(`Action=OperationName&RecursiveStruct.RecursiveList.member.1.NoRecurse=foo&RecursiveStruct.RecursiveList.member.2.NoRecurse=bar&Version=2014-01-01`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService9ProtocolTestRecursiveShapesCase5(t *testing.T) { - svc := NewInputService9ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService9TestShapeInputShape{ - RecursiveStruct: &InputService9TestShapeRecursiveStructType{ - RecursiveList: []*InputService9TestShapeRecursiveStructType{ - { - NoRecurse: aws.String("foo"), - }, - { - RecursiveStruct: &InputService9TestShapeRecursiveStructType{ - NoRecurse: aws.String("bar"), - }, - }, - }, - }, - } - req, _ := svc.InputService9TestCaseOperation5Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body, _ := ioutil.ReadAll(r.Body) - assert.Equal(t, util.Trim(`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 - assert.Equal(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService9ProtocolTestRecursiveShapesCase6(t *testing.T) { - svc := NewInputService9ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService9TestShapeInputShape{ - RecursiveStruct: &InputService9TestShapeRecursiveStructType{ - RecursiveMap: map[string]*InputService9TestShapeRecursiveStructType{ - "bar": { - NoRecurse: aws.String("bar"), - }, - "foo": { - NoRecurse: aws.String("foo"), - }, - }, - }, - } - req, _ := svc.InputService9TestCaseOperation6Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body, _ := ioutil.ReadAll(r.Body) - assert.Equal(t, util.Trim(`Action=OperationName&RecursiveStruct.RecursiveMap.entry.1.key=bar&RecursiveStruct.RecursiveMap.entry.1.value.NoRecurse=bar&RecursiveStruct.RecursiveMap.entry.2.key=foo&RecursiveStruct.RecursiveMap.entry.2.value.NoRecurse=foo&Version=2014-01-01`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/", r.URL.String()) - - // assert headers - -} diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/query/unmarshal.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/query/unmarshal.go index d80138399..a374f88b1 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/query/unmarshal.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/query/unmarshal.go @@ -6,12 +6,12 @@ import ( "encoding/xml" "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/service" + "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/internal/protocol/xml/xmlutil" ) // Unmarshal unmarshals a response for an AWS Query service. -func Unmarshal(r *service.Request) { +func Unmarshal(r *request.Request) { defer r.HTTPResponse.Body.Close() if r.DataFilled() { decoder := xml.NewDecoder(r.HTTPResponse.Body) @@ -24,6 +24,6 @@ func Unmarshal(r *service.Request) { } // UnmarshalMeta unmarshals header response values for an AWS Query service. -func UnmarshalMeta(r *service.Request) { +func UnmarshalMeta(r *request.Request) { // TODO implement unmarshaling of request IDs } diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/query/unmarshal_error.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/query/unmarshal_error.go index 14e3989d5..08609d920 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/query/unmarshal_error.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/query/unmarshal_error.go @@ -5,7 +5,7 @@ import ( "io" "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/service" + "github.com/aws/aws-sdk-go/aws/request" ) type xmlErrorResponse struct { @@ -16,7 +16,7 @@ type xmlErrorResponse struct { } // UnmarshalError unmarshals an error response for an AWS Query service. -func UnmarshalError(r *service.Request) { +func UnmarshalError(r *request.Request) { defer r.HTTPResponse.Body.Close() resp := &xmlErrorResponse{} diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/query/unmarshal_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/query/unmarshal_test.go deleted file mode 100644 index c34f24cac..000000000 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/query/unmarshal_test.go +++ /dev/null @@ -1,1420 +0,0 @@ -package query_test - -import ( - "bytes" - "encoding/json" - "encoding/xml" - "io" - "io/ioutil" - "net/http" - "net/url" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/defaults" - "github.com/aws/aws-sdk-go/aws/service" - "github.com/aws/aws-sdk-go/internal/protocol/query" - "github.com/aws/aws-sdk-go/internal/protocol/xml/xmlutil" - "github.com/aws/aws-sdk-go/internal/signer/v4" - "github.com/aws/aws-sdk-go/internal/util" - "github.com/stretchr/testify/assert" -) - -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 - -type OutputService1ProtocolTest struct { - *service.Service -} - -// New returns a new OutputService1ProtocolTest client. -func NewOutputService1ProtocolTest(config *aws.Config) *OutputService1ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "outputservice1protocoltest", - APIVersion: "", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(query.Build) - service.Handlers.Unmarshal.PushBack(query.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(query.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(query.UnmarshalError) - - return &OutputService1ProtocolTest{service} -} - -// newRequest creates a new request for a OutputService1ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService1ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opOutputService1TestCaseOperation1 = "OperationName" - -// OutputService1TestCaseOperation1Request generates a request for the OutputService1TestCaseOperation1 operation. -func (c *OutputService1ProtocolTest) OutputService1TestCaseOperation1Request(input *OutputService1TestShapeOutputService1TestCaseOperation1Input) (req *service.Request, output *OutputService1TestShapeOutputShape) { - op := &service.Operation{ - Name: opOutputService1TestCaseOperation1, - } - - if input == nil { - input = &OutputService1TestShapeOutputService1TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &OutputService1TestShapeOutputShape{} - req.Data = output - return -} - -func (c *OutputService1ProtocolTest) OutputService1TestCaseOperation1(input *OutputService1TestShapeOutputService1TestCaseOperation1Input) (*OutputService1TestShapeOutputShape, error) { - req, out := c.OutputService1TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type OutputService1TestShapeOutputService1TestCaseOperation1Input struct { - metadataOutputService1TestShapeOutputService1TestCaseOperation1Input `json:"-" xml:"-"` -} - -type metadataOutputService1TestShapeOutputService1TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService1TestShapeOutputShape struct { - 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"` - - metadataOutputService1TestShapeOutputShape `json:"-" xml:"-"` -} - -type metadataOutputService1TestShapeOutputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService2ProtocolTest struct { - *service.Service -} - -// New returns a new OutputService2ProtocolTest client. -func NewOutputService2ProtocolTest(config *aws.Config) *OutputService2ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "outputservice2protocoltest", - APIVersion: "", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(query.Build) - service.Handlers.Unmarshal.PushBack(query.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(query.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(query.UnmarshalError) - - return &OutputService2ProtocolTest{service} -} - -// newRequest creates a new request for a OutputService2ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService2ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opOutputService2TestCaseOperation1 = "OperationName" - -// OutputService2TestCaseOperation1Request generates a request for the OutputService2TestCaseOperation1 operation. -func (c *OutputService2ProtocolTest) OutputService2TestCaseOperation1Request(input *OutputService2TestShapeOutputService2TestCaseOperation1Input) (req *service.Request, output *OutputService2TestShapeOutputShape) { - op := &service.Operation{ - Name: opOutputService2TestCaseOperation1, - } - - if input == nil { - input = &OutputService2TestShapeOutputService2TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &OutputService2TestShapeOutputShape{} - req.Data = output - return -} - -func (c *OutputService2ProtocolTest) OutputService2TestCaseOperation1(input *OutputService2TestShapeOutputService2TestCaseOperation1Input) (*OutputService2TestShapeOutputShape, error) { - req, out := c.OutputService2TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type OutputService2TestShapeOutputService2TestCaseOperation1Input struct { - metadataOutputService2TestShapeOutputService2TestCaseOperation1Input `json:"-" xml:"-"` -} - -type metadataOutputService2TestShapeOutputService2TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService2TestShapeOutputShape struct { - Num *int64 `type:"integer"` - - Str *string `type:"string"` - - metadataOutputService2TestShapeOutputShape `json:"-" xml:"-"` -} - -type metadataOutputService2TestShapeOutputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService3ProtocolTest struct { - *service.Service -} - -// New returns a new OutputService3ProtocolTest client. -func NewOutputService3ProtocolTest(config *aws.Config) *OutputService3ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "outputservice3protocoltest", - APIVersion: "", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(query.Build) - service.Handlers.Unmarshal.PushBack(query.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(query.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(query.UnmarshalError) - - return &OutputService3ProtocolTest{service} -} - -// newRequest creates a new request for a OutputService3ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService3ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opOutputService3TestCaseOperation1 = "OperationName" - -// OutputService3TestCaseOperation1Request generates a request for the OutputService3TestCaseOperation1 operation. -func (c *OutputService3ProtocolTest) OutputService3TestCaseOperation1Request(input *OutputService3TestShapeOutputService3TestCaseOperation1Input) (req *service.Request, output *OutputService3TestShapeOutputShape) { - op := &service.Operation{ - Name: opOutputService3TestCaseOperation1, - } - - if input == nil { - input = &OutputService3TestShapeOutputService3TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &OutputService3TestShapeOutputShape{} - req.Data = output - return -} - -func (c *OutputService3ProtocolTest) OutputService3TestCaseOperation1(input *OutputService3TestShapeOutputService3TestCaseOperation1Input) (*OutputService3TestShapeOutputShape, error) { - req, out := c.OutputService3TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type OutputService3TestShapeOutputService3TestCaseOperation1Input struct { - metadataOutputService3TestShapeOutputService3TestCaseOperation1Input `json:"-" xml:"-"` -} - -type metadataOutputService3TestShapeOutputService3TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService3TestShapeOutputShape struct { - Blob []byte `type:"blob"` - - metadataOutputService3TestShapeOutputShape `json:"-" xml:"-"` -} - -type metadataOutputService3TestShapeOutputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService4ProtocolTest struct { - *service.Service -} - -// New returns a new OutputService4ProtocolTest client. -func NewOutputService4ProtocolTest(config *aws.Config) *OutputService4ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "outputservice4protocoltest", - APIVersion: "", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(query.Build) - service.Handlers.Unmarshal.PushBack(query.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(query.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(query.UnmarshalError) - - return &OutputService4ProtocolTest{service} -} - -// newRequest creates a new request for a OutputService4ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService4ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opOutputService4TestCaseOperation1 = "OperationName" - -// OutputService4TestCaseOperation1Request generates a request for the OutputService4TestCaseOperation1 operation. -func (c *OutputService4ProtocolTest) OutputService4TestCaseOperation1Request(input *OutputService4TestShapeOutputService4TestCaseOperation1Input) (req *service.Request, output *OutputService4TestShapeOutputShape) { - op := &service.Operation{ - Name: opOutputService4TestCaseOperation1, - } - - if input == nil { - input = &OutputService4TestShapeOutputService4TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &OutputService4TestShapeOutputShape{} - req.Data = output - return -} - -func (c *OutputService4ProtocolTest) OutputService4TestCaseOperation1(input *OutputService4TestShapeOutputService4TestCaseOperation1Input) (*OutputService4TestShapeOutputShape, error) { - req, out := c.OutputService4TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type OutputService4TestShapeOutputService4TestCaseOperation1Input struct { - metadataOutputService4TestShapeOutputService4TestCaseOperation1Input `json:"-" xml:"-"` -} - -type metadataOutputService4TestShapeOutputService4TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService4TestShapeOutputShape struct { - ListMember []*string `type:"list"` - - metadataOutputService4TestShapeOutputShape `json:"-" xml:"-"` -} - -type metadataOutputService4TestShapeOutputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService5ProtocolTest struct { - *service.Service -} - -// New returns a new OutputService5ProtocolTest client. -func NewOutputService5ProtocolTest(config *aws.Config) *OutputService5ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "outputservice5protocoltest", - APIVersion: "", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(query.Build) - service.Handlers.Unmarshal.PushBack(query.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(query.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(query.UnmarshalError) - - return &OutputService5ProtocolTest{service} -} - -// newRequest creates a new request for a OutputService5ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService5ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opOutputService5TestCaseOperation1 = "OperationName" - -// OutputService5TestCaseOperation1Request generates a request for the OutputService5TestCaseOperation1 operation. -func (c *OutputService5ProtocolTest) OutputService5TestCaseOperation1Request(input *OutputService5TestShapeOutputService5TestCaseOperation1Input) (req *service.Request, output *OutputService5TestShapeOutputShape) { - op := &service.Operation{ - Name: opOutputService5TestCaseOperation1, - } - - if input == nil { - input = &OutputService5TestShapeOutputService5TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &OutputService5TestShapeOutputShape{} - req.Data = output - return -} - -func (c *OutputService5ProtocolTest) OutputService5TestCaseOperation1(input *OutputService5TestShapeOutputService5TestCaseOperation1Input) (*OutputService5TestShapeOutputShape, error) { - req, out := c.OutputService5TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type OutputService5TestShapeOutputService5TestCaseOperation1Input struct { - metadataOutputService5TestShapeOutputService5TestCaseOperation1Input `json:"-" xml:"-"` -} - -type metadataOutputService5TestShapeOutputService5TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService5TestShapeOutputShape struct { - ListMember []*string `locationNameList:"item" type:"list"` - - metadataOutputService5TestShapeOutputShape `json:"-" xml:"-"` -} - -type metadataOutputService5TestShapeOutputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService6ProtocolTest struct { - *service.Service -} - -// New returns a new OutputService6ProtocolTest client. -func NewOutputService6ProtocolTest(config *aws.Config) *OutputService6ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "outputservice6protocoltest", - APIVersion: "", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(query.Build) - service.Handlers.Unmarshal.PushBack(query.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(query.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(query.UnmarshalError) - - return &OutputService6ProtocolTest{service} -} - -// newRequest creates a new request for a OutputService6ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService6ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opOutputService6TestCaseOperation1 = "OperationName" - -// OutputService6TestCaseOperation1Request generates a request for the OutputService6TestCaseOperation1 operation. -func (c *OutputService6ProtocolTest) OutputService6TestCaseOperation1Request(input *OutputService6TestShapeOutputService6TestCaseOperation1Input) (req *service.Request, output *OutputService6TestShapeOutputShape) { - op := &service.Operation{ - Name: opOutputService6TestCaseOperation1, - } - - if input == nil { - input = &OutputService6TestShapeOutputService6TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &OutputService6TestShapeOutputShape{} - req.Data = output - return -} - -func (c *OutputService6ProtocolTest) OutputService6TestCaseOperation1(input *OutputService6TestShapeOutputService6TestCaseOperation1Input) (*OutputService6TestShapeOutputShape, error) { - req, out := c.OutputService6TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type OutputService6TestShapeOutputService6TestCaseOperation1Input struct { - metadataOutputService6TestShapeOutputService6TestCaseOperation1Input `json:"-" xml:"-"` -} - -type metadataOutputService6TestShapeOutputService6TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService6TestShapeOutputShape struct { - ListMember []*string `type:"list" flattened:"true"` - - metadataOutputService6TestShapeOutputShape `json:"-" xml:"-"` -} - -type metadataOutputService6TestShapeOutputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService7ProtocolTest struct { - *service.Service -} - -// New returns a new OutputService7ProtocolTest client. -func NewOutputService7ProtocolTest(config *aws.Config) *OutputService7ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "outputservice7protocoltest", - APIVersion: "", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(query.Build) - service.Handlers.Unmarshal.PushBack(query.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(query.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(query.UnmarshalError) - - return &OutputService7ProtocolTest{service} -} - -// newRequest creates a new request for a OutputService7ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService7ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opOutputService7TestCaseOperation1 = "OperationName" - -// OutputService7TestCaseOperation1Request generates a request for the OutputService7TestCaseOperation1 operation. -func (c *OutputService7ProtocolTest) OutputService7TestCaseOperation1Request(input *OutputService7TestShapeOutputService7TestCaseOperation1Input) (req *service.Request, output *OutputService7TestShapeOutputShape) { - op := &service.Operation{ - Name: opOutputService7TestCaseOperation1, - } - - if input == nil { - input = &OutputService7TestShapeOutputService7TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &OutputService7TestShapeOutputShape{} - req.Data = output - return -} - -func (c *OutputService7ProtocolTest) OutputService7TestCaseOperation1(input *OutputService7TestShapeOutputService7TestCaseOperation1Input) (*OutputService7TestShapeOutputShape, error) { - req, out := c.OutputService7TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type OutputService7TestShapeOutputService7TestCaseOperation1Input struct { - metadataOutputService7TestShapeOutputService7TestCaseOperation1Input `json:"-" xml:"-"` -} - -type metadataOutputService7TestShapeOutputService7TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService7TestShapeOutputShape struct { - ListMember []*string `type:"list" flattened:"true"` - - metadataOutputService7TestShapeOutputShape `json:"-" xml:"-"` -} - -type metadataOutputService7TestShapeOutputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService8ProtocolTest struct { - *service.Service -} - -// New returns a new OutputService8ProtocolTest client. -func NewOutputService8ProtocolTest(config *aws.Config) *OutputService8ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "outputservice8protocoltest", - APIVersion: "", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(query.Build) - service.Handlers.Unmarshal.PushBack(query.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(query.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(query.UnmarshalError) - - return &OutputService8ProtocolTest{service} -} - -// newRequest creates a new request for a OutputService8ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService8ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opOutputService8TestCaseOperation1 = "OperationName" - -// OutputService8TestCaseOperation1Request generates a request for the OutputService8TestCaseOperation1 operation. -func (c *OutputService8ProtocolTest) OutputService8TestCaseOperation1Request(input *OutputService8TestShapeOutputService8TestCaseOperation1Input) (req *service.Request, output *OutputService8TestShapeOutputShape) { - op := &service.Operation{ - Name: opOutputService8TestCaseOperation1, - } - - if input == nil { - input = &OutputService8TestShapeOutputService8TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &OutputService8TestShapeOutputShape{} - req.Data = output - return -} - -func (c *OutputService8ProtocolTest) OutputService8TestCaseOperation1(input *OutputService8TestShapeOutputService8TestCaseOperation1Input) (*OutputService8TestShapeOutputShape, error) { - req, out := c.OutputService8TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type OutputService8TestShapeOutputService8TestCaseOperation1Input struct { - metadataOutputService8TestShapeOutputService8TestCaseOperation1Input `json:"-" xml:"-"` -} - -type metadataOutputService8TestShapeOutputService8TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService8TestShapeOutputShape struct { - List []*OutputService8TestShapeStructureShape `type:"list"` - - metadataOutputService8TestShapeOutputShape `json:"-" xml:"-"` -} - -type metadataOutputService8TestShapeOutputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService8TestShapeStructureShape struct { - Bar *string `type:"string"` - - Baz *string `type:"string"` - - Foo *string `type:"string"` - - metadataOutputService8TestShapeStructureShape `json:"-" xml:"-"` -} - -type metadataOutputService8TestShapeStructureShape struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService9ProtocolTest struct { - *service.Service -} - -// New returns a new OutputService9ProtocolTest client. -func NewOutputService9ProtocolTest(config *aws.Config) *OutputService9ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "outputservice9protocoltest", - APIVersion: "", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(query.Build) - service.Handlers.Unmarshal.PushBack(query.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(query.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(query.UnmarshalError) - - return &OutputService9ProtocolTest{service} -} - -// newRequest creates a new request for a OutputService9ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService9ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opOutputService9TestCaseOperation1 = "OperationName" - -// OutputService9TestCaseOperation1Request generates a request for the OutputService9TestCaseOperation1 operation. -func (c *OutputService9ProtocolTest) OutputService9TestCaseOperation1Request(input *OutputService9TestShapeOutputService9TestCaseOperation1Input) (req *service.Request, output *OutputService9TestShapeOutputShape) { - op := &service.Operation{ - Name: opOutputService9TestCaseOperation1, - } - - if input == nil { - input = &OutputService9TestShapeOutputService9TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &OutputService9TestShapeOutputShape{} - req.Data = output - return -} - -func (c *OutputService9ProtocolTest) OutputService9TestCaseOperation1(input *OutputService9TestShapeOutputService9TestCaseOperation1Input) (*OutputService9TestShapeOutputShape, error) { - req, out := c.OutputService9TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type OutputService9TestShapeOutputService9TestCaseOperation1Input struct { - metadataOutputService9TestShapeOutputService9TestCaseOperation1Input `json:"-" xml:"-"` -} - -type metadataOutputService9TestShapeOutputService9TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService9TestShapeOutputShape struct { - List []*OutputService9TestShapeStructureShape `type:"list" flattened:"true"` - - metadataOutputService9TestShapeOutputShape `json:"-" xml:"-"` -} - -type metadataOutputService9TestShapeOutputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService9TestShapeStructureShape struct { - Bar *string `type:"string"` - - Baz *string `type:"string"` - - Foo *string `type:"string"` - - metadataOutputService9TestShapeStructureShape `json:"-" xml:"-"` -} - -type metadataOutputService9TestShapeStructureShape struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService10ProtocolTest struct { - *service.Service -} - -// New returns a new OutputService10ProtocolTest client. -func NewOutputService10ProtocolTest(config *aws.Config) *OutputService10ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "outputservice10protocoltest", - APIVersion: "", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(query.Build) - service.Handlers.Unmarshal.PushBack(query.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(query.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(query.UnmarshalError) - - return &OutputService10ProtocolTest{service} -} - -// newRequest creates a new request for a OutputService10ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService10ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opOutputService10TestCaseOperation1 = "OperationName" - -// OutputService10TestCaseOperation1Request generates a request for the OutputService10TestCaseOperation1 operation. -func (c *OutputService10ProtocolTest) OutputService10TestCaseOperation1Request(input *OutputService10TestShapeOutputService10TestCaseOperation1Input) (req *service.Request, output *OutputService10TestShapeOutputShape) { - op := &service.Operation{ - Name: opOutputService10TestCaseOperation1, - } - - if input == nil { - input = &OutputService10TestShapeOutputService10TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &OutputService10TestShapeOutputShape{} - req.Data = output - return -} - -func (c *OutputService10ProtocolTest) OutputService10TestCaseOperation1(input *OutputService10TestShapeOutputService10TestCaseOperation1Input) (*OutputService10TestShapeOutputShape, error) { - req, out := c.OutputService10TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type OutputService10TestShapeOutputService10TestCaseOperation1Input struct { - metadataOutputService10TestShapeOutputService10TestCaseOperation1Input `json:"-" xml:"-"` -} - -type metadataOutputService10TestShapeOutputService10TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService10TestShapeOutputShape struct { - List []*string `locationNameList:"NamedList" type:"list" flattened:"true"` - - metadataOutputService10TestShapeOutputShape `json:"-" xml:"-"` -} - -type metadataOutputService10TestShapeOutputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService11ProtocolTest struct { - *service.Service -} - -// New returns a new OutputService11ProtocolTest client. -func NewOutputService11ProtocolTest(config *aws.Config) *OutputService11ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "outputservice11protocoltest", - APIVersion: "", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(query.Build) - service.Handlers.Unmarshal.PushBack(query.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(query.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(query.UnmarshalError) - - return &OutputService11ProtocolTest{service} -} - -// newRequest creates a new request for a OutputService11ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService11ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opOutputService11TestCaseOperation1 = "OperationName" - -// OutputService11TestCaseOperation1Request generates a request for the OutputService11TestCaseOperation1 operation. -func (c *OutputService11ProtocolTest) OutputService11TestCaseOperation1Request(input *OutputService11TestShapeOutputService11TestCaseOperation1Input) (req *service.Request, output *OutputService11TestShapeOutputShape) { - op := &service.Operation{ - Name: opOutputService11TestCaseOperation1, - } - - if input == nil { - input = &OutputService11TestShapeOutputService11TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &OutputService11TestShapeOutputShape{} - req.Data = output - return -} - -func (c *OutputService11ProtocolTest) OutputService11TestCaseOperation1(input *OutputService11TestShapeOutputService11TestCaseOperation1Input) (*OutputService11TestShapeOutputShape, error) { - req, out := c.OutputService11TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type OutputService11TestShapeOutputService11TestCaseOperation1Input struct { - metadataOutputService11TestShapeOutputService11TestCaseOperation1Input `json:"-" xml:"-"` -} - -type metadataOutputService11TestShapeOutputService11TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService11TestShapeOutputShape struct { - Map map[string]*OutputService11TestShapeStructType `type:"map"` - - metadataOutputService11TestShapeOutputShape `json:"-" xml:"-"` -} - -type metadataOutputService11TestShapeOutputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService11TestShapeStructType struct { - Foo *string `locationName:"foo" type:"string"` - - metadataOutputService11TestShapeStructType `json:"-" xml:"-"` -} - -type metadataOutputService11TestShapeStructType struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService12ProtocolTest struct { - *service.Service -} - -// New returns a new OutputService12ProtocolTest client. -func NewOutputService12ProtocolTest(config *aws.Config) *OutputService12ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "outputservice12protocoltest", - APIVersion: "", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(query.Build) - service.Handlers.Unmarshal.PushBack(query.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(query.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(query.UnmarshalError) - - return &OutputService12ProtocolTest{service} -} - -// newRequest creates a new request for a OutputService12ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService12ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opOutputService12TestCaseOperation1 = "OperationName" - -// OutputService12TestCaseOperation1Request generates a request for the OutputService12TestCaseOperation1 operation. -func (c *OutputService12ProtocolTest) OutputService12TestCaseOperation1Request(input *OutputService12TestShapeOutputService12TestCaseOperation1Input) (req *service.Request, output *OutputService12TestShapeOutputShape) { - op := &service.Operation{ - Name: opOutputService12TestCaseOperation1, - } - - if input == nil { - input = &OutputService12TestShapeOutputService12TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &OutputService12TestShapeOutputShape{} - req.Data = output - return -} - -func (c *OutputService12ProtocolTest) OutputService12TestCaseOperation1(input *OutputService12TestShapeOutputService12TestCaseOperation1Input) (*OutputService12TestShapeOutputShape, error) { - req, out := c.OutputService12TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type OutputService12TestShapeOutputService12TestCaseOperation1Input struct { - metadataOutputService12TestShapeOutputService12TestCaseOperation1Input `json:"-" xml:"-"` -} - -type metadataOutputService12TestShapeOutputService12TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService12TestShapeOutputShape struct { - Map map[string]*string `type:"map" flattened:"true"` - - metadataOutputService12TestShapeOutputShape `json:"-" xml:"-"` -} - -type metadataOutputService12TestShapeOutputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService13ProtocolTest struct { - *service.Service -} - -// New returns a new OutputService13ProtocolTest client. -func NewOutputService13ProtocolTest(config *aws.Config) *OutputService13ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "outputservice13protocoltest", - APIVersion: "", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(query.Build) - service.Handlers.Unmarshal.PushBack(query.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(query.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(query.UnmarshalError) - - return &OutputService13ProtocolTest{service} -} - -// newRequest creates a new request for a OutputService13ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService13ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opOutputService13TestCaseOperation1 = "OperationName" - -// OutputService13TestCaseOperation1Request generates a request for the OutputService13TestCaseOperation1 operation. -func (c *OutputService13ProtocolTest) OutputService13TestCaseOperation1Request(input *OutputService13TestShapeOutputService13TestCaseOperation1Input) (req *service.Request, output *OutputService13TestShapeOutputShape) { - op := &service.Operation{ - Name: opOutputService13TestCaseOperation1, - } - - if input == nil { - input = &OutputService13TestShapeOutputService13TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &OutputService13TestShapeOutputShape{} - req.Data = output - return -} - -func (c *OutputService13ProtocolTest) OutputService13TestCaseOperation1(input *OutputService13TestShapeOutputService13TestCaseOperation1Input) (*OutputService13TestShapeOutputShape, error) { - req, out := c.OutputService13TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type OutputService13TestShapeOutputService13TestCaseOperation1Input struct { - metadataOutputService13TestShapeOutputService13TestCaseOperation1Input `json:"-" xml:"-"` -} - -type metadataOutputService13TestShapeOutputService13TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService13TestShapeOutputShape struct { - Map map[string]*string `locationName:"Attribute" locationNameKey:"Name" locationNameValue:"Value" type:"map" flattened:"true"` - - metadataOutputService13TestShapeOutputShape `json:"-" xml:"-"` -} - -type metadataOutputService13TestShapeOutputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService14ProtocolTest struct { - *service.Service -} - -// New returns a new OutputService14ProtocolTest client. -func NewOutputService14ProtocolTest(config *aws.Config) *OutputService14ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "outputservice14protocoltest", - APIVersion: "", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(query.Build) - service.Handlers.Unmarshal.PushBack(query.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(query.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(query.UnmarshalError) - - return &OutputService14ProtocolTest{service} -} - -// newRequest creates a new request for a OutputService14ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService14ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opOutputService14TestCaseOperation1 = "OperationName" - -// OutputService14TestCaseOperation1Request generates a request for the OutputService14TestCaseOperation1 operation. -func (c *OutputService14ProtocolTest) OutputService14TestCaseOperation1Request(input *OutputService14TestShapeOutputService14TestCaseOperation1Input) (req *service.Request, output *OutputService14TestShapeOutputShape) { - op := &service.Operation{ - Name: opOutputService14TestCaseOperation1, - } - - if input == nil { - input = &OutputService14TestShapeOutputService14TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &OutputService14TestShapeOutputShape{} - req.Data = output - return -} - -func (c *OutputService14ProtocolTest) OutputService14TestCaseOperation1(input *OutputService14TestShapeOutputService14TestCaseOperation1Input) (*OutputService14TestShapeOutputShape, error) { - req, out := c.OutputService14TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type OutputService14TestShapeOutputService14TestCaseOperation1Input struct { - metadataOutputService14TestShapeOutputService14TestCaseOperation1Input `json:"-" xml:"-"` -} - -type metadataOutputService14TestShapeOutputService14TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService14TestShapeOutputShape struct { - Map map[string]*string `locationNameKey:"foo" locationNameValue:"bar" type:"map" flattened:"true"` - - metadataOutputService14TestShapeOutputShape `json:"-" xml:"-"` -} - -type metadataOutputService14TestShapeOutputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -// -// Tests begin here -// - -func TestOutputService1ProtocolTestScalarMembersCase1(t *testing.T) { - svc := NewOutputService1ProtocolTest(nil) - - 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) - assert.NoError(t, req.Error) - - // assert response - assert.NotNil(t, out) // ensure out variable is used - assert.Equal(t, "a", *out.Char) - assert.Equal(t, 1.3, *out.Double) - assert.Equal(t, false, *out.FalseBool) - assert.Equal(t, 1.2, *out.Float) - assert.Equal(t, int64(200), *out.Long) - assert.Equal(t, int64(123), *out.Num) - assert.Equal(t, "myname", *out.Str) - assert.Equal(t, time.Unix(1.4221728e+09, 0).UTC().String(), out.Timestamp.String()) - assert.Equal(t, true, *out.TrueBool) - -} - -func TestOutputService2ProtocolTestNotAllMembersInResponseCase1(t *testing.T) { - svc := NewOutputService2ProtocolTest(nil) - - 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) - assert.NoError(t, req.Error) - - // assert response - assert.NotNil(t, out) // ensure out variable is used - assert.Equal(t, "myname", *out.Str) - -} - -func TestOutputService3ProtocolTestBlobCase1(t *testing.T) { - svc := NewOutputService3ProtocolTest(nil) - - 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) - assert.NoError(t, req.Error) - - // assert response - assert.NotNil(t, out) // ensure out variable is used - assert.Equal(t, "value", string(out.Blob)) - -} - -func TestOutputService4ProtocolTestListsCase1(t *testing.T) { - svc := NewOutputService4ProtocolTest(nil) - - 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) - assert.NoError(t, req.Error) - - // assert response - assert.NotNil(t, out) // ensure out variable is used - assert.Equal(t, "abc", *out.ListMember[0]) - assert.Equal(t, "123", *out.ListMember[1]) - -} - -func TestOutputService5ProtocolTestListWithCustomMemberNameCase1(t *testing.T) { - svc := NewOutputService5ProtocolTest(nil) - - 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) - assert.NoError(t, req.Error) - - // assert response - assert.NotNil(t, out) // ensure out variable is used - assert.Equal(t, "abc", *out.ListMember[0]) - assert.Equal(t, "123", *out.ListMember[1]) - -} - -func TestOutputService6ProtocolTestFlattenedListCase1(t *testing.T) { - svc := NewOutputService6ProtocolTest(nil) - - 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) - assert.NoError(t, req.Error) - - // assert response - assert.NotNil(t, out) // ensure out variable is used - assert.Equal(t, "abc", *out.ListMember[0]) - assert.Equal(t, "123", *out.ListMember[1]) - -} - -func TestOutputService7ProtocolTestFlattenedSingleElementListCase1(t *testing.T) { - svc := NewOutputService7ProtocolTest(nil) - - 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) - assert.NoError(t, req.Error) - - // assert response - assert.NotNil(t, out) // ensure out variable is used - assert.Equal(t, "abc", *out.ListMember[0]) - -} - -func TestOutputService8ProtocolTestListOfStructuresCase1(t *testing.T) { - svc := NewOutputService8ProtocolTest(nil) - - 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) - assert.NoError(t, req.Error) - - // assert response - assert.NotNil(t, out) // ensure out variable is used - assert.Equal(t, "firstbar", *out.List[0].Bar) - assert.Equal(t, "firstbaz", *out.List[0].Baz) - assert.Equal(t, "firstfoo", *out.List[0].Foo) - assert.Equal(t, "secondbar", *out.List[1].Bar) - assert.Equal(t, "secondbaz", *out.List[1].Baz) - assert.Equal(t, "secondfoo", *out.List[1].Foo) - -} - -func TestOutputService9ProtocolTestFlattenedListOfStructuresCase1(t *testing.T) { - svc := NewOutputService9ProtocolTest(nil) - - 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) - assert.NoError(t, req.Error) - - // assert response - assert.NotNil(t, out) // ensure out variable is used - assert.Equal(t, "firstbar", *out.List[0].Bar) - assert.Equal(t, "firstbaz", *out.List[0].Baz) - assert.Equal(t, "firstfoo", *out.List[0].Foo) - assert.Equal(t, "secondbar", *out.List[1].Bar) - assert.Equal(t, "secondbaz", *out.List[1].Baz) - assert.Equal(t, "secondfoo", *out.List[1].Foo) - -} - -func TestOutputService10ProtocolTestFlattenedListWithLocationNameCase1(t *testing.T) { - svc := NewOutputService10ProtocolTest(nil) - - 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) - assert.NoError(t, req.Error) - - // assert response - assert.NotNil(t, out) // ensure out variable is used - assert.Equal(t, "a", *out.List[0]) - assert.Equal(t, "b", *out.List[1]) - -} - -func TestOutputService11ProtocolTestNormalMapCase1(t *testing.T) { - svc := NewOutputService11ProtocolTest(nil) - - 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) - assert.NoError(t, req.Error) - - // assert response - assert.NotNil(t, out) // ensure out variable is used - assert.Equal(t, "bam", *out.Map["baz"].Foo) - assert.Equal(t, "bar", *out.Map["qux"].Foo) - -} - -func TestOutputService12ProtocolTestFlattenedMapCase1(t *testing.T) { - svc := NewOutputService12ProtocolTest(nil) - - 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) - assert.NoError(t, req.Error) - - // assert response - assert.NotNil(t, out) // ensure out variable is used - assert.Equal(t, "bam", *out.Map["baz"]) - assert.Equal(t, "bar", *out.Map["qux"]) - -} - -func TestOutputService13ProtocolTestFlattenedMapInShapeDefinitionCase1(t *testing.T) { - svc := NewOutputService13ProtocolTest(nil) - - 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) - assert.NoError(t, req.Error) - - // assert response - assert.NotNil(t, out) // ensure out variable is used - assert.Equal(t, "bar", *out.Map["qux"]) - -} - -func TestOutputService14ProtocolTestNamedMapCase1(t *testing.T) { - svc := NewOutputService14ProtocolTest(nil) - - 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) - assert.NoError(t, req.Error) - - // assert response - assert.NotNil(t, out) // ensure out variable is used - assert.Equal(t, "bam", *out.Map["baz"]) - assert.Equal(t, "bar", *out.Map["qux"]) - -} diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/rest/build.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/rest/build.go index 587e3b4e4..326e96cc6 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/rest/build.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/rest/build.go @@ -14,7 +14,7 @@ import ( "time" "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/service" + "github.com/aws/aws-sdk-go/aws/request" ) // RFC822 returns an RFC822 formatted timestamp for AWS protocols @@ -37,7 +37,7 @@ func init() { } // Build builds the REST component of a service request. -func Build(r *service.Request) { +func Build(r *request.Request) { if r.ParamsFilled() { v := reflect.ValueOf(r.Params).Elem() buildLocationElements(r, v) @@ -45,7 +45,7 @@ func Build(r *service.Request) { } } -func buildLocationElements(r *service.Request, v reflect.Value) { +func buildLocationElements(r *request.Request, v reflect.Value) { query := r.HTTPRequest.URL.Query() for i := 0; i < v.NumField(); i++ { @@ -87,7 +87,7 @@ func buildLocationElements(r *service.Request, v reflect.Value) { updatePath(r.HTTPRequest.URL, r.HTTPRequest.URL.Path) } -func buildBody(r *service.Request, v reflect.Value) { +func buildBody(r *request.Request, v reflect.Value) { if field, ok := v.Type().FieldByName("SDKShapeTraits"); ok { if payloadName := field.Tag.Get("payload"); payloadName != "" { pfield, _ := v.Type().FieldByName(payloadName) @@ -112,7 +112,7 @@ func buildBody(r *service.Request, v reflect.Value) { } } -func buildHeader(r *service.Request, v reflect.Value, name string) { +func buildHeader(r *request.Request, v reflect.Value, name string) { str, err := convertType(v) if err != nil { r.Error = awserr.New("SerializationError", "failed to encode REST request", err) @@ -121,7 +121,7 @@ func buildHeader(r *service.Request, v reflect.Value, name string) { } } -func buildHeaderMap(r *service.Request, v reflect.Value, prefix string) { +func buildHeaderMap(r *request.Request, v reflect.Value, prefix string) { for _, key := range v.MapKeys() { str, err := convertType(v.MapIndex(key)) if err != nil { @@ -132,7 +132,7 @@ func buildHeaderMap(r *service.Request, v reflect.Value, prefix string) { } } -func buildURI(r *service.Request, v reflect.Value, name string) { +func buildURI(r *request.Request, v reflect.Value, name string) { value, err := convertType(v) if err != nil { r.Error = awserr.New("SerializationError", "failed to encode REST request", err) @@ -144,7 +144,7 @@ func buildURI(r *service.Request, v reflect.Value, name string) { } } -func buildQueryString(r *service.Request, v reflect.Value, name string, query url.Values) { +func buildQueryString(r *request.Request, v reflect.Value, name string, query url.Values) { str, err := convertType(v) if err != nil { r.Error = awserr.New("SerializationError", "failed to encode REST request", err) diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/rest/unmarshal.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/rest/unmarshal.go index 60b68213f..06d9accba 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/rest/unmarshal.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/rest/unmarshal.go @@ -12,19 +12,27 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/service" + "github.com/aws/aws-sdk-go/aws/request" ) // Unmarshal unmarshals the REST component of a response in a REST service. -func Unmarshal(r *service.Request) { +func Unmarshal(r *request.Request) { if r.DataFilled() { v := reflect.Indirect(reflect.ValueOf(r.Data)) unmarshalBody(r, v) + } +} + +// UnmarshalMeta unmarshals the REST metadata of a response in a REST service +func UnmarshalMeta(r *request.Request) { + r.RequestID = r.HTTPResponse.Header.Get("X-Amzn-Requestid") + if r.DataFilled() { + v := reflect.Indirect(reflect.ValueOf(r.Data)) unmarshalLocationElements(r, v) } } -func unmarshalBody(r *service.Request, v reflect.Value) { +func unmarshalBody(r *request.Request, v reflect.Value) { if field, ok := v.Type().FieldByName("SDKShapeTraits"); ok { if payloadName := field.Tag.Get("payload"); payloadName != "" { pfield, _ := v.Type().FieldByName(payloadName) @@ -65,7 +73,7 @@ func unmarshalBody(r *service.Request, v reflect.Value) { } } -func unmarshalLocationElements(r *service.Request, v reflect.Value) { +func unmarshalLocationElements(r *request.Request, v reflect.Value) { for i := 0; i < v.NumField(); i++ { m, field := v.Field(i), v.Type().Field(i) if n := field.Name; n[0:1] == strings.ToLower(n[0:1]) { diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/restxml/build_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/restxml/build_test.go deleted file mode 100644 index b50a585ee..000000000 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/restxml/build_test.go +++ /dev/null @@ -1,2719 +0,0 @@ -package restxml_test - -import ( - "bytes" - "encoding/json" - "encoding/xml" - "io" - "io/ioutil" - "net/http" - "net/url" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/defaults" - "github.com/aws/aws-sdk-go/aws/service" - "github.com/aws/aws-sdk-go/internal/protocol/restxml" - "github.com/aws/aws-sdk-go/internal/protocol/xml/xmlutil" - "github.com/aws/aws-sdk-go/internal/signer/v4" - "github.com/aws/aws-sdk-go/internal/util" - "github.com/stretchr/testify/assert" -) - -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 - -type InputService1ProtocolTest struct { - *service.Service -} - -// New returns a new InputService1ProtocolTest client. -func NewInputService1ProtocolTest(config *aws.Config) *InputService1ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "inputservice1protocoltest", - APIVersion: "2014-01-01", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(restxml.Build) - service.Handlers.Unmarshal.PushBack(restxml.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(restxml.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(restxml.UnmarshalError) - - return &InputService1ProtocolTest{service} -} - -// newRequest creates a new request for a InputService1ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService1ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opInputService1TestCaseOperation1 = "OperationName" - -// InputService1TestCaseOperation1Request generates a request for the InputService1TestCaseOperation1 operation. -func (c *InputService1ProtocolTest) InputService1TestCaseOperation1Request(input *InputService1TestShapeInputShape) (req *service.Request, output *InputService1TestShapeInputService1TestCaseOperation1Output) { - op := &service.Operation{ - Name: opInputService1TestCaseOperation1, - HTTPMethod: "POST", - HTTPPath: "/2014-01-01/hostedzone", - } - - if input == nil { - input = &InputService1TestShapeInputShape{} - } - - req = c.newRequest(op, input, output) - output = &InputService1TestShapeInputService1TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService1ProtocolTest) InputService1TestCaseOperation1(input *InputService1TestShapeInputShape) (*InputService1TestShapeInputService1TestCaseOperation1Output, error) { - req, out := c.InputService1TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -const opInputService1TestCaseOperation2 = "OperationName" - -// InputService1TestCaseOperation2Request generates a request for the InputService1TestCaseOperation2 operation. -func (c *InputService1ProtocolTest) InputService1TestCaseOperation2Request(input *InputService1TestShapeInputShape) (req *service.Request, output *InputService1TestShapeInputService1TestCaseOperation2Output) { - op := &service.Operation{ - Name: opInputService1TestCaseOperation2, - HTTPMethod: "PUT", - HTTPPath: "/2014-01-01/hostedzone", - } - - if input == nil { - input = &InputService1TestShapeInputShape{} - } - - req = c.newRequest(op, input, output) - output = &InputService1TestShapeInputService1TestCaseOperation2Output{} - req.Data = output - return -} - -func (c *InputService1ProtocolTest) InputService1TestCaseOperation2(input *InputService1TestShapeInputShape) (*InputService1TestShapeInputService1TestCaseOperation2Output, error) { - req, out := c.InputService1TestCaseOperation2Request(input) - err := req.Send() - return out, err -} - -type InputService1TestShapeInputService1TestCaseOperation1Output struct { - metadataInputService1TestShapeInputService1TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataInputService1TestShapeInputService1TestCaseOperation1Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService1TestShapeInputService1TestCaseOperation2Output struct { - metadataInputService1TestShapeInputService1TestCaseOperation2Output `json:"-" xml:"-"` -} - -type metadataInputService1TestShapeInputService1TestCaseOperation2Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService1TestShapeInputShape struct { - Description *string `type:"string"` - - Name *string `type:"string"` - - metadataInputService1TestShapeInputShape `json:"-" xml:"-"` -} - -type metadataInputService1TestShapeInputShape struct { - SDKShapeTraits bool `locationName:"OperationRequest" type:"structure" xmlURI:"https://foo/"` -} - -type InputService2ProtocolTest struct { - *service.Service -} - -// New returns a new InputService2ProtocolTest client. -func NewInputService2ProtocolTest(config *aws.Config) *InputService2ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "inputservice2protocoltest", - APIVersion: "2014-01-01", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(restxml.Build) - service.Handlers.Unmarshal.PushBack(restxml.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(restxml.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(restxml.UnmarshalError) - - return &InputService2ProtocolTest{service} -} - -// newRequest creates a new request for a InputService2ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService2ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opInputService2TestCaseOperation1 = "OperationName" - -// InputService2TestCaseOperation1Request generates a request for the InputService2TestCaseOperation1 operation. -func (c *InputService2ProtocolTest) InputService2TestCaseOperation1Request(input *InputService2TestShapeInputShape) (req *service.Request, output *InputService2TestShapeInputService2TestCaseOperation1Output) { - op := &service.Operation{ - Name: opInputService2TestCaseOperation1, - HTTPMethod: "POST", - HTTPPath: "/2014-01-01/hostedzone", - } - - if input == nil { - input = &InputService2TestShapeInputShape{} - } - - req = c.newRequest(op, input, output) - output = &InputService2TestShapeInputService2TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService2ProtocolTest) InputService2TestCaseOperation1(input *InputService2TestShapeInputShape) (*InputService2TestShapeInputService2TestCaseOperation1Output, error) { - req, out := c.InputService2TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type InputService2TestShapeInputService2TestCaseOperation1Output struct { - metadataInputService2TestShapeInputService2TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataInputService2TestShapeInputService2TestCaseOperation1Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService2TestShapeInputShape struct { - First *bool `type:"boolean"` - - Fourth *int64 `type:"integer"` - - Second *bool `type:"boolean"` - - Third *float64 `type:"float"` - - metadataInputService2TestShapeInputShape `json:"-" xml:"-"` -} - -type metadataInputService2TestShapeInputShape struct { - SDKShapeTraits bool `locationName:"OperationRequest" type:"structure" xmlURI:"https://foo/"` -} - -type InputService3ProtocolTest struct { - *service.Service -} - -// New returns a new InputService3ProtocolTest client. -func NewInputService3ProtocolTest(config *aws.Config) *InputService3ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "inputservice3protocoltest", - APIVersion: "2014-01-01", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(restxml.Build) - service.Handlers.Unmarshal.PushBack(restxml.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(restxml.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(restxml.UnmarshalError) - - return &InputService3ProtocolTest{service} -} - -// newRequest creates a new request for a InputService3ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService3ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opInputService3TestCaseOperation1 = "OperationName" - -// InputService3TestCaseOperation1Request generates a request for the InputService3TestCaseOperation1 operation. -func (c *InputService3ProtocolTest) InputService3TestCaseOperation1Request(input *InputService3TestShapeInputShape) (req *service.Request, output *InputService3TestShapeInputService3TestCaseOperation1Output) { - op := &service.Operation{ - Name: opInputService3TestCaseOperation1, - HTTPMethod: "POST", - HTTPPath: "/2014-01-01/hostedzone", - } - - if input == nil { - input = &InputService3TestShapeInputShape{} - } - - req = c.newRequest(op, input, output) - output = &InputService3TestShapeInputService3TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService3ProtocolTest) InputService3TestCaseOperation1(input *InputService3TestShapeInputShape) (*InputService3TestShapeInputService3TestCaseOperation1Output, error) { - req, out := c.InputService3TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type InputService3TestShapeInputService3TestCaseOperation1Output struct { - metadataInputService3TestShapeInputService3TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataInputService3TestShapeInputService3TestCaseOperation1Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService3TestShapeInputShape struct { - Description *string `type:"string"` - - SubStructure *InputService3TestShapeSubStructure `type:"structure"` - - metadataInputService3TestShapeInputShape `json:"-" xml:"-"` -} - -type metadataInputService3TestShapeInputShape struct { - SDKShapeTraits bool `locationName:"OperationRequest" type:"structure" xmlURI:"https://foo/"` -} - -type InputService3TestShapeSubStructure struct { - Bar *string `type:"string"` - - Foo *string `type:"string"` - - metadataInputService3TestShapeSubStructure `json:"-" xml:"-"` -} - -type metadataInputService3TestShapeSubStructure struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService4ProtocolTest struct { - *service.Service -} - -// New returns a new InputService4ProtocolTest client. -func NewInputService4ProtocolTest(config *aws.Config) *InputService4ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "inputservice4protocoltest", - APIVersion: "2014-01-01", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(restxml.Build) - service.Handlers.Unmarshal.PushBack(restxml.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(restxml.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(restxml.UnmarshalError) - - return &InputService4ProtocolTest{service} -} - -// newRequest creates a new request for a InputService4ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService4ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opInputService4TestCaseOperation1 = "OperationName" - -// InputService4TestCaseOperation1Request generates a request for the InputService4TestCaseOperation1 operation. -func (c *InputService4ProtocolTest) InputService4TestCaseOperation1Request(input *InputService4TestShapeInputShape) (req *service.Request, output *InputService4TestShapeInputService4TestCaseOperation1Output) { - op := &service.Operation{ - Name: opInputService4TestCaseOperation1, - HTTPMethod: "POST", - HTTPPath: "/2014-01-01/hostedzone", - } - - if input == nil { - input = &InputService4TestShapeInputShape{} - } - - req = c.newRequest(op, input, output) - output = &InputService4TestShapeInputService4TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService4ProtocolTest) InputService4TestCaseOperation1(input *InputService4TestShapeInputShape) (*InputService4TestShapeInputService4TestCaseOperation1Output, error) { - req, out := c.InputService4TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type InputService4TestShapeInputService4TestCaseOperation1Output struct { - metadataInputService4TestShapeInputService4TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataInputService4TestShapeInputService4TestCaseOperation1Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService4TestShapeInputShape struct { - Description *string `type:"string"` - - SubStructure *InputService4TestShapeSubStructure `type:"structure"` - - metadataInputService4TestShapeInputShape `json:"-" xml:"-"` -} - -type metadataInputService4TestShapeInputShape struct { - SDKShapeTraits bool `locationName:"OperationRequest" type:"structure" xmlURI:"https://foo/"` -} - -type InputService4TestShapeSubStructure struct { - Bar *string `type:"string"` - - Foo *string `type:"string"` - - metadataInputService4TestShapeSubStructure `json:"-" xml:"-"` -} - -type metadataInputService4TestShapeSubStructure struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService5ProtocolTest struct { - *service.Service -} - -// New returns a new InputService5ProtocolTest client. -func NewInputService5ProtocolTest(config *aws.Config) *InputService5ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "inputservice5protocoltest", - APIVersion: "2014-01-01", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(restxml.Build) - service.Handlers.Unmarshal.PushBack(restxml.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(restxml.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(restxml.UnmarshalError) - - return &InputService5ProtocolTest{service} -} - -// newRequest creates a new request for a InputService5ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService5ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opInputService5TestCaseOperation1 = "OperationName" - -// InputService5TestCaseOperation1Request generates a request for the InputService5TestCaseOperation1 operation. -func (c *InputService5ProtocolTest) InputService5TestCaseOperation1Request(input *InputService5TestShapeInputShape) (req *service.Request, output *InputService5TestShapeInputService5TestCaseOperation1Output) { - op := &service.Operation{ - Name: opInputService5TestCaseOperation1, - HTTPMethod: "POST", - HTTPPath: "/2014-01-01/hostedzone", - } - - if input == nil { - input = &InputService5TestShapeInputShape{} - } - - req = c.newRequest(op, input, output) - output = &InputService5TestShapeInputService5TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService5ProtocolTest) InputService5TestCaseOperation1(input *InputService5TestShapeInputShape) (*InputService5TestShapeInputService5TestCaseOperation1Output, error) { - req, out := c.InputService5TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type InputService5TestShapeInputService5TestCaseOperation1Output struct { - metadataInputService5TestShapeInputService5TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataInputService5TestShapeInputService5TestCaseOperation1Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService5TestShapeInputShape struct { - ListParam []*string `type:"list"` - - metadataInputService5TestShapeInputShape `json:"-" xml:"-"` -} - -type metadataInputService5TestShapeInputShape struct { - SDKShapeTraits bool `locationName:"OperationRequest" type:"structure" xmlURI:"https://foo/"` -} - -type InputService6ProtocolTest struct { - *service.Service -} - -// New returns a new InputService6ProtocolTest client. -func NewInputService6ProtocolTest(config *aws.Config) *InputService6ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "inputservice6protocoltest", - APIVersion: "2014-01-01", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(restxml.Build) - service.Handlers.Unmarshal.PushBack(restxml.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(restxml.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(restxml.UnmarshalError) - - return &InputService6ProtocolTest{service} -} - -// newRequest creates a new request for a InputService6ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService6ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opInputService6TestCaseOperation1 = "OperationName" - -// InputService6TestCaseOperation1Request generates a request for the InputService6TestCaseOperation1 operation. -func (c *InputService6ProtocolTest) InputService6TestCaseOperation1Request(input *InputService6TestShapeInputShape) (req *service.Request, output *InputService6TestShapeInputService6TestCaseOperation1Output) { - op := &service.Operation{ - Name: opInputService6TestCaseOperation1, - HTTPMethod: "POST", - HTTPPath: "/2014-01-01/hostedzone", - } - - if input == nil { - input = &InputService6TestShapeInputShape{} - } - - req = c.newRequest(op, input, output) - output = &InputService6TestShapeInputService6TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService6ProtocolTest) InputService6TestCaseOperation1(input *InputService6TestShapeInputShape) (*InputService6TestShapeInputService6TestCaseOperation1Output, error) { - req, out := c.InputService6TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type InputService6TestShapeInputService6TestCaseOperation1Output struct { - metadataInputService6TestShapeInputService6TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataInputService6TestShapeInputService6TestCaseOperation1Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService6TestShapeInputShape struct { - ListParam []*string `locationName:"AlternateName" locationNameList:"NotMember" type:"list"` - - metadataInputService6TestShapeInputShape `json:"-" xml:"-"` -} - -type metadataInputService6TestShapeInputShape struct { - SDKShapeTraits bool `locationName:"OperationRequest" type:"structure" xmlURI:"https://foo/"` -} - -type InputService7ProtocolTest struct { - *service.Service -} - -// New returns a new InputService7ProtocolTest client. -func NewInputService7ProtocolTest(config *aws.Config) *InputService7ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "inputservice7protocoltest", - APIVersion: "2014-01-01", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(restxml.Build) - service.Handlers.Unmarshal.PushBack(restxml.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(restxml.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(restxml.UnmarshalError) - - return &InputService7ProtocolTest{service} -} - -// newRequest creates a new request for a InputService7ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService7ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opInputService7TestCaseOperation1 = "OperationName" - -// InputService7TestCaseOperation1Request generates a request for the InputService7TestCaseOperation1 operation. -func (c *InputService7ProtocolTest) InputService7TestCaseOperation1Request(input *InputService7TestShapeInputShape) (req *service.Request, output *InputService7TestShapeInputService7TestCaseOperation1Output) { - op := &service.Operation{ - Name: opInputService7TestCaseOperation1, - HTTPMethod: "POST", - HTTPPath: "/2014-01-01/hostedzone", - } - - if input == nil { - input = &InputService7TestShapeInputShape{} - } - - req = c.newRequest(op, input, output) - output = &InputService7TestShapeInputService7TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService7ProtocolTest) InputService7TestCaseOperation1(input *InputService7TestShapeInputShape) (*InputService7TestShapeInputService7TestCaseOperation1Output, error) { - req, out := c.InputService7TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type InputService7TestShapeInputService7TestCaseOperation1Output struct { - metadataInputService7TestShapeInputService7TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataInputService7TestShapeInputService7TestCaseOperation1Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService7TestShapeInputShape struct { - ListParam []*string `type:"list" flattened:"true"` - - metadataInputService7TestShapeInputShape `json:"-" xml:"-"` -} - -type metadataInputService7TestShapeInputShape struct { - SDKShapeTraits bool `locationName:"OperationRequest" type:"structure" xmlURI:"https://foo/"` -} - -type InputService8ProtocolTest struct { - *service.Service -} - -// New returns a new InputService8ProtocolTest client. -func NewInputService8ProtocolTest(config *aws.Config) *InputService8ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "inputservice8protocoltest", - APIVersion: "2014-01-01", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(restxml.Build) - service.Handlers.Unmarshal.PushBack(restxml.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(restxml.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(restxml.UnmarshalError) - - return &InputService8ProtocolTest{service} -} - -// newRequest creates a new request for a InputService8ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService8ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opInputService8TestCaseOperation1 = "OperationName" - -// InputService8TestCaseOperation1Request generates a request for the InputService8TestCaseOperation1 operation. -func (c *InputService8ProtocolTest) InputService8TestCaseOperation1Request(input *InputService8TestShapeInputShape) (req *service.Request, output *InputService8TestShapeInputService8TestCaseOperation1Output) { - op := &service.Operation{ - Name: opInputService8TestCaseOperation1, - HTTPMethod: "POST", - HTTPPath: "/2014-01-01/hostedzone", - } - - if input == nil { - input = &InputService8TestShapeInputShape{} - } - - req = c.newRequest(op, input, output) - output = &InputService8TestShapeInputService8TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService8ProtocolTest) InputService8TestCaseOperation1(input *InputService8TestShapeInputShape) (*InputService8TestShapeInputService8TestCaseOperation1Output, error) { - req, out := c.InputService8TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type InputService8TestShapeInputService8TestCaseOperation1Output struct { - metadataInputService8TestShapeInputService8TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataInputService8TestShapeInputService8TestCaseOperation1Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService8TestShapeInputShape struct { - ListParam []*string `locationName:"item" type:"list" flattened:"true"` - - metadataInputService8TestShapeInputShape `json:"-" xml:"-"` -} - -type metadataInputService8TestShapeInputShape struct { - SDKShapeTraits bool `locationName:"OperationRequest" type:"structure" xmlURI:"https://foo/"` -} - -type InputService9ProtocolTest struct { - *service.Service -} - -// New returns a new InputService9ProtocolTest client. -func NewInputService9ProtocolTest(config *aws.Config) *InputService9ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "inputservice9protocoltest", - APIVersion: "2014-01-01", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(restxml.Build) - service.Handlers.Unmarshal.PushBack(restxml.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(restxml.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(restxml.UnmarshalError) - - return &InputService9ProtocolTest{service} -} - -// newRequest creates a new request for a InputService9ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService9ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opInputService9TestCaseOperation1 = "OperationName" - -// InputService9TestCaseOperation1Request generates a request for the InputService9TestCaseOperation1 operation. -func (c *InputService9ProtocolTest) InputService9TestCaseOperation1Request(input *InputService9TestShapeInputShape) (req *service.Request, output *InputService9TestShapeInputService9TestCaseOperation1Output) { - op := &service.Operation{ - Name: opInputService9TestCaseOperation1, - HTTPMethod: "POST", - HTTPPath: "/2014-01-01/hostedzone", - } - - if input == nil { - input = &InputService9TestShapeInputShape{} - } - - req = c.newRequest(op, input, output) - output = &InputService9TestShapeInputService9TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService9ProtocolTest) InputService9TestCaseOperation1(input *InputService9TestShapeInputShape) (*InputService9TestShapeInputService9TestCaseOperation1Output, error) { - req, out := c.InputService9TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type InputService9TestShapeInputService9TestCaseOperation1Output struct { - metadataInputService9TestShapeInputService9TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataInputService9TestShapeInputService9TestCaseOperation1Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService9TestShapeInputShape struct { - ListParam []*InputService9TestShapeSingleFieldStruct `locationName:"item" type:"list" flattened:"true"` - - metadataInputService9TestShapeInputShape `json:"-" xml:"-"` -} - -type metadataInputService9TestShapeInputShape struct { - SDKShapeTraits bool `locationName:"OperationRequest" type:"structure" xmlURI:"https://foo/"` -} - -type InputService9TestShapeSingleFieldStruct struct { - Element *string `locationName:"value" type:"string"` - - metadataInputService9TestShapeSingleFieldStruct `json:"-" xml:"-"` -} - -type metadataInputService9TestShapeSingleFieldStruct struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService10ProtocolTest struct { - *service.Service -} - -// New returns a new InputService10ProtocolTest client. -func NewInputService10ProtocolTest(config *aws.Config) *InputService10ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "inputservice10protocoltest", - APIVersion: "2014-01-01", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(restxml.Build) - service.Handlers.Unmarshal.PushBack(restxml.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(restxml.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(restxml.UnmarshalError) - - return &InputService10ProtocolTest{service} -} - -// newRequest creates a new request for a InputService10ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService10ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opInputService10TestCaseOperation1 = "OperationName" - -// InputService10TestCaseOperation1Request generates a request for the InputService10TestCaseOperation1 operation. -func (c *InputService10ProtocolTest) InputService10TestCaseOperation1Request(input *InputService10TestShapeInputShape) (req *service.Request, output *InputService10TestShapeInputService10TestCaseOperation1Output) { - op := &service.Operation{ - Name: opInputService10TestCaseOperation1, - HTTPMethod: "POST", - HTTPPath: "/2014-01-01/hostedzone", - } - - if input == nil { - input = &InputService10TestShapeInputShape{} - } - - req = c.newRequest(op, input, output) - output = &InputService10TestShapeInputService10TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService10ProtocolTest) InputService10TestCaseOperation1(input *InputService10TestShapeInputShape) (*InputService10TestShapeInputService10TestCaseOperation1Output, error) { - req, out := c.InputService10TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type InputService10TestShapeInputService10TestCaseOperation1Output struct { - metadataInputService10TestShapeInputService10TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataInputService10TestShapeInputService10TestCaseOperation1Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService10TestShapeInputShape struct { - StructureParam *InputService10TestShapeStructureShape `type:"structure"` - - metadataInputService10TestShapeInputShape `json:"-" xml:"-"` -} - -type metadataInputService10TestShapeInputShape struct { - SDKShapeTraits bool `locationName:"OperationRequest" type:"structure" xmlURI:"https://foo/"` -} - -type InputService10TestShapeStructureShape struct { - B []byte `locationName:"b" type:"blob"` - - T *time.Time `locationName:"t" type:"timestamp" timestampFormat:"iso8601"` - - metadataInputService10TestShapeStructureShape `json:"-" xml:"-"` -} - -type metadataInputService10TestShapeStructureShape struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService11ProtocolTest struct { - *service.Service -} - -// New returns a new InputService11ProtocolTest client. -func NewInputService11ProtocolTest(config *aws.Config) *InputService11ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "inputservice11protocoltest", - APIVersion: "2014-01-01", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(restxml.Build) - service.Handlers.Unmarshal.PushBack(restxml.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(restxml.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(restxml.UnmarshalError) - - return &InputService11ProtocolTest{service} -} - -// newRequest creates a new request for a InputService11ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService11ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opInputService11TestCaseOperation1 = "OperationName" - -// InputService11TestCaseOperation1Request generates a request for the InputService11TestCaseOperation1 operation. -func (c *InputService11ProtocolTest) InputService11TestCaseOperation1Request(input *InputService11TestShapeInputShape) (req *service.Request, output *InputService11TestShapeInputService11TestCaseOperation1Output) { - op := &service.Operation{ - Name: opInputService11TestCaseOperation1, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &InputService11TestShapeInputShape{} - } - - req = c.newRequest(op, input, output) - output = &InputService11TestShapeInputService11TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService11ProtocolTest) InputService11TestCaseOperation1(input *InputService11TestShapeInputShape) (*InputService11TestShapeInputService11TestCaseOperation1Output, error) { - req, out := c.InputService11TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type InputService11TestShapeInputService11TestCaseOperation1Output struct { - metadataInputService11TestShapeInputService11TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataInputService11TestShapeInputService11TestCaseOperation1Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService11TestShapeInputShape struct { - Foo map[string]*string `location:"headers" locationName:"x-foo-" type:"map"` - - metadataInputService11TestShapeInputShape `json:"-" xml:"-"` -} - -type metadataInputService11TestShapeInputShape struct { - SDKShapeTraits bool `locationName:"OperationRequest" type:"structure" xmlURI:"https://foo/"` -} - -type InputService12ProtocolTest struct { - *service.Service -} - -// New returns a new InputService12ProtocolTest client. -func NewInputService12ProtocolTest(config *aws.Config) *InputService12ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "inputservice12protocoltest", - APIVersion: "2014-01-01", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(restxml.Build) - service.Handlers.Unmarshal.PushBack(restxml.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(restxml.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(restxml.UnmarshalError) - - return &InputService12ProtocolTest{service} -} - -// newRequest creates a new request for a InputService12ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService12ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opInputService12TestCaseOperation1 = "OperationName" - -// InputService12TestCaseOperation1Request generates a request for the InputService12TestCaseOperation1 operation. -func (c *InputService12ProtocolTest) InputService12TestCaseOperation1Request(input *InputService12TestShapeInputShape) (req *service.Request, output *InputService12TestShapeInputService12TestCaseOperation1Output) { - op := &service.Operation{ - Name: opInputService12TestCaseOperation1, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &InputService12TestShapeInputShape{} - } - - req = c.newRequest(op, input, output) - output = &InputService12TestShapeInputService12TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService12ProtocolTest) InputService12TestCaseOperation1(input *InputService12TestShapeInputShape) (*InputService12TestShapeInputService12TestCaseOperation1Output, error) { - req, out := c.InputService12TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type InputService12TestShapeInputService12TestCaseOperation1Output struct { - metadataInputService12TestShapeInputService12TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataInputService12TestShapeInputService12TestCaseOperation1Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService12TestShapeInputShape struct { - Foo *string `locationName:"foo" type:"string"` - - metadataInputService12TestShapeInputShape `json:"-" xml:"-"` -} - -type metadataInputService12TestShapeInputShape struct { - SDKShapeTraits bool `type:"structure" payload:"Foo"` -} - -type InputService13ProtocolTest struct { - *service.Service -} - -// New returns a new InputService13ProtocolTest client. -func NewInputService13ProtocolTest(config *aws.Config) *InputService13ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "inputservice13protocoltest", - APIVersion: "2014-01-01", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(restxml.Build) - service.Handlers.Unmarshal.PushBack(restxml.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(restxml.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(restxml.UnmarshalError) - - return &InputService13ProtocolTest{service} -} - -// newRequest creates a new request for a InputService13ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService13ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opInputService13TestCaseOperation1 = "OperationName" - -// InputService13TestCaseOperation1Request generates a request for the InputService13TestCaseOperation1 operation. -func (c *InputService13ProtocolTest) InputService13TestCaseOperation1Request(input *InputService13TestShapeInputShape) (req *service.Request, output *InputService13TestShapeInputService13TestCaseOperation1Output) { - op := &service.Operation{ - Name: opInputService13TestCaseOperation1, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &InputService13TestShapeInputShape{} - } - - req = c.newRequest(op, input, output) - output = &InputService13TestShapeInputService13TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService13ProtocolTest) InputService13TestCaseOperation1(input *InputService13TestShapeInputShape) (*InputService13TestShapeInputService13TestCaseOperation1Output, error) { - req, out := c.InputService13TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -const opInputService13TestCaseOperation2 = "OperationName" - -// InputService13TestCaseOperation2Request generates a request for the InputService13TestCaseOperation2 operation. -func (c *InputService13ProtocolTest) InputService13TestCaseOperation2Request(input *InputService13TestShapeInputShape) (req *service.Request, output *InputService13TestShapeInputService13TestCaseOperation2Output) { - op := &service.Operation{ - Name: opInputService13TestCaseOperation2, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &InputService13TestShapeInputShape{} - } - - req = c.newRequest(op, input, output) - output = &InputService13TestShapeInputService13TestCaseOperation2Output{} - req.Data = output - return -} - -func (c *InputService13ProtocolTest) InputService13TestCaseOperation2(input *InputService13TestShapeInputShape) (*InputService13TestShapeInputService13TestCaseOperation2Output, error) { - req, out := c.InputService13TestCaseOperation2Request(input) - err := req.Send() - return out, err -} - -type InputService13TestShapeInputService13TestCaseOperation1Output struct { - metadataInputService13TestShapeInputService13TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataInputService13TestShapeInputService13TestCaseOperation1Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService13TestShapeInputService13TestCaseOperation2Output struct { - metadataInputService13TestShapeInputService13TestCaseOperation2Output `json:"-" xml:"-"` -} - -type metadataInputService13TestShapeInputService13TestCaseOperation2Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService13TestShapeInputShape struct { - Foo []byte `locationName:"foo" type:"blob"` - - metadataInputService13TestShapeInputShape `json:"-" xml:"-"` -} - -type metadataInputService13TestShapeInputShape struct { - SDKShapeTraits bool `type:"structure" payload:"Foo"` -} - -type InputService14ProtocolTest struct { - *service.Service -} - -// New returns a new InputService14ProtocolTest client. -func NewInputService14ProtocolTest(config *aws.Config) *InputService14ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "inputservice14protocoltest", - APIVersion: "2014-01-01", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(restxml.Build) - service.Handlers.Unmarshal.PushBack(restxml.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(restxml.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(restxml.UnmarshalError) - - return &InputService14ProtocolTest{service} -} - -// newRequest creates a new request for a InputService14ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService14ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opInputService14TestCaseOperation1 = "OperationName" - -// InputService14TestCaseOperation1Request generates a request for the InputService14TestCaseOperation1 operation. -func (c *InputService14ProtocolTest) InputService14TestCaseOperation1Request(input *InputService14TestShapeInputShape) (req *service.Request, output *InputService14TestShapeInputService14TestCaseOperation1Output) { - op := &service.Operation{ - Name: opInputService14TestCaseOperation1, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &InputService14TestShapeInputShape{} - } - - req = c.newRequest(op, input, output) - output = &InputService14TestShapeInputService14TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService14ProtocolTest) InputService14TestCaseOperation1(input *InputService14TestShapeInputShape) (*InputService14TestShapeInputService14TestCaseOperation1Output, error) { - req, out := c.InputService14TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -const opInputService14TestCaseOperation2 = "OperationName" - -// InputService14TestCaseOperation2Request generates a request for the InputService14TestCaseOperation2 operation. -func (c *InputService14ProtocolTest) InputService14TestCaseOperation2Request(input *InputService14TestShapeInputShape) (req *service.Request, output *InputService14TestShapeInputService14TestCaseOperation2Output) { - op := &service.Operation{ - Name: opInputService14TestCaseOperation2, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &InputService14TestShapeInputShape{} - } - - req = c.newRequest(op, input, output) - output = &InputService14TestShapeInputService14TestCaseOperation2Output{} - req.Data = output - return -} - -func (c *InputService14ProtocolTest) InputService14TestCaseOperation2(input *InputService14TestShapeInputShape) (*InputService14TestShapeInputService14TestCaseOperation2Output, error) { - req, out := c.InputService14TestCaseOperation2Request(input) - err := req.Send() - return out, err -} - -const opInputService14TestCaseOperation3 = "OperationName" - -// InputService14TestCaseOperation3Request generates a request for the InputService14TestCaseOperation3 operation. -func (c *InputService14ProtocolTest) InputService14TestCaseOperation3Request(input *InputService14TestShapeInputShape) (req *service.Request, output *InputService14TestShapeInputService14TestCaseOperation3Output) { - op := &service.Operation{ - Name: opInputService14TestCaseOperation3, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &InputService14TestShapeInputShape{} - } - - req = c.newRequest(op, input, output) - output = &InputService14TestShapeInputService14TestCaseOperation3Output{} - req.Data = output - return -} - -func (c *InputService14ProtocolTest) InputService14TestCaseOperation3(input *InputService14TestShapeInputShape) (*InputService14TestShapeInputService14TestCaseOperation3Output, error) { - req, out := c.InputService14TestCaseOperation3Request(input) - err := req.Send() - return out, err -} - -type InputService14TestShapeFooShape struct { - Baz *string `locationName:"baz" type:"string"` - - metadataInputService14TestShapeFooShape `json:"-" xml:"-"` -} - -type metadataInputService14TestShapeFooShape struct { - SDKShapeTraits bool `locationName:"foo" type:"structure"` -} - -type InputService14TestShapeInputService14TestCaseOperation1Output struct { - metadataInputService14TestShapeInputService14TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataInputService14TestShapeInputService14TestCaseOperation1Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService14TestShapeInputService14TestCaseOperation2Output struct { - metadataInputService14TestShapeInputService14TestCaseOperation2Output `json:"-" xml:"-"` -} - -type metadataInputService14TestShapeInputService14TestCaseOperation2Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService14TestShapeInputService14TestCaseOperation3Output struct { - metadataInputService14TestShapeInputService14TestCaseOperation3Output `json:"-" xml:"-"` -} - -type metadataInputService14TestShapeInputService14TestCaseOperation3Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService14TestShapeInputShape struct { - Foo *InputService14TestShapeFooShape `locationName:"foo" type:"structure"` - - metadataInputService14TestShapeInputShape `json:"-" xml:"-"` -} - -type metadataInputService14TestShapeInputShape struct { - SDKShapeTraits bool `type:"structure" payload:"Foo"` -} - -type InputService15ProtocolTest struct { - *service.Service -} - -// New returns a new InputService15ProtocolTest client. -func NewInputService15ProtocolTest(config *aws.Config) *InputService15ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "inputservice15protocoltest", - APIVersion: "2014-01-01", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(restxml.Build) - service.Handlers.Unmarshal.PushBack(restxml.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(restxml.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(restxml.UnmarshalError) - - return &InputService15ProtocolTest{service} -} - -// newRequest creates a new request for a InputService15ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService15ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opInputService15TestCaseOperation1 = "OperationName" - -// InputService15TestCaseOperation1Request generates a request for the InputService15TestCaseOperation1 operation. -func (c *InputService15ProtocolTest) InputService15TestCaseOperation1Request(input *InputService15TestShapeInputShape) (req *service.Request, output *InputService15TestShapeInputService15TestCaseOperation1Output) { - op := &service.Operation{ - Name: opInputService15TestCaseOperation1, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &InputService15TestShapeInputShape{} - } - - req = c.newRequest(op, input, output) - output = &InputService15TestShapeInputService15TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService15ProtocolTest) InputService15TestCaseOperation1(input *InputService15TestShapeInputShape) (*InputService15TestShapeInputService15TestCaseOperation1Output, error) { - req, out := c.InputService15TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type InputService15TestShapeGrant struct { - Grantee *InputService15TestShapeGrantee `type:"structure"` - - metadataInputService15TestShapeGrant `json:"-" xml:"-"` -} - -type metadataInputService15TestShapeGrant struct { - SDKShapeTraits bool `locationName:"Grant" type:"structure"` -} - -type InputService15TestShapeGrantee struct { - EmailAddress *string `type:"string"` - - Type *string `locationName:"xsi:type" type:"string" xmlAttribute:"true"` - - metadataInputService15TestShapeGrantee `json:"-" xml:"-"` -} - -type metadataInputService15TestShapeGrantee struct { - SDKShapeTraits bool `type:"structure" xmlPrefix:"xsi" xmlURI:"http://www.w3.org/2001/XMLSchema-instance"` -} - -type InputService15TestShapeInputService15TestCaseOperation1Output struct { - metadataInputService15TestShapeInputService15TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataInputService15TestShapeInputService15TestCaseOperation1Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService15TestShapeInputShape struct { - Grant *InputService15TestShapeGrant `locationName:"Grant" type:"structure"` - - metadataInputService15TestShapeInputShape `json:"-" xml:"-"` -} - -type metadataInputService15TestShapeInputShape struct { - SDKShapeTraits bool `type:"structure" payload:"Grant"` -} - -type InputService16ProtocolTest struct { - *service.Service -} - -// New returns a new InputService16ProtocolTest client. -func NewInputService16ProtocolTest(config *aws.Config) *InputService16ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "inputservice16protocoltest", - APIVersion: "2014-01-01", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(restxml.Build) - service.Handlers.Unmarshal.PushBack(restxml.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(restxml.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(restxml.UnmarshalError) - - return &InputService16ProtocolTest{service} -} - -// newRequest creates a new request for a InputService16ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService16ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opInputService16TestCaseOperation1 = "OperationName" - -// InputService16TestCaseOperation1Request generates a request for the InputService16TestCaseOperation1 operation. -func (c *InputService16ProtocolTest) InputService16TestCaseOperation1Request(input *InputService16TestShapeInputShape) (req *service.Request, output *InputService16TestShapeInputService16TestCaseOperation1Output) { - op := &service.Operation{ - Name: opInputService16TestCaseOperation1, - HTTPMethod: "GET", - HTTPPath: "/{Bucket}/{Key+}", - } - - if input == nil { - input = &InputService16TestShapeInputShape{} - } - - req = c.newRequest(op, input, output) - output = &InputService16TestShapeInputService16TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService16ProtocolTest) InputService16TestCaseOperation1(input *InputService16TestShapeInputShape) (*InputService16TestShapeInputService16TestCaseOperation1Output, error) { - req, out := c.InputService16TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type InputService16TestShapeInputService16TestCaseOperation1Output struct { - metadataInputService16TestShapeInputService16TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataInputService16TestShapeInputService16TestCaseOperation1Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService16TestShapeInputShape struct { - Bucket *string `location:"uri" type:"string"` - - Key *string `location:"uri" type:"string"` - - metadataInputService16TestShapeInputShape `json:"-" xml:"-"` -} - -type metadataInputService16TestShapeInputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService17ProtocolTest struct { - *service.Service -} - -// New returns a new InputService17ProtocolTest client. -func NewInputService17ProtocolTest(config *aws.Config) *InputService17ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "inputservice17protocoltest", - APIVersion: "2014-01-01", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(restxml.Build) - service.Handlers.Unmarshal.PushBack(restxml.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(restxml.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(restxml.UnmarshalError) - - return &InputService17ProtocolTest{service} -} - -// newRequest creates a new request for a InputService17ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService17ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opInputService17TestCaseOperation1 = "OperationName" - -// InputService17TestCaseOperation1Request generates a request for the InputService17TestCaseOperation1 operation. -func (c *InputService17ProtocolTest) InputService17TestCaseOperation1Request(input *InputService17TestShapeInputShape) (req *service.Request, output *InputService17TestShapeInputService17TestCaseOperation1Output) { - op := &service.Operation{ - Name: opInputService17TestCaseOperation1, - HTTPMethod: "POST", - HTTPPath: "/path", - } - - if input == nil { - input = &InputService17TestShapeInputShape{} - } - - req = c.newRequest(op, input, output) - output = &InputService17TestShapeInputService17TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService17ProtocolTest) InputService17TestCaseOperation1(input *InputService17TestShapeInputShape) (*InputService17TestShapeInputService17TestCaseOperation1Output, error) { - req, out := c.InputService17TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -const opInputService17TestCaseOperation2 = "OperationName" - -// InputService17TestCaseOperation2Request generates a request for the InputService17TestCaseOperation2 operation. -func (c *InputService17ProtocolTest) InputService17TestCaseOperation2Request(input *InputService17TestShapeInputShape) (req *service.Request, output *InputService17TestShapeInputService17TestCaseOperation2Output) { - op := &service.Operation{ - Name: opInputService17TestCaseOperation2, - HTTPMethod: "POST", - HTTPPath: "/path?abc=mno", - } - - if input == nil { - input = &InputService17TestShapeInputShape{} - } - - req = c.newRequest(op, input, output) - output = &InputService17TestShapeInputService17TestCaseOperation2Output{} - req.Data = output - return -} - -func (c *InputService17ProtocolTest) InputService17TestCaseOperation2(input *InputService17TestShapeInputShape) (*InputService17TestShapeInputService17TestCaseOperation2Output, error) { - req, out := c.InputService17TestCaseOperation2Request(input) - err := req.Send() - return out, err -} - -type InputService17TestShapeInputService17TestCaseOperation1Output struct { - metadataInputService17TestShapeInputService17TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataInputService17TestShapeInputService17TestCaseOperation1Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService17TestShapeInputService17TestCaseOperation2Output struct { - metadataInputService17TestShapeInputService17TestCaseOperation2Output `json:"-" xml:"-"` -} - -type metadataInputService17TestShapeInputService17TestCaseOperation2Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService17TestShapeInputShape struct { - Foo *string `location:"querystring" locationName:"param-name" type:"string"` - - metadataInputService17TestShapeInputShape `json:"-" xml:"-"` -} - -type metadataInputService17TestShapeInputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService18ProtocolTest struct { - *service.Service -} - -// New returns a new InputService18ProtocolTest client. -func NewInputService18ProtocolTest(config *aws.Config) *InputService18ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "inputservice18protocoltest", - APIVersion: "2014-01-01", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(restxml.Build) - service.Handlers.Unmarshal.PushBack(restxml.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(restxml.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(restxml.UnmarshalError) - - return &InputService18ProtocolTest{service} -} - -// newRequest creates a new request for a InputService18ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService18ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opInputService18TestCaseOperation1 = "OperationName" - -// InputService18TestCaseOperation1Request generates a request for the InputService18TestCaseOperation1 operation. -func (c *InputService18ProtocolTest) InputService18TestCaseOperation1Request(input *InputService18TestShapeInputShape) (req *service.Request, output *InputService18TestShapeInputService18TestCaseOperation1Output) { - op := &service.Operation{ - Name: opInputService18TestCaseOperation1, - HTTPMethod: "POST", - HTTPPath: "/path", - } - - if input == nil { - input = &InputService18TestShapeInputShape{} - } - - req = c.newRequest(op, input, output) - output = &InputService18TestShapeInputService18TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService18ProtocolTest) InputService18TestCaseOperation1(input *InputService18TestShapeInputShape) (*InputService18TestShapeInputService18TestCaseOperation1Output, error) { - req, out := c.InputService18TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -const opInputService18TestCaseOperation2 = "OperationName" - -// InputService18TestCaseOperation2Request generates a request for the InputService18TestCaseOperation2 operation. -func (c *InputService18ProtocolTest) InputService18TestCaseOperation2Request(input *InputService18TestShapeInputShape) (req *service.Request, output *InputService18TestShapeInputService18TestCaseOperation2Output) { - op := &service.Operation{ - Name: opInputService18TestCaseOperation2, - HTTPMethod: "POST", - HTTPPath: "/path", - } - - if input == nil { - input = &InputService18TestShapeInputShape{} - } - - req = c.newRequest(op, input, output) - output = &InputService18TestShapeInputService18TestCaseOperation2Output{} - req.Data = output - return -} - -func (c *InputService18ProtocolTest) InputService18TestCaseOperation2(input *InputService18TestShapeInputShape) (*InputService18TestShapeInputService18TestCaseOperation2Output, error) { - req, out := c.InputService18TestCaseOperation2Request(input) - err := req.Send() - return out, err -} - -const opInputService18TestCaseOperation3 = "OperationName" - -// InputService18TestCaseOperation3Request generates a request for the InputService18TestCaseOperation3 operation. -func (c *InputService18ProtocolTest) InputService18TestCaseOperation3Request(input *InputService18TestShapeInputShape) (req *service.Request, output *InputService18TestShapeInputService18TestCaseOperation3Output) { - op := &service.Operation{ - Name: opInputService18TestCaseOperation3, - HTTPMethod: "POST", - HTTPPath: "/path", - } - - if input == nil { - input = &InputService18TestShapeInputShape{} - } - - req = c.newRequest(op, input, output) - output = &InputService18TestShapeInputService18TestCaseOperation3Output{} - req.Data = output - return -} - -func (c *InputService18ProtocolTest) InputService18TestCaseOperation3(input *InputService18TestShapeInputShape) (*InputService18TestShapeInputService18TestCaseOperation3Output, error) { - req, out := c.InputService18TestCaseOperation3Request(input) - err := req.Send() - return out, err -} - -const opInputService18TestCaseOperation4 = "OperationName" - -// InputService18TestCaseOperation4Request generates a request for the InputService18TestCaseOperation4 operation. -func (c *InputService18ProtocolTest) InputService18TestCaseOperation4Request(input *InputService18TestShapeInputShape) (req *service.Request, output *InputService18TestShapeInputService18TestCaseOperation4Output) { - op := &service.Operation{ - Name: opInputService18TestCaseOperation4, - HTTPMethod: "POST", - HTTPPath: "/path", - } - - if input == nil { - input = &InputService18TestShapeInputShape{} - } - - req = c.newRequest(op, input, output) - output = &InputService18TestShapeInputService18TestCaseOperation4Output{} - req.Data = output - return -} - -func (c *InputService18ProtocolTest) InputService18TestCaseOperation4(input *InputService18TestShapeInputShape) (*InputService18TestShapeInputService18TestCaseOperation4Output, error) { - req, out := c.InputService18TestCaseOperation4Request(input) - err := req.Send() - return out, err -} - -const opInputService18TestCaseOperation5 = "OperationName" - -// InputService18TestCaseOperation5Request generates a request for the InputService18TestCaseOperation5 operation. -func (c *InputService18ProtocolTest) InputService18TestCaseOperation5Request(input *InputService18TestShapeInputShape) (req *service.Request, output *InputService18TestShapeInputService18TestCaseOperation5Output) { - op := &service.Operation{ - Name: opInputService18TestCaseOperation5, - HTTPMethod: "POST", - HTTPPath: "/path", - } - - if input == nil { - input = &InputService18TestShapeInputShape{} - } - - req = c.newRequest(op, input, output) - output = &InputService18TestShapeInputService18TestCaseOperation5Output{} - req.Data = output - return -} - -func (c *InputService18ProtocolTest) InputService18TestCaseOperation5(input *InputService18TestShapeInputShape) (*InputService18TestShapeInputService18TestCaseOperation5Output, error) { - req, out := c.InputService18TestCaseOperation5Request(input) - err := req.Send() - return out, err -} - -const opInputService18TestCaseOperation6 = "OperationName" - -// InputService18TestCaseOperation6Request generates a request for the InputService18TestCaseOperation6 operation. -func (c *InputService18ProtocolTest) InputService18TestCaseOperation6Request(input *InputService18TestShapeInputShape) (req *service.Request, output *InputService18TestShapeInputService18TestCaseOperation6Output) { - op := &service.Operation{ - Name: opInputService18TestCaseOperation6, - HTTPMethod: "POST", - HTTPPath: "/path", - } - - if input == nil { - input = &InputService18TestShapeInputShape{} - } - - req = c.newRequest(op, input, output) - output = &InputService18TestShapeInputService18TestCaseOperation6Output{} - req.Data = output - return -} - -func (c *InputService18ProtocolTest) InputService18TestCaseOperation6(input *InputService18TestShapeInputShape) (*InputService18TestShapeInputService18TestCaseOperation6Output, error) { - req, out := c.InputService18TestCaseOperation6Request(input) - err := req.Send() - return out, err -} - -type InputService18TestShapeInputService18TestCaseOperation1Output struct { - metadataInputService18TestShapeInputService18TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataInputService18TestShapeInputService18TestCaseOperation1Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService18TestShapeInputService18TestCaseOperation2Output struct { - metadataInputService18TestShapeInputService18TestCaseOperation2Output `json:"-" xml:"-"` -} - -type metadataInputService18TestShapeInputService18TestCaseOperation2Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService18TestShapeInputService18TestCaseOperation3Output struct { - metadataInputService18TestShapeInputService18TestCaseOperation3Output `json:"-" xml:"-"` -} - -type metadataInputService18TestShapeInputService18TestCaseOperation3Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService18TestShapeInputService18TestCaseOperation4Output struct { - metadataInputService18TestShapeInputService18TestCaseOperation4Output `json:"-" xml:"-"` -} - -type metadataInputService18TestShapeInputService18TestCaseOperation4Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService18TestShapeInputService18TestCaseOperation5Output struct { - metadataInputService18TestShapeInputService18TestCaseOperation5Output `json:"-" xml:"-"` -} - -type metadataInputService18TestShapeInputService18TestCaseOperation5Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService18TestShapeInputService18TestCaseOperation6Output struct { - metadataInputService18TestShapeInputService18TestCaseOperation6Output `json:"-" xml:"-"` -} - -type metadataInputService18TestShapeInputService18TestCaseOperation6Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService18TestShapeInputShape struct { - RecursiveStruct *InputService18TestShapeRecursiveStructType `type:"structure"` - - metadataInputService18TestShapeInputShape `json:"-" xml:"-"` -} - -type metadataInputService18TestShapeInputShape struct { - SDKShapeTraits bool `locationName:"OperationRequest" type:"structure" xmlURI:"https://foo/"` -} - -type InputService18TestShapeRecursiveStructType struct { - NoRecurse *string `type:"string"` - - RecursiveList []*InputService18TestShapeRecursiveStructType `type:"list"` - - RecursiveMap map[string]*InputService18TestShapeRecursiveStructType `type:"map"` - - RecursiveStruct *InputService18TestShapeRecursiveStructType `type:"structure"` - - metadataInputService18TestShapeRecursiveStructType `json:"-" xml:"-"` -} - -type metadataInputService18TestShapeRecursiveStructType struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService19ProtocolTest struct { - *service.Service -} - -// New returns a new InputService19ProtocolTest client. -func NewInputService19ProtocolTest(config *aws.Config) *InputService19ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "inputservice19protocoltest", - APIVersion: "2014-01-01", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(restxml.Build) - service.Handlers.Unmarshal.PushBack(restxml.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(restxml.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(restxml.UnmarshalError) - - return &InputService19ProtocolTest{service} -} - -// newRequest creates a new request for a InputService19ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService19ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opInputService19TestCaseOperation1 = "OperationName" - -// InputService19TestCaseOperation1Request generates a request for the InputService19TestCaseOperation1 operation. -func (c *InputService19ProtocolTest) InputService19TestCaseOperation1Request(input *InputService19TestShapeInputShape) (req *service.Request, output *InputService19TestShapeInputService19TestCaseOperation1Output) { - op := &service.Operation{ - Name: opInputService19TestCaseOperation1, - HTTPMethod: "POST", - HTTPPath: "/path", - } - - if input == nil { - input = &InputService19TestShapeInputShape{} - } - - req = c.newRequest(op, input, output) - output = &InputService19TestShapeInputService19TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService19ProtocolTest) InputService19TestCaseOperation1(input *InputService19TestShapeInputShape) (*InputService19TestShapeInputService19TestCaseOperation1Output, error) { - req, out := c.InputService19TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type InputService19TestShapeInputService19TestCaseOperation1Output struct { - metadataInputService19TestShapeInputService19TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataInputService19TestShapeInputService19TestCaseOperation1Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService19TestShapeInputShape struct { - TimeArgInHeader *time.Time `location:"header" locationName:"x-amz-timearg" type:"timestamp" timestampFormat:"rfc822"` - - metadataInputService19TestShapeInputShape `json:"-" xml:"-"` -} - -type metadataInputService19TestShapeInputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -// -// Tests begin here -// - -func TestInputService1ProtocolTestBasicXMLSerializationCase1(t *testing.T) { - svc := NewInputService1ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService1TestShapeInputShape{ - Description: aws.String("bar"), - Name: aws.String("foo"), - } - req, _ := svc.InputService1TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - restxml.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body := util.SortXML(r.Body) - assert.Equal(t, util.Trim(`barfoo`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/2014-01-01/hostedzone", r.URL.String()) - - // assert headers - -} - -func TestInputService1ProtocolTestBasicXMLSerializationCase2(t *testing.T) { - svc := NewInputService1ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService1TestShapeInputShape{ - Description: aws.String("bar"), - Name: aws.String("foo"), - } - req, _ := svc.InputService1TestCaseOperation2Request(input) - r := req.HTTPRequest - - // build request - restxml.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body := util.SortXML(r.Body) - assert.Equal(t, util.Trim(`barfoo`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/2014-01-01/hostedzone", r.URL.String()) - - // assert headers - -} - -func TestInputService2ProtocolTestSerializeOtherScalarTypesCase1(t *testing.T) { - svc := NewInputService2ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService2TestShapeInputShape{ - First: aws.Bool(true), - Fourth: aws.Int64(3), - Second: aws.Bool(false), - Third: aws.Float64(1.2), - } - req, _ := svc.InputService2TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - restxml.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body := util.SortXML(r.Body) - assert.Equal(t, util.Trim(`true3false1.2`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/2014-01-01/hostedzone", r.URL.String()) - - // assert headers - -} - -func TestInputService3ProtocolTestNestedStructuresCase1(t *testing.T) { - svc := NewInputService3ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService3TestShapeInputShape{ - Description: aws.String("baz"), - SubStructure: &InputService3TestShapeSubStructure{ - Bar: aws.String("b"), - Foo: aws.String("a"), - }, - } - req, _ := svc.InputService3TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - restxml.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body := util.SortXML(r.Body) - assert.Equal(t, util.Trim(`bazba`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/2014-01-01/hostedzone", r.URL.String()) - - // assert headers - -} - -func TestInputService4ProtocolTestNestedStructuresCase1(t *testing.T) { - svc := NewInputService4ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService4TestShapeInputShape{ - Description: aws.String("baz"), - SubStructure: &InputService4TestShapeSubStructure{}, - } - req, _ := svc.InputService4TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - restxml.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body := util.SortXML(r.Body) - assert.Equal(t, util.Trim(`baz`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/2014-01-01/hostedzone", r.URL.String()) - - // assert headers - -} - -func TestInputService5ProtocolTestNonFlattenedListsCase1(t *testing.T) { - svc := NewInputService5ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService5TestShapeInputShape{ - ListParam: []*string{ - aws.String("one"), - aws.String("two"), - aws.String("three"), - }, - } - req, _ := svc.InputService5TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - restxml.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body := util.SortXML(r.Body) - assert.Equal(t, util.Trim(`onetwothree`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/2014-01-01/hostedzone", r.URL.String()) - - // assert headers - -} - -func TestInputService6ProtocolTestNonFlattenedListsWithLocationNameCase1(t *testing.T) { - svc := NewInputService6ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService6TestShapeInputShape{ - ListParam: []*string{ - aws.String("one"), - aws.String("two"), - aws.String("three"), - }, - } - req, _ := svc.InputService6TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - restxml.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body := util.SortXML(r.Body) - assert.Equal(t, util.Trim(`onetwothree`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/2014-01-01/hostedzone", r.URL.String()) - - // assert headers - -} - -func TestInputService7ProtocolTestFlattenedListsCase1(t *testing.T) { - svc := NewInputService7ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService7TestShapeInputShape{ - ListParam: []*string{ - aws.String("one"), - aws.String("two"), - aws.String("three"), - }, - } - req, _ := svc.InputService7TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - restxml.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body := util.SortXML(r.Body) - assert.Equal(t, util.Trim(`onetwothree`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/2014-01-01/hostedzone", r.URL.String()) - - // assert headers - -} - -func TestInputService8ProtocolTestFlattenedListsWithLocationNameCase1(t *testing.T) { - svc := NewInputService8ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService8TestShapeInputShape{ - ListParam: []*string{ - aws.String("one"), - aws.String("two"), - aws.String("three"), - }, - } - req, _ := svc.InputService8TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - restxml.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body := util.SortXML(r.Body) - assert.Equal(t, util.Trim(`onetwothree`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/2014-01-01/hostedzone", r.URL.String()) - - // assert headers - -} - -func TestInputService9ProtocolTestListOfStructuresCase1(t *testing.T) { - svc := NewInputService9ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService9TestShapeInputShape{ - ListParam: []*InputService9TestShapeSingleFieldStruct{ - { - Element: aws.String("one"), - }, - { - Element: aws.String("two"), - }, - { - Element: aws.String("three"), - }, - }, - } - req, _ := svc.InputService9TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - restxml.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body := util.SortXML(r.Body) - assert.Equal(t, util.Trim(`onetwothree`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/2014-01-01/hostedzone", r.URL.String()) - - // assert headers - -} - -func TestInputService10ProtocolTestBlobAndTimestampShapesCase1(t *testing.T) { - svc := NewInputService10ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService10TestShapeInputShape{ - StructureParam: &InputService10TestShapeStructureShape{ - B: []byte("foo"), - T: aws.Time(time.Unix(1422172800, 0)), - }, - } - req, _ := svc.InputService10TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - restxml.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body := util.SortXML(r.Body) - assert.Equal(t, util.Trim(`Zm9v2015-01-25T08:00:00Z`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/2014-01-01/hostedzone", r.URL.String()) - - // assert headers - -} - -func TestInputService11ProtocolTestHeaderMapsCase1(t *testing.T) { - svc := NewInputService11ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService11TestShapeInputShape{ - Foo: map[string]*string{ - "a": aws.String("b"), - "c": aws.String("d"), - }, - } - req, _ := svc.InputService11TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - restxml.Build(req) - assert.NoError(t, req.Error) - - // assert URL - assert.Equal(t, "https://test/", r.URL.String()) - - // assert headers - assert.Equal(t, "b", r.Header.Get("x-foo-a")) - assert.Equal(t, "d", r.Header.Get("x-foo-c")) - -} - -func TestInputService12ProtocolTestStringPayloadCase1(t *testing.T) { - svc := NewInputService12ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService12TestShapeInputShape{ - Foo: aws.String("bar"), - } - req, _ := svc.InputService12TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - restxml.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body := util.SortXML(r.Body) - assert.Equal(t, util.Trim(`bar`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService13ProtocolTestBlobPayloadCase1(t *testing.T) { - svc := NewInputService13ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService13TestShapeInputShape{ - Foo: []byte("bar"), - } - req, _ := svc.InputService13TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - restxml.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body := util.SortXML(r.Body) - assert.Equal(t, util.Trim(`bar`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService13ProtocolTestBlobPayloadCase2(t *testing.T) { - svc := NewInputService13ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService13TestShapeInputShape{} - req, _ := svc.InputService13TestCaseOperation2Request(input) - r := req.HTTPRequest - - // build request - restxml.Build(req) - assert.NoError(t, req.Error) - - // assert URL - assert.Equal(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService14ProtocolTestStructurePayloadCase1(t *testing.T) { - svc := NewInputService14ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService14TestShapeInputShape{ - Foo: &InputService14TestShapeFooShape{ - Baz: aws.String("bar"), - }, - } - req, _ := svc.InputService14TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - restxml.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body := util.SortXML(r.Body) - assert.Equal(t, util.Trim(`bar`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService14ProtocolTestStructurePayloadCase2(t *testing.T) { - svc := NewInputService14ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService14TestShapeInputShape{ - Foo: &InputService14TestShapeFooShape{}, - } - req, _ := svc.InputService14TestCaseOperation2Request(input) - r := req.HTTPRequest - - // build request - restxml.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body := util.SortXML(r.Body) - assert.Equal(t, util.Trim(``), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService14ProtocolTestStructurePayloadCase3(t *testing.T) { - svc := NewInputService14ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService14TestShapeInputShape{} - req, _ := svc.InputService14TestCaseOperation3Request(input) - r := req.HTTPRequest - - // build request - restxml.Build(req) - assert.NoError(t, req.Error) - - // assert URL - assert.Equal(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService15ProtocolTestXMLAttributeCase1(t *testing.T) { - svc := NewInputService15ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService15TestShapeInputShape{ - Grant: &InputService15TestShapeGrant{ - Grantee: &InputService15TestShapeGrantee{ - EmailAddress: aws.String("foo@example.com"), - Type: aws.String("CanonicalUser"), - }, - }, - } - req, _ := svc.InputService15TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - restxml.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body := util.SortXML(r.Body) - assert.Equal(t, util.Trim(`foo@example.com`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService16ProtocolTestGreedyKeysCase1(t *testing.T) { - svc := NewInputService16ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService16TestShapeInputShape{ - Bucket: aws.String("my/bucket"), - Key: aws.String("testing /123"), - } - req, _ := svc.InputService16TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - restxml.Build(req) - assert.NoError(t, req.Error) - - // assert URL - assert.Equal(t, "https://test/my%2Fbucket/testing%20/123", r.URL.String()) - - // assert headers - -} - -func TestInputService17ProtocolTestOmitsNullQueryParamsButSerializesEmptyStringsCase1(t *testing.T) { - svc := NewInputService17ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService17TestShapeInputShape{} - req, _ := svc.InputService17TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - restxml.Build(req) - assert.NoError(t, req.Error) - - // assert URL - assert.Equal(t, "https://test/path", r.URL.String()) - - // assert headers - -} - -func TestInputService17ProtocolTestOmitsNullQueryParamsButSerializesEmptyStringsCase2(t *testing.T) { - svc := NewInputService17ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService17TestShapeInputShape{ - Foo: aws.String(""), - } - req, _ := svc.InputService17TestCaseOperation2Request(input) - r := req.HTTPRequest - - // build request - restxml.Build(req) - assert.NoError(t, req.Error) - - // assert URL - assert.Equal(t, "https://test/path?abc=mno¶m-name=", r.URL.String()) - - // assert headers - -} - -func TestInputService18ProtocolTestRecursiveShapesCase1(t *testing.T) { - svc := NewInputService18ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService18TestShapeInputShape{ - RecursiveStruct: &InputService18TestShapeRecursiveStructType{ - NoRecurse: aws.String("foo"), - }, - } - req, _ := svc.InputService18TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - restxml.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body := util.SortXML(r.Body) - assert.Equal(t, util.Trim(`foo`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/path", r.URL.String()) - - // assert headers - -} - -func TestInputService18ProtocolTestRecursiveShapesCase2(t *testing.T) { - svc := NewInputService18ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService18TestShapeInputShape{ - RecursiveStruct: &InputService18TestShapeRecursiveStructType{ - RecursiveStruct: &InputService18TestShapeRecursiveStructType{ - NoRecurse: aws.String("foo"), - }, - }, - } - req, _ := svc.InputService18TestCaseOperation2Request(input) - r := req.HTTPRequest - - // build request - restxml.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body := util.SortXML(r.Body) - assert.Equal(t, util.Trim(`foo`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/path", r.URL.String()) - - // assert headers - -} - -func TestInputService18ProtocolTestRecursiveShapesCase3(t *testing.T) { - svc := NewInputService18ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService18TestShapeInputShape{ - RecursiveStruct: &InputService18TestShapeRecursiveStructType{ - RecursiveStruct: &InputService18TestShapeRecursiveStructType{ - RecursiveStruct: &InputService18TestShapeRecursiveStructType{ - RecursiveStruct: &InputService18TestShapeRecursiveStructType{ - NoRecurse: aws.String("foo"), - }, - }, - }, - }, - } - req, _ := svc.InputService18TestCaseOperation3Request(input) - r := req.HTTPRequest - - // build request - restxml.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body := util.SortXML(r.Body) - assert.Equal(t, util.Trim(`foo`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/path", r.URL.String()) - - // assert headers - -} - -func TestInputService18ProtocolTestRecursiveShapesCase4(t *testing.T) { - svc := NewInputService18ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService18TestShapeInputShape{ - RecursiveStruct: &InputService18TestShapeRecursiveStructType{ - RecursiveList: []*InputService18TestShapeRecursiveStructType{ - { - NoRecurse: aws.String("foo"), - }, - { - NoRecurse: aws.String("bar"), - }, - }, - }, - } - req, _ := svc.InputService18TestCaseOperation4Request(input) - r := req.HTTPRequest - - // build request - restxml.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body := util.SortXML(r.Body) - assert.Equal(t, util.Trim(`foobar`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/path", r.URL.String()) - - // assert headers - -} - -func TestInputService18ProtocolTestRecursiveShapesCase5(t *testing.T) { - svc := NewInputService18ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService18TestShapeInputShape{ - RecursiveStruct: &InputService18TestShapeRecursiveStructType{ - RecursiveList: []*InputService18TestShapeRecursiveStructType{ - { - NoRecurse: aws.String("foo"), - }, - { - RecursiveStruct: &InputService18TestShapeRecursiveStructType{ - NoRecurse: aws.String("bar"), - }, - }, - }, - }, - } - req, _ := svc.InputService18TestCaseOperation5Request(input) - r := req.HTTPRequest - - // build request - restxml.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body := util.SortXML(r.Body) - assert.Equal(t, util.Trim(`foobar`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/path", r.URL.String()) - - // assert headers - -} - -func TestInputService18ProtocolTestRecursiveShapesCase6(t *testing.T) { - svc := NewInputService18ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService18TestShapeInputShape{ - RecursiveStruct: &InputService18TestShapeRecursiveStructType{ - RecursiveMap: map[string]*InputService18TestShapeRecursiveStructType{ - "bar": { - NoRecurse: aws.String("bar"), - }, - "foo": { - NoRecurse: aws.String("foo"), - }, - }, - }, - } - req, _ := svc.InputService18TestCaseOperation6Request(input) - r := req.HTTPRequest - - // build request - restxml.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body := util.SortXML(r.Body) - assert.Equal(t, util.Trim(`barbarfoofoo`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/path", r.URL.String()) - - // assert headers - -} - -func TestInputService19ProtocolTestTimestampInHeaderCase1(t *testing.T) { - svc := NewInputService19ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService19TestShapeInputShape{ - TimeArgInHeader: aws.Time(time.Unix(1422172800, 0)), - } - req, _ := svc.InputService19TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - restxml.Build(req) - assert.NoError(t, req.Error) - - // assert URL - assert.Equal(t, "https://test/path", r.URL.String()) - - // assert headers - assert.Equal(t, "Sun, 25 Jan 2015 08:00:00 GMT", r.Header.Get("x-amz-timearg")) - -} diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/restxml/restxml.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/restxml/restxml.go index b56e5c7db..1e88f901b 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/restxml/restxml.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/restxml/restxml.go @@ -10,21 +10,21 @@ import ( "encoding/xml" "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/service" + "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/internal/protocol/query" "github.com/aws/aws-sdk-go/internal/protocol/rest" "github.com/aws/aws-sdk-go/internal/protocol/xml/xmlutil" ) // Build builds a request payload for the REST XML protocol. -func Build(r *service.Request) { +func Build(r *request.Request) { rest.Build(r) if t := rest.PayloadType(r.Params); t == "structure" || t == "" { var buf bytes.Buffer err := xmlutil.BuildXML(r.Params, xml.NewEncoder(&buf)) if err != nil { - r.Error = awserr.New("SerializationError", "failed to enode rest XML request", err) + r.Error = awserr.New("SerializationError", "failed to encode rest XML request", err) return } r.SetBufferBody(buf.Bytes()) @@ -32,7 +32,7 @@ func Build(r *service.Request) { } // Unmarshal unmarshals a payload response for the REST XML protocol. -func Unmarshal(r *service.Request) { +func Unmarshal(r *request.Request) { if t := rest.PayloadType(r.Data); t == "structure" || t == "" { defer r.HTTPResponse.Body.Close() decoder := xml.NewDecoder(r.HTTPResponse.Body) @@ -41,15 +41,17 @@ func Unmarshal(r *service.Request) { r.Error = awserr.New("SerializationError", "failed to decode REST XML response", err) return } + } else { + rest.Unmarshal(r) } } // UnmarshalMeta unmarshals response headers for the REST XML protocol. -func UnmarshalMeta(r *service.Request) { - rest.Unmarshal(r) +func UnmarshalMeta(r *request.Request) { + rest.UnmarshalMeta(r) } // UnmarshalError unmarshals a response error for the REST XML protocol. -func UnmarshalError(r *service.Request) { +func UnmarshalError(r *request.Request) { query.UnmarshalError(r) } diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/restxml/unmarshal_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/restxml/unmarshal_test.go deleted file mode 100644 index 8a6af9d66..000000000 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/restxml/unmarshal_test.go +++ /dev/null @@ -1,1312 +0,0 @@ -package restxml_test - -import ( - "bytes" - "encoding/json" - "encoding/xml" - "io" - "io/ioutil" - "net/http" - "net/url" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/defaults" - "github.com/aws/aws-sdk-go/aws/service" - "github.com/aws/aws-sdk-go/internal/protocol/restxml" - "github.com/aws/aws-sdk-go/internal/protocol/xml/xmlutil" - "github.com/aws/aws-sdk-go/internal/signer/v4" - "github.com/aws/aws-sdk-go/internal/util" - "github.com/stretchr/testify/assert" -) - -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 - -type OutputService1ProtocolTest struct { - *service.Service -} - -// New returns a new OutputService1ProtocolTest client. -func NewOutputService1ProtocolTest(config *aws.Config) *OutputService1ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "outputservice1protocoltest", - APIVersion: "", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(restxml.Build) - service.Handlers.Unmarshal.PushBack(restxml.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(restxml.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(restxml.UnmarshalError) - - return &OutputService1ProtocolTest{service} -} - -// newRequest creates a new request for a OutputService1ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService1ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opOutputService1TestCaseOperation1 = "OperationName" - -// OutputService1TestCaseOperation1Request generates a request for the OutputService1TestCaseOperation1 operation. -func (c *OutputService1ProtocolTest) OutputService1TestCaseOperation1Request(input *OutputService1TestShapeOutputService1TestCaseOperation1Input) (req *service.Request, output *OutputService1TestShapeOutputShape) { - op := &service.Operation{ - Name: opOutputService1TestCaseOperation1, - } - - if input == nil { - input = &OutputService1TestShapeOutputService1TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &OutputService1TestShapeOutputShape{} - req.Data = output - return -} - -func (c *OutputService1ProtocolTest) OutputService1TestCaseOperation1(input *OutputService1TestShapeOutputService1TestCaseOperation1Input) (*OutputService1TestShapeOutputShape, error) { - req, out := c.OutputService1TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -const opOutputService1TestCaseOperation2 = "OperationName" - -// OutputService1TestCaseOperation2Request generates a request for the OutputService1TestCaseOperation2 operation. -func (c *OutputService1ProtocolTest) OutputService1TestCaseOperation2Request(input *OutputService1TestShapeOutputService1TestCaseOperation2Input) (req *service.Request, output *OutputService1TestShapeOutputShape) { - op := &service.Operation{ - Name: opOutputService1TestCaseOperation2, - } - - if input == nil { - input = &OutputService1TestShapeOutputService1TestCaseOperation2Input{} - } - - req = c.newRequest(op, input, output) - output = &OutputService1TestShapeOutputShape{} - req.Data = output - return -} - -func (c *OutputService1ProtocolTest) OutputService1TestCaseOperation2(input *OutputService1TestShapeOutputService1TestCaseOperation2Input) (*OutputService1TestShapeOutputShape, error) { - req, out := c.OutputService1TestCaseOperation2Request(input) - err := req.Send() - return out, err -} - -type OutputService1TestShapeOutputService1TestCaseOperation1Input struct { - metadataOutputService1TestShapeOutputService1TestCaseOperation1Input `json:"-" xml:"-"` -} - -type metadataOutputService1TestShapeOutputService1TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService1TestShapeOutputService1TestCaseOperation2Input struct { - metadataOutputService1TestShapeOutputService1TestCaseOperation2Input `json:"-" xml:"-"` -} - -type metadataOutputService1TestShapeOutputService1TestCaseOperation2Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService1TestShapeOutputShape struct { - Char *string `type:"character"` - - Double *float64 `type:"double"` - - FalseBool *bool `type:"boolean"` - - Float *float64 `type:"float"` - - ImaHeader *string `location:"header" type:"string"` - - ImaHeaderLocation *string `location:"header" locationName:"X-Foo" type:"string"` - - 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"` - - metadataOutputService1TestShapeOutputShape `json:"-" xml:"-"` -} - -type metadataOutputService1TestShapeOutputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService2ProtocolTest struct { - *service.Service -} - -// New returns a new OutputService2ProtocolTest client. -func NewOutputService2ProtocolTest(config *aws.Config) *OutputService2ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "outputservice2protocoltest", - APIVersion: "", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(restxml.Build) - service.Handlers.Unmarshal.PushBack(restxml.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(restxml.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(restxml.UnmarshalError) - - return &OutputService2ProtocolTest{service} -} - -// newRequest creates a new request for a OutputService2ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService2ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opOutputService2TestCaseOperation1 = "OperationName" - -// OutputService2TestCaseOperation1Request generates a request for the OutputService2TestCaseOperation1 operation. -func (c *OutputService2ProtocolTest) OutputService2TestCaseOperation1Request(input *OutputService2TestShapeOutputService2TestCaseOperation1Input) (req *service.Request, output *OutputService2TestShapeOutputShape) { - op := &service.Operation{ - Name: opOutputService2TestCaseOperation1, - } - - if input == nil { - input = &OutputService2TestShapeOutputService2TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &OutputService2TestShapeOutputShape{} - req.Data = output - return -} - -func (c *OutputService2ProtocolTest) OutputService2TestCaseOperation1(input *OutputService2TestShapeOutputService2TestCaseOperation1Input) (*OutputService2TestShapeOutputShape, error) { - req, out := c.OutputService2TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type OutputService2TestShapeOutputService2TestCaseOperation1Input struct { - metadataOutputService2TestShapeOutputService2TestCaseOperation1Input `json:"-" xml:"-"` -} - -type metadataOutputService2TestShapeOutputService2TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService2TestShapeOutputShape struct { - Blob []byte `type:"blob"` - - metadataOutputService2TestShapeOutputShape `json:"-" xml:"-"` -} - -type metadataOutputService2TestShapeOutputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService3ProtocolTest struct { - *service.Service -} - -// New returns a new OutputService3ProtocolTest client. -func NewOutputService3ProtocolTest(config *aws.Config) *OutputService3ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "outputservice3protocoltest", - APIVersion: "", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(restxml.Build) - service.Handlers.Unmarshal.PushBack(restxml.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(restxml.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(restxml.UnmarshalError) - - return &OutputService3ProtocolTest{service} -} - -// newRequest creates a new request for a OutputService3ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService3ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opOutputService3TestCaseOperation1 = "OperationName" - -// OutputService3TestCaseOperation1Request generates a request for the OutputService3TestCaseOperation1 operation. -func (c *OutputService3ProtocolTest) OutputService3TestCaseOperation1Request(input *OutputService3TestShapeOutputService3TestCaseOperation1Input) (req *service.Request, output *OutputService3TestShapeOutputShape) { - op := &service.Operation{ - Name: opOutputService3TestCaseOperation1, - } - - if input == nil { - input = &OutputService3TestShapeOutputService3TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &OutputService3TestShapeOutputShape{} - req.Data = output - return -} - -func (c *OutputService3ProtocolTest) OutputService3TestCaseOperation1(input *OutputService3TestShapeOutputService3TestCaseOperation1Input) (*OutputService3TestShapeOutputShape, error) { - req, out := c.OutputService3TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type OutputService3TestShapeOutputService3TestCaseOperation1Input struct { - metadataOutputService3TestShapeOutputService3TestCaseOperation1Input `json:"-" xml:"-"` -} - -type metadataOutputService3TestShapeOutputService3TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService3TestShapeOutputShape struct { - ListMember []*string `type:"list"` - - metadataOutputService3TestShapeOutputShape `json:"-" xml:"-"` -} - -type metadataOutputService3TestShapeOutputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService4ProtocolTest struct { - *service.Service -} - -// New returns a new OutputService4ProtocolTest client. -func NewOutputService4ProtocolTest(config *aws.Config) *OutputService4ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "outputservice4protocoltest", - APIVersion: "", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(restxml.Build) - service.Handlers.Unmarshal.PushBack(restxml.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(restxml.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(restxml.UnmarshalError) - - return &OutputService4ProtocolTest{service} -} - -// newRequest creates a new request for a OutputService4ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService4ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opOutputService4TestCaseOperation1 = "OperationName" - -// OutputService4TestCaseOperation1Request generates a request for the OutputService4TestCaseOperation1 operation. -func (c *OutputService4ProtocolTest) OutputService4TestCaseOperation1Request(input *OutputService4TestShapeOutputService4TestCaseOperation1Input) (req *service.Request, output *OutputService4TestShapeOutputShape) { - op := &service.Operation{ - Name: opOutputService4TestCaseOperation1, - } - - if input == nil { - input = &OutputService4TestShapeOutputService4TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &OutputService4TestShapeOutputShape{} - req.Data = output - return -} - -func (c *OutputService4ProtocolTest) OutputService4TestCaseOperation1(input *OutputService4TestShapeOutputService4TestCaseOperation1Input) (*OutputService4TestShapeOutputShape, error) { - req, out := c.OutputService4TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type OutputService4TestShapeOutputService4TestCaseOperation1Input struct { - metadataOutputService4TestShapeOutputService4TestCaseOperation1Input `json:"-" xml:"-"` -} - -type metadataOutputService4TestShapeOutputService4TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService4TestShapeOutputShape struct { - ListMember []*string `locationNameList:"item" type:"list"` - - metadataOutputService4TestShapeOutputShape `json:"-" xml:"-"` -} - -type metadataOutputService4TestShapeOutputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService5ProtocolTest struct { - *service.Service -} - -// New returns a new OutputService5ProtocolTest client. -func NewOutputService5ProtocolTest(config *aws.Config) *OutputService5ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "outputservice5protocoltest", - APIVersion: "", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(restxml.Build) - service.Handlers.Unmarshal.PushBack(restxml.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(restxml.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(restxml.UnmarshalError) - - return &OutputService5ProtocolTest{service} -} - -// newRequest creates a new request for a OutputService5ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService5ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opOutputService5TestCaseOperation1 = "OperationName" - -// OutputService5TestCaseOperation1Request generates a request for the OutputService5TestCaseOperation1 operation. -func (c *OutputService5ProtocolTest) OutputService5TestCaseOperation1Request(input *OutputService5TestShapeOutputService5TestCaseOperation1Input) (req *service.Request, output *OutputService5TestShapeOutputShape) { - op := &service.Operation{ - Name: opOutputService5TestCaseOperation1, - } - - if input == nil { - input = &OutputService5TestShapeOutputService5TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &OutputService5TestShapeOutputShape{} - req.Data = output - return -} - -func (c *OutputService5ProtocolTest) OutputService5TestCaseOperation1(input *OutputService5TestShapeOutputService5TestCaseOperation1Input) (*OutputService5TestShapeOutputShape, error) { - req, out := c.OutputService5TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type OutputService5TestShapeOutputService5TestCaseOperation1Input struct { - metadataOutputService5TestShapeOutputService5TestCaseOperation1Input `json:"-" xml:"-"` -} - -type metadataOutputService5TestShapeOutputService5TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService5TestShapeOutputShape struct { - ListMember []*string `type:"list" flattened:"true"` - - metadataOutputService5TestShapeOutputShape `json:"-" xml:"-"` -} - -type metadataOutputService5TestShapeOutputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService6ProtocolTest struct { - *service.Service -} - -// New returns a new OutputService6ProtocolTest client. -func NewOutputService6ProtocolTest(config *aws.Config) *OutputService6ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "outputservice6protocoltest", - APIVersion: "", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(restxml.Build) - service.Handlers.Unmarshal.PushBack(restxml.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(restxml.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(restxml.UnmarshalError) - - return &OutputService6ProtocolTest{service} -} - -// newRequest creates a new request for a OutputService6ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService6ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opOutputService6TestCaseOperation1 = "OperationName" - -// OutputService6TestCaseOperation1Request generates a request for the OutputService6TestCaseOperation1 operation. -func (c *OutputService6ProtocolTest) OutputService6TestCaseOperation1Request(input *OutputService6TestShapeOutputService6TestCaseOperation1Input) (req *service.Request, output *OutputService6TestShapeOutputShape) { - op := &service.Operation{ - Name: opOutputService6TestCaseOperation1, - } - - if input == nil { - input = &OutputService6TestShapeOutputService6TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &OutputService6TestShapeOutputShape{} - req.Data = output - return -} - -func (c *OutputService6ProtocolTest) OutputService6TestCaseOperation1(input *OutputService6TestShapeOutputService6TestCaseOperation1Input) (*OutputService6TestShapeOutputShape, error) { - req, out := c.OutputService6TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type OutputService6TestShapeOutputService6TestCaseOperation1Input struct { - metadataOutputService6TestShapeOutputService6TestCaseOperation1Input `json:"-" xml:"-"` -} - -type metadataOutputService6TestShapeOutputService6TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService6TestShapeOutputShape struct { - Map map[string]*OutputService6TestShapeSingleStructure `type:"map"` - - metadataOutputService6TestShapeOutputShape `json:"-" xml:"-"` -} - -type metadataOutputService6TestShapeOutputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService6TestShapeSingleStructure struct { - Foo *string `locationName:"foo" type:"string"` - - metadataOutputService6TestShapeSingleStructure `json:"-" xml:"-"` -} - -type metadataOutputService6TestShapeSingleStructure struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService7ProtocolTest struct { - *service.Service -} - -// New returns a new OutputService7ProtocolTest client. -func NewOutputService7ProtocolTest(config *aws.Config) *OutputService7ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "outputservice7protocoltest", - APIVersion: "", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(restxml.Build) - service.Handlers.Unmarshal.PushBack(restxml.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(restxml.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(restxml.UnmarshalError) - - return &OutputService7ProtocolTest{service} -} - -// newRequest creates a new request for a OutputService7ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService7ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opOutputService7TestCaseOperation1 = "OperationName" - -// OutputService7TestCaseOperation1Request generates a request for the OutputService7TestCaseOperation1 operation. -func (c *OutputService7ProtocolTest) OutputService7TestCaseOperation1Request(input *OutputService7TestShapeOutputService7TestCaseOperation1Input) (req *service.Request, output *OutputService7TestShapeOutputShape) { - op := &service.Operation{ - Name: opOutputService7TestCaseOperation1, - } - - if input == nil { - input = &OutputService7TestShapeOutputService7TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &OutputService7TestShapeOutputShape{} - req.Data = output - return -} - -func (c *OutputService7ProtocolTest) OutputService7TestCaseOperation1(input *OutputService7TestShapeOutputService7TestCaseOperation1Input) (*OutputService7TestShapeOutputShape, error) { - req, out := c.OutputService7TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type OutputService7TestShapeOutputService7TestCaseOperation1Input struct { - metadataOutputService7TestShapeOutputService7TestCaseOperation1Input `json:"-" xml:"-"` -} - -type metadataOutputService7TestShapeOutputService7TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService7TestShapeOutputShape struct { - Map map[string]*string `type:"map" flattened:"true"` - - metadataOutputService7TestShapeOutputShape `json:"-" xml:"-"` -} - -type metadataOutputService7TestShapeOutputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService8ProtocolTest struct { - *service.Service -} - -// New returns a new OutputService8ProtocolTest client. -func NewOutputService8ProtocolTest(config *aws.Config) *OutputService8ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "outputservice8protocoltest", - APIVersion: "", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(restxml.Build) - service.Handlers.Unmarshal.PushBack(restxml.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(restxml.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(restxml.UnmarshalError) - - return &OutputService8ProtocolTest{service} -} - -// newRequest creates a new request for a OutputService8ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService8ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opOutputService8TestCaseOperation1 = "OperationName" - -// OutputService8TestCaseOperation1Request generates a request for the OutputService8TestCaseOperation1 operation. -func (c *OutputService8ProtocolTest) OutputService8TestCaseOperation1Request(input *OutputService8TestShapeOutputService8TestCaseOperation1Input) (req *service.Request, output *OutputService8TestShapeOutputShape) { - op := &service.Operation{ - Name: opOutputService8TestCaseOperation1, - } - - if input == nil { - input = &OutputService8TestShapeOutputService8TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &OutputService8TestShapeOutputShape{} - req.Data = output - return -} - -func (c *OutputService8ProtocolTest) OutputService8TestCaseOperation1(input *OutputService8TestShapeOutputService8TestCaseOperation1Input) (*OutputService8TestShapeOutputShape, error) { - req, out := c.OutputService8TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type OutputService8TestShapeOutputService8TestCaseOperation1Input struct { - metadataOutputService8TestShapeOutputService8TestCaseOperation1Input `json:"-" xml:"-"` -} - -type metadataOutputService8TestShapeOutputService8TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService8TestShapeOutputShape struct { - Map map[string]*string `locationNameKey:"foo" locationNameValue:"bar" type:"map"` - - metadataOutputService8TestShapeOutputShape `json:"-" xml:"-"` -} - -type metadataOutputService8TestShapeOutputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService9ProtocolTest struct { - *service.Service -} - -// New returns a new OutputService9ProtocolTest client. -func NewOutputService9ProtocolTest(config *aws.Config) *OutputService9ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "outputservice9protocoltest", - APIVersion: "", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(restxml.Build) - service.Handlers.Unmarshal.PushBack(restxml.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(restxml.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(restxml.UnmarshalError) - - return &OutputService9ProtocolTest{service} -} - -// newRequest creates a new request for a OutputService9ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService9ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opOutputService9TestCaseOperation1 = "OperationName" - -// OutputService9TestCaseOperation1Request generates a request for the OutputService9TestCaseOperation1 operation. -func (c *OutputService9ProtocolTest) OutputService9TestCaseOperation1Request(input *OutputService9TestShapeOutputService9TestCaseOperation1Input) (req *service.Request, output *OutputService9TestShapeOutputShape) { - op := &service.Operation{ - Name: opOutputService9TestCaseOperation1, - } - - if input == nil { - input = &OutputService9TestShapeOutputService9TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &OutputService9TestShapeOutputShape{} - req.Data = output - return -} - -func (c *OutputService9ProtocolTest) OutputService9TestCaseOperation1(input *OutputService9TestShapeOutputService9TestCaseOperation1Input) (*OutputService9TestShapeOutputShape, error) { - req, out := c.OutputService9TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type OutputService9TestShapeOutputService9TestCaseOperation1Input struct { - metadataOutputService9TestShapeOutputService9TestCaseOperation1Input `json:"-" xml:"-"` -} - -type metadataOutputService9TestShapeOutputService9TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService9TestShapeOutputShape struct { - Data *OutputService9TestShapeSingleStructure `type:"structure"` - - Header *string `location:"header" locationName:"X-Foo" type:"string"` - - metadataOutputService9TestShapeOutputShape `json:"-" xml:"-"` -} - -type metadataOutputService9TestShapeOutputShape struct { - SDKShapeTraits bool `type:"structure" payload:"Data"` -} - -type OutputService9TestShapeSingleStructure struct { - Foo *string `type:"string"` - - metadataOutputService9TestShapeSingleStructure `json:"-" xml:"-"` -} - -type metadataOutputService9TestShapeSingleStructure struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService10ProtocolTest struct { - *service.Service -} - -// New returns a new OutputService10ProtocolTest client. -func NewOutputService10ProtocolTest(config *aws.Config) *OutputService10ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "outputservice10protocoltest", - APIVersion: "", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(restxml.Build) - service.Handlers.Unmarshal.PushBack(restxml.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(restxml.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(restxml.UnmarshalError) - - return &OutputService10ProtocolTest{service} -} - -// newRequest creates a new request for a OutputService10ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService10ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opOutputService10TestCaseOperation1 = "OperationName" - -// OutputService10TestCaseOperation1Request generates a request for the OutputService10TestCaseOperation1 operation. -func (c *OutputService10ProtocolTest) OutputService10TestCaseOperation1Request(input *OutputService10TestShapeOutputService10TestCaseOperation1Input) (req *service.Request, output *OutputService10TestShapeOutputShape) { - op := &service.Operation{ - Name: opOutputService10TestCaseOperation1, - } - - if input == nil { - input = &OutputService10TestShapeOutputService10TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &OutputService10TestShapeOutputShape{} - req.Data = output - return -} - -func (c *OutputService10ProtocolTest) OutputService10TestCaseOperation1(input *OutputService10TestShapeOutputService10TestCaseOperation1Input) (*OutputService10TestShapeOutputShape, error) { - req, out := c.OutputService10TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type OutputService10TestShapeOutputService10TestCaseOperation1Input struct { - metadataOutputService10TestShapeOutputService10TestCaseOperation1Input `json:"-" xml:"-"` -} - -type metadataOutputService10TestShapeOutputService10TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService10TestShapeOutputShape struct { - Stream []byte `type:"blob"` - - metadataOutputService10TestShapeOutputShape `json:"-" xml:"-"` -} - -type metadataOutputService10TestShapeOutputShape struct { - SDKShapeTraits bool `type:"structure" payload:"Stream"` -} - -type OutputService11ProtocolTest struct { - *service.Service -} - -// New returns a new OutputService11ProtocolTest client. -func NewOutputService11ProtocolTest(config *aws.Config) *OutputService11ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "outputservice11protocoltest", - APIVersion: "", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(restxml.Build) - service.Handlers.Unmarshal.PushBack(restxml.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(restxml.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(restxml.UnmarshalError) - - return &OutputService11ProtocolTest{service} -} - -// newRequest creates a new request for a OutputService11ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService11ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opOutputService11TestCaseOperation1 = "OperationName" - -// OutputService11TestCaseOperation1Request generates a request for the OutputService11TestCaseOperation1 operation. -func (c *OutputService11ProtocolTest) OutputService11TestCaseOperation1Request(input *OutputService11TestShapeOutputService11TestCaseOperation1Input) (req *service.Request, output *OutputService11TestShapeOutputShape) { - op := &service.Operation{ - Name: opOutputService11TestCaseOperation1, - } - - if input == nil { - input = &OutputService11TestShapeOutputService11TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &OutputService11TestShapeOutputShape{} - req.Data = output - return -} - -func (c *OutputService11ProtocolTest) OutputService11TestCaseOperation1(input *OutputService11TestShapeOutputService11TestCaseOperation1Input) (*OutputService11TestShapeOutputShape, error) { - req, out := c.OutputService11TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type OutputService11TestShapeOutputService11TestCaseOperation1Input struct { - metadataOutputService11TestShapeOutputService11TestCaseOperation1Input `json:"-" xml:"-"` -} - -type metadataOutputService11TestShapeOutputService11TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService11TestShapeOutputShape struct { - Char *string `location:"header" locationName:"x-char" type:"character"` - - Double *float64 `location:"header" locationName:"x-double" type:"double"` - - FalseBool *bool `location:"header" locationName:"x-false-bool" type:"boolean"` - - Float *float64 `location:"header" locationName:"x-float" type:"float"` - - Integer *int64 `location:"header" locationName:"x-int" type:"integer"` - - Long *int64 `location:"header" locationName:"x-long" type:"long"` - - Str *string `location:"header" locationName:"x-str" type:"string"` - - Timestamp *time.Time `location:"header" locationName:"x-timestamp" type:"timestamp" timestampFormat:"iso8601"` - - TrueBool *bool `location:"header" locationName:"x-true-bool" type:"boolean"` - - metadataOutputService11TestShapeOutputShape `json:"-" xml:"-"` -} - -type metadataOutputService11TestShapeOutputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService12ProtocolTest struct { - *service.Service -} - -// New returns a new OutputService12ProtocolTest client. -func NewOutputService12ProtocolTest(config *aws.Config) *OutputService12ProtocolTest { - service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "outputservice12protocoltest", - APIVersion: "", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(restxml.Build) - service.Handlers.Unmarshal.PushBack(restxml.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(restxml.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(restxml.UnmarshalError) - - return &OutputService12ProtocolTest{service} -} - -// newRequest creates a new request for a OutputService12ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService12ProtocolTest) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) - - return req -} - -const opOutputService12TestCaseOperation1 = "OperationName" - -// OutputService12TestCaseOperation1Request generates a request for the OutputService12TestCaseOperation1 operation. -func (c *OutputService12ProtocolTest) OutputService12TestCaseOperation1Request(input *OutputService12TestShapeOutputService12TestCaseOperation1Input) (req *service.Request, output *OutputService12TestShapeOutputShape) { - op := &service.Operation{ - Name: opOutputService12TestCaseOperation1, - } - - if input == nil { - input = &OutputService12TestShapeOutputService12TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &OutputService12TestShapeOutputShape{} - req.Data = output - return -} - -func (c *OutputService12ProtocolTest) OutputService12TestCaseOperation1(input *OutputService12TestShapeOutputService12TestCaseOperation1Input) (*OutputService12TestShapeOutputShape, error) { - req, out := c.OutputService12TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type OutputService12TestShapeOutputService12TestCaseOperation1Input struct { - metadataOutputService12TestShapeOutputService12TestCaseOperation1Input `json:"-" xml:"-"` -} - -type metadataOutputService12TestShapeOutputService12TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService12TestShapeOutputShape struct { - String *string `type:"string"` - - metadataOutputService12TestShapeOutputShape `json:"-" xml:"-"` -} - -type metadataOutputService12TestShapeOutputShape struct { - SDKShapeTraits bool `type:"structure" payload:"String"` -} - -// -// Tests begin here -// - -func TestOutputService1ProtocolTestScalarMembersCase1(t *testing.T) { - svc := NewOutputService1ProtocolTest(nil) - - buf := bytes.NewReader([]byte("myname123falsetrue1.21.3200a2015-01-25T08:00:00Z")) - req, out := svc.OutputService1TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - req.HTTPResponse.Header.Set("ImaHeader", "test") - req.HTTPResponse.Header.Set("X-Foo", "abc") - - // unmarshal response - restxml.UnmarshalMeta(req) - restxml.Unmarshal(req) - assert.NoError(t, req.Error) - - // assert response - assert.NotNil(t, out) // ensure out variable is used - assert.Equal(t, "a", *out.Char) - assert.Equal(t, 1.3, *out.Double) - assert.Equal(t, false, *out.FalseBool) - assert.Equal(t, 1.2, *out.Float) - assert.Equal(t, "test", *out.ImaHeader) - assert.Equal(t, "abc", *out.ImaHeaderLocation) - assert.Equal(t, int64(200), *out.Long) - assert.Equal(t, int64(123), *out.Num) - assert.Equal(t, "myname", *out.Str) - assert.Equal(t, time.Unix(1.4221728e+09, 0).UTC().String(), out.Timestamp.String()) - assert.Equal(t, true, *out.TrueBool) - -} - -func TestOutputService1ProtocolTestScalarMembersCase2(t *testing.T) { - svc := NewOutputService1ProtocolTest(nil) - - buf := bytes.NewReader([]byte("123falsetrue1.21.3200a2015-01-25T08:00:00Z")) - req, out := svc.OutputService1TestCaseOperation2Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - req.HTTPResponse.Header.Set("ImaHeader", "test") - req.HTTPResponse.Header.Set("X-Foo", "abc") - - // unmarshal response - restxml.UnmarshalMeta(req) - restxml.Unmarshal(req) - assert.NoError(t, req.Error) - - // assert response - assert.NotNil(t, out) // ensure out variable is used - assert.Equal(t, "a", *out.Char) - assert.Equal(t, 1.3, *out.Double) - assert.Equal(t, false, *out.FalseBool) - assert.Equal(t, 1.2, *out.Float) - assert.Equal(t, "test", *out.ImaHeader) - assert.Equal(t, "abc", *out.ImaHeaderLocation) - assert.Equal(t, int64(200), *out.Long) - assert.Equal(t, int64(123), *out.Num) - assert.Equal(t, "", *out.Str) - assert.Equal(t, time.Unix(1.4221728e+09, 0).UTC().String(), out.Timestamp.String()) - assert.Equal(t, true, *out.TrueBool) - -} - -func TestOutputService2ProtocolTestBlobCase1(t *testing.T) { - svc := NewOutputService2ProtocolTest(nil) - - buf := bytes.NewReader([]byte("dmFsdWU=")) - req, out := svc.OutputService2TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - restxml.UnmarshalMeta(req) - restxml.Unmarshal(req) - assert.NoError(t, req.Error) - - // assert response - assert.NotNil(t, out) // ensure out variable is used - assert.Equal(t, "value", string(out.Blob)) - -} - -func TestOutputService3ProtocolTestListsCase1(t *testing.T) { - svc := NewOutputService3ProtocolTest(nil) - - buf := bytes.NewReader([]byte("abc123")) - req, out := svc.OutputService3TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - restxml.UnmarshalMeta(req) - restxml.Unmarshal(req) - assert.NoError(t, req.Error) - - // assert response - assert.NotNil(t, out) // ensure out variable is used - assert.Equal(t, "abc", *out.ListMember[0]) - assert.Equal(t, "123", *out.ListMember[1]) - -} - -func TestOutputService4ProtocolTestListWithCustomMemberNameCase1(t *testing.T) { - svc := NewOutputService4ProtocolTest(nil) - - buf := bytes.NewReader([]byte("abc123")) - req, out := svc.OutputService4TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - restxml.UnmarshalMeta(req) - restxml.Unmarshal(req) - assert.NoError(t, req.Error) - - // assert response - assert.NotNil(t, out) // ensure out variable is used - assert.Equal(t, "abc", *out.ListMember[0]) - assert.Equal(t, "123", *out.ListMember[1]) - -} - -func TestOutputService5ProtocolTestFlattenedListCase1(t *testing.T) { - svc := NewOutputService5ProtocolTest(nil) - - buf := bytes.NewReader([]byte("abc123")) - req, out := svc.OutputService5TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - restxml.UnmarshalMeta(req) - restxml.Unmarshal(req) - assert.NoError(t, req.Error) - - // assert response - assert.NotNil(t, out) // ensure out variable is used - assert.Equal(t, "abc", *out.ListMember[0]) - assert.Equal(t, "123", *out.ListMember[1]) - -} - -func TestOutputService6ProtocolTestNormalMapCase1(t *testing.T) { - svc := NewOutputService6ProtocolTest(nil) - - buf := bytes.NewReader([]byte("quxbarbazbam")) - req, out := svc.OutputService6TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - restxml.UnmarshalMeta(req) - restxml.Unmarshal(req) - assert.NoError(t, req.Error) - - // assert response - assert.NotNil(t, out) // ensure out variable is used - assert.Equal(t, "bam", *out.Map["baz"].Foo) - assert.Equal(t, "bar", *out.Map["qux"].Foo) - -} - -func TestOutputService7ProtocolTestFlattenedMapCase1(t *testing.T) { - svc := NewOutputService7ProtocolTest(nil) - - buf := bytes.NewReader([]byte("quxbarbazbam")) - req, out := svc.OutputService7TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - restxml.UnmarshalMeta(req) - restxml.Unmarshal(req) - assert.NoError(t, req.Error) - - // assert response - assert.NotNil(t, out) // ensure out variable is used - assert.Equal(t, "bam", *out.Map["baz"]) - assert.Equal(t, "bar", *out.Map["qux"]) - -} - -func TestOutputService8ProtocolTestNamedMapCase1(t *testing.T) { - svc := NewOutputService8ProtocolTest(nil) - - buf := bytes.NewReader([]byte("quxbarbazbam")) - req, out := svc.OutputService8TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - restxml.UnmarshalMeta(req) - restxml.Unmarshal(req) - assert.NoError(t, req.Error) - - // assert response - assert.NotNil(t, out) // ensure out variable is used - assert.Equal(t, "bam", *out.Map["baz"]) - assert.Equal(t, "bar", *out.Map["qux"]) - -} - -func TestOutputService9ProtocolTestXMLPayloadCase1(t *testing.T) { - svc := NewOutputService9ProtocolTest(nil) - - buf := bytes.NewReader([]byte("abc")) - req, out := svc.OutputService9TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - req.HTTPResponse.Header.Set("X-Foo", "baz") - - // unmarshal response - restxml.UnmarshalMeta(req) - restxml.Unmarshal(req) - assert.NoError(t, req.Error) - - // assert response - assert.NotNil(t, out) // ensure out variable is used - assert.Equal(t, "abc", *out.Data.Foo) - assert.Equal(t, "baz", *out.Header) - -} - -func TestOutputService10ProtocolTestStreamingPayloadCase1(t *testing.T) { - svc := NewOutputService10ProtocolTest(nil) - - buf := bytes.NewReader([]byte("abc")) - req, out := svc.OutputService10TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - restxml.UnmarshalMeta(req) - restxml.Unmarshal(req) - assert.NoError(t, req.Error) - - // assert response - assert.NotNil(t, out) // ensure out variable is used - assert.Equal(t, "abc", string(out.Stream)) - -} - -func TestOutputService11ProtocolTestScalarMembersInHeadersCase1(t *testing.T) { - svc := NewOutputService11ProtocolTest(nil) - - buf := bytes.NewReader([]byte("")) - req, out := svc.OutputService11TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - req.HTTPResponse.Header.Set("x-char", "a") - req.HTTPResponse.Header.Set("x-double", "1.5") - req.HTTPResponse.Header.Set("x-false-bool", "false") - req.HTTPResponse.Header.Set("x-float", "1.5") - req.HTTPResponse.Header.Set("x-int", "1") - req.HTTPResponse.Header.Set("x-long", "100") - req.HTTPResponse.Header.Set("x-str", "string") - req.HTTPResponse.Header.Set("x-timestamp", "Sun, 25 Jan 2015 08:00:00 GMT") - req.HTTPResponse.Header.Set("x-true-bool", "true") - - // unmarshal response - restxml.UnmarshalMeta(req) - restxml.Unmarshal(req) - assert.NoError(t, req.Error) - - // assert response - assert.NotNil(t, out) // ensure out variable is used - assert.Equal(t, "a", *out.Char) - assert.Equal(t, 1.5, *out.Double) - assert.Equal(t, false, *out.FalseBool) - assert.Equal(t, 1.5, *out.Float) - assert.Equal(t, int64(1), *out.Integer) - assert.Equal(t, int64(100), *out.Long) - assert.Equal(t, "string", *out.Str) - assert.Equal(t, time.Unix(1.4221728e+09, 0).UTC().String(), out.Timestamp.String()) - assert.Equal(t, true, *out.TrueBool) - -} - -func TestOutputService12ProtocolTestStringCase1(t *testing.T) { - svc := NewOutputService12ProtocolTest(nil) - - buf := bytes.NewReader([]byte("operation result string")) - req, out := svc.OutputService12TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - restxml.UnmarshalMeta(req) - restxml.Unmarshal(req) - assert.NoError(t, req.Error) - - // assert response - assert.NotNil(t, out) // ensure out variable is used - assert.Equal(t, "operation result string", *out.String) - -} diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/signer/v4/functional_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/signer/v4/functional_test.go deleted file mode 100644 index fbb0e41cd..000000000 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/signer/v4/functional_test.go +++ /dev/null @@ -1,43 +0,0 @@ -package v4_test - -import ( - "net/url" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/internal/test/unit" - "github.com/aws/aws-sdk-go/service/s3" - "github.com/stretchr/testify/assert" -) - -var _ = unit.Imported - -func TestPresignHandler(t *testing.T) { - svc := s3.New(nil) - 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) - - assert.NoError(t, err) - - expectedDate := "19700101T000000Z" - expectedHeaders := "host;x-amz-acl" - expectedSig := "7edcb4e3a1bf12f4989018d75acbe3a7f03df24bd6f3112602d59fc551f0e4e2" - expectedCred := "AKID/19700101/mock-region/s3/aws4_request" - - u, _ := url.Parse(urlstr) - urlQ := u.Query() - assert.Equal(t, expectedSig, urlQ.Get("X-Amz-Signature")) - assert.Equal(t, expectedCred, urlQ.Get("X-Amz-Credential")) - assert.Equal(t, expectedHeaders, urlQ.Get("X-Amz-SignedHeaders")) - assert.Equal(t, expectedDate, urlQ.Get("X-Amz-Date")) - assert.Equal(t, "300", urlQ.Get("X-Amz-Expires")) - - assert.NotContains(t, urlstr, "+") // + encoded as %20 -} diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/signer/v4/v4.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/signer/v4/v4.go index fedea4f8c..fc7bc3535 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/signer/v4/v4.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/signer/v4/v4.go @@ -16,7 +16,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/aws/service" + "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/internal/protocol/rest" ) @@ -64,7 +64,7 @@ type signer struct { // Will sign the requests with the service config's Credentials object // Signing is skipped if the credentials is the credentials.AnonymousCredentials // object. -func Sign(req *service.Request) { +func Sign(req *request.Request) { // If the request does not need to be signed ignore the signing of the // request if the AnonymousCredentials object is used. if req.Service.Config.Credentials == credentials.AnonymousCredentials { diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/signer/v4/v4_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/signer/v4/v4_test.go deleted file mode 100644 index 52b5d76d9..000000000 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/signer/v4/v4_test.go +++ /dev/null @@ -1,246 +0,0 @@ -package v4 - -import ( - "net/http" - "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/service" - "github.com/stretchr/testify/assert" -) - -func buildSigner(serviceName string, region string, signTime time.Time, expireTime time.Duration, body string) signer { - 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=!@#$%^&* (+)") - - return signer{ - Request: req, - Time: signTime, - ExpireTime: expireTime, - Query: req.URL.Query(), - Body: reader, - ServiceName: serviceName, - Region: region, - 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) { - signer := buildSigner("dynamodb", "us-east-1", time.Unix(0, 0), 300*time.Second, "{}") - signer.sign() - - expectedDate := "19700101T000000Z" - expectedHeaders := "host;x-amz-meta-other-header;x-amz-target" - expectedSig := "5eeedebf6f995145ce56daa02902d10485246d3defb34f97b973c1f40ab82d36" - expectedCred := "AKID/19700101/us-east-1/dynamodb/aws4_request" - - q := signer.Request.URL.Query() - assert.Equal(t, expectedSig, q.Get("X-Amz-Signature")) - assert.Equal(t, expectedCred, q.Get("X-Amz-Credential")) - assert.Equal(t, expectedHeaders, q.Get("X-Amz-SignedHeaders")) - assert.Equal(t, expectedDate, q.Get("X-Amz-Date")) -} - -func TestSignRequest(t *testing.T) { - signer := buildSigner("dynamodb", "us-east-1", time.Unix(0, 0), 0, "{}") - signer.sign() - - expectedDate := "19700101T000000Z" - expectedSig := "AWS4-HMAC-SHA256 Credential=AKID/19700101/us-east-1/dynamodb/aws4_request, SignedHeaders=host;x-amz-date;x-amz-meta-other-header;x-amz-security-token;x-amz-target, Signature=69ada33fec48180dab153576e4dd80c4e04124f80dda3eccfed8a67c2b91ed5e" - - q := signer.Request.Header - assert.Equal(t, expectedSig, q.Get("Authorization")) - assert.Equal(t, expectedDate, q.Get("X-Amz-Date")) -} - -func TestSignEmptyBody(t *testing.T) { - signer := buildSigner("dynamodb", "us-east-1", time.Now(), 0, "") - signer.Body = nil - signer.sign() - hash := signer.Request.Header.Get("X-Amz-Content-Sha256") - assert.Equal(t, "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", hash) -} - -func TestSignBody(t *testing.T) { - signer := buildSigner("dynamodb", "us-east-1", time.Now(), 0, "hello") - signer.sign() - hash := signer.Request.Header.Get("X-Amz-Content-Sha256") - assert.Equal(t, "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824", hash) -} - -func TestSignSeekedBody(t *testing.T) { - signer := buildSigner("dynamodb", "us-east-1", time.Now(), 0, " hello") - signer.Body.Read(make([]byte, 3)) // consume first 3 bytes so body is now "hello" - signer.sign() - hash := signer.Request.Header.Get("X-Amz-Content-Sha256") - assert.Equal(t, "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824", hash) - - start, _ := signer.Body.Seek(0, 1) - assert.Equal(t, int64(3), start) -} - -func TestPresignEmptyBodyS3(t *testing.T) { - signer := buildSigner("s3", "us-east-1", time.Now(), 5*time.Minute, "hello") - signer.sign() - hash := signer.Request.Header.Get("X-Amz-Content-Sha256") - assert.Equal(t, "UNSIGNED-PAYLOAD", hash) -} - -func TestSignPrecomputedBodyChecksum(t *testing.T) { - signer := buildSigner("dynamodb", "us-east-1", time.Now(), 0, "hello") - signer.Request.Header.Set("X-Amz-Content-Sha256", "PRECOMPUTED") - signer.sign() - hash := signer.Request.Header.Get("X-Amz-Content-Sha256") - assert.Equal(t, "PRECOMPUTED", hash) -} - -func TestAnonymousCredentials(t *testing.T) { - r := service.NewRequest( - service.NewService(&aws.Config{Credentials: credentials.AnonymousCredentials}), - &service.Operation{ - Name: "BatchGetItem", - HTTPMethod: "POST", - HTTPPath: "/", - }, - nil, - nil, - ) - Sign(r) - - urlQ := r.HTTPRequest.URL.Query() - assert.Empty(t, urlQ.Get("X-Amz-Signature")) - assert.Empty(t, urlQ.Get("X-Amz-Credential")) - assert.Empty(t, urlQ.Get("X-Amz-SignedHeaders")) - assert.Empty(t, urlQ.Get("X-Amz-Date")) - - hQ := r.HTTPRequest.Header - assert.Empty(t, hQ.Get("Authorization")) - assert.Empty(t, hQ.Get("X-Amz-Date")) -} - -func TestIgnoreResignRequestWithValidCreds(t *testing.T) { - r := service.NewRequest( - service.NewService(&aws.Config{ - Credentials: credentials.NewStaticCredentials("AKID", "SECRET", "SESSION"), - Region: aws.String("us-west-2"), - }), - &service.Operation{ - Name: "BatchGetItem", - HTTPMethod: "POST", - HTTPPath: "/", - }, - nil, - nil, - ) - - Sign(r) - sig := r.HTTPRequest.Header.Get("Authorization") - - Sign(r) - assert.Equal(t, sig, r.HTTPRequest.Header.Get("Authorization")) -} - -func TestIgnorePreResignRequestWithValidCreds(t *testing.T) { - r := service.NewRequest( - service.NewService(&aws.Config{ - Credentials: credentials.NewStaticCredentials("AKID", "SECRET", "SESSION"), - Region: aws.String("us-west-2"), - }), - &service.Operation{ - Name: "BatchGetItem", - HTTPMethod: "POST", - HTTPPath: "/", - }, - nil, - nil, - ) - r.ExpireTime = time.Minute * 10 - - Sign(r) - sig := r.HTTPRequest.Header.Get("X-Amz-Signature") - - Sign(r) - assert.Equal(t, sig, r.HTTPRequest.Header.Get("X-Amz-Signature")) -} - -func TestResignRequestExpiredCreds(t *testing.T) { - creds := credentials.NewStaticCredentials("AKID", "SECRET", "SESSION") - r := service.NewRequest( - service.NewService(&aws.Config{Credentials: creds}), - &service.Operation{ - Name: "BatchGetItem", - HTTPMethod: "POST", - HTTPPath: "/", - }, - nil, - nil, - ) - Sign(r) - querySig := r.HTTPRequest.Header.Get("Authorization") - - creds.Expire() - - Sign(r) - assert.NotEqual(t, querySig, r.HTTPRequest.Header.Get("Authorization")) -} - -func TestPreResignRequestExpiredCreds(t *testing.T) { - provider := &credentials.StaticProvider{credentials.Value{"AKID", "SECRET", "SESSION"}} - creds := credentials.NewCredentials(provider) - r := service.NewRequest( - service.NewService(&aws.Config{Credentials: creds}), - &service.Operation{ - Name: "BatchGetItem", - HTTPMethod: "POST", - HTTPPath: "/", - }, - nil, - nil, - ) - r.ExpireTime = time.Minute * 10 - - Sign(r) - querySig := r.HTTPRequest.URL.Query().Get("X-Amz-Signature") - - creds.Expire() - r.Time = time.Now().Add(time.Hour * 48) - - Sign(r) - assert.NotEqual(t, querySig, r.HTTPRequest.URL.Query().Get("X-Amz-Signature")) -} - -func BenchmarkPresignRequest(b *testing.B) { - signer := buildSigner("dynamodb", "us-east-1", time.Now(), 300*time.Second, "{}") - for i := 0; i < b.N; i++ { - signer.sign() - } -} - -func BenchmarkSignRequest(b *testing.B) { - signer := buildSigner("dynamodb", "us-east-1", time.Now(), 0, "{}") - for i := 0; i < b.N; i++ { - signer.sign() - } -} diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/ec2/api.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/ec2/api.go index 363c9cb9a..0327851d6 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/ec2/api.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/ec2/api.go @@ -7,14 +7,14 @@ import ( "time" "github.com/aws/aws-sdk-go/aws/awsutil" - "github.com/aws/aws-sdk-go/aws/service" + "github.com/aws/aws-sdk-go/aws/request" ) const opAcceptVpcPeeringConnection = "AcceptVpcPeeringConnection" // AcceptVpcPeeringConnectionRequest generates a request for the AcceptVpcPeeringConnection operation. -func (c *EC2) AcceptVpcPeeringConnectionRequest(input *AcceptVpcPeeringConnectionInput) (req *service.Request, output *AcceptVpcPeeringConnectionOutput) { - op := &service.Operation{ +func (c *EC2) AcceptVpcPeeringConnectionRequest(input *AcceptVpcPeeringConnectionInput) (req *request.Request, output *AcceptVpcPeeringConnectionOutput) { + op := &request.Operation{ Name: opAcceptVpcPeeringConnection, HTTPMethod: "POST", HTTPPath: "/", @@ -43,8 +43,8 @@ func (c *EC2) AcceptVpcPeeringConnection(input *AcceptVpcPeeringConnectionInput) const opAllocateAddress = "AllocateAddress" // AllocateAddressRequest generates a request for the AllocateAddress operation. -func (c *EC2) AllocateAddressRequest(input *AllocateAddressInput) (req *service.Request, output *AllocateAddressOutput) { - op := &service.Operation{ +func (c *EC2) AllocateAddressRequest(input *AllocateAddressInput) (req *request.Request, output *AllocateAddressOutput) { + op := &request.Operation{ Name: opAllocateAddress, HTTPMethod: "POST", HTTPPath: "/", @@ -74,8 +74,8 @@ func (c *EC2) AllocateAddress(input *AllocateAddressInput) (*AllocateAddressOutp const opAssignPrivateIpAddresses = "AssignPrivateIpAddresses" // AssignPrivateIpAddressesRequest generates a request for the AssignPrivateIpAddresses operation. -func (c *EC2) AssignPrivateIpAddressesRequest(input *AssignPrivateIpAddressesInput) (req *service.Request, output *AssignPrivateIpAddressesOutput) { - op := &service.Operation{ +func (c *EC2) AssignPrivateIpAddressesRequest(input *AssignPrivateIpAddressesInput) (req *request.Request, output *AssignPrivateIpAddressesOutput) { + op := &request.Operation{ Name: opAssignPrivateIpAddresses, HTTPMethod: "POST", HTTPPath: "/", @@ -111,8 +111,8 @@ func (c *EC2) AssignPrivateIpAddresses(input *AssignPrivateIpAddressesInput) (*A const opAssociateAddress = "AssociateAddress" // AssociateAddressRequest generates a request for the AssociateAddress operation. -func (c *EC2) AssociateAddressRequest(input *AssociateAddressInput) (req *service.Request, output *AssociateAddressOutput) { - op := &service.Operation{ +func (c *EC2) AssociateAddressRequest(input *AssociateAddressInput) (req *request.Request, output *AssociateAddressOutput) { + op := &request.Operation{ Name: opAssociateAddress, HTTPMethod: "POST", HTTPPath: "/", @@ -154,8 +154,8 @@ func (c *EC2) AssociateAddress(input *AssociateAddressInput) (*AssociateAddressO const opAssociateDhcpOptions = "AssociateDhcpOptions" // AssociateDhcpOptionsRequest generates a request for the AssociateDhcpOptions operation. -func (c *EC2) AssociateDhcpOptionsRequest(input *AssociateDhcpOptionsInput) (req *service.Request, output *AssociateDhcpOptionsOutput) { - op := &service.Operation{ +func (c *EC2) AssociateDhcpOptionsRequest(input *AssociateDhcpOptionsInput) (req *request.Request, output *AssociateDhcpOptionsOutput) { + op := &request.Operation{ Name: opAssociateDhcpOptions, HTTPMethod: "POST", HTTPPath: "/", @@ -192,8 +192,8 @@ func (c *EC2) AssociateDhcpOptions(input *AssociateDhcpOptionsInput) (*Associate const opAssociateRouteTable = "AssociateRouteTable" // AssociateRouteTableRequest generates a request for the AssociateRouteTable operation. -func (c *EC2) AssociateRouteTableRequest(input *AssociateRouteTableInput) (req *service.Request, output *AssociateRouteTableOutput) { - op := &service.Operation{ +func (c *EC2) AssociateRouteTableRequest(input *AssociateRouteTableInput) (req *request.Request, output *AssociateRouteTableOutput) { + op := &request.Operation{ Name: opAssociateRouteTable, HTTPMethod: "POST", HTTPPath: "/", @@ -226,8 +226,8 @@ func (c *EC2) AssociateRouteTable(input *AssociateRouteTableInput) (*AssociateRo const opAttachClassicLinkVpc = "AttachClassicLinkVpc" // AttachClassicLinkVpcRequest generates a request for the AttachClassicLinkVpc operation. -func (c *EC2) AttachClassicLinkVpcRequest(input *AttachClassicLinkVpcInput) (req *service.Request, output *AttachClassicLinkVpcOutput) { - op := &service.Operation{ +func (c *EC2) AttachClassicLinkVpcRequest(input *AttachClassicLinkVpcInput) (req *request.Request, output *AttachClassicLinkVpcOutput) { + op := &request.Operation{ Name: opAttachClassicLinkVpc, HTTPMethod: "POST", HTTPPath: "/", @@ -264,8 +264,8 @@ func (c *EC2) AttachClassicLinkVpc(input *AttachClassicLinkVpcInput) (*AttachCla const opAttachInternetGateway = "AttachInternetGateway" // AttachInternetGatewayRequest generates a request for the AttachInternetGateway operation. -func (c *EC2) AttachInternetGatewayRequest(input *AttachInternetGatewayInput) (req *service.Request, output *AttachInternetGatewayOutput) { - op := &service.Operation{ +func (c *EC2) AttachInternetGatewayRequest(input *AttachInternetGatewayInput) (req *request.Request, output *AttachInternetGatewayOutput) { + op := &request.Operation{ Name: opAttachInternetGateway, HTTPMethod: "POST", HTTPPath: "/", @@ -293,8 +293,8 @@ func (c *EC2) AttachInternetGateway(input *AttachInternetGatewayInput) (*AttachI const opAttachNetworkInterface = "AttachNetworkInterface" // AttachNetworkInterfaceRequest generates a request for the AttachNetworkInterface operation. -func (c *EC2) AttachNetworkInterfaceRequest(input *AttachNetworkInterfaceInput) (req *service.Request, output *AttachNetworkInterfaceOutput) { - op := &service.Operation{ +func (c *EC2) AttachNetworkInterfaceRequest(input *AttachNetworkInterfaceInput) (req *request.Request, output *AttachNetworkInterfaceOutput) { + op := &request.Operation{ Name: opAttachNetworkInterface, HTTPMethod: "POST", HTTPPath: "/", @@ -320,8 +320,8 @@ func (c *EC2) AttachNetworkInterface(input *AttachNetworkInterfaceInput) (*Attac const opAttachVolume = "AttachVolume" // AttachVolumeRequest generates a request for the AttachVolume operation. -func (c *EC2) AttachVolumeRequest(input *AttachVolumeInput) (req *service.Request, output *VolumeAttachment) { - op := &service.Operation{ +func (c *EC2) AttachVolumeRequest(input *AttachVolumeInput) (req *request.Request, output *VolumeAttachment) { + op := &request.Operation{ Name: opAttachVolume, HTTPMethod: "POST", HTTPPath: "/", @@ -371,8 +371,8 @@ func (c *EC2) AttachVolume(input *AttachVolumeInput) (*VolumeAttachment, error) const opAttachVpnGateway = "AttachVpnGateway" // AttachVpnGatewayRequest generates a request for the AttachVpnGateway operation. -func (c *EC2) AttachVpnGatewayRequest(input *AttachVpnGatewayInput) (req *service.Request, output *AttachVpnGatewayOutput) { - op := &service.Operation{ +func (c *EC2) AttachVpnGatewayRequest(input *AttachVpnGatewayInput) (req *request.Request, output *AttachVpnGatewayOutput) { + op := &request.Operation{ Name: opAttachVpnGateway, HTTPMethod: "POST", HTTPPath: "/", @@ -400,8 +400,8 @@ func (c *EC2) AttachVpnGateway(input *AttachVpnGatewayInput) (*AttachVpnGatewayO const opAuthorizeSecurityGroupEgress = "AuthorizeSecurityGroupEgress" // AuthorizeSecurityGroupEgressRequest generates a request for the AuthorizeSecurityGroupEgress operation. -func (c *EC2) AuthorizeSecurityGroupEgressRequest(input *AuthorizeSecurityGroupEgressInput) (req *service.Request, output *AuthorizeSecurityGroupEgressOutput) { - op := &service.Operation{ +func (c *EC2) AuthorizeSecurityGroupEgressRequest(input *AuthorizeSecurityGroupEgressInput) (req *request.Request, output *AuthorizeSecurityGroupEgressOutput) { + op := &request.Operation{ Name: opAuthorizeSecurityGroupEgress, HTTPMethod: "POST", HTTPPath: "/", @@ -447,8 +447,8 @@ func (c *EC2) AuthorizeSecurityGroupEgress(input *AuthorizeSecurityGroupEgressIn const opAuthorizeSecurityGroupIngress = "AuthorizeSecurityGroupIngress" // AuthorizeSecurityGroupIngressRequest generates a request for the AuthorizeSecurityGroupIngress operation. -func (c *EC2) AuthorizeSecurityGroupIngressRequest(input *AuthorizeSecurityGroupIngressInput) (req *service.Request, output *AuthorizeSecurityGroupIngressOutput) { - op := &service.Operation{ +func (c *EC2) AuthorizeSecurityGroupIngressRequest(input *AuthorizeSecurityGroupIngressInput) (req *request.Request, output *AuthorizeSecurityGroupIngressOutput) { + op := &request.Operation{ Name: opAuthorizeSecurityGroupIngress, HTTPMethod: "POST", HTTPPath: "/", @@ -492,8 +492,8 @@ func (c *EC2) AuthorizeSecurityGroupIngress(input *AuthorizeSecurityGroupIngress const opBundleInstance = "BundleInstance" // BundleInstanceRequest generates a request for the BundleInstance operation. -func (c *EC2) BundleInstanceRequest(input *BundleInstanceInput) (req *service.Request, output *BundleInstanceOutput) { - op := &service.Operation{ +func (c *EC2) BundleInstanceRequest(input *BundleInstanceInput) (req *request.Request, output *BundleInstanceOutput) { + op := &request.Operation{ Name: opBundleInstance, HTTPMethod: "POST", HTTPPath: "/", @@ -528,8 +528,8 @@ func (c *EC2) BundleInstance(input *BundleInstanceInput) (*BundleInstanceOutput, const opCancelBundleTask = "CancelBundleTask" // CancelBundleTaskRequest generates a request for the CancelBundleTask operation. -func (c *EC2) CancelBundleTaskRequest(input *CancelBundleTaskInput) (req *service.Request, output *CancelBundleTaskOutput) { - op := &service.Operation{ +func (c *EC2) CancelBundleTaskRequest(input *CancelBundleTaskInput) (req *request.Request, output *CancelBundleTaskOutput) { + op := &request.Operation{ Name: opCancelBundleTask, HTTPMethod: "POST", HTTPPath: "/", @@ -555,8 +555,8 @@ func (c *EC2) CancelBundleTask(input *CancelBundleTaskInput) (*CancelBundleTaskO const opCancelConversionTask = "CancelConversionTask" // CancelConversionTaskRequest generates a request for the CancelConversionTask operation. -func (c *EC2) CancelConversionTaskRequest(input *CancelConversionTaskInput) (req *service.Request, output *CancelConversionTaskOutput) { - op := &service.Operation{ +func (c *EC2) CancelConversionTaskRequest(input *CancelConversionTaskInput) (req *request.Request, output *CancelConversionTaskOutput) { + op := &request.Operation{ Name: opCancelConversionTask, HTTPMethod: "POST", HTTPPath: "/", @@ -590,8 +590,8 @@ func (c *EC2) CancelConversionTask(input *CancelConversionTaskInput) (*CancelCon const opCancelExportTask = "CancelExportTask" // CancelExportTaskRequest generates a request for the CancelExportTask operation. -func (c *EC2) CancelExportTaskRequest(input *CancelExportTaskInput) (req *service.Request, output *CancelExportTaskOutput) { - op := &service.Operation{ +func (c *EC2) CancelExportTaskRequest(input *CancelExportTaskInput) (req *request.Request, output *CancelExportTaskOutput) { + op := &request.Operation{ Name: opCancelExportTask, HTTPMethod: "POST", HTTPPath: "/", @@ -620,8 +620,8 @@ func (c *EC2) CancelExportTask(input *CancelExportTaskInput) (*CancelExportTaskO const opCancelImportTask = "CancelImportTask" // CancelImportTaskRequest generates a request for the CancelImportTask operation. -func (c *EC2) CancelImportTaskRequest(input *CancelImportTaskInput) (req *service.Request, output *CancelImportTaskOutput) { - op := &service.Operation{ +func (c *EC2) CancelImportTaskRequest(input *CancelImportTaskInput) (req *request.Request, output *CancelImportTaskOutput) { + op := &request.Operation{ Name: opCancelImportTask, HTTPMethod: "POST", HTTPPath: "/", @@ -647,8 +647,8 @@ func (c *EC2) CancelImportTask(input *CancelImportTaskInput) (*CancelImportTaskO const opCancelReservedInstancesListing = "CancelReservedInstancesListing" // CancelReservedInstancesListingRequest generates a request for the CancelReservedInstancesListing operation. -func (c *EC2) CancelReservedInstancesListingRequest(input *CancelReservedInstancesListingInput) (req *service.Request, output *CancelReservedInstancesListingOutput) { - op := &service.Operation{ +func (c *EC2) CancelReservedInstancesListingRequest(input *CancelReservedInstancesListingInput) (req *request.Request, output *CancelReservedInstancesListingOutput) { + op := &request.Operation{ Name: opCancelReservedInstancesListing, HTTPMethod: "POST", HTTPPath: "/", @@ -678,8 +678,8 @@ func (c *EC2) CancelReservedInstancesListing(input *CancelReservedInstancesListi const opCancelSpotFleetRequests = "CancelSpotFleetRequests" // CancelSpotFleetRequestsRequest generates a request for the CancelSpotFleetRequests operation. -func (c *EC2) CancelSpotFleetRequestsRequest(input *CancelSpotFleetRequestsInput) (req *service.Request, output *CancelSpotFleetRequestsOutput) { - op := &service.Operation{ +func (c *EC2) CancelSpotFleetRequestsRequest(input *CancelSpotFleetRequestsInput) (req *request.Request, output *CancelSpotFleetRequestsOutput) { + op := &request.Operation{ Name: opCancelSpotFleetRequests, HTTPMethod: "POST", HTTPPath: "/", @@ -705,8 +705,8 @@ func (c *EC2) CancelSpotFleetRequests(input *CancelSpotFleetRequestsInput) (*Can const opCancelSpotInstanceRequests = "CancelSpotInstanceRequests" // CancelSpotInstanceRequestsRequest generates a request for the CancelSpotInstanceRequests operation. -func (c *EC2) CancelSpotInstanceRequestsRequest(input *CancelSpotInstanceRequestsInput) (req *service.Request, output *CancelSpotInstanceRequestsOutput) { - op := &service.Operation{ +func (c *EC2) CancelSpotInstanceRequestsRequest(input *CancelSpotInstanceRequestsInput) (req *request.Request, output *CancelSpotInstanceRequestsOutput) { + op := &request.Operation{ Name: opCancelSpotInstanceRequests, HTTPMethod: "POST", HTTPPath: "/", @@ -722,14 +722,14 @@ func (c *EC2) CancelSpotInstanceRequestsRequest(input *CancelSpotInstanceRequest return } -// Cancels one or more Spot Instance requests. Spot Instances are instances +// Cancels one or more Spot instance requests. Spot instances are instances // that Amazon EC2 starts on your behalf when the bid price that you specify -// exceeds the current Spot Price. Amazon EC2 periodically sets the Spot Price -// based on available Spot Instance capacity and current Spot Instance requests. +// exceeds the current Spot price. Amazon EC2 periodically sets the Spot price +// based on available Spot instance capacity and current Spot instance requests. // For more information, see Spot Instance Requests (http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-requests.html) // in the Amazon Elastic Compute Cloud User Guide. // -// Canceling a Spot Instance request does not terminate running Spot Instances +// Canceling a Spot instance request does not terminate running Spot instances // associated with the request. func (c *EC2) CancelSpotInstanceRequests(input *CancelSpotInstanceRequestsInput) (*CancelSpotInstanceRequestsOutput, error) { req, out := c.CancelSpotInstanceRequestsRequest(input) @@ -740,8 +740,8 @@ func (c *EC2) CancelSpotInstanceRequests(input *CancelSpotInstanceRequestsInput) const opConfirmProductInstance = "ConfirmProductInstance" // ConfirmProductInstanceRequest generates a request for the ConfirmProductInstance operation. -func (c *EC2) ConfirmProductInstanceRequest(input *ConfirmProductInstanceInput) (req *service.Request, output *ConfirmProductInstanceOutput) { - op := &service.Operation{ +func (c *EC2) ConfirmProductInstanceRequest(input *ConfirmProductInstanceInput) (req *request.Request, output *ConfirmProductInstanceOutput) { + op := &request.Operation{ Name: opConfirmProductInstance, HTTPMethod: "POST", HTTPPath: "/", @@ -770,8 +770,8 @@ func (c *EC2) ConfirmProductInstance(input *ConfirmProductInstanceInput) (*Confi const opCopyImage = "CopyImage" // CopyImageRequest generates a request for the CopyImage operation. -func (c *EC2) CopyImageRequest(input *CopyImageInput) (req *service.Request, output *CopyImageOutput) { - op := &service.Operation{ +func (c *EC2) CopyImageRequest(input *CopyImageInput) (req *request.Request, output *CopyImageOutput) { + op := &request.Operation{ Name: opCopyImage, HTTPMethod: "POST", HTTPPath: "/", @@ -803,8 +803,8 @@ func (c *EC2) CopyImage(input *CopyImageInput) (*CopyImageOutput, error) { const opCopySnapshot = "CopySnapshot" // CopySnapshotRequest generates a request for the CopySnapshot operation. -func (c *EC2) CopySnapshotRequest(input *CopySnapshotInput) (req *service.Request, output *CopySnapshotOutput) { - op := &service.Operation{ +func (c *EC2) CopySnapshotRequest(input *CopySnapshotInput) (req *request.Request, output *CopySnapshotOutput) { + op := &request.Operation{ Name: opCopySnapshot, HTTPMethod: "POST", HTTPPath: "/", @@ -843,8 +843,8 @@ func (c *EC2) CopySnapshot(input *CopySnapshotInput) (*CopySnapshotOutput, error const opCreateCustomerGateway = "CreateCustomerGateway" // CreateCustomerGatewayRequest generates a request for the CreateCustomerGateway operation. -func (c *EC2) CreateCustomerGatewayRequest(input *CreateCustomerGatewayInput) (req *service.Request, output *CreateCustomerGatewayOutput) { - op := &service.Operation{ +func (c *EC2) CreateCustomerGatewayRequest(input *CreateCustomerGatewayInput) (req *request.Request, output *CreateCustomerGatewayOutput) { + op := &request.Operation{ Name: opCreateCustomerGateway, HTTPMethod: "POST", HTTPPath: "/", @@ -894,8 +894,8 @@ func (c *EC2) CreateCustomerGateway(input *CreateCustomerGatewayInput) (*CreateC const opCreateDhcpOptions = "CreateDhcpOptions" // CreateDhcpOptionsRequest generates a request for the CreateDhcpOptions operation. -func (c *EC2) CreateDhcpOptionsRequest(input *CreateDhcpOptionsInput) (req *service.Request, output *CreateDhcpOptionsOutput) { - op := &service.Operation{ +func (c *EC2) CreateDhcpOptionsRequest(input *CreateDhcpOptionsInput) (req *request.Request, output *CreateDhcpOptionsOutput) { + op := &request.Operation{ Name: opCreateDhcpOptions, HTTPMethod: "POST", HTTPPath: "/", @@ -949,8 +949,8 @@ func (c *EC2) CreateDhcpOptions(input *CreateDhcpOptionsInput) (*CreateDhcpOptio const opCreateFlowLogs = "CreateFlowLogs" // CreateFlowLogsRequest generates a request for the CreateFlowLogs operation. -func (c *EC2) CreateFlowLogsRequest(input *CreateFlowLogsInput) (req *service.Request, output *CreateFlowLogsOutput) { - op := &service.Operation{ +func (c *EC2) CreateFlowLogsRequest(input *CreateFlowLogsInput) (req *request.Request, output *CreateFlowLogsOutput) { + op := &request.Operation{ Name: opCreateFlowLogs, HTTPMethod: "POST", HTTPPath: "/", @@ -985,8 +985,8 @@ func (c *EC2) CreateFlowLogs(input *CreateFlowLogsInput) (*CreateFlowLogsOutput, const opCreateImage = "CreateImage" // CreateImageRequest generates a request for the CreateImage operation. -func (c *EC2) CreateImageRequest(input *CreateImageInput) (req *service.Request, output *CreateImageOutput) { - op := &service.Operation{ +func (c *EC2) CreateImageRequest(input *CreateImageInput) (req *request.Request, output *CreateImageOutput) { + op := &request.Operation{ Name: opCreateImage, HTTPMethod: "POST", HTTPPath: "/", @@ -1021,8 +1021,8 @@ func (c *EC2) CreateImage(input *CreateImageInput) (*CreateImageOutput, error) { const opCreateInstanceExportTask = "CreateInstanceExportTask" // CreateInstanceExportTaskRequest generates a request for the CreateInstanceExportTask operation. -func (c *EC2) CreateInstanceExportTaskRequest(input *CreateInstanceExportTaskInput) (req *service.Request, output *CreateInstanceExportTaskOutput) { - op := &service.Operation{ +func (c *EC2) CreateInstanceExportTaskRequest(input *CreateInstanceExportTaskInput) (req *request.Request, output *CreateInstanceExportTaskOutput) { + op := &request.Operation{ Name: opCreateInstanceExportTask, HTTPMethod: "POST", HTTPPath: "/", @@ -1053,8 +1053,8 @@ func (c *EC2) CreateInstanceExportTask(input *CreateInstanceExportTaskInput) (*C const opCreateInternetGateway = "CreateInternetGateway" // CreateInternetGatewayRequest generates a request for the CreateInternetGateway operation. -func (c *EC2) CreateInternetGatewayRequest(input *CreateInternetGatewayInput) (req *service.Request, output *CreateInternetGatewayOutput) { - op := &service.Operation{ +func (c *EC2) CreateInternetGatewayRequest(input *CreateInternetGatewayInput) (req *request.Request, output *CreateInternetGatewayOutput) { + op := &request.Operation{ Name: opCreateInternetGateway, HTTPMethod: "POST", HTTPPath: "/", @@ -1084,8 +1084,8 @@ func (c *EC2) CreateInternetGateway(input *CreateInternetGatewayInput) (*CreateI const opCreateKeyPair = "CreateKeyPair" // CreateKeyPairRequest generates a request for the CreateKeyPair operation. -func (c *EC2) CreateKeyPairRequest(input *CreateKeyPairInput) (req *service.Request, output *CreateKeyPairOutput) { - op := &service.Operation{ +func (c *EC2) CreateKeyPairRequest(input *CreateKeyPairInput) (req *request.Request, output *CreateKeyPairOutput) { + op := &request.Operation{ Name: opCreateKeyPair, HTTPMethod: "POST", HTTPPath: "/", @@ -1122,8 +1122,8 @@ func (c *EC2) CreateKeyPair(input *CreateKeyPairInput) (*CreateKeyPairOutput, er const opCreateNetworkAcl = "CreateNetworkAcl" // CreateNetworkAclRequest generates a request for the CreateNetworkAcl operation. -func (c *EC2) CreateNetworkAclRequest(input *CreateNetworkAclInput) (req *service.Request, output *CreateNetworkAclOutput) { - op := &service.Operation{ +func (c *EC2) CreateNetworkAclRequest(input *CreateNetworkAclInput) (req *request.Request, output *CreateNetworkAclOutput) { + op := &request.Operation{ Name: opCreateNetworkAcl, HTTPMethod: "POST", HTTPPath: "/", @@ -1153,8 +1153,8 @@ func (c *EC2) CreateNetworkAcl(input *CreateNetworkAclInput) (*CreateNetworkAclO const opCreateNetworkAclEntry = "CreateNetworkAclEntry" // CreateNetworkAclEntryRequest generates a request for the CreateNetworkAclEntry operation. -func (c *EC2) CreateNetworkAclEntryRequest(input *CreateNetworkAclEntryInput) (req *service.Request, output *CreateNetworkAclEntryOutput) { - op := &service.Operation{ +func (c *EC2) CreateNetworkAclEntryRequest(input *CreateNetworkAclEntryInput) (req *request.Request, output *CreateNetworkAclEntryOutput) { + op := &request.Operation{ Name: opCreateNetworkAclEntry, HTTPMethod: "POST", HTTPPath: "/", @@ -1196,8 +1196,8 @@ func (c *EC2) CreateNetworkAclEntry(input *CreateNetworkAclEntryInput) (*CreateN const opCreateNetworkInterface = "CreateNetworkInterface" // CreateNetworkInterfaceRequest generates a request for the CreateNetworkInterface operation. -func (c *EC2) CreateNetworkInterfaceRequest(input *CreateNetworkInterfaceInput) (req *service.Request, output *CreateNetworkInterfaceOutput) { - op := &service.Operation{ +func (c *EC2) CreateNetworkInterfaceRequest(input *CreateNetworkInterfaceInput) (req *request.Request, output *CreateNetworkInterfaceOutput) { + op := &request.Operation{ Name: opCreateNetworkInterface, HTTPMethod: "POST", HTTPPath: "/", @@ -1227,8 +1227,8 @@ func (c *EC2) CreateNetworkInterface(input *CreateNetworkInterfaceInput) (*Creat const opCreatePlacementGroup = "CreatePlacementGroup" // CreatePlacementGroupRequest generates a request for the CreatePlacementGroup operation. -func (c *EC2) CreatePlacementGroupRequest(input *CreatePlacementGroupInput) (req *service.Request, output *CreatePlacementGroupOutput) { - op := &service.Operation{ +func (c *EC2) CreatePlacementGroupRequest(input *CreatePlacementGroupInput) (req *request.Request, output *CreatePlacementGroupOutput) { + op := &request.Operation{ Name: opCreatePlacementGroup, HTTPMethod: "POST", HTTPPath: "/", @@ -1259,8 +1259,8 @@ func (c *EC2) CreatePlacementGroup(input *CreatePlacementGroupInput) (*CreatePla const opCreateReservedInstancesListing = "CreateReservedInstancesListing" // CreateReservedInstancesListingRequest generates a request for the CreateReservedInstancesListing operation. -func (c *EC2) CreateReservedInstancesListingRequest(input *CreateReservedInstancesListingInput) (req *service.Request, output *CreateReservedInstancesListingOutput) { - op := &service.Operation{ +func (c *EC2) CreateReservedInstancesListingRequest(input *CreateReservedInstancesListingInput) (req *request.Request, output *CreateReservedInstancesListingOutput) { + op := &request.Operation{ Name: opCreateReservedInstancesListing, HTTPMethod: "POST", HTTPPath: "/", @@ -1305,8 +1305,8 @@ func (c *EC2) CreateReservedInstancesListing(input *CreateReservedInstancesListi const opCreateRoute = "CreateRoute" // CreateRouteRequest generates a request for the CreateRoute operation. -func (c *EC2) CreateRouteRequest(input *CreateRouteInput) (req *service.Request, output *CreateRouteOutput) { - op := &service.Operation{ +func (c *EC2) CreateRouteRequest(input *CreateRouteInput) (req *request.Request, output *CreateRouteOutput) { + op := &request.Operation{ Name: opCreateRoute, HTTPMethod: "POST", HTTPPath: "/", @@ -1350,8 +1350,8 @@ func (c *EC2) CreateRoute(input *CreateRouteInput) (*CreateRouteOutput, error) { const opCreateRouteTable = "CreateRouteTable" // CreateRouteTableRequest generates a request for the CreateRouteTable operation. -func (c *EC2) CreateRouteTableRequest(input *CreateRouteTableInput) (req *service.Request, output *CreateRouteTableOutput) { - op := &service.Operation{ +func (c *EC2) CreateRouteTableRequest(input *CreateRouteTableInput) (req *request.Request, output *CreateRouteTableOutput) { + op := &request.Operation{ Name: opCreateRouteTable, HTTPMethod: "POST", HTTPPath: "/", @@ -1381,8 +1381,8 @@ func (c *EC2) CreateRouteTable(input *CreateRouteTableInput) (*CreateRouteTableO const opCreateSecurityGroup = "CreateSecurityGroup" // CreateSecurityGroupRequest generates a request for the CreateSecurityGroup operation. -func (c *EC2) CreateSecurityGroupRequest(input *CreateSecurityGroupInput) (req *service.Request, output *CreateSecurityGroupOutput) { - op := &service.Operation{ +func (c *EC2) CreateSecurityGroupRequest(input *CreateSecurityGroupInput) (req *request.Request, output *CreateSecurityGroupOutput) { + op := &request.Operation{ Name: opCreateSecurityGroup, HTTPMethod: "POST", HTTPPath: "/", @@ -1434,8 +1434,8 @@ func (c *EC2) CreateSecurityGroup(input *CreateSecurityGroupInput) (*CreateSecur const opCreateSnapshot = "CreateSnapshot" // CreateSnapshotRequest generates a request for the CreateSnapshot operation. -func (c *EC2) CreateSnapshotRequest(input *CreateSnapshotInput) (req *service.Request, output *Snapshot) { - op := &service.Operation{ +func (c *EC2) CreateSnapshotRequest(input *CreateSnapshotInput) (req *request.Request, output *Snapshot) { + op := &request.Operation{ Name: opCreateSnapshot, HTTPMethod: "POST", HTTPPath: "/", @@ -1488,8 +1488,8 @@ func (c *EC2) CreateSnapshot(input *CreateSnapshotInput) (*Snapshot, error) { const opCreateSpotDatafeedSubscription = "CreateSpotDatafeedSubscription" // CreateSpotDatafeedSubscriptionRequest generates a request for the CreateSpotDatafeedSubscription operation. -func (c *EC2) CreateSpotDatafeedSubscriptionRequest(input *CreateSpotDatafeedSubscriptionInput) (req *service.Request, output *CreateSpotDatafeedSubscriptionOutput) { - op := &service.Operation{ +func (c *EC2) CreateSpotDatafeedSubscriptionRequest(input *CreateSpotDatafeedSubscriptionInput) (req *request.Request, output *CreateSpotDatafeedSubscriptionOutput) { + op := &request.Operation{ Name: opCreateSpotDatafeedSubscription, HTTPMethod: "POST", HTTPPath: "/", @@ -1505,7 +1505,7 @@ func (c *EC2) CreateSpotDatafeedSubscriptionRequest(input *CreateSpotDatafeedSub return } -// Creates a data feed for Spot Instances, enabling you to view Spot Instance +// Creates a data feed for Spot instances, enabling you to view Spot instance // usage logs. You can create one data feed per AWS account. For more information, // see Spot Instance Data Feed (http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-data-feeds.html) // in the Amazon Elastic Compute Cloud User Guide. @@ -1518,8 +1518,8 @@ func (c *EC2) CreateSpotDatafeedSubscription(input *CreateSpotDatafeedSubscripti const opCreateSubnet = "CreateSubnet" // CreateSubnetRequest generates a request for the CreateSubnet operation. -func (c *EC2) CreateSubnetRequest(input *CreateSubnetInput) (req *service.Request, output *CreateSubnetOutput) { - op := &service.Operation{ +func (c *EC2) CreateSubnetRequest(input *CreateSubnetInput) (req *request.Request, output *CreateSubnetOutput) { + op := &request.Operation{ Name: opCreateSubnet, HTTPMethod: "POST", HTTPPath: "/", @@ -1569,8 +1569,8 @@ func (c *EC2) CreateSubnet(input *CreateSubnetInput) (*CreateSubnetOutput, error const opCreateTags = "CreateTags" // CreateTagsRequest generates a request for the CreateTags operation. -func (c *EC2) CreateTagsRequest(input *CreateTagsInput) (req *service.Request, output *CreateTagsOutput) { - op := &service.Operation{ +func (c *EC2) CreateTagsRequest(input *CreateTagsInput) (req *request.Request, output *CreateTagsOutput) { + op := &request.Operation{ Name: opCreateTags, HTTPMethod: "POST", HTTPPath: "/", @@ -1601,8 +1601,8 @@ func (c *EC2) CreateTags(input *CreateTagsInput) (*CreateTagsOutput, error) { const opCreateVolume = "CreateVolume" // CreateVolumeRequest generates a request for the CreateVolume operation. -func (c *EC2) CreateVolumeRequest(input *CreateVolumeInput) (req *service.Request, output *Volume) { - op := &service.Operation{ +func (c *EC2) CreateVolumeRequest(input *CreateVolumeInput) (req *request.Request, output *Volume) { + op := &request.Operation{ Name: opCreateVolume, HTTPMethod: "POST", HTTPPath: "/", @@ -1643,8 +1643,8 @@ func (c *EC2) CreateVolume(input *CreateVolumeInput) (*Volume, error) { const opCreateVpc = "CreateVpc" // CreateVpcRequest generates a request for the CreateVpc operation. -func (c *EC2) CreateVpcRequest(input *CreateVpcInput) (req *service.Request, output *CreateVpcOutput) { - op := &service.Operation{ +func (c *EC2) CreateVpcRequest(input *CreateVpcInput) (req *request.Request, output *CreateVpcOutput) { + op := &request.Operation{ Name: opCreateVpc, HTTPMethod: "POST", HTTPPath: "/", @@ -1680,8 +1680,8 @@ func (c *EC2) CreateVpc(input *CreateVpcInput) (*CreateVpcOutput, error) { const opCreateVpcEndpoint = "CreateVpcEndpoint" // CreateVpcEndpointRequest generates a request for the CreateVpcEndpoint operation. -func (c *EC2) CreateVpcEndpointRequest(input *CreateVpcEndpointInput) (req *service.Request, output *CreateVpcEndpointOutput) { - op := &service.Operation{ +func (c *EC2) CreateVpcEndpointRequest(input *CreateVpcEndpointInput) (req *request.Request, output *CreateVpcEndpointOutput) { + op := &request.Operation{ Name: opCreateVpcEndpoint, HTTPMethod: "POST", HTTPPath: "/", @@ -1713,8 +1713,8 @@ func (c *EC2) CreateVpcEndpoint(input *CreateVpcEndpointInput) (*CreateVpcEndpoi const opCreateVpcPeeringConnection = "CreateVpcPeeringConnection" // CreateVpcPeeringConnectionRequest generates a request for the CreateVpcPeeringConnection operation. -func (c *EC2) CreateVpcPeeringConnectionRequest(input *CreateVpcPeeringConnectionInput) (req *service.Request, output *CreateVpcPeeringConnectionOutput) { - op := &service.Operation{ +func (c *EC2) CreateVpcPeeringConnectionRequest(input *CreateVpcPeeringConnectionInput) (req *request.Request, output *CreateVpcPeeringConnectionOutput) { + op := &request.Operation{ Name: opCreateVpcPeeringConnection, HTTPMethod: "POST", HTTPPath: "/", @@ -1750,8 +1750,8 @@ func (c *EC2) CreateVpcPeeringConnection(input *CreateVpcPeeringConnectionInput) const opCreateVpnConnection = "CreateVpnConnection" // CreateVpnConnectionRequest generates a request for the CreateVpnConnection operation. -func (c *EC2) CreateVpnConnectionRequest(input *CreateVpnConnectionInput) (req *service.Request, output *CreateVpnConnectionOutput) { - op := &service.Operation{ +func (c *EC2) CreateVpnConnectionRequest(input *CreateVpnConnectionInput) (req *request.Request, output *CreateVpnConnectionOutput) { + op := &request.Operation{ Name: opCreateVpnConnection, HTTPMethod: "POST", HTTPPath: "/", @@ -1793,8 +1793,8 @@ func (c *EC2) CreateVpnConnection(input *CreateVpnConnectionInput) (*CreateVpnCo const opCreateVpnConnectionRoute = "CreateVpnConnectionRoute" // CreateVpnConnectionRouteRequest generates a request for the CreateVpnConnectionRoute operation. -func (c *EC2) CreateVpnConnectionRouteRequest(input *CreateVpnConnectionRouteInput) (req *service.Request, output *CreateVpnConnectionRouteOutput) { - op := &service.Operation{ +func (c *EC2) CreateVpnConnectionRouteRequest(input *CreateVpnConnectionRouteInput) (req *request.Request, output *CreateVpnConnectionRouteOutput) { + op := &request.Operation{ Name: opCreateVpnConnectionRoute, HTTPMethod: "POST", HTTPPath: "/", @@ -1827,8 +1827,8 @@ func (c *EC2) CreateVpnConnectionRoute(input *CreateVpnConnectionRouteInput) (*C const opCreateVpnGateway = "CreateVpnGateway" // CreateVpnGatewayRequest generates a request for the CreateVpnGateway operation. -func (c *EC2) CreateVpnGatewayRequest(input *CreateVpnGatewayInput) (req *service.Request, output *CreateVpnGatewayOutput) { - op := &service.Operation{ +func (c *EC2) CreateVpnGatewayRequest(input *CreateVpnGatewayInput) (req *request.Request, output *CreateVpnGatewayOutput) { + op := &request.Operation{ Name: opCreateVpnGateway, HTTPMethod: "POST", HTTPPath: "/", @@ -1860,8 +1860,8 @@ func (c *EC2) CreateVpnGateway(input *CreateVpnGatewayInput) (*CreateVpnGatewayO const opDeleteCustomerGateway = "DeleteCustomerGateway" // DeleteCustomerGatewayRequest generates a request for the DeleteCustomerGateway operation. -func (c *EC2) DeleteCustomerGatewayRequest(input *DeleteCustomerGatewayInput) (req *service.Request, output *DeleteCustomerGatewayOutput) { - op := &service.Operation{ +func (c *EC2) DeleteCustomerGatewayRequest(input *DeleteCustomerGatewayInput) (req *request.Request, output *DeleteCustomerGatewayOutput) { + op := &request.Operation{ Name: opDeleteCustomerGateway, HTTPMethod: "POST", HTTPPath: "/", @@ -1888,8 +1888,8 @@ func (c *EC2) DeleteCustomerGateway(input *DeleteCustomerGatewayInput) (*DeleteC const opDeleteDhcpOptions = "DeleteDhcpOptions" // DeleteDhcpOptionsRequest generates a request for the DeleteDhcpOptions operation. -func (c *EC2) DeleteDhcpOptionsRequest(input *DeleteDhcpOptionsInput) (req *service.Request, output *DeleteDhcpOptionsOutput) { - op := &service.Operation{ +func (c *EC2) DeleteDhcpOptionsRequest(input *DeleteDhcpOptionsInput) (req *request.Request, output *DeleteDhcpOptionsOutput) { + op := &request.Operation{ Name: opDeleteDhcpOptions, HTTPMethod: "POST", HTTPPath: "/", @@ -1918,8 +1918,8 @@ func (c *EC2) DeleteDhcpOptions(input *DeleteDhcpOptionsInput) (*DeleteDhcpOptio const opDeleteFlowLogs = "DeleteFlowLogs" // DeleteFlowLogsRequest generates a request for the DeleteFlowLogs operation. -func (c *EC2) DeleteFlowLogsRequest(input *DeleteFlowLogsInput) (req *service.Request, output *DeleteFlowLogsOutput) { - op := &service.Operation{ +func (c *EC2) DeleteFlowLogsRequest(input *DeleteFlowLogsInput) (req *request.Request, output *DeleteFlowLogsOutput) { + op := &request.Operation{ Name: opDeleteFlowLogs, HTTPMethod: "POST", HTTPPath: "/", @@ -1945,8 +1945,8 @@ func (c *EC2) DeleteFlowLogs(input *DeleteFlowLogsInput) (*DeleteFlowLogsOutput, const opDeleteInternetGateway = "DeleteInternetGateway" // DeleteInternetGatewayRequest generates a request for the DeleteInternetGateway operation. -func (c *EC2) DeleteInternetGatewayRequest(input *DeleteInternetGatewayInput) (req *service.Request, output *DeleteInternetGatewayOutput) { - op := &service.Operation{ +func (c *EC2) DeleteInternetGatewayRequest(input *DeleteInternetGatewayInput) (req *request.Request, output *DeleteInternetGatewayOutput) { + op := &request.Operation{ Name: opDeleteInternetGateway, HTTPMethod: "POST", HTTPPath: "/", @@ -1973,8 +1973,8 @@ func (c *EC2) DeleteInternetGateway(input *DeleteInternetGatewayInput) (*DeleteI const opDeleteKeyPair = "DeleteKeyPair" // DeleteKeyPairRequest generates a request for the DeleteKeyPair operation. -func (c *EC2) DeleteKeyPairRequest(input *DeleteKeyPairInput) (req *service.Request, output *DeleteKeyPairOutput) { - op := &service.Operation{ +func (c *EC2) DeleteKeyPairRequest(input *DeleteKeyPairInput) (req *request.Request, output *DeleteKeyPairOutput) { + op := &request.Operation{ Name: opDeleteKeyPair, HTTPMethod: "POST", HTTPPath: "/", @@ -2000,8 +2000,8 @@ func (c *EC2) DeleteKeyPair(input *DeleteKeyPairInput) (*DeleteKeyPairOutput, er const opDeleteNetworkAcl = "DeleteNetworkAcl" // DeleteNetworkAclRequest generates a request for the DeleteNetworkAcl operation. -func (c *EC2) DeleteNetworkAclRequest(input *DeleteNetworkAclInput) (req *service.Request, output *DeleteNetworkAclOutput) { - op := &service.Operation{ +func (c *EC2) DeleteNetworkAclRequest(input *DeleteNetworkAclInput) (req *request.Request, output *DeleteNetworkAclOutput) { + op := &request.Operation{ Name: opDeleteNetworkAcl, HTTPMethod: "POST", HTTPPath: "/", @@ -2028,8 +2028,8 @@ func (c *EC2) DeleteNetworkAcl(input *DeleteNetworkAclInput) (*DeleteNetworkAclO const opDeleteNetworkAclEntry = "DeleteNetworkAclEntry" // DeleteNetworkAclEntryRequest generates a request for the DeleteNetworkAclEntry operation. -func (c *EC2) DeleteNetworkAclEntryRequest(input *DeleteNetworkAclEntryInput) (req *service.Request, output *DeleteNetworkAclEntryOutput) { - op := &service.Operation{ +func (c *EC2) DeleteNetworkAclEntryRequest(input *DeleteNetworkAclEntryInput) (req *request.Request, output *DeleteNetworkAclEntryOutput) { + op := &request.Operation{ Name: opDeleteNetworkAclEntry, HTTPMethod: "POST", HTTPPath: "/", @@ -2056,8 +2056,8 @@ func (c *EC2) DeleteNetworkAclEntry(input *DeleteNetworkAclEntryInput) (*DeleteN const opDeleteNetworkInterface = "DeleteNetworkInterface" // DeleteNetworkInterfaceRequest generates a request for the DeleteNetworkInterface operation. -func (c *EC2) DeleteNetworkInterfaceRequest(input *DeleteNetworkInterfaceInput) (req *service.Request, output *DeleteNetworkInterfaceOutput) { - op := &service.Operation{ +func (c *EC2) DeleteNetworkInterfaceRequest(input *DeleteNetworkInterfaceInput) (req *request.Request, output *DeleteNetworkInterfaceOutput) { + op := &request.Operation{ Name: opDeleteNetworkInterface, HTTPMethod: "POST", HTTPPath: "/", @@ -2084,8 +2084,8 @@ func (c *EC2) DeleteNetworkInterface(input *DeleteNetworkInterfaceInput) (*Delet const opDeletePlacementGroup = "DeletePlacementGroup" // DeletePlacementGroupRequest generates a request for the DeletePlacementGroup operation. -func (c *EC2) DeletePlacementGroupRequest(input *DeletePlacementGroupInput) (req *service.Request, output *DeletePlacementGroupOutput) { - op := &service.Operation{ +func (c *EC2) DeletePlacementGroupRequest(input *DeletePlacementGroupInput) (req *request.Request, output *DeletePlacementGroupOutput) { + op := &request.Operation{ Name: opDeletePlacementGroup, HTTPMethod: "POST", HTTPPath: "/", @@ -2114,8 +2114,8 @@ func (c *EC2) DeletePlacementGroup(input *DeletePlacementGroupInput) (*DeletePla const opDeleteRoute = "DeleteRoute" // DeleteRouteRequest generates a request for the DeleteRoute operation. -func (c *EC2) DeleteRouteRequest(input *DeleteRouteInput) (req *service.Request, output *DeleteRouteOutput) { - op := &service.Operation{ +func (c *EC2) DeleteRouteRequest(input *DeleteRouteInput) (req *request.Request, output *DeleteRouteOutput) { + op := &request.Operation{ Name: opDeleteRoute, HTTPMethod: "POST", HTTPPath: "/", @@ -2141,8 +2141,8 @@ func (c *EC2) DeleteRoute(input *DeleteRouteInput) (*DeleteRouteOutput, error) { const opDeleteRouteTable = "DeleteRouteTable" // DeleteRouteTableRequest generates a request for the DeleteRouteTable operation. -func (c *EC2) DeleteRouteTableRequest(input *DeleteRouteTableInput) (req *service.Request, output *DeleteRouteTableOutput) { - op := &service.Operation{ +func (c *EC2) DeleteRouteTableRequest(input *DeleteRouteTableInput) (req *request.Request, output *DeleteRouteTableOutput) { + op := &request.Operation{ Name: opDeleteRouteTable, HTTPMethod: "POST", HTTPPath: "/", @@ -2170,8 +2170,8 @@ func (c *EC2) DeleteRouteTable(input *DeleteRouteTableInput) (*DeleteRouteTableO const opDeleteSecurityGroup = "DeleteSecurityGroup" // DeleteSecurityGroupRequest generates a request for the DeleteSecurityGroup operation. -func (c *EC2) DeleteSecurityGroupRequest(input *DeleteSecurityGroupInput) (req *service.Request, output *DeleteSecurityGroupOutput) { - op := &service.Operation{ +func (c *EC2) DeleteSecurityGroupRequest(input *DeleteSecurityGroupInput) (req *request.Request, output *DeleteSecurityGroupOutput) { + op := &request.Operation{ Name: opDeleteSecurityGroup, HTTPMethod: "POST", HTTPPath: "/", @@ -2201,8 +2201,8 @@ func (c *EC2) DeleteSecurityGroup(input *DeleteSecurityGroupInput) (*DeleteSecur const opDeleteSnapshot = "DeleteSnapshot" // DeleteSnapshotRequest generates a request for the DeleteSnapshot operation. -func (c *EC2) DeleteSnapshotRequest(input *DeleteSnapshotInput) (req *service.Request, output *DeleteSnapshotOutput) { - op := &service.Operation{ +func (c *EC2) DeleteSnapshotRequest(input *DeleteSnapshotInput) (req *request.Request, output *DeleteSnapshotOutput) { + op := &request.Operation{ Name: opDeleteSnapshot, HTTPMethod: "POST", HTTPPath: "/", @@ -2242,8 +2242,8 @@ func (c *EC2) DeleteSnapshot(input *DeleteSnapshotInput) (*DeleteSnapshotOutput, const opDeleteSpotDatafeedSubscription = "DeleteSpotDatafeedSubscription" // DeleteSpotDatafeedSubscriptionRequest generates a request for the DeleteSpotDatafeedSubscription operation. -func (c *EC2) DeleteSpotDatafeedSubscriptionRequest(input *DeleteSpotDatafeedSubscriptionInput) (req *service.Request, output *DeleteSpotDatafeedSubscriptionOutput) { - op := &service.Operation{ +func (c *EC2) DeleteSpotDatafeedSubscriptionRequest(input *DeleteSpotDatafeedSubscriptionInput) (req *request.Request, output *DeleteSpotDatafeedSubscriptionOutput) { + op := &request.Operation{ Name: opDeleteSpotDatafeedSubscription, HTTPMethod: "POST", HTTPPath: "/", @@ -2259,9 +2259,7 @@ func (c *EC2) DeleteSpotDatafeedSubscriptionRequest(input *DeleteSpotDatafeedSub return } -// Deletes the data feed for Spot Instances. For more information, see Spot -// Instance Data Feed (http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-data-feeds.html) -// in the Amazon Elastic Compute Cloud User Guide. +// Deletes the data feed for Spot instances. func (c *EC2) DeleteSpotDatafeedSubscription(input *DeleteSpotDatafeedSubscriptionInput) (*DeleteSpotDatafeedSubscriptionOutput, error) { req, out := c.DeleteSpotDatafeedSubscriptionRequest(input) err := req.Send() @@ -2271,8 +2269,8 @@ func (c *EC2) DeleteSpotDatafeedSubscription(input *DeleteSpotDatafeedSubscripti const opDeleteSubnet = "DeleteSubnet" // DeleteSubnetRequest generates a request for the DeleteSubnet operation. -func (c *EC2) DeleteSubnetRequest(input *DeleteSubnetInput) (req *service.Request, output *DeleteSubnetOutput) { - op := &service.Operation{ +func (c *EC2) DeleteSubnetRequest(input *DeleteSubnetInput) (req *request.Request, output *DeleteSubnetOutput) { + op := &request.Operation{ Name: opDeleteSubnet, HTTPMethod: "POST", HTTPPath: "/", @@ -2299,8 +2297,8 @@ func (c *EC2) DeleteSubnet(input *DeleteSubnetInput) (*DeleteSubnetOutput, error const opDeleteTags = "DeleteTags" // DeleteTagsRequest generates a request for the DeleteTags operation. -func (c *EC2) DeleteTagsRequest(input *DeleteTagsInput) (req *service.Request, output *DeleteTagsOutput) { - op := &service.Operation{ +func (c *EC2) DeleteTagsRequest(input *DeleteTagsInput) (req *request.Request, output *DeleteTagsOutput) { + op := &request.Operation{ Name: opDeleteTags, HTTPMethod: "POST", HTTPPath: "/", @@ -2330,8 +2328,8 @@ func (c *EC2) DeleteTags(input *DeleteTagsInput) (*DeleteTagsOutput, error) { const opDeleteVolume = "DeleteVolume" // DeleteVolumeRequest generates a request for the DeleteVolume operation. -func (c *EC2) DeleteVolumeRequest(input *DeleteVolumeInput) (req *service.Request, output *DeleteVolumeOutput) { - op := &service.Operation{ +func (c *EC2) DeleteVolumeRequest(input *DeleteVolumeInput) (req *request.Request, output *DeleteVolumeOutput) { + op := &request.Operation{ Name: opDeleteVolume, HTTPMethod: "POST", HTTPPath: "/", @@ -2363,8 +2361,8 @@ func (c *EC2) DeleteVolume(input *DeleteVolumeInput) (*DeleteVolumeOutput, error const opDeleteVpc = "DeleteVpc" // DeleteVpcRequest generates a request for the DeleteVpc operation. -func (c *EC2) DeleteVpcRequest(input *DeleteVpcInput) (req *service.Request, output *DeleteVpcOutput) { - op := &service.Operation{ +func (c *EC2) DeleteVpcRequest(input *DeleteVpcInput) (req *request.Request, output *DeleteVpcOutput) { + op := &request.Operation{ Name: opDeleteVpc, HTTPMethod: "POST", HTTPPath: "/", @@ -2394,8 +2392,8 @@ func (c *EC2) DeleteVpc(input *DeleteVpcInput) (*DeleteVpcOutput, error) { const opDeleteVpcEndpoints = "DeleteVpcEndpoints" // DeleteVpcEndpointsRequest generates a request for the DeleteVpcEndpoints operation. -func (c *EC2) DeleteVpcEndpointsRequest(input *DeleteVpcEndpointsInput) (req *service.Request, output *DeleteVpcEndpointsOutput) { - op := &service.Operation{ +func (c *EC2) DeleteVpcEndpointsRequest(input *DeleteVpcEndpointsInput) (req *request.Request, output *DeleteVpcEndpointsOutput) { + op := &request.Operation{ Name: opDeleteVpcEndpoints, HTTPMethod: "POST", HTTPPath: "/", @@ -2422,8 +2420,8 @@ func (c *EC2) DeleteVpcEndpoints(input *DeleteVpcEndpointsInput) (*DeleteVpcEndp const opDeleteVpcPeeringConnection = "DeleteVpcPeeringConnection" // DeleteVpcPeeringConnectionRequest generates a request for the DeleteVpcPeeringConnection operation. -func (c *EC2) DeleteVpcPeeringConnectionRequest(input *DeleteVpcPeeringConnectionInput) (req *service.Request, output *DeleteVpcPeeringConnectionOutput) { - op := &service.Operation{ +func (c *EC2) DeleteVpcPeeringConnectionRequest(input *DeleteVpcPeeringConnectionInput) (req *request.Request, output *DeleteVpcPeeringConnectionOutput) { + op := &request.Operation{ Name: opDeleteVpcPeeringConnection, HTTPMethod: "POST", HTTPPath: "/", @@ -2452,8 +2450,8 @@ func (c *EC2) DeleteVpcPeeringConnection(input *DeleteVpcPeeringConnectionInput) const opDeleteVpnConnection = "DeleteVpnConnection" // DeleteVpnConnectionRequest generates a request for the DeleteVpnConnection operation. -func (c *EC2) DeleteVpnConnectionRequest(input *DeleteVpnConnectionInput) (req *service.Request, output *DeleteVpnConnectionOutput) { - op := &service.Operation{ +func (c *EC2) DeleteVpnConnectionRequest(input *DeleteVpnConnectionInput) (req *request.Request, output *DeleteVpnConnectionOutput) { + op := &request.Operation{ Name: opDeleteVpnConnection, HTTPMethod: "POST", HTTPPath: "/", @@ -2488,8 +2486,8 @@ func (c *EC2) DeleteVpnConnection(input *DeleteVpnConnectionInput) (*DeleteVpnCo const opDeleteVpnConnectionRoute = "DeleteVpnConnectionRoute" // DeleteVpnConnectionRouteRequest generates a request for the DeleteVpnConnectionRoute operation. -func (c *EC2) DeleteVpnConnectionRouteRequest(input *DeleteVpnConnectionRouteInput) (req *service.Request, output *DeleteVpnConnectionRouteOutput) { - op := &service.Operation{ +func (c *EC2) DeleteVpnConnectionRouteRequest(input *DeleteVpnConnectionRouteInput) (req *request.Request, output *DeleteVpnConnectionRouteOutput) { + op := &request.Operation{ Name: opDeleteVpnConnectionRoute, HTTPMethod: "POST", HTTPPath: "/", @@ -2518,8 +2516,8 @@ func (c *EC2) DeleteVpnConnectionRoute(input *DeleteVpnConnectionRouteInput) (*D const opDeleteVpnGateway = "DeleteVpnGateway" // DeleteVpnGatewayRequest generates a request for the DeleteVpnGateway operation. -func (c *EC2) DeleteVpnGatewayRequest(input *DeleteVpnGatewayInput) (req *service.Request, output *DeleteVpnGatewayOutput) { - op := &service.Operation{ +func (c *EC2) DeleteVpnGatewayRequest(input *DeleteVpnGatewayInput) (req *request.Request, output *DeleteVpnGatewayOutput) { + op := &request.Operation{ Name: opDeleteVpnGateway, HTTPMethod: "POST", HTTPPath: "/", @@ -2549,8 +2547,8 @@ func (c *EC2) DeleteVpnGateway(input *DeleteVpnGatewayInput) (*DeleteVpnGatewayO const opDeregisterImage = "DeregisterImage" // DeregisterImageRequest generates a request for the DeregisterImage operation. -func (c *EC2) DeregisterImageRequest(input *DeregisterImageInput) (req *service.Request, output *DeregisterImageOutput) { - op := &service.Operation{ +func (c *EC2) DeregisterImageRequest(input *DeregisterImageInput) (req *request.Request, output *DeregisterImageOutput) { + op := &request.Operation{ Name: opDeregisterImage, HTTPMethod: "POST", HTTPPath: "/", @@ -2579,8 +2577,8 @@ func (c *EC2) DeregisterImage(input *DeregisterImageInput) (*DeregisterImageOutp const opDescribeAccountAttributes = "DescribeAccountAttributes" // DescribeAccountAttributesRequest generates a request for the DescribeAccountAttributes operation. -func (c *EC2) DescribeAccountAttributesRequest(input *DescribeAccountAttributesInput) (req *service.Request, output *DescribeAccountAttributesOutput) { - op := &service.Operation{ +func (c *EC2) DescribeAccountAttributesRequest(input *DescribeAccountAttributesInput) (req *request.Request, output *DescribeAccountAttributesOutput) { + op := &request.Operation{ Name: opDescribeAccountAttributes, HTTPMethod: "POST", HTTPPath: "/", @@ -2624,8 +2622,8 @@ func (c *EC2) DescribeAccountAttributes(input *DescribeAccountAttributesInput) ( const opDescribeAddresses = "DescribeAddresses" // DescribeAddressesRequest generates a request for the DescribeAddresses operation. -func (c *EC2) DescribeAddressesRequest(input *DescribeAddressesInput) (req *service.Request, output *DescribeAddressesOutput) { - op := &service.Operation{ +func (c *EC2) DescribeAddressesRequest(input *DescribeAddressesInput) (req *request.Request, output *DescribeAddressesOutput) { + op := &request.Operation{ Name: opDescribeAddresses, HTTPMethod: "POST", HTTPPath: "/", @@ -2655,8 +2653,8 @@ func (c *EC2) DescribeAddresses(input *DescribeAddressesInput) (*DescribeAddress const opDescribeAvailabilityZones = "DescribeAvailabilityZones" // DescribeAvailabilityZonesRequest generates a request for the DescribeAvailabilityZones operation. -func (c *EC2) DescribeAvailabilityZonesRequest(input *DescribeAvailabilityZonesInput) (req *service.Request, output *DescribeAvailabilityZonesOutput) { - op := &service.Operation{ +func (c *EC2) DescribeAvailabilityZonesRequest(input *DescribeAvailabilityZonesInput) (req *request.Request, output *DescribeAvailabilityZonesOutput) { + op := &request.Operation{ Name: opDescribeAvailabilityZones, HTTPMethod: "POST", HTTPPath: "/", @@ -2688,8 +2686,8 @@ func (c *EC2) DescribeAvailabilityZones(input *DescribeAvailabilityZonesInput) ( const opDescribeBundleTasks = "DescribeBundleTasks" // DescribeBundleTasksRequest generates a request for the DescribeBundleTasks operation. -func (c *EC2) DescribeBundleTasksRequest(input *DescribeBundleTasksInput) (req *service.Request, output *DescribeBundleTasksOutput) { - op := &service.Operation{ +func (c *EC2) DescribeBundleTasksRequest(input *DescribeBundleTasksInput) (req *request.Request, output *DescribeBundleTasksOutput) { + op := &request.Operation{ Name: opDescribeBundleTasks, HTTPMethod: "POST", HTTPPath: "/", @@ -2720,8 +2718,8 @@ func (c *EC2) DescribeBundleTasks(input *DescribeBundleTasksInput) (*DescribeBun const opDescribeClassicLinkInstances = "DescribeClassicLinkInstances" // DescribeClassicLinkInstancesRequest generates a request for the DescribeClassicLinkInstances operation. -func (c *EC2) DescribeClassicLinkInstancesRequest(input *DescribeClassicLinkInstancesInput) (req *service.Request, output *DescribeClassicLinkInstancesOutput) { - op := &service.Operation{ +func (c *EC2) DescribeClassicLinkInstancesRequest(input *DescribeClassicLinkInstancesInput) (req *request.Request, output *DescribeClassicLinkInstancesOutput) { + op := &request.Operation{ Name: opDescribeClassicLinkInstances, HTTPMethod: "POST", HTTPPath: "/", @@ -2750,8 +2748,8 @@ func (c *EC2) DescribeClassicLinkInstances(input *DescribeClassicLinkInstancesIn const opDescribeConversionTasks = "DescribeConversionTasks" // DescribeConversionTasksRequest generates a request for the DescribeConversionTasks operation. -func (c *EC2) DescribeConversionTasksRequest(input *DescribeConversionTasksInput) (req *service.Request, output *DescribeConversionTasksOutput) { - op := &service.Operation{ +func (c *EC2) DescribeConversionTasksRequest(input *DescribeConversionTasksInput) (req *request.Request, output *DescribeConversionTasksOutput) { + op := &request.Operation{ Name: opDescribeConversionTasks, HTTPMethod: "POST", HTTPPath: "/", @@ -2780,8 +2778,8 @@ func (c *EC2) DescribeConversionTasks(input *DescribeConversionTasksInput) (*Des const opDescribeCustomerGateways = "DescribeCustomerGateways" // DescribeCustomerGatewaysRequest generates a request for the DescribeCustomerGateways operation. -func (c *EC2) DescribeCustomerGatewaysRequest(input *DescribeCustomerGatewaysInput) (req *service.Request, output *DescribeCustomerGatewaysOutput) { - op := &service.Operation{ +func (c *EC2) DescribeCustomerGatewaysRequest(input *DescribeCustomerGatewaysInput) (req *request.Request, output *DescribeCustomerGatewaysOutput) { + op := &request.Operation{ Name: opDescribeCustomerGateways, HTTPMethod: "POST", HTTPPath: "/", @@ -2811,8 +2809,8 @@ func (c *EC2) DescribeCustomerGateways(input *DescribeCustomerGatewaysInput) (*D const opDescribeDhcpOptions = "DescribeDhcpOptions" // DescribeDhcpOptionsRequest generates a request for the DescribeDhcpOptions operation. -func (c *EC2) DescribeDhcpOptionsRequest(input *DescribeDhcpOptionsInput) (req *service.Request, output *DescribeDhcpOptionsOutput) { - op := &service.Operation{ +func (c *EC2) DescribeDhcpOptionsRequest(input *DescribeDhcpOptionsInput) (req *request.Request, output *DescribeDhcpOptionsOutput) { + op := &request.Operation{ Name: opDescribeDhcpOptions, HTTPMethod: "POST", HTTPPath: "/", @@ -2841,8 +2839,8 @@ func (c *EC2) DescribeDhcpOptions(input *DescribeDhcpOptionsInput) (*DescribeDhc const opDescribeExportTasks = "DescribeExportTasks" // DescribeExportTasksRequest generates a request for the DescribeExportTasks operation. -func (c *EC2) DescribeExportTasksRequest(input *DescribeExportTasksInput) (req *service.Request, output *DescribeExportTasksOutput) { - op := &service.Operation{ +func (c *EC2) DescribeExportTasksRequest(input *DescribeExportTasksInput) (req *request.Request, output *DescribeExportTasksOutput) { + op := &request.Operation{ Name: opDescribeExportTasks, HTTPMethod: "POST", HTTPPath: "/", @@ -2868,8 +2866,8 @@ func (c *EC2) DescribeExportTasks(input *DescribeExportTasksInput) (*DescribeExp const opDescribeFlowLogs = "DescribeFlowLogs" // DescribeFlowLogsRequest generates a request for the DescribeFlowLogs operation. -func (c *EC2) DescribeFlowLogsRequest(input *DescribeFlowLogsInput) (req *service.Request, output *DescribeFlowLogsOutput) { - op := &service.Operation{ +func (c *EC2) DescribeFlowLogsRequest(input *DescribeFlowLogsInput) (req *request.Request, output *DescribeFlowLogsOutput) { + op := &request.Operation{ Name: opDescribeFlowLogs, HTTPMethod: "POST", HTTPPath: "/", @@ -2897,8 +2895,8 @@ func (c *EC2) DescribeFlowLogs(input *DescribeFlowLogsInput) (*DescribeFlowLogsO const opDescribeImageAttribute = "DescribeImageAttribute" // DescribeImageAttributeRequest generates a request for the DescribeImageAttribute operation. -func (c *EC2) DescribeImageAttributeRequest(input *DescribeImageAttributeInput) (req *service.Request, output *DescribeImageAttributeOutput) { - op := &service.Operation{ +func (c *EC2) DescribeImageAttributeRequest(input *DescribeImageAttributeInput) (req *request.Request, output *DescribeImageAttributeOutput) { + op := &request.Operation{ Name: opDescribeImageAttribute, HTTPMethod: "POST", HTTPPath: "/", @@ -2925,8 +2923,8 @@ func (c *EC2) DescribeImageAttribute(input *DescribeImageAttributeInput) (*Descr const opDescribeImages = "DescribeImages" // DescribeImagesRequest generates a request for the DescribeImages operation. -func (c *EC2) DescribeImagesRequest(input *DescribeImagesInput) (req *service.Request, output *DescribeImagesOutput) { - op := &service.Operation{ +func (c *EC2) DescribeImagesRequest(input *DescribeImagesInput) (req *request.Request, output *DescribeImagesOutput) { + op := &request.Operation{ Name: opDescribeImages, HTTPMethod: "POST", HTTPPath: "/", @@ -2958,8 +2956,8 @@ func (c *EC2) DescribeImages(input *DescribeImagesInput) (*DescribeImagesOutput, const opDescribeImportImageTasks = "DescribeImportImageTasks" // DescribeImportImageTasksRequest generates a request for the DescribeImportImageTasks operation. -func (c *EC2) DescribeImportImageTasksRequest(input *DescribeImportImageTasksInput) (req *service.Request, output *DescribeImportImageTasksOutput) { - op := &service.Operation{ +func (c *EC2) DescribeImportImageTasksRequest(input *DescribeImportImageTasksInput) (req *request.Request, output *DescribeImportImageTasksOutput) { + op := &request.Operation{ Name: opDescribeImportImageTasks, HTTPMethod: "POST", HTTPPath: "/", @@ -2986,8 +2984,8 @@ func (c *EC2) DescribeImportImageTasks(input *DescribeImportImageTasksInput) (*D const opDescribeImportSnapshotTasks = "DescribeImportSnapshotTasks" // DescribeImportSnapshotTasksRequest generates a request for the DescribeImportSnapshotTasks operation. -func (c *EC2) DescribeImportSnapshotTasksRequest(input *DescribeImportSnapshotTasksInput) (req *service.Request, output *DescribeImportSnapshotTasksOutput) { - op := &service.Operation{ +func (c *EC2) DescribeImportSnapshotTasksRequest(input *DescribeImportSnapshotTasksInput) (req *request.Request, output *DescribeImportSnapshotTasksOutput) { + op := &request.Operation{ Name: opDescribeImportSnapshotTasks, HTTPMethod: "POST", HTTPPath: "/", @@ -3013,8 +3011,8 @@ func (c *EC2) DescribeImportSnapshotTasks(input *DescribeImportSnapshotTasksInpu const opDescribeInstanceAttribute = "DescribeInstanceAttribute" // DescribeInstanceAttributeRequest generates a request for the DescribeInstanceAttribute operation. -func (c *EC2) DescribeInstanceAttributeRequest(input *DescribeInstanceAttributeInput) (req *service.Request, output *DescribeInstanceAttributeOutput) { - op := &service.Operation{ +func (c *EC2) DescribeInstanceAttributeRequest(input *DescribeInstanceAttributeInput) (req *request.Request, output *DescribeInstanceAttributeOutput) { + op := &request.Operation{ Name: opDescribeInstanceAttribute, HTTPMethod: "POST", HTTPPath: "/", @@ -3044,12 +3042,12 @@ func (c *EC2) DescribeInstanceAttribute(input *DescribeInstanceAttributeInput) ( const opDescribeInstanceStatus = "DescribeInstanceStatus" // DescribeInstanceStatusRequest generates a request for the DescribeInstanceStatus operation. -func (c *EC2) DescribeInstanceStatusRequest(input *DescribeInstanceStatusInput) (req *service.Request, output *DescribeInstanceStatusOutput) { - op := &service.Operation{ +func (c *EC2) DescribeInstanceStatusRequest(input *DescribeInstanceStatusInput) (req *request.Request, output *DescribeInstanceStatusOutput) { + op := &request.Operation{ Name: opDescribeInstanceStatus, HTTPMethod: "POST", HTTPPath: "/", - Paginator: &service.Paginator{ + Paginator: &request.Paginator{ InputTokens: []string{"NextToken"}, OutputTokens: []string{"NextToken"}, LimitToken: "MaxResults", @@ -3103,12 +3101,12 @@ func (c *EC2) DescribeInstanceStatusPages(input *DescribeInstanceStatusInput, fn const opDescribeInstances = "DescribeInstances" // DescribeInstancesRequest generates a request for the DescribeInstances operation. -func (c *EC2) DescribeInstancesRequest(input *DescribeInstancesInput) (req *service.Request, output *DescribeInstancesOutput) { - op := &service.Operation{ +func (c *EC2) DescribeInstancesRequest(input *DescribeInstancesInput) (req *request.Request, output *DescribeInstancesOutput) { + op := &request.Operation{ Name: opDescribeInstances, HTTPMethod: "POST", HTTPPath: "/", - Paginator: &service.Paginator{ + Paginator: &request.Paginator{ InputTokens: []string{"NextToken"}, OutputTokens: []string{"NextToken"}, LimitToken: "MaxResults", @@ -3152,8 +3150,8 @@ func (c *EC2) DescribeInstancesPages(input *DescribeInstancesInput, fn func(p *D const opDescribeInternetGateways = "DescribeInternetGateways" // DescribeInternetGatewaysRequest generates a request for the DescribeInternetGateways operation. -func (c *EC2) DescribeInternetGatewaysRequest(input *DescribeInternetGatewaysInput) (req *service.Request, output *DescribeInternetGatewaysOutput) { - op := &service.Operation{ +func (c *EC2) DescribeInternetGatewaysRequest(input *DescribeInternetGatewaysInput) (req *request.Request, output *DescribeInternetGatewaysOutput) { + op := &request.Operation{ Name: opDescribeInternetGateways, HTTPMethod: "POST", HTTPPath: "/", @@ -3179,8 +3177,8 @@ func (c *EC2) DescribeInternetGateways(input *DescribeInternetGatewaysInput) (*D const opDescribeKeyPairs = "DescribeKeyPairs" // DescribeKeyPairsRequest generates a request for the DescribeKeyPairs operation. -func (c *EC2) DescribeKeyPairsRequest(input *DescribeKeyPairsInput) (req *service.Request, output *DescribeKeyPairsOutput) { - op := &service.Operation{ +func (c *EC2) DescribeKeyPairsRequest(input *DescribeKeyPairsInput) (req *request.Request, output *DescribeKeyPairsOutput) { + op := &request.Operation{ Name: opDescribeKeyPairs, HTTPMethod: "POST", HTTPPath: "/", @@ -3209,8 +3207,8 @@ func (c *EC2) DescribeKeyPairs(input *DescribeKeyPairsInput) (*DescribeKeyPairsO const opDescribeMovingAddresses = "DescribeMovingAddresses" // DescribeMovingAddressesRequest generates a request for the DescribeMovingAddresses operation. -func (c *EC2) DescribeMovingAddressesRequest(input *DescribeMovingAddressesInput) (req *service.Request, output *DescribeMovingAddressesOutput) { - op := &service.Operation{ +func (c *EC2) DescribeMovingAddressesRequest(input *DescribeMovingAddressesInput) (req *request.Request, output *DescribeMovingAddressesOutput) { + op := &request.Operation{ Name: opDescribeMovingAddresses, HTTPMethod: "POST", HTTPPath: "/", @@ -3238,8 +3236,8 @@ func (c *EC2) DescribeMovingAddresses(input *DescribeMovingAddressesInput) (*Des const opDescribeNetworkAcls = "DescribeNetworkAcls" // DescribeNetworkAclsRequest generates a request for the DescribeNetworkAcls operation. -func (c *EC2) DescribeNetworkAclsRequest(input *DescribeNetworkAclsInput) (req *service.Request, output *DescribeNetworkAclsOutput) { - op := &service.Operation{ +func (c *EC2) DescribeNetworkAclsRequest(input *DescribeNetworkAclsInput) (req *request.Request, output *DescribeNetworkAclsOutput) { + op := &request.Operation{ Name: opDescribeNetworkAcls, HTTPMethod: "POST", HTTPPath: "/", @@ -3268,8 +3266,8 @@ func (c *EC2) DescribeNetworkAcls(input *DescribeNetworkAclsInput) (*DescribeNet const opDescribeNetworkInterfaceAttribute = "DescribeNetworkInterfaceAttribute" // DescribeNetworkInterfaceAttributeRequest generates a request for the DescribeNetworkInterfaceAttribute operation. -func (c *EC2) DescribeNetworkInterfaceAttributeRequest(input *DescribeNetworkInterfaceAttributeInput) (req *service.Request, output *DescribeNetworkInterfaceAttributeOutput) { - op := &service.Operation{ +func (c *EC2) DescribeNetworkInterfaceAttributeRequest(input *DescribeNetworkInterfaceAttributeInput) (req *request.Request, output *DescribeNetworkInterfaceAttributeOutput) { + op := &request.Operation{ Name: opDescribeNetworkInterfaceAttribute, HTTPMethod: "POST", HTTPPath: "/", @@ -3296,8 +3294,8 @@ func (c *EC2) DescribeNetworkInterfaceAttribute(input *DescribeNetworkInterfaceA const opDescribeNetworkInterfaces = "DescribeNetworkInterfaces" // DescribeNetworkInterfacesRequest generates a request for the DescribeNetworkInterfaces operation. -func (c *EC2) DescribeNetworkInterfacesRequest(input *DescribeNetworkInterfacesInput) (req *service.Request, output *DescribeNetworkInterfacesOutput) { - op := &service.Operation{ +func (c *EC2) DescribeNetworkInterfacesRequest(input *DescribeNetworkInterfacesInput) (req *request.Request, output *DescribeNetworkInterfacesOutput) { + op := &request.Operation{ Name: opDescribeNetworkInterfaces, HTTPMethod: "POST", HTTPPath: "/", @@ -3323,8 +3321,8 @@ func (c *EC2) DescribeNetworkInterfaces(input *DescribeNetworkInterfacesInput) ( const opDescribePlacementGroups = "DescribePlacementGroups" // DescribePlacementGroupsRequest generates a request for the DescribePlacementGroups operation. -func (c *EC2) DescribePlacementGroupsRequest(input *DescribePlacementGroupsInput) (req *service.Request, output *DescribePlacementGroupsOutput) { - op := &service.Operation{ +func (c *EC2) DescribePlacementGroupsRequest(input *DescribePlacementGroupsInput) (req *request.Request, output *DescribePlacementGroupsOutput) { + op := &request.Operation{ Name: opDescribePlacementGroups, HTTPMethod: "POST", HTTPPath: "/", @@ -3352,8 +3350,8 @@ func (c *EC2) DescribePlacementGroups(input *DescribePlacementGroupsInput) (*Des const opDescribePrefixLists = "DescribePrefixLists" // DescribePrefixListsRequest generates a request for the DescribePrefixLists operation. -func (c *EC2) DescribePrefixListsRequest(input *DescribePrefixListsInput) (req *service.Request, output *DescribePrefixListsOutput) { - op := &service.Operation{ +func (c *EC2) DescribePrefixListsRequest(input *DescribePrefixListsInput) (req *request.Request, output *DescribePrefixListsOutput) { + op := &request.Operation{ Name: opDescribePrefixLists, HTTPMethod: "POST", HTTPPath: "/", @@ -3383,8 +3381,8 @@ func (c *EC2) DescribePrefixLists(input *DescribePrefixListsInput) (*DescribePre const opDescribeRegions = "DescribeRegions" // DescribeRegionsRequest generates a request for the DescribeRegions operation. -func (c *EC2) DescribeRegionsRequest(input *DescribeRegionsInput) (req *service.Request, output *DescribeRegionsOutput) { - op := &service.Operation{ +func (c *EC2) DescribeRegionsRequest(input *DescribeRegionsInput) (req *request.Request, output *DescribeRegionsOutput) { + op := &request.Operation{ Name: opDescribeRegions, HTTPMethod: "POST", HTTPPath: "/", @@ -3413,8 +3411,8 @@ func (c *EC2) DescribeRegions(input *DescribeRegionsInput) (*DescribeRegionsOutp const opDescribeReservedInstances = "DescribeReservedInstances" // DescribeReservedInstancesRequest generates a request for the DescribeReservedInstances operation. -func (c *EC2) DescribeReservedInstancesRequest(input *DescribeReservedInstancesInput) (req *service.Request, output *DescribeReservedInstancesOutput) { - op := &service.Operation{ +func (c *EC2) DescribeReservedInstancesRequest(input *DescribeReservedInstancesInput) (req *request.Request, output *DescribeReservedInstancesOutput) { + op := &request.Operation{ Name: opDescribeReservedInstances, HTTPMethod: "POST", HTTPPath: "/", @@ -3443,8 +3441,8 @@ func (c *EC2) DescribeReservedInstances(input *DescribeReservedInstancesInput) ( const opDescribeReservedInstancesListings = "DescribeReservedInstancesListings" // DescribeReservedInstancesListingsRequest generates a request for the DescribeReservedInstancesListings operation. -func (c *EC2) DescribeReservedInstancesListingsRequest(input *DescribeReservedInstancesListingsInput) (req *service.Request, output *DescribeReservedInstancesListingsOutput) { - op := &service.Operation{ +func (c *EC2) DescribeReservedInstancesListingsRequest(input *DescribeReservedInstancesListingsInput) (req *request.Request, output *DescribeReservedInstancesListingsOutput) { + op := &request.Operation{ Name: opDescribeReservedInstancesListings, HTTPMethod: "POST", HTTPPath: "/", @@ -3491,12 +3489,12 @@ func (c *EC2) DescribeReservedInstancesListings(input *DescribeReservedInstances const opDescribeReservedInstancesModifications = "DescribeReservedInstancesModifications" // DescribeReservedInstancesModificationsRequest generates a request for the DescribeReservedInstancesModifications operation. -func (c *EC2) DescribeReservedInstancesModificationsRequest(input *DescribeReservedInstancesModificationsInput) (req *service.Request, output *DescribeReservedInstancesModificationsOutput) { - op := &service.Operation{ +func (c *EC2) DescribeReservedInstancesModificationsRequest(input *DescribeReservedInstancesModificationsInput) (req *request.Request, output *DescribeReservedInstancesModificationsOutput) { + op := &request.Operation{ Name: opDescribeReservedInstancesModifications, HTTPMethod: "POST", HTTPPath: "/", - Paginator: &service.Paginator{ + Paginator: &request.Paginator{ InputTokens: []string{"NextToken"}, OutputTokens: []string{"NextToken"}, LimitToken: "", @@ -3537,12 +3535,12 @@ func (c *EC2) DescribeReservedInstancesModificationsPages(input *DescribeReserve const opDescribeReservedInstancesOfferings = "DescribeReservedInstancesOfferings" // DescribeReservedInstancesOfferingsRequest generates a request for the DescribeReservedInstancesOfferings operation. -func (c *EC2) DescribeReservedInstancesOfferingsRequest(input *DescribeReservedInstancesOfferingsInput) (req *service.Request, output *DescribeReservedInstancesOfferingsOutput) { - op := &service.Operation{ +func (c *EC2) DescribeReservedInstancesOfferingsRequest(input *DescribeReservedInstancesOfferingsInput) (req *request.Request, output *DescribeReservedInstancesOfferingsOutput) { + op := &request.Operation{ Name: opDescribeReservedInstancesOfferings, HTTPMethod: "POST", HTTPPath: "/", - Paginator: &service.Paginator{ + Paginator: &request.Paginator{ InputTokens: []string{"NextToken"}, OutputTokens: []string{"NextToken"}, LimitToken: "MaxResults", @@ -3584,8 +3582,8 @@ func (c *EC2) DescribeReservedInstancesOfferingsPages(input *DescribeReservedIns const opDescribeRouteTables = "DescribeRouteTables" // DescribeRouteTablesRequest generates a request for the DescribeRouteTables operation. -func (c *EC2) DescribeRouteTablesRequest(input *DescribeRouteTablesInput) (req *service.Request, output *DescribeRouteTablesOutput) { - op := &service.Operation{ +func (c *EC2) DescribeRouteTablesRequest(input *DescribeRouteTablesInput) (req *request.Request, output *DescribeRouteTablesOutput) { + op := &request.Operation{ Name: opDescribeRouteTables, HTTPMethod: "POST", HTTPPath: "/", @@ -3619,8 +3617,8 @@ func (c *EC2) DescribeRouteTables(input *DescribeRouteTablesInput) (*DescribeRou const opDescribeSecurityGroups = "DescribeSecurityGroups" // DescribeSecurityGroupsRequest generates a request for the DescribeSecurityGroups operation. -func (c *EC2) DescribeSecurityGroupsRequest(input *DescribeSecurityGroupsInput) (req *service.Request, output *DescribeSecurityGroupsOutput) { - op := &service.Operation{ +func (c *EC2) DescribeSecurityGroupsRequest(input *DescribeSecurityGroupsInput) (req *request.Request, output *DescribeSecurityGroupsOutput) { + op := &request.Operation{ Name: opDescribeSecurityGroups, HTTPMethod: "POST", HTTPPath: "/", @@ -3653,8 +3651,8 @@ func (c *EC2) DescribeSecurityGroups(input *DescribeSecurityGroupsInput) (*Descr const opDescribeSnapshotAttribute = "DescribeSnapshotAttribute" // DescribeSnapshotAttributeRequest generates a request for the DescribeSnapshotAttribute operation. -func (c *EC2) DescribeSnapshotAttributeRequest(input *DescribeSnapshotAttributeInput) (req *service.Request, output *DescribeSnapshotAttributeOutput) { - op := &service.Operation{ +func (c *EC2) DescribeSnapshotAttributeRequest(input *DescribeSnapshotAttributeInput) (req *request.Request, output *DescribeSnapshotAttributeOutput) { + op := &request.Operation{ Name: opDescribeSnapshotAttribute, HTTPMethod: "POST", HTTPPath: "/", @@ -3684,12 +3682,12 @@ func (c *EC2) DescribeSnapshotAttribute(input *DescribeSnapshotAttributeInput) ( const opDescribeSnapshots = "DescribeSnapshots" // DescribeSnapshotsRequest generates a request for the DescribeSnapshots operation. -func (c *EC2) DescribeSnapshotsRequest(input *DescribeSnapshotsInput) (req *service.Request, output *DescribeSnapshotsOutput) { - op := &service.Operation{ +func (c *EC2) DescribeSnapshotsRequest(input *DescribeSnapshotsInput) (req *request.Request, output *DescribeSnapshotsOutput) { + op := &request.Operation{ Name: opDescribeSnapshots, HTTPMethod: "POST", HTTPPath: "/", - Paginator: &service.Paginator{ + Paginator: &request.Paginator{ InputTokens: []string{"NextToken"}, OutputTokens: []string{"NextToken"}, LimitToken: "", @@ -3763,8 +3761,8 @@ func (c *EC2) DescribeSnapshotsPages(input *DescribeSnapshotsInput, fn func(p *D const opDescribeSpotDatafeedSubscription = "DescribeSpotDatafeedSubscription" // DescribeSpotDatafeedSubscriptionRequest generates a request for the DescribeSpotDatafeedSubscription operation. -func (c *EC2) DescribeSpotDatafeedSubscriptionRequest(input *DescribeSpotDatafeedSubscriptionInput) (req *service.Request, output *DescribeSpotDatafeedSubscriptionOutput) { - op := &service.Operation{ +func (c *EC2) DescribeSpotDatafeedSubscriptionRequest(input *DescribeSpotDatafeedSubscriptionInput) (req *request.Request, output *DescribeSpotDatafeedSubscriptionOutput) { + op := &request.Operation{ Name: opDescribeSpotDatafeedSubscription, HTTPMethod: "POST", HTTPPath: "/", @@ -3780,7 +3778,7 @@ func (c *EC2) DescribeSpotDatafeedSubscriptionRequest(input *DescribeSpotDatafee return } -// Describes the data feed for Spot Instances. For more information, see Spot +// Describes the data feed for Spot instances. For more information, see Spot // Instance Data Feed (http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-data-feeds.html) // in the Amazon Elastic Compute Cloud User Guide. func (c *EC2) DescribeSpotDatafeedSubscription(input *DescribeSpotDatafeedSubscriptionInput) (*DescribeSpotDatafeedSubscriptionOutput, error) { @@ -3792,8 +3790,8 @@ func (c *EC2) DescribeSpotDatafeedSubscription(input *DescribeSpotDatafeedSubscr const opDescribeSpotFleetInstances = "DescribeSpotFleetInstances" // DescribeSpotFleetInstancesRequest generates a request for the DescribeSpotFleetInstances operation. -func (c *EC2) DescribeSpotFleetInstancesRequest(input *DescribeSpotFleetInstancesInput) (req *service.Request, output *DescribeSpotFleetInstancesOutput) { - op := &service.Operation{ +func (c *EC2) DescribeSpotFleetInstancesRequest(input *DescribeSpotFleetInstancesInput) (req *request.Request, output *DescribeSpotFleetInstancesOutput) { + op := &request.Operation{ Name: opDescribeSpotFleetInstances, HTTPMethod: "POST", HTTPPath: "/", @@ -3819,8 +3817,8 @@ func (c *EC2) DescribeSpotFleetInstances(input *DescribeSpotFleetInstancesInput) const opDescribeSpotFleetRequestHistory = "DescribeSpotFleetRequestHistory" // DescribeSpotFleetRequestHistoryRequest generates a request for the DescribeSpotFleetRequestHistory operation. -func (c *EC2) DescribeSpotFleetRequestHistoryRequest(input *DescribeSpotFleetRequestHistoryInput) (req *service.Request, output *DescribeSpotFleetRequestHistoryOutput) { - op := &service.Operation{ +func (c *EC2) DescribeSpotFleetRequestHistoryRequest(input *DescribeSpotFleetRequestHistoryInput) (req *request.Request, output *DescribeSpotFleetRequestHistoryOutput) { + op := &request.Operation{ Name: opDescribeSpotFleetRequestHistory, HTTPMethod: "POST", HTTPPath: "/", @@ -3851,8 +3849,8 @@ func (c *EC2) DescribeSpotFleetRequestHistory(input *DescribeSpotFleetRequestHis const opDescribeSpotFleetRequests = "DescribeSpotFleetRequests" // DescribeSpotFleetRequestsRequest generates a request for the DescribeSpotFleetRequests operation. -func (c *EC2) DescribeSpotFleetRequestsRequest(input *DescribeSpotFleetRequestsInput) (req *service.Request, output *DescribeSpotFleetRequestsOutput) { - op := &service.Operation{ +func (c *EC2) DescribeSpotFleetRequestsRequest(input *DescribeSpotFleetRequestsInput) (req *request.Request, output *DescribeSpotFleetRequestsOutput) { + op := &request.Operation{ Name: opDescribeSpotFleetRequests, HTTPMethod: "POST", HTTPPath: "/", @@ -3878,8 +3876,8 @@ func (c *EC2) DescribeSpotFleetRequests(input *DescribeSpotFleetRequestsInput) ( const opDescribeSpotInstanceRequests = "DescribeSpotInstanceRequests" // DescribeSpotInstanceRequestsRequest generates a request for the DescribeSpotInstanceRequests operation. -func (c *EC2) DescribeSpotInstanceRequestsRequest(input *DescribeSpotInstanceRequestsInput) (req *service.Request, output *DescribeSpotInstanceRequestsOutput) { - op := &service.Operation{ +func (c *EC2) DescribeSpotInstanceRequestsRequest(input *DescribeSpotInstanceRequestsInput) (req *request.Request, output *DescribeSpotInstanceRequestsOutput) { + op := &request.Operation{ Name: opDescribeSpotInstanceRequests, HTTPMethod: "POST", HTTPPath: "/", @@ -3895,15 +3893,15 @@ func (c *EC2) DescribeSpotInstanceRequestsRequest(input *DescribeSpotInstanceReq return } -// Describes the Spot Instance requests that belong to your account. Spot Instances +// Describes the Spot instance requests that belong to your account. Spot instances // are instances that Amazon EC2 launches when the bid price that you specify -// exceeds the current Spot Price. Amazon EC2 periodically sets the Spot Price -// based on available Spot Instance capacity and current Spot Instance requests. +// exceeds the current Spot price. Amazon EC2 periodically sets the Spot price +// based on available Spot instance capacity and current Spot instance requests. // For more information, see Spot Instance Requests (http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-requests.html) // in the Amazon Elastic Compute Cloud User Guide. // -// You can use DescribeSpotInstanceRequests to find a running Spot Instance -// by examining the response. If the status of the Spot Instance is fulfilled, +// You can use DescribeSpotInstanceRequests to find a running Spot instance +// by examining the response. If the status of the Spot instance is fulfilled, // the instance ID appears in the response and contains the identifier of the // instance. Alternatively, you can use DescribeInstances with a filter to look // for instances where the instance lifecycle is spot. @@ -3916,12 +3914,12 @@ func (c *EC2) DescribeSpotInstanceRequests(input *DescribeSpotInstanceRequestsIn const opDescribeSpotPriceHistory = "DescribeSpotPriceHistory" // DescribeSpotPriceHistoryRequest generates a request for the DescribeSpotPriceHistory operation. -func (c *EC2) DescribeSpotPriceHistoryRequest(input *DescribeSpotPriceHistoryInput) (req *service.Request, output *DescribeSpotPriceHistoryOutput) { - op := &service.Operation{ +func (c *EC2) DescribeSpotPriceHistoryRequest(input *DescribeSpotPriceHistoryInput) (req *request.Request, output *DescribeSpotPriceHistoryOutput) { + op := &request.Operation{ Name: opDescribeSpotPriceHistory, HTTPMethod: "POST", HTTPPath: "/", - Paginator: &service.Paginator{ + Paginator: &request.Paginator{ InputTokens: []string{"NextToken"}, OutputTokens: []string{"NextToken"}, LimitToken: "MaxResults", @@ -3939,7 +3937,7 @@ func (c *EC2) DescribeSpotPriceHistoryRequest(input *DescribeSpotPriceHistoryInp return } -// Describes the Spot Price history. The prices returned are listed in chronological +// Describes the Spot price history. The prices returned are listed in chronological // order, from the oldest to the most recent, for up to the past 90 days. For // more information, see Spot Instance Pricing History (http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-spot-instances-history.html) // in the Amazon Elastic Compute Cloud User Guide. @@ -3964,8 +3962,8 @@ func (c *EC2) DescribeSpotPriceHistoryPages(input *DescribeSpotPriceHistoryInput const opDescribeSubnets = "DescribeSubnets" // DescribeSubnetsRequest generates a request for the DescribeSubnets operation. -func (c *EC2) DescribeSubnetsRequest(input *DescribeSubnetsInput) (req *service.Request, output *DescribeSubnetsOutput) { - op := &service.Operation{ +func (c *EC2) DescribeSubnetsRequest(input *DescribeSubnetsInput) (req *request.Request, output *DescribeSubnetsOutput) { + op := &request.Operation{ Name: opDescribeSubnets, HTTPMethod: "POST", HTTPPath: "/", @@ -3994,8 +3992,8 @@ func (c *EC2) DescribeSubnets(input *DescribeSubnetsInput) (*DescribeSubnetsOutp const opDescribeTags = "DescribeTags" // DescribeTagsRequest generates a request for the DescribeTags operation. -func (c *EC2) DescribeTagsRequest(input *DescribeTagsInput) (req *service.Request, output *DescribeTagsOutput) { - op := &service.Operation{ +func (c *EC2) DescribeTagsRequest(input *DescribeTagsInput) (req *request.Request, output *DescribeTagsOutput) { + op := &request.Operation{ Name: opDescribeTags, HTTPMethod: "POST", HTTPPath: "/", @@ -4024,8 +4022,8 @@ func (c *EC2) DescribeTags(input *DescribeTagsInput) (*DescribeTagsOutput, error const opDescribeVolumeAttribute = "DescribeVolumeAttribute" // DescribeVolumeAttributeRequest generates a request for the DescribeVolumeAttribute operation. -func (c *EC2) DescribeVolumeAttributeRequest(input *DescribeVolumeAttributeInput) (req *service.Request, output *DescribeVolumeAttributeOutput) { - op := &service.Operation{ +func (c *EC2) DescribeVolumeAttributeRequest(input *DescribeVolumeAttributeInput) (req *request.Request, output *DescribeVolumeAttributeOutput) { + op := &request.Operation{ Name: opDescribeVolumeAttribute, HTTPMethod: "POST", HTTPPath: "/", @@ -4055,12 +4053,12 @@ func (c *EC2) DescribeVolumeAttribute(input *DescribeVolumeAttributeInput) (*Des const opDescribeVolumeStatus = "DescribeVolumeStatus" // DescribeVolumeStatusRequest generates a request for the DescribeVolumeStatus operation. -func (c *EC2) DescribeVolumeStatusRequest(input *DescribeVolumeStatusInput) (req *service.Request, output *DescribeVolumeStatusOutput) { - op := &service.Operation{ +func (c *EC2) DescribeVolumeStatusRequest(input *DescribeVolumeStatusInput) (req *request.Request, output *DescribeVolumeStatusOutput) { + op := &request.Operation{ Name: opDescribeVolumeStatus, HTTPMethod: "POST", HTTPPath: "/", - Paginator: &service.Paginator{ + Paginator: &request.Paginator{ InputTokens: []string{"NextToken"}, OutputTokens: []string{"NextToken"}, LimitToken: "MaxResults", @@ -4129,12 +4127,12 @@ func (c *EC2) DescribeVolumeStatusPages(input *DescribeVolumeStatusInput, fn fun const opDescribeVolumes = "DescribeVolumes" // DescribeVolumesRequest generates a request for the DescribeVolumes operation. -func (c *EC2) DescribeVolumesRequest(input *DescribeVolumesInput) (req *service.Request, output *DescribeVolumesOutput) { - op := &service.Operation{ +func (c *EC2) DescribeVolumesRequest(input *DescribeVolumesInput) (req *request.Request, output *DescribeVolumesOutput) { + op := &request.Operation{ Name: opDescribeVolumes, HTTPMethod: "POST", HTTPPath: "/", - Paginator: &service.Paginator{ + Paginator: &request.Paginator{ InputTokens: []string{"NextToken"}, OutputTokens: []string{"NextToken"}, LimitToken: "MaxResults", @@ -4179,8 +4177,8 @@ func (c *EC2) DescribeVolumesPages(input *DescribeVolumesInput, fn func(p *Descr const opDescribeVpcAttribute = "DescribeVpcAttribute" // DescribeVpcAttributeRequest generates a request for the DescribeVpcAttribute operation. -func (c *EC2) DescribeVpcAttributeRequest(input *DescribeVpcAttributeInput) (req *service.Request, output *DescribeVpcAttributeOutput) { - op := &service.Operation{ +func (c *EC2) DescribeVpcAttributeRequest(input *DescribeVpcAttributeInput) (req *request.Request, output *DescribeVpcAttributeOutput) { + op := &request.Operation{ Name: opDescribeVpcAttribute, HTTPMethod: "POST", HTTPPath: "/", @@ -4207,8 +4205,8 @@ func (c *EC2) DescribeVpcAttribute(input *DescribeVpcAttributeInput) (*DescribeV const opDescribeVpcClassicLink = "DescribeVpcClassicLink" // DescribeVpcClassicLinkRequest generates a request for the DescribeVpcClassicLink operation. -func (c *EC2) DescribeVpcClassicLinkRequest(input *DescribeVpcClassicLinkInput) (req *service.Request, output *DescribeVpcClassicLinkOutput) { - op := &service.Operation{ +func (c *EC2) DescribeVpcClassicLinkRequest(input *DescribeVpcClassicLinkInput) (req *request.Request, output *DescribeVpcClassicLinkOutput) { + op := &request.Operation{ Name: opDescribeVpcClassicLink, HTTPMethod: "POST", HTTPPath: "/", @@ -4234,8 +4232,8 @@ func (c *EC2) DescribeVpcClassicLink(input *DescribeVpcClassicLinkInput) (*Descr const opDescribeVpcEndpointServices = "DescribeVpcEndpointServices" // DescribeVpcEndpointServicesRequest generates a request for the DescribeVpcEndpointServices operation. -func (c *EC2) DescribeVpcEndpointServicesRequest(input *DescribeVpcEndpointServicesInput) (req *service.Request, output *DescribeVpcEndpointServicesOutput) { - op := &service.Operation{ +func (c *EC2) DescribeVpcEndpointServicesRequest(input *DescribeVpcEndpointServicesInput) (req *request.Request, output *DescribeVpcEndpointServicesOutput) { + op := &request.Operation{ Name: opDescribeVpcEndpointServices, HTTPMethod: "POST", HTTPPath: "/", @@ -4262,8 +4260,8 @@ func (c *EC2) DescribeVpcEndpointServices(input *DescribeVpcEndpointServicesInpu const opDescribeVpcEndpoints = "DescribeVpcEndpoints" // DescribeVpcEndpointsRequest generates a request for the DescribeVpcEndpoints operation. -func (c *EC2) DescribeVpcEndpointsRequest(input *DescribeVpcEndpointsInput) (req *service.Request, output *DescribeVpcEndpointsOutput) { - op := &service.Operation{ +func (c *EC2) DescribeVpcEndpointsRequest(input *DescribeVpcEndpointsInput) (req *request.Request, output *DescribeVpcEndpointsOutput) { + op := &request.Operation{ Name: opDescribeVpcEndpoints, HTTPMethod: "POST", HTTPPath: "/", @@ -4289,8 +4287,8 @@ func (c *EC2) DescribeVpcEndpoints(input *DescribeVpcEndpointsInput) (*DescribeV const opDescribeVpcPeeringConnections = "DescribeVpcPeeringConnections" // DescribeVpcPeeringConnectionsRequest generates a request for the DescribeVpcPeeringConnections operation. -func (c *EC2) DescribeVpcPeeringConnectionsRequest(input *DescribeVpcPeeringConnectionsInput) (req *service.Request, output *DescribeVpcPeeringConnectionsOutput) { - op := &service.Operation{ +func (c *EC2) DescribeVpcPeeringConnectionsRequest(input *DescribeVpcPeeringConnectionsInput) (req *request.Request, output *DescribeVpcPeeringConnectionsOutput) { + op := &request.Operation{ Name: opDescribeVpcPeeringConnections, HTTPMethod: "POST", HTTPPath: "/", @@ -4316,8 +4314,8 @@ func (c *EC2) DescribeVpcPeeringConnections(input *DescribeVpcPeeringConnections const opDescribeVpcs = "DescribeVpcs" // DescribeVpcsRequest generates a request for the DescribeVpcs operation. -func (c *EC2) DescribeVpcsRequest(input *DescribeVpcsInput) (req *service.Request, output *DescribeVpcsOutput) { - op := &service.Operation{ +func (c *EC2) DescribeVpcsRequest(input *DescribeVpcsInput) (req *request.Request, output *DescribeVpcsOutput) { + op := &request.Operation{ Name: opDescribeVpcs, HTTPMethod: "POST", HTTPPath: "/", @@ -4343,8 +4341,8 @@ func (c *EC2) DescribeVpcs(input *DescribeVpcsInput) (*DescribeVpcsOutput, error const opDescribeVpnConnections = "DescribeVpnConnections" // DescribeVpnConnectionsRequest generates a request for the DescribeVpnConnections operation. -func (c *EC2) DescribeVpnConnectionsRequest(input *DescribeVpnConnectionsInput) (req *service.Request, output *DescribeVpnConnectionsOutput) { - op := &service.Operation{ +func (c *EC2) DescribeVpnConnectionsRequest(input *DescribeVpnConnectionsInput) (req *request.Request, output *DescribeVpnConnectionsOutput) { + op := &request.Operation{ Name: opDescribeVpnConnections, HTTPMethod: "POST", HTTPPath: "/", @@ -4374,8 +4372,8 @@ func (c *EC2) DescribeVpnConnections(input *DescribeVpnConnectionsInput) (*Descr const opDescribeVpnGateways = "DescribeVpnGateways" // DescribeVpnGatewaysRequest generates a request for the DescribeVpnGateways operation. -func (c *EC2) DescribeVpnGatewaysRequest(input *DescribeVpnGatewaysInput) (req *service.Request, output *DescribeVpnGatewaysOutput) { - op := &service.Operation{ +func (c *EC2) DescribeVpnGatewaysRequest(input *DescribeVpnGatewaysInput) (req *request.Request, output *DescribeVpnGatewaysOutput) { + op := &request.Operation{ Name: opDescribeVpnGateways, HTTPMethod: "POST", HTTPPath: "/", @@ -4405,8 +4403,8 @@ func (c *EC2) DescribeVpnGateways(input *DescribeVpnGatewaysInput) (*DescribeVpn const opDetachClassicLinkVpc = "DetachClassicLinkVpc" // DetachClassicLinkVpcRequest generates a request for the DetachClassicLinkVpc operation. -func (c *EC2) DetachClassicLinkVpcRequest(input *DetachClassicLinkVpcInput) (req *service.Request, output *DetachClassicLinkVpcOutput) { - op := &service.Operation{ +func (c *EC2) DetachClassicLinkVpcRequest(input *DetachClassicLinkVpcInput) (req *request.Request, output *DetachClassicLinkVpcOutput) { + op := &request.Operation{ Name: opDetachClassicLinkVpc, HTTPMethod: "POST", HTTPPath: "/", @@ -4434,8 +4432,8 @@ func (c *EC2) DetachClassicLinkVpc(input *DetachClassicLinkVpcInput) (*DetachCla const opDetachInternetGateway = "DetachInternetGateway" // DetachInternetGatewayRequest generates a request for the DetachInternetGateway operation. -func (c *EC2) DetachInternetGatewayRequest(input *DetachInternetGatewayInput) (req *service.Request, output *DetachInternetGatewayOutput) { - op := &service.Operation{ +func (c *EC2) DetachInternetGatewayRequest(input *DetachInternetGatewayInput) (req *request.Request, output *DetachInternetGatewayOutput) { + op := &request.Operation{ Name: opDetachInternetGateway, HTTPMethod: "POST", HTTPPath: "/", @@ -4463,8 +4461,8 @@ func (c *EC2) DetachInternetGateway(input *DetachInternetGatewayInput) (*DetachI const opDetachNetworkInterface = "DetachNetworkInterface" // DetachNetworkInterfaceRequest generates a request for the DetachNetworkInterface operation. -func (c *EC2) DetachNetworkInterfaceRequest(input *DetachNetworkInterfaceInput) (req *service.Request, output *DetachNetworkInterfaceOutput) { - op := &service.Operation{ +func (c *EC2) DetachNetworkInterfaceRequest(input *DetachNetworkInterfaceInput) (req *request.Request, output *DetachNetworkInterfaceOutput) { + op := &request.Operation{ Name: opDetachNetworkInterface, HTTPMethod: "POST", HTTPPath: "/", @@ -4490,8 +4488,8 @@ func (c *EC2) DetachNetworkInterface(input *DetachNetworkInterfaceInput) (*Detac const opDetachVolume = "DetachVolume" // DetachVolumeRequest generates a request for the DetachVolume operation. -func (c *EC2) DetachVolumeRequest(input *DetachVolumeInput) (req *service.Request, output *VolumeAttachment) { - op := &service.Operation{ +func (c *EC2) DetachVolumeRequest(input *DetachVolumeInput) (req *request.Request, output *VolumeAttachment) { + op := &request.Operation{ Name: opDetachVolume, HTTPMethod: "POST", HTTPPath: "/", @@ -4529,8 +4527,8 @@ func (c *EC2) DetachVolume(input *DetachVolumeInput) (*VolumeAttachment, error) const opDetachVpnGateway = "DetachVpnGateway" // DetachVpnGatewayRequest generates a request for the DetachVpnGateway operation. -func (c *EC2) DetachVpnGatewayRequest(input *DetachVpnGatewayInput) (req *service.Request, output *DetachVpnGatewayOutput) { - op := &service.Operation{ +func (c *EC2) DetachVpnGatewayRequest(input *DetachVpnGatewayInput) (req *request.Request, output *DetachVpnGatewayOutput) { + op := &request.Operation{ Name: opDetachVpnGateway, HTTPMethod: "POST", HTTPPath: "/", @@ -4563,8 +4561,8 @@ func (c *EC2) DetachVpnGateway(input *DetachVpnGatewayInput) (*DetachVpnGatewayO const opDisableVgwRoutePropagation = "DisableVgwRoutePropagation" // DisableVgwRoutePropagationRequest generates a request for the DisableVgwRoutePropagation operation. -func (c *EC2) DisableVgwRoutePropagationRequest(input *DisableVgwRoutePropagationInput) (req *service.Request, output *DisableVgwRoutePropagationOutput) { - op := &service.Operation{ +func (c *EC2) DisableVgwRoutePropagationRequest(input *DisableVgwRoutePropagationInput) (req *request.Request, output *DisableVgwRoutePropagationOutput) { + op := &request.Operation{ Name: opDisableVgwRoutePropagation, HTTPMethod: "POST", HTTPPath: "/", @@ -4591,8 +4589,8 @@ func (c *EC2) DisableVgwRoutePropagation(input *DisableVgwRoutePropagationInput) const opDisableVpcClassicLink = "DisableVpcClassicLink" // DisableVpcClassicLinkRequest generates a request for the DisableVpcClassicLink operation. -func (c *EC2) DisableVpcClassicLinkRequest(input *DisableVpcClassicLinkInput) (req *service.Request, output *DisableVpcClassicLinkOutput) { - op := &service.Operation{ +func (c *EC2) DisableVpcClassicLinkRequest(input *DisableVpcClassicLinkInput) (req *request.Request, output *DisableVpcClassicLinkOutput) { + op := &request.Operation{ Name: opDisableVpcClassicLink, HTTPMethod: "POST", HTTPPath: "/", @@ -4619,8 +4617,8 @@ func (c *EC2) DisableVpcClassicLink(input *DisableVpcClassicLinkInput) (*Disable const opDisassociateAddress = "DisassociateAddress" // DisassociateAddressRequest generates a request for the DisassociateAddress operation. -func (c *EC2) DisassociateAddressRequest(input *DisassociateAddressInput) (req *service.Request, output *DisassociateAddressOutput) { - op := &service.Operation{ +func (c *EC2) DisassociateAddressRequest(input *DisassociateAddressInput) (req *request.Request, output *DisassociateAddressOutput) { + op := &request.Operation{ Name: opDisassociateAddress, HTTPMethod: "POST", HTTPPath: "/", @@ -4654,8 +4652,8 @@ func (c *EC2) DisassociateAddress(input *DisassociateAddressInput) (*Disassociat const opDisassociateRouteTable = "DisassociateRouteTable" // DisassociateRouteTableRequest generates a request for the DisassociateRouteTable operation. -func (c *EC2) DisassociateRouteTableRequest(input *DisassociateRouteTableInput) (req *service.Request, output *DisassociateRouteTableOutput) { - op := &service.Operation{ +func (c *EC2) DisassociateRouteTableRequest(input *DisassociateRouteTableInput) (req *request.Request, output *DisassociateRouteTableOutput) { + op := &request.Operation{ Name: opDisassociateRouteTable, HTTPMethod: "POST", HTTPPath: "/", @@ -4686,8 +4684,8 @@ func (c *EC2) DisassociateRouteTable(input *DisassociateRouteTableInput) (*Disas const opEnableVgwRoutePropagation = "EnableVgwRoutePropagation" // EnableVgwRoutePropagationRequest generates a request for the EnableVgwRoutePropagation operation. -func (c *EC2) EnableVgwRoutePropagationRequest(input *EnableVgwRoutePropagationInput) (req *service.Request, output *EnableVgwRoutePropagationOutput) { - op := &service.Operation{ +func (c *EC2) EnableVgwRoutePropagationRequest(input *EnableVgwRoutePropagationInput) (req *request.Request, output *EnableVgwRoutePropagationOutput) { + op := &request.Operation{ Name: opEnableVgwRoutePropagation, HTTPMethod: "POST", HTTPPath: "/", @@ -4714,8 +4712,8 @@ func (c *EC2) EnableVgwRoutePropagation(input *EnableVgwRoutePropagationInput) ( const opEnableVolumeIO = "EnableVolumeIO" // EnableVolumeIORequest generates a request for the EnableVolumeIO operation. -func (c *EC2) EnableVolumeIORequest(input *EnableVolumeIOInput) (req *service.Request, output *EnableVolumeIOOutput) { - op := &service.Operation{ +func (c *EC2) EnableVolumeIORequest(input *EnableVolumeIOInput) (req *request.Request, output *EnableVolumeIOOutput) { + op := &request.Operation{ Name: opEnableVolumeIO, HTTPMethod: "POST", HTTPPath: "/", @@ -4742,8 +4740,8 @@ func (c *EC2) EnableVolumeIO(input *EnableVolumeIOInput) (*EnableVolumeIOOutput, const opEnableVpcClassicLink = "EnableVpcClassicLink" // EnableVpcClassicLinkRequest generates a request for the EnableVpcClassicLink operation. -func (c *EC2) EnableVpcClassicLinkRequest(input *EnableVpcClassicLinkInput) (req *service.Request, output *EnableVpcClassicLinkOutput) { - op := &service.Operation{ +func (c *EC2) EnableVpcClassicLinkRequest(input *EnableVpcClassicLinkInput) (req *request.Request, output *EnableVpcClassicLinkOutput) { + op := &request.Operation{ Name: opEnableVpcClassicLink, HTTPMethod: "POST", HTTPPath: "/", @@ -4775,8 +4773,8 @@ func (c *EC2) EnableVpcClassicLink(input *EnableVpcClassicLinkInput) (*EnableVpc const opGetConsoleOutput = "GetConsoleOutput" // GetConsoleOutputRequest generates a request for the GetConsoleOutput operation. -func (c *EC2) GetConsoleOutputRequest(input *GetConsoleOutputInput) (req *service.Request, output *GetConsoleOutputOutput) { - op := &service.Operation{ +func (c *EC2) GetConsoleOutputRequest(input *GetConsoleOutputInput) (req *request.Request, output *GetConsoleOutputOutput) { + op := &request.Operation{ Name: opGetConsoleOutput, HTTPMethod: "POST", HTTPPath: "/", @@ -4819,8 +4817,8 @@ func (c *EC2) GetConsoleOutput(input *GetConsoleOutputInput) (*GetConsoleOutputO const opGetPasswordData = "GetPasswordData" // GetPasswordDataRequest generates a request for the GetPasswordData operation. -func (c *EC2) GetPasswordDataRequest(input *GetPasswordDataInput) (req *service.Request, output *GetPasswordDataOutput) { - op := &service.Operation{ +func (c *EC2) GetPasswordDataRequest(input *GetPasswordDataInput) (req *request.Request, output *GetPasswordDataOutput) { + op := &request.Operation{ Name: opGetPasswordData, HTTPMethod: "POST", HTTPPath: "/", @@ -4859,8 +4857,8 @@ func (c *EC2) GetPasswordData(input *GetPasswordDataInput) (*GetPasswordDataOutp const opImportImage = "ImportImage" // ImportImageRequest generates a request for the ImportImage operation. -func (c *EC2) ImportImageRequest(input *ImportImageInput) (req *service.Request, output *ImportImageOutput) { - op := &service.Operation{ +func (c *EC2) ImportImageRequest(input *ImportImageInput) (req *request.Request, output *ImportImageOutput) { + op := &request.Operation{ Name: opImportImage, HTTPMethod: "POST", HTTPPath: "/", @@ -4887,8 +4885,8 @@ func (c *EC2) ImportImage(input *ImportImageInput) (*ImportImageOutput, error) { const opImportInstance = "ImportInstance" // ImportInstanceRequest generates a request for the ImportInstance operation. -func (c *EC2) ImportInstanceRequest(input *ImportInstanceInput) (req *service.Request, output *ImportInstanceOutput) { - op := &service.Operation{ +func (c *EC2) ImportInstanceRequest(input *ImportInstanceInput) (req *request.Request, output *ImportInstanceOutput) { + op := &request.Operation{ Name: opImportInstance, HTTPMethod: "POST", HTTPPath: "/", @@ -4920,8 +4918,8 @@ func (c *EC2) ImportInstance(input *ImportInstanceInput) (*ImportInstanceOutput, const opImportKeyPair = "ImportKeyPair" // ImportKeyPairRequest generates a request for the ImportKeyPair operation. -func (c *EC2) ImportKeyPairRequest(input *ImportKeyPairInput) (req *service.Request, output *ImportKeyPairOutput) { - op := &service.Operation{ +func (c *EC2) ImportKeyPairRequest(input *ImportKeyPairInput) (req *request.Request, output *ImportKeyPairOutput) { + op := &request.Operation{ Name: opImportKeyPair, HTTPMethod: "POST", HTTPPath: "/", @@ -4954,8 +4952,8 @@ func (c *EC2) ImportKeyPair(input *ImportKeyPairInput) (*ImportKeyPairOutput, er const opImportSnapshot = "ImportSnapshot" // ImportSnapshotRequest generates a request for the ImportSnapshot operation. -func (c *EC2) ImportSnapshotRequest(input *ImportSnapshotInput) (req *service.Request, output *ImportSnapshotOutput) { - op := &service.Operation{ +func (c *EC2) ImportSnapshotRequest(input *ImportSnapshotInput) (req *request.Request, output *ImportSnapshotOutput) { + op := &request.Operation{ Name: opImportSnapshot, HTTPMethod: "POST", HTTPPath: "/", @@ -4981,8 +4979,8 @@ func (c *EC2) ImportSnapshot(input *ImportSnapshotInput) (*ImportSnapshotOutput, const opImportVolume = "ImportVolume" // ImportVolumeRequest generates a request for the ImportVolume operation. -func (c *EC2) ImportVolumeRequest(input *ImportVolumeInput) (req *service.Request, output *ImportVolumeOutput) { - op := &service.Operation{ +func (c *EC2) ImportVolumeRequest(input *ImportVolumeInput) (req *request.Request, output *ImportVolumeOutput) { + op := &request.Operation{ Name: opImportVolume, HTTPMethod: "POST", HTTPPath: "/", @@ -5013,8 +5011,8 @@ func (c *EC2) ImportVolume(input *ImportVolumeInput) (*ImportVolumeOutput, error const opModifyImageAttribute = "ModifyImageAttribute" // ModifyImageAttributeRequest generates a request for the ModifyImageAttribute operation. -func (c *EC2) ModifyImageAttributeRequest(input *ModifyImageAttributeInput) (req *service.Request, output *ModifyImageAttributeOutput) { - op := &service.Operation{ +func (c *EC2) ModifyImageAttributeRequest(input *ModifyImageAttributeInput) (req *request.Request, output *ModifyImageAttributeOutput) { + op := &request.Operation{ Name: opModifyImageAttribute, HTTPMethod: "POST", HTTPPath: "/", @@ -5044,8 +5042,8 @@ func (c *EC2) ModifyImageAttribute(input *ModifyImageAttributeInput) (*ModifyIma const opModifyInstanceAttribute = "ModifyInstanceAttribute" // ModifyInstanceAttributeRequest generates a request for the ModifyInstanceAttribute operation. -func (c *EC2) ModifyInstanceAttributeRequest(input *ModifyInstanceAttributeInput) (req *service.Request, output *ModifyInstanceAttributeOutput) { - op := &service.Operation{ +func (c *EC2) ModifyInstanceAttributeRequest(input *ModifyInstanceAttributeInput) (req *request.Request, output *ModifyInstanceAttributeOutput) { + op := &request.Operation{ Name: opModifyInstanceAttribute, HTTPMethod: "POST", HTTPPath: "/", @@ -5076,8 +5074,8 @@ func (c *EC2) ModifyInstanceAttribute(input *ModifyInstanceAttributeInput) (*Mod const opModifyNetworkInterfaceAttribute = "ModifyNetworkInterfaceAttribute" // ModifyNetworkInterfaceAttributeRequest generates a request for the ModifyNetworkInterfaceAttribute operation. -func (c *EC2) ModifyNetworkInterfaceAttributeRequest(input *ModifyNetworkInterfaceAttributeInput) (req *service.Request, output *ModifyNetworkInterfaceAttributeOutput) { - op := &service.Operation{ +func (c *EC2) ModifyNetworkInterfaceAttributeRequest(input *ModifyNetworkInterfaceAttributeInput) (req *request.Request, output *ModifyNetworkInterfaceAttributeOutput) { + op := &request.Operation{ Name: opModifyNetworkInterfaceAttribute, HTTPMethod: "POST", HTTPPath: "/", @@ -5104,8 +5102,8 @@ func (c *EC2) ModifyNetworkInterfaceAttribute(input *ModifyNetworkInterfaceAttri const opModifyReservedInstances = "ModifyReservedInstances" // ModifyReservedInstancesRequest generates a request for the ModifyReservedInstances operation. -func (c *EC2) ModifyReservedInstancesRequest(input *ModifyReservedInstancesInput) (req *service.Request, output *ModifyReservedInstancesOutput) { - op := &service.Operation{ +func (c *EC2) ModifyReservedInstancesRequest(input *ModifyReservedInstancesInput) (req *request.Request, output *ModifyReservedInstancesOutput) { + op := &request.Operation{ Name: opModifyReservedInstances, HTTPMethod: "POST", HTTPPath: "/", @@ -5137,8 +5135,8 @@ func (c *EC2) ModifyReservedInstances(input *ModifyReservedInstancesInput) (*Mod const opModifySnapshotAttribute = "ModifySnapshotAttribute" // ModifySnapshotAttributeRequest generates a request for the ModifySnapshotAttribute operation. -func (c *EC2) ModifySnapshotAttributeRequest(input *ModifySnapshotAttributeInput) (req *service.Request, output *ModifySnapshotAttributeOutput) { - op := &service.Operation{ +func (c *EC2) ModifySnapshotAttributeRequest(input *ModifySnapshotAttributeInput) (req *request.Request, output *ModifySnapshotAttributeOutput) { + op := &request.Operation{ Name: opModifySnapshotAttribute, HTTPMethod: "POST", HTTPPath: "/", @@ -5174,8 +5172,8 @@ func (c *EC2) ModifySnapshotAttribute(input *ModifySnapshotAttributeInput) (*Mod const opModifySubnetAttribute = "ModifySubnetAttribute" // ModifySubnetAttributeRequest generates a request for the ModifySubnetAttribute operation. -func (c *EC2) ModifySubnetAttributeRequest(input *ModifySubnetAttributeInput) (req *service.Request, output *ModifySubnetAttributeOutput) { - op := &service.Operation{ +func (c *EC2) ModifySubnetAttributeRequest(input *ModifySubnetAttributeInput) (req *request.Request, output *ModifySubnetAttributeOutput) { + op := &request.Operation{ Name: opModifySubnetAttribute, HTTPMethod: "POST", HTTPPath: "/", @@ -5201,8 +5199,8 @@ func (c *EC2) ModifySubnetAttribute(input *ModifySubnetAttributeInput) (*ModifyS const opModifyVolumeAttribute = "ModifyVolumeAttribute" // ModifyVolumeAttributeRequest generates a request for the ModifyVolumeAttribute operation. -func (c *EC2) ModifyVolumeAttributeRequest(input *ModifyVolumeAttributeInput) (req *service.Request, output *ModifyVolumeAttributeOutput) { - op := &service.Operation{ +func (c *EC2) ModifyVolumeAttributeRequest(input *ModifyVolumeAttributeInput) (req *request.Request, output *ModifyVolumeAttributeOutput) { + op := &request.Operation{ Name: opModifyVolumeAttribute, HTTPMethod: "POST", HTTPPath: "/", @@ -5237,8 +5235,8 @@ func (c *EC2) ModifyVolumeAttribute(input *ModifyVolumeAttributeInput) (*ModifyV const opModifyVpcAttribute = "ModifyVpcAttribute" // ModifyVpcAttributeRequest generates a request for the ModifyVpcAttribute operation. -func (c *EC2) ModifyVpcAttributeRequest(input *ModifyVpcAttributeInput) (req *service.Request, output *ModifyVpcAttributeOutput) { - op := &service.Operation{ +func (c *EC2) ModifyVpcAttributeRequest(input *ModifyVpcAttributeInput) (req *request.Request, output *ModifyVpcAttributeOutput) { + op := &request.Operation{ Name: opModifyVpcAttribute, HTTPMethod: "POST", HTTPPath: "/", @@ -5264,8 +5262,8 @@ func (c *EC2) ModifyVpcAttribute(input *ModifyVpcAttributeInput) (*ModifyVpcAttr const opModifyVpcEndpoint = "ModifyVpcEndpoint" // ModifyVpcEndpointRequest generates a request for the ModifyVpcEndpoint operation. -func (c *EC2) ModifyVpcEndpointRequest(input *ModifyVpcEndpointInput) (req *service.Request, output *ModifyVpcEndpointOutput) { - op := &service.Operation{ +func (c *EC2) ModifyVpcEndpointRequest(input *ModifyVpcEndpointInput) (req *request.Request, output *ModifyVpcEndpointOutput) { + op := &request.Operation{ Name: opModifyVpcEndpoint, HTTPMethod: "POST", HTTPPath: "/", @@ -5293,8 +5291,8 @@ func (c *EC2) ModifyVpcEndpoint(input *ModifyVpcEndpointInput) (*ModifyVpcEndpoi const opMonitorInstances = "MonitorInstances" // MonitorInstancesRequest generates a request for the MonitorInstances operation. -func (c *EC2) MonitorInstancesRequest(input *MonitorInstancesInput) (req *service.Request, output *MonitorInstancesOutput) { - op := &service.Operation{ +func (c *EC2) MonitorInstancesRequest(input *MonitorInstancesInput) (req *request.Request, output *MonitorInstancesOutput) { + op := &request.Operation{ Name: opMonitorInstances, HTTPMethod: "POST", HTTPPath: "/", @@ -5322,8 +5320,8 @@ func (c *EC2) MonitorInstances(input *MonitorInstancesInput) (*MonitorInstancesO const opMoveAddressToVpc = "MoveAddressToVpc" // MoveAddressToVpcRequest generates a request for the MoveAddressToVpc operation. -func (c *EC2) MoveAddressToVpcRequest(input *MoveAddressToVpcInput) (req *service.Request, output *MoveAddressToVpcOutput) { - op := &service.Operation{ +func (c *EC2) MoveAddressToVpcRequest(input *MoveAddressToVpcInput) (req *request.Request, output *MoveAddressToVpcOutput) { + op := &request.Operation{ Name: opMoveAddressToVpc, HTTPMethod: "POST", HTTPPath: "/", @@ -5355,8 +5353,8 @@ func (c *EC2) MoveAddressToVpc(input *MoveAddressToVpcInput) (*MoveAddressToVpcO const opPurchaseReservedInstancesOffering = "PurchaseReservedInstancesOffering" // PurchaseReservedInstancesOfferingRequest generates a request for the PurchaseReservedInstancesOffering operation. -func (c *EC2) PurchaseReservedInstancesOfferingRequest(input *PurchaseReservedInstancesOfferingInput) (req *service.Request, output *PurchaseReservedInstancesOfferingOutput) { - op := &service.Operation{ +func (c *EC2) PurchaseReservedInstancesOfferingRequest(input *PurchaseReservedInstancesOfferingInput) (req *request.Request, output *PurchaseReservedInstancesOfferingOutput) { + op := &request.Operation{ Name: opPurchaseReservedInstancesOffering, HTTPMethod: "POST", HTTPPath: "/", @@ -5393,8 +5391,8 @@ func (c *EC2) PurchaseReservedInstancesOffering(input *PurchaseReservedInstances const opRebootInstances = "RebootInstances" // RebootInstancesRequest generates a request for the RebootInstances operation. -func (c *EC2) RebootInstancesRequest(input *RebootInstancesInput) (req *service.Request, output *RebootInstancesOutput) { - op := &service.Operation{ +func (c *EC2) RebootInstancesRequest(input *RebootInstancesInput) (req *request.Request, output *RebootInstancesOutput) { + op := &request.Operation{ Name: opRebootInstances, HTTPMethod: "POST", HTTPPath: "/", @@ -5430,8 +5428,8 @@ func (c *EC2) RebootInstances(input *RebootInstancesInput) (*RebootInstancesOutp const opRegisterImage = "RegisterImage" // RegisterImageRequest generates a request for the RegisterImage operation. -func (c *EC2) RegisterImageRequest(input *RegisterImageInput) (req *service.Request, output *RegisterImageOutput) { - op := &service.Operation{ +func (c *EC2) RegisterImageRequest(input *RegisterImageInput) (req *request.Request, output *RegisterImageOutput) { + op := &request.Operation{ Name: opRegisterImage, HTTPMethod: "POST", HTTPPath: "/", @@ -5448,23 +5446,32 @@ func (c *EC2) RegisterImageRequest(input *RegisterImageInput) (req *service.Requ } // Registers an AMI. When you're creating an AMI, this is the final step you -// must complete before you can launch an instance from the AMI. This step is -// required if you're creating an instance store-backed Linux or Windows AMI. -// For more information, see Creating an Instance Store-Backed Linux AMI (http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/creating-an-ami-instance-store.html) -// and Creating an Instance Store-Backed Windows AMI (http://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/Creating_InstanceStoreBacked_WinAMI.html) +// must complete before you can launch an instance from the AMI. For more information +// about creating AMIs, see Creating Your Own AMIs (http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/creating-an-ami.html) // in the Amazon Elastic Compute Cloud User Guide. // // For Amazon EBS-backed instances, CreateImage creates and registers the AMI // in a single request, so you don't have to register the AMI yourself. // -// You can also use RegisterImage to create an Amazon EBS-backed AMI from a -// snapshot of a root device volume. For more information, see Launching an -// Instance from a Backup (http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-launch-snapshot.html) -// in the Amazon Elastic Compute Cloud User Guide. Note that although you can -// create a Windows AMI from a snapshot, you can't launch an instance from the -// AMI - use the CreateImage command instead. +// You can also use RegisterImage to create an Amazon EBS-backed Linux AMI +// from a snapshot of a root device volume. For more information, see Launching +// an Instance from a Snapshot (http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_LaunchingInstanceFromSnapshot.html) +// in the Amazon Elastic Compute Cloud User Guide. // -// If needed, you can deregister an AMI at any time. Any modifications you +// Some Linux distributions, such as Red Hat Enterprise Linux (RHEL) and SUSE +// Linux Enterprise Server (SLES), use the EC2 billingProduct code associated +// with an AMI to verify subscription status for package updates. Creating an +// AMI from an EBS snapshot does not maintain this billing code, and subsequent +// instances launched from such an AMI will not be able to connect to package +// update infrastructure. +// +// Similarly, although you can create a Windows AMI from a snapshot, you can't +// successfully launch an instance from the AMI. +// +// To create Windows AMIs or to create AMIs for Linux operating systems that +// must retain AMI billing codes to work properly, see CreateImage. +// +// If needed, you can deregister an AMI at any time. Any modifications you // make to an AMI backed by an instance store volume invalidates its registration. // If you make changes to an image, deregister the previous image and register // the new image. @@ -5480,8 +5487,8 @@ func (c *EC2) RegisterImage(input *RegisterImageInput) (*RegisterImageOutput, er const opRejectVpcPeeringConnection = "RejectVpcPeeringConnection" // RejectVpcPeeringConnectionRequest generates a request for the RejectVpcPeeringConnection operation. -func (c *EC2) RejectVpcPeeringConnectionRequest(input *RejectVpcPeeringConnectionInput) (req *service.Request, output *RejectVpcPeeringConnectionOutput) { - op := &service.Operation{ +func (c *EC2) RejectVpcPeeringConnectionRequest(input *RejectVpcPeeringConnectionInput) (req *request.Request, output *RejectVpcPeeringConnectionOutput) { + op := &request.Operation{ Name: opRejectVpcPeeringConnection, HTTPMethod: "POST", HTTPPath: "/", @@ -5511,8 +5518,8 @@ func (c *EC2) RejectVpcPeeringConnection(input *RejectVpcPeeringConnectionInput) const opReleaseAddress = "ReleaseAddress" // ReleaseAddressRequest generates a request for the ReleaseAddress operation. -func (c *EC2) ReleaseAddressRequest(input *ReleaseAddressInput) (req *service.Request, output *ReleaseAddressOutput) { - op := &service.Operation{ +func (c *EC2) ReleaseAddressRequest(input *ReleaseAddressInput) (req *request.Request, output *ReleaseAddressOutput) { + op := &request.Operation{ Name: opReleaseAddress, HTTPMethod: "POST", HTTPPath: "/", @@ -5552,8 +5559,8 @@ func (c *EC2) ReleaseAddress(input *ReleaseAddressInput) (*ReleaseAddressOutput, const opReplaceNetworkAclAssociation = "ReplaceNetworkAclAssociation" // ReplaceNetworkAclAssociationRequest generates a request for the ReplaceNetworkAclAssociation operation. -func (c *EC2) ReplaceNetworkAclAssociationRequest(input *ReplaceNetworkAclAssociationInput) (req *service.Request, output *ReplaceNetworkAclAssociationOutput) { - op := &service.Operation{ +func (c *EC2) ReplaceNetworkAclAssociationRequest(input *ReplaceNetworkAclAssociationInput) (req *request.Request, output *ReplaceNetworkAclAssociationOutput) { + op := &request.Operation{ Name: opReplaceNetworkAclAssociation, HTTPMethod: "POST", HTTPPath: "/", @@ -5582,8 +5589,8 @@ func (c *EC2) ReplaceNetworkAclAssociation(input *ReplaceNetworkAclAssociationIn const opReplaceNetworkAclEntry = "ReplaceNetworkAclEntry" // ReplaceNetworkAclEntryRequest generates a request for the ReplaceNetworkAclEntry operation. -func (c *EC2) ReplaceNetworkAclEntryRequest(input *ReplaceNetworkAclEntryInput) (req *service.Request, output *ReplaceNetworkAclEntryOutput) { - op := &service.Operation{ +func (c *EC2) ReplaceNetworkAclEntryRequest(input *ReplaceNetworkAclEntryInput) (req *request.Request, output *ReplaceNetworkAclEntryOutput) { + op := &request.Operation{ Name: opReplaceNetworkAclEntry, HTTPMethod: "POST", HTTPPath: "/", @@ -5611,8 +5618,8 @@ func (c *EC2) ReplaceNetworkAclEntry(input *ReplaceNetworkAclEntryInput) (*Repla const opReplaceRoute = "ReplaceRoute" // ReplaceRouteRequest generates a request for the ReplaceRoute operation. -func (c *EC2) ReplaceRouteRequest(input *ReplaceRouteInput) (req *service.Request, output *ReplaceRouteOutput) { - op := &service.Operation{ +func (c *EC2) ReplaceRouteRequest(input *ReplaceRouteInput) (req *request.Request, output *ReplaceRouteOutput) { + op := &request.Operation{ Name: opReplaceRoute, HTTPMethod: "POST", HTTPPath: "/", @@ -5643,8 +5650,8 @@ func (c *EC2) ReplaceRoute(input *ReplaceRouteInput) (*ReplaceRouteOutput, error const opReplaceRouteTableAssociation = "ReplaceRouteTableAssociation" // ReplaceRouteTableAssociationRequest generates a request for the ReplaceRouteTableAssociation operation. -func (c *EC2) ReplaceRouteTableAssociationRequest(input *ReplaceRouteTableAssociationInput) (req *service.Request, output *ReplaceRouteTableAssociationOutput) { - op := &service.Operation{ +func (c *EC2) ReplaceRouteTableAssociationRequest(input *ReplaceRouteTableAssociationInput) (req *request.Request, output *ReplaceRouteTableAssociationOutput) { + op := &request.Operation{ Name: opReplaceRouteTableAssociation, HTTPMethod: "POST", HTTPPath: "/", @@ -5678,8 +5685,8 @@ func (c *EC2) ReplaceRouteTableAssociation(input *ReplaceRouteTableAssociationIn const opReportInstanceStatus = "ReportInstanceStatus" // ReportInstanceStatusRequest generates a request for the ReportInstanceStatus operation. -func (c *EC2) ReportInstanceStatusRequest(input *ReportInstanceStatusInput) (req *service.Request, output *ReportInstanceStatusOutput) { - op := &service.Operation{ +func (c *EC2) ReportInstanceStatusRequest(input *ReportInstanceStatusInput) (req *request.Request, output *ReportInstanceStatusOutput) { + op := &request.Operation{ Name: opReportInstanceStatus, HTTPMethod: "POST", HTTPPath: "/", @@ -5711,8 +5718,8 @@ func (c *EC2) ReportInstanceStatus(input *ReportInstanceStatusInput) (*ReportIns const opRequestSpotFleet = "RequestSpotFleet" // RequestSpotFleetRequest generates a request for the RequestSpotFleet operation. -func (c *EC2) RequestSpotFleetRequest(input *RequestSpotFleetInput) (req *service.Request, output *RequestSpotFleetOutput) { - op := &service.Operation{ +func (c *EC2) RequestSpotFleetRequest(input *RequestSpotFleetInput) (req *request.Request, output *RequestSpotFleetOutput) { + op := &request.Operation{ Name: opRequestSpotFleet, HTTPMethod: "POST", HTTPPath: "/", @@ -5730,7 +5737,20 @@ func (c *EC2) RequestSpotFleetRequest(input *RequestSpotFleetInput) (req *servic // Creates a Spot fleet request. // -// For more information, see Spot Fleets (http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-fleet.html) +// You can submit a single request that includes multiple launch specifications +// that vary by instance type, AMI, Availability Zone, or subnet. +// +// By default, the Spot fleet requests Spot instances in the Spot pool where +// the price per unit is the lowest. Each launch specification can include its +// own instance weighting that reflects the value of the instance type to your +// application workload. +// +// Alternatively, you can specify that the Spot fleet distribute the target +// capacity across the Spot pools included in its launch specifications. By +// ensuring that the Spot instances in your Spot fleet are in different Spot +// pools, you can improve the availability of your fleet. +// +// For more information, see Spot Fleet Requests (http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-fleet-requests.html) // in the Amazon Elastic Compute Cloud User Guide. func (c *EC2) RequestSpotFleet(input *RequestSpotFleetInput) (*RequestSpotFleetOutput, error) { req, out := c.RequestSpotFleetRequest(input) @@ -5741,8 +5761,8 @@ func (c *EC2) RequestSpotFleet(input *RequestSpotFleetInput) (*RequestSpotFleetO const opRequestSpotInstances = "RequestSpotInstances" // RequestSpotInstancesRequest generates a request for the RequestSpotInstances operation. -func (c *EC2) RequestSpotInstancesRequest(input *RequestSpotInstancesInput) (req *service.Request, output *RequestSpotInstancesOutput) { - op := &service.Operation{ +func (c *EC2) RequestSpotInstancesRequest(input *RequestSpotInstancesInput) (req *request.Request, output *RequestSpotInstancesOutput) { + op := &request.Operation{ Name: opRequestSpotInstances, HTTPMethod: "POST", HTTPPath: "/", @@ -5758,10 +5778,10 @@ func (c *EC2) RequestSpotInstancesRequest(input *RequestSpotInstancesInput) (req return } -// Creates a Spot Instance request. Spot Instances are instances that Amazon +// Creates a Spot instance request. Spot instances are instances that Amazon // EC2 launches when the bid price that you specify exceeds the current Spot -// Price. Amazon EC2 periodically sets the Spot Price based on available Spot -// Instance capacity and current Spot Instance requests. For more information, +// price. Amazon EC2 periodically sets the Spot price based on available Spot +// Instance capacity and current Spot instance requests. For more information, // see Spot Instance Requests (http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-requests.html) // in the Amazon Elastic Compute Cloud User Guide. func (c *EC2) RequestSpotInstances(input *RequestSpotInstancesInput) (*RequestSpotInstancesOutput, error) { @@ -5773,8 +5793,8 @@ func (c *EC2) RequestSpotInstances(input *RequestSpotInstancesInput) (*RequestSp const opResetImageAttribute = "ResetImageAttribute" // ResetImageAttributeRequest generates a request for the ResetImageAttribute operation. -func (c *EC2) ResetImageAttributeRequest(input *ResetImageAttributeInput) (req *service.Request, output *ResetImageAttributeOutput) { - op := &service.Operation{ +func (c *EC2) ResetImageAttributeRequest(input *ResetImageAttributeInput) (req *request.Request, output *ResetImageAttributeOutput) { + op := &request.Operation{ Name: opResetImageAttribute, HTTPMethod: "POST", HTTPPath: "/", @@ -5802,8 +5822,8 @@ func (c *EC2) ResetImageAttribute(input *ResetImageAttributeInput) (*ResetImageA const opResetInstanceAttribute = "ResetInstanceAttribute" // ResetInstanceAttributeRequest generates a request for the ResetInstanceAttribute operation. -func (c *EC2) ResetInstanceAttributeRequest(input *ResetInstanceAttributeInput) (req *service.Request, output *ResetInstanceAttributeOutput) { - op := &service.Operation{ +func (c *EC2) ResetInstanceAttributeRequest(input *ResetInstanceAttributeInput) (req *request.Request, output *ResetInstanceAttributeOutput) { + op := &request.Operation{ Name: opResetInstanceAttribute, HTTPMethod: "POST", HTTPPath: "/", @@ -5837,8 +5857,8 @@ func (c *EC2) ResetInstanceAttribute(input *ResetInstanceAttributeInput) (*Reset const opResetNetworkInterfaceAttribute = "ResetNetworkInterfaceAttribute" // ResetNetworkInterfaceAttributeRequest generates a request for the ResetNetworkInterfaceAttribute operation. -func (c *EC2) ResetNetworkInterfaceAttributeRequest(input *ResetNetworkInterfaceAttributeInput) (req *service.Request, output *ResetNetworkInterfaceAttributeOutput) { - op := &service.Operation{ +func (c *EC2) ResetNetworkInterfaceAttributeRequest(input *ResetNetworkInterfaceAttributeInput) (req *request.Request, output *ResetNetworkInterfaceAttributeOutput) { + op := &request.Operation{ Name: opResetNetworkInterfaceAttribute, HTTPMethod: "POST", HTTPPath: "/", @@ -5865,8 +5885,8 @@ func (c *EC2) ResetNetworkInterfaceAttribute(input *ResetNetworkInterfaceAttribu const opResetSnapshotAttribute = "ResetSnapshotAttribute" // ResetSnapshotAttributeRequest generates a request for the ResetSnapshotAttribute operation. -func (c *EC2) ResetSnapshotAttributeRequest(input *ResetSnapshotAttributeInput) (req *service.Request, output *ResetSnapshotAttributeOutput) { - op := &service.Operation{ +func (c *EC2) ResetSnapshotAttributeRequest(input *ResetSnapshotAttributeInput) (req *request.Request, output *ResetSnapshotAttributeOutput) { + op := &request.Operation{ Name: opResetSnapshotAttribute, HTTPMethod: "POST", HTTPPath: "/", @@ -5896,8 +5916,8 @@ func (c *EC2) ResetSnapshotAttribute(input *ResetSnapshotAttributeInput) (*Reset const opRestoreAddressToClassic = "RestoreAddressToClassic" // RestoreAddressToClassicRequest generates a request for the RestoreAddressToClassic operation. -func (c *EC2) RestoreAddressToClassicRequest(input *RestoreAddressToClassicInput) (req *service.Request, output *RestoreAddressToClassicOutput) { - op := &service.Operation{ +func (c *EC2) RestoreAddressToClassicRequest(input *RestoreAddressToClassicInput) (req *request.Request, output *RestoreAddressToClassicOutput) { + op := &request.Operation{ Name: opRestoreAddressToClassic, HTTPMethod: "POST", HTTPPath: "/", @@ -5926,8 +5946,8 @@ func (c *EC2) RestoreAddressToClassic(input *RestoreAddressToClassicInput) (*Res const opRevokeSecurityGroupEgress = "RevokeSecurityGroupEgress" // RevokeSecurityGroupEgressRequest generates a request for the RevokeSecurityGroupEgress operation. -func (c *EC2) RevokeSecurityGroupEgressRequest(input *RevokeSecurityGroupEgressInput) (req *service.Request, output *RevokeSecurityGroupEgressOutput) { - op := &service.Operation{ +func (c *EC2) RevokeSecurityGroupEgressRequest(input *RevokeSecurityGroupEgressInput) (req *request.Request, output *RevokeSecurityGroupEgressOutput) { + op := &request.Operation{ Name: opRevokeSecurityGroupEgress, HTTPMethod: "POST", HTTPPath: "/", @@ -5963,8 +5983,8 @@ func (c *EC2) RevokeSecurityGroupEgress(input *RevokeSecurityGroupEgressInput) ( const opRevokeSecurityGroupIngress = "RevokeSecurityGroupIngress" // RevokeSecurityGroupIngressRequest generates a request for the RevokeSecurityGroupIngress operation. -func (c *EC2) RevokeSecurityGroupIngressRequest(input *RevokeSecurityGroupIngressInput) (req *service.Request, output *RevokeSecurityGroupIngressOutput) { - op := &service.Operation{ +func (c *EC2) RevokeSecurityGroupIngressRequest(input *RevokeSecurityGroupIngressInput) (req *request.Request, output *RevokeSecurityGroupIngressOutput) { + op := &request.Operation{ Name: opRevokeSecurityGroupIngress, HTTPMethod: "POST", HTTPPath: "/", @@ -6000,8 +6020,8 @@ func (c *EC2) RevokeSecurityGroupIngress(input *RevokeSecurityGroupIngressInput) const opRunInstances = "RunInstances" // RunInstancesRequest generates a request for the RunInstances operation. -func (c *EC2) RunInstancesRequest(input *RunInstancesInput) (req *service.Request, output *Reservation) { - op := &service.Operation{ +func (c *EC2) RunInstancesRequest(input *RunInstancesInput) (req *request.Request, output *Reservation) { + op := &request.Operation{ Name: opRunInstances, HTTPMethod: "POST", HTTPPath: "/", @@ -6029,6 +6049,12 @@ func (c *EC2) RunInstancesRequest(input *RunInstancesInput) (req *service.Reques // (http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-network-security.html) // in the Amazon Elastic Compute Cloud User Guide. // +// [EC2-VPC only accounts] If you don't specify a subnet in the request, we +// choose a default subnet from your default VPC for you. +// +// [EC2-Classic accounts] If you're launching into EC2-Classic and you don't +// specify an Availability Zone, we choose one for you. +// // Linux instances have access to the public key of the key pair at boot. You // can use this key to provide secure access to the instance. Amazon EC2 public // images use this feature to provide secure access without passwords. For more @@ -6059,8 +6085,8 @@ func (c *EC2) RunInstances(input *RunInstancesInput) (*Reservation, error) { const opStartInstances = "StartInstances" // StartInstancesRequest generates a request for the StartInstances operation. -func (c *EC2) StartInstancesRequest(input *StartInstancesInput) (req *service.Request, output *StartInstancesOutput) { - op := &service.Operation{ +func (c *EC2) StartInstancesRequest(input *StartInstancesInput) (req *request.Request, output *StartInstancesOutput) { + op := &request.Operation{ Name: opStartInstances, HTTPMethod: "POST", HTTPPath: "/", @@ -6104,8 +6130,8 @@ func (c *EC2) StartInstances(input *StartInstancesInput) (*StartInstancesOutput, const opStopInstances = "StopInstances" // StopInstancesRequest generates a request for the StopInstances operation. -func (c *EC2) StopInstancesRequest(input *StopInstancesInput) (req *service.Request, output *StopInstancesOutput) { - op := &service.Operation{ +func (c *EC2) StopInstancesRequest(input *StopInstancesInput) (req *request.Request, output *StopInstancesOutput) { + op := &request.Operation{ Name: opStopInstances, HTTPMethod: "POST", HTTPPath: "/", @@ -6161,8 +6187,8 @@ func (c *EC2) StopInstances(input *StopInstancesInput) (*StopInstancesOutput, er const opTerminateInstances = "TerminateInstances" // TerminateInstancesRequest generates a request for the TerminateInstances operation. -func (c *EC2) TerminateInstancesRequest(input *TerminateInstancesInput) (req *service.Request, output *TerminateInstancesOutput) { - op := &service.Operation{ +func (c *EC2) TerminateInstancesRequest(input *TerminateInstancesInput) (req *request.Request, output *TerminateInstancesOutput) { + op := &request.Operation{ Name: opTerminateInstances, HTTPMethod: "POST", HTTPPath: "/", @@ -6191,9 +6217,10 @@ func (c *EC2) TerminateInstancesRequest(input *TerminateInstancesInput) (req *se // instance store-backed instances. What happens to an instance differs if you // stop it or terminate it. For example, when you stop an instance, the root // device and any other devices attached to the instance persist. When you terminate -// an instance, the root device and any other devices attached during the instance -// launch are automatically deleted. For more information about the differences -// between stopping and terminating instances, see Instance Lifecycle (http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-lifecycle.html) +// an instance, any attached EBS volumes with the DeleteOnTermination block +// device mapping parameter set to true are automatically deleted. For more +// information about the differences between stopping and terminating instances, +// see Instance Lifecycle (http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-lifecycle.html) // in the Amazon Elastic Compute Cloud User Guide. // // For more information about troubleshooting, see Troubleshooting Terminating @@ -6208,8 +6235,8 @@ func (c *EC2) TerminateInstances(input *TerminateInstancesInput) (*TerminateInst const opUnassignPrivateIpAddresses = "UnassignPrivateIpAddresses" // UnassignPrivateIpAddressesRequest generates a request for the UnassignPrivateIpAddresses operation. -func (c *EC2) UnassignPrivateIpAddressesRequest(input *UnassignPrivateIpAddressesInput) (req *service.Request, output *UnassignPrivateIpAddressesOutput) { - op := &service.Operation{ +func (c *EC2) UnassignPrivateIpAddressesRequest(input *UnassignPrivateIpAddressesInput) (req *request.Request, output *UnassignPrivateIpAddressesOutput) { + op := &request.Operation{ Name: opUnassignPrivateIpAddresses, HTTPMethod: "POST", HTTPPath: "/", @@ -6235,8 +6262,8 @@ func (c *EC2) UnassignPrivateIpAddresses(input *UnassignPrivateIpAddressesInput) const opUnmonitorInstances = "UnmonitorInstances" // UnmonitorInstancesRequest generates a request for the UnmonitorInstances operation. -func (c *EC2) UnmonitorInstancesRequest(input *UnmonitorInstancesInput) (req *service.Request, output *UnmonitorInstancesOutput) { - op := &service.Operation{ +func (c *EC2) UnmonitorInstancesRequest(input *UnmonitorInstancesInput) (req *request.Request, output *UnmonitorInstancesOutput) { + op := &request.Operation{ Name: opUnmonitorInstances, HTTPMethod: "POST", HTTPPath: "/", @@ -6364,7 +6391,7 @@ type ActiveInstance struct { // The instance type. InstanceType *string `locationName:"instanceType" type:"string"` - // The ID of the Spot Instance request. + // The ID of the Spot instance request. SpotInstanceRequestId *string `locationName:"spotInstanceRequestId" type:"string"` metadataActiveInstance `json:"-" xml:"-"` @@ -7780,7 +7807,7 @@ type CancelSpotInstanceRequestsInput struct { // it is UnauthorizedOperation. DryRun *bool `locationName:"dryRun" type:"boolean"` - // One or more Spot Instance request IDs. + // One or more Spot instance request IDs. SpotInstanceRequestIds []*string `locationName:"SpotInstanceRequestId" locationNameList:"SpotInstanceRequestId" type:"list" required:"true"` metadataCancelSpotInstanceRequestsInput `json:"-" xml:"-"` @@ -7802,7 +7829,7 @@ func (s CancelSpotInstanceRequestsInput) GoString() string { // Contains the output of CancelSpotInstanceRequests. type CancelSpotInstanceRequestsOutput struct { - // One or more Spot Instance requests. + // One or more Spot instance requests. CancelledSpotInstanceRequests []*CancelledSpotInstanceRequest `locationName:"spotInstanceRequestSet" locationNameList:"item" type:"list"` metadataCancelSpotInstanceRequestsOutput `json:"-" xml:"-"` @@ -7822,12 +7849,12 @@ func (s CancelSpotInstanceRequestsOutput) GoString() string { return s.String() } -// Describes a request to cancel a Spot Instance. +// Describes a request to cancel a Spot instance. type CancelledSpotInstanceRequest struct { - // The ID of the Spot Instance request. + // The ID of the Spot instance request. SpotInstanceRequestId *string `locationName:"spotInstanceRequestId" type:"string"` - // The state of the Spot Instance request. + // The state of the Spot instance request. State *string `locationName:"state" type:"string" enum:"CancelSpotInstanceRequestState"` metadataCancelledSpotInstanceRequest `json:"-" xml:"-"` @@ -9072,7 +9099,7 @@ func (s CreateSnapshotInput) GoString() string { // Contains the parameters for CreateSpotDatafeedSubscription. type CreateSpotDatafeedSubscriptionInput struct { - // The Amazon S3 bucket in which to store the Spot Instance data feed. + // The Amazon S3 bucket in which to store the Spot instance data feed. Bucket *string `locationName:"bucket" type:"string" required:"true"` // Checks whether you have the required permissions for the action, without @@ -9103,7 +9130,7 @@ func (s CreateSpotDatafeedSubscriptionInput) GoString() string { // Contains the output of CreateSpotDatafeedSubscription. type CreateSpotDatafeedSubscriptionOutput struct { - // The Spot Instance data feed subscription. + // The Spot instance data feed subscription. SpotDatafeedSubscription *SpotDatafeedSubscription `locationName:"spotDatafeedSubscription" type:"structure"` metadataCreateSpotDatafeedSubscriptionOutput `json:"-" xml:"-"` @@ -13509,7 +13536,9 @@ type DescribeSecurityGroupsInput struct { // it is UnauthorizedOperation. DryRun *bool `locationName:"dryRun" type:"boolean"` - // One or more filters. + // One or more filters. If using multiple filters for rules, the results include + // security groups for which any combination of rules - not necessarily a single + // rule - match all filters. // // description - The description of the security group. // @@ -13801,7 +13830,7 @@ func (s DescribeSpotDatafeedSubscriptionInput) GoString() string { // Contains the output of DescribeSpotDatafeedSubscription. type DescribeSpotDatafeedSubscriptionOutput struct { - // The Spot Instance data feed subscription. + // The Spot instance data feed subscription. SpotDatafeedSubscription *SpotDatafeedSubscription `locationName:"spotDatafeedSubscription" type:"structure"` metadataDescribeSpotDatafeedSubscriptionOutput `json:"-" xml:"-"` @@ -14041,7 +14070,7 @@ type DescribeSpotInstanceRequestsInput struct { // // availability-zone-group - The Availability Zone group. // - // create-time - The time stamp when the Spot Instance request was created. + // create-time - The time stamp when the Spot instance request was created. // // fault-code - The fault code related to the request. // @@ -14049,7 +14078,7 @@ type DescribeSpotInstanceRequestsInput struct { // // instance-id - The ID of the instance that fulfilled the request. // - // launch-group - The Spot Instance launch group. + // launch-group - The Spot instance launch group. // // launch.block-device-mapping.delete-on-termination - Indicates whether // the Amazon EBS volume is deleted on instance termination. @@ -14077,7 +14106,7 @@ type DescribeSpotInstanceRequestsInput struct { // launch.key-name - The name of the key pair the instance launched with. // // launch.monitoring-enabled - Whether monitoring is enabled for the Spot - // Instance. + // instance. // // launch.ramdisk-id - The RAM disk ID. // @@ -14108,21 +14137,21 @@ type DescribeSpotInstanceRequestsInput struct { // product-description - The product description associated with the instance // (Linux/UNIX | Windows). // - // spot-instance-request-id - The Spot Instance request ID. + // spot-instance-request-id - The Spot instance request ID. // - // spot-price - The maximum hourly price for any Spot Instance launched to + // spot-price - The maximum hourly price for any Spot instance launched to // fulfill the request. // - // state - The state of the Spot Instance request (open | active | closed + // state - The state of the Spot instance request (open | active | closed // | cancelled | failed). Spot bid status information can help you track your - // Amazon EC2 Spot Instance requests. For more information, see Spot Bid Status + // Amazon EC2 Spot instance requests. For more information, see Spot Bid Status // (http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-bid-status.html) // in the Amazon Elastic Compute Cloud User Guide. // // status-code - The short code describing the most recent evaluation of - // your Spot Instance request. + // your Spot instance request. // - // status-message - The message explaining the status of the Spot Instance + // status-message - The message explaining the status of the Spot instance // request. // // tag:key=value - The key/value combination of a tag assigned to the resource. @@ -14137,7 +14166,7 @@ type DescribeSpotInstanceRequestsInput struct { // tag-value - The value of a tag assigned to the resource. This filter is // independent of the tag-key filter. // - // type - The type of Spot Instance request (one-time | persistent). + // type - The type of Spot instance request (one-time | persistent). // // launched-availability-zone - The Availability Zone in which the bid is // launched. @@ -14147,7 +14176,7 @@ type DescribeSpotInstanceRequestsInput struct { // valid-until - The end date of the request. Filters []*Filter `locationName:"Filter" locationNameList:"Filter" type:"list"` - // One or more Spot Instance request IDs. + // One or more Spot instance request IDs. SpotInstanceRequestIds []*string `locationName:"SpotInstanceRequestId" locationNameList:"SpotInstanceRequestId" type:"list"` metadataDescribeSpotInstanceRequestsInput `json:"-" xml:"-"` @@ -14169,7 +14198,7 @@ func (s DescribeSpotInstanceRequestsInput) GoString() string { // Contains the output of DescribeSpotInstanceRequests. type DescribeSpotInstanceRequestsOutput struct { - // One or more Spot Instance requests. + // One or more Spot instance requests. SpotInstanceRequests []*SpotInstanceRequest `locationName:"spotInstanceRequestSet" locationNameList:"item" type:"list"` metadataDescribeSpotInstanceRequestsOutput `json:"-" xml:"-"` @@ -14210,14 +14239,14 @@ type DescribeSpotPriceHistoryInput struct { // // instance-type - The type of instance (for example, m1.small). // - // product-description - The product description for the Spot Price (Linux/UNIX + // product-description - The product description for the Spot price (Linux/UNIX // | SUSE Linux | Windows | Linux/UNIX (Amazon VPC) | SUSE Linux (Amazon VPC) // | Windows (Amazon VPC)). // - // spot-price - The Spot Price. The value must match exactly (or use wildcards; + // spot-price - The Spot price. The value must match exactly (or use wildcards; // greater than or less than comparison is not supported). // - // timestamp - The timestamp of the Spot Price history, in UTC format (for + // timestamp - The timestamp of the Spot price history, in UTC format (for // example, YYYY-MM-DDTHH:MM:SSZ). You can use wildcards (* and ?). Greater // than or less than comparison is not supported. Filters []*Filter `locationName:"Filter" locationNameList:"Filter" type:"list"` @@ -14263,7 +14292,7 @@ type DescribeSpotPriceHistoryOutput struct { // when there are no more results to return. NextToken *string `locationName:"nextToken" type:"string"` - // The historical Spot Prices. + // The historical Spot prices. SpotPriceHistory []*SpotPrice `locationName:"spotPriceHistorySet" locationNameList:"item" type:"list"` metadataDescribeSpotPriceHistoryOutput `json:"-" xml:"-"` @@ -16179,32 +16208,32 @@ type EventInformation struct { // For more information, see the description. // // spotInstanceCountLimitExceeded - You've reached the limit on the number - // of Spot Instances that you can launch. + // of Spot instances that you can launch. // // The following are the fleetRequestChange events. // // active - The Spot fleet has been validated and Amazon EC2 is attempting - // to maintain the target number of running Spot Instances. + // to maintain the target number of running Spot instances. // - // cancelled - The Spot fleet is canceled and has no running Spot Instances. + // cancelled - The Spot fleet is canceled and has no running Spot instances. // The Spot fleet will be deleted two days after its instances were terminated. // // cancelled_running - The Spot fleet is canceled and will not launch additional - // Spot Instances, but its existing Spot Instances will continue to run until - // they are interrupted or terminated. + // Spot instances, but its existing Spot instances continue to run until they + // are interrupted or terminated. // - // cancelled_terminating - The Spot fleet is canceled and its Spot Instances + // cancelled_terminating - The Spot fleet is canceled and its Spot instances // are terminating. // // expired - The Spot fleet request has expired. A subsequent event indicates - // that the instances were terminated, if the request was created with terminateInstancesWithExpiration + // that the instances were terminated, if the request was created with TerminateInstancesWithExpiration // set. // // price_update - The bid price for a launch configuration was adjusted because // it was too high. This change is permanent. // // submitted - The Spot fleet request is being evaluated and Amazon EC2 is - // preparing to launch the target number of Spot Instances. + // preparing to launch the target number of Spot instances. // // The following are the instanceChange events. // @@ -18378,7 +18407,7 @@ type ModifyImageAttributeInput struct { LaunchPermission *LaunchPermissionModifications `type:"structure"` // The operation type. - OperationType *string `type:"string"` + OperationType *string `type:"string" enum:"OperationType"` // One or more product codes. After you add a product code to an AMI, it can't // be removed. This is only valid when modifying the productCodes attribute. @@ -18447,7 +18476,8 @@ type ModifyInstanceAttributeInput struct { BlockDeviceMappings []*InstanceBlockDeviceMappingSpecification `locationName:"blockDeviceMapping" locationNameList:"item" type:"list"` // If the value is true, you can't terminate the instance using the Amazon EC2 - // console, CLI, or API; otherwise, you can. + // console, CLI, or API; otherwise, you can. You cannot use this paramater for + // Spot Instances. DisableApiTermination *AttributeBooleanValue `locationName:"disableApiTermination" type:"structure"` // Checks whether you have the required permissions for the action, without @@ -18507,7 +18537,7 @@ type ModifyInstanceAttributeInput struct { UserData *BlobAttributeValue `locationName:"userData" type:"structure"` // A new value for the attribute. Use only with the kernel, ramdisk, userData, - // disableApiTermination, or intanceInitiateShutdownBehavior attribute. + // disableApiTermination, or instanceInitiatedShutdownBehavior attribute. Value *string `locationName:"value" type:"string"` metadataModifyInstanceAttributeInput `json:"-" xml:"-"` @@ -18678,7 +18708,7 @@ type ModifySnapshotAttributeInput struct { GroupNames []*string `locationName:"UserGroup" locationNameList:"GroupName" type:"list"` // The type of operation to perform to the attribute. - OperationType *string `type:"string"` + OperationType *string `type:"string" enum:"OperationType"` // The ID of the snapshot. SnapshotId *string `type:"string" required:"true"` @@ -20418,18 +20448,18 @@ type RequestSpotInstancesInput struct { // The user-specified name for a logical grouping of bids. // // When you specify an Availability Zone group in a Spot Instance request, - // all Spot Instances in the request are launched in the same Availability Zone. + // all Spot instances in the request are launched in the same Availability Zone. // Instance proximity is maintained with this parameter, but the choice of Availability // Zone is not. The group applies only to bids for Spot Instances of the same - // instance type. Any additional Spot Instance requests that are specified with + // instance type. Any additional Spot instance requests that are specified with // the same Availability Zone group name are launched in that same Availability // Zone, as long as at least one instance from the group is still active. // // If there is no active instance running in the Availability Zone group that - // you specify for a new Spot Instance request (all instances are terminated, + // you specify for a new Spot instance request (all instances are terminated, // the bid is expired, or the bid falls below current market), then Amazon EC2 // launches the instance in any Availability Zone where the constraint can be - // met. Consequently, the subsequent set of Spot Instances could be placed in + // met. Consequently, the subsequent set of Spot instances could be placed in // a different zone from the original request, even if you specified the same // Availability Zone group. // @@ -20447,12 +20477,12 @@ type RequestSpotInstancesInput struct { // it is UnauthorizedOperation. DryRun *bool `locationName:"dryRun" type:"boolean"` - // The maximum number of Spot Instances to launch. + // The maximum number of Spot instances to launch. // // Default: 1 InstanceCount *int64 `locationName:"instanceCount" type:"integer"` - // The instance launch group. Launch groups are Spot Instances that launch together + // The instance launch group. Launch groups are Spot instances that launch together // and terminate together. // // Default: Instances are launched and terminated individually @@ -20461,11 +20491,11 @@ type RequestSpotInstancesInput struct { // Describes the launch specification for an instance. LaunchSpecification *RequestSpotLaunchSpecification `type:"structure"` - // The maximum hourly price (bid) for any Spot Instance launched to fulfill + // The maximum hourly price (bid) for any Spot instance launched to fulfill // the request. SpotPrice *string `locationName:"spotPrice" type:"string" required:"true"` - // The Spot Instance request type. + // The Spot instance request type. // // Default: one-time Type *string `locationName:"type" type:"string" enum:"SpotInstanceType"` @@ -20506,7 +20536,7 @@ func (s RequestSpotInstancesInput) GoString() string { // Contains the output of RequestSpotInstances. type RequestSpotInstancesOutput struct { - // One or more Spot Instance requests. + // One or more Spot instance requests. SpotInstanceRequests []*SpotInstanceRequest `locationName:"spotInstanceRequestSet" locationNameList:"item" type:"list"` metadataRequestSpotInstancesOutput `json:"-" xml:"-"` @@ -21751,6 +21781,14 @@ func (s SecurityGroup) GoString() string { // Describes a snapshot. type Snapshot struct { + // The data encryption key identifier for the snapshot. This value is a unique + // identifier that corresponds to the data encryption key that was used to encrypt + // the original volume or snapshot copy. Because data encryption keys are inherited + // by volumes created from snapshots, and vice versa, if snapshots share the + // same data encryption key identifier, then they belong to the same volume/snapshot + // lineage. This parameter is only returned by the DescribeSnapshots API operation. + DataEncryptionKeyId *string `locationName:"dataEncryptionKeyId" type:"string"` + // The description for the snapshot. Description *string `locationName:"description" type:"string"` @@ -21772,7 +21810,8 @@ type Snapshot struct { // The progress of the snapshot, as a percentage. Progress *string `locationName:"progress" type:"string"` - // The ID of the snapshot. + // The ID of the snapshot. Each snapshot receives a unique identifier when it + // is created. SnapshotId *string `locationName:"snapshotId" type:"string"` // The time stamp when the snapshot was initiated. @@ -21781,10 +21820,17 @@ type Snapshot struct { // The snapshot state. State *string `locationName:"status" type:"string" enum:"SnapshotState"` + // Encrypted Amazon EBS snapshots are copied asynchronously. If a snapshot copy + // operation fails (for example, if the proper AWS Key Management Service (AWS + // KMS) permissions are not obtained) this field displays error state details + // to help you diagnose why the error occurred. This parameter is only returned + // by the DescribeSnapshots API operation. + StateMessage *string `locationName:"statusMessage" type:"string"` + // Any tags assigned to the snapshot. Tags []*Tag `locationName:"tagSet" locationNameList:"item" type:"list"` - // The ID of the volume. + // The ID of the volume that was used to create the snapshot. VolumeId *string `locationName:"volumeId" type:"string"` // The size of the volume, in GiB. @@ -21936,12 +21982,12 @@ func (s SnapshotTaskDetail) GoString() string { return s.String() } -// Describes the data feed for a Spot Instance. +// Describes the data feed for a Spot instance. type SpotDatafeedSubscription struct { - // The Amazon S3 bucket where the Spot Instance data feed is located. + // The Amazon S3 bucket where the Spot instance data feed is located. Bucket *string `locationName:"bucket" type:"string"` - // The fault codes for the Spot Instance request, if any. + // The fault codes for the Spot instance request, if any. Fault *SpotInstanceStateFault `locationName:"fault" type:"structure"` // The AWS account ID of the account. @@ -21950,7 +21996,7 @@ type SpotDatafeedSubscription struct { // The prefix that is prepended to data feed files. Prefix *string `locationName:"prefix" type:"string"` - // The state of the Spot Instance data feed subscription. + // The state of the Spot instance data feed subscription. State *string `locationName:"state" type:"string" enum:"DatafeedSubscriptionState"` metadataSpotDatafeedSubscription `json:"-" xml:"-"` @@ -21970,7 +22016,7 @@ func (s SpotDatafeedSubscription) GoString() string { return s.String() } -// Describes the launch specification for an instance. +// Describes the launch specification for one or more Spot instances. type SpotFleetLaunchSpecification struct { // Deprecated. AddressingType *string `locationName:"addressingType" type:"string"` @@ -21978,7 +22024,7 @@ type SpotFleetLaunchSpecification struct { // One or more block device mapping entries. BlockDeviceMappings []*BlockDeviceMapping `locationName:"blockDeviceMapping" locationNameList:"item" type:"list"` - // Indicates whether the instance is optimized for EBS I/O. This optimization + // Indicates whether the instances are optimized for EBS I/O. This optimization // provides dedicated throughput to Amazon EBS and an optimized configuration // stack to provide optimal EBS I/O performance. This optimization isn't available // with all instance types. Additional usage charges apply when using an EBS @@ -21987,7 +22033,7 @@ type SpotFleetLaunchSpecification struct { // Default: false EbsOptimized *bool `locationName:"ebsOptimized" type:"boolean"` - // Describes an IAM instance profile. + // The IAM instance profile. IamInstanceProfile *IamInstanceProfileSpecification `locationName:"iamInstanceProfile" type:"structure"` // The ID of the AMI. @@ -22002,13 +22048,13 @@ type SpotFleetLaunchSpecification struct { // The name of the key pair. KeyName *string `locationName:"keyName" type:"string"` - // Enable or disable monitoring for the instance. + // Enable or disable monitoring for the instances. Monitoring *SpotFleetMonitoring `locationName:"monitoring" type:"structure"` // One or more network interfaces. NetworkInterfaces []*InstanceNetworkInterfaceSpecification `locationName:"networkInterfaceSet" locationNameList:"item" type:"list"` - // Describes Spot Instance placement. + // The placement information. Placement *SpotPlacement `locationName:"placement" type:"structure"` // The ID of the RAM disk. @@ -22020,12 +22066,27 @@ type SpotFleetLaunchSpecification struct { // group. SecurityGroups []*GroupIdentifier `locationName:"groupSet" locationNameList:"item" type:"list"` - // The ID of the subnet in which to launch the instance. + // The bid price per unit hour for the specified instance type. If this value + // is not specified, the default is the Spot bid price specified for the fleet. + // To determine the bid price per unit hour, divide the Spot bid price by the + // value of WeightedCapacity. + SpotPrice *string `locationName:"spotPrice" type:"string"` + + // The ID of the subnet in which to launch the instances. SubnetId *string `locationName:"subnetId" type:"string"` // The Base64-encoded MIME user data to make available to the instances. UserData *string `locationName:"userData" type:"string"` + // The number of units provided by the specified instance type. These are the + // same units that you chose to set the target capacity in terms (instances + // or a performance characteristic such as vCPUs, memory, or I/O). + // + // If the target capacity divided by this value is not a whole number, we round + // the number of instances to the next whole number. If this value is not specified, + // the default is 1. + WeightedCapacity *float64 `locationName:"weightedCapacity" type:"double"` + metadataSpotFleetLaunchSpecification `json:"-" xml:"-"` } @@ -22097,28 +22158,33 @@ func (s SpotFleetRequestConfig) GoString() string { // Describes the configuration of a Spot fleet request. type SpotFleetRequestConfigData struct { + // Determines how to allocate the target capacity across the Spot pools specified + // by the Spot fleet request. The default is lowestPrice. + AllocationStrategy *string `locationName:"allocationStrategy" type:"string" enum:"AllocationStrategy"` + // A unique, case-sensitive identifier you provide to ensure idempotency of // your listings. This helps avoid duplicate listings. For more information, // see Ensuring Idempotency (http://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html). ClientToken *string `locationName:"clientToken" type:"string"` - // Grants the Spot fleet service permission to terminate instances on your behalf - // when you cancel a Spot fleet request using CancelSpotFleetRequests or when + // Grants the Spot fleet permission to terminate Spot instances on your behalf + // when you cancel its Spot fleet request using CancelSpotFleetRequests or when // the Spot fleet request expires, if you set terminateInstancesWithExpiration. IamFleetRole *string `locationName:"iamFleetRole" type:"string" required:"true"` - // Information about the launch specifications for the instances. - LaunchSpecifications []*SpotFleetLaunchSpecification `locationName:"launchSpecifications" locationNameList:"item" type:"list" required:"true"` + // Information about the launch specifications for the Spot fleet request. + LaunchSpecifications []*SpotFleetLaunchSpecification `locationName:"launchSpecifications" locationNameList:"item" min:"1" type:"list" required:"true"` - // The maximum hourly price (bid) for any Spot Instance launched to fulfill - // the request. + // The bid price per unit hour. SpotPrice *string `locationName:"spotPrice" type:"string" required:"true"` - // The maximum number of Spot Instances to launch. + // The number of units to request. You can choose to set the target capacity + // in terms of instances or a performance characteristic that is important to + // your application workload, such as vCPUs, memory, or I/O. TargetCapacity *int64 `locationName:"targetCapacity" type:"integer" required:"true"` - // Indicates whether running instances should be terminated when the Spot fleet - // request expires. + // Indicates whether running Spot instances should be terminated when the Spot + // fleet request expires. TerminateInstancesWithExpiration *bool `locationName:"terminateInstancesWithExpiration" type:"boolean"` // The start date and time of the request, in UTC format (for example, YYYY-MM-DDTHH:MM:SSZ). @@ -22126,7 +22192,7 @@ type SpotFleetRequestConfigData struct { ValidFrom *time.Time `locationName:"validFrom" type:"timestamp" timestampFormat:"iso8601"` // The end date and time of the request, in UTC format (for example, YYYY-MM-DDTHH:MM:SSZ). - // At this point, no new Spot Instance requests are placed or enabled to fulfill + // At this point, no new Spot instance requests are placed or enabled to fulfill // the request. ValidUntil *time.Time `locationName:"validUntil" type:"timestamp" timestampFormat:"iso8601"` @@ -22147,25 +22213,25 @@ func (s SpotFleetRequestConfigData) GoString() string { return s.String() } -// Describe a Spot Instance request. +// Describe a Spot instance request. type SpotInstanceRequest struct { // The Availability Zone group. If you specify the same Availability Zone group - // for all Spot Instance requests, all Spot Instances are launched in the same + // for all Spot instance requests, all Spot instances are launched in the same // Availability Zone. AvailabilityZoneGroup *string `locationName:"availabilityZoneGroup" type:"string"` - // The date and time when the Spot Instance request was created, in UTC format + // The date and time when the Spot instance request was created, in UTC format // (for example, YYYY-MM-DDTHH:MM:SSZ). CreateTime *time.Time `locationName:"createTime" type:"timestamp" timestampFormat:"iso8601"` - // The fault codes for the Spot Instance request, if any. + // The fault codes for the Spot instance request, if any. Fault *SpotInstanceStateFault `locationName:"fault" type:"structure"` - // The instance ID, if an instance has been launched to fulfill the Spot Instance + // The instance ID, if an instance has been launched to fulfill the Spot instance // request. InstanceId *string `locationName:"instanceId" type:"string"` - // The instance launch group. Launch groups are Spot Instances that launch together + // The instance launch group. Launch groups are Spot instances that launch together // and terminate together. LaunchGroup *string `locationName:"launchGroup" type:"string"` @@ -22175,29 +22241,29 @@ type SpotInstanceRequest struct { // The Availability Zone in which the bid is launched. LaunchedAvailabilityZone *string `locationName:"launchedAvailabilityZone" type:"string"` - // The product description associated with the Spot Instance. + // The product description associated with the Spot instance. ProductDescription *string `locationName:"productDescription" type:"string" enum:"RIProductDescription"` - // The ID of the Spot Instance request. + // The ID of the Spot instance request. SpotInstanceRequestId *string `locationName:"spotInstanceRequestId" type:"string"` - // The maximum hourly price (bid) for any Spot Instance launched to fulfill + // The maximum hourly price (bid) for any Spot instance launched to fulfill // the request. SpotPrice *string `locationName:"spotPrice" type:"string"` - // The state of the Spot Instance request. Spot bid status information can help - // you track your Spot Instance requests. For more information, see Spot Bid + // The state of the Spot instance request. Spot bid status information can help + // you track your Spot instance requests. For more information, see Spot Bid // Status (http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-bid-status.html) // in the Amazon Elastic Compute Cloud User Guide. State *string `locationName:"state" type:"string" enum:"SpotInstanceState"` - // The status code and status message describing the Spot Instance request. + // The status code and status message describing the Spot instance request. Status *SpotInstanceStatus `locationName:"status" type:"structure"` // Any tags assigned to the resource. Tags []*Tag `locationName:"tagSet" locationNameList:"item" type:"list"` - // The Spot Instance request type. + // The Spot instance request type. Type *string `locationName:"type" type:"string" enum:"SpotInstanceType"` // The start date of the request, in UTC format (for example, YYYY-MM-DDTHH:MM:SSZ). @@ -22230,12 +22296,12 @@ func (s SpotInstanceRequest) GoString() string { return s.String() } -// Describes a Spot Instance state change. +// Describes a Spot instance state change. type SpotInstanceStateFault struct { - // The reason code for the Spot Instance state change. + // The reason code for the Spot instance state change. Code *string `locationName:"code" type:"string"` - // The message for the Spot Instance state change. + // The message for the Spot instance state change. Message *string `locationName:"message" type:"string"` metadataSpotInstanceStateFault `json:"-" xml:"-"` @@ -22255,7 +22321,7 @@ func (s SpotInstanceStateFault) GoString() string { return s.String() } -// Describes the status of a Spot Instance request. +// Describes the status of a Spot instance request. type SpotInstanceStatus struct { // The status code. Code *string `locationName:"code" type:"string"` @@ -22284,7 +22350,7 @@ func (s SpotInstanceStatus) GoString() string { return s.String() } -// Describes Spot Instance placement. +// Describes Spot instance placement. type SpotPlacement struct { // The Availability Zone. AvailabilityZone *string `locationName:"availabilityZone" type:"string"` @@ -22309,7 +22375,7 @@ func (s SpotPlacement) GoString() string { return s.String() } -// Describes the maximum hourly price (bid) for any Spot Instance launched to +// Describes the maximum hourly price (bid) for any Spot instance launched to // fulfill the request. type SpotPrice struct { // The Availability Zone. @@ -22321,7 +22387,7 @@ type SpotPrice struct { // A general description of the AMI. ProductDescription *string `locationName:"productDescription" type:"string" enum:"RIProductDescription"` - // The maximum price (bid) that you are willing to pay for a Spot Instance. + // The maximum price (bid) that you are willing to pay for a Spot instance. SpotPrice *string `locationName:"spotPrice" type:"string"` // The date and time the request was created, in UTC format (for example, YYYY-MM-DDTHH:MM:SSZ). @@ -22793,7 +22859,7 @@ func (s UnsuccessfulItem) GoString() string { return s.String() } -// Information about the error that occured. For more information about errors, +// Information about the error that occurred. For more information about errors, // see Error Codes (http://docs.aws.amazon.com/AWSEC2/latest/APIReference/errors-overview.html). type UnsuccessfulItemError struct { // The error code. @@ -23627,6 +23693,13 @@ const ( AccountAttributeNameDefaultVpc = "default-vpc" ) +const ( + // @enum AllocationStrategy + AllocationStrategyLowestPrice = "lowestPrice" + // @enum AllocationStrategy + AllocationStrategyDiversified = "diversified" +) + const ( // @enum ArchitectureValues ArchitectureValuesI386 = "i386" @@ -24098,6 +24171,13 @@ const ( OfferingTypeValuesAllUpfront = "All Upfront" ) +const ( + // @enum OperationType + OperationTypeAdd = "add" + // @enum OperationType + OperationTypeRemove = "remove" +) + const ( // @enum PermissionGroup PermissionGroupAll = "all" diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/ec2/customizations.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/ec2/customizations.go index d042baebf..99f082047 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/ec2/customizations.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/ec2/customizations.go @@ -4,18 +4,18 @@ import ( "time" "github.com/aws/aws-sdk-go/aws/awsutil" - "github.com/aws/aws-sdk-go/aws/service" + "github.com/aws/aws-sdk-go/aws/request" ) func init() { - initRequest = func(r *service.Request) { + initRequest = func(r *request.Request) { if r.Operation.Name == opCopySnapshot { // fill the PresignedURL parameter r.Handlers.Build.PushFront(fillPresignedURL) } } } -func fillPresignedURL(r *service.Request) { +func fillPresignedURL(r *request.Request) { if !r.ParamsFilled() { return } diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/ec2/customizations_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/ec2/customizations_test.go deleted file mode 100644 index 38617b1ff..000000000 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/ec2/customizations_test.go +++ /dev/null @@ -1,36 +0,0 @@ -package ec2_test - -import ( - "io/ioutil" - "net/url" - "testing" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/internal/test/unit" - "github.com/aws/aws-sdk-go/service/ec2" - "github.com/stretchr/testify/assert" -) - -var _ = unit.Imported - -func TestCopySnapshotPresignedURL(t *testing.T) { - svc := ec2.New(&aws.Config{Region: aws.String("us-west-2")}) - - assert.NotPanics(t, func() { - // 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)) - url, _ := url.QueryUnescape(q.Get("PresignedUrl")) - assert.Equal(t, "us-west-2", q.Get("DestinationRegion")) - assert.Regexp(t, `^https://ec2\.us-west-1\.amazon.+&DestinationRegion=us-west-2`, url) -} diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/ec2/ec2iface/interface.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/ec2/ec2iface/interface.go index 88ce7c56c..e10a2aa1f 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/ec2/ec2iface/interface.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/ec2/ec2iface/interface.go @@ -4,753 +4,753 @@ package ec2iface import ( - "github.com/aws/aws-sdk-go/aws/service" + "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/service/ec2" ) // EC2API is the interface type for ec2.EC2. type EC2API interface { - AcceptVpcPeeringConnectionRequest(*ec2.AcceptVpcPeeringConnectionInput) (*service.Request, *ec2.AcceptVpcPeeringConnectionOutput) + AcceptVpcPeeringConnectionRequest(*ec2.AcceptVpcPeeringConnectionInput) (*request.Request, *ec2.AcceptVpcPeeringConnectionOutput) AcceptVpcPeeringConnection(*ec2.AcceptVpcPeeringConnectionInput) (*ec2.AcceptVpcPeeringConnectionOutput, error) - AllocateAddressRequest(*ec2.AllocateAddressInput) (*service.Request, *ec2.AllocateAddressOutput) + AllocateAddressRequest(*ec2.AllocateAddressInput) (*request.Request, *ec2.AllocateAddressOutput) AllocateAddress(*ec2.AllocateAddressInput) (*ec2.AllocateAddressOutput, error) - AssignPrivateIpAddressesRequest(*ec2.AssignPrivateIpAddressesInput) (*service.Request, *ec2.AssignPrivateIpAddressesOutput) + AssignPrivateIpAddressesRequest(*ec2.AssignPrivateIpAddressesInput) (*request.Request, *ec2.AssignPrivateIpAddressesOutput) AssignPrivateIpAddresses(*ec2.AssignPrivateIpAddressesInput) (*ec2.AssignPrivateIpAddressesOutput, error) - AssociateAddressRequest(*ec2.AssociateAddressInput) (*service.Request, *ec2.AssociateAddressOutput) + AssociateAddressRequest(*ec2.AssociateAddressInput) (*request.Request, *ec2.AssociateAddressOutput) AssociateAddress(*ec2.AssociateAddressInput) (*ec2.AssociateAddressOutput, error) - AssociateDhcpOptionsRequest(*ec2.AssociateDhcpOptionsInput) (*service.Request, *ec2.AssociateDhcpOptionsOutput) + AssociateDhcpOptionsRequest(*ec2.AssociateDhcpOptionsInput) (*request.Request, *ec2.AssociateDhcpOptionsOutput) AssociateDhcpOptions(*ec2.AssociateDhcpOptionsInput) (*ec2.AssociateDhcpOptionsOutput, error) - AssociateRouteTableRequest(*ec2.AssociateRouteTableInput) (*service.Request, *ec2.AssociateRouteTableOutput) + AssociateRouteTableRequest(*ec2.AssociateRouteTableInput) (*request.Request, *ec2.AssociateRouteTableOutput) AssociateRouteTable(*ec2.AssociateRouteTableInput) (*ec2.AssociateRouteTableOutput, error) - AttachClassicLinkVpcRequest(*ec2.AttachClassicLinkVpcInput) (*service.Request, *ec2.AttachClassicLinkVpcOutput) + AttachClassicLinkVpcRequest(*ec2.AttachClassicLinkVpcInput) (*request.Request, *ec2.AttachClassicLinkVpcOutput) AttachClassicLinkVpc(*ec2.AttachClassicLinkVpcInput) (*ec2.AttachClassicLinkVpcOutput, error) - AttachInternetGatewayRequest(*ec2.AttachInternetGatewayInput) (*service.Request, *ec2.AttachInternetGatewayOutput) + AttachInternetGatewayRequest(*ec2.AttachInternetGatewayInput) (*request.Request, *ec2.AttachInternetGatewayOutput) AttachInternetGateway(*ec2.AttachInternetGatewayInput) (*ec2.AttachInternetGatewayOutput, error) - AttachNetworkInterfaceRequest(*ec2.AttachNetworkInterfaceInput) (*service.Request, *ec2.AttachNetworkInterfaceOutput) + AttachNetworkInterfaceRequest(*ec2.AttachNetworkInterfaceInput) (*request.Request, *ec2.AttachNetworkInterfaceOutput) AttachNetworkInterface(*ec2.AttachNetworkInterfaceInput) (*ec2.AttachNetworkInterfaceOutput, error) - AttachVolumeRequest(*ec2.AttachVolumeInput) (*service.Request, *ec2.VolumeAttachment) + AttachVolumeRequest(*ec2.AttachVolumeInput) (*request.Request, *ec2.VolumeAttachment) AttachVolume(*ec2.AttachVolumeInput) (*ec2.VolumeAttachment, error) - AttachVpnGatewayRequest(*ec2.AttachVpnGatewayInput) (*service.Request, *ec2.AttachVpnGatewayOutput) + AttachVpnGatewayRequest(*ec2.AttachVpnGatewayInput) (*request.Request, *ec2.AttachVpnGatewayOutput) AttachVpnGateway(*ec2.AttachVpnGatewayInput) (*ec2.AttachVpnGatewayOutput, error) - AuthorizeSecurityGroupEgressRequest(*ec2.AuthorizeSecurityGroupEgressInput) (*service.Request, *ec2.AuthorizeSecurityGroupEgressOutput) + AuthorizeSecurityGroupEgressRequest(*ec2.AuthorizeSecurityGroupEgressInput) (*request.Request, *ec2.AuthorizeSecurityGroupEgressOutput) AuthorizeSecurityGroupEgress(*ec2.AuthorizeSecurityGroupEgressInput) (*ec2.AuthorizeSecurityGroupEgressOutput, error) - AuthorizeSecurityGroupIngressRequest(*ec2.AuthorizeSecurityGroupIngressInput) (*service.Request, *ec2.AuthorizeSecurityGroupIngressOutput) + AuthorizeSecurityGroupIngressRequest(*ec2.AuthorizeSecurityGroupIngressInput) (*request.Request, *ec2.AuthorizeSecurityGroupIngressOutput) AuthorizeSecurityGroupIngress(*ec2.AuthorizeSecurityGroupIngressInput) (*ec2.AuthorizeSecurityGroupIngressOutput, error) - BundleInstanceRequest(*ec2.BundleInstanceInput) (*service.Request, *ec2.BundleInstanceOutput) + BundleInstanceRequest(*ec2.BundleInstanceInput) (*request.Request, *ec2.BundleInstanceOutput) BundleInstance(*ec2.BundleInstanceInput) (*ec2.BundleInstanceOutput, error) - CancelBundleTaskRequest(*ec2.CancelBundleTaskInput) (*service.Request, *ec2.CancelBundleTaskOutput) + CancelBundleTaskRequest(*ec2.CancelBundleTaskInput) (*request.Request, *ec2.CancelBundleTaskOutput) CancelBundleTask(*ec2.CancelBundleTaskInput) (*ec2.CancelBundleTaskOutput, error) - CancelConversionTaskRequest(*ec2.CancelConversionTaskInput) (*service.Request, *ec2.CancelConversionTaskOutput) + CancelConversionTaskRequest(*ec2.CancelConversionTaskInput) (*request.Request, *ec2.CancelConversionTaskOutput) CancelConversionTask(*ec2.CancelConversionTaskInput) (*ec2.CancelConversionTaskOutput, error) - CancelExportTaskRequest(*ec2.CancelExportTaskInput) (*service.Request, *ec2.CancelExportTaskOutput) + CancelExportTaskRequest(*ec2.CancelExportTaskInput) (*request.Request, *ec2.CancelExportTaskOutput) CancelExportTask(*ec2.CancelExportTaskInput) (*ec2.CancelExportTaskOutput, error) - CancelImportTaskRequest(*ec2.CancelImportTaskInput) (*service.Request, *ec2.CancelImportTaskOutput) + CancelImportTaskRequest(*ec2.CancelImportTaskInput) (*request.Request, *ec2.CancelImportTaskOutput) CancelImportTask(*ec2.CancelImportTaskInput) (*ec2.CancelImportTaskOutput, error) - CancelReservedInstancesListingRequest(*ec2.CancelReservedInstancesListingInput) (*service.Request, *ec2.CancelReservedInstancesListingOutput) + CancelReservedInstancesListingRequest(*ec2.CancelReservedInstancesListingInput) (*request.Request, *ec2.CancelReservedInstancesListingOutput) CancelReservedInstancesListing(*ec2.CancelReservedInstancesListingInput) (*ec2.CancelReservedInstancesListingOutput, error) - CancelSpotFleetRequestsRequest(*ec2.CancelSpotFleetRequestsInput) (*service.Request, *ec2.CancelSpotFleetRequestsOutput) + CancelSpotFleetRequestsRequest(*ec2.CancelSpotFleetRequestsInput) (*request.Request, *ec2.CancelSpotFleetRequestsOutput) CancelSpotFleetRequests(*ec2.CancelSpotFleetRequestsInput) (*ec2.CancelSpotFleetRequestsOutput, error) - CancelSpotInstanceRequestsRequest(*ec2.CancelSpotInstanceRequestsInput) (*service.Request, *ec2.CancelSpotInstanceRequestsOutput) + CancelSpotInstanceRequestsRequest(*ec2.CancelSpotInstanceRequestsInput) (*request.Request, *ec2.CancelSpotInstanceRequestsOutput) CancelSpotInstanceRequests(*ec2.CancelSpotInstanceRequestsInput) (*ec2.CancelSpotInstanceRequestsOutput, error) - ConfirmProductInstanceRequest(*ec2.ConfirmProductInstanceInput) (*service.Request, *ec2.ConfirmProductInstanceOutput) + ConfirmProductInstanceRequest(*ec2.ConfirmProductInstanceInput) (*request.Request, *ec2.ConfirmProductInstanceOutput) ConfirmProductInstance(*ec2.ConfirmProductInstanceInput) (*ec2.ConfirmProductInstanceOutput, error) - CopyImageRequest(*ec2.CopyImageInput) (*service.Request, *ec2.CopyImageOutput) + CopyImageRequest(*ec2.CopyImageInput) (*request.Request, *ec2.CopyImageOutput) CopyImage(*ec2.CopyImageInput) (*ec2.CopyImageOutput, error) - CopySnapshotRequest(*ec2.CopySnapshotInput) (*service.Request, *ec2.CopySnapshotOutput) + CopySnapshotRequest(*ec2.CopySnapshotInput) (*request.Request, *ec2.CopySnapshotOutput) CopySnapshot(*ec2.CopySnapshotInput) (*ec2.CopySnapshotOutput, error) - CreateCustomerGatewayRequest(*ec2.CreateCustomerGatewayInput) (*service.Request, *ec2.CreateCustomerGatewayOutput) + CreateCustomerGatewayRequest(*ec2.CreateCustomerGatewayInput) (*request.Request, *ec2.CreateCustomerGatewayOutput) CreateCustomerGateway(*ec2.CreateCustomerGatewayInput) (*ec2.CreateCustomerGatewayOutput, error) - CreateDhcpOptionsRequest(*ec2.CreateDhcpOptionsInput) (*service.Request, *ec2.CreateDhcpOptionsOutput) + CreateDhcpOptionsRequest(*ec2.CreateDhcpOptionsInput) (*request.Request, *ec2.CreateDhcpOptionsOutput) CreateDhcpOptions(*ec2.CreateDhcpOptionsInput) (*ec2.CreateDhcpOptionsOutput, error) - CreateFlowLogsRequest(*ec2.CreateFlowLogsInput) (*service.Request, *ec2.CreateFlowLogsOutput) + CreateFlowLogsRequest(*ec2.CreateFlowLogsInput) (*request.Request, *ec2.CreateFlowLogsOutput) CreateFlowLogs(*ec2.CreateFlowLogsInput) (*ec2.CreateFlowLogsOutput, error) - CreateImageRequest(*ec2.CreateImageInput) (*service.Request, *ec2.CreateImageOutput) + CreateImageRequest(*ec2.CreateImageInput) (*request.Request, *ec2.CreateImageOutput) CreateImage(*ec2.CreateImageInput) (*ec2.CreateImageOutput, error) - CreateInstanceExportTaskRequest(*ec2.CreateInstanceExportTaskInput) (*service.Request, *ec2.CreateInstanceExportTaskOutput) + CreateInstanceExportTaskRequest(*ec2.CreateInstanceExportTaskInput) (*request.Request, *ec2.CreateInstanceExportTaskOutput) CreateInstanceExportTask(*ec2.CreateInstanceExportTaskInput) (*ec2.CreateInstanceExportTaskOutput, error) - CreateInternetGatewayRequest(*ec2.CreateInternetGatewayInput) (*service.Request, *ec2.CreateInternetGatewayOutput) + CreateInternetGatewayRequest(*ec2.CreateInternetGatewayInput) (*request.Request, *ec2.CreateInternetGatewayOutput) CreateInternetGateway(*ec2.CreateInternetGatewayInput) (*ec2.CreateInternetGatewayOutput, error) - CreateKeyPairRequest(*ec2.CreateKeyPairInput) (*service.Request, *ec2.CreateKeyPairOutput) + CreateKeyPairRequest(*ec2.CreateKeyPairInput) (*request.Request, *ec2.CreateKeyPairOutput) CreateKeyPair(*ec2.CreateKeyPairInput) (*ec2.CreateKeyPairOutput, error) - CreateNetworkAclRequest(*ec2.CreateNetworkAclInput) (*service.Request, *ec2.CreateNetworkAclOutput) + CreateNetworkAclRequest(*ec2.CreateNetworkAclInput) (*request.Request, *ec2.CreateNetworkAclOutput) CreateNetworkAcl(*ec2.CreateNetworkAclInput) (*ec2.CreateNetworkAclOutput, error) - CreateNetworkAclEntryRequest(*ec2.CreateNetworkAclEntryInput) (*service.Request, *ec2.CreateNetworkAclEntryOutput) + CreateNetworkAclEntryRequest(*ec2.CreateNetworkAclEntryInput) (*request.Request, *ec2.CreateNetworkAclEntryOutput) CreateNetworkAclEntry(*ec2.CreateNetworkAclEntryInput) (*ec2.CreateNetworkAclEntryOutput, error) - CreateNetworkInterfaceRequest(*ec2.CreateNetworkInterfaceInput) (*service.Request, *ec2.CreateNetworkInterfaceOutput) + CreateNetworkInterfaceRequest(*ec2.CreateNetworkInterfaceInput) (*request.Request, *ec2.CreateNetworkInterfaceOutput) CreateNetworkInterface(*ec2.CreateNetworkInterfaceInput) (*ec2.CreateNetworkInterfaceOutput, error) - CreatePlacementGroupRequest(*ec2.CreatePlacementGroupInput) (*service.Request, *ec2.CreatePlacementGroupOutput) + CreatePlacementGroupRequest(*ec2.CreatePlacementGroupInput) (*request.Request, *ec2.CreatePlacementGroupOutput) CreatePlacementGroup(*ec2.CreatePlacementGroupInput) (*ec2.CreatePlacementGroupOutput, error) - CreateReservedInstancesListingRequest(*ec2.CreateReservedInstancesListingInput) (*service.Request, *ec2.CreateReservedInstancesListingOutput) + CreateReservedInstancesListingRequest(*ec2.CreateReservedInstancesListingInput) (*request.Request, *ec2.CreateReservedInstancesListingOutput) CreateReservedInstancesListing(*ec2.CreateReservedInstancesListingInput) (*ec2.CreateReservedInstancesListingOutput, error) - CreateRouteRequest(*ec2.CreateRouteInput) (*service.Request, *ec2.CreateRouteOutput) + CreateRouteRequest(*ec2.CreateRouteInput) (*request.Request, *ec2.CreateRouteOutput) CreateRoute(*ec2.CreateRouteInput) (*ec2.CreateRouteOutput, error) - CreateRouteTableRequest(*ec2.CreateRouteTableInput) (*service.Request, *ec2.CreateRouteTableOutput) + CreateRouteTableRequest(*ec2.CreateRouteTableInput) (*request.Request, *ec2.CreateRouteTableOutput) CreateRouteTable(*ec2.CreateRouteTableInput) (*ec2.CreateRouteTableOutput, error) - CreateSecurityGroupRequest(*ec2.CreateSecurityGroupInput) (*service.Request, *ec2.CreateSecurityGroupOutput) + CreateSecurityGroupRequest(*ec2.CreateSecurityGroupInput) (*request.Request, *ec2.CreateSecurityGroupOutput) CreateSecurityGroup(*ec2.CreateSecurityGroupInput) (*ec2.CreateSecurityGroupOutput, error) - CreateSnapshotRequest(*ec2.CreateSnapshotInput) (*service.Request, *ec2.Snapshot) + CreateSnapshotRequest(*ec2.CreateSnapshotInput) (*request.Request, *ec2.Snapshot) CreateSnapshot(*ec2.CreateSnapshotInput) (*ec2.Snapshot, error) - CreateSpotDatafeedSubscriptionRequest(*ec2.CreateSpotDatafeedSubscriptionInput) (*service.Request, *ec2.CreateSpotDatafeedSubscriptionOutput) + CreateSpotDatafeedSubscriptionRequest(*ec2.CreateSpotDatafeedSubscriptionInput) (*request.Request, *ec2.CreateSpotDatafeedSubscriptionOutput) CreateSpotDatafeedSubscription(*ec2.CreateSpotDatafeedSubscriptionInput) (*ec2.CreateSpotDatafeedSubscriptionOutput, error) - CreateSubnetRequest(*ec2.CreateSubnetInput) (*service.Request, *ec2.CreateSubnetOutput) + CreateSubnetRequest(*ec2.CreateSubnetInput) (*request.Request, *ec2.CreateSubnetOutput) CreateSubnet(*ec2.CreateSubnetInput) (*ec2.CreateSubnetOutput, error) - CreateTagsRequest(*ec2.CreateTagsInput) (*service.Request, *ec2.CreateTagsOutput) + CreateTagsRequest(*ec2.CreateTagsInput) (*request.Request, *ec2.CreateTagsOutput) CreateTags(*ec2.CreateTagsInput) (*ec2.CreateTagsOutput, error) - CreateVolumeRequest(*ec2.CreateVolumeInput) (*service.Request, *ec2.Volume) + CreateVolumeRequest(*ec2.CreateVolumeInput) (*request.Request, *ec2.Volume) CreateVolume(*ec2.CreateVolumeInput) (*ec2.Volume, error) - CreateVpcRequest(*ec2.CreateVpcInput) (*service.Request, *ec2.CreateVpcOutput) + CreateVpcRequest(*ec2.CreateVpcInput) (*request.Request, *ec2.CreateVpcOutput) CreateVpc(*ec2.CreateVpcInput) (*ec2.CreateVpcOutput, error) - CreateVpcEndpointRequest(*ec2.CreateVpcEndpointInput) (*service.Request, *ec2.CreateVpcEndpointOutput) + CreateVpcEndpointRequest(*ec2.CreateVpcEndpointInput) (*request.Request, *ec2.CreateVpcEndpointOutput) CreateVpcEndpoint(*ec2.CreateVpcEndpointInput) (*ec2.CreateVpcEndpointOutput, error) - CreateVpcPeeringConnectionRequest(*ec2.CreateVpcPeeringConnectionInput) (*service.Request, *ec2.CreateVpcPeeringConnectionOutput) + CreateVpcPeeringConnectionRequest(*ec2.CreateVpcPeeringConnectionInput) (*request.Request, *ec2.CreateVpcPeeringConnectionOutput) CreateVpcPeeringConnection(*ec2.CreateVpcPeeringConnectionInput) (*ec2.CreateVpcPeeringConnectionOutput, error) - CreateVpnConnectionRequest(*ec2.CreateVpnConnectionInput) (*service.Request, *ec2.CreateVpnConnectionOutput) + CreateVpnConnectionRequest(*ec2.CreateVpnConnectionInput) (*request.Request, *ec2.CreateVpnConnectionOutput) CreateVpnConnection(*ec2.CreateVpnConnectionInput) (*ec2.CreateVpnConnectionOutput, error) - CreateVpnConnectionRouteRequest(*ec2.CreateVpnConnectionRouteInput) (*service.Request, *ec2.CreateVpnConnectionRouteOutput) + CreateVpnConnectionRouteRequest(*ec2.CreateVpnConnectionRouteInput) (*request.Request, *ec2.CreateVpnConnectionRouteOutput) CreateVpnConnectionRoute(*ec2.CreateVpnConnectionRouteInput) (*ec2.CreateVpnConnectionRouteOutput, error) - CreateVpnGatewayRequest(*ec2.CreateVpnGatewayInput) (*service.Request, *ec2.CreateVpnGatewayOutput) + CreateVpnGatewayRequest(*ec2.CreateVpnGatewayInput) (*request.Request, *ec2.CreateVpnGatewayOutput) CreateVpnGateway(*ec2.CreateVpnGatewayInput) (*ec2.CreateVpnGatewayOutput, error) - DeleteCustomerGatewayRequest(*ec2.DeleteCustomerGatewayInput) (*service.Request, *ec2.DeleteCustomerGatewayOutput) + DeleteCustomerGatewayRequest(*ec2.DeleteCustomerGatewayInput) (*request.Request, *ec2.DeleteCustomerGatewayOutput) DeleteCustomerGateway(*ec2.DeleteCustomerGatewayInput) (*ec2.DeleteCustomerGatewayOutput, error) - DeleteDhcpOptionsRequest(*ec2.DeleteDhcpOptionsInput) (*service.Request, *ec2.DeleteDhcpOptionsOutput) + DeleteDhcpOptionsRequest(*ec2.DeleteDhcpOptionsInput) (*request.Request, *ec2.DeleteDhcpOptionsOutput) DeleteDhcpOptions(*ec2.DeleteDhcpOptionsInput) (*ec2.DeleteDhcpOptionsOutput, error) - DeleteFlowLogsRequest(*ec2.DeleteFlowLogsInput) (*service.Request, *ec2.DeleteFlowLogsOutput) + DeleteFlowLogsRequest(*ec2.DeleteFlowLogsInput) (*request.Request, *ec2.DeleteFlowLogsOutput) DeleteFlowLogs(*ec2.DeleteFlowLogsInput) (*ec2.DeleteFlowLogsOutput, error) - DeleteInternetGatewayRequest(*ec2.DeleteInternetGatewayInput) (*service.Request, *ec2.DeleteInternetGatewayOutput) + DeleteInternetGatewayRequest(*ec2.DeleteInternetGatewayInput) (*request.Request, *ec2.DeleteInternetGatewayOutput) DeleteInternetGateway(*ec2.DeleteInternetGatewayInput) (*ec2.DeleteInternetGatewayOutput, error) - DeleteKeyPairRequest(*ec2.DeleteKeyPairInput) (*service.Request, *ec2.DeleteKeyPairOutput) + DeleteKeyPairRequest(*ec2.DeleteKeyPairInput) (*request.Request, *ec2.DeleteKeyPairOutput) DeleteKeyPair(*ec2.DeleteKeyPairInput) (*ec2.DeleteKeyPairOutput, error) - DeleteNetworkAclRequest(*ec2.DeleteNetworkAclInput) (*service.Request, *ec2.DeleteNetworkAclOutput) + DeleteNetworkAclRequest(*ec2.DeleteNetworkAclInput) (*request.Request, *ec2.DeleteNetworkAclOutput) DeleteNetworkAcl(*ec2.DeleteNetworkAclInput) (*ec2.DeleteNetworkAclOutput, error) - DeleteNetworkAclEntryRequest(*ec2.DeleteNetworkAclEntryInput) (*service.Request, *ec2.DeleteNetworkAclEntryOutput) + DeleteNetworkAclEntryRequest(*ec2.DeleteNetworkAclEntryInput) (*request.Request, *ec2.DeleteNetworkAclEntryOutput) DeleteNetworkAclEntry(*ec2.DeleteNetworkAclEntryInput) (*ec2.DeleteNetworkAclEntryOutput, error) - DeleteNetworkInterfaceRequest(*ec2.DeleteNetworkInterfaceInput) (*service.Request, *ec2.DeleteNetworkInterfaceOutput) + DeleteNetworkInterfaceRequest(*ec2.DeleteNetworkInterfaceInput) (*request.Request, *ec2.DeleteNetworkInterfaceOutput) DeleteNetworkInterface(*ec2.DeleteNetworkInterfaceInput) (*ec2.DeleteNetworkInterfaceOutput, error) - DeletePlacementGroupRequest(*ec2.DeletePlacementGroupInput) (*service.Request, *ec2.DeletePlacementGroupOutput) + DeletePlacementGroupRequest(*ec2.DeletePlacementGroupInput) (*request.Request, *ec2.DeletePlacementGroupOutput) DeletePlacementGroup(*ec2.DeletePlacementGroupInput) (*ec2.DeletePlacementGroupOutput, error) - DeleteRouteRequest(*ec2.DeleteRouteInput) (*service.Request, *ec2.DeleteRouteOutput) + DeleteRouteRequest(*ec2.DeleteRouteInput) (*request.Request, *ec2.DeleteRouteOutput) DeleteRoute(*ec2.DeleteRouteInput) (*ec2.DeleteRouteOutput, error) - DeleteRouteTableRequest(*ec2.DeleteRouteTableInput) (*service.Request, *ec2.DeleteRouteTableOutput) + DeleteRouteTableRequest(*ec2.DeleteRouteTableInput) (*request.Request, *ec2.DeleteRouteTableOutput) DeleteRouteTable(*ec2.DeleteRouteTableInput) (*ec2.DeleteRouteTableOutput, error) - DeleteSecurityGroupRequest(*ec2.DeleteSecurityGroupInput) (*service.Request, *ec2.DeleteSecurityGroupOutput) + DeleteSecurityGroupRequest(*ec2.DeleteSecurityGroupInput) (*request.Request, *ec2.DeleteSecurityGroupOutput) DeleteSecurityGroup(*ec2.DeleteSecurityGroupInput) (*ec2.DeleteSecurityGroupOutput, error) - DeleteSnapshotRequest(*ec2.DeleteSnapshotInput) (*service.Request, *ec2.DeleteSnapshotOutput) + DeleteSnapshotRequest(*ec2.DeleteSnapshotInput) (*request.Request, *ec2.DeleteSnapshotOutput) DeleteSnapshot(*ec2.DeleteSnapshotInput) (*ec2.DeleteSnapshotOutput, error) - DeleteSpotDatafeedSubscriptionRequest(*ec2.DeleteSpotDatafeedSubscriptionInput) (*service.Request, *ec2.DeleteSpotDatafeedSubscriptionOutput) + DeleteSpotDatafeedSubscriptionRequest(*ec2.DeleteSpotDatafeedSubscriptionInput) (*request.Request, *ec2.DeleteSpotDatafeedSubscriptionOutput) DeleteSpotDatafeedSubscription(*ec2.DeleteSpotDatafeedSubscriptionInput) (*ec2.DeleteSpotDatafeedSubscriptionOutput, error) - DeleteSubnetRequest(*ec2.DeleteSubnetInput) (*service.Request, *ec2.DeleteSubnetOutput) + DeleteSubnetRequest(*ec2.DeleteSubnetInput) (*request.Request, *ec2.DeleteSubnetOutput) DeleteSubnet(*ec2.DeleteSubnetInput) (*ec2.DeleteSubnetOutput, error) - DeleteTagsRequest(*ec2.DeleteTagsInput) (*service.Request, *ec2.DeleteTagsOutput) + DeleteTagsRequest(*ec2.DeleteTagsInput) (*request.Request, *ec2.DeleteTagsOutput) DeleteTags(*ec2.DeleteTagsInput) (*ec2.DeleteTagsOutput, error) - DeleteVolumeRequest(*ec2.DeleteVolumeInput) (*service.Request, *ec2.DeleteVolumeOutput) + DeleteVolumeRequest(*ec2.DeleteVolumeInput) (*request.Request, *ec2.DeleteVolumeOutput) DeleteVolume(*ec2.DeleteVolumeInput) (*ec2.DeleteVolumeOutput, error) - DeleteVpcRequest(*ec2.DeleteVpcInput) (*service.Request, *ec2.DeleteVpcOutput) + DeleteVpcRequest(*ec2.DeleteVpcInput) (*request.Request, *ec2.DeleteVpcOutput) DeleteVpc(*ec2.DeleteVpcInput) (*ec2.DeleteVpcOutput, error) - DeleteVpcEndpointsRequest(*ec2.DeleteVpcEndpointsInput) (*service.Request, *ec2.DeleteVpcEndpointsOutput) + DeleteVpcEndpointsRequest(*ec2.DeleteVpcEndpointsInput) (*request.Request, *ec2.DeleteVpcEndpointsOutput) DeleteVpcEndpoints(*ec2.DeleteVpcEndpointsInput) (*ec2.DeleteVpcEndpointsOutput, error) - DeleteVpcPeeringConnectionRequest(*ec2.DeleteVpcPeeringConnectionInput) (*service.Request, *ec2.DeleteVpcPeeringConnectionOutput) + DeleteVpcPeeringConnectionRequest(*ec2.DeleteVpcPeeringConnectionInput) (*request.Request, *ec2.DeleteVpcPeeringConnectionOutput) DeleteVpcPeeringConnection(*ec2.DeleteVpcPeeringConnectionInput) (*ec2.DeleteVpcPeeringConnectionOutput, error) - DeleteVpnConnectionRequest(*ec2.DeleteVpnConnectionInput) (*service.Request, *ec2.DeleteVpnConnectionOutput) + DeleteVpnConnectionRequest(*ec2.DeleteVpnConnectionInput) (*request.Request, *ec2.DeleteVpnConnectionOutput) DeleteVpnConnection(*ec2.DeleteVpnConnectionInput) (*ec2.DeleteVpnConnectionOutput, error) - DeleteVpnConnectionRouteRequest(*ec2.DeleteVpnConnectionRouteInput) (*service.Request, *ec2.DeleteVpnConnectionRouteOutput) + DeleteVpnConnectionRouteRequest(*ec2.DeleteVpnConnectionRouteInput) (*request.Request, *ec2.DeleteVpnConnectionRouteOutput) DeleteVpnConnectionRoute(*ec2.DeleteVpnConnectionRouteInput) (*ec2.DeleteVpnConnectionRouteOutput, error) - DeleteVpnGatewayRequest(*ec2.DeleteVpnGatewayInput) (*service.Request, *ec2.DeleteVpnGatewayOutput) + DeleteVpnGatewayRequest(*ec2.DeleteVpnGatewayInput) (*request.Request, *ec2.DeleteVpnGatewayOutput) DeleteVpnGateway(*ec2.DeleteVpnGatewayInput) (*ec2.DeleteVpnGatewayOutput, error) - DeregisterImageRequest(*ec2.DeregisterImageInput) (*service.Request, *ec2.DeregisterImageOutput) + DeregisterImageRequest(*ec2.DeregisterImageInput) (*request.Request, *ec2.DeregisterImageOutput) DeregisterImage(*ec2.DeregisterImageInput) (*ec2.DeregisterImageOutput, error) - DescribeAccountAttributesRequest(*ec2.DescribeAccountAttributesInput) (*service.Request, *ec2.DescribeAccountAttributesOutput) + DescribeAccountAttributesRequest(*ec2.DescribeAccountAttributesInput) (*request.Request, *ec2.DescribeAccountAttributesOutput) DescribeAccountAttributes(*ec2.DescribeAccountAttributesInput) (*ec2.DescribeAccountAttributesOutput, error) - DescribeAddressesRequest(*ec2.DescribeAddressesInput) (*service.Request, *ec2.DescribeAddressesOutput) + DescribeAddressesRequest(*ec2.DescribeAddressesInput) (*request.Request, *ec2.DescribeAddressesOutput) DescribeAddresses(*ec2.DescribeAddressesInput) (*ec2.DescribeAddressesOutput, error) - DescribeAvailabilityZonesRequest(*ec2.DescribeAvailabilityZonesInput) (*service.Request, *ec2.DescribeAvailabilityZonesOutput) + DescribeAvailabilityZonesRequest(*ec2.DescribeAvailabilityZonesInput) (*request.Request, *ec2.DescribeAvailabilityZonesOutput) DescribeAvailabilityZones(*ec2.DescribeAvailabilityZonesInput) (*ec2.DescribeAvailabilityZonesOutput, error) - DescribeBundleTasksRequest(*ec2.DescribeBundleTasksInput) (*service.Request, *ec2.DescribeBundleTasksOutput) + DescribeBundleTasksRequest(*ec2.DescribeBundleTasksInput) (*request.Request, *ec2.DescribeBundleTasksOutput) DescribeBundleTasks(*ec2.DescribeBundleTasksInput) (*ec2.DescribeBundleTasksOutput, error) - DescribeClassicLinkInstancesRequest(*ec2.DescribeClassicLinkInstancesInput) (*service.Request, *ec2.DescribeClassicLinkInstancesOutput) + DescribeClassicLinkInstancesRequest(*ec2.DescribeClassicLinkInstancesInput) (*request.Request, *ec2.DescribeClassicLinkInstancesOutput) DescribeClassicLinkInstances(*ec2.DescribeClassicLinkInstancesInput) (*ec2.DescribeClassicLinkInstancesOutput, error) - DescribeConversionTasksRequest(*ec2.DescribeConversionTasksInput) (*service.Request, *ec2.DescribeConversionTasksOutput) + DescribeConversionTasksRequest(*ec2.DescribeConversionTasksInput) (*request.Request, *ec2.DescribeConversionTasksOutput) DescribeConversionTasks(*ec2.DescribeConversionTasksInput) (*ec2.DescribeConversionTasksOutput, error) - DescribeCustomerGatewaysRequest(*ec2.DescribeCustomerGatewaysInput) (*service.Request, *ec2.DescribeCustomerGatewaysOutput) + DescribeCustomerGatewaysRequest(*ec2.DescribeCustomerGatewaysInput) (*request.Request, *ec2.DescribeCustomerGatewaysOutput) DescribeCustomerGateways(*ec2.DescribeCustomerGatewaysInput) (*ec2.DescribeCustomerGatewaysOutput, error) - DescribeDhcpOptionsRequest(*ec2.DescribeDhcpOptionsInput) (*service.Request, *ec2.DescribeDhcpOptionsOutput) + DescribeDhcpOptionsRequest(*ec2.DescribeDhcpOptionsInput) (*request.Request, *ec2.DescribeDhcpOptionsOutput) DescribeDhcpOptions(*ec2.DescribeDhcpOptionsInput) (*ec2.DescribeDhcpOptionsOutput, error) - DescribeExportTasksRequest(*ec2.DescribeExportTasksInput) (*service.Request, *ec2.DescribeExportTasksOutput) + DescribeExportTasksRequest(*ec2.DescribeExportTasksInput) (*request.Request, *ec2.DescribeExportTasksOutput) DescribeExportTasks(*ec2.DescribeExportTasksInput) (*ec2.DescribeExportTasksOutput, error) - DescribeFlowLogsRequest(*ec2.DescribeFlowLogsInput) (*service.Request, *ec2.DescribeFlowLogsOutput) + DescribeFlowLogsRequest(*ec2.DescribeFlowLogsInput) (*request.Request, *ec2.DescribeFlowLogsOutput) DescribeFlowLogs(*ec2.DescribeFlowLogsInput) (*ec2.DescribeFlowLogsOutput, error) - DescribeImageAttributeRequest(*ec2.DescribeImageAttributeInput) (*service.Request, *ec2.DescribeImageAttributeOutput) + DescribeImageAttributeRequest(*ec2.DescribeImageAttributeInput) (*request.Request, *ec2.DescribeImageAttributeOutput) DescribeImageAttribute(*ec2.DescribeImageAttributeInput) (*ec2.DescribeImageAttributeOutput, error) - DescribeImagesRequest(*ec2.DescribeImagesInput) (*service.Request, *ec2.DescribeImagesOutput) + DescribeImagesRequest(*ec2.DescribeImagesInput) (*request.Request, *ec2.DescribeImagesOutput) DescribeImages(*ec2.DescribeImagesInput) (*ec2.DescribeImagesOutput, error) - DescribeImportImageTasksRequest(*ec2.DescribeImportImageTasksInput) (*service.Request, *ec2.DescribeImportImageTasksOutput) + DescribeImportImageTasksRequest(*ec2.DescribeImportImageTasksInput) (*request.Request, *ec2.DescribeImportImageTasksOutput) DescribeImportImageTasks(*ec2.DescribeImportImageTasksInput) (*ec2.DescribeImportImageTasksOutput, error) - DescribeImportSnapshotTasksRequest(*ec2.DescribeImportSnapshotTasksInput) (*service.Request, *ec2.DescribeImportSnapshotTasksOutput) + DescribeImportSnapshotTasksRequest(*ec2.DescribeImportSnapshotTasksInput) (*request.Request, *ec2.DescribeImportSnapshotTasksOutput) DescribeImportSnapshotTasks(*ec2.DescribeImportSnapshotTasksInput) (*ec2.DescribeImportSnapshotTasksOutput, error) - DescribeInstanceAttributeRequest(*ec2.DescribeInstanceAttributeInput) (*service.Request, *ec2.DescribeInstanceAttributeOutput) + DescribeInstanceAttributeRequest(*ec2.DescribeInstanceAttributeInput) (*request.Request, *ec2.DescribeInstanceAttributeOutput) DescribeInstanceAttribute(*ec2.DescribeInstanceAttributeInput) (*ec2.DescribeInstanceAttributeOutput, error) - DescribeInstanceStatusRequest(*ec2.DescribeInstanceStatusInput) (*service.Request, *ec2.DescribeInstanceStatusOutput) + DescribeInstanceStatusRequest(*ec2.DescribeInstanceStatusInput) (*request.Request, *ec2.DescribeInstanceStatusOutput) DescribeInstanceStatus(*ec2.DescribeInstanceStatusInput) (*ec2.DescribeInstanceStatusOutput, error) DescribeInstanceStatusPages(*ec2.DescribeInstanceStatusInput, func(*ec2.DescribeInstanceStatusOutput, bool) bool) error - DescribeInstancesRequest(*ec2.DescribeInstancesInput) (*service.Request, *ec2.DescribeInstancesOutput) + DescribeInstancesRequest(*ec2.DescribeInstancesInput) (*request.Request, *ec2.DescribeInstancesOutput) DescribeInstances(*ec2.DescribeInstancesInput) (*ec2.DescribeInstancesOutput, error) DescribeInstancesPages(*ec2.DescribeInstancesInput, func(*ec2.DescribeInstancesOutput, bool) bool) error - DescribeInternetGatewaysRequest(*ec2.DescribeInternetGatewaysInput) (*service.Request, *ec2.DescribeInternetGatewaysOutput) + DescribeInternetGatewaysRequest(*ec2.DescribeInternetGatewaysInput) (*request.Request, *ec2.DescribeInternetGatewaysOutput) DescribeInternetGateways(*ec2.DescribeInternetGatewaysInput) (*ec2.DescribeInternetGatewaysOutput, error) - DescribeKeyPairsRequest(*ec2.DescribeKeyPairsInput) (*service.Request, *ec2.DescribeKeyPairsOutput) + DescribeKeyPairsRequest(*ec2.DescribeKeyPairsInput) (*request.Request, *ec2.DescribeKeyPairsOutput) DescribeKeyPairs(*ec2.DescribeKeyPairsInput) (*ec2.DescribeKeyPairsOutput, error) - DescribeMovingAddressesRequest(*ec2.DescribeMovingAddressesInput) (*service.Request, *ec2.DescribeMovingAddressesOutput) + DescribeMovingAddressesRequest(*ec2.DescribeMovingAddressesInput) (*request.Request, *ec2.DescribeMovingAddressesOutput) DescribeMovingAddresses(*ec2.DescribeMovingAddressesInput) (*ec2.DescribeMovingAddressesOutput, error) - DescribeNetworkAclsRequest(*ec2.DescribeNetworkAclsInput) (*service.Request, *ec2.DescribeNetworkAclsOutput) + DescribeNetworkAclsRequest(*ec2.DescribeNetworkAclsInput) (*request.Request, *ec2.DescribeNetworkAclsOutput) DescribeNetworkAcls(*ec2.DescribeNetworkAclsInput) (*ec2.DescribeNetworkAclsOutput, error) - DescribeNetworkInterfaceAttributeRequest(*ec2.DescribeNetworkInterfaceAttributeInput) (*service.Request, *ec2.DescribeNetworkInterfaceAttributeOutput) + DescribeNetworkInterfaceAttributeRequest(*ec2.DescribeNetworkInterfaceAttributeInput) (*request.Request, *ec2.DescribeNetworkInterfaceAttributeOutput) DescribeNetworkInterfaceAttribute(*ec2.DescribeNetworkInterfaceAttributeInput) (*ec2.DescribeNetworkInterfaceAttributeOutput, error) - DescribeNetworkInterfacesRequest(*ec2.DescribeNetworkInterfacesInput) (*service.Request, *ec2.DescribeNetworkInterfacesOutput) + DescribeNetworkInterfacesRequest(*ec2.DescribeNetworkInterfacesInput) (*request.Request, *ec2.DescribeNetworkInterfacesOutput) DescribeNetworkInterfaces(*ec2.DescribeNetworkInterfacesInput) (*ec2.DescribeNetworkInterfacesOutput, error) - DescribePlacementGroupsRequest(*ec2.DescribePlacementGroupsInput) (*service.Request, *ec2.DescribePlacementGroupsOutput) + DescribePlacementGroupsRequest(*ec2.DescribePlacementGroupsInput) (*request.Request, *ec2.DescribePlacementGroupsOutput) DescribePlacementGroups(*ec2.DescribePlacementGroupsInput) (*ec2.DescribePlacementGroupsOutput, error) - DescribePrefixListsRequest(*ec2.DescribePrefixListsInput) (*service.Request, *ec2.DescribePrefixListsOutput) + DescribePrefixListsRequest(*ec2.DescribePrefixListsInput) (*request.Request, *ec2.DescribePrefixListsOutput) DescribePrefixLists(*ec2.DescribePrefixListsInput) (*ec2.DescribePrefixListsOutput, error) - DescribeRegionsRequest(*ec2.DescribeRegionsInput) (*service.Request, *ec2.DescribeRegionsOutput) + DescribeRegionsRequest(*ec2.DescribeRegionsInput) (*request.Request, *ec2.DescribeRegionsOutput) DescribeRegions(*ec2.DescribeRegionsInput) (*ec2.DescribeRegionsOutput, error) - DescribeReservedInstancesRequest(*ec2.DescribeReservedInstancesInput) (*service.Request, *ec2.DescribeReservedInstancesOutput) + DescribeReservedInstancesRequest(*ec2.DescribeReservedInstancesInput) (*request.Request, *ec2.DescribeReservedInstancesOutput) DescribeReservedInstances(*ec2.DescribeReservedInstancesInput) (*ec2.DescribeReservedInstancesOutput, error) - DescribeReservedInstancesListingsRequest(*ec2.DescribeReservedInstancesListingsInput) (*service.Request, *ec2.DescribeReservedInstancesListingsOutput) + DescribeReservedInstancesListingsRequest(*ec2.DescribeReservedInstancesListingsInput) (*request.Request, *ec2.DescribeReservedInstancesListingsOutput) DescribeReservedInstancesListings(*ec2.DescribeReservedInstancesListingsInput) (*ec2.DescribeReservedInstancesListingsOutput, error) - DescribeReservedInstancesModificationsRequest(*ec2.DescribeReservedInstancesModificationsInput) (*service.Request, *ec2.DescribeReservedInstancesModificationsOutput) + DescribeReservedInstancesModificationsRequest(*ec2.DescribeReservedInstancesModificationsInput) (*request.Request, *ec2.DescribeReservedInstancesModificationsOutput) DescribeReservedInstancesModifications(*ec2.DescribeReservedInstancesModificationsInput) (*ec2.DescribeReservedInstancesModificationsOutput, error) DescribeReservedInstancesModificationsPages(*ec2.DescribeReservedInstancesModificationsInput, func(*ec2.DescribeReservedInstancesModificationsOutput, bool) bool) error - DescribeReservedInstancesOfferingsRequest(*ec2.DescribeReservedInstancesOfferingsInput) (*service.Request, *ec2.DescribeReservedInstancesOfferingsOutput) + DescribeReservedInstancesOfferingsRequest(*ec2.DescribeReservedInstancesOfferingsInput) (*request.Request, *ec2.DescribeReservedInstancesOfferingsOutput) DescribeReservedInstancesOfferings(*ec2.DescribeReservedInstancesOfferingsInput) (*ec2.DescribeReservedInstancesOfferingsOutput, error) DescribeReservedInstancesOfferingsPages(*ec2.DescribeReservedInstancesOfferingsInput, func(*ec2.DescribeReservedInstancesOfferingsOutput, bool) bool) error - DescribeRouteTablesRequest(*ec2.DescribeRouteTablesInput) (*service.Request, *ec2.DescribeRouteTablesOutput) + DescribeRouteTablesRequest(*ec2.DescribeRouteTablesInput) (*request.Request, *ec2.DescribeRouteTablesOutput) DescribeRouteTables(*ec2.DescribeRouteTablesInput) (*ec2.DescribeRouteTablesOutput, error) - DescribeSecurityGroupsRequest(*ec2.DescribeSecurityGroupsInput) (*service.Request, *ec2.DescribeSecurityGroupsOutput) + DescribeSecurityGroupsRequest(*ec2.DescribeSecurityGroupsInput) (*request.Request, *ec2.DescribeSecurityGroupsOutput) DescribeSecurityGroups(*ec2.DescribeSecurityGroupsInput) (*ec2.DescribeSecurityGroupsOutput, error) - DescribeSnapshotAttributeRequest(*ec2.DescribeSnapshotAttributeInput) (*service.Request, *ec2.DescribeSnapshotAttributeOutput) + DescribeSnapshotAttributeRequest(*ec2.DescribeSnapshotAttributeInput) (*request.Request, *ec2.DescribeSnapshotAttributeOutput) DescribeSnapshotAttribute(*ec2.DescribeSnapshotAttributeInput) (*ec2.DescribeSnapshotAttributeOutput, error) - DescribeSnapshotsRequest(*ec2.DescribeSnapshotsInput) (*service.Request, *ec2.DescribeSnapshotsOutput) + DescribeSnapshotsRequest(*ec2.DescribeSnapshotsInput) (*request.Request, *ec2.DescribeSnapshotsOutput) DescribeSnapshots(*ec2.DescribeSnapshotsInput) (*ec2.DescribeSnapshotsOutput, error) DescribeSnapshotsPages(*ec2.DescribeSnapshotsInput, func(*ec2.DescribeSnapshotsOutput, bool) bool) error - DescribeSpotDatafeedSubscriptionRequest(*ec2.DescribeSpotDatafeedSubscriptionInput) (*service.Request, *ec2.DescribeSpotDatafeedSubscriptionOutput) + DescribeSpotDatafeedSubscriptionRequest(*ec2.DescribeSpotDatafeedSubscriptionInput) (*request.Request, *ec2.DescribeSpotDatafeedSubscriptionOutput) DescribeSpotDatafeedSubscription(*ec2.DescribeSpotDatafeedSubscriptionInput) (*ec2.DescribeSpotDatafeedSubscriptionOutput, error) - DescribeSpotFleetInstancesRequest(*ec2.DescribeSpotFleetInstancesInput) (*service.Request, *ec2.DescribeSpotFleetInstancesOutput) + DescribeSpotFleetInstancesRequest(*ec2.DescribeSpotFleetInstancesInput) (*request.Request, *ec2.DescribeSpotFleetInstancesOutput) DescribeSpotFleetInstances(*ec2.DescribeSpotFleetInstancesInput) (*ec2.DescribeSpotFleetInstancesOutput, error) - DescribeSpotFleetRequestHistoryRequest(*ec2.DescribeSpotFleetRequestHistoryInput) (*service.Request, *ec2.DescribeSpotFleetRequestHistoryOutput) + DescribeSpotFleetRequestHistoryRequest(*ec2.DescribeSpotFleetRequestHistoryInput) (*request.Request, *ec2.DescribeSpotFleetRequestHistoryOutput) DescribeSpotFleetRequestHistory(*ec2.DescribeSpotFleetRequestHistoryInput) (*ec2.DescribeSpotFleetRequestHistoryOutput, error) - DescribeSpotFleetRequestsRequest(*ec2.DescribeSpotFleetRequestsInput) (*service.Request, *ec2.DescribeSpotFleetRequestsOutput) + DescribeSpotFleetRequestsRequest(*ec2.DescribeSpotFleetRequestsInput) (*request.Request, *ec2.DescribeSpotFleetRequestsOutput) DescribeSpotFleetRequests(*ec2.DescribeSpotFleetRequestsInput) (*ec2.DescribeSpotFleetRequestsOutput, error) - DescribeSpotInstanceRequestsRequest(*ec2.DescribeSpotInstanceRequestsInput) (*service.Request, *ec2.DescribeSpotInstanceRequestsOutput) + DescribeSpotInstanceRequestsRequest(*ec2.DescribeSpotInstanceRequestsInput) (*request.Request, *ec2.DescribeSpotInstanceRequestsOutput) DescribeSpotInstanceRequests(*ec2.DescribeSpotInstanceRequestsInput) (*ec2.DescribeSpotInstanceRequestsOutput, error) - DescribeSpotPriceHistoryRequest(*ec2.DescribeSpotPriceHistoryInput) (*service.Request, *ec2.DescribeSpotPriceHistoryOutput) + DescribeSpotPriceHistoryRequest(*ec2.DescribeSpotPriceHistoryInput) (*request.Request, *ec2.DescribeSpotPriceHistoryOutput) DescribeSpotPriceHistory(*ec2.DescribeSpotPriceHistoryInput) (*ec2.DescribeSpotPriceHistoryOutput, error) DescribeSpotPriceHistoryPages(*ec2.DescribeSpotPriceHistoryInput, func(*ec2.DescribeSpotPriceHistoryOutput, bool) bool) error - DescribeSubnetsRequest(*ec2.DescribeSubnetsInput) (*service.Request, *ec2.DescribeSubnetsOutput) + DescribeSubnetsRequest(*ec2.DescribeSubnetsInput) (*request.Request, *ec2.DescribeSubnetsOutput) DescribeSubnets(*ec2.DescribeSubnetsInput) (*ec2.DescribeSubnetsOutput, error) - DescribeTagsRequest(*ec2.DescribeTagsInput) (*service.Request, *ec2.DescribeTagsOutput) + DescribeTagsRequest(*ec2.DescribeTagsInput) (*request.Request, *ec2.DescribeTagsOutput) DescribeTags(*ec2.DescribeTagsInput) (*ec2.DescribeTagsOutput, error) - DescribeVolumeAttributeRequest(*ec2.DescribeVolumeAttributeInput) (*service.Request, *ec2.DescribeVolumeAttributeOutput) + DescribeVolumeAttributeRequest(*ec2.DescribeVolumeAttributeInput) (*request.Request, *ec2.DescribeVolumeAttributeOutput) DescribeVolumeAttribute(*ec2.DescribeVolumeAttributeInput) (*ec2.DescribeVolumeAttributeOutput, error) - DescribeVolumeStatusRequest(*ec2.DescribeVolumeStatusInput) (*service.Request, *ec2.DescribeVolumeStatusOutput) + DescribeVolumeStatusRequest(*ec2.DescribeVolumeStatusInput) (*request.Request, *ec2.DescribeVolumeStatusOutput) DescribeVolumeStatus(*ec2.DescribeVolumeStatusInput) (*ec2.DescribeVolumeStatusOutput, error) DescribeVolumeStatusPages(*ec2.DescribeVolumeStatusInput, func(*ec2.DescribeVolumeStatusOutput, bool) bool) error - DescribeVolumesRequest(*ec2.DescribeVolumesInput) (*service.Request, *ec2.DescribeVolumesOutput) + DescribeVolumesRequest(*ec2.DescribeVolumesInput) (*request.Request, *ec2.DescribeVolumesOutput) DescribeVolumes(*ec2.DescribeVolumesInput) (*ec2.DescribeVolumesOutput, error) DescribeVolumesPages(*ec2.DescribeVolumesInput, func(*ec2.DescribeVolumesOutput, bool) bool) error - DescribeVpcAttributeRequest(*ec2.DescribeVpcAttributeInput) (*service.Request, *ec2.DescribeVpcAttributeOutput) + DescribeVpcAttributeRequest(*ec2.DescribeVpcAttributeInput) (*request.Request, *ec2.DescribeVpcAttributeOutput) DescribeVpcAttribute(*ec2.DescribeVpcAttributeInput) (*ec2.DescribeVpcAttributeOutput, error) - DescribeVpcClassicLinkRequest(*ec2.DescribeVpcClassicLinkInput) (*service.Request, *ec2.DescribeVpcClassicLinkOutput) + DescribeVpcClassicLinkRequest(*ec2.DescribeVpcClassicLinkInput) (*request.Request, *ec2.DescribeVpcClassicLinkOutput) DescribeVpcClassicLink(*ec2.DescribeVpcClassicLinkInput) (*ec2.DescribeVpcClassicLinkOutput, error) - DescribeVpcEndpointServicesRequest(*ec2.DescribeVpcEndpointServicesInput) (*service.Request, *ec2.DescribeVpcEndpointServicesOutput) + DescribeVpcEndpointServicesRequest(*ec2.DescribeVpcEndpointServicesInput) (*request.Request, *ec2.DescribeVpcEndpointServicesOutput) DescribeVpcEndpointServices(*ec2.DescribeVpcEndpointServicesInput) (*ec2.DescribeVpcEndpointServicesOutput, error) - DescribeVpcEndpointsRequest(*ec2.DescribeVpcEndpointsInput) (*service.Request, *ec2.DescribeVpcEndpointsOutput) + DescribeVpcEndpointsRequest(*ec2.DescribeVpcEndpointsInput) (*request.Request, *ec2.DescribeVpcEndpointsOutput) DescribeVpcEndpoints(*ec2.DescribeVpcEndpointsInput) (*ec2.DescribeVpcEndpointsOutput, error) - DescribeVpcPeeringConnectionsRequest(*ec2.DescribeVpcPeeringConnectionsInput) (*service.Request, *ec2.DescribeVpcPeeringConnectionsOutput) + DescribeVpcPeeringConnectionsRequest(*ec2.DescribeVpcPeeringConnectionsInput) (*request.Request, *ec2.DescribeVpcPeeringConnectionsOutput) DescribeVpcPeeringConnections(*ec2.DescribeVpcPeeringConnectionsInput) (*ec2.DescribeVpcPeeringConnectionsOutput, error) - DescribeVpcsRequest(*ec2.DescribeVpcsInput) (*service.Request, *ec2.DescribeVpcsOutput) + DescribeVpcsRequest(*ec2.DescribeVpcsInput) (*request.Request, *ec2.DescribeVpcsOutput) DescribeVpcs(*ec2.DescribeVpcsInput) (*ec2.DescribeVpcsOutput, error) - DescribeVpnConnectionsRequest(*ec2.DescribeVpnConnectionsInput) (*service.Request, *ec2.DescribeVpnConnectionsOutput) + DescribeVpnConnectionsRequest(*ec2.DescribeVpnConnectionsInput) (*request.Request, *ec2.DescribeVpnConnectionsOutput) DescribeVpnConnections(*ec2.DescribeVpnConnectionsInput) (*ec2.DescribeVpnConnectionsOutput, error) - DescribeVpnGatewaysRequest(*ec2.DescribeVpnGatewaysInput) (*service.Request, *ec2.DescribeVpnGatewaysOutput) + DescribeVpnGatewaysRequest(*ec2.DescribeVpnGatewaysInput) (*request.Request, *ec2.DescribeVpnGatewaysOutput) DescribeVpnGateways(*ec2.DescribeVpnGatewaysInput) (*ec2.DescribeVpnGatewaysOutput, error) - DetachClassicLinkVpcRequest(*ec2.DetachClassicLinkVpcInput) (*service.Request, *ec2.DetachClassicLinkVpcOutput) + DetachClassicLinkVpcRequest(*ec2.DetachClassicLinkVpcInput) (*request.Request, *ec2.DetachClassicLinkVpcOutput) DetachClassicLinkVpc(*ec2.DetachClassicLinkVpcInput) (*ec2.DetachClassicLinkVpcOutput, error) - DetachInternetGatewayRequest(*ec2.DetachInternetGatewayInput) (*service.Request, *ec2.DetachInternetGatewayOutput) + DetachInternetGatewayRequest(*ec2.DetachInternetGatewayInput) (*request.Request, *ec2.DetachInternetGatewayOutput) DetachInternetGateway(*ec2.DetachInternetGatewayInput) (*ec2.DetachInternetGatewayOutput, error) - DetachNetworkInterfaceRequest(*ec2.DetachNetworkInterfaceInput) (*service.Request, *ec2.DetachNetworkInterfaceOutput) + DetachNetworkInterfaceRequest(*ec2.DetachNetworkInterfaceInput) (*request.Request, *ec2.DetachNetworkInterfaceOutput) DetachNetworkInterface(*ec2.DetachNetworkInterfaceInput) (*ec2.DetachNetworkInterfaceOutput, error) - DetachVolumeRequest(*ec2.DetachVolumeInput) (*service.Request, *ec2.VolumeAttachment) + DetachVolumeRequest(*ec2.DetachVolumeInput) (*request.Request, *ec2.VolumeAttachment) DetachVolume(*ec2.DetachVolumeInput) (*ec2.VolumeAttachment, error) - DetachVpnGatewayRequest(*ec2.DetachVpnGatewayInput) (*service.Request, *ec2.DetachVpnGatewayOutput) + DetachVpnGatewayRequest(*ec2.DetachVpnGatewayInput) (*request.Request, *ec2.DetachVpnGatewayOutput) DetachVpnGateway(*ec2.DetachVpnGatewayInput) (*ec2.DetachVpnGatewayOutput, error) - DisableVgwRoutePropagationRequest(*ec2.DisableVgwRoutePropagationInput) (*service.Request, *ec2.DisableVgwRoutePropagationOutput) + DisableVgwRoutePropagationRequest(*ec2.DisableVgwRoutePropagationInput) (*request.Request, *ec2.DisableVgwRoutePropagationOutput) DisableVgwRoutePropagation(*ec2.DisableVgwRoutePropagationInput) (*ec2.DisableVgwRoutePropagationOutput, error) - DisableVpcClassicLinkRequest(*ec2.DisableVpcClassicLinkInput) (*service.Request, *ec2.DisableVpcClassicLinkOutput) + DisableVpcClassicLinkRequest(*ec2.DisableVpcClassicLinkInput) (*request.Request, *ec2.DisableVpcClassicLinkOutput) DisableVpcClassicLink(*ec2.DisableVpcClassicLinkInput) (*ec2.DisableVpcClassicLinkOutput, error) - DisassociateAddressRequest(*ec2.DisassociateAddressInput) (*service.Request, *ec2.DisassociateAddressOutput) + DisassociateAddressRequest(*ec2.DisassociateAddressInput) (*request.Request, *ec2.DisassociateAddressOutput) DisassociateAddress(*ec2.DisassociateAddressInput) (*ec2.DisassociateAddressOutput, error) - DisassociateRouteTableRequest(*ec2.DisassociateRouteTableInput) (*service.Request, *ec2.DisassociateRouteTableOutput) + DisassociateRouteTableRequest(*ec2.DisassociateRouteTableInput) (*request.Request, *ec2.DisassociateRouteTableOutput) DisassociateRouteTable(*ec2.DisassociateRouteTableInput) (*ec2.DisassociateRouteTableOutput, error) - EnableVgwRoutePropagationRequest(*ec2.EnableVgwRoutePropagationInput) (*service.Request, *ec2.EnableVgwRoutePropagationOutput) + EnableVgwRoutePropagationRequest(*ec2.EnableVgwRoutePropagationInput) (*request.Request, *ec2.EnableVgwRoutePropagationOutput) EnableVgwRoutePropagation(*ec2.EnableVgwRoutePropagationInput) (*ec2.EnableVgwRoutePropagationOutput, error) - EnableVolumeIORequest(*ec2.EnableVolumeIOInput) (*service.Request, *ec2.EnableVolumeIOOutput) + EnableVolumeIORequest(*ec2.EnableVolumeIOInput) (*request.Request, *ec2.EnableVolumeIOOutput) EnableVolumeIO(*ec2.EnableVolumeIOInput) (*ec2.EnableVolumeIOOutput, error) - EnableVpcClassicLinkRequest(*ec2.EnableVpcClassicLinkInput) (*service.Request, *ec2.EnableVpcClassicLinkOutput) + EnableVpcClassicLinkRequest(*ec2.EnableVpcClassicLinkInput) (*request.Request, *ec2.EnableVpcClassicLinkOutput) EnableVpcClassicLink(*ec2.EnableVpcClassicLinkInput) (*ec2.EnableVpcClassicLinkOutput, error) - GetConsoleOutputRequest(*ec2.GetConsoleOutputInput) (*service.Request, *ec2.GetConsoleOutputOutput) + GetConsoleOutputRequest(*ec2.GetConsoleOutputInput) (*request.Request, *ec2.GetConsoleOutputOutput) GetConsoleOutput(*ec2.GetConsoleOutputInput) (*ec2.GetConsoleOutputOutput, error) - GetPasswordDataRequest(*ec2.GetPasswordDataInput) (*service.Request, *ec2.GetPasswordDataOutput) + GetPasswordDataRequest(*ec2.GetPasswordDataInput) (*request.Request, *ec2.GetPasswordDataOutput) GetPasswordData(*ec2.GetPasswordDataInput) (*ec2.GetPasswordDataOutput, error) - ImportImageRequest(*ec2.ImportImageInput) (*service.Request, *ec2.ImportImageOutput) + ImportImageRequest(*ec2.ImportImageInput) (*request.Request, *ec2.ImportImageOutput) ImportImage(*ec2.ImportImageInput) (*ec2.ImportImageOutput, error) - ImportInstanceRequest(*ec2.ImportInstanceInput) (*service.Request, *ec2.ImportInstanceOutput) + ImportInstanceRequest(*ec2.ImportInstanceInput) (*request.Request, *ec2.ImportInstanceOutput) ImportInstance(*ec2.ImportInstanceInput) (*ec2.ImportInstanceOutput, error) - ImportKeyPairRequest(*ec2.ImportKeyPairInput) (*service.Request, *ec2.ImportKeyPairOutput) + ImportKeyPairRequest(*ec2.ImportKeyPairInput) (*request.Request, *ec2.ImportKeyPairOutput) ImportKeyPair(*ec2.ImportKeyPairInput) (*ec2.ImportKeyPairOutput, error) - ImportSnapshotRequest(*ec2.ImportSnapshotInput) (*service.Request, *ec2.ImportSnapshotOutput) + ImportSnapshotRequest(*ec2.ImportSnapshotInput) (*request.Request, *ec2.ImportSnapshotOutput) ImportSnapshot(*ec2.ImportSnapshotInput) (*ec2.ImportSnapshotOutput, error) - ImportVolumeRequest(*ec2.ImportVolumeInput) (*service.Request, *ec2.ImportVolumeOutput) + ImportVolumeRequest(*ec2.ImportVolumeInput) (*request.Request, *ec2.ImportVolumeOutput) ImportVolume(*ec2.ImportVolumeInput) (*ec2.ImportVolumeOutput, error) - ModifyImageAttributeRequest(*ec2.ModifyImageAttributeInput) (*service.Request, *ec2.ModifyImageAttributeOutput) + ModifyImageAttributeRequest(*ec2.ModifyImageAttributeInput) (*request.Request, *ec2.ModifyImageAttributeOutput) ModifyImageAttribute(*ec2.ModifyImageAttributeInput) (*ec2.ModifyImageAttributeOutput, error) - ModifyInstanceAttributeRequest(*ec2.ModifyInstanceAttributeInput) (*service.Request, *ec2.ModifyInstanceAttributeOutput) + ModifyInstanceAttributeRequest(*ec2.ModifyInstanceAttributeInput) (*request.Request, *ec2.ModifyInstanceAttributeOutput) ModifyInstanceAttribute(*ec2.ModifyInstanceAttributeInput) (*ec2.ModifyInstanceAttributeOutput, error) - ModifyNetworkInterfaceAttributeRequest(*ec2.ModifyNetworkInterfaceAttributeInput) (*service.Request, *ec2.ModifyNetworkInterfaceAttributeOutput) + ModifyNetworkInterfaceAttributeRequest(*ec2.ModifyNetworkInterfaceAttributeInput) (*request.Request, *ec2.ModifyNetworkInterfaceAttributeOutput) ModifyNetworkInterfaceAttribute(*ec2.ModifyNetworkInterfaceAttributeInput) (*ec2.ModifyNetworkInterfaceAttributeOutput, error) - ModifyReservedInstancesRequest(*ec2.ModifyReservedInstancesInput) (*service.Request, *ec2.ModifyReservedInstancesOutput) + ModifyReservedInstancesRequest(*ec2.ModifyReservedInstancesInput) (*request.Request, *ec2.ModifyReservedInstancesOutput) ModifyReservedInstances(*ec2.ModifyReservedInstancesInput) (*ec2.ModifyReservedInstancesOutput, error) - ModifySnapshotAttributeRequest(*ec2.ModifySnapshotAttributeInput) (*service.Request, *ec2.ModifySnapshotAttributeOutput) + ModifySnapshotAttributeRequest(*ec2.ModifySnapshotAttributeInput) (*request.Request, *ec2.ModifySnapshotAttributeOutput) ModifySnapshotAttribute(*ec2.ModifySnapshotAttributeInput) (*ec2.ModifySnapshotAttributeOutput, error) - ModifySubnetAttributeRequest(*ec2.ModifySubnetAttributeInput) (*service.Request, *ec2.ModifySubnetAttributeOutput) + ModifySubnetAttributeRequest(*ec2.ModifySubnetAttributeInput) (*request.Request, *ec2.ModifySubnetAttributeOutput) ModifySubnetAttribute(*ec2.ModifySubnetAttributeInput) (*ec2.ModifySubnetAttributeOutput, error) - ModifyVolumeAttributeRequest(*ec2.ModifyVolumeAttributeInput) (*service.Request, *ec2.ModifyVolumeAttributeOutput) + ModifyVolumeAttributeRequest(*ec2.ModifyVolumeAttributeInput) (*request.Request, *ec2.ModifyVolumeAttributeOutput) ModifyVolumeAttribute(*ec2.ModifyVolumeAttributeInput) (*ec2.ModifyVolumeAttributeOutput, error) - ModifyVpcAttributeRequest(*ec2.ModifyVpcAttributeInput) (*service.Request, *ec2.ModifyVpcAttributeOutput) + ModifyVpcAttributeRequest(*ec2.ModifyVpcAttributeInput) (*request.Request, *ec2.ModifyVpcAttributeOutput) ModifyVpcAttribute(*ec2.ModifyVpcAttributeInput) (*ec2.ModifyVpcAttributeOutput, error) - ModifyVpcEndpointRequest(*ec2.ModifyVpcEndpointInput) (*service.Request, *ec2.ModifyVpcEndpointOutput) + ModifyVpcEndpointRequest(*ec2.ModifyVpcEndpointInput) (*request.Request, *ec2.ModifyVpcEndpointOutput) ModifyVpcEndpoint(*ec2.ModifyVpcEndpointInput) (*ec2.ModifyVpcEndpointOutput, error) - MonitorInstancesRequest(*ec2.MonitorInstancesInput) (*service.Request, *ec2.MonitorInstancesOutput) + MonitorInstancesRequest(*ec2.MonitorInstancesInput) (*request.Request, *ec2.MonitorInstancesOutput) MonitorInstances(*ec2.MonitorInstancesInput) (*ec2.MonitorInstancesOutput, error) - MoveAddressToVpcRequest(*ec2.MoveAddressToVpcInput) (*service.Request, *ec2.MoveAddressToVpcOutput) + MoveAddressToVpcRequest(*ec2.MoveAddressToVpcInput) (*request.Request, *ec2.MoveAddressToVpcOutput) MoveAddressToVpc(*ec2.MoveAddressToVpcInput) (*ec2.MoveAddressToVpcOutput, error) - PurchaseReservedInstancesOfferingRequest(*ec2.PurchaseReservedInstancesOfferingInput) (*service.Request, *ec2.PurchaseReservedInstancesOfferingOutput) + PurchaseReservedInstancesOfferingRequest(*ec2.PurchaseReservedInstancesOfferingInput) (*request.Request, *ec2.PurchaseReservedInstancesOfferingOutput) PurchaseReservedInstancesOffering(*ec2.PurchaseReservedInstancesOfferingInput) (*ec2.PurchaseReservedInstancesOfferingOutput, error) - RebootInstancesRequest(*ec2.RebootInstancesInput) (*service.Request, *ec2.RebootInstancesOutput) + RebootInstancesRequest(*ec2.RebootInstancesInput) (*request.Request, *ec2.RebootInstancesOutput) RebootInstances(*ec2.RebootInstancesInput) (*ec2.RebootInstancesOutput, error) - RegisterImageRequest(*ec2.RegisterImageInput) (*service.Request, *ec2.RegisterImageOutput) + RegisterImageRequest(*ec2.RegisterImageInput) (*request.Request, *ec2.RegisterImageOutput) RegisterImage(*ec2.RegisterImageInput) (*ec2.RegisterImageOutput, error) - RejectVpcPeeringConnectionRequest(*ec2.RejectVpcPeeringConnectionInput) (*service.Request, *ec2.RejectVpcPeeringConnectionOutput) + RejectVpcPeeringConnectionRequest(*ec2.RejectVpcPeeringConnectionInput) (*request.Request, *ec2.RejectVpcPeeringConnectionOutput) RejectVpcPeeringConnection(*ec2.RejectVpcPeeringConnectionInput) (*ec2.RejectVpcPeeringConnectionOutput, error) - ReleaseAddressRequest(*ec2.ReleaseAddressInput) (*service.Request, *ec2.ReleaseAddressOutput) + ReleaseAddressRequest(*ec2.ReleaseAddressInput) (*request.Request, *ec2.ReleaseAddressOutput) ReleaseAddress(*ec2.ReleaseAddressInput) (*ec2.ReleaseAddressOutput, error) - ReplaceNetworkAclAssociationRequest(*ec2.ReplaceNetworkAclAssociationInput) (*service.Request, *ec2.ReplaceNetworkAclAssociationOutput) + ReplaceNetworkAclAssociationRequest(*ec2.ReplaceNetworkAclAssociationInput) (*request.Request, *ec2.ReplaceNetworkAclAssociationOutput) ReplaceNetworkAclAssociation(*ec2.ReplaceNetworkAclAssociationInput) (*ec2.ReplaceNetworkAclAssociationOutput, error) - ReplaceNetworkAclEntryRequest(*ec2.ReplaceNetworkAclEntryInput) (*service.Request, *ec2.ReplaceNetworkAclEntryOutput) + ReplaceNetworkAclEntryRequest(*ec2.ReplaceNetworkAclEntryInput) (*request.Request, *ec2.ReplaceNetworkAclEntryOutput) ReplaceNetworkAclEntry(*ec2.ReplaceNetworkAclEntryInput) (*ec2.ReplaceNetworkAclEntryOutput, error) - ReplaceRouteRequest(*ec2.ReplaceRouteInput) (*service.Request, *ec2.ReplaceRouteOutput) + ReplaceRouteRequest(*ec2.ReplaceRouteInput) (*request.Request, *ec2.ReplaceRouteOutput) ReplaceRoute(*ec2.ReplaceRouteInput) (*ec2.ReplaceRouteOutput, error) - ReplaceRouteTableAssociationRequest(*ec2.ReplaceRouteTableAssociationInput) (*service.Request, *ec2.ReplaceRouteTableAssociationOutput) + ReplaceRouteTableAssociationRequest(*ec2.ReplaceRouteTableAssociationInput) (*request.Request, *ec2.ReplaceRouteTableAssociationOutput) ReplaceRouteTableAssociation(*ec2.ReplaceRouteTableAssociationInput) (*ec2.ReplaceRouteTableAssociationOutput, error) - ReportInstanceStatusRequest(*ec2.ReportInstanceStatusInput) (*service.Request, *ec2.ReportInstanceStatusOutput) + ReportInstanceStatusRequest(*ec2.ReportInstanceStatusInput) (*request.Request, *ec2.ReportInstanceStatusOutput) ReportInstanceStatus(*ec2.ReportInstanceStatusInput) (*ec2.ReportInstanceStatusOutput, error) - RequestSpotFleetRequest(*ec2.RequestSpotFleetInput) (*service.Request, *ec2.RequestSpotFleetOutput) + RequestSpotFleetRequest(*ec2.RequestSpotFleetInput) (*request.Request, *ec2.RequestSpotFleetOutput) RequestSpotFleet(*ec2.RequestSpotFleetInput) (*ec2.RequestSpotFleetOutput, error) - RequestSpotInstancesRequest(*ec2.RequestSpotInstancesInput) (*service.Request, *ec2.RequestSpotInstancesOutput) + RequestSpotInstancesRequest(*ec2.RequestSpotInstancesInput) (*request.Request, *ec2.RequestSpotInstancesOutput) RequestSpotInstances(*ec2.RequestSpotInstancesInput) (*ec2.RequestSpotInstancesOutput, error) - ResetImageAttributeRequest(*ec2.ResetImageAttributeInput) (*service.Request, *ec2.ResetImageAttributeOutput) + ResetImageAttributeRequest(*ec2.ResetImageAttributeInput) (*request.Request, *ec2.ResetImageAttributeOutput) ResetImageAttribute(*ec2.ResetImageAttributeInput) (*ec2.ResetImageAttributeOutput, error) - ResetInstanceAttributeRequest(*ec2.ResetInstanceAttributeInput) (*service.Request, *ec2.ResetInstanceAttributeOutput) + ResetInstanceAttributeRequest(*ec2.ResetInstanceAttributeInput) (*request.Request, *ec2.ResetInstanceAttributeOutput) ResetInstanceAttribute(*ec2.ResetInstanceAttributeInput) (*ec2.ResetInstanceAttributeOutput, error) - ResetNetworkInterfaceAttributeRequest(*ec2.ResetNetworkInterfaceAttributeInput) (*service.Request, *ec2.ResetNetworkInterfaceAttributeOutput) + ResetNetworkInterfaceAttributeRequest(*ec2.ResetNetworkInterfaceAttributeInput) (*request.Request, *ec2.ResetNetworkInterfaceAttributeOutput) ResetNetworkInterfaceAttribute(*ec2.ResetNetworkInterfaceAttributeInput) (*ec2.ResetNetworkInterfaceAttributeOutput, error) - ResetSnapshotAttributeRequest(*ec2.ResetSnapshotAttributeInput) (*service.Request, *ec2.ResetSnapshotAttributeOutput) + ResetSnapshotAttributeRequest(*ec2.ResetSnapshotAttributeInput) (*request.Request, *ec2.ResetSnapshotAttributeOutput) ResetSnapshotAttribute(*ec2.ResetSnapshotAttributeInput) (*ec2.ResetSnapshotAttributeOutput, error) - RestoreAddressToClassicRequest(*ec2.RestoreAddressToClassicInput) (*service.Request, *ec2.RestoreAddressToClassicOutput) + RestoreAddressToClassicRequest(*ec2.RestoreAddressToClassicInput) (*request.Request, *ec2.RestoreAddressToClassicOutput) RestoreAddressToClassic(*ec2.RestoreAddressToClassicInput) (*ec2.RestoreAddressToClassicOutput, error) - RevokeSecurityGroupEgressRequest(*ec2.RevokeSecurityGroupEgressInput) (*service.Request, *ec2.RevokeSecurityGroupEgressOutput) + RevokeSecurityGroupEgressRequest(*ec2.RevokeSecurityGroupEgressInput) (*request.Request, *ec2.RevokeSecurityGroupEgressOutput) RevokeSecurityGroupEgress(*ec2.RevokeSecurityGroupEgressInput) (*ec2.RevokeSecurityGroupEgressOutput, error) - RevokeSecurityGroupIngressRequest(*ec2.RevokeSecurityGroupIngressInput) (*service.Request, *ec2.RevokeSecurityGroupIngressOutput) + RevokeSecurityGroupIngressRequest(*ec2.RevokeSecurityGroupIngressInput) (*request.Request, *ec2.RevokeSecurityGroupIngressOutput) RevokeSecurityGroupIngress(*ec2.RevokeSecurityGroupIngressInput) (*ec2.RevokeSecurityGroupIngressOutput, error) - RunInstancesRequest(*ec2.RunInstancesInput) (*service.Request, *ec2.Reservation) + RunInstancesRequest(*ec2.RunInstancesInput) (*request.Request, *ec2.Reservation) RunInstances(*ec2.RunInstancesInput) (*ec2.Reservation, error) - StartInstancesRequest(*ec2.StartInstancesInput) (*service.Request, *ec2.StartInstancesOutput) + StartInstancesRequest(*ec2.StartInstancesInput) (*request.Request, *ec2.StartInstancesOutput) StartInstances(*ec2.StartInstancesInput) (*ec2.StartInstancesOutput, error) - StopInstancesRequest(*ec2.StopInstancesInput) (*service.Request, *ec2.StopInstancesOutput) + StopInstancesRequest(*ec2.StopInstancesInput) (*request.Request, *ec2.StopInstancesOutput) StopInstances(*ec2.StopInstancesInput) (*ec2.StopInstancesOutput, error) - TerminateInstancesRequest(*ec2.TerminateInstancesInput) (*service.Request, *ec2.TerminateInstancesOutput) + TerminateInstancesRequest(*ec2.TerminateInstancesInput) (*request.Request, *ec2.TerminateInstancesOutput) TerminateInstances(*ec2.TerminateInstancesInput) (*ec2.TerminateInstancesOutput, error) - UnassignPrivateIpAddressesRequest(*ec2.UnassignPrivateIpAddressesInput) (*service.Request, *ec2.UnassignPrivateIpAddressesOutput) + UnassignPrivateIpAddressesRequest(*ec2.UnassignPrivateIpAddressesInput) (*request.Request, *ec2.UnassignPrivateIpAddressesOutput) UnassignPrivateIpAddresses(*ec2.UnassignPrivateIpAddressesInput) (*ec2.UnassignPrivateIpAddressesOutput, error) - UnmonitorInstancesRequest(*ec2.UnmonitorInstancesInput) (*service.Request, *ec2.UnmonitorInstancesOutput) + UnmonitorInstancesRequest(*ec2.UnmonitorInstancesInput) (*request.Request, *ec2.UnmonitorInstancesOutput) UnmonitorInstances(*ec2.UnmonitorInstancesInput) (*ec2.UnmonitorInstancesOutput, error) } diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/ec2/ec2iface/interface_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/ec2/ec2iface/interface_test.go deleted file mode 100644 index 3941d260d..000000000 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/ec2/ec2iface/interface_test.go +++ /dev/null @@ -1,15 +0,0 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. - -package ec2iface_test - -import ( - "testing" - - "github.com/aws/aws-sdk-go/service/ec2" - "github.com/aws/aws-sdk-go/service/ec2/ec2iface" - "github.com/stretchr/testify/assert" -) - -func TestInterface(t *testing.T) { - assert.Implements(t, (*ec2iface.EC2API)(nil), ec2.New(nil)) -} diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/ec2/examples_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/ec2/examples_test.go deleted file mode 100644 index ad777614b..000000000 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/ec2/examples_test.go +++ /dev/null @@ -1,6619 +0,0 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. - -package ec2_test - -import ( - "bytes" - "fmt" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/awsutil" - "github.com/aws/aws-sdk-go/service/ec2" -) - -var _ time.Duration -var _ bytes.Buffer - -func ExampleEC2_AcceptVpcPeeringConnection() { - svc := ec2.New(nil) - - params := &ec2.AcceptVpcPeeringConnectionInput{ - DryRun: aws.Bool(true), - VpcPeeringConnectionId: aws.String("String"), - } - resp, err := svc.AcceptVpcPeeringConnection(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_AllocateAddress() { - svc := ec2.New(nil) - - params := &ec2.AllocateAddressInput{ - Domain: aws.String("DomainType"), - DryRun: aws.Bool(true), - } - resp, err := svc.AllocateAddress(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_AssignPrivateIpAddresses() { - svc := ec2.New(nil) - - params := &ec2.AssignPrivateIpAddressesInput{ - NetworkInterfaceId: aws.String("String"), // Required - AllowReassignment: aws.Bool(true), - PrivateIpAddresses: []*string{ - aws.String("String"), // Required - // More values... - }, - SecondaryPrivateIpAddressCount: aws.Int64(1), - } - resp, err := svc.AssignPrivateIpAddresses(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_AssociateAddress() { - svc := ec2.New(nil) - - params := &ec2.AssociateAddressInput{ - AllocationId: aws.String("String"), - AllowReassociation: aws.Bool(true), - DryRun: aws.Bool(true), - InstanceId: aws.String("String"), - NetworkInterfaceId: aws.String("String"), - PrivateIpAddress: aws.String("String"), - PublicIp: aws.String("String"), - } - resp, err := svc.AssociateAddress(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_AssociateDhcpOptions() { - svc := ec2.New(nil) - - params := &ec2.AssociateDhcpOptionsInput{ - DhcpOptionsId: aws.String("String"), // Required - VpcId: aws.String("String"), // Required - DryRun: aws.Bool(true), - } - resp, err := svc.AssociateDhcpOptions(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_AssociateRouteTable() { - svc := ec2.New(nil) - - params := &ec2.AssociateRouteTableInput{ - RouteTableId: aws.String("String"), // Required - SubnetId: aws.String("String"), // Required - DryRun: aws.Bool(true), - } - resp, err := svc.AssociateRouteTable(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_AttachClassicLinkVpc() { - svc := ec2.New(nil) - - params := &ec2.AttachClassicLinkVpcInput{ - Groups: []*string{ // Required - aws.String("String"), // Required - // More values... - }, - InstanceId: aws.String("String"), // Required - VpcId: aws.String("String"), // Required - DryRun: aws.Bool(true), - } - resp, err := svc.AttachClassicLinkVpc(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_AttachInternetGateway() { - svc := ec2.New(nil) - - params := &ec2.AttachInternetGatewayInput{ - InternetGatewayId: aws.String("String"), // Required - VpcId: aws.String("String"), // Required - DryRun: aws.Bool(true), - } - resp, err := svc.AttachInternetGateway(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_AttachNetworkInterface() { - svc := ec2.New(nil) - - params := &ec2.AttachNetworkInterfaceInput{ - DeviceIndex: aws.Int64(1), // Required - InstanceId: aws.String("String"), // Required - NetworkInterfaceId: aws.String("String"), // Required - DryRun: aws.Bool(true), - } - resp, err := svc.AttachNetworkInterface(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_AttachVolume() { - svc := ec2.New(nil) - - params := &ec2.AttachVolumeInput{ - Device: aws.String("String"), // Required - InstanceId: aws.String("String"), // Required - VolumeId: aws.String("String"), // Required - DryRun: aws.Bool(true), - } - resp, err := svc.AttachVolume(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_AttachVpnGateway() { - svc := ec2.New(nil) - - params := &ec2.AttachVpnGatewayInput{ - VpcId: aws.String("String"), // Required - VpnGatewayId: aws.String("String"), // Required - DryRun: aws.Bool(true), - } - resp, err := svc.AttachVpnGateway(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_AuthorizeSecurityGroupEgress() { - svc := ec2.New(nil) - - 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), - } - resp, err := svc.AuthorizeSecurityGroupEgress(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_AuthorizeSecurityGroupIngress() { - svc := ec2.New(nil) - - params := &ec2.AuthorizeSecurityGroupIngressInput{ - CidrIp: aws.String("String"), - DryRun: aws.Bool(true), - FromPort: aws.Int64(1), - GroupId: aws.String("String"), - GroupName: aws.String("String"), - 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), - } - resp, err := svc.AuthorizeSecurityGroupIngress(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_BundleInstance() { - svc := ec2.New(nil) - - params := &ec2.BundleInstanceInput{ - InstanceId: aws.String("String"), // Required - Storage: &ec2.Storage{ // Required - S3: &ec2.S3Storage{ - AWSAccessKeyId: aws.String("String"), - Bucket: aws.String("String"), - Prefix: aws.String("String"), - UploadPolicy: []byte("PAYLOAD"), - UploadPolicySignature: aws.String("String"), - }, - }, - DryRun: aws.Bool(true), - } - resp, err := svc.BundleInstance(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_CancelBundleTask() { - svc := ec2.New(nil) - - params := &ec2.CancelBundleTaskInput{ - BundleId: aws.String("String"), // Required - DryRun: aws.Bool(true), - } - resp, err := svc.CancelBundleTask(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_CancelConversionTask() { - svc := ec2.New(nil) - - params := &ec2.CancelConversionTaskInput{ - ConversionTaskId: aws.String("String"), // Required - DryRun: aws.Bool(true), - ReasonMessage: aws.String("String"), - } - resp, err := svc.CancelConversionTask(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_CancelExportTask() { - svc := ec2.New(nil) - - params := &ec2.CancelExportTaskInput{ - ExportTaskId: aws.String("String"), // Required - } - resp, err := svc.CancelExportTask(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_CancelImportTask() { - svc := ec2.New(nil) - - params := &ec2.CancelImportTaskInput{ - CancelReason: aws.String("String"), - DryRun: aws.Bool(true), - ImportTaskId: aws.String("String"), - } - resp, err := svc.CancelImportTask(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_CancelReservedInstancesListing() { - svc := ec2.New(nil) - - params := &ec2.CancelReservedInstancesListingInput{ - ReservedInstancesListingId: aws.String("String"), // Required - } - resp, err := svc.CancelReservedInstancesListing(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_CancelSpotFleetRequests() { - svc := ec2.New(nil) - - params := &ec2.CancelSpotFleetRequestsInput{ - SpotFleetRequestIds: []*string{ // Required - aws.String("String"), // Required - // More values... - }, - TerminateInstances: aws.Bool(true), // Required - DryRun: aws.Bool(true), - } - resp, err := svc.CancelSpotFleetRequests(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_CancelSpotInstanceRequests() { - svc := ec2.New(nil) - - params := &ec2.CancelSpotInstanceRequestsInput{ - SpotInstanceRequestIds: []*string{ // Required - aws.String("String"), // Required - // More values... - }, - DryRun: aws.Bool(true), - } - resp, err := svc.CancelSpotInstanceRequests(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_ConfirmProductInstance() { - svc := ec2.New(nil) - - params := &ec2.ConfirmProductInstanceInput{ - InstanceId: aws.String("String"), // Required - ProductCode: aws.String("String"), // Required - DryRun: aws.Bool(true), - } - resp, err := svc.ConfirmProductInstance(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_CopyImage() { - svc := ec2.New(nil) - - params := &ec2.CopyImageInput{ - Name: aws.String("String"), // Required - SourceImageId: aws.String("String"), // Required - SourceRegion: aws.String("String"), // Required - ClientToken: aws.String("String"), - Description: aws.String("String"), - DryRun: aws.Bool(true), - } - resp, err := svc.CopyImage(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_CopySnapshot() { - svc := ec2.New(nil) - - params := &ec2.CopySnapshotInput{ - SourceRegion: aws.String("String"), // Required - SourceSnapshotId: aws.String("String"), // Required - Description: aws.String("String"), - DestinationRegion: aws.String("String"), - DryRun: aws.Bool(true), - Encrypted: aws.Bool(true), - KmsKeyId: aws.String("String"), - PresignedUrl: aws.String("String"), - } - resp, err := svc.CopySnapshot(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_CreateCustomerGateway() { - svc := ec2.New(nil) - - params := &ec2.CreateCustomerGatewayInput{ - BgpAsn: aws.Int64(1), // Required - PublicIp: aws.String("String"), // Required - Type: aws.String("GatewayType"), // Required - DryRun: aws.Bool(true), - } - resp, err := svc.CreateCustomerGateway(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_CreateDhcpOptions() { - svc := ec2.New(nil) - - params := &ec2.CreateDhcpOptionsInput{ - DhcpConfigurations: []*ec2.NewDhcpConfiguration{ // Required - { // Required - Key: aws.String("String"), - Values: []*string{ - aws.String("String"), // Required - // More values... - }, - }, - // More values... - }, - DryRun: aws.Bool(true), - } - resp, err := svc.CreateDhcpOptions(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_CreateFlowLogs() { - svc := ec2.New(nil) - - params := &ec2.CreateFlowLogsInput{ - DeliverLogsPermissionArn: aws.String("String"), // Required - LogGroupName: aws.String("String"), // Required - ResourceIds: []*string{ // Required - aws.String("String"), // Required - // More values... - }, - ResourceType: aws.String("FlowLogsResourceType"), // Required - TrafficType: aws.String("TrafficType"), // Required - ClientToken: aws.String("String"), - } - resp, err := svc.CreateFlowLogs(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_CreateImage() { - svc := ec2.New(nil) - - params := &ec2.CreateImageInput{ - InstanceId: aws.String("String"), // Required - Name: aws.String("String"), // Required - BlockDeviceMappings: []*ec2.BlockDeviceMapping{ - { // Required - DeviceName: aws.String("String"), - Ebs: &ec2.EbsBlockDevice{ - DeleteOnTermination: aws.Bool(true), - Encrypted: aws.Bool(true), - Iops: aws.Int64(1), - SnapshotId: aws.String("String"), - VolumeSize: aws.Int64(1), - VolumeType: aws.String("VolumeType"), - }, - NoDevice: aws.String("String"), - VirtualName: aws.String("String"), - }, - // More values... - }, - Description: aws.String("String"), - DryRun: aws.Bool(true), - NoReboot: aws.Bool(true), - } - resp, err := svc.CreateImage(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_CreateInstanceExportTask() { - svc := ec2.New(nil) - - params := &ec2.CreateInstanceExportTaskInput{ - InstanceId: aws.String("String"), // Required - Description: aws.String("String"), - ExportToS3Task: &ec2.ExportToS3TaskSpecification{ - ContainerFormat: aws.String("ContainerFormat"), - DiskImageFormat: aws.String("DiskImageFormat"), - S3Bucket: aws.String("String"), - S3Prefix: aws.String("String"), - }, - TargetEnvironment: aws.String("ExportEnvironment"), - } - resp, err := svc.CreateInstanceExportTask(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_CreateInternetGateway() { - svc := ec2.New(nil) - - params := &ec2.CreateInternetGatewayInput{ - DryRun: aws.Bool(true), - } - resp, err := svc.CreateInternetGateway(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_CreateKeyPair() { - svc := ec2.New(nil) - - params := &ec2.CreateKeyPairInput{ - KeyName: aws.String("String"), // Required - DryRun: aws.Bool(true), - } - resp, err := svc.CreateKeyPair(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_CreateNetworkAcl() { - svc := ec2.New(nil) - - params := &ec2.CreateNetworkAclInput{ - VpcId: aws.String("String"), // Required - DryRun: aws.Bool(true), - } - resp, err := svc.CreateNetworkAcl(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_CreateNetworkAclEntry() { - svc := ec2.New(nil) - - params := &ec2.CreateNetworkAclEntryInput{ - CidrBlock: aws.String("String"), // Required - Egress: aws.Bool(true), // Required - NetworkAclId: aws.String("String"), // Required - Protocol: aws.String("String"), // Required - RuleAction: aws.String("RuleAction"), // Required - RuleNumber: aws.Int64(1), // Required - DryRun: aws.Bool(true), - IcmpTypeCode: &ec2.IcmpTypeCode{ - Code: aws.Int64(1), - Type: aws.Int64(1), - }, - PortRange: &ec2.PortRange{ - From: aws.Int64(1), - To: aws.Int64(1), - }, - } - resp, err := svc.CreateNetworkAclEntry(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_CreateNetworkInterface() { - svc := ec2.New(nil) - - params := &ec2.CreateNetworkInterfaceInput{ - SubnetId: aws.String("String"), // Required - Description: aws.String("String"), - DryRun: aws.Bool(true), - Groups: []*string{ - aws.String("String"), // Required - // More values... - }, - PrivateIpAddress: aws.String("String"), - PrivateIpAddresses: []*ec2.PrivateIpAddressSpecification{ - { // Required - PrivateIpAddress: aws.String("String"), // Required - Primary: aws.Bool(true), - }, - // More values... - }, - SecondaryPrivateIpAddressCount: aws.Int64(1), - } - resp, err := svc.CreateNetworkInterface(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_CreatePlacementGroup() { - svc := ec2.New(nil) - - params := &ec2.CreatePlacementGroupInput{ - GroupName: aws.String("String"), // Required - Strategy: aws.String("PlacementStrategy"), // Required - DryRun: aws.Bool(true), - } - resp, err := svc.CreatePlacementGroup(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_CreateReservedInstancesListing() { - svc := ec2.New(nil) - - params := &ec2.CreateReservedInstancesListingInput{ - ClientToken: aws.String("String"), // Required - InstanceCount: aws.Int64(1), // Required - PriceSchedules: []*ec2.PriceScheduleSpecification{ // Required - { // Required - CurrencyCode: aws.String("CurrencyCodeValues"), - Price: aws.Float64(1.0), - Term: aws.Int64(1), - }, - // More values... - }, - ReservedInstancesId: aws.String("String"), // Required - } - resp, err := svc.CreateReservedInstancesListing(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_CreateRoute() { - svc := ec2.New(nil) - - params := &ec2.CreateRouteInput{ - DestinationCidrBlock: aws.String("String"), // Required - RouteTableId: aws.String("String"), // Required - DryRun: aws.Bool(true), - GatewayId: aws.String("String"), - InstanceId: aws.String("String"), - NetworkInterfaceId: aws.String("String"), - VpcPeeringConnectionId: aws.String("String"), - } - resp, err := svc.CreateRoute(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_CreateRouteTable() { - svc := ec2.New(nil) - - params := &ec2.CreateRouteTableInput{ - VpcId: aws.String("String"), // Required - DryRun: aws.Bool(true), - } - resp, err := svc.CreateRouteTable(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_CreateSecurityGroup() { - svc := ec2.New(nil) - - params := &ec2.CreateSecurityGroupInput{ - Description: aws.String("String"), // Required - GroupName: aws.String("String"), // Required - DryRun: aws.Bool(true), - VpcId: aws.String("String"), - } - resp, err := svc.CreateSecurityGroup(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_CreateSnapshot() { - svc := ec2.New(nil) - - params := &ec2.CreateSnapshotInput{ - VolumeId: aws.String("String"), // Required - Description: aws.String("String"), - DryRun: aws.Bool(true), - } - resp, err := svc.CreateSnapshot(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_CreateSpotDatafeedSubscription() { - svc := ec2.New(nil) - - params := &ec2.CreateSpotDatafeedSubscriptionInput{ - Bucket: aws.String("String"), // Required - DryRun: aws.Bool(true), - Prefix: aws.String("String"), - } - resp, err := svc.CreateSpotDatafeedSubscription(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_CreateSubnet() { - svc := ec2.New(nil) - - params := &ec2.CreateSubnetInput{ - CidrBlock: aws.String("String"), // Required - VpcId: aws.String("String"), // Required - AvailabilityZone: aws.String("String"), - DryRun: aws.Bool(true), - } - resp, err := svc.CreateSubnet(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_CreateTags() { - svc := ec2.New(nil) - - params := &ec2.CreateTagsInput{ - Resources: []*string{ // Required - aws.String("String"), // Required - // More values... - }, - Tags: []*ec2.Tag{ // Required - { // Required - Key: aws.String("String"), - Value: aws.String("String"), - }, - // More values... - }, - DryRun: aws.Bool(true), - } - resp, err := svc.CreateTags(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_CreateVolume() { - svc := ec2.New(nil) - - params := &ec2.CreateVolumeInput{ - AvailabilityZone: aws.String("String"), // Required - DryRun: aws.Bool(true), - Encrypted: aws.Bool(true), - Iops: aws.Int64(1), - KmsKeyId: aws.String("String"), - Size: aws.Int64(1), - SnapshotId: aws.String("String"), - VolumeType: aws.String("VolumeType"), - } - resp, err := svc.CreateVolume(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_CreateVpc() { - svc := ec2.New(nil) - - params := &ec2.CreateVpcInput{ - CidrBlock: aws.String("String"), // Required - DryRun: aws.Bool(true), - InstanceTenancy: aws.String("Tenancy"), - } - resp, err := svc.CreateVpc(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_CreateVpcEndpoint() { - svc := ec2.New(nil) - - params := &ec2.CreateVpcEndpointInput{ - ServiceName: aws.String("String"), // Required - VpcId: aws.String("String"), // Required - ClientToken: aws.String("String"), - DryRun: aws.Bool(true), - PolicyDocument: aws.String("String"), - RouteTableIds: []*string{ - aws.String("String"), // Required - // More values... - }, - } - resp, err := svc.CreateVpcEndpoint(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_CreateVpcPeeringConnection() { - svc := ec2.New(nil) - - params := &ec2.CreateVpcPeeringConnectionInput{ - DryRun: aws.Bool(true), - PeerOwnerId: aws.String("String"), - PeerVpcId: aws.String("String"), - VpcId: aws.String("String"), - } - resp, err := svc.CreateVpcPeeringConnection(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_CreateVpnConnection() { - svc := ec2.New(nil) - - params := &ec2.CreateVpnConnectionInput{ - CustomerGatewayId: aws.String("String"), // Required - Type: aws.String("String"), // Required - VpnGatewayId: aws.String("String"), // Required - DryRun: aws.Bool(true), - Options: &ec2.VpnConnectionOptionsSpecification{ - StaticRoutesOnly: aws.Bool(true), - }, - } - resp, err := svc.CreateVpnConnection(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_CreateVpnConnectionRoute() { - svc := ec2.New(nil) - - params := &ec2.CreateVpnConnectionRouteInput{ - DestinationCidrBlock: aws.String("String"), // Required - VpnConnectionId: aws.String("String"), // Required - } - resp, err := svc.CreateVpnConnectionRoute(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_CreateVpnGateway() { - svc := ec2.New(nil) - - params := &ec2.CreateVpnGatewayInput{ - Type: aws.String("GatewayType"), // Required - AvailabilityZone: aws.String("String"), - DryRun: aws.Bool(true), - } - resp, err := svc.CreateVpnGateway(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DeleteCustomerGateway() { - svc := ec2.New(nil) - - params := &ec2.DeleteCustomerGatewayInput{ - CustomerGatewayId: aws.String("String"), // Required - DryRun: aws.Bool(true), - } - resp, err := svc.DeleteCustomerGateway(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DeleteDhcpOptions() { - svc := ec2.New(nil) - - params := &ec2.DeleteDhcpOptionsInput{ - DhcpOptionsId: aws.String("String"), // Required - DryRun: aws.Bool(true), - } - resp, err := svc.DeleteDhcpOptions(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DeleteFlowLogs() { - svc := ec2.New(nil) - - params := &ec2.DeleteFlowLogsInput{ - FlowLogIds: []*string{ // Required - aws.String("String"), // Required - // More values... - }, - } - resp, err := svc.DeleteFlowLogs(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DeleteInternetGateway() { - svc := ec2.New(nil) - - params := &ec2.DeleteInternetGatewayInput{ - InternetGatewayId: aws.String("String"), // Required - DryRun: aws.Bool(true), - } - resp, err := svc.DeleteInternetGateway(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DeleteKeyPair() { - svc := ec2.New(nil) - - params := &ec2.DeleteKeyPairInput{ - KeyName: aws.String("String"), // Required - DryRun: aws.Bool(true), - } - resp, err := svc.DeleteKeyPair(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DeleteNetworkAcl() { - svc := ec2.New(nil) - - params := &ec2.DeleteNetworkAclInput{ - NetworkAclId: aws.String("String"), // Required - DryRun: aws.Bool(true), - } - resp, err := svc.DeleteNetworkAcl(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DeleteNetworkAclEntry() { - svc := ec2.New(nil) - - params := &ec2.DeleteNetworkAclEntryInput{ - Egress: aws.Bool(true), // Required - NetworkAclId: aws.String("String"), // Required - RuleNumber: aws.Int64(1), // Required - DryRun: aws.Bool(true), - } - resp, err := svc.DeleteNetworkAclEntry(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DeleteNetworkInterface() { - svc := ec2.New(nil) - - params := &ec2.DeleteNetworkInterfaceInput{ - NetworkInterfaceId: aws.String("String"), // Required - DryRun: aws.Bool(true), - } - resp, err := svc.DeleteNetworkInterface(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DeletePlacementGroup() { - svc := ec2.New(nil) - - params := &ec2.DeletePlacementGroupInput{ - GroupName: aws.String("String"), // Required - DryRun: aws.Bool(true), - } - resp, err := svc.DeletePlacementGroup(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DeleteRoute() { - svc := ec2.New(nil) - - params := &ec2.DeleteRouteInput{ - DestinationCidrBlock: aws.String("String"), // Required - RouteTableId: aws.String("String"), // Required - DryRun: aws.Bool(true), - } - resp, err := svc.DeleteRoute(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DeleteRouteTable() { - svc := ec2.New(nil) - - params := &ec2.DeleteRouteTableInput{ - RouteTableId: aws.String("String"), // Required - DryRun: aws.Bool(true), - } - resp, err := svc.DeleteRouteTable(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DeleteSecurityGroup() { - svc := ec2.New(nil) - - params := &ec2.DeleteSecurityGroupInput{ - DryRun: aws.Bool(true), - GroupId: aws.String("String"), - GroupName: aws.String("String"), - } - resp, err := svc.DeleteSecurityGroup(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DeleteSnapshot() { - svc := ec2.New(nil) - - params := &ec2.DeleteSnapshotInput{ - SnapshotId: aws.String("String"), // Required - DryRun: aws.Bool(true), - } - resp, err := svc.DeleteSnapshot(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DeleteSpotDatafeedSubscription() { - svc := ec2.New(nil) - - params := &ec2.DeleteSpotDatafeedSubscriptionInput{ - DryRun: aws.Bool(true), - } - resp, err := svc.DeleteSpotDatafeedSubscription(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DeleteSubnet() { - svc := ec2.New(nil) - - params := &ec2.DeleteSubnetInput{ - SubnetId: aws.String("String"), // Required - DryRun: aws.Bool(true), - } - resp, err := svc.DeleteSubnet(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DeleteTags() { - svc := ec2.New(nil) - - params := &ec2.DeleteTagsInput{ - Resources: []*string{ // Required - aws.String("String"), // Required - // More values... - }, - DryRun: aws.Bool(true), - Tags: []*ec2.Tag{ - { // Required - Key: aws.String("String"), - Value: aws.String("String"), - }, - // More values... - }, - } - resp, err := svc.DeleteTags(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DeleteVolume() { - svc := ec2.New(nil) - - params := &ec2.DeleteVolumeInput{ - VolumeId: aws.String("String"), // Required - DryRun: aws.Bool(true), - } - resp, err := svc.DeleteVolume(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DeleteVpc() { - svc := ec2.New(nil) - - params := &ec2.DeleteVpcInput{ - VpcId: aws.String("String"), // Required - DryRun: aws.Bool(true), - } - resp, err := svc.DeleteVpc(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DeleteVpcEndpoints() { - svc := ec2.New(nil) - - params := &ec2.DeleteVpcEndpointsInput{ - VpcEndpointIds: []*string{ // Required - aws.String("String"), // Required - // More values... - }, - DryRun: aws.Bool(true), - } - resp, err := svc.DeleteVpcEndpoints(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DeleteVpcPeeringConnection() { - svc := ec2.New(nil) - - params := &ec2.DeleteVpcPeeringConnectionInput{ - VpcPeeringConnectionId: aws.String("String"), // Required - DryRun: aws.Bool(true), - } - resp, err := svc.DeleteVpcPeeringConnection(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DeleteVpnConnection() { - svc := ec2.New(nil) - - params := &ec2.DeleteVpnConnectionInput{ - VpnConnectionId: aws.String("String"), // Required - DryRun: aws.Bool(true), - } - resp, err := svc.DeleteVpnConnection(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DeleteVpnConnectionRoute() { - svc := ec2.New(nil) - - params := &ec2.DeleteVpnConnectionRouteInput{ - DestinationCidrBlock: aws.String("String"), // Required - VpnConnectionId: aws.String("String"), // Required - } - resp, err := svc.DeleteVpnConnectionRoute(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DeleteVpnGateway() { - svc := ec2.New(nil) - - params := &ec2.DeleteVpnGatewayInput{ - VpnGatewayId: aws.String("String"), // Required - DryRun: aws.Bool(true), - } - resp, err := svc.DeleteVpnGateway(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DeregisterImage() { - svc := ec2.New(nil) - - params := &ec2.DeregisterImageInput{ - ImageId: aws.String("String"), // Required - DryRun: aws.Bool(true), - } - resp, err := svc.DeregisterImage(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DescribeAccountAttributes() { - svc := ec2.New(nil) - - params := &ec2.DescribeAccountAttributesInput{ - AttributeNames: []*string{ - aws.String("AccountAttributeName"), // Required - // More values... - }, - DryRun: aws.Bool(true), - } - resp, err := svc.DescribeAccountAttributes(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DescribeAddresses() { - svc := ec2.New(nil) - - params := &ec2.DescribeAddressesInput{ - AllocationIds: []*string{ - aws.String("String"), // Required - // More values... - }, - DryRun: aws.Bool(true), - Filters: []*ec2.Filter{ - { // Required - Name: aws.String("String"), - Values: []*string{ - aws.String("String"), // Required - // More values... - }, - }, - // More values... - }, - PublicIps: []*string{ - aws.String("String"), // Required - // More values... - }, - } - resp, err := svc.DescribeAddresses(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DescribeAvailabilityZones() { - svc := ec2.New(nil) - - params := &ec2.DescribeAvailabilityZonesInput{ - DryRun: aws.Bool(true), - Filters: []*ec2.Filter{ - { // Required - Name: aws.String("String"), - Values: []*string{ - aws.String("String"), // Required - // More values... - }, - }, - // More values... - }, - ZoneNames: []*string{ - aws.String("String"), // Required - // More values... - }, - } - resp, err := svc.DescribeAvailabilityZones(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DescribeBundleTasks() { - svc := ec2.New(nil) - - params := &ec2.DescribeBundleTasksInput{ - BundleIds: []*string{ - aws.String("String"), // Required - // More values... - }, - DryRun: aws.Bool(true), - Filters: []*ec2.Filter{ - { // Required - Name: aws.String("String"), - Values: []*string{ - aws.String("String"), // Required - // More values... - }, - }, - // More values... - }, - } - resp, err := svc.DescribeBundleTasks(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DescribeClassicLinkInstances() { - svc := ec2.New(nil) - - params := &ec2.DescribeClassicLinkInstancesInput{ - DryRun: aws.Bool(true), - Filters: []*ec2.Filter{ - { // Required - Name: aws.String("String"), - Values: []*string{ - aws.String("String"), // Required - // More values... - }, - }, - // More values... - }, - InstanceIds: []*string{ - aws.String("String"), // Required - // More values... - }, - MaxResults: aws.Int64(1), - NextToken: aws.String("String"), - } - resp, err := svc.DescribeClassicLinkInstances(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DescribeConversionTasks() { - svc := ec2.New(nil) - - params := &ec2.DescribeConversionTasksInput{ - ConversionTaskIds: []*string{ - aws.String("String"), // Required - // More values... - }, - DryRun: aws.Bool(true), - Filters: []*ec2.Filter{ - { // Required - Name: aws.String("String"), - Values: []*string{ - aws.String("String"), // Required - // More values... - }, - }, - // More values... - }, - } - resp, err := svc.DescribeConversionTasks(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DescribeCustomerGateways() { - svc := ec2.New(nil) - - params := &ec2.DescribeCustomerGatewaysInput{ - CustomerGatewayIds: []*string{ - aws.String("String"), // Required - // More values... - }, - DryRun: aws.Bool(true), - Filters: []*ec2.Filter{ - { // Required - Name: aws.String("String"), - Values: []*string{ - aws.String("String"), // Required - // More values... - }, - }, - // More values... - }, - } - resp, err := svc.DescribeCustomerGateways(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DescribeDhcpOptions() { - svc := ec2.New(nil) - - params := &ec2.DescribeDhcpOptionsInput{ - DhcpOptionsIds: []*string{ - aws.String("String"), // Required - // More values... - }, - DryRun: aws.Bool(true), - Filters: []*ec2.Filter{ - { // Required - Name: aws.String("String"), - Values: []*string{ - aws.String("String"), // Required - // More values... - }, - }, - // More values... - }, - } - resp, err := svc.DescribeDhcpOptions(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DescribeExportTasks() { - svc := ec2.New(nil) - - params := &ec2.DescribeExportTasksInput{ - ExportTaskIds: []*string{ - aws.String("String"), // Required - // More values... - }, - } - resp, err := svc.DescribeExportTasks(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DescribeFlowLogs() { - svc := ec2.New(nil) - - params := &ec2.DescribeFlowLogsInput{ - Filter: []*ec2.Filter{ - { // Required - Name: aws.String("String"), - Values: []*string{ - aws.String("String"), // Required - // More values... - }, - }, - // More values... - }, - FlowLogIds: []*string{ - aws.String("String"), // Required - // More values... - }, - MaxResults: aws.Int64(1), - NextToken: aws.String("String"), - } - resp, err := svc.DescribeFlowLogs(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DescribeImageAttribute() { - svc := ec2.New(nil) - - params := &ec2.DescribeImageAttributeInput{ - Attribute: aws.String("ImageAttributeName"), // Required - ImageId: aws.String("String"), // Required - DryRun: aws.Bool(true), - } - resp, err := svc.DescribeImageAttribute(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DescribeImages() { - svc := ec2.New(nil) - - params := &ec2.DescribeImagesInput{ - DryRun: aws.Bool(true), - ExecutableUsers: []*string{ - aws.String("String"), // Required - // More values... - }, - Filters: []*ec2.Filter{ - { // Required - Name: aws.String("String"), - Values: []*string{ - aws.String("String"), // Required - // More values... - }, - }, - // More values... - }, - ImageIds: []*string{ - aws.String("String"), // Required - // More values... - }, - Owners: []*string{ - aws.String("String"), // Required - // More values... - }, - } - resp, err := svc.DescribeImages(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DescribeImportImageTasks() { - svc := ec2.New(nil) - - params := &ec2.DescribeImportImageTasksInput{ - DryRun: aws.Bool(true), - Filters: []*ec2.Filter{ - { // Required - Name: aws.String("String"), - Values: []*string{ - aws.String("String"), // Required - // More values... - }, - }, - // More values... - }, - ImportTaskIds: []*string{ - aws.String("String"), // Required - // More values... - }, - MaxResults: aws.Int64(1), - NextToken: aws.String("String"), - } - resp, err := svc.DescribeImportImageTasks(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DescribeImportSnapshotTasks() { - svc := ec2.New(nil) - - params := &ec2.DescribeImportSnapshotTasksInput{ - DryRun: aws.Bool(true), - Filters: []*ec2.Filter{ - { // Required - Name: aws.String("String"), - Values: []*string{ - aws.String("String"), // Required - // More values... - }, - }, - // More values... - }, - ImportTaskIds: []*string{ - aws.String("String"), // Required - // More values... - }, - MaxResults: aws.Int64(1), - NextToken: aws.String("String"), - } - resp, err := svc.DescribeImportSnapshotTasks(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DescribeInstanceAttribute() { - svc := ec2.New(nil) - - params := &ec2.DescribeInstanceAttributeInput{ - Attribute: aws.String("InstanceAttributeName"), // Required - InstanceId: aws.String("String"), // Required - DryRun: aws.Bool(true), - } - resp, err := svc.DescribeInstanceAttribute(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DescribeInstanceStatus() { - svc := ec2.New(nil) - - params := &ec2.DescribeInstanceStatusInput{ - DryRun: aws.Bool(true), - Filters: []*ec2.Filter{ - { // Required - Name: aws.String("String"), - Values: []*string{ - aws.String("String"), // Required - // More values... - }, - }, - // More values... - }, - IncludeAllInstances: aws.Bool(true), - InstanceIds: []*string{ - aws.String("String"), // Required - // More values... - }, - MaxResults: aws.Int64(1), - NextToken: aws.String("String"), - } - resp, err := svc.DescribeInstanceStatus(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DescribeInstances() { - svc := ec2.New(nil) - - params := &ec2.DescribeInstancesInput{ - DryRun: aws.Bool(true), - Filters: []*ec2.Filter{ - { // Required - Name: aws.String("String"), - Values: []*string{ - aws.String("String"), // Required - // More values... - }, - }, - // More values... - }, - InstanceIds: []*string{ - aws.String("String"), // Required - // More values... - }, - MaxResults: aws.Int64(1), - NextToken: aws.String("String"), - } - resp, err := svc.DescribeInstances(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DescribeInternetGateways() { - svc := ec2.New(nil) - - params := &ec2.DescribeInternetGatewaysInput{ - DryRun: aws.Bool(true), - Filters: []*ec2.Filter{ - { // Required - Name: aws.String("String"), - Values: []*string{ - aws.String("String"), // Required - // More values... - }, - }, - // More values... - }, - InternetGatewayIds: []*string{ - aws.String("String"), // Required - // More values... - }, - } - resp, err := svc.DescribeInternetGateways(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DescribeKeyPairs() { - svc := ec2.New(nil) - - params := &ec2.DescribeKeyPairsInput{ - DryRun: aws.Bool(true), - Filters: []*ec2.Filter{ - { // Required - Name: aws.String("String"), - Values: []*string{ - aws.String("String"), // Required - // More values... - }, - }, - // More values... - }, - KeyNames: []*string{ - aws.String("String"), // Required - // More values... - }, - } - resp, err := svc.DescribeKeyPairs(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DescribeMovingAddresses() { - svc := ec2.New(nil) - - params := &ec2.DescribeMovingAddressesInput{ - DryRun: aws.Bool(true), - Filters: []*ec2.Filter{ - { // Required - Name: aws.String("String"), - Values: []*string{ - aws.String("String"), // Required - // More values... - }, - }, - // More values... - }, - MaxResults: aws.Int64(1), - NextToken: aws.String("String"), - PublicIps: []*string{ - aws.String("String"), // Required - // More values... - }, - } - resp, err := svc.DescribeMovingAddresses(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DescribeNetworkAcls() { - svc := ec2.New(nil) - - params := &ec2.DescribeNetworkAclsInput{ - DryRun: aws.Bool(true), - Filters: []*ec2.Filter{ - { // Required - Name: aws.String("String"), - Values: []*string{ - aws.String("String"), // Required - // More values... - }, - }, - // More values... - }, - NetworkAclIds: []*string{ - aws.String("String"), // Required - // More values... - }, - } - resp, err := svc.DescribeNetworkAcls(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DescribeNetworkInterfaceAttribute() { - svc := ec2.New(nil) - - params := &ec2.DescribeNetworkInterfaceAttributeInput{ - NetworkInterfaceId: aws.String("String"), // Required - Attribute: aws.String("NetworkInterfaceAttribute"), - DryRun: aws.Bool(true), - } - resp, err := svc.DescribeNetworkInterfaceAttribute(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DescribeNetworkInterfaces() { - svc := ec2.New(nil) - - params := &ec2.DescribeNetworkInterfacesInput{ - DryRun: aws.Bool(true), - Filters: []*ec2.Filter{ - { // Required - Name: aws.String("String"), - Values: []*string{ - aws.String("String"), // Required - // More values... - }, - }, - // More values... - }, - NetworkInterfaceIds: []*string{ - aws.String("String"), // Required - // More values... - }, - } - resp, err := svc.DescribeNetworkInterfaces(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DescribePlacementGroups() { - svc := ec2.New(nil) - - params := &ec2.DescribePlacementGroupsInput{ - DryRun: aws.Bool(true), - Filters: []*ec2.Filter{ - { // Required - Name: aws.String("String"), - Values: []*string{ - aws.String("String"), // Required - // More values... - }, - }, - // More values... - }, - GroupNames: []*string{ - aws.String("String"), // Required - // More values... - }, - } - resp, err := svc.DescribePlacementGroups(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DescribePrefixLists() { - svc := ec2.New(nil) - - params := &ec2.DescribePrefixListsInput{ - DryRun: aws.Bool(true), - Filters: []*ec2.Filter{ - { // Required - Name: aws.String("String"), - Values: []*string{ - aws.String("String"), // Required - // More values... - }, - }, - // More values... - }, - MaxResults: aws.Int64(1), - NextToken: aws.String("String"), - PrefixListIds: []*string{ - aws.String("String"), // Required - // More values... - }, - } - resp, err := svc.DescribePrefixLists(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DescribeRegions() { - svc := ec2.New(nil) - - params := &ec2.DescribeRegionsInput{ - DryRun: aws.Bool(true), - Filters: []*ec2.Filter{ - { // Required - Name: aws.String("String"), - Values: []*string{ - aws.String("String"), // Required - // More values... - }, - }, - // More values... - }, - RegionNames: []*string{ - aws.String("String"), // Required - // More values... - }, - } - resp, err := svc.DescribeRegions(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DescribeReservedInstances() { - svc := ec2.New(nil) - - params := &ec2.DescribeReservedInstancesInput{ - DryRun: aws.Bool(true), - Filters: []*ec2.Filter{ - { // Required - Name: aws.String("String"), - Values: []*string{ - aws.String("String"), // Required - // More values... - }, - }, - // More values... - }, - OfferingType: aws.String("OfferingTypeValues"), - ReservedInstancesIds: []*string{ - aws.String("String"), // Required - // More values... - }, - } - resp, err := svc.DescribeReservedInstances(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DescribeReservedInstancesListings() { - svc := ec2.New(nil) - - params := &ec2.DescribeReservedInstancesListingsInput{ - Filters: []*ec2.Filter{ - { // Required - Name: aws.String("String"), - Values: []*string{ - aws.String("String"), // Required - // More values... - }, - }, - // More values... - }, - ReservedInstancesId: aws.String("String"), - ReservedInstancesListingId: aws.String("String"), - } - resp, err := svc.DescribeReservedInstancesListings(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DescribeReservedInstancesModifications() { - svc := ec2.New(nil) - - params := &ec2.DescribeReservedInstancesModificationsInput{ - Filters: []*ec2.Filter{ - { // Required - Name: aws.String("String"), - Values: []*string{ - aws.String("String"), // Required - // More values... - }, - }, - // More values... - }, - NextToken: aws.String("String"), - ReservedInstancesModificationIds: []*string{ - aws.String("String"), // Required - // More values... - }, - } - resp, err := svc.DescribeReservedInstancesModifications(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DescribeReservedInstancesOfferings() { - svc := ec2.New(nil) - - params := &ec2.DescribeReservedInstancesOfferingsInput{ - AvailabilityZone: aws.String("String"), - DryRun: aws.Bool(true), - Filters: []*ec2.Filter{ - { // Required - Name: aws.String("String"), - Values: []*string{ - aws.String("String"), // Required - // More values... - }, - }, - // More values... - }, - IncludeMarketplace: aws.Bool(true), - InstanceTenancy: aws.String("Tenancy"), - InstanceType: aws.String("InstanceType"), - MaxDuration: aws.Int64(1), - MaxInstanceCount: aws.Int64(1), - MaxResults: aws.Int64(1), - MinDuration: aws.Int64(1), - NextToken: aws.String("String"), - OfferingType: aws.String("OfferingTypeValues"), - ProductDescription: aws.String("RIProductDescription"), - ReservedInstancesOfferingIds: []*string{ - aws.String("String"), // Required - // More values... - }, - } - resp, err := svc.DescribeReservedInstancesOfferings(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DescribeRouteTables() { - svc := ec2.New(nil) - - params := &ec2.DescribeRouteTablesInput{ - DryRun: aws.Bool(true), - Filters: []*ec2.Filter{ - { // Required - Name: aws.String("String"), - Values: []*string{ - aws.String("String"), // Required - // More values... - }, - }, - // More values... - }, - RouteTableIds: []*string{ - aws.String("String"), // Required - // More values... - }, - } - resp, err := svc.DescribeRouteTables(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DescribeSecurityGroups() { - svc := ec2.New(nil) - - params := &ec2.DescribeSecurityGroupsInput{ - DryRun: aws.Bool(true), - Filters: []*ec2.Filter{ - { // Required - Name: aws.String("String"), - Values: []*string{ - aws.String("String"), // Required - // More values... - }, - }, - // More values... - }, - GroupIds: []*string{ - aws.String("String"), // Required - // More values... - }, - GroupNames: []*string{ - aws.String("String"), // Required - // More values... - }, - } - resp, err := svc.DescribeSecurityGroups(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DescribeSnapshotAttribute() { - svc := ec2.New(nil) - - params := &ec2.DescribeSnapshotAttributeInput{ - Attribute: aws.String("SnapshotAttributeName"), // Required - SnapshotId: aws.String("String"), // Required - DryRun: aws.Bool(true), - } - resp, err := svc.DescribeSnapshotAttribute(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DescribeSnapshots() { - svc := ec2.New(nil) - - params := &ec2.DescribeSnapshotsInput{ - DryRun: aws.Bool(true), - Filters: []*ec2.Filter{ - { // Required - Name: aws.String("String"), - Values: []*string{ - aws.String("String"), // Required - // More values... - }, - }, - // More values... - }, - MaxResults: aws.Int64(1), - NextToken: aws.String("String"), - OwnerIds: []*string{ - aws.String("String"), // Required - // More values... - }, - RestorableByUserIds: []*string{ - aws.String("String"), // Required - // More values... - }, - SnapshotIds: []*string{ - aws.String("String"), // Required - // More values... - }, - } - resp, err := svc.DescribeSnapshots(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DescribeSpotDatafeedSubscription() { - svc := ec2.New(nil) - - params := &ec2.DescribeSpotDatafeedSubscriptionInput{ - DryRun: aws.Bool(true), - } - resp, err := svc.DescribeSpotDatafeedSubscription(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DescribeSpotFleetInstances() { - svc := ec2.New(nil) - - params := &ec2.DescribeSpotFleetInstancesInput{ - SpotFleetRequestId: aws.String("String"), // Required - DryRun: aws.Bool(true), - MaxResults: aws.Int64(1), - NextToken: aws.String("String"), - } - resp, err := svc.DescribeSpotFleetInstances(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DescribeSpotFleetRequestHistory() { - svc := ec2.New(nil) - - params := &ec2.DescribeSpotFleetRequestHistoryInput{ - SpotFleetRequestId: aws.String("String"), // Required - StartTime: aws.Time(time.Now()), // Required - DryRun: aws.Bool(true), - EventType: aws.String("EventType"), - MaxResults: aws.Int64(1), - NextToken: aws.String("String"), - } - resp, err := svc.DescribeSpotFleetRequestHistory(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DescribeSpotFleetRequests() { - svc := ec2.New(nil) - - params := &ec2.DescribeSpotFleetRequestsInput{ - DryRun: aws.Bool(true), - MaxResults: aws.Int64(1), - NextToken: aws.String("String"), - SpotFleetRequestIds: []*string{ - aws.String("String"), // Required - // More values... - }, - } - resp, err := svc.DescribeSpotFleetRequests(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DescribeSpotInstanceRequests() { - svc := ec2.New(nil) - - params := &ec2.DescribeSpotInstanceRequestsInput{ - DryRun: aws.Bool(true), - Filters: []*ec2.Filter{ - { // Required - Name: aws.String("String"), - Values: []*string{ - aws.String("String"), // Required - // More values... - }, - }, - // More values... - }, - SpotInstanceRequestIds: []*string{ - aws.String("String"), // Required - // More values... - }, - } - resp, err := svc.DescribeSpotInstanceRequests(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DescribeSpotPriceHistory() { - svc := ec2.New(nil) - - params := &ec2.DescribeSpotPriceHistoryInput{ - AvailabilityZone: aws.String("String"), - DryRun: aws.Bool(true), - EndTime: aws.Time(time.Now()), - Filters: []*ec2.Filter{ - { // Required - Name: aws.String("String"), - Values: []*string{ - aws.String("String"), // Required - // More values... - }, - }, - // More values... - }, - InstanceTypes: []*string{ - aws.String("InstanceType"), // Required - // More values... - }, - MaxResults: aws.Int64(1), - NextToken: aws.String("String"), - ProductDescriptions: []*string{ - aws.String("String"), // Required - // More values... - }, - StartTime: aws.Time(time.Now()), - } - resp, err := svc.DescribeSpotPriceHistory(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DescribeSubnets() { - svc := ec2.New(nil) - - params := &ec2.DescribeSubnetsInput{ - DryRun: aws.Bool(true), - Filters: []*ec2.Filter{ - { // Required - Name: aws.String("String"), - Values: []*string{ - aws.String("String"), // Required - // More values... - }, - }, - // More values... - }, - SubnetIds: []*string{ - aws.String("String"), // Required - // More values... - }, - } - resp, err := svc.DescribeSubnets(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DescribeTags() { - svc := ec2.New(nil) - - params := &ec2.DescribeTagsInput{ - DryRun: aws.Bool(true), - Filters: []*ec2.Filter{ - { // Required - Name: aws.String("String"), - Values: []*string{ - aws.String("String"), // Required - // More values... - }, - }, - // More values... - }, - MaxResults: aws.Int64(1), - NextToken: aws.String("String"), - } - resp, err := svc.DescribeTags(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DescribeVolumeAttribute() { - svc := ec2.New(nil) - - params := &ec2.DescribeVolumeAttributeInput{ - VolumeId: aws.String("String"), // Required - Attribute: aws.String("VolumeAttributeName"), - DryRun: aws.Bool(true), - } - resp, err := svc.DescribeVolumeAttribute(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DescribeVolumeStatus() { - svc := ec2.New(nil) - - params := &ec2.DescribeVolumeStatusInput{ - DryRun: aws.Bool(true), - Filters: []*ec2.Filter{ - { // Required - Name: aws.String("String"), - Values: []*string{ - aws.String("String"), // Required - // More values... - }, - }, - // More values... - }, - MaxResults: aws.Int64(1), - NextToken: aws.String("String"), - VolumeIds: []*string{ - aws.String("String"), // Required - // More values... - }, - } - resp, err := svc.DescribeVolumeStatus(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DescribeVolumes() { - svc := ec2.New(nil) - - params := &ec2.DescribeVolumesInput{ - DryRun: aws.Bool(true), - Filters: []*ec2.Filter{ - { // Required - Name: aws.String("String"), - Values: []*string{ - aws.String("String"), // Required - // More values... - }, - }, - // More values... - }, - MaxResults: aws.Int64(1), - NextToken: aws.String("String"), - VolumeIds: []*string{ - aws.String("String"), // Required - // More values... - }, - } - resp, err := svc.DescribeVolumes(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DescribeVpcAttribute() { - svc := ec2.New(nil) - - params := &ec2.DescribeVpcAttributeInput{ - VpcId: aws.String("String"), // Required - Attribute: aws.String("VpcAttributeName"), - DryRun: aws.Bool(true), - } - resp, err := svc.DescribeVpcAttribute(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DescribeVpcClassicLink() { - svc := ec2.New(nil) - - params := &ec2.DescribeVpcClassicLinkInput{ - DryRun: aws.Bool(true), - Filters: []*ec2.Filter{ - { // Required - Name: aws.String("String"), - Values: []*string{ - aws.String("String"), // Required - // More values... - }, - }, - // More values... - }, - VpcIds: []*string{ - aws.String("String"), // Required - // More values... - }, - } - resp, err := svc.DescribeVpcClassicLink(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DescribeVpcEndpointServices() { - svc := ec2.New(nil) - - params := &ec2.DescribeVpcEndpointServicesInput{ - DryRun: aws.Bool(true), - MaxResults: aws.Int64(1), - NextToken: aws.String("String"), - } - resp, err := svc.DescribeVpcEndpointServices(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DescribeVpcEndpoints() { - svc := ec2.New(nil) - - params := &ec2.DescribeVpcEndpointsInput{ - DryRun: aws.Bool(true), - Filters: []*ec2.Filter{ - { // Required - Name: aws.String("String"), - Values: []*string{ - aws.String("String"), // Required - // More values... - }, - }, - // More values... - }, - MaxResults: aws.Int64(1), - NextToken: aws.String("String"), - VpcEndpointIds: []*string{ - aws.String("String"), // Required - // More values... - }, - } - resp, err := svc.DescribeVpcEndpoints(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DescribeVpcPeeringConnections() { - svc := ec2.New(nil) - - params := &ec2.DescribeVpcPeeringConnectionsInput{ - DryRun: aws.Bool(true), - Filters: []*ec2.Filter{ - { // Required - Name: aws.String("String"), - Values: []*string{ - aws.String("String"), // Required - // More values... - }, - }, - // More values... - }, - VpcPeeringConnectionIds: []*string{ - aws.String("String"), // Required - // More values... - }, - } - resp, err := svc.DescribeVpcPeeringConnections(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DescribeVpcs() { - svc := ec2.New(nil) - - params := &ec2.DescribeVpcsInput{ - DryRun: aws.Bool(true), - Filters: []*ec2.Filter{ - { // Required - Name: aws.String("String"), - Values: []*string{ - aws.String("String"), // Required - // More values... - }, - }, - // More values... - }, - VpcIds: []*string{ - aws.String("String"), // Required - // More values... - }, - } - resp, err := svc.DescribeVpcs(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DescribeVpnConnections() { - svc := ec2.New(nil) - - params := &ec2.DescribeVpnConnectionsInput{ - DryRun: aws.Bool(true), - Filters: []*ec2.Filter{ - { // Required - Name: aws.String("String"), - Values: []*string{ - aws.String("String"), // Required - // More values... - }, - }, - // More values... - }, - VpnConnectionIds: []*string{ - aws.String("String"), // Required - // More values... - }, - } - resp, err := svc.DescribeVpnConnections(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DescribeVpnGateways() { - svc := ec2.New(nil) - - params := &ec2.DescribeVpnGatewaysInput{ - DryRun: aws.Bool(true), - Filters: []*ec2.Filter{ - { // Required - Name: aws.String("String"), - Values: []*string{ - aws.String("String"), // Required - // More values... - }, - }, - // More values... - }, - VpnGatewayIds: []*string{ - aws.String("String"), // Required - // More values... - }, - } - resp, err := svc.DescribeVpnGateways(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DetachClassicLinkVpc() { - svc := ec2.New(nil) - - params := &ec2.DetachClassicLinkVpcInput{ - InstanceId: aws.String("String"), // Required - VpcId: aws.String("String"), // Required - DryRun: aws.Bool(true), - } - resp, err := svc.DetachClassicLinkVpc(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DetachInternetGateway() { - svc := ec2.New(nil) - - params := &ec2.DetachInternetGatewayInput{ - InternetGatewayId: aws.String("String"), // Required - VpcId: aws.String("String"), // Required - DryRun: aws.Bool(true), - } - resp, err := svc.DetachInternetGateway(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DetachNetworkInterface() { - svc := ec2.New(nil) - - params := &ec2.DetachNetworkInterfaceInput{ - AttachmentId: aws.String("String"), // Required - DryRun: aws.Bool(true), - Force: aws.Bool(true), - } - resp, err := svc.DetachNetworkInterface(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DetachVolume() { - svc := ec2.New(nil) - - params := &ec2.DetachVolumeInput{ - VolumeId: aws.String("String"), // Required - Device: aws.String("String"), - DryRun: aws.Bool(true), - Force: aws.Bool(true), - InstanceId: aws.String("String"), - } - resp, err := svc.DetachVolume(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DetachVpnGateway() { - svc := ec2.New(nil) - - params := &ec2.DetachVpnGatewayInput{ - VpcId: aws.String("String"), // Required - VpnGatewayId: aws.String("String"), // Required - DryRun: aws.Bool(true), - } - resp, err := svc.DetachVpnGateway(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DisableVgwRoutePropagation() { - svc := ec2.New(nil) - - params := &ec2.DisableVgwRoutePropagationInput{ - GatewayId: aws.String("String"), // Required - RouteTableId: aws.String("String"), // Required - } - resp, err := svc.DisableVgwRoutePropagation(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DisableVpcClassicLink() { - svc := ec2.New(nil) - - params := &ec2.DisableVpcClassicLinkInput{ - VpcId: aws.String("String"), // Required - DryRun: aws.Bool(true), - } - resp, err := svc.DisableVpcClassicLink(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DisassociateAddress() { - svc := ec2.New(nil) - - params := &ec2.DisassociateAddressInput{ - AssociationId: aws.String("String"), - DryRun: aws.Bool(true), - PublicIp: aws.String("String"), - } - resp, err := svc.DisassociateAddress(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_DisassociateRouteTable() { - svc := ec2.New(nil) - - params := &ec2.DisassociateRouteTableInput{ - AssociationId: aws.String("String"), // Required - DryRun: aws.Bool(true), - } - resp, err := svc.DisassociateRouteTable(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_EnableVgwRoutePropagation() { - svc := ec2.New(nil) - - params := &ec2.EnableVgwRoutePropagationInput{ - GatewayId: aws.String("String"), // Required - RouteTableId: aws.String("String"), // Required - } - resp, err := svc.EnableVgwRoutePropagation(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_EnableVolumeIO() { - svc := ec2.New(nil) - - params := &ec2.EnableVolumeIOInput{ - VolumeId: aws.String("String"), // Required - DryRun: aws.Bool(true), - } - resp, err := svc.EnableVolumeIO(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_EnableVpcClassicLink() { - svc := ec2.New(nil) - - params := &ec2.EnableVpcClassicLinkInput{ - VpcId: aws.String("String"), // Required - DryRun: aws.Bool(true), - } - resp, err := svc.EnableVpcClassicLink(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_GetConsoleOutput() { - svc := ec2.New(nil) - - params := &ec2.GetConsoleOutputInput{ - InstanceId: aws.String("String"), // Required - DryRun: aws.Bool(true), - } - resp, err := svc.GetConsoleOutput(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_GetPasswordData() { - svc := ec2.New(nil) - - params := &ec2.GetPasswordDataInput{ - InstanceId: aws.String("String"), // Required - DryRun: aws.Bool(true), - } - resp, err := svc.GetPasswordData(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_ImportImage() { - svc := ec2.New(nil) - - params := &ec2.ImportImageInput{ - Architecture: aws.String("String"), - ClientData: &ec2.ClientData{ - Comment: aws.String("String"), - UploadEnd: aws.Time(time.Now()), - UploadSize: aws.Float64(1.0), - UploadStart: aws.Time(time.Now()), - }, - ClientToken: aws.String("String"), - Description: aws.String("String"), - DiskContainers: []*ec2.ImageDiskContainer{ - { // Required - Description: aws.String("String"), - DeviceName: aws.String("String"), - Format: aws.String("String"), - SnapshotId: aws.String("String"), - Url: aws.String("String"), - UserBucket: &ec2.UserBucket{ - S3Bucket: aws.String("String"), - S3Key: aws.String("String"), - }, - }, - // More values... - }, - DryRun: aws.Bool(true), - Hypervisor: aws.String("String"), - LicenseType: aws.String("String"), - Platform: aws.String("String"), - RoleName: aws.String("String"), - } - resp, err := svc.ImportImage(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_ImportInstance() { - svc := ec2.New(nil) - - params := &ec2.ImportInstanceInput{ - Platform: aws.String("PlatformValues"), // Required - Description: aws.String("String"), - DiskImages: []*ec2.DiskImage{ - { // Required - Description: aws.String("String"), - Image: &ec2.DiskImageDetail{ - Bytes: aws.Int64(1), // Required - Format: aws.String("DiskImageFormat"), // Required - ImportManifestUrl: aws.String("String"), // Required - }, - Volume: &ec2.VolumeDetail{ - Size: aws.Int64(1), // Required - }, - }, - // More values... - }, - DryRun: aws.Bool(true), - LaunchSpecification: &ec2.ImportInstanceLaunchSpecification{ - AdditionalInfo: aws.String("String"), - Architecture: aws.String("ArchitectureValues"), - GroupIds: []*string{ - aws.String("String"), // Required - // More values... - }, - GroupNames: []*string{ - aws.String("String"), // Required - // More values... - }, - InstanceInitiatedShutdownBehavior: aws.String("ShutdownBehavior"), - InstanceType: aws.String("InstanceType"), - Monitoring: aws.Bool(true), - Placement: &ec2.Placement{ - AvailabilityZone: aws.String("String"), - GroupName: aws.String("String"), - Tenancy: aws.String("Tenancy"), - }, - PrivateIpAddress: aws.String("String"), - SubnetId: aws.String("String"), - UserData: &ec2.UserData{ - Data: aws.String("String"), - }, - }, - } - resp, err := svc.ImportInstance(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_ImportKeyPair() { - svc := ec2.New(nil) - - params := &ec2.ImportKeyPairInput{ - KeyName: aws.String("String"), // Required - PublicKeyMaterial: []byte("PAYLOAD"), // Required - DryRun: aws.Bool(true), - } - resp, err := svc.ImportKeyPair(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_ImportSnapshot() { - svc := ec2.New(nil) - - params := &ec2.ImportSnapshotInput{ - ClientData: &ec2.ClientData{ - Comment: aws.String("String"), - UploadEnd: aws.Time(time.Now()), - UploadSize: aws.Float64(1.0), - UploadStart: aws.Time(time.Now()), - }, - ClientToken: aws.String("String"), - Description: aws.String("String"), - DiskContainer: &ec2.SnapshotDiskContainer{ - Description: aws.String("String"), - Format: aws.String("String"), - Url: aws.String("String"), - UserBucket: &ec2.UserBucket{ - S3Bucket: aws.String("String"), - S3Key: aws.String("String"), - }, - }, - DryRun: aws.Bool(true), - RoleName: aws.String("String"), - } - resp, err := svc.ImportSnapshot(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_ImportVolume() { - svc := ec2.New(nil) - - params := &ec2.ImportVolumeInput{ - AvailabilityZone: aws.String("String"), // Required - Image: &ec2.DiskImageDetail{ // Required - Bytes: aws.Int64(1), // Required - Format: aws.String("DiskImageFormat"), // Required - ImportManifestUrl: aws.String("String"), // Required - }, - Volume: &ec2.VolumeDetail{ // Required - Size: aws.Int64(1), // Required - }, - Description: aws.String("String"), - DryRun: aws.Bool(true), - } - resp, err := svc.ImportVolume(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_ModifyImageAttribute() { - svc := ec2.New(nil) - - params := &ec2.ModifyImageAttributeInput{ - ImageId: aws.String("String"), // Required - Attribute: aws.String("String"), - Description: &ec2.AttributeValue{ - Value: aws.String("String"), - }, - DryRun: aws.Bool(true), - LaunchPermission: &ec2.LaunchPermissionModifications{ - Add: []*ec2.LaunchPermission{ - { // Required - Group: aws.String("PermissionGroup"), - UserId: aws.String("String"), - }, - // More values... - }, - Remove: []*ec2.LaunchPermission{ - { // Required - Group: aws.String("PermissionGroup"), - UserId: aws.String("String"), - }, - // More values... - }, - }, - OperationType: aws.String("String"), - ProductCodes: []*string{ - aws.String("String"), // Required - // More values... - }, - UserGroups: []*string{ - aws.String("String"), // Required - // More values... - }, - UserIds: []*string{ - aws.String("String"), // Required - // More values... - }, - Value: aws.String("String"), - } - resp, err := svc.ModifyImageAttribute(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_ModifyInstanceAttribute() { - svc := ec2.New(nil) - - params := &ec2.ModifyInstanceAttributeInput{ - InstanceId: aws.String("String"), // Required - Attribute: aws.String("InstanceAttributeName"), - BlockDeviceMappings: []*ec2.InstanceBlockDeviceMappingSpecification{ - { // Required - DeviceName: aws.String("String"), - Ebs: &ec2.EbsInstanceBlockDeviceSpecification{ - DeleteOnTermination: aws.Bool(true), - VolumeId: aws.String("String"), - }, - NoDevice: aws.String("String"), - VirtualName: aws.String("String"), - }, - // More values... - }, - DisableApiTermination: &ec2.AttributeBooleanValue{ - Value: aws.Bool(true), - }, - DryRun: aws.Bool(true), - EbsOptimized: &ec2.AttributeBooleanValue{ - Value: aws.Bool(true), - }, - Groups: []*string{ - aws.String("String"), // Required - // More values... - }, - InstanceInitiatedShutdownBehavior: &ec2.AttributeValue{ - Value: aws.String("String"), - }, - InstanceType: &ec2.AttributeValue{ - Value: aws.String("String"), - }, - Kernel: &ec2.AttributeValue{ - Value: aws.String("String"), - }, - Ramdisk: &ec2.AttributeValue{ - Value: aws.String("String"), - }, - SourceDestCheck: &ec2.AttributeBooleanValue{ - Value: aws.Bool(true), - }, - SriovNetSupport: &ec2.AttributeValue{ - Value: aws.String("String"), - }, - UserData: &ec2.BlobAttributeValue{ - Value: []byte("PAYLOAD"), - }, - Value: aws.String("String"), - } - resp, err := svc.ModifyInstanceAttribute(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_ModifyNetworkInterfaceAttribute() { - svc := ec2.New(nil) - - params := &ec2.ModifyNetworkInterfaceAttributeInput{ - NetworkInterfaceId: aws.String("String"), // Required - Attachment: &ec2.NetworkInterfaceAttachmentChanges{ - AttachmentId: aws.String("String"), - DeleteOnTermination: aws.Bool(true), - }, - Description: &ec2.AttributeValue{ - Value: aws.String("String"), - }, - DryRun: aws.Bool(true), - Groups: []*string{ - aws.String("String"), // Required - // More values... - }, - SourceDestCheck: &ec2.AttributeBooleanValue{ - Value: aws.Bool(true), - }, - } - resp, err := svc.ModifyNetworkInterfaceAttribute(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_ModifyReservedInstances() { - svc := ec2.New(nil) - - params := &ec2.ModifyReservedInstancesInput{ - ReservedInstancesIds: []*string{ // Required - aws.String("String"), // Required - // More values... - }, - TargetConfigurations: []*ec2.ReservedInstancesConfiguration{ // Required - { // Required - AvailabilityZone: aws.String("String"), - InstanceCount: aws.Int64(1), - InstanceType: aws.String("InstanceType"), - Platform: aws.String("String"), - }, - // More values... - }, - ClientToken: aws.String("String"), - } - resp, err := svc.ModifyReservedInstances(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_ModifySnapshotAttribute() { - svc := ec2.New(nil) - - params := &ec2.ModifySnapshotAttributeInput{ - SnapshotId: aws.String("String"), // Required - Attribute: aws.String("SnapshotAttributeName"), - CreateVolumePermission: &ec2.CreateVolumePermissionModifications{ - Add: []*ec2.CreateVolumePermission{ - { // Required - Group: aws.String("PermissionGroup"), - UserId: aws.String("String"), - }, - // More values... - }, - Remove: []*ec2.CreateVolumePermission{ - { // Required - Group: aws.String("PermissionGroup"), - UserId: aws.String("String"), - }, - // More values... - }, - }, - DryRun: aws.Bool(true), - GroupNames: []*string{ - aws.String("String"), // Required - // More values... - }, - OperationType: aws.String("String"), - UserIds: []*string{ - aws.String("String"), // Required - // More values... - }, - } - resp, err := svc.ModifySnapshotAttribute(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_ModifySubnetAttribute() { - svc := ec2.New(nil) - - params := &ec2.ModifySubnetAttributeInput{ - SubnetId: aws.String("String"), // Required - MapPublicIpOnLaunch: &ec2.AttributeBooleanValue{ - Value: aws.Bool(true), - }, - } - resp, err := svc.ModifySubnetAttribute(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_ModifyVolumeAttribute() { - svc := ec2.New(nil) - - params := &ec2.ModifyVolumeAttributeInput{ - VolumeId: aws.String("String"), // Required - AutoEnableIO: &ec2.AttributeBooleanValue{ - Value: aws.Bool(true), - }, - DryRun: aws.Bool(true), - } - resp, err := svc.ModifyVolumeAttribute(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_ModifyVpcAttribute() { - svc := ec2.New(nil) - - params := &ec2.ModifyVpcAttributeInput{ - VpcId: aws.String("String"), // Required - EnableDnsHostnames: &ec2.AttributeBooleanValue{ - Value: aws.Bool(true), - }, - EnableDnsSupport: &ec2.AttributeBooleanValue{ - Value: aws.Bool(true), - }, - } - resp, err := svc.ModifyVpcAttribute(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_ModifyVpcEndpoint() { - svc := ec2.New(nil) - - params := &ec2.ModifyVpcEndpointInput{ - VpcEndpointId: aws.String("String"), // Required - AddRouteTableIds: []*string{ - aws.String("String"), // Required - // More values... - }, - DryRun: aws.Bool(true), - PolicyDocument: aws.String("String"), - RemoveRouteTableIds: []*string{ - aws.String("String"), // Required - // More values... - }, - ResetPolicy: aws.Bool(true), - } - resp, err := svc.ModifyVpcEndpoint(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_MonitorInstances() { - svc := ec2.New(nil) - - params := &ec2.MonitorInstancesInput{ - InstanceIds: []*string{ // Required - aws.String("String"), // Required - // More values... - }, - DryRun: aws.Bool(true), - } - resp, err := svc.MonitorInstances(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_MoveAddressToVpc() { - svc := ec2.New(nil) - - params := &ec2.MoveAddressToVpcInput{ - PublicIp: aws.String("String"), // Required - DryRun: aws.Bool(true), - } - resp, err := svc.MoveAddressToVpc(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_PurchaseReservedInstancesOffering() { - svc := ec2.New(nil) - - params := &ec2.PurchaseReservedInstancesOfferingInput{ - InstanceCount: aws.Int64(1), // Required - ReservedInstancesOfferingId: aws.String("String"), // Required - DryRun: aws.Bool(true), - LimitPrice: &ec2.ReservedInstanceLimitPrice{ - Amount: aws.Float64(1.0), - CurrencyCode: aws.String("CurrencyCodeValues"), - }, - } - resp, err := svc.PurchaseReservedInstancesOffering(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_RebootInstances() { - svc := ec2.New(nil) - - params := &ec2.RebootInstancesInput{ - InstanceIds: []*string{ // Required - aws.String("String"), // Required - // More values... - }, - DryRun: aws.Bool(true), - } - resp, err := svc.RebootInstances(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_RegisterImage() { - svc := ec2.New(nil) - - params := &ec2.RegisterImageInput{ - Name: aws.String("String"), // Required - Architecture: aws.String("ArchitectureValues"), - BlockDeviceMappings: []*ec2.BlockDeviceMapping{ - { // Required - DeviceName: aws.String("String"), - Ebs: &ec2.EbsBlockDevice{ - DeleteOnTermination: aws.Bool(true), - Encrypted: aws.Bool(true), - Iops: aws.Int64(1), - SnapshotId: aws.String("String"), - VolumeSize: aws.Int64(1), - VolumeType: aws.String("VolumeType"), - }, - NoDevice: aws.String("String"), - VirtualName: aws.String("String"), - }, - // More values... - }, - Description: aws.String("String"), - DryRun: aws.Bool(true), - ImageLocation: aws.String("String"), - KernelId: aws.String("String"), - RamdiskId: aws.String("String"), - RootDeviceName: aws.String("String"), - SriovNetSupport: aws.String("String"), - VirtualizationType: aws.String("String"), - } - resp, err := svc.RegisterImage(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_RejectVpcPeeringConnection() { - svc := ec2.New(nil) - - params := &ec2.RejectVpcPeeringConnectionInput{ - VpcPeeringConnectionId: aws.String("String"), // Required - DryRun: aws.Bool(true), - } - resp, err := svc.RejectVpcPeeringConnection(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_ReleaseAddress() { - svc := ec2.New(nil) - - params := &ec2.ReleaseAddressInput{ - AllocationId: aws.String("String"), - DryRun: aws.Bool(true), - PublicIp: aws.String("String"), - } - resp, err := svc.ReleaseAddress(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_ReplaceNetworkAclAssociation() { - svc := ec2.New(nil) - - params := &ec2.ReplaceNetworkAclAssociationInput{ - AssociationId: aws.String("String"), // Required - NetworkAclId: aws.String("String"), // Required - DryRun: aws.Bool(true), - } - resp, err := svc.ReplaceNetworkAclAssociation(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_ReplaceNetworkAclEntry() { - svc := ec2.New(nil) - - params := &ec2.ReplaceNetworkAclEntryInput{ - CidrBlock: aws.String("String"), // Required - Egress: aws.Bool(true), // Required - NetworkAclId: aws.String("String"), // Required - Protocol: aws.String("String"), // Required - RuleAction: aws.String("RuleAction"), // Required - RuleNumber: aws.Int64(1), // Required - DryRun: aws.Bool(true), - IcmpTypeCode: &ec2.IcmpTypeCode{ - Code: aws.Int64(1), - Type: aws.Int64(1), - }, - PortRange: &ec2.PortRange{ - From: aws.Int64(1), - To: aws.Int64(1), - }, - } - resp, err := svc.ReplaceNetworkAclEntry(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_ReplaceRoute() { - svc := ec2.New(nil) - - params := &ec2.ReplaceRouteInput{ - DestinationCidrBlock: aws.String("String"), // Required - RouteTableId: aws.String("String"), // Required - DryRun: aws.Bool(true), - GatewayId: aws.String("String"), - InstanceId: aws.String("String"), - NetworkInterfaceId: aws.String("String"), - VpcPeeringConnectionId: aws.String("String"), - } - resp, err := svc.ReplaceRoute(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_ReplaceRouteTableAssociation() { - svc := ec2.New(nil) - - params := &ec2.ReplaceRouteTableAssociationInput{ - AssociationId: aws.String("String"), // Required - RouteTableId: aws.String("String"), // Required - DryRun: aws.Bool(true), - } - resp, err := svc.ReplaceRouteTableAssociation(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_ReportInstanceStatus() { - svc := ec2.New(nil) - - params := &ec2.ReportInstanceStatusInput{ - Instances: []*string{ // Required - aws.String("String"), // Required - // More values... - }, - ReasonCodes: []*string{ // Required - aws.String("ReportInstanceReasonCodes"), // Required - // More values... - }, - Status: aws.String("ReportStatusType"), // Required - Description: aws.String("String"), - DryRun: aws.Bool(true), - EndTime: aws.Time(time.Now()), - StartTime: aws.Time(time.Now()), - } - resp, err := svc.ReportInstanceStatus(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_RequestSpotFleet() { - svc := ec2.New(nil) - - params := &ec2.RequestSpotFleetInput{ - SpotFleetRequestConfig: &ec2.SpotFleetRequestConfigData{ // Required - IamFleetRole: aws.String("String"), // Required - LaunchSpecifications: []*ec2.SpotFleetLaunchSpecification{ // Required - { // Required - AddressingType: aws.String("String"), - BlockDeviceMappings: []*ec2.BlockDeviceMapping{ - { // Required - DeviceName: aws.String("String"), - Ebs: &ec2.EbsBlockDevice{ - DeleteOnTermination: aws.Bool(true), - Encrypted: aws.Bool(true), - Iops: aws.Int64(1), - SnapshotId: aws.String("String"), - VolumeSize: aws.Int64(1), - VolumeType: aws.String("VolumeType"), - }, - NoDevice: aws.String("String"), - VirtualName: aws.String("String"), - }, - // More values... - }, - EbsOptimized: aws.Bool(true), - IamInstanceProfile: &ec2.IamInstanceProfileSpecification{ - Arn: aws.String("String"), - Name: aws.String("String"), - }, - ImageId: aws.String("String"), - InstanceType: aws.String("InstanceType"), - KernelId: aws.String("String"), - KeyName: aws.String("String"), - Monitoring: &ec2.SpotFleetMonitoring{ - Enabled: aws.Bool(true), - }, - NetworkInterfaces: []*ec2.InstanceNetworkInterfaceSpecification{ - { // Required - AssociatePublicIpAddress: aws.Bool(true), - DeleteOnTermination: aws.Bool(true), - Description: aws.String("String"), - DeviceIndex: aws.Int64(1), - Groups: []*string{ - aws.String("String"), // Required - // More values... - }, - NetworkInterfaceId: aws.String("String"), - PrivateIpAddress: aws.String("String"), - PrivateIpAddresses: []*ec2.PrivateIpAddressSpecification{ - { // Required - PrivateIpAddress: aws.String("String"), // Required - Primary: aws.Bool(true), - }, - // More values... - }, - SecondaryPrivateIpAddressCount: aws.Int64(1), - SubnetId: aws.String("String"), - }, - // More values... - }, - Placement: &ec2.SpotPlacement{ - AvailabilityZone: aws.String("String"), - GroupName: aws.String("String"), - }, - RamdiskId: aws.String("String"), - SecurityGroups: []*ec2.GroupIdentifier{ - { // Required - GroupId: aws.String("String"), - GroupName: aws.String("String"), - }, - // More values... - }, - SubnetId: aws.String("String"), - UserData: aws.String("String"), - }, - // More values... - }, - SpotPrice: aws.String("String"), // Required - TargetCapacity: aws.Int64(1), // Required - ClientToken: aws.String("String"), - TerminateInstancesWithExpiration: aws.Bool(true), - ValidFrom: aws.Time(time.Now()), - ValidUntil: aws.Time(time.Now()), - }, - DryRun: aws.Bool(true), - } - resp, err := svc.RequestSpotFleet(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_RequestSpotInstances() { - svc := ec2.New(nil) - - params := &ec2.RequestSpotInstancesInput{ - SpotPrice: aws.String("String"), // Required - AvailabilityZoneGroup: aws.String("String"), - ClientToken: aws.String("String"), - DryRun: aws.Bool(true), - InstanceCount: aws.Int64(1), - LaunchGroup: aws.String("String"), - LaunchSpecification: &ec2.RequestSpotLaunchSpecification{ - AddressingType: aws.String("String"), - BlockDeviceMappings: []*ec2.BlockDeviceMapping{ - { // Required - DeviceName: aws.String("String"), - Ebs: &ec2.EbsBlockDevice{ - DeleteOnTermination: aws.Bool(true), - Encrypted: aws.Bool(true), - Iops: aws.Int64(1), - SnapshotId: aws.String("String"), - VolumeSize: aws.Int64(1), - VolumeType: aws.String("VolumeType"), - }, - NoDevice: aws.String("String"), - VirtualName: aws.String("String"), - }, - // More values... - }, - EbsOptimized: aws.Bool(true), - IamInstanceProfile: &ec2.IamInstanceProfileSpecification{ - Arn: aws.String("String"), - Name: aws.String("String"), - }, - ImageId: aws.String("String"), - InstanceType: aws.String("InstanceType"), - KernelId: aws.String("String"), - KeyName: aws.String("String"), - Monitoring: &ec2.RunInstancesMonitoringEnabled{ - Enabled: aws.Bool(true), // Required - }, - NetworkInterfaces: []*ec2.InstanceNetworkInterfaceSpecification{ - { // Required - AssociatePublicIpAddress: aws.Bool(true), - DeleteOnTermination: aws.Bool(true), - Description: aws.String("String"), - DeviceIndex: aws.Int64(1), - Groups: []*string{ - aws.String("String"), // Required - // More values... - }, - NetworkInterfaceId: aws.String("String"), - PrivateIpAddress: aws.String("String"), - PrivateIpAddresses: []*ec2.PrivateIpAddressSpecification{ - { // Required - PrivateIpAddress: aws.String("String"), // Required - Primary: aws.Bool(true), - }, - // More values... - }, - SecondaryPrivateIpAddressCount: aws.Int64(1), - SubnetId: aws.String("String"), - }, - // More values... - }, - Placement: &ec2.SpotPlacement{ - AvailabilityZone: aws.String("String"), - GroupName: aws.String("String"), - }, - RamdiskId: aws.String("String"), - SecurityGroupIds: []*string{ - aws.String("String"), // Required - // More values... - }, - SecurityGroups: []*string{ - aws.String("String"), // Required - // More values... - }, - SubnetId: aws.String("String"), - UserData: aws.String("String"), - }, - Type: aws.String("SpotInstanceType"), - ValidFrom: aws.Time(time.Now()), - ValidUntil: aws.Time(time.Now()), - } - resp, err := svc.RequestSpotInstances(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_ResetImageAttribute() { - svc := ec2.New(nil) - - params := &ec2.ResetImageAttributeInput{ - Attribute: aws.String("ResetImageAttributeName"), // Required - ImageId: aws.String("String"), // Required - DryRun: aws.Bool(true), - } - resp, err := svc.ResetImageAttribute(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_ResetInstanceAttribute() { - svc := ec2.New(nil) - - params := &ec2.ResetInstanceAttributeInput{ - Attribute: aws.String("InstanceAttributeName"), // Required - InstanceId: aws.String("String"), // Required - DryRun: aws.Bool(true), - } - resp, err := svc.ResetInstanceAttribute(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_ResetNetworkInterfaceAttribute() { - svc := ec2.New(nil) - - params := &ec2.ResetNetworkInterfaceAttributeInput{ - NetworkInterfaceId: aws.String("String"), // Required - DryRun: aws.Bool(true), - SourceDestCheck: aws.String("String"), - } - resp, err := svc.ResetNetworkInterfaceAttribute(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_ResetSnapshotAttribute() { - svc := ec2.New(nil) - - params := &ec2.ResetSnapshotAttributeInput{ - Attribute: aws.String("SnapshotAttributeName"), // Required - SnapshotId: aws.String("String"), // Required - DryRun: aws.Bool(true), - } - resp, err := svc.ResetSnapshotAttribute(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_RestoreAddressToClassic() { - svc := ec2.New(nil) - - params := &ec2.RestoreAddressToClassicInput{ - PublicIp: aws.String("String"), // Required - DryRun: aws.Bool(true), - } - resp, err := svc.RestoreAddressToClassic(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_RevokeSecurityGroupEgress() { - svc := ec2.New(nil) - - params := &ec2.RevokeSecurityGroupEgressInput{ - 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), - } - resp, err := svc.RevokeSecurityGroupEgress(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_RevokeSecurityGroupIngress() { - svc := ec2.New(nil) - - params := &ec2.RevokeSecurityGroupIngressInput{ - CidrIp: aws.String("String"), - DryRun: aws.Bool(true), - FromPort: aws.Int64(1), - GroupId: aws.String("String"), - GroupName: aws.String("String"), - 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), - } - resp, err := svc.RevokeSecurityGroupIngress(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_RunInstances() { - svc := ec2.New(nil) - - params := &ec2.RunInstancesInput{ - ImageId: aws.String("String"), // Required - MaxCount: aws.Int64(1), // Required - MinCount: aws.Int64(1), // Required - AdditionalInfo: aws.String("String"), - BlockDeviceMappings: []*ec2.BlockDeviceMapping{ - { // Required - DeviceName: aws.String("String"), - Ebs: &ec2.EbsBlockDevice{ - DeleteOnTermination: aws.Bool(true), - Encrypted: aws.Bool(true), - Iops: aws.Int64(1), - SnapshotId: aws.String("String"), - VolumeSize: aws.Int64(1), - VolumeType: aws.String("VolumeType"), - }, - NoDevice: aws.String("String"), - VirtualName: aws.String("String"), - }, - // More values... - }, - ClientToken: aws.String("String"), - DisableApiTermination: aws.Bool(true), - DryRun: aws.Bool(true), - EbsOptimized: aws.Bool(true), - IamInstanceProfile: &ec2.IamInstanceProfileSpecification{ - Arn: aws.String("String"), - Name: aws.String("String"), - }, - InstanceInitiatedShutdownBehavior: aws.String("ShutdownBehavior"), - InstanceType: aws.String("InstanceType"), - KernelId: aws.String("String"), - KeyName: aws.String("String"), - Monitoring: &ec2.RunInstancesMonitoringEnabled{ - Enabled: aws.Bool(true), // Required - }, - NetworkInterfaces: []*ec2.InstanceNetworkInterfaceSpecification{ - { // Required - AssociatePublicIpAddress: aws.Bool(true), - DeleteOnTermination: aws.Bool(true), - Description: aws.String("String"), - DeviceIndex: aws.Int64(1), - Groups: []*string{ - aws.String("String"), // Required - // More values... - }, - NetworkInterfaceId: aws.String("String"), - PrivateIpAddress: aws.String("String"), - PrivateIpAddresses: []*ec2.PrivateIpAddressSpecification{ - { // Required - PrivateIpAddress: aws.String("String"), // Required - Primary: aws.Bool(true), - }, - // More values... - }, - SecondaryPrivateIpAddressCount: aws.Int64(1), - SubnetId: aws.String("String"), - }, - // More values... - }, - Placement: &ec2.Placement{ - AvailabilityZone: aws.String("String"), - GroupName: aws.String("String"), - Tenancy: aws.String("Tenancy"), - }, - PrivateIpAddress: aws.String("String"), - RamdiskId: aws.String("String"), - SecurityGroupIds: []*string{ - aws.String("String"), // Required - // More values... - }, - SecurityGroups: []*string{ - aws.String("String"), // Required - // More values... - }, - SubnetId: aws.String("String"), - UserData: aws.String("String"), - } - resp, err := svc.RunInstances(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_StartInstances() { - svc := ec2.New(nil) - - params := &ec2.StartInstancesInput{ - InstanceIds: []*string{ // Required - aws.String("String"), // Required - // More values... - }, - AdditionalInfo: aws.String("String"), - DryRun: aws.Bool(true), - } - resp, err := svc.StartInstances(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_StopInstances() { - svc := ec2.New(nil) - - params := &ec2.StopInstancesInput{ - InstanceIds: []*string{ // Required - aws.String("String"), // Required - // More values... - }, - DryRun: aws.Bool(true), - Force: aws.Bool(true), - } - resp, err := svc.StopInstances(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_TerminateInstances() { - svc := ec2.New(nil) - - params := &ec2.TerminateInstancesInput{ - InstanceIds: []*string{ // Required - aws.String("String"), // Required - // More values... - }, - DryRun: aws.Bool(true), - } - resp, err := svc.TerminateInstances(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_UnassignPrivateIpAddresses() { - svc := ec2.New(nil) - - params := &ec2.UnassignPrivateIpAddressesInput{ - NetworkInterfaceId: aws.String("String"), // Required - PrivateIpAddresses: []*string{ // Required - aws.String("String"), // Required - // More values... - }, - } - resp, err := svc.UnassignPrivateIpAddresses(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleEC2_UnmonitorInstances() { - svc := ec2.New(nil) - - params := &ec2.UnmonitorInstancesInput{ - InstanceIds: []*string{ // Required - aws.String("String"), // Required - // More values... - }, - DryRun: aws.Bool(true), - } - resp, err := svc.UnmonitorInstances(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/ec2/service.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/ec2/service.go index 8078ad665..102c8fe02 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/ec2/service.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/ec2/service.go @@ -5,7 +5,9 @@ package ec2 import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/defaults" + "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/aws/service" + "github.com/aws/aws-sdk-go/aws/service/serviceinfo" "github.com/aws/aws-sdk-go/internal/protocol/ec2query" "github.com/aws/aws-sdk-go/internal/signer/v4" ) @@ -22,14 +24,16 @@ type EC2 struct { var initService func(*service.Service) // Used for custom request initialization logic -var initRequest func(*service.Request) +var initRequest func(*request.Request) // New returns a new EC2 client. func New(config *aws.Config) *EC2 { service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "ec2", - APIVersion: "2015-04-15", + ServiceInfo: serviceinfo.ServiceInfo{ + Config: defaults.DefaultConfig.Merge(config), + ServiceName: "ec2", + APIVersion: "2015-04-15", + }, } service.Initialize() @@ -50,8 +54,8 @@ func New(config *aws.Config) *EC2 { // newRequest creates a new request for a EC2 operation and runs any // custom request initialization. -func (c *EC2) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) +func (c *EC2) newRequest(op *request.Operation, params, data interface{}) *request.Request { + req := c.NewRequest(op, params, data) // Run custom request initialization if present if initRequest != nil { diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/iam/api.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/iam/api.go index 07ef9b4c2..f46bfb4cd 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/iam/api.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/iam/api.go @@ -7,14 +7,14 @@ import ( "time" "github.com/aws/aws-sdk-go/aws/awsutil" - "github.com/aws/aws-sdk-go/aws/service" + "github.com/aws/aws-sdk-go/aws/request" ) const opAddClientIDToOpenIDConnectProvider = "AddClientIDToOpenIDConnectProvider" // AddClientIDToOpenIDConnectProviderRequest generates a request for the AddClientIDToOpenIDConnectProvider operation. -func (c *IAM) AddClientIDToOpenIDConnectProviderRequest(input *AddClientIDToOpenIDConnectProviderInput) (req *service.Request, output *AddClientIDToOpenIDConnectProviderOutput) { - op := &service.Operation{ +func (c *IAM) AddClientIDToOpenIDConnectProviderRequest(input *AddClientIDToOpenIDConnectProviderInput) (req *request.Request, output *AddClientIDToOpenIDConnectProviderOutput) { + op := &request.Operation{ Name: opAddClientIDToOpenIDConnectProvider, HTTPMethod: "POST", HTTPPath: "/", @@ -44,8 +44,8 @@ func (c *IAM) AddClientIDToOpenIDConnectProvider(input *AddClientIDToOpenIDConne const opAddRoleToInstanceProfile = "AddRoleToInstanceProfile" // AddRoleToInstanceProfileRequest generates a request for the AddRoleToInstanceProfile operation. -func (c *IAM) AddRoleToInstanceProfileRequest(input *AddRoleToInstanceProfileInput) (req *service.Request, output *AddRoleToInstanceProfileOutput) { - op := &service.Operation{ +func (c *IAM) AddRoleToInstanceProfileRequest(input *AddRoleToInstanceProfileInput) (req *request.Request, output *AddRoleToInstanceProfileOutput) { + op := &request.Operation{ Name: opAddRoleToInstanceProfile, HTTPMethod: "POST", HTTPPath: "/", @@ -74,8 +74,8 @@ func (c *IAM) AddRoleToInstanceProfile(input *AddRoleToInstanceProfileInput) (*A const opAddUserToGroup = "AddUserToGroup" // AddUserToGroupRequest generates a request for the AddUserToGroup operation. -func (c *IAM) AddUserToGroupRequest(input *AddUserToGroupInput) (req *service.Request, output *AddUserToGroupOutput) { - op := &service.Operation{ +func (c *IAM) AddUserToGroupRequest(input *AddUserToGroupInput) (req *request.Request, output *AddUserToGroupOutput) { + op := &request.Operation{ Name: opAddUserToGroup, HTTPMethod: "POST", HTTPPath: "/", @@ -101,8 +101,8 @@ func (c *IAM) AddUserToGroup(input *AddUserToGroupInput) (*AddUserToGroupOutput, const opAttachGroupPolicy = "AttachGroupPolicy" // AttachGroupPolicyRequest generates a request for the AttachGroupPolicy operation. -func (c *IAM) AttachGroupPolicyRequest(input *AttachGroupPolicyInput) (req *service.Request, output *AttachGroupPolicyOutput) { - op := &service.Operation{ +func (c *IAM) AttachGroupPolicyRequest(input *AttachGroupPolicyInput) (req *request.Request, output *AttachGroupPolicyOutput) { + op := &request.Operation{ Name: opAttachGroupPolicy, HTTPMethod: "POST", HTTPPath: "/", @@ -125,7 +125,7 @@ func (c *IAM) AttachGroupPolicyRequest(input *AttachGroupPolicyInput) (req *serv // // For more information about policies, refer to Managed Policies and Inline // Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html) -// in the Using IAM guide. +// in the IAM User Guide. func (c *IAM) AttachGroupPolicy(input *AttachGroupPolicyInput) (*AttachGroupPolicyOutput, error) { req, out := c.AttachGroupPolicyRequest(input) err := req.Send() @@ -135,8 +135,8 @@ func (c *IAM) AttachGroupPolicy(input *AttachGroupPolicyInput) (*AttachGroupPoli const opAttachRolePolicy = "AttachRolePolicy" // AttachRolePolicyRequest generates a request for the AttachRolePolicy operation. -func (c *IAM) AttachRolePolicyRequest(input *AttachRolePolicyInput) (req *service.Request, output *AttachRolePolicyOutput) { - op := &service.Operation{ +func (c *IAM) AttachRolePolicyRequest(input *AttachRolePolicyInput) (req *request.Request, output *AttachRolePolicyOutput) { + op := &request.Operation{ Name: opAttachRolePolicy, HTTPMethod: "POST", HTTPPath: "/", @@ -163,7 +163,7 @@ func (c *IAM) AttachRolePolicyRequest(input *AttachRolePolicyInput) (req *servic // Use this API to attach a managed policy to a role. To embed an inline policy // in a role, use PutRolePolicy. For more information about policies, refer // to Managed Policies and Inline Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html) -// in the Using IAM guide. +// in the IAM User Guide. func (c *IAM) AttachRolePolicy(input *AttachRolePolicyInput) (*AttachRolePolicyOutput, error) { req, out := c.AttachRolePolicyRequest(input) err := req.Send() @@ -173,8 +173,8 @@ func (c *IAM) AttachRolePolicy(input *AttachRolePolicyInput) (*AttachRolePolicyO const opAttachUserPolicy = "AttachUserPolicy" // AttachUserPolicyRequest generates a request for the AttachUserPolicy operation. -func (c *IAM) AttachUserPolicyRequest(input *AttachUserPolicyInput) (req *service.Request, output *AttachUserPolicyOutput) { - op := &service.Operation{ +func (c *IAM) AttachUserPolicyRequest(input *AttachUserPolicyInput) (req *request.Request, output *AttachUserPolicyOutput) { + op := &request.Operation{ Name: opAttachUserPolicy, HTTPMethod: "POST", HTTPPath: "/", @@ -197,7 +197,7 @@ func (c *IAM) AttachUserPolicyRequest(input *AttachUserPolicyInput) (req *servic // // For more information about policies, refer to Managed Policies and Inline // Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html) -// in the Using IAM guide. +// in the IAM User Guide. func (c *IAM) AttachUserPolicy(input *AttachUserPolicyInput) (*AttachUserPolicyOutput, error) { req, out := c.AttachUserPolicyRequest(input) err := req.Send() @@ -207,8 +207,8 @@ func (c *IAM) AttachUserPolicy(input *AttachUserPolicyInput) (*AttachUserPolicyO const opChangePassword = "ChangePassword" // ChangePasswordRequest generates a request for the ChangePassword operation. -func (c *IAM) ChangePasswordRequest(input *ChangePasswordInput) (req *service.Request, output *ChangePasswordOutput) { - op := &service.Operation{ +func (c *IAM) ChangePasswordRequest(input *ChangePasswordInput) (req *request.Request, output *ChangePasswordOutput) { + op := &request.Operation{ Name: opChangePassword, HTTPMethod: "POST", HTTPPath: "/", @@ -229,7 +229,7 @@ func (c *IAM) ChangePasswordRequest(input *ChangePasswordInput) (req *service.Re // // To change the password for a different user, see UpdateLoginProfile. For // more information about modifying passwords, see Managing Passwords (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_ManagingLogins.html) -// in the Using IAM guide. +// in the IAM User Guide. func (c *IAM) ChangePassword(input *ChangePasswordInput) (*ChangePasswordOutput, error) { req, out := c.ChangePasswordRequest(input) err := req.Send() @@ -239,8 +239,8 @@ func (c *IAM) ChangePassword(input *ChangePasswordInput) (*ChangePasswordOutput, const opCreateAccessKey = "CreateAccessKey" // CreateAccessKeyRequest generates a request for the CreateAccessKey operation. -func (c *IAM) CreateAccessKeyRequest(input *CreateAccessKeyInput) (req *service.Request, output *CreateAccessKeyOutput) { - op := &service.Operation{ +func (c *IAM) CreateAccessKeyRequest(input *CreateAccessKeyInput) (req *request.Request, output *CreateAccessKeyOutput) { + op := &request.Operation{ Name: opCreateAccessKey, HTTPMethod: "POST", HTTPPath: "/", @@ -266,7 +266,7 @@ func (c *IAM) CreateAccessKeyRequest(input *CreateAccessKeyInput) (req *service. // // For information about limits on the number of keys you can create, see // Limitations on IAM Entities (http://docs.aws.amazon.com/IAM/latest/UserGuide/LimitationsOnEntities.html) -// in the Using IAM guide. +// in the IAM User Guide. // // To ensure the security of your AWS account, the secret access key is accessible // only during key and user creation. You must save the key (for example, in @@ -282,8 +282,8 @@ func (c *IAM) CreateAccessKey(input *CreateAccessKeyInput) (*CreateAccessKeyOutp const opCreateAccountAlias = "CreateAccountAlias" // CreateAccountAliasRequest generates a request for the CreateAccountAlias operation. -func (c *IAM) CreateAccountAliasRequest(input *CreateAccountAliasInput) (req *service.Request, output *CreateAccountAliasOutput) { - op := &service.Operation{ +func (c *IAM) CreateAccountAliasRequest(input *CreateAccountAliasInput) (req *request.Request, output *CreateAccountAliasOutput) { + op := &request.Operation{ Name: opCreateAccountAlias, HTTPMethod: "POST", HTTPPath: "/", @@ -301,7 +301,7 @@ func (c *IAM) CreateAccountAliasRequest(input *CreateAccountAliasInput) (req *se // Creates an alias for your AWS account. For information about using an AWS // account alias, see Using an Alias for Your AWS Account ID (http://docs.aws.amazon.com/IAM/latest/UserGuide/AccountAlias.html) -// in the Using IAM guide. +// in the IAM User Guide. func (c *IAM) CreateAccountAlias(input *CreateAccountAliasInput) (*CreateAccountAliasOutput, error) { req, out := c.CreateAccountAliasRequest(input) err := req.Send() @@ -311,8 +311,8 @@ func (c *IAM) CreateAccountAlias(input *CreateAccountAliasInput) (*CreateAccount const opCreateGroup = "CreateGroup" // CreateGroupRequest generates a request for the CreateGroup operation. -func (c *IAM) CreateGroupRequest(input *CreateGroupInput) (req *service.Request, output *CreateGroupOutput) { - op := &service.Operation{ +func (c *IAM) CreateGroupRequest(input *CreateGroupInput) (req *request.Request, output *CreateGroupOutput) { + op := &request.Operation{ Name: opCreateGroup, HTTPMethod: "POST", HTTPPath: "/", @@ -332,7 +332,7 @@ func (c *IAM) CreateGroupRequest(input *CreateGroupInput) (req *service.Request, // // For information about the number of groups you can create, see Limitations // on IAM Entities (http://docs.aws.amazon.com/IAM/latest/UserGuide/LimitationsOnEntities.html) -// in the Using IAM guide. +// in the IAM User Guide. func (c *IAM) CreateGroup(input *CreateGroupInput) (*CreateGroupOutput, error) { req, out := c.CreateGroupRequest(input) err := req.Send() @@ -342,8 +342,8 @@ func (c *IAM) CreateGroup(input *CreateGroupInput) (*CreateGroupOutput, error) { const opCreateInstanceProfile = "CreateInstanceProfile" // CreateInstanceProfileRequest generates a request for the CreateInstanceProfile operation. -func (c *IAM) CreateInstanceProfileRequest(input *CreateInstanceProfileInput) (req *service.Request, output *CreateInstanceProfileOutput) { - op := &service.Operation{ +func (c *IAM) CreateInstanceProfileRequest(input *CreateInstanceProfileInput) (req *request.Request, output *CreateInstanceProfileOutput) { + op := &request.Operation{ Name: opCreateInstanceProfile, HTTPMethod: "POST", HTTPPath: "/", @@ -364,7 +364,7 @@ func (c *IAM) CreateInstanceProfileRequest(input *CreateInstanceProfileInput) (r // // For information about the number of instance profiles you can create, see // Limitations on IAM Entities (http://docs.aws.amazon.com/IAM/latest/UserGuide/LimitationsOnEntities.html) -// in the Using IAM guide. +// in the IAM User Guide. func (c *IAM) CreateInstanceProfile(input *CreateInstanceProfileInput) (*CreateInstanceProfileOutput, error) { req, out := c.CreateInstanceProfileRequest(input) err := req.Send() @@ -374,8 +374,8 @@ func (c *IAM) CreateInstanceProfile(input *CreateInstanceProfileInput) (*CreateI const opCreateLoginProfile = "CreateLoginProfile" // CreateLoginProfileRequest generates a request for the CreateLoginProfile operation. -func (c *IAM) CreateLoginProfileRequest(input *CreateLoginProfileInput) (req *service.Request, output *CreateLoginProfileOutput) { - op := &service.Operation{ +func (c *IAM) CreateLoginProfileRequest(input *CreateLoginProfileInput) (req *request.Request, output *CreateLoginProfileOutput) { + op := &request.Operation{ Name: opCreateLoginProfile, HTTPMethod: "POST", HTTPPath: "/", @@ -404,8 +404,8 @@ func (c *IAM) CreateLoginProfile(input *CreateLoginProfileInput) (*CreateLoginPr const opCreateOpenIDConnectProvider = "CreateOpenIDConnectProvider" // CreateOpenIDConnectProviderRequest generates a request for the CreateOpenIDConnectProvider operation. -func (c *IAM) CreateOpenIDConnectProviderRequest(input *CreateOpenIDConnectProviderInput) (req *service.Request, output *CreateOpenIDConnectProviderOutput) { - op := &service.Operation{ +func (c *IAM) CreateOpenIDConnectProviderRequest(input *CreateOpenIDConnectProviderInput) (req *request.Request, output *CreateOpenIDConnectProviderOutput) { + op := &request.Operation{ Name: opCreateOpenIDConnectProvider, HTTPMethod: "POST", HTTPPath: "/", @@ -447,8 +447,8 @@ func (c *IAM) CreateOpenIDConnectProvider(input *CreateOpenIDConnectProviderInpu const opCreatePolicy = "CreatePolicy" // CreatePolicyRequest generates a request for the CreatePolicy operation. -func (c *IAM) CreatePolicyRequest(input *CreatePolicyInput) (req *service.Request, output *CreatePolicyOutput) { - op := &service.Operation{ +func (c *IAM) CreatePolicyRequest(input *CreatePolicyInput) (req *request.Request, output *CreatePolicyOutput) { + op := &request.Operation{ Name: opCreatePolicy, HTTPMethod: "POST", HTTPPath: "/", @@ -469,11 +469,11 @@ func (c *IAM) CreatePolicyRequest(input *CreatePolicyInput) (req *service.Reques // This operation creates a policy version with a version identifier of v1 // and sets v1 as the policy's default version. For more information about policy // versions, see Versioning for Managed Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-versions.html) -// in the Using IAM guide. +// in the IAM User Guide. // // For more information about managed policies in general, refer to Managed // Policies and Inline Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html) -// in the Using IAM guide. +// in the IAM User Guide. func (c *IAM) CreatePolicy(input *CreatePolicyInput) (*CreatePolicyOutput, error) { req, out := c.CreatePolicyRequest(input) err := req.Send() @@ -483,8 +483,8 @@ func (c *IAM) CreatePolicy(input *CreatePolicyInput) (*CreatePolicyOutput, error const opCreatePolicyVersion = "CreatePolicyVersion" // CreatePolicyVersionRequest generates a request for the CreatePolicyVersion operation. -func (c *IAM) CreatePolicyVersionRequest(input *CreatePolicyVersionInput) (req *service.Request, output *CreatePolicyVersionOutput) { - op := &service.Operation{ +func (c *IAM) CreatePolicyVersionRequest(input *CreatePolicyVersionInput) (req *request.Request, output *CreatePolicyVersionOutput) { + op := &request.Operation{ Name: opCreatePolicyVersion, HTTPMethod: "POST", HTTPPath: "/", @@ -512,7 +512,7 @@ func (c *IAM) CreatePolicyVersionRequest(input *CreatePolicyVersionInput) (req * // // For more information about managed policy versions, see Versioning for Managed // Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-versions.html) -// in the Using IAM guide. +// in the IAM User Guide. func (c *IAM) CreatePolicyVersion(input *CreatePolicyVersionInput) (*CreatePolicyVersionOutput, error) { req, out := c.CreatePolicyVersionRequest(input) err := req.Send() @@ -522,8 +522,8 @@ func (c *IAM) CreatePolicyVersion(input *CreatePolicyVersionInput) (*CreatePolic const opCreateRole = "CreateRole" // CreateRoleRequest generates a request for the CreateRole operation. -func (c *IAM) CreateRoleRequest(input *CreateRoleInput) (req *service.Request, output *CreateRoleOutput) { - op := &service.Operation{ +func (c *IAM) CreateRoleRequest(input *CreateRoleInput) (req *request.Request, output *CreateRoleOutput) { + op := &request.Operation{ Name: opCreateRole, HTTPMethod: "POST", HTTPPath: "/", @@ -543,7 +543,7 @@ func (c *IAM) CreateRoleRequest(input *CreateRoleInput) (req *service.Request, o // go to Working with Roles (http://docs.aws.amazon.com/IAM/latest/UserGuide/WorkingWithRoles.html). // For information about limitations on role names and the number of roles you // can create, go to Limitations on IAM Entities (http://docs.aws.amazon.com/IAM/latest/UserGuide/LimitationsOnEntities.html) -// in the Using IAM guide. +// in the IAM User Guide. // // The policy in the following example grants permission to an EC2 instance // to assume the role. @@ -556,8 +556,8 @@ func (c *IAM) CreateRole(input *CreateRoleInput) (*CreateRoleOutput, error) { const opCreateSAMLProvider = "CreateSAMLProvider" // CreateSAMLProviderRequest generates a request for the CreateSAMLProvider operation. -func (c *IAM) CreateSAMLProviderRequest(input *CreateSAMLProviderInput) (req *service.Request, output *CreateSAMLProviderOutput) { - op := &service.Operation{ +func (c *IAM) CreateSAMLProviderRequest(input *CreateSAMLProviderInput) (req *request.Request, output *CreateSAMLProviderOutput) { + op := &request.Operation{ Name: opCreateSAMLProvider, HTTPMethod: "POST", HTTPPath: "/", @@ -590,9 +590,10 @@ func (c *IAM) CreateSAMLProviderRequest(input *CreateSAMLProviderInput) (req *se // your organization's IdP. // // This operation requires Signature Version 4 (http://docs.aws.amazon.com/general/latest/gr/signature-version-4.html). -// For more information, see Giving Console Access Using SAML (http://docs.aws.amazon.com/STS/latest/UsingSTS/STSMgmtConsole-SAML.html) -// and Creating Temporary Security Credentials for SAML Federation (http://docs.aws.amazon.com/STS/latest/UsingSTS/CreatingSAML.html) -// in the Using Temporary Credentials guide. +// For more information, see Enabling SAML 2.0 Federated Users to Access the +// AWS Management Console (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_enable-console-saml.html) +// and About SAML 2.0-based Federation (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_saml.html) +// in the IAM User Guide. func (c *IAM) CreateSAMLProvider(input *CreateSAMLProviderInput) (*CreateSAMLProviderOutput, error) { req, out := c.CreateSAMLProviderRequest(input) err := req.Send() @@ -602,8 +603,8 @@ func (c *IAM) CreateSAMLProvider(input *CreateSAMLProviderInput) (*CreateSAMLPro const opCreateUser = "CreateUser" // CreateUserRequest generates a request for the CreateUser operation. -func (c *IAM) CreateUserRequest(input *CreateUserInput) (req *service.Request, output *CreateUserOutput) { - op := &service.Operation{ +func (c *IAM) CreateUserRequest(input *CreateUserInput) (req *request.Request, output *CreateUserOutput) { + op := &request.Operation{ Name: opCreateUser, HTTPMethod: "POST", HTTPPath: "/", @@ -623,7 +624,7 @@ func (c *IAM) CreateUserRequest(input *CreateUserInput) (req *service.Request, o // // For information about limitations on the number of users you can create, // see Limitations on IAM Entities (http://docs.aws.amazon.com/IAM/latest/UserGuide/LimitationsOnEntities.html) -// in the Using IAM guide. +// in the IAM User Guide. func (c *IAM) CreateUser(input *CreateUserInput) (*CreateUserOutput, error) { req, out := c.CreateUserRequest(input) err := req.Send() @@ -633,8 +634,8 @@ func (c *IAM) CreateUser(input *CreateUserInput) (*CreateUserOutput, error) { const opCreateVirtualMFADevice = "CreateVirtualMFADevice" // CreateVirtualMFADeviceRequest generates a request for the CreateVirtualMFADevice operation. -func (c *IAM) CreateVirtualMFADeviceRequest(input *CreateVirtualMFADeviceInput) (req *service.Request, output *CreateVirtualMFADeviceOutput) { - op := &service.Operation{ +func (c *IAM) CreateVirtualMFADeviceRequest(input *CreateVirtualMFADeviceInput) (req *request.Request, output *CreateVirtualMFADeviceOutput) { + op := &request.Operation{ Name: opCreateVirtualMFADevice, HTTPMethod: "POST", HTTPPath: "/", @@ -673,8 +674,8 @@ func (c *IAM) CreateVirtualMFADevice(input *CreateVirtualMFADeviceInput) (*Creat const opDeactivateMFADevice = "DeactivateMFADevice" // DeactivateMFADeviceRequest generates a request for the DeactivateMFADevice operation. -func (c *IAM) DeactivateMFADeviceRequest(input *DeactivateMFADeviceInput) (req *service.Request, output *DeactivateMFADeviceOutput) { - op := &service.Operation{ +func (c *IAM) DeactivateMFADeviceRequest(input *DeactivateMFADeviceInput) (req *request.Request, output *DeactivateMFADeviceOutput) { + op := &request.Operation{ Name: opDeactivateMFADevice, HTTPMethod: "POST", HTTPPath: "/", @@ -705,8 +706,8 @@ func (c *IAM) DeactivateMFADevice(input *DeactivateMFADeviceInput) (*DeactivateM const opDeleteAccessKey = "DeleteAccessKey" // DeleteAccessKeyRequest generates a request for the DeleteAccessKey operation. -func (c *IAM) DeleteAccessKeyRequest(input *DeleteAccessKeyInput) (req *service.Request, output *DeleteAccessKeyOutput) { - op := &service.Operation{ +func (c *IAM) DeleteAccessKeyRequest(input *DeleteAccessKeyInput) (req *request.Request, output *DeleteAccessKeyOutput) { + op := &request.Operation{ Name: opDeleteAccessKey, HTTPMethod: "POST", HTTPPath: "/", @@ -737,8 +738,8 @@ func (c *IAM) DeleteAccessKey(input *DeleteAccessKeyInput) (*DeleteAccessKeyOutp const opDeleteAccountAlias = "DeleteAccountAlias" // DeleteAccountAliasRequest generates a request for the DeleteAccountAlias operation. -func (c *IAM) DeleteAccountAliasRequest(input *DeleteAccountAliasInput) (req *service.Request, output *DeleteAccountAliasOutput) { - op := &service.Operation{ +func (c *IAM) DeleteAccountAliasRequest(input *DeleteAccountAliasInput) (req *request.Request, output *DeleteAccountAliasOutput) { + op := &request.Operation{ Name: opDeleteAccountAlias, HTTPMethod: "POST", HTTPPath: "/", @@ -756,7 +757,7 @@ func (c *IAM) DeleteAccountAliasRequest(input *DeleteAccountAliasInput) (req *se // Deletes the specified AWS account alias. For information about using an AWS // account alias, see Using an Alias for Your AWS Account ID (http://docs.aws.amazon.com/IAM/latest/UserGuide/AccountAlias.html) -// in the Using IAM guide. +// in the IAM User Guide. func (c *IAM) DeleteAccountAlias(input *DeleteAccountAliasInput) (*DeleteAccountAliasOutput, error) { req, out := c.DeleteAccountAliasRequest(input) err := req.Send() @@ -766,8 +767,8 @@ func (c *IAM) DeleteAccountAlias(input *DeleteAccountAliasInput) (*DeleteAccount const opDeleteAccountPasswordPolicy = "DeleteAccountPasswordPolicy" // DeleteAccountPasswordPolicyRequest generates a request for the DeleteAccountPasswordPolicy operation. -func (c *IAM) DeleteAccountPasswordPolicyRequest(input *DeleteAccountPasswordPolicyInput) (req *service.Request, output *DeleteAccountPasswordPolicyOutput) { - op := &service.Operation{ +func (c *IAM) DeleteAccountPasswordPolicyRequest(input *DeleteAccountPasswordPolicyInput) (req *request.Request, output *DeleteAccountPasswordPolicyOutput) { + op := &request.Operation{ Name: opDeleteAccountPasswordPolicy, HTTPMethod: "POST", HTTPPath: "/", @@ -793,8 +794,8 @@ func (c *IAM) DeleteAccountPasswordPolicy(input *DeleteAccountPasswordPolicyInpu const opDeleteGroup = "DeleteGroup" // DeleteGroupRequest generates a request for the DeleteGroup operation. -func (c *IAM) DeleteGroupRequest(input *DeleteGroupInput) (req *service.Request, output *DeleteGroupOutput) { - op := &service.Operation{ +func (c *IAM) DeleteGroupRequest(input *DeleteGroupInput) (req *request.Request, output *DeleteGroupOutput) { + op := &request.Operation{ Name: opDeleteGroup, HTTPMethod: "POST", HTTPPath: "/", @@ -821,8 +822,8 @@ func (c *IAM) DeleteGroup(input *DeleteGroupInput) (*DeleteGroupOutput, error) { const opDeleteGroupPolicy = "DeleteGroupPolicy" // DeleteGroupPolicyRequest generates a request for the DeleteGroupPolicy operation. -func (c *IAM) DeleteGroupPolicyRequest(input *DeleteGroupPolicyInput) (req *service.Request, output *DeleteGroupPolicyOutput) { - op := &service.Operation{ +func (c *IAM) DeleteGroupPolicyRequest(input *DeleteGroupPolicyInput) (req *request.Request, output *DeleteGroupPolicyOutput) { + op := &request.Operation{ Name: opDeleteGroupPolicy, HTTPMethod: "POST", HTTPPath: "/", @@ -843,7 +844,7 @@ func (c *IAM) DeleteGroupPolicyRequest(input *DeleteGroupPolicyInput) (req *serv // A group can also have managed policies attached to it. To detach a managed // policy from a group, use DetachGroupPolicy. For more information about policies, // refer to Managed Policies and Inline Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html) -// in the Using IAM guide. +// in the IAM User Guide. func (c *IAM) DeleteGroupPolicy(input *DeleteGroupPolicyInput) (*DeleteGroupPolicyOutput, error) { req, out := c.DeleteGroupPolicyRequest(input) err := req.Send() @@ -853,8 +854,8 @@ func (c *IAM) DeleteGroupPolicy(input *DeleteGroupPolicyInput) (*DeleteGroupPoli const opDeleteInstanceProfile = "DeleteInstanceProfile" // DeleteInstanceProfileRequest generates a request for the DeleteInstanceProfile operation. -func (c *IAM) DeleteInstanceProfileRequest(input *DeleteInstanceProfileInput) (req *service.Request, output *DeleteInstanceProfileOutput) { - op := &service.Operation{ +func (c *IAM) DeleteInstanceProfileRequest(input *DeleteInstanceProfileInput) (req *request.Request, output *DeleteInstanceProfileOutput) { + op := &request.Operation{ Name: opDeleteInstanceProfile, HTTPMethod: "POST", HTTPPath: "/", @@ -887,8 +888,8 @@ func (c *IAM) DeleteInstanceProfile(input *DeleteInstanceProfileInput) (*DeleteI const opDeleteLoginProfile = "DeleteLoginProfile" // DeleteLoginProfileRequest generates a request for the DeleteLoginProfile operation. -func (c *IAM) DeleteLoginProfileRequest(input *DeleteLoginProfileInput) (req *service.Request, output *DeleteLoginProfileOutput) { - op := &service.Operation{ +func (c *IAM) DeleteLoginProfileRequest(input *DeleteLoginProfileInput) (req *request.Request, output *DeleteLoginProfileOutput) { + op := &request.Operation{ Name: opDeleteLoginProfile, HTTPMethod: "POST", HTTPPath: "/", @@ -920,8 +921,8 @@ func (c *IAM) DeleteLoginProfile(input *DeleteLoginProfileInput) (*DeleteLoginPr const opDeleteOpenIDConnectProvider = "DeleteOpenIDConnectProvider" // DeleteOpenIDConnectProviderRequest generates a request for the DeleteOpenIDConnectProvider operation. -func (c *IAM) DeleteOpenIDConnectProviderRequest(input *DeleteOpenIDConnectProviderInput) (req *service.Request, output *DeleteOpenIDConnectProviderOutput) { - op := &service.Operation{ +func (c *IAM) DeleteOpenIDConnectProviderRequest(input *DeleteOpenIDConnectProviderInput) (req *request.Request, output *DeleteOpenIDConnectProviderOutput) { + op := &request.Operation{ Name: opDeleteOpenIDConnectProvider, HTTPMethod: "POST", HTTPPath: "/", @@ -954,8 +955,8 @@ func (c *IAM) DeleteOpenIDConnectProvider(input *DeleteOpenIDConnectProviderInpu const opDeletePolicy = "DeletePolicy" // DeletePolicyRequest generates a request for the DeletePolicy operation. -func (c *IAM) DeletePolicyRequest(input *DeletePolicyInput) (req *service.Request, output *DeletePolicyOutput) { - op := &service.Operation{ +func (c *IAM) DeletePolicyRequest(input *DeletePolicyInput) (req *request.Request, output *DeletePolicyOutput) { + op := &request.Operation{ Name: opDeletePolicy, HTTPMethod: "POST", HTTPPath: "/", @@ -988,7 +989,7 @@ func (c *IAM) DeletePolicyRequest(input *DeletePolicyInput) (req *service.Reques // // For information about managed policies, refer to Managed Policies and Inline // Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html) -// in the Using IAM guide. +// in the IAM User Guide. func (c *IAM) DeletePolicy(input *DeletePolicyInput) (*DeletePolicyOutput, error) { req, out := c.DeletePolicyRequest(input) err := req.Send() @@ -998,8 +999,8 @@ func (c *IAM) DeletePolicy(input *DeletePolicyInput) (*DeletePolicyOutput, error const opDeletePolicyVersion = "DeletePolicyVersion" // DeletePolicyVersionRequest generates a request for the DeletePolicyVersion operation. -func (c *IAM) DeletePolicyVersionRequest(input *DeletePolicyVersionInput) (req *service.Request, output *DeletePolicyVersionOutput) { - op := &service.Operation{ +func (c *IAM) DeletePolicyVersionRequest(input *DeletePolicyVersionInput) (req *request.Request, output *DeletePolicyVersionOutput) { + op := &request.Operation{ Name: opDeletePolicyVersion, HTTPMethod: "POST", HTTPPath: "/", @@ -1023,7 +1024,7 @@ func (c *IAM) DeletePolicyVersionRequest(input *DeletePolicyVersionInput) (req * // // For information about versions for managed policies, refer to Versioning // for Managed Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-versions.html) -// in the Using IAM guide. +// in the IAM User Guide. func (c *IAM) DeletePolicyVersion(input *DeletePolicyVersionInput) (*DeletePolicyVersionOutput, error) { req, out := c.DeletePolicyVersionRequest(input) err := req.Send() @@ -1033,8 +1034,8 @@ func (c *IAM) DeletePolicyVersion(input *DeletePolicyVersionInput) (*DeletePolic const opDeleteRole = "DeleteRole" // DeleteRoleRequest generates a request for the DeleteRole operation. -func (c *IAM) DeleteRoleRequest(input *DeleteRoleInput) (req *service.Request, output *DeleteRoleOutput) { - op := &service.Operation{ +func (c *IAM) DeleteRoleRequest(input *DeleteRoleInput) (req *request.Request, output *DeleteRoleOutput) { + op := &request.Operation{ Name: opDeleteRole, HTTPMethod: "POST", HTTPPath: "/", @@ -1065,8 +1066,8 @@ func (c *IAM) DeleteRole(input *DeleteRoleInput) (*DeleteRoleOutput, error) { const opDeleteRolePolicy = "DeleteRolePolicy" // DeleteRolePolicyRequest generates a request for the DeleteRolePolicy operation. -func (c *IAM) DeleteRolePolicyRequest(input *DeleteRolePolicyInput) (req *service.Request, output *DeleteRolePolicyOutput) { - op := &service.Operation{ +func (c *IAM) DeleteRolePolicyRequest(input *DeleteRolePolicyInput) (req *request.Request, output *DeleteRolePolicyOutput) { + op := &request.Operation{ Name: opDeleteRolePolicy, HTTPMethod: "POST", HTTPPath: "/", @@ -1087,7 +1088,7 @@ func (c *IAM) DeleteRolePolicyRequest(input *DeleteRolePolicyInput) (req *servic // A role can also have managed policies attached to it. To detach a managed // policy from a role, use DetachRolePolicy. For more information about policies, // refer to Managed Policies and Inline Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html) -// in the Using IAM guide. +// in the IAM User Guide. func (c *IAM) DeleteRolePolicy(input *DeleteRolePolicyInput) (*DeleteRolePolicyOutput, error) { req, out := c.DeleteRolePolicyRequest(input) err := req.Send() @@ -1097,8 +1098,8 @@ func (c *IAM) DeleteRolePolicy(input *DeleteRolePolicyInput) (*DeleteRolePolicyO const opDeleteSAMLProvider = "DeleteSAMLProvider" // DeleteSAMLProviderRequest generates a request for the DeleteSAMLProvider operation. -func (c *IAM) DeleteSAMLProviderRequest(input *DeleteSAMLProviderInput) (req *service.Request, output *DeleteSAMLProviderOutput) { - op := &service.Operation{ +func (c *IAM) DeleteSAMLProviderRequest(input *DeleteSAMLProviderInput) (req *request.Request, output *DeleteSAMLProviderOutput) { + op := &request.Operation{ Name: opDeleteSAMLProvider, HTTPMethod: "POST", HTTPPath: "/", @@ -1130,8 +1131,8 @@ func (c *IAM) DeleteSAMLProvider(input *DeleteSAMLProviderInput) (*DeleteSAMLPro const opDeleteSSHPublicKey = "DeleteSSHPublicKey" // DeleteSSHPublicKeyRequest generates a request for the DeleteSSHPublicKey operation. -func (c *IAM) DeleteSSHPublicKeyRequest(input *DeleteSSHPublicKeyInput) (req *service.Request, output *DeleteSSHPublicKeyOutput) { - op := &service.Operation{ +func (c *IAM) DeleteSSHPublicKeyRequest(input *DeleteSSHPublicKeyInput) (req *request.Request, output *DeleteSSHPublicKeyOutput) { + op := &request.Operation{ Name: opDeleteSSHPublicKey, HTTPMethod: "POST", HTTPPath: "/", @@ -1163,8 +1164,8 @@ func (c *IAM) DeleteSSHPublicKey(input *DeleteSSHPublicKeyInput) (*DeleteSSHPubl const opDeleteServerCertificate = "DeleteServerCertificate" // DeleteServerCertificateRequest generates a request for the DeleteServerCertificate operation. -func (c *IAM) DeleteServerCertificateRequest(input *DeleteServerCertificateInput) (req *service.Request, output *DeleteServerCertificateOutput) { - op := &service.Operation{ +func (c *IAM) DeleteServerCertificateRequest(input *DeleteServerCertificateInput) (req *request.Request, output *DeleteServerCertificateOutput) { + op := &request.Operation{ Name: opDeleteServerCertificate, HTTPMethod: "POST", HTTPPath: "/", @@ -1200,8 +1201,8 @@ func (c *IAM) DeleteServerCertificate(input *DeleteServerCertificateInput) (*Del const opDeleteSigningCertificate = "DeleteSigningCertificate" // DeleteSigningCertificateRequest generates a request for the DeleteSigningCertificate operation. -func (c *IAM) DeleteSigningCertificateRequest(input *DeleteSigningCertificateInput) (req *service.Request, output *DeleteSigningCertificateOutput) { - op := &service.Operation{ +func (c *IAM) DeleteSigningCertificateRequest(input *DeleteSigningCertificateInput) (req *request.Request, output *DeleteSigningCertificateOutput) { + op := &request.Operation{ Name: opDeleteSigningCertificate, HTTPMethod: "POST", HTTPPath: "/", @@ -1232,8 +1233,8 @@ func (c *IAM) DeleteSigningCertificate(input *DeleteSigningCertificateInput) (*D const opDeleteUser = "DeleteUser" // DeleteUserRequest generates a request for the DeleteUser operation. -func (c *IAM) DeleteUserRequest(input *DeleteUserInput) (req *service.Request, output *DeleteUserOutput) { - op := &service.Operation{ +func (c *IAM) DeleteUserRequest(input *DeleteUserInput) (req *request.Request, output *DeleteUserOutput) { + op := &request.Operation{ Name: opDeleteUser, HTTPMethod: "POST", HTTPPath: "/", @@ -1260,8 +1261,8 @@ func (c *IAM) DeleteUser(input *DeleteUserInput) (*DeleteUserOutput, error) { const opDeleteUserPolicy = "DeleteUserPolicy" // DeleteUserPolicyRequest generates a request for the DeleteUserPolicy operation. -func (c *IAM) DeleteUserPolicyRequest(input *DeleteUserPolicyInput) (req *service.Request, output *DeleteUserPolicyOutput) { - op := &service.Operation{ +func (c *IAM) DeleteUserPolicyRequest(input *DeleteUserPolicyInput) (req *request.Request, output *DeleteUserPolicyOutput) { + op := &request.Operation{ Name: opDeleteUserPolicy, HTTPMethod: "POST", HTTPPath: "/", @@ -1282,7 +1283,7 @@ func (c *IAM) DeleteUserPolicyRequest(input *DeleteUserPolicyInput) (req *servic // A user can also have managed policies attached to it. To detach a managed // policy from a user, use DetachUserPolicy. For more information about policies, // refer to Managed Policies and Inline Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html) -// in the Using IAM guide. +// in the IAM User Guide. func (c *IAM) DeleteUserPolicy(input *DeleteUserPolicyInput) (*DeleteUserPolicyOutput, error) { req, out := c.DeleteUserPolicyRequest(input) err := req.Send() @@ -1292,8 +1293,8 @@ func (c *IAM) DeleteUserPolicy(input *DeleteUserPolicyInput) (*DeleteUserPolicyO const opDeleteVirtualMFADevice = "DeleteVirtualMFADevice" // DeleteVirtualMFADeviceRequest generates a request for the DeleteVirtualMFADevice operation. -func (c *IAM) DeleteVirtualMFADeviceRequest(input *DeleteVirtualMFADeviceInput) (req *service.Request, output *DeleteVirtualMFADeviceOutput) { - op := &service.Operation{ +func (c *IAM) DeleteVirtualMFADeviceRequest(input *DeleteVirtualMFADeviceInput) (req *request.Request, output *DeleteVirtualMFADeviceOutput) { + op := &request.Operation{ Name: opDeleteVirtualMFADevice, HTTPMethod: "POST", HTTPPath: "/", @@ -1322,8 +1323,8 @@ func (c *IAM) DeleteVirtualMFADevice(input *DeleteVirtualMFADeviceInput) (*Delet const opDetachGroupPolicy = "DetachGroupPolicy" // DetachGroupPolicyRequest generates a request for the DetachGroupPolicy operation. -func (c *IAM) DetachGroupPolicyRequest(input *DetachGroupPolicyInput) (req *service.Request, output *DetachGroupPolicyOutput) { - op := &service.Operation{ +func (c *IAM) DetachGroupPolicyRequest(input *DetachGroupPolicyInput) (req *request.Request, output *DetachGroupPolicyOutput) { + op := &request.Operation{ Name: opDetachGroupPolicy, HTTPMethod: "POST", HTTPPath: "/", @@ -1344,7 +1345,7 @@ func (c *IAM) DetachGroupPolicyRequest(input *DetachGroupPolicyInput) (req *serv // A group can also have inline policies embedded with it. To delete an inline // policy, use the DeleteGroupPolicy API. For information about policies, refer // to Managed Policies and Inline Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html) -// in the Using IAM guide. +// in the IAM User Guide. func (c *IAM) DetachGroupPolicy(input *DetachGroupPolicyInput) (*DetachGroupPolicyOutput, error) { req, out := c.DetachGroupPolicyRequest(input) err := req.Send() @@ -1354,8 +1355,8 @@ func (c *IAM) DetachGroupPolicy(input *DetachGroupPolicyInput) (*DetachGroupPoli const opDetachRolePolicy = "DetachRolePolicy" // DetachRolePolicyRequest generates a request for the DetachRolePolicy operation. -func (c *IAM) DetachRolePolicyRequest(input *DetachRolePolicyInput) (req *service.Request, output *DetachRolePolicyOutput) { - op := &service.Operation{ +func (c *IAM) DetachRolePolicyRequest(input *DetachRolePolicyInput) (req *request.Request, output *DetachRolePolicyOutput) { + op := &request.Operation{ Name: opDetachRolePolicy, HTTPMethod: "POST", HTTPPath: "/", @@ -1376,7 +1377,7 @@ func (c *IAM) DetachRolePolicyRequest(input *DetachRolePolicyInput) (req *servic // A role can also have inline policies embedded with it. To delete an inline // policy, use the DeleteRolePolicy API. For information about policies, refer // to Managed Policies and Inline Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html) -// in the Using IAM guide. +// in the IAM User Guide. func (c *IAM) DetachRolePolicy(input *DetachRolePolicyInput) (*DetachRolePolicyOutput, error) { req, out := c.DetachRolePolicyRequest(input) err := req.Send() @@ -1386,8 +1387,8 @@ func (c *IAM) DetachRolePolicy(input *DetachRolePolicyInput) (*DetachRolePolicyO const opDetachUserPolicy = "DetachUserPolicy" // DetachUserPolicyRequest generates a request for the DetachUserPolicy operation. -func (c *IAM) DetachUserPolicyRequest(input *DetachUserPolicyInput) (req *service.Request, output *DetachUserPolicyOutput) { - op := &service.Operation{ +func (c *IAM) DetachUserPolicyRequest(input *DetachUserPolicyInput) (req *request.Request, output *DetachUserPolicyOutput) { + op := &request.Operation{ Name: opDetachUserPolicy, HTTPMethod: "POST", HTTPPath: "/", @@ -1408,7 +1409,7 @@ func (c *IAM) DetachUserPolicyRequest(input *DetachUserPolicyInput) (req *servic // A user can also have inline policies embedded with it. To delete an inline // policy, use the DeleteUserPolicy API. For information about policies, refer // to Managed Policies and Inline Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html) -// in the Using IAM guide. +// in the IAM User Guide. func (c *IAM) DetachUserPolicy(input *DetachUserPolicyInput) (*DetachUserPolicyOutput, error) { req, out := c.DetachUserPolicyRequest(input) err := req.Send() @@ -1418,8 +1419,8 @@ func (c *IAM) DetachUserPolicy(input *DetachUserPolicyInput) (*DetachUserPolicyO const opEnableMFADevice = "EnableMFADevice" // EnableMFADeviceRequest generates a request for the EnableMFADevice operation. -func (c *IAM) EnableMFADeviceRequest(input *EnableMFADeviceInput) (req *service.Request, output *EnableMFADeviceOutput) { - op := &service.Operation{ +func (c *IAM) EnableMFADeviceRequest(input *EnableMFADeviceInput) (req *request.Request, output *EnableMFADeviceOutput) { + op := &request.Operation{ Name: opEnableMFADevice, HTTPMethod: "POST", HTTPPath: "/", @@ -1447,8 +1448,8 @@ func (c *IAM) EnableMFADevice(input *EnableMFADeviceInput) (*EnableMFADeviceOutp const opGenerateCredentialReport = "GenerateCredentialReport" // GenerateCredentialReportRequest generates a request for the GenerateCredentialReport operation. -func (c *IAM) GenerateCredentialReportRequest(input *GenerateCredentialReportInput) (req *service.Request, output *GenerateCredentialReportOutput) { - op := &service.Operation{ +func (c *IAM) GenerateCredentialReportRequest(input *GenerateCredentialReportInput) (req *request.Request, output *GenerateCredentialReportOutput) { + op := &request.Operation{ Name: opGenerateCredentialReport, HTTPMethod: "POST", HTTPPath: "/", @@ -1466,7 +1467,7 @@ func (c *IAM) GenerateCredentialReportRequest(input *GenerateCredentialReportInp // Generates a credential report for the AWS account. For more information about // the credential report, see Getting Credential Reports (http://docs.aws.amazon.com/IAM/latest/UserGuide/credential-reports.html) -// in the Using IAM guide. +// in the IAM User Guide. func (c *IAM) GenerateCredentialReport(input *GenerateCredentialReportInput) (*GenerateCredentialReportOutput, error) { req, out := c.GenerateCredentialReportRequest(input) err := req.Send() @@ -1476,8 +1477,8 @@ func (c *IAM) GenerateCredentialReport(input *GenerateCredentialReportInput) (*G const opGetAccessKeyLastUsed = "GetAccessKeyLastUsed" // GetAccessKeyLastUsedRequest generates a request for the GetAccessKeyLastUsed operation. -func (c *IAM) GetAccessKeyLastUsedRequest(input *GetAccessKeyLastUsedInput) (req *service.Request, output *GetAccessKeyLastUsedOutput) { - op := &service.Operation{ +func (c *IAM) GetAccessKeyLastUsedRequest(input *GetAccessKeyLastUsedInput) (req *request.Request, output *GetAccessKeyLastUsedOutput) { + op := &request.Operation{ Name: opGetAccessKeyLastUsed, HTTPMethod: "POST", HTTPPath: "/", @@ -1506,12 +1507,12 @@ func (c *IAM) GetAccessKeyLastUsed(input *GetAccessKeyLastUsedInput) (*GetAccess const opGetAccountAuthorizationDetails = "GetAccountAuthorizationDetails" // GetAccountAuthorizationDetailsRequest generates a request for the GetAccountAuthorizationDetails operation. -func (c *IAM) GetAccountAuthorizationDetailsRequest(input *GetAccountAuthorizationDetailsInput) (req *service.Request, output *GetAccountAuthorizationDetailsOutput) { - op := &service.Operation{ +func (c *IAM) GetAccountAuthorizationDetailsRequest(input *GetAccountAuthorizationDetailsInput) (req *request.Request, output *GetAccountAuthorizationDetailsOutput) { + op := &request.Operation{ Name: opGetAccountAuthorizationDetails, HTTPMethod: "POST", HTTPPath: "/", - Paginator: &service.Paginator{ + Paginator: &request.Paginator{ InputTokens: []string{"Marker"}, OutputTokens: []string{"Marker"}, LimitToken: "MaxItems", @@ -1552,8 +1553,8 @@ func (c *IAM) GetAccountAuthorizationDetailsPages(input *GetAccountAuthorization const opGetAccountPasswordPolicy = "GetAccountPasswordPolicy" // GetAccountPasswordPolicyRequest generates a request for the GetAccountPasswordPolicy operation. -func (c *IAM) GetAccountPasswordPolicyRequest(input *GetAccountPasswordPolicyInput) (req *service.Request, output *GetAccountPasswordPolicyOutput) { - op := &service.Operation{ +func (c *IAM) GetAccountPasswordPolicyRequest(input *GetAccountPasswordPolicyInput) (req *request.Request, output *GetAccountPasswordPolicyOutput) { + op := &request.Operation{ Name: opGetAccountPasswordPolicy, HTTPMethod: "POST", HTTPPath: "/", @@ -1580,8 +1581,8 @@ func (c *IAM) GetAccountPasswordPolicy(input *GetAccountPasswordPolicyInput) (*G const opGetAccountSummary = "GetAccountSummary" // GetAccountSummaryRequest generates a request for the GetAccountSummary operation. -func (c *IAM) GetAccountSummaryRequest(input *GetAccountSummaryInput) (req *service.Request, output *GetAccountSummaryOutput) { - op := &service.Operation{ +func (c *IAM) GetAccountSummaryRequest(input *GetAccountSummaryInput) (req *request.Request, output *GetAccountSummaryOutput) { + op := &request.Operation{ Name: opGetAccountSummary, HTTPMethod: "POST", HTTPPath: "/", @@ -1601,18 +1602,99 @@ func (c *IAM) GetAccountSummaryRequest(input *GetAccountSummaryInput) (req *serv // // For information about limitations on IAM entities, see Limitations on IAM // Entities (http://docs.aws.amazon.com/IAM/latest/UserGuide/LimitationsOnEntities.html) -// in the Using IAM guide. +// in the IAM User Guide. func (c *IAM) GetAccountSummary(input *GetAccountSummaryInput) (*GetAccountSummaryOutput, error) { req, out := c.GetAccountSummaryRequest(input) err := req.Send() return out, err } +const opGetContextKeysForCustomPolicy = "GetContextKeysForCustomPolicy" + +// GetContextKeysForCustomPolicyRequest generates a request for the GetContextKeysForCustomPolicy operation. +func (c *IAM) GetContextKeysForCustomPolicyRequest(input *GetContextKeysForCustomPolicyInput) (req *request.Request, output *GetContextKeysForPolicyResponse) { + op := &request.Operation{ + Name: opGetContextKeysForCustomPolicy, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &GetContextKeysForCustomPolicyInput{} + } + + req = c.newRequest(op, input, output) + output = &GetContextKeysForPolicyResponse{} + req.Data = output + return +} + +// Gets a list of all of the context keys referenced in Condition elements in +// the input policies. The policies are supplied as a list of one or more strings. +// To get the context keys from policies associated with an IAM user, group, +// or role, use GetContextKeysForPrincipalPolicy. +// +// Context keys are variables maintained by AWS and its services that provide +// details about the context of an API query request, and can be evaluated by +// using the Condition element of an IAM policy. Use GetContextKeysForCustomPolicy +// to understand what key names and values you must supply when you call SimulateCustomPolicy. +// Note that all parameters are shown in unencoded form here for clarity, but +// must be URL encoded to be included as a part of a real HTML request. +func (c *IAM) GetContextKeysForCustomPolicy(input *GetContextKeysForCustomPolicyInput) (*GetContextKeysForPolicyResponse, error) { + req, out := c.GetContextKeysForCustomPolicyRequest(input) + err := req.Send() + return out, err +} + +const opGetContextKeysForPrincipalPolicy = "GetContextKeysForPrincipalPolicy" + +// GetContextKeysForPrincipalPolicyRequest generates a request for the GetContextKeysForPrincipalPolicy operation. +func (c *IAM) GetContextKeysForPrincipalPolicyRequest(input *GetContextKeysForPrincipalPolicyInput) (req *request.Request, output *GetContextKeysForPolicyResponse) { + op := &request.Operation{ + Name: opGetContextKeysForPrincipalPolicy, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &GetContextKeysForPrincipalPolicyInput{} + } + + req = c.newRequest(op, input, output) + output = &GetContextKeysForPolicyResponse{} + req.Data = output + return +} + +// Gets a list of all of the context keys referenced in Condition elements in +// all of the IAM policies attached to the specified IAM entity. The entity +// can be an IAM user, group, or role. If you specify a user, then the request +// also includes all of the policies attached to groups that the user is a member +// of. +// +// You can optionally include a list of one or more additional policies, specified +// as strings. If you want to include only a list of policies by string, use +// GetContextKeysForCustomPolicy instead. +// +// Note: This API discloses information about the permissions granted to other +// users. If you do not want users to see other user's permissions, then consider +// allowing them to use GetContextKeysForCustomPolicy instead. +// +// Context keys are variables maintained by AWS and its services that provide +// details about the context of an API query request, and can be evaluated by +// using the Condition element of an IAM policy. Use GetContextKeysForPrincipalPolicy +// to understand what key names and values you must supply when you call SimulatePrincipalPolicy. +func (c *IAM) GetContextKeysForPrincipalPolicy(input *GetContextKeysForPrincipalPolicyInput) (*GetContextKeysForPolicyResponse, error) { + req, out := c.GetContextKeysForPrincipalPolicyRequest(input) + err := req.Send() + return out, err +} + const opGetCredentialReport = "GetCredentialReport" // GetCredentialReportRequest generates a request for the GetCredentialReport operation. -func (c *IAM) GetCredentialReportRequest(input *GetCredentialReportInput) (req *service.Request, output *GetCredentialReportOutput) { - op := &service.Operation{ +func (c *IAM) GetCredentialReportRequest(input *GetCredentialReportInput) (req *request.Request, output *GetCredentialReportOutput) { + op := &request.Operation{ Name: opGetCredentialReport, HTTPMethod: "POST", HTTPPath: "/", @@ -1630,7 +1712,7 @@ func (c *IAM) GetCredentialReportRequest(input *GetCredentialReportInput) (req * // Retrieves a credential report for the AWS account. For more information about // the credential report, see Getting Credential Reports (http://docs.aws.amazon.com/IAM/latest/UserGuide/credential-reports.html) -// in the Using IAM guide. +// in the IAM User Guide. func (c *IAM) GetCredentialReport(input *GetCredentialReportInput) (*GetCredentialReportOutput, error) { req, out := c.GetCredentialReportRequest(input) err := req.Send() @@ -1640,12 +1722,12 @@ func (c *IAM) GetCredentialReport(input *GetCredentialReportInput) (*GetCredenti const opGetGroup = "GetGroup" // GetGroupRequest generates a request for the GetGroup operation. -func (c *IAM) GetGroupRequest(input *GetGroupInput) (req *service.Request, output *GetGroupOutput) { - op := &service.Operation{ +func (c *IAM) GetGroupRequest(input *GetGroupInput) (req *request.Request, output *GetGroupOutput) { + op := &request.Operation{ Name: opGetGroup, HTTPMethod: "POST", HTTPPath: "/", - Paginator: &service.Paginator{ + Paginator: &request.Paginator{ InputTokens: []string{"Marker"}, OutputTokens: []string{"Marker"}, LimitToken: "MaxItems", @@ -1681,8 +1763,8 @@ func (c *IAM) GetGroupPages(input *GetGroupInput, fn func(p *GetGroupOutput, las const opGetGroupPolicy = "GetGroupPolicy" // GetGroupPolicyRequest generates a request for the GetGroupPolicy operation. -func (c *IAM) GetGroupPolicyRequest(input *GetGroupPolicyInput) (req *service.Request, output *GetGroupPolicyOutput) { - op := &service.Operation{ +func (c *IAM) GetGroupPolicyRequest(input *GetGroupPolicyInput) (req *request.Request, output *GetGroupPolicyOutput) { + op := &request.Operation{ Name: opGetGroupPolicy, HTTPMethod: "POST", HTTPPath: "/", @@ -1708,7 +1790,7 @@ func (c *IAM) GetGroupPolicyRequest(input *GetGroupPolicyInput) (req *service.Re // // For more information about policies, refer to Managed Policies and Inline // Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html) -// in the Using IAM guide. +// in the IAM User Guide. func (c *IAM) GetGroupPolicy(input *GetGroupPolicyInput) (*GetGroupPolicyOutput, error) { req, out := c.GetGroupPolicyRequest(input) err := req.Send() @@ -1718,8 +1800,8 @@ func (c *IAM) GetGroupPolicy(input *GetGroupPolicyInput) (*GetGroupPolicyOutput, const opGetInstanceProfile = "GetInstanceProfile" // GetInstanceProfileRequest generates a request for the GetInstanceProfile operation. -func (c *IAM) GetInstanceProfileRequest(input *GetInstanceProfileInput) (req *service.Request, output *GetInstanceProfileOutput) { - op := &service.Operation{ +func (c *IAM) GetInstanceProfileRequest(input *GetInstanceProfileInput) (req *request.Request, output *GetInstanceProfileOutput) { + op := &request.Operation{ Name: opGetInstanceProfile, HTTPMethod: "POST", HTTPPath: "/", @@ -1748,8 +1830,8 @@ func (c *IAM) GetInstanceProfile(input *GetInstanceProfileInput) (*GetInstancePr const opGetLoginProfile = "GetLoginProfile" // GetLoginProfileRequest generates a request for the GetLoginProfile operation. -func (c *IAM) GetLoginProfileRequest(input *GetLoginProfileInput) (req *service.Request, output *GetLoginProfileOutput) { - op := &service.Operation{ +func (c *IAM) GetLoginProfileRequest(input *GetLoginProfileInput) (req *request.Request, output *GetLoginProfileOutput) { + op := &request.Operation{ Name: opGetLoginProfile, HTTPMethod: "POST", HTTPPath: "/", @@ -1777,8 +1859,8 @@ func (c *IAM) GetLoginProfile(input *GetLoginProfileInput) (*GetLoginProfileOutp const opGetOpenIDConnectProvider = "GetOpenIDConnectProvider" // GetOpenIDConnectProviderRequest generates a request for the GetOpenIDConnectProvider operation. -func (c *IAM) GetOpenIDConnectProviderRequest(input *GetOpenIDConnectProviderInput) (req *service.Request, output *GetOpenIDConnectProviderOutput) { - op := &service.Operation{ +func (c *IAM) GetOpenIDConnectProviderRequest(input *GetOpenIDConnectProviderInput) (req *request.Request, output *GetOpenIDConnectProviderOutput) { + op := &request.Operation{ Name: opGetOpenIDConnectProvider, HTTPMethod: "POST", HTTPPath: "/", @@ -1804,8 +1886,8 @@ func (c *IAM) GetOpenIDConnectProvider(input *GetOpenIDConnectProviderInput) (*G const opGetPolicy = "GetPolicy" // GetPolicyRequest generates a request for the GetPolicy operation. -func (c *IAM) GetPolicyRequest(input *GetPolicyInput) (req *service.Request, output *GetPolicyOutput) { - op := &service.Operation{ +func (c *IAM) GetPolicyRequest(input *GetPolicyInput) (req *request.Request, output *GetPolicyOutput) { + op := &request.Operation{ Name: opGetPolicy, HTTPMethod: "POST", HTTPPath: "/", @@ -1834,7 +1916,7 @@ func (c *IAM) GetPolicyRequest(input *GetPolicyInput) (req *service.Request, out // // For more information about policies, refer to Managed Policies and Inline // Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html) -// in the Using IAM guide. +// in the IAM User Guide. func (c *IAM) GetPolicy(input *GetPolicyInput) (*GetPolicyOutput, error) { req, out := c.GetPolicyRequest(input) err := req.Send() @@ -1844,8 +1926,8 @@ func (c *IAM) GetPolicy(input *GetPolicyInput) (*GetPolicyOutput, error) { const opGetPolicyVersion = "GetPolicyVersion" // GetPolicyVersionRequest generates a request for the GetPolicyVersion operation. -func (c *IAM) GetPolicyVersionRequest(input *GetPolicyVersionInput) (req *service.Request, output *GetPolicyVersionOutput) { - op := &service.Operation{ +func (c *IAM) GetPolicyVersionRequest(input *GetPolicyVersionInput) (req *request.Request, output *GetPolicyVersionOutput) { + op := &request.Operation{ Name: opGetPolicyVersion, HTTPMethod: "POST", HTTPPath: "/", @@ -1872,7 +1954,7 @@ func (c *IAM) GetPolicyVersionRequest(input *GetPolicyVersionInput) (req *servic // // For more information about the types of policies, refer to Managed Policies // and Inline Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html) -// in the Using IAM guide. +// in the IAM User Guide. func (c *IAM) GetPolicyVersion(input *GetPolicyVersionInput) (*GetPolicyVersionOutput, error) { req, out := c.GetPolicyVersionRequest(input) err := req.Send() @@ -1882,8 +1964,8 @@ func (c *IAM) GetPolicyVersion(input *GetPolicyVersionInput) (*GetPolicyVersionO const opGetRole = "GetRole" // GetRoleRequest generates a request for the GetRole operation. -func (c *IAM) GetRoleRequest(input *GetRoleInput) (req *service.Request, output *GetRoleOutput) { - op := &service.Operation{ +func (c *IAM) GetRoleRequest(input *GetRoleInput) (req *request.Request, output *GetRoleOutput) { + op := &request.Operation{ Name: opGetRole, HTTPMethod: "POST", HTTPPath: "/", @@ -1912,8 +1994,8 @@ func (c *IAM) GetRole(input *GetRoleInput) (*GetRoleOutput, error) { const opGetRolePolicy = "GetRolePolicy" // GetRolePolicyRequest generates a request for the GetRolePolicy operation. -func (c *IAM) GetRolePolicyRequest(input *GetRolePolicyInput) (req *service.Request, output *GetRolePolicyOutput) { - op := &service.Operation{ +func (c *IAM) GetRolePolicyRequest(input *GetRolePolicyInput) (req *request.Request, output *GetRolePolicyOutput) { + op := &request.Operation{ Name: opGetRolePolicy, HTTPMethod: "POST", HTTPPath: "/", @@ -1939,7 +2021,7 @@ func (c *IAM) GetRolePolicyRequest(input *GetRolePolicyInput) (req *service.Requ // // For more information about policies, refer to Managed Policies and Inline // Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html) -// in the Using IAM guide. +// in the IAM User Guide. // // For more information about roles, go to Using Roles to Delegate Permissions // and Federate Identities (http://docs.aws.amazon.com/IAM/latest/UserGuide/roles-toplevel.html). @@ -1952,8 +2034,8 @@ func (c *IAM) GetRolePolicy(input *GetRolePolicyInput) (*GetRolePolicyOutput, er const opGetSAMLProvider = "GetSAMLProvider" // GetSAMLProviderRequest generates a request for the GetSAMLProvider operation. -func (c *IAM) GetSAMLProviderRequest(input *GetSAMLProviderInput) (req *service.Request, output *GetSAMLProviderOutput) { - op := &service.Operation{ +func (c *IAM) GetSAMLProviderRequest(input *GetSAMLProviderInput) (req *request.Request, output *GetSAMLProviderOutput) { + op := &request.Operation{ Name: opGetSAMLProvider, HTTPMethod: "POST", HTTPPath: "/", @@ -1982,8 +2064,8 @@ func (c *IAM) GetSAMLProvider(input *GetSAMLProviderInput) (*GetSAMLProviderOutp const opGetSSHPublicKey = "GetSSHPublicKey" // GetSSHPublicKeyRequest generates a request for the GetSSHPublicKey operation. -func (c *IAM) GetSSHPublicKeyRequest(input *GetSSHPublicKeyInput) (req *service.Request, output *GetSSHPublicKeyOutput) { - op := &service.Operation{ +func (c *IAM) GetSSHPublicKeyRequest(input *GetSSHPublicKeyInput) (req *request.Request, output *GetSSHPublicKeyOutput) { + op := &request.Operation{ Name: opGetSSHPublicKey, HTTPMethod: "POST", HTTPPath: "/", @@ -2015,8 +2097,8 @@ func (c *IAM) GetSSHPublicKey(input *GetSSHPublicKeyInput) (*GetSSHPublicKeyOutp const opGetServerCertificate = "GetServerCertificate" // GetServerCertificateRequest generates a request for the GetServerCertificate operation. -func (c *IAM) GetServerCertificateRequest(input *GetServerCertificateInput) (req *service.Request, output *GetServerCertificateOutput) { - op := &service.Operation{ +func (c *IAM) GetServerCertificateRequest(input *GetServerCertificateInput) (req *request.Request, output *GetServerCertificateOutput) { + op := &request.Operation{ Name: opGetServerCertificate, HTTPMethod: "POST", HTTPPath: "/", @@ -2042,8 +2124,8 @@ func (c *IAM) GetServerCertificate(input *GetServerCertificateInput) (*GetServer const opGetUser = "GetUser" // GetUserRequest generates a request for the GetUser operation. -func (c *IAM) GetUserRequest(input *GetUserInput) (req *service.Request, output *GetUserOutput) { - op := &service.Operation{ +func (c *IAM) GetUserRequest(input *GetUserInput) (req *request.Request, output *GetUserOutput) { + op := &request.Operation{ Name: opGetUser, HTTPMethod: "POST", HTTPPath: "/", @@ -2073,8 +2155,8 @@ func (c *IAM) GetUser(input *GetUserInput) (*GetUserOutput, error) { const opGetUserPolicy = "GetUserPolicy" // GetUserPolicyRequest generates a request for the GetUserPolicy operation. -func (c *IAM) GetUserPolicyRequest(input *GetUserPolicyInput) (req *service.Request, output *GetUserPolicyOutput) { - op := &service.Operation{ +func (c *IAM) GetUserPolicyRequest(input *GetUserPolicyInput) (req *request.Request, output *GetUserPolicyOutput) { + op := &request.Operation{ Name: opGetUserPolicy, HTTPMethod: "POST", HTTPPath: "/", @@ -2100,7 +2182,7 @@ func (c *IAM) GetUserPolicyRequest(input *GetUserPolicyInput) (req *service.Requ // // For more information about policies, refer to Managed Policies and Inline // Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html) -// in the Using IAM guide. +// in the IAM User Guide. func (c *IAM) GetUserPolicy(input *GetUserPolicyInput) (*GetUserPolicyOutput, error) { req, out := c.GetUserPolicyRequest(input) err := req.Send() @@ -2110,12 +2192,12 @@ func (c *IAM) GetUserPolicy(input *GetUserPolicyInput) (*GetUserPolicyOutput, er const opListAccessKeys = "ListAccessKeys" // ListAccessKeysRequest generates a request for the ListAccessKeys operation. -func (c *IAM) ListAccessKeysRequest(input *ListAccessKeysInput) (req *service.Request, output *ListAccessKeysOutput) { - op := &service.Operation{ +func (c *IAM) ListAccessKeysRequest(input *ListAccessKeysInput) (req *request.Request, output *ListAccessKeysOutput) { + op := &request.Operation{ Name: opListAccessKeys, HTTPMethod: "POST", HTTPPath: "/", - Paginator: &service.Paginator{ + Paginator: &request.Paginator{ InputTokens: []string{"Marker"}, OutputTokens: []string{"Marker"}, LimitToken: "MaxItems", @@ -2162,12 +2244,12 @@ func (c *IAM) ListAccessKeysPages(input *ListAccessKeysInput, fn func(p *ListAcc const opListAccountAliases = "ListAccountAliases" // ListAccountAliasesRequest generates a request for the ListAccountAliases operation. -func (c *IAM) ListAccountAliasesRequest(input *ListAccountAliasesInput) (req *service.Request, output *ListAccountAliasesOutput) { - op := &service.Operation{ +func (c *IAM) ListAccountAliasesRequest(input *ListAccountAliasesInput) (req *request.Request, output *ListAccountAliasesOutput) { + op := &request.Operation{ Name: opListAccountAliases, HTTPMethod: "POST", HTTPPath: "/", - Paginator: &service.Paginator{ + Paginator: &request.Paginator{ InputTokens: []string{"Marker"}, OutputTokens: []string{"Marker"}, LimitToken: "MaxItems", @@ -2187,7 +2269,7 @@ func (c *IAM) ListAccountAliasesRequest(input *ListAccountAliasesInput) (req *se // Lists the account aliases associated with the account. For information about // using an AWS account alias, see Using an Alias for Your AWS Account ID (http://docs.aws.amazon.com/IAM/latest/UserGuide/AccountAlias.html) -// in the Using IAM guide. +// in the IAM User Guide. // // You can paginate the results using the MaxItems and Marker parameters. func (c *IAM) ListAccountAliases(input *ListAccountAliasesInput) (*ListAccountAliasesOutput, error) { @@ -2206,12 +2288,12 @@ func (c *IAM) ListAccountAliasesPages(input *ListAccountAliasesInput, fn func(p const opListAttachedGroupPolicies = "ListAttachedGroupPolicies" // ListAttachedGroupPoliciesRequest generates a request for the ListAttachedGroupPolicies operation. -func (c *IAM) ListAttachedGroupPoliciesRequest(input *ListAttachedGroupPoliciesInput) (req *service.Request, output *ListAttachedGroupPoliciesOutput) { - op := &service.Operation{ +func (c *IAM) ListAttachedGroupPoliciesRequest(input *ListAttachedGroupPoliciesInput) (req *request.Request, output *ListAttachedGroupPoliciesOutput) { + op := &request.Operation{ Name: opListAttachedGroupPolicies, HTTPMethod: "POST", HTTPPath: "/", - Paginator: &service.Paginator{ + Paginator: &request.Paginator{ InputTokens: []string{"Marker"}, OutputTokens: []string{"Marker"}, LimitToken: "MaxItems", @@ -2234,7 +2316,7 @@ func (c *IAM) ListAttachedGroupPoliciesRequest(input *ListAttachedGroupPoliciesI // A group can also have inline policies embedded with it. To list the inline // policies for a group, use the ListGroupPolicies API. For information about // policies, refer to Managed Policies and Inline Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html) -// in the Using IAM guide. +// in the IAM User Guide. // // You can paginate the results using the MaxItems and Marker parameters. You // can use the PathPrefix parameter to limit the list of policies to only those @@ -2257,12 +2339,12 @@ func (c *IAM) ListAttachedGroupPoliciesPages(input *ListAttachedGroupPoliciesInp const opListAttachedRolePolicies = "ListAttachedRolePolicies" // ListAttachedRolePoliciesRequest generates a request for the ListAttachedRolePolicies operation. -func (c *IAM) ListAttachedRolePoliciesRequest(input *ListAttachedRolePoliciesInput) (req *service.Request, output *ListAttachedRolePoliciesOutput) { - op := &service.Operation{ +func (c *IAM) ListAttachedRolePoliciesRequest(input *ListAttachedRolePoliciesInput) (req *request.Request, output *ListAttachedRolePoliciesOutput) { + op := &request.Operation{ Name: opListAttachedRolePolicies, HTTPMethod: "POST", HTTPPath: "/", - Paginator: &service.Paginator{ + Paginator: &request.Paginator{ InputTokens: []string{"Marker"}, OutputTokens: []string{"Marker"}, LimitToken: "MaxItems", @@ -2285,7 +2367,7 @@ func (c *IAM) ListAttachedRolePoliciesRequest(input *ListAttachedRolePoliciesInp // A role can also have inline policies embedded with it. To list the inline // policies for a role, use the ListRolePolicies API. For information about // policies, refer to Managed Policies and Inline Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html) -// in the Using IAM guide. +// in the IAM User Guide. // // You can paginate the results using the MaxItems and Marker parameters. You // can use the PathPrefix parameter to limit the list of policies to only those @@ -2308,12 +2390,12 @@ func (c *IAM) ListAttachedRolePoliciesPages(input *ListAttachedRolePoliciesInput const opListAttachedUserPolicies = "ListAttachedUserPolicies" // ListAttachedUserPoliciesRequest generates a request for the ListAttachedUserPolicies operation. -func (c *IAM) ListAttachedUserPoliciesRequest(input *ListAttachedUserPoliciesInput) (req *service.Request, output *ListAttachedUserPoliciesOutput) { - op := &service.Operation{ +func (c *IAM) ListAttachedUserPoliciesRequest(input *ListAttachedUserPoliciesInput) (req *request.Request, output *ListAttachedUserPoliciesOutput) { + op := &request.Operation{ Name: opListAttachedUserPolicies, HTTPMethod: "POST", HTTPPath: "/", - Paginator: &service.Paginator{ + Paginator: &request.Paginator{ InputTokens: []string{"Marker"}, OutputTokens: []string{"Marker"}, LimitToken: "MaxItems", @@ -2336,7 +2418,7 @@ func (c *IAM) ListAttachedUserPoliciesRequest(input *ListAttachedUserPoliciesInp // A user can also have inline policies embedded with it. To list the inline // policies for a user, use the ListUserPolicies API. For information about // policies, refer to Managed Policies and Inline Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html) -// in the Using IAM guide. +// in the IAM User Guide. // // You can paginate the results using the MaxItems and Marker parameters. You // can use the PathPrefix parameter to limit the list of policies to only those @@ -2359,12 +2441,12 @@ func (c *IAM) ListAttachedUserPoliciesPages(input *ListAttachedUserPoliciesInput const opListEntitiesForPolicy = "ListEntitiesForPolicy" // ListEntitiesForPolicyRequest generates a request for the ListEntitiesForPolicy operation. -func (c *IAM) ListEntitiesForPolicyRequest(input *ListEntitiesForPolicyInput) (req *service.Request, output *ListEntitiesForPolicyOutput) { - op := &service.Operation{ +func (c *IAM) ListEntitiesForPolicyRequest(input *ListEntitiesForPolicyInput) (req *request.Request, output *ListEntitiesForPolicyOutput) { + op := &request.Operation{ Name: opListEntitiesForPolicy, HTTPMethod: "POST", HTTPPath: "/", - Paginator: &service.Paginator{ + Paginator: &request.Paginator{ InputTokens: []string{"Marker"}, OutputTokens: []string{"Marker"}, LimitToken: "MaxItems", @@ -2407,12 +2489,12 @@ func (c *IAM) ListEntitiesForPolicyPages(input *ListEntitiesForPolicyInput, fn f const opListGroupPolicies = "ListGroupPolicies" // ListGroupPoliciesRequest generates a request for the ListGroupPolicies operation. -func (c *IAM) ListGroupPoliciesRequest(input *ListGroupPoliciesInput) (req *service.Request, output *ListGroupPoliciesOutput) { - op := &service.Operation{ +func (c *IAM) ListGroupPoliciesRequest(input *ListGroupPoliciesInput) (req *request.Request, output *ListGroupPoliciesOutput) { + op := &request.Operation{ Name: opListGroupPolicies, HTTPMethod: "POST", HTTPPath: "/", - Paginator: &service.Paginator{ + Paginator: &request.Paginator{ InputTokens: []string{"Marker"}, OutputTokens: []string{"Marker"}, LimitToken: "MaxItems", @@ -2437,7 +2519,7 @@ func (c *IAM) ListGroupPoliciesRequest(input *ListGroupPoliciesInput) (req *serv // policies that are attached to a group, use ListAttachedGroupPolicies. For // more information about policies, refer to Managed Policies and Inline Policies // (http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html) -// in the Using IAM guide. +// in the IAM User Guide. // // You can paginate the results using the MaxItems and Marker parameters. If // there are no inline policies embedded with the specified group, the action @@ -2458,12 +2540,12 @@ func (c *IAM) ListGroupPoliciesPages(input *ListGroupPoliciesInput, fn func(p *L const opListGroups = "ListGroups" // ListGroupsRequest generates a request for the ListGroups operation. -func (c *IAM) ListGroupsRequest(input *ListGroupsInput) (req *service.Request, output *ListGroupsOutput) { - op := &service.Operation{ +func (c *IAM) ListGroupsRequest(input *ListGroupsInput) (req *request.Request, output *ListGroupsOutput) { + op := &request.Operation{ Name: opListGroups, HTTPMethod: "POST", HTTPPath: "/", - Paginator: &service.Paginator{ + Paginator: &request.Paginator{ InputTokens: []string{"Marker"}, OutputTokens: []string{"Marker"}, LimitToken: "MaxItems", @@ -2500,12 +2582,12 @@ func (c *IAM) ListGroupsPages(input *ListGroupsInput, fn func(p *ListGroupsOutpu const opListGroupsForUser = "ListGroupsForUser" // ListGroupsForUserRequest generates a request for the ListGroupsForUser operation. -func (c *IAM) ListGroupsForUserRequest(input *ListGroupsForUserInput) (req *service.Request, output *ListGroupsForUserOutput) { - op := &service.Operation{ +func (c *IAM) ListGroupsForUserRequest(input *ListGroupsForUserInput) (req *request.Request, output *ListGroupsForUserOutput) { + op := &request.Operation{ Name: opListGroupsForUser, HTTPMethod: "POST", HTTPPath: "/", - Paginator: &service.Paginator{ + Paginator: &request.Paginator{ InputTokens: []string{"Marker"}, OutputTokens: []string{"Marker"}, LimitToken: "MaxItems", @@ -2542,12 +2624,12 @@ func (c *IAM) ListGroupsForUserPages(input *ListGroupsForUserInput, fn func(p *L const opListInstanceProfiles = "ListInstanceProfiles" // ListInstanceProfilesRequest generates a request for the ListInstanceProfiles operation. -func (c *IAM) ListInstanceProfilesRequest(input *ListInstanceProfilesInput) (req *service.Request, output *ListInstanceProfilesOutput) { - op := &service.Operation{ +func (c *IAM) ListInstanceProfilesRequest(input *ListInstanceProfilesInput) (req *request.Request, output *ListInstanceProfilesOutput) { + op := &request.Operation{ Name: opListInstanceProfiles, HTTPMethod: "POST", HTTPPath: "/", - Paginator: &service.Paginator{ + Paginator: &request.Paginator{ InputTokens: []string{"Marker"}, OutputTokens: []string{"Marker"}, LimitToken: "MaxItems", @@ -2586,12 +2668,12 @@ func (c *IAM) ListInstanceProfilesPages(input *ListInstanceProfilesInput, fn fun const opListInstanceProfilesForRole = "ListInstanceProfilesForRole" // ListInstanceProfilesForRoleRequest generates a request for the ListInstanceProfilesForRole operation. -func (c *IAM) ListInstanceProfilesForRoleRequest(input *ListInstanceProfilesForRoleInput) (req *service.Request, output *ListInstanceProfilesForRoleOutput) { - op := &service.Operation{ +func (c *IAM) ListInstanceProfilesForRoleRequest(input *ListInstanceProfilesForRoleInput) (req *request.Request, output *ListInstanceProfilesForRoleOutput) { + op := &request.Operation{ Name: opListInstanceProfilesForRole, HTTPMethod: "POST", HTTPPath: "/", - Paginator: &service.Paginator{ + Paginator: &request.Paginator{ InputTokens: []string{"Marker"}, OutputTokens: []string{"Marker"}, LimitToken: "MaxItems", @@ -2630,12 +2712,12 @@ func (c *IAM) ListInstanceProfilesForRolePages(input *ListInstanceProfilesForRol const opListMFADevices = "ListMFADevices" // ListMFADevicesRequest generates a request for the ListMFADevices operation. -func (c *IAM) ListMFADevicesRequest(input *ListMFADevicesInput) (req *service.Request, output *ListMFADevicesOutput) { - op := &service.Operation{ +func (c *IAM) ListMFADevicesRequest(input *ListMFADevicesInput) (req *request.Request, output *ListMFADevicesOutput) { + op := &request.Operation{ Name: opListMFADevices, HTTPMethod: "POST", HTTPPath: "/", - Paginator: &service.Paginator{ + Paginator: &request.Paginator{ InputTokens: []string{"Marker"}, OutputTokens: []string{"Marker"}, LimitToken: "MaxItems", @@ -2675,8 +2757,8 @@ func (c *IAM) ListMFADevicesPages(input *ListMFADevicesInput, fn func(p *ListMFA const opListOpenIDConnectProviders = "ListOpenIDConnectProviders" // ListOpenIDConnectProvidersRequest generates a request for the ListOpenIDConnectProviders operation. -func (c *IAM) ListOpenIDConnectProvidersRequest(input *ListOpenIDConnectProvidersInput) (req *service.Request, output *ListOpenIDConnectProvidersOutput) { - op := &service.Operation{ +func (c *IAM) ListOpenIDConnectProvidersRequest(input *ListOpenIDConnectProvidersInput) (req *request.Request, output *ListOpenIDConnectProvidersOutput) { + op := &request.Operation{ Name: opListOpenIDConnectProviders, HTTPMethod: "POST", HTTPPath: "/", @@ -2702,12 +2784,12 @@ func (c *IAM) ListOpenIDConnectProviders(input *ListOpenIDConnectProvidersInput) const opListPolicies = "ListPolicies" // ListPoliciesRequest generates a request for the ListPolicies operation. -func (c *IAM) ListPoliciesRequest(input *ListPoliciesInput) (req *service.Request, output *ListPoliciesOutput) { - op := &service.Operation{ +func (c *IAM) ListPoliciesRequest(input *ListPoliciesInput) (req *request.Request, output *ListPoliciesOutput) { + op := &request.Operation{ Name: opListPolicies, HTTPMethod: "POST", HTTPPath: "/", - Paginator: &service.Paginator{ + Paginator: &request.Paginator{ InputTokens: []string{"Marker"}, OutputTokens: []string{"Marker"}, LimitToken: "MaxItems", @@ -2737,7 +2819,7 @@ func (c *IAM) ListPoliciesRequest(input *ListPoliciesInput) (req *service.Reques // // For more information about managed policies, refer to Managed Policies and // Inline Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html) -// in the Using IAM guide. +// in the IAM User Guide. func (c *IAM) ListPolicies(input *ListPoliciesInput) (*ListPoliciesOutput, error) { req, out := c.ListPoliciesRequest(input) err := req.Send() @@ -2754,8 +2836,8 @@ func (c *IAM) ListPoliciesPages(input *ListPoliciesInput, fn func(p *ListPolicie const opListPolicyVersions = "ListPolicyVersions" // ListPolicyVersionsRequest generates a request for the ListPolicyVersions operation. -func (c *IAM) ListPolicyVersionsRequest(input *ListPolicyVersionsInput) (req *service.Request, output *ListPolicyVersionsOutput) { - op := &service.Operation{ +func (c *IAM) ListPolicyVersionsRequest(input *ListPolicyVersionsInput) (req *request.Request, output *ListPolicyVersionsOutput) { + op := &request.Operation{ Name: opListPolicyVersions, HTTPMethod: "POST", HTTPPath: "/", @@ -2776,7 +2858,7 @@ func (c *IAM) ListPolicyVersionsRequest(input *ListPolicyVersionsInput) (req *se // // For more information about managed policies, refer to Managed Policies and // Inline Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html) -// in the Using IAM guide. +// in the IAM User Guide. func (c *IAM) ListPolicyVersions(input *ListPolicyVersionsInput) (*ListPolicyVersionsOutput, error) { req, out := c.ListPolicyVersionsRequest(input) err := req.Send() @@ -2786,12 +2868,12 @@ func (c *IAM) ListPolicyVersions(input *ListPolicyVersionsInput) (*ListPolicyVer const opListRolePolicies = "ListRolePolicies" // ListRolePoliciesRequest generates a request for the ListRolePolicies operation. -func (c *IAM) ListRolePoliciesRequest(input *ListRolePoliciesInput) (req *service.Request, output *ListRolePoliciesOutput) { - op := &service.Operation{ +func (c *IAM) ListRolePoliciesRequest(input *ListRolePoliciesInput) (req *request.Request, output *ListRolePoliciesOutput) { + op := &request.Operation{ Name: opListRolePolicies, HTTPMethod: "POST", HTTPPath: "/", - Paginator: &service.Paginator{ + Paginator: &request.Paginator{ InputTokens: []string{"Marker"}, OutputTokens: []string{"Marker"}, LimitToken: "MaxItems", @@ -2816,7 +2898,7 @@ func (c *IAM) ListRolePoliciesRequest(input *ListRolePoliciesInput) (req *servic // policies that are attached to a role, use ListAttachedRolePolicies. For more // information about policies, refer to Managed Policies and Inline Policies // (http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html) -// in the Using IAM guide. +// in the IAM User Guide. // // You can paginate the results using the MaxItems and Marker parameters. If // there are no inline policies embedded with the specified role, the action @@ -2837,12 +2919,12 @@ func (c *IAM) ListRolePoliciesPages(input *ListRolePoliciesInput, fn func(p *Lis const opListRoles = "ListRoles" // ListRolesRequest generates a request for the ListRoles operation. -func (c *IAM) ListRolesRequest(input *ListRolesInput) (req *service.Request, output *ListRolesOutput) { - op := &service.Operation{ +func (c *IAM) ListRolesRequest(input *ListRolesInput) (req *request.Request, output *ListRolesOutput) { + op := &request.Operation{ Name: opListRoles, HTTPMethod: "POST", HTTPPath: "/", - Paginator: &service.Paginator{ + Paginator: &request.Paginator{ InputTokens: []string{"Marker"}, OutputTokens: []string{"Marker"}, LimitToken: "MaxItems", @@ -2881,8 +2963,8 @@ func (c *IAM) ListRolesPages(input *ListRolesInput, fn func(p *ListRolesOutput, const opListSAMLProviders = "ListSAMLProviders" // ListSAMLProvidersRequest generates a request for the ListSAMLProviders operation. -func (c *IAM) ListSAMLProvidersRequest(input *ListSAMLProvidersInput) (req *service.Request, output *ListSAMLProvidersOutput) { - op := &service.Operation{ +func (c *IAM) ListSAMLProvidersRequest(input *ListSAMLProvidersInput) (req *request.Request, output *ListSAMLProvidersOutput) { + op := &request.Operation{ Name: opListSAMLProviders, HTTPMethod: "POST", HTTPPath: "/", @@ -2910,8 +2992,8 @@ func (c *IAM) ListSAMLProviders(input *ListSAMLProvidersInput) (*ListSAMLProvide const opListSSHPublicKeys = "ListSSHPublicKeys" // ListSSHPublicKeysRequest generates a request for the ListSSHPublicKeys operation. -func (c *IAM) ListSSHPublicKeysRequest(input *ListSSHPublicKeysInput) (req *service.Request, output *ListSSHPublicKeysOutput) { - op := &service.Operation{ +func (c *IAM) ListSSHPublicKeysRequest(input *ListSSHPublicKeysInput) (req *request.Request, output *ListSSHPublicKeysOutput) { + op := &request.Operation{ Name: opListSSHPublicKeys, HTTPMethod: "POST", HTTPPath: "/", @@ -2947,12 +3029,12 @@ func (c *IAM) ListSSHPublicKeys(input *ListSSHPublicKeysInput) (*ListSSHPublicKe const opListServerCertificates = "ListServerCertificates" // ListServerCertificatesRequest generates a request for the ListServerCertificates operation. -func (c *IAM) ListServerCertificatesRequest(input *ListServerCertificatesInput) (req *service.Request, output *ListServerCertificatesOutput) { - op := &service.Operation{ +func (c *IAM) ListServerCertificatesRequest(input *ListServerCertificatesInput) (req *request.Request, output *ListServerCertificatesOutput) { + op := &request.Operation{ Name: opListServerCertificates, HTTPMethod: "POST", HTTPPath: "/", - Paginator: &service.Paginator{ + Paginator: &request.Paginator{ InputTokens: []string{"Marker"}, OutputTokens: []string{"Marker"}, LimitToken: "MaxItems", @@ -2990,12 +3072,12 @@ func (c *IAM) ListServerCertificatesPages(input *ListServerCertificatesInput, fn const opListSigningCertificates = "ListSigningCertificates" // ListSigningCertificatesRequest generates a request for the ListSigningCertificates operation. -func (c *IAM) ListSigningCertificatesRequest(input *ListSigningCertificatesInput) (req *service.Request, output *ListSigningCertificatesOutput) { - op := &service.Operation{ +func (c *IAM) ListSigningCertificatesRequest(input *ListSigningCertificatesInput) (req *request.Request, output *ListSigningCertificatesOutput) { + op := &request.Operation{ Name: opListSigningCertificates, HTTPMethod: "POST", HTTPPath: "/", - Paginator: &service.Paginator{ + Paginator: &request.Paginator{ InputTokens: []string{"Marker"}, OutputTokens: []string{"Marker"}, LimitToken: "MaxItems", @@ -3039,12 +3121,12 @@ func (c *IAM) ListSigningCertificatesPages(input *ListSigningCertificatesInput, const opListUserPolicies = "ListUserPolicies" // ListUserPoliciesRequest generates a request for the ListUserPolicies operation. -func (c *IAM) ListUserPoliciesRequest(input *ListUserPoliciesInput) (req *service.Request, output *ListUserPoliciesOutput) { - op := &service.Operation{ +func (c *IAM) ListUserPoliciesRequest(input *ListUserPoliciesInput) (req *request.Request, output *ListUserPoliciesOutput) { + op := &request.Operation{ Name: opListUserPolicies, HTTPMethod: "POST", HTTPPath: "/", - Paginator: &service.Paginator{ + Paginator: &request.Paginator{ InputTokens: []string{"Marker"}, OutputTokens: []string{"Marker"}, LimitToken: "MaxItems", @@ -3068,7 +3150,7 @@ func (c *IAM) ListUserPoliciesRequest(input *ListUserPoliciesInput) (req *servic // policies that are attached to a user, use ListAttachedUserPolicies. For more // information about policies, refer to Managed Policies and Inline Policies // (http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html) -// in the Using IAM guide. +// in the IAM User Guide. // // You can paginate the results using the MaxItems and Marker parameters. If // there are no inline policies embedded with the specified user, the action @@ -3089,12 +3171,12 @@ func (c *IAM) ListUserPoliciesPages(input *ListUserPoliciesInput, fn func(p *Lis const opListUsers = "ListUsers" // ListUsersRequest generates a request for the ListUsers operation. -func (c *IAM) ListUsersRequest(input *ListUsersInput) (req *service.Request, output *ListUsersOutput) { - op := &service.Operation{ +func (c *IAM) ListUsersRequest(input *ListUsersInput) (req *request.Request, output *ListUsersOutput) { + op := &request.Operation{ Name: opListUsers, HTTPMethod: "POST", HTTPPath: "/", - Paginator: &service.Paginator{ + Paginator: &request.Paginator{ InputTokens: []string{"Marker"}, OutputTokens: []string{"Marker"}, LimitToken: "MaxItems", @@ -3133,12 +3215,12 @@ func (c *IAM) ListUsersPages(input *ListUsersInput, fn func(p *ListUsersOutput, const opListVirtualMFADevices = "ListVirtualMFADevices" // ListVirtualMFADevicesRequest generates a request for the ListVirtualMFADevices operation. -func (c *IAM) ListVirtualMFADevicesRequest(input *ListVirtualMFADevicesInput) (req *service.Request, output *ListVirtualMFADevicesOutput) { - op := &service.Operation{ +func (c *IAM) ListVirtualMFADevicesRequest(input *ListVirtualMFADevicesInput) (req *request.Request, output *ListVirtualMFADevicesOutput) { + op := &request.Operation{ Name: opListVirtualMFADevices, HTTPMethod: "POST", HTTPPath: "/", - Paginator: &service.Paginator{ + Paginator: &request.Paginator{ InputTokens: []string{"Marker"}, OutputTokens: []string{"Marker"}, LimitToken: "MaxItems", @@ -3178,8 +3260,8 @@ func (c *IAM) ListVirtualMFADevicesPages(input *ListVirtualMFADevicesInput, fn f const opPutGroupPolicy = "PutGroupPolicy" // PutGroupPolicyRequest generates a request for the PutGroupPolicy operation. -func (c *IAM) PutGroupPolicyRequest(input *PutGroupPolicyInput) (req *service.Request, output *PutGroupPolicyOutput) { - op := &service.Operation{ +func (c *IAM) PutGroupPolicyRequest(input *PutGroupPolicyInput) (req *request.Request, output *PutGroupPolicyOutput) { + op := &request.Operation{ Name: opPutGroupPolicy, HTTPMethod: "POST", HTTPPath: "/", @@ -3202,11 +3284,11 @@ func (c *IAM) PutGroupPolicyRequest(input *PutGroupPolicyInput) (req *service.Re // policy to a group, use AttachGroupPolicy. To create a new managed policy, // use CreatePolicy. For information about policies, refer to Managed Policies // and Inline Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html) -// in the Using IAM guide. +// in the IAM User Guide. // // For information about limits on the number of inline policies that you can // embed in a group, see Limitations on IAM Entities (http://docs.aws.amazon.com/IAM/latest/UserGuide/LimitationsOnEntities.html) -// in the Using IAM guide. +// in the IAM User Guide. // // Because policy documents can be large, you should use POST rather than GET // when calling PutGroupPolicy. For general information about using the Query @@ -3221,8 +3303,8 @@ func (c *IAM) PutGroupPolicy(input *PutGroupPolicyInput) (*PutGroupPolicyOutput, const opPutRolePolicy = "PutRolePolicy" // PutRolePolicyRequest generates a request for the PutRolePolicy operation. -func (c *IAM) PutRolePolicyRequest(input *PutRolePolicyInput) (req *service.Request, output *PutRolePolicyOutput) { - op := &service.Operation{ +func (c *IAM) PutRolePolicyRequest(input *PutRolePolicyInput) (req *request.Request, output *PutRolePolicyOutput) { + op := &request.Operation{ Name: opPutRolePolicy, HTTPMethod: "POST", HTTPPath: "/", @@ -3251,11 +3333,11 @@ func (c *IAM) PutRolePolicyRequest(input *PutRolePolicyInput) (req *service.Requ // policy to a role, use AttachRolePolicy. To create a new managed policy, use // CreatePolicy. For information about policies, refer to Managed Policies and // Inline Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html) -// in the Using IAM guide. +// in the IAM User Guide. // // For information about limits on the number of inline policies that you can // embed with a role, see Limitations on IAM Entities (http://docs.aws.amazon.com/IAM/latest/UserGuide/LimitationsOnEntities.html) -// in the Using IAM guide. +// in the IAM User Guide. // // Because policy documents can be large, you should use POST rather than GET // when calling PutRolePolicy. For general information about using the Query @@ -3270,8 +3352,8 @@ func (c *IAM) PutRolePolicy(input *PutRolePolicyInput) (*PutRolePolicyOutput, er const opPutUserPolicy = "PutUserPolicy" // PutUserPolicyRequest generates a request for the PutUserPolicy operation. -func (c *IAM) PutUserPolicyRequest(input *PutUserPolicyInput) (req *service.Request, output *PutUserPolicyOutput) { - op := &service.Operation{ +func (c *IAM) PutUserPolicyRequest(input *PutUserPolicyInput) (req *request.Request, output *PutUserPolicyOutput) { + op := &request.Operation{ Name: opPutUserPolicy, HTTPMethod: "POST", HTTPPath: "/", @@ -3294,11 +3376,11 @@ func (c *IAM) PutUserPolicyRequest(input *PutUserPolicyInput) (req *service.Requ // policy to a user, use AttachUserPolicy. To create a new managed policy, use // CreatePolicy. For information about policies, refer to Managed Policies and // Inline Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html) -// in the Using IAM guide. +// in the IAM User Guide. // // For information about limits on the number of inline policies that you can // embed in a user, see Limitations on IAM Entities (http://docs.aws.amazon.com/IAM/latest/UserGuide/LimitationsOnEntities.html) -// in the Using IAM guide. +// in the IAM User Guide. // // Because policy documents can be large, you should use POST rather than GET // when calling PutUserPolicy. For general information about using the Query @@ -3313,8 +3395,8 @@ func (c *IAM) PutUserPolicy(input *PutUserPolicyInput) (*PutUserPolicyOutput, er const opRemoveClientIDFromOpenIDConnectProvider = "RemoveClientIDFromOpenIDConnectProvider" // RemoveClientIDFromOpenIDConnectProviderRequest generates a request for the RemoveClientIDFromOpenIDConnectProvider operation. -func (c *IAM) RemoveClientIDFromOpenIDConnectProviderRequest(input *RemoveClientIDFromOpenIDConnectProviderInput) (req *service.Request, output *RemoveClientIDFromOpenIDConnectProviderOutput) { - op := &service.Operation{ +func (c *IAM) RemoveClientIDFromOpenIDConnectProviderRequest(input *RemoveClientIDFromOpenIDConnectProviderInput) (req *request.Request, output *RemoveClientIDFromOpenIDConnectProviderOutput) { + op := &request.Operation{ Name: opRemoveClientIDFromOpenIDConnectProvider, HTTPMethod: "POST", HTTPPath: "/", @@ -3344,8 +3426,8 @@ func (c *IAM) RemoveClientIDFromOpenIDConnectProvider(input *RemoveClientIDFromO const opRemoveRoleFromInstanceProfile = "RemoveRoleFromInstanceProfile" // RemoveRoleFromInstanceProfileRequest generates a request for the RemoveRoleFromInstanceProfile operation. -func (c *IAM) RemoveRoleFromInstanceProfileRequest(input *RemoveRoleFromInstanceProfileInput) (req *service.Request, output *RemoveRoleFromInstanceProfileOutput) { - op := &service.Operation{ +func (c *IAM) RemoveRoleFromInstanceProfileRequest(input *RemoveRoleFromInstanceProfileInput) (req *request.Request, output *RemoveRoleFromInstanceProfileOutput) { + op := &request.Operation{ Name: opRemoveRoleFromInstanceProfile, HTTPMethod: "POST", HTTPPath: "/", @@ -3379,8 +3461,8 @@ func (c *IAM) RemoveRoleFromInstanceProfile(input *RemoveRoleFromInstanceProfile const opRemoveUserFromGroup = "RemoveUserFromGroup" // RemoveUserFromGroupRequest generates a request for the RemoveUserFromGroup operation. -func (c *IAM) RemoveUserFromGroupRequest(input *RemoveUserFromGroupInput) (req *service.Request, output *RemoveUserFromGroupOutput) { - op := &service.Operation{ +func (c *IAM) RemoveUserFromGroupRequest(input *RemoveUserFromGroupInput) (req *request.Request, output *RemoveUserFromGroupOutput) { + op := &request.Operation{ Name: opRemoveUserFromGroup, HTTPMethod: "POST", HTTPPath: "/", @@ -3406,8 +3488,8 @@ func (c *IAM) RemoveUserFromGroup(input *RemoveUserFromGroupInput) (*RemoveUserF const opResyncMFADevice = "ResyncMFADevice" // ResyncMFADeviceRequest generates a request for the ResyncMFADevice operation. -func (c *IAM) ResyncMFADeviceRequest(input *ResyncMFADeviceInput) (req *service.Request, output *ResyncMFADeviceOutput) { - op := &service.Operation{ +func (c *IAM) ResyncMFADeviceRequest(input *ResyncMFADeviceInput) (req *request.Request, output *ResyncMFADeviceOutput) { + op := &request.Operation{ Name: opResyncMFADevice, HTTPMethod: "POST", HTTPPath: "/", @@ -3437,8 +3519,8 @@ func (c *IAM) ResyncMFADevice(input *ResyncMFADeviceInput) (*ResyncMFADeviceOutp const opSetDefaultPolicyVersion = "SetDefaultPolicyVersion" // SetDefaultPolicyVersionRequest generates a request for the SetDefaultPolicyVersion operation. -func (c *IAM) SetDefaultPolicyVersionRequest(input *SetDefaultPolicyVersionInput) (req *service.Request, output *SetDefaultPolicyVersionOutput) { - op := &service.Operation{ +func (c *IAM) SetDefaultPolicyVersionRequest(input *SetDefaultPolicyVersionInput) (req *request.Request, output *SetDefaultPolicyVersionOutput) { + op := &request.Operation{ Name: opSetDefaultPolicyVersion, HTTPMethod: "POST", HTTPPath: "/", @@ -3463,18 +3545,111 @@ func (c *IAM) SetDefaultPolicyVersionRequest(input *SetDefaultPolicyVersionInput // // For information about managed policies, refer to Managed Policies and Inline // Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html) -// in the Using IAM guide. +// in the IAM User Guide. func (c *IAM) SetDefaultPolicyVersion(input *SetDefaultPolicyVersionInput) (*SetDefaultPolicyVersionOutput, error) { req, out := c.SetDefaultPolicyVersionRequest(input) err := req.Send() return out, err } +const opSimulateCustomPolicy = "SimulateCustomPolicy" + +// SimulateCustomPolicyRequest generates a request for the SimulateCustomPolicy operation. +func (c *IAM) SimulateCustomPolicyRequest(input *SimulateCustomPolicyInput) (req *request.Request, output *SimulatePolicyResponse) { + op := &request.Operation{ + Name: opSimulateCustomPolicy, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &SimulateCustomPolicyInput{} + } + + req = c.newRequest(op, input, output) + output = &SimulatePolicyResponse{} + req.Data = output + return +} + +// Simulate a set of IAM policies against a list of API actions and AWS resources +// to determine the policies' effective permissions. The policies are provided +// as a list of strings. +// +// The simulation does not perform the API actions, it only checks the authorization +// to determine if the simulated policies allow or deny the actions. +// +// If you want to simulate existing policies attached to an IAM user, group, +// or role, use SimulatePrincipalPolicy instead. +// +// Context keys are variables maintained by AWS and its services that provide +// details about the context of an API query request, and can be evaluated by +// using the Condition element of an IAM policy. To get the list of context +// keys required by the policies to simulate them correctly, use GetContextKeysForCustomPolicy. +// +// If the output is long, you can paginate the results using the MaxItems and +// Marker parameters. +func (c *IAM) SimulateCustomPolicy(input *SimulateCustomPolicyInput) (*SimulatePolicyResponse, error) { + req, out := c.SimulateCustomPolicyRequest(input) + err := req.Send() + return out, err +} + +const opSimulatePrincipalPolicy = "SimulatePrincipalPolicy" + +// SimulatePrincipalPolicyRequest generates a request for the SimulatePrincipalPolicy operation. +func (c *IAM) SimulatePrincipalPolicyRequest(input *SimulatePrincipalPolicyInput) (req *request.Request, output *SimulatePolicyResponse) { + op := &request.Operation{ + Name: opSimulatePrincipalPolicy, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &SimulatePrincipalPolicyInput{} + } + + req = c.newRequest(op, input, output) + output = &SimulatePolicyResponse{} + req.Data = output + return +} + +// Simulate the set of IAM policies attached to an IAM entity against a list +// of API actions and AWS resources to determine the policies' effective permissions. +// The entity can be an IAM user, group, or role. If you specify a user, then +// the simulation also includes all of the policies attached to groups that +// the user is a member of. +// +// You can optionally include a list of one or more additional policies specified +// as strings to include in the simulation. If you want to simulate only policies +// specified as strings, use SimulateCustomPolicy instead. +// +// The simulation does not perform the API actions, it only checks the authorization +// to determine if the simulated policies allow or deny the actions. +// +// Note: This API discloses information about the permissions granted to other +// users. If you do not want users to see other user's permissions, then consider +// allowing them to use SimulateCustomPolicy instead. +// +// Context keys are variables maintained by AWS and its services that provide +// details about the context of an API query request, and can be evaluated by +// using the Condition element of an IAM policy. To get the list of context +// keys required by the policies to simulate them correctly, use GetContextKeysForPrincipalPolicy. +// +// If the output is long, you can paginate the results using the MaxItems and +// Marker parameters. +func (c *IAM) SimulatePrincipalPolicy(input *SimulatePrincipalPolicyInput) (*SimulatePolicyResponse, error) { + req, out := c.SimulatePrincipalPolicyRequest(input) + err := req.Send() + return out, err +} + const opUpdateAccessKey = "UpdateAccessKey" // UpdateAccessKeyRequest generates a request for the UpdateAccessKey operation. -func (c *IAM) UpdateAccessKeyRequest(input *UpdateAccessKeyInput) (req *service.Request, output *UpdateAccessKeyOutput) { - op := &service.Operation{ +func (c *IAM) UpdateAccessKeyRequest(input *UpdateAccessKeyInput) (req *request.Request, output *UpdateAccessKeyOutput) { + op := &request.Operation{ Name: opUpdateAccessKey, HTTPMethod: "POST", HTTPPath: "/", @@ -3501,7 +3676,7 @@ func (c *IAM) UpdateAccessKeyRequest(input *UpdateAccessKeyInput) (req *service. // // For information about rotating keys, see Managing Keys and Certificates // (http://docs.aws.amazon.com/IAM/latest/UserGuide/ManagingCredentials.html) -// in the Using IAM guide. +// in the IAM User Guide. func (c *IAM) UpdateAccessKey(input *UpdateAccessKeyInput) (*UpdateAccessKeyOutput, error) { req, out := c.UpdateAccessKeyRequest(input) err := req.Send() @@ -3511,8 +3686,8 @@ func (c *IAM) UpdateAccessKey(input *UpdateAccessKeyInput) (*UpdateAccessKeyOutp const opUpdateAccountPasswordPolicy = "UpdateAccountPasswordPolicy" // UpdateAccountPasswordPolicyRequest generates a request for the UpdateAccountPasswordPolicy operation. -func (c *IAM) UpdateAccountPasswordPolicyRequest(input *UpdateAccountPasswordPolicyInput) (req *service.Request, output *UpdateAccountPasswordPolicyOutput) { - op := &service.Operation{ +func (c *IAM) UpdateAccountPasswordPolicyRequest(input *UpdateAccountPasswordPolicyInput) (req *request.Request, output *UpdateAccountPasswordPolicyOutput) { + op := &request.Operation{ Name: opUpdateAccountPasswordPolicy, HTTPMethod: "POST", HTTPPath: "/", @@ -3537,7 +3712,7 @@ func (c *IAM) UpdateAccountPasswordPolicyRequest(input *UpdateAccountPasswordPol // // For more information about using a password policy, see Managing an IAM // Password Policy (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_ManagingPasswordPolicies.html) -// in the Using IAM guide. +// in the IAM User Guide. func (c *IAM) UpdateAccountPasswordPolicy(input *UpdateAccountPasswordPolicyInput) (*UpdateAccountPasswordPolicyOutput, error) { req, out := c.UpdateAccountPasswordPolicyRequest(input) err := req.Send() @@ -3547,8 +3722,8 @@ func (c *IAM) UpdateAccountPasswordPolicy(input *UpdateAccountPasswordPolicyInpu const opUpdateAssumeRolePolicy = "UpdateAssumeRolePolicy" // UpdateAssumeRolePolicyRequest generates a request for the UpdateAssumeRolePolicy operation. -func (c *IAM) UpdateAssumeRolePolicyRequest(input *UpdateAssumeRolePolicyInput) (req *service.Request, output *UpdateAssumeRolePolicyOutput) { - op := &service.Operation{ +func (c *IAM) UpdateAssumeRolePolicyRequest(input *UpdateAssumeRolePolicyInput) (req *request.Request, output *UpdateAssumeRolePolicyOutput) { + op := &request.Operation{ Name: opUpdateAssumeRolePolicy, HTTPMethod: "POST", HTTPPath: "/", @@ -3576,8 +3751,8 @@ func (c *IAM) UpdateAssumeRolePolicy(input *UpdateAssumeRolePolicyInput) (*Updat const opUpdateGroup = "UpdateGroup" // UpdateGroupRequest generates a request for the UpdateGroup operation. -func (c *IAM) UpdateGroupRequest(input *UpdateGroupInput) (req *service.Request, output *UpdateGroupOutput) { - op := &service.Operation{ +func (c *IAM) UpdateGroupRequest(input *UpdateGroupInput) (req *request.Request, output *UpdateGroupOutput) { + op := &request.Operation{ Name: opUpdateGroup, HTTPMethod: "POST", HTTPPath: "/", @@ -3597,7 +3772,7 @@ func (c *IAM) UpdateGroupRequest(input *UpdateGroupInput) (req *service.Request, // // You should understand the implications of changing a group's path or name. // For more information, see Renaming Users and Groups (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_WorkingWithGroupsAndUsers.html) -// in the Using IAM guide. To change a group name the requester must have appropriate +// in the IAM User Guide. To change a group name the requester must have appropriate // permissions on both the source object and the target object. For example, // to change Managers to MGRs, the entity making the request must have permission // on Managers and MGRs, or must have permission on all (*). For more information @@ -3612,8 +3787,8 @@ func (c *IAM) UpdateGroup(input *UpdateGroupInput) (*UpdateGroupOutput, error) { const opUpdateLoginProfile = "UpdateLoginProfile" // UpdateLoginProfileRequest generates a request for the UpdateLoginProfile operation. -func (c *IAM) UpdateLoginProfileRequest(input *UpdateLoginProfileInput) (req *service.Request, output *UpdateLoginProfileOutput) { - op := &service.Operation{ +func (c *IAM) UpdateLoginProfileRequest(input *UpdateLoginProfileInput) (req *request.Request, output *UpdateLoginProfileOutput) { + op := &request.Operation{ Name: opUpdateLoginProfile, HTTPMethod: "POST", HTTPPath: "/", @@ -3633,7 +3808,7 @@ func (c *IAM) UpdateLoginProfileRequest(input *UpdateLoginProfileInput) (req *se // // Users can change their own passwords by calling ChangePassword. For more // information about modifying passwords, see Managing Passwords (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_ManagingLogins.html) -// in the Using IAM guide. +// in the IAM User Guide. func (c *IAM) UpdateLoginProfile(input *UpdateLoginProfileInput) (*UpdateLoginProfileOutput, error) { req, out := c.UpdateLoginProfileRequest(input) err := req.Send() @@ -3643,8 +3818,8 @@ func (c *IAM) UpdateLoginProfile(input *UpdateLoginProfileInput) (*UpdateLoginPr const opUpdateOpenIDConnectProviderThumbprint = "UpdateOpenIDConnectProviderThumbprint" // UpdateOpenIDConnectProviderThumbprintRequest generates a request for the UpdateOpenIDConnectProviderThumbprint operation. -func (c *IAM) UpdateOpenIDConnectProviderThumbprintRequest(input *UpdateOpenIDConnectProviderThumbprintInput) (req *service.Request, output *UpdateOpenIDConnectProviderThumbprintOutput) { - op := &service.Operation{ +func (c *IAM) UpdateOpenIDConnectProviderThumbprintRequest(input *UpdateOpenIDConnectProviderThumbprintInput) (req *request.Request, output *UpdateOpenIDConnectProviderThumbprintOutput) { + op := &request.Operation{ Name: opUpdateOpenIDConnectProviderThumbprint, HTTPMethod: "POST", HTTPPath: "/", @@ -3683,8 +3858,8 @@ func (c *IAM) UpdateOpenIDConnectProviderThumbprint(input *UpdateOpenIDConnectPr const opUpdateSAMLProvider = "UpdateSAMLProvider" // UpdateSAMLProviderRequest generates a request for the UpdateSAMLProvider operation. -func (c *IAM) UpdateSAMLProviderRequest(input *UpdateSAMLProviderInput) (req *service.Request, output *UpdateSAMLProviderOutput) { - op := &service.Operation{ +func (c *IAM) UpdateSAMLProviderRequest(input *UpdateSAMLProviderInput) (req *request.Request, output *UpdateSAMLProviderOutput) { + op := &request.Operation{ Name: opUpdateSAMLProvider, HTTPMethod: "POST", HTTPPath: "/", @@ -3712,8 +3887,8 @@ func (c *IAM) UpdateSAMLProvider(input *UpdateSAMLProviderInput) (*UpdateSAMLPro const opUpdateSSHPublicKey = "UpdateSSHPublicKey" // UpdateSSHPublicKeyRequest generates a request for the UpdateSSHPublicKey operation. -func (c *IAM) UpdateSSHPublicKeyRequest(input *UpdateSSHPublicKeyInput) (req *service.Request, output *UpdateSSHPublicKeyOutput) { - op := &service.Operation{ +func (c *IAM) UpdateSSHPublicKeyRequest(input *UpdateSSHPublicKeyInput) (req *request.Request, output *UpdateSSHPublicKeyOutput) { + op := &request.Operation{ Name: opUpdateSSHPublicKey, HTTPMethod: "POST", HTTPPath: "/", @@ -3748,8 +3923,8 @@ func (c *IAM) UpdateSSHPublicKey(input *UpdateSSHPublicKeyInput) (*UpdateSSHPubl const opUpdateServerCertificate = "UpdateServerCertificate" // UpdateServerCertificateRequest generates a request for the UpdateServerCertificate operation. -func (c *IAM) UpdateServerCertificateRequest(input *UpdateServerCertificateInput) (req *service.Request, output *UpdateServerCertificateOutput) { - op := &service.Operation{ +func (c *IAM) UpdateServerCertificateRequest(input *UpdateServerCertificateInput) (req *request.Request, output *UpdateServerCertificateOutput) { + op := &request.Operation{ Name: opUpdateServerCertificate, HTTPMethod: "POST", HTTPPath: "/", @@ -3769,7 +3944,7 @@ func (c *IAM) UpdateServerCertificateRequest(input *UpdateServerCertificateInput // // You should understand the implications of changing a server certificate's // path or name. For more information, see Managing Server Certificates (http://docs.aws.amazon.com/IAM/latest/UserGuide/ManagingServerCerts.html) -// in the Using IAM guide. To change a server certificate name the requester +// in the IAM User Guide. To change a server certificate name the requester // must have appropriate permissions on both the source object and the target // object. For example, to change the name from ProductionCert to ProdCert, // the entity making the request must have permission on ProductionCert and @@ -3785,8 +3960,8 @@ func (c *IAM) UpdateServerCertificate(input *UpdateServerCertificateInput) (*Upd const opUpdateSigningCertificate = "UpdateSigningCertificate" // UpdateSigningCertificateRequest generates a request for the UpdateSigningCertificate operation. -func (c *IAM) UpdateSigningCertificateRequest(input *UpdateSigningCertificateInput) (req *service.Request, output *UpdateSigningCertificateOutput) { - op := &service.Operation{ +func (c *IAM) UpdateSigningCertificateRequest(input *UpdateSigningCertificateInput) (req *request.Request, output *UpdateSigningCertificateOutput) { + op := &request.Operation{ Name: opUpdateSigningCertificate, HTTPMethod: "POST", HTTPPath: "/", @@ -3819,8 +3994,8 @@ func (c *IAM) UpdateSigningCertificate(input *UpdateSigningCertificateInput) (*U const opUpdateUser = "UpdateUser" // UpdateUserRequest generates a request for the UpdateUser operation. -func (c *IAM) UpdateUserRequest(input *UpdateUserInput) (req *service.Request, output *UpdateUserOutput) { - op := &service.Operation{ +func (c *IAM) UpdateUserRequest(input *UpdateUserInput) (req *request.Request, output *UpdateUserOutput) { + op := &request.Operation{ Name: opUpdateUser, HTTPMethod: "POST", HTTPPath: "/", @@ -3840,7 +4015,7 @@ func (c *IAM) UpdateUserRequest(input *UpdateUserInput) (req *service.Request, o // // You should understand the implications of changing a user's path or name. // For more information, see Renaming Users and Groups (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_WorkingWithGroupsAndUsers.html) -// in the Using IAM guide. To change a user name the requester must have appropriate +// in the IAM User Guide. To change a user name the requester must have appropriate // permissions on both the source object and the target object. For example, // to change Bob to Robert, the entity making the request must have permission // on Bob and Robert, or must have permission on all (*). For more information @@ -3855,8 +4030,8 @@ func (c *IAM) UpdateUser(input *UpdateUserInput) (*UpdateUserOutput, error) { const opUploadSSHPublicKey = "UploadSSHPublicKey" // UploadSSHPublicKeyRequest generates a request for the UploadSSHPublicKey operation. -func (c *IAM) UploadSSHPublicKeyRequest(input *UploadSSHPublicKeyInput) (req *service.Request, output *UploadSSHPublicKeyOutput) { - op := &service.Operation{ +func (c *IAM) UploadSSHPublicKeyRequest(input *UploadSSHPublicKeyInput) (req *request.Request, output *UploadSSHPublicKeyOutput) { + op := &request.Operation{ Name: opUploadSSHPublicKey, HTTPMethod: "POST", HTTPPath: "/", @@ -3888,8 +4063,8 @@ func (c *IAM) UploadSSHPublicKey(input *UploadSSHPublicKeyInput) (*UploadSSHPubl const opUploadServerCertificate = "UploadServerCertificate" // UploadServerCertificateRequest generates a request for the UploadServerCertificate operation. -func (c *IAM) UploadServerCertificateRequest(input *UploadServerCertificateInput) (req *service.Request, output *UploadServerCertificateOutput) { - op := &service.Operation{ +func (c *IAM) UploadServerCertificateRequest(input *UploadServerCertificateInput) (req *request.Request, output *UploadServerCertificateOutput) { + op := &request.Operation{ Name: opUploadServerCertificate, HTTPMethod: "POST", HTTPPath: "/", @@ -3911,7 +4086,7 @@ func (c *IAM) UploadServerCertificateRequest(input *UploadServerCertificateInput // // For information about the number of server certificates you can upload, // see Limitations on IAM Entities (http://docs.aws.amazon.com/IAM/latest/UserGuide/LimitationsOnEntities.html) -// in the Using IAM guide. +// in the IAM User Guide. // // Because the body of the public key certificate, private key, and the certificate // chain can be large, you should use POST rather than GET when calling UploadServerCertificate. @@ -3919,7 +4094,7 @@ func (c *IAM) UploadServerCertificateRequest(input *UploadServerCertificateInput // API, go to Signing AWS API Requests (http://docs.aws.amazon.com/general/latest/gr/signing_aws_api_requests.html) // in the AWS General Reference. For general information about using the Query // API with IAM, go to Making Query Requests (http://docs.aws.amazon.com/IAM/latest/UserGuide/IAM_UsingQueryAPI.html) -// in the Using IAM guide. +// in the IAM User Guide. func (c *IAM) UploadServerCertificate(input *UploadServerCertificateInput) (*UploadServerCertificateOutput, error) { req, out := c.UploadServerCertificateRequest(input) err := req.Send() @@ -3929,8 +4104,8 @@ func (c *IAM) UploadServerCertificate(input *UploadServerCertificateInput) (*Upl const opUploadSigningCertificate = "UploadSigningCertificate" // UploadSigningCertificateRequest generates a request for the UploadSigningCertificate operation. -func (c *IAM) UploadSigningCertificateRequest(input *UploadSigningCertificateInput) (req *service.Request, output *UploadSigningCertificateOutput) { - op := &service.Operation{ +func (c *IAM) UploadSigningCertificateRequest(input *UploadSigningCertificateInput) (req *request.Request, output *UploadSigningCertificateOutput) { + op := &request.Operation{ Name: opUploadSigningCertificate, HTTPMethod: "POST", HTTPPath: "/", @@ -3980,7 +4155,7 @@ func (c *IAM) UploadSigningCertificate(input *UploadSigningCertificateInput) (*U // key, you must create a new access key. type AccessKey struct { // The ID for this access key. - AccessKeyId *string `type:"string" required:"true"` + AccessKeyId *string `min:"16" type:"string" required:"true"` // The date when the access key was created. CreateDate *time.Time `type:"timestamp" timestampFormat:"iso8601"` @@ -3993,7 +4168,7 @@ type AccessKey struct { Status *string `type:"string" required:"true" enum:"statusType"` // The name of the IAM user that the access key is associated with. - UserName *string `type:"string" required:"true"` + UserName *string `min:"1" type:"string" required:"true"` metadataAccessKey `json:"-" xml:"-"` } @@ -4075,7 +4250,7 @@ func (s AccessKeyLastUsed) GoString() string { // This data type is used as a response element in the ListAccessKeys action. type AccessKeyMetadata struct { // The ID for this access key. - AccessKeyId *string `type:"string"` + AccessKeyId *string `min:"16" type:"string"` // The date when the access key was created. CreateDate *time.Time `type:"timestamp" timestampFormat:"iso8601"` @@ -4085,7 +4260,7 @@ type AccessKeyMetadata struct { Status *string `type:"string" enum:"statusType"` // The name of the IAM user that the key is associated with. - UserName *string `type:"string"` + UserName *string `min:"1" type:"string"` metadataAccessKeyMetadata `json:"-" xml:"-"` } @@ -4106,12 +4281,12 @@ func (s AccessKeyMetadata) GoString() string { type AddClientIDToOpenIDConnectProviderInput struct { // The client ID (also known as audience) to add to the IAM OpenID Connect provider. - ClientID *string `type:"string" required:"true"` + ClientID *string `min:"1" type:"string" required:"true"` // The Amazon Resource Name (ARN) of the IAM OpenID Connect (OIDC) provider // to add the client ID to. You can get a list of OIDC provider ARNs by using // the ListOpenIDConnectProviders action. - OpenIDConnectProviderArn *string `type:"string" required:"true"` + OpenIDConnectProviderArn *string `min:"20" type:"string" required:"true"` metadataAddClientIDToOpenIDConnectProviderInput `json:"-" xml:"-"` } @@ -4150,10 +4325,10 @@ func (s AddClientIDToOpenIDConnectProviderOutput) GoString() string { type AddRoleToInstanceProfileInput struct { // The name of the instance profile to update. - InstanceProfileName *string `type:"string" required:"true"` + InstanceProfileName *string `min:"1" type:"string" required:"true"` // The name of the role to add. - RoleName *string `type:"string" required:"true"` + RoleName *string `min:"1" type:"string" required:"true"` metadataAddRoleToInstanceProfileInput `json:"-" xml:"-"` } @@ -4192,10 +4367,10 @@ func (s AddRoleToInstanceProfileOutput) GoString() string { type AddUserToGroupInput struct { // The name of the group to update. - GroupName *string `type:"string" required:"true"` + GroupName *string `min:"1" type:"string" required:"true"` // The name of the user to add. - UserName *string `type:"string" required:"true"` + UserName *string `min:"1" type:"string" required:"true"` metadataAddUserToGroupInput `json:"-" xml:"-"` } @@ -4234,14 +4409,14 @@ func (s AddUserToGroupOutput) GoString() string { type AttachGroupPolicyInput struct { // The name (friendly name, not ARN) of the group to attach the policy to. - GroupName *string `type:"string" required:"true"` + GroupName *string `min:"1" type:"string" required:"true"` // The Amazon Resource Name (ARN). ARNs are unique identifiers for AWS resources. // // For more information about ARNs, go to Amazon Resource Names (ARNs) and // AWS Service Namespaces (http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) // in the AWS General Reference. - PolicyArn *string `type:"string" required:"true"` + PolicyArn *string `min:"20" type:"string" required:"true"` metadataAttachGroupPolicyInput `json:"-" xml:"-"` } @@ -4284,10 +4459,10 @@ type AttachRolePolicyInput struct { // For more information about ARNs, go to Amazon Resource Names (ARNs) and // AWS Service Namespaces (http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) // in the AWS General Reference. - PolicyArn *string `type:"string" required:"true"` + PolicyArn *string `min:"20" type:"string" required:"true"` // The name (friendly name, not ARN) of the role to attach the policy to. - RoleName *string `type:"string" required:"true"` + RoleName *string `min:"1" type:"string" required:"true"` metadataAttachRolePolicyInput `json:"-" xml:"-"` } @@ -4330,10 +4505,10 @@ type AttachUserPolicyInput struct { // For more information about ARNs, go to Amazon Resource Names (ARNs) and // AWS Service Namespaces (http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) // in the AWS General Reference. - PolicyArn *string `type:"string" required:"true"` + PolicyArn *string `min:"20" type:"string" required:"true"` // The name (friendly name, not ARN) of the user to attach the policy to. - UserName *string `type:"string" required:"true"` + UserName *string `min:"1" type:"string" required:"true"` metadataAttachUserPolicyInput `json:"-" xml:"-"` } @@ -4386,10 +4561,10 @@ type AttachedPolicy struct { // For more information about ARNs, go to Amazon Resource Names (ARNs) and // AWS Service Namespaces (http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) // in the AWS General Reference. - PolicyArn *string `type:"string"` + PolicyArn *string `min:"20" type:"string"` // The friendly name of the attached policy. - PolicyName *string `type:"string"` + PolicyName *string `min:"1" type:"string"` metadataAttachedPolicy `json:"-" xml:"-"` } @@ -4411,10 +4586,10 @@ func (s AttachedPolicy) GoString() string { type ChangePasswordInput struct { // The new password. The new password must conform to the AWS account's password // policy, if one exists. - NewPassword *string `type:"string" required:"true"` + NewPassword *string `min:"1" type:"string" required:"true"` // The IAM user's current password. - OldPassword *string `type:"string" required:"true"` + OldPassword *string `min:"1" type:"string" required:"true"` metadataChangePasswordInput `json:"-" xml:"-"` } @@ -4451,9 +4626,46 @@ func (s ChangePasswordOutput) GoString() string { return s.String() } +// Contains information about a condition context key. It includes the name +// of the key and specifies the value (or values, if the context key supports +// multiple values) to use in the simulation. This information is used when +// evaluating the Condition elements of the input policies. +// +// This data type is used as an input parameter to SimulatePolicy. +type ContextEntry struct { + // The full name of a condition context key, including the service prefix. For + // example, aws:SourceIp or s3:VersionId. + ContextKeyName *string `min:"5" type:"string"` + + // The data type of the value (or values) specified in the ContextKeyValues + // parameter. + ContextKeyType *string `type:"string" enum:"ContextKeyTypeEnum"` + + // The value (or values, if the condition context key supports multiple values) + // to provide to the simulation for use when the key is referenced by a Condition + // element in an input policy. + ContextKeyValues []*string `type:"list"` + + metadataContextEntry `json:"-" xml:"-"` +} + +type metadataContextEntry struct { + SDKShapeTraits bool `type:"structure"` +} + +// String returns the string representation +func (s ContextEntry) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ContextEntry) GoString() string { + return s.String() +} + type CreateAccessKeyInput struct { // The user name that the new key will belong to. - UserName *string `type:"string"` + UserName *string `min:"1" type:"string"` metadataCreateAccessKeyInput `json:"-" xml:"-"` } @@ -4496,7 +4708,7 @@ func (s CreateAccessKeyOutput) GoString() string { type CreateAccountAliasInput struct { // The account alias to create. - AccountAlias *string `type:"string" required:"true"` + AccountAlias *string `min:"3" type:"string" required:"true"` metadataCreateAccountAliasInput `json:"-" xml:"-"` } @@ -4535,7 +4747,7 @@ func (s CreateAccountAliasOutput) GoString() string { type CreateGroupInput struct { // The name of the group to create. Do not include the path in this value. - GroupName *string `type:"string" required:"true"` + GroupName *string `min:"1" type:"string" required:"true"` // The path to the group. For more information about paths, see IAM Identifiers // (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html) @@ -4543,7 +4755,7 @@ type CreateGroupInput struct { // // This parameter is optional. If it is not included, it defaults to a slash // (/). - Path *string `type:"string"` + Path *string `min:"1" type:"string"` metadataCreateGroupInput `json:"-" xml:"-"` } @@ -4586,7 +4798,7 @@ func (s CreateGroupOutput) GoString() string { type CreateInstanceProfileInput struct { // The name of the instance profile to create. - InstanceProfileName *string `type:"string" required:"true"` + InstanceProfileName *string `min:"1" type:"string" required:"true"` // The path to the instance profile. For more information about paths, see IAM // Identifiers (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html) @@ -4594,7 +4806,7 @@ type CreateInstanceProfileInput struct { // // This parameter is optional. If it is not included, it defaults to a slash // (/). - Path *string `type:"string"` + Path *string `min:"1" type:"string"` metadataCreateInstanceProfileInput `json:"-" xml:"-"` } @@ -4637,13 +4849,13 @@ func (s CreateInstanceProfileOutput) GoString() string { type CreateLoginProfileInput struct { // The new password for the user. - Password *string `type:"string" required:"true"` + Password *string `min:"1" type:"string" required:"true"` // Specifies whether the user is required to set a new password on next sign-in. PasswordResetRequired *bool `type:"boolean"` // The name of the user to create a password for. - UserName *string `type:"string" required:"true"` + UserName *string `min:"1" type:"string" required:"true"` metadataCreateLoginProfileInput `json:"-" xml:"-"` } @@ -4716,7 +4928,7 @@ type CreateOpenIDConnectProviderInput struct { // // For more information about obtaining the OIDC provider's thumbprint, see // Obtaining the Thumbprint for an OpenID Connect Provider (http://docs.aws.amazon.com/IAM/latest/UserGuide/identity-providers-oidc-obtain-thumbprint.html) - // in the Using IAM guide. + // in the IAM User Guide. ThumbprintList []*string `type:"list" required:"true"` // The URL of the identity provider. The URL must begin with "https://" and @@ -4728,7 +4940,7 @@ type CreateOpenIDConnectProviderInput struct { // You cannot register the same provider multiple times in a single AWS account. // If you try to submit a URL that has already been used for an OpenID Connect // provider in the AWS account, you will get an error. - Url *string `type:"string" required:"true"` + Url *string `min:"1" type:"string" required:"true"` metadataCreateOpenIDConnectProviderInput `json:"-" xml:"-"` } @@ -4751,7 +4963,7 @@ func (s CreateOpenIDConnectProviderInput) GoString() string { type CreateOpenIDConnectProviderOutput struct { // The Amazon Resource Name (ARN) of the IAM OpenID Connect provider that was // created. For more information, see OpenIDConnectProviderListEntry. - OpenIDConnectProviderArn *string `type:"string"` + OpenIDConnectProviderArn *string `min:"20" type:"string"` metadataCreateOpenIDConnectProviderOutput `json:"-" xml:"-"` } @@ -4783,17 +4995,17 @@ type CreatePolicyInput struct { // The path for the policy. // // For more information about paths, see IAM Identifiers (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html) - // in the Using IAM guide. + // in the IAM User Guide. // // This parameter is optional. If it is not included, it defaults to a slash // (/). Path *string `type:"string"` // The policy document. - PolicyDocument *string `type:"string" required:"true"` + PolicyDocument *string `min:"1" type:"string" required:"true"` // The name of the policy document. - PolicyName *string `type:"string" required:"true"` + PolicyName *string `min:"1" type:"string" required:"true"` metadataCreatePolicyInput `json:"-" xml:"-"` } @@ -4840,10 +5052,10 @@ type CreatePolicyVersionInput struct { // For more information about ARNs, go to Amazon Resource Names (ARNs) and // AWS Service Namespaces (http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) // in the AWS General Reference. - PolicyArn *string `type:"string" required:"true"` + PolicyArn *string `min:"20" type:"string" required:"true"` // The policy document. - PolicyDocument *string `type:"string" required:"true"` + PolicyDocument *string `min:"1" type:"string" required:"true"` // Specifies whether to set this version as the policy's default version. // @@ -4853,7 +5065,7 @@ type CreatePolicyVersionInput struct { // // For more information about managed policy versions, see Versioning for Managed // Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-versions.html) - // in the Using IAM guide. + // in the IAM User Guide. SetAsDefault *bool `type:"boolean"` metadataCreatePolicyVersionInput `json:"-" xml:"-"` @@ -4897,7 +5109,7 @@ func (s CreatePolicyVersionOutput) GoString() string { type CreateRoleInput struct { // The policy that grants an entity permission to assume the role. - AssumeRolePolicyDocument *string `type:"string" required:"true"` + AssumeRolePolicyDocument *string `min:"1" type:"string" required:"true"` // The path to the role. For more information about paths, see IAM Identifiers // (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html) @@ -4905,10 +5117,10 @@ type CreateRoleInput struct { // // This parameter is optional. If it is not included, it defaults to a slash // (/). - Path *string `type:"string"` + Path *string `min:"1" type:"string"` // The name of the role to create. - RoleName *string `type:"string" required:"true"` + RoleName *string `min:"1" type:"string" required:"true"` metadataCreateRoleInput `json:"-" xml:"-"` } @@ -4951,7 +5163,7 @@ func (s CreateRoleOutput) GoString() string { type CreateSAMLProviderInput struct { // The name of the provider to create. - Name *string `type:"string" required:"true"` + Name *string `min:"1" type:"string" required:"true"` // An XML document generated by an identity provider (IdP) that supports SAML // 2.0. The document includes the issuer's name, expiration information, and @@ -4959,10 +5171,9 @@ type CreateSAMLProviderInput struct { // that are received from the IdP. You must generate the metadata document using // the identity management software that is used as your organization's IdP. // - // For more information, see Creating Temporary Security Credentials for SAML - // Federation (http://docs.aws.amazon.com/STS/latest/UsingSTS/CreatingSAML.html) - // in the Using Temporary Security Credentials guide. - SAMLMetadataDocument *string `type:"string" required:"true"` + // For more information, see About SAML 2.0-based Federation (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_saml.html) + // in the IAM User Guide + SAMLMetadataDocument *string `min:"1000" type:"string" required:"true"` metadataCreateSAMLProviderInput `json:"-" xml:"-"` } @@ -4984,7 +5195,7 @@ func (s CreateSAMLProviderInput) GoString() string { // Contains the response to a successful CreateSAMLProvider request. type CreateSAMLProviderOutput struct { // The Amazon Resource Name (ARN) of the SAML provider. - SAMLProviderArn *string `type:"string"` + SAMLProviderArn *string `min:"20" type:"string"` metadataCreateSAMLProviderOutput `json:"-" xml:"-"` } @@ -5010,10 +5221,10 @@ type CreateUserInput struct { // // This parameter is optional. If it is not included, it defaults to a slash // (/). - Path *string `type:"string"` + Path *string `min:"1" type:"string"` // The name of the user to create. - UserName *string `type:"string" required:"true"` + UserName *string `min:"1" type:"string" required:"true"` metadataCreateUserInput `json:"-" xml:"-"` } @@ -5061,11 +5272,11 @@ type CreateVirtualMFADeviceInput struct { // // This parameter is optional. If it is not included, it defaults to a slash // (/). - Path *string `type:"string"` + Path *string `min:"1" type:"string"` // The name of the virtual MFA device. Use with path to uniquely identify a // virtual MFA device. - VirtualMFADeviceName *string `type:"string" required:"true"` + VirtualMFADeviceName *string `min:"1" type:"string" required:"true"` metadataCreateVirtualMFADeviceInput `json:"-" xml:"-"` } @@ -5109,10 +5320,10 @@ func (s CreateVirtualMFADeviceOutput) GoString() string { type DeactivateMFADeviceInput struct { // The serial number that uniquely identifies the MFA device. For virtual MFA // devices, the serial number is the device ARN. - SerialNumber *string `type:"string" required:"true"` + SerialNumber *string `min:"9" type:"string" required:"true"` // The name of the user whose MFA device you want to deactivate. - UserName *string `type:"string" required:"true"` + UserName *string `min:"1" type:"string" required:"true"` metadataDeactivateMFADeviceInput `json:"-" xml:"-"` } @@ -5152,10 +5363,10 @@ func (s DeactivateMFADeviceOutput) GoString() string { type DeleteAccessKeyInput struct { // The access key ID for the access key ID and secret access key you want to // delete. - AccessKeyId *string `type:"string" required:"true"` + AccessKeyId *string `min:"16" type:"string" required:"true"` // The name of the user whose key you want to delete. - UserName *string `type:"string"` + UserName *string `min:"1" type:"string"` metadataDeleteAccessKeyInput `json:"-" xml:"-"` } @@ -5194,7 +5405,7 @@ func (s DeleteAccessKeyOutput) GoString() string { type DeleteAccountAliasInput struct { // The name of the account alias to delete. - AccountAlias *string `type:"string" required:"true"` + AccountAlias *string `min:"3" type:"string" required:"true"` metadataDeleteAccountAliasInput `json:"-" xml:"-"` } @@ -5269,7 +5480,7 @@ func (s DeleteAccountPasswordPolicyOutput) GoString() string { type DeleteGroupInput struct { // The name of the group to delete. - GroupName *string `type:"string" required:"true"` + GroupName *string `min:"1" type:"string" required:"true"` metadataDeleteGroupInput `json:"-" xml:"-"` } @@ -5309,10 +5520,10 @@ func (s DeleteGroupOutput) GoString() string { type DeleteGroupPolicyInput struct { // The name (friendly name, not ARN) identifying the group that the policy is // embedded in. - GroupName *string `type:"string" required:"true"` + GroupName *string `min:"1" type:"string" required:"true"` // The name identifying the policy document to delete. - PolicyName *string `type:"string" required:"true"` + PolicyName *string `min:"1" type:"string" required:"true"` metadataDeleteGroupPolicyInput `json:"-" xml:"-"` } @@ -5351,7 +5562,7 @@ func (s DeleteGroupPolicyOutput) GoString() string { type DeleteInstanceProfileInput struct { // The name of the instance profile to delete. - InstanceProfileName *string `type:"string" required:"true"` + InstanceProfileName *string `min:"1" type:"string" required:"true"` metadataDeleteInstanceProfileInput `json:"-" xml:"-"` } @@ -5390,7 +5601,7 @@ func (s DeleteInstanceProfileOutput) GoString() string { type DeleteLoginProfileInput struct { // The name of the user whose password you want to delete. - UserName *string `type:"string" required:"true"` + UserName *string `min:"1" type:"string" required:"true"` metadataDeleteLoginProfileInput `json:"-" xml:"-"` } @@ -5431,7 +5642,7 @@ type DeleteOpenIDConnectProviderInput struct { // The Amazon Resource Name (ARN) of the IAM OpenID Connect provider to delete. // You can get a list of OpenID Connect provider ARNs by using the ListOpenIDConnectProviders // action. - OpenIDConnectProviderArn *string `type:"string" required:"true"` + OpenIDConnectProviderArn *string `min:"20" type:"string" required:"true"` metadataDeleteOpenIDConnectProviderInput `json:"-" xml:"-"` } @@ -5474,7 +5685,7 @@ type DeletePolicyInput struct { // For more information about ARNs, go to Amazon Resource Names (ARNs) and // AWS Service Namespaces (http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) // in the AWS General Reference. - PolicyArn *string `type:"string" required:"true"` + PolicyArn *string `min:"20" type:"string" required:"true"` metadataDeletePolicyInput `json:"-" xml:"-"` } @@ -5517,13 +5728,13 @@ type DeletePolicyVersionInput struct { // For more information about ARNs, go to Amazon Resource Names (ARNs) and // AWS Service Namespaces (http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) // in the AWS General Reference. - PolicyArn *string `type:"string" required:"true"` + PolicyArn *string `min:"20" type:"string" required:"true"` // The policy version to delete. // // For more information about managed policy versions, see Versioning for Managed // Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-versions.html) - // in the Using IAM guide. + // in the IAM User Guide. VersionId *string `type:"string" required:"true"` metadataDeletePolicyVersionInput `json:"-" xml:"-"` @@ -5563,7 +5774,7 @@ func (s DeletePolicyVersionOutput) GoString() string { type DeleteRoleInput struct { // The name of the role to delete. - RoleName *string `type:"string" required:"true"` + RoleName *string `min:"1" type:"string" required:"true"` metadataDeleteRoleInput `json:"-" xml:"-"` } @@ -5602,11 +5813,11 @@ func (s DeleteRoleOutput) GoString() string { type DeleteRolePolicyInput struct { // The name identifying the policy document to delete. - PolicyName *string `type:"string" required:"true"` + PolicyName *string `min:"1" type:"string" required:"true"` // The name (friendly name, not ARN) identifying the role that the policy is // embedded in. - RoleName *string `type:"string" required:"true"` + RoleName *string `min:"1" type:"string" required:"true"` metadataDeleteRolePolicyInput `json:"-" xml:"-"` } @@ -5645,7 +5856,7 @@ func (s DeleteRolePolicyOutput) GoString() string { type DeleteSAMLProviderInput struct { // The Amazon Resource Name (ARN) of the SAML provider to delete. - SAMLProviderArn *string `type:"string" required:"true"` + SAMLProviderArn *string `min:"20" type:"string" required:"true"` metadataDeleteSAMLProviderInput `json:"-" xml:"-"` } @@ -5684,10 +5895,10 @@ func (s DeleteSAMLProviderOutput) GoString() string { type DeleteSSHPublicKeyInput struct { // The unique identifier for the SSH public key. - SSHPublicKeyId *string `type:"string" required:"true"` + SSHPublicKeyId *string `min:"20" type:"string" required:"true"` // The name of the IAM user associated with the SSH public key. - UserName *string `type:"string" required:"true"` + UserName *string `min:"1" type:"string" required:"true"` metadataDeleteSSHPublicKeyInput `json:"-" xml:"-"` } @@ -5726,7 +5937,7 @@ func (s DeleteSSHPublicKeyOutput) GoString() string { type DeleteServerCertificateInput struct { // The name of the server certificate you want to delete. - ServerCertificateName *string `type:"string" required:"true"` + ServerCertificateName *string `min:"1" type:"string" required:"true"` metadataDeleteServerCertificateInput `json:"-" xml:"-"` } @@ -5765,10 +5976,10 @@ func (s DeleteServerCertificateOutput) GoString() string { type DeleteSigningCertificateInput struct { // The ID of the signing certificate to delete. - CertificateId *string `type:"string" required:"true"` + CertificateId *string `min:"24" type:"string" required:"true"` // The name of the user the signing certificate belongs to. - UserName *string `type:"string"` + UserName *string `min:"1" type:"string"` metadataDeleteSigningCertificateInput `json:"-" xml:"-"` } @@ -5807,7 +6018,7 @@ func (s DeleteSigningCertificateOutput) GoString() string { type DeleteUserInput struct { // The name of the user to delete. - UserName *string `type:"string" required:"true"` + UserName *string `min:"1" type:"string" required:"true"` metadataDeleteUserInput `json:"-" xml:"-"` } @@ -5846,11 +6057,11 @@ func (s DeleteUserOutput) GoString() string { type DeleteUserPolicyInput struct { // The name identifying the policy document to delete. - PolicyName *string `type:"string" required:"true"` + PolicyName *string `min:"1" type:"string" required:"true"` // The name (friendly name, not ARN) identifying the user that the policy is // embedded in. - UserName *string `type:"string" required:"true"` + UserName *string `min:"1" type:"string" required:"true"` metadataDeleteUserPolicyInput `json:"-" xml:"-"` } @@ -5890,7 +6101,7 @@ func (s DeleteUserPolicyOutput) GoString() string { type DeleteVirtualMFADeviceInput struct { // The serial number that uniquely identifies the MFA device. For virtual MFA // devices, the serial number is the same as the ARN. - SerialNumber *string `type:"string" required:"true"` + SerialNumber *string `min:"9" type:"string" required:"true"` metadataDeleteVirtualMFADeviceInput `json:"-" xml:"-"` } @@ -5929,14 +6140,14 @@ func (s DeleteVirtualMFADeviceOutput) GoString() string { type DetachGroupPolicyInput struct { // The name (friendly name, not ARN) of the group to detach the policy from. - GroupName *string `type:"string" required:"true"` + GroupName *string `min:"1" type:"string" required:"true"` // The Amazon Resource Name (ARN). ARNs are unique identifiers for AWS resources. // // For more information about ARNs, go to Amazon Resource Names (ARNs) and // AWS Service Namespaces (http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) // in the AWS General Reference. - PolicyArn *string `type:"string" required:"true"` + PolicyArn *string `min:"20" type:"string" required:"true"` metadataDetachGroupPolicyInput `json:"-" xml:"-"` } @@ -5979,10 +6190,10 @@ type DetachRolePolicyInput struct { // For more information about ARNs, go to Amazon Resource Names (ARNs) and // AWS Service Namespaces (http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) // in the AWS General Reference. - PolicyArn *string `type:"string" required:"true"` + PolicyArn *string `min:"20" type:"string" required:"true"` // The name (friendly name, not ARN) of the role to detach the policy from. - RoleName *string `type:"string" required:"true"` + RoleName *string `min:"1" type:"string" required:"true"` metadataDetachRolePolicyInput `json:"-" xml:"-"` } @@ -6025,10 +6236,10 @@ type DetachUserPolicyInput struct { // For more information about ARNs, go to Amazon Resource Names (ARNs) and // AWS Service Namespaces (http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) // in the AWS General Reference. - PolicyArn *string `type:"string" required:"true"` + PolicyArn *string `min:"20" type:"string" required:"true"` // The name (friendly name, not ARN) of the user to detach the policy from. - UserName *string `type:"string" required:"true"` + UserName *string `min:"1" type:"string" required:"true"` metadataDetachUserPolicyInput `json:"-" xml:"-"` } @@ -6067,17 +6278,17 @@ func (s DetachUserPolicyOutput) GoString() string { type EnableMFADeviceInput struct { // An authentication code emitted by the device. - AuthenticationCode1 *string `type:"string" required:"true"` + AuthenticationCode1 *string `min:"6" type:"string" required:"true"` // A subsequent authentication code emitted by the device. - AuthenticationCode2 *string `type:"string" required:"true"` + AuthenticationCode2 *string `min:"6" type:"string" required:"true"` // The serial number that uniquely identifies the MFA device. For virtual MFA // devices, the serial number is the device ARN. - SerialNumber *string `type:"string" required:"true"` + SerialNumber *string `min:"9" type:"string" required:"true"` // The name of the user for whom you want to enable the MFA device. - UserName *string `type:"string" required:"true"` + UserName *string `min:"1" type:"string" required:"true"` metadataEnableMFADeviceInput `json:"-" xml:"-"` } @@ -6114,6 +6325,54 @@ func (s EnableMFADeviceOutput) GoString() string { return s.String() } +// Contains the results of a simulation. +// +// This data type is used by the return parameter of SimulatePolicy. +type EvaluationResult struct { + // The name of the API action tested on the indicated resource. + EvalActionName *string `min:"3" type:"string" required:"true"` + + // The result of the simulation. + EvalDecision *string `type:"string" required:"true" enum:"PolicyEvaluationDecisionType"` + + // The ARN of the resource that the indicated API action was tested on. + EvalResourceName *string `min:"1" type:"string" required:"true"` + + // A list of the statements in the input policies that determine the result + // for this scenario. Remember that even if multiple statements allow the action + // on the resource, if only one statement denies that action, then the explicit + // deny overrides any allow, and the deny statement is the only entry included + // in the result. + MatchedStatements []*Statement `type:"list"` + + // A list of context keys that are required by the included input policies but + // that were not provided by one of the input parameters. To discover the context + // keys used by a set of policies, you can call GetContextKeysForCustomPolicy + // or GetContextKeysForPrincipalPolicy. + // + // If the response includes any keys in this list, then the reported results + // might be untrustworthy because the simulation could not completely evaluate + // all of the conditions specified in the policies that would occur in a real + // world request. + MissingContextValues []*string `type:"list"` + + metadataEvaluationResult `json:"-" xml:"-"` +} + +type metadataEvaluationResult struct { + SDKShapeTraits bool `type:"structure"` +} + +// String returns the string representation +func (s EvaluationResult) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s EvaluationResult) GoString() string { + return s.String() +} + type GenerateCredentialReportInput struct { metadataGenerateCredentialReportInput `json:"-" xml:"-"` } @@ -6159,7 +6418,7 @@ func (s GenerateCredentialReportOutput) GoString() string { type GetAccessKeyLastUsedInput struct { // The identifier of an access key. - AccessKeyId *string `type:"string" required:"true"` + AccessKeyId *string `min:"16" type:"string" required:"true"` metadataGetAccessKeyLastUsedInput `json:"-" xml:"-"` } @@ -6186,7 +6445,7 @@ type GetAccessKeyLastUsedOutput struct { AccessKeyLastUsed *AccessKeyLastUsed `type:"structure"` // The name of the AWS IAM user that owns this access key. - UserName *string `type:"string"` + UserName *string `min:"1" type:"string"` metadataGetAccessKeyLastUsedOutput `json:"-" xml:"-"` } @@ -6210,17 +6469,22 @@ type GetAccountAuthorizationDetailsInput struct { // policy) for filtering the results. Filter []*string `type:"list"` - // Use this parameter only when paginating results and only after you have received - // a response where the results are truncated. Set it to the value of the Marker - // element in the response you just received. - Marker *string `type:"string"` + // Use this parameter only when paginating results and only after you receive + // a response indicating that the results are truncated. Set it to the value + // of the Marker element in the response you received to inform the next call + // about where to start. + Marker *string `min:"1" type:"string"` // Use this only when paginating results to indicate the maximum number of items // you want in the response. If there are additional items beyond the maximum // you specify, the IsTruncated response element is true. // // This parameter is optional. If you do not include it, it defaults to 100. - MaxItems *int64 `type:"integer"` + // Note that IAM might return fewer results, even when there are more results + // available. If this is the case, the IsTruncated response element returns + // true and Marker contains a value to include in the subsequent call that tells + // the service where to continue from. + MaxItems *int64 `min:"1" type:"integer"` metadataGetAccountAuthorizationDetailsInput `json:"-" xml:"-"` } @@ -6246,12 +6510,15 @@ type GetAccountAuthorizationDetailsOutput struct { // A flag that indicates whether there are more items to return. If your results // were truncated, you can make a subsequent pagination request using the Marker - // request parameter to retrieve more items. + // request parameter to retrieve more items. Note that IAM might return fewer + // than the MaxItems number of results even when there are more results available. + // We recommend that you check IsTruncated after every call to ensure that you + // receive all of your results. IsTruncated *bool `type:"boolean"` // When IsTruncated is true, this element is present and contains the value // to use for the Marker parameter in a subsequent pagination request. - Marker *string `type:"string"` + Marker *string `min:"1" type:"string"` // A list containing information about managed policies. Policies []*ManagedPolicyDetail `type:"list"` @@ -6504,6 +6771,83 @@ func (s GetAccountSummaryOutput) GoString() string { return s.String() } +type GetContextKeysForCustomPolicyInput struct { + // A list of policies for which you want list of context keys used in Condition + // elements. + PolicyInputList []*string `type:"list" required:"true"` + + metadataGetContextKeysForCustomPolicyInput `json:"-" xml:"-"` +} + +type metadataGetContextKeysForCustomPolicyInput struct { + SDKShapeTraits bool `type:"structure"` +} + +// String returns the string representation +func (s GetContextKeysForCustomPolicyInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetContextKeysForCustomPolicyInput) GoString() string { + return s.String() +} + +// Contains the response to a successful GetContextKeysForPrincipalPolicy or +// GetContextKeysForCustomPolicy request. +type GetContextKeysForPolicyResponse struct { + // The list of context keys that are used in the Condition elements of the input + // policies. + ContextKeyNames []*string `type:"list"` + + metadataGetContextKeysForPolicyResponse `json:"-" xml:"-"` +} + +type metadataGetContextKeysForPolicyResponse struct { + SDKShapeTraits bool `type:"structure"` +} + +// String returns the string representation +func (s GetContextKeysForPolicyResponse) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetContextKeysForPolicyResponse) GoString() string { + return s.String() +} + +type GetContextKeysForPrincipalPolicyInput struct { + // A optional list of additional policies for which you want list of context + // keys used in Condition elements. + PolicyInputList []*string `type:"list"` + + // The ARN of a user, group, or role whose policies contain the context keys + // that you want listed. If you specify a user, the list includes context keys + // that are found in all policies attached to the user as well as to all groups + // that the user is a member of. If you pick a group or a role, then it includes + // only those context keys that are found in policies attached to that entity. + // Note that all parameters are shown in unencoded form here for clarity, but + // must be URL encoded to be included as a part of a real HTML request. + PolicySourceArn *string `min:"20" type:"string" required:"true"` + + metadataGetContextKeysForPrincipalPolicyInput `json:"-" xml:"-"` +} + +type metadataGetContextKeysForPrincipalPolicyInput struct { + SDKShapeTraits bool `type:"structure"` +} + +// String returns the string representation +func (s GetContextKeysForPrincipalPolicyInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetContextKeysForPrincipalPolicyInput) GoString() string { + return s.String() +} + type GetCredentialReportInput struct { metadataGetCredentialReportInput `json:"-" xml:"-"` } @@ -6553,19 +6897,24 @@ func (s GetCredentialReportOutput) GoString() string { type GetGroupInput struct { // The name of the group. - GroupName *string `type:"string" required:"true"` + GroupName *string `min:"1" type:"string" required:"true"` - // Use this parameter only when paginating results and only after you have received - // a response where the results are truncated. Set it to the value of the Marker - // element in the response you just received. - Marker *string `type:"string"` + // Use this parameter only when paginating results and only after you receive + // a response indicating that the results are truncated. Set it to the value + // of the Marker element in the response you received to inform the next call + // about where to start. + Marker *string `min:"1" type:"string"` // Use this only when paginating results to indicate the maximum number of items // you want in the response. If there are additional items beyond the maximum // you specify, the IsTruncated response element is true. // // This parameter is optional. If you do not include it, it defaults to 100. - MaxItems *int64 `type:"integer"` + // Note that IAM might return fewer results, even when there are more results + // available. If this is the case, the IsTruncated response element returns + // true and Marker contains a value to include in the subsequent call that tells + // the service where to continue from. + MaxItems *int64 `min:"1" type:"integer"` metadataGetGroupInput `json:"-" xml:"-"` } @@ -6591,12 +6940,15 @@ type GetGroupOutput struct { // A flag that indicates whether there are more items to return. If your results // were truncated, you can make a subsequent pagination request using the Marker - // request parameter to retrieve more items. + // request parameter to retrieve more items. Note that IAM might return fewer + // than the MaxItems number of results even when there are more results available. + // We recommend that you check IsTruncated after every call to ensure that you + // receive all of your results. IsTruncated *bool `type:"boolean"` // When IsTruncated is true, this element is present and contains the value // to use for the Marker parameter in a subsequent pagination request. - Marker *string `type:"string"` + Marker *string `min:"1" type:"string"` // A list of users in the group. Users []*User `type:"list" required:"true"` @@ -6620,10 +6972,10 @@ func (s GetGroupOutput) GoString() string { type GetGroupPolicyInput struct { // The name of the group the policy is associated with. - GroupName *string `type:"string" required:"true"` + GroupName *string `min:"1" type:"string" required:"true"` // The name of the policy document to get. - PolicyName *string `type:"string" required:"true"` + PolicyName *string `min:"1" type:"string" required:"true"` metadataGetGroupPolicyInput `json:"-" xml:"-"` } @@ -6645,13 +6997,13 @@ func (s GetGroupPolicyInput) GoString() string { // Contains the response to a successful GetGroupPolicy request. type GetGroupPolicyOutput struct { // The group the policy is associated with. - GroupName *string `type:"string" required:"true"` + GroupName *string `min:"1" type:"string" required:"true"` // The policy document. - PolicyDocument *string `type:"string" required:"true"` + PolicyDocument *string `min:"1" type:"string" required:"true"` // The name of the policy. - PolicyName *string `type:"string" required:"true"` + PolicyName *string `min:"1" type:"string" required:"true"` metadataGetGroupPolicyOutput `json:"-" xml:"-"` } @@ -6672,7 +7024,7 @@ func (s GetGroupPolicyOutput) GoString() string { type GetInstanceProfileInput struct { // The name of the instance profile to get information about. - InstanceProfileName *string `type:"string" required:"true"` + InstanceProfileName *string `min:"1" type:"string" required:"true"` metadataGetInstanceProfileInput `json:"-" xml:"-"` } @@ -6715,7 +7067,7 @@ func (s GetInstanceProfileOutput) GoString() string { type GetLoginProfileInput struct { // The name of the user whose login profile you want to retrieve. - UserName *string `type:"string" required:"true"` + UserName *string `min:"1" type:"string" required:"true"` metadataGetLoginProfileInput `json:"-" xml:"-"` } @@ -6760,7 +7112,7 @@ type GetOpenIDConnectProviderInput struct { // The Amazon Resource Name (ARN) of the IAM OpenID Connect (OIDC) provider // to get information for. You can get a list of OIDC provider ARNs by using // the ListOpenIDConnectProviders action. - OpenIDConnectProviderArn *string `type:"string" required:"true"` + OpenIDConnectProviderArn *string `min:"20" type:"string" required:"true"` metadataGetOpenIDConnectProviderInput `json:"-" xml:"-"` } @@ -6795,7 +7147,7 @@ type GetOpenIDConnectProviderOutput struct { // The URL that the IAM OpenID Connect provider is associated with. For more // information, see CreateOpenIDConnectProvider. - Url *string `type:"string"` + Url *string `min:"1" type:"string"` metadataGetOpenIDConnectProviderOutput `json:"-" xml:"-"` } @@ -6820,7 +7172,7 @@ type GetPolicyInput struct { // For more information about ARNs, go to Amazon Resource Names (ARNs) and // AWS Service Namespaces (http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) // in the AWS General Reference. - PolicyArn *string `type:"string" required:"true"` + PolicyArn *string `min:"20" type:"string" required:"true"` metadataGetPolicyInput `json:"-" xml:"-"` } @@ -6867,7 +7219,7 @@ type GetPolicyVersionInput struct { // For more information about ARNs, go to Amazon Resource Names (ARNs) and // AWS Service Namespaces (http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) // in the AWS General Reference. - PolicyArn *string `type:"string" required:"true"` + PolicyArn *string `min:"20" type:"string" required:"true"` // Identifies the policy version to retrieve. VersionId *string `type:"string" required:"true"` @@ -6895,7 +7247,7 @@ type GetPolicyVersionOutput struct { // // For more information about managed policy versions, see Versioning for Managed // Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-versions.html) - // in the Using IAM guide. + // in the IAM User Guide. PolicyVersion *PolicyVersion `type:"structure"` metadataGetPolicyVersionOutput `json:"-" xml:"-"` @@ -6917,7 +7269,7 @@ func (s GetPolicyVersionOutput) GoString() string { type GetRoleInput struct { // The name of the role to get information about. - RoleName *string `type:"string" required:"true"` + RoleName *string `min:"1" type:"string" required:"true"` metadataGetRoleInput `json:"-" xml:"-"` } @@ -6960,10 +7312,10 @@ func (s GetRoleOutput) GoString() string { type GetRolePolicyInput struct { // The name of the policy document to get. - PolicyName *string `type:"string" required:"true"` + PolicyName *string `min:"1" type:"string" required:"true"` // The name of the role associated with the policy. - RoleName *string `type:"string" required:"true"` + RoleName *string `min:"1" type:"string" required:"true"` metadataGetRolePolicyInput `json:"-" xml:"-"` } @@ -6985,13 +7337,13 @@ func (s GetRolePolicyInput) GoString() string { // Contains the response to a successful GetRolePolicy request. type GetRolePolicyOutput struct { // The policy document. - PolicyDocument *string `type:"string" required:"true"` + PolicyDocument *string `min:"1" type:"string" required:"true"` // The name of the policy. - PolicyName *string `type:"string" required:"true"` + PolicyName *string `min:"1" type:"string" required:"true"` // The role the policy is associated with. - RoleName *string `type:"string" required:"true"` + RoleName *string `min:"1" type:"string" required:"true"` metadataGetRolePolicyOutput `json:"-" xml:"-"` } @@ -7012,7 +7364,7 @@ func (s GetRolePolicyOutput) GoString() string { type GetSAMLProviderInput struct { // The Amazon Resource Name (ARN) of the SAML provider to get information about. - SAMLProviderArn *string `type:"string" required:"true"` + SAMLProviderArn *string `min:"20" type:"string" required:"true"` metadataGetSAMLProviderInput `json:"-" xml:"-"` } @@ -7037,7 +7389,7 @@ type GetSAMLProviderOutput struct { CreateDate *time.Time `type:"timestamp" timestampFormat:"iso8601"` // The XML metadata document that includes information about an identity provider. - SAMLMetadataDocument *string `type:"string"` + SAMLMetadataDocument *string `min:"1000" type:"string"` // The expiration date and time for the SAML provider. ValidUntil *time.Time `type:"timestamp" timestampFormat:"iso8601"` @@ -7066,10 +7418,10 @@ type GetSSHPublicKeyInput struct { Encoding *string `type:"string" required:"true" enum:"encodingType"` // The unique identifier for the SSH public key. - SSHPublicKeyId *string `type:"string" required:"true"` + SSHPublicKeyId *string `min:"20" type:"string" required:"true"` // The name of the IAM user associated with the SSH public key. - UserName *string `type:"string" required:"true"` + UserName *string `min:"1" type:"string" required:"true"` metadataGetSSHPublicKeyInput `json:"-" xml:"-"` } @@ -7112,7 +7464,7 @@ func (s GetSSHPublicKeyOutput) GoString() string { type GetServerCertificateInput struct { // The name of the server certificate you want to retrieve information about. - ServerCertificateName *string `type:"string" required:"true"` + ServerCertificateName *string `min:"1" type:"string" required:"true"` metadataGetServerCertificateInput `json:"-" xml:"-"` } @@ -7158,7 +7510,7 @@ type GetUserInput struct { // // This parameter is optional. If it is not included, it defaults to the user // making the request. - UserName *string `type:"string"` + UserName *string `min:"1" type:"string"` metadataGetUserInput `json:"-" xml:"-"` } @@ -7201,10 +7553,10 @@ func (s GetUserOutput) GoString() string { type GetUserPolicyInput struct { // The name of the policy document to get. - PolicyName *string `type:"string" required:"true"` + PolicyName *string `min:"1" type:"string" required:"true"` // The name of the user who the policy is associated with. - UserName *string `type:"string" required:"true"` + UserName *string `min:"1" type:"string" required:"true"` metadataGetUserPolicyInput `json:"-" xml:"-"` } @@ -7226,13 +7578,13 @@ func (s GetUserPolicyInput) GoString() string { // Contains the response to a successful GetUserPolicy request. type GetUserPolicyOutput struct { // The policy document. - PolicyDocument *string `type:"string" required:"true"` + PolicyDocument *string `min:"1" type:"string" required:"true"` // The name of the policy. - PolicyName *string `type:"string" required:"true"` + PolicyName *string `min:"1" type:"string" required:"true"` // The user the policy is associated with. - UserName *string `type:"string" required:"true"` + UserName *string `min:"1" type:"string" required:"true"` metadataGetUserPolicyOutput `json:"-" xml:"-"` } @@ -7260,7 +7612,7 @@ type Group struct { // The Amazon Resource Name (ARN) specifying the group. For more information // about ARNs and how to use them in policies, see IAM Identifiers (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html) // in the Using IAM guide. - Arn *string `type:"string" required:"true"` + Arn *string `min:"20" type:"string" required:"true"` // The date and time, in ISO 8601 date-time format (http://www.iso.org/iso/iso8601), // when the group was created. @@ -7269,15 +7621,15 @@ type Group struct { // The stable and unique string identifying the group. For more information // about IDs, see IAM Identifiers (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html) // in the Using IAM guide. - GroupId *string `type:"string" required:"true"` + GroupId *string `min:"16" type:"string" required:"true"` // The friendly name that identifies the group. - GroupName *string `type:"string" required:"true"` + GroupName *string `min:"1" type:"string" required:"true"` // The path to the group. For more information about paths, see IAM Identifiers // (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html) // in the Using IAM guide. - Path *string `type:"string" required:"true"` + Path *string `min:"1" type:"string" required:"true"` metadataGroup `json:"-" xml:"-"` } @@ -7306,7 +7658,7 @@ type GroupDetail struct { // For more information about ARNs, go to Amazon Resource Names (ARNs) and // AWS Service Namespaces (http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) // in the AWS General Reference. - Arn *string `type:"string"` + Arn *string `min:"20" type:"string"` // A list of the managed policies attached to the group. AttachedManagedPolicies []*AttachedPolicy `type:"list"` @@ -7318,10 +7670,10 @@ type GroupDetail struct { // The stable and unique string identifying the group. For more information // about IDs, see IAM Identifiers (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html) // in the Using IAM guide. - GroupId *string `type:"string"` + GroupId *string `min:"16" type:"string"` // The friendly name that identifies the group. - GroupName *string `type:"string"` + GroupName *string `min:"1" type:"string"` // A list of the inline policies embedded in the group. GroupPolicyList []*PolicyDetail `type:"list"` @@ -7329,7 +7681,7 @@ type GroupDetail struct { // The path to the group. For more information about paths, see IAM Identifiers // (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html) // in the Using IAM guide. - Path *string `type:"string"` + Path *string `min:"1" type:"string"` metadataGroupDetail `json:"-" xml:"-"` } @@ -7364,7 +7716,7 @@ type InstanceProfile struct { // information about ARNs and how to use them in policies, see IAM Identifiers // (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html) // in the Using IAM guide. - Arn *string `type:"string" required:"true"` + Arn *string `min:"20" type:"string" required:"true"` // The date when the instance profile was created. CreateDate *time.Time `type:"timestamp" timestampFormat:"iso8601" required:"true"` @@ -7372,15 +7724,15 @@ type InstanceProfile struct { // The stable and unique string identifying the instance profile. For more information // about IDs, see IAM Identifiers (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html) // in the Using IAM guide. - InstanceProfileId *string `type:"string" required:"true"` + InstanceProfileId *string `min:"16" type:"string" required:"true"` // The name identifying the instance profile. - InstanceProfileName *string `type:"string" required:"true"` + InstanceProfileName *string `min:"1" type:"string" required:"true"` // The path to the instance profile. For more information about paths, see IAM // Identifiers (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html) // in the Using IAM guide. - Path *string `type:"string" required:"true"` + Path *string `min:"1" type:"string" required:"true"` // The role associated with the instance profile. Roles []*Role `type:"list" required:"true"` @@ -7403,20 +7755,25 @@ func (s InstanceProfile) GoString() string { } type ListAccessKeysInput struct { - // Use this parameter only when paginating results and only after you have received - // a response where the results are truncated. Set it to the value of the Marker - // element in the response you just received. - Marker *string `type:"string"` + // Use this parameter only when paginating results and only after you receive + // a response indicating that the results are truncated. Set it to the value + // of the Marker element in the response you received to inform the next call + // about where to start. + Marker *string `min:"1" type:"string"` // Use this only when paginating results to indicate the maximum number of items // you want in the response. If there are additional items beyond the maximum // you specify, the IsTruncated response element is true. // // This parameter is optional. If you do not include it, it defaults to 100. - MaxItems *int64 `type:"integer"` + // Note that IAM might return fewer results, even when there are more results + // available. If this is the case, the IsTruncated response element returns + // true and Marker contains a value to include in the subsequent call that tells + // the service where to continue from. + MaxItems *int64 `min:"1" type:"integer"` // The name of the user. - UserName *string `type:"string"` + UserName *string `min:"1" type:"string"` metadataListAccessKeysInput `json:"-" xml:"-"` } @@ -7442,12 +7799,15 @@ type ListAccessKeysOutput struct { // A flag that indicates whether there are more items to return. If your results // were truncated, you can make a subsequent pagination request using the Marker - // request parameter to retrieve more items. + // request parameter to retrieve more items. Note that IAM might return fewer + // than the MaxItems number of results even when there are more results available. + // We recommend that you check IsTruncated after every call to ensure that you + // receive all of your results. IsTruncated *bool `type:"boolean"` // When IsTruncated is true, this element is present and contains the value // to use for the Marker parameter in a subsequent pagination request. - Marker *string `type:"string"` + Marker *string `min:"1" type:"string"` metadataListAccessKeysOutput `json:"-" xml:"-"` } @@ -7467,17 +7827,22 @@ func (s ListAccessKeysOutput) GoString() string { } type ListAccountAliasesInput struct { - // Use this parameter only when paginating results and only after you have received - // a response where the results are truncated. Set it to the value of the Marker - // element in the response you just received. - Marker *string `type:"string"` + // Use this parameter only when paginating results and only after you receive + // a response indicating that the results are truncated. Set it to the value + // of the Marker element in the response you received to inform the next call + // about where to start. + Marker *string `min:"1" type:"string"` // Use this only when paginating results to indicate the maximum number of items // you want in the response. If there are additional items beyond the maximum // you specify, the IsTruncated response element is true. // // This parameter is optional. If you do not include it, it defaults to 100. - MaxItems *int64 `type:"integer"` + // Note that IAM might return fewer results, even when there are more results + // available. If this is the case, the IsTruncated response element returns + // true and Marker contains a value to include in the subsequent call that tells + // the service where to continue from. + MaxItems *int64 `min:"1" type:"integer"` metadataListAccountAliasesInput `json:"-" xml:"-"` } @@ -7503,12 +7868,15 @@ type ListAccountAliasesOutput struct { // A flag that indicates whether there are more items to return. If your results // were truncated, you can make a subsequent pagination request using the Marker - // request parameter to retrieve more items. + // request parameter to retrieve more items. Note that IAM might return fewer + // than the MaxItems number of results even when there are more results available. + // We recommend that you check IsTruncated after every call to ensure that you + // receive all of your results. IsTruncated *bool `type:"boolean"` // When IsTruncated is true, this element is present and contains the value // to use for the Marker parameter in a subsequent pagination request. - Marker *string `type:"string"` + Marker *string `min:"1" type:"string"` metadataListAccountAliasesOutput `json:"-" xml:"-"` } @@ -7530,19 +7898,24 @@ func (s ListAccountAliasesOutput) GoString() string { type ListAttachedGroupPoliciesInput struct { // The name (friendly name, not ARN) of the group to list attached policies // for. - GroupName *string `type:"string" required:"true"` + GroupName *string `min:"1" type:"string" required:"true"` - // Use this parameter only when paginating results and only after you have received - // a response where the results are truncated. Set it to the value of the Marker - // element in the response you just received. - Marker *string `type:"string"` + // Use this parameter only when paginating results and only after you receive + // a response indicating that the results are truncated. Set it to the value + // of the Marker element in the response you received to inform the next call + // about where to start. + Marker *string `min:"1" type:"string"` // Use this only when paginating results to indicate the maximum number of items // you want in the response. If there are additional items beyond the maximum // you specify, the IsTruncated response element is true. // // This parameter is optional. If you do not include it, it defaults to 100. - MaxItems *int64 `type:"integer"` + // Note that IAM might return fewer results, even when there are more results + // available. If this is the case, the IsTruncated response element returns + // true and Marker contains a value to include in the subsequent call that tells + // the service where to continue from. + MaxItems *int64 `min:"1" type:"integer"` // The path prefix for filtering the results. This parameter is optional. If // it is not included, it defaults to a slash (/), listing all policies. @@ -7572,12 +7945,15 @@ type ListAttachedGroupPoliciesOutput struct { // A flag that indicates whether there are more items to return. If your results // were truncated, you can make a subsequent pagination request using the Marker - // request parameter to retrieve more items. + // request parameter to retrieve more items. Note that IAM might return fewer + // than the MaxItems number of results even when there are more results available. + // We recommend that you check IsTruncated after every call to ensure that you + // receive all of your results. IsTruncated *bool `type:"boolean"` // When IsTruncated is true, this element is present and contains the value // to use for the Marker parameter in a subsequent pagination request. - Marker *string `type:"string"` + Marker *string `min:"1" type:"string"` metadataListAttachedGroupPoliciesOutput `json:"-" xml:"-"` } @@ -7597,24 +7973,29 @@ func (s ListAttachedGroupPoliciesOutput) GoString() string { } type ListAttachedRolePoliciesInput struct { - // Use this parameter only when paginating results and only after you have received - // a response where the results are truncated. Set it to the value of the Marker - // element in the response you just received. - Marker *string `type:"string"` + // Use this parameter only when paginating results and only after you receive + // a response indicating that the results are truncated. Set it to the value + // of the Marker element in the response you received to inform the next call + // about where to start. + Marker *string `min:"1" type:"string"` // Use this only when paginating results to indicate the maximum number of items // you want in the response. If there are additional items beyond the maximum // you specify, the IsTruncated response element is true. // // This parameter is optional. If you do not include it, it defaults to 100. - MaxItems *int64 `type:"integer"` + // Note that IAM might return fewer results, even when there are more results + // available. If this is the case, the IsTruncated response element returns + // true and Marker contains a value to include in the subsequent call that tells + // the service where to continue from. + MaxItems *int64 `min:"1" type:"integer"` // The path prefix for filtering the results. This parameter is optional. If // it is not included, it defaults to a slash (/), listing all policies. PathPrefix *string `type:"string"` // The name (friendly name, not ARN) of the role to list attached policies for. - RoleName *string `type:"string" required:"true"` + RoleName *string `min:"1" type:"string" required:"true"` metadataListAttachedRolePoliciesInput `json:"-" xml:"-"` } @@ -7640,12 +8021,15 @@ type ListAttachedRolePoliciesOutput struct { // A flag that indicates whether there are more items to return. If your results // were truncated, you can make a subsequent pagination request using the Marker - // request parameter to retrieve more items. + // request parameter to retrieve more items. Note that IAM might return fewer + // than the MaxItems number of results even when there are more results available. + // We recommend that you check IsTruncated after every call to ensure that you + // receive all of your results. IsTruncated *bool `type:"boolean"` // When IsTruncated is true, this element is present and contains the value // to use for the Marker parameter in a subsequent pagination request. - Marker *string `type:"string"` + Marker *string `min:"1" type:"string"` metadataListAttachedRolePoliciesOutput `json:"-" xml:"-"` } @@ -7665,24 +8049,29 @@ func (s ListAttachedRolePoliciesOutput) GoString() string { } type ListAttachedUserPoliciesInput struct { - // Use this parameter only when paginating results and only after you have received - // a response where the results are truncated. Set it to the value of the Marker - // element in the response you just received. - Marker *string `type:"string"` + // Use this parameter only when paginating results and only after you receive + // a response indicating that the results are truncated. Set it to the value + // of the Marker element in the response you received to inform the next call + // about where to start. + Marker *string `min:"1" type:"string"` // Use this only when paginating results to indicate the maximum number of items // you want in the response. If there are additional items beyond the maximum // you specify, the IsTruncated response element is true. // // This parameter is optional. If you do not include it, it defaults to 100. - MaxItems *int64 `type:"integer"` + // Note that IAM might return fewer results, even when there are more results + // available. If this is the case, the IsTruncated response element returns + // true and Marker contains a value to include in the subsequent call that tells + // the service where to continue from. + MaxItems *int64 `min:"1" type:"integer"` // The path prefix for filtering the results. This parameter is optional. If // it is not included, it defaults to a slash (/), listing all policies. PathPrefix *string `type:"string"` // The name (friendly name, not ARN) of the user to list attached policies for. - UserName *string `type:"string" required:"true"` + UserName *string `min:"1" type:"string" required:"true"` metadataListAttachedUserPoliciesInput `json:"-" xml:"-"` } @@ -7708,12 +8097,15 @@ type ListAttachedUserPoliciesOutput struct { // A flag that indicates whether there are more items to return. If your results // were truncated, you can make a subsequent pagination request using the Marker - // request parameter to retrieve more items. + // request parameter to retrieve more items. Note that IAM might return fewer + // than the MaxItems number of results even when there are more results available. + // We recommend that you check IsTruncated after every call to ensure that you + // receive all of your results. IsTruncated *bool `type:"boolean"` // When IsTruncated is true, this element is present and contains the value // to use for the Marker parameter in a subsequent pagination request. - Marker *string `type:"string"` + Marker *string `min:"1" type:"string"` metadataListAttachedUserPoliciesOutput `json:"-" xml:"-"` } @@ -7740,28 +8132,33 @@ type ListEntitiesForPolicyInput struct { // not included, all attached entities (users, groups, and roles) are returned. EntityFilter *string `type:"string" enum:"EntityType"` - // Use this parameter only when paginating results and only after you have received - // a response where the results are truncated. Set it to the value of the Marker - // element in the response you just received. - Marker *string `type:"string"` + // Use this parameter only when paginating results and only after you receive + // a response indicating that the results are truncated. Set it to the value + // of the Marker element in the response you received to inform the next call + // about where to start. + Marker *string `min:"1" type:"string"` // Use this only when paginating results to indicate the maximum number of items // you want in the response. If there are additional items beyond the maximum // you specify, the IsTruncated response element is true. // // This parameter is optional. If you do not include it, it defaults to 100. - MaxItems *int64 `type:"integer"` + // Note that IAM might return fewer results, even when there are more results + // available. If this is the case, the IsTruncated response element returns + // true and Marker contains a value to include in the subsequent call that tells + // the service where to continue from. + MaxItems *int64 `min:"1" type:"integer"` // The path prefix for filtering the results. This parameter is optional. If // it is not included, it defaults to a slash (/), listing all entities. - PathPrefix *string `type:"string"` + PathPrefix *string `min:"1" type:"string"` // The Amazon Resource Name (ARN). ARNs are unique identifiers for AWS resources. // // For more information about ARNs, go to Amazon Resource Names (ARNs) and // AWS Service Namespaces (http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) // in the AWS General Reference. - PolicyArn *string `type:"string" required:"true"` + PolicyArn *string `min:"20" type:"string" required:"true"` metadataListEntitiesForPolicyInput `json:"-" xml:"-"` } @@ -7784,12 +8181,15 @@ func (s ListEntitiesForPolicyInput) GoString() string { type ListEntitiesForPolicyOutput struct { // A flag that indicates whether there are more items to return. If your results // were truncated, you can make a subsequent pagination request using the Marker - // request parameter to retrieve more items. + // request parameter to retrieve more items. Note that IAM might return fewer + // than the MaxItems number of results even when there are more results available. + // We recommend that you check IsTruncated after every call to ensure that you + // receive all of your results. IsTruncated *bool `type:"boolean"` // When IsTruncated is true, this element is present and contains the value // to use for the Marker parameter in a subsequent pagination request. - Marker *string `type:"string"` + Marker *string `min:"1" type:"string"` // A list of groups that the policy is attached to. PolicyGroups []*PolicyGroup `type:"list"` @@ -7819,19 +8219,24 @@ func (s ListEntitiesForPolicyOutput) GoString() string { type ListGroupPoliciesInput struct { // The name of the group to list policies for. - GroupName *string `type:"string" required:"true"` + GroupName *string `min:"1" type:"string" required:"true"` - // Use this parameter only when paginating results and only after you have received - // a response where the results are truncated. Set it to the value of the Marker - // element in the response you just received. - Marker *string `type:"string"` + // Use this parameter only when paginating results and only after you receive + // a response indicating that the results are truncated. Set it to the value + // of the Marker element in the response you received to inform the next call + // about where to start. + Marker *string `min:"1" type:"string"` // Use this only when paginating results to indicate the maximum number of items // you want in the response. If there are additional items beyond the maximum // you specify, the IsTruncated response element is true. // // This parameter is optional. If you do not include it, it defaults to 100. - MaxItems *int64 `type:"integer"` + // Note that IAM might return fewer results, even when there are more results + // available. If this is the case, the IsTruncated response element returns + // true and Marker contains a value to include in the subsequent call that tells + // the service where to continue from. + MaxItems *int64 `min:"1" type:"integer"` metadataListGroupPoliciesInput `json:"-" xml:"-"` } @@ -7854,12 +8259,15 @@ func (s ListGroupPoliciesInput) GoString() string { type ListGroupPoliciesOutput struct { // A flag that indicates whether there are more items to return. If your results // were truncated, you can make a subsequent pagination request using the Marker - // request parameter to retrieve more items. + // request parameter to retrieve more items. Note that IAM might return fewer + // than the MaxItems number of results even when there are more results available. + // We recommend that you check IsTruncated after every call to ensure that you + // receive all of your results. IsTruncated *bool `type:"boolean"` // When IsTruncated is true, this element is present and contains the value // to use for the Marker parameter in a subsequent pagination request. - Marker *string `type:"string"` + Marker *string `min:"1" type:"string"` // A list of policy names. PolicyNames []*string `type:"list" required:"true"` @@ -7882,20 +8290,25 @@ func (s ListGroupPoliciesOutput) GoString() string { } type ListGroupsForUserInput struct { - // Use this parameter only when paginating results and only after you have received - // a response where the results are truncated. Set it to the value of the Marker - // element in the response you just received. - Marker *string `type:"string"` + // Use this parameter only when paginating results and only after you receive + // a response indicating that the results are truncated. Set it to the value + // of the Marker element in the response you received to inform the next call + // about where to start. + Marker *string `min:"1" type:"string"` // Use this only when paginating results to indicate the maximum number of items // you want in the response. If there are additional items beyond the maximum // you specify, the IsTruncated response element is true. // // This parameter is optional. If you do not include it, it defaults to 100. - MaxItems *int64 `type:"integer"` + // Note that IAM might return fewer results, even when there are more results + // available. If this is the case, the IsTruncated response element returns + // true and Marker contains a value to include in the subsequent call that tells + // the service where to continue from. + MaxItems *int64 `min:"1" type:"integer"` // The name of the user to list groups for. - UserName *string `type:"string" required:"true"` + UserName *string `min:"1" type:"string" required:"true"` metadataListGroupsForUserInput `json:"-" xml:"-"` } @@ -7921,12 +8334,15 @@ type ListGroupsForUserOutput struct { // A flag that indicates whether there are more items to return. If your results // were truncated, you can make a subsequent pagination request using the Marker - // request parameter to retrieve more items. + // request parameter to retrieve more items. Note that IAM might return fewer + // than the MaxItems number of results even when there are more results available. + // We recommend that you check IsTruncated after every call to ensure that you + // receive all of your results. IsTruncated *bool `type:"boolean"` // When IsTruncated is true, this element is present and contains the value // to use for the Marker parameter in a subsequent pagination request. - Marker *string `type:"string"` + Marker *string `min:"1" type:"string"` metadataListGroupsForUserOutput `json:"-" xml:"-"` } @@ -7946,24 +8362,29 @@ func (s ListGroupsForUserOutput) GoString() string { } type ListGroupsInput struct { - // Use this parameter only when paginating results and only after you have received - // a response where the results are truncated. Set it to the value of the Marker - // element in the response you just received. - Marker *string `type:"string"` + // Use this parameter only when paginating results and only after you receive + // a response indicating that the results are truncated. Set it to the value + // of the Marker element in the response you received to inform the next call + // about where to start. + Marker *string `min:"1" type:"string"` // Use this only when paginating results to indicate the maximum number of items // you want in the response. If there are additional items beyond the maximum // you specify, the IsTruncated response element is true. // // This parameter is optional. If you do not include it, it defaults to 100. - MaxItems *int64 `type:"integer"` + // Note that IAM might return fewer results, even when there are more results + // available. If this is the case, the IsTruncated response element returns + // true and Marker contains a value to include in the subsequent call that tells + // the service where to continue from. + MaxItems *int64 `min:"1" type:"integer"` // The path prefix for filtering the results. For example, the prefix /division_abc/subdivision_xyz/ // gets all groups whose path starts with /division_abc/subdivision_xyz/. // // This parameter is optional. If it is not included, it defaults to a slash // (/), listing all groups. - PathPrefix *string `type:"string"` + PathPrefix *string `min:"1" type:"string"` metadataListGroupsInput `json:"-" xml:"-"` } @@ -7989,12 +8410,15 @@ type ListGroupsOutput struct { // A flag that indicates whether there are more items to return. If your results // were truncated, you can make a subsequent pagination request using the Marker - // request parameter to retrieve more items. + // request parameter to retrieve more items. Note that IAM might return fewer + // than the MaxItems number of results even when there are more results available. + // We recommend that you check IsTruncated after every call to ensure that you + // receive all of your results. IsTruncated *bool `type:"boolean"` // When IsTruncated is true, this element is present and contains the value // to use for the Marker parameter in a subsequent pagination request. - Marker *string `type:"string"` + Marker *string `min:"1" type:"string"` metadataListGroupsOutput `json:"-" xml:"-"` } @@ -8014,20 +8438,25 @@ func (s ListGroupsOutput) GoString() string { } type ListInstanceProfilesForRoleInput struct { - // Use this parameter only when paginating results and only after you have received - // a response where the results are truncated. Set it to the value of the Marker - // element in the response you just received. - Marker *string `type:"string"` + // Use this parameter only when paginating results and only after you receive + // a response indicating that the results are truncated. Set it to the value + // of the Marker element in the response you received to inform the next call + // about where to start. + Marker *string `min:"1" type:"string"` // Use this only when paginating results to indicate the maximum number of items // you want in the response. If there are additional items beyond the maximum // you specify, the IsTruncated response element is true. // // This parameter is optional. If you do not include it, it defaults to 100. - MaxItems *int64 `type:"integer"` + // Note that IAM might return fewer results, even when there are more results + // available. If this is the case, the IsTruncated response element returns + // true and Marker contains a value to include in the subsequent call that tells + // the service where to continue from. + MaxItems *int64 `min:"1" type:"integer"` // The name of the role to list instance profiles for. - RoleName *string `type:"string" required:"true"` + RoleName *string `min:"1" type:"string" required:"true"` metadataListInstanceProfilesForRoleInput `json:"-" xml:"-"` } @@ -8053,12 +8482,15 @@ type ListInstanceProfilesForRoleOutput struct { // A flag that indicates whether there are more items to return. If your results // were truncated, you can make a subsequent pagination request using the Marker - // request parameter to retrieve more items. + // request parameter to retrieve more items. Note that IAM might return fewer + // than the MaxItems number of results even when there are more results available. + // We recommend that you check IsTruncated after every call to ensure that you + // receive all of your results. IsTruncated *bool `type:"boolean"` // When IsTruncated is true, this element is present and contains the value // to use for the Marker parameter in a subsequent pagination request. - Marker *string `type:"string"` + Marker *string `min:"1" type:"string"` metadataListInstanceProfilesForRoleOutput `json:"-" xml:"-"` } @@ -8078,24 +8510,29 @@ func (s ListInstanceProfilesForRoleOutput) GoString() string { } type ListInstanceProfilesInput struct { - // Use this parameter only when paginating results and only after you have received - // a response where the results are truncated. Set it to the value of the Marker - // element in the response you just received. - Marker *string `type:"string"` + // Use this parameter only when paginating results and only after you receive + // a response indicating that the results are truncated. Set it to the value + // of the Marker element in the response you received to inform the next call + // about where to start. + Marker *string `min:"1" type:"string"` // Use this only when paginating results to indicate the maximum number of items // you want in the response. If there are additional items beyond the maximum // you specify, the IsTruncated response element is true. // // This parameter is optional. If you do not include it, it defaults to 100. - MaxItems *int64 `type:"integer"` + // Note that IAM might return fewer results, even when there are more results + // available. If this is the case, the IsTruncated response element returns + // true and Marker contains a value to include in the subsequent call that tells + // the service where to continue from. + MaxItems *int64 `min:"1" type:"integer"` // The path prefix for filtering the results. For example, the prefix /application_abc/component_xyz/ // gets all instance profiles whose path starts with /application_abc/component_xyz/. // // This parameter is optional. If it is not included, it defaults to a slash // (/), listing all instance profiles. - PathPrefix *string `type:"string"` + PathPrefix *string `min:"1" type:"string"` metadataListInstanceProfilesInput `json:"-" xml:"-"` } @@ -8121,12 +8558,15 @@ type ListInstanceProfilesOutput struct { // A flag that indicates whether there are more items to return. If your results // were truncated, you can make a subsequent pagination request using the Marker - // request parameter to retrieve more items. + // request parameter to retrieve more items. Note that IAM might return fewer + // than the MaxItems number of results even when there are more results available. + // We recommend that you check IsTruncated after every call to ensure that you + // receive all of your results. IsTruncated *bool `type:"boolean"` // When IsTruncated is true, this element is present and contains the value // to use for the Marker parameter in a subsequent pagination request. - Marker *string `type:"string"` + Marker *string `min:"1" type:"string"` metadataListInstanceProfilesOutput `json:"-" xml:"-"` } @@ -8146,20 +8586,25 @@ func (s ListInstanceProfilesOutput) GoString() string { } type ListMFADevicesInput struct { - // Use this parameter only when paginating results and only after you have received - // a response where the results are truncated. Set it to the value of the Marker - // element in the response you just received. - Marker *string `type:"string"` + // Use this parameter only when paginating results and only after you receive + // a response indicating that the results are truncated. Set it to the value + // of the Marker element in the response you received to inform the next call + // about where to start. + Marker *string `min:"1" type:"string"` // Use this only when paginating results to indicate the maximum number of items // you want in the response. If there are additional items beyond the maximum // you specify, the IsTruncated response element is true. // // This parameter is optional. If you do not include it, it defaults to 100. - MaxItems *int64 `type:"integer"` + // Note that IAM might return fewer results, even when there are more results + // available. If this is the case, the IsTruncated response element returns + // true and Marker contains a value to include in the subsequent call that tells + // the service where to continue from. + MaxItems *int64 `min:"1" type:"integer"` // The name of the user whose MFA devices you want to list. - UserName *string `type:"string"` + UserName *string `min:"1" type:"string"` metadataListMFADevicesInput `json:"-" xml:"-"` } @@ -8182,7 +8627,10 @@ func (s ListMFADevicesInput) GoString() string { type ListMFADevicesOutput struct { // A flag that indicates whether there are more items to return. If your results // were truncated, you can make a subsequent pagination request using the Marker - // request parameter to retrieve more items. + // request parameter to retrieve more items. Note that IAM might return fewer + // than the MaxItems number of results even when there are more results available. + // We recommend that you check IsTruncated after every call to ensure that you + // receive all of your results. IsTruncated *bool `type:"boolean"` // A list of MFA devices. @@ -8190,7 +8638,7 @@ type ListMFADevicesOutput struct { // When IsTruncated is true, this element is present and contains the value // to use for the Marker parameter in a subsequent pagination request. - Marker *string `type:"string"` + Marker *string `min:"1" type:"string"` metadataListMFADevicesOutput `json:"-" xml:"-"` } @@ -8250,17 +8698,22 @@ func (s ListOpenIDConnectProvidersOutput) GoString() string { } type ListPoliciesInput struct { - // Use this parameter only when paginating results and only after you have received - // a response where the results are truncated. Set it to the value of the Marker - // element in the response you just received. - Marker *string `type:"string"` + // Use this parameter only when paginating results and only after you receive + // a response indicating that the results are truncated. Set it to the value + // of the Marker element in the response you received to inform the next call + // about where to start. + Marker *string `min:"1" type:"string"` // Use this only when paginating results to indicate the maximum number of items // you want in the response. If there are additional items beyond the maximum // you specify, the IsTruncated response element is true. // // This parameter is optional. If you do not include it, it defaults to 100. - MaxItems *int64 `type:"integer"` + // Note that IAM might return fewer results, even when there are more results + // available. If this is the case, the IsTruncated response element returns + // true and Marker contains a value to include in the subsequent call that tells + // the service where to continue from. + MaxItems *int64 `min:"1" type:"integer"` // A flag to filter the results to only the attached policies. // @@ -8303,12 +8756,15 @@ func (s ListPoliciesInput) GoString() string { type ListPoliciesOutput struct { // A flag that indicates whether there are more items to return. If your results // were truncated, you can make a subsequent pagination request using the Marker - // request parameter to retrieve more items. + // request parameter to retrieve more items. Note that IAM might return fewer + // than the MaxItems number of results even when there are more results available. + // We recommend that you check IsTruncated after every call to ensure that you + // receive all of your results. IsTruncated *bool `type:"boolean"` // When IsTruncated is true, this element is present and contains the value // to use for the Marker parameter in a subsequent pagination request. - Marker *string `type:"string"` + Marker *string `min:"1" type:"string"` // A list of policies. Policies []*Policy `type:"list"` @@ -8331,24 +8787,29 @@ func (s ListPoliciesOutput) GoString() string { } type ListPolicyVersionsInput struct { - // Use this parameter only when paginating results and only after you have received - // a response where the results are truncated. Set it to the value of the Marker - // element in the response you just received. - Marker *string `type:"string"` + // Use this parameter only when paginating results and only after you receive + // a response indicating that the results are truncated. Set it to the value + // of the Marker element in the response you received to inform the next call + // about where to start. + Marker *string `min:"1" type:"string"` // Use this only when paginating results to indicate the maximum number of items // you want in the response. If there are additional items beyond the maximum // you specify, the IsTruncated response element is true. // // This parameter is optional. If you do not include it, it defaults to 100. - MaxItems *int64 `type:"integer"` + // Note that IAM might return fewer results, even when there are more results + // available. If this is the case, the IsTruncated response element returns + // true and Marker contains a value to include in the subsequent call that tells + // the service where to continue from. + MaxItems *int64 `min:"1" type:"integer"` // The Amazon Resource Name (ARN). ARNs are unique identifiers for AWS resources. // // For more information about ARNs, go to Amazon Resource Names (ARNs) and // AWS Service Namespaces (http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) // in the AWS General Reference. - PolicyArn *string `type:"string" required:"true"` + PolicyArn *string `min:"20" type:"string" required:"true"` metadataListPolicyVersionsInput `json:"-" xml:"-"` } @@ -8371,18 +8832,21 @@ func (s ListPolicyVersionsInput) GoString() string { type ListPolicyVersionsOutput struct { // A flag that indicates whether there are more items to return. If your results // were truncated, you can make a subsequent pagination request using the Marker - // request parameter to retrieve more items. + // request parameter to retrieve more items. Note that IAM might return fewer + // than the MaxItems number of results even when there are more results available. + // We recommend that you check IsTruncated after every call to ensure that you + // receive all of your results. IsTruncated *bool `type:"boolean"` // When IsTruncated is true, this element is present and contains the value // to use for the Marker parameter in a subsequent pagination request. - Marker *string `type:"string"` + Marker *string `min:"1" type:"string"` // A list of policy versions. // // For more information about managed policy versions, see Versioning for Managed // Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-versions.html) - // in the Using IAM guide. + // in the IAM User Guide. Versions []*PolicyVersion `type:"list"` metadataListPolicyVersionsOutput `json:"-" xml:"-"` @@ -8403,20 +8867,25 @@ func (s ListPolicyVersionsOutput) GoString() string { } type ListRolePoliciesInput struct { - // Use this parameter only when paginating results and only after you have received - // a response where the results are truncated. Set it to the value of the Marker - // element in the response you just received. - Marker *string `type:"string"` + // Use this parameter only when paginating results and only after you receive + // a response indicating that the results are truncated. Set it to the value + // of the Marker element in the response you received to inform the next call + // about where to start. + Marker *string `min:"1" type:"string"` // Use this only when paginating results to indicate the maximum number of items // you want in the response. If there are additional items beyond the maximum // you specify, the IsTruncated response element is true. // // This parameter is optional. If you do not include it, it defaults to 100. - MaxItems *int64 `type:"integer"` + // Note that IAM might return fewer results, even when there are more results + // available. If this is the case, the IsTruncated response element returns + // true and Marker contains a value to include in the subsequent call that tells + // the service where to continue from. + MaxItems *int64 `min:"1" type:"integer"` // The name of the role to list policies for. - RoleName *string `type:"string" required:"true"` + RoleName *string `min:"1" type:"string" required:"true"` metadataListRolePoliciesInput `json:"-" xml:"-"` } @@ -8439,12 +8908,15 @@ func (s ListRolePoliciesInput) GoString() string { type ListRolePoliciesOutput struct { // A flag that indicates whether there are more items to return. If your results // were truncated, you can make a subsequent pagination request using the Marker - // request parameter to retrieve more items. + // request parameter to retrieve more items. Note that IAM might return fewer + // than the MaxItems number of results even when there are more results available. + // We recommend that you check IsTruncated after every call to ensure that you + // receive all of your results. IsTruncated *bool `type:"boolean"` // When IsTruncated is true, this element is present and contains the value // to use for the Marker parameter in a subsequent pagination request. - Marker *string `type:"string"` + Marker *string `min:"1" type:"string"` // A list of policy names. PolicyNames []*string `type:"list" required:"true"` @@ -8467,24 +8939,29 @@ func (s ListRolePoliciesOutput) GoString() string { } type ListRolesInput struct { - // Use this parameter only when paginating results and only after you have received - // a response where the results are truncated. Set it to the value of the Marker - // element in the response you just received. - Marker *string `type:"string"` + // Use this parameter only when paginating results and only after you receive + // a response indicating that the results are truncated. Set it to the value + // of the Marker element in the response you received to inform the next call + // about where to start. + Marker *string `min:"1" type:"string"` // Use this only when paginating results to indicate the maximum number of items // you want in the response. If there are additional items beyond the maximum // you specify, the IsTruncated response element is true. // // This parameter is optional. If you do not include it, it defaults to 100. - MaxItems *int64 `type:"integer"` + // Note that IAM might return fewer results, even when there are more results + // available. If this is the case, the IsTruncated response element returns + // true and Marker contains a value to include in the subsequent call that tells + // the service where to continue from. + MaxItems *int64 `min:"1" type:"integer"` // The path prefix for filtering the results. For example, the prefix /application_abc/component_xyz/ // gets all roles whose path starts with /application_abc/component_xyz/. // // This parameter is optional. If it is not included, it defaults to a slash // (/), listing all roles. - PathPrefix *string `type:"string"` + PathPrefix *string `min:"1" type:"string"` metadataListRolesInput `json:"-" xml:"-"` } @@ -8507,12 +8984,15 @@ func (s ListRolesInput) GoString() string { type ListRolesOutput struct { // A flag that indicates whether there are more items to return. If your results // were truncated, you can make a subsequent pagination request using the Marker - // request parameter to retrieve more items. + // request parameter to retrieve more items. Note that IAM might return fewer + // than the MaxItems number of results even when there are more results available. + // We recommend that you check IsTruncated after every call to ensure that you + // receive all of your results. IsTruncated *bool `type:"boolean"` // When IsTruncated is true, this element is present and contains the value // to use for the Marker parameter in a subsequent pagination request. - Marker *string `type:"string"` + Marker *string `min:"1" type:"string"` // A list of roles. Roles []*Role `type:"list" required:"true"` @@ -8575,22 +9055,27 @@ func (s ListSAMLProvidersOutput) GoString() string { } type ListSSHPublicKeysInput struct { - // Use this parameter only when paginating results and only after you have received - // a response where the results are truncated. Set it to the value of the Marker - // element in the response you just received. - Marker *string `type:"string"` + // Use this parameter only when paginating results and only after you receive + // a response indicating that the results are truncated. Set it to the value + // of the Marker element in the response you received to inform the next call + // about where to start. + Marker *string `min:"1" type:"string"` // Use this only when paginating results to indicate the maximum number of items // you want in the response. If there are additional items beyond the maximum // you specify, the IsTruncated response element is true. // // This parameter is optional. If you do not include it, it defaults to 100. - MaxItems *int64 `type:"integer"` + // Note that IAM might return fewer results, even when there are more results + // available. If this is the case, the IsTruncated response element returns + // true and Marker contains a value to include in the subsequent call that tells + // the service where to continue from. + MaxItems *int64 `min:"1" type:"integer"` // The name of the IAM user to list SSH public keys for. If none is specified, // the UserName field is determined implicitly based on the AWS access key used // to sign the request. - UserName *string `type:"string"` + UserName *string `min:"1" type:"string"` metadataListSSHPublicKeysInput `json:"-" xml:"-"` } @@ -8613,12 +9098,15 @@ func (s ListSSHPublicKeysInput) GoString() string { type ListSSHPublicKeysOutput struct { // A flag that indicates whether there are more items to return. If your results // were truncated, you can make a subsequent pagination request using the Marker - // request parameter to retrieve more items. + // request parameter to retrieve more items. Note that IAM might return fewer + // than the MaxItems number of results even when there are more results available. + // We recommend that you check IsTruncated after every call to ensure that you + // receive all of your results. IsTruncated *bool `type:"boolean"` // When IsTruncated is true, this element is present and contains the value // to use for the Marker parameter in a subsequent pagination request. - Marker *string `type:"string"` + Marker *string `min:"1" type:"string"` // A list of SSH public keys. SSHPublicKeys []*SSHPublicKeyMetadata `type:"list"` @@ -8641,24 +9129,29 @@ func (s ListSSHPublicKeysOutput) GoString() string { } type ListServerCertificatesInput struct { - // Use this parameter only when paginating results and only after you have received - // a response where the results are truncated. Set it to the value of the Marker - // element in the response you just received. - Marker *string `type:"string"` + // Use this parameter only when paginating results and only after you receive + // a response indicating that the results are truncated. Set it to the value + // of the Marker element in the response you received to inform the next call + // about where to start. + Marker *string `min:"1" type:"string"` // Use this only when paginating results to indicate the maximum number of items // you want in the response. If there are additional items beyond the maximum // you specify, the IsTruncated response element is true. // // This parameter is optional. If you do not include it, it defaults to 100. - MaxItems *int64 `type:"integer"` + // Note that IAM might return fewer results, even when there are more results + // available. If this is the case, the IsTruncated response element returns + // true and Marker contains a value to include in the subsequent call that tells + // the service where to continue from. + MaxItems *int64 `min:"1" type:"integer"` // The path prefix for filtering the results. For example: /company/servercerts // would get all server certificates for which the path starts with /company/servercerts. // // This parameter is optional. If it is not included, it defaults to a slash // (/), listing all server certificates. - PathPrefix *string `type:"string"` + PathPrefix *string `min:"1" type:"string"` metadataListServerCertificatesInput `json:"-" xml:"-"` } @@ -8681,12 +9174,15 @@ func (s ListServerCertificatesInput) GoString() string { type ListServerCertificatesOutput struct { // A flag that indicates whether there are more items to return. If your results // were truncated, you can make a subsequent pagination request using the Marker - // request parameter to retrieve more items. + // request parameter to retrieve more items. Note that IAM might return fewer + // than the MaxItems number of results even when there are more results available. + // We recommend that you check IsTruncated after every call to ensure that you + // receive all of your results. IsTruncated *bool `type:"boolean"` // When IsTruncated is true, this element is present and contains the value // to use for the Marker parameter in a subsequent pagination request. - Marker *string `type:"string"` + Marker *string `min:"1" type:"string"` // A list of server certificates. ServerCertificateMetadataList []*ServerCertificateMetadata `type:"list" required:"true"` @@ -8709,20 +9205,25 @@ func (s ListServerCertificatesOutput) GoString() string { } type ListSigningCertificatesInput struct { - // Use this parameter only when paginating results and only after you have received - // a response where the results are truncated. Set it to the value of the Marker - // element in the response you just received. - Marker *string `type:"string"` + // Use this parameter only when paginating results and only after you receive + // a response indicating that the results are truncated. Set it to the value + // of the Marker element in the response you received to inform the next call + // about where to start. + Marker *string `min:"1" type:"string"` // Use this only when paginating results to indicate the maximum number of items // you want in the response. If there are additional items beyond the maximum // you specify, the IsTruncated response element is true. // // This parameter is optional. If you do not include it, it defaults to 100. - MaxItems *int64 `type:"integer"` + // Note that IAM might return fewer results, even when there are more results + // available. If this is the case, the IsTruncated response element returns + // true and Marker contains a value to include in the subsequent call that tells + // the service where to continue from. + MaxItems *int64 `min:"1" type:"integer"` // The name of the user. - UserName *string `type:"string"` + UserName *string `min:"1" type:"string"` metadataListSigningCertificatesInput `json:"-" xml:"-"` } @@ -8748,12 +9249,15 @@ type ListSigningCertificatesOutput struct { // A flag that indicates whether there are more items to return. If your results // were truncated, you can make a subsequent pagination request using the Marker - // request parameter to retrieve more items. + // request parameter to retrieve more items. Note that IAM might return fewer + // than the MaxItems number of results even when there are more results available. + // We recommend that you check IsTruncated after every call to ensure that you + // receive all of your results. IsTruncated *bool `type:"boolean"` // When IsTruncated is true, this element is present and contains the value // to use for the Marker parameter in a subsequent pagination request. - Marker *string `type:"string"` + Marker *string `min:"1" type:"string"` metadataListSigningCertificatesOutput `json:"-" xml:"-"` } @@ -8773,20 +9277,25 @@ func (s ListSigningCertificatesOutput) GoString() string { } type ListUserPoliciesInput struct { - // Use this parameter only when paginating results and only after you have received - // a response where the results are truncated. Set it to the value of the Marker - // element in the response you just received. - Marker *string `type:"string"` + // Use this parameter only when paginating results and only after you receive + // a response indicating that the results are truncated. Set it to the value + // of the Marker element in the response you received to inform the next call + // about where to start. + Marker *string `min:"1" type:"string"` // Use this only when paginating results to indicate the maximum number of items // you want in the response. If there are additional items beyond the maximum // you specify, the IsTruncated response element is true. // // This parameter is optional. If you do not include it, it defaults to 100. - MaxItems *int64 `type:"integer"` + // Note that IAM might return fewer results, even when there are more results + // available. If this is the case, the IsTruncated response element returns + // true and Marker contains a value to include in the subsequent call that tells + // the service where to continue from. + MaxItems *int64 `min:"1" type:"integer"` // The name of the user to list policies for. - UserName *string `type:"string" required:"true"` + UserName *string `min:"1" type:"string" required:"true"` metadataListUserPoliciesInput `json:"-" xml:"-"` } @@ -8809,12 +9318,15 @@ func (s ListUserPoliciesInput) GoString() string { type ListUserPoliciesOutput struct { // A flag that indicates whether there are more items to return. If your results // were truncated, you can make a subsequent pagination request using the Marker - // request parameter to retrieve more items. + // request parameter to retrieve more items. Note that IAM might return fewer + // than the MaxItems number of results even when there are more results available. + // We recommend that you check IsTruncated after every call to ensure that you + // receive all of your results. IsTruncated *bool `type:"boolean"` // When IsTruncated is true, this element is present and contains the value // to use for the Marker parameter in a subsequent pagination request. - Marker *string `type:"string"` + Marker *string `min:"1" type:"string"` // A list of policy names. PolicyNames []*string `type:"list" required:"true"` @@ -8837,24 +9349,29 @@ func (s ListUserPoliciesOutput) GoString() string { } type ListUsersInput struct { - // Use this parameter only when paginating results and only after you have received - // a response where the results are truncated. Set it to the value of the Marker - // element in the response you just received. - Marker *string `type:"string"` + // Use this parameter only when paginating results and only after you receive + // a response indicating that the results are truncated. Set it to the value + // of the Marker element in the response you received to inform the next call + // about where to start. + Marker *string `min:"1" type:"string"` // Use this only when paginating results to indicate the maximum number of items // you want in the response. If there are additional items beyond the maximum // you specify, the IsTruncated response element is true. // // This parameter is optional. If you do not include it, it defaults to 100. - MaxItems *int64 `type:"integer"` + // Note that IAM might return fewer results, even when there are more results + // available. If this is the case, the IsTruncated response element returns + // true and Marker contains a value to include in the subsequent call that tells + // the service where to continue from. + MaxItems *int64 `min:"1" type:"integer"` // The path prefix for filtering the results. For example: /division_abc/subdivision_xyz/, // which would get all user names whose path starts with /division_abc/subdivision_xyz/. // // This parameter is optional. If it is not included, it defaults to a slash // (/), listing all user names. - PathPrefix *string `type:"string"` + PathPrefix *string `min:"1" type:"string"` metadataListUsersInput `json:"-" xml:"-"` } @@ -8877,12 +9394,15 @@ func (s ListUsersInput) GoString() string { type ListUsersOutput struct { // A flag that indicates whether there are more items to return. If your results // were truncated, you can make a subsequent pagination request using the Marker - // request parameter to retrieve more items. + // request parameter to retrieve more items. Note that IAM might return fewer + // than the MaxItems number of results even when there are more results available. + // We recommend that you check IsTruncated after every call to ensure that you + // receive all of your results. IsTruncated *bool `type:"boolean"` // When IsTruncated is true, this element is present and contains the value // to use for the Marker parameter in a subsequent pagination request. - Marker *string `type:"string"` + Marker *string `min:"1" type:"string"` // A list of users. Users []*User `type:"list" required:"true"` @@ -8910,17 +9430,22 @@ type ListVirtualMFADevicesInput struct { // assigned and unassigned virtual MFA devices. AssignmentStatus *string `type:"string" enum:"assignmentStatusType"` - // Use this parameter only when paginating results and only after you have received - // a response where the results are truncated. Set it to the value of the Marker - // element in the response you just received. - Marker *string `type:"string"` + // Use this parameter only when paginating results and only after you receive + // a response indicating that the results are truncated. Set it to the value + // of the Marker element in the response you received to inform the next call + // about where to start. + Marker *string `min:"1" type:"string"` // Use this only when paginating results to indicate the maximum number of items // you want in the response. If there are additional items beyond the maximum // you specify, the IsTruncated response element is true. // // This parameter is optional. If you do not include it, it defaults to 100. - MaxItems *int64 `type:"integer"` + // Note that IAM might return fewer results, even when there are more results + // available. If this is the case, the IsTruncated response element returns + // true and Marker contains a value to include in the subsequent call that tells + // the service where to continue from. + MaxItems *int64 `min:"1" type:"integer"` metadataListVirtualMFADevicesInput `json:"-" xml:"-"` } @@ -8943,12 +9468,15 @@ func (s ListVirtualMFADevicesInput) GoString() string { type ListVirtualMFADevicesOutput struct { // A flag that indicates whether there are more items to return. If your results // were truncated, you can make a subsequent pagination request using the Marker - // request parameter to retrieve more items. + // request parameter to retrieve more items. Note that IAM might return fewer + // than the MaxItems number of results even when there are more results available. + // We recommend that you check IsTruncated after every call to ensure that you + // receive all of your results. IsTruncated *bool `type:"boolean"` // When IsTruncated is true, this element is present and contains the value // to use for the Marker parameter in a subsequent pagination request. - Marker *string `type:"string"` + Marker *string `min:"1" type:"string"` // The list of virtual MFA devices in the current account that match the AssignmentStatus // value that was passed in the request. @@ -8984,7 +9512,7 @@ type LoginProfile struct { // The name of the user, which can be used for signing in to the AWS Management // Console. - UserName *string `type:"string" required:"true"` + UserName *string `min:"1" type:"string" required:"true"` metadataLoginProfile `json:"-" xml:"-"` } @@ -9012,10 +9540,10 @@ type MFADevice struct { // The serial number that uniquely identifies the MFA device. For virtual MFA // devices, the serial number is the device ARN. - SerialNumber *string `type:"string" required:"true"` + SerialNumber *string `min:"9" type:"string" required:"true"` // The user with whom the MFA device is associated. - UserName *string `type:"string" required:"true"` + UserName *string `min:"1" type:"string" required:"true"` metadataMFADevice `json:"-" xml:"-"` } @@ -9050,7 +9578,7 @@ type ManagedPolicyDetail struct { // For more information about ARNs, go to Amazon Resource Names (ARNs) and // AWS Service Namespaces (http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) // in the AWS General Reference. - Arn *string `type:"string"` + Arn *string `min:"20" type:"string"` // The number of principal entities (users, groups, and roles) that the policy // is attached to. @@ -9084,10 +9612,10 @@ type ManagedPolicyDetail struct { // // For more information about IDs, see IAM Identifiers (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html) // in the Using IAM guide. - PolicyId *string `type:"string"` + PolicyId *string `min:"16" type:"string"` // The friendly name (not ARN) identifying the policy. - PolicyName *string `type:"string"` + PolicyName *string `min:"1" type:"string"` // A list containing information about the versions of the policy. PolicyVersionList []*PolicyVersion `type:"list"` @@ -9125,7 +9653,7 @@ type OpenIDConnectProviderListEntry struct { // For more information about ARNs, go to Amazon Resource Names (ARNs) and // AWS Service Namespaces (http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) // in the AWS General Reference. - Arn *string `type:"string"` + Arn *string `min:"20" type:"string"` metadataOpenIDConnectProviderListEntry `json:"-" xml:"-"` } @@ -9161,14 +9689,14 @@ type PasswordPolicy struct { HardExpiry *bool `type:"boolean"` // The number of days that an IAM user password is valid. - MaxPasswordAge *int64 `type:"integer"` + MaxPasswordAge *int64 `min:"1" type:"integer"` // Minimum length to require for IAM user passwords. - MinimumPasswordLength *int64 `type:"integer"` + MinimumPasswordLength *int64 `min:"6" type:"integer"` // Specifies the number of previous passwords that IAM users are prevented from // reusing. - PasswordReusePrevention *int64 `type:"integer"` + PasswordReusePrevention *int64 `min:"1" type:"integer"` // Specifies whether to require lowercase characters for IAM user passwords. RequireLowercaseCharacters *bool `type:"boolean"` @@ -9213,7 +9741,7 @@ type Policy struct { // For more information about ARNs, go to Amazon Resource Names (ARNs) and // AWS Service Namespaces (http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) // in the AWS General Reference. - Arn *string `type:"string"` + Arn *string `min:"20" type:"string"` // The number of entities (users, groups, and roles) that the policy is attached // to. @@ -9245,10 +9773,10 @@ type Policy struct { // // For more information about IDs, see IAM Identifiers (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html) // in the Using IAM guide. - PolicyId *string `type:"string"` + PolicyId *string `min:"16" type:"string"` // The friendly name (not ARN) identifying the policy. - PolicyName *string `type:"string"` + PolicyName *string `min:"1" type:"string"` // The date and time, in ISO 8601 date-time format (http://www.iso.org/iso/iso8601), // when the policy was last updated. @@ -9282,10 +9810,10 @@ func (s Policy) GoString() string { // action. type PolicyDetail struct { // The policy document. - PolicyDocument *string `type:"string"` + PolicyDocument *string `min:"1" type:"string"` // The name of the policy. - PolicyName *string `type:"string"` + PolicyName *string `min:"1" type:"string"` metadataPolicyDetail `json:"-" xml:"-"` } @@ -9314,7 +9842,7 @@ func (s PolicyDetail) GoString() string { // in the Using IAM guide. type PolicyGroup struct { // The name (friendly name, not ARN) identifying the group. - GroupName *string `type:"string"` + GroupName *string `min:"1" type:"string"` metadataPolicyGroup `json:"-" xml:"-"` } @@ -9343,7 +9871,7 @@ func (s PolicyGroup) GoString() string { // in the Using IAM guide. type PolicyRole struct { // The name (friendly name, not ARN) identifying the role. - RoleName *string `type:"string"` + RoleName *string `min:"1" type:"string"` metadataPolicyRole `json:"-" xml:"-"` } @@ -9372,7 +9900,7 @@ func (s PolicyRole) GoString() string { // in the Using IAM guide. type PolicyUser struct { // The name (friendly name, not ARN) identifying the user. - UserName *string `type:"string"` + UserName *string `min:"1" type:"string"` metadataPolicyUser `json:"-" xml:"-"` } @@ -9410,7 +9938,7 @@ type PolicyVersion struct { // The policy document is returned in the response to the GetPolicyVersion // and GetAccountAuthorizationDetails operations. It is not returned in the // response to the CreatePolicyVersion or ListPolicyVersions operations. - Document *string `type:"string"` + Document *string `min:"1" type:"string"` // Specifies whether the policy version is set as the policy's default version. IsDefaultVersion *bool `type:"boolean"` @@ -9438,15 +9966,43 @@ func (s PolicyVersion) GoString() string { return s.String() } +// Contains the row and column of a location of a Statement element in a policy +// document. +// +// This data type is used as a member of the Statement type. +type Position struct { + // The column in the line containing the specified position in the document. + Column *int64 `type:"integer"` + + // The line containing the specified position in the document. + Line *int64 `type:"integer"` + + metadataPosition `json:"-" xml:"-"` +} + +type metadataPosition struct { + SDKShapeTraits bool `type:"structure"` +} + +// String returns the string representation +func (s Position) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s Position) GoString() string { + return s.String() +} + type PutGroupPolicyInput struct { // The name of the group to associate the policy with. - GroupName *string `type:"string" required:"true"` + GroupName *string `min:"1" type:"string" required:"true"` // The policy document. - PolicyDocument *string `type:"string" required:"true"` + PolicyDocument *string `min:"1" type:"string" required:"true"` // The name of the policy document. - PolicyName *string `type:"string" required:"true"` + PolicyName *string `min:"1" type:"string" required:"true"` metadataPutGroupPolicyInput `json:"-" xml:"-"` } @@ -9485,13 +10041,13 @@ func (s PutGroupPolicyOutput) GoString() string { type PutRolePolicyInput struct { // The policy document. - PolicyDocument *string `type:"string" required:"true"` + PolicyDocument *string `min:"1" type:"string" required:"true"` // The name of the policy document. - PolicyName *string `type:"string" required:"true"` + PolicyName *string `min:"1" type:"string" required:"true"` // The name of the role to associate the policy with. - RoleName *string `type:"string" required:"true"` + RoleName *string `min:"1" type:"string" required:"true"` metadataPutRolePolicyInput `json:"-" xml:"-"` } @@ -9530,13 +10086,13 @@ func (s PutRolePolicyOutput) GoString() string { type PutUserPolicyInput struct { // The policy document. - PolicyDocument *string `type:"string" required:"true"` + PolicyDocument *string `min:"1" type:"string" required:"true"` // The name of the policy document. - PolicyName *string `type:"string" required:"true"` + PolicyName *string `min:"1" type:"string" required:"true"` // The name of the user to associate the policy with. - UserName *string `type:"string" required:"true"` + UserName *string `min:"1" type:"string" required:"true"` metadataPutUserPolicyInput `json:"-" xml:"-"` } @@ -9576,12 +10132,12 @@ func (s PutUserPolicyOutput) GoString() string { type RemoveClientIDFromOpenIDConnectProviderInput struct { // The client ID (also known as audience) to remove from the IAM OpenID Connect // provider. For more information about client IDs, see CreateOpenIDConnectProvider. - ClientID *string `type:"string" required:"true"` + ClientID *string `min:"1" type:"string" required:"true"` // The Amazon Resource Name (ARN) of the IAM OpenID Connect (OIDC) provider // to remove the client ID from. You can get a list of OIDC provider ARNs by // using the ListOpenIDConnectProviders action. - OpenIDConnectProviderArn *string `type:"string" required:"true"` + OpenIDConnectProviderArn *string `min:"20" type:"string" required:"true"` metadataRemoveClientIDFromOpenIDConnectProviderInput `json:"-" xml:"-"` } @@ -9620,10 +10176,10 @@ func (s RemoveClientIDFromOpenIDConnectProviderOutput) GoString() string { type RemoveRoleFromInstanceProfileInput struct { // The name of the instance profile to update. - InstanceProfileName *string `type:"string" required:"true"` + InstanceProfileName *string `min:"1" type:"string" required:"true"` // The name of the role to remove. - RoleName *string `type:"string" required:"true"` + RoleName *string `min:"1" type:"string" required:"true"` metadataRemoveRoleFromInstanceProfileInput `json:"-" xml:"-"` } @@ -9662,10 +10218,10 @@ func (s RemoveRoleFromInstanceProfileOutput) GoString() string { type RemoveUserFromGroupInput struct { // The name of the group to update. - GroupName *string `type:"string" required:"true"` + GroupName *string `min:"1" type:"string" required:"true"` // The name of the user to remove. - UserName *string `type:"string" required:"true"` + UserName *string `min:"1" type:"string" required:"true"` metadataRemoveUserFromGroupInput `json:"-" xml:"-"` } @@ -9704,16 +10260,16 @@ func (s RemoveUserFromGroupOutput) GoString() string { type ResyncMFADeviceInput struct { // An authentication code emitted by the device. - AuthenticationCode1 *string `type:"string" required:"true"` + AuthenticationCode1 *string `min:"6" type:"string" required:"true"` // A subsequent authentication code emitted by the device. - AuthenticationCode2 *string `type:"string" required:"true"` + AuthenticationCode2 *string `min:"6" type:"string" required:"true"` // Serial number that uniquely identifies the MFA device. - SerialNumber *string `type:"string" required:"true"` + SerialNumber *string `min:"9" type:"string" required:"true"` // The name of the user whose MFA device you want to resynchronize. - UserName *string `type:"string" required:"true"` + UserName *string `min:"1" type:"string" required:"true"` metadataResyncMFADeviceInput `json:"-" xml:"-"` } @@ -9763,10 +10319,10 @@ type Role struct { // The Amazon Resource Name (ARN) specifying the role. For more information // about ARNs and how to use them in policies, see IAM Identifiers (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html) // in the Using IAM guide. - Arn *string `type:"string" required:"true"` + Arn *string `min:"20" type:"string" required:"true"` // The policy that grants an entity permission to assume the role. - AssumeRolePolicyDocument *string `type:"string"` + AssumeRolePolicyDocument *string `min:"1" type:"string"` // The date and time, in ISO 8601 date-time format (http://www.iso.org/iso/iso8601), // when the role was created. @@ -9775,15 +10331,15 @@ type Role struct { // The path to the role. For more information about paths, see IAM Identifiers // (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html) // in the Using IAM guide. - Path *string `type:"string" required:"true"` + Path *string `min:"1" type:"string" required:"true"` // The stable and unique string identifying the role. For more information about // IDs, see IAM Identifiers (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html) // in the Using IAM guide. - RoleId *string `type:"string" required:"true"` + RoleId *string `min:"16" type:"string" required:"true"` // The friendly name that identifies the role. - RoleName *string `type:"string" required:"true"` + RoleName *string `min:"1" type:"string" required:"true"` metadataRole `json:"-" xml:"-"` } @@ -9812,10 +10368,10 @@ type RoleDetail struct { // For more information about ARNs, go to Amazon Resource Names (ARNs) and // AWS Service Namespaces (http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) // in the AWS General Reference. - Arn *string `type:"string"` + Arn *string `min:"20" type:"string"` // The trust policy that grants permission to assume the role. - AssumeRolePolicyDocument *string `type:"string"` + AssumeRolePolicyDocument *string `min:"1" type:"string"` // A list of managed policies attached to the role. These policies are the role's // access (permissions) policies. @@ -9831,15 +10387,15 @@ type RoleDetail struct { // The path to the role. For more information about paths, see IAM Identifiers // (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html) // in the Using IAM guide. - Path *string `type:"string"` + Path *string `min:"1" type:"string"` // The stable and unique string identifying the role. For more information about // IDs, see IAM Identifiers (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html) // in the Using IAM guide. - RoleId *string `type:"string"` + RoleId *string `min:"16" type:"string"` // The friendly name that identifies the role. - RoleName *string `type:"string"` + RoleName *string `min:"1" type:"string"` // A list of inline policies embedded in the role. These policies are the role's // access (permissions) policies. @@ -9865,7 +10421,7 @@ func (s RoleDetail) GoString() string { // Contains the list of SAML providers for this account. type SAMLProviderListEntry struct { // The Amazon Resource Name (ARN) of the SAML provider. - Arn *string `type:"string"` + Arn *string `min:"20" type:"string"` // The date and time when the SAML provider was created. CreateDate *time.Time `type:"timestamp" timestampFormat:"iso8601"` @@ -9896,13 +10452,13 @@ func (s SAMLProviderListEntry) GoString() string { // UploadSSHPublicKey actions. type SSHPublicKey struct { // The MD5 message digest of the SSH public key. - Fingerprint *string `type:"string" required:"true"` + Fingerprint *string `min:"48" type:"string" required:"true"` // The SSH public key. - SSHPublicKeyBody *string `type:"string" required:"true"` + SSHPublicKeyBody *string `min:"1" type:"string" required:"true"` // The unique identifier for the SSH public key. - SSHPublicKeyId *string `type:"string" required:"true"` + SSHPublicKeyId *string `min:"20" type:"string" required:"true"` // The status of the SSH public key. Active means the key can be used for authentication // with an AWS CodeCommit repository. Inactive means the key cannot be used. @@ -9913,7 +10469,7 @@ type SSHPublicKey struct { UploadDate *time.Time `type:"timestamp" timestampFormat:"iso8601"` // The name of the IAM user associated with the SSH public key. - UserName *string `type:"string" required:"true"` + UserName *string `min:"1" type:"string" required:"true"` metadataSSHPublicKey `json:"-" xml:"-"` } @@ -9937,7 +10493,7 @@ func (s SSHPublicKey) GoString() string { // This data type is used as a response element in the ListSSHPublicKeys action. type SSHPublicKeyMetadata struct { // The unique identifier for the SSH public key. - SSHPublicKeyId *string `type:"string" required:"true"` + SSHPublicKeyId *string `min:"20" type:"string" required:"true"` // The status of the SSH public key. Active means the key can be used for authentication // with an AWS CodeCommit repository. Inactive means the key cannot be used. @@ -9948,7 +10504,7 @@ type SSHPublicKeyMetadata struct { UploadDate *time.Time `type:"timestamp" timestampFormat:"iso8601" required:"true"` // The name of the IAM user associated with the SSH public key. - UserName *string `type:"string" required:"true"` + UserName *string `min:"1" type:"string" required:"true"` metadataSSHPublicKeyMetadata `json:"-" xml:"-"` } @@ -9973,10 +10529,10 @@ func (s SSHPublicKeyMetadata) GoString() string { // action. type ServerCertificate struct { // The contents of the public key certificate. - CertificateBody *string `type:"string" required:"true"` + CertificateBody *string `min:"1" type:"string" required:"true"` // The contents of the public key certificate chain. - CertificateChain *string `type:"string"` + CertificateChain *string `min:"1" type:"string"` // The meta information of the server certificate, such as its name, path, ID, // and ARN. @@ -10009,7 +10565,7 @@ type ServerCertificateMetadata struct { // information about ARNs and how to use them in policies, see IAM Identifiers // (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html) // in the Using IAM guide. - Arn *string `type:"string" required:"true"` + Arn *string `min:"20" type:"string" required:"true"` // The date on which the certificate is set to expire. Expiration *time.Time `type:"timestamp" timestampFormat:"iso8601"` @@ -10017,15 +10573,15 @@ type ServerCertificateMetadata struct { // The path to the server certificate. For more information about paths, see // IAM Identifiers (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html) // in the Using IAM guide. - Path *string `type:"string" required:"true"` + Path *string `min:"1" type:"string" required:"true"` // The stable and unique string identifying the server certificate. For more // information about IDs, see IAM Identifiers (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html) // in the Using IAM guide. - ServerCertificateId *string `type:"string" required:"true"` + ServerCertificateId *string `min:"16" type:"string" required:"true"` // The name that identifies the server certificate. - ServerCertificateName *string `type:"string" required:"true"` + ServerCertificateName *string `min:"1" type:"string" required:"true"` // The date when the server certificate was uploaded. UploadDate *time.Time `type:"timestamp" timestampFormat:"iso8601"` @@ -10053,13 +10609,13 @@ type SetDefaultPolicyVersionInput struct { // For more information about ARNs, go to Amazon Resource Names (ARNs) and // AWS Service Namespaces (http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) // in the AWS General Reference. - PolicyArn *string `type:"string" required:"true"` + PolicyArn *string `min:"20" type:"string" required:"true"` // The version of the policy to set as the default (operative) version. // // For more information about managed policy versions, see Versioning for Managed // Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-versions.html) - // in the Using IAM guide. + // in the IAM User Guide. VersionId *string `type:"string" required:"true"` metadataSetDefaultPolicyVersionInput `json:"-" xml:"-"` @@ -10103,10 +10659,10 @@ func (s SetDefaultPolicyVersionOutput) GoString() string { // and ListSigningCertificates actions. type SigningCertificate struct { // The contents of the signing certificate. - CertificateBody *string `type:"string" required:"true"` + CertificateBody *string `min:"1" type:"string" required:"true"` // The ID for the signing certificate. - CertificateId *string `type:"string" required:"true"` + CertificateId *string `min:"24" type:"string" required:"true"` // The status of the signing certificate. Active means the key is valid for // API calls, while Inactive means it is not. @@ -10116,7 +10672,7 @@ type SigningCertificate struct { UploadDate *time.Time `type:"timestamp" timestampFormat:"iso8601"` // The name of the user the signing certificate is associated with. - UserName *string `type:"string" required:"true"` + UserName *string `min:"1" type:"string" required:"true"` metadataSigningCertificate `json:"-" xml:"-"` } @@ -10135,9 +10691,200 @@ func (s SigningCertificate) GoString() string { return s.String() } +type SimulateCustomPolicyInput struct { + // A list of names of API actions to evaluate in the simulation. Each action + // is evaluated for each resource. Each action must include the service identifier, + // such as iam:CreateUser. + ActionNames []*string `type:"list" required:"true"` + + // A list of context keys and corresponding values that are used by the simulation. + // Whenever a context key is evaluated by a Condition element in one of the + // simulated IAM permission policies, the corresponding value is supplied. + ContextEntries []*ContextEntry `type:"list"` + + // Use this parameter only when paginating results and only after you receive + // a response indicating that the results are truncated. Set it to the value + // of the Marker element in the response you received to inform the next call + // about where to start. + Marker *string `min:"1" type:"string"` + + // Use this only when paginating results to indicate the maximum number of items + // you want in the response. If there are additional items beyond the maximum + // you specify, the IsTruncated response element is true. + // + // This parameter is optional. If you do not include it, it defaults to 100. + // Note that IAM might return fewer results, even when there are more results + // available. If this is the case, the IsTruncated response element returns + // true and Marker contains a value to include in the subsequent call that tells + // the service where to continue from. + MaxItems *int64 `min:"1" type:"integer"` + + // A list of policy documents to include in the simulation. Each document is + // specified as a string containing the complete, valid JSON text of an IAM + // policy. + PolicyInputList []*string `type:"list" required:"true"` + + // A list of ARNs of AWS resources to include in the simulation. If this parameter + // is not provided then the value defaults to * (all resources). Each API in + // the ActionNames parameter is evaluated for each resource in this list. The + // simulation determines the access result (allowed or denied) of each combination + // and reports it in the response. + ResourceArns []*string `type:"list"` + + metadataSimulateCustomPolicyInput `json:"-" xml:"-"` +} + +type metadataSimulateCustomPolicyInput struct { + SDKShapeTraits bool `type:"structure"` +} + +// String returns the string representation +func (s SimulateCustomPolicyInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s SimulateCustomPolicyInput) GoString() string { + return s.String() +} + +// Contains the response to a successful SimulatePrincipalPolicy or SimulateCustomPolicy +// request. +type SimulatePolicyResponse struct { + // The results of the simulation. + EvaluationResults []*EvaluationResult `type:"list"` + + // A flag that indicates whether there are more items to return. If your results + // were truncated, you can make a subsequent pagination request using the Marker + // request parameter to retrieve more items. Note that IAM might return fewer + // than the MaxItems number of results even when there are more results available. + // We recommend that you check IsTruncated after every call to ensure that you + // receive all of your results. + IsTruncated *bool `type:"boolean"` + + // When IsTruncated is true, this element is present and contains the value + // to use for the Marker parameter in a subsequent pagination request. + Marker *string `min:"1" type:"string"` + + metadataSimulatePolicyResponse `json:"-" xml:"-"` +} + +type metadataSimulatePolicyResponse struct { + SDKShapeTraits bool `type:"structure"` +} + +// String returns the string representation +func (s SimulatePolicyResponse) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s SimulatePolicyResponse) GoString() string { + return s.String() +} + +type SimulatePrincipalPolicyInput struct { + // A list of names of API actions to evaluate in the simulation. Each action + // is evaluated for each resource. Each action must include the service identifier, + // such as iam:CreateUser. + ActionNames []*string `type:"list" required:"true"` + + // A list of context keys and corresponding values that are used by the simulation. + // Whenever a context key is evaluated by a Condition element in one of the + // simulated IAM permission policies, the corresponding value is supplied. + ContextEntries []*ContextEntry `type:"list"` + + // Use this parameter only when paginating results and only after you receive + // a response indicating that the results are truncated. Set it to the value + // of the Marker element in the response you received to inform the next call + // about where to start. + Marker *string `min:"1" type:"string"` + + // Use this only when paginating results to indicate the maximum number of items + // you want in the response. If there are additional items beyond the maximum + // you specify, the IsTruncated response element is true. + // + // This parameter is optional. If you do not include it, it defaults to 100. + // Note that IAM might return fewer results, even when there are more results + // available. If this is the case, the IsTruncated response element returns + // true and Marker contains a value to include in the subsequent call that tells + // the service where to continue from. + MaxItems *int64 `min:"1" type:"integer"` + + // An optional list of additional policy documents to include in the simulation. + // Each document is specified as a string containing the complete, valid JSON + // text of an IAM policy. + PolicyInputList []*string `type:"list"` + + // The Amazon Resource Name (ARN) of a user, group, or role whose policies you + // want to include in the simulation. If you specify a user, group, or role, + // the simulation includes all policies associated with that entity. If you + // specify a user, the simulation also includes all policies attached to any + // groups the user is a member of. + PolicySourceArn *string `min:"20" type:"string" required:"true"` + + // A list of ARNs of AWS resources to include in the simulation. If this parameter + // is not provided then the value defaults to * (all resources). Each API in + // the ActionNames parameter is evaluated for each resource in this list. The + // simulation determines the access result (allowed or denied) of each combination + // and reports it in the response. + ResourceArns []*string `type:"list"` + + metadataSimulatePrincipalPolicyInput `json:"-" xml:"-"` +} + +type metadataSimulatePrincipalPolicyInput struct { + SDKShapeTraits bool `type:"structure"` +} + +// String returns the string representation +func (s SimulatePrincipalPolicyInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s SimulatePrincipalPolicyInput) GoString() string { + return s.String() +} + +// Contains a reference to a Statement element in a policy document that determines +// the result of the simulation. +// +// This data type is used by the MatchedStatements member of the EvaluationResult +// type. +type Statement struct { + // The row and column of the end of a Statement in an IAM policy. + EndPosition *Position `type:"structure"` + + // The identifier of the policy that was provided as an input. + SourcePolicyId *string `type:"string"` + + // The type of the policy. + SourcePolicyType *string `type:"string" enum:"PolicySourceType"` + + // The row and column of the beginning of the Statement in an IAM policy. + StartPosition *Position `type:"structure"` + + metadataStatement `json:"-" xml:"-"` +} + +type metadataStatement struct { + SDKShapeTraits bool `type:"structure"` +} + +// String returns the string representation +func (s Statement) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s Statement) GoString() string { + return s.String() +} + type UpdateAccessKeyInput struct { // The access key ID of the secret access key you want to update. - AccessKeyId *string `type:"string" required:"true"` + AccessKeyId *string `min:"16" type:"string" required:"true"` // The status you want to assign to the secret access key. Active means the // key can be used for API calls to AWS, while Inactive means the key cannot @@ -10145,7 +10892,7 @@ type UpdateAccessKeyInput struct { Status *string `type:"string" required:"true" enum:"statusType"` // The name of the user whose key you want to update. - UserName *string `type:"string"` + UserName *string `min:"1" type:"string"` metadataUpdateAccessKeyInput `json:"-" xml:"-"` } @@ -10186,7 +10933,7 @@ type UpdateAccountPasswordPolicyInput struct { // Allows all IAM users in your account to use the AWS Management Console to // change their own passwords. For more information, see Letting IAM Users Change // Their Own Passwords (http://docs.aws.amazon.com/IAM/latest/UserGuide/HowToPwdIAMUser.html) - // in the Using IAM guide. + // in the IAM User Guide. // // Default value: false AllowUsersToChangePassword *bool `type:"boolean"` @@ -10200,19 +10947,19 @@ type UpdateAccountPasswordPolicyInput struct { // of 0 means IAM user passwords never expire. // // Default value: 0 - MaxPasswordAge *int64 `type:"integer"` + MaxPasswordAge *int64 `min:"1" type:"integer"` // The minimum number of characters allowed in an IAM user password. // // Default value: 6 - MinimumPasswordLength *int64 `type:"integer"` + MinimumPasswordLength *int64 `min:"6" type:"integer"` // Specifies the number of previous passwords that IAM users are prevented from // reusing. The default value of 0 means IAM users are not prevented from reusing // previous passwords. // // Default value: 0 - PasswordReusePrevention *int64 `type:"integer"` + PasswordReusePrevention *int64 `min:"1" type:"integer"` // Specifies whether IAM user passwords must contain at least one lowercase // character from the ISO basic Latin alphabet (a to z). @@ -10277,10 +11024,10 @@ func (s UpdateAccountPasswordPolicyOutput) GoString() string { type UpdateAssumeRolePolicyInput struct { // The policy that grants an entity permission to assume the role. - PolicyDocument *string `type:"string" required:"true"` + PolicyDocument *string `min:"1" type:"string" required:"true"` // The name of the role to update. - RoleName *string `type:"string" required:"true"` + RoleName *string `min:"1" type:"string" required:"true"` metadataUpdateAssumeRolePolicyInput `json:"-" xml:"-"` } @@ -10320,13 +11067,13 @@ func (s UpdateAssumeRolePolicyOutput) GoString() string { type UpdateGroupInput struct { // Name of the group to update. If you're changing the name of the group, this // is the original name. - GroupName *string `type:"string" required:"true"` + GroupName *string `min:"1" type:"string" required:"true"` // New name for the group. Only include this if changing the group's name. - NewGroupName *string `type:"string"` + NewGroupName *string `min:"1" type:"string"` // New path for the group. Only include this if changing the group's path. - NewPath *string `type:"string"` + NewPath *string `min:"1" type:"string"` metadataUpdateGroupInput `json:"-" xml:"-"` } @@ -10365,13 +11112,13 @@ func (s UpdateGroupOutput) GoString() string { type UpdateLoginProfileInput struct { // The new password for the specified user. - Password *string `type:"string"` + Password *string `min:"1" type:"string"` // Require the specified user to set a new password on next sign-in. PasswordResetRequired *bool `type:"boolean"` // The name of the user whose password you want to update. - UserName *string `type:"string" required:"true"` + UserName *string `min:"1" type:"string" required:"true"` metadataUpdateLoginProfileInput `json:"-" xml:"-"` } @@ -10412,7 +11159,7 @@ type UpdateOpenIDConnectProviderThumbprintInput struct { // The Amazon Resource Name (ARN) of the IAM OpenID Connect (OIDC) provider // to update the thumbprint for. You can get a list of OIDC provider ARNs by // using the ListOpenIDConnectProviders action. - OpenIDConnectProviderArn *string `type:"string" required:"true"` + OpenIDConnectProviderArn *string `min:"20" type:"string" required:"true"` // A list of certificate thumbprints that are associated with the specified // IAM OpenID Connect provider. For more information, see CreateOpenIDConnectProvider. @@ -10459,10 +11206,10 @@ type UpdateSAMLProviderInput struct { // keys that can be used to validate the SAML authentication response (assertions) // that are received from the IdP. You must generate the metadata document using // the identity management software that is used as your organization's IdP. - SAMLMetadataDocument *string `type:"string" required:"true"` + SAMLMetadataDocument *string `min:"1000" type:"string" required:"true"` // The Amazon Resource Name (ARN) of the SAML provider to update. - SAMLProviderArn *string `type:"string" required:"true"` + SAMLProviderArn *string `min:"20" type:"string" required:"true"` metadataUpdateSAMLProviderInput `json:"-" xml:"-"` } @@ -10484,7 +11231,7 @@ func (s UpdateSAMLProviderInput) GoString() string { // Contains the response to a successful UpdateSAMLProvider request. type UpdateSAMLProviderOutput struct { // The Amazon Resource Name (ARN) of the SAML provider that was updated. - SAMLProviderArn *string `type:"string"` + SAMLProviderArn *string `min:"20" type:"string"` metadataUpdateSAMLProviderOutput `json:"-" xml:"-"` } @@ -10505,7 +11252,7 @@ func (s UpdateSAMLProviderOutput) GoString() string { type UpdateSSHPublicKeyInput struct { // The unique identifier for the SSH public key. - SSHPublicKeyId *string `type:"string" required:"true"` + SSHPublicKeyId *string `min:"20" type:"string" required:"true"` // The status to assign to the SSH public key. Active means the key can be used // for authentication with an AWS CodeCommit repository. Inactive means the @@ -10513,7 +11260,7 @@ type UpdateSSHPublicKeyInput struct { Status *string `type:"string" required:"true" enum:"statusType"` // The name of the IAM user associated with the SSH public key. - UserName *string `type:"string" required:"true"` + UserName *string `min:"1" type:"string" required:"true"` metadataUpdateSSHPublicKeyInput `json:"-" xml:"-"` } @@ -10553,15 +11300,15 @@ func (s UpdateSSHPublicKeyOutput) GoString() string { type UpdateServerCertificateInput struct { // The new path for the server certificate. Include this only if you are updating // the server certificate's path. - NewPath *string `type:"string"` + NewPath *string `min:"1" type:"string"` // The new name for the server certificate. Include this only if you are updating // the server certificate's name. The name of the certificate cannot contain // any spaces. - NewServerCertificateName *string `type:"string"` + NewServerCertificateName *string `min:"1" type:"string"` // The name of the server certificate that you want to update. - ServerCertificateName *string `type:"string" required:"true"` + ServerCertificateName *string `min:"1" type:"string" required:"true"` metadataUpdateServerCertificateInput `json:"-" xml:"-"` } @@ -10600,7 +11347,7 @@ func (s UpdateServerCertificateOutput) GoString() string { type UpdateSigningCertificateInput struct { // The ID of the signing certificate you want to update. - CertificateId *string `type:"string" required:"true"` + CertificateId *string `min:"24" type:"string" required:"true"` // The status you want to assign to the certificate. Active means the certificate // can be used for API calls to AWS, while Inactive means the certificate cannot @@ -10608,7 +11355,7 @@ type UpdateSigningCertificateInput struct { Status *string `type:"string" required:"true" enum:"statusType"` // The name of the user the signing certificate belongs to. - UserName *string `type:"string"` + UserName *string `min:"1" type:"string"` metadataUpdateSigningCertificateInput `json:"-" xml:"-"` } @@ -10648,15 +11395,15 @@ func (s UpdateSigningCertificateOutput) GoString() string { type UpdateUserInput struct { // New path for the user. Include this parameter only if you're changing the // user's path. - NewPath *string `type:"string"` + NewPath *string `min:"1" type:"string"` // New name for the user. Include this parameter only if you're changing the // user's name. - NewUserName *string `type:"string"` + NewUserName *string `min:"1" type:"string"` // Name of the user to update. If you're changing the name of the user, this // is the original user name. - UserName *string `type:"string" required:"true"` + UserName *string `min:"1" type:"string" required:"true"` metadataUpdateUserInput `json:"-" xml:"-"` } @@ -10696,10 +11443,10 @@ func (s UpdateUserOutput) GoString() string { type UploadSSHPublicKeyInput struct { // The SSH public key. The public key must be encoded in ssh-rsa format or PEM // format. - SSHPublicKeyBody *string `type:"string" required:"true"` + SSHPublicKeyBody *string `min:"1" type:"string" required:"true"` // The name of the IAM user to associate the SSH public key with. - UserName *string `type:"string" required:"true"` + UserName *string `min:"1" type:"string" required:"true"` metadataUploadSSHPublicKeyInput `json:"-" xml:"-"` } @@ -10742,11 +11489,11 @@ func (s UploadSSHPublicKeyOutput) GoString() string { type UploadServerCertificateInput struct { // The contents of the public key certificate in PEM-encoded format. - CertificateBody *string `type:"string" required:"true"` + CertificateBody *string `min:"1" type:"string" required:"true"` // The contents of the certificate chain. This is typically a concatenation // of the PEM-encoded public key certificates of the chain. - CertificateChain *string `type:"string"` + CertificateChain *string `min:"1" type:"string"` // The path for the server certificate. For more information about paths, see // IAM Identifiers (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html) @@ -10759,14 +11506,14 @@ type UploadServerCertificateInput struct { // CloudFront distributions, you must specify a path using the --path option. // The path must begin with /cloudfront and must include a trailing slash (for // example, /cloudfront/test/). - Path *string `type:"string"` + Path *string `min:"1" type:"string"` // The contents of the private key in PEM-encoded format. - PrivateKey *string `type:"string" required:"true"` + PrivateKey *string `min:"1" type:"string" required:"true"` // The name for the server certificate. Do not include the path in this value. // The name of the certificate cannot contain any spaces. - ServerCertificateName *string `type:"string" required:"true"` + ServerCertificateName *string `min:"1" type:"string" required:"true"` metadataUploadServerCertificateInput `json:"-" xml:"-"` } @@ -10810,10 +11557,10 @@ func (s UploadServerCertificateOutput) GoString() string { type UploadSigningCertificateInput struct { // The contents of the signing certificate. - CertificateBody *string `type:"string" required:"true"` + CertificateBody *string `min:"1" type:"string" required:"true"` // The name of the user the signing certificate is for. - UserName *string `type:"string"` + UserName *string `min:"1" type:"string"` metadataUploadSigningCertificateInput `json:"-" xml:"-"` } @@ -10867,7 +11614,7 @@ type User struct { // The Amazon Resource Name (ARN) that identifies the user. For more information // about ARNs and how to use ARNs in policies, see IAM Identifiers (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html) // in the Using IAM guide. - Arn *string `type:"string" required:"true"` + Arn *string `min:"20" type:"string" required:"true"` // The date and time, in ISO 8601 date-time format (http://www.iso.org/iso/iso8601), // when the user was created. @@ -10894,15 +11641,15 @@ type User struct { // The path to the user. For more information about paths, see IAM Identifiers // (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html) // in the Using IAM guide. - Path *string `type:"string" required:"true"` + Path *string `min:"1" type:"string" required:"true"` // The stable and unique string identifying the user. For more information about // IDs, see IAM Identifiers (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html) // in the Using IAM guide. - UserId *string `type:"string" required:"true"` + UserId *string `min:"16" type:"string" required:"true"` // The friendly name identifying the user. - UserName *string `type:"string" required:"true"` + UserName *string `min:"1" type:"string" required:"true"` metadataUser `json:"-" xml:"-"` } @@ -10932,7 +11679,7 @@ type UserDetail struct { // For more information about ARNs, go to Amazon Resource Names (ARNs) and // AWS Service Namespaces (http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) // in the AWS General Reference. - Arn *string `type:"string"` + Arn *string `min:"20" type:"string"` // A list of the managed policies attached to the user. AttachedManagedPolicies []*AttachedPolicy `type:"list"` @@ -10947,15 +11694,15 @@ type UserDetail struct { // The path to the user. For more information about paths, see IAM Identifiers // (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html) // in the Using IAM guide. - Path *string `type:"string"` + Path *string `min:"1" type:"string"` // The stable and unique string identifying the user. For more information about // IDs, see IAM Identifiers (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html) // in the Using IAM guide. - UserId *string `type:"string"` + UserId *string `min:"16" type:"string"` // The friendly name identifying the user. - UserName *string `type:"string"` + UserName *string `min:"1" type:"string"` // A list of the inline policies embedded in the user. UserPolicyList []*PolicyDetail `type:"list"` @@ -10993,7 +11740,7 @@ type VirtualMFADevice struct { QRCodePNG []byte `type:"blob"` // The serial number associated with VirtualMFADevice. - SerialNumber *string `type:"string" required:"true"` + SerialNumber *string `min:"9" type:"string" required:"true"` // Contains information about an IAM user entity. // @@ -11023,6 +11770,33 @@ func (s VirtualMFADevice) GoString() string { return s.String() } +const ( + // @enum ContextKeyTypeEnum + ContextKeyTypeEnumString = "string" + // @enum ContextKeyTypeEnum + ContextKeyTypeEnumStringList = "stringList" + // @enum ContextKeyTypeEnum + ContextKeyTypeEnumNumeric = "numeric" + // @enum ContextKeyTypeEnum + ContextKeyTypeEnumNumericList = "numericList" + // @enum ContextKeyTypeEnum + ContextKeyTypeEnumBoolean = "boolean" + // @enum ContextKeyTypeEnum + ContextKeyTypeEnumBooleanList = "booleanList" + // @enum ContextKeyTypeEnum + ContextKeyTypeEnumIp = "ip" + // @enum ContextKeyTypeEnum + ContextKeyTypeEnumIpList = "ipList" + // @enum ContextKeyTypeEnum + ContextKeyTypeEnumBinary = "binary" + // @enum ContextKeyTypeEnum + ContextKeyTypeEnumBinaryList = "binaryList" + // @enum ContextKeyTypeEnum + ContextKeyTypeEnumDate = "date" + // @enum ContextKeyTypeEnum + ContextKeyTypeEnumDateList = "dateList" +) + const ( // @enum EntityType EntityTypeUser = "User" @@ -11036,6 +11810,30 @@ const ( EntityTypeAwsmanagedPolicy = "AWSManagedPolicy" ) +const ( + // @enum PolicyEvaluationDecisionType + PolicyEvaluationDecisionTypeAllowed = "allowed" + // @enum PolicyEvaluationDecisionType + PolicyEvaluationDecisionTypeExplicitDeny = "explicitDeny" + // @enum PolicyEvaluationDecisionType + PolicyEvaluationDecisionTypeImplicitDeny = "implicitDeny" +) + +const ( + // @enum PolicySourceType + PolicySourceTypeUser = "user" + // @enum PolicySourceType + PolicySourceTypeGroup = "group" + // @enum PolicySourceType + PolicySourceTypeRole = "role" + // @enum PolicySourceType + PolicySourceTypeAwsManaged = "aws-managed" + // @enum PolicySourceType + PolicySourceTypeUserManaged = "user-managed" + // @enum PolicySourceType + PolicySourceTypeNone = "none" +) + const ( // @enum ReportFormatType ReportFormatTypeTextCsv = "text/csv" diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/iam/examples_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/iam/examples_test.go deleted file mode 100644 index 09798c2ab..000000000 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/iam/examples_test.go +++ /dev/null @@ -1,3099 +0,0 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. - -package iam_test - -import ( - "bytes" - "fmt" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/awsutil" - "github.com/aws/aws-sdk-go/service/iam" -) - -var _ time.Duration -var _ bytes.Buffer - -func ExampleIAM_AddClientIDToOpenIDConnectProvider() { - svc := iam.New(nil) - - params := &iam.AddClientIDToOpenIDConnectProviderInput{ - ClientID: aws.String("clientIDType"), // Required - OpenIDConnectProviderArn: aws.String("arnType"), // Required - } - resp, err := svc.AddClientIDToOpenIDConnectProvider(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_AddRoleToInstanceProfile() { - svc := iam.New(nil) - - params := &iam.AddRoleToInstanceProfileInput{ - InstanceProfileName: aws.String("instanceProfileNameType"), // Required - RoleName: aws.String("roleNameType"), // Required - } - resp, err := svc.AddRoleToInstanceProfile(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_AddUserToGroup() { - svc := iam.New(nil) - - params := &iam.AddUserToGroupInput{ - GroupName: aws.String("groupNameType"), // Required - UserName: aws.String("existingUserNameType"), // Required - } - resp, err := svc.AddUserToGroup(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_AttachGroupPolicy() { - svc := iam.New(nil) - - params := &iam.AttachGroupPolicyInput{ - GroupName: aws.String("groupNameType"), // Required - PolicyArn: aws.String("arnType"), // Required - } - resp, err := svc.AttachGroupPolicy(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_AttachRolePolicy() { - svc := iam.New(nil) - - params := &iam.AttachRolePolicyInput{ - PolicyArn: aws.String("arnType"), // Required - RoleName: aws.String("roleNameType"), // Required - } - resp, err := svc.AttachRolePolicy(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_AttachUserPolicy() { - svc := iam.New(nil) - - params := &iam.AttachUserPolicyInput{ - PolicyArn: aws.String("arnType"), // Required - UserName: aws.String("userNameType"), // Required - } - resp, err := svc.AttachUserPolicy(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_ChangePassword() { - svc := iam.New(nil) - - params := &iam.ChangePasswordInput{ - NewPassword: aws.String("passwordType"), // Required - OldPassword: aws.String("passwordType"), // Required - } - resp, err := svc.ChangePassword(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_CreateAccessKey() { - svc := iam.New(nil) - - params := &iam.CreateAccessKeyInput{ - UserName: aws.String("existingUserNameType"), - } - resp, err := svc.CreateAccessKey(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_CreateAccountAlias() { - svc := iam.New(nil) - - params := &iam.CreateAccountAliasInput{ - AccountAlias: aws.String("accountAliasType"), // Required - } - resp, err := svc.CreateAccountAlias(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_CreateGroup() { - svc := iam.New(nil) - - params := &iam.CreateGroupInput{ - GroupName: aws.String("groupNameType"), // Required - Path: aws.String("pathType"), - } - resp, err := svc.CreateGroup(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_CreateInstanceProfile() { - svc := iam.New(nil) - - params := &iam.CreateInstanceProfileInput{ - InstanceProfileName: aws.String("instanceProfileNameType"), // Required - Path: aws.String("pathType"), - } - resp, err := svc.CreateInstanceProfile(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_CreateLoginProfile() { - svc := iam.New(nil) - - params := &iam.CreateLoginProfileInput{ - Password: aws.String("passwordType"), // Required - UserName: aws.String("userNameType"), // Required - PasswordResetRequired: aws.Bool(true), - } - resp, err := svc.CreateLoginProfile(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_CreateOpenIDConnectProvider() { - svc := iam.New(nil) - - params := &iam.CreateOpenIDConnectProviderInput{ - ThumbprintList: []*string{ // Required - aws.String("thumbprintType"), // Required - // More values... - }, - Url: aws.String("OpenIDConnectProviderUrlType"), // Required - ClientIDList: []*string{ - aws.String("clientIDType"), // Required - // More values... - }, - } - resp, err := svc.CreateOpenIDConnectProvider(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_CreatePolicy() { - svc := iam.New(nil) - - params := &iam.CreatePolicyInput{ - PolicyDocument: aws.String("policyDocumentType"), // Required - PolicyName: aws.String("policyNameType"), // Required - Description: aws.String("policyDescriptionType"), - Path: aws.String("policyPathType"), - } - resp, err := svc.CreatePolicy(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_CreatePolicyVersion() { - svc := iam.New(nil) - - params := &iam.CreatePolicyVersionInput{ - PolicyArn: aws.String("arnType"), // Required - PolicyDocument: aws.String("policyDocumentType"), // Required - SetAsDefault: aws.Bool(true), - } - resp, err := svc.CreatePolicyVersion(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_CreateRole() { - svc := iam.New(nil) - - params := &iam.CreateRoleInput{ - AssumeRolePolicyDocument: aws.String("policyDocumentType"), // Required - RoleName: aws.String("roleNameType"), // Required - Path: aws.String("pathType"), - } - resp, err := svc.CreateRole(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_CreateSAMLProvider() { - svc := iam.New(nil) - - params := &iam.CreateSAMLProviderInput{ - Name: aws.String("SAMLProviderNameType"), // Required - SAMLMetadataDocument: aws.String("SAMLMetadataDocumentType"), // Required - } - resp, err := svc.CreateSAMLProvider(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_CreateUser() { - svc := iam.New(nil) - - params := &iam.CreateUserInput{ - UserName: aws.String("userNameType"), // Required - Path: aws.String("pathType"), - } - resp, err := svc.CreateUser(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_CreateVirtualMFADevice() { - svc := iam.New(nil) - - params := &iam.CreateVirtualMFADeviceInput{ - VirtualMFADeviceName: aws.String("virtualMFADeviceName"), // Required - Path: aws.String("pathType"), - } - resp, err := svc.CreateVirtualMFADevice(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_DeactivateMFADevice() { - svc := iam.New(nil) - - params := &iam.DeactivateMFADeviceInput{ - SerialNumber: aws.String("serialNumberType"), // Required - UserName: aws.String("existingUserNameType"), // Required - } - resp, err := svc.DeactivateMFADevice(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_DeleteAccessKey() { - svc := iam.New(nil) - - params := &iam.DeleteAccessKeyInput{ - AccessKeyId: aws.String("accessKeyIdType"), // Required - UserName: aws.String("existingUserNameType"), - } - resp, err := svc.DeleteAccessKey(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_DeleteAccountAlias() { - svc := iam.New(nil) - - params := &iam.DeleteAccountAliasInput{ - AccountAlias: aws.String("accountAliasType"), // Required - } - resp, err := svc.DeleteAccountAlias(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_DeleteAccountPasswordPolicy() { - svc := iam.New(nil) - - var params *iam.DeleteAccountPasswordPolicyInput - resp, err := svc.DeleteAccountPasswordPolicy(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_DeleteGroup() { - svc := iam.New(nil) - - params := &iam.DeleteGroupInput{ - GroupName: aws.String("groupNameType"), // Required - } - resp, err := svc.DeleteGroup(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_DeleteGroupPolicy() { - svc := iam.New(nil) - - params := &iam.DeleteGroupPolicyInput{ - GroupName: aws.String("groupNameType"), // Required - PolicyName: aws.String("policyNameType"), // Required - } - resp, err := svc.DeleteGroupPolicy(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_DeleteInstanceProfile() { - svc := iam.New(nil) - - params := &iam.DeleteInstanceProfileInput{ - InstanceProfileName: aws.String("instanceProfileNameType"), // Required - } - resp, err := svc.DeleteInstanceProfile(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_DeleteLoginProfile() { - svc := iam.New(nil) - - params := &iam.DeleteLoginProfileInput{ - UserName: aws.String("userNameType"), // Required - } - resp, err := svc.DeleteLoginProfile(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_DeleteOpenIDConnectProvider() { - svc := iam.New(nil) - - params := &iam.DeleteOpenIDConnectProviderInput{ - OpenIDConnectProviderArn: aws.String("arnType"), // Required - } - resp, err := svc.DeleteOpenIDConnectProvider(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_DeletePolicy() { - svc := iam.New(nil) - - params := &iam.DeletePolicyInput{ - PolicyArn: aws.String("arnType"), // Required - } - resp, err := svc.DeletePolicy(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_DeletePolicyVersion() { - svc := iam.New(nil) - - params := &iam.DeletePolicyVersionInput{ - PolicyArn: aws.String("arnType"), // Required - VersionId: aws.String("policyVersionIdType"), // Required - } - resp, err := svc.DeletePolicyVersion(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_DeleteRole() { - svc := iam.New(nil) - - params := &iam.DeleteRoleInput{ - RoleName: aws.String("roleNameType"), // Required - } - resp, err := svc.DeleteRole(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_DeleteRolePolicy() { - svc := iam.New(nil) - - params := &iam.DeleteRolePolicyInput{ - PolicyName: aws.String("policyNameType"), // Required - RoleName: aws.String("roleNameType"), // Required - } - resp, err := svc.DeleteRolePolicy(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_DeleteSAMLProvider() { - svc := iam.New(nil) - - params := &iam.DeleteSAMLProviderInput{ - SAMLProviderArn: aws.String("arnType"), // Required - } - resp, err := svc.DeleteSAMLProvider(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_DeleteSSHPublicKey() { - svc := iam.New(nil) - - params := &iam.DeleteSSHPublicKeyInput{ - SSHPublicKeyId: aws.String("publicKeyIdType"), // Required - UserName: aws.String("userNameType"), // Required - } - resp, err := svc.DeleteSSHPublicKey(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_DeleteServerCertificate() { - svc := iam.New(nil) - - params := &iam.DeleteServerCertificateInput{ - ServerCertificateName: aws.String("serverCertificateNameType"), // Required - } - resp, err := svc.DeleteServerCertificate(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_DeleteSigningCertificate() { - svc := iam.New(nil) - - params := &iam.DeleteSigningCertificateInput{ - CertificateId: aws.String("certificateIdType"), // Required - UserName: aws.String("existingUserNameType"), - } - resp, err := svc.DeleteSigningCertificate(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_DeleteUser() { - svc := iam.New(nil) - - params := &iam.DeleteUserInput{ - UserName: aws.String("existingUserNameType"), // Required - } - resp, err := svc.DeleteUser(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_DeleteUserPolicy() { - svc := iam.New(nil) - - params := &iam.DeleteUserPolicyInput{ - PolicyName: aws.String("policyNameType"), // Required - UserName: aws.String("existingUserNameType"), // Required - } - resp, err := svc.DeleteUserPolicy(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_DeleteVirtualMFADevice() { - svc := iam.New(nil) - - params := &iam.DeleteVirtualMFADeviceInput{ - SerialNumber: aws.String("serialNumberType"), // Required - } - resp, err := svc.DeleteVirtualMFADevice(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_DetachGroupPolicy() { - svc := iam.New(nil) - - params := &iam.DetachGroupPolicyInput{ - GroupName: aws.String("groupNameType"), // Required - PolicyArn: aws.String("arnType"), // Required - } - resp, err := svc.DetachGroupPolicy(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_DetachRolePolicy() { - svc := iam.New(nil) - - params := &iam.DetachRolePolicyInput{ - PolicyArn: aws.String("arnType"), // Required - RoleName: aws.String("roleNameType"), // Required - } - resp, err := svc.DetachRolePolicy(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_DetachUserPolicy() { - svc := iam.New(nil) - - params := &iam.DetachUserPolicyInput{ - PolicyArn: aws.String("arnType"), // Required - UserName: aws.String("userNameType"), // Required - } - resp, err := svc.DetachUserPolicy(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_EnableMFADevice() { - svc := iam.New(nil) - - params := &iam.EnableMFADeviceInput{ - AuthenticationCode1: aws.String("authenticationCodeType"), // Required - AuthenticationCode2: aws.String("authenticationCodeType"), // Required - SerialNumber: aws.String("serialNumberType"), // Required - UserName: aws.String("existingUserNameType"), // Required - } - resp, err := svc.EnableMFADevice(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_GenerateCredentialReport() { - svc := iam.New(nil) - - var params *iam.GenerateCredentialReportInput - resp, err := svc.GenerateCredentialReport(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_GetAccessKeyLastUsed() { - svc := iam.New(nil) - - params := &iam.GetAccessKeyLastUsedInput{ - AccessKeyId: aws.String("accessKeyIdType"), // Required - } - resp, err := svc.GetAccessKeyLastUsed(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_GetAccountAuthorizationDetails() { - svc := iam.New(nil) - - params := &iam.GetAccountAuthorizationDetailsInput{ - Filter: []*string{ - aws.String("EntityType"), // Required - // More values... - }, - Marker: aws.String("markerType"), - MaxItems: aws.Int64(1), - } - resp, err := svc.GetAccountAuthorizationDetails(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_GetAccountPasswordPolicy() { - svc := iam.New(nil) - - var params *iam.GetAccountPasswordPolicyInput - resp, err := svc.GetAccountPasswordPolicy(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_GetAccountSummary() { - svc := iam.New(nil) - - var params *iam.GetAccountSummaryInput - resp, err := svc.GetAccountSummary(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_GetCredentialReport() { - svc := iam.New(nil) - - var params *iam.GetCredentialReportInput - resp, err := svc.GetCredentialReport(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_GetGroup() { - svc := iam.New(nil) - - params := &iam.GetGroupInput{ - GroupName: aws.String("groupNameType"), // Required - Marker: aws.String("markerType"), - MaxItems: aws.Int64(1), - } - resp, err := svc.GetGroup(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_GetGroupPolicy() { - svc := iam.New(nil) - - params := &iam.GetGroupPolicyInput{ - GroupName: aws.String("groupNameType"), // Required - PolicyName: aws.String("policyNameType"), // Required - } - resp, err := svc.GetGroupPolicy(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_GetInstanceProfile() { - svc := iam.New(nil) - - params := &iam.GetInstanceProfileInput{ - InstanceProfileName: aws.String("instanceProfileNameType"), // Required - } - resp, err := svc.GetInstanceProfile(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_GetLoginProfile() { - svc := iam.New(nil) - - params := &iam.GetLoginProfileInput{ - UserName: aws.String("userNameType"), // Required - } - resp, err := svc.GetLoginProfile(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_GetOpenIDConnectProvider() { - svc := iam.New(nil) - - params := &iam.GetOpenIDConnectProviderInput{ - OpenIDConnectProviderArn: aws.String("arnType"), // Required - } - resp, err := svc.GetOpenIDConnectProvider(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_GetPolicy() { - svc := iam.New(nil) - - params := &iam.GetPolicyInput{ - PolicyArn: aws.String("arnType"), // Required - } - resp, err := svc.GetPolicy(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_GetPolicyVersion() { - svc := iam.New(nil) - - params := &iam.GetPolicyVersionInput{ - PolicyArn: aws.String("arnType"), // Required - VersionId: aws.String("policyVersionIdType"), // Required - } - resp, err := svc.GetPolicyVersion(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_GetRole() { - svc := iam.New(nil) - - params := &iam.GetRoleInput{ - RoleName: aws.String("roleNameType"), // Required - } - resp, err := svc.GetRole(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_GetRolePolicy() { - svc := iam.New(nil) - - params := &iam.GetRolePolicyInput{ - PolicyName: aws.String("policyNameType"), // Required - RoleName: aws.String("roleNameType"), // Required - } - resp, err := svc.GetRolePolicy(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_GetSAMLProvider() { - svc := iam.New(nil) - - params := &iam.GetSAMLProviderInput{ - SAMLProviderArn: aws.String("arnType"), // Required - } - resp, err := svc.GetSAMLProvider(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_GetSSHPublicKey() { - svc := iam.New(nil) - - params := &iam.GetSSHPublicKeyInput{ - Encoding: aws.String("encodingType"), // Required - SSHPublicKeyId: aws.String("publicKeyIdType"), // Required - UserName: aws.String("userNameType"), // Required - } - resp, err := svc.GetSSHPublicKey(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_GetServerCertificate() { - svc := iam.New(nil) - - params := &iam.GetServerCertificateInput{ - ServerCertificateName: aws.String("serverCertificateNameType"), // Required - } - resp, err := svc.GetServerCertificate(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_GetUser() { - svc := iam.New(nil) - - params := &iam.GetUserInput{ - UserName: aws.String("existingUserNameType"), - } - resp, err := svc.GetUser(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_GetUserPolicy() { - svc := iam.New(nil) - - params := &iam.GetUserPolicyInput{ - PolicyName: aws.String("policyNameType"), // Required - UserName: aws.String("existingUserNameType"), // Required - } - resp, err := svc.GetUserPolicy(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_ListAccessKeys() { - svc := iam.New(nil) - - params := &iam.ListAccessKeysInput{ - Marker: aws.String("markerType"), - MaxItems: aws.Int64(1), - UserName: aws.String("existingUserNameType"), - } - resp, err := svc.ListAccessKeys(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_ListAccountAliases() { - svc := iam.New(nil) - - params := &iam.ListAccountAliasesInput{ - Marker: aws.String("markerType"), - MaxItems: aws.Int64(1), - } - resp, err := svc.ListAccountAliases(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_ListAttachedGroupPolicies() { - svc := iam.New(nil) - - params := &iam.ListAttachedGroupPoliciesInput{ - GroupName: aws.String("groupNameType"), // Required - Marker: aws.String("markerType"), - MaxItems: aws.Int64(1), - PathPrefix: aws.String("policyPathType"), - } - resp, err := svc.ListAttachedGroupPolicies(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_ListAttachedRolePolicies() { - svc := iam.New(nil) - - params := &iam.ListAttachedRolePoliciesInput{ - RoleName: aws.String("roleNameType"), // Required - Marker: aws.String("markerType"), - MaxItems: aws.Int64(1), - PathPrefix: aws.String("policyPathType"), - } - resp, err := svc.ListAttachedRolePolicies(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_ListAttachedUserPolicies() { - svc := iam.New(nil) - - params := &iam.ListAttachedUserPoliciesInput{ - UserName: aws.String("userNameType"), // Required - Marker: aws.String("markerType"), - MaxItems: aws.Int64(1), - PathPrefix: aws.String("policyPathType"), - } - resp, err := svc.ListAttachedUserPolicies(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_ListEntitiesForPolicy() { - svc := iam.New(nil) - - params := &iam.ListEntitiesForPolicyInput{ - PolicyArn: aws.String("arnType"), // Required - EntityFilter: aws.String("EntityType"), - Marker: aws.String("markerType"), - MaxItems: aws.Int64(1), - PathPrefix: aws.String("pathType"), - } - resp, err := svc.ListEntitiesForPolicy(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_ListGroupPolicies() { - svc := iam.New(nil) - - params := &iam.ListGroupPoliciesInput{ - GroupName: aws.String("groupNameType"), // Required - Marker: aws.String("markerType"), - MaxItems: aws.Int64(1), - } - resp, err := svc.ListGroupPolicies(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_ListGroups() { - svc := iam.New(nil) - - params := &iam.ListGroupsInput{ - Marker: aws.String("markerType"), - MaxItems: aws.Int64(1), - PathPrefix: aws.String("pathPrefixType"), - } - resp, err := svc.ListGroups(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_ListGroupsForUser() { - svc := iam.New(nil) - - params := &iam.ListGroupsForUserInput{ - UserName: aws.String("existingUserNameType"), // Required - Marker: aws.String("markerType"), - MaxItems: aws.Int64(1), - } - resp, err := svc.ListGroupsForUser(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_ListInstanceProfiles() { - svc := iam.New(nil) - - params := &iam.ListInstanceProfilesInput{ - Marker: aws.String("markerType"), - MaxItems: aws.Int64(1), - PathPrefix: aws.String("pathPrefixType"), - } - resp, err := svc.ListInstanceProfiles(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_ListInstanceProfilesForRole() { - svc := iam.New(nil) - - params := &iam.ListInstanceProfilesForRoleInput{ - RoleName: aws.String("roleNameType"), // Required - Marker: aws.String("markerType"), - MaxItems: aws.Int64(1), - } - resp, err := svc.ListInstanceProfilesForRole(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_ListMFADevices() { - svc := iam.New(nil) - - params := &iam.ListMFADevicesInput{ - Marker: aws.String("markerType"), - MaxItems: aws.Int64(1), - UserName: aws.String("existingUserNameType"), - } - resp, err := svc.ListMFADevices(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_ListOpenIDConnectProviders() { - svc := iam.New(nil) - - var params *iam.ListOpenIDConnectProvidersInput - resp, err := svc.ListOpenIDConnectProviders(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_ListPolicies() { - svc := iam.New(nil) - - params := &iam.ListPoliciesInput{ - Marker: aws.String("markerType"), - MaxItems: aws.Int64(1), - OnlyAttached: aws.Bool(true), - PathPrefix: aws.String("policyPathType"), - Scope: aws.String("policyScopeType"), - } - resp, err := svc.ListPolicies(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_ListPolicyVersions() { - svc := iam.New(nil) - - params := &iam.ListPolicyVersionsInput{ - PolicyArn: aws.String("arnType"), // Required - Marker: aws.String("markerType"), - MaxItems: aws.Int64(1), - } - resp, err := svc.ListPolicyVersions(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_ListRolePolicies() { - svc := iam.New(nil) - - params := &iam.ListRolePoliciesInput{ - RoleName: aws.String("roleNameType"), // Required - Marker: aws.String("markerType"), - MaxItems: aws.Int64(1), - } - resp, err := svc.ListRolePolicies(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_ListRoles() { - svc := iam.New(nil) - - params := &iam.ListRolesInput{ - Marker: aws.String("markerType"), - MaxItems: aws.Int64(1), - PathPrefix: aws.String("pathPrefixType"), - } - resp, err := svc.ListRoles(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_ListSAMLProviders() { - svc := iam.New(nil) - - var params *iam.ListSAMLProvidersInput - resp, err := svc.ListSAMLProviders(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_ListSSHPublicKeys() { - svc := iam.New(nil) - - params := &iam.ListSSHPublicKeysInput{ - Marker: aws.String("markerType"), - MaxItems: aws.Int64(1), - UserName: aws.String("userNameType"), - } - resp, err := svc.ListSSHPublicKeys(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_ListServerCertificates() { - svc := iam.New(nil) - - params := &iam.ListServerCertificatesInput{ - Marker: aws.String("markerType"), - MaxItems: aws.Int64(1), - PathPrefix: aws.String("pathPrefixType"), - } - resp, err := svc.ListServerCertificates(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_ListSigningCertificates() { - svc := iam.New(nil) - - params := &iam.ListSigningCertificatesInput{ - Marker: aws.String("markerType"), - MaxItems: aws.Int64(1), - UserName: aws.String("existingUserNameType"), - } - resp, err := svc.ListSigningCertificates(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_ListUserPolicies() { - svc := iam.New(nil) - - params := &iam.ListUserPoliciesInput{ - UserName: aws.String("existingUserNameType"), // Required - Marker: aws.String("markerType"), - MaxItems: aws.Int64(1), - } - resp, err := svc.ListUserPolicies(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_ListUsers() { - svc := iam.New(nil) - - params := &iam.ListUsersInput{ - Marker: aws.String("markerType"), - MaxItems: aws.Int64(1), - PathPrefix: aws.String("pathPrefixType"), - } - resp, err := svc.ListUsers(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_ListVirtualMFADevices() { - svc := iam.New(nil) - - params := &iam.ListVirtualMFADevicesInput{ - AssignmentStatus: aws.String("assignmentStatusType"), - Marker: aws.String("markerType"), - MaxItems: aws.Int64(1), - } - resp, err := svc.ListVirtualMFADevices(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_PutGroupPolicy() { - svc := iam.New(nil) - - params := &iam.PutGroupPolicyInput{ - GroupName: aws.String("groupNameType"), // Required - PolicyDocument: aws.String("policyDocumentType"), // Required - PolicyName: aws.String("policyNameType"), // Required - } - resp, err := svc.PutGroupPolicy(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_PutRolePolicy() { - svc := iam.New(nil) - - params := &iam.PutRolePolicyInput{ - PolicyDocument: aws.String("policyDocumentType"), // Required - PolicyName: aws.String("policyNameType"), // Required - RoleName: aws.String("roleNameType"), // Required - } - resp, err := svc.PutRolePolicy(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_PutUserPolicy() { - svc := iam.New(nil) - - params := &iam.PutUserPolicyInput{ - PolicyDocument: aws.String("policyDocumentType"), // Required - PolicyName: aws.String("policyNameType"), // Required - UserName: aws.String("existingUserNameType"), // Required - } - resp, err := svc.PutUserPolicy(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_RemoveClientIDFromOpenIDConnectProvider() { - svc := iam.New(nil) - - params := &iam.RemoveClientIDFromOpenIDConnectProviderInput{ - ClientID: aws.String("clientIDType"), // Required - OpenIDConnectProviderArn: aws.String("arnType"), // Required - } - resp, err := svc.RemoveClientIDFromOpenIDConnectProvider(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_RemoveRoleFromInstanceProfile() { - svc := iam.New(nil) - - params := &iam.RemoveRoleFromInstanceProfileInput{ - InstanceProfileName: aws.String("instanceProfileNameType"), // Required - RoleName: aws.String("roleNameType"), // Required - } - resp, err := svc.RemoveRoleFromInstanceProfile(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_RemoveUserFromGroup() { - svc := iam.New(nil) - - params := &iam.RemoveUserFromGroupInput{ - GroupName: aws.String("groupNameType"), // Required - UserName: aws.String("existingUserNameType"), // Required - } - resp, err := svc.RemoveUserFromGroup(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_ResyncMFADevice() { - svc := iam.New(nil) - - params := &iam.ResyncMFADeviceInput{ - AuthenticationCode1: aws.String("authenticationCodeType"), // Required - AuthenticationCode2: aws.String("authenticationCodeType"), // Required - SerialNumber: aws.String("serialNumberType"), // Required - UserName: aws.String("existingUserNameType"), // Required - } - resp, err := svc.ResyncMFADevice(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_SetDefaultPolicyVersion() { - svc := iam.New(nil) - - params := &iam.SetDefaultPolicyVersionInput{ - PolicyArn: aws.String("arnType"), // Required - VersionId: aws.String("policyVersionIdType"), // Required - } - resp, err := svc.SetDefaultPolicyVersion(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_UpdateAccessKey() { - svc := iam.New(nil) - - params := &iam.UpdateAccessKeyInput{ - AccessKeyId: aws.String("accessKeyIdType"), // Required - Status: aws.String("statusType"), // Required - UserName: aws.String("existingUserNameType"), - } - resp, err := svc.UpdateAccessKey(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_UpdateAccountPasswordPolicy() { - svc := iam.New(nil) - - params := &iam.UpdateAccountPasswordPolicyInput{ - AllowUsersToChangePassword: aws.Bool(true), - HardExpiry: aws.Bool(true), - MaxPasswordAge: aws.Int64(1), - MinimumPasswordLength: aws.Int64(1), - PasswordReusePrevention: aws.Int64(1), - RequireLowercaseCharacters: aws.Bool(true), - RequireNumbers: aws.Bool(true), - RequireSymbols: aws.Bool(true), - RequireUppercaseCharacters: aws.Bool(true), - } - resp, err := svc.UpdateAccountPasswordPolicy(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_UpdateAssumeRolePolicy() { - svc := iam.New(nil) - - params := &iam.UpdateAssumeRolePolicyInput{ - PolicyDocument: aws.String("policyDocumentType"), // Required - RoleName: aws.String("roleNameType"), // Required - } - resp, err := svc.UpdateAssumeRolePolicy(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_UpdateGroup() { - svc := iam.New(nil) - - params := &iam.UpdateGroupInput{ - GroupName: aws.String("groupNameType"), // Required - NewGroupName: aws.String("groupNameType"), - NewPath: aws.String("pathType"), - } - resp, err := svc.UpdateGroup(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_UpdateLoginProfile() { - svc := iam.New(nil) - - params := &iam.UpdateLoginProfileInput{ - UserName: aws.String("userNameType"), // Required - Password: aws.String("passwordType"), - PasswordResetRequired: aws.Bool(true), - } - resp, err := svc.UpdateLoginProfile(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_UpdateOpenIDConnectProviderThumbprint() { - svc := iam.New(nil) - - params := &iam.UpdateOpenIDConnectProviderThumbprintInput{ - OpenIDConnectProviderArn: aws.String("arnType"), // Required - ThumbprintList: []*string{ // Required - aws.String("thumbprintType"), // Required - // More values... - }, - } - resp, err := svc.UpdateOpenIDConnectProviderThumbprint(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_UpdateSAMLProvider() { - svc := iam.New(nil) - - params := &iam.UpdateSAMLProviderInput{ - SAMLMetadataDocument: aws.String("SAMLMetadataDocumentType"), // Required - SAMLProviderArn: aws.String("arnType"), // Required - } - resp, err := svc.UpdateSAMLProvider(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_UpdateSSHPublicKey() { - svc := iam.New(nil) - - params := &iam.UpdateSSHPublicKeyInput{ - SSHPublicKeyId: aws.String("publicKeyIdType"), // Required - Status: aws.String("statusType"), // Required - UserName: aws.String("userNameType"), // Required - } - resp, err := svc.UpdateSSHPublicKey(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_UpdateServerCertificate() { - svc := iam.New(nil) - - params := &iam.UpdateServerCertificateInput{ - ServerCertificateName: aws.String("serverCertificateNameType"), // Required - NewPath: aws.String("pathType"), - NewServerCertificateName: aws.String("serverCertificateNameType"), - } - resp, err := svc.UpdateServerCertificate(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_UpdateSigningCertificate() { - svc := iam.New(nil) - - params := &iam.UpdateSigningCertificateInput{ - CertificateId: aws.String("certificateIdType"), // Required - Status: aws.String("statusType"), // Required - UserName: aws.String("existingUserNameType"), - } - resp, err := svc.UpdateSigningCertificate(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_UpdateUser() { - svc := iam.New(nil) - - params := &iam.UpdateUserInput{ - UserName: aws.String("existingUserNameType"), // Required - NewPath: aws.String("pathType"), - NewUserName: aws.String("userNameType"), - } - resp, err := svc.UpdateUser(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_UploadSSHPublicKey() { - svc := iam.New(nil) - - params := &iam.UploadSSHPublicKeyInput{ - SSHPublicKeyBody: aws.String("publicKeyMaterialType"), // Required - UserName: aws.String("userNameType"), // Required - } - resp, err := svc.UploadSSHPublicKey(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_UploadServerCertificate() { - svc := iam.New(nil) - - params := &iam.UploadServerCertificateInput{ - CertificateBody: aws.String("certificateBodyType"), // Required - PrivateKey: aws.String("privateKeyType"), // Required - ServerCertificateName: aws.String("serverCertificateNameType"), // Required - CertificateChain: aws.String("certificateChainType"), - Path: aws.String("pathType"), - } - resp, err := svc.UploadServerCertificate(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleIAM_UploadSigningCertificate() { - svc := iam.New(nil) - - params := &iam.UploadSigningCertificateInput{ - CertificateBody: aws.String("certificateBodyType"), // Required - UserName: aws.String("existingUserNameType"), - } - resp, err := svc.UploadSigningCertificate(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/iam/iamiface/interface.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/iam/iamiface/interface.go index bc9638676..d2dcd0ca2 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/iam/iamiface/interface.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/iam/iamiface/interface.go @@ -4,489 +4,505 @@ package iamiface import ( - "github.com/aws/aws-sdk-go/aws/service" + "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/service/iam" ) // IAMAPI is the interface type for iam.IAM. type IAMAPI interface { - AddClientIDToOpenIDConnectProviderRequest(*iam.AddClientIDToOpenIDConnectProviderInput) (*service.Request, *iam.AddClientIDToOpenIDConnectProviderOutput) + AddClientIDToOpenIDConnectProviderRequest(*iam.AddClientIDToOpenIDConnectProviderInput) (*request.Request, *iam.AddClientIDToOpenIDConnectProviderOutput) AddClientIDToOpenIDConnectProvider(*iam.AddClientIDToOpenIDConnectProviderInput) (*iam.AddClientIDToOpenIDConnectProviderOutput, error) - AddRoleToInstanceProfileRequest(*iam.AddRoleToInstanceProfileInput) (*service.Request, *iam.AddRoleToInstanceProfileOutput) + AddRoleToInstanceProfileRequest(*iam.AddRoleToInstanceProfileInput) (*request.Request, *iam.AddRoleToInstanceProfileOutput) AddRoleToInstanceProfile(*iam.AddRoleToInstanceProfileInput) (*iam.AddRoleToInstanceProfileOutput, error) - AddUserToGroupRequest(*iam.AddUserToGroupInput) (*service.Request, *iam.AddUserToGroupOutput) + AddUserToGroupRequest(*iam.AddUserToGroupInput) (*request.Request, *iam.AddUserToGroupOutput) AddUserToGroup(*iam.AddUserToGroupInput) (*iam.AddUserToGroupOutput, error) - AttachGroupPolicyRequest(*iam.AttachGroupPolicyInput) (*service.Request, *iam.AttachGroupPolicyOutput) + AttachGroupPolicyRequest(*iam.AttachGroupPolicyInput) (*request.Request, *iam.AttachGroupPolicyOutput) AttachGroupPolicy(*iam.AttachGroupPolicyInput) (*iam.AttachGroupPolicyOutput, error) - AttachRolePolicyRequest(*iam.AttachRolePolicyInput) (*service.Request, *iam.AttachRolePolicyOutput) + AttachRolePolicyRequest(*iam.AttachRolePolicyInput) (*request.Request, *iam.AttachRolePolicyOutput) AttachRolePolicy(*iam.AttachRolePolicyInput) (*iam.AttachRolePolicyOutput, error) - AttachUserPolicyRequest(*iam.AttachUserPolicyInput) (*service.Request, *iam.AttachUserPolicyOutput) + AttachUserPolicyRequest(*iam.AttachUserPolicyInput) (*request.Request, *iam.AttachUserPolicyOutput) AttachUserPolicy(*iam.AttachUserPolicyInput) (*iam.AttachUserPolicyOutput, error) - ChangePasswordRequest(*iam.ChangePasswordInput) (*service.Request, *iam.ChangePasswordOutput) + ChangePasswordRequest(*iam.ChangePasswordInput) (*request.Request, *iam.ChangePasswordOutput) ChangePassword(*iam.ChangePasswordInput) (*iam.ChangePasswordOutput, error) - CreateAccessKeyRequest(*iam.CreateAccessKeyInput) (*service.Request, *iam.CreateAccessKeyOutput) + CreateAccessKeyRequest(*iam.CreateAccessKeyInput) (*request.Request, *iam.CreateAccessKeyOutput) CreateAccessKey(*iam.CreateAccessKeyInput) (*iam.CreateAccessKeyOutput, error) - CreateAccountAliasRequest(*iam.CreateAccountAliasInput) (*service.Request, *iam.CreateAccountAliasOutput) + CreateAccountAliasRequest(*iam.CreateAccountAliasInput) (*request.Request, *iam.CreateAccountAliasOutput) CreateAccountAlias(*iam.CreateAccountAliasInput) (*iam.CreateAccountAliasOutput, error) - CreateGroupRequest(*iam.CreateGroupInput) (*service.Request, *iam.CreateGroupOutput) + CreateGroupRequest(*iam.CreateGroupInput) (*request.Request, *iam.CreateGroupOutput) CreateGroup(*iam.CreateGroupInput) (*iam.CreateGroupOutput, error) - CreateInstanceProfileRequest(*iam.CreateInstanceProfileInput) (*service.Request, *iam.CreateInstanceProfileOutput) + CreateInstanceProfileRequest(*iam.CreateInstanceProfileInput) (*request.Request, *iam.CreateInstanceProfileOutput) CreateInstanceProfile(*iam.CreateInstanceProfileInput) (*iam.CreateInstanceProfileOutput, error) - CreateLoginProfileRequest(*iam.CreateLoginProfileInput) (*service.Request, *iam.CreateLoginProfileOutput) + CreateLoginProfileRequest(*iam.CreateLoginProfileInput) (*request.Request, *iam.CreateLoginProfileOutput) CreateLoginProfile(*iam.CreateLoginProfileInput) (*iam.CreateLoginProfileOutput, error) - CreateOpenIDConnectProviderRequest(*iam.CreateOpenIDConnectProviderInput) (*service.Request, *iam.CreateOpenIDConnectProviderOutput) + CreateOpenIDConnectProviderRequest(*iam.CreateOpenIDConnectProviderInput) (*request.Request, *iam.CreateOpenIDConnectProviderOutput) CreateOpenIDConnectProvider(*iam.CreateOpenIDConnectProviderInput) (*iam.CreateOpenIDConnectProviderOutput, error) - CreatePolicyRequest(*iam.CreatePolicyInput) (*service.Request, *iam.CreatePolicyOutput) + CreatePolicyRequest(*iam.CreatePolicyInput) (*request.Request, *iam.CreatePolicyOutput) CreatePolicy(*iam.CreatePolicyInput) (*iam.CreatePolicyOutput, error) - CreatePolicyVersionRequest(*iam.CreatePolicyVersionInput) (*service.Request, *iam.CreatePolicyVersionOutput) + CreatePolicyVersionRequest(*iam.CreatePolicyVersionInput) (*request.Request, *iam.CreatePolicyVersionOutput) CreatePolicyVersion(*iam.CreatePolicyVersionInput) (*iam.CreatePolicyVersionOutput, error) - CreateRoleRequest(*iam.CreateRoleInput) (*service.Request, *iam.CreateRoleOutput) + CreateRoleRequest(*iam.CreateRoleInput) (*request.Request, *iam.CreateRoleOutput) CreateRole(*iam.CreateRoleInput) (*iam.CreateRoleOutput, error) - CreateSAMLProviderRequest(*iam.CreateSAMLProviderInput) (*service.Request, *iam.CreateSAMLProviderOutput) + CreateSAMLProviderRequest(*iam.CreateSAMLProviderInput) (*request.Request, *iam.CreateSAMLProviderOutput) CreateSAMLProvider(*iam.CreateSAMLProviderInput) (*iam.CreateSAMLProviderOutput, error) - CreateUserRequest(*iam.CreateUserInput) (*service.Request, *iam.CreateUserOutput) + CreateUserRequest(*iam.CreateUserInput) (*request.Request, *iam.CreateUserOutput) CreateUser(*iam.CreateUserInput) (*iam.CreateUserOutput, error) - CreateVirtualMFADeviceRequest(*iam.CreateVirtualMFADeviceInput) (*service.Request, *iam.CreateVirtualMFADeviceOutput) + CreateVirtualMFADeviceRequest(*iam.CreateVirtualMFADeviceInput) (*request.Request, *iam.CreateVirtualMFADeviceOutput) CreateVirtualMFADevice(*iam.CreateVirtualMFADeviceInput) (*iam.CreateVirtualMFADeviceOutput, error) - DeactivateMFADeviceRequest(*iam.DeactivateMFADeviceInput) (*service.Request, *iam.DeactivateMFADeviceOutput) + DeactivateMFADeviceRequest(*iam.DeactivateMFADeviceInput) (*request.Request, *iam.DeactivateMFADeviceOutput) DeactivateMFADevice(*iam.DeactivateMFADeviceInput) (*iam.DeactivateMFADeviceOutput, error) - DeleteAccessKeyRequest(*iam.DeleteAccessKeyInput) (*service.Request, *iam.DeleteAccessKeyOutput) + DeleteAccessKeyRequest(*iam.DeleteAccessKeyInput) (*request.Request, *iam.DeleteAccessKeyOutput) DeleteAccessKey(*iam.DeleteAccessKeyInput) (*iam.DeleteAccessKeyOutput, error) - DeleteAccountAliasRequest(*iam.DeleteAccountAliasInput) (*service.Request, *iam.DeleteAccountAliasOutput) + DeleteAccountAliasRequest(*iam.DeleteAccountAliasInput) (*request.Request, *iam.DeleteAccountAliasOutput) DeleteAccountAlias(*iam.DeleteAccountAliasInput) (*iam.DeleteAccountAliasOutput, error) - DeleteAccountPasswordPolicyRequest(*iam.DeleteAccountPasswordPolicyInput) (*service.Request, *iam.DeleteAccountPasswordPolicyOutput) + DeleteAccountPasswordPolicyRequest(*iam.DeleteAccountPasswordPolicyInput) (*request.Request, *iam.DeleteAccountPasswordPolicyOutput) DeleteAccountPasswordPolicy(*iam.DeleteAccountPasswordPolicyInput) (*iam.DeleteAccountPasswordPolicyOutput, error) - DeleteGroupRequest(*iam.DeleteGroupInput) (*service.Request, *iam.DeleteGroupOutput) + DeleteGroupRequest(*iam.DeleteGroupInput) (*request.Request, *iam.DeleteGroupOutput) DeleteGroup(*iam.DeleteGroupInput) (*iam.DeleteGroupOutput, error) - DeleteGroupPolicyRequest(*iam.DeleteGroupPolicyInput) (*service.Request, *iam.DeleteGroupPolicyOutput) + DeleteGroupPolicyRequest(*iam.DeleteGroupPolicyInput) (*request.Request, *iam.DeleteGroupPolicyOutput) DeleteGroupPolicy(*iam.DeleteGroupPolicyInput) (*iam.DeleteGroupPolicyOutput, error) - DeleteInstanceProfileRequest(*iam.DeleteInstanceProfileInput) (*service.Request, *iam.DeleteInstanceProfileOutput) + DeleteInstanceProfileRequest(*iam.DeleteInstanceProfileInput) (*request.Request, *iam.DeleteInstanceProfileOutput) DeleteInstanceProfile(*iam.DeleteInstanceProfileInput) (*iam.DeleteInstanceProfileOutput, error) - DeleteLoginProfileRequest(*iam.DeleteLoginProfileInput) (*service.Request, *iam.DeleteLoginProfileOutput) + DeleteLoginProfileRequest(*iam.DeleteLoginProfileInput) (*request.Request, *iam.DeleteLoginProfileOutput) DeleteLoginProfile(*iam.DeleteLoginProfileInput) (*iam.DeleteLoginProfileOutput, error) - DeleteOpenIDConnectProviderRequest(*iam.DeleteOpenIDConnectProviderInput) (*service.Request, *iam.DeleteOpenIDConnectProviderOutput) + DeleteOpenIDConnectProviderRequest(*iam.DeleteOpenIDConnectProviderInput) (*request.Request, *iam.DeleteOpenIDConnectProviderOutput) DeleteOpenIDConnectProvider(*iam.DeleteOpenIDConnectProviderInput) (*iam.DeleteOpenIDConnectProviderOutput, error) - DeletePolicyRequest(*iam.DeletePolicyInput) (*service.Request, *iam.DeletePolicyOutput) + DeletePolicyRequest(*iam.DeletePolicyInput) (*request.Request, *iam.DeletePolicyOutput) DeletePolicy(*iam.DeletePolicyInput) (*iam.DeletePolicyOutput, error) - DeletePolicyVersionRequest(*iam.DeletePolicyVersionInput) (*service.Request, *iam.DeletePolicyVersionOutput) + DeletePolicyVersionRequest(*iam.DeletePolicyVersionInput) (*request.Request, *iam.DeletePolicyVersionOutput) DeletePolicyVersion(*iam.DeletePolicyVersionInput) (*iam.DeletePolicyVersionOutput, error) - DeleteRoleRequest(*iam.DeleteRoleInput) (*service.Request, *iam.DeleteRoleOutput) + DeleteRoleRequest(*iam.DeleteRoleInput) (*request.Request, *iam.DeleteRoleOutput) DeleteRole(*iam.DeleteRoleInput) (*iam.DeleteRoleOutput, error) - DeleteRolePolicyRequest(*iam.DeleteRolePolicyInput) (*service.Request, *iam.DeleteRolePolicyOutput) + DeleteRolePolicyRequest(*iam.DeleteRolePolicyInput) (*request.Request, *iam.DeleteRolePolicyOutput) DeleteRolePolicy(*iam.DeleteRolePolicyInput) (*iam.DeleteRolePolicyOutput, error) - DeleteSAMLProviderRequest(*iam.DeleteSAMLProviderInput) (*service.Request, *iam.DeleteSAMLProviderOutput) + DeleteSAMLProviderRequest(*iam.DeleteSAMLProviderInput) (*request.Request, *iam.DeleteSAMLProviderOutput) DeleteSAMLProvider(*iam.DeleteSAMLProviderInput) (*iam.DeleteSAMLProviderOutput, error) - DeleteSSHPublicKeyRequest(*iam.DeleteSSHPublicKeyInput) (*service.Request, *iam.DeleteSSHPublicKeyOutput) + DeleteSSHPublicKeyRequest(*iam.DeleteSSHPublicKeyInput) (*request.Request, *iam.DeleteSSHPublicKeyOutput) DeleteSSHPublicKey(*iam.DeleteSSHPublicKeyInput) (*iam.DeleteSSHPublicKeyOutput, error) - DeleteServerCertificateRequest(*iam.DeleteServerCertificateInput) (*service.Request, *iam.DeleteServerCertificateOutput) + DeleteServerCertificateRequest(*iam.DeleteServerCertificateInput) (*request.Request, *iam.DeleteServerCertificateOutput) DeleteServerCertificate(*iam.DeleteServerCertificateInput) (*iam.DeleteServerCertificateOutput, error) - DeleteSigningCertificateRequest(*iam.DeleteSigningCertificateInput) (*service.Request, *iam.DeleteSigningCertificateOutput) + DeleteSigningCertificateRequest(*iam.DeleteSigningCertificateInput) (*request.Request, *iam.DeleteSigningCertificateOutput) DeleteSigningCertificate(*iam.DeleteSigningCertificateInput) (*iam.DeleteSigningCertificateOutput, error) - DeleteUserRequest(*iam.DeleteUserInput) (*service.Request, *iam.DeleteUserOutput) + DeleteUserRequest(*iam.DeleteUserInput) (*request.Request, *iam.DeleteUserOutput) DeleteUser(*iam.DeleteUserInput) (*iam.DeleteUserOutput, error) - DeleteUserPolicyRequest(*iam.DeleteUserPolicyInput) (*service.Request, *iam.DeleteUserPolicyOutput) + DeleteUserPolicyRequest(*iam.DeleteUserPolicyInput) (*request.Request, *iam.DeleteUserPolicyOutput) DeleteUserPolicy(*iam.DeleteUserPolicyInput) (*iam.DeleteUserPolicyOutput, error) - DeleteVirtualMFADeviceRequest(*iam.DeleteVirtualMFADeviceInput) (*service.Request, *iam.DeleteVirtualMFADeviceOutput) + DeleteVirtualMFADeviceRequest(*iam.DeleteVirtualMFADeviceInput) (*request.Request, *iam.DeleteVirtualMFADeviceOutput) DeleteVirtualMFADevice(*iam.DeleteVirtualMFADeviceInput) (*iam.DeleteVirtualMFADeviceOutput, error) - DetachGroupPolicyRequest(*iam.DetachGroupPolicyInput) (*service.Request, *iam.DetachGroupPolicyOutput) + DetachGroupPolicyRequest(*iam.DetachGroupPolicyInput) (*request.Request, *iam.DetachGroupPolicyOutput) DetachGroupPolicy(*iam.DetachGroupPolicyInput) (*iam.DetachGroupPolicyOutput, error) - DetachRolePolicyRequest(*iam.DetachRolePolicyInput) (*service.Request, *iam.DetachRolePolicyOutput) + DetachRolePolicyRequest(*iam.DetachRolePolicyInput) (*request.Request, *iam.DetachRolePolicyOutput) DetachRolePolicy(*iam.DetachRolePolicyInput) (*iam.DetachRolePolicyOutput, error) - DetachUserPolicyRequest(*iam.DetachUserPolicyInput) (*service.Request, *iam.DetachUserPolicyOutput) + DetachUserPolicyRequest(*iam.DetachUserPolicyInput) (*request.Request, *iam.DetachUserPolicyOutput) DetachUserPolicy(*iam.DetachUserPolicyInput) (*iam.DetachUserPolicyOutput, error) - EnableMFADeviceRequest(*iam.EnableMFADeviceInput) (*service.Request, *iam.EnableMFADeviceOutput) + EnableMFADeviceRequest(*iam.EnableMFADeviceInput) (*request.Request, *iam.EnableMFADeviceOutput) EnableMFADevice(*iam.EnableMFADeviceInput) (*iam.EnableMFADeviceOutput, error) - GenerateCredentialReportRequest(*iam.GenerateCredentialReportInput) (*service.Request, *iam.GenerateCredentialReportOutput) + GenerateCredentialReportRequest(*iam.GenerateCredentialReportInput) (*request.Request, *iam.GenerateCredentialReportOutput) GenerateCredentialReport(*iam.GenerateCredentialReportInput) (*iam.GenerateCredentialReportOutput, error) - GetAccessKeyLastUsedRequest(*iam.GetAccessKeyLastUsedInput) (*service.Request, *iam.GetAccessKeyLastUsedOutput) + GetAccessKeyLastUsedRequest(*iam.GetAccessKeyLastUsedInput) (*request.Request, *iam.GetAccessKeyLastUsedOutput) GetAccessKeyLastUsed(*iam.GetAccessKeyLastUsedInput) (*iam.GetAccessKeyLastUsedOutput, error) - GetAccountAuthorizationDetailsRequest(*iam.GetAccountAuthorizationDetailsInput) (*service.Request, *iam.GetAccountAuthorizationDetailsOutput) + GetAccountAuthorizationDetailsRequest(*iam.GetAccountAuthorizationDetailsInput) (*request.Request, *iam.GetAccountAuthorizationDetailsOutput) GetAccountAuthorizationDetails(*iam.GetAccountAuthorizationDetailsInput) (*iam.GetAccountAuthorizationDetailsOutput, error) GetAccountAuthorizationDetailsPages(*iam.GetAccountAuthorizationDetailsInput, func(*iam.GetAccountAuthorizationDetailsOutput, bool) bool) error - GetAccountPasswordPolicyRequest(*iam.GetAccountPasswordPolicyInput) (*service.Request, *iam.GetAccountPasswordPolicyOutput) + GetAccountPasswordPolicyRequest(*iam.GetAccountPasswordPolicyInput) (*request.Request, *iam.GetAccountPasswordPolicyOutput) GetAccountPasswordPolicy(*iam.GetAccountPasswordPolicyInput) (*iam.GetAccountPasswordPolicyOutput, error) - GetAccountSummaryRequest(*iam.GetAccountSummaryInput) (*service.Request, *iam.GetAccountSummaryOutput) + GetAccountSummaryRequest(*iam.GetAccountSummaryInput) (*request.Request, *iam.GetAccountSummaryOutput) GetAccountSummary(*iam.GetAccountSummaryInput) (*iam.GetAccountSummaryOutput, error) - GetCredentialReportRequest(*iam.GetCredentialReportInput) (*service.Request, *iam.GetCredentialReportOutput) + GetContextKeysForCustomPolicyRequest(*iam.GetContextKeysForCustomPolicyInput) (*request.Request, *iam.GetContextKeysForPolicyResponse) + + GetContextKeysForCustomPolicy(*iam.GetContextKeysForCustomPolicyInput) (*iam.GetContextKeysForPolicyResponse, error) + + GetContextKeysForPrincipalPolicyRequest(*iam.GetContextKeysForPrincipalPolicyInput) (*request.Request, *iam.GetContextKeysForPolicyResponse) + + GetContextKeysForPrincipalPolicy(*iam.GetContextKeysForPrincipalPolicyInput) (*iam.GetContextKeysForPolicyResponse, error) + + GetCredentialReportRequest(*iam.GetCredentialReportInput) (*request.Request, *iam.GetCredentialReportOutput) GetCredentialReport(*iam.GetCredentialReportInput) (*iam.GetCredentialReportOutput, error) - GetGroupRequest(*iam.GetGroupInput) (*service.Request, *iam.GetGroupOutput) + GetGroupRequest(*iam.GetGroupInput) (*request.Request, *iam.GetGroupOutput) GetGroup(*iam.GetGroupInput) (*iam.GetGroupOutput, error) GetGroupPages(*iam.GetGroupInput, func(*iam.GetGroupOutput, bool) bool) error - GetGroupPolicyRequest(*iam.GetGroupPolicyInput) (*service.Request, *iam.GetGroupPolicyOutput) + GetGroupPolicyRequest(*iam.GetGroupPolicyInput) (*request.Request, *iam.GetGroupPolicyOutput) GetGroupPolicy(*iam.GetGroupPolicyInput) (*iam.GetGroupPolicyOutput, error) - GetInstanceProfileRequest(*iam.GetInstanceProfileInput) (*service.Request, *iam.GetInstanceProfileOutput) + GetInstanceProfileRequest(*iam.GetInstanceProfileInput) (*request.Request, *iam.GetInstanceProfileOutput) GetInstanceProfile(*iam.GetInstanceProfileInput) (*iam.GetInstanceProfileOutput, error) - GetLoginProfileRequest(*iam.GetLoginProfileInput) (*service.Request, *iam.GetLoginProfileOutput) + GetLoginProfileRequest(*iam.GetLoginProfileInput) (*request.Request, *iam.GetLoginProfileOutput) GetLoginProfile(*iam.GetLoginProfileInput) (*iam.GetLoginProfileOutput, error) - GetOpenIDConnectProviderRequest(*iam.GetOpenIDConnectProviderInput) (*service.Request, *iam.GetOpenIDConnectProviderOutput) + GetOpenIDConnectProviderRequest(*iam.GetOpenIDConnectProviderInput) (*request.Request, *iam.GetOpenIDConnectProviderOutput) GetOpenIDConnectProvider(*iam.GetOpenIDConnectProviderInput) (*iam.GetOpenIDConnectProviderOutput, error) - GetPolicyRequest(*iam.GetPolicyInput) (*service.Request, *iam.GetPolicyOutput) + GetPolicyRequest(*iam.GetPolicyInput) (*request.Request, *iam.GetPolicyOutput) GetPolicy(*iam.GetPolicyInput) (*iam.GetPolicyOutput, error) - GetPolicyVersionRequest(*iam.GetPolicyVersionInput) (*service.Request, *iam.GetPolicyVersionOutput) + GetPolicyVersionRequest(*iam.GetPolicyVersionInput) (*request.Request, *iam.GetPolicyVersionOutput) GetPolicyVersion(*iam.GetPolicyVersionInput) (*iam.GetPolicyVersionOutput, error) - GetRoleRequest(*iam.GetRoleInput) (*service.Request, *iam.GetRoleOutput) + GetRoleRequest(*iam.GetRoleInput) (*request.Request, *iam.GetRoleOutput) GetRole(*iam.GetRoleInput) (*iam.GetRoleOutput, error) - GetRolePolicyRequest(*iam.GetRolePolicyInput) (*service.Request, *iam.GetRolePolicyOutput) + GetRolePolicyRequest(*iam.GetRolePolicyInput) (*request.Request, *iam.GetRolePolicyOutput) GetRolePolicy(*iam.GetRolePolicyInput) (*iam.GetRolePolicyOutput, error) - GetSAMLProviderRequest(*iam.GetSAMLProviderInput) (*service.Request, *iam.GetSAMLProviderOutput) + GetSAMLProviderRequest(*iam.GetSAMLProviderInput) (*request.Request, *iam.GetSAMLProviderOutput) GetSAMLProvider(*iam.GetSAMLProviderInput) (*iam.GetSAMLProviderOutput, error) - GetSSHPublicKeyRequest(*iam.GetSSHPublicKeyInput) (*service.Request, *iam.GetSSHPublicKeyOutput) + GetSSHPublicKeyRequest(*iam.GetSSHPublicKeyInput) (*request.Request, *iam.GetSSHPublicKeyOutput) GetSSHPublicKey(*iam.GetSSHPublicKeyInput) (*iam.GetSSHPublicKeyOutput, error) - GetServerCertificateRequest(*iam.GetServerCertificateInput) (*service.Request, *iam.GetServerCertificateOutput) + GetServerCertificateRequest(*iam.GetServerCertificateInput) (*request.Request, *iam.GetServerCertificateOutput) GetServerCertificate(*iam.GetServerCertificateInput) (*iam.GetServerCertificateOutput, error) - GetUserRequest(*iam.GetUserInput) (*service.Request, *iam.GetUserOutput) + GetUserRequest(*iam.GetUserInput) (*request.Request, *iam.GetUserOutput) GetUser(*iam.GetUserInput) (*iam.GetUserOutput, error) - GetUserPolicyRequest(*iam.GetUserPolicyInput) (*service.Request, *iam.GetUserPolicyOutput) + GetUserPolicyRequest(*iam.GetUserPolicyInput) (*request.Request, *iam.GetUserPolicyOutput) GetUserPolicy(*iam.GetUserPolicyInput) (*iam.GetUserPolicyOutput, error) - ListAccessKeysRequest(*iam.ListAccessKeysInput) (*service.Request, *iam.ListAccessKeysOutput) + ListAccessKeysRequest(*iam.ListAccessKeysInput) (*request.Request, *iam.ListAccessKeysOutput) ListAccessKeys(*iam.ListAccessKeysInput) (*iam.ListAccessKeysOutput, error) ListAccessKeysPages(*iam.ListAccessKeysInput, func(*iam.ListAccessKeysOutput, bool) bool) error - ListAccountAliasesRequest(*iam.ListAccountAliasesInput) (*service.Request, *iam.ListAccountAliasesOutput) + ListAccountAliasesRequest(*iam.ListAccountAliasesInput) (*request.Request, *iam.ListAccountAliasesOutput) ListAccountAliases(*iam.ListAccountAliasesInput) (*iam.ListAccountAliasesOutput, error) ListAccountAliasesPages(*iam.ListAccountAliasesInput, func(*iam.ListAccountAliasesOutput, bool) bool) error - ListAttachedGroupPoliciesRequest(*iam.ListAttachedGroupPoliciesInput) (*service.Request, *iam.ListAttachedGroupPoliciesOutput) + ListAttachedGroupPoliciesRequest(*iam.ListAttachedGroupPoliciesInput) (*request.Request, *iam.ListAttachedGroupPoliciesOutput) ListAttachedGroupPolicies(*iam.ListAttachedGroupPoliciesInput) (*iam.ListAttachedGroupPoliciesOutput, error) ListAttachedGroupPoliciesPages(*iam.ListAttachedGroupPoliciesInput, func(*iam.ListAttachedGroupPoliciesOutput, bool) bool) error - ListAttachedRolePoliciesRequest(*iam.ListAttachedRolePoliciesInput) (*service.Request, *iam.ListAttachedRolePoliciesOutput) + ListAttachedRolePoliciesRequest(*iam.ListAttachedRolePoliciesInput) (*request.Request, *iam.ListAttachedRolePoliciesOutput) ListAttachedRolePolicies(*iam.ListAttachedRolePoliciesInput) (*iam.ListAttachedRolePoliciesOutput, error) ListAttachedRolePoliciesPages(*iam.ListAttachedRolePoliciesInput, func(*iam.ListAttachedRolePoliciesOutput, bool) bool) error - ListAttachedUserPoliciesRequest(*iam.ListAttachedUserPoliciesInput) (*service.Request, *iam.ListAttachedUserPoliciesOutput) + ListAttachedUserPoliciesRequest(*iam.ListAttachedUserPoliciesInput) (*request.Request, *iam.ListAttachedUserPoliciesOutput) ListAttachedUserPolicies(*iam.ListAttachedUserPoliciesInput) (*iam.ListAttachedUserPoliciesOutput, error) ListAttachedUserPoliciesPages(*iam.ListAttachedUserPoliciesInput, func(*iam.ListAttachedUserPoliciesOutput, bool) bool) error - ListEntitiesForPolicyRequest(*iam.ListEntitiesForPolicyInput) (*service.Request, *iam.ListEntitiesForPolicyOutput) + ListEntitiesForPolicyRequest(*iam.ListEntitiesForPolicyInput) (*request.Request, *iam.ListEntitiesForPolicyOutput) ListEntitiesForPolicy(*iam.ListEntitiesForPolicyInput) (*iam.ListEntitiesForPolicyOutput, error) ListEntitiesForPolicyPages(*iam.ListEntitiesForPolicyInput, func(*iam.ListEntitiesForPolicyOutput, bool) bool) error - ListGroupPoliciesRequest(*iam.ListGroupPoliciesInput) (*service.Request, *iam.ListGroupPoliciesOutput) + ListGroupPoliciesRequest(*iam.ListGroupPoliciesInput) (*request.Request, *iam.ListGroupPoliciesOutput) ListGroupPolicies(*iam.ListGroupPoliciesInput) (*iam.ListGroupPoliciesOutput, error) ListGroupPoliciesPages(*iam.ListGroupPoliciesInput, func(*iam.ListGroupPoliciesOutput, bool) bool) error - ListGroupsRequest(*iam.ListGroupsInput) (*service.Request, *iam.ListGroupsOutput) + ListGroupsRequest(*iam.ListGroupsInput) (*request.Request, *iam.ListGroupsOutput) ListGroups(*iam.ListGroupsInput) (*iam.ListGroupsOutput, error) ListGroupsPages(*iam.ListGroupsInput, func(*iam.ListGroupsOutput, bool) bool) error - ListGroupsForUserRequest(*iam.ListGroupsForUserInput) (*service.Request, *iam.ListGroupsForUserOutput) + ListGroupsForUserRequest(*iam.ListGroupsForUserInput) (*request.Request, *iam.ListGroupsForUserOutput) ListGroupsForUser(*iam.ListGroupsForUserInput) (*iam.ListGroupsForUserOutput, error) ListGroupsForUserPages(*iam.ListGroupsForUserInput, func(*iam.ListGroupsForUserOutput, bool) bool) error - ListInstanceProfilesRequest(*iam.ListInstanceProfilesInput) (*service.Request, *iam.ListInstanceProfilesOutput) + ListInstanceProfilesRequest(*iam.ListInstanceProfilesInput) (*request.Request, *iam.ListInstanceProfilesOutput) ListInstanceProfiles(*iam.ListInstanceProfilesInput) (*iam.ListInstanceProfilesOutput, error) ListInstanceProfilesPages(*iam.ListInstanceProfilesInput, func(*iam.ListInstanceProfilesOutput, bool) bool) error - ListInstanceProfilesForRoleRequest(*iam.ListInstanceProfilesForRoleInput) (*service.Request, *iam.ListInstanceProfilesForRoleOutput) + ListInstanceProfilesForRoleRequest(*iam.ListInstanceProfilesForRoleInput) (*request.Request, *iam.ListInstanceProfilesForRoleOutput) ListInstanceProfilesForRole(*iam.ListInstanceProfilesForRoleInput) (*iam.ListInstanceProfilesForRoleOutput, error) ListInstanceProfilesForRolePages(*iam.ListInstanceProfilesForRoleInput, func(*iam.ListInstanceProfilesForRoleOutput, bool) bool) error - ListMFADevicesRequest(*iam.ListMFADevicesInput) (*service.Request, *iam.ListMFADevicesOutput) + ListMFADevicesRequest(*iam.ListMFADevicesInput) (*request.Request, *iam.ListMFADevicesOutput) ListMFADevices(*iam.ListMFADevicesInput) (*iam.ListMFADevicesOutput, error) ListMFADevicesPages(*iam.ListMFADevicesInput, func(*iam.ListMFADevicesOutput, bool) bool) error - ListOpenIDConnectProvidersRequest(*iam.ListOpenIDConnectProvidersInput) (*service.Request, *iam.ListOpenIDConnectProvidersOutput) + ListOpenIDConnectProvidersRequest(*iam.ListOpenIDConnectProvidersInput) (*request.Request, *iam.ListOpenIDConnectProvidersOutput) ListOpenIDConnectProviders(*iam.ListOpenIDConnectProvidersInput) (*iam.ListOpenIDConnectProvidersOutput, error) - ListPoliciesRequest(*iam.ListPoliciesInput) (*service.Request, *iam.ListPoliciesOutput) + ListPoliciesRequest(*iam.ListPoliciesInput) (*request.Request, *iam.ListPoliciesOutput) ListPolicies(*iam.ListPoliciesInput) (*iam.ListPoliciesOutput, error) ListPoliciesPages(*iam.ListPoliciesInput, func(*iam.ListPoliciesOutput, bool) bool) error - ListPolicyVersionsRequest(*iam.ListPolicyVersionsInput) (*service.Request, *iam.ListPolicyVersionsOutput) + ListPolicyVersionsRequest(*iam.ListPolicyVersionsInput) (*request.Request, *iam.ListPolicyVersionsOutput) ListPolicyVersions(*iam.ListPolicyVersionsInput) (*iam.ListPolicyVersionsOutput, error) - ListRolePoliciesRequest(*iam.ListRolePoliciesInput) (*service.Request, *iam.ListRolePoliciesOutput) + ListRolePoliciesRequest(*iam.ListRolePoliciesInput) (*request.Request, *iam.ListRolePoliciesOutput) ListRolePolicies(*iam.ListRolePoliciesInput) (*iam.ListRolePoliciesOutput, error) ListRolePoliciesPages(*iam.ListRolePoliciesInput, func(*iam.ListRolePoliciesOutput, bool) bool) error - ListRolesRequest(*iam.ListRolesInput) (*service.Request, *iam.ListRolesOutput) + ListRolesRequest(*iam.ListRolesInput) (*request.Request, *iam.ListRolesOutput) ListRoles(*iam.ListRolesInput) (*iam.ListRolesOutput, error) ListRolesPages(*iam.ListRolesInput, func(*iam.ListRolesOutput, bool) bool) error - ListSAMLProvidersRequest(*iam.ListSAMLProvidersInput) (*service.Request, *iam.ListSAMLProvidersOutput) + ListSAMLProvidersRequest(*iam.ListSAMLProvidersInput) (*request.Request, *iam.ListSAMLProvidersOutput) ListSAMLProviders(*iam.ListSAMLProvidersInput) (*iam.ListSAMLProvidersOutput, error) - ListSSHPublicKeysRequest(*iam.ListSSHPublicKeysInput) (*service.Request, *iam.ListSSHPublicKeysOutput) + ListSSHPublicKeysRequest(*iam.ListSSHPublicKeysInput) (*request.Request, *iam.ListSSHPublicKeysOutput) ListSSHPublicKeys(*iam.ListSSHPublicKeysInput) (*iam.ListSSHPublicKeysOutput, error) - ListServerCertificatesRequest(*iam.ListServerCertificatesInput) (*service.Request, *iam.ListServerCertificatesOutput) + ListServerCertificatesRequest(*iam.ListServerCertificatesInput) (*request.Request, *iam.ListServerCertificatesOutput) ListServerCertificates(*iam.ListServerCertificatesInput) (*iam.ListServerCertificatesOutput, error) ListServerCertificatesPages(*iam.ListServerCertificatesInput, func(*iam.ListServerCertificatesOutput, bool) bool) error - ListSigningCertificatesRequest(*iam.ListSigningCertificatesInput) (*service.Request, *iam.ListSigningCertificatesOutput) + ListSigningCertificatesRequest(*iam.ListSigningCertificatesInput) (*request.Request, *iam.ListSigningCertificatesOutput) ListSigningCertificates(*iam.ListSigningCertificatesInput) (*iam.ListSigningCertificatesOutput, error) ListSigningCertificatesPages(*iam.ListSigningCertificatesInput, func(*iam.ListSigningCertificatesOutput, bool) bool) error - ListUserPoliciesRequest(*iam.ListUserPoliciesInput) (*service.Request, *iam.ListUserPoliciesOutput) + ListUserPoliciesRequest(*iam.ListUserPoliciesInput) (*request.Request, *iam.ListUserPoliciesOutput) ListUserPolicies(*iam.ListUserPoliciesInput) (*iam.ListUserPoliciesOutput, error) ListUserPoliciesPages(*iam.ListUserPoliciesInput, func(*iam.ListUserPoliciesOutput, bool) bool) error - ListUsersRequest(*iam.ListUsersInput) (*service.Request, *iam.ListUsersOutput) + ListUsersRequest(*iam.ListUsersInput) (*request.Request, *iam.ListUsersOutput) ListUsers(*iam.ListUsersInput) (*iam.ListUsersOutput, error) ListUsersPages(*iam.ListUsersInput, func(*iam.ListUsersOutput, bool) bool) error - ListVirtualMFADevicesRequest(*iam.ListVirtualMFADevicesInput) (*service.Request, *iam.ListVirtualMFADevicesOutput) + ListVirtualMFADevicesRequest(*iam.ListVirtualMFADevicesInput) (*request.Request, *iam.ListVirtualMFADevicesOutput) ListVirtualMFADevices(*iam.ListVirtualMFADevicesInput) (*iam.ListVirtualMFADevicesOutput, error) ListVirtualMFADevicesPages(*iam.ListVirtualMFADevicesInput, func(*iam.ListVirtualMFADevicesOutput, bool) bool) error - PutGroupPolicyRequest(*iam.PutGroupPolicyInput) (*service.Request, *iam.PutGroupPolicyOutput) + PutGroupPolicyRequest(*iam.PutGroupPolicyInput) (*request.Request, *iam.PutGroupPolicyOutput) PutGroupPolicy(*iam.PutGroupPolicyInput) (*iam.PutGroupPolicyOutput, error) - PutRolePolicyRequest(*iam.PutRolePolicyInput) (*service.Request, *iam.PutRolePolicyOutput) + PutRolePolicyRequest(*iam.PutRolePolicyInput) (*request.Request, *iam.PutRolePolicyOutput) PutRolePolicy(*iam.PutRolePolicyInput) (*iam.PutRolePolicyOutput, error) - PutUserPolicyRequest(*iam.PutUserPolicyInput) (*service.Request, *iam.PutUserPolicyOutput) + PutUserPolicyRequest(*iam.PutUserPolicyInput) (*request.Request, *iam.PutUserPolicyOutput) PutUserPolicy(*iam.PutUserPolicyInput) (*iam.PutUserPolicyOutput, error) - RemoveClientIDFromOpenIDConnectProviderRequest(*iam.RemoveClientIDFromOpenIDConnectProviderInput) (*service.Request, *iam.RemoveClientIDFromOpenIDConnectProviderOutput) + RemoveClientIDFromOpenIDConnectProviderRequest(*iam.RemoveClientIDFromOpenIDConnectProviderInput) (*request.Request, *iam.RemoveClientIDFromOpenIDConnectProviderOutput) RemoveClientIDFromOpenIDConnectProvider(*iam.RemoveClientIDFromOpenIDConnectProviderInput) (*iam.RemoveClientIDFromOpenIDConnectProviderOutput, error) - RemoveRoleFromInstanceProfileRequest(*iam.RemoveRoleFromInstanceProfileInput) (*service.Request, *iam.RemoveRoleFromInstanceProfileOutput) + RemoveRoleFromInstanceProfileRequest(*iam.RemoveRoleFromInstanceProfileInput) (*request.Request, *iam.RemoveRoleFromInstanceProfileOutput) RemoveRoleFromInstanceProfile(*iam.RemoveRoleFromInstanceProfileInput) (*iam.RemoveRoleFromInstanceProfileOutput, error) - RemoveUserFromGroupRequest(*iam.RemoveUserFromGroupInput) (*service.Request, *iam.RemoveUserFromGroupOutput) + RemoveUserFromGroupRequest(*iam.RemoveUserFromGroupInput) (*request.Request, *iam.RemoveUserFromGroupOutput) RemoveUserFromGroup(*iam.RemoveUserFromGroupInput) (*iam.RemoveUserFromGroupOutput, error) - ResyncMFADeviceRequest(*iam.ResyncMFADeviceInput) (*service.Request, *iam.ResyncMFADeviceOutput) + ResyncMFADeviceRequest(*iam.ResyncMFADeviceInput) (*request.Request, *iam.ResyncMFADeviceOutput) ResyncMFADevice(*iam.ResyncMFADeviceInput) (*iam.ResyncMFADeviceOutput, error) - SetDefaultPolicyVersionRequest(*iam.SetDefaultPolicyVersionInput) (*service.Request, *iam.SetDefaultPolicyVersionOutput) + SetDefaultPolicyVersionRequest(*iam.SetDefaultPolicyVersionInput) (*request.Request, *iam.SetDefaultPolicyVersionOutput) SetDefaultPolicyVersion(*iam.SetDefaultPolicyVersionInput) (*iam.SetDefaultPolicyVersionOutput, error) - UpdateAccessKeyRequest(*iam.UpdateAccessKeyInput) (*service.Request, *iam.UpdateAccessKeyOutput) + SimulateCustomPolicyRequest(*iam.SimulateCustomPolicyInput) (*request.Request, *iam.SimulatePolicyResponse) + + SimulateCustomPolicy(*iam.SimulateCustomPolicyInput) (*iam.SimulatePolicyResponse, error) + + SimulatePrincipalPolicyRequest(*iam.SimulatePrincipalPolicyInput) (*request.Request, *iam.SimulatePolicyResponse) + + SimulatePrincipalPolicy(*iam.SimulatePrincipalPolicyInput) (*iam.SimulatePolicyResponse, error) + + UpdateAccessKeyRequest(*iam.UpdateAccessKeyInput) (*request.Request, *iam.UpdateAccessKeyOutput) UpdateAccessKey(*iam.UpdateAccessKeyInput) (*iam.UpdateAccessKeyOutput, error) - UpdateAccountPasswordPolicyRequest(*iam.UpdateAccountPasswordPolicyInput) (*service.Request, *iam.UpdateAccountPasswordPolicyOutput) + UpdateAccountPasswordPolicyRequest(*iam.UpdateAccountPasswordPolicyInput) (*request.Request, *iam.UpdateAccountPasswordPolicyOutput) UpdateAccountPasswordPolicy(*iam.UpdateAccountPasswordPolicyInput) (*iam.UpdateAccountPasswordPolicyOutput, error) - UpdateAssumeRolePolicyRequest(*iam.UpdateAssumeRolePolicyInput) (*service.Request, *iam.UpdateAssumeRolePolicyOutput) + UpdateAssumeRolePolicyRequest(*iam.UpdateAssumeRolePolicyInput) (*request.Request, *iam.UpdateAssumeRolePolicyOutput) UpdateAssumeRolePolicy(*iam.UpdateAssumeRolePolicyInput) (*iam.UpdateAssumeRolePolicyOutput, error) - UpdateGroupRequest(*iam.UpdateGroupInput) (*service.Request, *iam.UpdateGroupOutput) + UpdateGroupRequest(*iam.UpdateGroupInput) (*request.Request, *iam.UpdateGroupOutput) UpdateGroup(*iam.UpdateGroupInput) (*iam.UpdateGroupOutput, error) - UpdateLoginProfileRequest(*iam.UpdateLoginProfileInput) (*service.Request, *iam.UpdateLoginProfileOutput) + UpdateLoginProfileRequest(*iam.UpdateLoginProfileInput) (*request.Request, *iam.UpdateLoginProfileOutput) UpdateLoginProfile(*iam.UpdateLoginProfileInput) (*iam.UpdateLoginProfileOutput, error) - UpdateOpenIDConnectProviderThumbprintRequest(*iam.UpdateOpenIDConnectProviderThumbprintInput) (*service.Request, *iam.UpdateOpenIDConnectProviderThumbprintOutput) + UpdateOpenIDConnectProviderThumbprintRequest(*iam.UpdateOpenIDConnectProviderThumbprintInput) (*request.Request, *iam.UpdateOpenIDConnectProviderThumbprintOutput) UpdateOpenIDConnectProviderThumbprint(*iam.UpdateOpenIDConnectProviderThumbprintInput) (*iam.UpdateOpenIDConnectProviderThumbprintOutput, error) - UpdateSAMLProviderRequest(*iam.UpdateSAMLProviderInput) (*service.Request, *iam.UpdateSAMLProviderOutput) + UpdateSAMLProviderRequest(*iam.UpdateSAMLProviderInput) (*request.Request, *iam.UpdateSAMLProviderOutput) UpdateSAMLProvider(*iam.UpdateSAMLProviderInput) (*iam.UpdateSAMLProviderOutput, error) - UpdateSSHPublicKeyRequest(*iam.UpdateSSHPublicKeyInput) (*service.Request, *iam.UpdateSSHPublicKeyOutput) + UpdateSSHPublicKeyRequest(*iam.UpdateSSHPublicKeyInput) (*request.Request, *iam.UpdateSSHPublicKeyOutput) UpdateSSHPublicKey(*iam.UpdateSSHPublicKeyInput) (*iam.UpdateSSHPublicKeyOutput, error) - UpdateServerCertificateRequest(*iam.UpdateServerCertificateInput) (*service.Request, *iam.UpdateServerCertificateOutput) + UpdateServerCertificateRequest(*iam.UpdateServerCertificateInput) (*request.Request, *iam.UpdateServerCertificateOutput) UpdateServerCertificate(*iam.UpdateServerCertificateInput) (*iam.UpdateServerCertificateOutput, error) - UpdateSigningCertificateRequest(*iam.UpdateSigningCertificateInput) (*service.Request, *iam.UpdateSigningCertificateOutput) + UpdateSigningCertificateRequest(*iam.UpdateSigningCertificateInput) (*request.Request, *iam.UpdateSigningCertificateOutput) UpdateSigningCertificate(*iam.UpdateSigningCertificateInput) (*iam.UpdateSigningCertificateOutput, error) - UpdateUserRequest(*iam.UpdateUserInput) (*service.Request, *iam.UpdateUserOutput) + UpdateUserRequest(*iam.UpdateUserInput) (*request.Request, *iam.UpdateUserOutput) UpdateUser(*iam.UpdateUserInput) (*iam.UpdateUserOutput, error) - UploadSSHPublicKeyRequest(*iam.UploadSSHPublicKeyInput) (*service.Request, *iam.UploadSSHPublicKeyOutput) + UploadSSHPublicKeyRequest(*iam.UploadSSHPublicKeyInput) (*request.Request, *iam.UploadSSHPublicKeyOutput) UploadSSHPublicKey(*iam.UploadSSHPublicKeyInput) (*iam.UploadSSHPublicKeyOutput, error) - UploadServerCertificateRequest(*iam.UploadServerCertificateInput) (*service.Request, *iam.UploadServerCertificateOutput) + UploadServerCertificateRequest(*iam.UploadServerCertificateInput) (*request.Request, *iam.UploadServerCertificateOutput) UploadServerCertificate(*iam.UploadServerCertificateInput) (*iam.UploadServerCertificateOutput, error) - UploadSigningCertificateRequest(*iam.UploadSigningCertificateInput) (*service.Request, *iam.UploadSigningCertificateOutput) + UploadSigningCertificateRequest(*iam.UploadSigningCertificateInput) (*request.Request, *iam.UploadSigningCertificateOutput) UploadSigningCertificate(*iam.UploadSigningCertificateInput) (*iam.UploadSigningCertificateOutput, error) } diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/iam/iamiface/interface_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/iam/iamiface/interface_test.go deleted file mode 100644 index 51e71d9d8..000000000 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/iam/iamiface/interface_test.go +++ /dev/null @@ -1,15 +0,0 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. - -package iamiface_test - -import ( - "testing" - - "github.com/aws/aws-sdk-go/service/iam" - "github.com/aws/aws-sdk-go/service/iam/iamiface" - "github.com/stretchr/testify/assert" -) - -func TestInterface(t *testing.T) { - assert.Implements(t, (*iamiface.IAMAPI)(nil), iam.New(nil)) -} diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/iam/service.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/iam/service.go index 3fd9ff83a..23ea20a6a 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/iam/service.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/iam/service.go @@ -5,7 +5,9 @@ package iam import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/defaults" + "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/aws/service" + "github.com/aws/aws-sdk-go/aws/service/serviceinfo" "github.com/aws/aws-sdk-go/internal/protocol/query" "github.com/aws/aws-sdk-go/internal/signer/v4" ) @@ -55,9 +57,7 @@ import ( // This topic provides general information about the types of credentials used // for accessing AWS. IAM Best Practices (http://docs.aws.amazon.com/IAM/latest/UserGuide/IAMBestPractices.html). // This topic presents a list of suggestions for using the IAM service to help -// secure your AWS resources. AWS Security Token Service (http://docs.aws.amazon.com/STS/latest/UsingSTS/). -// This guide describes how to create and use temporary security credentials. -// Signing AWS API Requests (http://docs.aws.amazon.com/general/latest/gr/signing_aws_api_requests.html). +// secure your AWS resources. Signing AWS API Requests (http://docs.aws.amazon.com/general/latest/gr/signing_aws_api_requests.html). // This set of topics walk you through the process of signing a request using // an access key ID and secret access key. type IAM struct { @@ -68,14 +68,16 @@ type IAM struct { var initService func(*service.Service) // Used for custom request initialization logic -var initRequest func(*service.Request) +var initRequest func(*request.Request) // New returns a new IAM client. func New(config *aws.Config) *IAM { service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "iam", - APIVersion: "2010-05-08", + ServiceInfo: serviceinfo.ServiceInfo{ + Config: defaults.DefaultConfig.Merge(config), + ServiceName: "iam", + APIVersion: "2010-05-08", + }, } service.Initialize() @@ -96,8 +98,8 @@ func New(config *aws.Config) *IAM { // newRequest creates a new request for a IAM operation and runs any // custom request initialization. -func (c *IAM) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) +func (c *IAM) newRequest(op *request.Operation, params, data interface{}) *request.Request { + req := c.NewRequest(op, params, data) // Run custom request initialization if present if initRequest != nil { diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/api.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/api.go index 7b206beb6..20bcc637f 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/api.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/api.go @@ -8,14 +8,14 @@ import ( "time" "github.com/aws/aws-sdk-go/aws/awsutil" - "github.com/aws/aws-sdk-go/aws/service" + "github.com/aws/aws-sdk-go/aws/request" ) const opAbortMultipartUpload = "AbortMultipartUpload" // AbortMultipartUploadRequest generates a request for the AbortMultipartUpload operation. -func (c *S3) AbortMultipartUploadRequest(input *AbortMultipartUploadInput) (req *service.Request, output *AbortMultipartUploadOutput) { - op := &service.Operation{ +func (c *S3) AbortMultipartUploadRequest(input *AbortMultipartUploadInput) (req *request.Request, output *AbortMultipartUploadOutput) { + op := &request.Operation{ Name: opAbortMultipartUpload, HTTPMethod: "DELETE", HTTPPath: "/{Bucket}/{Key+}", @@ -45,8 +45,8 @@ func (c *S3) AbortMultipartUpload(input *AbortMultipartUploadInput) (*AbortMulti const opCompleteMultipartUpload = "CompleteMultipartUpload" // CompleteMultipartUploadRequest generates a request for the CompleteMultipartUpload operation. -func (c *S3) CompleteMultipartUploadRequest(input *CompleteMultipartUploadInput) (req *service.Request, output *CompleteMultipartUploadOutput) { - op := &service.Operation{ +func (c *S3) CompleteMultipartUploadRequest(input *CompleteMultipartUploadInput) (req *request.Request, output *CompleteMultipartUploadOutput) { + op := &request.Operation{ Name: opCompleteMultipartUpload, HTTPMethod: "POST", HTTPPath: "/{Bucket}/{Key+}", @@ -72,8 +72,8 @@ func (c *S3) CompleteMultipartUpload(input *CompleteMultipartUploadInput) (*Comp const opCopyObject = "CopyObject" // CopyObjectRequest generates a request for the CopyObject operation. -func (c *S3) CopyObjectRequest(input *CopyObjectInput) (req *service.Request, output *CopyObjectOutput) { - op := &service.Operation{ +func (c *S3) CopyObjectRequest(input *CopyObjectInput) (req *request.Request, output *CopyObjectOutput) { + op := &request.Operation{ Name: opCopyObject, HTTPMethod: "PUT", HTTPPath: "/{Bucket}/{Key+}", @@ -99,8 +99,8 @@ func (c *S3) CopyObject(input *CopyObjectInput) (*CopyObjectOutput, error) { const opCreateBucket = "CreateBucket" // CreateBucketRequest generates a request for the CreateBucket operation. -func (c *S3) CreateBucketRequest(input *CreateBucketInput) (req *service.Request, output *CreateBucketOutput) { - op := &service.Operation{ +func (c *S3) CreateBucketRequest(input *CreateBucketInput) (req *request.Request, output *CreateBucketOutput) { + op := &request.Operation{ Name: opCreateBucket, HTTPMethod: "PUT", HTTPPath: "/{Bucket}", @@ -126,8 +126,8 @@ func (c *S3) CreateBucket(input *CreateBucketInput) (*CreateBucketOutput, error) const opCreateMultipartUpload = "CreateMultipartUpload" // CreateMultipartUploadRequest generates a request for the CreateMultipartUpload operation. -func (c *S3) CreateMultipartUploadRequest(input *CreateMultipartUploadInput) (req *service.Request, output *CreateMultipartUploadOutput) { - op := &service.Operation{ +func (c *S3) CreateMultipartUploadRequest(input *CreateMultipartUploadInput) (req *request.Request, output *CreateMultipartUploadOutput) { + op := &request.Operation{ Name: opCreateMultipartUpload, HTTPMethod: "POST", HTTPPath: "/{Bucket}/{Key+}?uploads", @@ -159,8 +159,8 @@ func (c *S3) CreateMultipartUpload(input *CreateMultipartUploadInput) (*CreateMu const opDeleteBucket = "DeleteBucket" // DeleteBucketRequest generates a request for the DeleteBucket operation. -func (c *S3) DeleteBucketRequest(input *DeleteBucketInput) (req *service.Request, output *DeleteBucketOutput) { - op := &service.Operation{ +func (c *S3) DeleteBucketRequest(input *DeleteBucketInput) (req *request.Request, output *DeleteBucketOutput) { + op := &request.Operation{ Name: opDeleteBucket, HTTPMethod: "DELETE", HTTPPath: "/{Bucket}", @@ -187,8 +187,8 @@ func (c *S3) DeleteBucket(input *DeleteBucketInput) (*DeleteBucketOutput, error) const opDeleteBucketCors = "DeleteBucketCors" // DeleteBucketCorsRequest generates a request for the DeleteBucketCors operation. -func (c *S3) DeleteBucketCorsRequest(input *DeleteBucketCorsInput) (req *service.Request, output *DeleteBucketCorsOutput) { - op := &service.Operation{ +func (c *S3) DeleteBucketCorsRequest(input *DeleteBucketCorsInput) (req *request.Request, output *DeleteBucketCorsOutput) { + op := &request.Operation{ Name: opDeleteBucketCors, HTTPMethod: "DELETE", HTTPPath: "/{Bucket}?cors", @@ -214,8 +214,8 @@ func (c *S3) DeleteBucketCors(input *DeleteBucketCorsInput) (*DeleteBucketCorsOu const opDeleteBucketLifecycle = "DeleteBucketLifecycle" // DeleteBucketLifecycleRequest generates a request for the DeleteBucketLifecycle operation. -func (c *S3) DeleteBucketLifecycleRequest(input *DeleteBucketLifecycleInput) (req *service.Request, output *DeleteBucketLifecycleOutput) { - op := &service.Operation{ +func (c *S3) DeleteBucketLifecycleRequest(input *DeleteBucketLifecycleInput) (req *request.Request, output *DeleteBucketLifecycleOutput) { + op := &request.Operation{ Name: opDeleteBucketLifecycle, HTTPMethod: "DELETE", HTTPPath: "/{Bucket}?lifecycle", @@ -241,8 +241,8 @@ func (c *S3) DeleteBucketLifecycle(input *DeleteBucketLifecycleInput) (*DeleteBu const opDeleteBucketPolicy = "DeleteBucketPolicy" // DeleteBucketPolicyRequest generates a request for the DeleteBucketPolicy operation. -func (c *S3) DeleteBucketPolicyRequest(input *DeleteBucketPolicyInput) (req *service.Request, output *DeleteBucketPolicyOutput) { - op := &service.Operation{ +func (c *S3) DeleteBucketPolicyRequest(input *DeleteBucketPolicyInput) (req *request.Request, output *DeleteBucketPolicyOutput) { + op := &request.Operation{ Name: opDeleteBucketPolicy, HTTPMethod: "DELETE", HTTPPath: "/{Bucket}?policy", @@ -268,8 +268,8 @@ func (c *S3) DeleteBucketPolicy(input *DeleteBucketPolicyInput) (*DeleteBucketPo const opDeleteBucketReplication = "DeleteBucketReplication" // DeleteBucketReplicationRequest generates a request for the DeleteBucketReplication operation. -func (c *S3) DeleteBucketReplicationRequest(input *DeleteBucketReplicationInput) (req *service.Request, output *DeleteBucketReplicationOutput) { - op := &service.Operation{ +func (c *S3) DeleteBucketReplicationRequest(input *DeleteBucketReplicationInput) (req *request.Request, output *DeleteBucketReplicationOutput) { + op := &request.Operation{ Name: opDeleteBucketReplication, HTTPMethod: "DELETE", HTTPPath: "/{Bucket}?replication", @@ -294,8 +294,8 @@ func (c *S3) DeleteBucketReplication(input *DeleteBucketReplicationInput) (*Dele const opDeleteBucketTagging = "DeleteBucketTagging" // DeleteBucketTaggingRequest generates a request for the DeleteBucketTagging operation. -func (c *S3) DeleteBucketTaggingRequest(input *DeleteBucketTaggingInput) (req *service.Request, output *DeleteBucketTaggingOutput) { - op := &service.Operation{ +func (c *S3) DeleteBucketTaggingRequest(input *DeleteBucketTaggingInput) (req *request.Request, output *DeleteBucketTaggingOutput) { + op := &request.Operation{ Name: opDeleteBucketTagging, HTTPMethod: "DELETE", HTTPPath: "/{Bucket}?tagging", @@ -321,8 +321,8 @@ func (c *S3) DeleteBucketTagging(input *DeleteBucketTaggingInput) (*DeleteBucket const opDeleteBucketWebsite = "DeleteBucketWebsite" // DeleteBucketWebsiteRequest generates a request for the DeleteBucketWebsite operation. -func (c *S3) DeleteBucketWebsiteRequest(input *DeleteBucketWebsiteInput) (req *service.Request, output *DeleteBucketWebsiteOutput) { - op := &service.Operation{ +func (c *S3) DeleteBucketWebsiteRequest(input *DeleteBucketWebsiteInput) (req *request.Request, output *DeleteBucketWebsiteOutput) { + op := &request.Operation{ Name: opDeleteBucketWebsite, HTTPMethod: "DELETE", HTTPPath: "/{Bucket}?website", @@ -348,8 +348,8 @@ func (c *S3) DeleteBucketWebsite(input *DeleteBucketWebsiteInput) (*DeleteBucket const opDeleteObject = "DeleteObject" // DeleteObjectRequest generates a request for the DeleteObject operation. -func (c *S3) DeleteObjectRequest(input *DeleteObjectInput) (req *service.Request, output *DeleteObjectOutput) { - op := &service.Operation{ +func (c *S3) DeleteObjectRequest(input *DeleteObjectInput) (req *request.Request, output *DeleteObjectOutput) { + op := &request.Operation{ Name: opDeleteObject, HTTPMethod: "DELETE", HTTPPath: "/{Bucket}/{Key+}", @@ -377,8 +377,8 @@ func (c *S3) DeleteObject(input *DeleteObjectInput) (*DeleteObjectOutput, error) const opDeleteObjects = "DeleteObjects" // DeleteObjectsRequest generates a request for the DeleteObjects operation. -func (c *S3) DeleteObjectsRequest(input *DeleteObjectsInput) (req *service.Request, output *DeleteObjectsOutput) { - op := &service.Operation{ +func (c *S3) DeleteObjectsRequest(input *DeleteObjectsInput) (req *request.Request, output *DeleteObjectsOutput) { + op := &request.Operation{ Name: opDeleteObjects, HTTPMethod: "POST", HTTPPath: "/{Bucket}?delete", @@ -405,8 +405,8 @@ func (c *S3) DeleteObjects(input *DeleteObjectsInput) (*DeleteObjectsOutput, err const opGetBucketAcl = "GetBucketAcl" // GetBucketAclRequest generates a request for the GetBucketAcl operation. -func (c *S3) GetBucketAclRequest(input *GetBucketAclInput) (req *service.Request, output *GetBucketAclOutput) { - op := &service.Operation{ +func (c *S3) GetBucketAclRequest(input *GetBucketAclInput) (req *request.Request, output *GetBucketAclOutput) { + op := &request.Operation{ Name: opGetBucketAcl, HTTPMethod: "GET", HTTPPath: "/{Bucket}?acl", @@ -432,8 +432,8 @@ func (c *S3) GetBucketAcl(input *GetBucketAclInput) (*GetBucketAclOutput, error) const opGetBucketCors = "GetBucketCors" // GetBucketCorsRequest generates a request for the GetBucketCors operation. -func (c *S3) GetBucketCorsRequest(input *GetBucketCorsInput) (req *service.Request, output *GetBucketCorsOutput) { - op := &service.Operation{ +func (c *S3) GetBucketCorsRequest(input *GetBucketCorsInput) (req *request.Request, output *GetBucketCorsOutput) { + op := &request.Operation{ Name: opGetBucketCors, HTTPMethod: "GET", HTTPPath: "/{Bucket}?cors", @@ -459,8 +459,8 @@ func (c *S3) GetBucketCors(input *GetBucketCorsInput) (*GetBucketCorsOutput, err const opGetBucketLifecycle = "GetBucketLifecycle" // GetBucketLifecycleRequest generates a request for the GetBucketLifecycle operation. -func (c *S3) GetBucketLifecycleRequest(input *GetBucketLifecycleInput) (req *service.Request, output *GetBucketLifecycleOutput) { - op := &service.Operation{ +func (c *S3) GetBucketLifecycleRequest(input *GetBucketLifecycleInput) (req *request.Request, output *GetBucketLifecycleOutput) { + op := &request.Operation{ Name: opGetBucketLifecycle, HTTPMethod: "GET", HTTPPath: "/{Bucket}?lifecycle", @@ -476,18 +476,45 @@ func (c *S3) GetBucketLifecycleRequest(input *GetBucketLifecycleInput) (req *ser return } -// Returns the lifecycle configuration information set on the bucket. +// Deprecated, see the GetBucketLifecycleConfiguration operation. func (c *S3) GetBucketLifecycle(input *GetBucketLifecycleInput) (*GetBucketLifecycleOutput, error) { req, out := c.GetBucketLifecycleRequest(input) err := req.Send() return out, err } +const opGetBucketLifecycleConfiguration = "GetBucketLifecycleConfiguration" + +// GetBucketLifecycleConfigurationRequest generates a request for the GetBucketLifecycleConfiguration operation. +func (c *S3) GetBucketLifecycleConfigurationRequest(input *GetBucketLifecycleConfigurationInput) (req *request.Request, output *GetBucketLifecycleConfigurationOutput) { + op := &request.Operation{ + Name: opGetBucketLifecycleConfiguration, + HTTPMethod: "GET", + HTTPPath: "/{Bucket}?lifecycle", + } + + if input == nil { + input = &GetBucketLifecycleConfigurationInput{} + } + + req = c.newRequest(op, input, output) + output = &GetBucketLifecycleConfigurationOutput{} + req.Data = output + return +} + +// Returns the lifecycle configuration information set on the bucket. +func (c *S3) GetBucketLifecycleConfiguration(input *GetBucketLifecycleConfigurationInput) (*GetBucketLifecycleConfigurationOutput, error) { + req, out := c.GetBucketLifecycleConfigurationRequest(input) + err := req.Send() + return out, err +} + const opGetBucketLocation = "GetBucketLocation" // GetBucketLocationRequest generates a request for the GetBucketLocation operation. -func (c *S3) GetBucketLocationRequest(input *GetBucketLocationInput) (req *service.Request, output *GetBucketLocationOutput) { - op := &service.Operation{ +func (c *S3) GetBucketLocationRequest(input *GetBucketLocationInput) (req *request.Request, output *GetBucketLocationOutput) { + op := &request.Operation{ Name: opGetBucketLocation, HTTPMethod: "GET", HTTPPath: "/{Bucket}?location", @@ -513,8 +540,8 @@ func (c *S3) GetBucketLocation(input *GetBucketLocationInput) (*GetBucketLocatio const opGetBucketLogging = "GetBucketLogging" // GetBucketLoggingRequest generates a request for the GetBucketLogging operation. -func (c *S3) GetBucketLoggingRequest(input *GetBucketLoggingInput) (req *service.Request, output *GetBucketLoggingOutput) { - op := &service.Operation{ +func (c *S3) GetBucketLoggingRequest(input *GetBucketLoggingInput) (req *request.Request, output *GetBucketLoggingOutput) { + op := &request.Operation{ Name: opGetBucketLogging, HTTPMethod: "GET", HTTPPath: "/{Bucket}?logging", @@ -541,8 +568,8 @@ func (c *S3) GetBucketLogging(input *GetBucketLoggingInput) (*GetBucketLoggingOu const opGetBucketNotification = "GetBucketNotification" // GetBucketNotificationRequest generates a request for the GetBucketNotification operation. -func (c *S3) GetBucketNotificationRequest(input *GetBucketNotificationConfigurationRequest) (req *service.Request, output *NotificationConfigurationDeprecated) { - op := &service.Operation{ +func (c *S3) GetBucketNotificationRequest(input *GetBucketNotificationConfigurationRequest) (req *request.Request, output *NotificationConfigurationDeprecated) { + op := &request.Operation{ Name: opGetBucketNotification, HTTPMethod: "GET", HTTPPath: "/{Bucket}?notification", @@ -568,8 +595,8 @@ func (c *S3) GetBucketNotification(input *GetBucketNotificationConfigurationRequ const opGetBucketNotificationConfiguration = "GetBucketNotificationConfiguration" // GetBucketNotificationConfigurationRequest generates a request for the GetBucketNotificationConfiguration operation. -func (c *S3) GetBucketNotificationConfigurationRequest(input *GetBucketNotificationConfigurationRequest) (req *service.Request, output *NotificationConfiguration) { - op := &service.Operation{ +func (c *S3) GetBucketNotificationConfigurationRequest(input *GetBucketNotificationConfigurationRequest) (req *request.Request, output *NotificationConfiguration) { + op := &request.Operation{ Name: opGetBucketNotificationConfiguration, HTTPMethod: "GET", HTTPPath: "/{Bucket}?notification", @@ -595,8 +622,8 @@ func (c *S3) GetBucketNotificationConfiguration(input *GetBucketNotificationConf const opGetBucketPolicy = "GetBucketPolicy" // GetBucketPolicyRequest generates a request for the GetBucketPolicy operation. -func (c *S3) GetBucketPolicyRequest(input *GetBucketPolicyInput) (req *service.Request, output *GetBucketPolicyOutput) { - op := &service.Operation{ +func (c *S3) GetBucketPolicyRequest(input *GetBucketPolicyInput) (req *request.Request, output *GetBucketPolicyOutput) { + op := &request.Operation{ Name: opGetBucketPolicy, HTTPMethod: "GET", HTTPPath: "/{Bucket}?policy", @@ -622,8 +649,8 @@ func (c *S3) GetBucketPolicy(input *GetBucketPolicyInput) (*GetBucketPolicyOutpu const opGetBucketReplication = "GetBucketReplication" // GetBucketReplicationRequest generates a request for the GetBucketReplication operation. -func (c *S3) GetBucketReplicationRequest(input *GetBucketReplicationInput) (req *service.Request, output *GetBucketReplicationOutput) { - op := &service.Operation{ +func (c *S3) GetBucketReplicationRequest(input *GetBucketReplicationInput) (req *request.Request, output *GetBucketReplicationOutput) { + op := &request.Operation{ Name: opGetBucketReplication, HTTPMethod: "GET", HTTPPath: "/{Bucket}?replication", @@ -648,8 +675,8 @@ func (c *S3) GetBucketReplication(input *GetBucketReplicationInput) (*GetBucketR const opGetBucketRequestPayment = "GetBucketRequestPayment" // GetBucketRequestPaymentRequest generates a request for the GetBucketRequestPayment operation. -func (c *S3) GetBucketRequestPaymentRequest(input *GetBucketRequestPaymentInput) (req *service.Request, output *GetBucketRequestPaymentOutput) { - op := &service.Operation{ +func (c *S3) GetBucketRequestPaymentRequest(input *GetBucketRequestPaymentInput) (req *request.Request, output *GetBucketRequestPaymentOutput) { + op := &request.Operation{ Name: opGetBucketRequestPayment, HTTPMethod: "GET", HTTPPath: "/{Bucket}?requestPayment", @@ -675,8 +702,8 @@ func (c *S3) GetBucketRequestPayment(input *GetBucketRequestPaymentInput) (*GetB const opGetBucketTagging = "GetBucketTagging" // GetBucketTaggingRequest generates a request for the GetBucketTagging operation. -func (c *S3) GetBucketTaggingRequest(input *GetBucketTaggingInput) (req *service.Request, output *GetBucketTaggingOutput) { - op := &service.Operation{ +func (c *S3) GetBucketTaggingRequest(input *GetBucketTaggingInput) (req *request.Request, output *GetBucketTaggingOutput) { + op := &request.Operation{ Name: opGetBucketTagging, HTTPMethod: "GET", HTTPPath: "/{Bucket}?tagging", @@ -702,8 +729,8 @@ func (c *S3) GetBucketTagging(input *GetBucketTaggingInput) (*GetBucketTaggingOu const opGetBucketVersioning = "GetBucketVersioning" // GetBucketVersioningRequest generates a request for the GetBucketVersioning operation. -func (c *S3) GetBucketVersioningRequest(input *GetBucketVersioningInput) (req *service.Request, output *GetBucketVersioningOutput) { - op := &service.Operation{ +func (c *S3) GetBucketVersioningRequest(input *GetBucketVersioningInput) (req *request.Request, output *GetBucketVersioningOutput) { + op := &request.Operation{ Name: opGetBucketVersioning, HTTPMethod: "GET", HTTPPath: "/{Bucket}?versioning", @@ -729,8 +756,8 @@ func (c *S3) GetBucketVersioning(input *GetBucketVersioningInput) (*GetBucketVer const opGetBucketWebsite = "GetBucketWebsite" // GetBucketWebsiteRequest generates a request for the GetBucketWebsite operation. -func (c *S3) GetBucketWebsiteRequest(input *GetBucketWebsiteInput) (req *service.Request, output *GetBucketWebsiteOutput) { - op := &service.Operation{ +func (c *S3) GetBucketWebsiteRequest(input *GetBucketWebsiteInput) (req *request.Request, output *GetBucketWebsiteOutput) { + op := &request.Operation{ Name: opGetBucketWebsite, HTTPMethod: "GET", HTTPPath: "/{Bucket}?website", @@ -756,8 +783,8 @@ func (c *S3) GetBucketWebsite(input *GetBucketWebsiteInput) (*GetBucketWebsiteOu const opGetObject = "GetObject" // GetObjectRequest generates a request for the GetObject operation. -func (c *S3) GetObjectRequest(input *GetObjectInput) (req *service.Request, output *GetObjectOutput) { - op := &service.Operation{ +func (c *S3) GetObjectRequest(input *GetObjectInput) (req *request.Request, output *GetObjectOutput) { + op := &request.Operation{ Name: opGetObject, HTTPMethod: "GET", HTTPPath: "/{Bucket}/{Key+}", @@ -783,8 +810,8 @@ func (c *S3) GetObject(input *GetObjectInput) (*GetObjectOutput, error) { const opGetObjectAcl = "GetObjectAcl" // GetObjectAclRequest generates a request for the GetObjectAcl operation. -func (c *S3) GetObjectAclRequest(input *GetObjectAclInput) (req *service.Request, output *GetObjectAclOutput) { - op := &service.Operation{ +func (c *S3) GetObjectAclRequest(input *GetObjectAclInput) (req *request.Request, output *GetObjectAclOutput) { + op := &request.Operation{ Name: opGetObjectAcl, HTTPMethod: "GET", HTTPPath: "/{Bucket}/{Key+}?acl", @@ -810,8 +837,8 @@ func (c *S3) GetObjectAcl(input *GetObjectAclInput) (*GetObjectAclOutput, error) const opGetObjectTorrent = "GetObjectTorrent" // GetObjectTorrentRequest generates a request for the GetObjectTorrent operation. -func (c *S3) GetObjectTorrentRequest(input *GetObjectTorrentInput) (req *service.Request, output *GetObjectTorrentOutput) { - op := &service.Operation{ +func (c *S3) GetObjectTorrentRequest(input *GetObjectTorrentInput) (req *request.Request, output *GetObjectTorrentOutput) { + op := &request.Operation{ Name: opGetObjectTorrent, HTTPMethod: "GET", HTTPPath: "/{Bucket}/{Key+}?torrent", @@ -837,8 +864,8 @@ func (c *S3) GetObjectTorrent(input *GetObjectTorrentInput) (*GetObjectTorrentOu const opHeadBucket = "HeadBucket" // HeadBucketRequest generates a request for the HeadBucket operation. -func (c *S3) HeadBucketRequest(input *HeadBucketInput) (req *service.Request, output *HeadBucketOutput) { - op := &service.Operation{ +func (c *S3) HeadBucketRequest(input *HeadBucketInput) (req *request.Request, output *HeadBucketOutput) { + op := &request.Operation{ Name: opHeadBucket, HTTPMethod: "HEAD", HTTPPath: "/{Bucket}", @@ -865,8 +892,8 @@ func (c *S3) HeadBucket(input *HeadBucketInput) (*HeadBucketOutput, error) { const opHeadObject = "HeadObject" // HeadObjectRequest generates a request for the HeadObject operation. -func (c *S3) HeadObjectRequest(input *HeadObjectInput) (req *service.Request, output *HeadObjectOutput) { - op := &service.Operation{ +func (c *S3) HeadObjectRequest(input *HeadObjectInput) (req *request.Request, output *HeadObjectOutput) { + op := &request.Operation{ Name: opHeadObject, HTTPMethod: "HEAD", HTTPPath: "/{Bucket}/{Key+}", @@ -894,8 +921,8 @@ func (c *S3) HeadObject(input *HeadObjectInput) (*HeadObjectOutput, error) { const opListBuckets = "ListBuckets" // ListBucketsRequest generates a request for the ListBuckets operation. -func (c *S3) ListBucketsRequest(input *ListBucketsInput) (req *service.Request, output *ListBucketsOutput) { - op := &service.Operation{ +func (c *S3) ListBucketsRequest(input *ListBucketsInput) (req *request.Request, output *ListBucketsOutput) { + op := &request.Operation{ Name: opListBuckets, HTTPMethod: "GET", HTTPPath: "/", @@ -921,12 +948,12 @@ func (c *S3) ListBuckets(input *ListBucketsInput) (*ListBucketsOutput, error) { const opListMultipartUploads = "ListMultipartUploads" // ListMultipartUploadsRequest generates a request for the ListMultipartUploads operation. -func (c *S3) ListMultipartUploadsRequest(input *ListMultipartUploadsInput) (req *service.Request, output *ListMultipartUploadsOutput) { - op := &service.Operation{ +func (c *S3) ListMultipartUploadsRequest(input *ListMultipartUploadsInput) (req *request.Request, output *ListMultipartUploadsOutput) { + op := &request.Operation{ Name: opListMultipartUploads, HTTPMethod: "GET", HTTPPath: "/{Bucket}?uploads", - Paginator: &service.Paginator{ + Paginator: &request.Paginator{ InputTokens: []string{"KeyMarker", "UploadIdMarker"}, OutputTokens: []string{"NextKeyMarker", "NextUploadIdMarker"}, LimitToken: "MaxUploads", @@ -961,12 +988,12 @@ func (c *S3) ListMultipartUploadsPages(input *ListMultipartUploadsInput, fn func const opListObjectVersions = "ListObjectVersions" // ListObjectVersionsRequest generates a request for the ListObjectVersions operation. -func (c *S3) ListObjectVersionsRequest(input *ListObjectVersionsInput) (req *service.Request, output *ListObjectVersionsOutput) { - op := &service.Operation{ +func (c *S3) ListObjectVersionsRequest(input *ListObjectVersionsInput) (req *request.Request, output *ListObjectVersionsOutput) { + op := &request.Operation{ Name: opListObjectVersions, HTTPMethod: "GET", HTTPPath: "/{Bucket}?versions", - Paginator: &service.Paginator{ + Paginator: &request.Paginator{ InputTokens: []string{"KeyMarker", "VersionIdMarker"}, OutputTokens: []string{"NextKeyMarker", "NextVersionIdMarker"}, LimitToken: "MaxKeys", @@ -1001,12 +1028,12 @@ func (c *S3) ListObjectVersionsPages(input *ListObjectVersionsInput, fn func(p * const opListObjects = "ListObjects" // ListObjectsRequest generates a request for the ListObjects operation. -func (c *S3) ListObjectsRequest(input *ListObjectsInput) (req *service.Request, output *ListObjectsOutput) { - op := &service.Operation{ +func (c *S3) ListObjectsRequest(input *ListObjectsInput) (req *request.Request, output *ListObjectsOutput) { + op := &request.Operation{ Name: opListObjects, HTTPMethod: "GET", HTTPPath: "/{Bucket}", - Paginator: &service.Paginator{ + Paginator: &request.Paginator{ InputTokens: []string{"Marker"}, OutputTokens: []string{"NextMarker || Contents[-1].Key"}, LimitToken: "MaxKeys", @@ -1043,12 +1070,12 @@ func (c *S3) ListObjectsPages(input *ListObjectsInput, fn func(p *ListObjectsOut const opListParts = "ListParts" // ListPartsRequest generates a request for the ListParts operation. -func (c *S3) ListPartsRequest(input *ListPartsInput) (req *service.Request, output *ListPartsOutput) { - op := &service.Operation{ +func (c *S3) ListPartsRequest(input *ListPartsInput) (req *request.Request, output *ListPartsOutput) { + op := &request.Operation{ Name: opListParts, HTTPMethod: "GET", HTTPPath: "/{Bucket}/{Key+}", - Paginator: &service.Paginator{ + Paginator: &request.Paginator{ InputTokens: []string{"PartNumberMarker"}, OutputTokens: []string{"NextPartNumberMarker"}, LimitToken: "MaxParts", @@ -1083,8 +1110,8 @@ func (c *S3) ListPartsPages(input *ListPartsInput, fn func(p *ListPartsOutput, l const opPutBucketAcl = "PutBucketAcl" // PutBucketAclRequest generates a request for the PutBucketAcl operation. -func (c *S3) PutBucketAclRequest(input *PutBucketAclInput) (req *service.Request, output *PutBucketAclOutput) { - op := &service.Operation{ +func (c *S3) PutBucketAclRequest(input *PutBucketAclInput) (req *request.Request, output *PutBucketAclOutput) { + op := &request.Operation{ Name: opPutBucketAcl, HTTPMethod: "PUT", HTTPPath: "/{Bucket}?acl", @@ -1110,8 +1137,8 @@ func (c *S3) PutBucketAcl(input *PutBucketAclInput) (*PutBucketAclOutput, error) const opPutBucketCors = "PutBucketCors" // PutBucketCorsRequest generates a request for the PutBucketCors operation. -func (c *S3) PutBucketCorsRequest(input *PutBucketCorsInput) (req *service.Request, output *PutBucketCorsOutput) { - op := &service.Operation{ +func (c *S3) PutBucketCorsRequest(input *PutBucketCorsInput) (req *request.Request, output *PutBucketCorsOutput) { + op := &request.Operation{ Name: opPutBucketCors, HTTPMethod: "PUT", HTTPPath: "/{Bucket}?cors", @@ -1137,8 +1164,8 @@ func (c *S3) PutBucketCors(input *PutBucketCorsInput) (*PutBucketCorsOutput, err const opPutBucketLifecycle = "PutBucketLifecycle" // PutBucketLifecycleRequest generates a request for the PutBucketLifecycle operation. -func (c *S3) PutBucketLifecycleRequest(input *PutBucketLifecycleInput) (req *service.Request, output *PutBucketLifecycleOutput) { - op := &service.Operation{ +func (c *S3) PutBucketLifecycleRequest(input *PutBucketLifecycleInput) (req *request.Request, output *PutBucketLifecycleOutput) { + op := &request.Operation{ Name: opPutBucketLifecycle, HTTPMethod: "PUT", HTTPPath: "/{Bucket}?lifecycle", @@ -1154,19 +1181,46 @@ func (c *S3) PutBucketLifecycleRequest(input *PutBucketLifecycleInput) (req *ser return } -// Sets lifecycle configuration for your bucket. If a lifecycle configuration -// exists, it replaces it. +// Deprecated, see the PutBucketLifecycleConfiguration operation. func (c *S3) PutBucketLifecycle(input *PutBucketLifecycleInput) (*PutBucketLifecycleOutput, error) { req, out := c.PutBucketLifecycleRequest(input) err := req.Send() return out, err } +const opPutBucketLifecycleConfiguration = "PutBucketLifecycleConfiguration" + +// PutBucketLifecycleConfigurationRequest generates a request for the PutBucketLifecycleConfiguration operation. +func (c *S3) PutBucketLifecycleConfigurationRequest(input *PutBucketLifecycleConfigurationInput) (req *request.Request, output *PutBucketLifecycleConfigurationOutput) { + op := &request.Operation{ + Name: opPutBucketLifecycleConfiguration, + HTTPMethod: "PUT", + HTTPPath: "/{Bucket}?lifecycle", + } + + if input == nil { + input = &PutBucketLifecycleConfigurationInput{} + } + + req = c.newRequest(op, input, output) + output = &PutBucketLifecycleConfigurationOutput{} + req.Data = output + return +} + +// Sets lifecycle configuration for your bucket. If a lifecycle configuration +// exists, it replaces it. +func (c *S3) PutBucketLifecycleConfiguration(input *PutBucketLifecycleConfigurationInput) (*PutBucketLifecycleConfigurationOutput, error) { + req, out := c.PutBucketLifecycleConfigurationRequest(input) + err := req.Send() + return out, err +} + const opPutBucketLogging = "PutBucketLogging" // PutBucketLoggingRequest generates a request for the PutBucketLogging operation. -func (c *S3) PutBucketLoggingRequest(input *PutBucketLoggingInput) (req *service.Request, output *PutBucketLoggingOutput) { - op := &service.Operation{ +func (c *S3) PutBucketLoggingRequest(input *PutBucketLoggingInput) (req *request.Request, output *PutBucketLoggingOutput) { + op := &request.Operation{ Name: opPutBucketLogging, HTTPMethod: "PUT", HTTPPath: "/{Bucket}?logging", @@ -1194,8 +1248,8 @@ func (c *S3) PutBucketLogging(input *PutBucketLoggingInput) (*PutBucketLoggingOu const opPutBucketNotification = "PutBucketNotification" // PutBucketNotificationRequest generates a request for the PutBucketNotification operation. -func (c *S3) PutBucketNotificationRequest(input *PutBucketNotificationInput) (req *service.Request, output *PutBucketNotificationOutput) { - op := &service.Operation{ +func (c *S3) PutBucketNotificationRequest(input *PutBucketNotificationInput) (req *request.Request, output *PutBucketNotificationOutput) { + op := &request.Operation{ Name: opPutBucketNotification, HTTPMethod: "PUT", HTTPPath: "/{Bucket}?notification", @@ -1221,8 +1275,8 @@ func (c *S3) PutBucketNotification(input *PutBucketNotificationInput) (*PutBucke const opPutBucketNotificationConfiguration = "PutBucketNotificationConfiguration" // PutBucketNotificationConfigurationRequest generates a request for the PutBucketNotificationConfiguration operation. -func (c *S3) PutBucketNotificationConfigurationRequest(input *PutBucketNotificationConfigurationInput) (req *service.Request, output *PutBucketNotificationConfigurationOutput) { - op := &service.Operation{ +func (c *S3) PutBucketNotificationConfigurationRequest(input *PutBucketNotificationConfigurationInput) (req *request.Request, output *PutBucketNotificationConfigurationOutput) { + op := &request.Operation{ Name: opPutBucketNotificationConfiguration, HTTPMethod: "PUT", HTTPPath: "/{Bucket}?notification", @@ -1248,8 +1302,8 @@ func (c *S3) PutBucketNotificationConfiguration(input *PutBucketNotificationConf const opPutBucketPolicy = "PutBucketPolicy" // PutBucketPolicyRequest generates a request for the PutBucketPolicy operation. -func (c *S3) PutBucketPolicyRequest(input *PutBucketPolicyInput) (req *service.Request, output *PutBucketPolicyOutput) { - op := &service.Operation{ +func (c *S3) PutBucketPolicyRequest(input *PutBucketPolicyInput) (req *request.Request, output *PutBucketPolicyOutput) { + op := &request.Operation{ Name: opPutBucketPolicy, HTTPMethod: "PUT", HTTPPath: "/{Bucket}?policy", @@ -1276,8 +1330,8 @@ func (c *S3) PutBucketPolicy(input *PutBucketPolicyInput) (*PutBucketPolicyOutpu const opPutBucketReplication = "PutBucketReplication" // PutBucketReplicationRequest generates a request for the PutBucketReplication operation. -func (c *S3) PutBucketReplicationRequest(input *PutBucketReplicationInput) (req *service.Request, output *PutBucketReplicationOutput) { - op := &service.Operation{ +func (c *S3) PutBucketReplicationRequest(input *PutBucketReplicationInput) (req *request.Request, output *PutBucketReplicationOutput) { + op := &request.Operation{ Name: opPutBucketReplication, HTTPMethod: "PUT", HTTPPath: "/{Bucket}?replication", @@ -1304,8 +1358,8 @@ func (c *S3) PutBucketReplication(input *PutBucketReplicationInput) (*PutBucketR const opPutBucketRequestPayment = "PutBucketRequestPayment" // PutBucketRequestPaymentRequest generates a request for the PutBucketRequestPayment operation. -func (c *S3) PutBucketRequestPaymentRequest(input *PutBucketRequestPaymentInput) (req *service.Request, output *PutBucketRequestPaymentOutput) { - op := &service.Operation{ +func (c *S3) PutBucketRequestPaymentRequest(input *PutBucketRequestPaymentInput) (req *request.Request, output *PutBucketRequestPaymentOutput) { + op := &request.Operation{ Name: opPutBucketRequestPayment, HTTPMethod: "PUT", HTTPPath: "/{Bucket}?requestPayment", @@ -1335,8 +1389,8 @@ func (c *S3) PutBucketRequestPayment(input *PutBucketRequestPaymentInput) (*PutB const opPutBucketTagging = "PutBucketTagging" // PutBucketTaggingRequest generates a request for the PutBucketTagging operation. -func (c *S3) PutBucketTaggingRequest(input *PutBucketTaggingInput) (req *service.Request, output *PutBucketTaggingOutput) { - op := &service.Operation{ +func (c *S3) PutBucketTaggingRequest(input *PutBucketTaggingInput) (req *request.Request, output *PutBucketTaggingOutput) { + op := &request.Operation{ Name: opPutBucketTagging, HTTPMethod: "PUT", HTTPPath: "/{Bucket}?tagging", @@ -1362,8 +1416,8 @@ func (c *S3) PutBucketTagging(input *PutBucketTaggingInput) (*PutBucketTaggingOu const opPutBucketVersioning = "PutBucketVersioning" // PutBucketVersioningRequest generates a request for the PutBucketVersioning operation. -func (c *S3) PutBucketVersioningRequest(input *PutBucketVersioningInput) (req *service.Request, output *PutBucketVersioningOutput) { - op := &service.Operation{ +func (c *S3) PutBucketVersioningRequest(input *PutBucketVersioningInput) (req *request.Request, output *PutBucketVersioningOutput) { + op := &request.Operation{ Name: opPutBucketVersioning, HTTPMethod: "PUT", HTTPPath: "/{Bucket}?versioning", @@ -1390,8 +1444,8 @@ func (c *S3) PutBucketVersioning(input *PutBucketVersioningInput) (*PutBucketVer const opPutBucketWebsite = "PutBucketWebsite" // PutBucketWebsiteRequest generates a request for the PutBucketWebsite operation. -func (c *S3) PutBucketWebsiteRequest(input *PutBucketWebsiteInput) (req *service.Request, output *PutBucketWebsiteOutput) { - op := &service.Operation{ +func (c *S3) PutBucketWebsiteRequest(input *PutBucketWebsiteInput) (req *request.Request, output *PutBucketWebsiteOutput) { + op := &request.Operation{ Name: opPutBucketWebsite, HTTPMethod: "PUT", HTTPPath: "/{Bucket}?website", @@ -1417,8 +1471,8 @@ func (c *S3) PutBucketWebsite(input *PutBucketWebsiteInput) (*PutBucketWebsiteOu const opPutObject = "PutObject" // PutObjectRequest generates a request for the PutObject operation. -func (c *S3) PutObjectRequest(input *PutObjectInput) (req *service.Request, output *PutObjectOutput) { - op := &service.Operation{ +func (c *S3) PutObjectRequest(input *PutObjectInput) (req *request.Request, output *PutObjectOutput) { + op := &request.Operation{ Name: opPutObject, HTTPMethod: "PUT", HTTPPath: "/{Bucket}/{Key+}", @@ -1444,8 +1498,8 @@ func (c *S3) PutObject(input *PutObjectInput) (*PutObjectOutput, error) { const opPutObjectAcl = "PutObjectAcl" // PutObjectAclRequest generates a request for the PutObjectAcl operation. -func (c *S3) PutObjectAclRequest(input *PutObjectAclInput) (req *service.Request, output *PutObjectAclOutput) { - op := &service.Operation{ +func (c *S3) PutObjectAclRequest(input *PutObjectAclInput) (req *request.Request, output *PutObjectAclOutput) { + op := &request.Operation{ Name: opPutObjectAcl, HTTPMethod: "PUT", HTTPPath: "/{Bucket}/{Key+}?acl", @@ -1472,8 +1526,8 @@ func (c *S3) PutObjectAcl(input *PutObjectAclInput) (*PutObjectAclOutput, error) const opRestoreObject = "RestoreObject" // RestoreObjectRequest generates a request for the RestoreObject operation. -func (c *S3) RestoreObjectRequest(input *RestoreObjectInput) (req *service.Request, output *RestoreObjectOutput) { - op := &service.Operation{ +func (c *S3) RestoreObjectRequest(input *RestoreObjectInput) (req *request.Request, output *RestoreObjectOutput) { + op := &request.Operation{ Name: opRestoreObject, HTTPMethod: "POST", HTTPPath: "/{Bucket}/{Key+}?restore", @@ -1499,8 +1553,8 @@ func (c *S3) RestoreObject(input *RestoreObjectInput) (*RestoreObjectOutput, err const opUploadPart = "UploadPart" // UploadPartRequest generates a request for the UploadPart operation. -func (c *S3) UploadPartRequest(input *UploadPartInput) (req *service.Request, output *UploadPartOutput) { - op := &service.Operation{ +func (c *S3) UploadPartRequest(input *UploadPartInput) (req *request.Request, output *UploadPartOutput) { + op := &request.Operation{ Name: opUploadPart, HTTPMethod: "PUT", HTTPPath: "/{Bucket}/{Key+}", @@ -1532,8 +1586,8 @@ func (c *S3) UploadPart(input *UploadPartInput) (*UploadPartOutput, error) { const opUploadPartCopy = "UploadPartCopy" // UploadPartCopyRequest generates a request for the UploadPartCopy operation. -func (c *S3) UploadPartCopyRequest(input *UploadPartCopyInput) (req *service.Request, output *UploadPartCopyOutput) { - op := &service.Operation{ +func (c *S3) UploadPartCopyRequest(input *UploadPartCopyInput) (req *request.Request, output *UploadPartCopyOutput) { + op := &request.Operation{ Name: opUploadPartCopy, HTTPMethod: "PUT", HTTPPath: "/{Bucket}/{Key+}", @@ -1559,7 +1613,7 @@ func (c *S3) UploadPartCopy(input *UploadPartCopyInput) (*UploadPartCopyOutput, type AbortMultipartUploadInput struct { Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - Key *string `location:"uri" locationName:"Key" type:"string" required:"true"` + Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` // Confirms that the requester knows that she or he will be charged for the // request. Bucket owners need not specify this parameter in their requests. @@ -1655,6 +1709,26 @@ func (s Bucket) GoString() string { return s.String() } +type BucketLifecycleConfiguration struct { + Rules []*LifecycleRule `locationName:"Rule" type:"list" flattened:"true" required:"true"` + + metadataBucketLifecycleConfiguration `json:"-" xml:"-"` +} + +type metadataBucketLifecycleConfiguration struct { + SDKShapeTraits bool `type:"structure"` +} + +// String returns the string representation +func (s BucketLifecycleConfiguration) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s BucketLifecycleConfiguration) GoString() string { + return s.String() +} + type BucketLoggingStatus struct { LoggingEnabled *LoggingEnabled `type:"structure"` @@ -1676,7 +1750,7 @@ func (s BucketLoggingStatus) GoString() string { } type CORSConfiguration struct { - CORSRules []*CORSRule `locationName:"CORSRule" type:"list" flattened:"true"` + CORSRules []*CORSRule `locationName:"CORSRule" type:"list" flattened:"true" required:"true"` metadataCORSConfiguration `json:"-" xml:"-"` } @@ -1701,10 +1775,10 @@ type CORSRule struct { // Identifies HTTP methods that the domain/origin specified in the rule is allowed // to execute. - AllowedMethods []*string `locationName:"AllowedMethod" type:"list" flattened:"true"` + AllowedMethods []*string `locationName:"AllowedMethod" type:"list" flattened:"true" required:"true"` // One or more origins you want customers to be able to access the bucket from. - AllowedOrigins []*string `locationName:"AllowedOrigin" type:"list" flattened:"true"` + AllowedOrigins []*string `locationName:"AllowedOrigin" type:"list" flattened:"true" required:"true"` // One or more headers in the response that you want customers to be able to // access from their applications (for example, from a JavaScript XMLHttpRequest @@ -1786,7 +1860,7 @@ func (s CommonPrefix) GoString() string { type CompleteMultipartUploadInput struct { Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - Key *string `location:"uri" locationName:"Key" type:"string" required:"true"` + Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` MultipartUpload *CompletedMultipartUpload `locationName:"CompleteMultipartUpload" type:"structure"` @@ -1825,7 +1899,7 @@ type CompleteMultipartUploadOutput struct { // date (expiry-date) and rule ID (rule-id). The value of rule-id is URL encoded. Expiration *string `location:"header" locationName:"x-amz-expiration" type:"string"` - Key *string `type:"string"` + Key *string `min:"1" type:"string"` Location *string `type:"string"` @@ -2008,7 +2082,7 @@ type CopyObjectInput struct { // Allows grantee to write the ACL for the applicable object. GrantWriteACP *string `location:"header" locationName:"x-amz-grant-write-acp" type:"string"` - Key *string `location:"uri" locationName:"Key" type:"string" required:"true"` + Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` // A map of metadata to store with the object in S3. Metadata map[string]*string `location:"headers" locationName:"x-amz-meta-" type:"map"` @@ -2287,7 +2361,7 @@ type CreateMultipartUploadInput struct { // Allows grantee to write the ACL for the applicable object. GrantWriteACP *string `location:"header" locationName:"x-amz-grant-write-acp" type:"string"` - Key *string `location:"uri" locationName:"Key" type:"string" required:"true"` + Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` // A map of metadata to store with the object in S3. Metadata map[string]*string `location:"headers" locationName:"x-amz-meta-" type:"map"` @@ -2353,7 +2427,7 @@ type CreateMultipartUploadOutput struct { Bucket *string `locationName:"Bucket" type:"string"` // Object key for which the multipart upload was initiated. - Key *string `type:"string"` + Key *string `min:"1" type:"string"` // If present, indicates that the requester was successfully charged for the // request. @@ -2693,7 +2767,7 @@ type DeleteMarkerEntry struct { IsLatest *bool `type:"boolean"` // The object key. - Key *string `type:"string"` + Key *string `min:"1" type:"string"` // Date and time the object was last modified. LastModified *time.Time `type:"timestamp" timestampFormat:"iso8601"` @@ -2723,7 +2797,7 @@ func (s DeleteMarkerEntry) GoString() string { type DeleteObjectInput struct { Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - Key *string `location:"uri" locationName:"Key" type:"string" required:"true"` + Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` // The concatenation of the authentication device's serial number, a space, // and the value that is displayed on your authentication device. @@ -2848,7 +2922,7 @@ type DeletedObject struct { DeleteMarkerVersionId *string `type:"string"` - Key *string `type:"string"` + Key *string `min:"1" type:"string"` VersionId *string `type:"string"` @@ -2874,6 +2948,9 @@ type Destination struct { // replicas of the object identified by the rule. Bucket *string `type:"string" required:"true"` + // The class of storage used to store the object. + StorageClass *string `type:"string" enum:"StorageClass"` + metadataDestination `json:"-" xml:"-"` } @@ -2894,7 +2971,7 @@ func (s Destination) GoString() string { type Error struct { Code *string `type:"string"` - Key *string `type:"string"` + Key *string `min:"1" type:"string"` Message *string `type:"string"` @@ -2919,7 +2996,7 @@ func (s Error) GoString() string { type ErrorDocument struct { // The object key name to use when a 4XX class error occurs. - Key *string `type:"string" required:"true"` + Key *string `min:"1" type:"string" required:"true"` metadataErrorDocument `json:"-" xml:"-"` } @@ -2938,6 +3015,34 @@ func (s ErrorDocument) GoString() string { return s.String() } +// Container for key value pair that defines the criteria for the filter rule. +type FilterRule struct { + // Object key name prefix or suffix identifying one or more objects to which + // the filtering rule applies. Maximum prefix length can be up to 1,024 characters. + // Overlapping prefixes and suffixes are not supported. For more information, + // go to Configuring Event Notifications (http://docs.aws.amazon.com/AmazonS3/latest/dev/NotificationHowTo.html) + // in the Amazon Simple Storage Service Developer Guide. + Name *string `type:"string" enum:"FilterRuleName"` + + Value *string `type:"string"` + + metadataFilterRule `json:"-" xml:"-"` +} + +type metadataFilterRule struct { + SDKShapeTraits bool `type:"structure"` +} + +// String returns the string representation +func (s FilterRule) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s FilterRule) GoString() string { + return s.String() +} + type GetBucketAclInput struct { Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` @@ -3021,6 +3126,46 @@ func (s GetBucketCorsOutput) GoString() string { return s.String() } +type GetBucketLifecycleConfigurationInput struct { + Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + + metadataGetBucketLifecycleConfigurationInput `json:"-" xml:"-"` +} + +type metadataGetBucketLifecycleConfigurationInput struct { + SDKShapeTraits bool `type:"structure"` +} + +// String returns the string representation +func (s GetBucketLifecycleConfigurationInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetBucketLifecycleConfigurationInput) GoString() string { + return s.String() +} + +type GetBucketLifecycleConfigurationOutput struct { + Rules []*LifecycleRule `locationName:"Rule" type:"list" flattened:"true"` + + metadataGetBucketLifecycleConfigurationOutput `json:"-" xml:"-"` +} + +type metadataGetBucketLifecycleConfigurationOutput struct { + SDKShapeTraits bool `type:"structure"` +} + +// String returns the string representation +func (s GetBucketLifecycleConfigurationOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetBucketLifecycleConfigurationOutput) GoString() string { + return s.String() +} + type GetBucketLifecycleInput struct { Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` @@ -3042,7 +3187,7 @@ func (s GetBucketLifecycleInput) GoString() string { } type GetBucketLifecycleOutput struct { - Rules []*LifecycleRule `locationName:"Rule" type:"list" flattened:"true"` + Rules []*Rule `locationName:"Rule" type:"list" flattened:"true"` metadataGetBucketLifecycleOutput `json:"-" xml:"-"` } @@ -3421,7 +3566,7 @@ func (s GetBucketWebsiteOutput) GoString() string { type GetObjectAclInput struct { Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - Key *string `location:"uri" locationName:"Key" type:"string" required:"true"` + Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` // Confirms that the requester knows that she or he will be charged for the // request. Bucket owners need not specify this parameter in their requests. @@ -3495,7 +3640,7 @@ type GetObjectInput struct { // otherwise return a 412 (precondition failed). IfUnmodifiedSince *time.Time `location:"header" locationName:"If-Unmodified-Since" type:"timestamp" timestampFormat:"rfc822"` - Key *string `location:"uri" locationName:"Key" type:"string" required:"true"` + Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` // Downloads the specified range bytes of an object. For more information about // the HTTP Range header, go to http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35. @@ -3676,7 +3821,7 @@ func (s GetObjectOutput) GoString() string { type GetObjectTorrentInput struct { Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - Key *string `location:"uri" locationName:"Key" type:"string" required:"true"` + Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` // Confirms that the requester knows that she or he will be charged for the // request. Bucket owners need not specify this parameter in their requests. @@ -3838,7 +3983,7 @@ type HeadObjectInput struct { // otherwise return a 412 (precondition failed). IfUnmodifiedSince *time.Time `location:"header" locationName:"If-Unmodified-Since" type:"timestamp" timestampFormat:"rfc822"` - Key *string `location:"uri" locationName:"Key" type:"string" required:"true"` + Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` // Downloads the specified range bytes of an object. For more information about // the HTTP Range header, go to http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35. @@ -4041,10 +4186,38 @@ func (s Initiator) GoString() string { return s.String() } +// Container for object key name prefix and suffix filtering rules. +type KeyFilter struct { + // A list of containers for key value pair that defines the criteria for the + // filter rule. + FilterRules []*FilterRule `locationName:"FilterRule" type:"list" flattened:"true"` + + metadataKeyFilter `json:"-" xml:"-"` +} + +type metadataKeyFilter struct { + SDKShapeTraits bool `type:"structure"` +} + +// String returns the string representation +func (s KeyFilter) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s KeyFilter) GoString() string { + return s.String() +} + // Container for specifying the AWS Lambda notification configuration. type LambdaFunctionConfiguration struct { Events []*string `locationName:"Event" type:"list" flattened:"true" required:"true"` + // Container for object key name filtering rules. For information about key + // name filtering, go to Configuring Event Notifications (http://docs.aws.amazon.com/AmazonS3/latest/dev/NotificationHowTo.html) + // in the Amazon Simple Storage Service Developer Guide. + Filter *NotificationConfigurationFilter `type:"structure"` + // Optional unique identifier for configurations in a notification configuration. // If you don't provide one, Amazon S3 will assign an ID. Id *string `type:"string"` @@ -4071,7 +4244,7 @@ func (s LambdaFunctionConfiguration) GoString() string { } type LifecycleConfiguration struct { - Rules []*LifecycleRule `locationName:"Rule" type:"list" flattened:"true" required:"true"` + Rules []*Rule `locationName:"Rule" type:"list" flattened:"true" required:"true"` metadataLifecycleConfiguration `json:"-" xml:"-"` } @@ -4129,12 +4302,7 @@ type LifecycleRule struct { // period in the object's lifetime. NoncurrentVersionExpiration *NoncurrentVersionExpiration `type:"structure"` - // Container for the transition rule that describes when noncurrent objects - // transition to the GLACIER storage class. If your bucket is versioning-enabled - // (or versioning is suspended), you can set this action to request that Amazon - // S3 transition noncurrent object versions to the GLACIER storage class at - // a specific period in the object's lifetime. - NoncurrentVersionTransition *NoncurrentVersionTransition `type:"structure"` + NoncurrentVersionTransitions []*NoncurrentVersionTransition `locationName:"NoncurrentVersionTransition" type:"list" flattened:"true"` // Prefix identifying one or more objects to which the rule applies. Prefix *string `type:"string" required:"true"` @@ -4143,7 +4311,7 @@ type LifecycleRule struct { // is not currently being applied. Status *string `type:"string" required:"true" enum:"ExpirationStatus"` - Transition *Transition `type:"structure"` + Transitions []*Transition `locationName:"Transition" type:"list" flattened:"true"` metadataLifecycleRule `json:"-" xml:"-"` } @@ -4498,7 +4666,7 @@ func (s ListObjectsOutput) GoString() string { type ListPartsInput struct { Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - Key *string `location:"uri" locationName:"Key" type:"string" required:"true"` + Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` // Sets the maximum number of parts to return. MaxParts *int64 `location:"querystring" locationName:"max-parts" type:"integer"` @@ -4544,7 +4712,7 @@ type ListPartsOutput struct { IsTruncated *bool `type:"boolean"` // Object key for which the multipart upload was initiated. - Key *string `type:"string"` + Key *string `min:"1" type:"string"` // Maximum number of parts that were allowed in the response. MaxParts *int64 `type:"integer"` @@ -4628,7 +4796,7 @@ type MultipartUpload struct { Initiator *Initiator `type:"structure"` // Key of the object for which the multipart upload was initiated. - Key *string `type:"string"` + Key *string `min:"1" type:"string"` Owner *Owner `type:"structure"` @@ -4686,10 +4854,10 @@ func (s NoncurrentVersionExpiration) GoString() string { } // Container for the transition rule that describes when noncurrent objects -// transition to the GLACIER storage class. If your bucket is versioning-enabled -// (or versioning is suspended), you can set this action to request that Amazon -// S3 transition noncurrent object versions to the GLACIER storage class at -// a specific period in the object's lifetime. +// transition to the STANDARD_IA or GLACIER storage class. If your bucket is +// versioning-enabled (or versioning is suspended), you can set this action +// to request that Amazon S3 transition noncurrent object versions to the STANDARD_IA +// or GLACIER storage class at a specific period in the object's lifetime. type NoncurrentVersionTransition struct { // Specifies the number of days an object is noncurrent before Amazon S3 can // perform the associated action. For information about the noncurrent days @@ -4768,10 +4936,34 @@ func (s NotificationConfigurationDeprecated) GoString() string { return s.String() } +// Container for object key name filtering rules. For information about key +// name filtering, go to Configuring Event Notifications (http://docs.aws.amazon.com/AmazonS3/latest/dev/NotificationHowTo.html) +// in the Amazon Simple Storage Service Developer Guide. +type NotificationConfigurationFilter struct { + // Container for object key name prefix and suffix filtering rules. + Key *KeyFilter `locationName:"S3Key" type:"structure"` + + metadataNotificationConfigurationFilter `json:"-" xml:"-"` +} + +type metadataNotificationConfigurationFilter struct { + SDKShapeTraits bool `type:"structure"` +} + +// String returns the string representation +func (s NotificationConfigurationFilter) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s NotificationConfigurationFilter) GoString() string { + return s.String() +} + type Object struct { ETag *string `type:"string"` - Key *string `type:"string"` + Key *string `min:"1" type:"string"` LastModified *time.Time `type:"timestamp" timestampFormat:"iso8601"` @@ -4801,7 +4993,7 @@ func (s Object) GoString() string { type ObjectIdentifier struct { // Key name of the object to delete. - Key *string `type:"string" required:"true"` + Key *string `min:"1" type:"string" required:"true"` // VersionId for the specific version of the object to delete. VersionId *string `type:"string"` @@ -4831,7 +5023,7 @@ type ObjectVersion struct { IsLatest *bool `type:"boolean"` // The object key. - Key *string `type:"string"` + Key *string `min:"1" type:"string"` // Date and time the object was last modified. LastModified *time.Time `type:"timestamp" timestampFormat:"iso8601"` @@ -4979,7 +5171,7 @@ func (s PutBucketAclOutput) GoString() string { type PutBucketCorsInput struct { Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - CORSConfiguration *CORSConfiguration `locationName:"CORSConfiguration" type:"structure"` + CORSConfiguration *CORSConfiguration `locationName:"CORSConfiguration" type:"structure" required:"true"` metadataPutBucketCorsInput `json:"-" xml:"-"` } @@ -5016,6 +5208,46 @@ func (s PutBucketCorsOutput) GoString() string { return s.String() } +type PutBucketLifecycleConfigurationInput struct { + Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + + LifecycleConfiguration *BucketLifecycleConfiguration `locationName:"LifecycleConfiguration" type:"structure"` + + metadataPutBucketLifecycleConfigurationInput `json:"-" xml:"-"` +} + +type metadataPutBucketLifecycleConfigurationInput struct { + SDKShapeTraits bool `type:"structure" payload:"LifecycleConfiguration"` +} + +// String returns the string representation +func (s PutBucketLifecycleConfigurationInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s PutBucketLifecycleConfigurationInput) GoString() string { + return s.String() +} + +type PutBucketLifecycleConfigurationOutput struct { + metadataPutBucketLifecycleConfigurationOutput `json:"-" xml:"-"` +} + +type metadataPutBucketLifecycleConfigurationOutput struct { + SDKShapeTraits bool `type:"structure"` +} + +// String returns the string representation +func (s PutBucketLifecycleConfigurationOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s PutBucketLifecycleConfigurationOutput) GoString() string { + return s.String() +} + type PutBucketLifecycleInput struct { Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` @@ -5449,7 +5681,7 @@ type PutObjectAclInput struct { // Allows grantee to write the ACL for the applicable bucket. GrantWriteACP *string `location:"header" locationName:"x-amz-grant-write-acp" type:"string"` - Key *string `location:"uri" locationName:"Key" type:"string" required:"true"` + Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` // Confirms that the requester knows that she or he will be charged for the // request. Bucket owners need not specify this parameter in their requests. @@ -5541,7 +5773,7 @@ type PutObjectInput struct { // Allows grantee to write the ACL for the applicable object. GrantWriteACP *string `location:"header" locationName:"x-amz-grant-write-acp" type:"string"` - Key *string `location:"uri" locationName:"Key" type:"string" required:"true"` + Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` // A map of metadata to store with the object in S3. Metadata map[string]*string `location:"headers" locationName:"x-amz-meta-" type:"map"` @@ -5657,6 +5889,11 @@ func (s PutObjectOutput) GoString() string { type QueueConfiguration struct { Events []*string `locationName:"Event" type:"list" flattened:"true" required:"true"` + // Container for object key name filtering rules. For information about key + // name filtering, go to Configuring Event Notifications (http://docs.aws.amazon.com/AmazonS3/latest/dev/NotificationHowTo.html) + // in the Amazon Simple Storage Service Developer Guide. + Filter *NotificationConfigurationFilter `type:"structure"` + // Optional unique identifier for configurations in a notification configuration. // If you don't provide one, Amazon S3 will assign an ID. Id *string `type:"string"` @@ -5861,7 +6098,7 @@ func (s RequestPaymentConfiguration) GoString() string { type RestoreObjectInput struct { Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - Key *string `location:"uri" locationName:"Key" type:"string" required:"true"` + Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` // Confirms that the requester knows that she or he will be charged for the // request. Bucket owners need not specify this parameter in their requests. @@ -5962,9 +6199,55 @@ func (s RoutingRule) GoString() string { return s.String() } +type Rule struct { + Expiration *LifecycleExpiration `type:"structure"` + + // Unique identifier for the rule. The value cannot be longer than 255 characters. + ID *string `type:"string"` + + // Specifies when noncurrent object versions expire. Upon expiration, Amazon + // S3 permanently deletes the noncurrent object versions. You set this lifecycle + // configuration action on a bucket that has versioning enabled (or suspended) + // to request that Amazon S3 delete noncurrent object versions at a specific + // period in the object's lifetime. + NoncurrentVersionExpiration *NoncurrentVersionExpiration `type:"structure"` + + // Container for the transition rule that describes when noncurrent objects + // transition to the STANDARD_IA or GLACIER storage class. If your bucket is + // versioning-enabled (or versioning is suspended), you can set this action + // to request that Amazon S3 transition noncurrent object versions to the STANDARD_IA + // or GLACIER storage class at a specific period in the object's lifetime. + NoncurrentVersionTransition *NoncurrentVersionTransition `type:"structure"` + + // Prefix identifying one or more objects to which the rule applies. + Prefix *string `type:"string" required:"true"` + + // If 'Enabled', the rule is currently being applied. If 'Disabled', the rule + // is not currently being applied. + Status *string `type:"string" required:"true" enum:"ExpirationStatus"` + + Transition *Transition `type:"structure"` + + metadataRule `json:"-" xml:"-"` +} + +type metadataRule struct { + SDKShapeTraits bool `type:"structure"` +} + +// String returns the string representation +func (s Rule) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s Rule) GoString() string { + return s.String() +} + type Tag struct { // Name of the tag. - Key *string `type:"string" required:"true"` + Key *string `min:"1" type:"string" required:"true"` // Value of the tag. Value *string `type:"string" required:"true"` @@ -6034,6 +6317,11 @@ func (s TargetGrant) GoString() string { type TopicConfiguration struct { Events []*string `locationName:"Event" type:"list" flattened:"true" required:"true"` + // Container for object key name filtering rules. For information about key + // name filtering, go to Configuring Event Notifications (http://docs.aws.amazon.com/AmazonS3/latest/dev/NotificationHowTo.html) + // in the Amazon Simple Storage Service Developer Guide. + Filter *NotificationConfigurationFilter `type:"structure"` + // Optional unique identifier for configurations in a notification configuration. // If you don't provide one, Amazon S3 will assign an ID. Id *string `type:"string"` @@ -6159,7 +6447,7 @@ type UploadPartCopyInput struct { // key was transmitted without error. CopySourceSSECustomerKeyMD5 *string `location:"header" locationName:"x-amz-copy-source-server-side-encryption-customer-key-MD5" type:"string"` - Key *string `location:"uri" locationName:"Key" type:"string" required:"true"` + Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` // Part number of part being copied. This is a positive integer between 1 and // 10,000. @@ -6262,7 +6550,7 @@ type UploadPartInput struct { // body cannot be determined automatically. ContentLength *int64 `location:"header" locationName:"Content-Length" type:"integer"` - Key *string `location:"uri" locationName:"Key" type:"string" required:"true"` + Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` // Part number of part being uploaded. This is a positive integer between 1 // and 10,000. @@ -6495,6 +6783,13 @@ const ( ExpirationStatusDisabled = "Disabled" ) +const ( + // @enum FilterRuleName + FilterRuleNamePrefix = "prefix" + // @enum FilterRuleName + FilterRuleNameSuffix = "suffix" +) + const ( // @enum MFADelete MFADeleteEnabled = "Enabled" @@ -6619,12 +6914,14 @@ const ( // @enum StorageClass StorageClassReducedRedundancy = "REDUCED_REDUNDANCY" // @enum StorageClass - StorageClassLt = "LT" + StorageClassStandardIa = "STANDARD_IA" ) const ( // @enum TransitionStorageClass TransitionStorageClassGlacier = "GLACIER" + // @enum TransitionStorageClass + TransitionStorageClassStandardIa = "STANDARD_IA" ) const ( diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/bucket_location.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/bucket_location.go index 7e7cb6373..0feec1ce7 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/bucket_location.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/bucket_location.go @@ -7,12 +7,12 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/aws/awsutil" - "github.com/aws/aws-sdk-go/aws/service" + "github.com/aws/aws-sdk-go/aws/request" ) var reBucketLocation = regexp.MustCompile(`>([^<>]+)<\/Location`) -func buildGetBucketLocation(r *service.Request) { +func buildGetBucketLocation(r *request.Request) { if r.DataFilled() { out := r.Data.(*GetBucketLocationOutput) b, err := ioutil.ReadAll(r.HTTPResponse.Body) @@ -29,14 +29,14 @@ func buildGetBucketLocation(r *service.Request) { } } -func populateLocationConstraint(r *service.Request) { - if r.ParamsFilled() && aws.StringValue(r.Config.Region) != "us-east-1" { +func populateLocationConstraint(r *request.Request) { + if r.ParamsFilled() && aws.StringValue(r.Service.Config.Region) != "us-east-1" { in := r.Params.(*CreateBucketInput) if in.CreateBucketConfiguration == nil { r.Params = awsutil.CopyOf(r.Params) in = r.Params.(*CreateBucketInput) in.CreateBucketConfiguration = &CreateBucketConfiguration{ - LocationConstraint: r.Config.Region, + LocationConstraint: r.Service.Config.Region, } } } diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/bucket_location_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/bucket_location_test.go deleted file mode 100644 index 020b3ac22..000000000 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/bucket_location_test.go +++ /dev/null @@ -1,76 +0,0 @@ -package s3_test - -import ( - "bytes" - "io/ioutil" - "net/http" - "testing" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awsutil" - "github.com/aws/aws-sdk-go/aws/service" - "github.com/aws/aws-sdk-go/internal/test/unit" - "github.com/aws/aws-sdk-go/service/s3" - "github.com/stretchr/testify/assert" -) - -var _ = unit.Imported -var s3LocationTests = []struct { - body string - loc string -}{ - {``, ``}, - {`EU`, `EU`}, -} - -func TestGetBucketLocation(t *testing.T) { - for _, test := range s3LocationTests { - s := s3.New(nil) - s.Handlers.Send.Clear() - s.Handlers.Send.PushBack(func(r *service.Request) { - reader := ioutil.NopCloser(bytes.NewReader([]byte(test.body))) - r.HTTPResponse = &http.Response{StatusCode: 200, Body: reader} - }) - - resp, err := s.GetBucketLocation(&s3.GetBucketLocationInput{Bucket: aws.String("bucket")}) - assert.NoError(t, err) - if test.loc == "" { - assert.Nil(t, resp.LocationConstraint) - } else { - assert.Equal(t, test.loc, *resp.LocationConstraint) - } - } -} - -func TestPopulateLocationConstraint(t *testing.T) { - s := s3.New(nil) - in := &s3.CreateBucketInput{ - Bucket: aws.String("bucket"), - } - req, _ := s.CreateBucketRequest(in) - err := req.Build() - assert.NoError(t, err) - assert.Equal(t, "mock-region", awsutil.ValuesAtPath(req.Params, "CreateBucketConfiguration.LocationConstraint")[0]) - assert.Nil(t, in.CreateBucketConfiguration) // don't modify original params -} - -func TestNoPopulateLocationConstraintIfProvided(t *testing.T) { - s := s3.New(nil) - req, _ := s.CreateBucketRequest(&s3.CreateBucketInput{ - Bucket: aws.String("bucket"), - CreateBucketConfiguration: &s3.CreateBucketConfiguration{}, - }) - err := req.Build() - assert.NoError(t, err) - assert.Equal(t, 0, len(awsutil.ValuesAtPath(req.Params, "CreateBucketConfiguration.LocationConstraint"))) -} - -func TestNoPopulateLocationConstraintIfClassic(t *testing.T) { - s := s3.New(&aws.Config{Region: aws.String("us-east-1")}) - req, _ := s.CreateBucketRequest(&s3.CreateBucketInput{ - Bucket: aws.String("bucket"), - }) - err := req.Build() - assert.NoError(t, err) - assert.Equal(t, 0, len(awsutil.ValuesAtPath(req.Params, "CreateBucketConfiguration.LocationConstraint"))) -} diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/content_md5.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/content_md5.go index eab6b0b1a..9fc5df94d 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/content_md5.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/content_md5.go @@ -6,12 +6,12 @@ import ( "io" "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/service" + "github.com/aws/aws-sdk-go/aws/request" ) // contentMD5 computes and sets the HTTP Content-MD5 header for requests that // require it. -func contentMD5(r *service.Request) { +func contentMD5(r *request.Request) { h := md5.New() // hash the body. seek back to the first position after reading to reset diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/customizations.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/customizations.go index 0c2494220..db3005e1a 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/customizations.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/customizations.go @@ -1,6 +1,9 @@ package s3 -import "github.com/aws/aws-sdk-go/aws/service" +import ( + "github.com/aws/aws-sdk-go/aws/request" + "github.com/aws/aws-sdk-go/aws/service" +) func init() { initService = func(s *service.Service) { @@ -16,7 +19,7 @@ func init() { s.Handlers.UnmarshalError.PushBack(unmarshalError) } - initRequest = func(r *service.Request) { + initRequest = func(r *request.Request) { switch r.Operation.Name { case opPutBucketCors, opPutBucketLifecycle, opPutBucketPolicy, opPutBucketTagging, opDeleteObjects: // These S3 operations require Content-MD5 to be set @@ -27,6 +30,8 @@ func init() { case opCreateBucket: // Auto-populate LocationConstraint with current region r.Handlers.Validate.PushFront(populateLocationConstraint) + case opCopyObject, opUploadPartCopy, opCompleteMultipartUpload: + r.Handlers.Unmarshal.PushFront(copyMultipartStatusOKUnmarhsalError) } } } diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/customizations_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/customizations_test.go deleted file mode 100644 index d95551ee2..000000000 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/customizations_test.go +++ /dev/null @@ -1,91 +0,0 @@ -package s3_test - -import ( - "crypto/md5" - "encoding/base64" - "io/ioutil" - "testing" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/service" - "github.com/aws/aws-sdk-go/internal/test/unit" - "github.com/aws/aws-sdk-go/service/s3" - "github.com/stretchr/testify/assert" -) - -var _ = unit.Imported - -func assertMD5(t *testing.T, req *service.Request) { - err := req.Build() - assert.NoError(t, err) - - b, _ := ioutil.ReadAll(req.HTTPRequest.Body) - out := md5.Sum(b) - assert.NotEmpty(t, b) - assert.Equal(t, base64.StdEncoding.EncodeToString(out[:]), req.HTTPRequest.Header.Get("Content-MD5")) -} - -func TestMD5InPutBucketCors(t *testing.T) { - svc := s3.New(nil) - req, _ := svc.PutBucketCorsRequest(&s3.PutBucketCorsInput{ - Bucket: aws.String("bucketname"), - CORSConfiguration: &s3.CORSConfiguration{ - CORSRules: []*s3.CORSRule{ - {AllowedMethods: []*string{aws.String("GET")}}, - }, - }, - }) - assertMD5(t, req) -} - -func TestMD5InPutBucketLifecycle(t *testing.T) { - svc := s3.New(nil) - req, _ := svc.PutBucketLifecycleRequest(&s3.PutBucketLifecycleInput{ - Bucket: aws.String("bucketname"), - LifecycleConfiguration: &s3.LifecycleConfiguration{ - Rules: []*s3.LifecycleRule{ - { - ID: aws.String("ID"), - Prefix: aws.String("Prefix"), - Status: aws.String("Enabled"), - }, - }, - }, - }) - assertMD5(t, req) -} - -func TestMD5InPutBucketPolicy(t *testing.T) { - svc := s3.New(nil) - req, _ := svc.PutBucketPolicyRequest(&s3.PutBucketPolicyInput{ - Bucket: aws.String("bucketname"), - Policy: aws.String("{}"), - }) - assertMD5(t, req) -} - -func TestMD5InPutBucketTagging(t *testing.T) { - svc := s3.New(nil) - req, _ := svc.PutBucketTaggingRequest(&s3.PutBucketTaggingInput{ - Bucket: aws.String("bucketname"), - Tagging: &s3.Tagging{ - TagSet: []*s3.Tag{ - {Key: aws.String("KEY"), Value: aws.String("VALUE")}, - }, - }, - }) - assertMD5(t, req) -} - -func TestMD5InDeleteObjects(t *testing.T) { - svc := s3.New(nil) - req, _ := svc.DeleteObjectsRequest(&s3.DeleteObjectsInput{ - Bucket: aws.String("bucketname"), - Delete: &s3.Delete{ - Objects: []*s3.ObjectIdentifier{ - {Key: aws.String("key")}, - }, - }, - }) - assertMD5(t, req) -} diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/examples_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/examples_test.go deleted file mode 100644 index f97fd2d96..000000000 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/examples_test.go +++ /dev/null @@ -1,1928 +0,0 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. - -package s3_test - -import ( - "bytes" - "fmt" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/awsutil" - "github.com/aws/aws-sdk-go/service/s3" -) - -var _ time.Duration -var _ bytes.Buffer - -func ExampleS3_AbortMultipartUpload() { - svc := s3.New(nil) - - params := &s3.AbortMultipartUploadInput{ - Bucket: aws.String("BucketName"), // Required - Key: aws.String("ObjectKey"), // Required - UploadId: aws.String("MultipartUploadId"), // Required - RequestPayer: aws.String("RequestPayer"), - } - resp, err := svc.AbortMultipartUpload(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleS3_CompleteMultipartUpload() { - svc := s3.New(nil) - - params := &s3.CompleteMultipartUploadInput{ - Bucket: aws.String("BucketName"), // Required - Key: aws.String("ObjectKey"), // Required - UploadId: aws.String("MultipartUploadId"), // Required - MultipartUpload: &s3.CompletedMultipartUpload{ - Parts: []*s3.CompletedPart{ - { // Required - ETag: aws.String("ETag"), - PartNumber: aws.Int64(1), - }, - // More values... - }, - }, - RequestPayer: aws.String("RequestPayer"), - } - resp, err := svc.CompleteMultipartUpload(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleS3_CopyObject() { - svc := s3.New(nil) - - params := &s3.CopyObjectInput{ - Bucket: aws.String("BucketName"), // Required - CopySource: aws.String("CopySource"), // Required - Key: aws.String("ObjectKey"), // Required - ACL: aws.String("ObjectCannedACL"), - CacheControl: aws.String("CacheControl"), - ContentDisposition: aws.String("ContentDisposition"), - ContentEncoding: aws.String("ContentEncoding"), - ContentLanguage: aws.String("ContentLanguage"), - ContentType: aws.String("ContentType"), - CopySourceIfMatch: aws.String("CopySourceIfMatch"), - CopySourceIfModifiedSince: aws.Time(time.Now()), - CopySourceIfNoneMatch: aws.String("CopySourceIfNoneMatch"), - CopySourceIfUnmodifiedSince: aws.Time(time.Now()), - CopySourceSSECustomerAlgorithm: aws.String("CopySourceSSECustomerAlgorithm"), - CopySourceSSECustomerKey: aws.String("CopySourceSSECustomerKey"), - CopySourceSSECustomerKeyMD5: aws.String("CopySourceSSECustomerKeyMD5"), - Expires: aws.Time(time.Now()), - GrantFullControl: aws.String("GrantFullControl"), - GrantRead: aws.String("GrantRead"), - GrantReadACP: aws.String("GrantReadACP"), - GrantWriteACP: aws.String("GrantWriteACP"), - Metadata: map[string]*string{ - "Key": aws.String("MetadataValue"), // Required - // More values... - }, - MetadataDirective: aws.String("MetadataDirective"), - RequestPayer: aws.String("RequestPayer"), - SSECustomerAlgorithm: aws.String("SSECustomerAlgorithm"), - SSECustomerKey: aws.String("SSECustomerKey"), - SSECustomerKeyMD5: aws.String("SSECustomerKeyMD5"), - SSEKMSKeyId: aws.String("SSEKMSKeyId"), - ServerSideEncryption: aws.String("ServerSideEncryption"), - StorageClass: aws.String("StorageClass"), - WebsiteRedirectLocation: aws.String("WebsiteRedirectLocation"), - } - resp, err := svc.CopyObject(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleS3_CreateBucket() { - svc := s3.New(nil) - - params := &s3.CreateBucketInput{ - Bucket: aws.String("BucketName"), // Required - ACL: aws.String("BucketCannedACL"), - CreateBucketConfiguration: &s3.CreateBucketConfiguration{ - LocationConstraint: aws.String("BucketLocationConstraint"), - }, - GrantFullControl: aws.String("GrantFullControl"), - GrantRead: aws.String("GrantRead"), - GrantReadACP: aws.String("GrantReadACP"), - GrantWrite: aws.String("GrantWrite"), - GrantWriteACP: aws.String("GrantWriteACP"), - } - resp, err := svc.CreateBucket(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleS3_CreateMultipartUpload() { - svc := s3.New(nil) - - params := &s3.CreateMultipartUploadInput{ - Bucket: aws.String("BucketName"), // Required - Key: aws.String("ObjectKey"), // Required - ACL: aws.String("ObjectCannedACL"), - CacheControl: aws.String("CacheControl"), - ContentDisposition: aws.String("ContentDisposition"), - ContentEncoding: aws.String("ContentEncoding"), - ContentLanguage: aws.String("ContentLanguage"), - ContentType: aws.String("ContentType"), - Expires: aws.Time(time.Now()), - GrantFullControl: aws.String("GrantFullControl"), - GrantRead: aws.String("GrantRead"), - GrantReadACP: aws.String("GrantReadACP"), - GrantWriteACP: aws.String("GrantWriteACP"), - Metadata: map[string]*string{ - "Key": aws.String("MetadataValue"), // Required - // More values... - }, - RequestPayer: aws.String("RequestPayer"), - SSECustomerAlgorithm: aws.String("SSECustomerAlgorithm"), - SSECustomerKey: aws.String("SSECustomerKey"), - SSECustomerKeyMD5: aws.String("SSECustomerKeyMD5"), - SSEKMSKeyId: aws.String("SSEKMSKeyId"), - ServerSideEncryption: aws.String("ServerSideEncryption"), - StorageClass: aws.String("StorageClass"), - WebsiteRedirectLocation: aws.String("WebsiteRedirectLocation"), - } - resp, err := svc.CreateMultipartUpload(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleS3_DeleteBucket() { - svc := s3.New(nil) - - params := &s3.DeleteBucketInput{ - Bucket: aws.String("BucketName"), // Required - } - resp, err := svc.DeleteBucket(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleS3_DeleteBucketCors() { - svc := s3.New(nil) - - params := &s3.DeleteBucketCorsInput{ - Bucket: aws.String("BucketName"), // Required - } - resp, err := svc.DeleteBucketCors(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleS3_DeleteBucketLifecycle() { - svc := s3.New(nil) - - params := &s3.DeleteBucketLifecycleInput{ - Bucket: aws.String("BucketName"), // Required - } - resp, err := svc.DeleteBucketLifecycle(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleS3_DeleteBucketPolicy() { - svc := s3.New(nil) - - params := &s3.DeleteBucketPolicyInput{ - Bucket: aws.String("BucketName"), // Required - } - resp, err := svc.DeleteBucketPolicy(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleS3_DeleteBucketReplication() { - svc := s3.New(nil) - - params := &s3.DeleteBucketReplicationInput{ - Bucket: aws.String("BucketName"), // Required - } - resp, err := svc.DeleteBucketReplication(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleS3_DeleteBucketTagging() { - svc := s3.New(nil) - - params := &s3.DeleteBucketTaggingInput{ - Bucket: aws.String("BucketName"), // Required - } - resp, err := svc.DeleteBucketTagging(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleS3_DeleteBucketWebsite() { - svc := s3.New(nil) - - params := &s3.DeleteBucketWebsiteInput{ - Bucket: aws.String("BucketName"), // Required - } - resp, err := svc.DeleteBucketWebsite(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleS3_DeleteObject() { - svc := s3.New(nil) - - params := &s3.DeleteObjectInput{ - Bucket: aws.String("BucketName"), // Required - Key: aws.String("ObjectKey"), // Required - MFA: aws.String("MFA"), - RequestPayer: aws.String("RequestPayer"), - VersionId: aws.String("ObjectVersionId"), - } - resp, err := svc.DeleteObject(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleS3_DeleteObjects() { - svc := s3.New(nil) - - params := &s3.DeleteObjectsInput{ - Bucket: aws.String("BucketName"), // Required - Delete: &s3.Delete{ // Required - Objects: []*s3.ObjectIdentifier{ // Required - { // Required - Key: aws.String("ObjectKey"), // Required - VersionId: aws.String("ObjectVersionId"), - }, - // More values... - }, - Quiet: aws.Bool(true), - }, - MFA: aws.String("MFA"), - RequestPayer: aws.String("RequestPayer"), - } - resp, err := svc.DeleteObjects(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleS3_GetBucketAcl() { - svc := s3.New(nil) - - params := &s3.GetBucketAclInput{ - Bucket: aws.String("BucketName"), // Required - } - resp, err := svc.GetBucketAcl(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleS3_GetBucketCors() { - svc := s3.New(nil) - - params := &s3.GetBucketCorsInput{ - Bucket: aws.String("BucketName"), // Required - } - resp, err := svc.GetBucketCors(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleS3_GetBucketLifecycle() { - svc := s3.New(nil) - - params := &s3.GetBucketLifecycleInput{ - Bucket: aws.String("BucketName"), // Required - } - resp, err := svc.GetBucketLifecycle(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleS3_GetBucketLocation() { - svc := s3.New(nil) - - params := &s3.GetBucketLocationInput{ - Bucket: aws.String("BucketName"), // Required - } - resp, err := svc.GetBucketLocation(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleS3_GetBucketLogging() { - svc := s3.New(nil) - - params := &s3.GetBucketLoggingInput{ - Bucket: aws.String("BucketName"), // Required - } - resp, err := svc.GetBucketLogging(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleS3_GetBucketNotification() { - svc := s3.New(nil) - - params := &s3.GetBucketNotificationConfigurationRequest{ - Bucket: aws.String("BucketName"), // Required - } - resp, err := svc.GetBucketNotification(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleS3_GetBucketNotificationConfiguration() { - svc := s3.New(nil) - - params := &s3.GetBucketNotificationConfigurationRequest{ - Bucket: aws.String("BucketName"), // Required - } - resp, err := svc.GetBucketNotificationConfiguration(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleS3_GetBucketPolicy() { - svc := s3.New(nil) - - params := &s3.GetBucketPolicyInput{ - Bucket: aws.String("BucketName"), // Required - } - resp, err := svc.GetBucketPolicy(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleS3_GetBucketReplication() { - svc := s3.New(nil) - - params := &s3.GetBucketReplicationInput{ - Bucket: aws.String("BucketName"), // Required - } - resp, err := svc.GetBucketReplication(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleS3_GetBucketRequestPayment() { - svc := s3.New(nil) - - params := &s3.GetBucketRequestPaymentInput{ - Bucket: aws.String("BucketName"), // Required - } - resp, err := svc.GetBucketRequestPayment(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleS3_GetBucketTagging() { - svc := s3.New(nil) - - params := &s3.GetBucketTaggingInput{ - Bucket: aws.String("BucketName"), // Required - } - resp, err := svc.GetBucketTagging(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleS3_GetBucketVersioning() { - svc := s3.New(nil) - - params := &s3.GetBucketVersioningInput{ - Bucket: aws.String("BucketName"), // Required - } - resp, err := svc.GetBucketVersioning(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleS3_GetBucketWebsite() { - svc := s3.New(nil) - - params := &s3.GetBucketWebsiteInput{ - Bucket: aws.String("BucketName"), // Required - } - resp, err := svc.GetBucketWebsite(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleS3_GetObject() { - svc := s3.New(nil) - - params := &s3.GetObjectInput{ - Bucket: aws.String("BucketName"), // Required - Key: aws.String("ObjectKey"), // Required - IfMatch: aws.String("IfMatch"), - IfModifiedSince: aws.Time(time.Now()), - IfNoneMatch: aws.String("IfNoneMatch"), - IfUnmodifiedSince: aws.Time(time.Now()), - Range: aws.String("Range"), - RequestPayer: aws.String("RequestPayer"), - ResponseCacheControl: aws.String("ResponseCacheControl"), - ResponseContentDisposition: aws.String("ResponseContentDisposition"), - ResponseContentEncoding: aws.String("ResponseContentEncoding"), - ResponseContentLanguage: aws.String("ResponseContentLanguage"), - ResponseContentType: aws.String("ResponseContentType"), - ResponseExpires: aws.Time(time.Now()), - SSECustomerAlgorithm: aws.String("SSECustomerAlgorithm"), - SSECustomerKey: aws.String("SSECustomerKey"), - SSECustomerKeyMD5: aws.String("SSECustomerKeyMD5"), - VersionId: aws.String("ObjectVersionId"), - } - resp, err := svc.GetObject(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleS3_GetObjectAcl() { - svc := s3.New(nil) - - params := &s3.GetObjectAclInput{ - Bucket: aws.String("BucketName"), // Required - Key: aws.String("ObjectKey"), // Required - RequestPayer: aws.String("RequestPayer"), - VersionId: aws.String("ObjectVersionId"), - } - resp, err := svc.GetObjectAcl(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleS3_GetObjectTorrent() { - svc := s3.New(nil) - - params := &s3.GetObjectTorrentInput{ - Bucket: aws.String("BucketName"), // Required - Key: aws.String("ObjectKey"), // Required - RequestPayer: aws.String("RequestPayer"), - } - resp, err := svc.GetObjectTorrent(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleS3_HeadBucket() { - svc := s3.New(nil) - - params := &s3.HeadBucketInput{ - Bucket: aws.String("BucketName"), // Required - } - resp, err := svc.HeadBucket(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleS3_HeadObject() { - svc := s3.New(nil) - - params := &s3.HeadObjectInput{ - Bucket: aws.String("BucketName"), // Required - Key: aws.String("ObjectKey"), // Required - IfMatch: aws.String("IfMatch"), - IfModifiedSince: aws.Time(time.Now()), - IfNoneMatch: aws.String("IfNoneMatch"), - IfUnmodifiedSince: aws.Time(time.Now()), - Range: aws.String("Range"), - RequestPayer: aws.String("RequestPayer"), - SSECustomerAlgorithm: aws.String("SSECustomerAlgorithm"), - SSECustomerKey: aws.String("SSECustomerKey"), - SSECustomerKeyMD5: aws.String("SSECustomerKeyMD5"), - VersionId: aws.String("ObjectVersionId"), - } - resp, err := svc.HeadObject(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleS3_ListBuckets() { - svc := s3.New(nil) - - var params *s3.ListBucketsInput - resp, err := svc.ListBuckets(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleS3_ListMultipartUploads() { - svc := s3.New(nil) - - params := &s3.ListMultipartUploadsInput{ - Bucket: aws.String("BucketName"), // Required - Delimiter: aws.String("Delimiter"), - EncodingType: aws.String("EncodingType"), - KeyMarker: aws.String("KeyMarker"), - MaxUploads: aws.Int64(1), - Prefix: aws.String("Prefix"), - UploadIdMarker: aws.String("UploadIdMarker"), - } - resp, err := svc.ListMultipartUploads(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleS3_ListObjectVersions() { - svc := s3.New(nil) - - params := &s3.ListObjectVersionsInput{ - Bucket: aws.String("BucketName"), // Required - Delimiter: aws.String("Delimiter"), - EncodingType: aws.String("EncodingType"), - KeyMarker: aws.String("KeyMarker"), - MaxKeys: aws.Int64(1), - Prefix: aws.String("Prefix"), - VersionIdMarker: aws.String("VersionIdMarker"), - } - resp, err := svc.ListObjectVersions(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleS3_ListObjects() { - svc := s3.New(nil) - - params := &s3.ListObjectsInput{ - Bucket: aws.String("BucketName"), // Required - Delimiter: aws.String("Delimiter"), - EncodingType: aws.String("EncodingType"), - Marker: aws.String("Marker"), - MaxKeys: aws.Int64(1), - Prefix: aws.String("Prefix"), - } - resp, err := svc.ListObjects(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleS3_ListParts() { - svc := s3.New(nil) - - params := &s3.ListPartsInput{ - Bucket: aws.String("BucketName"), // Required - Key: aws.String("ObjectKey"), // Required - UploadId: aws.String("MultipartUploadId"), // Required - MaxParts: aws.Int64(1), - PartNumberMarker: aws.Int64(1), - RequestPayer: aws.String("RequestPayer"), - } - resp, err := svc.ListParts(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleS3_PutBucketAcl() { - svc := s3.New(nil) - - params := &s3.PutBucketAclInput{ - Bucket: aws.String("BucketName"), // Required - ACL: aws.String("BucketCannedACL"), - AccessControlPolicy: &s3.AccessControlPolicy{ - Grants: []*s3.Grant{ - { // Required - Grantee: &s3.Grantee{ - Type: aws.String("Type"), // Required - DisplayName: aws.String("DisplayName"), - EmailAddress: aws.String("EmailAddress"), - ID: aws.String("ID"), - URI: aws.String("URI"), - }, - Permission: aws.String("Permission"), - }, - // More values... - }, - Owner: &s3.Owner{ - DisplayName: aws.String("DisplayName"), - ID: aws.String("ID"), - }, - }, - GrantFullControl: aws.String("GrantFullControl"), - GrantRead: aws.String("GrantRead"), - GrantReadACP: aws.String("GrantReadACP"), - GrantWrite: aws.String("GrantWrite"), - GrantWriteACP: aws.String("GrantWriteACP"), - } - resp, err := svc.PutBucketAcl(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleS3_PutBucketCors() { - svc := s3.New(nil) - - params := &s3.PutBucketCorsInput{ - Bucket: aws.String("BucketName"), // Required - CORSConfiguration: &s3.CORSConfiguration{ - CORSRules: []*s3.CORSRule{ - { // Required - AllowedHeaders: []*string{ - aws.String("AllowedHeader"), // Required - // More values... - }, - AllowedMethods: []*string{ - aws.String("AllowedMethod"), // Required - // More values... - }, - AllowedOrigins: []*string{ - aws.String("AllowedOrigin"), // Required - // More values... - }, - ExposeHeaders: []*string{ - aws.String("ExposeHeader"), // Required - // More values... - }, - MaxAgeSeconds: aws.Int64(1), - }, - // More values... - }, - }, - } - resp, err := svc.PutBucketCors(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleS3_PutBucketLifecycle() { - svc := s3.New(nil) - - params := &s3.PutBucketLifecycleInput{ - Bucket: aws.String("BucketName"), // Required - LifecycleConfiguration: &s3.LifecycleConfiguration{ - Rules: []*s3.LifecycleRule{ // Required - { // Required - Prefix: aws.String("Prefix"), // Required - Status: aws.String("ExpirationStatus"), // Required - Expiration: &s3.LifecycleExpiration{ - Date: aws.Time(time.Now()), - Days: aws.Int64(1), - }, - ID: aws.String("ID"), - NoncurrentVersionExpiration: &s3.NoncurrentVersionExpiration{ - NoncurrentDays: aws.Int64(1), - }, - NoncurrentVersionTransition: &s3.NoncurrentVersionTransition{ - NoncurrentDays: aws.Int64(1), - StorageClass: aws.String("TransitionStorageClass"), - }, - Transition: &s3.Transition{ - Date: aws.Time(time.Now()), - Days: aws.Int64(1), - StorageClass: aws.String("TransitionStorageClass"), - }, - }, - // More values... - }, - }, - } - resp, err := svc.PutBucketLifecycle(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleS3_PutBucketLogging() { - svc := s3.New(nil) - - params := &s3.PutBucketLoggingInput{ - Bucket: aws.String("BucketName"), // Required - BucketLoggingStatus: &s3.BucketLoggingStatus{ // Required - LoggingEnabled: &s3.LoggingEnabled{ - TargetBucket: aws.String("TargetBucket"), - TargetGrants: []*s3.TargetGrant{ - { // Required - Grantee: &s3.Grantee{ - Type: aws.String("Type"), // Required - DisplayName: aws.String("DisplayName"), - EmailAddress: aws.String("EmailAddress"), - ID: aws.String("ID"), - URI: aws.String("URI"), - }, - Permission: aws.String("BucketLogsPermission"), - }, - // More values... - }, - TargetPrefix: aws.String("TargetPrefix"), - }, - }, - } - resp, err := svc.PutBucketLogging(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleS3_PutBucketNotification() { - svc := s3.New(nil) - - params := &s3.PutBucketNotificationInput{ - Bucket: aws.String("BucketName"), // Required - NotificationConfiguration: &s3.NotificationConfigurationDeprecated{ // Required - CloudFunctionConfiguration: &s3.CloudFunctionConfiguration{ - CloudFunction: aws.String("CloudFunction"), - Event: aws.String("Event"), - Events: []*string{ - aws.String("Event"), // Required - // More values... - }, - Id: aws.String("NotificationId"), - InvocationRole: aws.String("CloudFunctionInvocationRole"), - }, - QueueConfiguration: &s3.QueueConfigurationDeprecated{ - Event: aws.String("Event"), - Events: []*string{ - aws.String("Event"), // Required - // More values... - }, - Id: aws.String("NotificationId"), - Queue: aws.String("QueueArn"), - }, - TopicConfiguration: &s3.TopicConfigurationDeprecated{ - Event: aws.String("Event"), - Events: []*string{ - aws.String("Event"), // Required - // More values... - }, - Id: aws.String("NotificationId"), - Topic: aws.String("TopicArn"), - }, - }, - } - resp, err := svc.PutBucketNotification(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleS3_PutBucketNotificationConfiguration() { - svc := s3.New(nil) - - params := &s3.PutBucketNotificationConfigurationInput{ - Bucket: aws.String("BucketName"), // Required - NotificationConfiguration: &s3.NotificationConfiguration{ // Required - LambdaFunctionConfigurations: []*s3.LambdaFunctionConfiguration{ - { // Required - Events: []*string{ // Required - aws.String("Event"), // Required - // More values... - }, - LambdaFunctionArn: aws.String("LambdaFunctionArn"), // Required - Id: aws.String("NotificationId"), - }, - // More values... - }, - QueueConfigurations: []*s3.QueueConfiguration{ - { // Required - Events: []*string{ // Required - aws.String("Event"), // Required - // More values... - }, - QueueArn: aws.String("QueueArn"), // Required - Id: aws.String("NotificationId"), - }, - // More values... - }, - TopicConfigurations: []*s3.TopicConfiguration{ - { // Required - Events: []*string{ // Required - aws.String("Event"), // Required - // More values... - }, - TopicArn: aws.String("TopicArn"), // Required - Id: aws.String("NotificationId"), - }, - // More values... - }, - }, - } - resp, err := svc.PutBucketNotificationConfiguration(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleS3_PutBucketPolicy() { - svc := s3.New(nil) - - params := &s3.PutBucketPolicyInput{ - Bucket: aws.String("BucketName"), // Required - Policy: aws.String("Policy"), // Required - } - resp, err := svc.PutBucketPolicy(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleS3_PutBucketReplication() { - svc := s3.New(nil) - - params := &s3.PutBucketReplicationInput{ - Bucket: aws.String("BucketName"), // Required - ReplicationConfiguration: &s3.ReplicationConfiguration{ // Required - Role: aws.String("Role"), // Required - Rules: []*s3.ReplicationRule{ // Required - { // Required - Destination: &s3.Destination{ // Required - Bucket: aws.String("BucketName"), // Required - }, - Prefix: aws.String("Prefix"), // Required - Status: aws.String("ReplicationRuleStatus"), // Required - ID: aws.String("ID"), - }, - // More values... - }, - }, - } - resp, err := svc.PutBucketReplication(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleS3_PutBucketRequestPayment() { - svc := s3.New(nil) - - params := &s3.PutBucketRequestPaymentInput{ - Bucket: aws.String("BucketName"), // Required - RequestPaymentConfiguration: &s3.RequestPaymentConfiguration{ // Required - Payer: aws.String("Payer"), // Required - }, - } - resp, err := svc.PutBucketRequestPayment(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleS3_PutBucketTagging() { - svc := s3.New(nil) - - params := &s3.PutBucketTaggingInput{ - Bucket: aws.String("BucketName"), // Required - Tagging: &s3.Tagging{ // Required - TagSet: []*s3.Tag{ // Required - { // Required - Key: aws.String("ObjectKey"), // Required - Value: aws.String("Value"), // Required - }, - // More values... - }, - }, - } - resp, err := svc.PutBucketTagging(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleS3_PutBucketVersioning() { - svc := s3.New(nil) - - params := &s3.PutBucketVersioningInput{ - Bucket: aws.String("BucketName"), // Required - VersioningConfiguration: &s3.VersioningConfiguration{ // Required - MFADelete: aws.String("MFADelete"), - Status: aws.String("BucketVersioningStatus"), - }, - MFA: aws.String("MFA"), - } - resp, err := svc.PutBucketVersioning(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleS3_PutBucketWebsite() { - svc := s3.New(nil) - - params := &s3.PutBucketWebsiteInput{ - Bucket: aws.String("BucketName"), // Required - WebsiteConfiguration: &s3.WebsiteConfiguration{ // Required - ErrorDocument: &s3.ErrorDocument{ - Key: aws.String("ObjectKey"), // Required - }, - IndexDocument: &s3.IndexDocument{ - Suffix: aws.String("Suffix"), // Required - }, - RedirectAllRequestsTo: &s3.RedirectAllRequestsTo{ - HostName: aws.String("HostName"), // Required - Protocol: aws.String("Protocol"), - }, - RoutingRules: []*s3.RoutingRule{ - { // Required - Redirect: &s3.Redirect{ // Required - HostName: aws.String("HostName"), - HttpRedirectCode: aws.String("HttpRedirectCode"), - Protocol: aws.String("Protocol"), - ReplaceKeyPrefixWith: aws.String("ReplaceKeyPrefixWith"), - ReplaceKeyWith: aws.String("ReplaceKeyWith"), - }, - Condition: &s3.Condition{ - HttpErrorCodeReturnedEquals: aws.String("HttpErrorCodeReturnedEquals"), - KeyPrefixEquals: aws.String("KeyPrefixEquals"), - }, - }, - // More values... - }, - }, - } - resp, err := svc.PutBucketWebsite(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleS3_PutObject() { - svc := s3.New(nil) - - params := &s3.PutObjectInput{ - Bucket: aws.String("BucketName"), // Required - Key: aws.String("ObjectKey"), // Required - ACL: aws.String("ObjectCannedACL"), - Body: bytes.NewReader([]byte("PAYLOAD")), - CacheControl: aws.String("CacheControl"), - ContentDisposition: aws.String("ContentDisposition"), - ContentEncoding: aws.String("ContentEncoding"), - ContentLanguage: aws.String("ContentLanguage"), - ContentLength: aws.Int64(1), - ContentType: aws.String("ContentType"), - Expires: aws.Time(time.Now()), - GrantFullControl: aws.String("GrantFullControl"), - GrantRead: aws.String("GrantRead"), - GrantReadACP: aws.String("GrantReadACP"), - GrantWriteACP: aws.String("GrantWriteACP"), - Metadata: map[string]*string{ - "Key": aws.String("MetadataValue"), // Required - // More values... - }, - RequestPayer: aws.String("RequestPayer"), - SSECustomerAlgorithm: aws.String("SSECustomerAlgorithm"), - SSECustomerKey: aws.String("SSECustomerKey"), - SSECustomerKeyMD5: aws.String("SSECustomerKeyMD5"), - SSEKMSKeyId: aws.String("SSEKMSKeyId"), - ServerSideEncryption: aws.String("ServerSideEncryption"), - StorageClass: aws.String("StorageClass"), - WebsiteRedirectLocation: aws.String("WebsiteRedirectLocation"), - } - resp, err := svc.PutObject(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleS3_PutObjectAcl() { - svc := s3.New(nil) - - params := &s3.PutObjectAclInput{ - Bucket: aws.String("BucketName"), // Required - Key: aws.String("ObjectKey"), // Required - ACL: aws.String("ObjectCannedACL"), - AccessControlPolicy: &s3.AccessControlPolicy{ - Grants: []*s3.Grant{ - { // Required - Grantee: &s3.Grantee{ - Type: aws.String("Type"), // Required - DisplayName: aws.String("DisplayName"), - EmailAddress: aws.String("EmailAddress"), - ID: aws.String("ID"), - URI: aws.String("URI"), - }, - Permission: aws.String("Permission"), - }, - // More values... - }, - Owner: &s3.Owner{ - DisplayName: aws.String("DisplayName"), - ID: aws.String("ID"), - }, - }, - GrantFullControl: aws.String("GrantFullControl"), - GrantRead: aws.String("GrantRead"), - GrantReadACP: aws.String("GrantReadACP"), - GrantWrite: aws.String("GrantWrite"), - GrantWriteACP: aws.String("GrantWriteACP"), - RequestPayer: aws.String("RequestPayer"), - } - resp, err := svc.PutObjectAcl(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleS3_RestoreObject() { - svc := s3.New(nil) - - params := &s3.RestoreObjectInput{ - Bucket: aws.String("BucketName"), // Required - Key: aws.String("ObjectKey"), // Required - RequestPayer: aws.String("RequestPayer"), - RestoreRequest: &s3.RestoreRequest{ - Days: aws.Int64(1), // Required - }, - VersionId: aws.String("ObjectVersionId"), - } - resp, err := svc.RestoreObject(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleS3_UploadPart() { - svc := s3.New(nil) - - params := &s3.UploadPartInput{ - Bucket: aws.String("BucketName"), // Required - Key: aws.String("ObjectKey"), // Required - PartNumber: aws.Int64(1), // Required - UploadId: aws.String("MultipartUploadId"), // Required - Body: bytes.NewReader([]byte("PAYLOAD")), - ContentLength: aws.Int64(1), - RequestPayer: aws.String("RequestPayer"), - SSECustomerAlgorithm: aws.String("SSECustomerAlgorithm"), - SSECustomerKey: aws.String("SSECustomerKey"), - SSECustomerKeyMD5: aws.String("SSECustomerKeyMD5"), - } - resp, err := svc.UploadPart(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} - -func ExampleS3_UploadPartCopy() { - svc := s3.New(nil) - - params := &s3.UploadPartCopyInput{ - Bucket: aws.String("BucketName"), // Required - CopySource: aws.String("CopySource"), // Required - Key: aws.String("ObjectKey"), // Required - PartNumber: aws.Int64(1), // Required - UploadId: aws.String("MultipartUploadId"), // Required - CopySourceIfMatch: aws.String("CopySourceIfMatch"), - CopySourceIfModifiedSince: aws.Time(time.Now()), - CopySourceIfNoneMatch: aws.String("CopySourceIfNoneMatch"), - CopySourceIfUnmodifiedSince: aws.Time(time.Now()), - CopySourceRange: aws.String("CopySourceRange"), - CopySourceSSECustomerAlgorithm: aws.String("CopySourceSSECustomerAlgorithm"), - CopySourceSSECustomerKey: aws.String("CopySourceSSECustomerKey"), - CopySourceSSECustomerKeyMD5: aws.String("CopySourceSSECustomerKeyMD5"), - RequestPayer: aws.String("RequestPayer"), - SSECustomerAlgorithm: aws.String("SSECustomerAlgorithm"), - SSECustomerKey: aws.String("SSECustomerKey"), - SSECustomerKeyMD5: aws.String("SSECustomerKeyMD5"), - } - resp, err := svc.UploadPartCopy(params) - - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - // Generic AWS error with Code, Message, and original error (if any) - fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) - if reqErr, ok := err.(awserr.RequestFailure); ok { - // A service error occurred - fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) - } - } else { - // This case should never be hit, the SDK should always return an - // error which satisfies the awserr.Error interface. - fmt.Println(err.Error()) - } - } - - // Pretty-print the response data. - fmt.Println(awsutil.Prettify(resp)) -} diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/host_style_bucket.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/host_style_bucket.go index 55106442f..47c8495e8 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/host_style_bucket.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/host_style_bucket.go @@ -6,7 +6,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awsutil" - "github.com/aws/aws-sdk-go/aws/service" + "github.com/aws/aws-sdk-go/aws/request" ) var reDomain = regexp.MustCompile(`^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$`) @@ -23,8 +23,8 @@ func dnsCompatibleBucketName(bucket string) bool { // hostStyleBucketName returns true if the request should put the bucket in // the host. This is false if S3ForcePathStyle is explicitly set or if the // bucket is not DNS compatible. -func hostStyleBucketName(r *service.Request, bucket string) bool { - if aws.BoolValue(r.Config.S3ForcePathStyle) { +func hostStyleBucketName(r *request.Request, bucket string) bool { + if aws.BoolValue(r.Service.Config.S3ForcePathStyle) { return false } @@ -34,11 +34,17 @@ func hostStyleBucketName(r *service.Request, bucket string) bool { return false } + // GetBucketLocation should be able to be called from any region within + // a partition, and return the associated region of the bucket. + if r.Operation.Name == opGetBucketLocation { + return false + } + // Use host-style if the bucket is DNS compatible return dnsCompatibleBucketName(bucket) } -func updateHostWithBucket(r *service.Request) { +func updateHostWithBucket(r *request.Request) { b := awsutil.ValuesAtPath(r.Params, "Bucket") if len(b) == 0 { return diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/host_style_bucket_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/host_style_bucket_test.go deleted file mode 100644 index c4347d44b..000000000 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/host_style_bucket_test.go +++ /dev/null @@ -1,61 +0,0 @@ -package s3_test - -import ( - "testing" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/internal/test/unit" - "github.com/aws/aws-sdk-go/service/s3" - "github.com/stretchr/testify/assert" -) - -type s3BucketTest struct { - bucket string - url string -} - -var ( - _ = unit.Imported - - sslTests = []s3BucketTest{ - {"abc", "https://abc.s3.mock-region.amazonaws.com/"}, - {"a$b$c", "https://s3.mock-region.amazonaws.com/a%24b%24c"}, - {"a.b.c", "https://s3.mock-region.amazonaws.com/a.b.c"}, - {"a..bc", "https://s3.mock-region.amazonaws.com/a..bc"}, - } - - nosslTests = []s3BucketTest{ - {"a.b.c", "http://a.b.c.s3.mock-region.amazonaws.com/"}, - {"a..bc", "http://s3.mock-region.amazonaws.com/a..bc"}, - } - - forcepathTests = []s3BucketTest{ - {"abc", "https://s3.mock-region.amazonaws.com/abc"}, - {"a$b$c", "https://s3.mock-region.amazonaws.com/a%24b%24c"}, - {"a.b.c", "https://s3.mock-region.amazonaws.com/a.b.c"}, - {"a..bc", "https://s3.mock-region.amazonaws.com/a..bc"}, - } -) - -func runTests(t *testing.T, svc *s3.S3, tests []s3BucketTest) { - for _, test := range tests { - req, _ := svc.ListObjectsRequest(&s3.ListObjectsInput{Bucket: &test.bucket}) - req.Build() - assert.Equal(t, test.url, req.HTTPRequest.URL.String()) - } -} - -func TestHostStyleBucketBuild(t *testing.T) { - s := s3.New(nil) - runTests(t, s, sslTests) -} - -func TestHostStyleBucketBuildNoSSL(t *testing.T) { - s := s3.New(&aws.Config{DisableSSL: aws.Bool(true)}) - runTests(t, s, nosslTests) -} - -func TestPathStyleBucketBuild(t *testing.T) { - s := s3.New(&aws.Config{S3ForcePathStyle: aws.Bool(true)}) - runTests(t, s, forcepathTests) -} diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/s3iface/interface.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/s3iface/interface.go index 86cce906a..d51ef693a 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/s3iface/interface.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/s3iface/interface.go @@ -4,233 +4,241 @@ package s3iface import ( - "github.com/aws/aws-sdk-go/aws/service" + "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/service/s3" ) // S3API is the interface type for s3.S3. type S3API interface { - AbortMultipartUploadRequest(*s3.AbortMultipartUploadInput) (*service.Request, *s3.AbortMultipartUploadOutput) + AbortMultipartUploadRequest(*s3.AbortMultipartUploadInput) (*request.Request, *s3.AbortMultipartUploadOutput) AbortMultipartUpload(*s3.AbortMultipartUploadInput) (*s3.AbortMultipartUploadOutput, error) - CompleteMultipartUploadRequest(*s3.CompleteMultipartUploadInput) (*service.Request, *s3.CompleteMultipartUploadOutput) + CompleteMultipartUploadRequest(*s3.CompleteMultipartUploadInput) (*request.Request, *s3.CompleteMultipartUploadOutput) CompleteMultipartUpload(*s3.CompleteMultipartUploadInput) (*s3.CompleteMultipartUploadOutput, error) - CopyObjectRequest(*s3.CopyObjectInput) (*service.Request, *s3.CopyObjectOutput) + CopyObjectRequest(*s3.CopyObjectInput) (*request.Request, *s3.CopyObjectOutput) CopyObject(*s3.CopyObjectInput) (*s3.CopyObjectOutput, error) - CreateBucketRequest(*s3.CreateBucketInput) (*service.Request, *s3.CreateBucketOutput) + CreateBucketRequest(*s3.CreateBucketInput) (*request.Request, *s3.CreateBucketOutput) CreateBucket(*s3.CreateBucketInput) (*s3.CreateBucketOutput, error) - CreateMultipartUploadRequest(*s3.CreateMultipartUploadInput) (*service.Request, *s3.CreateMultipartUploadOutput) + CreateMultipartUploadRequest(*s3.CreateMultipartUploadInput) (*request.Request, *s3.CreateMultipartUploadOutput) CreateMultipartUpload(*s3.CreateMultipartUploadInput) (*s3.CreateMultipartUploadOutput, error) - DeleteBucketRequest(*s3.DeleteBucketInput) (*service.Request, *s3.DeleteBucketOutput) + DeleteBucketRequest(*s3.DeleteBucketInput) (*request.Request, *s3.DeleteBucketOutput) DeleteBucket(*s3.DeleteBucketInput) (*s3.DeleteBucketOutput, error) - DeleteBucketCorsRequest(*s3.DeleteBucketCorsInput) (*service.Request, *s3.DeleteBucketCorsOutput) + DeleteBucketCorsRequest(*s3.DeleteBucketCorsInput) (*request.Request, *s3.DeleteBucketCorsOutput) DeleteBucketCors(*s3.DeleteBucketCorsInput) (*s3.DeleteBucketCorsOutput, error) - DeleteBucketLifecycleRequest(*s3.DeleteBucketLifecycleInput) (*service.Request, *s3.DeleteBucketLifecycleOutput) + DeleteBucketLifecycleRequest(*s3.DeleteBucketLifecycleInput) (*request.Request, *s3.DeleteBucketLifecycleOutput) DeleteBucketLifecycle(*s3.DeleteBucketLifecycleInput) (*s3.DeleteBucketLifecycleOutput, error) - DeleteBucketPolicyRequest(*s3.DeleteBucketPolicyInput) (*service.Request, *s3.DeleteBucketPolicyOutput) + DeleteBucketPolicyRequest(*s3.DeleteBucketPolicyInput) (*request.Request, *s3.DeleteBucketPolicyOutput) DeleteBucketPolicy(*s3.DeleteBucketPolicyInput) (*s3.DeleteBucketPolicyOutput, error) - DeleteBucketReplicationRequest(*s3.DeleteBucketReplicationInput) (*service.Request, *s3.DeleteBucketReplicationOutput) + DeleteBucketReplicationRequest(*s3.DeleteBucketReplicationInput) (*request.Request, *s3.DeleteBucketReplicationOutput) DeleteBucketReplication(*s3.DeleteBucketReplicationInput) (*s3.DeleteBucketReplicationOutput, error) - DeleteBucketTaggingRequest(*s3.DeleteBucketTaggingInput) (*service.Request, *s3.DeleteBucketTaggingOutput) + DeleteBucketTaggingRequest(*s3.DeleteBucketTaggingInput) (*request.Request, *s3.DeleteBucketTaggingOutput) DeleteBucketTagging(*s3.DeleteBucketTaggingInput) (*s3.DeleteBucketTaggingOutput, error) - DeleteBucketWebsiteRequest(*s3.DeleteBucketWebsiteInput) (*service.Request, *s3.DeleteBucketWebsiteOutput) + DeleteBucketWebsiteRequest(*s3.DeleteBucketWebsiteInput) (*request.Request, *s3.DeleteBucketWebsiteOutput) DeleteBucketWebsite(*s3.DeleteBucketWebsiteInput) (*s3.DeleteBucketWebsiteOutput, error) - DeleteObjectRequest(*s3.DeleteObjectInput) (*service.Request, *s3.DeleteObjectOutput) + DeleteObjectRequest(*s3.DeleteObjectInput) (*request.Request, *s3.DeleteObjectOutput) DeleteObject(*s3.DeleteObjectInput) (*s3.DeleteObjectOutput, error) - DeleteObjectsRequest(*s3.DeleteObjectsInput) (*service.Request, *s3.DeleteObjectsOutput) + DeleteObjectsRequest(*s3.DeleteObjectsInput) (*request.Request, *s3.DeleteObjectsOutput) DeleteObjects(*s3.DeleteObjectsInput) (*s3.DeleteObjectsOutput, error) - GetBucketAclRequest(*s3.GetBucketAclInput) (*service.Request, *s3.GetBucketAclOutput) + GetBucketAclRequest(*s3.GetBucketAclInput) (*request.Request, *s3.GetBucketAclOutput) GetBucketAcl(*s3.GetBucketAclInput) (*s3.GetBucketAclOutput, error) - GetBucketCorsRequest(*s3.GetBucketCorsInput) (*service.Request, *s3.GetBucketCorsOutput) + GetBucketCorsRequest(*s3.GetBucketCorsInput) (*request.Request, *s3.GetBucketCorsOutput) GetBucketCors(*s3.GetBucketCorsInput) (*s3.GetBucketCorsOutput, error) - GetBucketLifecycleRequest(*s3.GetBucketLifecycleInput) (*service.Request, *s3.GetBucketLifecycleOutput) + GetBucketLifecycleRequest(*s3.GetBucketLifecycleInput) (*request.Request, *s3.GetBucketLifecycleOutput) GetBucketLifecycle(*s3.GetBucketLifecycleInput) (*s3.GetBucketLifecycleOutput, error) - GetBucketLocationRequest(*s3.GetBucketLocationInput) (*service.Request, *s3.GetBucketLocationOutput) + GetBucketLifecycleConfigurationRequest(*s3.GetBucketLifecycleConfigurationInput) (*request.Request, *s3.GetBucketLifecycleConfigurationOutput) + + GetBucketLifecycleConfiguration(*s3.GetBucketLifecycleConfigurationInput) (*s3.GetBucketLifecycleConfigurationOutput, error) + + GetBucketLocationRequest(*s3.GetBucketLocationInput) (*request.Request, *s3.GetBucketLocationOutput) GetBucketLocation(*s3.GetBucketLocationInput) (*s3.GetBucketLocationOutput, error) - GetBucketLoggingRequest(*s3.GetBucketLoggingInput) (*service.Request, *s3.GetBucketLoggingOutput) + GetBucketLoggingRequest(*s3.GetBucketLoggingInput) (*request.Request, *s3.GetBucketLoggingOutput) GetBucketLogging(*s3.GetBucketLoggingInput) (*s3.GetBucketLoggingOutput, error) - GetBucketNotificationRequest(*s3.GetBucketNotificationConfigurationRequest) (*service.Request, *s3.NotificationConfigurationDeprecated) + GetBucketNotificationRequest(*s3.GetBucketNotificationConfigurationRequest) (*request.Request, *s3.NotificationConfigurationDeprecated) GetBucketNotification(*s3.GetBucketNotificationConfigurationRequest) (*s3.NotificationConfigurationDeprecated, error) - GetBucketNotificationConfigurationRequest(*s3.GetBucketNotificationConfigurationRequest) (*service.Request, *s3.NotificationConfiguration) + GetBucketNotificationConfigurationRequest(*s3.GetBucketNotificationConfigurationRequest) (*request.Request, *s3.NotificationConfiguration) GetBucketNotificationConfiguration(*s3.GetBucketNotificationConfigurationRequest) (*s3.NotificationConfiguration, error) - GetBucketPolicyRequest(*s3.GetBucketPolicyInput) (*service.Request, *s3.GetBucketPolicyOutput) + GetBucketPolicyRequest(*s3.GetBucketPolicyInput) (*request.Request, *s3.GetBucketPolicyOutput) GetBucketPolicy(*s3.GetBucketPolicyInput) (*s3.GetBucketPolicyOutput, error) - GetBucketReplicationRequest(*s3.GetBucketReplicationInput) (*service.Request, *s3.GetBucketReplicationOutput) + GetBucketReplicationRequest(*s3.GetBucketReplicationInput) (*request.Request, *s3.GetBucketReplicationOutput) GetBucketReplication(*s3.GetBucketReplicationInput) (*s3.GetBucketReplicationOutput, error) - GetBucketRequestPaymentRequest(*s3.GetBucketRequestPaymentInput) (*service.Request, *s3.GetBucketRequestPaymentOutput) + GetBucketRequestPaymentRequest(*s3.GetBucketRequestPaymentInput) (*request.Request, *s3.GetBucketRequestPaymentOutput) GetBucketRequestPayment(*s3.GetBucketRequestPaymentInput) (*s3.GetBucketRequestPaymentOutput, error) - GetBucketTaggingRequest(*s3.GetBucketTaggingInput) (*service.Request, *s3.GetBucketTaggingOutput) + GetBucketTaggingRequest(*s3.GetBucketTaggingInput) (*request.Request, *s3.GetBucketTaggingOutput) GetBucketTagging(*s3.GetBucketTaggingInput) (*s3.GetBucketTaggingOutput, error) - GetBucketVersioningRequest(*s3.GetBucketVersioningInput) (*service.Request, *s3.GetBucketVersioningOutput) + GetBucketVersioningRequest(*s3.GetBucketVersioningInput) (*request.Request, *s3.GetBucketVersioningOutput) GetBucketVersioning(*s3.GetBucketVersioningInput) (*s3.GetBucketVersioningOutput, error) - GetBucketWebsiteRequest(*s3.GetBucketWebsiteInput) (*service.Request, *s3.GetBucketWebsiteOutput) + GetBucketWebsiteRequest(*s3.GetBucketWebsiteInput) (*request.Request, *s3.GetBucketWebsiteOutput) GetBucketWebsite(*s3.GetBucketWebsiteInput) (*s3.GetBucketWebsiteOutput, error) - GetObjectRequest(*s3.GetObjectInput) (*service.Request, *s3.GetObjectOutput) + GetObjectRequest(*s3.GetObjectInput) (*request.Request, *s3.GetObjectOutput) GetObject(*s3.GetObjectInput) (*s3.GetObjectOutput, error) - GetObjectAclRequest(*s3.GetObjectAclInput) (*service.Request, *s3.GetObjectAclOutput) + GetObjectAclRequest(*s3.GetObjectAclInput) (*request.Request, *s3.GetObjectAclOutput) GetObjectAcl(*s3.GetObjectAclInput) (*s3.GetObjectAclOutput, error) - GetObjectTorrentRequest(*s3.GetObjectTorrentInput) (*service.Request, *s3.GetObjectTorrentOutput) + GetObjectTorrentRequest(*s3.GetObjectTorrentInput) (*request.Request, *s3.GetObjectTorrentOutput) GetObjectTorrent(*s3.GetObjectTorrentInput) (*s3.GetObjectTorrentOutput, error) - HeadBucketRequest(*s3.HeadBucketInput) (*service.Request, *s3.HeadBucketOutput) + HeadBucketRequest(*s3.HeadBucketInput) (*request.Request, *s3.HeadBucketOutput) HeadBucket(*s3.HeadBucketInput) (*s3.HeadBucketOutput, error) - HeadObjectRequest(*s3.HeadObjectInput) (*service.Request, *s3.HeadObjectOutput) + HeadObjectRequest(*s3.HeadObjectInput) (*request.Request, *s3.HeadObjectOutput) HeadObject(*s3.HeadObjectInput) (*s3.HeadObjectOutput, error) - ListBucketsRequest(*s3.ListBucketsInput) (*service.Request, *s3.ListBucketsOutput) + ListBucketsRequest(*s3.ListBucketsInput) (*request.Request, *s3.ListBucketsOutput) ListBuckets(*s3.ListBucketsInput) (*s3.ListBucketsOutput, error) - ListMultipartUploadsRequest(*s3.ListMultipartUploadsInput) (*service.Request, *s3.ListMultipartUploadsOutput) + ListMultipartUploadsRequest(*s3.ListMultipartUploadsInput) (*request.Request, *s3.ListMultipartUploadsOutput) ListMultipartUploads(*s3.ListMultipartUploadsInput) (*s3.ListMultipartUploadsOutput, error) ListMultipartUploadsPages(*s3.ListMultipartUploadsInput, func(*s3.ListMultipartUploadsOutput, bool) bool) error - ListObjectVersionsRequest(*s3.ListObjectVersionsInput) (*service.Request, *s3.ListObjectVersionsOutput) + ListObjectVersionsRequest(*s3.ListObjectVersionsInput) (*request.Request, *s3.ListObjectVersionsOutput) ListObjectVersions(*s3.ListObjectVersionsInput) (*s3.ListObjectVersionsOutput, error) ListObjectVersionsPages(*s3.ListObjectVersionsInput, func(*s3.ListObjectVersionsOutput, bool) bool) error - ListObjectsRequest(*s3.ListObjectsInput) (*service.Request, *s3.ListObjectsOutput) + ListObjectsRequest(*s3.ListObjectsInput) (*request.Request, *s3.ListObjectsOutput) ListObjects(*s3.ListObjectsInput) (*s3.ListObjectsOutput, error) ListObjectsPages(*s3.ListObjectsInput, func(*s3.ListObjectsOutput, bool) bool) error - ListPartsRequest(*s3.ListPartsInput) (*service.Request, *s3.ListPartsOutput) + ListPartsRequest(*s3.ListPartsInput) (*request.Request, *s3.ListPartsOutput) ListParts(*s3.ListPartsInput) (*s3.ListPartsOutput, error) ListPartsPages(*s3.ListPartsInput, func(*s3.ListPartsOutput, bool) bool) error - PutBucketAclRequest(*s3.PutBucketAclInput) (*service.Request, *s3.PutBucketAclOutput) + PutBucketAclRequest(*s3.PutBucketAclInput) (*request.Request, *s3.PutBucketAclOutput) PutBucketAcl(*s3.PutBucketAclInput) (*s3.PutBucketAclOutput, error) - PutBucketCorsRequest(*s3.PutBucketCorsInput) (*service.Request, *s3.PutBucketCorsOutput) + PutBucketCorsRequest(*s3.PutBucketCorsInput) (*request.Request, *s3.PutBucketCorsOutput) PutBucketCors(*s3.PutBucketCorsInput) (*s3.PutBucketCorsOutput, error) - PutBucketLifecycleRequest(*s3.PutBucketLifecycleInput) (*service.Request, *s3.PutBucketLifecycleOutput) + PutBucketLifecycleRequest(*s3.PutBucketLifecycleInput) (*request.Request, *s3.PutBucketLifecycleOutput) PutBucketLifecycle(*s3.PutBucketLifecycleInput) (*s3.PutBucketLifecycleOutput, error) - PutBucketLoggingRequest(*s3.PutBucketLoggingInput) (*service.Request, *s3.PutBucketLoggingOutput) + PutBucketLifecycleConfigurationRequest(*s3.PutBucketLifecycleConfigurationInput) (*request.Request, *s3.PutBucketLifecycleConfigurationOutput) + + PutBucketLifecycleConfiguration(*s3.PutBucketLifecycleConfigurationInput) (*s3.PutBucketLifecycleConfigurationOutput, error) + + PutBucketLoggingRequest(*s3.PutBucketLoggingInput) (*request.Request, *s3.PutBucketLoggingOutput) PutBucketLogging(*s3.PutBucketLoggingInput) (*s3.PutBucketLoggingOutput, error) - PutBucketNotificationRequest(*s3.PutBucketNotificationInput) (*service.Request, *s3.PutBucketNotificationOutput) + PutBucketNotificationRequest(*s3.PutBucketNotificationInput) (*request.Request, *s3.PutBucketNotificationOutput) PutBucketNotification(*s3.PutBucketNotificationInput) (*s3.PutBucketNotificationOutput, error) - PutBucketNotificationConfigurationRequest(*s3.PutBucketNotificationConfigurationInput) (*service.Request, *s3.PutBucketNotificationConfigurationOutput) + PutBucketNotificationConfigurationRequest(*s3.PutBucketNotificationConfigurationInput) (*request.Request, *s3.PutBucketNotificationConfigurationOutput) PutBucketNotificationConfiguration(*s3.PutBucketNotificationConfigurationInput) (*s3.PutBucketNotificationConfigurationOutput, error) - PutBucketPolicyRequest(*s3.PutBucketPolicyInput) (*service.Request, *s3.PutBucketPolicyOutput) + PutBucketPolicyRequest(*s3.PutBucketPolicyInput) (*request.Request, *s3.PutBucketPolicyOutput) PutBucketPolicy(*s3.PutBucketPolicyInput) (*s3.PutBucketPolicyOutput, error) - PutBucketReplicationRequest(*s3.PutBucketReplicationInput) (*service.Request, *s3.PutBucketReplicationOutput) + PutBucketReplicationRequest(*s3.PutBucketReplicationInput) (*request.Request, *s3.PutBucketReplicationOutput) PutBucketReplication(*s3.PutBucketReplicationInput) (*s3.PutBucketReplicationOutput, error) - PutBucketRequestPaymentRequest(*s3.PutBucketRequestPaymentInput) (*service.Request, *s3.PutBucketRequestPaymentOutput) + PutBucketRequestPaymentRequest(*s3.PutBucketRequestPaymentInput) (*request.Request, *s3.PutBucketRequestPaymentOutput) PutBucketRequestPayment(*s3.PutBucketRequestPaymentInput) (*s3.PutBucketRequestPaymentOutput, error) - PutBucketTaggingRequest(*s3.PutBucketTaggingInput) (*service.Request, *s3.PutBucketTaggingOutput) + PutBucketTaggingRequest(*s3.PutBucketTaggingInput) (*request.Request, *s3.PutBucketTaggingOutput) PutBucketTagging(*s3.PutBucketTaggingInput) (*s3.PutBucketTaggingOutput, error) - PutBucketVersioningRequest(*s3.PutBucketVersioningInput) (*service.Request, *s3.PutBucketVersioningOutput) + PutBucketVersioningRequest(*s3.PutBucketVersioningInput) (*request.Request, *s3.PutBucketVersioningOutput) PutBucketVersioning(*s3.PutBucketVersioningInput) (*s3.PutBucketVersioningOutput, error) - PutBucketWebsiteRequest(*s3.PutBucketWebsiteInput) (*service.Request, *s3.PutBucketWebsiteOutput) + PutBucketWebsiteRequest(*s3.PutBucketWebsiteInput) (*request.Request, *s3.PutBucketWebsiteOutput) PutBucketWebsite(*s3.PutBucketWebsiteInput) (*s3.PutBucketWebsiteOutput, error) - PutObjectRequest(*s3.PutObjectInput) (*service.Request, *s3.PutObjectOutput) + PutObjectRequest(*s3.PutObjectInput) (*request.Request, *s3.PutObjectOutput) PutObject(*s3.PutObjectInput) (*s3.PutObjectOutput, error) - PutObjectAclRequest(*s3.PutObjectAclInput) (*service.Request, *s3.PutObjectAclOutput) + PutObjectAclRequest(*s3.PutObjectAclInput) (*request.Request, *s3.PutObjectAclOutput) PutObjectAcl(*s3.PutObjectAclInput) (*s3.PutObjectAclOutput, error) - RestoreObjectRequest(*s3.RestoreObjectInput) (*service.Request, *s3.RestoreObjectOutput) + RestoreObjectRequest(*s3.RestoreObjectInput) (*request.Request, *s3.RestoreObjectOutput) RestoreObject(*s3.RestoreObjectInput) (*s3.RestoreObjectOutput, error) - UploadPartRequest(*s3.UploadPartInput) (*service.Request, *s3.UploadPartOutput) + UploadPartRequest(*s3.UploadPartInput) (*request.Request, *s3.UploadPartOutput) UploadPart(*s3.UploadPartInput) (*s3.UploadPartOutput, error) - UploadPartCopyRequest(*s3.UploadPartCopyInput) (*service.Request, *s3.UploadPartCopyOutput) + UploadPartCopyRequest(*s3.UploadPartCopyInput) (*request.Request, *s3.UploadPartCopyOutput) UploadPartCopy(*s3.UploadPartCopyInput) (*s3.UploadPartCopyOutput, error) } diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/s3iface/interface_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/s3iface/interface_test.go deleted file mode 100644 index cd672155a..000000000 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/s3iface/interface_test.go +++ /dev/null @@ -1,15 +0,0 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. - -package s3iface_test - -import ( - "testing" - - "github.com/aws/aws-sdk-go/service/s3" - "github.com/aws/aws-sdk-go/service/s3/s3iface" - "github.com/stretchr/testify/assert" -) - -func TestInterface(t *testing.T) { - assert.Implements(t, (*s3iface.S3API)(nil), s3.New(nil)) -} diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/s3manager/download.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/s3manager/download.go index 1711791e9..39825cfe6 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/s3manager/download.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/s3manager/download.go @@ -10,6 +10,7 @@ import ( "github.com/aws/aws-sdk-go/aws/awsutil" "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/service/s3/s3iface" ) // The default range of bytes to get at a time when using Download(). @@ -37,7 +38,7 @@ type DownloadOptions struct { // An S3 client to use when performing downloads. Leave this as nil to use // a default client. - S3 *s3.S3 + S3 s3iface.S3API } // NewDownloader creates a new Downloader structure that downloads an object diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/s3manager/download_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/s3manager/download_test.go deleted file mode 100644 index 4a6613c3e..000000000 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/s3manager/download_test.go +++ /dev/null @@ -1,141 +0,0 @@ -package s3manager_test - -import ( - "bytes" - "fmt" - "io/ioutil" - "net/http" - "regexp" - "strconv" - "sync" - "testing" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/service" - "github.com/aws/aws-sdk-go/internal/test/unit" - "github.com/aws/aws-sdk-go/service/s3" - "github.com/aws/aws-sdk-go/service/s3/s3manager" - "github.com/stretchr/testify/assert" -) - -var _ = unit.Imported - -func dlLoggingSvc(data []byte) (*s3.S3, *[]string, *[]string) { - var m sync.Mutex - names := []string{} - ranges := []string{} - - svc := s3.New(nil) - svc.Handlers.Send.Clear() - svc.Handlers.Send.PushBack(func(r *service.Request) { - m.Lock() - defer m.Unlock() - - names = append(names, r.Operation.Name) - ranges = append(ranges, *r.Params.(*s3.GetObjectInput).Range) - - rerng := regexp.MustCompile(`bytes=(\d+)-(\d+)`) - rng := rerng.FindStringSubmatch(r.HTTPRequest.Header.Get("Range")) - start, _ := strconv.ParseInt(rng[1], 10, 64) - fin, _ := strconv.ParseInt(rng[2], 10, 64) - fin++ - - if fin > int64(len(data)) { - fin = int64(len(data)) - } - - r.HTTPResponse = &http.Response{ - StatusCode: 200, - Body: ioutil.NopCloser(bytes.NewReader(data[start:fin])), - Header: http.Header{}, - } - r.HTTPResponse.Header.Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", - start, fin, len(data))) - }) - - return svc, &names, &ranges -} - -func TestDownloadOrder(t *testing.T) { - s, names, ranges := dlLoggingSvc(buf12MB) - - opts := &s3manager.DownloadOptions{S3: s, Concurrency: 1} - d := s3manager.NewDownloader(opts) - w := &aws.WriteAtBuffer{} - n, err := d.Download(w, &s3.GetObjectInput{ - Bucket: aws.String("bucket"), - Key: aws.String("key"), - }) - - assert.Nil(t, err) - assert.Equal(t, int64(len(buf12MB)), n) - assert.Equal(t, []string{"GetObject", "GetObject", "GetObject"}, *names) - assert.Equal(t, []string{"bytes=0-5242879", "bytes=5242880-10485759", "bytes=10485760-15728639"}, *ranges) - - count := 0 - for _, b := range w.Bytes() { - count += int(b) - } - assert.Equal(t, 0, count) -} - -func TestDownloadZero(t *testing.T) { - s, names, ranges := dlLoggingSvc([]byte{}) - - opts := &s3manager.DownloadOptions{S3: s} - d := s3manager.NewDownloader(opts) - w := &aws.WriteAtBuffer{} - n, err := d.Download(w, &s3.GetObjectInput{ - Bucket: aws.String("bucket"), - Key: aws.String("key"), - }) - - assert.Nil(t, err) - assert.Equal(t, int64(0), n) - assert.Equal(t, []string{"GetObject"}, *names) - assert.Equal(t, []string{"bytes=0-5242879"}, *ranges) -} - -func TestDownloadSetPartSize(t *testing.T) { - s, names, ranges := dlLoggingSvc([]byte{1, 2, 3}) - - opts := &s3manager.DownloadOptions{S3: s, PartSize: 1, Concurrency: 1} - d := s3manager.NewDownloader(opts) - w := &aws.WriteAtBuffer{} - n, err := d.Download(w, &s3.GetObjectInput{ - Bucket: aws.String("bucket"), - Key: aws.String("key"), - }) - - assert.Nil(t, err) - assert.Equal(t, int64(3), n) - assert.Equal(t, []string{"GetObject", "GetObject", "GetObject"}, *names) - assert.Equal(t, []string{"bytes=0-0", "bytes=1-1", "bytes=2-2"}, *ranges) - assert.Equal(t, []byte{1, 2, 3}, w.Bytes()) -} - -func TestDownloadError(t *testing.T) { - s, names, _ := dlLoggingSvc([]byte{1, 2, 3}) - opts := &s3manager.DownloadOptions{S3: s, PartSize: 1, Concurrency: 1} - - num := 0 - s.Handlers.Send.PushBack(func(r *service.Request) { - num++ - if num > 1 { - r.HTTPResponse.StatusCode = 400 - r.HTTPResponse.Body = ioutil.NopCloser(bytes.NewReader([]byte{})) - } - }) - - d := s3manager.NewDownloader(opts) - w := &aws.WriteAtBuffer{} - n, err := d.Download(w, &s3.GetObjectInput{ - Bucket: aws.String("bucket"), - Key: aws.String("key"), - }) - - assert.NotNil(t, err) - assert.Equal(t, int64(1), n) - assert.Equal(t, []string{"GetObject", "GetObject"}, *names) - assert.Equal(t, []byte{1}, w.Bytes()) -} diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/s3manager/upload.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/s3manager/upload.go index 65846c30d..6749353f9 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/s3manager/upload.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/s3manager/upload.go @@ -11,6 +11,7 @@ import ( "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/aws/awsutil" "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/service/s3/s3iface" ) // The maximum allowed number of parts in a multi-part upload on Amazon S3. @@ -215,7 +216,7 @@ type UploadOptions struct { // The client to use when uploading to S3. Leave this as nil to use the // default S3 client. - S3 *s3.S3 + S3 s3iface.S3API } // NewUploader creates a new Uploader object to upload data to S3. Pass in diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/s3manager/upload_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/s3manager/upload_test.go deleted file mode 100644 index 2fc19de40..000000000 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/s3manager/upload_test.go +++ /dev/null @@ -1,463 +0,0 @@ -package s3manager_test - -import ( - "bytes" - "fmt" - "io" - "io/ioutil" - "net/http" - "sort" - "sync" - "testing" - "strings" - "net/http/httptest" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/awsutil" - "github.com/aws/aws-sdk-go/aws/service" - "github.com/aws/aws-sdk-go/internal/test/unit" - "github.com/aws/aws-sdk-go/service/s3" - "github.com/aws/aws-sdk-go/service/s3/s3manager" - "github.com/stretchr/testify/assert" -) - -var _ = unit.Imported -var buf12MB = make([]byte, 1024*1024*12) -var buf2MB = make([]byte, 1024*1024*2) - -var emptyList = []string{} - -func val(i interface{}, s string) interface{} { - return awsutil.ValuesAtPath(i, s)[0] -} - -func contains(src []string, s string) bool { - for _, v := range src { - if s == v { - return true - } - } - return false -} - -func loggingSvc(ignoreOps []string) (*s3.S3, *[]string, *[]interface{}) { - var m sync.Mutex - partNum := 0 - names := []string{} - params := []interface{}{} - svc := s3.New(nil) - svc.Handlers.Unmarshal.Clear() - svc.Handlers.UnmarshalMeta.Clear() - svc.Handlers.UnmarshalError.Clear() - svc.Handlers.Send.Clear() - svc.Handlers.Send.PushBack(func(r *service.Request) { - m.Lock() - defer m.Unlock() - - if !contains(ignoreOps, r.Operation.Name) { - names = append(names, r.Operation.Name) - params = append(params, r.Params) - } - - r.HTTPResponse = &http.Response{ - StatusCode: 200, - Body: ioutil.NopCloser(bytes.NewReader([]byte{})), - } - - switch data := r.Data.(type) { - case *s3.CreateMultipartUploadOutput: - data.UploadId = aws.String("UPLOAD-ID") - case *s3.UploadPartOutput: - partNum++ - data.ETag = aws.String(fmt.Sprintf("ETAG%d", partNum)) - case *s3.CompleteMultipartUploadOutput: - data.Location = aws.String("https://location") - } - }) - - return svc, &names, ¶ms -} - -func buflen(i interface{}) int { - r := i.(io.Reader) - b, _ := ioutil.ReadAll(r) - return len(b) -} - -func TestUploadOrderMulti(t *testing.T) { - s, ops, args := loggingSvc(emptyList) - mgr := s3manager.NewUploader(&s3manager.UploadOptions{S3: s}) - resp, err := mgr.Upload(&s3manager.UploadInput{ - Bucket: aws.String("Bucket"), - Key: aws.String("Key"), - Body: bytes.NewReader(buf12MB), - ServerSideEncryption: aws.String("AES256"), - ContentType: aws.String("content/type"), - }) - - assert.NoError(t, err) - assert.Equal(t, []string{"CreateMultipartUpload", "UploadPart", "UploadPart", "UploadPart", "CompleteMultipartUpload"}, *ops) - assert.Equal(t, "https://location", resp.Location) - assert.Equal(t, "UPLOAD-ID", resp.UploadID) - - // Validate input values - - // UploadPart - assert.Equal(t, "UPLOAD-ID", val((*args)[1], "UploadId")) - assert.Equal(t, "UPLOAD-ID", val((*args)[2], "UploadId")) - assert.Equal(t, "UPLOAD-ID", val((*args)[3], "UploadId")) - - // CompleteMultipartUpload - assert.Equal(t, "UPLOAD-ID", val((*args)[4], "UploadId")) - assert.Equal(t, int64(1), val((*args)[4], "MultipartUpload.Parts[0].PartNumber")) - assert.Equal(t, int64(2), val((*args)[4], "MultipartUpload.Parts[1].PartNumber")) - assert.Equal(t, int64(3), val((*args)[4], "MultipartUpload.Parts[2].PartNumber")) - assert.Regexp(t, `^ETAG\d+$`, val((*args)[4], "MultipartUpload.Parts[0].ETag")) - assert.Regexp(t, `^ETAG\d+$`, val((*args)[4], "MultipartUpload.Parts[1].ETag")) - assert.Regexp(t, `^ETAG\d+$`, val((*args)[4], "MultipartUpload.Parts[2].ETag")) - - // Custom headers - assert.Equal(t, "AES256", val((*args)[0], "ServerSideEncryption")) - assert.Equal(t, "content/type", val((*args)[0], "ContentType")) -} - -func TestUploadOrderMultiDifferentPartSize(t *testing.T) { - s, ops, args := loggingSvc(emptyList) - mgr := s3manager.NewUploader(&s3manager.UploadOptions{ - S3: s, - PartSize: 1024 * 1024 * 7, - Concurrency: 1, - }) - _, err := mgr.Upload(&s3manager.UploadInput{ - Bucket: aws.String("Bucket"), - Key: aws.String("Key"), - Body: bytes.NewReader(buf12MB), - }) - - assert.NoError(t, err) - assert.Equal(t, []string{"CreateMultipartUpload", "UploadPart", "UploadPart", "CompleteMultipartUpload"}, *ops) - - // Part lengths - assert.Equal(t, 1024*1024*7, buflen(val((*args)[1], "Body"))) - assert.Equal(t, 1024*1024*5, buflen(val((*args)[2], "Body"))) -} - -func TestUploadIncreasePartSize(t *testing.T) { - s3manager.MaxUploadParts = 2 - defer func() { s3manager.MaxUploadParts = 10000 }() - - s, ops, args := loggingSvc(emptyList) - opts := &s3manager.UploadOptions{S3: s, Concurrency: 1} - mgr := s3manager.NewUploader(opts) - _, err := mgr.Upload(&s3manager.UploadInput{ - Bucket: aws.String("Bucket"), - Key: aws.String("Key"), - Body: bytes.NewReader(buf12MB), - }) - - assert.NoError(t, err) - assert.Equal(t, int64(0), opts.PartSize) // don't modify orig options - assert.Equal(t, []string{"CreateMultipartUpload", "UploadPart", "UploadPart", "CompleteMultipartUpload"}, *ops) - - // Part lengths - assert.Equal(t, 1024*1024*6, buflen(val((*args)[1], "Body"))) - assert.Equal(t, 1024*1024*6, buflen(val((*args)[2], "Body"))) -} - -func TestUploadFailIfPartSizeTooSmall(t *testing.T) { - opts := &s3manager.UploadOptions{PartSize: 5} - mgr := s3manager.NewUploader(opts) - resp, err := mgr.Upload(&s3manager.UploadInput{ - Bucket: aws.String("Bucket"), - Key: aws.String("Key"), - Body: bytes.NewReader(buf12MB), - }) - - assert.Nil(t, resp) - assert.NotNil(t, err) - - aerr := err.(awserr.Error) - assert.Equal(t, "ConfigError", aerr.Code()) - assert.Contains(t, aerr.Message(), "part size must be at least") -} - -func TestUploadOrderSingle(t *testing.T) { - s, ops, args := loggingSvc(emptyList) - mgr := s3manager.NewUploader(&s3manager.UploadOptions{S3: s}) - resp, err := mgr.Upload(&s3manager.UploadInput{ - Bucket: aws.String("Bucket"), - Key: aws.String("Key"), - Body: bytes.NewReader(buf2MB), - ServerSideEncryption: aws.String("AES256"), - ContentType: aws.String("content/type"), - }) - - assert.NoError(t, err) - assert.Equal(t, []string{"PutObject"}, *ops) - assert.NotEqual(t, "", resp.Location) - assert.Equal(t, "", resp.UploadID) - assert.Equal(t, "AES256", val((*args)[0], "ServerSideEncryption")) - assert.Equal(t, "content/type", val((*args)[0], "ContentType")) -} - -func TestUploadOrderSingleFailure(t *testing.T) { - s, ops, _ := loggingSvc(emptyList) - s.Handlers.Send.PushBack(func(r *service.Request) { - r.HTTPResponse.StatusCode = 400 - }) - mgr := s3manager.NewUploader(&s3manager.UploadOptions{S3: s}) - resp, err := mgr.Upload(&s3manager.UploadInput{ - Bucket: aws.String("Bucket"), - Key: aws.String("Key"), - Body: bytes.NewReader(buf2MB), - }) - - assert.Error(t, err) - assert.Equal(t, []string{"PutObject"}, *ops) - assert.Nil(t, resp) -} - -func TestUploadOrderZero(t *testing.T) { - s, ops, args := loggingSvc(emptyList) - mgr := s3manager.NewUploader(&s3manager.UploadOptions{S3: s}) - resp, err := mgr.Upload(&s3manager.UploadInput{ - Bucket: aws.String("Bucket"), - Key: aws.String("Key"), - Body: bytes.NewReader(make([]byte, 0)), - }) - - assert.NoError(t, err) - assert.Equal(t, []string{"PutObject"}, *ops) - assert.NotEqual(t, "", resp.Location) - assert.Equal(t, "", resp.UploadID) - assert.Equal(t, 0, buflen(val((*args)[0], "Body"))) -} - -func TestUploadOrderMultiFailure(t *testing.T) { - s, ops, _ := loggingSvc(emptyList) - s.Handlers.Send.PushBack(func(r *service.Request) { - switch t := r.Data.(type) { - case *s3.UploadPartOutput: - if *t.ETag == "ETAG2" { - r.HTTPResponse.StatusCode = 400 - } - } - }) - - mgr := s3manager.NewUploader(&s3manager.UploadOptions{S3: s, Concurrency: 1}) - _, err := mgr.Upload(&s3manager.UploadInput{ - Bucket: aws.String("Bucket"), - Key: aws.String("Key"), - Body: bytes.NewReader(buf12MB), - }) - - assert.Error(t, err) - assert.Equal(t, []string{"CreateMultipartUpload", "UploadPart", "UploadPart", "AbortMultipartUpload"}, *ops) -} - -func TestUploadOrderMultiFailureOnComplete(t *testing.T) { - s, ops, _ := loggingSvc(emptyList) - s.Handlers.Send.PushBack(func(r *service.Request) { - switch r.Data.(type) { - case *s3.CompleteMultipartUploadOutput: - r.HTTPResponse.StatusCode = 400 - } - }) - - mgr := s3manager.NewUploader(&s3manager.UploadOptions{S3: s, Concurrency: 1}) - _, err := mgr.Upload(&s3manager.UploadInput{ - Bucket: aws.String("Bucket"), - Key: aws.String("Key"), - Body: bytes.NewReader(buf12MB), - }) - - assert.Error(t, err) - assert.Equal(t, []string{"CreateMultipartUpload", "UploadPart", "UploadPart", - "UploadPart", "CompleteMultipartUpload", "AbortMultipartUpload"}, *ops) -} - -func TestUploadOrderMultiFailureOnCreate(t *testing.T) { - s, ops, _ := loggingSvc(emptyList) - s.Handlers.Send.PushBack(func(r *service.Request) { - switch r.Data.(type) { - case *s3.CreateMultipartUploadOutput: - r.HTTPResponse.StatusCode = 400 - } - }) - - mgr := s3manager.NewUploader(&s3manager.UploadOptions{S3: s}) - _, err := mgr.Upload(&s3manager.UploadInput{ - Bucket: aws.String("Bucket"), - Key: aws.String("Key"), - Body: bytes.NewReader(make([]byte, 1024*1024*12)), - }) - - assert.Error(t, err) - assert.Equal(t, []string{"CreateMultipartUpload"}, *ops) -} - -func TestUploadOrderMultiFailureLeaveParts(t *testing.T) { - s, ops, _ := loggingSvc(emptyList) - s.Handlers.Send.PushBack(func(r *service.Request) { - switch data := r.Data.(type) { - case *s3.UploadPartOutput: - if *data.ETag == "ETAG2" { - r.HTTPResponse.StatusCode = 400 - } - } - }) - - mgr := s3manager.NewUploader(&s3manager.UploadOptions{ - S3: s, - Concurrency: 1, - LeavePartsOnError: true, - }) - _, err := mgr.Upload(&s3manager.UploadInput{ - Bucket: aws.String("Bucket"), - Key: aws.String("Key"), - Body: bytes.NewReader(make([]byte, 1024*1024*12)), - }) - - assert.Error(t, err) - assert.Equal(t, []string{"CreateMultipartUpload", "UploadPart", "UploadPart"}, *ops) -} - -type failreader struct { - times int - failCount int -} - -func (f *failreader) Read(b []byte) (int, error) { - f.failCount++ - if f.failCount >= f.times { - return 0, fmt.Errorf("random failure") - } - return len(b), nil -} - -func TestUploadOrderReadFail1(t *testing.T) { - s, ops, _ := loggingSvc(emptyList) - mgr := s3manager.NewUploader(&s3manager.UploadOptions{S3: s}) - _, err := mgr.Upload(&s3manager.UploadInput{ - Bucket: aws.String("Bucket"), - Key: aws.String("Key"), - Body: &failreader{times: 1}, - }) - - assert.Equal(t, "ReadRequestBody", err.(awserr.Error).Code()) - assert.EqualError(t, err.(awserr.Error).OrigErr(), "random failure") - assert.Equal(t, []string{}, *ops) -} - -func TestUploadOrderReadFail2(t *testing.T) { - s, ops, _ := loggingSvc([]string{"UploadPart"}) - mgr := s3manager.NewUploader(&s3manager.UploadOptions{S3: s, Concurrency: 1}) - _, err := mgr.Upload(&s3manager.UploadInput{ - Bucket: aws.String("Bucket"), - Key: aws.String("Key"), - Body: &failreader{times: 2}, - }) - - assert.Equal(t, "ReadRequestBody", err.(awserr.Error).Code()) - assert.EqualError(t, err.(awserr.Error).OrigErr(), "random failure") - assert.Equal(t, []string{"CreateMultipartUpload", "AbortMultipartUpload"}, *ops) -} - -type sizedReader struct { - size int - cur int -} - -func (s *sizedReader) Read(p []byte) (n int, err error) { - if s.cur >= s.size { - return 0, io.EOF - } - - n = len(p) - s.cur += len(p) - if s.cur > s.size { - n -= s.cur - s.size - } - - return -} - -func TestUploadOrderMultiBufferedReader(t *testing.T) { - s, ops, args := loggingSvc(emptyList) - mgr := s3manager.NewUploader(&s3manager.UploadOptions{S3: s}) - _, err := mgr.Upload(&s3manager.UploadInput{ - Bucket: aws.String("Bucket"), - Key: aws.String("Key"), - Body: &sizedReader{size: 1024 * 1024 * 12}, - }) - - assert.NoError(t, err) - assert.Equal(t, []string{"CreateMultipartUpload", "UploadPart", "UploadPart", "UploadPart", "CompleteMultipartUpload"}, *ops) - - // Part lengths - parts := []int{ - buflen(val((*args)[1], "Body")), - buflen(val((*args)[2], "Body")), - buflen(val((*args)[3], "Body")), - } - sort.Ints(parts) - assert.Equal(t, []int{1024 * 1024 * 2, 1024 * 1024 * 5, 1024 * 1024 * 5}, parts) -} - -func TestUploadOrderMultiBufferedReaderExceedTotalParts(t *testing.T) { - s3manager.MaxUploadParts = 2 - defer func() { s3manager.MaxUploadParts = 10000 }() - s, ops, _ := loggingSvc([]string{"UploadPart"}) - mgr := s3manager.NewUploader(&s3manager.UploadOptions{S3: s, Concurrency: 1}) - resp, err := mgr.Upload(&s3manager.UploadInput{ - Bucket: aws.String("Bucket"), - Key: aws.String("Key"), - Body: &sizedReader{size: 1024 * 1024 * 12}, - }) - - assert.Error(t, err) - assert.Nil(t, resp) - assert.Equal(t, []string{"CreateMultipartUpload", "AbortMultipartUpload"}, *ops) - - aerr := err.(awserr.Error) - assert.Equal(t, "TotalPartsExceeded", aerr.Code()) - assert.Contains(t, aerr.Message(), "exceeded total allowed parts (2)") -} - -func TestUploadOrderSingleBufferedReader(t *testing.T) { - s, ops, _ := loggingSvc(emptyList) - mgr := s3manager.NewUploader(&s3manager.UploadOptions{S3: s}) - resp, err := mgr.Upload(&s3manager.UploadInput{ - Bucket: aws.String("Bucket"), - Key: aws.String("Key"), - Body: &sizedReader{size: 1024 * 1024 * 2}, - }) - - assert.NoError(t, err) - assert.Equal(t, []string{"PutObject"}, *ops) - assert.NotEqual(t, "", resp.Location) - assert.Equal(t, "", resp.UploadID) -} - -func TestUploadZeroLenObject(t *testing.T) { - requestMade := false - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request){ - requestMade = true - w.WriteHeader(http.StatusOK) - })) - svc := s3.New(&aws.Config{ - Endpoint: aws.String(server.URL), - }) - mgr := s3manager.NewUploader(&s3manager.UploadOptions{S3: svc}) - resp, err := mgr.Upload(&s3manager.UploadInput{ - Bucket: aws.String("Bucket"), - Key: aws.String("Key"), - Body: strings.NewReader(""), - }) - - assert.NoError(t, err) - assert.True(t, requestMade) - assert.NotEqual(t, "", resp.Location) - assert.Equal(t, "", resp.UploadID) -} diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/service.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/service.go index f70bd4517..daeca34c2 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/service.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/service.go @@ -5,7 +5,9 @@ package s3 import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/defaults" + "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/aws/service" + "github.com/aws/aws-sdk-go/aws/service/serviceinfo" "github.com/aws/aws-sdk-go/internal/protocol/restxml" "github.com/aws/aws-sdk-go/internal/signer/v4" ) @@ -19,14 +21,16 @@ type S3 struct { var initService func(*service.Service) // Used for custom request initialization logic -var initRequest func(*service.Request) +var initRequest func(*request.Request) // New returns a new S3 client. func New(config *aws.Config) *S3 { service := &service.Service{ - Config: defaults.DefaultConfig.Merge(config), - ServiceName: "s3", - APIVersion: "2006-03-01", + ServiceInfo: serviceinfo.ServiceInfo{ + Config: defaults.DefaultConfig.Merge(config), + ServiceName: "s3", + APIVersion: "2006-03-01", + }, } service.Initialize() @@ -47,8 +51,8 @@ func New(config *aws.Config) *S3 { // newRequest creates a new request for a S3 operation and runs any // custom request initialization. -func (c *S3) newRequest(op *service.Operation, params, data interface{}) *service.Request { - req := service.NewRequest(c.Service, op, params, data) +func (c *S3) newRequest(op *request.Operation, params, data interface{}) *request.Request { + req := c.NewRequest(op, params, data) // Run custom request initialization if present if initRequest != nil { diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/sse.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/sse.go index 7c2e945a3..5ab9ca2a7 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/sse.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/sse.go @@ -6,12 +6,12 @@ import ( "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/aws/awsutil" - "github.com/aws/aws-sdk-go/aws/service" + "github.com/aws/aws-sdk-go/aws/request" ) var errSSERequiresSSL = awserr.New("ConfigError", "cannot send SSE keys over HTTP.", nil) -func validateSSERequiresSSL(r *service.Request) { +func validateSSERequiresSSL(r *request.Request) { if r.HTTPRequest.URL.Scheme != "https" { p := awsutil.ValuesAtPath(r.Params, "SSECustomerKey||CopySourceSSECustomerKey") if len(p) > 0 { @@ -20,7 +20,7 @@ func validateSSERequiresSSL(r *service.Request) { } } -func computeSSEKeys(r *service.Request) { +func computeSSEKeys(r *request.Request) { headers := []string{ "x-amz-server-side-encryption-customer-key", "x-amz-copy-source-server-side-encryption-customer-key", diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/sse_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/sse_test.go deleted file mode 100644 index 4e6ecdce3..000000000 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/sse_test.go +++ /dev/null @@ -1,81 +0,0 @@ -package s3_test - -import ( - "testing" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/internal/test/unit" - "github.com/aws/aws-sdk-go/service/s3" - "github.com/stretchr/testify/assert" -) - -var _ = unit.Imported - -func TestSSECustomerKeyOverHTTPError(t *testing.T) { - s := s3.New(&aws.Config{DisableSSL: aws.Bool(true)}) - req, _ := s.CopyObjectRequest(&s3.CopyObjectInput{ - Bucket: aws.String("bucket"), - CopySource: aws.String("bucket/source"), - Key: aws.String("dest"), - SSECustomerKey: aws.String("key"), - }) - err := req.Build() - - assert.Error(t, err) - assert.Equal(t, "ConfigError", err.(awserr.Error).Code()) - assert.Contains(t, err.(awserr.Error).Message(), "cannot send SSE keys over HTTP") -} - -func TestCopySourceSSECustomerKeyOverHTTPError(t *testing.T) { - s := s3.New(&aws.Config{DisableSSL: aws.Bool(true)}) - req, _ := s.CopyObjectRequest(&s3.CopyObjectInput{ - Bucket: aws.String("bucket"), - CopySource: aws.String("bucket/source"), - Key: aws.String("dest"), - CopySourceSSECustomerKey: aws.String("key"), - }) - err := req.Build() - - assert.Error(t, err) - assert.Equal(t, "ConfigError", err.(awserr.Error).Code()) - assert.Contains(t, err.(awserr.Error).Message(), "cannot send SSE keys over HTTP") -} - -func TestComputeSSEKeys(t *testing.T) { - s := s3.New(nil) - req, _ := s.CopyObjectRequest(&s3.CopyObjectInput{ - Bucket: aws.String("bucket"), - CopySource: aws.String("bucket/source"), - Key: aws.String("dest"), - SSECustomerKey: aws.String("key"), - CopySourceSSECustomerKey: aws.String("key"), - }) - err := req.Build() - - assert.NoError(t, err) - assert.Equal(t, "a2V5", req.HTTPRequest.Header.Get("x-amz-server-side-encryption-customer-key")) - assert.Equal(t, "a2V5", req.HTTPRequest.Header.Get("x-amz-copy-source-server-side-encryption-customer-key")) - assert.Equal(t, "PG4LipwVIkqCKLmpjKFTHQ==", req.HTTPRequest.Header.Get("x-amz-server-side-encryption-customer-key-md5")) - assert.Equal(t, "PG4LipwVIkqCKLmpjKFTHQ==", req.HTTPRequest.Header.Get("x-amz-copy-source-server-side-encryption-customer-key-md5")) -} - -func TestComputeSSEKeysShortcircuit(t *testing.T) { - s := s3.New(nil) - req, _ := s.CopyObjectRequest(&s3.CopyObjectInput{ - Bucket: aws.String("bucket"), - CopySource: aws.String("bucket/source"), - Key: aws.String("dest"), - SSECustomerKey: aws.String("key"), - CopySourceSSECustomerKey: aws.String("key"), - SSECustomerKeyMD5: aws.String("MD5"), - CopySourceSSECustomerKeyMD5: aws.String("MD5"), - }) - err := req.Build() - - assert.NoError(t, err) - assert.Equal(t, "a2V5", req.HTTPRequest.Header.Get("x-amz-server-side-encryption-customer-key")) - assert.Equal(t, "a2V5", req.HTTPRequest.Header.Get("x-amz-copy-source-server-side-encryption-customer-key")) - assert.Equal(t, "MD5", req.HTTPRequest.Header.Get("x-amz-server-side-encryption-customer-key-md5")) - assert.Equal(t, "MD5", req.HTTPRequest.Header.Get("x-amz-copy-source-server-side-encryption-customer-key-md5")) -} diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/statusok_error.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/statusok_error.go new file mode 100644 index 000000000..ce65fcdaf --- /dev/null +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/statusok_error.go @@ -0,0 +1,36 @@ +package s3 + +import ( + "bytes" + "io/ioutil" + "net/http" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/awserr" + "github.com/aws/aws-sdk-go/aws/request" +) + +func copyMultipartStatusOKUnmarhsalError(r *request.Request) { + b, err := ioutil.ReadAll(r.HTTPResponse.Body) + if err != nil { + r.Error = awserr.New("SerializationError", "unable to read response body", err) + return + } + body := bytes.NewReader(b) + r.HTTPResponse.Body = aws.ReadSeekCloser(body) + defer r.HTTPResponse.Body.(aws.ReaderSeekerCloser).Seek(0, 0) + + if body.Len() == 0 { + // If there is no body don't attempt to parse the body. + return + } + + unmarshalError(r) + if err, ok := r.Error.(awserr.Error); ok && err != nil { + if err.Code() == "SerializationError" { + r.Error = nil + return + } + r.HTTPResponse.StatusCode = http.StatusServiceUnavailable + } +} diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/unmarshal_error.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/unmarshal_error.go index 1f80dc914..ed4505bf3 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/unmarshal_error.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/unmarshal_error.go @@ -2,11 +2,14 @@ package s3 import ( "encoding/xml" + "fmt" "io" + "net/http" "strings" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/service" + "github.com/aws/aws-sdk-go/aws/request" ) type xmlErrorResponse struct { @@ -15,9 +18,15 @@ type xmlErrorResponse struct { Message string `xml:"Message"` } -func unmarshalError(r *service.Request) { +func unmarshalError(r *request.Request) { defer r.HTTPResponse.Body.Close() + if r.HTTPResponse.StatusCode == http.StatusMovedPermanently { + r.Error = awserr.New("BucketRegionError", + fmt.Sprintf("incorrect region, the bucket is not in '%s' region", aws.StringValue(r.Service.Config.Region)), nil) + return + } + if r.HTTPResponse.ContentLength == int64(0) { // No body, use status code to generate an awserr.Error r.Error = awserr.NewRequestFailure( diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/unmarshal_error_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/unmarshal_error_test.go deleted file mode 100644 index acc1aae1b..000000000 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/unmarshal_error_test.go +++ /dev/null @@ -1,54 +0,0 @@ -package s3_test - -import ( - "bytes" - "io/ioutil" - "net/http" - "testing" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/service" - "github.com/aws/aws-sdk-go/internal/test/unit" - "github.com/aws/aws-sdk-go/service/s3" - "github.com/stretchr/testify/assert" -) - -var _ = unit.Imported - -var s3StatusCodeErrorTests = []struct { - scode int - status string - body string - code string - message string -}{ - {301, "Moved Permanently", "", "MovedPermanently", "Moved Permanently"}, - {403, "Forbidden", "", "Forbidden", "Forbidden"}, - {400, "Bad Request", "", "BadRequest", "Bad Request"}, - {404, "Not Found", "", "NotFound", "Not Found"}, - {500, "Internal Error", "", "InternalError", "Internal Error"}, -} - -func TestStatusCodeError(t *testing.T) { - for _, test := range s3StatusCodeErrorTests { - s := s3.New(nil) - s.Handlers.Send.Clear() - s.Handlers.Send.PushBack(func(r *service.Request) { - body := ioutil.NopCloser(bytes.NewReader([]byte(test.body))) - r.HTTPResponse = &http.Response{ - ContentLength: int64(len(test.body)), - StatusCode: test.scode, - Status: test.status, - Body: body, - } - }) - _, err := s.PutBucketAcl(&s3.PutBucketAclInput{ - Bucket: aws.String("bucket"), ACL: aws.String("public-read"), - }) - - assert.Error(t, err) - assert.Equal(t, test.code, err.(awserr.Error).Code()) - assert.Equal(t, test.message, err.(awserr.Error).Message()) - } -} diff --git a/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/add_child_test.go b/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/add_child_test.go deleted file mode 100644 index 26223ff1c..000000000 --- a/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/add_child_test.go +++ /dev/null @@ -1,73 +0,0 @@ -package etcd - -import "testing" - -func TestAddChild(t *testing.T) { - c := NewClient(nil) - defer func() { - c.Delete("fooDir", true) - c.Delete("nonexistentDir", true) - }() - - c.CreateDir("fooDir", 5) - - _, err := c.AddChild("fooDir", "v0", 5) - if err != nil { - t.Fatal(err) - } - - _, err = c.AddChild("fooDir", "v1", 5) - if err != nil { - t.Fatal(err) - } - - resp, err := c.Get("fooDir", true, false) - // The child with v0 should proceed the child with v1 because it's added - // earlier, so it should have a lower key. - if !(len(resp.Node.Nodes) == 2 && (resp.Node.Nodes[0].Value == "v0" && resp.Node.Nodes[1].Value == "v1")) { - t.Fatalf("AddChild 1 failed. There should be two chlidren whose values are v0 and v1, respectively."+ - " The response was: %#v", resp) - } - - // Creating a child under a nonexistent directory should succeed. - // The directory should be created. - resp, err = c.AddChild("nonexistentDir", "foo", 5) - if err != nil { - t.Fatal(err) - } -} - -func TestAddChildDir(t *testing.T) { - c := NewClient(nil) - defer func() { - c.Delete("fooDir", true) - c.Delete("nonexistentDir", true) - }() - - c.CreateDir("fooDir", 5) - - _, err := c.AddChildDir("fooDir", 5) - if err != nil { - t.Fatal(err) - } - - _, err = c.AddChildDir("fooDir", 5) - if err != nil { - t.Fatal(err) - } - - resp, err := c.Get("fooDir", true, false) - // The child with v0 should proceed the child with v1 because it's added - // earlier, so it should have a lower key. - if !(len(resp.Node.Nodes) == 2 && (len(resp.Node.Nodes[0].Nodes) == 0 && len(resp.Node.Nodes[1].Nodes) == 0)) { - t.Fatalf("AddChildDir 1 failed. There should be two chlidren whose values are v0 and v1, respectively."+ - " The response was: %#v", resp) - } - - // Creating a child under a nonexistent directory should succeed. - // The directory should be created. - resp, err = c.AddChildDir("nonexistentDir", 5) - if err != nil { - t.Fatal(err) - } -} diff --git a/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/client_test.go b/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/client_test.go deleted file mode 100644 index 4720d8d69..000000000 --- a/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/client_test.go +++ /dev/null @@ -1,108 +0,0 @@ -package etcd - -import ( - "encoding/json" - "fmt" - "net" - "net/url" - "os" - "testing" -) - -// To pass this test, we need to create a cluster of 3 machines -// The server should be listening on localhost:4001, 4002, 4003 -func TestSync(t *testing.T) { - fmt.Println("Make sure there are three nodes at 0.0.0.0:4001-4003") - - // Explicit trailing slash to ensure this doesn't reproduce: - // https://github.com/coreos/go-etcd/issues/82 - c := NewClient([]string{"http://127.0.0.1:4001/"}) - - success := c.SyncCluster() - if !success { - t.Fatal("cannot sync machines") - } - - for _, m := range c.GetCluster() { - u, err := url.Parse(m) - if err != nil { - t.Fatal(err) - } - if u.Scheme != "http" { - t.Fatal("scheme must be http") - } - - host, _, err := net.SplitHostPort(u.Host) - if err != nil { - t.Fatal(err) - } - if host != "localhost" { - t.Fatal("Host must be localhost") - } - } - - badMachines := []string{"abc", "edef"} - - success = c.SetCluster(badMachines) - - if success { - t.Fatal("should not sync on bad machines") - } - - goodMachines := []string{"127.0.0.1:4002"} - - success = c.SetCluster(goodMachines) - - if !success { - t.Fatal("cannot sync machines") - } else { - fmt.Println(c.cluster.Machines) - } - -} - -func TestPersistence(t *testing.T) { - c := NewClient(nil) - c.SyncCluster() - - fo, err := os.Create("config.json") - if err != nil { - t.Fatal(err) - } - defer func() { - if err := fo.Close(); err != nil { - panic(err) - } - }() - - c.SetPersistence(fo) - err = c.saveConfig() - if err != nil { - t.Fatal(err) - } - - c2, err := NewClientFromFile("config.json") - if err != nil { - t.Fatal(err) - } - - // Verify that the two clients have the same config - b1, _ := json.Marshal(c) - b2, _ := json.Marshal(c2) - - if string(b1) != string(b2) { - t.Fatalf("The two configs should be equal!") - } -} - -func TestClientRetry(t *testing.T) { - c := NewClient([]string{"http://strange", "http://127.0.0.1:4001"}) - // use first endpoint as the picked url - c.cluster.picked = 0 - if _, err := c.Set("foo", "bar", 5); err != nil { - t.Fatal(err) - } - if _, err := c.Delete("foo", true); err != nil { - t.Fatal(err) - } -} diff --git a/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/compare_and_delete_test.go b/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/compare_and_delete_test.go deleted file mode 100644 index 223e50f29..000000000 --- a/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/compare_and_delete_test.go +++ /dev/null @@ -1,46 +0,0 @@ -package etcd - -import ( - "testing" -) - -func TestCompareAndDelete(t *testing.T) { - c := NewClient(nil) - defer func() { - c.Delete("foo", true) - }() - - c.Set("foo", "bar", 5) - - // This should succeed an correct prevValue - resp, err := c.CompareAndDelete("foo", "bar", 0) - if err != nil { - t.Fatal(err) - } - if !(resp.PrevNode.Value == "bar" && resp.PrevNode.Key == "/foo" && resp.PrevNode.TTL == 5) { - t.Fatalf("CompareAndDelete 1 prevNode failed: %#v", resp) - } - - resp, _ = c.Set("foo", "bar", 5) - // This should fail because it gives an incorrect prevValue - _, err = c.CompareAndDelete("foo", "xxx", 0) - if err == nil { - t.Fatalf("CompareAndDelete 2 should have failed. The response is: %#v", resp) - } - - // This should succeed because it gives an correct prevIndex - resp, err = c.CompareAndDelete("foo", "", resp.Node.ModifiedIndex) - if err != nil { - t.Fatal(err) - } - if !(resp.PrevNode.Value == "bar" && resp.PrevNode.Key == "/foo" && resp.PrevNode.TTL == 5) { - t.Fatalf("CompareAndSwap 3 prevNode failed: %#v", resp) - } - - c.Set("foo", "bar", 5) - // This should fail because it gives an incorrect prevIndex - resp, err = c.CompareAndDelete("foo", "", 29817514) - if err == nil { - t.Fatalf("CompareAndDelete 4 should have failed. The response is: %#v", resp) - } -} diff --git a/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/compare_and_swap_test.go b/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/compare_and_swap_test.go deleted file mode 100644 index 14a1b00f5..000000000 --- a/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/compare_and_swap_test.go +++ /dev/null @@ -1,57 +0,0 @@ -package etcd - -import ( - "testing" -) - -func TestCompareAndSwap(t *testing.T) { - c := NewClient(nil) - defer func() { - c.Delete("foo", true) - }() - - c.Set("foo", "bar", 5) - - // This should succeed - resp, err := c.CompareAndSwap("foo", "bar2", 5, "bar", 0) - if err != nil { - t.Fatal(err) - } - if !(resp.Node.Value == "bar2" && resp.Node.Key == "/foo" && resp.Node.TTL == 5) { - t.Fatalf("CompareAndSwap 1 failed: %#v", resp) - } - - if !(resp.PrevNode.Value == "bar" && resp.PrevNode.Key == "/foo" && resp.PrevNode.TTL == 5) { - t.Fatalf("CompareAndSwap 1 prevNode failed: %#v", resp) - } - - // This should fail because it gives an incorrect prevValue - resp, err = c.CompareAndSwap("foo", "bar3", 5, "xxx", 0) - if err == nil { - t.Fatalf("CompareAndSwap 2 should have failed. The response is: %#v", resp) - } - - resp, err = c.Set("foo", "bar", 5) - if err != nil { - t.Fatal(err) - } - - // This should succeed - resp, err = c.CompareAndSwap("foo", "bar2", 5, "", resp.Node.ModifiedIndex) - if err != nil { - t.Fatal(err) - } - if !(resp.Node.Value == "bar2" && resp.Node.Key == "/foo" && resp.Node.TTL == 5) { - t.Fatalf("CompareAndSwap 3 failed: %#v", resp) - } - - if !(resp.PrevNode.Value == "bar" && resp.PrevNode.Key == "/foo" && resp.PrevNode.TTL == 5) { - t.Fatalf("CompareAndSwap 3 prevNode failed: %#v", resp) - } - - // This should fail because it gives an incorrect prevIndex - resp, err = c.CompareAndSwap("foo", "bar3", 5, "", 29817514) - if err == nil { - t.Fatalf("CompareAndSwap 4 should have failed. The response is: %#v", resp) - } -} diff --git a/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/debug_test.go b/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/debug_test.go deleted file mode 100644 index 97f6d1110..000000000 --- a/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/debug_test.go +++ /dev/null @@ -1,28 +0,0 @@ -package etcd - -import ( - "testing" -) - -type Foo struct{} -type Bar struct { - one string - two int -} - -// Tests that logs don't panic with arbitrary interfaces -func TestDebug(t *testing.T) { - f := &Foo{} - b := &Bar{"asfd", 3} - for _, test := range []interface{}{ - 1234, - "asdf", - f, - b, - } { - logger.Debug(test) - logger.Debugf("something, %s", test) - logger.Warning(test) - logger.Warningf("something, %s", test) - } -} diff --git a/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/delete_test.go b/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/delete_test.go deleted file mode 100644 index 590497155..000000000 --- a/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/delete_test.go +++ /dev/null @@ -1,81 +0,0 @@ -package etcd - -import ( - "testing" -) - -func TestDelete(t *testing.T) { - c := NewClient(nil) - defer func() { - c.Delete("foo", true) - }() - - c.Set("foo", "bar", 5) - resp, err := c.Delete("foo", false) - if err != nil { - t.Fatal(err) - } - - if !(resp.Node.Value == "") { - t.Fatalf("Delete failed with %s", resp.Node.Value) - } - - if !(resp.PrevNode.Value == "bar") { - t.Fatalf("Delete PrevNode failed with %s", resp.Node.Value) - } - - resp, err = c.Delete("foo", false) - if err == nil { - t.Fatalf("Delete should have failed because the key foo did not exist. "+ - "The response was: %v", resp) - } -} - -func TestDeleteAll(t *testing.T) { - c := NewClient(nil) - defer func() { - c.Delete("foo", true) - c.Delete("fooDir", true) - }() - - c.SetDir("foo", 5) - // test delete an empty dir - resp, err := c.DeleteDir("foo") - if err != nil { - t.Fatal(err) - } - - if !(resp.Node.Value == "") { - t.Fatalf("DeleteAll 1 failed: %#v", resp) - } - - if !(resp.PrevNode.Dir == true && resp.PrevNode.Value == "") { - t.Fatalf("DeleteAll 1 PrevNode failed: %#v", resp) - } - - c.CreateDir("fooDir", 5) - c.Set("fooDir/foo", "bar", 5) - _, err = c.DeleteDir("fooDir") - if err == nil { - t.Fatal("should not able to delete a non-empty dir with deletedir") - } - - resp, err = c.Delete("fooDir", true) - if err != nil { - t.Fatal(err) - } - - if !(resp.Node.Value == "") { - t.Fatalf("DeleteAll 2 failed: %#v", resp) - } - - if !(resp.PrevNode.Dir == true && resp.PrevNode.Value == "") { - t.Fatalf("DeleteAll 2 PrevNode failed: %#v", resp) - } - - resp, err = c.Delete("foo", true) - if err == nil { - t.Fatalf("DeleteAll should have failed because the key foo did not exist. "+ - "The response was: %v", resp) - } -} diff --git a/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/get_test.go b/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/get_test.go deleted file mode 100644 index 279c4e26f..000000000 --- a/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/get_test.go +++ /dev/null @@ -1,131 +0,0 @@ -package etcd - -import ( - "reflect" - "testing" -) - -// cleanNode scrubs Expiration, ModifiedIndex and CreatedIndex of a node. -func cleanNode(n *Node) { - n.Expiration = nil - n.ModifiedIndex = 0 - n.CreatedIndex = 0 -} - -// cleanResult scrubs a result object two levels deep of Expiration, -// ModifiedIndex and CreatedIndex. -func cleanResult(result *Response) { - // TODO(philips): make this recursive. - cleanNode(result.Node) - for i, _ := range result.Node.Nodes { - cleanNode(result.Node.Nodes[i]) - for j, _ := range result.Node.Nodes[i].Nodes { - cleanNode(result.Node.Nodes[i].Nodes[j]) - } - } -} - -func TestGet(t *testing.T) { - c := NewClient(nil) - defer func() { - c.Delete("foo", true) - }() - - c.Set("foo", "bar", 5) - - result, err := c.Get("foo", false, false) - - if err != nil { - t.Fatal(err) - } - - if result.Node.Key != "/foo" || result.Node.Value != "bar" { - t.Fatalf("Get failed with %s %s %v", result.Node.Key, result.Node.Value, result.Node.TTL) - } - - result, err = c.Get("goo", false, false) - if err == nil { - t.Fatalf("should not be able to get non-exist key") - } -} - -func TestGetAll(t *testing.T) { - c := NewClient(nil) - defer func() { - c.Delete("fooDir", true) - }() - - c.CreateDir("fooDir", 5) - c.Set("fooDir/k0", "v0", 5) - c.Set("fooDir/k1", "v1", 5) - - // Return kv-pairs in sorted order - result, err := c.Get("fooDir", true, false) - - if err != nil { - t.Fatal(err) - } - - expected := Nodes{ - &Node{ - Key: "/fooDir/k0", - Value: "v0", - TTL: 5, - }, - &Node{ - Key: "/fooDir/k1", - Value: "v1", - TTL: 5, - }, - } - - cleanResult(result) - - if !reflect.DeepEqual(result.Node.Nodes, expected) { - t.Fatalf("(actual) %v != (expected) %v", result.Node.Nodes, expected) - } - - // Test the `recursive` option - c.CreateDir("fooDir/childDir", 5) - c.Set("fooDir/childDir/k2", "v2", 5) - - // Return kv-pairs in sorted order - result, err = c.Get("fooDir", true, true) - - cleanResult(result) - - if err != nil { - t.Fatal(err) - } - - expected = Nodes{ - &Node{ - Key: "/fooDir/childDir", - Dir: true, - Nodes: Nodes{ - &Node{ - Key: "/fooDir/childDir/k2", - Value: "v2", - TTL: 5, - }, - }, - TTL: 5, - }, - &Node{ - Key: "/fooDir/k0", - Value: "v0", - TTL: 5, - }, - &Node{ - Key: "/fooDir/k1", - Value: "v1", - TTL: 5, - }, - } - - cleanResult(result) - - if !reflect.DeepEqual(result.Node.Nodes, expected) { - t.Fatalf("(actual) %v != (expected) %v", result.Node.Nodes, expected) - } -} diff --git a/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/member_test.go b/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/member_test.go deleted file mode 100644 index 53ebdd4bf..000000000 --- a/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/member_test.go +++ /dev/null @@ -1,71 +0,0 @@ -package etcd - -import ( - "encoding/json" - "reflect" - "testing" -) - -func TestMemberCollectionUnmarshal(t *testing.T) { - tests := []struct { - body []byte - want memberCollection - }{ - { - body: []byte(`{"members":[]}`), - want: memberCollection([]Member{}), - }, - { - body: []byte(`{"members":[{"id":"2745e2525fce8fe","peerURLs":["http://127.0.0.1:7003"],"name":"node3","clientURLs":["http://127.0.0.1:4003"]},{"id":"42134f434382925","peerURLs":["http://127.0.0.1:2380","http://127.0.0.1:7001"],"name":"node1","clientURLs":["http://127.0.0.1:2379","http://127.0.0.1:4001"]},{"id":"94088180e21eb87b","peerURLs":["http://127.0.0.1:7002"],"name":"node2","clientURLs":["http://127.0.0.1:4002"]}]}`), - want: memberCollection( - []Member{ - { - ID: "2745e2525fce8fe", - Name: "node3", - PeerURLs: []string{ - "http://127.0.0.1:7003", - }, - ClientURLs: []string{ - "http://127.0.0.1:4003", - }, - }, - { - ID: "42134f434382925", - Name: "node1", - PeerURLs: []string{ - "http://127.0.0.1:2380", - "http://127.0.0.1:7001", - }, - ClientURLs: []string{ - "http://127.0.0.1:2379", - "http://127.0.0.1:4001", - }, - }, - { - ID: "94088180e21eb87b", - Name: "node2", - PeerURLs: []string{ - "http://127.0.0.1:7002", - }, - ClientURLs: []string{ - "http://127.0.0.1:4002", - }, - }, - }, - ), - }, - } - - for i, tt := range tests { - var got memberCollection - err := json.Unmarshal(tt.body, &got) - if err != nil { - t.Errorf("#%d: unexpected error: %v", i, err) - continue - } - - if !reflect.DeepEqual(tt.want, got) { - t.Errorf("#%d: incorrect output: want=%#v, got=%#v", i, tt.want, got) - } - } -} diff --git a/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/requests_test.go b/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/requests_test.go deleted file mode 100644 index 7a2bd190a..000000000 --- a/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/requests_test.go +++ /dev/null @@ -1,22 +0,0 @@ -package etcd - -import "testing" - -func TestKeyToPath(t *testing.T) { - tests := []struct { - key string - wpath string - }{ - {"", "keys/"}, - {"foo", "keys/foo"}, - {"foo/bar", "keys/foo/bar"}, - {"%z", "keys/%25z"}, - {"/", "keys/"}, - } - for i, tt := range tests { - path := keyToPath(tt.key) - if path != tt.wpath { - t.Errorf("#%d: path = %s, want %s", i, path, tt.wpath) - } - } -} diff --git a/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/response.generated.go b/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/response.generated.go index eb05e4c89..397488b14 100644 --- a/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/response.generated.go +++ b/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/response.generated.go @@ -9,501 +9,519 @@ import ( "errors" "fmt" codec1978 "github.com/ugorji/go/codec" - "net/http" + pkg1_http "net/http" "reflect" "runtime" - "time" + time "time" ) const ( - codecSelferC_UTF84402 = 1 - codecSelferC_RAW4402 = 0 - codecSelverValueTypeArray4402 = 10 - codecSelverValueTypeMap4402 = 9 + codecSelferC_UTF86669 = 1 + codecSelferC_RAW6669 = 0 + codecSelverValueTypeArray6669 = 10 + codecSelverValueTypeMap6669 = 9 ) var ( - codecSelferBitsize4402 = uint8(reflect.TypeOf(uint(0)).Bits()) - codecSelferOnlyMapOrArrayEncodeToStructErr4402 = errors.New(`only encoded map or array can be decoded into a struct`) + codecSelferBitsize6669 = uint8(reflect.TypeOf(uint(0)).Bits()) + codecSelferOnlyMapOrArrayEncodeToStructErr6669 = errors.New(`only encoded map or array can be decoded into a struct`) ) -type codecSelfer4402 struct{} +type codecSelfer6669 struct{} func init() { - if codec1978.GenVersion != 2 { + if codec1978.GenVersion != 4 { _, file, _, _ := runtime.Caller(0) err := fmt.Errorf("codecgen version mismatch: current: %v, need %v. Re-generate file: %v", - 2, codec1978.GenVersion, file) + 4, codec1978.GenVersion, file) panic(err) } if false { // reference the types, but skip this branch at build/run time - var v0 http.Header + var v0 pkg1_http.Header var v1 time.Time _, _ = v0, v1 } } func (x responseType) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer4402 + var h codecSelfer6669 z, r := codec1978.GenHelperEncoder(e) _, _, _ = h, z, r - r.EncodeInt(int64(x)) + yym1 := z.EncBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.EncExt(x) { + } else { + r.EncodeInt(int64(x)) + } } func (x *responseType) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer4402 + var h codecSelfer6669 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r - *((*int)(x)) = int(r.DecodeInt(codecSelferBitsize4402)) + yym2 := z.DecBinary() + _ = yym2 + if false { + } else if z.HasExtensions() && z.DecExt(x) { + } else { + *((*int)(x)) = int(r.DecodeInt(codecSelferBitsize6669)) + } } func (x *RawResponse) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer4402 + var h codecSelfer6669 z, r := codec1978.GenHelperEncoder(e) _, _, _ = h, z, r if x == nil { r.EncodeNil() } else { - yysep1 := !z.EncBinary() - yy2arr1 := z.EncBasicHandle().StructToArray - var yyfirst1 bool - var yyq1 [3]bool - _, _, _, _ = yysep1, yyfirst1, yyq1, yy2arr1 - const yyr1 bool = false - if yyr1 || yy2arr1 { - r.EncodeArrayStart(3) + yym3 := z.EncBinary() + _ = yym3 + if false { + } else if z.HasExtensions() && z.EncExt(x) { } else { - var yynn1 int = 3 - for _, b := range yyq1 { - if b { - yynn1++ + yysep4 := !z.EncBinary() + yy2arr4 := z.EncBasicHandle().StructToArray + var yyq4 [3]bool + _, _, _ = yysep4, yyq4, yy2arr4 + const yyr4 bool = false + if yyr4 || yy2arr4 { + r.EncodeArrayStart(3) + } else { + var yynn4 int = 3 + for _, b := range yyq4 { + if b { + yynn4++ + } + } + r.EncodeMapStart(yynn4) + } + if yyr4 || yy2arr4 { + yym6 := z.EncBinary() + _ = yym6 + if false { + } else { + r.EncodeInt(int64(x.StatusCode)) + } + } else { + r.EncodeString(codecSelferC_UTF86669, string("StatusCode")) + yym7 := z.EncBinary() + _ = yym7 + if false { + } else { + r.EncodeInt(int64(x.StatusCode)) } } - r.EncodeMapStart(yynn1) - } - if yyr1 || yy2arr1 { - r.EncodeInt(int64(x.StatusCode)) - } else { - yyfirst1 = true - r.EncodeString(codecSelferC_UTF84402, string("StatusCode")) - if yysep1 { - r.EncodeMapKVSeparator() - } - r.EncodeInt(int64(x.StatusCode)) - } - if yyr1 || yy2arr1 { - if yysep1 { - r.EncodeArrayEntrySeparator() - } - if x.Body == nil { - r.EncodeNil() + if yyr4 || yy2arr4 { + if x.Body == nil { + r.EncodeNil() + } else { + yym9 := z.EncBinary() + _ = yym9 + if false { + } else { + r.EncodeStringBytes(codecSelferC_RAW6669, []byte(x.Body)) + } + } } else { - r.EncodeStringBytes(codecSelferC_RAW4402, []byte(x.Body)) + r.EncodeString(codecSelferC_UTF86669, string("Body")) + if x.Body == nil { + r.EncodeNil() + } else { + yym10 := z.EncBinary() + _ = yym10 + if false { + } else { + r.EncodeStringBytes(codecSelferC_RAW6669, []byte(x.Body)) + } + } } - } else { - if yyfirst1 { - r.EncodeMapEntrySeparator() + if yyr4 || yy2arr4 { + if x.Header == nil { + r.EncodeNil() + } else { + yym12 := z.EncBinary() + _ = yym12 + if false { + } else if z.HasExtensions() && z.EncExt(x.Header) { + } else { + h.enchttp_Header((pkg1_http.Header)(x.Header), e) + } + } } else { - yyfirst1 = true + r.EncodeString(codecSelferC_UTF86669, string("Header")) + if x.Header == nil { + r.EncodeNil() + } else { + yym13 := z.EncBinary() + _ = yym13 + if false { + } else if z.HasExtensions() && z.EncExt(x.Header) { + } else { + h.enchttp_Header((pkg1_http.Header)(x.Header), e) + } + } } - r.EncodeString(codecSelferC_UTF84402, string("Body")) - if yysep1 { - r.EncodeMapKVSeparator() - } - if x.Body == nil { - r.EncodeNil() - } else { - r.EncodeStringBytes(codecSelferC_RAW4402, []byte(x.Body)) - } - } - if yyr1 || yy2arr1 { - if yysep1 { - r.EncodeArrayEntrySeparator() - } - if x.Header == nil { - r.EncodeNil() - } else { - h.enchttp_Header(http.Header(x.Header), e) - } - } else { - if yyfirst1 { - r.EncodeMapEntrySeparator() - } else { - yyfirst1 = true - } - r.EncodeString(codecSelferC_UTF84402, string("Header")) - if yysep1 { - r.EncodeMapKVSeparator() - } - if x.Header == nil { - r.EncodeNil() - } else { - h.enchttp_Header(http.Header(x.Header), e) - } - } - if yysep1 { - if yyr1 || yy2arr1 { - r.EncodeArrayEnd() - } else { - r.EncodeMapEnd() + if yysep4 { + r.EncodeEnd() } } } } func (x *RawResponse) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer4402 + var h codecSelfer6669 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r - if r.IsContainerType(codecSelverValueTypeMap4402) { - yyl5 := r.ReadMapStart() - if yyl5 == 0 { - r.ReadMapEnd() - } else { - x.codecDecodeSelfFromMap(yyl5, d) - } - } else if r.IsContainerType(codecSelverValueTypeArray4402) { - yyl5 := r.ReadArrayStart() - if yyl5 == 0 { - r.ReadArrayEnd() - } else { - x.codecDecodeSelfFromArray(yyl5, d) - } + yym14 := z.DecBinary() + _ = yym14 + if false { + } else if z.HasExtensions() && z.DecExt(x) { } else { - panic(codecSelferOnlyMapOrArrayEncodeToStructErr4402) + if r.IsContainerType(codecSelverValueTypeMap6669) { + yyl15 := r.ReadMapStart() + if yyl15 == 0 { + r.ReadEnd() + } else { + x.codecDecodeSelfFromMap(yyl15, d) + } + } else if r.IsContainerType(codecSelverValueTypeArray6669) { + yyl15 := r.ReadArrayStart() + if yyl15 == 0 { + r.ReadEnd() + } else { + x.codecDecodeSelfFromArray(yyl15, d) + } + } else { + panic(codecSelferOnlyMapOrArrayEncodeToStructErr6669) + } } } func (x *RawResponse) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer4402 + var h codecSelfer6669 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r - var yys6Slc = z.DecScratchBuffer() // default slice to decode into - _ = yys6Slc - var yyhl6 bool = l >= 0 - for yyj6 := 0; ; yyj6++ { - if yyhl6 { - if yyj6 >= l { + var yys16Slc = z.DecScratchBuffer() // default slice to decode into + _ = yys16Slc + var yyhl16 bool = l >= 0 + for yyj16 := 0; ; yyj16++ { + if yyhl16 { + if yyj16 >= l { break } } else { if r.CheckBreak() { break } - if yyj6 > 0 { - r.ReadMapEntrySeparator() - } } - yys6Slc = r.DecodeBytes(yys6Slc, true, true) - yys6 := string(yys6Slc) - if !yyhl6 { - r.ReadMapKVSeparator() - } - switch yys6 { + yys16Slc = r.DecodeBytes(yys16Slc, true, true) + yys16 := string(yys16Slc) + switch yys16 { case "StatusCode": if r.TryDecodeAsNil() { x.StatusCode = 0 } else { - x.StatusCode = int(r.DecodeInt(codecSelferBitsize4402)) + x.StatusCode = int(r.DecodeInt(codecSelferBitsize6669)) } case "Body": if r.TryDecodeAsNil() { x.Body = nil } else { - yyv8 := &x.Body - *yyv8 = r.DecodeBytes(*(*[]byte)(yyv8), false, false) + yyv18 := &x.Body + yym19 := z.DecBinary() + _ = yym19 + if false { + } else { + *yyv18 = r.DecodeBytes(*(*[]byte)(yyv18), false, false) + } } case "Header": if r.TryDecodeAsNil() { x.Header = nil } else { - yyv9 := &x.Header - h.dechttp_Header((*http.Header)(yyv9), d) + yyv20 := &x.Header + yym21 := z.DecBinary() + _ = yym21 + if false { + } else if z.HasExtensions() && z.DecExt(yyv20) { + } else { + h.dechttp_Header((*pkg1_http.Header)(yyv20), d) + } } default: - z.DecStructFieldNotFound(-1, yys6) - } // end switch yys6 - } // end for yyj6 - if !yyhl6 { - r.ReadMapEnd() + z.DecStructFieldNotFound(-1, yys16) + } // end switch yys16 + } // end for yyj16 + if !yyhl16 { + r.ReadEnd() } } func (x *RawResponse) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer4402 + var h codecSelfer6669 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r - var yyj10 int - var yyb10 bool - var yyhl10 bool = l >= 0 - yyj10++ - if yyhl10 { - yyb10 = yyj10 > l + var yyj22 int + var yyb22 bool + var yyhl22 bool = l >= 0 + yyj22++ + if yyhl22 { + yyb22 = yyj22 > l } else { - yyb10 = r.CheckBreak() + yyb22 = r.CheckBreak() } - if yyb10 { - r.ReadArrayEnd() + if yyb22 { + r.ReadEnd() return } if r.TryDecodeAsNil() { x.StatusCode = 0 } else { - x.StatusCode = int(r.DecodeInt(codecSelferBitsize4402)) + x.StatusCode = int(r.DecodeInt(codecSelferBitsize6669)) } - yyj10++ - if yyhl10 { - yyb10 = yyj10 > l + yyj22++ + if yyhl22 { + yyb22 = yyj22 > l } else { - yyb10 = r.CheckBreak() + yyb22 = r.CheckBreak() } - if yyb10 { - r.ReadArrayEnd() + if yyb22 { + r.ReadEnd() return } - r.ReadArrayEntrySeparator() if r.TryDecodeAsNil() { x.Body = nil } else { - yyv12 := &x.Body - *yyv12 = r.DecodeBytes(*(*[]byte)(yyv12), false, false) + yyv24 := &x.Body + yym25 := z.DecBinary() + _ = yym25 + if false { + } else { + *yyv24 = r.DecodeBytes(*(*[]byte)(yyv24), false, false) + } } - yyj10++ - if yyhl10 { - yyb10 = yyj10 > l + yyj22++ + if yyhl22 { + yyb22 = yyj22 > l } else { - yyb10 = r.CheckBreak() + yyb22 = r.CheckBreak() } - if yyb10 { - r.ReadArrayEnd() + if yyb22 { + r.ReadEnd() return } - r.ReadArrayEntrySeparator() if r.TryDecodeAsNil() { x.Header = nil } else { - yyv13 := &x.Header - h.dechttp_Header((*http.Header)(yyv13), d) + yyv26 := &x.Header + yym27 := z.DecBinary() + _ = yym27 + if false { + } else if z.HasExtensions() && z.DecExt(yyv26) { + } else { + h.dechttp_Header((*pkg1_http.Header)(yyv26), d) + } } for { - yyj10++ - if yyhl10 { - yyb10 = yyj10 > l + yyj22++ + if yyhl22 { + yyb22 = yyj22 > l } else { - yyb10 = r.CheckBreak() + yyb22 = r.CheckBreak() } - if yyb10 { + if yyb22 { break } - if yyj10 > 1 { - r.ReadArrayEntrySeparator() - } - z.DecStructFieldNotFound(yyj10-1, "") + z.DecStructFieldNotFound(yyj22-1, "") } - r.ReadArrayEnd() + r.ReadEnd() } func (x *Response) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer4402 + var h codecSelfer6669 z, r := codec1978.GenHelperEncoder(e) _, _, _ = h, z, r if x == nil { r.EncodeNil() } else { - yysep14 := !z.EncBinary() - yy2arr14 := z.EncBasicHandle().StructToArray - var yyfirst14 bool - var yyq14 [6]bool - _, _, _, _ = yysep14, yyfirst14, yyq14, yy2arr14 - const yyr14 bool = false - yyq14[2] = x.PrevNode != nil - if yyr14 || yy2arr14 { - r.EncodeArrayStart(6) + yym28 := z.EncBinary() + _ = yym28 + if false { + } else if z.HasExtensions() && z.EncExt(x) { } else { - var yynn14 int = 5 - for _, b := range yyq14 { - if b { - yynn14++ + yysep29 := !z.EncBinary() + yy2arr29 := z.EncBasicHandle().StructToArray + var yyq29 [6]bool + _, _, _ = yysep29, yyq29, yy2arr29 + const yyr29 bool = false + yyq29[2] = x.PrevNode != nil + if yyr29 || yy2arr29 { + r.EncodeArrayStart(6) + } else { + var yynn29 int = 5 + for _, b := range yyq29 { + if b { + yynn29++ + } + } + r.EncodeMapStart(yynn29) + } + if yyr29 || yy2arr29 { + yym31 := z.EncBinary() + _ = yym31 + if false { + } else { + r.EncodeString(codecSelferC_UTF86669, string(x.Action)) + } + } else { + r.EncodeString(codecSelferC_UTF86669, string("action")) + yym32 := z.EncBinary() + _ = yym32 + if false { + } else { + r.EncodeString(codecSelferC_UTF86669, string(x.Action)) } } - r.EncodeMapStart(yynn14) - } - if yyr14 || yy2arr14 { - r.EncodeString(codecSelferC_UTF84402, string(x.Action)) - } else { - yyfirst14 = true - r.EncodeString(codecSelferC_UTF84402, string("action")) - if yysep14 { - r.EncodeMapKVSeparator() - } - r.EncodeString(codecSelferC_UTF84402, string(x.Action)) - } - if yyr14 || yy2arr14 { - if yysep14 { - r.EncodeArrayEntrySeparator() - } - if x.Node == nil { - r.EncodeNil() - } else { - x.Node.CodecEncodeSelf(e) - } - } else { - if yyfirst14 { - r.EncodeMapEntrySeparator() - } else { - yyfirst14 = true - } - r.EncodeString(codecSelferC_UTF84402, string("node")) - if yysep14 { - r.EncodeMapKVSeparator() - } - if x.Node == nil { - r.EncodeNil() - } else { - x.Node.CodecEncodeSelf(e) - } - } - if yyr14 || yy2arr14 { - if yysep14 { - r.EncodeArrayEntrySeparator() - } - if yyq14[2] { - if x.PrevNode == nil { + if yyr29 || yy2arr29 { + if x.Node == nil { r.EncodeNil() } else { - x.PrevNode.CodecEncodeSelf(e) + x.Node.CodecEncodeSelf(e) } } else { - r.EncodeNil() - } - } else { - if yyq14[2] { - if yyfirst14 { - r.EncodeMapEntrySeparator() - } else { - yyfirst14 = true - } - r.EncodeString(codecSelferC_UTF84402, string("prevNode")) - if yysep14 { - r.EncodeMapKVSeparator() - } - if x.PrevNode == nil { + r.EncodeString(codecSelferC_UTF86669, string("node")) + if x.Node == nil { r.EncodeNil() } else { - x.PrevNode.CodecEncodeSelf(e) + x.Node.CodecEncodeSelf(e) } } - } - if yyr14 || yy2arr14 { - if yysep14 { - r.EncodeArrayEntrySeparator() - } - r.EncodeUint(uint64(x.EtcdIndex)) - } else { - if yyfirst14 { - r.EncodeMapEntrySeparator() + if yyr29 || yy2arr29 { + if yyq29[2] { + if x.PrevNode == nil { + r.EncodeNil() + } else { + x.PrevNode.CodecEncodeSelf(e) + } + } else { + r.EncodeNil() + } } else { - yyfirst14 = true + if yyq29[2] { + r.EncodeString(codecSelferC_UTF86669, string("prevNode")) + if x.PrevNode == nil { + r.EncodeNil() + } else { + x.PrevNode.CodecEncodeSelf(e) + } + } } - r.EncodeString(codecSelferC_UTF84402, string("etcdIndex")) - if yysep14 { - r.EncodeMapKVSeparator() - } - r.EncodeUint(uint64(x.EtcdIndex)) - } - if yyr14 || yy2arr14 { - if yysep14 { - r.EncodeArrayEntrySeparator() - } - r.EncodeUint(uint64(x.RaftIndex)) - } else { - if yyfirst14 { - r.EncodeMapEntrySeparator() + if yyr29 || yy2arr29 { + yym36 := z.EncBinary() + _ = yym36 + if false { + } else { + r.EncodeUint(uint64(x.EtcdIndex)) + } } else { - yyfirst14 = true + r.EncodeString(codecSelferC_UTF86669, string("etcdIndex")) + yym37 := z.EncBinary() + _ = yym37 + if false { + } else { + r.EncodeUint(uint64(x.EtcdIndex)) + } } - r.EncodeString(codecSelferC_UTF84402, string("raftIndex")) - if yysep14 { - r.EncodeMapKVSeparator() - } - r.EncodeUint(uint64(x.RaftIndex)) - } - if yyr14 || yy2arr14 { - if yysep14 { - r.EncodeArrayEntrySeparator() - } - r.EncodeUint(uint64(x.RaftTerm)) - } else { - if yyfirst14 { - r.EncodeMapEntrySeparator() + if yyr29 || yy2arr29 { + yym39 := z.EncBinary() + _ = yym39 + if false { + } else { + r.EncodeUint(uint64(x.RaftIndex)) + } } else { - yyfirst14 = true + r.EncodeString(codecSelferC_UTF86669, string("raftIndex")) + yym40 := z.EncBinary() + _ = yym40 + if false { + } else { + r.EncodeUint(uint64(x.RaftIndex)) + } } - r.EncodeString(codecSelferC_UTF84402, string("raftTerm")) - if yysep14 { - r.EncodeMapKVSeparator() - } - r.EncodeUint(uint64(x.RaftTerm)) - } - if yysep14 { - if yyr14 || yy2arr14 { - r.EncodeArrayEnd() + if yyr29 || yy2arr29 { + yym42 := z.EncBinary() + _ = yym42 + if false { + } else { + r.EncodeUint(uint64(x.RaftTerm)) + } } else { - r.EncodeMapEnd() + r.EncodeString(codecSelferC_UTF86669, string("raftTerm")) + yym43 := z.EncBinary() + _ = yym43 + if false { + } else { + r.EncodeUint(uint64(x.RaftTerm)) + } + } + if yysep29 { + r.EncodeEnd() } } } } func (x *Response) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer4402 + var h codecSelfer6669 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r - if r.IsContainerType(codecSelverValueTypeMap4402) { - yyl21 := r.ReadMapStart() - if yyl21 == 0 { - r.ReadMapEnd() - } else { - x.codecDecodeSelfFromMap(yyl21, d) - } - } else if r.IsContainerType(codecSelverValueTypeArray4402) { - yyl21 := r.ReadArrayStart() - if yyl21 == 0 { - r.ReadArrayEnd() - } else { - x.codecDecodeSelfFromArray(yyl21, d) - } + yym44 := z.DecBinary() + _ = yym44 + if false { + } else if z.HasExtensions() && z.DecExt(x) { } else { - panic(codecSelferOnlyMapOrArrayEncodeToStructErr4402) + if r.IsContainerType(codecSelverValueTypeMap6669) { + yyl45 := r.ReadMapStart() + if yyl45 == 0 { + r.ReadEnd() + } else { + x.codecDecodeSelfFromMap(yyl45, d) + } + } else if r.IsContainerType(codecSelverValueTypeArray6669) { + yyl45 := r.ReadArrayStart() + if yyl45 == 0 { + r.ReadEnd() + } else { + x.codecDecodeSelfFromArray(yyl45, d) + } + } else { + panic(codecSelferOnlyMapOrArrayEncodeToStructErr6669) + } } } func (x *Response) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer4402 + var h codecSelfer6669 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r - var yys22Slc = z.DecScratchBuffer() // default slice to decode into - _ = yys22Slc - var yyhl22 bool = l >= 0 - for yyj22 := 0; ; yyj22++ { - if yyhl22 { - if yyj22 >= l { + var yys46Slc = z.DecScratchBuffer() // default slice to decode into + _ = yys46Slc + var yyhl46 bool = l >= 0 + for yyj46 := 0; ; yyj46++ { + if yyhl46 { + if yyj46 >= l { break } } else { if r.CheckBreak() { break } - if yyj22 > 0 { - r.ReadMapEntrySeparator() - } } - yys22Slc = r.DecodeBytes(yys22Slc, true, true) - yys22 := string(yys22Slc) - if !yyhl22 { - r.ReadMapKVSeparator() - } - switch yys22 { + yys46Slc = r.DecodeBytes(yys46Slc, true, true) + yys46 := string(yys46Slc) + switch yys46 { case "action": if r.TryDecodeAsNil() { x.Action = "" @@ -551,29 +569,29 @@ func (x *Response) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { x.RaftTerm = uint64(r.DecodeUint(64)) } default: - z.DecStructFieldNotFound(-1, yys22) - } // end switch yys22 - } // end for yyj22 - if !yyhl22 { - r.ReadMapEnd() + z.DecStructFieldNotFound(-1, yys46) + } // end switch yys46 + } // end for yyj46 + if !yyhl46 { + r.ReadEnd() } } func (x *Response) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer4402 + var h codecSelfer6669 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r - var yyj29 int - var yyb29 bool - var yyhl29 bool = l >= 0 - yyj29++ - if yyhl29 { - yyb29 = yyj29 > l + var yyj53 int + var yyb53 bool + var yyhl53 bool = l >= 0 + yyj53++ + if yyhl53 { + yyb53 = yyj53 > l } else { - yyb29 = r.CheckBreak() + yyb53 = r.CheckBreak() } - if yyb29 { - r.ReadArrayEnd() + if yyb53 { + r.ReadEnd() return } if r.TryDecodeAsNil() { @@ -581,17 +599,16 @@ func (x *Response) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { } else { x.Action = string(r.DecodeString()) } - yyj29++ - if yyhl29 { - yyb29 = yyj29 > l + yyj53++ + if yyhl53 { + yyb53 = yyj53 > l } else { - yyb29 = r.CheckBreak() + yyb53 = r.CheckBreak() } - if yyb29 { - r.ReadArrayEnd() + if yyb53 { + r.ReadEnd() return } - r.ReadArrayEntrySeparator() if r.TryDecodeAsNil() { if x.Node != nil { x.Node = nil @@ -602,17 +619,16 @@ func (x *Response) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { } x.Node.CodecDecodeSelf(d) } - yyj29++ - if yyhl29 { - yyb29 = yyj29 > l + yyj53++ + if yyhl53 { + yyb53 = yyj53 > l } else { - yyb29 = r.CheckBreak() + yyb53 = r.CheckBreak() } - if yyb29 { - r.ReadArrayEnd() + if yyb53 { + r.ReadEnd() return } - r.ReadArrayEntrySeparator() if r.TryDecodeAsNil() { if x.PrevNode != nil { x.PrevNode = nil @@ -623,349 +639,347 @@ func (x *Response) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { } x.PrevNode.CodecDecodeSelf(d) } - yyj29++ - if yyhl29 { - yyb29 = yyj29 > l + yyj53++ + if yyhl53 { + yyb53 = yyj53 > l } else { - yyb29 = r.CheckBreak() + yyb53 = r.CheckBreak() } - if yyb29 { - r.ReadArrayEnd() + if yyb53 { + r.ReadEnd() return } - r.ReadArrayEntrySeparator() if r.TryDecodeAsNil() { x.EtcdIndex = 0 } else { x.EtcdIndex = uint64(r.DecodeUint(64)) } - yyj29++ - if yyhl29 { - yyb29 = yyj29 > l + yyj53++ + if yyhl53 { + yyb53 = yyj53 > l } else { - yyb29 = r.CheckBreak() + yyb53 = r.CheckBreak() } - if yyb29 { - r.ReadArrayEnd() + if yyb53 { + r.ReadEnd() return } - r.ReadArrayEntrySeparator() if r.TryDecodeAsNil() { x.RaftIndex = 0 } else { x.RaftIndex = uint64(r.DecodeUint(64)) } - yyj29++ - if yyhl29 { - yyb29 = yyj29 > l + yyj53++ + if yyhl53 { + yyb53 = yyj53 > l } else { - yyb29 = r.CheckBreak() + yyb53 = r.CheckBreak() } - if yyb29 { - r.ReadArrayEnd() + if yyb53 { + r.ReadEnd() return } - r.ReadArrayEntrySeparator() if r.TryDecodeAsNil() { x.RaftTerm = 0 } else { x.RaftTerm = uint64(r.DecodeUint(64)) } for { - yyj29++ - if yyhl29 { - yyb29 = yyj29 > l + yyj53++ + if yyhl53 { + yyb53 = yyj53 > l } else { - yyb29 = r.CheckBreak() + yyb53 = r.CheckBreak() } - if yyb29 { + if yyb53 { break } - if yyj29 > 1 { - r.ReadArrayEntrySeparator() - } - z.DecStructFieldNotFound(yyj29-1, "") + z.DecStructFieldNotFound(yyj53-1, "") } - r.ReadArrayEnd() + r.ReadEnd() } func (x *Node) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer4402 + var h codecSelfer6669 z, r := codec1978.GenHelperEncoder(e) _, _, _ = h, z, r if x == nil { r.EncodeNil() } else { - yysep36 := !z.EncBinary() - yy2arr36 := z.EncBasicHandle().StructToArray - var yyfirst36 bool - var yyq36 [8]bool - _, _, _, _ = yysep36, yyfirst36, yyq36, yy2arr36 - const yyr36 bool = false - yyq36[1] = x.Value != "" - yyq36[2] = x.Dir != false - yyq36[3] = x.Expiration != nil - yyq36[4] = x.TTL != 0 - yyq36[5] = len(x.Nodes) != 0 - yyq36[6] = x.ModifiedIndex != 0 - yyq36[7] = x.CreatedIndex != 0 - if yyr36 || yy2arr36 { - r.EncodeArrayStart(8) + yym60 := z.EncBinary() + _ = yym60 + if false { + } else if z.HasExtensions() && z.EncExt(x) { } else { - var yynn36 int = 1 - for _, b := range yyq36 { - if b { - yynn36++ - } - } - r.EncodeMapStart(yynn36) - } - if yyr36 || yy2arr36 { - r.EncodeString(codecSelferC_UTF84402, string(x.Key)) - } else { - yyfirst36 = true - r.EncodeString(codecSelferC_UTF84402, string("key")) - if yysep36 { - r.EncodeMapKVSeparator() - } - r.EncodeString(codecSelferC_UTF84402, string(x.Key)) - } - if yyr36 || yy2arr36 { - if yysep36 { - r.EncodeArrayEntrySeparator() - } - if yyq36[1] { - r.EncodeString(codecSelferC_UTF84402, string(x.Value)) + yysep61 := !z.EncBinary() + yy2arr61 := z.EncBasicHandle().StructToArray + var yyq61 [8]bool + _, _, _ = yysep61, yyq61, yy2arr61 + const yyr61 bool = false + yyq61[1] = x.Value != "" + yyq61[2] = x.Dir != false + yyq61[3] = x.Expiration != nil + yyq61[4] = x.TTL != 0 + yyq61[5] = len(x.Nodes) != 0 + yyq61[6] = x.ModifiedIndex != 0 + yyq61[7] = x.CreatedIndex != 0 + if yyr61 || yy2arr61 { + r.EncodeArrayStart(8) } else { - r.EncodeString(codecSelferC_UTF84402, "") + var yynn61 int = 1 + for _, b := range yyq61 { + if b { + yynn61++ + } + } + r.EncodeMapStart(yynn61) } - } else { - if yyq36[1] { - if yyfirst36 { - r.EncodeMapEntrySeparator() + if yyr61 || yy2arr61 { + yym63 := z.EncBinary() + _ = yym63 + if false { } else { - yyfirst36 = true + r.EncodeString(codecSelferC_UTF86669, string(x.Key)) } - r.EncodeString(codecSelferC_UTF84402, string("value")) - if yysep36 { - r.EncodeMapKVSeparator() - } - r.EncodeString(codecSelferC_UTF84402, string(x.Value)) - } - } - if yyr36 || yy2arr36 { - if yysep36 { - r.EncodeArrayEntrySeparator() - } - if yyq36[2] { - r.EncodeBool(bool(x.Dir)) } else { - r.EncodeBool(false) - } - } else { - if yyq36[2] { - if yyfirst36 { - r.EncodeMapEntrySeparator() + r.EncodeString(codecSelferC_UTF86669, string("key")) + yym64 := z.EncBinary() + _ = yym64 + if false { } else { - yyfirst36 = true + r.EncodeString(codecSelferC_UTF86669, string(x.Key)) } - r.EncodeString(codecSelferC_UTF84402, string("dir")) - if yysep36 { - r.EncodeMapKVSeparator() + } + if yyr61 || yy2arr61 { + if yyq61[1] { + yym66 := z.EncBinary() + _ = yym66 + if false { + } else { + r.EncodeString(codecSelferC_UTF86669, string(x.Value)) + } + } else { + r.EncodeString(codecSelferC_UTF86669, "") + } + } else { + if yyq61[1] { + r.EncodeString(codecSelferC_UTF86669, string("value")) + yym67 := z.EncBinary() + _ = yym67 + if false { + } else { + r.EncodeString(codecSelferC_UTF86669, string(x.Value)) + } } - r.EncodeBool(bool(x.Dir)) } - } - if yyr36 || yy2arr36 { - if yysep36 { - r.EncodeArrayEntrySeparator() + if yyr61 || yy2arr61 { + if yyq61[2] { + yym69 := z.EncBinary() + _ = yym69 + if false { + } else { + r.EncodeBool(bool(x.Dir)) + } + } else { + r.EncodeBool(false) + } + } else { + if yyq61[2] { + r.EncodeString(codecSelferC_UTF86669, string("dir")) + yym70 := z.EncBinary() + _ = yym70 + if false { + } else { + r.EncodeBool(bool(x.Dir)) + } + } } - if yyq36[3] { - if x.Expiration == nil { + if yyr61 || yy2arr61 { + if yyq61[3] { + if x.Expiration == nil { + r.EncodeNil() + } else { + yym72 := z.EncBinary() + _ = yym72 + if false { + } else if yym73 := z.TimeRtidIfBinc(); yym73 != 0 { + r.EncodeBuiltin(yym73, x.Expiration) + } else if z.HasExtensions() && z.EncExt(x.Expiration) { + } else if yym72 { + z.EncBinaryMarshal(x.Expiration) + } else if !yym72 && z.IsJSONHandle() { + z.EncJSONMarshal(x.Expiration) + } else { + z.EncFallback(x.Expiration) + } + } + } else { r.EncodeNil() - } else { - z.EncFallback(x.Expiration) } } else { - r.EncodeNil() + if yyq61[3] { + r.EncodeString(codecSelferC_UTF86669, string("expiration")) + if x.Expiration == nil { + r.EncodeNil() + } else { + yym74 := z.EncBinary() + _ = yym74 + if false { + } else if yym75 := z.TimeRtidIfBinc(); yym75 != 0 { + r.EncodeBuiltin(yym75, x.Expiration) + } else if z.HasExtensions() && z.EncExt(x.Expiration) { + } else if yym74 { + z.EncBinaryMarshal(x.Expiration) + } else if !yym74 && z.IsJSONHandle() { + z.EncJSONMarshal(x.Expiration) + } else { + z.EncFallback(x.Expiration) + } + } + } } - } else { - if yyq36[3] { - if yyfirst36 { - r.EncodeMapEntrySeparator() + if yyr61 || yy2arr61 { + if yyq61[4] { + yym77 := z.EncBinary() + _ = yym77 + if false { + } else { + r.EncodeInt(int64(x.TTL)) + } } else { - yyfirst36 = true + r.EncodeInt(0) } - r.EncodeString(codecSelferC_UTF84402, string("expiration")) - if yysep36 { - r.EncodeMapKVSeparator() + } else { + if yyq61[4] { + r.EncodeString(codecSelferC_UTF86669, string("ttl")) + yym78 := z.EncBinary() + _ = yym78 + if false { + } else { + r.EncodeInt(int64(x.TTL)) + } } - if x.Expiration == nil { + } + if yyr61 || yy2arr61 { + if yyq61[5] { + if x.Nodes == nil { + r.EncodeNil() + } else { + x.Nodes.CodecEncodeSelf(e) + } + } else { r.EncodeNil() - } else { - z.EncFallback(x.Expiration) - } - } - } - if yyr36 || yy2arr36 { - if yysep36 { - r.EncodeArrayEntrySeparator() - } - if yyq36[4] { - r.EncodeInt(int64(x.TTL)) - } else { - r.EncodeInt(0) - } - } else { - if yyq36[4] { - if yyfirst36 { - r.EncodeMapEntrySeparator() - } else { - yyfirst36 = true - } - r.EncodeString(codecSelferC_UTF84402, string("ttl")) - if yysep36 { - r.EncodeMapKVSeparator() - } - r.EncodeInt(int64(x.TTL)) - } - } - if yyr36 || yy2arr36 { - if yysep36 { - r.EncodeArrayEntrySeparator() - } - if yyq36[5] { - if x.Nodes == nil { - r.EncodeNil() - } else { - x.Nodes.CodecEncodeSelf(e) } } else { - r.EncodeNil() + if yyq61[5] { + r.EncodeString(codecSelferC_UTF86669, string("nodes")) + if x.Nodes == nil { + r.EncodeNil() + } else { + x.Nodes.CodecEncodeSelf(e) + } + } } - } else { - if yyq36[5] { - if yyfirst36 { - r.EncodeMapEntrySeparator() + if yyr61 || yy2arr61 { + if yyq61[6] { + yym81 := z.EncBinary() + _ = yym81 + if false { + } else { + r.EncodeUint(uint64(x.ModifiedIndex)) + } } else { - yyfirst36 = true + r.EncodeUint(0) } - r.EncodeString(codecSelferC_UTF84402, string("nodes")) - if yysep36 { - r.EncodeMapKVSeparator() - } - if x.Nodes == nil { - r.EncodeNil() - } else { - x.Nodes.CodecEncodeSelf(e) - } - } - } - if yyr36 || yy2arr36 { - if yysep36 { - r.EncodeArrayEntrySeparator() - } - if yyq36[6] { - r.EncodeUint(uint64(x.ModifiedIndex)) } else { - r.EncodeUint(0) + if yyq61[6] { + r.EncodeString(codecSelferC_UTF86669, string("modifiedIndex")) + yym82 := z.EncBinary() + _ = yym82 + if false { + } else { + r.EncodeUint(uint64(x.ModifiedIndex)) + } + } } - } else { - if yyq36[6] { - if yyfirst36 { - r.EncodeMapEntrySeparator() + if yyr61 || yy2arr61 { + if yyq61[7] { + yym84 := z.EncBinary() + _ = yym84 + if false { + } else { + r.EncodeUint(uint64(x.CreatedIndex)) + } } else { - yyfirst36 = true + r.EncodeUint(0) } - r.EncodeString(codecSelferC_UTF84402, string("modifiedIndex")) - if yysep36 { - r.EncodeMapKVSeparator() - } - r.EncodeUint(uint64(x.ModifiedIndex)) - } - } - if yyr36 || yy2arr36 { - if yysep36 { - r.EncodeArrayEntrySeparator() - } - if yyq36[7] { - r.EncodeUint(uint64(x.CreatedIndex)) } else { - r.EncodeUint(0) - } - } else { - if yyq36[7] { - if yyfirst36 { - r.EncodeMapEntrySeparator() - } else { - yyfirst36 = true + if yyq61[7] { + r.EncodeString(codecSelferC_UTF86669, string("createdIndex")) + yym85 := z.EncBinary() + _ = yym85 + if false { + } else { + r.EncodeUint(uint64(x.CreatedIndex)) + } } - r.EncodeString(codecSelferC_UTF84402, string("createdIndex")) - if yysep36 { - r.EncodeMapKVSeparator() - } - r.EncodeUint(uint64(x.CreatedIndex)) } - } - if yysep36 { - if yyr36 || yy2arr36 { - r.EncodeArrayEnd() - } else { - r.EncodeMapEnd() + if yysep61 { + r.EncodeEnd() } } } } func (x *Node) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer4402 + var h codecSelfer6669 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r - if r.IsContainerType(codecSelverValueTypeMap4402) { - yyl45 := r.ReadMapStart() - if yyl45 == 0 { - r.ReadMapEnd() - } else { - x.codecDecodeSelfFromMap(yyl45, d) - } - } else if r.IsContainerType(codecSelverValueTypeArray4402) { - yyl45 := r.ReadArrayStart() - if yyl45 == 0 { - r.ReadArrayEnd() - } else { - x.codecDecodeSelfFromArray(yyl45, d) - } + yym86 := z.DecBinary() + _ = yym86 + if false { + } else if z.HasExtensions() && z.DecExt(x) { } else { - panic(codecSelferOnlyMapOrArrayEncodeToStructErr4402) + if r.IsContainerType(codecSelverValueTypeMap6669) { + yyl87 := r.ReadMapStart() + if yyl87 == 0 { + r.ReadEnd() + } else { + x.codecDecodeSelfFromMap(yyl87, d) + } + } else if r.IsContainerType(codecSelverValueTypeArray6669) { + yyl87 := r.ReadArrayStart() + if yyl87 == 0 { + r.ReadEnd() + } else { + x.codecDecodeSelfFromArray(yyl87, d) + } + } else { + panic(codecSelferOnlyMapOrArrayEncodeToStructErr6669) + } } } func (x *Node) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer4402 + var h codecSelfer6669 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r - var yys46Slc = z.DecScratchBuffer() // default slice to decode into - _ = yys46Slc - var yyhl46 bool = l >= 0 - for yyj46 := 0; ; yyj46++ { - if yyhl46 { - if yyj46 >= l { + var yys88Slc = z.DecScratchBuffer() // default slice to decode into + _ = yys88Slc + var yyhl88 bool = l >= 0 + for yyj88 := 0; ; yyj88++ { + if yyhl88 { + if yyj88 >= l { break } } else { if r.CheckBreak() { break } - if yyj46 > 0 { - r.ReadMapEntrySeparator() - } } - yys46Slc = r.DecodeBytes(yys46Slc, true, true) - yys46 := string(yys46Slc) - if !yyhl46 { - r.ReadMapKVSeparator() - } - switch yys46 { + yys88Slc = r.DecodeBytes(yys88Slc, true, true) + yys88 := string(yys88Slc) + switch yys88 { case "key": if r.TryDecodeAsNil() { x.Key = "" @@ -993,7 +1007,19 @@ func (x *Node) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { if x.Expiration == nil { x.Expiration = new(time.Time) } - z.DecFallback(x.Expiration, false) + yym93 := z.DecBinary() + _ = yym93 + if false { + } else if yym94 := z.TimeRtidIfBinc(); yym94 != 0 { + r.DecodeBuiltin(yym94, x.Expiration) + } else if z.HasExtensions() && z.DecExt(x.Expiration) { + } else if yym93 { + z.DecBinaryUnmarshal(x.Expiration) + } else if !yym93 && z.IsJSONHandle() { + z.DecJSONUnmarshal(x.Expiration) + } else { + z.DecFallback(x.Expiration, false) + } } case "ttl": if r.TryDecodeAsNil() { @@ -1005,8 +1031,8 @@ func (x *Node) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { if r.TryDecodeAsNil() { x.Nodes = nil } else { - yyv52 := &x.Nodes - yyv52.CodecDecodeSelf(d) + yyv96 := &x.Nodes + yyv96.CodecDecodeSelf(d) } case "modifiedIndex": if r.TryDecodeAsNil() { @@ -1021,29 +1047,29 @@ func (x *Node) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { x.CreatedIndex = uint64(r.DecodeUint(64)) } default: - z.DecStructFieldNotFound(-1, yys46) - } // end switch yys46 - } // end for yyj46 - if !yyhl46 { - r.ReadMapEnd() + z.DecStructFieldNotFound(-1, yys88) + } // end switch yys88 + } // end for yyj88 + if !yyhl88 { + r.ReadEnd() } } func (x *Node) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer4402 + var h codecSelfer6669 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r - var yyj55 int - var yyb55 bool - var yyhl55 bool = l >= 0 - yyj55++ - if yyhl55 { - yyb55 = yyj55 > l + var yyj99 int + var yyb99 bool + var yyhl99 bool = l >= 0 + yyj99++ + if yyhl99 { + yyb99 = yyj99 > l } else { - yyb55 = r.CheckBreak() + yyb99 = r.CheckBreak() } - if yyb55 { - r.ReadArrayEnd() + if yyb99 { + r.ReadEnd() return } if r.TryDecodeAsNil() { @@ -1051,49 +1077,46 @@ func (x *Node) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { } else { x.Key = string(r.DecodeString()) } - yyj55++ - if yyhl55 { - yyb55 = yyj55 > l + yyj99++ + if yyhl99 { + yyb99 = yyj99 > l } else { - yyb55 = r.CheckBreak() + yyb99 = r.CheckBreak() } - if yyb55 { - r.ReadArrayEnd() + if yyb99 { + r.ReadEnd() return } - r.ReadArrayEntrySeparator() if r.TryDecodeAsNil() { x.Value = "" } else { x.Value = string(r.DecodeString()) } - yyj55++ - if yyhl55 { - yyb55 = yyj55 > l + yyj99++ + if yyhl99 { + yyb99 = yyj99 > l } else { - yyb55 = r.CheckBreak() + yyb99 = r.CheckBreak() } - if yyb55 { - r.ReadArrayEnd() + if yyb99 { + r.ReadEnd() return } - r.ReadArrayEntrySeparator() if r.TryDecodeAsNil() { x.Dir = false } else { x.Dir = bool(r.DecodeBool()) } - yyj55++ - if yyhl55 { - yyb55 = yyj55 > l + yyj99++ + if yyhl99 { + yyb99 = yyj99 > l } else { - yyb55 = r.CheckBreak() + yyb99 = r.CheckBreak() } - if yyb55 { - r.ReadArrayEnd() + if yyb99 { + r.ReadEnd() return } - r.ReadArrayEntrySeparator() if r.TryDecodeAsNil() { if x.Expiration != nil { x.Expiration = nil @@ -1102,308 +1125,308 @@ func (x *Node) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { if x.Expiration == nil { x.Expiration = new(time.Time) } - z.DecFallback(x.Expiration, false) + yym104 := z.DecBinary() + _ = yym104 + if false { + } else if yym105 := z.TimeRtidIfBinc(); yym105 != 0 { + r.DecodeBuiltin(yym105, x.Expiration) + } else if z.HasExtensions() && z.DecExt(x.Expiration) { + } else if yym104 { + z.DecBinaryUnmarshal(x.Expiration) + } else if !yym104 && z.IsJSONHandle() { + z.DecJSONUnmarshal(x.Expiration) + } else { + z.DecFallback(x.Expiration, false) + } } - yyj55++ - if yyhl55 { - yyb55 = yyj55 > l + yyj99++ + if yyhl99 { + yyb99 = yyj99 > l } else { - yyb55 = r.CheckBreak() + yyb99 = r.CheckBreak() } - if yyb55 { - r.ReadArrayEnd() + if yyb99 { + r.ReadEnd() return } - r.ReadArrayEntrySeparator() if r.TryDecodeAsNil() { x.TTL = 0 } else { x.TTL = int64(r.DecodeInt(64)) } - yyj55++ - if yyhl55 { - yyb55 = yyj55 > l + yyj99++ + if yyhl99 { + yyb99 = yyj99 > l } else { - yyb55 = r.CheckBreak() + yyb99 = r.CheckBreak() } - if yyb55 { - r.ReadArrayEnd() + if yyb99 { + r.ReadEnd() return } - r.ReadArrayEntrySeparator() if r.TryDecodeAsNil() { x.Nodes = nil } else { - yyv61 := &x.Nodes - yyv61.CodecDecodeSelf(d) + yyv107 := &x.Nodes + yyv107.CodecDecodeSelf(d) } - yyj55++ - if yyhl55 { - yyb55 = yyj55 > l + yyj99++ + if yyhl99 { + yyb99 = yyj99 > l } else { - yyb55 = r.CheckBreak() + yyb99 = r.CheckBreak() } - if yyb55 { - r.ReadArrayEnd() + if yyb99 { + r.ReadEnd() return } - r.ReadArrayEntrySeparator() if r.TryDecodeAsNil() { x.ModifiedIndex = 0 } else { x.ModifiedIndex = uint64(r.DecodeUint(64)) } - yyj55++ - if yyhl55 { - yyb55 = yyj55 > l + yyj99++ + if yyhl99 { + yyb99 = yyj99 > l } else { - yyb55 = r.CheckBreak() + yyb99 = r.CheckBreak() } - if yyb55 { - r.ReadArrayEnd() + if yyb99 { + r.ReadEnd() return } - r.ReadArrayEntrySeparator() if r.TryDecodeAsNil() { x.CreatedIndex = 0 } else { x.CreatedIndex = uint64(r.DecodeUint(64)) } for { - yyj55++ - if yyhl55 { - yyb55 = yyj55 > l + yyj99++ + if yyhl99 { + yyb99 = yyj99 > l } else { - yyb55 = r.CheckBreak() + yyb99 = r.CheckBreak() } - if yyb55 { + if yyb99 { break } - if yyj55 > 1 { - r.ReadArrayEntrySeparator() - } - z.DecStructFieldNotFound(yyj55-1, "") + z.DecStructFieldNotFound(yyj99-1, "") } - r.ReadArrayEnd() + r.ReadEnd() } func (x Nodes) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer4402 + var h codecSelfer6669 z, r := codec1978.GenHelperEncoder(e) _, _, _ = h, z, r if x == nil { r.EncodeNil() } else { - h.encNodes(Nodes(x), e) + yym110 := z.EncBinary() + _ = yym110 + if false { + } else if z.HasExtensions() && z.EncExt(x) { + } else { + h.encNodes((Nodes)(x), e) + } } } func (x *Nodes) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer4402 + var h codecSelfer6669 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r - h.decNodes((*Nodes)(x), d) + yym111 := z.DecBinary() + _ = yym111 + if false { + } else if z.HasExtensions() && z.DecExt(x) { + } else { + h.decNodes((*Nodes)(x), d) + } } -func (x codecSelfer4402) enchttp_Header(v http.Header, e *codec1978.Encoder) { - var h codecSelfer4402 +func (x codecSelfer6669) enchttp_Header(v pkg1_http.Header, e *codec1978.Encoder) { + var h codecSelfer6669 z, r := codec1978.GenHelperEncoder(e) _, _, _ = h, z, r r.EncodeMapStart(len(v)) - yys64 := !z.EncBinary() - yyj64 := 0 - if yys64 { - for yyk64, yyv64 := range v { - if yyj64 > 0 { - r.EncodeMapEntrySeparator() - } - r.EncodeString(codecSelferC_UTF84402, string(yyk64)) - r.EncodeMapKVSeparator() - if yyv64 == nil { - r.EncodeNil() - } else { - z.F.EncSliceStringV(yyv64, false, e) - } - yyj64++ + for yyk112, yyv112 := range v { + yym113 := z.EncBinary() + _ = yym113 + if false { + } else { + r.EncodeString(codecSelferC_UTF86669, string(yyk112)) } - r.EncodeMapEnd() - } else { - for yyk64, yyv64 := range v { - r.EncodeString(codecSelferC_UTF84402, string(yyk64)) - if yyv64 == nil { - r.EncodeNil() + if yyv112 == nil { + r.EncodeNil() + } else { + yym114 := z.EncBinary() + _ = yym114 + if false { } else { - z.F.EncSliceStringV(yyv64, false, e) + z.F.EncSliceStringV(yyv112, false, e) } } } + r.EncodeEnd() } -func (x codecSelfer4402) dechttp_Header(v *http.Header, d *codec1978.Decoder) { - var h codecSelfer4402 +func (x codecSelfer6669) dechttp_Header(v *pkg1_http.Header, d *codec1978.Decoder) { + var h codecSelfer6669 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r - yyv65 := *v - yyl65 := r.ReadMapStart() - if yyv65 == nil { - if yyl65 > 0 { - yyv65 = make(map[string][]string, yyl65) + yyv115 := *v + yyl115 := r.ReadMapStart() + if yyv115 == nil { + if yyl115 > 0 { + yyv115 = make(map[string][]string, yyl115) } else { - yyv65 = make(map[string][]string) // supports indefinite-length, etc + yyv115 = make(map[string][]string) // supports indefinite-length, etc } - *v = yyv65 + *v = yyv115 } - if yyl65 > 0 { - for yyj65 := 0; yyj65 < yyl65; yyj65++ { - var yymk65 string + if yyl115 > 0 { + for yyj115 := 0; yyj115 < yyl115; yyj115++ { + var yymk115 string if r.TryDecodeAsNil() { - yymk65 = "" + yymk115 = "" } else { - yymk65 = string(r.DecodeString()) + yymk115 = string(r.DecodeString()) } - yymv65 := yyv65[yymk65] + yymv115 := yyv115[yymk115] if r.TryDecodeAsNil() { - yymv65 = nil + yymv115 = nil } else { - yyv67 := &yymv65 - z.F.DecSliceStringX(yyv67, false, d) + yyv117 := &yymv115 + yym118 := z.DecBinary() + _ = yym118 + if false { + } else { + z.F.DecSliceStringX(yyv117, false, d) + } } - if yyv65 != nil { - yyv65[yymk65] = yymv65 + if yyv115 != nil { + yyv115[yymk115] = yymv115 } } - } else if yyl65 < 0 { - for yyj65 := 0; !r.CheckBreak(); yyj65++ { - if yyj65 > 0 { - r.ReadMapEntrySeparator() - } - var yymk65 string + } else if yyl115 < 0 { + for yyj115 := 0; !r.CheckBreak(); yyj115++ { + var yymk115 string if r.TryDecodeAsNil() { - yymk65 = "" + yymk115 = "" } else { - yymk65 = string(r.DecodeString()) + yymk115 = string(r.DecodeString()) } - r.ReadMapKVSeparator() - yymv65 := yyv65[yymk65] + yymv115 := yyv115[yymk115] if r.TryDecodeAsNil() { - yymv65 = nil + yymv115 = nil } else { - yyv69 := &yymv65 - z.F.DecSliceStringX(yyv69, false, d) + yyv120 := &yymv115 + yym121 := z.DecBinary() + _ = yym121 + if false { + } else { + z.F.DecSliceStringX(yyv120, false, d) + } } - if yyv65 != nil { - yyv65[yymk65] = yymv65 + if yyv115 != nil { + yyv115[yymk115] = yymv115 } } - r.ReadMapEnd() + r.ReadEnd() } // else len==0: TODO: Should we clear map entries? } -func (x codecSelfer4402) encNodes(v Nodes, e *codec1978.Encoder) { - var h codecSelfer4402 +func (x codecSelfer6669) encNodes(v Nodes, e *codec1978.Encoder) { + var h codecSelfer6669 z, r := codec1978.GenHelperEncoder(e) _, _, _ = h, z, r r.EncodeArrayStart(len(v)) - yys70 := !z.EncBinary() - if yys70 { - for yyi70, yyv70 := range v { - if yyi70 > 0 { - r.EncodeArrayEntrySeparator() - } - if yyv70 == nil { - r.EncodeNil() - } else { - yyv70.CodecEncodeSelf(e) - } - } - r.EncodeArrayEnd() - } else { - for _, yyv70 := range v { - if yyv70 == nil { - r.EncodeNil() - } else { - yyv70.CodecEncodeSelf(e) - } + for _, yyv122 := range v { + if yyv122 == nil { + r.EncodeNil() + } else { + yyv122.CodecEncodeSelf(e) } } + r.EncodeEnd() } -func (x codecSelfer4402) decNodes(v *Nodes, d *codec1978.Decoder) { - var h codecSelfer4402 +func (x codecSelfer6669) decNodes(v *Nodes, d *codec1978.Decoder) { + var h codecSelfer6669 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r - yyv71 := *v - yyh71, yyl71 := z.DecSliceHelperStart() + yyv123 := *v + yyh123, yyl123 := z.DecSliceHelperStart() - var yyc71 bool - if yyv71 == nil { - if yyl71 <= 0 { - yyv71 = make(Nodes, 0) + var yyc123 bool + _ = yyc123 + + if yyv123 == nil { + if yyl123 <= 0 { + yyv123 = make(Nodes, 0) } else { - yyv71 = make(Nodes, yyl71) + yyv123 = make(Nodes, yyl123) } - yyc71 = true + yyc123 = true } - if yyl71 == 0 { - if len(yyv71) != 0 { - yyv71 = yyv71[:0] - yyc71 = true + if yyl123 == 0 { + if len(yyv123) != 0 { + yyv123 = yyv123[:0] + yyc123 = true } - } else if yyl71 > 0 { + } else if yyl123 > 0 { - yyn71 := yyl71 - if yyl71 > cap(yyv71) { - yyv71 = make([]*Node, yyl71, yyl71) - yyc71 = true + yyn123 := yyl123 + if yyl123 > cap(yyv123) { + yyv123 = make([]*Node, yyl123, yyl123) + yyc123 = true - } else if yyl71 != len(yyv71) { - yyv71 = yyv71[:yyl71] - yyc71 = true + } else if yyl123 != len(yyv123) { + yyv123 = yyv123[:yyl123] + yyc123 = true } - yyj71 := 0 - for ; yyj71 < yyn71; yyj71++ { + yyj123 := 0 + for ; yyj123 < yyn123; yyj123++ { if r.TryDecodeAsNil() { - if yyv71[yyj71] != nil { - *yyv71[yyj71] = Node{} + if yyv123[yyj123] != nil { + *yyv123[yyj123] = Node{} } } else { - if yyv71[yyj71] == nil { - yyv71[yyj71] = new(Node) + if yyv123[yyj123] == nil { + yyv123[yyj123] = new(Node) } - yyw72 := yyv71[yyj71] - yyw72.CodecDecodeSelf(d) + yyw124 := yyv123[yyj123] + yyw124.CodecDecodeSelf(d) } } } else { - for yyj71 := 0; !r.CheckBreak(); yyj71++ { - if yyj71 >= len(yyv71) { - yyv71 = append(yyv71, nil) // var yyz71 *Node - yyc71 = true - } - if yyj71 > 0 { - yyh71.Sep(yyj71) + for yyj123 := 0; !r.CheckBreak(); yyj123++ { + if yyj123 >= len(yyv123) { + yyv123 = append(yyv123, nil) // var yyz123 *Node + yyc123 = true } - if yyj71 < len(yyv71) { + if yyj123 < len(yyv123) { if r.TryDecodeAsNil() { - if yyv71[yyj71] != nil { - *yyv71[yyj71] = Node{} + if yyv123[yyj123] != nil { + *yyv123[yyj123] = Node{} } } else { - if yyv71[yyj71] == nil { - yyv71[yyj71] = new(Node) + if yyv123[yyj123] == nil { + yyv123[yyj123] = new(Node) } - yyw73 := yyv71[yyj71] - yyw73.CodecDecodeSelf(d) + yyw125 := yyv123[yyj123] + yyw125.CodecDecodeSelf(d) } } else { @@ -1411,9 +1434,10 @@ func (x codecSelfer4402) decNodes(v *Nodes, d *codec1978.Decoder) { } } - yyh71.End() + yyh123.End() } - if yyc71 { - *v = yyv71 + if yyc123 { + *v = yyv123 } + } diff --git a/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/response_test.go b/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/response_test.go deleted file mode 100644 index 23e0c56eb..000000000 --- a/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/response_test.go +++ /dev/null @@ -1,75 +0,0 @@ -package etcd - -import ( - "net/http" - "reflect" - "strings" - "testing" - - "github.com/ugorji/go/codec" -) - -func createTestNode(size int) *Node { - return &Node{ - Key: strings.Repeat("a", 30), - Value: strings.Repeat("a", size), - TTL: 123456789, - ModifiedIndex: 123456, - CreatedIndex: 123456, - } -} - -func createTestNodeWithChildren(children, size int) *Node { - node := createTestNode(size) - for i := 0; i < children; i++ { - node.Nodes = append(node.Nodes, createTestNode(size)) - } - return node -} - -func createTestResponse(children, size int) *Response { - return &Response{ - Action: "aaaaa", - Node: createTestNodeWithChildren(children, size), - PrevNode: nil, - EtcdIndex: 123456, - RaftIndex: 123456, - RaftTerm: 123456, - } -} - -func benchmarkResponseUnmarshalling(b *testing.B, children, size int) { - response := createTestResponse(children, size) - - rr := RawResponse{http.StatusOK, make([]byte, 0), http.Header{}} - codec.NewEncoderBytes(&rr.Body, new(codec.JsonHandle)).Encode(response) - - b.ResetTimer() - newResponse := new(Response) - var err error - for i := 0; i < b.N; i++ { - if newResponse, err = rr.Unmarshal(); err != nil { - b.Errorf("Error: %v", err) - } - - } - if !reflect.DeepEqual(response.Node, newResponse.Node) { - b.Errorf("Unexpected difference in a parsed response: \n%+v\n%+v", response, newResponse) - } -} - -func BenchmarkSmallResponseUnmarshal(b *testing.B) { - benchmarkResponseUnmarshalling(b, 30, 20) -} - -func BenchmarkManySmallResponseUnmarshal(b *testing.B) { - benchmarkResponseUnmarshalling(b, 3000, 20) -} - -func BenchmarkMediumResponseUnmarshal(b *testing.B) { - benchmarkResponseUnmarshalling(b, 300, 200) -} - -func BenchmarkLargeResponseUnmarshal(b *testing.B) { - benchmarkResponseUnmarshalling(b, 3000, 2000) -} diff --git a/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/set_curl_chan_test.go b/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/set_curl_chan_test.go deleted file mode 100644 index 87c86b830..000000000 --- a/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/set_curl_chan_test.go +++ /dev/null @@ -1,42 +0,0 @@ -package etcd - -import ( - "fmt" - "testing" -) - -func TestSetCurlChan(t *testing.T) { - c := NewClient(nil) - c.OpenCURL() - - defer func() { - c.Delete("foo", true) - }() - - _, err := c.Set("foo", "bar", 5) - if err != nil { - t.Fatal(err) - } - - expected := fmt.Sprintf("curl -X PUT %s/v2/keys/foo -d value=bar -d ttl=5", - c.cluster.pick()) - actual := c.RecvCURL() - if expected != actual { - t.Fatalf(`Command "%s" is not equal to expected value "%s"`, - actual, expected) - } - - c.SetConsistency(STRONG_CONSISTENCY) - _, err = c.Get("foo", false, false) - if err != nil { - t.Fatal(err) - } - - expected = fmt.Sprintf("curl -X GET %s/v2/keys/foo?quorum=true&recursive=false&sorted=false", - c.cluster.pick()) - actual = c.RecvCURL() - if expected != actual { - t.Fatalf(`Command "%s" is not equal to expected value "%s"`, - actual, expected) - } -} diff --git a/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/set_update_create_test.go b/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/set_update_create_test.go deleted file mode 100644 index ced0f06e7..000000000 --- a/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/set_update_create_test.go +++ /dev/null @@ -1,241 +0,0 @@ -package etcd - -import ( - "testing" -) - -func TestSet(t *testing.T) { - c := NewClient(nil) - defer func() { - c.Delete("foo", true) - }() - - resp, err := c.Set("foo", "bar", 5) - if err != nil { - t.Fatal(err) - } - if resp.Node.Key != "/foo" || resp.Node.Value != "bar" || resp.Node.TTL != 5 { - t.Fatalf("Set 1 failed: %#v", resp) - } - if resp.PrevNode != nil { - t.Fatalf("Set 1 PrevNode failed: %#v", resp) - } - - resp, err = c.Set("foo", "bar2", 5) - if err != nil { - t.Fatal(err) - } - if !(resp.Node.Key == "/foo" && resp.Node.Value == "bar2" && resp.Node.TTL == 5) { - t.Fatalf("Set 2 failed: %#v", resp) - } - if resp.PrevNode.Key != "/foo" || resp.PrevNode.Value != "bar" || resp.Node.TTL != 5 { - t.Fatalf("Set 2 PrevNode failed: %#v", resp) - } -} - -func TestUpdate(t *testing.T) { - c := NewClient(nil) - defer func() { - c.Delete("foo", true) - c.Delete("nonexistent", true) - }() - - resp, err := c.Set("foo", "bar", 5) - - if err != nil { - t.Fatal(err) - } - - // This should succeed. - resp, err = c.Update("foo", "wakawaka", 5) - if err != nil { - t.Fatal(err) - } - - if !(resp.Action == "update" && resp.Node.Key == "/foo" && resp.Node.TTL == 5) { - t.Fatalf("Update 1 failed: %#v", resp) - } - if !(resp.PrevNode.Key == "/foo" && resp.PrevNode.Value == "bar" && resp.Node.TTL == 5) { - t.Fatalf("Update 1 prevValue failed: %#v", resp) - } - - // This should fail because the key does not exist. - resp, err = c.Update("nonexistent", "whatever", 5) - if err == nil { - t.Fatalf("The key %v did not exist, so the update should have failed."+ - "The response was: %#v", resp.Node.Key, resp) - } -} - -func TestCreate(t *testing.T) { - c := NewClient(nil) - defer func() { - c.Delete("newKey", true) - }() - - newKey := "/newKey" - newValue := "/newValue" - - // This should succeed - resp, err := c.Create(newKey, newValue, 5) - if err != nil { - t.Fatal(err) - } - - if !(resp.Action == "create" && resp.Node.Key == newKey && - resp.Node.Value == newValue && resp.Node.TTL == 5) { - t.Fatalf("Create 1 failed: %#v", resp) - } - if resp.PrevNode != nil { - t.Fatalf("Create 1 PrevNode failed: %#v", resp) - } - - // This should fail, because the key is already there - resp, err = c.Create(newKey, newValue, 5) - if err == nil { - t.Fatalf("The key %v did exist, so the creation should have failed."+ - "The response was: %#v", resp.Node.Key, resp) - } -} - -func TestCreateInOrder(t *testing.T) { - c := NewClient(nil) - dir := "/queue" - defer func() { - c.DeleteDir(dir) - }() - - var firstKey, secondKey string - - resp, err := c.CreateInOrder(dir, "1", 5) - if err != nil { - t.Fatal(err) - } - - if !(resp.Action == "create" && resp.Node.Value == "1" && resp.Node.TTL == 5) { - t.Fatalf("Create 1 failed: %#v", resp) - } - - firstKey = resp.Node.Key - - resp, err = c.CreateInOrder(dir, "2", 5) - if err != nil { - t.Fatal(err) - } - - if !(resp.Action == "create" && resp.Node.Value == "2" && resp.Node.TTL == 5) { - t.Fatalf("Create 2 failed: %#v", resp) - } - - secondKey = resp.Node.Key - - if firstKey >= secondKey { - t.Fatalf("Expected first key to be greater than second key, but %s is not greater than %s", - firstKey, secondKey) - } -} - -func TestSetDir(t *testing.T) { - c := NewClient(nil) - defer func() { - c.Delete("foo", true) - c.Delete("fooDir", true) - }() - - resp, err := c.CreateDir("fooDir", 5) - if err != nil { - t.Fatal(err) - } - if !(resp.Node.Key == "/fooDir" && resp.Node.Value == "" && resp.Node.TTL == 5) { - t.Fatalf("SetDir 1 failed: %#v", resp) - } - if resp.PrevNode != nil { - t.Fatalf("SetDir 1 PrevNode failed: %#v", resp) - } - - // This should fail because /fooDir already points to a directory - resp, err = c.CreateDir("/fooDir", 5) - if err == nil { - t.Fatalf("fooDir already points to a directory, so SetDir should have failed."+ - "The response was: %#v", resp) - } - - _, err = c.Set("foo", "bar", 5) - if err != nil { - t.Fatal(err) - } - - // This should succeed - // It should replace the key - resp, err = c.SetDir("foo", 5) - if err != nil { - t.Fatal(err) - } - if !(resp.Node.Key == "/foo" && resp.Node.Value == "" && resp.Node.TTL == 5) { - t.Fatalf("SetDir 2 failed: %#v", resp) - } - if !(resp.PrevNode.Key == "/foo" && resp.PrevNode.Value == "bar" && resp.PrevNode.TTL == 5) { - t.Fatalf("SetDir 2 failed: %#v", resp) - } -} - -func TestUpdateDir(t *testing.T) { - c := NewClient(nil) - defer func() { - c.Delete("fooDir", true) - }() - - resp, err := c.CreateDir("fooDir", 5) - if err != nil { - t.Fatal(err) - } - - // This should succeed. - resp, err = c.UpdateDir("fooDir", 5) - if err != nil { - t.Fatal(err) - } - - if !(resp.Action == "update" && resp.Node.Key == "/fooDir" && - resp.Node.Value == "" && resp.Node.TTL == 5) { - t.Fatalf("UpdateDir 1 failed: %#v", resp) - } - if !(resp.PrevNode.Key == "/fooDir" && resp.PrevNode.Dir == true && resp.PrevNode.TTL == 5) { - t.Fatalf("UpdateDir 1 PrevNode failed: %#v", resp) - } - - // This should fail because the key does not exist. - resp, err = c.UpdateDir("nonexistentDir", 5) - if err == nil { - t.Fatalf("The key %v did not exist, so the update should have failed."+ - "The response was: %#v", resp.Node.Key, resp) - } -} - -func TestCreateDir(t *testing.T) { - c := NewClient(nil) - defer func() { - c.Delete("fooDir", true) - }() - - // This should succeed - resp, err := c.CreateDir("fooDir", 5) - if err != nil { - t.Fatal(err) - } - - if !(resp.Action == "create" && resp.Node.Key == "/fooDir" && - resp.Node.Value == "" && resp.Node.TTL == 5) { - t.Fatalf("CreateDir 1 failed: %#v", resp) - } - if resp.PrevNode != nil { - t.Fatalf("CreateDir 1 PrevNode failed: %#v", resp) - } - - // This should fail, because the key is already there - resp, err = c.CreateDir("fooDir", 5) - if err == nil { - t.Fatalf("The key %v did exist, so the creation should have failed."+ - "The response was: %#v", resp.Node.Key, resp) - } -} diff --git a/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/watch_test.go b/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/watch_test.go deleted file mode 100644 index 43e1dfeb8..000000000 --- a/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/watch_test.go +++ /dev/null @@ -1,119 +0,0 @@ -package etcd - -import ( - "fmt" - "runtime" - "testing" - "time" -) - -func TestWatch(t *testing.T) { - c := NewClient(nil) - defer func() { - c.Delete("watch_foo", true) - }() - - go setHelper("watch_foo", "bar", c) - - resp, err := c.Watch("watch_foo", 0, false, nil, nil) - if err != nil { - t.Fatal(err) - } - if !(resp.Node.Key == "/watch_foo" && resp.Node.Value == "bar") { - t.Fatalf("Watch 1 failed: %#v", resp) - } - - go setHelper("watch_foo", "bar", c) - - resp, err = c.Watch("watch_foo", resp.Node.ModifiedIndex+1, false, nil, nil) - if err != nil { - t.Fatal(err) - } - if !(resp.Node.Key == "/watch_foo" && resp.Node.Value == "bar") { - t.Fatalf("Watch 2 failed: %#v", resp) - } - - routineNum := runtime.NumGoroutine() - - ch := make(chan *Response, 10) - stop := make(chan bool, 1) - - go setLoop("watch_foo", "bar", c) - - go receiver(ch, stop) - - _, err = c.Watch("watch_foo", 0, false, ch, stop) - if err != ErrWatchStoppedByUser { - t.Fatalf("Watch returned a non-user stop error") - } - - if newRoutineNum := runtime.NumGoroutine(); newRoutineNum != routineNum { - t.Fatalf("Routine numbers differ after watch stop: %v, %v", routineNum, newRoutineNum) - } -} - -func TestWatchAll(t *testing.T) { - c := NewClient(nil) - defer func() { - c.Delete("watch_foo", true) - }() - - go setHelper("watch_foo/foo", "bar", c) - - resp, err := c.Watch("watch_foo", 0, true, nil, nil) - if err != nil { - t.Fatal(err) - } - if !(resp.Node.Key == "/watch_foo/foo" && resp.Node.Value == "bar") { - t.Fatalf("WatchAll 1 failed: %#v", resp) - } - - go setHelper("watch_foo/foo", "bar", c) - - resp, err = c.Watch("watch_foo", resp.Node.ModifiedIndex+1, true, nil, nil) - if err != nil { - t.Fatal(err) - } - if !(resp.Node.Key == "/watch_foo/foo" && resp.Node.Value == "bar") { - t.Fatalf("WatchAll 2 failed: %#v", resp) - } - - ch := make(chan *Response, 10) - stop := make(chan bool, 1) - - routineNum := runtime.NumGoroutine() - - go setLoop("watch_foo/foo", "bar", c) - - go receiver(ch, stop) - - _, err = c.Watch("watch_foo", 0, true, ch, stop) - if err != ErrWatchStoppedByUser { - t.Fatalf("Watch returned a non-user stop error") - } - - if newRoutineNum := runtime.NumGoroutine(); newRoutineNum != routineNum { - t.Fatalf("Routine numbers differ after watch stop: %v, %v", routineNum, newRoutineNum) - } -} - -func setHelper(key, value string, c *Client) { - time.Sleep(time.Second) - c.Set(key, value, 100) -} - -func setLoop(key, value string, c *Client) { - time.Sleep(time.Second) - for i := 0; i < 10; i++ { - newValue := fmt.Sprintf("%s_%v", value, i) - c.Set(key, newValue, 100) - time.Sleep(time.Second / 10) - } -} - -func receiver(c chan *Response, stop chan bool) { - for i := 0; i < 10; i++ { - <-c - } - stop <- true -} diff --git a/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/.travis.yml b/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/.travis.yml index dfe286eb0..d6089146c 100644 --- a/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/.travis.yml +++ b/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/.travis.yml @@ -3,3 +3,5 @@ language: go go: - 1.3.3 - 1.4.2 + - 1.5 + - tip diff --git a/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/README.md b/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/README.md index 1435ddba0..001c0a338 100644 --- a/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/README.md +++ b/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/README.md @@ -48,6 +48,12 @@ Parsing and verifying tokens is pretty straight forward. You pass in the token tokenString, err := token.SignedString(mySigningKey) ``` +## 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 + ## 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). diff --git a/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/ecdsa_test.go b/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/ecdsa_test.go deleted file mode 100644 index 98e3e5edb..000000000 --- a/Godeps/_workspace/src/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"}, - "eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.MEQCIHoSJnmGlPaVQDqacx_2XlXEhhqtWceVopjomc2PJLtdAiAUTeGPoNYxZw0z8mgOnnIcjoxRuNDVZvybRZF3wR1l8w", - "ES256", - map[string]interface{}{"foo": "bar"}, - true, - }, - { - "Basic ES384", - map[string]string{"private": "test/ec384-private.pem", "public": "test/ec384-public.pem"}, - "eyJhbGciOiJFUzM4NCIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.MGUCMQCHBr61FXDuFY9xUhyp8iWQAuBIaSgaf1z2j_8XrKcCfzTPzoSa3SZKq-m3L492xe8CMG3kafRMeuaN5Aw8ZJxmOLhkTo4D3-LaGzcaUWINvWvkwFMl7dMC863s0gov6xvXuA", - "ES384", - map[string]interface{}{"foo": "bar"}, - true, - }, - { - "Basic ES512", - map[string]string{"private": "test/ec512-private.pem", "public": "test/ec512-public.pem"}, - "eyJhbGciOiJFUzUxMiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.MIGIAkIAmVKjdJE5lG1byOFgZZVTeNDRp6E7SNvUj0UrvpzoBH6nrleWVTcwfHzbwWuooNpPADDSFR_Ql3ze-Vwwi8hBqQsCQgHn-ZooL8zegkOVeEEsqd7WHWdhb8UekFCYw3X8JnNP-D3wvZQ1-tkkHakt5gZ2-xO29TxfSPun4ViGkMYa7Q4N-Q", - "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/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/example_test.go b/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/example_test.go deleted file mode 100644 index edb48e4db..000000000 --- a/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/example_test.go +++ /dev/null @@ -1,52 +0,0 @@ -package jwt_test - -import ( - "fmt" - "github.com/dgrijalva/jwt-go" - "time" -) - -func ExampleParse(myToken string, myLookupKey func(interface{}) (interface{}, error)) { - token, err := jwt.Parse(myToken, func(token *jwt.Token) (interface{}, error) { - return myLookupKey(token.Header["kid"]) - }) - - if err == nil && token.Valid { - fmt.Println("Your token is valid. I like your style.") - } else { - fmt.Println("This token is terrible! I cannot accept this.") - } -} - -func ExampleNew(mySigningKey []byte) (string, error) { - // Create the token - token := jwt.New(jwt.SigningMethodHS256) - // Set some claims - token.Claims["foo"] = "bar" - token.Claims["exp"] = time.Now().Add(time.Hour * 72).Unix() - // Sign and get the complete encoded token as a string - tokenString, err := token.SignedString(mySigningKey) - return tokenString, err -} - -func ExampleParse_errorChecking(myToken string, myLookupKey func(interface{}) (interface{}, error)) { - token, err := jwt.Parse(myToken, func(token *jwt.Token) (interface{}, error) { - return myLookupKey(token.Header["kid"]) - }) - - 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) - } - -} diff --git a/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/hmac_test.go b/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/hmac_test.go deleted file mode 100644 index c7e114f4f..000000000 --- a/Godeps/_workspace/src/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/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/jwt_test.go b/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/jwt_test.go deleted file mode 100644 index 9108dedb4..000000000 --- a/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/jwt_test.go +++ /dev/null @@ -1,187 +0,0 @@ -package jwt_test - -import ( - "fmt" - "github.com/dgrijalva/jwt-go" - "io/ioutil" - "net/http" - "reflect" - "testing" - "time" -) - -var ( - jwtTestDefaultKey []byte - 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, fmt.Errorf("error loading key") } - nilKeyFunc jwt.Keyfunc = nil -) - -var jwtTestData = []struct { - name string - tokenString string - keyfunc jwt.Keyfunc - claims map[string]interface{} - valid bool - errors uint32 -}{ - { - "basic", - "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.FhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg", - defaultKeyFunc, - map[string]interface{}{"foo": "bar"}, - true, - 0, - }, - { - "basic expired", - "", // autogen - defaultKeyFunc, - map[string]interface{}{"foo": "bar", "exp": float64(time.Now().Unix() - 100)}, - false, - jwt.ValidationErrorExpired, - }, - { - "basic nbf", - "", // autogen - defaultKeyFunc, - map[string]interface{}{"foo": "bar", "nbf": float64(time.Now().Unix() + 100)}, - false, - jwt.ValidationErrorNotValidYet, - }, - { - "expired and nbf", - "", // autogen - defaultKeyFunc, - map[string]interface{}{"foo": "bar", "nbf": float64(time.Now().Unix() + 100), "exp": float64(time.Now().Unix() - 100)}, - false, - jwt.ValidationErrorNotValidYet | jwt.ValidationErrorExpired, - }, - { - "basic invalid", - "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.EhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg", - defaultKeyFunc, - map[string]interface{}{"foo": "bar"}, - false, - jwt.ValidationErrorSignatureInvalid, - }, - { - "basic nokeyfunc", - "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.FhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg", - nilKeyFunc, - map[string]interface{}{"foo": "bar"}, - false, - jwt.ValidationErrorUnverifiable, - }, - { - "basic nokey", - "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.FhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg", - emptyKeyFunc, - map[string]interface{}{"foo": "bar"}, - false, - jwt.ValidationErrorSignatureInvalid, - }, - { - "basic errorkey", - "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.FhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg", - errorKeyFunc, - map[string]interface{}{"foo": "bar"}, - false, - jwt.ValidationErrorUnverifiable, - }, -} - -func init() { - var e error - if jwtTestDefaultKey, e = ioutil.ReadFile("test/sample_key.pub"); e != nil { - panic(e) - } -} - -func makeSample(c map[string]interface{}) string { - key, e := ioutil.ReadFile("test/sample_key") - if e != nil { - panic(e.Error()) - } - - token := jwt.New(jwt.SigningMethodRS256) - token.Claims = c - s, e := token.SignedString(key) - - if e != nil { - panic(e.Error()) - } - - return s -} - -func TestJWT(t *testing.T) { - for _, data := range jwtTestData { - if data.tokenString == "" { - data.tokenString = makeSample(data.claims) - } - token, err := jwt.Parse(data.tokenString, data.keyfunc) - - 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 data.errors != 0 { - if err == nil { - t.Errorf("[%v] Expecting error. Didn't get one.", data.name) - } else { - // compare the bitfield part of the error - if err.(*jwt.ValidationError).Errors != data.errors { - t.Errorf("[%v] Errors don't match expectation", data.name) - } - - } - } - } -} - -func TestParseRequest(t *testing.T) { - // Bearer token request - for _, data := range jwtTestData { - if data.tokenString == "" { - data.tokenString = makeSample(data.claims) - } - - r, _ := http.NewRequest("GET", "/", nil) - r.Header.Set("Authorization", fmt.Sprintf("Bearer %v", data.tokenString)) - token, err := jwt.ParseFromRequest(r, data.keyfunc) - - if token == nil { - t.Errorf("[%v] Token was not found: %v", data.name, err) - continue - } - 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: %v", data.name, err) - } - if !data.valid && err == nil { - t.Errorf("[%v] Invalid token passed validation", 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/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/rsa_pss_test.go b/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/rsa_pss_test.go deleted file mode 100644 index 9045aaf34..000000000 --- a/Godeps/_workspace/src/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/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/rsa_test.go b/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/rsa_test.go deleted file mode 100644 index 13ba1fcdc..000000000 --- a/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/rsa_test.go +++ /dev/null @@ -1,174 +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) { - key, _ := ioutil.ReadFile("test/sample_key.pub") - - 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) { - key, _ := ioutil.ReadFile("test/sample_key") - - 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/Godeps/_workspace/src/github.com/duosecurity/duo_api_golang/authapi/authapi_test.go b/Godeps/_workspace/src/github.com/duosecurity/duo_api_golang/authapi/authapi_test.go deleted file mode 100644 index 45fbbaf95..000000000 --- a/Godeps/_workspace/src/github.com/duosecurity/duo_api_golang/authapi/authapi_test.go +++ /dev/null @@ -1,497 +0,0 @@ -package authapi - -import ( - "testing" - "fmt" - "strings" - "net/http" - "net/http/httptest" - "time" - "github.com/duosecurity/duo_api_golang" - ) - -func buildAuthApi(url string) *AuthApi { - ikey := "eyekey" - skey := "esskey" - host := strings.Split(url, "//")[1] - userAgent := "GoTestClient" - return NewAuthApi(*duoapi.NewDuoApi(ikey, - skey, - host, - userAgent, - duoapi.SetTimeout(1*time.Second), - duoapi.SetInsecure())) -} - -// Timeouts are set to 1 second. Take 15 seconds to respond and verify -// that the client times out. -func TestTimeout(t *testing.T) { - ts := httptest.NewTLSServer(http.HandlerFunc(func (w http.ResponseWriter, r *http.Request) { - time.Sleep(15*time.Second) - })) - - duo := buildAuthApi(ts.URL) - - start := time.Now() - _, err := duo.Ping() - duration := time.Since(start) - if duration.Seconds() > 2 { - t.Error("Timeout took %d seconds", duration.Seconds()) - } - if err == nil { - t.Error("Expected timeout error.") - } -} - -// Test a successful ping request / response. -func TestPing(t *testing.T) { - ts := httptest.NewTLSServer(http.HandlerFunc(func (w http.ResponseWriter, r *http.Request) { - fmt.Fprintln(w, ` - { - "stat": "OK", - "response": { - "time": 1357020061, - "unexpected_parameter" : "blah" - } - }`) - })) - defer ts.Close() - - duo := buildAuthApi(ts.URL) - - result, err := duo.Ping() - if err != nil { - t.Error("Unexpected error from Ping call" + err.Error()) - } - if result.Stat != "OK" { - t.Error("Expected OK, but got " + result.Stat) - } - if result.Response.Time != 1357020061 { - t.Errorf("Expected 1357020061, but got %d", result.Response.Time) - } -} - -// Test a successful Check request / response. -func TestCheck(t *testing.T) { - ts := httptest.NewTLSServer( - http.HandlerFunc( - func (w http.ResponseWriter, r *http.Request) { - fmt.Fprintln(w, ` - { - "stat": "OK", - "response": { - "time": 1357020061 - } - }`)})) - defer ts.Close() - - duo := buildAuthApi(ts.URL) - - result, err := duo.Check() - if err != nil { - t.Error("Failed TestCheck: " + err.Error()) - } - if result.Stat != "OK" { - t.Error("Expected OK, but got " + result.Stat) - } - if result.Response.Time != 1357020061 { - t.Errorf("Expected 1357020061, but got %d", result.Response.Time) - } -} - -// Test a successful logo request / response. -func TestLogo(t *testing.T) { - ts := httptest.NewTLSServer( - http.HandlerFunc( - func (w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "image/png") - w.Write([]byte("\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00" + - "\x00\x00\x01\x00\x00\x00\x01\x08\x06\x00" + - "\x00\x00\x1f\x15\xc4\x89\x00\x00\x00\nIDATx" + - "\x9cc\x00\x01\x00\x00\x05\x00\x01\r\n-\xb4\x00" + - "\x00\x00\x00IEND\xaeB`\x82")) - })) - defer ts.Close() - - duo := buildAuthApi(ts.URL) - - _, err := duo.Logo() - if err != nil { - t.Error("Failed TestCheck: " + err.Error()) - } -} - -// Test a failure logo reqeust / response. -func TestLogoError(t *testing.T) { - ts := httptest.NewTLSServer( - http.HandlerFunc( - func (w http.ResponseWriter, r *http.Request) { - // Return a 400, as if the logo was not found. - w.WriteHeader(400) - fmt.Fprintln(w, ` - { - "stat": "FAIL", - "code": 40002, - "message": "Logo not found", - "message_detail": "Why u no have logo?" - }`) - })) - defer ts.Close() - - duo := buildAuthApi(ts.URL) - - res, err := duo.Logo() - if err != nil { - t.Error("Failed TestCheck: " + err.Error()) - } - if res.Stat != "FAIL" { - t.Error("Expected FAIL, but got " + res.Stat) - } - if res.Code == nil || *res.Code != 40002 { - t.Error("Unexpected response code.") - } - if res.Message == nil || *res.Message != "Logo not found" { - t.Error("Unexpected message.") - } - if res.Message_Detail == nil || *res.Message_Detail != "Why u no have logo?" { - t.Error("Unexpected message detail.") - } -} - -// Test a successful enroll request / response. -func TestEnroll(t *testing.T) { - ts := httptest.NewTLSServer( - http.HandlerFunc( - func (w http.ResponseWriter, r *http.Request) { - if r.FormValue("username") != "49c6c3097adb386048c84354d82ea63d" { - t.Error("TestEnroll failed to set 'username' query parameter:" + - r.RequestURI) - } - if r.FormValue("valid_secs") != "10" { - t.Error("TestEnroll failed to set 'valid_secs' query parameter: " + - r.RequestURI) - } - fmt.Fprintln(w, ` - { - "stat": "OK", - "response": { - "activation_barcode": "https://api-eval.duosecurity.com/frame/qr?value=8LIRa5danrICkhHtkLxi-cKLu2DWzDYCmBwBHY2YzW5ZYnYaRxA", - "activation_code": "duo://8LIRa5danrICkhHtkLxi-cKLu2DWzDYCmBwBHY2YzW5ZYnYaRxA", - "expiration": 1357020061, - "user_id": "DU94SWSN4ADHHJHF2HXT", - "username": "49c6c3097adb386048c84354d82ea63d" - } - }`)})) - defer ts.Close() - - duo := buildAuthApi(ts.URL) - - result, err := duo.Enroll(EnrollUsername("49c6c3097adb386048c84354d82ea63d"), EnrollValidSeconds(10)) - if err != nil { - t.Error("Failed TestEnroll: " + err.Error()) - } - if result.Stat != "OK" { - t.Error("Expected OK, but got " + result.Stat) - } - if result.Response.Activation_Barcode != "https://api-eval.duosecurity.com/frame/qr?value=8LIRa5danrICkhHtkLxi-cKLu2DWzDYCmBwBHY2YzW5ZYnYaRxA" { - t.Error("Unexpected activation_barcode: " + result.Response.Activation_Barcode) - } - if result.Response.Activation_Code != "duo://8LIRa5danrICkhHtkLxi-cKLu2DWzDYCmBwBHY2YzW5ZYnYaRxA" { - t.Error("Unexpected activation code: " + result.Response.Activation_Code) - } - if result.Response.Expiration != 1357020061 { - t.Errorf("Unexpected expiration time: %d", result.Response.Expiration) - } - if result.Response.User_Id != "DU94SWSN4ADHHJHF2HXT" { - t.Error("Unexpected user id: " + result.Response.User_Id) - } - if result.Response.Username != "49c6c3097adb386048c84354d82ea63d" { - t.Error("Unexpected username: " + result.Response.Username) - } -} - -// Test a succesful enroll status request / response. -func TestEnrollStatus(t *testing.T) { - ts := httptest.NewTLSServer( - http.HandlerFunc( - func (w http.ResponseWriter, r *http.Request) { - if r.FormValue("user_id") != "49c6c3097adb386048c84354d82ea63d" { - t.Error("TestEnrollStatus failed to set 'user_id' query parameter:" + - r.RequestURI) - } - if r.FormValue("activation_code") != "10" { - t.Error("TestEnrollStatus failed to set 'activation_code' query parameter: " + - r.RequestURI) - } - fmt.Fprintln(w, ` - { - "stat": "OK", - "response": "success" - }`)})) - defer ts.Close() - - duo := buildAuthApi(ts.URL) - - result, err := duo.EnrollStatus("49c6c3097adb386048c84354d82ea63d", "10") - if err != nil { - t.Error("Failed TestEnrollStatus: " + err.Error()) - } - if result.Stat != "OK" { - t.Error("Expected OK, but got " + result.Stat) - } - if result.Response != "success" { - t.Error("Unexpected response: " + result.Response) - } -} - -// Test a successful preauth with user id. The client doesn't enforce api requirements, -// such as requiring only one of user id or username, but we'll cover the username -// in another test anyway. -func TestPreauthUserId(t *testing.T) { - ts := httptest.NewTLSServer( - http.HandlerFunc( - func (w http.ResponseWriter, r *http.Request) { - if r.FormValue("ipaddr") != "127.0.0.1" { - t.Error("TestPreauth failed to set 'ipaddr' query parameter:" + - r.RequestURI) - } - if r.FormValue("user_id") != "10" { - t.Error("TestEnrollStatus failed to set 'user_id' query parameter: " + - r.RequestURI) - } - if r.FormValue("trusted_device_token") != "l33t" { - t.Error("TestEnrollStatus failed to set 'trusted_device_token' query parameter: " + - r.RequestURI) - } - fmt.Fprintln(w, ` - { - "stat": "OK", - "response": { - "result": "auth", - "status_msg": "Account is active", - "devices": [ - { - "device": "DPFZRS9FB0D46QFTM891", - "type": "phone", - "number": "XXX-XXX-0100", - "name": "", - "capabilities": [ - "push", - "sms", - "phone" - ] - }, - { - "device": "DHEKH0JJIYC1LX3AZWO4", - "type": "token", - "name": "0" - } - ] - } - }`)})) - defer ts.Close() - - duo := buildAuthApi(ts.URL) - - res, err := duo.Preauth(PreauthUserId("10"), PreauthIpAddr("127.0.0.1"), PreauthTrustedToken("l33t")) - if err != nil { - t.Error("Failed TestPreauthUserId: " + err.Error()) - } - if res.Stat != "OK" { - t.Error("Unexpected stat: " + res.Stat) - } - if res.Response.Result != "auth" { - t.Error("Unexpected response result: " + res.Response.Result) - } - if res.Response.Status_Msg != "Account is active" { - t.Error("Unexpected status message: " + res.Response.Status_Msg) - } - if len(res.Response.Devices) != 2 { - t.Errorf("Unexpected devices length: %d", len(res.Response.Devices)) - } - if res.Response.Devices[0].Device != "DPFZRS9FB0D46QFTM891" { - t.Error("Unexpected [0] device name: " + res.Response.Devices[0].Device) - } - if res.Response.Devices[0].Type != "phone" { - t.Error("Unexpected [0] device type: " + res.Response.Devices[0].Type) - } - if res.Response.Devices[0].Number != "XXX-XXX-0100" { - t.Error("Unexpected [0] device number: " + res.Response.Devices[0].Number) - } - if res.Response.Devices[0].Name != "" { - t.Error("Unexpected [0] devices name :" + res.Response.Devices[0].Name) - } - if len(res.Response.Devices[0].Capabilities) != 3 { - t.Errorf("Unexpected [0] device capabilities length: %d", len(res.Response.Devices[0].Capabilities)) - } - if res.Response.Devices[0].Capabilities[0] != "push" { - t.Error("Unexpected [0] device capability: " + res.Response.Devices[0].Capabilities[0]) - } - if res.Response.Devices[0].Capabilities[1] != "sms" { - t.Error("Unexpected [0] device capability: " + res.Response.Devices[0].Capabilities[1]) - } - if res.Response.Devices[0].Capabilities[2] != "phone" { - t.Error("Unexpected [0] device capability: " + res.Response.Devices[0].Capabilities[2]) - } - if res.Response.Devices[1].Device != "DHEKH0JJIYC1LX3AZWO4" { - t.Error("Unexpected [1] device name: " + res.Response.Devices[1].Device) - } - if res.Response.Devices[1].Type != "token" { - t.Error("Unexpected [1] device type: " + res.Response.Devices[1].Type) - } - if res.Response.Devices[1].Name != "0" { - t.Error("Unexpected [1] devices name :" + res.Response.Devices[1].Name) - } - if len(res.Response.Devices[1].Capabilities) != 0 { - t.Errorf("Unexpected [1] device capabilities length: %d", len(res.Response.Devices[1].Capabilities)) - } -} - -// Test preauth enroll with username, and an enroll response. -func TestPreauthEnroll(t *testing.T) { - ts := httptest.NewTLSServer( - http.HandlerFunc( - func (w http.ResponseWriter, r *http.Request) { - if r.FormValue("username") != "10" { - t.Error("TestEnrollStatus failed to set 'username' query parameter: " + - r.RequestURI) - } - fmt.Fprintln(w, ` - { - "stat": "OK", - "response": { - "enroll_portal_url": "https://api-3945ef22.duosecurity.com/portal?48bac5d9393fb2c2", - "result": "enroll", - "status_msg": "Enroll an authentication device to proceed" - } - }`)})) - defer ts.Close() - - duo := buildAuthApi(ts.URL) - - res, err := duo.Preauth(PreauthUsername("10")) - if err != nil { - t.Error("Failed TestPreauthEnroll: " + err.Error()) - } - if res.Stat != "OK" { - t.Error("Unexpected stat: " + res.Stat) - } - if res.Response.Enroll_Portal_Url != "https://api-3945ef22.duosecurity.com/portal?48bac5d9393fb2c2" { - t.Error("Unexpected enroll portal URL: " + res.Response.Enroll_Portal_Url) - } - if res.Response.Result != "enroll" { - t.Error("Unexpected response result: " + res.Response.Result) - } - if res.Response.Status_Msg != "Enroll an authentication device to proceed" { - t.Error("Unexpected status msg: " + res.Response.Status_Msg) - } -} - -// Test an authentication request / response. This won't work against the Duo -// server, because the request parameters included are illegal. But we can -// verify that the go code sets the query parameters correctly. -func TestAuth(t *testing.T) { - ts := httptest.NewTLSServer( - http.HandlerFunc( - func (w http.ResponseWriter, r *http.Request) { - expected := map[string]string { - "username" : "username value", - "user_id" : "user_id value", - "factor" : "auto", - "ipaddr" : "40.40.40.10", - "async" : "1", - "device" : "primary", - "type" : "request", - "display_username" : "display username", - - } - for key, value := range expected { - if r.FormValue(key) != value { - t.Errorf("TestAuth failed to set '%s' query parameter: " + - r.RequestURI, key) - } - } - fmt.Fprintln(w, ` - { - "stat": "OK", - "response": { - "result": "allow", - "status": "allow", - "status_msg": "Success. Logging you in..." - } - }`)})) - defer ts.Close() - - duo := buildAuthApi(ts.URL) - - res, err := duo.Auth("auto", - AuthUserId("user_id value"), - AuthUsername("username value"), - AuthIpAddr("40.40.40.10"), - AuthAsync(), - AuthDevice("primary"), - AuthType("request"), - AuthDisplayUsername("display username"), - ) - if err != nil { - t.Error("Failed TestAuth: " + err.Error()) - } - if res.Stat != "OK" { - t.Error("Unexpected stat: " + res.Stat) - } - if res.Response.Result != "allow" { - t.Error("Unexpected response result: " + res.Response.Result) - } - if res.Response.Status != "allow" { - t.Error("Unexpected response status: " + res.Response.Status) - } - if res.Response.Status_Msg != "Success. Logging you in..." { - t.Error("Unexpected response status msg: " + res.Response.Status_Msg) - } -} - -// Test AuthStatus request / response. -func TestAuthStatus(t *testing.T) { - ts := httptest.NewTLSServer( - http.HandlerFunc( - func (w http.ResponseWriter, r *http.Request) { - expected := map[string]string { - "txid" : "4", - } - for key, value := range expected { - if r.FormValue(key) != value { - t.Errorf("TestAuthStatus failed to set '%s' query parameter: " + - r.RequestURI, key) - } - } - fmt.Fprintln(w, ` - { - "stat": "OK", - "response": { - "result": "waiting", - "status": "pushed", - "status_msg": "Pushed a login request to your phone..." - } - }`)})) - defer ts.Close() - - duo := buildAuthApi(ts.URL) - - res, err := duo.AuthStatus("4") - if err != nil { - t.Error("Failed TestAuthStatus: " + err.Error()) - } - - if res.Stat != "OK" { - t.Error("Unexpected stat: " + res.Stat) - } - if res.Response.Result != "waiting" { - t.Error("Unexpected response result: " + res.Response.Result) - } - if res.Response.Status != "pushed" { - t.Error("Unexpected response status: " + res.Response.Status) - } - if res.Response.Status_Msg != "Pushed a login request to your phone..." { - t.Error("Unexpected response status msg: " + res.Response.Status_Msg) - } -} diff --git a/Godeps/_workspace/src/github.com/duosecurity/duo_api_golang/duo_test.go b/Godeps/_workspace/src/github.com/duosecurity/duo_api_golang/duo_test.go deleted file mode 100644 index 01278457e..000000000 --- a/Godeps/_workspace/src/github.com/duosecurity/duo_api_golang/duo_test.go +++ /dev/null @@ -1,156 +0,0 @@ -package duoapi - -import ( - "testing" - "net/url" - "strings" -) - -func TestCanonicalize(t *testing.T) { - values := url.Values{} - values.Set("username", "H ell?o") - values.Set("password", "H-._~i") - values.Add("password", "A(!'*)") - params_str := canonicalize("post", - "API-XXX.duosecurity.COM", - "/auth/v2/ping", - values, - "5") - params := strings.Split(params_str, "\n") - if len(params) != 5 { - t.Error("Expected 5 parameters, but got " + string(len(params))) - } - if params[1] != string("POST") { - t.Error("Expected POST, but got " + params[1]) - } - if params[2] != string("api-xxx.duosecurity.com") { - t.Error("Expected api-xxx.duosecurity.com, but got " + params[2]) - } - if params[3] != string("/auth/v2/ping") { - t.Error("Expected /auth/v2/ping, but got " + params[3]) - } - if params[4] != string("password=A%28%21%27%2A%29&password=H-._~i&username=H%20ell%3Fo") { - t.Error("Expected sorted escaped params, but got " + params[4]) - } -} - -func encodeAndValidate(t *testing.T, input url.Values, output string) { - values := url.Values{} - for key, val := range input { - values.Set(key, val[0]) - } - params_str := canonicalize("post", - "API-XXX.duosecurity.com", - "/auth/v2/ping", - values, - "5") - params := strings.Split(params_str, "\n") - if params[4] != output { - t.Error("Mismatch\n" + output + "\n" + params[4]) - } - -} - -func TestSimple(t *testing.T) { - values := url.Values{} - values.Set("realname", "First Last") - values.Set("username", "root") - - encodeAndValidate(t, values, "realname=First%20Last&username=root") -} - -func TestZero(t *testing.T) { - values := url.Values{} - encodeAndValidate(t, values, "") -} - -func TestOne(t *testing.T) { - values := url.Values{} - values.Set("realname", "First Last") - encodeAndValidate(t, values, "realname=First%20Last") -} - -func TestPrintableAsciiCharaceters(t *testing.T) { - values := url.Values{} - values.Set("digits", "0123456789") - values.Set("letters", "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") - values.Set("punctuation", "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~") - values.Set("whitespace", "\t\n\x0b\x0c\r ") - encodeAndValidate(t, values, "digits=0123456789&letters=abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ&punctuation=%21%22%23%24%25%26%27%28%29%2A%2B%2C-.%2F%3A%3B%3C%3D%3E%3F%40%5B%5C%5D%5E_%60%7B%7C%7D~&whitespace=%09%0A%0B%0C%0D%20") -} - -func TestSortOrderWithCommonPrefix(t *testing.T) { - values := url.Values{} - values.Set("foo", "1") - values.Set("foo_bar", "2") - encodeAndValidate(t, values, "foo=1&foo_bar=2") -} - -func TestUnicodeFuzzValues(t *testing.T) { - values := url.Values{} - values.Set("bar", "⠕ꪣ㟏䮷㛩찅暎腢슽ꇱ") - values.Set("baz", "ෳ蒽噩馅뢤갺篧潩鍊뤜") - values.Set("foo", "퓎훖礸僀訠輕ﴋ耤岳왕") - values.Set("qux", "讗졆-芎茚쳊ꋔ谾뢲馾") - encodeAndValidate(t, values, "bar=%E2%A0%95%EA%AA%A3%E3%9F%8F%E4%AE%B7%E3%9B%A9%EC%B0%85%E6%9A%8E%E8%85%A2%EC%8A%BD%EA%87%B1&baz=%E0%B7%B3%E8%92%BD%E5%99%A9%E9%A6%85%EB%A2%A4%EA%B0%BA%E7%AF%A7%E6%BD%A9%E9%8D%8A%EB%A4%9C&foo=%ED%93%8E%ED%9B%96%E7%A4%B8%E5%83%80%E8%A8%A0%E8%BC%95%EF%B4%8B%E8%80%A4%E5%B2%B3%EC%99%95&qux=%E8%AE%97%EC%A1%86-%E8%8A%8E%E8%8C%9A%EC%B3%8A%EA%8B%94%E8%B0%BE%EB%A2%B2%E9%A6%BE") -} - -func TestUnicodeFuzzKeysAndValues(t *testing.T) { - values := url.Values{} - values.Set("䚚⡻㗐軳朧倪ࠐ킑È셰", - "ཅ᩶㐚敌숿鬉ꯢ荃ᬧ惐") - values.Set("瑉繋쳻姿﹟获귌逌쿑砓", - "趷倢鋓䋯⁽蜰곾嘗ॆ丰") - values.Set("瑰錔逜麮䃘䈁苘豰ᴱꁂ", - "៙ந鍘꫟ꐪ䢾ﮖ濩럿㋳") - values.Set("싅Ⱍ☠㘗隳F蘅⃨갡头", - "ﮩ䆪붃萋☕㹮攭ꢵ핫U") - encodeAndValidate(t, values, "%E4%9A%9A%E2%A1%BB%E3%97%90%E8%BB%B3%E6%9C%A7%E5%80%AA%E0%A0%90%ED%82%91%C3%88%EC%85%B0=%E0%BD%85%E1%A9%B6%E3%90%9A%E6%95%8C%EC%88%BF%E9%AC%89%EA%AF%A2%E8%8D%83%E1%AC%A7%E6%83%90&%E7%91%89%E7%B9%8B%EC%B3%BB%E5%A7%BF%EF%B9%9F%E8%8E%B7%EA%B7%8C%E9%80%8C%EC%BF%91%E7%A0%93=%E8%B6%B7%E5%80%A2%E9%8B%93%E4%8B%AF%E2%81%BD%E8%9C%B0%EA%B3%BE%E5%98%97%E0%A5%86%E4%B8%B0&%E7%91%B0%E9%8C%94%E9%80%9C%E9%BA%AE%E4%83%98%E4%88%81%E8%8B%98%E8%B1%B0%E1%B4%B1%EA%81%82=%E1%9F%99%E0%AE%A8%E9%8D%98%EA%AB%9F%EA%90%AA%E4%A2%BE%EF%AE%96%E6%BF%A9%EB%9F%BF%E3%8B%B3&%EC%8B%85%E2%B0%9D%E2%98%A0%E3%98%97%E9%9A%B3F%E8%98%85%E2%83%A8%EA%B0%A1%E5%A4%B4=%EF%AE%A9%E4%86%AA%EB%B6%83%E8%90%8B%E2%98%95%E3%B9%AE%E6%94%AD%EA%A2%B5%ED%95%ABU") -} - -func TestSign(t *testing.T) { - values := url.Values{} - values.Set("realname", "First Last") - values.Set("username", "root") - res := sign("DIWJ8X6AEYOR5OMC6TQ1", - "Zh5eGmUq9zpfQnyUIu5OL9iWoMMv5ZNmk3zLJ4Ep", - "POST", - "api-XXXXXXXX.duosecurity.com", - "/accounts/v1/account/list", - "Tue, 21 Aug 2012 17:29:18 -0000", - values) - if res != "Basic RElXSjhYNkFFWU9SNU9NQzZUUTE6MmQ5N2Q2MTY2MzE5Nzgx" + - "YjVhM2EwN2FmMzlkMzY2ZjQ5MTIzNGVkYw==" { - t.Error("Signature did not produce output documented at " + - "https://www.duosecurity.com/docs/authapi :(") - } -} - -func TestV2Canonicalize(t *testing.T) { - values := url.Values{} - values.Set("䚚⡻㗐軳朧倪ࠐ킑È셰", - "ཅ᩶㐚敌숿鬉ꯢ荃ᬧ惐") - values.Set("瑉繋쳻姿﹟获귌逌쿑砓", - "趷倢鋓䋯⁽蜰곾嘗ॆ丰") - values.Set("瑰錔逜麮䃘䈁苘豰ᴱꁂ", - "៙ந鍘꫟ꐪ䢾ﮖ濩럿㋳") - values.Set("싅Ⱍ☠㘗隳F蘅⃨갡头", - "ﮩ䆪붃萋☕㹮攭ꢵ핫U") - canon := canonicalize( - "PoSt", - "foO.BAr52.cOm", - "/Foo/BaR2/qux", - values, - "Fri, 07 Dec 2012 17:18:00 -0000") - expected := "Fri, 07 Dec 2012 17:18:00 -0000\nPOST\nfoo.bar52.com\n/Foo/BaR2/qux\n%E4%9A%9A%E2%A1%BB%E3%97%90%E8%BB%B3%E6%9C%A7%E5%80%AA%E0%A0%90%ED%82%91%C3%88%EC%85%B0=%E0%BD%85%E1%A9%B6%E3%90%9A%E6%95%8C%EC%88%BF%E9%AC%89%EA%AF%A2%E8%8D%83%E1%AC%A7%E6%83%90&%E7%91%89%E7%B9%8B%EC%B3%BB%E5%A7%BF%EF%B9%9F%E8%8E%B7%EA%B7%8C%E9%80%8C%EC%BF%91%E7%A0%93=%E8%B6%B7%E5%80%A2%E9%8B%93%E4%8B%AF%E2%81%BD%E8%9C%B0%EA%B3%BE%E5%98%97%E0%A5%86%E4%B8%B0&%E7%91%B0%E9%8C%94%E9%80%9C%E9%BA%AE%E4%83%98%E4%88%81%E8%8B%98%E8%B1%B0%E1%B4%B1%EA%81%82=%E1%9F%99%E0%AE%A8%E9%8D%98%EA%AB%9F%EA%90%AA%E4%A2%BE%EF%AE%96%E6%BF%A9%EB%9F%BF%E3%8B%B3&%EC%8B%85%E2%B0%9D%E2%98%A0%E3%98%97%E9%9A%B3F%E8%98%85%E2%83%A8%EA%B0%A1%E5%A4%B4=%EF%AE%A9%E4%86%AA%EB%B6%83%E8%90%8B%E2%98%95%E3%B9%AE%E6%94%AD%EA%A2%B5%ED%95%ABU" - if canon != expected { - t.Error("Mismatch!\n" + expected + "\n" + canon) - } -} - -func TestNewDuo(t *testing.T) { - duo := NewDuoApi("ABC", "123", "api-XXXXXXX.duosecurity.com", "go-client") - if duo == nil { - t.Fatal("Failed to create a new Duo Api") - } -} diff --git a/Godeps/_workspace/src/github.com/fatih/structs/field_test.go b/Godeps/_workspace/src/github.com/fatih/structs/field_test.go deleted file mode 100644 index 46187d655..000000000 --- a/Godeps/_workspace/src/github.com/fatih/structs/field_test.go +++ /dev/null @@ -1,324 +0,0 @@ -package structs - -import ( - "reflect" - "testing" -) - -// A test struct that defines all cases -type Foo struct { - A string - B int `structs:"y"` - C bool `json:"c"` - d string // not exported - E *Baz - x string `xml:"x"` // not exported, with tag - Y []string - Z map[string]interface{} - *Bar // embedded -} - -type Baz struct { - A string - B int -} - -type Bar struct { - E string - F int - g []string -} - -func newStruct() *Struct { - b := &Bar{ - E: "example", - F: 2, - g: []string{"zeynep", "fatih"}, - } - - // B and x is not initialized for testing - f := &Foo{ - A: "gopher", - C: true, - d: "small", - E: nil, - Y: []string{"example"}, - Z: nil, - } - f.Bar = b - - return New(f) -} - -func TestField_Set(t *testing.T) { - s := newStruct() - - f := s.Field("A") - err := f.Set("fatih") - if err != nil { - t.Error(err) - } - - if f.Value().(string) != "fatih" { - t.Errorf("Setted value is wrong: %s want: %s", f.Value().(string), "fatih") - } - - f = s.Field("Y") - err = f.Set([]string{"override", "with", "this"}) - if err != nil { - t.Error(err) - } - - sliceLen := len(f.Value().([]string)) - if sliceLen != 3 { - t.Errorf("Setted values slice length is wrong: %d, want: %d", sliceLen, 3) - } - - f = s.Field("C") - err = f.Set(false) - if err != nil { - t.Error(err) - } - - if f.Value().(bool) { - t.Errorf("Setted value is wrong: %s want: %s", f.Value().(bool), false) - } - - // let's pass a different type - f = s.Field("A") - err = f.Set(123) // Field A is of type string, but we are going to pass an integer - if err == nil { - t.Error("Setting a field's value with a different type than the field's type should return an error") - } - - // old value should be still there :) - if f.Value().(string) != "fatih" { - t.Errorf("Setted value is wrong: %s want: %s", f.Value().(string), "fatih") - } - - // let's access an unexported field, which should give an error - f = s.Field("d") - err = f.Set("large") - if err != errNotExported { - t.Error(err) - } - - // let's set a pointer to struct - b := &Bar{ - E: "gopher", - F: 2, - } - - f = s.Field("Bar") - err = f.Set(b) - if err != nil { - t.Error(err) - } - - baz := &Baz{ - A: "helloWorld", - B: 42, - } - - f = s.Field("E") - err = f.Set(baz) - if err != nil { - t.Error(err) - } - - ba := s.Field("E").Value().(*Baz) - - if ba.A != "helloWorld" { - t.Errorf("could not set baz. Got: %s Want: helloWorld", ba.A) - } -} - -func TestField(t *testing.T) { - s := newStruct() - - defer func() { - err := recover() - if err == nil { - t.Error("Retrieveing a non existing field from the struct should panic") - } - }() - - _ = s.Field("no-field") -} - -func TestField_Kind(t *testing.T) { - s := newStruct() - - f := s.Field("A") - if f.Kind() != reflect.String { - t.Errorf("Field A has wrong kind: %s want: %s", f.Kind(), reflect.String) - } - - f = s.Field("B") - if f.Kind() != reflect.Int { - t.Errorf("Field B has wrong kind: %s want: %s", f.Kind(), reflect.Int) - } - - // unexported - f = s.Field("d") - if f.Kind() != reflect.String { - t.Errorf("Field d has wrong kind: %s want: %s", f.Kind(), reflect.String) - } -} - -func TestField_Tag(t *testing.T) { - s := newStruct() - - v := s.Field("B").Tag("json") - if v != "" { - t.Errorf("Field's tag value of a non existing tag should return empty, got: %s", v) - } - - v = s.Field("C").Tag("json") - if v != "c" { - t.Errorf("Field's tag value of the existing field C should return 'c', got: %s", v) - } - - v = s.Field("d").Tag("json") - if v != "" { - t.Errorf("Field's tag value of a non exported field should return empty, got: %s", v) - } - - v = s.Field("x").Tag("xml") - if v != "x" { - t.Errorf("Field's tag value of a non exported field with a tag should return 'x', got: %s", v) - } - - v = s.Field("A").Tag("json") - if v != "" { - t.Errorf("Field's tag value of a existing field without a tag should return empty, got: %s", v) - } -} - -func TestField_Value(t *testing.T) { - s := newStruct() - - v := s.Field("A").Value() - val, ok := v.(string) - if !ok { - t.Errorf("Field's value of a A should be string") - } - - if val != "gopher" { - t.Errorf("Field's value of a existing tag should return 'gopher', got: %s", val) - } - - defer func() { - err := recover() - if err == nil { - t.Error("Value of a non exported field from the field should panic") - } - }() - - // should panic - _ = s.Field("d").Value() -} - -func TestField_IsEmbedded(t *testing.T) { - s := newStruct() - - if !s.Field("Bar").IsEmbedded() { - t.Errorf("Fields 'Bar' field is an embedded field") - } - - if s.Field("d").IsEmbedded() { - t.Errorf("Fields 'd' field is not an embedded field") - } -} - -func TestField_IsExported(t *testing.T) { - s := newStruct() - - if !s.Field("Bar").IsExported() { - t.Errorf("Fields 'Bar' field is an exported field") - } - - if !s.Field("A").IsExported() { - t.Errorf("Fields 'A' field is an exported field") - } - - if s.Field("d").IsExported() { - t.Errorf("Fields 'd' field is not an exported field") - } -} - -func TestField_IsZero(t *testing.T) { - s := newStruct() - - if s.Field("A").IsZero() { - t.Errorf("Fields 'A' field is an initialized field") - } - - if !s.Field("B").IsZero() { - t.Errorf("Fields 'B' field is not an initialized field") - } -} - -func TestField_Name(t *testing.T) { - s := newStruct() - - if s.Field("A").Name() != "A" { - t.Errorf("Fields 'A' field should have the name 'A'") - } -} - -func TestField_Field(t *testing.T) { - s := newStruct() - - e := s.Field("Bar").Field("E") - - val, ok := e.Value().(string) - if !ok { - t.Error("The value of the field 'e' inside 'Bar' struct should be string") - } - - if val != "example" { - t.Errorf("The value of 'e' should be 'example, got: %s", val) - } - - defer func() { - err := recover() - if err == nil { - t.Error("Field of a non existing nested struct should panic") - } - }() - - _ = s.Field("Bar").Field("e") -} - -func TestField_Fields(t *testing.T) { - s := newStruct() - fields := s.Field("Bar").Fields() - - if len(fields) != 3 { - t.Errorf("We expect 3 fields in embedded struct, was: %d", len(fields)) - } -} - -func TestField_FieldOk(t *testing.T) { - s := newStruct() - - b, ok := s.FieldOk("Bar") - if !ok { - t.Error("The field 'Bar' should exists.") - } - - e, ok := b.FieldOk("E") - if !ok { - t.Error("The field 'E' should exists.") - } - - val, ok := e.Value().(string) - if !ok { - t.Error("The value of the field 'e' inside 'Bar' struct should be string") - } - - if val != "example" { - t.Errorf("The value of 'e' should be 'example, got: %s", val) - } -} diff --git a/Godeps/_workspace/src/github.com/fatih/structs/structs_example_test.go b/Godeps/_workspace/src/github.com/fatih/structs/structs_example_test.go deleted file mode 100644 index 32bb82937..000000000 --- a/Godeps/_workspace/src/github.com/fatih/structs/structs_example_test.go +++ /dev/null @@ -1,351 +0,0 @@ -package structs - -import ( - "fmt" - "time" -) - -func ExampleNew() { - type Server struct { - Name string - ID int32 - Enabled bool - } - - server := &Server{ - Name: "Arslan", - ID: 123456, - Enabled: true, - } - - s := New(server) - - fmt.Printf("Name : %v\n", s.Name()) - fmt.Printf("Values : %v\n", s.Values()) - fmt.Printf("Value of ID : %v\n", s.Field("ID").Value()) - // Output: - // Name : Server - // Values : [Arslan 123456 true] - // Value of ID : 123456 - -} - -func ExampleMap() { - type Server struct { - Name string - ID int32 - Enabled bool - } - - s := &Server{ - Name: "Arslan", - ID: 123456, - Enabled: true, - } - - m := Map(s) - - fmt.Printf("%#v\n", m["Name"]) - fmt.Printf("%#v\n", m["ID"]) - fmt.Printf("%#v\n", m["Enabled"]) - // Output: - // "Arslan" - // 123456 - // true - -} - -func ExampleMap_tags() { - // Custom tags can change the map keys instead of using the fields name - type Server struct { - Name string `structs:"server_name"` - ID int32 `structs:"server_id"` - Enabled bool `structs:"enabled"` - } - - s := &Server{ - Name: "Zeynep", - ID: 789012, - } - - m := Map(s) - - // access them by the custom tags defined above - fmt.Printf("%#v\n", m["server_name"]) - fmt.Printf("%#v\n", m["server_id"]) - fmt.Printf("%#v\n", m["enabled"]) - // Output: - // "Zeynep" - // 789012 - // false - -} - -func ExampleMap_nested() { - // By default field with struct types are processed too. We can stop - // processing them via "omitnested" tag option. - type Server struct { - Name string `structs:"server_name"` - ID int32 `structs:"server_id"` - Time time.Time `structs:"time,omitnested"` // do not convert to map[string]interface{} - } - - const shortForm = "2006-Jan-02" - t, _ := time.Parse("2006-Jan-02", "2013-Feb-03") - - s := &Server{ - Name: "Zeynep", - ID: 789012, - Time: t, - } - - m := Map(s) - - // access them by the custom tags defined above - fmt.Printf("%v\n", m["server_name"]) - fmt.Printf("%v\n", m["server_id"]) - fmt.Printf("%v\n", m["time"].(time.Time)) - // Output: - // Zeynep - // 789012 - // 2013-02-03 00:00:00 +0000 UTC -} - -func ExampleMap_omitEmpty() { - // By default field with struct types of zero values are processed too. We - // can stop processing them via "omitempty" tag option. - type Server struct { - Name string `structs:",omitempty"` - ID int32 `structs:"server_id,omitempty"` - Location string - } - - // Only add location - s := &Server{ - Location: "Tokyo", - } - - m := Map(s) - - // map contains only the Location field - fmt.Printf("%v\n", m) - // Output: - // map[Location:Tokyo] -} - -func ExampleValues() { - type Server struct { - Name string - ID int32 - Enabled bool - } - - s := &Server{ - Name: "Fatih", - ID: 135790, - Enabled: false, - } - - m := Values(s) - - fmt.Printf("Values: %+v\n", m) - // Output: - // Values: [Fatih 135790 false] -} - -func ExampleValues_omitEmpty() { - // By default field with struct types of zero values are processed too. We - // can stop processing them via "omitempty" tag option. - type Server struct { - Name string `structs:",omitempty"` - ID int32 `structs:"server_id,omitempty"` - Location string - } - - // Only add location - s := &Server{ - Location: "Ankara", - } - - m := Values(s) - - // values contains only the Location field - fmt.Printf("Values: %+v\n", m) - // Output: - // Values: [Ankara] -} - -func ExampleValues_tags() { - type Location struct { - City string - Country string - } - - type Server struct { - Name string - ID int32 - Enabled bool - Location Location `structs:"-"` // values from location are not included anymore - } - - s := &Server{ - Name: "Fatih", - ID: 135790, - Enabled: false, - Location: Location{City: "Ankara", Country: "Turkey"}, - } - - // Let get all values from the struct s. Note that we don't include values - // from the Location field - m := Values(s) - - fmt.Printf("Values: %+v\n", m) - // Output: - // Values: [Fatih 135790 false] -} - -func ExampleFields() { - type Access struct { - Name string - LastAccessed time.Time - Number int - } - - s := &Access{ - Name: "Fatih", - LastAccessed: time.Now(), - Number: 1234567, - } - - fields := Fields(s) - - for i, field := range fields { - fmt.Printf("[%d] %+v\n", i, field.Name()) - } - - // Output: - // [0] Name - // [1] LastAccessed - // [2] Number -} - -func ExampleFields_nested() { - type Person struct { - Name string - Number int - } - - type Access struct { - Person Person - HasPermission bool - LastAccessed time.Time - } - - s := &Access{ - Person: Person{Name: "fatih", Number: 1234567}, - LastAccessed: time.Now(), - HasPermission: true, - } - - // Let's get all fields from the struct s. - fields := Fields(s) - - for _, field := range fields { - if field.Name() == "Person" { - fmt.Printf("Access.Person.Name: %+v\n", field.Field("Name").Value()) - } - } - - // Output: - // Access.Person.Name: fatih -} - -func ExampleField() { - type Person struct { - Name string - Number int - } - - type Access struct { - Person Person - HasPermission bool - LastAccessed time.Time - } - - access := &Access{ - Person: Person{Name: "fatih", Number: 1234567}, - LastAccessed: time.Now(), - HasPermission: true, - } - - // Create a new Struct type - s := New(access) - - // Get the Field type for "Person" field - p := s.Field("Person") - - // Get the underlying "Name field" and print the value of it - name := p.Field("Name") - - fmt.Printf("Value of Person.Access.Name: %+v\n", name.Value()) - - // Output: - // Value of Person.Access.Name: fatih - -} - -func ExampleIsZero() { - type Server struct { - Name string - ID int32 - Enabled bool - } - - // Nothing is initalized - a := &Server{} - isZeroA := IsZero(a) - - // Name and Enabled is initialized, but not ID - b := &Server{ - Name: "Golang", - Enabled: true, - } - isZeroB := IsZero(b) - - fmt.Printf("%#v\n", isZeroA) - fmt.Printf("%#v\n", isZeroB) - // Output: - // true - // false -} - -func ExampleHasZero() { - // Let's define an Access struct. Note that the "Enabled" field is not - // going to be checked because we added the "structs" tag to the field. - type Access struct { - Name string - LastAccessed time.Time - Number int - Enabled bool `structs:"-"` - } - - // Name and Number is not initialized. - a := &Access{ - LastAccessed: time.Now(), - } - hasZeroA := HasZero(a) - - // Name and Number is initialized. - b := &Access{ - Name: "Fatih", - LastAccessed: time.Now(), - Number: 12345, - } - hasZeroB := HasZero(b) - - fmt.Printf("%#v\n", hasZeroA) - fmt.Printf("%#v\n", hasZeroB) - // Output: - // true - // false -} diff --git a/Godeps/_workspace/src/github.com/fatih/structs/structs_test.go b/Godeps/_workspace/src/github.com/fatih/structs/structs_test.go deleted file mode 100644 index 14e3de72f..000000000 --- a/Godeps/_workspace/src/github.com/fatih/structs/structs_test.go +++ /dev/null @@ -1,898 +0,0 @@ -package structs - -import ( - "fmt" - "reflect" - "testing" - "time" -) - -func TestMapNonStruct(t *testing.T) { - foo := []string{"foo"} - - defer func() { - err := recover() - if err == nil { - t.Error("Passing a non struct into Map should panic") - } - }() - - // this should panic. We are going to recover and and test it - _ = Map(foo) -} - -func TestStructIndexes(t *testing.T) { - type C struct { - something int - Props map[string]interface{} - } - - defer func() { - err := recover() - if err != nil { - fmt.Printf("err %+v\n", err) - t.Error("Using mixed indexes should not panic") - } - }() - - // They should not panic - _ = Map(&C{}) - _ = Fields(&C{}) - _ = Values(&C{}) - _ = IsZero(&C{}) - _ = HasZero(&C{}) -} - -func TestMap(t *testing.T) { - var T = struct { - A string - B int - C bool - }{ - A: "a-value", - B: 2, - C: true, - } - - a := Map(T) - - if typ := reflect.TypeOf(a).Kind(); typ != reflect.Map { - t.Errorf("Map should return a map type, got: %v", typ) - } - - // we have three fields - if len(a) != 3 { - t.Errorf("Map should return a map of len 3, got: %d", len(a)) - } - - inMap := func(val interface{}) bool { - for _, v := range a { - if reflect.DeepEqual(v, val) { - return true - } - } - - return false - } - - for _, val := range []interface{}{"a-value", 2, true} { - if !inMap(val) { - t.Errorf("Map should have the value %v", val) - } - } - -} - -func TestMap_Tag(t *testing.T) { - var T = struct { - A string `structs:"x"` - B int `structs:"y"` - C bool `structs:"z"` - }{ - A: "a-value", - B: 2, - C: true, - } - - a := Map(T) - - inMap := func(key interface{}) bool { - for k := range a { - if reflect.DeepEqual(k, key) { - return true - } - } - return false - } - - for _, key := range []string{"x", "y", "z"} { - if !inMap(key) { - t.Errorf("Map should have the key %v", key) - } - } - -} - -func TestMap_CustomTag(t *testing.T) { - var T = struct { - A string `json:"x"` - B int `json:"y"` - C bool `json:"z"` - D struct { - E string `json:"jkl"` - } `json:"nested"` - }{ - A: "a-value", - B: 2, - C: true, - } - T.D.E = "e-value" - - s := New(T) - s.TagName = "json" - - a := s.Map() - - inMap := func(key interface{}) bool { - for k := range a { - if reflect.DeepEqual(k, key) { - return true - } - } - return false - } - - for _, key := range []string{"x", "y", "z"} { - if !inMap(key) { - t.Errorf("Map should have the key %v", key) - } - } - - nested, ok := a["nested"].(map[string]interface{}) - if !ok { - t.Fatalf("Map should contain the D field that is tagged as 'nested'") - } - - e, ok := nested["jkl"].(string) - if !ok { - t.Fatalf("Map should contain the D.E field that is tagged as 'jkl'") - } - - if e != "e-value" { - t.Errorf("D.E field should be equal to 'e-value', got: '%v'", e) - } - -} - -func TestMap_MultipleCustomTag(t *testing.T) { - var A = struct { - X string `aa:"ax"` - }{"a_value"} - - aStruct := New(A) - aStruct.TagName = "aa" - - var B = struct { - X string `bb:"bx"` - }{"b_value"} - - bStruct := New(B) - bStruct.TagName = "bb" - - a, b := aStruct.Map(), bStruct.Map() - if !reflect.DeepEqual(a, map[string]interface{}{"ax": "a_value"}) { - t.Error("Map should have field ax with value a_value") - } - - if !reflect.DeepEqual(b, map[string]interface{}{"bx": "b_value"}) { - t.Error("Map should have field bx with value b_value") - } -} - -func TestMap_OmitEmpty(t *testing.T) { - type A struct { - Name string - Value string `structs:",omitempty"` - Time time.Time `structs:",omitempty"` - } - a := A{} - - m := Map(a) - - _, ok := m["Value"].(map[string]interface{}) - if ok { - t.Error("Map should not contain the Value field that is tagged as omitempty") - } - - _, ok = m["Time"].(map[string]interface{}) - if ok { - t.Error("Map should not contain the Time field that is tagged as omitempty") - } -} - -func TestMap_OmitNested(t *testing.T) { - type A struct { - Name string - Value string - Time time.Time `structs:",omitnested"` - } - a := A{Time: time.Now()} - - type B struct { - Desc string - A A - } - b := &B{A: a} - - m := Map(b) - - in, ok := m["A"].(map[string]interface{}) - if !ok { - t.Error("Map nested structs is not available in the map") - } - - // should not happen - if _, ok := in["Time"].(map[string]interface{}); ok { - t.Error("Map nested struct should omit recursiving parsing of Time") - } - - if _, ok := in["Time"].(time.Time); !ok { - t.Error("Map nested struct should stop parsing of Time at is current value") - } -} - -func TestMap_Nested(t *testing.T) { - type A struct { - Name string - } - a := &A{Name: "example"} - - type B struct { - A *A - } - b := &B{A: a} - - m := Map(b) - - if typ := reflect.TypeOf(m).Kind(); typ != reflect.Map { - t.Errorf("Map should return a map type, got: %v", typ) - } - - in, ok := m["A"].(map[string]interface{}) - if !ok { - t.Error("Map nested structs is not available in the map") - } - - if name := in["Name"].(string); name != "example" { - t.Errorf("Map nested struct's name field should give example, got: %s", name) - } -} - -func TestMap_Anonymous(t *testing.T) { - type A struct { - Name string - } - a := &A{Name: "example"} - - type B struct { - *A - } - b := &B{} - b.A = a - - m := Map(b) - - if typ := reflect.TypeOf(m).Kind(); typ != reflect.Map { - t.Errorf("Map should return a map type, got: %v", typ) - } - - in, ok := m["A"].(map[string]interface{}) - if !ok { - t.Error("Embedded structs is not available in the map") - } - - if name := in["Name"].(string); name != "example" { - t.Errorf("Embedded A struct's Name field should give example, got: %s", name) - } -} - -func TestStruct(t *testing.T) { - var T = struct{}{} - - if !IsStruct(T) { - t.Errorf("T should be a struct, got: %T", T) - } - - if !IsStruct(&T) { - t.Errorf("T should be a struct, got: %T", T) - } - -} - -func TestValues(t *testing.T) { - var T = struct { - A string - B int - C bool - }{ - A: "a-value", - B: 2, - C: true, - } - - s := Values(T) - - if typ := reflect.TypeOf(s).Kind(); typ != reflect.Slice { - t.Errorf("Values should return a slice type, got: %v", typ) - } - - inSlice := func(val interface{}) bool { - for _, v := range s { - if reflect.DeepEqual(v, val) { - return true - } - } - return false - } - - for _, val := range []interface{}{"a-value", 2, true} { - if !inSlice(val) { - t.Errorf("Values should have the value %v", val) - } - } -} - -func TestValues_OmitEmpty(t *testing.T) { - type A struct { - Name string - Value int `structs:",omitempty"` - } - - a := A{Name: "example"} - s := Values(a) - - if len(s) != 1 { - t.Errorf("Values of omitted empty fields should be not counted") - } - - if s[0].(string) != "example" { - t.Errorf("Values of omitted empty fields should left the value example") - } -} - -func TestValues_OmitNested(t *testing.T) { - type A struct { - Name string - Value int - } - - a := A{ - Name: "example", - Value: 123, - } - - type B struct { - A A `structs:",omitnested"` - C int - } - b := &B{A: a, C: 123} - - s := Values(b) - - if len(s) != 2 { - t.Errorf("Values of omitted nested struct should be not counted") - } - - inSlice := func(val interface{}) bool { - for _, v := range s { - if reflect.DeepEqual(v, val) { - return true - } - } - return false - } - - for _, val := range []interface{}{123, a} { - if !inSlice(val) { - t.Errorf("Values should have the value %v", val) - } - } -} - -func TestValues_Nested(t *testing.T) { - type A struct { - Name string - } - a := A{Name: "example"} - - type B struct { - A A - C int - } - b := &B{A: a, C: 123} - - s := Values(b) - - inSlice := func(val interface{}) bool { - for _, v := range s { - if reflect.DeepEqual(v, val) { - return true - } - } - return false - } - - for _, val := range []interface{}{"example", 123} { - if !inSlice(val) { - t.Errorf("Values should have the value %v", val) - } - } -} - -func TestValues_Anonymous(t *testing.T) { - type A struct { - Name string - } - a := A{Name: "example"} - - type B struct { - A - C int - } - b := &B{C: 123} - b.A = a - - s := Values(b) - - inSlice := func(val interface{}) bool { - for _, v := range s { - if reflect.DeepEqual(v, val) { - return true - } - } - return false - } - - for _, val := range []interface{}{"example", 123} { - if !inSlice(val) { - t.Errorf("Values should have the value %v", val) - } - } -} - -func TestNames(t *testing.T) { - var T = struct { - A string - B int - C bool - }{ - A: "a-value", - B: 2, - C: true, - } - - s := Names(T) - - if len(s) != 3 { - t.Errorf("Names should return a slice of len 3, got: %d", len(s)) - } - - inSlice := func(val string) bool { - for _, v := range s { - if reflect.DeepEqual(v, val) { - return true - } - } - return false - } - - for _, val := range []string{"A", "B", "C"} { - if !inSlice(val) { - t.Errorf("Names should have the value %v", val) - } - } -} - -func TestFields(t *testing.T) { - var T = struct { - A string - B int - C bool - }{ - A: "a-value", - B: 2, - C: true, - } - - s := Fields(T) - - if len(s) != 3 { - t.Errorf("Fields should return a slice of len 3, got: %d", len(s)) - } - - inSlice := func(val string) bool { - for _, v := range s { - if reflect.DeepEqual(v.Name(), val) { - return true - } - } - return false - } - - for _, val := range []string{"A", "B", "C"} { - if !inSlice(val) { - t.Errorf("Fields should have the value %v", val) - } - } -} - -func TestFields_OmitNested(t *testing.T) { - type A struct { - Name string - Enabled bool - } - a := A{Name: "example"} - - type B struct { - A A - C int - Value string `structs:"-"` - Number int - } - b := &B{A: a, C: 123} - - s := Fields(b) - - if len(s) != 3 { - t.Errorf("Fields should omit nested struct. Expecting 2 got: %d", len(s)) - } - - inSlice := func(val interface{}) bool { - for _, v := range s { - if reflect.DeepEqual(v.Name(), val) { - return true - } - } - return false - } - - for _, val := range []interface{}{"A", "C"} { - if !inSlice(val) { - t.Errorf("Fields should have the value %v", val) - } - } -} - -func TestFields_Anonymous(t *testing.T) { - type A struct { - Name string - } - a := A{Name: "example"} - - type B struct { - A - C int - } - b := &B{C: 123} - b.A = a - - s := Fields(b) - - inSlice := func(val interface{}) bool { - for _, v := range s { - if reflect.DeepEqual(v.Name(), val) { - return true - } - } - return false - } - - for _, val := range []interface{}{"A", "C"} { - if !inSlice(val) { - t.Errorf("Fields should have the value %v", val) - } - } -} - -func TestIsZero(t *testing.T) { - var T = struct { - A string - B int - C bool `structs:"-"` - D []string - }{} - - ok := IsZero(T) - if !ok { - t.Error("IsZero should return true because none of the fields are initialized.") - } - - var X = struct { - A string - F *bool - }{ - A: "a-value", - } - - ok = IsZero(X) - if ok { - t.Error("IsZero should return false because A is initialized") - } - - var Y = struct { - A string - B int - }{ - A: "a-value", - B: 123, - } - - ok = IsZero(Y) - if ok { - t.Error("IsZero should return false because A and B is initialized") - } -} - -func TestIsZero_OmitNested(t *testing.T) { - type A struct { - Name string - D string - } - a := A{Name: "example"} - - type B struct { - A A `structs:",omitnested"` - C int - } - b := &B{A: a, C: 123} - - ok := IsZero(b) - if ok { - t.Error("IsZero should return false because A, B and C are initialized") - } - - aZero := A{} - bZero := &B{A: aZero} - - ok = IsZero(bZero) - if !ok { - t.Error("IsZero should return true because neither A nor B is initialized") - } - -} - -func TestIsZero_Nested(t *testing.T) { - type A struct { - Name string - D string - } - a := A{Name: "example"} - - type B struct { - A A - C int - } - b := &B{A: a, C: 123} - - ok := IsZero(b) - if ok { - t.Error("IsZero should return false because A, B and C are initialized") - } - - aZero := A{} - bZero := &B{A: aZero} - - ok = IsZero(bZero) - if !ok { - t.Error("IsZero should return true because neither A nor B is initialized") - } - -} - -func TestIsZero_Anonymous(t *testing.T) { - type A struct { - Name string - D string - } - a := A{Name: "example"} - - type B struct { - A - C int - } - b := &B{C: 123} - b.A = a - - ok := IsZero(b) - if ok { - t.Error("IsZero should return false because A, B and C are initialized") - } - - aZero := A{} - bZero := &B{} - bZero.A = aZero - - ok = IsZero(bZero) - if !ok { - t.Error("IsZero should return true because neither A nor B is initialized") - } -} - -func TestHasZero(t *testing.T) { - var T = struct { - A string - B int - C bool `structs:"-"` - D []string - }{ - A: "a-value", - B: 2, - } - - ok := HasZero(T) - if !ok { - t.Error("HasZero should return true because A and B are initialized.") - } - - var X = struct { - A string - F *bool - }{ - A: "a-value", - } - - ok = HasZero(X) - if !ok { - t.Error("HasZero should return true because A is initialized") - } - - var Y = struct { - A string - B int - }{ - A: "a-value", - B: 123, - } - - ok = HasZero(Y) - if ok { - t.Error("HasZero should return false because A and B is initialized") - } -} - -func TestHasZero_OmitNested(t *testing.T) { - type A struct { - Name string - D string - } - a := A{Name: "example"} - - type B struct { - A A `structs:",omitnested"` - C int - } - b := &B{A: a, C: 123} - - // Because the Field A inside B is omitted HasZero should return false - // because it will stop iterating deeper andnot going to lookup for D - ok := HasZero(b) - if ok { - t.Error("HasZero should return false because A and C are initialized") - } -} - -func TestHasZero_Nested(t *testing.T) { - type A struct { - Name string - D string - } - a := A{Name: "example"} - - type B struct { - A A - C int - } - b := &B{A: a, C: 123} - - ok := HasZero(b) - if !ok { - t.Error("HasZero should return true because D is not initialized") - } -} - -func TestHasZero_Anonymous(t *testing.T) { - type A struct { - Name string - D string - } - a := A{Name: "example"} - - type B struct { - A - C int - } - b := &B{C: 123} - b.A = a - - ok := HasZero(b) - if !ok { - t.Error("HasZero should return false because D is not initialized") - } -} - -func TestName(t *testing.T) { - type Foo struct { - A string - B bool - } - f := &Foo{} - - n := Name(f) - if n != "Foo" { - t.Errorf("Name should return Foo, got: %s", n) - } - - unnamed := struct{ Name string }{Name: "Cihangir"} - m := Name(unnamed) - if m != "" { - t.Errorf("Name should return empty string for unnamed struct, got: %s", n) - } - - defer func() { - err := recover() - if err == nil { - t.Error("Name should panic if a non struct is passed") - } - }() - - Name([]string{}) -} - -func TestNestedNilPointer(t *testing.T) { - type Collar struct { - Engraving string - } - - type Dog struct { - Name string - Collar *Collar - } - - type Person struct { - Name string - Dog *Dog - } - - person := &Person{ - Name: "John", - } - - personWithDog := &Person{ - Name: "Ron", - Dog: &Dog{ - Name: "Rover", - }, - } - - personWithDogWithCollar := &Person{ - Name: "Kon", - Dog: &Dog{ - Name: "Ruffles", - Collar: &Collar{ - Engraving: "If lost, call Kon", - }, - }, - } - - defer func() { - err := recover() - if err != nil { - fmt.Printf("err %+v\n", err) - t.Error("Internal nil pointer should not panic") - } - }() - - _ = Map(person) // Panics - _ = Map(personWithDog) // Panics - _ = Map(personWithDogWithCollar) // Doesn't panic -} diff --git a/Godeps/_workspace/src/github.com/fatih/structs/tags_test.go b/Godeps/_workspace/src/github.com/fatih/structs/tags_test.go deleted file mode 100644 index 5d12724f1..000000000 --- a/Godeps/_workspace/src/github.com/fatih/structs/tags_test.go +++ /dev/null @@ -1,46 +0,0 @@ -package structs - -import "testing" - -func TestParseTag_Name(t *testing.T) { - tags := []struct { - tag string - has bool - }{ - {"", false}, - {"name", true}, - {"name,opt", true}, - {"name , opt, opt2", false}, // has a single whitespace - {", opt, opt2", false}, - } - - for _, tag := range tags { - name, _ := parseTag(tag.tag) - - if (name != "name") && tag.has { - t.Errorf("Parse tag should return name: %#v", tag) - } - } -} - -func TestParseTag_Opts(t *testing.T) { - tags := []struct { - opts string - has bool - }{ - {"name", false}, - {"name,opt", true}, - {"name , opt, opt2", false}, // has a single whitespace - {",opt, opt2", true}, - {", opt3, opt4", false}, - } - - // search for "opt" - for _, tag := range tags { - _, opts := parseTag(tag.opts) - - if opts.Has("opt") != tag.has { - t.Errorf("Tag opts should have opt: %#v", tag) - } - } -} diff --git a/Godeps/_workspace/src/github.com/go-ldap/ldap/dn_test.go b/Godeps/_workspace/src/github.com/go-ldap/ldap/dn_test.go deleted file mode 100644 index 6740e1819..000000000 --- a/Godeps/_workspace/src/github.com/go-ldap/ldap/dn_test.go +++ /dev/null @@ -1,70 +0,0 @@ -package ldap - -import ( - "reflect" - "testing" -) - -func TestSuccessfulDNParsing(t *testing.T) { - testcases := map[string]DN { - "": DN{[]*RelativeDN{}}, - "cn=Jim\\2C \\22Hasse Hö\\22 Hansson!,dc=dummy,dc=com": DN{[]*RelativeDN{ - &RelativeDN{[]*AttributeTypeAndValue{&AttributeTypeAndValue{"cn", "Jim, \"Hasse Hö\" Hansson!"},}}, - &RelativeDN{[]*AttributeTypeAndValue{&AttributeTypeAndValue{"dc", "dummy"},}}, - &RelativeDN{[]*AttributeTypeAndValue{&AttributeTypeAndValue{"dc", "com"}, }},}}, - "UID=jsmith,DC=example,DC=net": DN{[]*RelativeDN{ - &RelativeDN{[]*AttributeTypeAndValue{&AttributeTypeAndValue{"UID", "jsmith"},}}, - &RelativeDN{[]*AttributeTypeAndValue{&AttributeTypeAndValue{"DC", "example"},}}, - &RelativeDN{[]*AttributeTypeAndValue{&AttributeTypeAndValue{"DC", "net"}, }},}}, - "OU=Sales+CN=J. Smith,DC=example,DC=net": DN{[]*RelativeDN{ - &RelativeDN{[]*AttributeTypeAndValue{ - &AttributeTypeAndValue{"OU", "Sales"}, - &AttributeTypeAndValue{"CN", "J. Smith"},}}, - &RelativeDN{[]*AttributeTypeAndValue{&AttributeTypeAndValue{"DC", "example"},}}, - &RelativeDN{[]*AttributeTypeAndValue{&AttributeTypeAndValue{"DC", "net"}, }},}}, - "1.3.6.1.4.1.1466.0=#04024869": DN{[]*RelativeDN{ - &RelativeDN{[]*AttributeTypeAndValue{&AttributeTypeAndValue{"1.3.6.1.4.1.1466.0", "Hi"},}},}}, - "1.3.6.1.4.1.1466.0=#04024869,DC=net": DN{[]*RelativeDN{ - &RelativeDN{[]*AttributeTypeAndValue{&AttributeTypeAndValue{"1.3.6.1.4.1.1466.0", "Hi"},}}, - &RelativeDN{[]*AttributeTypeAndValue{&AttributeTypeAndValue{"DC", "net"}, }},}}, - "CN=Lu\\C4\\8Di\\C4\\87": DN{[]*RelativeDN{ - &RelativeDN{[]*AttributeTypeAndValue{&AttributeTypeAndValue{"CN", "Lučić"},}},}}, - } - - for test, answer := range testcases { - dn, err := ParseDN(test) - if err != nil { - t.Errorf(err.Error()) - continue - } - if !reflect.DeepEqual(dn, &answer) { - t.Errorf("Parsed DN %s is not equal to the expected structure", test) - for _, rdn := range dn.RDNs { - for _, attribs := range rdn.Attributes { - t.Logf("#%v\n", attribs) - } - } - } - } -} - -func TestErrorDNParsing(t *testing.T) { - testcases := map[string]string { - "*": "DN ended with incomplete type, value pair", - "cn=Jim\\0Test": "Failed to decode escaped character: encoding/hex: invalid byte: U+0054 'T'", - "cn=Jim\\0": "Got corrupted escaped character", - "DC=example,=net": "DN ended with incomplete type, value pair", - "1=#0402486": "Failed to decode BER encoding: encoding/hex: odd length hex string", - } - - for test, answer := range testcases { - _, err := ParseDN(test) - if err == nil { - t.Errorf("Expected %s to fail parsing but succeeded\n", test) - } else if err.Error() != answer { - t.Errorf("Unexpected error on %s:\n%s\nvs.\n%s\n", test, answer, err.Error()) - } - } -} - - diff --git a/Godeps/_workspace/src/github.com/go-ldap/ldap/example_test.go b/Godeps/_workspace/src/github.com/go-ldap/ldap/example_test.go deleted file mode 100644 index 0d441f43b..000000000 --- a/Godeps/_workspace/src/github.com/go-ldap/ldap/example_test.go +++ /dev/null @@ -1,305 +0,0 @@ -package ldap_test - -import ( - "crypto/tls" - "fmt" - "log" - - "github.com/go-ldap/ldap" -) - -// ExampleConn_Bind demonstrats how to bind a connection to an ldap user -// allowing access to restricted attrabutes that user has access to -func ExampleConn_Bind() { - l, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", "ldap.example.com", 389)) - if err != nil { - log.Fatal(err) - } - defer l.Close() - - err = l.Bind("cn=read-only-admin,dc=example,dc=com", "password") - if err != nil { - log.Fatal(err) - } -} - -// ExampleConn_Search demonstrates how to use the search interface -func ExampleConn_Search() { - l, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", "ldap.example.com", 389)) - if err != nil { - log.Fatal(err) - } - defer l.Close() - - searchRequest := ldap.NewSearchRequest( - "dc=example,dc=com", // The base dn to search - ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false, - "(&(objectClass=organizationalPerson))", // The filter to apply - []string{"dn", "cn"}, // A list attributes to retrieve - nil, - ) - - sr, err := l.Search(searchRequest) - if err != nil { - log.Fatal(err) - } - - for _, entry := range sr.Entries { - fmt.Printf("%s: %v\n", entry.DN, entry.GetAttributeValue("cn")) - } -} - -// ExampleStartTLS demonstrates how to start a TLS connection -func ExampleConn_StartTLS() { - l, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", "ldap.example.com", 389)) - if err != nil { - log.Fatal(err) - } - defer l.Close() - - // Reconnect with TLS - err = l.StartTLS(&tls.Config{InsecureSkipVerify: true}) - if err != nil { - log.Fatal(err) - } - - // Opertations via l are now encrypted -} - -// ExampleConn_Compare demonstrates how to comapre an attribute with a value -func ExampleConn_Compare() { - l, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", "ldap.example.com", 389)) - if err != nil { - log.Fatal(err) - } - defer l.Close() - - matched, err := l.Compare("cn=user,dc=example,dc=com", "uid", "someuserid") - if err != nil { - log.Fatal(err) - } - - fmt.Println(matched) -} - -func ExampleConn_PasswordModify_admin() { - l, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", "ldap.example.com", 389)) - if err != nil { - log.Fatal(err) - } - defer l.Close() - - err = l.Bind("cn=admin,dc=example,dc=com", "password") - if err != nil { - log.Fatal(err) - } - - passwordModifyRequest := ldap.NewPasswordModifyRequest("cn=user,dc=example,dc=com", "", "NewPassword") - _, err = l.PasswordModify(passwordModifyRequest) - - if err != nil { - log.Fatalf("Password could not be changed: %s", err.Error()) - } -} - -func ExampleConn_PasswordModify_generatedPassword() { - l, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", "ldap.example.com", 389)) - if err != nil { - log.Fatal(err) - } - defer l.Close() - - err = l.Bind("cn=user,dc=example,dc=com", "password") - if err != nil { - log.Fatal(err) - } - - passwordModifyRequest := ldap.NewPasswordModifyRequest("", "OldPassword", "") - passwordModifyResponse, err := l.PasswordModify(passwordModifyRequest) - if err != nil { - log.Fatalf("Password could not be changed: %s", err.Error()) - } - - generatedPassword := passwordModifyResponse.GeneratedPassword - log.Printf("Generated password: %s\n", generatedPassword) -} - -func ExampleConn_PasswordModify_setNewPassword() { - l, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", "ldap.example.com", 389)) - if err != nil { - log.Fatal(err) - } - defer l.Close() - - err = l.Bind("cn=user,dc=example,dc=com", "password") - if err != nil { - log.Fatal(err) - } - - passwordModifyRequest := ldap.NewPasswordModifyRequest("", "OldPassword", "NewPassword") - _, err = l.PasswordModify(passwordModifyRequest) - - if err != nil { - log.Fatalf("Password could not be changed: %s", err.Error()) - } -} - -func ExampleConn_Modify() { - l, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", "ldap.example.com", 389)) - if err != nil { - log.Fatal(err) - } - defer l.Close() - - // Add a description, and replace the mail attributes - modify := ldap.NewModifyRequest("cn=user,dc=example,dc=com") - modify.Add("description", []string{"An example user"}) - modify.Replace("mail", []string{"user@example.org"}) - - err = l.Modify(modify) - if err != nil { - log.Fatal(err) - } -} - -// Example User Authentication shows how a typical application can verify a login attempt -func Example_userAuthentication() { - // The username and password we want to check - username := "someuser" - password := "userpassword" - - bindusername := "readonly" - bindpassword := "password" - - l, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", "ldap.example.com", 389)) - if err != nil { - log.Fatal(err) - } - defer l.Close() - - // Reconnect with TLS - err = l.StartTLS(&tls.Config{InsecureSkipVerify: true}) - if err != nil { - log.Fatal(err) - } - - // First bind with a read only user - err = l.Bind(bindusername, bindpassword) - if err != nil { - log.Fatal(err) - } - - // Search for the given username - searchRequest := ldap.NewSearchRequest( - "dc=example,dc=com", - ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false, - fmt.Sprintf("(&(objectClass=organizationalPerson)&(uid=%s))", username), - []string{"dn"}, - nil, - ) - - sr, err := l.Search(searchRequest) - if err != nil { - log.Fatal(err) - } - - if len(sr.Entries) != 1 { - log.Fatal("User does not exist or too many entries returned") - } - - userdn := sr.Entries[0].DN - - // Bind as the user to verify their password - err = l.Bind(userdn, password) - if err != nil { - log.Fatal(err) - } - - // Rebind as the read only user for any futher queries - err = l.Bind(bindusername, bindpassword) - if err != nil { - log.Fatal(err) - } -} - -func Example_beherappolicy() { - l, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", "ldap.example.com", 389)) - if err != nil { - log.Fatal(err) - } - defer l.Close() - - controls := []ldap.Control{} - controls = append(controls, ldap.NewControlBeheraPasswordPolicy()) - bindRequest := ldap.NewSimpleBindRequest("cn=admin,dc=example,dc=com", "password", controls) - - r, err := l.SimpleBind(bindRequest) - ppolicyControl := ldap.FindControl(r.Controls, ldap.ControlTypeBeheraPasswordPolicy) - - var ppolicy *ldap.ControlBeheraPasswordPolicy - if ppolicyControl != nil { - ppolicy = ppolicyControl.(*ldap.ControlBeheraPasswordPolicy) - } else { - log.Printf("ppolicyControl response not avaliable.\n") - } - if err != nil { - errStr := "ERROR: Cannot bind: " + err.Error() - if ppolicy != nil && ppolicy.Error >= 0 { - errStr += ":" + ppolicy.ErrorString - } - log.Print(errStr) - } else { - logStr := "Login Ok" - if ppolicy != nil { - if ppolicy.Expire >= 0 { - logStr += fmt.Sprintf(". Password expires in %d seconds\n", ppolicy.Expire) - } else if ppolicy.Grace >= 0 { - logStr += fmt.Sprintf(". Password expired, %d grace logins remain\n", ppolicy.Grace) - } - } - log.Print(logStr) - } -} - -func Example_vchuppolicy() { - l, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", "ldap.example.com", 389)) - if err != nil { - log.Fatal(err) - } - defer l.Close() - l.Debug = true - - bindRequest := ldap.NewSimpleBindRequest("cn=admin,dc=example,dc=com", "password", nil) - - r, err := l.SimpleBind(bindRequest) - - passwordMustChangeControl := ldap.FindControl(r.Controls, ldap.ControlTypeVChuPasswordMustChange) - var passwordMustChange *ldap.ControlVChuPasswordMustChange - if passwordMustChangeControl != nil { - passwordMustChange = passwordMustChangeControl.(*ldap.ControlVChuPasswordMustChange) - } - - if passwordMustChange != nil && passwordMustChange.MustChange { - log.Printf("Password Must be changed.\n") - } - - passwordWarningControl := ldap.FindControl(r.Controls, ldap.ControlTypeVChuPasswordWarning) - - var passwordWarning *ldap.ControlVChuPasswordWarning - if passwordWarningControl != nil { - passwordWarning = passwordWarningControl.(*ldap.ControlVChuPasswordWarning) - } else { - log.Printf("ppolicyControl response not available.\n") - } - if err != nil { - log.Print("ERROR: Cannot bind: " + err.Error()) - } else { - logStr := "Login Ok" - if passwordWarning != nil { - if passwordWarning.Expire >= 0 { - logStr += fmt.Sprintf(". Password expires in %d seconds\n", passwordWarning.Expire) - } - } - log.Print(logStr) - } -} diff --git a/Godeps/_workspace/src/github.com/go-ldap/ldap/filter_test.go b/Godeps/_workspace/src/github.com/go-ldap/ldap/filter_test.go deleted file mode 100644 index 8281256e5..000000000 --- a/Godeps/_workspace/src/github.com/go-ldap/ldap/filter_test.go +++ /dev/null @@ -1,96 +0,0 @@ -package ldap - -import ( - "testing" - - "gopkg.in/asn1-ber.v1" -) - -type compileTest struct { - filterStr string - filterType int -} - -var testFilters = []compileTest{ - compileTest{filterStr: "(&(sn=Miller)(givenName=Bob))", filterType: FilterAnd}, - compileTest{filterStr: "(|(sn=Miller)(givenName=Bob))", filterType: FilterOr}, - compileTest{filterStr: "(!(sn=Miller))", filterType: FilterNot}, - compileTest{filterStr: "(sn=Miller)", filterType: FilterEqualityMatch}, - compileTest{filterStr: "(sn=Mill*)", filterType: FilterSubstrings}, - compileTest{filterStr: "(sn=*Mill)", filterType: FilterSubstrings}, - compileTest{filterStr: "(sn=*Mill*)", filterType: FilterSubstrings}, - compileTest{filterStr: "(sn=*i*le*)", filterType: FilterSubstrings}, - compileTest{filterStr: "(sn=Mi*l*r)", filterType: FilterSubstrings}, - compileTest{filterStr: "(sn=Mi*le*)", filterType: FilterSubstrings}, - compileTest{filterStr: "(sn=*i*ler)", filterType: FilterSubstrings}, - compileTest{filterStr: "(sn>=Miller)", filterType: FilterGreaterOrEqual}, - compileTest{filterStr: "(sn<=Miller)", filterType: FilterLessOrEqual}, - compileTest{filterStr: "(sn=*)", filterType: FilterPresent}, - compileTest{filterStr: "(sn~=Miller)", filterType: FilterApproxMatch}, - compileTest{filterStr: `(objectGUID='\fc\fe\a3\ab\f9\90N\aaGm\d5I~\d12)`, filterType: FilterEqualityMatch}, - // compileTest{ filterStr: "()", filterType: FilterExtensibleMatch }, -} - -var testInvalidFilters = []string{ - `(objectGUID=\zz)`, - `(objectGUID=\a)`, -} - -func TestFilter(t *testing.T) { - // Test Compiler and Decompiler - for _, i := range testFilters { - filter, err := CompileFilter(i.filterStr) - if err != nil { - t.Errorf("Problem compiling %s - %s", i.filterStr, err.Error()) - } else if filter.Tag != ber.Tag(i.filterType) { - t.Errorf("%q Expected %q got %q", i.filterStr, FilterMap[uint64(i.filterType)], FilterMap[uint64(filter.Tag)]) - } else { - o, err := DecompileFilter(filter) - if err != nil { - t.Errorf("Problem compiling %s - %s", i.filterStr, err.Error()) - } else if i.filterStr != o { - t.Errorf("%q expected, got %q", i.filterStr, o) - } - } - } -} - -func TestInvalidFilter(t *testing.T) { - for _, filterStr := range testInvalidFilters { - if _, err := CompileFilter(filterStr); err == nil { - t.Errorf("Problem compiling %s - expected err", filterStr) - } - } -} - -func BenchmarkFilterCompile(b *testing.B) { - b.StopTimer() - filters := make([]string, len(testFilters)) - - // Test Compiler and Decompiler - for idx, i := range testFilters { - filters[idx] = i.filterStr - } - - maxIdx := len(filters) - b.StartTimer() - for i := 0; i < b.N; i++ { - CompileFilter(filters[i%maxIdx]) - } -} - -func BenchmarkFilterDecompile(b *testing.B) { - b.StopTimer() - filters := make([]*ber.Packet, len(testFilters)) - - // Test Compiler and Decompiler - for idx, i := range testFilters { - filters[idx], _ = CompileFilter(i.filterStr) - } - - maxIdx := len(filters) - b.StartTimer() - for i := 0; i < b.N; i++ { - DecompileFilter(filters[i%maxIdx]) - } -} diff --git a/Godeps/_workspace/src/github.com/go-ldap/ldap/ldap_test.go b/Godeps/_workspace/src/github.com/go-ldap/ldap/ldap_test.go deleted file mode 100644 index e9933f99a..000000000 --- a/Godeps/_workspace/src/github.com/go-ldap/ldap/ldap_test.go +++ /dev/null @@ -1,247 +0,0 @@ -package ldap - -import ( - "crypto/tls" - "fmt" - "testing" -) - -var ldapServer = "ldap.itd.umich.edu" -var ldapPort = uint16(389) -var ldapTLSPort = uint16(636) -var baseDN = "dc=umich,dc=edu" -var filter = []string{ - "(cn=cis-fac)", - "(&(owner=*)(cn=cis-fac))", - "(&(objectclass=rfc822mailgroup)(cn=*Computer*))", - "(&(objectclass=rfc822mailgroup)(cn=*Mathematics*))"} -var attributes = []string{ - "cn", - "description"} - -func TestDial(t *testing.T) { - fmt.Printf("TestDial: starting...\n") - l, err := Dial("tcp", fmt.Sprintf("%s:%d", ldapServer, ldapPort)) - if err != nil { - t.Errorf(err.Error()) - return - } - defer l.Close() - fmt.Printf("TestDial: finished...\n") -} - -func TestDialTLS(t *testing.T) { - fmt.Printf("TestDialTLS: starting...\n") - l, err := DialTLS("tcp", fmt.Sprintf("%s:%d", ldapServer, ldapTLSPort), &tls.Config{InsecureSkipVerify: true}) - if err != nil { - t.Errorf(err.Error()) - return - } - defer l.Close() - fmt.Printf("TestDialTLS: finished...\n") -} - -func TestStartTLS(t *testing.T) { - fmt.Printf("TestStartTLS: starting...\n") - l, err := Dial("tcp", fmt.Sprintf("%s:%d", ldapServer, ldapPort)) - if err != nil { - t.Errorf(err.Error()) - return - } - err = l.StartTLS(&tls.Config{InsecureSkipVerify: true}) - if err != nil { - t.Errorf(err.Error()) - return - } - fmt.Printf("TestStartTLS: finished...\n") -} - -func TestSearch(t *testing.T) { - fmt.Printf("TestSearch: starting...\n") - l, err := Dial("tcp", fmt.Sprintf("%s:%d", ldapServer, ldapPort)) - if err != nil { - t.Errorf(err.Error()) - return - } - defer l.Close() - - searchRequest := NewSearchRequest( - baseDN, - ScopeWholeSubtree, DerefAlways, 0, 0, false, - filter[0], - attributes, - nil) - - sr, err := l.Search(searchRequest) - if err != nil { - t.Errorf(err.Error()) - return - } - - fmt.Printf("TestSearch: %s -> num of entries = %d\n", searchRequest.Filter, len(sr.Entries)) -} - -func TestSearchStartTLS(t *testing.T) { - fmt.Printf("TestSearchStartTLS: starting...\n") - l, err := Dial("tcp", fmt.Sprintf("%s:%d", ldapServer, ldapPort)) - if err != nil { - t.Errorf(err.Error()) - return - } - defer l.Close() - - searchRequest := NewSearchRequest( - baseDN, - ScopeWholeSubtree, DerefAlways, 0, 0, false, - filter[0], - attributes, - nil) - - sr, err := l.Search(searchRequest) - if err != nil { - t.Errorf(err.Error()) - return - } - - fmt.Printf("TestSearchStartTLS: %s -> num of entries = %d\n", searchRequest.Filter, len(sr.Entries)) - - fmt.Printf("TestSearchStartTLS: upgrading with startTLS\n") - err = l.StartTLS(&tls.Config{InsecureSkipVerify: true}) - if err != nil { - t.Errorf(err.Error()) - return - } - - sr, err = l.Search(searchRequest) - if err != nil { - t.Errorf(err.Error()) - return - } - - fmt.Printf("TestSearchStartTLS: %s -> num of entries = %d\n", searchRequest.Filter, len(sr.Entries)) -} - -func TestSearchWithPaging(t *testing.T) { - fmt.Printf("TestSearchWithPaging: starting...\n") - l, err := Dial("tcp", fmt.Sprintf("%s:%d", ldapServer, ldapPort)) - if err != nil { - t.Errorf(err.Error()) - return - } - defer l.Close() - - err = l.Bind("", "") - if err != nil { - t.Errorf(err.Error()) - return - } - - searchRequest := NewSearchRequest( - baseDN, - ScopeWholeSubtree, DerefAlways, 0, 0, false, - filter[2], - attributes, - nil) - sr, err := l.SearchWithPaging(searchRequest, 5) - if err != nil { - t.Errorf(err.Error()) - return - } - - fmt.Printf("TestSearchWithPaging: %s -> num of entries = %d\n", searchRequest.Filter, len(sr.Entries)) -} - -func searchGoroutine(t *testing.T, l *Conn, results chan *SearchResult, i int) { - searchRequest := NewSearchRequest( - baseDN, - ScopeWholeSubtree, DerefAlways, 0, 0, false, - filter[i], - attributes, - nil) - sr, err := l.Search(searchRequest) - if err != nil { - t.Errorf(err.Error()) - results <- nil - return - } - results <- sr -} - -func testMultiGoroutineSearch(t *testing.T, TLS bool, startTLS bool) { - fmt.Printf("TestMultiGoroutineSearch: starting...\n") - var l *Conn - var err error - if TLS { - l, err = DialTLS("tcp", fmt.Sprintf("%s:%d", ldapServer, ldapTLSPort), &tls.Config{InsecureSkipVerify: true}) - if err != nil { - t.Errorf(err.Error()) - return - } - defer l.Close() - } else { - l, err = Dial("tcp", fmt.Sprintf("%s:%d", ldapServer, ldapPort)) - if err != nil { - t.Errorf(err.Error()) - return - } - if startTLS { - fmt.Printf("TestMultiGoroutineSearch: using StartTLS...\n") - err := l.StartTLS(&tls.Config{InsecureSkipVerify: true}) - if err != nil { - t.Errorf(err.Error()) - return - } - - } - } - - results := make([]chan *SearchResult, len(filter)) - for i := range filter { - results[i] = make(chan *SearchResult) - go searchGoroutine(t, l, results[i], i) - } - for i := range filter { - sr := <-results[i] - if sr == nil { - t.Errorf("Did not receive results from goroutine for %q", filter[i]) - } else { - fmt.Printf("TestMultiGoroutineSearch(%d): %s -> num of entries = %d\n", i, filter[i], len(sr.Entries)) - } - } -} - -func TestMultiGoroutineSearch(t *testing.T) { - testMultiGoroutineSearch(t, false, false) - testMultiGoroutineSearch(t, true, true) - testMultiGoroutineSearch(t, false, true) -} - -func TestEscapeFilter(t *testing.T) { - if got, want := EscapeFilter("a\x00b(c)d*e\\f"), `a\00b\28c\29d\2ae\5cf`; got != want { - t.Errorf("Got %s, expected %s", want, got) - } - if got, want := EscapeFilter("Lučić"), `Lu\c4\8di\c4\87`; got != want { - t.Errorf("Got %s, expected %s", want, got) - } -} - -func TestCompare(t *testing.T) { - fmt.Printf("TestCompare: starting...\n") - l, err := Dial("tcp", fmt.Sprintf("%s:%d", ldapServer, ldapPort)) - if err != nil { - t.Fatal(err.Error()) - } - defer l.Close() - - dn := "cn=math mich,ou=User Groups,ou=Groups,dc=umich,dc=edu" - attribute := "cn" - value := "math mich" - - sr, err := l.Compare(dn, attribute, value) - if err != nil { - t.Errorf(err.Error()) - return - } - - fmt.Printf("TestCompare: -> num of entries = %d\n", sr) -} diff --git a/Godeps/_workspace/src/github.com/go-sql-driver/mysql/README.md b/Godeps/_workspace/src/github.com/go-sql-driver/mysql/README.md index 6a2bb2ca3..72b921eaf 100644 --- a/Godeps/_workspace/src/github.com/go-sql-driver/mysql/README.md +++ b/Godeps/_workspace/src/github.com/go-sql-driver/mysql/README.md @@ -30,7 +30,7 @@ A MySQL-Driver for Go's [database/sql](http://golang.org/pkg/database/sql) packa ## Features * Lightweight and [fast](https://github.com/go-sql-driver/sql-benchmark "golang MySQL-Driver performance") * Native Go implementation. No C-bindings, just pure Go - * Connections over TCP/IPv4, TCP/IPv6 or Unix domain sockets + * Connections over TCP/IPv4, TCP/IPv6, Unix domain sockets or [custom protocols](http://godoc.org/github.com/go-sql-driver/mysql#DialFunc) * Automatic handling of broken connections * Automatic Connection Pooling *(by database/sql package)* * Supports queries larger than 16MB diff --git a/Godeps/_workspace/src/github.com/go-sql-driver/mysql/benchmark_test.go b/Godeps/_workspace/src/github.com/go-sql-driver/mysql/benchmark_test.go deleted file mode 100644 index fb8a2f5f3..000000000 --- a/Godeps/_workspace/src/github.com/go-sql-driver/mysql/benchmark_test.go +++ /dev/null @@ -1,246 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package -// -// Copyright 2013 The Go-MySQL-Driver Authors. All rights reserved. -// -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this file, -// You can obtain one at http://mozilla.org/MPL/2.0/. - -package mysql - -import ( - "bytes" - "database/sql" - "database/sql/driver" - "math" - "strings" - "sync" - "sync/atomic" - "testing" - "time" -) - -type TB testing.B - -func (tb *TB) check(err error) { - if err != nil { - tb.Fatal(err) - } -} - -func (tb *TB) checkDB(db *sql.DB, err error) *sql.DB { - tb.check(err) - return db -} - -func (tb *TB) checkRows(rows *sql.Rows, err error) *sql.Rows { - tb.check(err) - return rows -} - -func (tb *TB) checkStmt(stmt *sql.Stmt, err error) *sql.Stmt { - tb.check(err) - return stmt -} - -func initDB(b *testing.B, queries ...string) *sql.DB { - tb := (*TB)(b) - db := tb.checkDB(sql.Open("mysql", dsn)) - for _, query := range queries { - if _, err := db.Exec(query); err != nil { - if w, ok := err.(MySQLWarnings); ok { - b.Logf("Warning on %q: %v", query, w) - } else { - b.Fatalf("Error on %q: %v", query, err) - } - } - } - return db -} - -const concurrencyLevel = 10 - -func BenchmarkQuery(b *testing.B) { - tb := (*TB)(b) - b.StopTimer() - b.ReportAllocs() - db := initDB(b, - "DROP TABLE IF EXISTS foo", - "CREATE TABLE foo (id INT PRIMARY KEY, val CHAR(50))", - `INSERT INTO foo VALUES (1, "one")`, - `INSERT INTO foo VALUES (2, "two")`, - ) - db.SetMaxIdleConns(concurrencyLevel) - defer db.Close() - - stmt := tb.checkStmt(db.Prepare("SELECT val FROM foo WHERE id=?")) - defer stmt.Close() - - remain := int64(b.N) - var wg sync.WaitGroup - wg.Add(concurrencyLevel) - defer wg.Wait() - b.StartTimer() - - for i := 0; i < concurrencyLevel; i++ { - go func() { - for { - if atomic.AddInt64(&remain, -1) < 0 { - wg.Done() - return - } - - var got string - tb.check(stmt.QueryRow(1).Scan(&got)) - if got != "one" { - b.Errorf("query = %q; want one", got) - wg.Done() - return - } - } - }() - } -} - -func BenchmarkExec(b *testing.B) { - tb := (*TB)(b) - b.StopTimer() - b.ReportAllocs() - db := tb.checkDB(sql.Open("mysql", dsn)) - db.SetMaxIdleConns(concurrencyLevel) - defer db.Close() - - stmt := tb.checkStmt(db.Prepare("DO 1")) - defer stmt.Close() - - remain := int64(b.N) - var wg sync.WaitGroup - wg.Add(concurrencyLevel) - defer wg.Wait() - b.StartTimer() - - for i := 0; i < concurrencyLevel; i++ { - go func() { - for { - if atomic.AddInt64(&remain, -1) < 0 { - wg.Done() - return - } - - if _, err := stmt.Exec(); err != nil { - b.Fatal(err.Error()) - } - } - }() - } -} - -// data, but no db writes -var roundtripSample []byte - -func initRoundtripBenchmarks() ([]byte, int, int) { - if roundtripSample == nil { - roundtripSample = []byte(strings.Repeat("0123456789abcdef", 1024*1024)) - } - return roundtripSample, 16, len(roundtripSample) -} - -func BenchmarkRoundtripTxt(b *testing.B) { - b.StopTimer() - sample, min, max := initRoundtripBenchmarks() - sampleString := string(sample) - b.ReportAllocs() - tb := (*TB)(b) - db := tb.checkDB(sql.Open("mysql", dsn)) - defer db.Close() - b.StartTimer() - var result string - for i := 0; i < b.N; i++ { - length := min + i - if length > max { - length = max - } - test := sampleString[0:length] - rows := tb.checkRows(db.Query(`SELECT "` + test + `"`)) - if !rows.Next() { - rows.Close() - b.Fatalf("crashed") - } - err := rows.Scan(&result) - if err != nil { - rows.Close() - b.Fatalf("crashed") - } - if result != test { - rows.Close() - b.Errorf("mismatch") - } - rows.Close() - } -} - -func BenchmarkRoundtripBin(b *testing.B) { - b.StopTimer() - sample, min, max := initRoundtripBenchmarks() - b.ReportAllocs() - tb := (*TB)(b) - db := tb.checkDB(sql.Open("mysql", dsn)) - defer db.Close() - stmt := tb.checkStmt(db.Prepare("SELECT ?")) - defer stmt.Close() - b.StartTimer() - var result sql.RawBytes - for i := 0; i < b.N; i++ { - length := min + i - if length > max { - length = max - } - test := sample[0:length] - rows := tb.checkRows(stmt.Query(test)) - if !rows.Next() { - rows.Close() - b.Fatalf("crashed") - } - err := rows.Scan(&result) - if err != nil { - rows.Close() - b.Fatalf("crashed") - } - if !bytes.Equal(result, test) { - rows.Close() - b.Errorf("mismatch") - } - rows.Close() - } -} - -func BenchmarkInterpolation(b *testing.B) { - mc := &mysqlConn{ - cfg: &config{ - interpolateParams: true, - loc: time.UTC, - }, - maxPacketAllowed: maxPacketSize, - maxWriteSize: maxPacketSize - 1, - buf: newBuffer(nil), - } - - args := []driver.Value{ - int64(42424242), - float64(math.Pi), - false, - time.Unix(1423411542, 807015000), - []byte("bytes containing special chars ' \" \a \x00"), - "string containing special chars ' \" \a \x00", - } - q := "SELECT ?, ?, ?, ?, ?, ?" - - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - _, err := mc.interpolateParams(q, args) - if err != nil { - b.Fatal(err) - } - } -} diff --git a/Godeps/_workspace/src/github.com/go-sql-driver/mysql/driver_test.go b/Godeps/_workspace/src/github.com/go-sql-driver/mysql/driver_test.go deleted file mode 100644 index f9da416ec..000000000 --- a/Godeps/_workspace/src/github.com/go-sql-driver/mysql/driver_test.go +++ /dev/null @@ -1,1681 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package -// -// Copyright 2013 The Go-MySQL-Driver Authors. All rights reserved. -// -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this file, -// You can obtain one at http://mozilla.org/MPL/2.0/. - -package mysql - -import ( - "crypto/tls" - "database/sql" - "database/sql/driver" - "fmt" - "io" - "io/ioutil" - "net" - "net/url" - "os" - "strings" - "sync" - "sync/atomic" - "testing" - "time" -) - -var ( - user string - pass string - prot string - addr string - dbname string - dsn string - netAddr string - available bool -) - -var ( - tDate = time.Date(2012, 6, 14, 0, 0, 0, 0, time.UTC) - sDate = "2012-06-14" - tDateTime = time.Date(2011, 11, 20, 21, 27, 37, 0, time.UTC) - sDateTime = "2011-11-20 21:27:37" - tDate0 = time.Time{} - sDate0 = "0000-00-00" - sDateTime0 = "0000-00-00 00:00:00" -) - -// See https://github.com/go-sql-driver/mysql/wiki/Testing -func init() { - // get environment variables - env := func(key, defaultValue string) string { - if value := os.Getenv(key); value != "" { - return value - } - return defaultValue - } - user = env("MYSQL_TEST_USER", "root") - pass = env("MYSQL_TEST_PASS", "") - prot = env("MYSQL_TEST_PROT", "tcp") - addr = env("MYSQL_TEST_ADDR", "localhost:3306") - dbname = env("MYSQL_TEST_DBNAME", "gotest") - netAddr = fmt.Sprintf("%s(%s)", prot, addr) - dsn = fmt.Sprintf("%s:%s@%s/%s?timeout=30s&strict=true", user, pass, netAddr, dbname) - c, err := net.Dial(prot, addr) - if err == nil { - available = true - c.Close() - } -} - -type DBTest struct { - *testing.T - db *sql.DB -} - -func runTests(t *testing.T, dsn string, tests ...func(dbt *DBTest)) { - if !available { - t.Skipf("MySQL-Server not running on %s", netAddr) - } - - db, err := sql.Open("mysql", dsn) - if err != nil { - t.Fatalf("Error connecting: %s", err.Error()) - } - defer db.Close() - - db.Exec("DROP TABLE IF EXISTS test") - - dsn2 := dsn + "&interpolateParams=true" - var db2 *sql.DB - if _, err := parseDSN(dsn2); err != errInvalidDSNUnsafeCollation { - db2, err = sql.Open("mysql", dsn2) - if err != nil { - t.Fatalf("Error connecting: %s", err.Error()) - } - defer db2.Close() - } - - dbt := &DBTest{t, db} - dbt2 := &DBTest{t, db2} - for _, test := range tests { - test(dbt) - dbt.db.Exec("DROP TABLE IF EXISTS test") - if db2 != nil { - test(dbt2) - dbt2.db.Exec("DROP TABLE IF EXISTS test") - } - } -} - -func (dbt *DBTest) fail(method, query string, err error) { - if len(query) > 300 { - query = "[query too large to print]" - } - dbt.Fatalf("Error on %s %s: %s", method, query, err.Error()) -} - -func (dbt *DBTest) mustExec(query string, args ...interface{}) (res sql.Result) { - res, err := dbt.db.Exec(query, args...) - if err != nil { - dbt.fail("Exec", query, err) - } - return res -} - -func (dbt *DBTest) mustQuery(query string, args ...interface{}) (rows *sql.Rows) { - rows, err := dbt.db.Query(query, args...) - if err != nil { - dbt.fail("Query", query, err) - } - return rows -} - -func TestEmptyQuery(t *testing.T) { - runTests(t, dsn, func(dbt *DBTest) { - // just a comment, no query - rows := dbt.mustQuery("--") - // will hang before #255 - if rows.Next() { - dbt.Errorf("Next on rows must be false") - } - }) -} - -func TestCRUD(t *testing.T) { - runTests(t, dsn, func(dbt *DBTest) { - // Create Table - dbt.mustExec("CREATE TABLE test (value BOOL)") - - // Test for unexpected data - var out bool - rows := dbt.mustQuery("SELECT * FROM test") - if rows.Next() { - dbt.Error("unexpected data in empty table") - } - - // Create Data - res := dbt.mustExec("INSERT INTO test VALUES (1)") - count, err := res.RowsAffected() - if err != nil { - dbt.Fatalf("res.RowsAffected() returned error: %s", err.Error()) - } - if count != 1 { - dbt.Fatalf("Expected 1 affected row, got %d", count) - } - - id, err := res.LastInsertId() - if err != nil { - dbt.Fatalf("res.LastInsertId() returned error: %s", err.Error()) - } - if id != 0 { - dbt.Fatalf("Expected InsertID 0, got %d", id) - } - - // Read - rows = dbt.mustQuery("SELECT value FROM test") - if rows.Next() { - rows.Scan(&out) - if true != out { - dbt.Errorf("true != %t", out) - } - - if rows.Next() { - dbt.Error("unexpected data") - } - } else { - dbt.Error("no data") - } - - // Update - res = dbt.mustExec("UPDATE test SET value = ? WHERE value = ?", false, true) - count, err = res.RowsAffected() - if err != nil { - dbt.Fatalf("res.RowsAffected() returned error: %s", err.Error()) - } - if count != 1 { - dbt.Fatalf("Expected 1 affected row, got %d", count) - } - - // Check Update - rows = dbt.mustQuery("SELECT value FROM test") - if rows.Next() { - rows.Scan(&out) - if false != out { - dbt.Errorf("false != %t", out) - } - - if rows.Next() { - dbt.Error("unexpected data") - } - } else { - dbt.Error("no data") - } - - // Delete - res = dbt.mustExec("DELETE FROM test WHERE value = ?", false) - count, err = res.RowsAffected() - if err != nil { - dbt.Fatalf("res.RowsAffected() returned error: %s", err.Error()) - } - if count != 1 { - dbt.Fatalf("Expected 1 affected row, got %d", count) - } - - // Check for unexpected rows - res = dbt.mustExec("DELETE FROM test") - count, err = res.RowsAffected() - if err != nil { - dbt.Fatalf("res.RowsAffected() returned error: %s", err.Error()) - } - if count != 0 { - dbt.Fatalf("Expected 0 affected row, got %d", count) - } - }) -} - -func TestInt(t *testing.T) { - runTests(t, dsn, func(dbt *DBTest) { - types := [5]string{"TINYINT", "SMALLINT", "MEDIUMINT", "INT", "BIGINT"} - in := int64(42) - var out int64 - var rows *sql.Rows - - // SIGNED - for _, v := range types { - dbt.mustExec("CREATE TABLE test (value " + v + ")") - - dbt.mustExec("INSERT INTO test VALUES (?)", in) - - rows = dbt.mustQuery("SELECT value FROM test") - if rows.Next() { - rows.Scan(&out) - if in != out { - dbt.Errorf("%s: %d != %d", v, in, out) - } - } else { - dbt.Errorf("%s: no data", v) - } - - dbt.mustExec("DROP TABLE IF EXISTS test") - } - - // UNSIGNED ZEROFILL - for _, v := range types { - dbt.mustExec("CREATE TABLE test (value " + v + " ZEROFILL)") - - dbt.mustExec("INSERT INTO test VALUES (?)", in) - - rows = dbt.mustQuery("SELECT value FROM test") - if rows.Next() { - rows.Scan(&out) - if in != out { - dbt.Errorf("%s ZEROFILL: %d != %d", v, in, out) - } - } else { - dbt.Errorf("%s ZEROFILL: no data", v) - } - - dbt.mustExec("DROP TABLE IF EXISTS test") - } - }) -} - -func TestFloat(t *testing.T) { - runTests(t, dsn, func(dbt *DBTest) { - types := [2]string{"FLOAT", "DOUBLE"} - in := float32(42.23) - var out float32 - var rows *sql.Rows - for _, v := range types { - dbt.mustExec("CREATE TABLE test (value " + v + ")") - dbt.mustExec("INSERT INTO test VALUES (?)", in) - rows = dbt.mustQuery("SELECT value FROM test") - if rows.Next() { - rows.Scan(&out) - if in != out { - dbt.Errorf("%s: %g != %g", v, in, out) - } - } else { - dbt.Errorf("%s: no data", v) - } - dbt.mustExec("DROP TABLE IF EXISTS test") - } - }) -} - -func TestString(t *testing.T) { - runTests(t, dsn, func(dbt *DBTest) { - types := [6]string{"CHAR(255)", "VARCHAR(255)", "TINYTEXT", "TEXT", "MEDIUMTEXT", "LONGTEXT"} - in := "κόσμε üöäßñóùéàâÿœ'îë Árvíztűrő いろはにほへとちりぬるを イロハニホヘト דג סקרן чащах น่าฟังเอย" - var out string - var rows *sql.Rows - - for _, v := range types { - dbt.mustExec("CREATE TABLE test (value " + v + ") CHARACTER SET utf8") - - dbt.mustExec("INSERT INTO test VALUES (?)", in) - - rows = dbt.mustQuery("SELECT value FROM test") - if rows.Next() { - rows.Scan(&out) - if in != out { - dbt.Errorf("%s: %s != %s", v, in, out) - } - } else { - dbt.Errorf("%s: no data", v) - } - - dbt.mustExec("DROP TABLE IF EXISTS test") - } - - // BLOB - dbt.mustExec("CREATE TABLE test (id int, value BLOB) CHARACTER SET utf8") - - id := 2 - in = "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, " + - "sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, " + - "sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. " + - "Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. " + - "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, " + - "sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, " + - "sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. " + - "Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet." - dbt.mustExec("INSERT INTO test VALUES (?, ?)", id, in) - - err := dbt.db.QueryRow("SELECT value FROM test WHERE id = ?", id).Scan(&out) - if err != nil { - dbt.Fatalf("Error on BLOB-Query: %s", err.Error()) - } else if out != in { - dbt.Errorf("BLOB: %s != %s", in, out) - } - }) -} - -type timeTests struct { - dbtype string - tlayout string - tests []timeTest -} - -type timeTest struct { - s string // leading "!": do not use t as value in queries - t time.Time -} - -type timeMode byte - -func (t timeMode) String() string { - switch t { - case binaryString: - return "binary:string" - case binaryTime: - return "binary:time.Time" - case textString: - return "text:string" - } - panic("unsupported timeMode") -} - -func (t timeMode) Binary() bool { - switch t { - case binaryString, binaryTime: - return true - } - return false -} - -const ( - binaryString timeMode = iota - binaryTime - textString -) - -func (t timeTest) genQuery(dbtype string, mode timeMode) string { - var inner string - if mode.Binary() { - inner = "?" - } else { - inner = `"%s"` - } - return `SELECT cast(` + inner + ` as ` + dbtype + `)` -} - -func (t timeTest) run(dbt *DBTest, dbtype, tlayout string, mode timeMode) { - var rows *sql.Rows - query := t.genQuery(dbtype, mode) - switch mode { - case binaryString: - rows = dbt.mustQuery(query, t.s) - case binaryTime: - rows = dbt.mustQuery(query, t.t) - case textString: - query = fmt.Sprintf(query, t.s) - rows = dbt.mustQuery(query) - default: - panic("unsupported mode") - } - defer rows.Close() - var err error - if !rows.Next() { - err = rows.Err() - if err == nil { - err = fmt.Errorf("no data") - } - dbt.Errorf("%s [%s]: %s", dbtype, mode, err) - return - } - var dst interface{} - err = rows.Scan(&dst) - if err != nil { - dbt.Errorf("%s [%s]: %s", dbtype, mode, err) - return - } - switch val := dst.(type) { - case []uint8: - str := string(val) - if str == t.s { - return - } - if mode.Binary() && dbtype == "DATETIME" && len(str) == 26 && str[:19] == t.s { - // a fix mainly for TravisCI: - // accept full microsecond resolution in result for DATETIME columns - // where the binary protocol was used - return - } - dbt.Errorf("%s [%s] to string: expected %q, got %q", - dbtype, mode, - t.s, str, - ) - case time.Time: - if val == t.t { - return - } - dbt.Errorf("%s [%s] to string: expected %q, got %q", - dbtype, mode, - t.s, val.Format(tlayout), - ) - default: - fmt.Printf("%#v\n", []interface{}{dbtype, tlayout, mode, t.s, t.t}) - dbt.Errorf("%s [%s]: unhandled type %T (is '%v')", - dbtype, mode, - val, val, - ) - } -} - -func TestDateTime(t *testing.T) { - afterTime := func(t time.Time, d string) time.Time { - dur, err := time.ParseDuration(d) - if err != nil { - panic(err) - } - return t.Add(dur) - } - // NOTE: MySQL rounds DATETIME(x) up - but that's not included in the tests - format := "2006-01-02 15:04:05.999999" - t0 := time.Time{} - tstr0 := "0000-00-00 00:00:00.000000" - testcases := []timeTests{ - {"DATE", format[:10], []timeTest{ - {t: time.Date(2011, 11, 20, 0, 0, 0, 0, time.UTC)}, - {t: t0, s: tstr0[:10]}, - }}, - {"DATETIME", format[:19], []timeTest{ - {t: time.Date(2011, 11, 20, 21, 27, 37, 0, time.UTC)}, - {t: t0, s: tstr0[:19]}, - }}, - {"DATETIME(0)", format[:21], []timeTest{ - {t: time.Date(2011, 11, 20, 21, 27, 37, 0, time.UTC)}, - {t: t0, s: tstr0[:19]}, - }}, - {"DATETIME(1)", format[:21], []timeTest{ - {t: time.Date(2011, 11, 20, 21, 27, 37, 100000000, time.UTC)}, - {t: t0, s: tstr0[:21]}, - }}, - {"DATETIME(6)", format, []timeTest{ - {t: time.Date(2011, 11, 20, 21, 27, 37, 123456000, time.UTC)}, - {t: t0, s: tstr0}, - }}, - {"TIME", format[11:19], []timeTest{ - {t: afterTime(t0, "12345s")}, - {s: "!-12:34:56"}, - {s: "!-838:59:59"}, - {s: "!838:59:59"}, - {t: t0, s: tstr0[11:19]}, - }}, - {"TIME(0)", format[11:19], []timeTest{ - {t: afterTime(t0, "12345s")}, - {s: "!-12:34:56"}, - {s: "!-838:59:59"}, - {s: "!838:59:59"}, - {t: t0, s: tstr0[11:19]}, - }}, - {"TIME(1)", format[11:21], []timeTest{ - {t: afterTime(t0, "12345600ms")}, - {s: "!-12:34:56.7"}, - {s: "!-838:59:58.9"}, - {s: "!838:59:58.9"}, - {t: t0, s: tstr0[11:21]}, - }}, - {"TIME(6)", format[11:], []timeTest{ - {t: afterTime(t0, "1234567890123000ns")}, - {s: "!-12:34:56.789012"}, - {s: "!-838:59:58.999999"}, - {s: "!838:59:58.999999"}, - {t: t0, s: tstr0[11:]}, - }}, - } - dsns := []string{ - dsn + "&parseTime=true", - dsn + "&parseTime=false", - } - for _, testdsn := range dsns { - runTests(t, testdsn, func(dbt *DBTest) { - microsecsSupported := false - zeroDateSupported := false - var rows *sql.Rows - var err error - rows, err = dbt.db.Query(`SELECT cast("00:00:00.1" as TIME(1)) = "00:00:00.1"`) - if err == nil { - rows.Scan(µsecsSupported) - rows.Close() - } - rows, err = dbt.db.Query(`SELECT cast("0000-00-00" as DATE) = "0000-00-00"`) - if err == nil { - rows.Scan(&zeroDateSupported) - rows.Close() - } - for _, setups := range testcases { - if t := setups.dbtype; !microsecsSupported && t[len(t)-1:] == ")" { - // skip fractional second tests if unsupported by server - continue - } - for _, setup := range setups.tests { - allowBinTime := true - if setup.s == "" { - // fill time string whereever Go can reliable produce it - setup.s = setup.t.Format(setups.tlayout) - } else if setup.s[0] == '!' { - // skip tests using setup.t as source in queries - allowBinTime = false - // fix setup.s - remove the "!" - setup.s = setup.s[1:] - } - if !zeroDateSupported && setup.s == tstr0[:len(setup.s)] { - // skip disallowed 0000-00-00 date - continue - } - setup.run(dbt, setups.dbtype, setups.tlayout, textString) - setup.run(dbt, setups.dbtype, setups.tlayout, binaryString) - if allowBinTime { - setup.run(dbt, setups.dbtype, setups.tlayout, binaryTime) - } - } - } - }) - } -} - -func TestTimestampMicros(t *testing.T) { - format := "2006-01-02 15:04:05.999999" - f0 := format[:19] - f1 := format[:21] - f6 := format[:26] - runTests(t, dsn, func(dbt *DBTest) { - // check if microseconds are supported. - // Do not use timestamp(x) for that check - before 5.5.6, x would mean display width - // and not precision. - // Se last paragraph at http://dev.mysql.com/doc/refman/5.6/en/fractional-seconds.html - microsecsSupported := false - if rows, err := dbt.db.Query(`SELECT cast("00:00:00.1" as TIME(1)) = "00:00:00.1"`); err == nil { - rows.Scan(µsecsSupported) - rows.Close() - } - if !microsecsSupported { - // skip test - return - } - _, err := dbt.db.Exec(` - CREATE TABLE test ( - value0 TIMESTAMP NOT NULL DEFAULT '` + f0 + `', - value1 TIMESTAMP(1) NOT NULL DEFAULT '` + f1 + `', - value6 TIMESTAMP(6) NOT NULL DEFAULT '` + f6 + `' - )`, - ) - if err != nil { - dbt.Error(err) - } - defer dbt.mustExec("DROP TABLE IF EXISTS test") - dbt.mustExec("INSERT INTO test SET value0=?, value1=?, value6=?", f0, f1, f6) - var res0, res1, res6 string - rows := dbt.mustQuery("SELECT * FROM test") - if !rows.Next() { - dbt.Errorf("test contained no selectable values") - } - err = rows.Scan(&res0, &res1, &res6) - if err != nil { - dbt.Error(err) - } - if res0 != f0 { - dbt.Errorf("expected %q, got %q", f0, res0) - } - if res1 != f1 { - dbt.Errorf("expected %q, got %q", f1, res1) - } - if res6 != f6 { - dbt.Errorf("expected %q, got %q", f6, res6) - } - }) -} - -func TestNULL(t *testing.T) { - runTests(t, dsn, func(dbt *DBTest) { - nullStmt, err := dbt.db.Prepare("SELECT NULL") - if err != nil { - dbt.Fatal(err) - } - defer nullStmt.Close() - - nonNullStmt, err := dbt.db.Prepare("SELECT 1") - if err != nil { - dbt.Fatal(err) - } - defer nonNullStmt.Close() - - // NullBool - var nb sql.NullBool - // Invalid - if err = nullStmt.QueryRow().Scan(&nb); err != nil { - dbt.Fatal(err) - } - if nb.Valid { - dbt.Error("Valid NullBool which should be invalid") - } - // Valid - if err = nonNullStmt.QueryRow().Scan(&nb); err != nil { - dbt.Fatal(err) - } - if !nb.Valid { - dbt.Error("Invalid NullBool which should be valid") - } else if nb.Bool != true { - dbt.Errorf("Unexpected NullBool value: %t (should be true)", nb.Bool) - } - - // NullFloat64 - var nf sql.NullFloat64 - // Invalid - if err = nullStmt.QueryRow().Scan(&nf); err != nil { - dbt.Fatal(err) - } - if nf.Valid { - dbt.Error("Valid NullFloat64 which should be invalid") - } - // Valid - if err = nonNullStmt.QueryRow().Scan(&nf); err != nil { - dbt.Fatal(err) - } - if !nf.Valid { - dbt.Error("Invalid NullFloat64 which should be valid") - } else if nf.Float64 != float64(1) { - dbt.Errorf("Unexpected NullFloat64 value: %f (should be 1.0)", nf.Float64) - } - - // NullInt64 - var ni sql.NullInt64 - // Invalid - if err = nullStmt.QueryRow().Scan(&ni); err != nil { - dbt.Fatal(err) - } - if ni.Valid { - dbt.Error("Valid NullInt64 which should be invalid") - } - // Valid - if err = nonNullStmt.QueryRow().Scan(&ni); err != nil { - dbt.Fatal(err) - } - if !ni.Valid { - dbt.Error("Invalid NullInt64 which should be valid") - } else if ni.Int64 != int64(1) { - dbt.Errorf("Unexpected NullInt64 value: %d (should be 1)", ni.Int64) - } - - // NullString - var ns sql.NullString - // Invalid - if err = nullStmt.QueryRow().Scan(&ns); err != nil { - dbt.Fatal(err) - } - if ns.Valid { - dbt.Error("Valid NullString which should be invalid") - } - // Valid - if err = nonNullStmt.QueryRow().Scan(&ns); err != nil { - dbt.Fatal(err) - } - if !ns.Valid { - dbt.Error("Invalid NullString which should be valid") - } else if ns.String != `1` { - dbt.Error("Unexpected NullString value:" + ns.String + " (should be `1`)") - } - - // nil-bytes - var b []byte - // Read nil - if err = nullStmt.QueryRow().Scan(&b); err != nil { - dbt.Fatal(err) - } - if b != nil { - dbt.Error("Non-nil []byte wich should be nil") - } - // Read non-nil - if err = nonNullStmt.QueryRow().Scan(&b); err != nil { - dbt.Fatal(err) - } - if b == nil { - dbt.Error("Nil []byte wich should be non-nil") - } - // Insert nil - b = nil - success := false - if err = dbt.db.QueryRow("SELECT ? IS NULL", b).Scan(&success); err != nil { - dbt.Fatal(err) - } - if !success { - dbt.Error("Inserting []byte(nil) as NULL failed") - } - // Check input==output with input==nil - b = nil - if err = dbt.db.QueryRow("SELECT ?", b).Scan(&b); err != nil { - dbt.Fatal(err) - } - if b != nil { - dbt.Error("Non-nil echo from nil input") - } - // Check input==output with input!=nil - b = []byte("") - if err = dbt.db.QueryRow("SELECT ?", b).Scan(&b); err != nil { - dbt.Fatal(err) - } - if b == nil { - dbt.Error("nil echo from non-nil input") - } - - // Insert NULL - dbt.mustExec("CREATE TABLE test (dummmy1 int, value int, dummy2 int)") - - dbt.mustExec("INSERT INTO test VALUES (?, ?, ?)", 1, nil, 2) - - var out interface{} - rows := dbt.mustQuery("SELECT * FROM test") - if rows.Next() { - rows.Scan(&out) - if out != nil { - dbt.Errorf("%v != nil", out) - } - } else { - dbt.Error("no data") - } - }) -} - -func TestUint64(t *testing.T) { - const ( - u0 = uint64(0) - uall = ^u0 - uhigh = uall >> 1 - utop = ^uhigh - s0 = int64(0) - sall = ^s0 - shigh = int64(uhigh) - stop = ^shigh - ) - runTests(t, dsn, func(dbt *DBTest) { - stmt, err := dbt.db.Prepare(`SELECT ?, ?, ? ,?, ?, ?, ?, ?`) - if err != nil { - dbt.Fatal(err) - } - defer stmt.Close() - row := stmt.QueryRow( - u0, uhigh, utop, uall, - s0, shigh, stop, sall, - ) - - var ua, ub, uc, ud uint64 - var sa, sb, sc, sd int64 - - err = row.Scan(&ua, &ub, &uc, &ud, &sa, &sb, &sc, &sd) - if err != nil { - dbt.Fatal(err) - } - switch { - case ua != u0, - ub != uhigh, - uc != utop, - ud != uall, - sa != s0, - sb != shigh, - sc != stop, - sd != sall: - dbt.Fatal("Unexpected result value") - } - }) -} - -func TestLongData(t *testing.T) { - runTests(t, dsn, func(dbt *DBTest) { - var maxAllowedPacketSize int - err := dbt.db.QueryRow("select @@max_allowed_packet").Scan(&maxAllowedPacketSize) - if err != nil { - dbt.Fatal(err) - } - maxAllowedPacketSize-- - - // don't get too ambitious - if maxAllowedPacketSize > 1<<25 { - maxAllowedPacketSize = 1 << 25 - } - - dbt.mustExec("CREATE TABLE test (value LONGBLOB)") - - in := strings.Repeat(`a`, maxAllowedPacketSize+1) - var out string - var rows *sql.Rows - - // Long text data - const nonDataQueryLen = 28 // length query w/o value - inS := in[:maxAllowedPacketSize-nonDataQueryLen] - dbt.mustExec("INSERT INTO test VALUES('" + inS + "')") - rows = dbt.mustQuery("SELECT value FROM test") - if rows.Next() { - rows.Scan(&out) - if inS != out { - dbt.Fatalf("LONGBLOB: length in: %d, length out: %d", len(inS), len(out)) - } - if rows.Next() { - dbt.Error("LONGBLOB: unexpexted row") - } - } else { - dbt.Fatalf("LONGBLOB: no data") - } - - // Empty table - dbt.mustExec("TRUNCATE TABLE test") - - // Long binary data - dbt.mustExec("INSERT INTO test VALUES(?)", in) - rows = dbt.mustQuery("SELECT value FROM test WHERE 1=?", 1) - if rows.Next() { - rows.Scan(&out) - if in != out { - dbt.Fatalf("LONGBLOB: length in: %d, length out: %d", len(in), len(out)) - } - if rows.Next() { - dbt.Error("LONGBLOB: unexpexted row") - } - } else { - if err = rows.Err(); err != nil { - dbt.Fatalf("LONGBLOB: no data (err: %s)", err.Error()) - } else { - dbt.Fatal("LONGBLOB: no data (err: )") - } - } - }) -} - -func TestLoadData(t *testing.T) { - runTests(t, dsn, func(dbt *DBTest) { - verifyLoadDataResult := func() { - rows, err := dbt.db.Query("SELECT * FROM test") - if err != nil { - dbt.Fatal(err.Error()) - } - - i := 0 - values := [4]string{ - "a string", - "a string containing a \t", - "a string containing a \n", - "a string containing both \t\n", - } - - var id int - var value string - - for rows.Next() { - i++ - err = rows.Scan(&id, &value) - if err != nil { - dbt.Fatal(err.Error()) - } - if i != id { - dbt.Fatalf("%d != %d", i, id) - } - if values[i-1] != value { - dbt.Fatalf("%q != %q", values[i-1], value) - } - } - err = rows.Err() - if err != nil { - dbt.Fatal(err.Error()) - } - - if i != 4 { - dbt.Fatalf("Rows count mismatch. Got %d, want 4", i) - } - } - file, err := ioutil.TempFile("", "gotest") - defer os.Remove(file.Name()) - if err != nil { - dbt.Fatal(err) - } - file.WriteString("1\ta string\n2\ta string containing a \\t\n3\ta string containing a \\n\n4\ta string containing both \\t\\n\n") - file.Close() - - dbt.db.Exec("DROP TABLE IF EXISTS test") - dbt.mustExec("CREATE TABLE test (id INT NOT NULL PRIMARY KEY, value TEXT NOT NULL) CHARACTER SET utf8") - - // Local File - RegisterLocalFile(file.Name()) - dbt.mustExec(fmt.Sprintf("LOAD DATA LOCAL INFILE %q INTO TABLE test", file.Name())) - verifyLoadDataResult() - // negative test - _, err = dbt.db.Exec("LOAD DATA LOCAL INFILE 'doesnotexist' INTO TABLE test") - if err == nil { - dbt.Fatal("Load non-existent file didn't fail") - } else if err.Error() != "Local File 'doesnotexist' is not registered. Use the DSN parameter 'allowAllFiles=true' to allow all files" { - dbt.Fatal(err.Error()) - } - - // Empty table - dbt.mustExec("TRUNCATE TABLE test") - - // Reader - RegisterReaderHandler("test", func() io.Reader { - file, err = os.Open(file.Name()) - if err != nil { - dbt.Fatal(err) - } - return file - }) - dbt.mustExec("LOAD DATA LOCAL INFILE 'Reader::test' INTO TABLE test") - verifyLoadDataResult() - // negative test - _, err = dbt.db.Exec("LOAD DATA LOCAL INFILE 'Reader::doesnotexist' INTO TABLE test") - if err == nil { - dbt.Fatal("Load non-existent Reader didn't fail") - } else if err.Error() != "Reader 'doesnotexist' is not registered" { - dbt.Fatal(err.Error()) - } - }) -} - -func TestFoundRows(t *testing.T) { - runTests(t, dsn, func(dbt *DBTest) { - dbt.mustExec("CREATE TABLE test (id INT NOT NULL ,data INT NOT NULL)") - dbt.mustExec("INSERT INTO test (id, data) VALUES (0, 0),(0, 0),(1, 0),(1, 0),(1, 1)") - - res := dbt.mustExec("UPDATE test SET data = 1 WHERE id = 0") - count, err := res.RowsAffected() - if err != nil { - dbt.Fatalf("res.RowsAffected() returned error: %s", err.Error()) - } - if count != 2 { - dbt.Fatalf("Expected 2 affected rows, got %d", count) - } - res = dbt.mustExec("UPDATE test SET data = 1 WHERE id = 1") - count, err = res.RowsAffected() - if err != nil { - dbt.Fatalf("res.RowsAffected() returned error: %s", err.Error()) - } - if count != 2 { - dbt.Fatalf("Expected 2 affected rows, got %d", count) - } - }) - runTests(t, dsn+"&clientFoundRows=true", func(dbt *DBTest) { - dbt.mustExec("CREATE TABLE test (id INT NOT NULL ,data INT NOT NULL)") - dbt.mustExec("INSERT INTO test (id, data) VALUES (0, 0),(0, 0),(1, 0),(1, 0),(1, 1)") - - res := dbt.mustExec("UPDATE test SET data = 1 WHERE id = 0") - count, err := res.RowsAffected() - if err != nil { - dbt.Fatalf("res.RowsAffected() returned error: %s", err.Error()) - } - if count != 2 { - dbt.Fatalf("Expected 2 matched rows, got %d", count) - } - res = dbt.mustExec("UPDATE test SET data = 1 WHERE id = 1") - count, err = res.RowsAffected() - if err != nil { - dbt.Fatalf("res.RowsAffected() returned error: %s", err.Error()) - } - if count != 3 { - dbt.Fatalf("Expected 3 matched rows, got %d", count) - } - }) -} - -func TestStrict(t *testing.T) { - // ALLOW_INVALID_DATES to get rid of stricter modes - we want to test for warnings, not errors - relaxedDsn := dsn + "&sql_mode=ALLOW_INVALID_DATES" - // make sure the MySQL version is recent enough with a separate connection - // before running the test - conn, err := MySQLDriver{}.Open(relaxedDsn) - if conn != nil { - conn.Close() - } - if me, ok := err.(*MySQLError); ok && me.Number == 1231 { - // Error 1231: Variable 'sql_mode' can't be set to the value of 'ALLOW_INVALID_DATES' - // => skip test, MySQL server version is too old - return - } - runTests(t, relaxedDsn, func(dbt *DBTest) { - dbt.mustExec("CREATE TABLE test (a TINYINT NOT NULL, b CHAR(4))") - - var queries = [...]struct { - in string - codes []string - }{ - {"DROP TABLE IF EXISTS no_such_table", []string{"1051"}}, - {"INSERT INTO test VALUES(10,'mysql'),(NULL,'test'),(300,'Open Source')", []string{"1265", "1048", "1264", "1265"}}, - } - var err error - - var checkWarnings = func(err error, mode string, idx int) { - if err == nil { - dbt.Errorf("Expected STRICT error on query [%s] %s", mode, queries[idx].in) - } - - if warnings, ok := err.(MySQLWarnings); ok { - var codes = make([]string, len(warnings)) - for i := range warnings { - codes[i] = warnings[i].Code - } - if len(codes) != len(queries[idx].codes) { - dbt.Errorf("Unexpected STRICT error count on query [%s] %s: Wanted %v, Got %v", mode, queries[idx].in, queries[idx].codes, codes) - } - - for i := range warnings { - if codes[i] != queries[idx].codes[i] { - dbt.Errorf("Unexpected STRICT error codes on query [%s] %s: Wanted %v, Got %v", mode, queries[idx].in, queries[idx].codes, codes) - return - } - } - - } else { - dbt.Errorf("Unexpected error on query [%s] %s: %s", mode, queries[idx].in, err.Error()) - } - } - - // text protocol - for i := range queries { - _, err = dbt.db.Exec(queries[i].in) - checkWarnings(err, "text", i) - } - - var stmt *sql.Stmt - - // binary protocol - for i := range queries { - stmt, err = dbt.db.Prepare(queries[i].in) - if err != nil { - dbt.Errorf("Error on preparing query %s: %s", queries[i].in, err.Error()) - } - - _, err = stmt.Exec() - checkWarnings(err, "binary", i) - - err = stmt.Close() - if err != nil { - dbt.Errorf("Error on closing stmt for query %s: %s", queries[i].in, err.Error()) - } - } - }) -} - -func TestTLS(t *testing.T) { - tlsTest := func(dbt *DBTest) { - if err := dbt.db.Ping(); err != nil { - if err == ErrNoTLS { - dbt.Skip("Server does not support TLS") - } else { - dbt.Fatalf("Error on Ping: %s", err.Error()) - } - } - - rows := dbt.mustQuery("SHOW STATUS LIKE 'Ssl_cipher'") - - var variable, value *sql.RawBytes - for rows.Next() { - if err := rows.Scan(&variable, &value); err != nil { - dbt.Fatal(err.Error()) - } - - if value == nil { - dbt.Fatal("No Cipher") - } - } - } - - runTests(t, dsn+"&tls=skip-verify", tlsTest) - - // Verify that registering / using a custom cfg works - RegisterTLSConfig("custom-skip-verify", &tls.Config{ - InsecureSkipVerify: true, - }) - runTests(t, dsn+"&tls=custom-skip-verify", tlsTest) -} - -func TestReuseClosedConnection(t *testing.T) { - // this test does not use sql.database, it uses the driver directly - if !available { - t.Skipf("MySQL-Server not running on %s", netAddr) - } - - md := &MySQLDriver{} - conn, err := md.Open(dsn) - if err != nil { - t.Fatalf("Error connecting: %s", err.Error()) - } - stmt, err := conn.Prepare("DO 1") - if err != nil { - t.Fatalf("Error preparing statement: %s", err.Error()) - } - _, err = stmt.Exec(nil) - if err != nil { - t.Fatalf("Error executing statement: %s", err.Error()) - } - err = conn.Close() - if err != nil { - t.Fatalf("Error closing connection: %s", err.Error()) - } - - defer func() { - if err := recover(); err != nil { - t.Errorf("Panic after reusing a closed connection: %v", err) - } - }() - _, err = stmt.Exec(nil) - if err != nil && err != driver.ErrBadConn { - t.Errorf("Unexpected error '%s', expected '%s'", - err.Error(), driver.ErrBadConn.Error()) - } -} - -func TestCharset(t *testing.T) { - if !available { - t.Skipf("MySQL-Server not running on %s", netAddr) - } - - mustSetCharset := func(charsetParam, expected string) { - runTests(t, dsn+"&"+charsetParam, func(dbt *DBTest) { - rows := dbt.mustQuery("SELECT @@character_set_connection") - defer rows.Close() - - if !rows.Next() { - dbt.Fatalf("Error getting connection charset: %s", rows.Err()) - } - - var got string - rows.Scan(&got) - - if got != expected { - dbt.Fatalf("Expected connection charset %s but got %s", expected, got) - } - }) - } - - // non utf8 test - mustSetCharset("charset=ascii", "ascii") - - // when the first charset is invalid, use the second - mustSetCharset("charset=none,utf8", "utf8") - - // when the first charset is valid, use it - mustSetCharset("charset=ascii,utf8", "ascii") - mustSetCharset("charset=utf8,ascii", "utf8") -} - -func TestFailingCharset(t *testing.T) { - runTests(t, dsn+"&charset=none", func(dbt *DBTest) { - // run query to really establish connection... - _, err := dbt.db.Exec("SELECT 1") - if err == nil { - dbt.db.Close() - t.Fatalf("Connection must not succeed without a valid charset") - } - }) -} - -func TestCollation(t *testing.T) { - if !available { - t.Skipf("MySQL-Server not running on %s", netAddr) - } - - defaultCollation := "utf8_general_ci" - testCollations := []string{ - "", // do not set - defaultCollation, // driver default - "latin1_general_ci", - "binary", - "utf8_unicode_ci", - "cp1257_bin", - } - - for _, collation := range testCollations { - var expected, tdsn string - if collation != "" { - tdsn = dsn + "&collation=" + collation - expected = collation - } else { - tdsn = dsn - expected = defaultCollation - } - - runTests(t, tdsn, func(dbt *DBTest) { - var got string - if err := dbt.db.QueryRow("SELECT @@collation_connection").Scan(&got); err != nil { - dbt.Fatal(err) - } - - if got != expected { - dbt.Fatalf("Expected connection collation %s but got %s", expected, got) - } - }) - } -} - -func TestColumnsWithAlias(t *testing.T) { - runTests(t, dsn+"&columnsWithAlias=true", func(dbt *DBTest) { - rows := dbt.mustQuery("SELECT 1 AS A") - defer rows.Close() - cols, _ := rows.Columns() - if len(cols) != 1 { - t.Fatalf("expected 1 column, got %d", len(cols)) - } - if cols[0] != "A" { - t.Fatalf("expected column name \"A\", got \"%s\"", cols[0]) - } - rows.Close() - - rows = dbt.mustQuery("SELECT * FROM (SELECT 1 AS one) AS A") - cols, _ = rows.Columns() - if len(cols) != 1 { - t.Fatalf("expected 1 column, got %d", len(cols)) - } - if cols[0] != "A.one" { - t.Fatalf("expected column name \"A.one\", got \"%s\"", cols[0]) - } - }) -} - -func TestRawBytesResultExceedsBuffer(t *testing.T) { - runTests(t, dsn, func(dbt *DBTest) { - // defaultBufSize from buffer.go - expected := strings.Repeat("abc", defaultBufSize) - - rows := dbt.mustQuery("SELECT '" + expected + "'") - defer rows.Close() - if !rows.Next() { - dbt.Error("expected result, got none") - } - var result sql.RawBytes - rows.Scan(&result) - if expected != string(result) { - dbt.Error("result did not match expected value") - } - }) -} - -func TestTimezoneConversion(t *testing.T) { - zones := []string{"UTC", "US/Central", "US/Pacific", "Local"} - - // Regression test for timezone handling - tzTest := func(dbt *DBTest) { - - // Create table - dbt.mustExec("CREATE TABLE test (ts TIMESTAMP)") - - // Insert local time into database (should be converted) - usCentral, _ := time.LoadLocation("US/Central") - reftime := time.Date(2014, 05, 30, 18, 03, 17, 0, time.UTC).In(usCentral) - dbt.mustExec("INSERT INTO test VALUE (?)", reftime) - - // Retrieve time from DB - rows := dbt.mustQuery("SELECT ts FROM test") - if !rows.Next() { - dbt.Fatal("Didn't get any rows out") - } - - var dbTime time.Time - err := rows.Scan(&dbTime) - if err != nil { - dbt.Fatal("Err", err) - } - - // Check that dates match - if reftime.Unix() != dbTime.Unix() { - dbt.Errorf("Times don't match.\n") - dbt.Errorf(" Now(%v)=%v\n", usCentral, reftime) - dbt.Errorf(" Now(UTC)=%v\n", dbTime) - } - } - - for _, tz := range zones { - runTests(t, dsn+"&parseTime=true&loc="+url.QueryEscape(tz), tzTest) - } -} - -// Special cases - -func TestRowsClose(t *testing.T) { - runTests(t, dsn, func(dbt *DBTest) { - rows, err := dbt.db.Query("SELECT 1") - if err != nil { - dbt.Fatal(err) - } - - err = rows.Close() - if err != nil { - dbt.Fatal(err) - } - - if rows.Next() { - dbt.Fatal("Unexpected row after rows.Close()") - } - - err = rows.Err() - if err != nil { - dbt.Fatal(err) - } - }) -} - -// dangling statements -// http://code.google.com/p/go/issues/detail?id=3865 -func TestCloseStmtBeforeRows(t *testing.T) { - runTests(t, dsn, func(dbt *DBTest) { - stmt, err := dbt.db.Prepare("SELECT 1") - if err != nil { - dbt.Fatal(err) - } - - rows, err := stmt.Query() - if err != nil { - stmt.Close() - dbt.Fatal(err) - } - defer rows.Close() - - err = stmt.Close() - if err != nil { - dbt.Fatal(err) - } - - if !rows.Next() { - dbt.Fatal("Getting row failed") - } else { - err = rows.Err() - if err != nil { - dbt.Fatal(err) - } - - var out bool - err = rows.Scan(&out) - if err != nil { - dbt.Fatalf("Error on rows.Scan(): %s", err.Error()) - } - if out != true { - dbt.Errorf("true != %t", out) - } - } - }) -} - -// It is valid to have multiple Rows for the same Stmt -// http://code.google.com/p/go/issues/detail?id=3734 -func TestStmtMultiRows(t *testing.T) { - runTests(t, dsn, func(dbt *DBTest) { - stmt, err := dbt.db.Prepare("SELECT 1 UNION SELECT 0") - if err != nil { - dbt.Fatal(err) - } - - rows1, err := stmt.Query() - if err != nil { - stmt.Close() - dbt.Fatal(err) - } - defer rows1.Close() - - rows2, err := stmt.Query() - if err != nil { - stmt.Close() - dbt.Fatal(err) - } - defer rows2.Close() - - var out bool - - // 1 - if !rows1.Next() { - dbt.Fatal("1st rows1.Next failed") - } else { - err = rows1.Err() - if err != nil { - dbt.Fatal(err) - } - - err = rows1.Scan(&out) - if err != nil { - dbt.Fatalf("Error on rows.Scan(): %s", err.Error()) - } - if out != true { - dbt.Errorf("true != %t", out) - } - } - - if !rows2.Next() { - dbt.Fatal("1st rows2.Next failed") - } else { - err = rows2.Err() - if err != nil { - dbt.Fatal(err) - } - - err = rows2.Scan(&out) - if err != nil { - dbt.Fatalf("Error on rows.Scan(): %s", err.Error()) - } - if out != true { - dbt.Errorf("true != %t", out) - } - } - - // 2 - if !rows1.Next() { - dbt.Fatal("2nd rows1.Next failed") - } else { - err = rows1.Err() - if err != nil { - dbt.Fatal(err) - } - - err = rows1.Scan(&out) - if err != nil { - dbt.Fatalf("Error on rows.Scan(): %s", err.Error()) - } - if out != false { - dbt.Errorf("false != %t", out) - } - - if rows1.Next() { - dbt.Fatal("Unexpected row on rows1") - } - err = rows1.Close() - if err != nil { - dbt.Fatal(err) - } - } - - if !rows2.Next() { - dbt.Fatal("2nd rows2.Next failed") - } else { - err = rows2.Err() - if err != nil { - dbt.Fatal(err) - } - - err = rows2.Scan(&out) - if err != nil { - dbt.Fatalf("Error on rows.Scan(): %s", err.Error()) - } - if out != false { - dbt.Errorf("false != %t", out) - } - - if rows2.Next() { - dbt.Fatal("Unexpected row on rows2") - } - err = rows2.Close() - if err != nil { - dbt.Fatal(err) - } - } - }) -} - -// Regression test for -// * more than 32 NULL parameters (issue 209) -// * more parameters than fit into the buffer (issue 201) -func TestPreparedManyCols(t *testing.T) { - const numParams = defaultBufSize - runTests(t, dsn, func(dbt *DBTest) { - query := "SELECT ?" + strings.Repeat(",?", numParams-1) - stmt, err := dbt.db.Prepare(query) - if err != nil { - dbt.Fatal(err) - } - defer stmt.Close() - // create more parameters than fit into the buffer - // which will take nil-values - params := make([]interface{}, numParams) - rows, err := stmt.Query(params...) - if err != nil { - stmt.Close() - dbt.Fatal(err) - } - defer rows.Close() - }) -} - -func TestConcurrent(t *testing.T) { - if enabled, _ := readBool(os.Getenv("MYSQL_TEST_CONCURRENT")); !enabled { - t.Skip("MYSQL_TEST_CONCURRENT env var not set") - } - - runTests(t, dsn, func(dbt *DBTest) { - var max int - err := dbt.db.QueryRow("SELECT @@max_connections").Scan(&max) - if err != nil { - dbt.Fatalf("%s", err.Error()) - } - dbt.Logf("Testing up to %d concurrent connections \r\n", max) - - var remaining, succeeded int32 = int32(max), 0 - - var wg sync.WaitGroup - wg.Add(max) - - var fatalError string - var once sync.Once - fatalf := func(s string, vals ...interface{}) { - once.Do(func() { - fatalError = fmt.Sprintf(s, vals...) - }) - } - - for i := 0; i < max; i++ { - go func(id int) { - defer wg.Done() - - tx, err := dbt.db.Begin() - atomic.AddInt32(&remaining, -1) - - if err != nil { - if err.Error() != "Error 1040: Too many connections" { - fatalf("Error on Conn %d: %s", id, err.Error()) - } - return - } - - // keep the connection busy until all connections are open - for remaining > 0 { - if _, err = tx.Exec("DO 1"); err != nil { - fatalf("Error on Conn %d: %s", id, err.Error()) - return - } - } - - if err = tx.Commit(); err != nil { - fatalf("Error on Conn %d: %s", id, err.Error()) - return - } - - // everything went fine with this connection - atomic.AddInt32(&succeeded, 1) - }(i) - } - - // wait until all conections are open - wg.Wait() - - if fatalError != "" { - dbt.Fatal(fatalError) - } - - dbt.Logf("Reached %d concurrent connections\r\n", succeeded) - }) -} - -// Tests custom dial functions -func TestCustomDial(t *testing.T) { - if !available { - t.Skipf("MySQL-Server not running on %s", netAddr) - } - - // our custom dial function which justs wraps net.Dial here - RegisterDial("mydial", func(addr string) (net.Conn, error) { - return net.Dial(prot, addr) - }) - - db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@mydial(%s)/%s?timeout=30s&strict=true", user, pass, addr, dbname)) - if err != nil { - t.Fatalf("Error connecting: %s", err.Error()) - } - defer db.Close() - - if _, err = db.Exec("DO 1"); err != nil { - t.Fatalf("Connection failed: %s", err.Error()) - } -} - -func TestSqlInjection(t *testing.T) { - createTest := func(arg string) func(dbt *DBTest) { - return func(dbt *DBTest) { - dbt.mustExec("CREATE TABLE test (v INTEGER)") - dbt.mustExec("INSERT INTO test VALUES (?)", 1) - - var v int - // NULL can't be equal to anything, the idea here is to inject query so it returns row - // This test verifies that escapeQuotes and escapeBackslash are working properly - err := dbt.db.QueryRow("SELECT v FROM test WHERE NULL = ?", arg).Scan(&v) - if err == sql.ErrNoRows { - return // success, sql injection failed - } else if err == nil { - dbt.Errorf("Sql injection successful with arg: %s", arg) - } else { - dbt.Errorf("Error running query with arg: %s; err: %s", arg, err.Error()) - } - } - } - - dsns := []string{ - dsn, - dsn + "&sql_mode=NO_BACKSLASH_ESCAPES", - } - for _, testdsn := range dsns { - runTests(t, testdsn, createTest("1 OR 1=1")) - runTests(t, testdsn, createTest("' OR '1'='1")) - } -} - -// Test if inserted data is correctly retrieved after being escaped -func TestInsertRetrieveEscapedData(t *testing.T) { - testData := func(dbt *DBTest) { - dbt.mustExec("CREATE TABLE test (v VARCHAR(255))") - - // All sequences that are escaped by escapeQuotes and escapeBackslash - v := "foo \x00\n\r\x1a\"'\\" - dbt.mustExec("INSERT INTO test VALUES (?)", v) - - var out string - err := dbt.db.QueryRow("SELECT v FROM test").Scan(&out) - if err != nil { - dbt.Fatalf("%s", err.Error()) - } - - if out != v { - dbt.Errorf("%q != %q", out, v) - } - } - - dsns := []string{ - dsn, - dsn + "&sql_mode=NO_BACKSLASH_ESCAPES", - } - for _, testdsn := range dsns { - runTests(t, testdsn, testData) - } -} diff --git a/Godeps/_workspace/src/github.com/go-sql-driver/mysql/errors_test.go b/Godeps/_workspace/src/github.com/go-sql-driver/mysql/errors_test.go deleted file mode 100644 index 96f9126d6..000000000 --- a/Godeps/_workspace/src/github.com/go-sql-driver/mysql/errors_test.go +++ /dev/null @@ -1,42 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package -// -// Copyright 2013 The Go-MySQL-Driver Authors. All rights reserved. -// -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this file, -// You can obtain one at http://mozilla.org/MPL/2.0/. - -package mysql - -import ( - "bytes" - "log" - "testing" -) - -func TestErrorsSetLogger(t *testing.T) { - previous := errLog - defer func() { - errLog = previous - }() - - // set up logger - const expected = "prefix: test\n" - buffer := bytes.NewBuffer(make([]byte, 0, 64)) - logger := log.New(buffer, "prefix: ", 0) - - // print - SetLogger(logger) - errLog.Print("test") - - // check result - if actual := buffer.String(); actual != expected { - t.Errorf("expected %q, got %q", expected, actual) - } -} - -func TestErrorsStrictIgnoreNotes(t *testing.T) { - runTests(t, dsn+"&sql_notes=false", func(dbt *DBTest) { - dbt.mustExec("DROP TABLE IF EXISTS does_not_exist") - }) -} diff --git a/Godeps/_workspace/src/github.com/go-sql-driver/mysql/utils_test.go b/Godeps/_workspace/src/github.com/go-sql-driver/mysql/utils_test.go deleted file mode 100644 index 79fbdd1eb..000000000 --- a/Godeps/_workspace/src/github.com/go-sql-driver/mysql/utils_test.go +++ /dev/null @@ -1,346 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package -// -// Copyright 2013 The Go-MySQL-Driver Authors. All rights reserved. -// -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this file, -// You can obtain one at http://mozilla.org/MPL/2.0/. - -package mysql - -import ( - "bytes" - "crypto/tls" - "encoding/binary" - "fmt" - "testing" - "time" -) - -var testDSNs = []struct { - in string - out string - loc *time.Location -}{ - {"username:password@protocol(address)/dbname?param=value", "&{user:username passwd:password net:protocol addr:address dbname:dbname params:map[param:value] loc:%p tls: timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false allowCleartextPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.UTC}, - {"username:password@protocol(address)/dbname?param=value&columnsWithAlias=true", "&{user:username passwd:password net:protocol addr:address dbname:dbname params:map[param:value] loc:%p tls: timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false allowCleartextPasswords:false clientFoundRows:false columnsWithAlias:true interpolateParams:false}", time.UTC}, - {"user@unix(/path/to/socket)/dbname?charset=utf8", "&{user:user passwd: net:unix addr:/path/to/socket dbname:dbname params:map[charset:utf8] loc:%p tls: timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false allowCleartextPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.UTC}, - {"user:password@tcp(localhost:5555)/dbname?charset=utf8&tls=true", "&{user:user passwd:password net:tcp addr:localhost:5555 dbname:dbname params:map[charset:utf8] loc:%p tls: timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false allowCleartextPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.UTC}, - {"user:password@tcp(localhost:5555)/dbname?charset=utf8mb4,utf8&tls=skip-verify", "&{user:user passwd:password net:tcp addr:localhost:5555 dbname:dbname params:map[charset:utf8mb4,utf8] loc:%p tls: timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false allowCleartextPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.UTC}, - {"user:password@/dbname?loc=UTC&timeout=30s&allowAllFiles=1&clientFoundRows=true&allowOldPasswords=TRUE&collation=utf8mb4_unicode_ci", "&{user:user passwd:password net:tcp addr:127.0.0.1:3306 dbname:dbname params:map[] loc:%p tls: timeout:30000000000 collation:224 allowAllFiles:true allowOldPasswords:true allowCleartextPasswords:false clientFoundRows:true columnsWithAlias:false interpolateParams:false}", time.UTC}, - {"user:p@ss(word)@tcp([de:ad:be:ef::ca:fe]:80)/dbname?loc=Local", "&{user:user passwd:p@ss(word) net:tcp addr:[de:ad:be:ef::ca:fe]:80 dbname:dbname params:map[] loc:%p tls: timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false allowCleartextPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.Local}, - {"/dbname", "&{user: passwd: net:tcp addr:127.0.0.1:3306 dbname:dbname params:map[] loc:%p tls: timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false allowCleartextPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.UTC}, - {"@/", "&{user: passwd: net:tcp addr:127.0.0.1:3306 dbname: params:map[] loc:%p tls: timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false allowCleartextPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.UTC}, - {"/", "&{user: passwd: net:tcp addr:127.0.0.1:3306 dbname: params:map[] loc:%p tls: timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false allowCleartextPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.UTC}, - {"", "&{user: passwd: net:tcp addr:127.0.0.1:3306 dbname: params:map[] loc:%p tls: timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false allowCleartextPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.UTC}, - {"user:p@/ssword@/", "&{user:user passwd:p@/ssword net:tcp addr:127.0.0.1:3306 dbname: params:map[] loc:%p tls: timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false allowCleartextPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.UTC}, - {"unix/?arg=%2Fsome%2Fpath.ext", "&{user: passwd: net:unix addr:/tmp/mysql.sock dbname: params:map[arg:/some/path.ext] loc:%p tls: timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false allowCleartextPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.UTC}, -} - -func TestDSNParser(t *testing.T) { - var cfg *config - var err error - var res string - - for i, tst := range testDSNs { - cfg, err = parseDSN(tst.in) - if err != nil { - t.Error(err.Error()) - } - - // pointer not static - cfg.tls = nil - - res = fmt.Sprintf("%+v", cfg) - if res != fmt.Sprintf(tst.out, tst.loc) { - t.Errorf("%d. parseDSN(%q) => %q, want %q", i, tst.in, res, fmt.Sprintf(tst.out, tst.loc)) - } - } -} - -func TestDSNParserInvalid(t *testing.T) { - var invalidDSNs = []string{ - "@net(addr/", // no closing brace - "@tcp(/", // no closing brace - "tcp(/", // no closing brace - "(/", // no closing brace - "net(addr)//", // unescaped - "user:pass@tcp(1.2.3.4:3306)", // no trailing slash - //"/dbname?arg=/some/unescaped/path", - } - - for i, tst := range invalidDSNs { - if _, err := parseDSN(tst); err == nil { - t.Errorf("invalid DSN #%d. (%s) didn't error!", i, tst) - } - } -} - -func TestDSNWithCustomTLS(t *testing.T) { - baseDSN := "user:password@tcp(localhost:5555)/dbname?tls=" - tlsCfg := tls.Config{} - - RegisterTLSConfig("utils_test", &tlsCfg) - - // Custom TLS is missing - tst := baseDSN + "invalid_tls" - cfg, err := parseDSN(tst) - if err == nil { - t.Errorf("Invalid custom TLS in DSN (%s) but did not error. Got config: %#v", tst, cfg) - } - - tst = baseDSN + "utils_test" - - // Custom TLS with a server name - name := "foohost" - tlsCfg.ServerName = name - cfg, err = parseDSN(tst) - - if err != nil { - t.Error(err.Error()) - } else if cfg.tls.ServerName != name { - t.Errorf("Did not get the correct TLS ServerName (%s) parsing DSN (%s).", name, tst) - } - - // Custom TLS without a server name - name = "localhost" - tlsCfg.ServerName = "" - cfg, err = parseDSN(tst) - - if err != nil { - t.Error(err.Error()) - } else if cfg.tls.ServerName != name { - t.Errorf("Did not get the correct ServerName (%s) parsing DSN (%s).", name, tst) - } - - DeregisterTLSConfig("utils_test") -} - -func TestDSNUnsafeCollation(t *testing.T) { - _, err := parseDSN("/dbname?collation=gbk_chinese_ci&interpolateParams=true") - if err != errInvalidDSNUnsafeCollation { - t.Error("Expected %v, Got %v", errInvalidDSNUnsafeCollation, err) - } - - _, err = parseDSN("/dbname?collation=gbk_chinese_ci&interpolateParams=false") - if err != nil { - t.Error("Expected %v, Got %v", nil, err) - } - - _, err = parseDSN("/dbname?collation=gbk_chinese_ci") - if err != nil { - t.Error("Expected %v, Got %v", nil, err) - } - - _, err = parseDSN("/dbname?collation=ascii_bin&interpolateParams=true") - if err != nil { - t.Error("Expected %v, Got %v", nil, err) - } - - _, err = parseDSN("/dbname?collation=latin1_german1_ci&interpolateParams=true") - if err != nil { - t.Error("Expected %v, Got %v", nil, err) - } - - _, err = parseDSN("/dbname?collation=utf8_general_ci&interpolateParams=true") - if err != nil { - t.Error("Expected %v, Got %v", nil, err) - } - - _, err = parseDSN("/dbname?collation=utf8mb4_general_ci&interpolateParams=true") - if err != nil { - t.Error("Expected %v, Got %v", nil, err) - } -} - -func BenchmarkParseDSN(b *testing.B) { - b.ReportAllocs() - - for i := 0; i < b.N; i++ { - for _, tst := range testDSNs { - if _, err := parseDSN(tst.in); err != nil { - b.Error(err.Error()) - } - } - } -} - -func TestScanNullTime(t *testing.T) { - var scanTests = []struct { - in interface{} - error bool - valid bool - time time.Time - }{ - {tDate, false, true, tDate}, - {sDate, false, true, tDate}, - {[]byte(sDate), false, true, tDate}, - {tDateTime, false, true, tDateTime}, - {sDateTime, false, true, tDateTime}, - {[]byte(sDateTime), false, true, tDateTime}, - {tDate0, false, true, tDate0}, - {sDate0, false, true, tDate0}, - {[]byte(sDate0), false, true, tDate0}, - {sDateTime0, false, true, tDate0}, - {[]byte(sDateTime0), false, true, tDate0}, - {"", true, false, tDate0}, - {"1234", true, false, tDate0}, - {0, true, false, tDate0}, - } - - var nt = NullTime{} - var err error - - for _, tst := range scanTests { - err = nt.Scan(tst.in) - if (err != nil) != tst.error { - t.Errorf("%v: expected error status %t, got %t", tst.in, tst.error, (err != nil)) - } - if nt.Valid != tst.valid { - t.Errorf("%v: expected valid status %t, got %t", tst.in, tst.valid, nt.Valid) - } - if nt.Time != tst.time { - t.Errorf("%v: expected time %v, got %v", tst.in, tst.time, nt.Time) - } - } -} - -func TestLengthEncodedInteger(t *testing.T) { - var integerTests = []struct { - num uint64 - encoded []byte - }{ - {0x0000000000000000, []byte{0x00}}, - {0x0000000000000012, []byte{0x12}}, - {0x00000000000000fa, []byte{0xfa}}, - {0x0000000000000100, []byte{0xfc, 0x00, 0x01}}, - {0x0000000000001234, []byte{0xfc, 0x34, 0x12}}, - {0x000000000000ffff, []byte{0xfc, 0xff, 0xff}}, - {0x0000000000010000, []byte{0xfd, 0x00, 0x00, 0x01}}, - {0x0000000000123456, []byte{0xfd, 0x56, 0x34, 0x12}}, - {0x0000000000ffffff, []byte{0xfd, 0xff, 0xff, 0xff}}, - {0x0000000001000000, []byte{0xfe, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00}}, - {0x123456789abcdef0, []byte{0xfe, 0xf0, 0xde, 0xbc, 0x9a, 0x78, 0x56, 0x34, 0x12}}, - {0xffffffffffffffff, []byte{0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}}, - } - - for _, tst := range integerTests { - num, isNull, numLen := readLengthEncodedInteger(tst.encoded) - if isNull { - t.Errorf("%x: expected %d, got NULL", tst.encoded, tst.num) - } - if num != tst.num { - t.Errorf("%x: expected %d, got %d", tst.encoded, tst.num, num) - } - if numLen != len(tst.encoded) { - t.Errorf("%x: expected size %d, got %d", tst.encoded, len(tst.encoded), numLen) - } - encoded := appendLengthEncodedInteger(nil, num) - if !bytes.Equal(encoded, tst.encoded) { - t.Errorf("%v: expected %x, got %x", num, tst.encoded, encoded) - } - } -} - -func TestOldPass(t *testing.T) { - scramble := []byte{9, 8, 7, 6, 5, 4, 3, 2} - vectors := []struct { - pass string - out string - }{ - {" pass", "47575c5a435b4251"}, - {"pass ", "47575c5a435b4251"}, - {"123\t456", "575c47505b5b5559"}, - {"C0mpl!ca ted#PASS123", "5d5d554849584a45"}, - } - for _, tuple := range vectors { - ours := scrambleOldPassword(scramble, []byte(tuple.pass)) - if tuple.out != fmt.Sprintf("%x", ours) { - t.Errorf("Failed old password %q", tuple.pass) - } - } -} - -func TestFormatBinaryDateTime(t *testing.T) { - rawDate := [11]byte{} - binary.LittleEndian.PutUint16(rawDate[:2], 1978) // years - rawDate[2] = 12 // months - rawDate[3] = 30 // days - rawDate[4] = 15 // hours - rawDate[5] = 46 // minutes - rawDate[6] = 23 // seconds - binary.LittleEndian.PutUint32(rawDate[7:], 987654) // microseconds - expect := func(expected string, inlen, outlen uint8) { - actual, _ := formatBinaryDateTime(rawDate[:inlen], outlen, false) - bytes, ok := actual.([]byte) - if !ok { - t.Errorf("formatBinaryDateTime must return []byte, was %T", actual) - } - if string(bytes) != expected { - t.Errorf( - "expected %q, got %q for length in %d, out %d", - bytes, actual, inlen, outlen, - ) - } - } - expect("0000-00-00", 0, 10) - expect("0000-00-00 00:00:00", 0, 19) - expect("1978-12-30", 4, 10) - expect("1978-12-30 15:46:23", 7, 19) - expect("1978-12-30 15:46:23.987654", 11, 26) -} - -func TestEscapeBackslash(t *testing.T) { - expect := func(expected, value string) { - actual := string(escapeBytesBackslash([]byte{}, []byte(value))) - if actual != expected { - t.Errorf( - "expected %s, got %s", - expected, actual, - ) - } - - actual = string(escapeStringBackslash([]byte{}, value)) - if actual != expected { - t.Errorf( - "expected %s, got %s", - expected, actual, - ) - } - } - - expect("foo\\0bar", "foo\x00bar") - expect("foo\\nbar", "foo\nbar") - expect("foo\\rbar", "foo\rbar") - expect("foo\\Zbar", "foo\x1abar") - expect("foo\\\"bar", "foo\"bar") - expect("foo\\\\bar", "foo\\bar") - expect("foo\\'bar", "foo'bar") -} - -func TestEscapeQuotes(t *testing.T) { - expect := func(expected, value string) { - actual := string(escapeBytesQuotes([]byte{}, []byte(value))) - if actual != expected { - t.Errorf( - "expected %s, got %s", - expected, actual, - ) - } - - actual = string(escapeStringQuotes([]byte{}, value)) - if actual != expected { - t.Errorf( - "expected %s, got %s", - expected, actual, - ) - } - } - - expect("foo\x00bar", "foo\x00bar") // not affected - expect("foo\nbar", "foo\nbar") // not affected - expect("foo\rbar", "foo\rbar") // not affected - expect("foo\x1abar", "foo\x1abar") // not affected - expect("foo''bar", "foo'bar") // affected - expect("foo\"bar", "foo\"bar") // not affected -} diff --git a/Godeps/_workspace/src/github.com/gocql/gocql/.travis.yml b/Godeps/_workspace/src/github.com/gocql/gocql/.travis.yml index 5a5602280..413ec2460 100644 --- a/Godeps/_workspace/src/github.com/gocql/gocql/.travis.yml +++ b/Godeps/_workspace/src/github.com/gocql/gocql/.travis.yml @@ -13,14 +13,14 @@ env: global: - GOMAXPROCS=2 matrix: - - CASS=1.2.19 AUTH=false - - CASS=2.0.14 AUTH=false + - CASS=2.0.16 AUTH=false - CASS=2.1.5 AUTH=false - CASS=2.1.5 AUTH=true + - CASS=2.2.0 AUTH=false go: - - 1.3 - 1.4 + - 1.5 install: - pip install --user cql PyYAML six diff --git a/Godeps/_workspace/src/github.com/gocql/gocql/AUTHORS b/Godeps/_workspace/src/github.com/gocql/gocql/AUTHORS index a7e448a1f..8cfe3e0c5 100644 --- a/Godeps/_workspace/src/github.com/gocql/gocql/AUTHORS +++ b/Godeps/_workspace/src/github.com/gocql/gocql/AUTHORS @@ -53,3 +53,4 @@ Matt Heath Jamie Cuthill Adrian Casajus John Weldon +Adrien Bustany diff --git a/Godeps/_workspace/src/github.com/gocql/gocql/README.md b/Godeps/_workspace/src/github.com/gocql/gocql/README.md index a7e17371c..db8eeb044 100644 --- a/Godeps/_workspace/src/github.com/gocql/gocql/README.md +++ b/Godeps/_workspace/src/github.com/gocql/gocql/README.md @@ -17,10 +17,10 @@ Supported Versions The following matrix shows the versions of Go and Cassandra that are tested with the integration test suite as part of the CI build: -Go/Cassandra | 1.2.19 | 2.0.14 | 2.1.5 +Go/Cassandra | 1.2.x | 2.0.x | 2.1.x -------------| -------| ------| --------- -1.3 | yes | yes | yes 1.4 | yes | yes | yes +1.5 | yes | yes | yes Sunsetting Model @@ -58,7 +58,7 @@ Features * Optional frame compression (using snappy) * Automatic query preparation * Support for query tracing -* Experimental support for [binary protocol version 3](https://github.com/apache/cassandra/blob/trunk/doc/native_protocol_v3.spec) +* Support for Cassandra 2.1+ [binary protocol version 3](https://github.com/apache/cassandra/blob/trunk/doc/native_protocol_v3.spec) * Support for up to 32768 streams * Support for tuple types * Support for client side timestamps by default @@ -96,7 +96,7 @@ Example of incorrect usage: } ``` This will result in an err being returned from the session.Query line as the user is trying to execute a "use" -statement. +statement. Example ------- diff --git a/Godeps/_workspace/src/github.com/gocql/gocql/cass1batch_test.go b/Godeps/_workspace/src/github.com/gocql/gocql/cass1batch_test.go deleted file mode 100644 index 35750a41d..000000000 --- a/Godeps/_workspace/src/github.com/gocql/gocql/cass1batch_test.go +++ /dev/null @@ -1,60 +0,0 @@ -// +build all integration - -package gocql - -import ( - "strings" - "testing" -) - -func TestProto1BatchInsert(t *testing.T) { - session := createSession(t) - if err := session.Query("CREATE TABLE large (id int primary key)").Exec(); err != nil { - t.Fatal("create table:", err) - } - defer session.Close() - - begin := "BEGIN BATCH" - end := "APPLY BATCH" - query := "INSERT INTO large (id) VALUES (?)" - fullQuery := strings.Join([]string{begin, query, end}, "\n") - args := []interface{}{5} - if err := session.Query(fullQuery, args...).Consistency(Quorum).Exec(); err != nil { - t.Fatal(err) - } - -} - -func TestShouldPrepareFunction(t *testing.T) { - var shouldPrepareTests = []struct { - Stmt string - Result bool - }{ - {` - BEGIN BATCH - INSERT INTO users (userID, password) - VALUES ('smith', 'secret') - APPLY BATCH - ; - `, true}, - {`INSERT INTO users (userID, password, name) VALUES ('user2', 'ch@ngem3b', 'second user')`, true}, - {`BEGIN COUNTER BATCH UPDATE stats SET views = views + 1 WHERE pageid = 1 APPLY BATCH`, true}, - {`delete name from users where userID = 'smith';`, true}, - {` UPDATE users SET password = 'secret' WHERE userID = 'smith' `, true}, - {`CREATE TABLE users ( - user_name varchar PRIMARY KEY, - password varchar, - gender varchar, - session_token varchar, - state varchar, - birth_year bigint - );`, false}, - } - - for _, test := range shouldPrepareTests { - q := &Query{stmt: test.Stmt} - if got := q.shouldPrepare(); got != test.Result { - t.Fatalf("%q: got %v, expected %v\n", test.Stmt, got, test.Result) - } - } -} diff --git a/Godeps/_workspace/src/github.com/gocql/gocql/cassandra_test.go b/Godeps/_workspace/src/github.com/gocql/gocql/cassandra_test.go deleted file mode 100644 index 31cbc1136..000000000 --- a/Godeps/_workspace/src/github.com/gocql/gocql/cassandra_test.go +++ /dev/null @@ -1,2060 +0,0 @@ -// +build all integration - -package gocql - -import ( - "bytes" - "flag" - "fmt" - "log" - "math" - "math/big" - "net" - "reflect" - "strconv" - "strings" - "sync" - "testing" - "time" - "unicode" - - "gopkg.in/inf.v0" -) - -var ( - flagCluster = flag.String("cluster", "127.0.0.1", "a comma-separated list of host:port tuples") - flagProto = flag.Int("proto", 2, "protcol version") - flagCQL = flag.String("cql", "3.0.0", "CQL version") - flagRF = flag.Int("rf", 1, "replication factor for test keyspace") - clusterSize = flag.Int("clusterSize", 1, "the expected size of the cluster") - flagRetry = flag.Int("retries", 5, "number of times to retry queries") - flagAutoWait = flag.Duration("autowait", 1000*time.Millisecond, "time to wait for autodiscovery to fill the hosts poll") - flagRunSslTest = flag.Bool("runssl", false, "Set to true to run ssl test") - flagRunAuthTest = flag.Bool("runauth", false, "Set to true to run authentication test") - flagCompressTest = flag.String("compressor", "", "compressor to use") - clusterHosts []string -) - -func init() { - flag.Parse() - clusterHosts = strings.Split(*flagCluster, ",") - log.SetFlags(log.Lshortfile | log.LstdFlags) -} - -func addSslOptions(cluster *ClusterConfig) *ClusterConfig { - if *flagRunSslTest { - cluster.SslOpts = &SslOptions{ - CertPath: "testdata/pki/gocql.crt", - KeyPath: "testdata/pki/gocql.key", - CaPath: "testdata/pki/ca.crt", - EnableHostVerification: false, - } - } - return cluster -} - -var initOnce sync.Once - -func createTable(s *Session, table string) error { - err := s.Query(table).Consistency(All).Exec() - if *clusterSize > 1 { - // wait for table definition to propogate - time.Sleep(1 * time.Second) - } - return err -} - -func createCluster() *ClusterConfig { - cluster := NewCluster(clusterHosts...) - cluster.ProtoVersion = *flagProto - cluster.CQLVersion = *flagCQL - cluster.Timeout = 5 * time.Second - cluster.Consistency = Quorum - if *flagRetry > 0 { - cluster.RetryPolicy = &SimpleRetryPolicy{NumRetries: *flagRetry} - } - - switch *flagCompressTest { - case "snappy": - cluster.Compressor = &SnappyCompressor{} - case "": - default: - panic("invalid compressor: " + *flagCompressTest) - } - - cluster = addSslOptions(cluster) - return cluster -} - -func createKeyspace(tb testing.TB, cluster *ClusterConfig, keyspace string) { - session, err := cluster.CreateSession() - if err != nil { - tb.Fatal("createSession:", err) - } - defer session.Close() - if err = session.Query(`DROP KEYSPACE IF EXISTS ` + keyspace).Exec(); err != nil { - tb.Log("drop keyspace:", err) - } - if err := session.Query(fmt.Sprintf(`CREATE KEYSPACE %s - WITH replication = { - 'class' : 'SimpleStrategy', - 'replication_factor' : %d - }`, keyspace, *flagRF)).Consistency(All).Exec(); err != nil { - tb.Fatalf("error creating keyspace %s: %v", keyspace, err) - } - tb.Logf("Created keyspace %s", keyspace) -} - -func createSessionFromCluster(cluster *ClusterConfig, tb testing.TB) *Session { - // Drop and re-create the keyspace once. Different tests should use their own - // individual tables, but can assume that the table does not exist before. - initOnce.Do(func() { - createKeyspace(tb, cluster, "gocql_test") - }) - - cluster.Keyspace = "gocql_test" - session, err := cluster.CreateSession() - if err != nil { - tb.Fatal("createSession:", err) - } - - return session -} - -func createSession(tb testing.TB) *Session { - cluster := createCluster() - return createSessionFromCluster(cluster, tb) -} - -// TestAuthentication verifies that gocql will work with a host configured to only accept authenticated connections -func TestAuthentication(t *testing.T) { - - if *flagProto < 2 { - t.Skip("Authentication is not supported with protocol < 2") - } - - if !*flagRunAuthTest { - t.Skip("Authentication is not configured in the target cluster") - } - - cluster := createCluster() - - cluster.Authenticator = PasswordAuthenticator{ - Username: "cassandra", - Password: "cassandra", - } - - session, err := cluster.CreateSession() - - if err != nil { - t.Fatalf("Authentication error: %s", err) - } - - session.Close() -} - -//TestRingDiscovery makes sure that you can autodiscover other cluster members when you seed a cluster config with just one node -func TestRingDiscovery(t *testing.T) { - cluster := createCluster() - cluster.Hosts = clusterHosts[:1] - cluster.DiscoverHosts = true - - session, err := cluster.CreateSession() - if err != nil { - t.Fatalf("got error connecting to the cluster %v", err) - } - - if *clusterSize > 1 { - // wait for autodiscovery to update the pool with the list of known hosts - time.Sleep(*flagAutoWait) - } - - size := len(session.Pool.(*SimplePool).connPool) - - if *clusterSize != size { - t.Logf("WARN: Expected a cluster size of %d, but actual size was %d", *clusterSize, size) - } - - session.Close() -} - -func TestEmptyHosts(t *testing.T) { - cluster := createCluster() - cluster.Hosts = nil - if session, err := cluster.CreateSession(); err == nil { - session.Close() - t.Error("expected err, got nil") - } -} - -//TestUseStatementError checks to make sure the correct error is returned when the user tries to execute a use statement. -func TestUseStatementError(t *testing.T) { - session := createSession(t) - defer session.Close() - - if err := session.Query("USE gocql_test").Exec(); err != nil { - if err != ErrUseStmt { - t.Error("expected ErrUseStmt, got " + err.Error()) - } - } else { - t.Error("expected err, got nil.") - } -} - -//TestInvalidKeyspace checks that an invalid keyspace will return promptly and without a flood of connections -func TestInvalidKeyspace(t *testing.T) { - cluster := createCluster() - cluster.Keyspace = "invalidKeyspace" - session, err := cluster.CreateSession() - if err != nil { - if err != ErrNoConnectionsStarted { - t.Errorf("Expected ErrNoConnections but got %v", err) - } - } else { - session.Close() //Clean up the session - t.Error("expected err, got nil.") - } -} - -func TestTracing(t *testing.T) { - session := createSession(t) - defer session.Close() - - if err := createTable(session, `CREATE TABLE trace (id int primary key)`); err != nil { - t.Fatal("create:", err) - } - - buf := &bytes.Buffer{} - trace := NewTraceWriter(session, buf) - - if err := session.Query(`INSERT INTO trace (id) VALUES (?)`, 42).Trace(trace).Exec(); err != nil { - t.Error("insert:", err) - } else if buf.Len() == 0 { - t.Error("insert: failed to obtain any tracing") - } - buf.Reset() - - var value int - if err := session.Query(`SELECT id FROM trace WHERE id = ?`, 42).Trace(trace).Scan(&value); err != nil { - t.Error("select:", err) - } else if value != 42 { - t.Errorf("value: expected %d, got %d", 42, value) - } else if buf.Len() == 0 { - t.Error("select: failed to obtain any tracing") - } -} - -func TestPaging(t *testing.T) { - if *flagProto == 1 { - t.Skip("Paging not supported. Please use Cassandra >= 2.0") - } - - session := createSession(t) - defer session.Close() - - if err := createTable(session, "CREATE TABLE paging (id int primary key)"); err != nil { - t.Fatal("create table:", err) - } - for i := 0; i < 100; i++ { - if err := session.Query("INSERT INTO paging (id) VALUES (?)", i).Exec(); err != nil { - t.Fatal("insert:", err) - } - } - - iter := session.Query("SELECT id FROM paging").PageSize(10).Iter() - var id int - count := 0 - for iter.Scan(&id) { - count++ - } - if err := iter.Close(); err != nil { - t.Fatal("close:", err) - } - if count != 100 { - t.Fatalf("expected %d, got %d", 100, count) - } -} - -func TestCAS(t *testing.T) { - if *flagProto == 1 { - t.Skip("lightweight transactions not supported. Please use Cassandra >= 2.0") - } - - session := createSession(t) - defer session.Close() - session.cfg.SerialConsistency = LocalSerial - - if err := createTable(session, `CREATE TABLE cas_table ( - title varchar, - revid timeuuid, - last_modified timestamp, - PRIMARY KEY (title, revid) - )`); err != nil { - t.Fatal("create:", err) - } - - title, revid, modified := "baz", TimeUUID(), time.Now() - var titleCAS string - var revidCAS UUID - var modifiedCAS time.Time - - if applied, err := session.Query(`INSERT INTO cas_table (title, revid, last_modified) - VALUES (?, ?, ?) IF NOT EXISTS`, - title, revid, modified).ScanCAS(&titleCAS, &revidCAS, &modifiedCAS); err != nil { - t.Fatal("insert:", err) - } else if !applied { - t.Fatal("insert should have been applied") - } - - if applied, err := session.Query(`INSERT INTO cas_table (title, revid, last_modified) - VALUES (?, ?, ?) IF NOT EXISTS`, - title, revid, modified).ScanCAS(&titleCAS, &revidCAS, &modifiedCAS); err != nil { - t.Fatal("insert:", err) - } else if applied { - t.Fatal("insert should not have been applied") - } else if title != titleCAS || revid != revidCAS { - t.Fatalf("expected %s/%v/%v but got %s/%v/%v", title, revid, modified, titleCAS, revidCAS, modifiedCAS) - } - - tenSecondsLater := modified.Add(10 * time.Second) - - if applied, err := session.Query(`DELETE FROM cas_table WHERE title = ? and revid = ? IF last_modified = ?`, - title, revid, tenSecondsLater).ScanCAS(&modifiedCAS); err != nil { - t.Fatal("delete:", err) - } else if applied { - t.Fatal("delete should have not been applied") - } - - if modifiedCAS.Unix() != tenSecondsLater.Add(-10*time.Second).Unix() { - t.Fatalf("Was expecting modified CAS to be %v; but was one second later", modifiedCAS.UTC()) - } - - if _, err := session.Query(`DELETE FROM cas_table WHERE title = ? and revid = ? IF last_modified = ?`, - title, revid, tenSecondsLater).ScanCAS(); err.Error() != "count mismatch" { - t.Fatalf("delete: was expecting count mismatch error but got %s", err) - } - - if applied, err := session.Query(`DELETE FROM cas_table WHERE title = ? and revid = ? IF last_modified = ?`, - title, revid, modified).ScanCAS(&modifiedCAS); err != nil { - t.Fatal("delete:", err) - } else if !applied { - t.Fatal("delete should have been applied") - } -} - -func TestMapScanCAS(t *testing.T) { - if *flagProto == 1 { - t.Skip("lightweight transactions not supported. Please use Cassandra >= 2.0") - } - - session := createSession(t) - defer session.Close() - - if err := createTable(session, `CREATE TABLE cas_table2 ( - title varchar, - revid timeuuid, - last_modified timestamp, - deleted boolean, - PRIMARY KEY (title, revid) - )`); err != nil { - t.Fatal("create:", err) - } - - title, revid, modified, deleted := "baz", TimeUUID(), time.Now(), false - mapCAS := map[string]interface{}{} - - if applied, err := session.Query(`INSERT INTO cas_table2 (title, revid, last_modified, deleted) - VALUES (?, ?, ?, ?) IF NOT EXISTS`, - title, revid, modified, deleted).MapScanCAS(mapCAS); err != nil { - t.Fatal("insert:", err) - } else if !applied { - t.Fatal("insert should have been applied") - } - - mapCAS = map[string]interface{}{} - if applied, err := session.Query(`INSERT INTO cas_table2 (title, revid, last_modified, deleted) - VALUES (?, ?, ?, ?) IF NOT EXISTS`, - title, revid, modified, deleted).MapScanCAS(mapCAS); err != nil { - t.Fatal("insert:", err) - } else if applied { - t.Fatal("insert should not have been applied") - } else if title != mapCAS["title"] || revid != mapCAS["revid"] || deleted != mapCAS["deleted"] { - t.Fatalf("expected %s/%v/%v/%v but got %s/%v/%v%v", title, revid, modified, false, mapCAS["title"], mapCAS["revid"], mapCAS["last_modified"], mapCAS["deleted"]) - } - -} - -func TestBatch(t *testing.T) { - if *flagProto == 1 { - t.Skip("atomic batches not supported. Please use Cassandra >= 2.0") - } - - session := createSession(t) - defer session.Close() - - if err := createTable(session, `CREATE TABLE batch_table (id int primary key)`); err != nil { - t.Fatal("create table:", err) - } - - batch := NewBatch(LoggedBatch) - for i := 0; i < 100; i++ { - batch.Query(`INSERT INTO batch_table (id) VALUES (?)`, i) - } - if err := session.ExecuteBatch(batch); err != nil { - t.Fatal("execute batch:", err) - } - - count := 0 - if err := session.Query(`SELECT COUNT(*) FROM batch_table`).Scan(&count); err != nil { - t.Fatal("select count:", err) - } else if count != 100 { - t.Fatalf("count: expected %d, got %d\n", 100, count) - } -} - -func TestUnpreparedBatch(t *testing.T) { - if *flagProto == 1 { - t.Skip("atomic batches not supported. Please use Cassandra >= 2.0") - } - - session := createSession(t) - defer session.Close() - - if err := createTable(session, `CREATE TABLE batch_unprepared (id int primary key, c counter)`); err != nil { - t.Fatal("create table:", err) - } - - var batch *Batch - if *flagProto == 2 { - batch = NewBatch(CounterBatch) - } else { - batch = NewBatch(UnloggedBatch) - } - - for i := 0; i < 100; i++ { - batch.Query(`UPDATE batch_unprepared SET c = c + 1 WHERE id = 1`) - } - - if err := session.ExecuteBatch(batch); err != nil { - t.Fatal("execute batch:", err) - } - - count := 0 - if err := session.Query(`SELECT COUNT(*) FROM batch_unprepared`).Scan(&count); err != nil { - t.Fatal("select count:", err) - } else if count != 1 { - t.Fatalf("count: expected %d, got %d\n", 100, count) - } - - if err := session.Query(`SELECT c FROM batch_unprepared`).Scan(&count); err != nil { - t.Fatal("select count:", err) - } else if count != 100 { - t.Fatalf("count: expected %d, got %d\n", 100, count) - } -} - -// TestBatchLimit tests gocql to make sure batch operations larger than the maximum -// statement limit are not submitted to a cassandra node. -func TestBatchLimit(t *testing.T) { - if *flagProto == 1 { - t.Skip("atomic batches not supported. Please use Cassandra >= 2.0") - } - session := createSession(t) - defer session.Close() - - if err := createTable(session, `CREATE TABLE batch_table2 (id int primary key)`); err != nil { - t.Fatal("create table:", err) - } - - batch := NewBatch(LoggedBatch) - for i := 0; i < 65537; i++ { - batch.Query(`INSERT INTO batch_table2 (id) VALUES (?)`, i) - } - if err := session.ExecuteBatch(batch); err != ErrTooManyStmts { - t.Fatal("gocql attempted to execute a batch larger than the support limit of statements.") - } - -} - -func TestWhereIn(t *testing.T) { - session := createSession(t) - defer session.Close() - - if err := createTable(session, `CREATE TABLE where_in_table (id int, cluster int, primary key (id,cluster))`); err != nil { - t.Fatal("create table:", err) - } - - if err := session.Query("INSERT INTO where_in_table (id, cluster) VALUES (?,?)", 100, 200).Exec(); err != nil { - t.Fatal("insert:", err) - } - - iter := session.Query("SELECT * FROM where_in_table WHERE id = ? AND cluster IN (?)", 100, 200).Iter() - var id, cluster int - count := 0 - for iter.Scan(&id, &cluster) { - count++ - } - - if id != 100 || cluster != 200 { - t.Fatalf("Was expecting id and cluster to be (100,200) but were (%d,%d)", id, cluster) - } -} - -// TestTooManyQueryArgs tests to make sure the library correctly handles the application level bug -// whereby too many query arguments are passed to a query -func TestTooManyQueryArgs(t *testing.T) { - if *flagProto == 1 { - t.Skip("atomic batches not supported. Please use Cassandra >= 2.0") - } - session := createSession(t) - defer session.Close() - - if err := createTable(session, `CREATE TABLE too_many_query_args (id int primary key, value int)`); err != nil { - t.Fatal("create table:", err) - } - - _, err := session.Query(`SELECT * FROM too_many_query_args WHERE id = ?`, 1, 2).Iter().SliceMap() - - if err == nil { - t.Fatal("'`SELECT * FROM too_many_query_args WHERE id = ?`, 1, 2' should return an ErrQueryArgLength") - } - - if err != ErrQueryArgLength { - t.Fatalf("'`SELECT * FROM too_many_query_args WHERE id = ?`, 1, 2' should return an ErrQueryArgLength, but returned: %s", err) - } - - batch := session.NewBatch(UnloggedBatch) - batch.Query("INSERT INTO too_many_query_args (id, value) VALUES (?, ?)", 1, 2, 3) - err = session.ExecuteBatch(batch) - - if err == nil { - t.Fatal("'`INSERT INTO too_many_query_args (id, value) VALUES (?, ?)`, 1, 2, 3' should return an ErrQueryArgLength") - } - - if err != ErrQueryArgLength { - t.Fatalf("'INSERT INTO too_many_query_args (id, value) VALUES (?, ?)`, 1, 2, 3' should return an ErrQueryArgLength, but returned: %s", err) - } - -} - -// TestNotEnoughQueryArgs tests to make sure the library correctly handles the application level bug -// whereby not enough query arguments are passed to a query -func TestNotEnoughQueryArgs(t *testing.T) { - if *flagProto == 1 { - t.Skip("atomic batches not supported. Please use Cassandra >= 2.0") - } - session := createSession(t) - defer session.Close() - - if err := createTable(session, `CREATE TABLE not_enough_query_args (id int, cluster int, value int, primary key (id, cluster))`); err != nil { - t.Fatal("create table:", err) - } - - _, err := session.Query(`SELECT * FROM not_enough_query_args WHERE id = ? and cluster = ?`, 1).Iter().SliceMap() - - if err == nil { - t.Fatal("'`SELECT * FROM not_enough_query_args WHERE id = ? and cluster = ?`, 1' should return an ErrQueryArgLength") - } - - if err != ErrQueryArgLength { - t.Fatalf("'`SELECT * FROM too_few_query_args WHERE id = ? and cluster = ?`, 1' should return an ErrQueryArgLength, but returned: %s", err) - } - - batch := session.NewBatch(UnloggedBatch) - batch.Query("INSERT INTO not_enough_query_args (id, cluster, value) VALUES (?, ?, ?)", 1, 2) - err = session.ExecuteBatch(batch) - - if err == nil { - t.Fatal("'`INSERT INTO not_enough_query_args (id, cluster, value) VALUES (?, ?, ?)`, 1, 2' should return an ErrQueryArgLength") - } - - if err != ErrQueryArgLength { - t.Fatalf("'INSERT INTO not_enough_query_args (id, cluster, value) VALUES (?, ?, ?)`, 1, 2' should return an ErrQueryArgLength, but returned: %s", err) - } -} - -// TestCreateSessionTimeout tests to make sure the CreateSession function timeouts out correctly -// and prevents an infinite loop of connection retries. -func TestCreateSessionTimeout(t *testing.T) { - go func() { - <-time.After(2 * time.Second) - t.Error("no startup timeout") - }() - - cluster := createCluster() - cluster.Hosts = []string{"127.0.0.1:1"} - session, err := cluster.CreateSession() - if err == nil { - session.Close() - t.Fatal("expected ErrNoConnectionsStarted, but no error was returned.") - } - - if err != ErrNoConnectionsStarted { - t.Fatalf("expected ErrNoConnectionsStarted, but received %v", err) - } -} - -type FullName struct { - FirstName string - LastName string -} - -func (n FullName) MarshalCQL(info TypeInfo) ([]byte, error) { - return []byte(n.FirstName + " " + n.LastName), nil -} - -func (n *FullName) UnmarshalCQL(info TypeInfo, data []byte) error { - t := strings.SplitN(string(data), " ", 2) - n.FirstName, n.LastName = t[0], t[1] - return nil -} - -func TestMapScanWithRefMap(t *testing.T) { - session := createSession(t) - defer session.Close() - if err := createTable(session, `CREATE TABLE scan_map_ref_table ( - testtext text PRIMARY KEY, - testfullname text, - testint int, - )`); err != nil { - t.Fatal("create table:", err) - } - m := make(map[string]interface{}) - m["testtext"] = "testtext" - m["testfullname"] = FullName{"John", "Doe"} - m["testint"] = 100 - - if err := session.Query(`INSERT INTO scan_map_ref_table (testtext, testfullname, testint) values (?,?,?)`, m["testtext"], m["testfullname"], m["testint"]).Exec(); err != nil { - t.Fatal("insert:", err) - } - - var testText string - var testFullName FullName - ret := map[string]interface{}{ - "testtext": &testText, - "testfullname": &testFullName, - // testint is not set here. - } - iter := session.Query(`SELECT * FROM scan_map_ref_table`).Iter() - if ok := iter.MapScan(ret); !ok { - t.Fatal("select:", iter.Close()) - } else { - if ret["testtext"] != "testtext" { - t.Fatal("returned testtext did not match") - } - f := ret["testfullname"].(FullName) - if f.FirstName != "John" || f.LastName != "Doe" { - t.Fatal("returned testfullname did not match") - } - if ret["testint"] != 100 { - t.Fatal("returned testinit did not match") - } - } - -} - -func TestSliceMap(t *testing.T) { - session := createSession(t) - defer session.Close() - if err := createTable(session, `CREATE TABLE slice_map_table ( - testuuid timeuuid PRIMARY KEY, - testtimestamp timestamp, - testvarchar varchar, - testbigint bigint, - testblob blob, - testbool boolean, - testfloat float, - testdouble double, - testint int, - testdecimal decimal, - testlist list, - testset set, - testmap map, - testvarint varint, - testinet inet - )`); err != nil { - t.Fatal("create table:", err) - } - m := make(map[string]interface{}) - - bigInt := new(big.Int) - if _, ok := bigInt.SetString("830169365738487321165427203929228", 10); !ok { - t.Fatal("Failed setting bigint by string") - } - - m["testuuid"] = TimeUUID() - m["testvarchar"] = "Test VarChar" - m["testbigint"] = time.Now().Unix() - m["testtimestamp"] = time.Now().Truncate(time.Millisecond).UTC() - m["testblob"] = []byte("test blob") - m["testbool"] = true - m["testfloat"] = float32(4.564) - m["testdouble"] = float64(4.815162342) - m["testint"] = 2343 - m["testdecimal"] = inf.NewDec(100, 0) - m["testlist"] = []string{"quux", "foo", "bar", "baz", "quux"} - m["testset"] = []int{1, 2, 3, 4, 5, 6, 7, 8, 9} - m["testmap"] = map[string]string{"field1": "val1", "field2": "val2", "field3": "val3"} - m["testvarint"] = bigInt - m["testinet"] = "213.212.2.19" - sliceMap := []map[string]interface{}{m} - if err := session.Query(`INSERT INTO slice_map_table (testuuid, testtimestamp, testvarchar, testbigint, testblob, testbool, testfloat, testdouble, testint, testdecimal, testlist, testset, testmap, testvarint, testinet) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, - m["testuuid"], m["testtimestamp"], m["testvarchar"], m["testbigint"], m["testblob"], m["testbool"], m["testfloat"], m["testdouble"], m["testint"], m["testdecimal"], m["testlist"], m["testset"], m["testmap"], m["testvarint"], m["testinet"]).Exec(); err != nil { - t.Fatal("insert:", err) - } - if returned, retErr := session.Query(`SELECT * FROM slice_map_table`).Iter().SliceMap(); retErr != nil { - t.Fatal("select:", retErr) - } else { - matchSliceMap(t, sliceMap, returned[0]) - } - - // Test for Iter.MapScan() - { - testMap := make(map[string]interface{}) - if !session.Query(`SELECT * FROM slice_map_table`).Iter().MapScan(testMap) { - t.Fatal("MapScan failed to work with one row") - } - matchSliceMap(t, sliceMap, testMap) - } - - // Test for Query.MapScan() - { - testMap := make(map[string]interface{}) - if session.Query(`SELECT * FROM slice_map_table`).MapScan(testMap) != nil { - t.Fatal("MapScan failed to work with one row") - } - matchSliceMap(t, sliceMap, testMap) - } -} -func matchSliceMap(t *testing.T, sliceMap []map[string]interface{}, testMap map[string]interface{}) { - if sliceMap[0]["testuuid"] != testMap["testuuid"] { - t.Fatal("returned testuuid did not match") - } - if sliceMap[0]["testtimestamp"] != testMap["testtimestamp"] { - t.Fatal("returned testtimestamp did not match") - } - if sliceMap[0]["testvarchar"] != testMap["testvarchar"] { - t.Fatal("returned testvarchar did not match") - } - if sliceMap[0]["testbigint"] != testMap["testbigint"] { - t.Fatal("returned testbigint did not match") - } - if !reflect.DeepEqual(sliceMap[0]["testblob"], testMap["testblob"]) { - t.Fatal("returned testblob did not match") - } - if sliceMap[0]["testbool"] != testMap["testbool"] { - t.Fatal("returned testbool did not match") - } - if sliceMap[0]["testfloat"] != testMap["testfloat"] { - t.Fatal("returned testfloat did not match") - } - if sliceMap[0]["testdouble"] != testMap["testdouble"] { - t.Fatal("returned testdouble did not match") - } - if sliceMap[0]["testinet"] != testMap["testinet"] { - t.Fatal("returned testinet did not match") - } - - expectedDecimal := sliceMap[0]["testdecimal"].(*inf.Dec) - returnedDecimal := testMap["testdecimal"].(*inf.Dec) - - if expectedDecimal.Cmp(returnedDecimal) != 0 { - t.Fatal("returned testdecimal did not match") - } - - if !reflect.DeepEqual(sliceMap[0]["testlist"], testMap["testlist"]) { - t.Fatal("returned testlist did not match") - } - if !reflect.DeepEqual(sliceMap[0]["testset"], testMap["testset"]) { - t.Fatal("returned testset did not match") - } - if !reflect.DeepEqual(sliceMap[0]["testmap"], testMap["testmap"]) { - t.Fatal("returned testmap did not match") - } - if sliceMap[0]["testint"] != testMap["testint"] { - t.Fatal("returned testint did not match") - } -} - -func TestScanWithNilArguments(t *testing.T) { - session := createSession(t) - defer session.Close() - - if err := createTable(session, `CREATE TABLE scan_with_nil_arguments ( - foo varchar, - bar int, - PRIMARY KEY (foo, bar) - )`); err != nil { - t.Fatal("create:", err) - } - for i := 1; i <= 20; i++ { - if err := session.Query("INSERT INTO scan_with_nil_arguments (foo, bar) VALUES (?, ?)", - "squares", i*i).Exec(); err != nil { - t.Fatal("insert:", err) - } - } - - iter := session.Query("SELECT * FROM scan_with_nil_arguments WHERE foo = ?", "squares").Iter() - var n int - count := 0 - for iter.Scan(nil, &n) { - count += n - } - if err := iter.Close(); err != nil { - t.Fatal("close:", err) - } - if count != 2870 { - t.Fatalf("expected %d, got %d", 2870, count) - } -} - -func TestScanCASWithNilArguments(t *testing.T) { - if *flagProto == 1 { - t.Skip("lightweight transactions not supported. Please use Cassandra >= 2.0") - } - - session := createSession(t) - defer session.Close() - - if err := createTable(session, `CREATE TABLE scan_cas_with_nil_arguments ( - foo varchar, - bar varchar, - PRIMARY KEY (foo, bar) - )`); err != nil { - t.Fatal("create:", err) - } - - foo := "baz" - var cas string - - if applied, err := session.Query(`INSERT INTO scan_cas_with_nil_arguments (foo, bar) - VALUES (?, ?) IF NOT EXISTS`, - foo, foo).ScanCAS(nil, nil); err != nil { - t.Fatal("insert:", err) - } else if !applied { - t.Fatal("insert should have been applied") - } - - if applied, err := session.Query(`INSERT INTO scan_cas_with_nil_arguments (foo, bar) - VALUES (?, ?) IF NOT EXISTS`, - foo, foo).ScanCAS(&cas, nil); err != nil { - t.Fatal("insert:", err) - } else if applied { - t.Fatal("insert should not have been applied") - } else if foo != cas { - t.Fatalf("expected %v but got %v", foo, cas) - } - - if applied, err := session.Query(`INSERT INTO scan_cas_with_nil_arguments (foo, bar) - VALUES (?, ?) IF NOT EXISTS`, - foo, foo).ScanCAS(nil, &cas); err != nil { - t.Fatal("insert:", err) - } else if applied { - t.Fatal("insert should not have been applied") - } else if foo != cas { - t.Fatalf("expected %v but got %v", foo, cas) - } -} - -func TestRebindQueryInfo(t *testing.T) { - session := createSession(t) - defer session.Close() - - if err := createTable(session, "CREATE TABLE rebind_query (id int, value text, PRIMARY KEY (id))"); err != nil { - t.Fatalf("failed to create table with error '%v'", err) - } - - if err := session.Query("INSERT INTO rebind_query (id, value) VALUES (?, ?)", 23, "quux").Exec(); err != nil { - t.Fatalf("insert into rebind_query failed, err '%v'", err) - } - - if err := session.Query("INSERT INTO rebind_query (id, value) VALUES (?, ?)", 24, "w00t").Exec(); err != nil { - t.Fatalf("insert into rebind_query failed, err '%v'", err) - } - - q := session.Query("SELECT value FROM rebind_query WHERE ID = ?") - q.Bind(23) - - iter := q.Iter() - var value string - for iter.Scan(&value) { - } - - if value != "quux" { - t.Fatalf("expected %v but got %v", "quux", value) - } - - q.Bind(24) - iter = q.Iter() - - for iter.Scan(&value) { - } - - if value != "w00t" { - t.Fatalf("expected %v but got %v", "quux", value) - } -} - -//TestStaticQueryInfo makes sure that the application can manually bind query parameters using the simplest possible static binding strategy -func TestStaticQueryInfo(t *testing.T) { - session := createSession(t) - defer session.Close() - - if err := createTable(session, "CREATE TABLE static_query_info (id int, value text, PRIMARY KEY (id))"); err != nil { - t.Fatalf("failed to create table with error '%v'", err) - } - - if err := session.Query("INSERT INTO static_query_info (id, value) VALUES (?, ?)", 113, "foo").Exec(); err != nil { - t.Fatalf("insert into static_query_info failed, err '%v'", err) - } - - autobinder := func(q *QueryInfo) ([]interface{}, error) { - values := make([]interface{}, 1) - values[0] = 113 - return values, nil - } - - qry := session.Bind("SELECT id, value FROM static_query_info WHERE id = ?", autobinder) - - if err := qry.Exec(); err != nil { - t.Fatalf("expose query info failed, error '%v'", err) - } - - iter := qry.Iter() - - var id int - var value string - - iter.Scan(&id, &value) - - if err := iter.Close(); err != nil { - t.Fatalf("query with exposed info failed, err '%v'", err) - } - - if value != "foo" { - t.Fatalf("Expected value %s, but got %s", "foo", value) - } - -} - -type ClusteredKeyValue struct { - Id int - Cluster int - Value string -} - -func (kv *ClusteredKeyValue) Bind(q *QueryInfo) ([]interface{}, error) { - values := make([]interface{}, len(q.Args)) - - for i, info := range q.Args { - fieldName := upcaseInitial(info.Name) - value := reflect.ValueOf(kv) - field := reflect.Indirect(value).FieldByName(fieldName) - values[i] = field.Addr().Interface() - } - - return values, nil -} - -func upcaseInitial(str string) string { - for i, v := range str { - return string(unicode.ToUpper(v)) + str[i+1:] - } - return "" -} - -//TestBoundQueryInfo makes sure that the application can manually bind query parameters using the query meta data supplied at runtime -func TestBoundQueryInfo(t *testing.T) { - - session := createSession(t) - defer session.Close() - - if err := createTable(session, "CREATE TABLE clustered_query_info (id int, cluster int, value text, PRIMARY KEY (id, cluster))"); err != nil { - t.Fatalf("failed to create table with error '%v'", err) - } - - write := &ClusteredKeyValue{Id: 200, Cluster: 300, Value: "baz"} - - insert := session.Bind("INSERT INTO clustered_query_info (id, cluster, value) VALUES (?, ?,?)", write.Bind) - - if err := insert.Exec(); err != nil { - t.Fatalf("insert into clustered_query_info failed, err '%v'", err) - } - - read := &ClusteredKeyValue{Id: 200, Cluster: 300} - - qry := session.Bind("SELECT id, cluster, value FROM clustered_query_info WHERE id = ? and cluster = ?", read.Bind) - - iter := qry.Iter() - - var id, cluster int - var value string - - iter.Scan(&id, &cluster, &value) - - if err := iter.Close(); err != nil { - t.Fatalf("query with clustered_query_info info failed, err '%v'", err) - } - - if value != "baz" { - t.Fatalf("Expected value %s, but got %s", "baz", value) - } - -} - -//TestBatchQueryInfo makes sure that the application can manually bind query parameters when executing in a batch -func TestBatchQueryInfo(t *testing.T) { - - if *flagProto == 1 { - t.Skip("atomic batches not supported. Please use Cassandra >= 2.0") - } - - session := createSession(t) - defer session.Close() - - if err := createTable(session, "CREATE TABLE batch_query_info (id int, cluster int, value text, PRIMARY KEY (id, cluster))"); err != nil { - t.Fatalf("failed to create table with error '%v'", err) - } - - write := func(q *QueryInfo) ([]interface{}, error) { - values := make([]interface{}, 3) - values[0] = 4000 - values[1] = 5000 - values[2] = "bar" - return values, nil - } - - batch := session.NewBatch(LoggedBatch) - batch.Bind("INSERT INTO batch_query_info (id, cluster, value) VALUES (?, ?,?)", write) - - if err := session.ExecuteBatch(batch); err != nil { - t.Fatalf("batch insert into batch_query_info failed, err '%v'", err) - } - - read := func(q *QueryInfo) ([]interface{}, error) { - values := make([]interface{}, 2) - values[0] = 4000 - values[1] = 5000 - return values, nil - } - - qry := session.Bind("SELECT id, cluster, value FROM batch_query_info WHERE id = ? and cluster = ?", read) - - iter := qry.Iter() - - var id, cluster int - var value string - - iter.Scan(&id, &cluster, &value) - - if err := iter.Close(); err != nil { - t.Fatalf("query with batch_query_info info failed, err '%v'", err) - } - - if value != "bar" { - t.Fatalf("Expected value %s, but got %s", "bar", value) - } -} - -func injectInvalidPreparedStatement(t *testing.T, session *Session, table string) (string, *Conn) { - if err := createTable(session, `CREATE TABLE `+table+` ( - foo varchar, - bar int, - PRIMARY KEY (foo, bar) - )`); err != nil { - t.Fatal("create:", err) - } - stmt := "INSERT INTO " + table + " (foo, bar) VALUES (?, 7)" - conn := session.Pool.Pick(nil) - flight := new(inflightPrepare) - stmtsLRU.Lock() - stmtsLRU.lru.Add(conn.addr+stmt, flight) - stmtsLRU.Unlock() - flight.info = &resultPreparedFrame{ - preparedID: []byte{'f', 'o', 'o', 'b', 'a', 'r'}, - reqMeta: resultMetadata{ - columns: []ColumnInfo{ - { - Keyspace: "gocql_test", - Table: table, - Name: "foo", - TypeInfo: NativeType{ - typ: TypeVarchar, - }, - }, - }}, - } - return stmt, conn -} - -func TestMissingSchemaPrepare(t *testing.T) { - s := createSession(t) - conn := s.Pool.Pick(nil) - defer s.Close() - - insertQry := &Query{stmt: "INSERT INTO invalidschemaprep (val) VALUES (?)", values: []interface{}{5}, cons: s.cons, - session: s, pageSize: s.pageSize, trace: s.trace, - prefetch: s.prefetch, rt: s.cfg.RetryPolicy} - - if err := conn.executeQuery(insertQry).err; err == nil { - t.Fatal("expected error, but got nil.") - } - - if err := createTable(s, "CREATE TABLE invalidschemaprep (val int, PRIMARY KEY (val))"); err != nil { - t.Fatal("create table:", err) - } - - if err := conn.executeQuery(insertQry).err; err != nil { - t.Fatal(err) // unconfigured columnfamily - } -} - -func TestReprepareStatement(t *testing.T) { - session := createSession(t) - defer session.Close() - stmt, conn := injectInvalidPreparedStatement(t, session, "test_reprepare_statement") - query := session.Query(stmt, "bar") - if err := conn.executeQuery(query).Close(); err != nil { - t.Fatalf("Failed to execute query for reprepare statement: %v", err) - } -} - -func TestReprepareBatch(t *testing.T) { - if *flagProto == 1 { - t.Skip("atomic batches not supported. Please use Cassandra >= 2.0") - } - session := createSession(t) - defer session.Close() - stmt, conn := injectInvalidPreparedStatement(t, session, "test_reprepare_statement_batch") - batch := session.NewBatch(UnloggedBatch) - batch.Query(stmt, "bar") - if err := conn.executeBatch(batch); err != nil { - t.Fatalf("Failed to execute query for reprepare statement: %v", err) - } - -} - -func TestQueryInfo(t *testing.T) { - session := createSession(t) - defer session.Close() - - conn := session.Pool.Pick(nil) - info, err := conn.prepareStatement("SELECT release_version, host_id FROM system.local WHERE key = ?", nil) - - if err != nil { - t.Fatalf("Failed to execute query for preparing statement: %v", err) - } - - if len(info.reqMeta.columns) != 1 { - t.Fatalf("Was not expecting meta data for %d query arguments, but got %d\n", 1, len(info.reqMeta.columns)) - } - - if *flagProto > 1 { - if len(info.respMeta.columns) != 2 { - t.Fatalf("Was not expecting meta data for %d result columns, but got %d\n", 2, len(info.respMeta.columns)) - } - } -} - -//TestPreparedCacheEviction will make sure that the cache size is maintained -func TestPreparedCacheEviction(t *testing.T) { - session := createSession(t) - defer session.Close() - stmtsLRU.Lock() - stmtsLRU.Max(4) - stmtsLRU.Unlock() - - if err := createTable(session, "CREATE TABLE prepcachetest (id int,mod int,PRIMARY KEY (id))"); err != nil { - t.Fatalf("failed to create table with error '%v'", err) - } - //Fill the table - for i := 0; i < 2; i++ { - if err := session.Query("INSERT INTO prepcachetest (id,mod) VALUES (?, ?)", i, 10000%(i+1)).Exec(); err != nil { - t.Fatalf("insert into prepcachetest failed, err '%v'", err) - } - } - //Populate the prepared statement cache with select statements - var id, mod int - for i := 0; i < 2; i++ { - err := session.Query("SELECT id,mod FROM prepcachetest WHERE id = "+strconv.FormatInt(int64(i), 10)).Scan(&id, &mod) - if err != nil { - t.Fatalf("select from prepcachetest failed, error '%v'", err) - } - } - - //generate an update statement to test they are prepared - err := session.Query("UPDATE prepcachetest SET mod = ? WHERE id = ?", 1, 11).Exec() - if err != nil { - t.Fatalf("update prepcachetest failed, error '%v'", err) - } - - //generate a delete statement to test they are prepared - err = session.Query("DELETE FROM prepcachetest WHERE id = ?", 1).Exec() - if err != nil { - t.Fatalf("delete from prepcachetest failed, error '%v'", err) - } - - //generate an insert statement to test they are prepared - err = session.Query("INSERT INTO prepcachetest (id,mod) VALUES (?, ?)", 3, 11).Exec() - if err != nil { - t.Fatalf("insert into prepcachetest failed, error '%v'", err) - } - - stmtsLRU.Lock() - - //Make sure the cache size is maintained - if stmtsLRU.lru.Len() != stmtsLRU.lru.MaxEntries { - t.Fatalf("expected cache size of %v, got %v", stmtsLRU.lru.MaxEntries, stmtsLRU.lru.Len()) - } - - //Walk through all the configured hosts and test cache retention and eviction - var selFound, insFound, updFound, delFound, selEvict bool - for i := range session.cfg.Hosts { - _, ok := stmtsLRU.lru.Get(session.cfg.Hosts[i] + ":9042gocql_testSELECT id,mod FROM prepcachetest WHERE id = 1") - selFound = selFound || ok - - _, ok = stmtsLRU.lru.Get(session.cfg.Hosts[i] + ":9042gocql_testINSERT INTO prepcachetest (id,mod) VALUES (?, ?)") - insFound = insFound || ok - - _, ok = stmtsLRU.lru.Get(session.cfg.Hosts[i] + ":9042gocql_testUPDATE prepcachetest SET mod = ? WHERE id = ?") - updFound = updFound || ok - - _, ok = stmtsLRU.lru.Get(session.cfg.Hosts[i] + ":9042gocql_testDELETE FROM prepcachetest WHERE id = ?") - delFound = delFound || ok - - _, ok = stmtsLRU.lru.Get(session.cfg.Hosts[i] + ":9042gocql_testSELECT id,mod FROM prepcachetest WHERE id = 0") - selEvict = selEvict || !ok - } - - stmtsLRU.Unlock() - - if !selEvict { - t.Fatalf("expected first select statement to be purged, but statement was found in the cache.") - } - if !selFound { - t.Fatalf("expected second select statement to be cached, but statement was purged or not prepared.") - } - if !insFound { - t.Fatalf("expected insert statement to be cached, but statement was purged or not prepared.") - } - if !updFound { - t.Fatalf("expected update statement to be cached, but statement was purged or not prepared.") - } - if !delFound { - t.Error("expected delete statement to be cached, but statement was purged or not prepared.") - } -} - -func TestPreparedCacheKey(t *testing.T) { - session := createSession(t) - defer session.Close() - - // create a second keyspace - cluster2 := createCluster() - createKeyspace(t, cluster2, "gocql_test2") - cluster2.Keyspace = "gocql_test2" - session2, err := cluster2.CreateSession() - if err != nil { - t.Fatal("create session:", err) - } - defer session2.Close() - - // both keyspaces have a table named "test_stmt_cache_key" - if err := createTable(session, "CREATE TABLE test_stmt_cache_key (id varchar primary key, field varchar)"); err != nil { - t.Fatal("create table:", err) - } - if err := createTable(session2, "CREATE TABLE test_stmt_cache_key (id varchar primary key, field varchar)"); err != nil { - t.Fatal("create table:", err) - } - - // both tables have a single row with the same partition key but different column value - if err = session.Query(`INSERT INTO test_stmt_cache_key (id, field) VALUES (?, ?)`, "key", "one").Exec(); err != nil { - t.Fatal("insert:", err) - } - if err = session2.Query(`INSERT INTO test_stmt_cache_key (id, field) VALUES (?, ?)`, "key", "two").Exec(); err != nil { - t.Fatal("insert:", err) - } - - // should be able to see different values in each keyspace - var value string - if err = session.Query("SELECT field FROM test_stmt_cache_key WHERE id = ?", "key").Scan(&value); err != nil { - t.Fatal("select:", err) - } - if value != "one" { - t.Errorf("Expected one, got %s", value) - } - - if err = session2.Query("SELECT field FROM test_stmt_cache_key WHERE id = ?", "key").Scan(&value); err != nil { - t.Fatal("select:", err) - } - if value != "two" { - t.Errorf("Expected two, got %s", value) - } -} - -//TestMarshalFloat64Ptr tests to see that a pointer to a float64 is marshalled correctly. -func TestMarshalFloat64Ptr(t *testing.T) { - session := createSession(t) - defer session.Close() - - if err := createTable(session, "CREATE TABLE float_test (id double, test double, primary key (id))"); err != nil { - t.Fatal("create table:", err) - } - testNum := float64(7500) - if err := session.Query(`INSERT INTO float_test (id,test) VALUES (?,?)`, float64(7500.00), &testNum).Exec(); err != nil { - t.Fatal("insert float64:", err) - } -} - -//TestMarshalInet tests to see that a pointer to a float64 is marshalled correctly. -func TestMarshalInet(t *testing.T) { - session := createSession(t) - defer session.Close() - - if err := createTable(session, "CREATE TABLE inet_test (ip inet, name text, primary key (ip))"); err != nil { - t.Fatal("create table:", err) - } - stringIp := "123.34.45.56" - if err := session.Query(`INSERT INTO inet_test (ip,name) VALUES (?,?)`, stringIp, "Test IP 1").Exec(); err != nil { - t.Fatal("insert string inet:", err) - } - var stringResult string - if err := session.Query("SELECT ip FROM inet_test").Scan(&stringResult); err != nil { - t.Fatalf("select for string from inet_test 1 failed: %v", err) - } - if stringResult != stringIp { - t.Errorf("Expected %s, was %s", stringIp, stringResult) - } - - var ipResult net.IP - if err := session.Query("SELECT ip FROM inet_test").Scan(&ipResult); err != nil { - t.Fatalf("select for net.IP from inet_test 1 failed: %v", err) - } - if ipResult.String() != stringIp { - t.Errorf("Expected %s, was %s", stringIp, ipResult.String()) - } - - if err := session.Query(`DELETE FROM inet_test WHERE ip = ?`, stringIp).Exec(); err != nil { - t.Fatal("delete inet table:", err) - } - - netIp := net.ParseIP("222.43.54.65") - if err := session.Query(`INSERT INTO inet_test (ip,name) VALUES (?,?)`, netIp, "Test IP 2").Exec(); err != nil { - t.Fatal("insert netIp inet:", err) - } - - if err := session.Query("SELECT ip FROM inet_test").Scan(&stringResult); err != nil { - t.Fatalf("select for string from inet_test 2 failed: %v", err) - } - if stringResult != netIp.String() { - t.Errorf("Expected %s, was %s", netIp.String(), stringResult) - } - if err := session.Query("SELECT ip FROM inet_test").Scan(&ipResult); err != nil { - t.Fatalf("select for net.IP from inet_test 2 failed: %v", err) - } - if ipResult.String() != netIp.String() { - t.Errorf("Expected %s, was %s", netIp.String(), ipResult.String()) - } - -} - -func TestVarint(t *testing.T) { - session := createSession(t) - defer session.Close() - - if err := createTable(session, "CREATE TABLE varint_test (id varchar, test varint, test2 varint, primary key (id))"); err != nil { - t.Fatalf("failed to create table with error '%v'", err) - } - - if err := session.Query(`INSERT INTO varint_test (id, test) VALUES (?, ?)`, "id", 0).Exec(); err != nil { - t.Fatalf("insert varint: %v", err) - } - - var result int - if err := session.Query("SELECT test FROM varint_test").Scan(&result); err != nil { - t.Fatalf("select from varint_test failed: %v", err) - } - - if result != 0 { - t.Errorf("Expected 0, was %d", result) - } - - if err := session.Query(`INSERT INTO varint_test (id, test) VALUES (?, ?)`, "id", -1).Exec(); err != nil { - t.Fatalf("insert varint: %v", err) - } - - if err := session.Query("SELECT test FROM varint_test").Scan(&result); err != nil { - t.Fatalf("select from varint_test failed: %v", err) - } - - if result != -1 { - t.Errorf("Expected -1, was %d", result) - } - - if err := session.Query(`INSERT INTO varint_test (id, test) VALUES (?, ?)`, "id", int64(math.MaxInt32)+1).Exec(); err != nil { - t.Fatalf("insert varint: %v", err) - } - - var result64 int64 - if err := session.Query("SELECT test FROM varint_test").Scan(&result64); err != nil { - t.Fatalf("select from varint_test failed: %v", err) - } - - if result64 != int64(math.MaxInt32)+1 { - t.Errorf("Expected %d, was %d", int64(math.MaxInt32)+1, result64) - } - - biggie := new(big.Int) - biggie.SetString("36893488147419103232", 10) // > 2**64 - if err := session.Query(`INSERT INTO varint_test (id, test) VALUES (?, ?)`, "id", biggie).Exec(); err != nil { - t.Fatalf("insert varint: %v", err) - } - - resultBig := new(big.Int) - if err := session.Query("SELECT test FROM varint_test").Scan(resultBig); err != nil { - t.Fatalf("select from varint_test failed: %v", err) - } - - if resultBig.String() != biggie.String() { - t.Errorf("Expected %s, was %s", biggie.String(), resultBig.String()) - } - - err := session.Query("SELECT test FROM varint_test").Scan(&result64) - if err == nil || strings.Index(err.Error(), "out of range") == -1 { - t.Errorf("expected out of range error since value is too big for int64") - } - - // value not set in cassandra, leave bind variable empty - resultBig = new(big.Int) - if err := session.Query("SELECT test2 FROM varint_test").Scan(resultBig); err != nil { - t.Fatalf("select from varint_test failed: %v", err) - } - - if resultBig.Int64() != 0 { - t.Errorf("Expected %s, was %s", biggie.String(), resultBig.String()) - } - - // can use double pointer to explicitly detect value is not set in cassandra - if err := session.Query("SELECT test2 FROM varint_test").Scan(&resultBig); err != nil { - t.Fatalf("select from varint_test failed: %v", err) - } - - if resultBig != nil { - t.Errorf("Expected %v, was %v", nil, *resultBig) - } -} - -//TestQueryStats confirms that the stats are returning valid data. Accuracy may be questionable. -func TestQueryStats(t *testing.T) { - session := createSession(t) - defer session.Close() - qry := session.Query("SELECT * FROM system.peers") - if err := qry.Exec(); err != nil { - t.Fatalf("query failed. %v", err) - } else { - if qry.Attempts() < 1 { - t.Fatal("expected at least 1 attempt, but got 0") - } - if qry.Latency() <= 0 { - t.Fatalf("expected latency to be greater than 0, but got %v instead.", qry.Latency()) - } - } -} - -//TestBatchStats confirms that the stats are returning valid data. Accuracy may be questionable. -func TestBatchStats(t *testing.T) { - if *flagProto == 1 { - t.Skip("atomic batches not supported. Please use Cassandra >= 2.0") - } - session := createSession(t) - defer session.Close() - - if err := createTable(session, "CREATE TABLE batchStats (id int, PRIMARY KEY (id))"); err != nil { - t.Fatalf("failed to create table with error '%v'", err) - } - - b := session.NewBatch(LoggedBatch) - b.Query("INSERT INTO batchStats (id) VALUES (?)", 1) - b.Query("INSERT INTO batchStats (id) VALUES (?)", 2) - - if err := session.ExecuteBatch(b); err != nil { - t.Fatalf("query failed. %v", err) - } else { - if b.Attempts() < 1 { - t.Fatal("expected at least 1 attempt, but got 0") - } - if b.Latency() <= 0 { - t.Fatalf("expected latency to be greater than 0, but got %v instead.", b.Latency()) - } - } -} - -//TestNilInQuery tests to see that a nil value passed to a query is handled by Cassandra -//TODO validate the nil value by reading back the nil. Need to fix Unmarshalling. -func TestNilInQuery(t *testing.T) { - session := createSession(t) - defer session.Close() - - if err := createTable(session, "CREATE TABLE testNilInsert (id int, count int, PRIMARY KEY (id))"); err != nil { - t.Fatalf("failed to create table with error '%v'", err) - } - if err := session.Query("INSERT INTO testNilInsert (id,count) VALUES (?,?)", 1, nil).Exec(); err != nil { - t.Fatalf("failed to insert with err: %v", err) - } - - var id int - - if err := session.Query("SELECT id FROM testNilInsert").Scan(&id); err != nil { - t.Fatalf("failed to select with err: %v", err) - } else if id != 1 { - t.Fatalf("expected id to be 1, got %v", id) - } -} - -// Don't initialize time.Time bind variable if cassandra timestamp column is empty -func TestEmptyTimestamp(t *testing.T) { - session := createSession(t) - defer session.Close() - - if err := createTable(session, "CREATE TABLE test_empty_timestamp (id int, time timestamp, num int, PRIMARY KEY (id))"); err != nil { - t.Fatalf("failed to create table with error '%v'", err) - } - - if err := session.Query("INSERT INTO test_empty_timestamp (id, num) VALUES (?,?)", 1, 561).Exec(); err != nil { - t.Fatalf("failed to insert with err: %v", err) - } - - var timeVal time.Time - - if err := session.Query("SELECT time FROM test_empty_timestamp where id = ?", 1).Scan(&timeVal); err != nil { - t.Fatalf("failed to select with err: %v", err) - } - - if !timeVal.IsZero() { - t.Errorf("time.Time bind variable should still be empty (was %s)", timeVal) - } -} - -// Integration test of just querying for data from the system.schema_keyspace table -func TestGetKeyspaceMetadata(t *testing.T) { - session := createSession(t) - defer session.Close() - - keyspaceMetadata, err := getKeyspaceMetadata(session, "gocql_test") - if err != nil { - t.Fatalf("failed to query the keyspace metadata with err: %v", err) - } - if keyspaceMetadata == nil { - t.Fatal("failed to query the keyspace metadata, nil returned") - } - if keyspaceMetadata.Name != "gocql_test" { - t.Errorf("Expected keyspace name to be 'gocql' but was '%s'", keyspaceMetadata.Name) - } - if keyspaceMetadata.StrategyClass != "org.apache.cassandra.locator.SimpleStrategy" { - t.Errorf("Expected replication strategy class to be 'org.apache.cassandra.locator.SimpleStrategy' but was '%s'", keyspaceMetadata.StrategyClass) - } - if keyspaceMetadata.StrategyOptions == nil { - t.Error("Expected replication strategy options map but was nil") - } - rfStr, ok := keyspaceMetadata.StrategyOptions["replication_factor"] - if !ok { - t.Fatalf("Expected strategy option 'replication_factor' but was not found in %v", keyspaceMetadata.StrategyOptions) - } - rfInt, err := strconv.Atoi(rfStr.(string)) - if err != nil { - t.Fatalf("Error converting string to int with err: %v", err) - } - if rfInt != *flagRF { - t.Errorf("Expected replication factor to be %d but was %d", *flagRF, rfInt) - } -} - -// Integration test of just querying for data from the system.schema_columnfamilies table -func TestGetTableMetadata(t *testing.T) { - session := createSession(t) - defer session.Close() - - if err := createTable(session, "CREATE TABLE test_table_metadata (first_id int, second_id int, third_id int, PRIMARY KEY (first_id, second_id))"); err != nil { - t.Fatalf("failed to create table with error '%v'", err) - } - - tables, err := getTableMetadata(session, "gocql_test") - if err != nil { - t.Fatalf("failed to query the table metadata with err: %v", err) - } - if tables == nil { - t.Fatal("failed to query the table metadata, nil returned") - } - - var testTable *TableMetadata - - // verify all tables have minimum expected data - for i := range tables { - table := &tables[i] - - if table.Name == "" { - t.Errorf("Expected table name to be set, but it was empty: index=%d metadata=%+v", i, table) - } - if table.Keyspace != "gocql_test" { - t.Errorf("Expected keyspace for '%d' table metadata to be 'gocql_test' but was '%s'", table.Name, table.Keyspace) - } - if table.KeyValidator == "" { - t.Errorf("Expected key validator to be set for table %s", table.Name) - } - if table.Comparator == "" { - t.Errorf("Expected comparator to be set for table %s", table.Name) - } - if table.DefaultValidator == "" { - t.Errorf("Expected default validator to be set for table %s", table.Name) - } - - // these fields are not set until the metadata is compiled - if table.PartitionKey != nil { - t.Errorf("Did not expect partition key for table %s", table.Name) - } - if table.ClusteringColumns != nil { - t.Errorf("Did not expect clustering columns for table %s", table.Name) - } - if table.Columns != nil { - t.Errorf("Did not expect columns for table %s", table.Name) - } - - // for the next part of the test after this loop, find the metadata for the test table - if table.Name == "test_table_metadata" { - testTable = table - } - } - - // verify actual values on the test tables - if testTable == nil { - t.Fatal("Expected table metadata for name 'test_table_metadata'") - } - if testTable.KeyValidator != "org.apache.cassandra.db.marshal.Int32Type" { - t.Errorf("Expected test_table_metadata key validator to be 'org.apache.cassandra.db.marshal.Int32Type' but was '%s'", testTable.KeyValidator) - } - if testTable.Comparator != "org.apache.cassandra.db.marshal.CompositeType(org.apache.cassandra.db.marshal.Int32Type,org.apache.cassandra.db.marshal.UTF8Type)" { - t.Errorf("Expected test_table_metadata key validator to be 'org.apache.cassandra.db.marshal.CompositeType(org.apache.cassandra.db.marshal.Int32Type,org.apache.cassandra.db.marshal.UTF8Type)' but was '%s'", testTable.Comparator) - } - if testTable.DefaultValidator != "org.apache.cassandra.db.marshal.BytesType" { - t.Errorf("Expected test_table_metadata key validator to be 'org.apache.cassandra.db.marshal.BytesType' but was '%s'", testTable.DefaultValidator) - } - expectedKeyAliases := []string{"first_id"} - if !reflect.DeepEqual(testTable.KeyAliases, expectedKeyAliases) { - t.Errorf("Expected key aliases %v but was %v", expectedKeyAliases, testTable.KeyAliases) - } - expectedColumnAliases := []string{"second_id"} - if !reflect.DeepEqual(testTable.ColumnAliases, expectedColumnAliases) { - t.Errorf("Expected key aliases %v but was %v", expectedColumnAliases, testTable.ColumnAliases) - } - if testTable.ValueAlias != "" { - t.Errorf("Expected value alias '' but was '%s'", testTable.ValueAlias) - } -} - -// Integration test of just querying for data from the system.schema_columns table -func TestGetColumnMetadata(t *testing.T) { - session := createSession(t) - defer session.Close() - - if err := createTable(session, "CREATE TABLE test_column_metadata (first_id int, second_id int, third_id int, PRIMARY KEY (first_id, second_id))"); err != nil { - t.Fatalf("failed to create table with error '%v'", err) - } - - if err := session.Query("CREATE INDEX index_column_metadata ON test_column_metadata ( third_id )").Exec(); err != nil { - t.Fatalf("failed to create index with err: %v", err) - } - - columns, err := getColumnMetadata(session, "gocql_test") - if err != nil { - t.Fatalf("failed to query column metadata with err: %v", err) - } - if columns == nil { - t.Fatal("failed to query column metadata, nil returned") - } - - testColumns := map[string]*ColumnMetadata{} - - // verify actual values on the test columns - for i := range columns { - column := &columns[i] - - if column.Name == "" { - t.Errorf("Expected column name to be set, but it was empty: index=%d metadata=%+v", i, column) - } - if column.Table == "" { - t.Errorf("Expected column %s table name to be set, but it was empty", column.Name) - } - if column.Keyspace != "gocql_test" { - t.Errorf("Expected column %s keyspace name to be 'gocql_test', but it was '%s'", column.Name, column.Keyspace) - } - if column.Kind == "" { - t.Errorf("Expected column %s kind to be set, but it was empty", column.Name) - } - if session.cfg.ProtoVersion == 1 && column.Kind != "regular" { - t.Errorf("Expected column %s kind to be set to 'regular' for proto V1 but it was '%s'", column.Name, column.Kind) - } - if column.Validator == "" { - t.Errorf("Expected column %s validator to be set, but it was empty", column.Name) - } - - // find the test table columns for the next step after this loop - if column.Table == "test_column_metadata" { - testColumns[column.Name] = column - } - } - - if *flagProto == 1 { - // V1 proto only returns "regular columns" - if len(testColumns) != 1 { - t.Errorf("Expected 1 test columns but there were %d", len(testColumns)) - } - thirdID, found := testColumns["third_id"] - if !found { - t.Fatalf("Expected to find column 'third_id' metadata but there was only %v", testColumns) - } - - if thirdID.Kind != REGULAR { - t.Errorf("Expected %s column kind to be '%s' but it was '%s'", thirdID.Name, REGULAR, thirdID.Kind) - } - - if thirdID.Index.Name != "index_column_metadata" { - t.Errorf("Expected %s column index name to be 'index_column_metadata' but it was '%s'", thirdID.Name, thirdID.Index.Name) - } - } else { - if len(testColumns) != 3 { - t.Errorf("Expected 3 test columns but there were %d", len(testColumns)) - } - firstID, found := testColumns["first_id"] - if !found { - t.Fatalf("Expected to find column 'first_id' metadata but there was only %v", testColumns) - } - secondID, found := testColumns["second_id"] - if !found { - t.Fatalf("Expected to find column 'second_id' metadata but there was only %v", testColumns) - } - thirdID, found := testColumns["third_id"] - if !found { - t.Fatalf("Expected to find column 'third_id' metadata but there was only %v", testColumns) - } - - if firstID.Kind != PARTITION_KEY { - t.Errorf("Expected %s column kind to be '%s' but it was '%s'", firstID.Name, PARTITION_KEY, firstID.Kind) - } - if secondID.Kind != CLUSTERING_KEY { - t.Errorf("Expected %s column kind to be '%s' but it was '%s'", secondID.Name, CLUSTERING_KEY, secondID.Kind) - } - if thirdID.Kind != REGULAR { - t.Errorf("Expected %s column kind to be '%s' but it was '%s'", thirdID.Name, REGULAR, thirdID.Kind) - } - - if thirdID.Index.Name != "index_column_metadata" { - t.Errorf("Expected %s column index name to be 'index_column_metadata' but it was '%s'", thirdID.Name, thirdID.Index.Name) - } - } -} - -// Integration test of querying and composition the keyspace metadata -func TestKeyspaceMetadata(t *testing.T) { - session := createSession(t) - defer session.Close() - - if err := createTable(session, "CREATE TABLE test_metadata (first_id int, second_id int, third_id int, PRIMARY KEY (first_id, second_id))"); err != nil { - t.Fatalf("failed to create table with error '%v'", err) - } - - if err := session.Query("CREATE INDEX index_metadata ON test_metadata ( third_id )").Exec(); err != nil { - t.Fatalf("failed to create index with err: %v", err) - } - - keyspaceMetadata, err := session.KeyspaceMetadata("gocql_test") - if err != nil { - t.Fatalf("failed to query keyspace metadata with err: %v", err) - } - if keyspaceMetadata == nil { - t.Fatal("expected the keyspace metadata to not be nil, but it was nil") - } - if keyspaceMetadata.Name != session.cfg.Keyspace { - t.Fatalf("Expected the keyspace name to be %s but was %s", session.cfg.Keyspace, keyspaceMetadata.Name) - } - if len(keyspaceMetadata.Tables) == 0 { - t.Errorf("Expected tables but there were none") - } - - tableMetadata, found := keyspaceMetadata.Tables["test_metadata"] - if !found { - t.Fatalf("failed to find the test_metadata table metadata") - } - - if len(tableMetadata.PartitionKey) != 1 { - t.Errorf("expected partition key length of 1, but was %d", len(tableMetadata.PartitionKey)) - } - for i, column := range tableMetadata.PartitionKey { - if column == nil { - t.Errorf("partition key column metadata at index %d was nil", i) - } - } - if tableMetadata.PartitionKey[0].Name != "first_id" { - t.Errorf("Expected the first partition key column to be 'first_id' but was '%s'", tableMetadata.PartitionKey[0].Name) - } - if len(tableMetadata.ClusteringColumns) != 1 { - t.Fatalf("expected clustering columns length of 1, but was %d", len(tableMetadata.ClusteringColumns)) - } - for i, column := range tableMetadata.ClusteringColumns { - if column == nil { - t.Fatalf("clustering column metadata at index %d was nil", i) - } - } - if tableMetadata.ClusteringColumns[0].Name != "second_id" { - t.Errorf("Expected the first clustering column to be 'second_id' but was '%s'", tableMetadata.ClusteringColumns[0].Name) - } - thirdColumn, found := tableMetadata.Columns["third_id"] - if !found { - t.Fatalf("Expected a column definition for 'third_id'") - } - if thirdColumn.Index.Name != "index_metadata" { - t.Errorf("Expected column index named 'index_metadata' but was '%s'", thirdColumn.Index.Name) - } -} - -// Integration test of the routing key calculation -func TestRoutingKey(t *testing.T) { - session := createSession(t) - defer session.Close() - - if err := createTable(session, "CREATE TABLE test_single_routing_key (first_id int, second_id int, PRIMARY KEY (first_id, second_id))"); err != nil { - t.Fatalf("failed to create table with error '%v'", err) - } - if err := createTable(session, "CREATE TABLE test_composite_routing_key (first_id int, second_id int, PRIMARY KEY ((first_id, second_id)))"); err != nil { - t.Fatalf("failed to create table with error '%v'", err) - } - - routingKeyInfo, err := session.routingKeyInfo("SELECT * FROM test_single_routing_key WHERE second_id=? AND first_id=?") - if err != nil { - t.Fatalf("failed to get routing key info due to error: %v", err) - } - if routingKeyInfo == nil { - t.Fatal("Expected routing key info, but was nil") - } - if len(routingKeyInfo.indexes) != 1 { - t.Fatalf("Expected routing key indexes length to be 1 but was %d", len(routingKeyInfo.indexes)) - } - if routingKeyInfo.indexes[0] != 1 { - t.Errorf("Expected routing key index[0] to be 1 but was %d", routingKeyInfo.indexes[0]) - } - if len(routingKeyInfo.types) != 1 { - t.Fatalf("Expected routing key types length to be 1 but was %d", len(routingKeyInfo.types)) - } - if routingKeyInfo.types[0] == nil { - t.Fatal("Expected routing key types[0] to be non-nil") - } - if routingKeyInfo.types[0].Type() != TypeInt { - t.Fatalf("Expected routing key types[0].Type to be %v but was %v", TypeInt, routingKeyInfo.types[0].Type()) - } - - // verify the cache is working - routingKeyInfo, err = session.routingKeyInfo("SELECT * FROM test_single_routing_key WHERE second_id=? AND first_id=?") - if err != nil { - t.Fatalf("failed to get routing key info due to error: %v", err) - } - if len(routingKeyInfo.indexes) != 1 { - t.Fatalf("Expected routing key indexes length to be 1 but was %d", len(routingKeyInfo.indexes)) - } - if routingKeyInfo.indexes[0] != 1 { - t.Errorf("Expected routing key index[0] to be 1 but was %d", routingKeyInfo.indexes[0]) - } - if len(routingKeyInfo.types) != 1 { - t.Fatalf("Expected routing key types length to be 1 but was %d", len(routingKeyInfo.types)) - } - if routingKeyInfo.types[0] == nil { - t.Fatal("Expected routing key types[0] to be non-nil") - } - if routingKeyInfo.types[0].Type() != TypeInt { - t.Fatalf("Expected routing key types[0] to be %v but was %v", TypeInt, routingKeyInfo.types[0].Type()) - } - cacheSize := session.routingKeyInfoCache.lru.Len() - if cacheSize != 1 { - t.Errorf("Expected cache size to be 1 but was %d", cacheSize) - } - - query := session.Query("SELECT * FROM test_single_routing_key WHERE second_id=? AND first_id=?", 1, 2) - routingKey, err := query.GetRoutingKey() - if err != nil { - t.Fatalf("Failed to get routing key due to error: %v", err) - } - expectedRoutingKey := []byte{0, 0, 0, 2} - if !reflect.DeepEqual(expectedRoutingKey, routingKey) { - t.Errorf("Expected routing key %v but was %v", expectedRoutingKey, routingKey) - } - - routingKeyInfo, err = session.routingKeyInfo("SELECT * FROM test_composite_routing_key WHERE second_id=? AND first_id=?") - if err != nil { - t.Fatalf("failed to get routing key info due to error: %v", err) - } - if routingKeyInfo == nil { - t.Fatal("Expected routing key info, but was nil") - } - if len(routingKeyInfo.indexes) != 2 { - t.Fatalf("Expected routing key indexes length to be 2 but was %d", len(routingKeyInfo.indexes)) - } - if routingKeyInfo.indexes[0] != 1 { - t.Errorf("Expected routing key index[0] to be 1 but was %d", routingKeyInfo.indexes[0]) - } - if routingKeyInfo.indexes[1] != 0 { - t.Errorf("Expected routing key index[1] to be 0 but was %d", routingKeyInfo.indexes[1]) - } - if len(routingKeyInfo.types) != 2 { - t.Fatalf("Expected routing key types length to be 1 but was %d", len(routingKeyInfo.types)) - } - if routingKeyInfo.types[0] == nil { - t.Fatal("Expected routing key types[0] to be non-nil") - } - if routingKeyInfo.types[0].Type() != TypeInt { - t.Fatalf("Expected routing key types[0] to be %v but was %v", TypeInt, routingKeyInfo.types[0].Type()) - } - if routingKeyInfo.types[1] == nil { - t.Fatal("Expected routing key types[1] to be non-nil") - } - if routingKeyInfo.types[1].Type() != TypeInt { - t.Fatalf("Expected routing key types[0] to be %v but was %v", TypeInt, routingKeyInfo.types[1].Type()) - } - - query = session.Query("SELECT * FROM test_composite_routing_key WHERE second_id=? AND first_id=?", 1, 2) - routingKey, err = query.GetRoutingKey() - if err != nil { - t.Fatalf("Failed to get routing key due to error: %v", err) - } - expectedRoutingKey = []byte{0, 4, 0, 0, 0, 2, 0, 0, 4, 0, 0, 0, 1, 0} - if !reflect.DeepEqual(expectedRoutingKey, routingKey) { - t.Errorf("Expected routing key %v but was %v", expectedRoutingKey, routingKey) - } - - // verify the cache is working - cacheSize = session.routingKeyInfoCache.lru.Len() - if cacheSize != 2 { - t.Errorf("Expected cache size to be 2 but was %d", cacheSize) - } -} - -// Integration test of the token-aware policy-based connection pool -func TestTokenAwareConnPool(t *testing.T) { - cluster := createCluster() - cluster.ConnPoolType = NewTokenAwareConnPool - cluster.DiscoverHosts = true - - // Drop and re-create the keyspace once. Different tests should use their own - // individual tables, but can assume that the table does not exist before. - initOnce.Do(func() { - createKeyspace(t, cluster, "gocql_test") - }) - - cluster.Keyspace = "gocql_test" - session, err := cluster.CreateSession() - if err != nil { - t.Fatal("createSession:", err) - } - defer session.Close() - - if *clusterSize > 1 { - // wait for autodiscovery to update the pool with the list of known hosts - time.Sleep(*flagAutoWait) - } - - if session.Pool.Size() != cluster.NumConns*len(cluster.Hosts) { - t.Errorf("Expected pool size %d but was %d", cluster.NumConns*len(cluster.Hosts), session.Pool.Size()) - } - - if err := createTable(session, "CREATE TABLE test_token_aware (id int, data text, PRIMARY KEY (id))"); err != nil { - t.Fatalf("failed to create test_token_aware table with err: %v", err) - } - query := session.Query("INSERT INTO test_token_aware (id, data) VALUES (?,?)", 42, "8 * 6 =") - if err := query.Exec(); err != nil { - t.Fatalf("failed to insert with err: %v", err) - } - query = session.Query("SELECT data FROM test_token_aware where id = ?", 42).Consistency(One) - iter := query.Iter() - var data string - if !iter.Scan(&data) { - t.Error("failed to scan data") - } - if err := iter.Close(); err != nil { - t.Errorf("iter failed with err: %v", err) - } - - // TODO add verification that the query went to the correct host -} - -type frameWriterFunc func(framer *framer, streamID int) error - -func (f frameWriterFunc) writeFrame(framer *framer, streamID int) error { - return f(framer, streamID) -} - -func TestStream0(t *testing.T) { - session := createSession(t) - defer session.Close() - - var conn *Conn - for i := 0; i < 5; i++ { - if conn != nil { - break - } - - conn = session.Pool.Pick(nil) - } - - if conn == nil { - t.Fatal("no connections available in the pool") - } - - writer := frameWriterFunc(func(f *framer, streamID int) error { - if streamID == 0 { - t.Fatal("should not use stream 0 for requests") - } - f.writeHeader(0, opError, streamID) - f.writeString("i am a bad frame") - f.wbuf[0] = 0xFF - return f.finishWrite() - }) - - const expErr = "gocql: error on stream 0:" - // need to write out an invalid frame, which we need a connection to do - frame, err := conn.exec(writer, nil) - if err == nil { - t.Fatal("expected to get an error on stream 0") - } else if !strings.HasPrefix(err.Error(), expErr) { - t.Fatalf("expected to get error prefix %q got %q", expErr, err.Error()) - } else if frame != nil { - t.Fatalf("expected to get nil frame got %+v", frame) - } -} - -func TestNegativeStream(t *testing.T) { - session := createSession(t) - defer session.Close() - - var conn *Conn - for i := 0; i < 5; i++ { - if conn != nil { - break - } - - conn = session.Pool.Pick(nil) - } - - if conn == nil { - t.Fatal("no connections available in the pool") - } - - const stream = -50 - writer := frameWriterFunc(func(f *framer, streamID int) error { - f.writeHeader(0, opOptions, stream) - return f.finishWrite() - }) - - frame, err := conn.exec(writer, nil) - if err == nil { - t.Fatalf("expected to get an error on stream %d", stream) - } else if frame != nil { - t.Fatalf("expected to get nil frame got %+v", frame) - } -} diff --git a/Godeps/_workspace/src/github.com/gocql/gocql/cluster.go b/Godeps/_workspace/src/github.com/gocql/gocql/cluster.go index 94b1bc486..817cbeb41 100644 --- a/Godeps/_workspace/src/github.com/gocql/gocql/cluster.go +++ b/Godeps/_workspace/src/github.com/gocql/gocql/cluster.go @@ -9,7 +9,7 @@ import ( "sync" "time" - "github.com/golang/groupcache/lru" + "github.com/gocql/gocql/lru" ) const defaultMaxPreparedStmts = 1000 diff --git a/Godeps/_workspace/src/github.com/gocql/gocql/compressor_test.go b/Godeps/_workspace/src/github.com/gocql/gocql/compressor_test.go deleted file mode 100644 index cbf16a468..000000000 --- a/Godeps/_workspace/src/github.com/gocql/gocql/compressor_test.go +++ /dev/null @@ -1,40 +0,0 @@ -// +build all unit - -package gocql - -import ( - "bytes" - "testing" - - "github.com/golang/snappy" -) - -func TestSnappyCompressor(t *testing.T) { - c := SnappyCompressor{} - if c.Name() != "snappy" { - t.Fatalf("expected name to be 'snappy', got %v", c.Name()) - } - - str := "My Test String" - //Test Encoding - expected := snappy.Encode(nil, []byte(str)) - if res, err := c.Encode([]byte(str)); err != nil { - t.Fatalf("failed to encode '%v' with error %v", str, err) - } else if bytes.Compare(expected, res) != 0 { - t.Fatal("failed to match the expected encoded value with the result encoded value.") - } - - val, err := c.Encode([]byte(str)) - if err != nil { - t.Fatalf("failed to encode '%v' with error '%v'", str, err) - } - - //Test Decoding - if expected, err := snappy.Decode(nil, val); err != nil { - t.Fatalf("failed to decode '%v' with error %v", val, err) - } else if res, err := c.Decode(val); err != nil { - t.Fatalf("failed to decode '%v' with error %v", val, err) - } else if bytes.Compare(expected, res) != 0 { - t.Fatal("failed to match the expected decoded value with the result decoded value.") - } -} diff --git a/Godeps/_workspace/src/github.com/gocql/gocql/conn.go b/Godeps/_workspace/src/github.com/gocql/gocql/conn.go index cec77c3f6..618cebdf2 100644 --- a/Godeps/_workspace/src/github.com/gocql/gocql/conn.go +++ b/Godeps/_workspace/src/github.com/gocql/gocql/conn.go @@ -144,7 +144,7 @@ func Connect(addr string, cfg ConnConfig, errorHandler ConnErrorHandler) (*Conn, } // going to default to proto 2 - if cfg.ProtoVersion < protoVersion1 || cfg.ProtoVersion > protoVersion3 { + if cfg.ProtoVersion < protoVersion1 || cfg.ProtoVersion > protoVersion4 { log.Printf("unsupported protocol version: %d using 2\n", cfg.ProtoVersion) cfg.ProtoVersion = 2 } @@ -462,12 +462,25 @@ func (c *Conn) exec(req frameWriter, tracer Tracer) (frame, error) { err := req.writeFrame(framer, stream) if err != nil { + // I think this is the correct thing to do, im not entirely sure. It is not + // ideal as readers might still get some data, but they probably wont. + // Here we need to be careful as the stream is not available and if all + // writes just timeout or fail then the pool might use this connection to + // send a frame on, with all the streams used up and not returned. + c.closeWithError(err) return nil, err } select { case err := <-call.resp: if err != nil { + if !c.Closed() { + // if the connection is closed then we cant release the stream, + // this is because the request is still outstanding and we have + // been handed another error from another stream which caused the + // connection to close. + c.releaseStream(stream) + } return nil, err } case <-time.After(c.timeout): @@ -633,7 +646,7 @@ func (c *Conn) executeQuery(qry *Query) *Iter { rows: x.rows, } - if len(x.meta.pagingState) > 0 { + if len(x.meta.pagingState) > 0 && !qry.disableAutoPage { iter.next = &nextIter{ qry: *qry, pos: int((1 - qry.prefetch) * float64(len(iter.rows))), @@ -646,7 +659,7 @@ func (c *Conn) executeQuery(qry *Query) *Iter { } return iter - case *resultKeyspaceFrame, *resultSchemaChangeFrame: + case *resultKeyspaceFrame, *resultSchemaChangeFrame, *schemaChangeKeyspace, *schemaChangeTable: return &Iter{} case *RequestErrUnprepared: stmtsLRU.Lock() @@ -661,7 +674,7 @@ func (c *Conn) executeQuery(qry *Query) *Iter { case error: return &Iter{err: x} default: - return &Iter{err: NewErrProtocol("Unknown type in response to execute query: %s", x)} + return &Iter{err: NewErrProtocol("Unknown type in response to execute query (%T): %s", x, x)} } } diff --git a/Godeps/_workspace/src/github.com/gocql/gocql/conn_test.go b/Godeps/_workspace/src/github.com/gocql/gocql/conn_test.go deleted file mode 100644 index 85aea6437..000000000 --- a/Godeps/_workspace/src/github.com/gocql/gocql/conn_test.go +++ /dev/null @@ -1,817 +0,0 @@ -// Copyright (c) 2012 The gocql Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. -// +build all unit - -package gocql - -import ( - "crypto/tls" - "crypto/x509" - "fmt" - "io" - "io/ioutil" - "net" - "strings" - "sync" - "sync/atomic" - "testing" - "time" -) - -const ( - defaultProto = protoVersion2 -) - -func TestJoinHostPort(t *testing.T) { - tests := map[string]string{ - "127.0.0.1:0": JoinHostPort("127.0.0.1", 0), - "127.0.0.1:1": JoinHostPort("127.0.0.1:1", 9142), - "[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:0": JoinHostPort("2001:0db8:85a3:0000:0000:8a2e:0370:7334", 0), - "[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:1": JoinHostPort("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:1", 9142), - } - for k, v := range tests { - if k != v { - t.Fatalf("expected '%v', got '%v'", k, v) - } - } -} - -func TestSimple(t *testing.T) { - srv := NewTestServer(t, defaultProto) - defer srv.Stop() - - cluster := NewCluster(srv.Address) - cluster.ProtoVersion = int(defaultProto) - db, err := cluster.CreateSession() - if err != nil { - t.Errorf("0x%x: NewCluster: %v", defaultProto, err) - return - } - - if err := db.Query("void").Exec(); err != nil { - t.Errorf("0x%x: %v", defaultProto, err) - } -} - -func TestSSLSimple(t *testing.T) { - srv := NewSSLTestServer(t, defaultProto) - defer srv.Stop() - - db, err := createTestSslCluster(srv.Address, defaultProto, true).CreateSession() - if err != nil { - t.Fatalf("0x%x: NewCluster: %v", defaultProto, err) - } - - if err := db.Query("void").Exec(); err != nil { - t.Fatalf("0x%x: %v", defaultProto, err) - } -} - -func TestSSLSimpleNoClientCert(t *testing.T) { - srv := NewSSLTestServer(t, defaultProto) - defer srv.Stop() - - db, err := createTestSslCluster(srv.Address, defaultProto, false).CreateSession() - if err != nil { - t.Fatalf("0x%x: NewCluster: %v", defaultProto, err) - } - - if err := db.Query("void").Exec(); err != nil { - t.Fatalf("0x%x: %v", defaultProto, err) - } -} - -func createTestSslCluster(hosts string, proto uint8, useClientCert bool) *ClusterConfig { - cluster := NewCluster(hosts) - sslOpts := &SslOptions{ - CaPath: "testdata/pki/ca.crt", - EnableHostVerification: false, - } - if useClientCert { - sslOpts.CertPath = "testdata/pki/gocql.crt" - sslOpts.KeyPath = "testdata/pki/gocql.key" - } - cluster.SslOpts = sslOpts - cluster.ProtoVersion = int(proto) - return cluster -} - -func TestClosed(t *testing.T) { - t.Skip("Skipping the execution of TestClosed for now to try to concentrate on more important test failures on Travis") - - srv := NewTestServer(t, defaultProto) - defer srv.Stop() - - cluster := NewCluster(srv.Address) - cluster.ProtoVersion = int(defaultProto) - - session, err := cluster.CreateSession() - defer session.Close() - if err != nil { - t.Errorf("0x%x: NewCluster: %v", defaultProto, err) - return - } - - if err := session.Query("void").Exec(); err != ErrSessionClosed { - t.Errorf("0x%x: expected %#v, got %#v", defaultProto, ErrSessionClosed, err) - return - } -} - -func newTestSession(addr string, proto uint8) (*Session, error) { - cluster := NewCluster(addr) - cluster.ProtoVersion = int(proto) - return cluster.CreateSession() -} - -func TestTimeout(t *testing.T) { - - srv := NewTestServer(t, defaultProto) - defer srv.Stop() - - db, err := newTestSession(srv.Address, defaultProto) - if err != nil { - t.Errorf("NewCluster: %v", err) - return - } - defer db.Close() - - go func() { - <-time.After(2 * time.Second) - t.Errorf("no timeout") - }() - - if err := db.Query("kill").Exec(); err == nil { - t.Errorf("expected error") - } -} - -// TestQueryRetry will test to make sure that gocql will execute -// the exact amount of retry queries designated by the user. -func TestQueryRetry(t *testing.T) { - srv := NewTestServer(t, defaultProto) - defer srv.Stop() - - db, err := newTestSession(srv.Address, defaultProto) - if err != nil { - t.Fatalf("NewCluster: %v", err) - } - defer db.Close() - - go func() { - <-time.After(5 * time.Second) - t.Fatalf("no timeout") - }() - rt := &SimpleRetryPolicy{NumRetries: 1} - - qry := db.Query("kill").RetryPolicy(rt) - if err := qry.Exec(); err == nil { - t.Fatalf("expected error") - } - - requests := atomic.LoadInt64(&srv.nKillReq) - attempts := qry.Attempts() - if requests != int64(attempts) { - t.Fatalf("expected requests %v to match query attemps %v", requests, attempts) - } - - //Minus 1 from the requests variable since there is the initial query attempt - if requests-1 != int64(rt.NumRetries) { - t.Fatalf("failed to retry the query %v time(s). Query executed %v times", rt.NumRetries, requests-1) - } -} - -func TestSimplePoolRoundRobin(t *testing.T) { - servers := make([]*TestServer, 5) - addrs := make([]string, len(servers)) - for n := 0; n < len(servers); n++ { - servers[n] = NewTestServer(t, defaultProto) - addrs[n] = servers[n].Address - defer servers[n].Stop() - } - cluster := NewCluster(addrs...) - cluster.ProtoVersion = defaultProto - - db, err := cluster.CreateSession() - time.Sleep(1 * time.Second) // Sleep to allow the Cluster.fillPool to complete - - if err != nil { - t.Fatalf("NewCluster: %v", err) - } - - var wg sync.WaitGroup - wg.Add(5) - for n := 0; n < 5; n++ { - go func() { - for j := 0; j < 5; j++ { - if err := db.Query("void").Exec(); err != nil { - t.Fatal(err) - } - } - wg.Done() - }() - } - wg.Wait() - - diff := 0 - for n := 1; n < len(servers); n++ { - d := 0 - if servers[n].nreq > servers[n-1].nreq { - d = int(servers[n].nreq - servers[n-1].nreq) - } else { - d = int(servers[n-1].nreq - servers[n].nreq) - } - if d > diff { - diff = d - } - } - - if diff > 0 { - t.Errorf("Expected 0 difference in usage but was %d", diff) - } -} - -func TestConnClosing(t *testing.T) { - t.Skip("Skipping until test can be ran reliably") - - srv := NewTestServer(t, protoVersion2) - defer srv.Stop() - - db, err := NewCluster(srv.Address).CreateSession() - if err != nil { - t.Errorf("NewCluster: %v", err) - } - defer db.Close() - - numConns := db.cfg.NumConns - count := db.cfg.NumStreams * numConns - - wg := &sync.WaitGroup{} - wg.Add(count) - for i := 0; i < count; i++ { - go func(wg *sync.WaitGroup) { - wg.Done() - db.Query("kill").Exec() - }(wg) - } - - wg.Wait() - - time.Sleep(1 * time.Second) //Sleep so the fillPool can complete. - pool := db.Pool.(ConnectionPool) - conns := pool.Size() - - if conns != numConns { - t.Errorf("Expected to have %d connections but have %d", numConns, conns) - } -} - -func TestStreams_Protocol1(t *testing.T) { - srv := NewTestServer(t, protoVersion1) - defer srv.Stop() - - // TODO: these are more like session tests and should instead operate - // on a single Conn - cluster := NewCluster(srv.Address) - cluster.NumConns = 1 - cluster.ProtoVersion = 1 - - db, err := cluster.CreateSession() - if err != nil { - t.Fatal(err) - } - defer db.Close() - - var wg sync.WaitGroup - for i := 1; i < db.cfg.NumStreams; i++ { - // here were just validating that if we send NumStream request we get - // a response for every stream and the lengths for the queries are set - // correctly. - wg.Add(1) - go func() { - defer wg.Done() - if err := db.Query("void").Exec(); err != nil { - t.Error(err) - } - }() - } - wg.Wait() -} - -func TestStreams_Protocol2(t *testing.T) { - srv := NewTestServer(t, protoVersion2) - defer srv.Stop() - - // TODO: these are more like session tests and should instead operate - // on a single Conn - cluster := NewCluster(srv.Address) - cluster.NumConns = 1 - cluster.ProtoVersion = 2 - - db, err := cluster.CreateSession() - if err != nil { - t.Fatal(err) - } - defer db.Close() - - for i := 1; i < db.cfg.NumStreams; i++ { - // the test server processes each conn synchronously - // here were just validating that if we send NumStream request we get - // a response for every stream and the lengths for the queries are set - // correctly. - if err = db.Query("void").Exec(); err != nil { - t.Fatal(err) - } - } -} - -func TestStreams_Protocol3(t *testing.T) { - srv := NewTestServer(t, protoVersion3) - defer srv.Stop() - - // TODO: these are more like session tests and should instead operate - // on a single Conn - cluster := NewCluster(srv.Address) - cluster.NumConns = 1 - cluster.ProtoVersion = 3 - - db, err := cluster.CreateSession() - if err != nil { - t.Fatal(err) - } - defer db.Close() - - for i := 1; i < db.cfg.NumStreams; i++ { - // the test server processes each conn synchronously - // here were just validating that if we send NumStream request we get - // a response for every stream and the lengths for the queries are set - // correctly. - if err = db.Query("void").Exec(); err != nil { - t.Fatal(err) - } - } -} - -func BenchmarkProtocolV3(b *testing.B) { - srv := NewTestServer(b, protoVersion3) - defer srv.Stop() - - // TODO: these are more like session tests and should instead operate - // on a single Conn - cluster := NewCluster(srv.Address) - cluster.NumConns = 1 - cluster.ProtoVersion = 3 - - db, err := cluster.CreateSession() - if err != nil { - b.Fatal(err) - } - defer db.Close() - - b.ResetTimer() - b.ReportAllocs() - for i := 0; i < b.N; i++ { - if err = db.Query("void").Exec(); err != nil { - b.Fatal(err) - } - } -} - -func TestRoundRobinConnPoolRoundRobin(t *testing.T) { - // create 5 test servers - servers := make([]*TestServer, 5) - addrs := make([]string, len(servers)) - for n := 0; n < len(servers); n++ { - servers[n] = NewTestServer(t, defaultProto) - addrs[n] = servers[n].Address - defer servers[n].Stop() - } - - // create a new cluster using the policy-based round robin conn pool - cluster := NewCluster(addrs...) - cluster.ConnPoolType = NewRoundRobinConnPool - - db, err := cluster.CreateSession() - if err != nil { - t.Fatalf("failed to create a new session: %v", err) - } - - // Sleep to allow the pool to fill - time.Sleep(100 * time.Millisecond) - - // run concurrent queries against the pool, server usage should - // be even - var wg sync.WaitGroup - wg.Add(5) - for n := 0; n < 5; n++ { - go func() { - for j := 0; j < 5; j++ { - if err := db.Query("void").Exec(); err != nil { - t.Errorf("Query failed with error: %v", err) - } - } - wg.Done() - }() - } - wg.Wait() - - db.Close() - - // wait for the pool to drain - time.Sleep(100 * time.Millisecond) - size := db.Pool.Size() - if size != 0 { - t.Errorf("connection pool did not drain, still contains %d connections", size) - } - - // verify that server usage is even - diff := 0 - for n := 1; n < len(servers); n++ { - d := 0 - if servers[n].nreq > servers[n-1].nreq { - d = int(servers[n].nreq - servers[n-1].nreq) - } else { - d = int(servers[n-1].nreq - servers[n].nreq) - } - if d > diff { - diff = d - } - } - - if diff > 0 { - t.Errorf("expected 0 difference in usage but was %d", diff) - } -} - -// This tests that the policy connection pool handles SSL correctly -func TestPolicyConnPoolSSL(t *testing.T) { - srv := NewSSLTestServer(t, defaultProto) - defer srv.Stop() - - cluster := createTestSslCluster(srv.Address, defaultProto, true) - cluster.ConnPoolType = NewRoundRobinConnPool - - db, err := cluster.CreateSession() - if err != nil { - t.Fatalf("failed to create new session: %v", err) - } - - if err := db.Query("void").Exec(); err != nil { - t.Errorf("query failed due to error: %v", err) - } - - db.Close() - - // wait for the pool to drain - time.Sleep(100 * time.Millisecond) - size := db.Pool.Size() - if size != 0 { - t.Errorf("connection pool did not drain, still contains %d connections", size) - } -} - -func TestQueryTimeout(t *testing.T) { - srv := NewTestServer(t, defaultProto) - defer srv.Stop() - - cluster := NewCluster(srv.Address) - // Set the timeout arbitrarily low so that the query hits the timeout in a - // timely manner. - cluster.Timeout = 1 * time.Millisecond - - db, err := cluster.CreateSession() - if err != nil { - t.Errorf("NewCluster: %v", err) - } - defer db.Close() - - ch := make(chan error, 1) - - go func() { - err := db.Query("timeout").Exec() - if err != nil { - ch <- err - return - } - t.Errorf("err was nil, expected to get a timeout after %v", db.cfg.Timeout) - }() - - select { - case err := <-ch: - if err != ErrTimeoutNoResponse { - t.Fatalf("expected to get %v for timeout got %v", ErrTimeoutNoResponse, err) - } - case <-time.After(10*time.Millisecond + db.cfg.Timeout): - // ensure that the query goroutines have been scheduled - t.Fatalf("query did not timeout after %v", db.cfg.Timeout) - } -} - -func TestQueryTimeoutReuseStream(t *testing.T) { - srv := NewTestServer(t, defaultProto) - defer srv.Stop() - - cluster := NewCluster(srv.Address) - // Set the timeout arbitrarily low so that the query hits the timeout in a - // timely manner. - cluster.Timeout = 1 * time.Millisecond - cluster.NumConns = 1 - cluster.NumStreams = 1 - - db, err := cluster.CreateSession() - if err != nil { - t.Fatalf("NewCluster: %v", err) - } - defer db.Close() - - db.Query("slow").Exec() - - err = db.Query("void").Exec() - if err != nil { - t.Fatal(err) - } -} - -func TestQueryTimeoutClose(t *testing.T) { - srv := NewTestServer(t, defaultProto) - defer srv.Stop() - - cluster := NewCluster(srv.Address) - // Set the timeout arbitrarily low so that the query hits the timeout in a - // timely manner. - cluster.Timeout = 1000 * time.Millisecond - cluster.NumConns = 1 - cluster.NumStreams = 1 - - db, err := cluster.CreateSession() - if err != nil { - t.Fatalf("NewCluster: %v", err) - } - - ch := make(chan error) - go func() { - err := db.Query("timeout").Exec() - ch <- err - }() - // ensure that the above goroutine gets sheduled - time.Sleep(50 * time.Millisecond) - - db.Close() - select { - case err = <-ch: - case <-time.After(1 * time.Second): - t.Fatal("timedout waiting to get a response once cluster is closed") - } - - if err != ErrConnectionClosed { - t.Fatalf("expected to get %v got %v", ErrConnectionClosed, err) - } -} - -func TestExecPanic(t *testing.T) { - t.Skip("test can cause unrelated failures, skipping until it can be fixed.") - srv := NewTestServer(t, defaultProto) - defer srv.Stop() - - cluster := NewCluster(srv.Address) - // Set the timeout arbitrarily low so that the query hits the timeout in a - // timely manner. - cluster.Timeout = 5 * time.Millisecond - cluster.NumConns = 1 - // cluster.NumStreams = 1 - - db, err := cluster.CreateSession() - if err != nil { - t.Fatal(err) - } - defer db.Close() - - streams := db.cfg.NumStreams - - wg := &sync.WaitGroup{} - wg.Add(streams) - for i := 0; i < streams; i++ { - go func() { - defer wg.Done() - q := db.Query("void") - for { - if err := q.Exec(); err != nil { - return - } - } - }() - } - - wg.Add(1) - - go func() { - defer wg.Done() - for i := 0; i < int(TimeoutLimit); i++ { - db.Query("timeout").Exec() - } - }() - - wg.Wait() - - time.Sleep(500 * time.Millisecond) -} - -func NewTestServer(t testing.TB, protocol uint8) *TestServer { - laddr, err := net.ResolveTCPAddr("tcp", "127.0.0.1:0") - if err != nil { - t.Fatal(err) - } - - listen, err := net.ListenTCP("tcp", laddr) - if err != nil { - t.Fatal(err) - } - - headerSize := 8 - if protocol > protoVersion2 { - headerSize = 9 - } - - srv := &TestServer{ - Address: listen.Addr().String(), - listen: listen, - t: t, - protocol: protocol, - headerSize: headerSize, - quit: make(chan struct{}), - } - - go srv.serve() - - return srv -} - -func NewSSLTestServer(t testing.TB, protocol uint8) *TestServer { - pem, err := ioutil.ReadFile("testdata/pki/ca.crt") - certPool := x509.NewCertPool() - if !certPool.AppendCertsFromPEM(pem) { - t.Errorf("Failed parsing or appending certs") - } - mycert, err := tls.LoadX509KeyPair("testdata/pki/cassandra.crt", "testdata/pki/cassandra.key") - if err != nil { - t.Errorf("could not load cert") - } - config := &tls.Config{ - Certificates: []tls.Certificate{mycert}, - RootCAs: certPool, - } - listen, err := tls.Listen("tcp", "127.0.0.1:0", config) - if err != nil { - t.Fatal(err) - } - - headerSize := 8 - if protocol > protoVersion2 { - headerSize = 9 - } - - srv := &TestServer{ - Address: listen.Addr().String(), - listen: listen, - t: t, - protocol: protocol, - headerSize: headerSize, - quit: make(chan struct{}), - } - go srv.serve() - return srv -} - -type TestServer struct { - Address string - t testing.TB - nreq uint64 - listen net.Listener - nKillReq int64 - compressor Compressor - - protocol byte - headerSize int - - quit chan struct{} -} - -func (srv *TestServer) serve() { - defer srv.listen.Close() - for { - conn, err := srv.listen.Accept() - if err != nil { - break - } - go func(conn net.Conn) { - defer conn.Close() - for { - framer, err := srv.readFrame(conn) - if err != nil { - if err == io.EOF { - return - } - - srv.t.Error(err) - return - } - - atomic.AddUint64(&srv.nreq, 1) - - go srv.process(framer) - } - }(conn) - } -} - -func (srv *TestServer) Stop() { - srv.listen.Close() - close(srv.quit) -} - -func (srv *TestServer) process(f *framer) { - head := f.header - if head == nil { - srv.t.Error("process frame with a nil header") - return - } - - switch head.op { - case opStartup: - f.writeHeader(0, opReady, head.stream) - case opOptions: - f.writeHeader(0, opSupported, head.stream) - f.writeShort(0) - case opQuery: - query := f.readLongString() - first := query - if n := strings.Index(query, " "); n > 0 { - first = first[:n] - } - switch strings.ToLower(first) { - case "kill": - atomic.AddInt64(&srv.nKillReq, 1) - f.writeHeader(0, opError, head.stream) - f.writeInt(0x1001) - f.writeString("query killed") - case "use": - f.writeInt(resultKindKeyspace) - f.writeString(strings.TrimSpace(query[3:])) - case "void": - f.writeHeader(0, opResult, head.stream) - f.writeInt(resultKindVoid) - case "timeout": - <-srv.quit - return - case "slow": - go func() { - f.writeHeader(0, opResult, head.stream) - f.writeInt(resultKindVoid) - f.wbuf[0] = srv.protocol | 0x80 - select { - case <-srv.quit: - case <-time.After(50 * time.Millisecond): - f.finishWrite() - } - }() - return - default: - f.writeHeader(0, opResult, head.stream) - f.writeInt(resultKindVoid) - } - default: - f.writeHeader(0, opError, head.stream) - f.writeInt(0) - f.writeString("not supported") - } - - f.wbuf[0] = srv.protocol | 0x80 - - if err := f.finishWrite(); err != nil { - srv.t.Error(err) - } -} - -func (srv *TestServer) readFrame(conn net.Conn) (*framer, error) { - buf := make([]byte, srv.headerSize) - head, err := readHeader(conn, buf) - if err != nil { - return nil, err - } - framer := newFramer(conn, conn, nil, srv.protocol) - - err = framer.readFrame(&head) - if err != nil { - return nil, err - } - - // should be a request frame - if head.version.response() { - return nil, fmt.Errorf("expected to read a request frame got version: %v", head.version) - } else if head.version.version() != srv.protocol { - return nil, fmt.Errorf("expected to read protocol version 0x%x got 0x%x", srv.protocol, head.version.version()) - } - - return framer, nil -} diff --git a/Godeps/_workspace/src/github.com/gocql/gocql/connectionpool.go b/Godeps/_workspace/src/github.com/gocql/gocql/connectionpool.go index 9f9904be1..512206286 100644 --- a/Godeps/_workspace/src/github.com/gocql/gocql/connectionpool.go +++ b/Godeps/_workspace/src/github.com/gocql/gocql/connectionpool.go @@ -22,7 +22,7 @@ import ( Purpose The connection pool in gocql opens and closes connections as well as selects an available connection -for gocql to execute a query against. The pool is also respnsible for handling connection errors that +for gocql to execute a query against. The pool is also responsible for handling connection errors that are caught by the connection experiencing the error. A connection pool should make a copy of the variables used from the ClusterConfig provided to the pool diff --git a/Godeps/_workspace/src/github.com/gocql/gocql/errors.go b/Godeps/_workspace/src/github.com/gocql/gocql/errors.go index 1f959dc07..cd7124e8f 100644 --- a/Godeps/_workspace/src/github.com/gocql/gocql/errors.go +++ b/Godeps/_workspace/src/github.com/gocql/gocql/errors.go @@ -3,21 +3,23 @@ package gocql import "fmt" const ( - errServer = 0x0000 - errProtocol = 0x000A - errCredentials = 0x0100 - errUnavailable = 0x1000 - errOverloaded = 0x1001 - errBootstrapping = 0x1002 - errTruncate = 0x1003 - errWriteTimeout = 0x1100 - errReadTimeout = 0x1200 - errSyntax = 0x2000 - errUnauthorized = 0x2100 - errInvalid = 0x2200 - errConfig = 0x2300 - errAlreadyExists = 0x2400 - errUnprepared = 0x2500 + errServer = 0x0000 + errProtocol = 0x000A + errCredentials = 0x0100 + errUnavailable = 0x1000 + errOverloaded = 0x1001 + errBootstrapping = 0x1002 + errTruncate = 0x1003 + errWriteTimeout = 0x1100 + errReadTimeout = 0x1200 + errReadFailure = 0x1300 + errFunctionFailure = 0x1400 + errSyntax = 0x2000 + errUnauthorized = 0x2100 + errInvalid = 0x2200 + errConfig = 0x2300 + errAlreadyExists = 0x2400 + errUnprepared = 0x2500 ) type RequestError interface { @@ -86,3 +88,19 @@ type RequestErrUnprepared struct { errorFrame StatementId []byte } + +type RequestErrReadFailure struct { + errorFrame + Consistency Consistency + Received int + BlockFor int + NumFailures int + DataPresent bool +} + +type RequestErrFunctionFailure struct { + errorFrame + Keyspace string + Function string + ArgTypes []string +} diff --git a/Godeps/_workspace/src/github.com/gocql/gocql/errors_test.go b/Godeps/_workspace/src/github.com/gocql/gocql/errors_test.go deleted file mode 100644 index 8c4a588df..000000000 --- a/Godeps/_workspace/src/github.com/gocql/gocql/errors_test.go +++ /dev/null @@ -1,29 +0,0 @@ -// +build all integration - -package gocql - -import ( - "testing" -) - -func TestErrorsParse(t *testing.T) { - session := createSession(t) - defer session.Close() - - if err := createTable(session, `CREATE TABLE errors_parse (id int primary key)`); err != nil { - t.Fatal("create:", err) - } - - if err := createTable(session, `CREATE TABLE errors_parse (id int primary key)`); err == nil { - t.Fatal("Should have gotten already exists error from cassandra server.") - } else { - switch e := err.(type) { - case *RequestErrAlreadyExists: - if e.Table != "errors_parse" { - t.Fatal("Failed to parse error response from cassandra for ErrAlreadyExists.") - } - default: - t.Fatal("Failed to parse error response from cassandra for ErrAlreadyExists.") - } - } -} diff --git a/Godeps/_workspace/src/github.com/gocql/gocql/frame.go b/Godeps/_workspace/src/github.com/gocql/gocql/frame.go index ba1ad2e47..5100528bb 100644 --- a/Godeps/_workspace/src/github.com/gocql/gocql/frame.go +++ b/Godeps/_workspace/src/github.com/gocql/gocql/frame.go @@ -9,6 +9,7 @@ import ( "fmt" "io" "io/ioutil" + "log" "net" "runtime" "sync" @@ -21,6 +22,7 @@ const ( protoVersion1 = 0x01 protoVersion2 = 0x02 protoVersion3 = 0x03 + protoVersion4 = 0x04 maxFrameSize = 256 * 1024 * 1024 ) @@ -132,8 +134,10 @@ const ( flagWithNameValues = 0x40 // header flags - flagCompress byte = 0x01 - flagTracing = 0x02 + flagCompress byte = 0x01 + flagTracing byte = 0x02 + flagCustomPayload byte = 0x04 + flagWarning byte = 0x08 ) type Consistency uint16 @@ -315,8 +319,8 @@ func readHeader(r io.Reader, p []byte) (head frameHeader, err error) { version := p[0] & protoVersionMask - if version < protoVersion1 || version > protoVersion3 { - err = fmt.Errorf("invalid version: %x", version) + if version < protoVersion1 || version > protoVersion4 { + err = fmt.Errorf("gocql: invalid version: %x", version) return } @@ -408,6 +412,14 @@ func (f *framer) parseFrame() (frame frame, err error) { f.readTrace() } + if f.header.flags&flagWarning == flagWarning { + warnings := f.readStringList() + // what to do with warnings? + for _, v := range warnings { + log.Println(v) + } + } + // asumes that the frame body has been read into rbuf switch f.header.op { case opError: @@ -490,6 +502,23 @@ func (f *framer) parseErrorFrame() frame { errorFrame: errD, StatementId: stmtId, } + case errReadFailure: + res := &RequestErrReadFailure{ + errorFrame: errD, + } + res.Consistency = f.readConsistency() + res.Received = f.readInt() + res.BlockFor = f.readInt() + res.DataPresent = f.readByte() != 0 + return res + case errFunctionFailure: + res := RequestErrFunctionFailure{ + errorFrame: errD, + } + res.Keyspace = f.readString() + res.Function = f.readString() + res.ArgTypes = f.readStringList() + return res default: return &errD } @@ -600,6 +629,10 @@ type writeStartupFrame struct { opts map[string]string } +func (w writeStartupFrame) String() string { + return fmt.Sprintf("[startup opts=%+v]", w.opts) +} + func (w *writeStartupFrame) writeFrame(framer *framer, streamID int) error { return framer.writeStartupFrame(streamID, w.opts) } @@ -689,6 +722,74 @@ func (f *framer) readTypeInfo() TypeInfo { return simple } +type preparedMetadata struct { + resultMetadata + + // proto v4+ + pkeyColumns []int +} + +func (r preparedMetadata) String() string { + return fmt.Sprintf("[paging_metadata flags=0x%x pkey=%q paging_state=% X columns=%v]", r.flags, r.pkeyColumns, r.pagingState, r.columns) +} + +func (f *framer) parsePreparedMetadata() preparedMetadata { + // TODO: deduplicate this from parseMetadata + meta := preparedMetadata{} + meta.flags = f.readInt() + + colCount := f.readInt() + if colCount < 0 { + panic(fmt.Errorf("received negative column count: %d", colCount)) + } + meta.actualColCount = colCount + + if f.proto >= protoVersion4 { + pkeyCount := f.readInt() + pkeys := make([]int, pkeyCount) + for i := 0; i < pkeyCount; i++ { + pkeys[i] = int(f.readShort()) + } + meta.pkeyColumns = pkeys + } + + if meta.flags&flagHasMorePages == flagHasMorePages { + meta.pagingState = f.readBytes() + } + + if meta.flags&flagNoMetaData == flagNoMetaData { + return meta + } + + var keyspace, table string + globalSpec := meta.flags&flagGlobalTableSpec == flagGlobalTableSpec + if globalSpec { + keyspace = f.readString() + table = f.readString() + } + + var cols []ColumnInfo + if colCount < 1000 { + // preallocate columninfo to avoid excess copying + cols = make([]ColumnInfo, colCount) + for i := 0; i < colCount; i++ { + f.readCol(&cols[i], &meta.resultMetadata, globalSpec, keyspace, table) + } + } else { + // use append, huge number of columns usually indicates a corrupt frame or + // just a huge row. + for i := 0; i < colCount; i++ { + var col ColumnInfo + f.readCol(&col, &meta.resultMetadata, globalSpec, keyspace, table) + cols = append(cols, col) + } + } + + meta.columns = cols + + return meta +} + type resultMetadata struct { flags int @@ -858,7 +959,7 @@ type resultPreparedFrame struct { frameHeader preparedID []byte - reqMeta resultMetadata + reqMeta preparedMetadata respMeta resultMetadata } @@ -866,7 +967,7 @@ func (f *framer) parseResultPrepared() frame { frame := &resultPreparedFrame{ frameHeader: *f.header, preparedID: f.readShortBytes(), - reqMeta: f.parseResultMetadata(), + reqMeta: f.parsePreparedMetadata(), } if f.proto < protoVersion2 { @@ -890,29 +991,90 @@ func (s *resultSchemaChangeFrame) String() string { return fmt.Sprintf("[result_schema_change change=%s keyspace=%s table=%s]", s.change, s.keyspace, s.table) } -func (f *framer) parseResultSchemaChange() frame { - frame := &resultSchemaChangeFrame{ - frameHeader: *f.header, - } +type schemaChangeKeyspace struct { + frameHeader + + change string + keyspace string +} + +func (f schemaChangeKeyspace) String() string { + return fmt.Sprintf("[event schema_change_keyspace change=%q keyspace=%q]", f.change, f.keyspace) +} + +type schemaChangeTable struct { + frameHeader + + change string + keyspace string + object string +} + +func (f schemaChangeTable) String() string { + return fmt.Sprintf("[event schema_change change=%q keyspace=%q object=%q]", f.change, f.keyspace, f.object) +} + +type schemaChangeFunction struct { + frameHeader + + change string + keyspace string + name string + args []string +} + +func (f *framer) parseResultSchemaChange() frame { + if f.proto <= protoVersion2 { + frame := &resultSchemaChangeFrame{ + frameHeader: *f.header, + } - if f.proto < protoVersion3 { frame.change = f.readString() frame.keyspace = f.readString() frame.table = f.readString() + + return frame } else { - // TODO: improve type representation of this - frame.change = f.readString() + change := f.readString() target := f.readString() + + // TODO: could just use a seperate type for each target switch target { case "KEYSPACE": + frame := &schemaChangeKeyspace{ + frameHeader: *f.header, + change: change, + } + frame.keyspace = f.readString() + + return frame case "TABLE", "TYPE": + frame := &schemaChangeTable{ + frameHeader: *f.header, + change: change, + } + frame.keyspace = f.readString() - frame.table = f.readString() + frame.object = f.readString() + + return frame + case "FUNCTION", "AGGREGATE": + frame := &schemaChangeFunction{ + frameHeader: *f.header, + change: change, + } + + frame.keyspace = f.readString() + frame.name = f.readString() + frame.args = f.readStringList() + + return frame + default: + panic(fmt.Errorf("gocql: unknown SCHEMA_CHANGE target: %q change: %q", target, change)) } } - return frame } type authenticateFrame struct { diff --git a/Godeps/_workspace/src/github.com/gocql/gocql/frame_test.go b/Godeps/_workspace/src/github.com/gocql/gocql/frame_test.go deleted file mode 100644 index 87dcfb9a7..000000000 --- a/Godeps/_workspace/src/github.com/gocql/gocql/frame_test.go +++ /dev/null @@ -1,98 +0,0 @@ -package gocql - -import ( - "bytes" - "testing" -) - -func TestFuzzBugs(t *testing.T) { - // these inputs are found using go-fuzz (https://github.com/dvyukov/go-fuzz) - // and should cause a panic unless fixed. - tests := [][]byte{ - []byte("00000\xa0000"), - []byte("\x8000\x0e\x00\x00\x00\x000"), - []byte("\x8000\x00\x00\x00\x00\t0000000000"), - []byte("\xa0\xff\x01\xae\xefqE\xf2\x1a"), - []byte("\x8200\b\x00\x00\x00c\x00\x00\x00\x02000\x01\x00\x00\x00\x03" + - "\x00\n0000000000\x00\x14000000" + - "00000000000000\x00\x020000" + - "\x00\a000000000\x00\x050000000" + - "\xff0000000000000000000" + - "0000000"), - []byte("\x82\xe600\x00\x00\x00\x000"), - []byte("\x8200\b\x00\x00\x00\b0\x00\x00\x00\x040000"), - []byte("\x8200\x00\x00\x00\x00\x100\x00\x00\x12\x00\x00\x0000000" + - "00000"), - []byte("\x83000\b\x00\x00\x00\x14\x00\x00\x00\x020000000" + - "000000000"), - []byte("\x83000\b\x00\x00\x000\x00\x00\x00\x04\x00\x1000000" + - "00000000000000e00000" + - "000\x800000000000000000" + - "0000000000000"), - } - - for i, test := range tests { - t.Logf("test %d input: %q", i, test) - - var bw bytes.Buffer - - r := bytes.NewReader(test) - head, err := readHeader(r, make([]byte, 9)) - if err != nil { - continue - } - - framer := newFramer(r, &bw, nil, byte(head.version)) - err = framer.readFrame(&head) - if err != nil { - continue - } - - _, err = framer.parseFrame() - if err != nil { - continue - } - - t.Errorf("(%d) expected to fail for input %q", i, test) - } -} - -func TestFrameWriteTooLong(t *testing.T) { - w := &bytes.Buffer{} - framer := newFramer(nil, w, nil, 2) - - framer.writeHeader(0, opStartup, 1) - framer.writeBytes(make([]byte, maxFrameSize+1)) - err := framer.finishWrite() - if err != ErrFrameTooBig { - t.Fatalf("expected to get %v got %v", ErrFrameTooBig, err) - } -} - -func TestFrameReadTooLong(t *testing.T) { - r := &bytes.Buffer{} - r.Write(make([]byte, maxFrameSize+1)) - // write a new header right after this frame to verify that we can read it - r.Write([]byte{0x02, 0x00, 0x00, opReady, 0x00, 0x00, 0x00, 0x00}) - - framer := newFramer(r, nil, nil, 2) - - head := frameHeader{ - version: 2, - op: opReady, - length: r.Len() - 8, - } - - err := framer.readFrame(&head) - if err != ErrFrameTooBig { - t.Fatalf("expected to get %v got %v", ErrFrameTooBig, err) - } - - head, err = readHeader(r, make([]byte, 8)) - if err != nil { - t.Fatal(err) - } - if head.op != opReady { - t.Fatalf("expected to get header %v got %v", opReady, head.op) - } -} diff --git a/Godeps/_workspace/src/github.com/gocql/gocql/helpers.go b/Godeps/_workspace/src/github.com/gocql/gocql/helpers.go index 8e1ca0a4b..08778a07e 100644 --- a/Godeps/_workspace/src/github.com/gocql/gocql/helpers.go +++ b/Godeps/_workspace/src/github.com/gocql/gocql/helpers.go @@ -50,6 +50,8 @@ func goType(t TypeInfo) reflect.Type { // what can we do here? all there is to do is to make a list of interface{} tuple := t.(TupleTypeInfo) return reflect.TypeOf(make([]interface{}, len(tuple.Elems))) + case TypeUDT: + return reflect.TypeOf(make(map[string]interface{})) default: return nil } @@ -81,7 +83,7 @@ func getApacheCassandraType(class string) Type { return TypeInt case "DateType", "TimestampType": return TypeTimestamp - case "UUIDType": + case "UUIDType", "LexicalUUIDType": return TypeUUID case "UTF8Type": return TypeVarchar diff --git a/Godeps/_workspace/src/github.com/gocql/gocql/integration.sh b/Godeps/_workspace/src/github.com/gocql/gocql/integration.sh index 543b7d1e5..c5bf5d7bc 100644 --- a/Godeps/_workspace/src/github.com/gocql/gocql/integration.sh +++ b/Godeps/_workspace/src/github.com/gocql/gocql/integration.sh @@ -47,8 +47,12 @@ function run_tests() { local proto=2 if [[ $version == 1.2.* ]]; then proto=1 + elif [[ $version == 2.0.* ]]; then + proto=2 elif [[ $version == 2.1.* ]]; then proto=3 + elif [[ $version == 2.2.* ]]; then + proto=4 fi if [ "$auth" = true ] diff --git a/Godeps/_workspace/src/github.com/gocql/gocql/lru/lru.go b/Godeps/_workspace/src/github.com/gocql/gocql/lru/lru.go new file mode 100644 index 000000000..0ad367838 --- /dev/null +++ b/Godeps/_workspace/src/github.com/gocql/gocql/lru/lru.go @@ -0,0 +1,123 @@ +/* +Copyright 2015 To gocql authors +Copyright 2013 Google Inc. + +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 lru implements an LRU cache. +package lru + +import "container/list" + +// Cache is an LRU cache. It is not safe for concurrent access. +// +// This cache has been forked from github.com/golang/groupcache/lru, but +// specialized with string keys to avoid the allocations caused by wrapping them +// in interface{}. +type Cache struct { + // MaxEntries is the maximum number of cache entries before + // an item is evicted. Zero means no limit. + MaxEntries int + + // OnEvicted optionally specificies a callback function to be + // executed when an entry is purged from the cache. + OnEvicted func(key string, value interface{}) + + ll *list.List + cache map[string]*list.Element +} + +type entry struct { + key string + value interface{} +} + +// New creates a new Cache. +// If maxEntries is zero, the cache has no limit and it's assumed +// that eviction is done by the caller. +func New(maxEntries int) *Cache { + return &Cache{ + MaxEntries: maxEntries, + ll: list.New(), + cache: make(map[string]*list.Element), + } +} + +// Add adds a value to the cache. +func (c *Cache) Add(key string, value interface{}) { + if c.cache == nil { + c.cache = make(map[string]*list.Element) + c.ll = list.New() + } + if ee, ok := c.cache[key]; ok { + c.ll.MoveToFront(ee) + ee.Value.(*entry).value = value + return + } + ele := c.ll.PushFront(&entry{key, value}) + c.cache[key] = ele + if c.MaxEntries != 0 && c.ll.Len() > c.MaxEntries { + c.RemoveOldest() + } +} + +// Get looks up a key's value from the cache. +func (c *Cache) Get(key string) (value interface{}, ok bool) { + if c.cache == nil { + return + } + if ele, hit := c.cache[key]; hit { + c.ll.MoveToFront(ele) + return ele.Value.(*entry).value, true + } + return +} + +// Remove removes the provided key from the cache. +func (c *Cache) Remove(key string) { + if c.cache == nil { + return + } + if ele, hit := c.cache[key]; hit { + c.removeElement(ele) + } +} + +// RemoveOldest removes the oldest item from the cache. +func (c *Cache) RemoveOldest() { + if c.cache == nil { + return + } + ele := c.ll.Back() + if ele != nil { + c.removeElement(ele) + } +} + +func (c *Cache) removeElement(e *list.Element) { + c.ll.Remove(e) + kv := e.Value.(*entry) + delete(c.cache, kv.key) + if c.OnEvicted != nil { + c.OnEvicted(kv.key, kv.value) + } +} + +// Len returns the number of items in the cache. +func (c *Cache) Len() int { + if c.cache == nil { + return 0 + } + return c.ll.Len() +} diff --git a/Godeps/_workspace/src/github.com/gocql/gocql/marshal.go b/Godeps/_workspace/src/github.com/gocql/gocql/marshal.go index 4fcb22aab..3cccb8811 100644 --- a/Godeps/_workspace/src/github.com/gocql/gocql/marshal.go +++ b/Godeps/_workspace/src/github.com/gocql/gocql/marshal.go @@ -1368,6 +1368,48 @@ func unmarshalUDT(info TypeInfo, data []byte, value interface{}) error { } } + return nil + case *map[string]interface{}: + udt := info.(UDTTypeInfo) + + rv := reflect.ValueOf(value) + if rv.Kind() != reflect.Ptr { + return unmarshalErrorf("can not unmarshal into non-pointer %T", value) + } + + rv = rv.Elem() + t := rv.Type() + if t.Kind() != reflect.Map { + return unmarshalErrorf("can not unmarshal %s into %T", info, value) + } else if data == nil { + rv.Set(reflect.Zero(t)) + return nil + } + + rv.Set(reflect.MakeMap(t)) + m := *v + + for _, e := range udt.Elements { + size := readInt(data[:4]) + data = data[4:] + + val := reflect.New(goType(e.Type)) + + var err error + if size < 0 { + err = Unmarshal(e.Type, nil, val.Interface()) + } else { + err = Unmarshal(e.Type, data[:size], val.Interface()) + data = data[size:] + } + + if err != nil { + return err + } + + m[e.Name] = val.Elem().Interface() + } + return nil } @@ -1533,26 +1575,26 @@ type Type int const ( TypeCustom Type = 0x0000 - TypeAscii = 0x0001 - TypeBigInt = 0x0002 - TypeBlob = 0x0003 - TypeBoolean = 0x0004 - TypeCounter = 0x0005 - TypeDecimal = 0x0006 - TypeDouble = 0x0007 - TypeFloat = 0x0008 - TypeInt = 0x0009 - TypeTimestamp = 0x000B - TypeUUID = 0x000C - TypeVarchar = 0x000D - TypeVarint = 0x000E - TypeTimeUUID = 0x000F - TypeInet = 0x0010 - TypeList = 0x0020 - TypeMap = 0x0021 - TypeSet = 0x0022 - TypeUDT = 0x0030 - TypeTuple = 0x0031 + TypeAscii Type = 0x0001 + TypeBigInt Type = 0x0002 + TypeBlob Type = 0x0003 + TypeBoolean Type = 0x0004 + TypeCounter Type = 0x0005 + TypeDecimal Type = 0x0006 + TypeDouble Type = 0x0007 + TypeFloat Type = 0x0008 + TypeInt Type = 0x0009 + TypeTimestamp Type = 0x000B + TypeUUID Type = 0x000C + TypeVarchar Type = 0x000D + TypeVarint Type = 0x000E + TypeTimeUUID Type = 0x000F + TypeInet Type = 0x0010 + TypeList Type = 0x0020 + TypeMap Type = 0x0021 + TypeSet Type = 0x0022 + TypeUDT Type = 0x0030 + TypeTuple Type = 0x0031 ) // String returns the name of the identifier. diff --git a/Godeps/_workspace/src/github.com/gocql/gocql/marshal_test.go b/Godeps/_workspace/src/github.com/gocql/gocql/marshal_test.go deleted file mode 100644 index e0493a99b..000000000 --- a/Godeps/_workspace/src/github.com/gocql/gocql/marshal_test.go +++ /dev/null @@ -1,862 +0,0 @@ -// +build all unit - -package gocql - -import ( - "bytes" - "math" - "math/big" - "net" - "reflect" - "strings" - "testing" - "time" - - "gopkg.in/inf.v0" -) - -var marshalTests = []struct { - Info TypeInfo - Data []byte - Value interface{} -}{ - { - NativeType{proto: 2, typ: TypeVarchar}, - []byte("hello world"), - []byte("hello world"), - }, - { - NativeType{proto: 2, typ: TypeVarchar}, - []byte("hello world"), - "hello world", - }, - { - NativeType{proto: 2, typ: TypeVarchar}, - []byte(nil), - []byte(nil), - }, - { - NativeType{proto: 2, typ: TypeVarchar}, - []byte("hello world"), - MyString("hello world"), - }, - { - NativeType{proto: 2, typ: TypeVarchar}, - []byte("HELLO WORLD"), - CustomString("hello world"), - }, - { - NativeType{proto: 2, typ: TypeBlob}, - []byte("hello\x00"), - []byte("hello\x00"), - }, - { - NativeType{proto: 2, typ: TypeBlob}, - []byte(nil), - []byte(nil), - }, - { - NativeType{proto: 2, typ: TypeTimeUUID}, - []byte{0x3d, 0xcd, 0x98, 0x0, 0xf3, 0xd9, 0x11, 0xbf, 0x86, 0xd4, 0xb8, 0xe8, 0x56, 0x2c, 0xc, 0xd0}, - func() UUID { - x, _ := UUIDFromBytes([]byte{0x3d, 0xcd, 0x98, 0x0, 0xf3, 0xd9, 0x11, 0xbf, 0x86, 0xd4, 0xb8, 0xe8, 0x56, 0x2c, 0xc, 0xd0}) - return x - }(), - }, - { - NativeType{proto: 2, typ: TypeInt}, - []byte("\x00\x00\x00\x00"), - 0, - }, - { - NativeType{proto: 2, typ: TypeInt}, - []byte("\x01\x02\x03\x04"), - int(16909060), - }, - { - NativeType{proto: 2, typ: TypeInt}, - []byte("\x80\x00\x00\x00"), - int32(math.MinInt32), - }, - { - NativeType{proto: 2, typ: TypeInt}, - []byte("\x7f\xff\xff\xff"), - int32(math.MaxInt32), - }, - { - NativeType{proto: 2, typ: TypeInt}, - []byte("\x00\x00\x00\x00"), - "0", - }, - { - NativeType{proto: 2, typ: TypeInt}, - []byte("\x01\x02\x03\x04"), - "16909060", - }, - { - NativeType{proto: 2, typ: TypeInt}, - []byte("\x80\x00\x00\x00"), - "-2147483648", // math.MinInt32 - }, - { - NativeType{proto: 2, typ: TypeInt}, - []byte("\x7f\xff\xff\xff"), - "2147483647", // math.MaxInt32 - }, - { - NativeType{proto: 2, typ: TypeBigInt}, - []byte("\x00\x00\x00\x00\x00\x00\x00\x00"), - 0, - }, - { - NativeType{proto: 2, typ: TypeBigInt}, - []byte("\x01\x02\x03\x04\x05\x06\x07\x08"), - 72623859790382856, - }, - { - NativeType{proto: 2, typ: TypeBigInt}, - []byte("\x80\x00\x00\x00\x00\x00\x00\x00"), - int64(math.MinInt64), - }, - { - NativeType{proto: 2, typ: TypeBigInt}, - []byte("\x7f\xff\xff\xff\xff\xff\xff\xff"), - int64(math.MaxInt64), - }, - { - NativeType{proto: 2, typ: TypeBigInt}, - []byte("\x00\x00\x00\x00\x00\x00\x00\x00"), - "0", - }, - { - NativeType{proto: 2, typ: TypeBigInt}, - []byte("\x01\x02\x03\x04\x05\x06\x07\x08"), - "72623859790382856", - }, - { - NativeType{proto: 2, typ: TypeBigInt}, - []byte("\x80\x00\x00\x00\x00\x00\x00\x00"), - "-9223372036854775808", // math.MinInt64 - }, - { - NativeType{proto: 2, typ: TypeBigInt}, - []byte("\x7f\xff\xff\xff\xff\xff\xff\xff"), - "9223372036854775807", // math.MaxInt64 - }, - { - NativeType{proto: 2, typ: TypeBoolean}, - []byte("\x00"), - false, - }, - { - NativeType{proto: 2, typ: TypeBoolean}, - []byte("\x01"), - true, - }, - { - NativeType{proto: 2, typ: TypeFloat}, - []byte("\x40\x49\x0f\xdb"), - float32(3.14159265), - }, - { - NativeType{proto: 2, typ: TypeDouble}, - []byte("\x40\x09\x21\xfb\x53\xc8\xd4\xf1"), - float64(3.14159265), - }, - { - NativeType{proto: 2, typ: TypeDecimal}, - []byte("\x00\x00\x00\x00\x00"), - inf.NewDec(0, 0), - }, - { - NativeType{proto: 2, typ: TypeDecimal}, - []byte("\x00\x00\x00\x00\x64"), - inf.NewDec(100, 0), - }, - { - NativeType{proto: 2, typ: TypeDecimal}, - []byte("\x00\x00\x00\x02\x19"), - decimalize("0.25"), - }, - { - NativeType{proto: 2, typ: TypeDecimal}, - []byte("\x00\x00\x00\x13\xD5\a;\x20\x14\xA2\x91"), - decimalize("-0.0012095473475870063"), // From the iconara/cql-rb test suite - }, - { - NativeType{proto: 2, typ: TypeDecimal}, - []byte("\x00\x00\x00\x13*\xF8\xC4\xDF\xEB]o"), - decimalize("0.0012095473475870063"), // From the iconara/cql-rb test suite - }, - { - NativeType{proto: 2, typ: TypeDecimal}, - []byte("\x00\x00\x00\x12\xF2\xD8\x02\xB6R\x7F\x99\xEE\x98#\x99\xA9V"), - decimalize("-1042342234234.123423435647768234"), // From the iconara/cql-rb test suite - }, - { - NativeType{proto: 2, typ: TypeDecimal}, - []byte("\x00\x00\x00\r\nJ\x04\"^\x91\x04\x8a\xb1\x18\xfe"), - decimalize("1243878957943.1234124191998"), // From the datastax/python-driver test suite - }, - { - NativeType{proto: 2, typ: TypeDecimal}, - []byte("\x00\x00\x00\x06\xe5\xde]\x98Y"), - decimalize("-112233.441191"), // From the datastax/python-driver test suite - }, - { - NativeType{proto: 2, typ: TypeDecimal}, - []byte("\x00\x00\x00\x14\x00\xfa\xce"), - decimalize("0.00000000000000064206"), // From the datastax/python-driver test suite - }, - { - NativeType{proto: 2, typ: TypeDecimal}, - []byte("\x00\x00\x00\x14\xff\x052"), - decimalize("-0.00000000000000064206"), // From the datastax/python-driver test suite - }, - { - NativeType{proto: 2, typ: TypeDecimal}, - []byte("\xff\xff\xff\x9c\x00\xfa\xce"), - inf.NewDec(64206, -100), // From the datastax/python-driver test suite - }, - { - NativeType{proto: 2, typ: TypeTimestamp}, - []byte("\x00\x00\x01\x40\x77\x16\xe1\xb8"), - time.Date(2013, time.August, 13, 9, 52, 3, 0, time.UTC), - }, - { - NativeType{proto: 2, typ: TypeTimestamp}, - []byte("\x00\x00\x01\x40\x77\x16\xe1\xb8"), - int64(1376387523000), - }, - { - CollectionType{ - NativeType: NativeType{proto: 2, typ: TypeList}, - Elem: NativeType{proto: 2, typ: TypeInt}, - }, - []byte("\x00\x02\x00\x04\x00\x00\x00\x01\x00\x04\x00\x00\x00\x02"), - []int{1, 2}, - }, - { - CollectionType{ - NativeType: NativeType{proto: 2, typ: TypeList}, - Elem: NativeType{proto: 2, typ: TypeInt}, - }, - []byte("\x00\x02\x00\x04\x00\x00\x00\x01\x00\x04\x00\x00\x00\x02"), - [2]int{1, 2}, - }, - { - CollectionType{ - NativeType: NativeType{proto: 2, typ: TypeSet}, - Elem: NativeType{proto: 2, typ: TypeInt}, - }, - []byte("\x00\x02\x00\x04\x00\x00\x00\x01\x00\x04\x00\x00\x00\x02"), - []int{1, 2}, - }, - { - CollectionType{ - NativeType: NativeType{proto: 2, typ: TypeSet}, - Elem: NativeType{proto: 2, typ: TypeInt}, - }, - []byte(nil), - []int(nil), - }, - { - CollectionType{ - NativeType: NativeType{proto: 2, typ: TypeMap}, - Key: NativeType{proto: 2, typ: TypeVarchar}, - Elem: NativeType{proto: 2, typ: TypeInt}, - }, - []byte("\x00\x01\x00\x03foo\x00\x04\x00\x00\x00\x01"), - map[string]int{"foo": 1}, - }, - { - CollectionType{ - NativeType: NativeType{proto: 2, typ: TypeMap}, - Key: NativeType{proto: 2, typ: TypeVarchar}, - Elem: NativeType{proto: 2, typ: TypeInt}, - }, - []byte(nil), - map[string]int(nil), - }, - { - CollectionType{ - NativeType: NativeType{proto: 2, typ: TypeList}, - Elem: NativeType{proto: 2, typ: TypeVarchar}, - }, - bytes.Join([][]byte{ - []byte("\x00\x01\xFF\xFF"), - bytes.Repeat([]byte("X"), 65535)}, []byte("")), - []string{strings.Repeat("X", 65535)}, - }, - { - CollectionType{ - NativeType: NativeType{proto: 2, typ: TypeMap}, - Key: NativeType{proto: 2, typ: TypeVarchar}, - Elem: NativeType{proto: 2, typ: TypeVarchar}, - }, - bytes.Join([][]byte{ - []byte("\x00\x01\xFF\xFF"), - bytes.Repeat([]byte("X"), 65535), - []byte("\xFF\xFF"), - bytes.Repeat([]byte("Y"), 65535)}, []byte("")), - map[string]string{ - strings.Repeat("X", 65535): strings.Repeat("Y", 65535), - }, - }, - { - NativeType{proto: 2, typ: TypeVarint}, - []byte("\x00"), - 0, - }, - { - NativeType{proto: 2, typ: TypeVarint}, - []byte("\x37\xE2\x3C\xEC"), - int32(937573612), - }, - { - NativeType{proto: 2, typ: TypeVarint}, - []byte("\x37\xE2\x3C\xEC"), - big.NewInt(937573612), - }, - { - NativeType{proto: 2, typ: TypeVarint}, - []byte("\x03\x9EV \x15\f\x03\x9DK\x18\xCDI\\$?\a["), - bigintize("1231312312331283012830129382342342412123"), // From the iconara/cql-rb test suite - }, - { - NativeType{proto: 2, typ: TypeVarint}, - []byte("\xC9v\x8D:\x86"), - big.NewInt(-234234234234), // From the iconara/cql-rb test suite - }, - { - NativeType{proto: 2, typ: TypeVarint}, - []byte("f\x1e\xfd\xf2\xe3\xb1\x9f|\x04_\x15"), - bigintize("123456789123456789123456789"), // From the datastax/python-driver test suite - }, - { - NativeType{proto: 2, typ: TypeInet}, - []byte("\x7F\x00\x00\x01"), - net.ParseIP("127.0.0.1").To4(), - }, - { - NativeType{proto: 2, typ: TypeInet}, - []byte("\xFF\xFF\xFF\xFF"), - net.ParseIP("255.255.255.255").To4(), - }, - { - NativeType{proto: 2, typ: TypeInet}, - []byte("\x7F\x00\x00\x01"), - "127.0.0.1", - }, - { - NativeType{proto: 2, typ: TypeInet}, - []byte("\xFF\xFF\xFF\xFF"), - "255.255.255.255", - }, - { - NativeType{proto: 2, typ: TypeInet}, - []byte("\x21\xDA\x00\xd3\x00\x00\x2f\x3b\x02\xaa\x00\xff\xfe\x28\x9c\x5a"), - "21da:d3:0:2f3b:2aa:ff:fe28:9c5a", - }, - { - NativeType{proto: 2, typ: TypeInet}, - []byte("\xfe\x80\x00\x00\x00\x00\x00\x00\x02\x02\xb3\xff\xfe\x1e\x83\x29"), - "fe80::202:b3ff:fe1e:8329", - }, - { - NativeType{proto: 2, typ: TypeInet}, - []byte("\x21\xDA\x00\xd3\x00\x00\x2f\x3b\x02\xaa\x00\xff\xfe\x28\x9c\x5a"), - net.ParseIP("21da:d3:0:2f3b:2aa:ff:fe28:9c5a"), - }, - { - NativeType{proto: 2, typ: TypeInet}, - []byte("\xfe\x80\x00\x00\x00\x00\x00\x00\x02\x02\xb3\xff\xfe\x1e\x83\x29"), - net.ParseIP("fe80::202:b3ff:fe1e:8329"), - }, - { - NativeType{proto: 2, typ: TypeInt}, - []byte(nil), - nil, - }, - { - NativeType{proto: 2, typ: TypeVarchar}, - []byte("nullable string"), - func() *string { - value := "nullable string" - return &value - }(), - }, - { - NativeType{proto: 2, typ: TypeVarchar}, - []byte{}, - (*string)(nil), - }, - { - NativeType{proto: 2, typ: TypeInt}, - []byte("\x7f\xff\xff\xff"), - func() *int { - var value int = math.MaxInt32 - return &value - }(), - }, - { - NativeType{proto: 2, typ: TypeInt}, - []byte(nil), - (*int)(nil), - }, - { - NativeType{proto: 2, typ: TypeTimeUUID}, - []byte{0x3d, 0xcd, 0x98, 0x0, 0xf3, 0xd9, 0x11, 0xbf, 0x86, 0xd4, 0xb8, 0xe8, 0x56, 0x2c, 0xc, 0xd0}, - &UUID{0x3d, 0xcd, 0x98, 0x0, 0xf3, 0xd9, 0x11, 0xbf, 0x86, 0xd4, 0xb8, 0xe8, 0x56, 0x2c, 0xc, 0xd0}, - }, - { - NativeType{proto: 2, typ: TypeTimeUUID}, - []byte{}, - (*UUID)(nil), - }, - { - NativeType{proto: 2, typ: TypeTimestamp}, - []byte("\x00\x00\x01\x40\x77\x16\xe1\xb8"), - func() *time.Time { - t := time.Date(2013, time.August, 13, 9, 52, 3, 0, time.UTC) - return &t - }(), - }, - { - NativeType{proto: 2, typ: TypeTimestamp}, - []byte(nil), - (*time.Time)(nil), - }, - { - NativeType{proto: 2, typ: TypeBoolean}, - []byte("\x00"), - func() *bool { - b := false - return &b - }(), - }, - { - NativeType{proto: 2, typ: TypeBoolean}, - []byte("\x01"), - func() *bool { - b := true - return &b - }(), - }, - { - NativeType{proto: 2, typ: TypeBoolean}, - []byte(nil), - (*bool)(nil), - }, - { - NativeType{proto: 2, typ: TypeFloat}, - []byte("\x40\x49\x0f\xdb"), - func() *float32 { - f := float32(3.14159265) - return &f - }(), - }, - { - NativeType{proto: 2, typ: TypeFloat}, - []byte(nil), - (*float32)(nil), - }, - { - NativeType{proto: 2, typ: TypeDouble}, - []byte("\x40\x09\x21\xfb\x53\xc8\xd4\xf1"), - func() *float64 { - d := float64(3.14159265) - return &d - }(), - }, - { - NativeType{proto: 2, typ: TypeDouble}, - []byte(nil), - (*float64)(nil), - }, - { - NativeType{proto: 2, typ: TypeInet}, - []byte("\x7F\x00\x00\x01"), - func() *net.IP { - ip := net.ParseIP("127.0.0.1").To4() - return &ip - }(), - }, - { - NativeType{proto: 2, typ: TypeInet}, - []byte(nil), - (*net.IP)(nil), - }, - { - CollectionType{ - NativeType: NativeType{proto: 2, typ: TypeList}, - Elem: NativeType{proto: 2, typ: TypeInt}, - }, - []byte("\x00\x02\x00\x04\x00\x00\x00\x01\x00\x04\x00\x00\x00\x02"), - func() *[]int { - l := []int{1, 2} - return &l - }(), - }, - { - CollectionType{ - NativeType: NativeType{proto: 2, typ: TypeList}, - Elem: NativeType{proto: 2, typ: TypeInt}, - }, - []byte(nil), - (*[]int)(nil), - }, - { - CollectionType{ - NativeType: NativeType{proto: 2, typ: TypeMap}, - Key: NativeType{proto: 2, typ: TypeVarchar}, - Elem: NativeType{proto: 2, typ: TypeInt}, - }, - []byte("\x00\x01\x00\x03foo\x00\x04\x00\x00\x00\x01"), - func() *map[string]int { - m := map[string]int{"foo": 1} - return &m - }(), - }, - { - CollectionType{ - NativeType: NativeType{proto: 2, typ: TypeMap}, - Key: NativeType{proto: 2, typ: TypeVarchar}, - Elem: NativeType{proto: 2, typ: TypeInt}, - }, - []byte(nil), - (*map[string]int)(nil), - }, - { - NativeType{proto: 2, typ: TypeVarchar}, - []byte("HELLO WORLD"), - func() *CustomString { - customString := CustomString("hello world") - return &customString - }(), - }, - { - NativeType{proto: 2, typ: TypeVarchar}, - []byte(nil), - (*CustomString)(nil), - }, -} - -func decimalize(s string) *inf.Dec { - i, _ := new(inf.Dec).SetString(s) - return i -} - -func bigintize(s string) *big.Int { - i, _ := new(big.Int).SetString(s, 10) - return i -} - -func TestMarshal(t *testing.T) { - for i, test := range marshalTests { - data, err := Marshal(test.Info, test.Value) - if err != nil { - t.Errorf("marshalTest[%d]: %v", i, err) - continue - } - if !bytes.Equal(data, test.Data) { - t.Errorf("marshalTest[%d]: expected %q, got %q (%#v)", i, test.Data, data, test.Value) - } - } -} - -func TestUnmarshal(t *testing.T) { - for i, test := range marshalTests { - if test.Value != nil { - v := reflect.New(reflect.TypeOf(test.Value)) - err := Unmarshal(test.Info, test.Data, v.Interface()) - if err != nil { - t.Errorf("unmarshalTest[%d]: %v", i, err) - continue - } - if !reflect.DeepEqual(v.Elem().Interface(), test.Value) { - t.Errorf("unmarshalTest[%d]: expected %#v, got %#v.", i, test.Value, v.Elem().Interface()) - } - } else { - if err := Unmarshal(test.Info, test.Data, test.Value); nil == err { - t.Errorf("unmarshalTest[%d]: %#v not return error.", i, test.Value) - } - } - } -} - -func TestMarshalVarint(t *testing.T) { - varintTests := []struct { - Value interface{} - Marshaled []byte - Unmarshaled *big.Int - }{ - { - Value: int8(0), - Marshaled: []byte("\x00"), - Unmarshaled: big.NewInt(0), - }, - { - Value: uint8(255), - Marshaled: []byte("\x00\xFF"), - Unmarshaled: big.NewInt(255), - }, - { - Value: int8(-1), - Marshaled: []byte("\xFF"), - Unmarshaled: big.NewInt(-1), - }, - { - Value: big.NewInt(math.MaxInt32), - Marshaled: []byte("\x7F\xFF\xFF\xFF"), - Unmarshaled: big.NewInt(math.MaxInt32), - }, - { - Value: big.NewInt(int64(math.MaxInt32) + 1), - Marshaled: []byte("\x00\x80\x00\x00\x00"), - Unmarshaled: big.NewInt(int64(math.MaxInt32) + 1), - }, - { - Value: big.NewInt(math.MinInt32), - Marshaled: []byte("\x80\x00\x00\x00"), - Unmarshaled: big.NewInt(math.MinInt32), - }, - { - Value: big.NewInt(int64(math.MinInt32) - 1), - Marshaled: []byte("\xFF\x7F\xFF\xFF\xFF"), - Unmarshaled: big.NewInt(int64(math.MinInt32) - 1), - }, - { - Value: math.MinInt64, - Marshaled: []byte("\x80\x00\x00\x00\x00\x00\x00\x00"), - Unmarshaled: big.NewInt(math.MinInt64), - }, - { - Value: uint64(math.MaxInt64) + 1, - Marshaled: []byte("\x00\x80\x00\x00\x00\x00\x00\x00\x00"), - Unmarshaled: bigintize("9223372036854775808"), - }, - { - Value: bigintize("2361183241434822606848"), // 2**71 - Marshaled: []byte("\x00\x80\x00\x00\x00\x00\x00\x00\x00\x00"), - Unmarshaled: bigintize("2361183241434822606848"), - }, - { - Value: bigintize("-9223372036854775809"), // -2**63 - 1 - Marshaled: []byte("\xFF\x7F\xFF\xFF\xFF\xFF\xFF\xFF\xFF"), - Unmarshaled: bigintize("-9223372036854775809"), - }, - } - - for i, test := range varintTests { - data, err := Marshal(NativeType{proto: 2, typ: TypeVarint}, test.Value) - if err != nil { - t.Errorf("error marshaling varint: %v (test #%d)", err, i) - } - - if !bytes.Equal(test.Marshaled, data) { - t.Errorf("marshaled varint mismatch: expected %v, got %v (test #%d)", test.Marshaled, data, i) - } - - binder := new(big.Int) - err = Unmarshal(NativeType{proto: 2, typ: TypeVarint}, test.Marshaled, binder) - if err != nil { - t.Errorf("error unmarshaling varint: %v (test #%d)", err, i) - } - - if test.Unmarshaled.Cmp(binder) != 0 { - t.Errorf("unmarshaled varint mismatch: expected %v, got %v (test #%d)", test.Unmarshaled, binder, i) - } - } -} - -func equalStringSlice(leftList, rightList []string) bool { - if len(leftList) != len(rightList) { - return false - } - for index := range leftList { - if rightList[index] != leftList[index] { - return false - } - } - return true -} - -func TestMarshalList(t *testing.T) { - typeInfo := CollectionType{ - NativeType: NativeType{proto: 2, typ: TypeList}, - Elem: NativeType{proto: 2, typ: TypeVarchar}, - } - - sourceLists := [][]string{ - []string{"valueA"}, - []string{"valueA", "valueB"}, - []string{"valueB"}, - } - - listDatas := [][]byte{} - - for _, list := range sourceLists { - listData, marshalErr := Marshal(typeInfo, list) - if nil != marshalErr { - t.Errorf("Error marshal %+v of type %+v: %s", list, typeInfo, marshalErr) - } - listDatas = append(listDatas, listData) - } - - outputLists := [][]string{} - - var outputList []string - - for _, listData := range listDatas { - if unmarshalErr := Unmarshal(typeInfo, listData, &outputList); nil != unmarshalErr { - t.Error(unmarshalErr) - } - outputLists = append(outputLists, outputList) - } - - for index, sourceList := range sourceLists { - outputList := outputLists[index] - if !equalStringSlice(sourceList, outputList) { - t.Errorf("Lists %+v not equal to lists %+v, but should", sourceList, outputList) - } - } -} - -type CustomString string - -func (c CustomString) MarshalCQL(info TypeInfo) ([]byte, error) { - return []byte(strings.ToUpper(string(c))), nil -} -func (c *CustomString) UnmarshalCQL(info TypeInfo, data []byte) error { - *c = CustomString(strings.ToLower(string(data))) - return nil -} - -type MyString string - -type MyInt int - -var typeLookupTest = []struct { - TypeName string - ExpectedType Type -}{ - {"AsciiType", TypeAscii}, - {"LongType", TypeBigInt}, - {"BytesType", TypeBlob}, - {"BooleanType", TypeBoolean}, - {"CounterColumnType", TypeCounter}, - {"DecimalType", TypeDecimal}, - {"DoubleType", TypeDouble}, - {"FloatType", TypeFloat}, - {"Int32Type", TypeInt}, - {"DateType", TypeTimestamp}, - {"TimestampType", TypeTimestamp}, - {"UUIDType", TypeUUID}, - {"UTF8Type", TypeVarchar}, - {"IntegerType", TypeVarint}, - {"TimeUUIDType", TypeTimeUUID}, - {"InetAddressType", TypeInet}, - {"MapType", TypeMap}, - {"ListType", TypeList}, - {"SetType", TypeSet}, - {"unknown", TypeCustom}, -} - -func testType(t *testing.T, cassType string, expectedType Type) { - if computedType := getApacheCassandraType(apacheCassandraTypePrefix + cassType); computedType != expectedType { - t.Errorf("Cassandra custom type lookup for %s failed. Expected %s, got %s.", cassType, expectedType.String(), computedType.String()) - } -} - -func TestLookupCassType(t *testing.T) { - for _, lookupTest := range typeLookupTest { - testType(t, lookupTest.TypeName, lookupTest.ExpectedType) - } -} - -type MyPointerMarshaler struct{} - -func (m *MyPointerMarshaler) MarshalCQL(_ TypeInfo) ([]byte, error) { - return []byte{42}, nil -} - -func TestMarshalPointer(t *testing.T) { - m := &MyPointerMarshaler{} - typ := NativeType{proto: 2, typ: TypeInt} - - data, err := Marshal(typ, m) - - if err != nil { - t.Errorf("Pointer marshaling failed. Error: %s", err) - } - if len(data) != 1 || data[0] != 42 { - t.Errorf("Pointer marshaling failed. Expected %+v, got %+v", []byte{42}, data) - } -} - -func TestMarshalTimestamp(t *testing.T) { - var marshalTimestampTests = []struct { - Info TypeInfo - Data []byte - Value interface{} - }{ - { - NativeType{proto: 2, typ: TypeTimestamp}, - []byte("\x00\x00\x01\x40\x77\x16\xe1\xb8"), - time.Date(2013, time.August, 13, 9, 52, 3, 0, time.UTC), - }, - { - NativeType{proto: 2, typ: TypeTimestamp}, - []byte("\x00\x00\x01\x40\x77\x16\xe1\xb8"), - int64(1376387523000), - }, - { - // 9223372036854 is the maximum time representable in ms since the epoch - // with int64 if using UnixNano to convert - NativeType{proto: 2, typ: TypeTimestamp}, - []byte("\x00\x00\x08\x63\x7b\xd0\x5a\xf6"), - time.Date(2262, time.April, 11, 23, 47, 16, 854775807, time.UTC), - }, - { - // One nanosecond after causes overflow when using UnixNano - // Instead it should resolve to the same time in ms - NativeType{proto: 2, typ: TypeTimestamp}, - []byte("\x00\x00\x08\x63\x7b\xd0\x5a\xf6"), - time.Date(2262, time.April, 11, 23, 47, 16, 854775808, time.UTC), - }, - { - // -9223372036855 is the minimum time representable in ms since the epoch - // with int64 if using UnixNano to convert - NativeType{proto: 2, typ: TypeTimestamp}, - []byte("\xff\xff\xf7\x9c\x84\x2f\xa5\x09"), - time.Date(1677, time.September, 21, 00, 12, 43, 145224192, time.UTC), - }, - { - // One nanosecond earlier causes overflow when using UnixNano - // it should resolve to the same time in ms - NativeType{proto: 2, typ: TypeTimestamp}, - []byte("\xff\xff\xf7\x9c\x84\x2f\xa5\x09"), - time.Date(1677, time.September, 21, 00, 12, 43, 145224191, time.UTC), - }, - { - // Store the zero time as a blank slice - NativeType{proto: 2, typ: TypeTimestamp}, - []byte{}, - time.Time{}, - }, - } - - for i, test := range marshalTimestampTests { - t.Log(i, test) - data, err := Marshal(test.Info, test.Value) - if err != nil { - t.Errorf("marshalTest[%d]: %v", i, err) - continue - } - if !bytes.Equal(data, test.Data) { - t.Errorf("marshalTest[%d]: expected %x (%v), got %x (%v) for time %s", i, - test.Data, decBigInt(test.Data), data, decBigInt(data), test.Value) - } - } -} diff --git a/Godeps/_workspace/src/github.com/gocql/gocql/metadata.go b/Godeps/_workspace/src/github.com/gocql/gocql/metadata.go index 131684b7d..92965c3a8 100644 --- a/Godeps/_workspace/src/github.com/gocql/gocql/metadata.go +++ b/Godeps/_workspace/src/github.com/gocql/gocql/metadata.go @@ -375,12 +375,20 @@ func getKeyspaceMetadata( } // query for only the table metadata in the specified keyspace from system.schema_columnfamilies -func getTableMetadata( - session *Session, - keyspaceName string, -) ([]TableMetadata, error) { - query := session.Query( - ` +func getTableMetadata(session *Session, keyspaceName string) ([]TableMetadata, error) { + + var ( + scan func(iter *Iter, table *TableMetadata) bool + stmt string + + keyAliasesJSON []byte + columnAliasesJSON []byte + ) + + if session.cfg.ProtoVersion < protoVersion4 { + // we have key aliases + // TODO: Do we need key_aliases? + stmt = ` SELECT columnfamily_name, key_validator, @@ -390,29 +398,49 @@ func getTableMetadata( column_aliases, value_alias FROM system.schema_columnfamilies - WHERE keyspace_name = ? - `, - keyspaceName, - ) + WHERE keyspace_name = ?` + + scan = func(iter *Iter, table *TableMetadata) bool { + return iter.Scan( + &table.Name, + &table.KeyValidator, + &table.Comparator, + &table.DefaultValidator, + &keyAliasesJSON, + &columnAliasesJSON, + &table.ValueAlias, + ) + } + } else { + stmt = ` + SELECT + columnfamily_name, + key_validator, + comparator, + default_validator + FROM system.schema_columnfamilies + WHERE keyspace_name = ?` + + scan = func(iter *Iter, table *TableMetadata) bool { + return iter.Scan( + &table.Name, + &table.KeyValidator, + &table.Comparator, + &table.DefaultValidator, + ) + } + } + // Set a routing key to avoid GetRoutingKey from computing the routing key // TODO use a separate connection (pool) for system keyspace queries. + query := session.Query(stmt, keyspaceName) query.RoutingKey([]byte{}) iter := query.Iter() tables := []TableMetadata{} table := TableMetadata{Keyspace: keyspaceName} - var keyAliasesJSON []byte - var columnAliasesJSON []byte - for iter.Scan( - &table.Name, - &table.KeyValidator, - &table.Comparator, - &table.DefaultValidator, - &keyAliasesJSON, - &columnAliasesJSON, - &table.ValueAlias, - ) { + for scan(iter, &table) { var err error // decode the key aliases diff --git a/Godeps/_workspace/src/github.com/gocql/gocql/metadata_test.go b/Godeps/_workspace/src/github.com/gocql/gocql/metadata_test.go deleted file mode 100644 index 7ce9c7ce6..000000000 --- a/Godeps/_workspace/src/github.com/gocql/gocql/metadata_test.go +++ /dev/null @@ -1,815 +0,0 @@ -// Copyright (c) 2015 The gocql 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 gocql - -import ( - "strconv" - "testing" -) - -// Tests V1 and V2 metadata "compilation" from example data which might be returned -// from metadata schema queries (see getKeyspaceMetadata, getTableMetadata, and getColumnMetadata) -func TestCompileMetadata(t *testing.T) { - // V1 tests - these are all based on real examples from the integration test ccm cluster - keyspace := &KeyspaceMetadata{ - Name: "V1Keyspace", - } - tables := []TableMetadata{ - TableMetadata{ - // This table, found in the system keyspace, has no key aliases or column aliases - Keyspace: "V1Keyspace", - Name: "Schema", - KeyValidator: "org.apache.cassandra.db.marshal.BytesType", - Comparator: "org.apache.cassandra.db.marshal.UTF8Type", - DefaultValidator: "org.apache.cassandra.db.marshal.BytesType", - KeyAliases: []string{}, - ColumnAliases: []string{}, - ValueAlias: "", - }, - TableMetadata{ - // This table, found in the system keyspace, has key aliases, column aliases, and a value alias. - Keyspace: "V1Keyspace", - Name: "hints", - KeyValidator: "org.apache.cassandra.db.marshal.UUIDType", - Comparator: "org.apache.cassandra.db.marshal.CompositeType(org.apache.cassandra.db.marshal.TimeUUIDType,org.apache.cassandra.db.marshal.Int32Type)", - DefaultValidator: "org.apache.cassandra.db.marshal.BytesType", - KeyAliases: []string{"target_id"}, - ColumnAliases: []string{"hint_id", "message_version"}, - ValueAlias: "mutation", - }, - TableMetadata{ - // This table, found in the system keyspace, has a comparator with collections, but no column aliases - Keyspace: "V1Keyspace", - Name: "peers", - KeyValidator: "org.apache.cassandra.db.marshal.InetAddressType", - Comparator: "org.apache.cassandra.db.marshal.CompositeType(org.apache.cassandra.db.marshal.UTF8Type,org.apache.cassandra.db.marshal.ColumnToCollectionType(746f6b656e73:org.apache.cassandra.db.marshal.SetType(org.apache.cassandra.db.marshal.UTF8Type)))", - DefaultValidator: "org.apache.cassandra.db.marshal.BytesType", - KeyAliases: []string{"peer"}, - ColumnAliases: []string{}, - ValueAlias: "", - }, - TableMetadata{ - // This table, found in the system keyspace, has a column alias, but not a composite comparator - Keyspace: "V1Keyspace", - Name: "IndexInfo", - KeyValidator: "org.apache.cassandra.db.marshal.UTF8Type", - Comparator: "org.apache.cassandra.db.marshal.ReversedType(org.apache.cassandra.db.marshal.UTF8Type)", - DefaultValidator: "org.apache.cassandra.db.marshal.BytesType", - KeyAliases: []string{"table_name"}, - ColumnAliases: []string{"index_name"}, - ValueAlias: "", - }, - TableMetadata{ - // This table, found in the gocql_test keyspace following an integration test run, has a composite comparator with collections as well as a column alias - Keyspace: "V1Keyspace", - Name: "wiki_page", - KeyValidator: "org.apache.cassandra.db.marshal.UTF8Type", - Comparator: "org.apache.cassandra.db.marshal.CompositeType(org.apache.cassandra.db.marshal.TimeUUIDType,org.apache.cassandra.db.marshal.UTF8Type,org.apache.cassandra.db.marshal.ColumnToCollectionType(74616773:org.apache.cassandra.db.marshal.SetType(org.apache.cassandra.db.marshal.UTF8Type),6174746163686d656e7473:org.apache.cassandra.db.marshal.MapType(org.apache.cassandra.db.marshal.UTF8Type,org.apache.cassandra.db.marshal.BytesType)))", - DefaultValidator: "org.apache.cassandra.db.marshal.BytesType", - KeyAliases: []string{"title"}, - ColumnAliases: []string{"revid"}, - ValueAlias: "", - }, - TableMetadata{ - // This is a made up example with multiple unnamed aliases - Keyspace: "V1Keyspace", - Name: "no_names", - KeyValidator: "org.apache.cassandra.db.marshal.CompositeType(org.apache.cassandra.db.marshal.UUIDType,org.apache.cassandra.db.marshal.UUIDType)", - Comparator: "org.apache.cassandra.db.marshal.CompositeType(org.apache.cassandra.db.marshal.Int32Type,org.apache.cassandra.db.marshal.Int32Type,org.apache.cassandra.db.marshal.Int32Type)", - DefaultValidator: "org.apache.cassandra.db.marshal.BytesType", - KeyAliases: []string{}, - ColumnAliases: []string{}, - ValueAlias: "", - }, - } - columns := []ColumnMetadata{ - // Here are the regular columns from the peers table for testing regular columns - ColumnMetadata{Keyspace: "V1Keyspace", Table: "peers", Kind: REGULAR, Name: "data_center", ComponentIndex: 0, Validator: "org.apache.cassandra.db.marshal.UTF8Type"}, - ColumnMetadata{Keyspace: "V1Keyspace", Table: "peers", Kind: REGULAR, Name: "host_id", ComponentIndex: 0, Validator: "org.apache.cassandra.db.marshal.UUIDType"}, - ColumnMetadata{Keyspace: "V1Keyspace", Table: "peers", Kind: REGULAR, Name: "rack", ComponentIndex: 0, Validator: "org.apache.cassandra.db.marshal.UTF8Type"}, - ColumnMetadata{Keyspace: "V1Keyspace", Table: "peers", Kind: REGULAR, Name: "release_version", ComponentIndex: 0, Validator: "org.apache.cassandra.db.marshal.UTF8Type"}, - ColumnMetadata{Keyspace: "V1Keyspace", Table: "peers", Kind: REGULAR, Name: "rpc_address", ComponentIndex: 0, Validator: "org.apache.cassandra.db.marshal.InetAddressType"}, - ColumnMetadata{Keyspace: "V1Keyspace", Table: "peers", Kind: REGULAR, Name: "schema_version", ComponentIndex: 0, Validator: "org.apache.cassandra.db.marshal.UUIDType"}, - ColumnMetadata{Keyspace: "V1Keyspace", Table: "peers", Kind: REGULAR, Name: "tokens", ComponentIndex: 0, Validator: "org.apache.cassandra.db.marshal.SetType(org.apache.cassandra.db.marshal.UTF8Type)"}, - } - compileMetadata(1, keyspace, tables, columns) - assertKeyspaceMetadata( - t, - keyspace, - &KeyspaceMetadata{ - Name: "V1Keyspace", - Tables: map[string]*TableMetadata{ - "Schema": &TableMetadata{ - PartitionKey: []*ColumnMetadata{ - &ColumnMetadata{ - Name: "key", - Type: NativeType{typ: TypeBlob}, - }, - }, - ClusteringColumns: []*ColumnMetadata{}, - Columns: map[string]*ColumnMetadata{ - "key": &ColumnMetadata{ - Name: "key", - Type: NativeType{typ: TypeBlob}, - Kind: PARTITION_KEY, - }, - }, - }, - "hints": &TableMetadata{ - PartitionKey: []*ColumnMetadata{ - &ColumnMetadata{ - Name: "target_id", - Type: NativeType{typ: TypeUUID}, - }, - }, - ClusteringColumns: []*ColumnMetadata{ - &ColumnMetadata{ - Name: "hint_id", - Type: NativeType{typ: TypeTimeUUID}, - Order: ASC, - }, - &ColumnMetadata{ - Name: "message_version", - Type: NativeType{typ: TypeInt}, - Order: ASC, - }, - }, - Columns: map[string]*ColumnMetadata{ - "target_id": &ColumnMetadata{ - Name: "target_id", - Type: NativeType{typ: TypeUUID}, - Kind: PARTITION_KEY, - }, - "hint_id": &ColumnMetadata{ - Name: "hint_id", - Type: NativeType{typ: TypeTimeUUID}, - Order: ASC, - Kind: CLUSTERING_KEY, - }, - "message_version": &ColumnMetadata{ - Name: "message_version", - Type: NativeType{typ: TypeInt}, - Order: ASC, - Kind: CLUSTERING_KEY, - }, - "mutation": &ColumnMetadata{ - Name: "mutation", - Type: NativeType{typ: TypeBlob}, - Kind: REGULAR, - }, - }, - }, - "peers": &TableMetadata{ - PartitionKey: []*ColumnMetadata{ - &ColumnMetadata{ - Name: "peer", - Type: NativeType{typ: TypeInet}, - }, - }, - ClusteringColumns: []*ColumnMetadata{}, - Columns: map[string]*ColumnMetadata{ - "peer": &ColumnMetadata{ - Name: "peer", - Type: NativeType{typ: TypeInet}, - Kind: PARTITION_KEY, - }, - "data_center": &ColumnMetadata{Keyspace: "V1Keyspace", Table: "peers", Kind: REGULAR, Name: "data_center", ComponentIndex: 0, Validator: "org.apache.cassandra.db.marshal.UTF8Type", Type: NativeType{typ: TypeVarchar}}, - "host_id": &ColumnMetadata{Keyspace: "V1Keyspace", Table: "peers", Kind: REGULAR, Name: "host_id", ComponentIndex: 0, Validator: "org.apache.cassandra.db.marshal.UUIDType", Type: NativeType{typ: TypeUUID}}, - "rack": &ColumnMetadata{Keyspace: "V1Keyspace", Table: "peers", Kind: REGULAR, Name: "rack", ComponentIndex: 0, Validator: "org.apache.cassandra.db.marshal.UTF8Type", Type: NativeType{typ: TypeVarchar}}, - "release_version": &ColumnMetadata{Keyspace: "V1Keyspace", Table: "peers", Kind: REGULAR, Name: "release_version", ComponentIndex: 0, Validator: "org.apache.cassandra.db.marshal.UTF8Type", Type: NativeType{typ: TypeVarchar}}, - "rpc_address": &ColumnMetadata{Keyspace: "V1Keyspace", Table: "peers", Kind: REGULAR, Name: "rpc_address", ComponentIndex: 0, Validator: "org.apache.cassandra.db.marshal.InetAddressType", Type: NativeType{typ: TypeInet}}, - "schema_version": &ColumnMetadata{Keyspace: "V1Keyspace", Table: "peers", Kind: REGULAR, Name: "schema_version", ComponentIndex: 0, Validator: "org.apache.cassandra.db.marshal.UUIDType", Type: NativeType{typ: TypeUUID}}, - "tokens": &ColumnMetadata{Keyspace: "V1Keyspace", Table: "peers", Kind: REGULAR, Name: "tokens", ComponentIndex: 0, Validator: "org.apache.cassandra.db.marshal.SetType(org.apache.cassandra.db.marshal.UTF8Type)", Type: CollectionType{NativeType: NativeType{typ: TypeSet}}}, - }, - }, - "IndexInfo": &TableMetadata{ - PartitionKey: []*ColumnMetadata{ - &ColumnMetadata{ - Name: "table_name", - Type: NativeType{typ: TypeVarchar}, - }, - }, - ClusteringColumns: []*ColumnMetadata{ - &ColumnMetadata{ - Name: "index_name", - Type: NativeType{typ: TypeVarchar}, - Order: DESC, - }, - }, - Columns: map[string]*ColumnMetadata{ - "table_name": &ColumnMetadata{ - Name: "table_name", - Type: NativeType{typ: TypeVarchar}, - Kind: PARTITION_KEY, - }, - "index_name": &ColumnMetadata{ - Name: "index_name", - Type: NativeType{typ: TypeVarchar}, - Order: DESC, - Kind: CLUSTERING_KEY, - }, - "value": &ColumnMetadata{ - Name: "value", - Type: NativeType{typ: TypeBlob}, - Kind: REGULAR, - }, - }, - }, - "wiki_page": &TableMetadata{ - PartitionKey: []*ColumnMetadata{ - &ColumnMetadata{ - Name: "title", - Type: NativeType{typ: TypeVarchar}, - }, - }, - ClusteringColumns: []*ColumnMetadata{ - &ColumnMetadata{ - Name: "revid", - Type: NativeType{typ: TypeTimeUUID}, - Order: ASC, - }, - }, - Columns: map[string]*ColumnMetadata{ - "title": &ColumnMetadata{ - Name: "title", - Type: NativeType{typ: TypeVarchar}, - Kind: PARTITION_KEY, - }, - "revid": &ColumnMetadata{ - Name: "revid", - Type: NativeType{typ: TypeTimeUUID}, - Kind: CLUSTERING_KEY, - }, - }, - }, - "no_names": &TableMetadata{ - PartitionKey: []*ColumnMetadata{ - &ColumnMetadata{ - Name: "key", - Type: NativeType{typ: TypeUUID}, - }, - &ColumnMetadata{ - Name: "key2", - Type: NativeType{typ: TypeUUID}, - }, - }, - ClusteringColumns: []*ColumnMetadata{ - &ColumnMetadata{ - Name: "column", - Type: NativeType{typ: TypeInt}, - Order: ASC, - }, - &ColumnMetadata{ - Name: "column2", - Type: NativeType{typ: TypeInt}, - Order: ASC, - }, - &ColumnMetadata{ - Name: "column3", - Type: NativeType{typ: TypeInt}, - Order: ASC, - }, - }, - Columns: map[string]*ColumnMetadata{ - "key": &ColumnMetadata{ - Name: "key", - Type: NativeType{typ: TypeUUID}, - Kind: PARTITION_KEY, - }, - "key2": &ColumnMetadata{ - Name: "key2", - Type: NativeType{typ: TypeUUID}, - Kind: PARTITION_KEY, - }, - "column": &ColumnMetadata{ - Name: "column", - Type: NativeType{typ: TypeInt}, - Order: ASC, - Kind: CLUSTERING_KEY, - }, - "column2": &ColumnMetadata{ - Name: "column2", - Type: NativeType{typ: TypeInt}, - Order: ASC, - Kind: CLUSTERING_KEY, - }, - "column3": &ColumnMetadata{ - Name: "column3", - Type: NativeType{typ: TypeInt}, - Order: ASC, - Kind: CLUSTERING_KEY, - }, - "value": &ColumnMetadata{ - Name: "value", - Type: NativeType{typ: TypeBlob}, - Kind: REGULAR, - }, - }, - }, - }, - }, - ) - - // V2 test - V2+ protocol is simpler so here are some toy examples to verify that the mapping works - keyspace = &KeyspaceMetadata{ - Name: "V2Keyspace", - } - tables = []TableMetadata{ - TableMetadata{ - Keyspace: "V2Keyspace", - Name: "Table1", - }, - TableMetadata{ - Keyspace: "V2Keyspace", - Name: "Table2", - }, - } - columns = []ColumnMetadata{ - ColumnMetadata{ - Keyspace: "V2Keyspace", - Table: "Table1", - Name: "KEY1", - Kind: PARTITION_KEY, - ComponentIndex: 0, - Validator: "org.apache.cassandra.db.marshal.UTF8Type", - }, - ColumnMetadata{ - Keyspace: "V2Keyspace", - Table: "Table1", - Name: "Key1", - Kind: PARTITION_KEY, - ComponentIndex: 0, - Validator: "org.apache.cassandra.db.marshal.UTF8Type", - }, - ColumnMetadata{ - Keyspace: "V2Keyspace", - Table: "Table2", - Name: "Column1", - Kind: PARTITION_KEY, - ComponentIndex: 0, - Validator: "org.apache.cassandra.db.marshal.UTF8Type", - }, - ColumnMetadata{ - Keyspace: "V2Keyspace", - Table: "Table2", - Name: "Column2", - Kind: CLUSTERING_KEY, - ComponentIndex: 0, - Validator: "org.apache.cassandra.db.marshal.UTF8Type", - }, - ColumnMetadata{ - Keyspace: "V2Keyspace", - Table: "Table2", - Name: "Column3", - Kind: CLUSTERING_KEY, - ComponentIndex: 1, - Validator: "org.apache.cassandra.db.marshal.ReversedType(org.apache.cassandra.db.marshal.UTF8Type)", - }, - ColumnMetadata{ - Keyspace: "V2Keyspace", - Table: "Table2", - Name: "Column4", - Kind: REGULAR, - Validator: "org.apache.cassandra.db.marshal.UTF8Type", - }, - } - compileMetadata(2, keyspace, tables, columns) - assertKeyspaceMetadata( - t, - keyspace, - &KeyspaceMetadata{ - Name: "V2Keyspace", - Tables: map[string]*TableMetadata{ - "Table1": &TableMetadata{ - PartitionKey: []*ColumnMetadata{ - &ColumnMetadata{ - Name: "Key1", - Type: NativeType{typ: TypeVarchar}, - }, - }, - ClusteringColumns: []*ColumnMetadata{}, - Columns: map[string]*ColumnMetadata{ - "KEY1": &ColumnMetadata{ - Name: "KEY1", - Type: NativeType{typ: TypeVarchar}, - Kind: PARTITION_KEY, - }, - "Key1": &ColumnMetadata{ - Name: "Key1", - Type: NativeType{typ: TypeVarchar}, - Kind: PARTITION_KEY, - }, - }, - }, - "Table2": &TableMetadata{ - PartitionKey: []*ColumnMetadata{ - &ColumnMetadata{ - Name: "Column1", - Type: NativeType{typ: TypeVarchar}, - }, - }, - ClusteringColumns: []*ColumnMetadata{ - &ColumnMetadata{ - Name: "Column2", - Type: NativeType{typ: TypeVarchar}, - Order: ASC, - }, - &ColumnMetadata{ - Name: "Column3", - Type: NativeType{typ: TypeVarchar}, - Order: DESC, - }, - }, - Columns: map[string]*ColumnMetadata{ - "Column1": &ColumnMetadata{ - Name: "Column1", - Type: NativeType{typ: TypeVarchar}, - Kind: PARTITION_KEY, - }, - "Column2": &ColumnMetadata{ - Name: "Column2", - Type: NativeType{typ: TypeVarchar}, - Order: ASC, - Kind: CLUSTERING_KEY, - }, - "Column3": &ColumnMetadata{ - Name: "Column3", - Type: NativeType{typ: TypeVarchar}, - Order: DESC, - Kind: CLUSTERING_KEY, - }, - "Column4": &ColumnMetadata{ - Name: "Column4", - Type: NativeType{typ: TypeVarchar}, - Kind: REGULAR, - }, - }, - }, - }, - }, - ) -} - -// Helper function for asserting that actual metadata returned was as expected -func assertKeyspaceMetadata(t *testing.T, actual, expected *KeyspaceMetadata) { - if len(expected.Tables) != len(actual.Tables) { - t.Errorf("Expected len(%s.Tables) to be %v but was %v", expected.Name, len(expected.Tables), len(actual.Tables)) - } - for keyT := range expected.Tables { - et := expected.Tables[keyT] - at, found := actual.Tables[keyT] - - if !found { - t.Errorf("Expected %s.Tables[%s] but was not found", expected.Name, keyT) - } else { - if keyT != at.Name { - t.Errorf("Expected %s.Tables[%s].Name to be %v but was %v", expected.Name, keyT, keyT, at.Name) - } - if len(et.PartitionKey) != len(at.PartitionKey) { - t.Errorf("Expected len(%s.Tables[%s].PartitionKey) to be %v but was %v", expected.Name, keyT, len(et.PartitionKey), len(at.PartitionKey)) - } else { - for i := range et.PartitionKey { - if et.PartitionKey[i].Name != at.PartitionKey[i].Name { - t.Errorf("Expected %s.Tables[%s].PartitionKey[%d].Name to be '%v' but was '%v'", expected.Name, keyT, i, et.PartitionKey[i].Name, at.PartitionKey[i].Name) - } - if expected.Name != at.PartitionKey[i].Keyspace { - t.Errorf("Expected %s.Tables[%s].PartitionKey[%d].Keyspace to be '%v' but was '%v'", expected.Name, keyT, i, expected.Name, at.PartitionKey[i].Keyspace) - } - if keyT != at.PartitionKey[i].Table { - t.Errorf("Expected %s.Tables[%s].PartitionKey[%d].Table to be '%v' but was '%v'", expected.Name, keyT, i, keyT, at.PartitionKey[i].Table) - } - if et.PartitionKey[i].Type.Type() != at.PartitionKey[i].Type.Type() { - t.Errorf("Expected %s.Tables[%s].PartitionKey[%d].Type.Type to be %v but was %v", expected.Name, keyT, i, et.PartitionKey[i].Type.Type(), at.PartitionKey[i].Type.Type()) - } - if i != at.PartitionKey[i].ComponentIndex { - t.Errorf("Expected %s.Tables[%s].PartitionKey[%d].ComponentIndex to be %v but was %v", expected.Name, keyT, i, i, at.PartitionKey[i].ComponentIndex) - } - if PARTITION_KEY != at.PartitionKey[i].Kind { - t.Errorf("Expected %s.Tables[%s].PartitionKey[%d].Kind to be '%v' but was '%v'", expected.Name, keyT, i, PARTITION_KEY, at.PartitionKey[i].Kind) - } - } - } - if len(et.ClusteringColumns) != len(at.ClusteringColumns) { - t.Errorf("Expected len(%s.Tables[%s].ClusteringColumns) to be %v but was %v", expected.Name, keyT, len(et.ClusteringColumns), len(at.ClusteringColumns)) - } else { - for i := range et.ClusteringColumns { - if at.ClusteringColumns[i] == nil { - t.Fatalf("Unexpected nil value: %s.Tables[%s].ClusteringColumns[%d]", expected.Name, keyT, i) - } - if et.ClusteringColumns[i].Name != at.ClusteringColumns[i].Name { - t.Errorf("Expected %s.Tables[%s].ClusteringColumns[%d].Name to be '%v' but was '%v'", expected.Name, keyT, i, et.ClusteringColumns[i].Name, at.ClusteringColumns[i].Name) - } - if expected.Name != at.ClusteringColumns[i].Keyspace { - t.Errorf("Expected %s.Tables[%s].ClusteringColumns[%d].Keyspace to be '%v' but was '%v'", expected.Name, keyT, i, expected.Name, at.ClusteringColumns[i].Keyspace) - } - if keyT != at.ClusteringColumns[i].Table { - t.Errorf("Expected %s.Tables[%s].ClusteringColumns[%d].Table to be '%v' but was '%v'", expected.Name, keyT, i, keyT, at.ClusteringColumns[i].Table) - } - if et.ClusteringColumns[i].Type.Type() != at.ClusteringColumns[i].Type.Type() { - t.Errorf("Expected %s.Tables[%s].ClusteringColumns[%d].Type.Type to be %v but was %v", expected.Name, keyT, i, et.ClusteringColumns[i].Type.Type(), at.ClusteringColumns[i].Type.Type()) - } - if i != at.ClusteringColumns[i].ComponentIndex { - t.Errorf("Expected %s.Tables[%s].ClusteringColumns[%d].ComponentIndex to be %v but was %v", expected.Name, keyT, i, i, at.ClusteringColumns[i].ComponentIndex) - } - if et.ClusteringColumns[i].Order != at.ClusteringColumns[i].Order { - t.Errorf("Expected %s.Tables[%s].ClusteringColumns[%d].Order to be %v but was %v", expected.Name, keyT, i, et.ClusteringColumns[i].Order, at.ClusteringColumns[i].Order) - } - if CLUSTERING_KEY != at.ClusteringColumns[i].Kind { - t.Errorf("Expected %s.Tables[%s].ClusteringColumns[%d].Kind to be '%v' but was '%v'", expected.Name, keyT, i, CLUSTERING_KEY, at.ClusteringColumns[i].Kind) - } - } - } - if len(et.Columns) != len(at.Columns) { - eKeys := make([]string, 0, len(et.Columns)) - for key := range et.Columns { - eKeys = append(eKeys, key) - } - aKeys := make([]string, 0, len(at.Columns)) - for key := range at.Columns { - aKeys = append(aKeys, key) - } - t.Errorf("Expected len(%s.Tables[%s].Columns) to be %v (keys:%v) but was %v (keys:%v)", expected.Name, keyT, len(et.Columns), eKeys, len(at.Columns), aKeys) - } else { - for keyC := range et.Columns { - ec := et.Columns[keyC] - ac, found := at.Columns[keyC] - - if !found { - t.Errorf("Expected %s.Tables[%s].Columns[%s] but was not found", expected.Name, keyT, keyC) - } else { - if keyC != ac.Name { - t.Errorf("Expected %s.Tables[%s].Columns[%s].Name to be '%v' but was '%v'", expected.Name, keyT, keyC, keyC, at.Name) - } - if expected.Name != ac.Keyspace { - t.Errorf("Expected %s.Tables[%s].Columns[%s].Keyspace to be '%v' but was '%v'", expected.Name, keyT, keyC, expected.Name, ac.Keyspace) - } - if keyT != ac.Table { - t.Errorf("Expected %s.Tables[%s].Columns[%s].Table to be '%v' but was '%v'", expected.Name, keyT, keyC, keyT, ac.Table) - } - if ec.Type.Type() != ac.Type.Type() { - t.Errorf("Expected %s.Tables[%s].Columns[%s].Type.Type to be %v but was %v", expected.Name, keyT, keyC, ec.Type.Type(), ac.Type.Type()) - } - if ec.Order != ac.Order { - t.Errorf("Expected %s.Tables[%s].Columns[%s].Order to be %v but was %v", expected.Name, keyT, keyC, ec.Order, ac.Order) - } - if ec.Kind != ac.Kind { - t.Errorf("Expected %s.Tables[%s].Columns[%s].Kind to be '%v' but was '%v'", expected.Name, keyT, keyC, ec.Kind, ac.Kind) - } - } - } - } - } - } -} - -// Tests the cassandra type definition parser -func TestTypeParser(t *testing.T) { - // native type - assertParseNonCompositeType( - t, - "org.apache.cassandra.db.marshal.UTF8Type", - assertTypeInfo{Type: TypeVarchar}, - ) - - // reversed - assertParseNonCompositeType( - t, - "org.apache.cassandra.db.marshal.ReversedType(org.apache.cassandra.db.marshal.UUIDType)", - assertTypeInfo{Type: TypeUUID, Reversed: true}, - ) - - // set - assertParseNonCompositeType( - t, - "org.apache.cassandra.db.marshal.SetType(org.apache.cassandra.db.marshal.Int32Type)", - assertTypeInfo{ - Type: TypeSet, - Elem: &assertTypeInfo{Type: TypeInt}, - }, - ) - - // list - assertParseNonCompositeType( - t, - "org.apache.cassandra.db.marshal.ListType(org.apache.cassandra.db.marshal.TimeUUIDType)", - assertTypeInfo{ - Type: TypeList, - Elem: &assertTypeInfo{Type: TypeTimeUUID}, - }, - ) - - // map - assertParseNonCompositeType( - t, - " org.apache.cassandra.db.marshal.MapType( org.apache.cassandra.db.marshal.UUIDType , org.apache.cassandra.db.marshal.BytesType ) ", - assertTypeInfo{ - Type: TypeMap, - Key: &assertTypeInfo{Type: TypeUUID}, - Elem: &assertTypeInfo{Type: TypeBlob}, - }, - ) - - // custom - assertParseNonCompositeType( - t, - "org.apache.cassandra.db.marshal.UserType(sandbox,61646472657373,737472656574:org.apache.cassandra.db.marshal.UTF8Type,63697479:org.apache.cassandra.db.marshal.UTF8Type,7a6970:org.apache.cassandra.db.marshal.Int32Type)", - assertTypeInfo{Type: TypeCustom, Custom: "org.apache.cassandra.db.marshal.UserType(sandbox,61646472657373,737472656574:org.apache.cassandra.db.marshal.UTF8Type,63697479:org.apache.cassandra.db.marshal.UTF8Type,7a6970:org.apache.cassandra.db.marshal.Int32Type)"}, - ) - assertParseNonCompositeType( - t, - "org.apache.cassandra.db.marshal.DynamicCompositeType(u=>org.apache.cassandra.db.marshal.UUIDType,d=>org.apache.cassandra.db.marshal.DateType,t=>org.apache.cassandra.db.marshal.TimeUUIDType,b=>org.apache.cassandra.db.marshal.BytesType,s=>org.apache.cassandra.db.marshal.UTF8Type,B=>org.apache.cassandra.db.marshal.BooleanType,a=>org.apache.cassandra.db.marshal.AsciiType,l=>org.apache.cassandra.db.marshal.LongType,i=>org.apache.cassandra.db.marshal.IntegerType,x=>org.apache.cassandra.db.marshal.LexicalUUIDType)", - assertTypeInfo{Type: TypeCustom, Custom: "org.apache.cassandra.db.marshal.DynamicCompositeType(u=>org.apache.cassandra.db.marshal.UUIDType,d=>org.apache.cassandra.db.marshal.DateType,t=>org.apache.cassandra.db.marshal.TimeUUIDType,b=>org.apache.cassandra.db.marshal.BytesType,s=>org.apache.cassandra.db.marshal.UTF8Type,B=>org.apache.cassandra.db.marshal.BooleanType,a=>org.apache.cassandra.db.marshal.AsciiType,l=>org.apache.cassandra.db.marshal.LongType,i=>org.apache.cassandra.db.marshal.IntegerType,x=>org.apache.cassandra.db.marshal.LexicalUUIDType)"}, - ) - - // composite defs - assertParseCompositeType( - t, - "org.apache.cassandra.db.marshal.CompositeType(org.apache.cassandra.db.marshal.UTF8Type)", - []assertTypeInfo{ - assertTypeInfo{Type: TypeVarchar}, - }, - nil, - ) - assertParseCompositeType( - t, - "org.apache.cassandra.db.marshal.CompositeType(org.apache.cassandra.db.marshal.ReversedType(org.apache.cassandra.db.marshal.DateType),org.apache.cassandra.db.marshal.UTF8Type)", - []assertTypeInfo{ - assertTypeInfo{Type: TypeTimestamp, Reversed: true}, - assertTypeInfo{Type: TypeVarchar}, - }, - nil, - ) - assertParseCompositeType( - t, - "org.apache.cassandra.db.marshal.CompositeType(org.apache.cassandra.db.marshal.UTF8Type,org.apache.cassandra.db.marshal.ColumnToCollectionType(726f77735f6d6572676564:org.apache.cassandra.db.marshal.MapType(org.apache.cassandra.db.marshal.Int32Type,org.apache.cassandra.db.marshal.LongType)))", - []assertTypeInfo{ - assertTypeInfo{Type: TypeVarchar}, - }, - map[string]assertTypeInfo{ - "rows_merged": assertTypeInfo{ - Type: TypeMap, - Key: &assertTypeInfo{Type: TypeInt}, - Elem: &assertTypeInfo{Type: TypeBigInt}, - }, - }, - ) -} - -// expected data holder -type assertTypeInfo struct { - Type Type - Reversed bool - Elem *assertTypeInfo - Key *assertTypeInfo - Custom string -} - -// Helper function for asserting that the type parser returns the expected -// results for the given definition -func assertParseNonCompositeType( - t *testing.T, - def string, - typeExpected assertTypeInfo, -) { - - result := parseType(def) - if len(result.reversed) != 1 { - t.Errorf("%s expected %d reversed values but there were %d", def, 1, len(result.reversed)) - } - - assertParseNonCompositeTypes( - t, - def, - []assertTypeInfo{typeExpected}, - result.types, - ) - - // expect no composite part of the result - if result.isComposite { - t.Errorf("%s: Expected not composite", def) - } - if result.collections != nil { - t.Errorf("%s: Expected nil collections: %v", def, result.collections) - } -} - -// Helper function for asserting that the type parser returns the expected -// results for the given definition -func assertParseCompositeType( - t *testing.T, - def string, - typesExpected []assertTypeInfo, - collectionsExpected map[string]assertTypeInfo, -) { - - result := parseType(def) - if len(result.reversed) != len(typesExpected) { - t.Errorf("%s expected %d reversed values but there were %d", def, len(typesExpected), len(result.reversed)) - } - - assertParseNonCompositeTypes( - t, - def, - typesExpected, - result.types, - ) - - // expect composite part of the result - if !result.isComposite { - t.Errorf("%s: Expected composite", def) - } - if result.collections == nil { - t.Errorf("%s: Expected non-nil collections: %v", def, result.collections) - } - - for name, typeExpected := range collectionsExpected { - // check for an actual type for this name - typeActual, found := result.collections[name] - if !found { - t.Errorf("%s.tcollections: Expected param named %s but there wasn't", def, name) - } else { - // remove the actual from the collection so we can detect extras - delete(result.collections, name) - - // check the type - assertParseNonCompositeTypes( - t, - def+"collections["+name+"]", - []assertTypeInfo{typeExpected}, - []TypeInfo{typeActual}, - ) - } - } - - if len(result.collections) != 0 { - t.Errorf("%s.collections: Expected no more types in collections, but there was %v", def, result.collections) - } -} - -// Helper function for asserting that the type parser returns the expected -// results for the given definition -func assertParseNonCompositeTypes( - t *testing.T, - context string, - typesExpected []assertTypeInfo, - typesActual []TypeInfo, -) { - if len(typesActual) != len(typesExpected) { - t.Errorf("%s: Expected %d types, but there were %d", context, len(typesExpected), len(typesActual)) - } - - for i := range typesExpected { - typeExpected := typesExpected[i] - typeActual := typesActual[i] - - // shadow copy the context for local modification - context := context - if len(typesExpected) > 1 { - context = context + "[" + strconv.Itoa(i) + "]" - } - - // check the type - if typeActual.Type() != typeExpected.Type { - t.Errorf("%s: Expected to parse Type to %s but was %s", context, typeExpected.Type, typeActual.Type()) - } - // check the custom - if typeActual.Custom() != typeExpected.Custom { - t.Errorf("%s: Expected to parse Custom %s but was %s", context, typeExpected.Custom, typeActual.Custom()) - } - - collection, _ := typeActual.(CollectionType) - // check the elem - if typeExpected.Elem != nil { - if collection.Elem == nil { - t.Errorf("%s: Expected to parse Elem, but was nil ", context) - } else { - assertParseNonCompositeTypes( - t, - context+".Elem", - []assertTypeInfo{*typeExpected.Elem}, - []TypeInfo{collection.Elem}, - ) - } - } else if collection.Elem != nil { - t.Errorf("%s: Expected to not parse Elem, but was %+v", context, collection.Elem) - } - - // check the key - if typeExpected.Key != nil { - if collection.Key == nil { - t.Errorf("%s: Expected to parse Key, but was nil ", context) - } else { - assertParseNonCompositeTypes( - t, - context+".Key", - []assertTypeInfo{*typeExpected.Key}, - []TypeInfo{collection.Key}, - ) - } - } else if collection.Key != nil { - t.Errorf("%s: Expected to not parse Key, but was %+v", context, collection.Key) - } - } -} diff --git a/Godeps/_workspace/src/github.com/gocql/gocql/murmur.go b/Godeps/_workspace/src/github.com/gocql/gocql/murmur.go new file mode 100644 index 000000000..eb287f5b4 --- /dev/null +++ b/Godeps/_workspace/src/github.com/gocql/gocql/murmur.go @@ -0,0 +1,139 @@ +// +build !appengine + +package gocql + +import ( + "unsafe" +) + +func murmur3H1(data []byte) uint64 { + length := len(data) + + var h1, h2, k1, k2 uint64 + + const ( + c1 = 0x87c37b91114253d5 + c2 = 0x4cf5ad432745937f + ) + + // body + nBlocks := length / 16 + for i := 0; i < nBlocks; i++ { + block := (*[2]uint64)(unsafe.Pointer(&data[i*16])) + + k1 = block[0] + k2 = block[1] + + k1 *= c1 + k1 = (k1 << 31) | (k1 >> 33) // ROTL64(k1, 31) + k1 *= c2 + h1 ^= k1 + + h1 = (h1 << 27) | (h1 >> 37) // ROTL64(h1, 27) + h1 += h2 + h1 = h1*5 + 0x52dce729 + + k2 *= c2 + k2 = (k2 << 33) | (k2 >> 31) // ROTL64(k2, 33) + k2 *= c1 + h2 ^= k2 + + h2 = (h2 << 31) | (h2 >> 33) // ROTL64(h2, 31) + h2 += h1 + h2 = h2*5 + 0x38495ab5 + } + + // tail + tail := data[nBlocks*16:] + k1 = 0 + k2 = 0 + switch length & 15 { + case 15: + k2 ^= uint64(tail[14]) << 48 + fallthrough + case 14: + k2 ^= uint64(tail[13]) << 40 + fallthrough + case 13: + k2 ^= uint64(tail[12]) << 32 + fallthrough + case 12: + k2 ^= uint64(tail[11]) << 24 + fallthrough + case 11: + k2 ^= uint64(tail[10]) << 16 + fallthrough + case 10: + k2 ^= uint64(tail[9]) << 8 + fallthrough + case 9: + k2 ^= uint64(tail[8]) + + k2 *= c2 + k2 = (k2 << 33) | (k2 >> 31) // ROTL64(k2, 33) + k2 *= c1 + h2 ^= k2 + + fallthrough + case 8: + k1 ^= uint64(tail[7]) << 56 + fallthrough + case 7: + k1 ^= uint64(tail[6]) << 48 + fallthrough + case 6: + k1 ^= uint64(tail[5]) << 40 + fallthrough + case 5: + k1 ^= uint64(tail[4]) << 32 + fallthrough + case 4: + k1 ^= uint64(tail[3]) << 24 + fallthrough + case 3: + k1 ^= uint64(tail[2]) << 16 + fallthrough + case 2: + k1 ^= uint64(tail[1]) << 8 + fallthrough + case 1: + k1 ^= uint64(tail[0]) + + k1 *= c1 + k1 = (k1 << 31) | (k1 >> 33) // ROTL64(k1, 31) + k1 *= c2 + h1 ^= k1 + } + + h1 ^= uint64(length) + h2 ^= uint64(length) + + h1 += h2 + h2 += h1 + + // finalizer + const ( + fmix1 = 0xff51afd7ed558ccd + fmix2 = 0xc4ceb9fe1a85ec53 + ) + + // fmix64(h1) + h1 ^= h1 >> 33 + h1 *= fmix1 + h1 ^= h1 >> 33 + h1 *= fmix2 + h1 ^= h1 >> 33 + + // fmix64(h2) + h2 ^= h2 >> 33 + h2 *= fmix1 + h2 ^= h2 >> 33 + h2 *= fmix2 + h2 ^= h2 >> 33 + + h1 += h2 + // the following is extraneous since h2 is discarded + // h2 += h1 + + return h1 +} diff --git a/Godeps/_workspace/src/github.com/gocql/gocql/murmur_appengine.go b/Godeps/_workspace/src/github.com/gocql/gocql/murmur_appengine.go new file mode 100644 index 000000000..9899b425f --- /dev/null +++ b/Godeps/_workspace/src/github.com/gocql/gocql/murmur_appengine.go @@ -0,0 +1,137 @@ +// +build appengine + +package gocql + +import "encoding/binary" + +func murmur3H1(data []byte) uint64 { + length := len(data) + + var h1, h2, k1, k2 uint64 + + const ( + c1 = 0x87c37b91114253d5 + c2 = 0x4cf5ad432745937f + ) + + // body + nBlocks := length / 16 + for i := 0; i < nBlocks; i++ { + // block := (*[2]uint64)(unsafe.Pointer(&data[i*16])) + + k1 = binary.LittleEndian.Uint64(data[i*16:]) + k2 = binary.LittleEndian.Uint64(data[(i*16)+8:]) + + k1 *= c1 + k1 = (k1 << 31) | (k1 >> 33) // ROTL64(k1, 31) + k1 *= c2 + h1 ^= k1 + + h1 = (h1 << 27) | (h1 >> 37) // ROTL64(h1, 27) + h1 += h2 + h1 = h1*5 + 0x52dce729 + + k2 *= c2 + k2 = (k2 << 33) | (k2 >> 31) // ROTL64(k2, 33) + k2 *= c1 + h2 ^= k2 + + h2 = (h2 << 31) | (h2 >> 33) // ROTL64(h2, 31) + h2 += h1 + h2 = h2*5 + 0x38495ab5 + } + + // tail + tail := data[nBlocks*16:] + k1 = 0 + k2 = 0 + switch length & 15 { + case 15: + k2 ^= uint64(tail[14]) << 48 + fallthrough + case 14: + k2 ^= uint64(tail[13]) << 40 + fallthrough + case 13: + k2 ^= uint64(tail[12]) << 32 + fallthrough + case 12: + k2 ^= uint64(tail[11]) << 24 + fallthrough + case 11: + k2 ^= uint64(tail[10]) << 16 + fallthrough + case 10: + k2 ^= uint64(tail[9]) << 8 + fallthrough + case 9: + k2 ^= uint64(tail[8]) + + k2 *= c2 + k2 = (k2 << 33) | (k2 >> 31) // ROTL64(k2, 33) + k2 *= c1 + h2 ^= k2 + + fallthrough + case 8: + k1 ^= uint64(tail[7]) << 56 + fallthrough + case 7: + k1 ^= uint64(tail[6]) << 48 + fallthrough + case 6: + k1 ^= uint64(tail[5]) << 40 + fallthrough + case 5: + k1 ^= uint64(tail[4]) << 32 + fallthrough + case 4: + k1 ^= uint64(tail[3]) << 24 + fallthrough + case 3: + k1 ^= uint64(tail[2]) << 16 + fallthrough + case 2: + k1 ^= uint64(tail[1]) << 8 + fallthrough + case 1: + k1 ^= uint64(tail[0]) + + k1 *= c1 + k1 = (k1 << 31) | (k1 >> 33) // ROTL64(k1, 31) + k1 *= c2 + h1 ^= k1 + } + + h1 ^= uint64(length) + h2 ^= uint64(length) + + h1 += h2 + h2 += h1 + + // finalizer + const ( + fmix1 = 0xff51afd7ed558ccd + fmix2 = 0xc4ceb9fe1a85ec53 + ) + + // fmix64(h1) + h1 ^= h1 >> 33 + h1 *= fmix1 + h1 ^= h1 >> 33 + h1 *= fmix2 + h1 ^= h1 >> 33 + + // fmix64(h2) + h2 ^= h2 >> 33 + h2 *= fmix1 + h2 ^= h2 >> 33 + h2 *= fmix2 + h2 ^= h2 >> 33 + + h1 += h2 + // the following is extraneous since h2 is discarded + // h2 += h1 + + return h1 +} diff --git a/Godeps/_workspace/src/github.com/gocql/gocql/policies_test.go b/Godeps/_workspace/src/github.com/gocql/gocql/policies_test.go deleted file mode 100644 index 78f147f4c..000000000 --- a/Godeps/_workspace/src/github.com/gocql/gocql/policies_test.go +++ /dev/null @@ -1,125 +0,0 @@ -// Copyright (c) 2015 The gocql 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 gocql - -import "testing" - -// Tests of the round-robin host selection policy implementation -func TestRoundRobinHostPolicy(t *testing.T) { - policy := NewRoundRobinHostPolicy() - - hosts := []HostInfo{ - HostInfo{HostId: "0"}, - HostInfo{HostId: "1"}, - } - - policy.SetHosts(hosts) - - // the first host selected is actually at [1], but this is ok for RR - // interleaved iteration should always increment the host - iterA := policy.Pick(nil) - if actual := iterA(); actual != &hosts[1] { - t.Errorf("Expected hosts[1] but was hosts[%s]", actual.HostId) - } - iterB := policy.Pick(nil) - if actual := iterB(); actual != &hosts[0] { - t.Errorf("Expected hosts[0] but was hosts[%s]", actual.HostId) - } - if actual := iterB(); actual != &hosts[1] { - t.Errorf("Expected hosts[1] but was hosts[%s]", actual.HostId) - } - if actual := iterA(); actual != &hosts[0] { - t.Errorf("Expected hosts[0] but was hosts[%s]", actual.HostId) - } - - iterC := policy.Pick(nil) - if actual := iterC(); actual != &hosts[1] { - t.Errorf("Expected hosts[1] but was hosts[%s]", actual.HostId) - } - if actual := iterC(); actual != &hosts[0] { - t.Errorf("Expected hosts[0] but was hosts[%s]", actual.HostId) - } -} - -// Tests of the token-aware host selection policy implementation with a -// round-robin host selection policy fallback. -func TestTokenAwareHostPolicy(t *testing.T) { - policy := NewTokenAwareHostPolicy(NewRoundRobinHostPolicy()) - - query := &Query{} - - iter := policy.Pick(nil) - if iter == nil { - t.Fatal("host iterator was nil") - } - actual := iter() - if actual != nil { - t.Fatalf("expected nil from iterator, but was %v", actual) - } - - // set the hosts - hosts := []HostInfo{ - HostInfo{Peer: "0", Tokens: []string{"00"}}, - HostInfo{Peer: "1", Tokens: []string{"25"}}, - HostInfo{Peer: "2", Tokens: []string{"50"}}, - HostInfo{Peer: "3", Tokens: []string{"75"}}, - } - policy.SetHosts(hosts) - - // the token ring is not setup without the partitioner, but the fallback - // should work - if actual := policy.Pick(nil)(); actual.Peer != "1" { - t.Errorf("Expected peer 1 but was %s", actual.Peer) - } - - query.RoutingKey([]byte("30")) - if actual := policy.Pick(query)(); actual.Peer != "2" { - t.Errorf("Expected peer 2 but was %s", actual.Peer) - } - - policy.SetPartitioner("OrderedPartitioner") - - // now the token ring is configured - query.RoutingKey([]byte("20")) - iter = policy.Pick(query) - if actual := iter(); actual.Peer != "1" { - t.Errorf("Expected peer 1 but was %s", actual.Peer) - } - // rest are round robin - if actual := iter(); actual.Peer != "3" { - t.Errorf("Expected peer 3 but was %s", actual.Peer) - } - if actual := iter(); actual.Peer != "0" { - t.Errorf("Expected peer 0 but was %s", actual.Peer) - } - if actual := iter(); actual.Peer != "2" { - t.Errorf("Expected peer 2 but was %s", actual.Peer) - } -} - -// Tests of the round-robin connection selection policy implementation -func TestRoundRobinConnPolicy(t *testing.T) { - policy := NewRoundRobinConnPolicy() - - conn0 := &Conn{} - conn1 := &Conn{} - conn := []*Conn{ - conn0, - conn1, - } - - policy.SetConns(conn) - - // the first conn selected is actually at [1], but this is ok for RR - if actual := policy.Pick(nil); actual != conn1 { - t.Error("Expected conn1") - } - if actual := policy.Pick(nil); actual != conn0 { - t.Error("Expected conn0") - } - if actual := policy.Pick(nil); actual != conn1 { - t.Error("Expected conn1") - } -} diff --git a/Godeps/_workspace/src/github.com/gocql/gocql/session.go b/Godeps/_workspace/src/github.com/gocql/gocql/session.go index 52bd915ce..33c356a78 100644 --- a/Godeps/_workspace/src/github.com/gocql/gocql/session.go +++ b/Godeps/_workspace/src/github.com/gocql/gocql/session.go @@ -15,7 +15,7 @@ import ( "time" "unicode" - "github.com/golang/groupcache/lru" + "github.com/gocql/gocql/lru" ) // Session is the interface used by users to interact with the database. @@ -260,9 +260,8 @@ func (s *Session) KeyspaceMetadata(keyspace string) (*KeyspaceMetadata, error) { // returns routing key indexes and type info func (s *Session) routingKeyInfo(stmt string) (*routingKeyInfo, error) { s.routingKeyInfoCache.mu.Lock() - cacheKey := s.cfg.Keyspace + stmt - entry, cached := s.routingKeyInfoCache.lru.Get(cacheKey) + entry, cached := s.routingKeyInfoCache.lru.Get(stmt) if cached { // done accessing the cache s.routingKeyInfoCache.mu.Unlock() @@ -286,7 +285,7 @@ func (s *Session) routingKeyInfo(stmt string) (*routingKeyInfo, error) { inflight := new(inflightCachedEntry) inflight.wg.Add(1) defer inflight.wg.Done() - s.routingKeyInfoCache.lru.Add(cacheKey, inflight) + s.routingKeyInfoCache.lru.Add(stmt, inflight) s.routingKeyInfoCache.mu.Unlock() var ( @@ -300,14 +299,14 @@ func (s *Session) routingKeyInfo(stmt string) (*routingKeyInfo, error) { // no connections inflight.err = ErrNoConnections // don't cache this error - s.routingKeyInfoCache.Remove(cacheKey) + s.routingKeyInfoCache.Remove(stmt) return nil, inflight.err } prepared, inflight.err = conn.prepareStatement(stmt, nil) if inflight.err != nil { // don't cache this error - s.routingKeyInfoCache.Remove(cacheKey) + s.routingKeyInfoCache.Remove(stmt) return nil, inflight.err } @@ -323,7 +322,7 @@ func (s *Session) routingKeyInfo(stmt string) (*routingKeyInfo, error) { keyspaceMetadata, inflight.err = s.KeyspaceMetadata(s.cfg.Keyspace) if inflight.err != nil { // don't cache this error - s.routingKeyInfoCache.Remove(cacheKey) + s.routingKeyInfoCache.Remove(stmt) return nil, inflight.err } @@ -334,7 +333,7 @@ func (s *Session) routingKeyInfo(stmt string) (*routingKeyInfo, error) { // in the metadata code, or that the table was just dropped. inflight.err = ErrNoMetadata // don't cache this error - s.routingKeyInfoCache.Remove(cacheKey) + s.routingKeyInfoCache.Remove(stmt) return nil, inflight.err } @@ -422,6 +421,7 @@ type Query struct { cons Consistency pageSize int routingKey []byte + routingKeyBuffer []byte pageState []byte prefetch float64 trace Tracer @@ -432,6 +432,8 @@ type Query struct { totalLatency int64 serialCons SerialConsistency defaultTimestamp bool + + disableAutoPage bool } // String implements the stringer interface. @@ -532,8 +534,14 @@ func (q *Query) GetRoutingKey() ([]byte, error) { return routingKey, nil } + // We allocate that buffer only once, so that further re-bind/exec of the + // same query don't allocate more memory. + if q.routingKeyBuffer == nil { + q.routingKeyBuffer = make([]byte, 0, 256) + } + // composite routing key - buf := &bytes.Buffer{} + buf := bytes.NewBuffer(q.routingKeyBuffer) for i := range routingKeyInfo.indexes { encoded, err := Marshal( routingKeyInfo.types[i], @@ -542,7 +550,9 @@ func (q *Query) GetRoutingKey() ([]byte, error) { if err != nil { return nil, err } - binary.Write(buf, binary.BigEndian, int16(len(encoded))) + lenBuf := []byte{0x00, 0x00} + binary.BigEndian.PutUint16(lenBuf, uint16(len(encoded))) + buf.Write(lenBuf) buf.Write(encoded) buf.WriteByte(0x00) } @@ -603,16 +613,33 @@ func (q *Query) SerialConsistency(cons SerialConsistency) *Query { return q } +// PageState sets the paging state for the query to resume paging from a specific +// point in time. Setting this will disable to query paging for this query, and +// must be used for all subsequent pages. +func (q *Query) PageState(state []byte) *Query { + q.pageState = state + q.disableAutoPage = true + return q +} + // Exec executes the query without returning any rows. func (q *Query) Exec() error { iter := q.Iter() return iter.err } +func isUseStatement(stmt string) bool { + if len(stmt) < 3 { + return false + } + + return strings.ToLower(stmt[0:3]) == "use" +} + // Iter executes the query and returns an iterator capable of iterating // over all results. func (q *Query) Iter() *Iter { - if strings.Index(strings.ToLower(q.stmt), "use") == 0 { + if isUseStatement(q.stmt) { return &Iter{err: ErrUseStmt} } return q.session.executeQuery(q) @@ -775,6 +802,12 @@ func (iter *Iter) checkErrAndNotFound() error { return nil } +// PageState return the current paging state for a query which can be used for +// subsequent quries to resume paging this point. +func (iter *Iter) PageState() []byte { + return iter.meta.pagingState +} + type nextIter struct { qry Query pos int diff --git a/Godeps/_workspace/src/github.com/gocql/gocql/session_test.go b/Godeps/_workspace/src/github.com/gocql/gocql/session_test.go deleted file mode 100644 index fa41b6689..000000000 --- a/Godeps/_workspace/src/github.com/gocql/gocql/session_test.go +++ /dev/null @@ -1,255 +0,0 @@ -// +build all integration - -package gocql - -import ( - "fmt" - "testing" -) - -func TestSessionAPI(t *testing.T) { - - cfg := &ClusterConfig{} - pool, err := NewSimplePool(cfg) - if err != nil { - t.Fatal(err) - } - - s := &Session{ - Pool: pool, - cfg: *cfg, - cons: Quorum, - } - - defer s.Close() - - s.SetConsistency(All) - if s.cons != All { - t.Fatalf("expected consistency 'All', got '%v'", s.cons) - } - - s.SetPageSize(100) - if s.pageSize != 100 { - t.Fatalf("expected pageSize 100, got %v", s.pageSize) - } - - s.SetPrefetch(0.75) - if s.prefetch != 0.75 { - t.Fatalf("expceted prefetch 0.75, got %v", s.prefetch) - } - - trace := &traceWriter{} - - s.SetTrace(trace) - if s.trace != trace { - t.Fatalf("expected traceWriter '%v',got '%v'", trace, s.trace) - } - - qry := s.Query("test", 1) - if v, ok := qry.values[0].(int); !ok { - t.Fatalf("expected qry.values[0] to be an int, got %v", qry.values[0]) - } else if v != 1 { - t.Fatalf("expceted qry.values[0] to be 1, got %v", v) - } else if qry.stmt != "test" { - t.Fatalf("expected qry.stmt to be 'test', got '%v'", qry.stmt) - } - - boundQry := s.Bind("test", func(q *QueryInfo) ([]interface{}, error) { - return nil, nil - }) - if boundQry.binding == nil { - t.Fatal("expected qry.binding to be defined, got nil") - } else if boundQry.stmt != "test" { - t.Fatalf("expected qry.stmt to be 'test', got '%v'", boundQry.stmt) - } - - itr := s.executeQuery(qry) - if itr.err != ErrNoConnections { - t.Fatalf("expected itr.err to be '%v', got '%v'", ErrNoConnections, itr.err) - } - - testBatch := s.NewBatch(LoggedBatch) - testBatch.Query("test") - err = s.ExecuteBatch(testBatch) - - if err != ErrNoConnections { - t.Fatalf("expected session.ExecuteBatch to return '%v', got '%v'", ErrNoConnections, err) - } - - s.Close() - if !s.Closed() { - t.Fatal("expected s.Closed() to be true, got false") - } - //Should just return cleanly - s.Close() - - err = s.ExecuteBatch(testBatch) - if err != ErrSessionClosed { - t.Fatalf("expected session.ExecuteBatch to return '%v', got '%v'", ErrSessionClosed, err) - } -} - -func TestQueryBasicAPI(t *testing.T) { - qry := &Query{} - - if qry.Latency() != 0 { - t.Fatalf("expected Query.Latency() to return 0, got %v", qry.Latency()) - } - - qry.attempts = 2 - qry.totalLatency = 4 - if qry.Attempts() != 2 { - t.Fatalf("expected Query.Attempts() to return 2, got %v", qry.Attempts()) - } - if qry.Latency() != 2 { - t.Fatalf("expected Query.Latency() to return 2, got %v", qry.Latency()) - } - - qry.Consistency(All) - if qry.GetConsistency() != All { - t.Fatalf("expected Query.GetConsistency to return 'All', got '%s'", qry.GetConsistency()) - } - - trace := &traceWriter{} - qry.Trace(trace) - if qry.trace != trace { - t.Fatalf("expected Query.Trace to be '%v', got '%v'", trace, qry.trace) - } - - qry.PageSize(10) - if qry.pageSize != 10 { - t.Fatalf("expected Query.PageSize to be 10, got %v", qry.pageSize) - } - - qry.Prefetch(0.75) - if qry.prefetch != 0.75 { - t.Fatalf("expected Query.Prefetch to be 0.75, got %v", qry.prefetch) - } - - rt := &SimpleRetryPolicy{NumRetries: 3} - if qry.RetryPolicy(rt); qry.rt != rt { - t.Fatalf("expected Query.RetryPolicy to be '%v', got '%v'", rt, qry.rt) - } - - qry.Bind(qry) - if qry.values[0] != qry { - t.Fatalf("expected Query.Values[0] to be '%v', got '%v'", qry, qry.values[0]) - } -} - -func TestQueryShouldPrepare(t *testing.T) { - toPrepare := []string{"select * ", "INSERT INTO", "update table", "delete from", "begin batch"} - cantPrepare := []string{"create table", "USE table", "LIST keyspaces", "alter table", "drop table", "grant user", "revoke user"} - q := &Query{} - - for i := 0; i < len(toPrepare); i++ { - q.stmt = toPrepare[i] - if !q.shouldPrepare() { - t.Fatalf("expected Query.shouldPrepare to return true, got false for statement '%v'", toPrepare[i]) - } - } - - for i := 0; i < len(cantPrepare); i++ { - q.stmt = cantPrepare[i] - if q.shouldPrepare() { - t.Fatalf("expected Query.shouldPrepare to return false, got true for statement '%v'", cantPrepare[i]) - } - } -} - -func TestBatchBasicAPI(t *testing.T) { - - cfg := &ClusterConfig{RetryPolicy: &SimpleRetryPolicy{NumRetries: 2}} - pool, err := NewSimplePool(cfg) - if err != nil { - t.Fatal(err) - } - - s := &Session{ - Pool: pool, - cfg: *cfg, - cons: Quorum, - } - defer s.Close() - - b := s.NewBatch(UnloggedBatch) - if b.Type != UnloggedBatch { - t.Fatalf("expceted batch.Type to be '%v', got '%v'", UnloggedBatch, b.Type) - } else if b.rt != cfg.RetryPolicy { - t.Fatalf("expceted batch.RetryPolicy to be '%v', got '%v'", cfg.RetryPolicy, b.rt) - } - - b = NewBatch(LoggedBatch) - if b.Type != LoggedBatch { - t.Fatalf("expected batch.Type to be '%v', got '%v'", LoggedBatch, b.Type) - } - - b.attempts = 1 - if b.Attempts() != 1 { - t.Fatalf("expceted batch.Attempts() to return %v, got %v", 1, b.Attempts()) - } - - if b.Latency() != 0 { - t.Fatalf("expected batch.Latency() to be 0, got %v", b.Latency()) - } - - b.totalLatency = 4 - if b.Latency() != 4 { - t.Fatalf("expected batch.Latency() to return %v, got %v", 4, b.Latency()) - } - - b.Cons = One - if b.GetConsistency() != One { - t.Fatalf("expected batch.GetConsistency() to return 'One', got '%s'", b.GetConsistency()) - } - - b.Query("test", 1) - if b.Entries[0].Stmt != "test" { - t.Fatalf("expected batch.Entries[0].Stmt to be 'test', got '%v'", b.Entries[0].Stmt) - } else if b.Entries[0].Args[0].(int) != 1 { - t.Fatalf("expected batch.Entries[0].Args[0] to be 1, got %v", b.Entries[0].Args[0]) - } - - b.Bind("test2", func(q *QueryInfo) ([]interface{}, error) { - return nil, nil - }) - - if b.Entries[1].Stmt != "test2" { - t.Fatalf("expected batch.Entries[1].Stmt to be 'test2', got '%v'", b.Entries[1].Stmt) - } else if b.Entries[1].binding == nil { - t.Fatal("expected batch.Entries[1].binding to be defined, got nil") - } - r := &SimpleRetryPolicy{NumRetries: 4} - - b.RetryPolicy(r) - if b.rt != r { - t.Fatalf("expected batch.RetryPolicy to be '%v', got '%v'", r, b.rt) - } - - if b.Size() != 2 { - t.Fatalf("expected batch.Size() to return 2, got %v", b.Size()) - } - -} - -func TestConsistencyNames(t *testing.T) { - names := map[fmt.Stringer]string{ - Any: "ANY", - One: "ONE", - Two: "TWO", - Three: "THREE", - Quorum: "QUORUM", - All: "ALL", - LocalQuorum: "LOCAL_QUORUM", - EachQuorum: "EACH_QUORUM", - Serial: "SERIAL", - LocalSerial: "LOCAL_SERIAL", - LocalOne: "LOCAL_ONE", - } - - for k, v := range names { - if k.String() != v { - t.Fatalf("expected '%v', got '%v'", v, k.String()) - } - } -} diff --git a/Godeps/_workspace/src/github.com/gocql/gocql/stress_test.go b/Godeps/_workspace/src/github.com/gocql/gocql/stress_test.go deleted file mode 100644 index 57e07085d..000000000 --- a/Godeps/_workspace/src/github.com/gocql/gocql/stress_test.go +++ /dev/null @@ -1,40 +0,0 @@ -// +build all integration - -package gocql - -import ( - "sync/atomic" - - "testing" -) - -func BenchmarkConnStress(b *testing.B) { - const workers = 16 - - cluster := createCluster() - cluster.NumConns = 1 - cluster.NumStreams = workers - session := createSessionFromCluster(cluster, b) - defer session.Close() - - if err := createTable(session, "CREATE TABLE IF NOT EXISTS conn_stress (id int primary key)"); err != nil { - b.Fatal(err) - } - - var seed uint64 - writer := func(pb *testing.PB) { - seed := atomic.AddUint64(&seed, 1) - var i uint64 = 0 - for pb.Next() { - if err := session.Query("insert into conn_stress (id) values (?)", i*seed).Exec(); err != nil { - b.Error(err) - return - } - i++ - } - } - - b.SetParallelism(workers) - b.RunParallel(writer) - -} diff --git a/Godeps/_workspace/src/github.com/gocql/gocql/testdata/pki/.keystore b/Godeps/_workspace/src/github.com/gocql/gocql/testdata/pki/.keystore deleted file mode 100644 index 0bbf1929f..000000000 --- a/Godeps/_workspace/src/github.com/gocql/gocql/testdata/pki/.keystore +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:d9d7522bb1c517241b555d66e3ba3e98922309c6378e625e991ee69372c97b7e -size 2178 diff --git a/Godeps/_workspace/src/github.com/gocql/gocql/testdata/pki/.truststore b/Godeps/_workspace/src/github.com/gocql/gocql/testdata/pki/.truststore deleted file mode 100644 index e7f20ba11..000000000 --- a/Godeps/_workspace/src/github.com/gocql/gocql/testdata/pki/.truststore +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:02b50c1f6bb4f5a6fb013c2c9ebe47ecd08db683dca48045f08e9e9ca98d8963 -size 882 diff --git a/Godeps/_workspace/src/github.com/gocql/gocql/testdata/pki/ca.crt b/Godeps/_workspace/src/github.com/gocql/gocql/testdata/pki/ca.crt deleted file mode 100644 index fc3ba63f2..000000000 --- a/Godeps/_workspace/src/github.com/gocql/gocql/testdata/pki/ca.crt +++ /dev/null @@ -1,20 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDLzCCAhegAwIBAgIJAIKbAXgemwsjMA0GCSqGSIb3DQEBCwUAMBQxEjAQBgNV -BAMTCWNhc3NhbmRyYTAeFw0xNDA5MTkyMTE4MTNaFw0yNDA5MTYyMTE4MTNaMBQx -EjAQBgNVBAMTCWNhc3NhbmRyYTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC -ggEBAL5fX0l1WDNa+mO1krxw7k8lfUQn+Ec4L3Mqv6IstGoNdCPq4YRA+SXRD5YC -k/UXrFBWh9Hbs849GiuTYMPdj9HDLYz40RaQjM9GbieS23iy3UStQ0tKhxaaG6FN -6XBypXFKCTsanu0TkEoDGhAkSzAMcCAC3gkFBzMrZ5qt4HEzjY9rasZ2gthN+xop -nq3t4dDkE8HGaiFJcFvqTor7xmrnAaPjrPzUpvOF/ObIC09omwg/KXdPRx4DKPon -gCMKEE3ckebKnJvbsRX3WO8H5nTHBYZ6v1JxLZz5pqmV+P0NGxldCARM0gCQUBz5 -wjMJkD/3e1ETC+q6uwfnAG0hlD8CAwEAAaOBgzCBgDAdBgNVHQ4EFgQUjHzn0nYF -iXEaI1vUWbRR4lwKXOgwRAYDVR0jBD0wO4AUjHzn0nYFiXEaI1vUWbRR4lwKXOih -GKQWMBQxEjAQBgNVBAMTCWNhc3NhbmRyYYIJAIKbAXgemwsjMAwGA1UdEwQFMAMB -Af8wCwYDVR0PBAQDAgEGMA0GCSqGSIb3DQEBCwUAA4IBAQBCYDdIhtf/Y12Et947 -am1B8TzSX+/iQ1V1J3JtvgD5F4fvNjfArat/I3D277WREUTAc76o16BCp2OBGqzO -zf9MvZPkjkAUoyU0TtPUEHyqxq4gZxbWKugIZGYkmQ1hCvSIgA5UnjRL3dylMmZb -Y33JJA2QY63FZwnhmWsM8FYZwh+8MzVCQx3mgXC/k/jS6OuYyIT/KjxQHHjyr5ZS -zAAQln1IcZycLfh1w5MtCFahCIethFcVDnWUWYPcPGDGgMJW7WBpNZdHbLxYY8cI -eCc3Hcrbdc/CG5CaLJeqUidBayjnlUIO/NNgglkJ1KhQzkM6bd+37e0AX1hLIqx7 -gIZR ------END CERTIFICATE----- diff --git a/Godeps/_workspace/src/github.com/gocql/gocql/testdata/pki/ca.key b/Godeps/_workspace/src/github.com/gocql/gocql/testdata/pki/ca.key deleted file mode 100644 index 4360c17a2..000000000 --- a/Godeps/_workspace/src/github.com/gocql/gocql/testdata/pki/ca.key +++ /dev/null @@ -1,30 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -Proc-Type: 4,ENCRYPTED -DEK-Info: DES-EDE3-CBC,54C8072C0FF3B3A3 - -27eijmHdgB+s3beNPmU0+iz+muxMD0BVvWkDzyec/uawMv/Cn4c3mYXOcsFxS3BL -+qLT9MEttOmjqhHSaVrDYOPKoJIMpn+bVeKiR08V89icO36shEPy1feGqanagKtw -ecgzFDBTA8ZbqjAhftXlhTwxADebvNms/2aDh5Aw04vIcbo8nQ/8z1Wz8O7Firsn -kaseSTMTC6lxc+pa2V1X6mN0/2UpDi55bZbx1Z/mQ3+1CsdHOx0p7m/KY2m3ysov -XluaC0sqmzHkcwNgDhUs3Jh+apE33vXzLGU+W4BDOwrYJiL6KpspZW/mJj3OEx8B -8xdAZU3a/ei8NUA/lDStGmcYX+dOysExwJ6GMrCBm9iufZiefDQCQ8yRqWnr6Zop -lsFd+CqHNWYxfWDI1pSUBw3bsgIjevI0f0B7PxkFEF0DmIhCgB324/uqToRzGsOF -4MSVg6cSK7Sjo/u3r8r75A3aUAcY8NbR3peiZfAPMsTiUcfp4DoU+MJTqkX5PyQq -FNxHOJoARZqjjQ2IhZiUQWfIINHvZ8F9G2K7VaES8A0EATyUghqaRyeLbyI3IYdW -pGZBzrpGtdFlk9AVetHDDlY+gQiurtYhxOsxvlxJJuTj8FV+A5NWSElfPele0OiR -iprE3xkFSk3whHu5L1vnzamvdSlnBWOAE7pQD7kQA6NmcEw/tqnXK0dVdAw8RIFh -4BKgv0sNrXzBgnzE8+bKLUf1a2Byc/YKuBrI7EpSZ9/VHYvOcgmOxNxMmRS6NYd1 -Ly+agQn0AyvsDmSlBZBp8GCzVp6JYBMDKSXyPVN8+wjK9OQM0PZdEdXouMwPCOVN -oNSjhmMtfjOsnG2SZ9tRas3p0qFdfh/N/E6Q7QHG3WD3cUIEweFV9ji1FTSRUrIa -shuKug8MUfNjvDJNMsdGyf6Hi/7Iik++42Rq3ZdTy0ZVkj5snv5yBN77pr2M/J4b -M+dsXjyXPO4SDW3kP/e3RnLRlWmUv1PNdOmNDdjBBUTKgVZ3ur+4HmSY1iDvhlUF -/hz2tz3/XUKQwYuv3KJVlBhLrniXeES36GK+JQadIszrjwb5N4q4p6xrIdIR7XgR -TJCSL1NGPLeQyjK6byWLNPRcCGrvnxWs0k0ev6trMRJL1EjsIFDCJam9szhcXkZP -iYl1d7ZMKPS3cAqCjdaFRSe65cZ+qI/cqxiv122orq/jkDY7ZSA9rWywY4YnYQ7A -BqvcPzC/6K0bteXqmMQkIy/84aSnEts6ecb/4s5e5xXLhHe0dchG0HkasC/Gb+v/ -m9NOqACTerWvSD+Ecv9OvnBjP+GTlA1g7xTiRANLXsTJuiJomtxewXcV6kGZEMmZ -QWerGtPJGGUx36WRWrMiPeBfWZoIbjYGPmOO5mYNXMTjABGGWcFnKAqWUKsFihi9 -pC0OpZ7A0dtc9uSm0ZmsHUc3XENMHTeeEN+qgWxVKcMzRKEcnapu/0OcHrOUHDZf -qPoG4EkNnG9kPMq3HzvFPx3qbQ017yl87vAkWy/Edo+ojfHoNghRBVGCw1zt/BMN -eJbFFHop+rQ87omz8WIL4K+zVf91rJ0REVAJssQVDo16O5wrMo+f+c8v2GANQks5 ------END RSA PRIVATE KEY----- diff --git a/Godeps/_workspace/src/github.com/gocql/gocql/testdata/pki/cassandra.crt b/Godeps/_workspace/src/github.com/gocql/gocql/testdata/pki/cassandra.crt deleted file mode 100644 index 9d2facf9d..000000000 --- a/Godeps/_workspace/src/github.com/gocql/gocql/testdata/pki/cassandra.crt +++ /dev/null @@ -1,83 +0,0 @@ -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 2 (0x2) - Signature Algorithm: sha256WithRSAEncryption - Issuer: CN=cassandra - Validity - Not Before: Sep 19 21:18:48 2014 GMT - Not After : Sep 16 21:18:48 2024 GMT - Subject: CN=cassandra - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - RSA Public Key: (2048 bit) - Modulus (2048 bit): - 00:e5:9c:20:9e:de:98:73:44:41:0d:37:4c:62:c3: - 9f:87:5f:9b:4f:aa:cf:f6:90:6e:a5:e0:89:88:7a: - 00:c6:bb:d7:80:87:69:2e:fa:f0:35:59:80:6e:82: - 25:c8:b3:6c:f6:a4:97:97:93:93:ea:f0:70:70:a4: - e1:b7:aa:da:c1:99:66:9b:93:04:3a:ce:0b:83:07: - 06:22:3d:a6:db:7f:68:0f:49:80:bd:86:a8:bb:54: - 6d:38:5f:0f:b0:fa:1b:97:24:ae:cc:9d:37:98:7e: - 76:cc:e3:1b:45:1b:21:25:17:02:c0:1a:c5:fb:76: - c3:8b:93:d7:c5:85:14:0a:5c:a4:12:e7:18:69:98: - f5:76:cd:78:cd:99:5a:29:65:f1:68:20:97:d3:be: - 09:b3:68:1b:f2:a3:a2:9a:73:58:53:7e:ed:86:32: - a3:5a:d5:46:03:f9:b3:b4:ec:63:71:ba:bb:fb:6f: - f9:82:63:e4:55:47:7a:7a:e4:7b:17:6b:d7:e6:cf: - 3b:c9:ab:0c:30:15:c9:ed:c7:d6:fc:b6:72:b2:14: - 7d:c7:f3:7f:8a:f4:63:70:64:8e:0f:db:e8:3a:45: - 47:cd:b9:7b:ae:c8:31:c1:52:d1:3e:34:12:b7:73: - e7:ba:89:86:9a:36:ed:a0:5a:69:d0:d4:e3:b6:16: - 85:af - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: - CA:FALSE - X509v3 Subject Key Identifier: - 4A:D3:EC:63:07:E0:8F:1A:4E:F5:09:43:90:9F:7A:C5:31:D1:8F:D8 - X509v3 Authority Key Identifier: - keyid:8C:7C:E7:D2:76:05:89:71:1A:23:5B:D4:59:B4:51:E2:5C:0A:5C:E8 - DirName:/CN=cassandra - serial:82:9B:01:78:1E:9B:0B:23 - - X509v3 Extended Key Usage: - TLS Web Server Authentication - X509v3 Key Usage: - Digital Signature, Key Encipherment - Signature Algorithm: sha256WithRSAEncryption - ac:bc:80:82:2d:6d:f1:a0:46:eb:00:05:d2:25:9a:83:66:57: - 40:51:6e:ff:db:e3:28:04:7b:16:63:74:ec:55:a0:c0:5b:47: - 13:e1:5a:a5:6d:22:d0:e5:fe:c1:51:e8:f6:c6:9c:f9:be:b7: - be:82:14:e4:a0:b2:0b:9f:ee:68:bc:ac:17:0d:13:50:c6:9e: - 52:91:8c:a0:98:db:4e:2d:f6:3d:6e:85:0a:bb:b9:dd:01:bf: - ad:52:dd:6e:e4:41:01:a5:93:58:dd:3f:cf:bf:15:e6:25:aa: - a0:4f:98:0d:75:8a:3f:5b:ba:67:37:f6:b1:0b:3f:21:34:97: - 50:9a:85:97:2b:b6:05:41:9a:f3:cf:c4:92:23:06:ab:3e:87: - 98:30:eb:cb:d3:83:ab:04:7d:5c:b9:f0:12:d1:43:b3:c5:7d: - 33:9a:2e:2b:80:3a:66:be:f1:8c:08:37:7a:93:9c:9b:60:60: - 53:71:16:70:86:df:ca:5f:a9:0b:e2:8b:3d:af:02:62:3b:61: - 30:da:53:89:e3:d8:0b:88:04:9a:93:6a:f6:28:f8:dd:0d:8f: - 0c:82:5b:c0:e5:f8:0d:ad:06:76:a7:3b:4b:ae:54:37:25:15: - f5:0c:67:0f:77:c5:c4:97:68:09:c3:02:a7:a0:46:10:1c:d1: - 95:3a:4c:94 ------BEGIN CERTIFICATE----- -MIIDOTCCAiGgAwIBAgIBAjANBgkqhkiG9w0BAQsFADAUMRIwEAYDVQQDEwljYXNz -YW5kcmEwHhcNMTQwOTE5MjExODQ4WhcNMjQwOTE2MjExODQ4WjAUMRIwEAYDVQQD -EwljYXNzYW5kcmEwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDlnCCe -3phzREENN0xiw5+HX5tPqs/2kG6l4ImIegDGu9eAh2ku+vA1WYBugiXIs2z2pJeX -k5Pq8HBwpOG3qtrBmWabkwQ6zguDBwYiPabbf2gPSYC9hqi7VG04Xw+w+huXJK7M -nTeYfnbM4xtFGyElFwLAGsX7dsOLk9fFhRQKXKQS5xhpmPV2zXjNmVopZfFoIJfT -vgmzaBvyo6Kac1hTfu2GMqNa1UYD+bO07GNxurv7b/mCY+RVR3p65HsXa9fmzzvJ -qwwwFcntx9b8tnKyFH3H83+K9GNwZI4P2+g6RUfNuXuuyDHBUtE+NBK3c+e6iYaa -Nu2gWmnQ1OO2FoWvAgMBAAGjgZUwgZIwCQYDVR0TBAIwADAdBgNVHQ4EFgQUStPs -YwfgjxpO9QlDkJ96xTHRj9gwRAYDVR0jBD0wO4AUjHzn0nYFiXEaI1vUWbRR4lwK -XOihGKQWMBQxEjAQBgNVBAMTCWNhc3NhbmRyYYIJAIKbAXgemwsjMBMGA1UdJQQM -MAoGCCsGAQUFBwMBMAsGA1UdDwQEAwIFoDANBgkqhkiG9w0BAQsFAAOCAQEArLyA -gi1t8aBG6wAF0iWag2ZXQFFu/9vjKAR7FmN07FWgwFtHE+FapW0i0OX+wVHo9sac -+b63voIU5KCyC5/uaLysFw0TUMaeUpGMoJjbTi32PW6FCru53QG/rVLdbuRBAaWT -WN0/z78V5iWqoE+YDXWKP1u6Zzf2sQs/ITSXUJqFlyu2BUGa88/EkiMGqz6HmDDr -y9ODqwR9XLnwEtFDs8V9M5ouK4A6Zr7xjAg3epOcm2BgU3EWcIbfyl+pC+KLPa8C -YjthMNpTiePYC4gEmpNq9ij43Q2PDIJbwOX4Da0Gdqc7S65UNyUV9QxnD3fFxJdo -CcMCp6BGEBzRlTpMlA== ------END CERTIFICATE----- diff --git a/Godeps/_workspace/src/github.com/gocql/gocql/testdata/pki/cassandra.key b/Godeps/_workspace/src/github.com/gocql/gocql/testdata/pki/cassandra.key deleted file mode 100644 index 6878e8209..000000000 --- a/Godeps/_workspace/src/github.com/gocql/gocql/testdata/pki/cassandra.key +++ /dev/null @@ -1,27 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIIEpQIBAAKCAQEA5Zwgnt6Yc0RBDTdMYsOfh1+bT6rP9pBupeCJiHoAxrvXgIdp -LvrwNVmAboIlyLNs9qSXl5OT6vBwcKTht6rawZlmm5MEOs4LgwcGIj2m239oD0mA -vYaou1RtOF8PsPoblySuzJ03mH52zOMbRRshJRcCwBrF+3bDi5PXxYUUClykEucY -aZj1ds14zZlaKWXxaCCX074Js2gb8qOimnNYU37thjKjWtVGA/mztOxjcbq7+2/5 -gmPkVUd6euR7F2vX5s87yasMMBXJ7cfW/LZyshR9x/N/ivRjcGSOD9voOkVHzbl7 -rsgxwVLRPjQSt3PnuomGmjbtoFpp0NTjthaFrwIDAQABAoIBAQChjdjl73kUoVGk -GuSEGWCFv59nzqfEtJsl23bpr+4b5s8agCxiAe5Bm1fiaXBsZtKkN+rxm8TX6ZUz -rM+ki3KgBW9Mx4SSW6d96dNHBFoC1wJAv1b2A2l1ZVHz9+7ydwgysHzNO1GC2nh8 -cM8fMJeBoU8uG6hx5n5wFvYa5CfVoUQh8+Oq0b+mVxEFKHmRPnWp9/jPzL5eBIdr -ulbDt9S3dKJtouHgHBUNdkq/7Ex3QeHrUOahX6Y4eX1rzLnfLYY+0J4EA2PCKvgQ -bfKCxVnnzL6ywviH8eS3ql6OvTfnbK9kCRw7WxX9CC50qKj3EmwC/51MPhWohWlq -jw3qf38BAoGBAPPNyb3vUiyUqoErZxxIPFc2ob3vCjj06cvi7uKpOgrkdgC3iBhz -aCFQ28r7LrxLAHaKvNvwp71Lc7WYo8WWkLI1DVn0dx+GiQYW3DbNcwZOS40ZQz5L -zsjEcG4+cnZmuqGZBMNvQ+xUjkuucxvxPWKpEKM18GfDjgEkKbmDr+uNAoGBAPEY -kVSfSZGtP0MoXIfRkrxBlhvCj9m+p60P37pyHrJBrlrwvxB7x3Oz8S70D6kV8s2g -vVHgOS3VPj17VaQG8a3jBLKjzp5JLe34G8D1Ny8GqDc2wzOBtZySpJbifXuSUSPk -cqF7yiu1cD/wRPlwyWxBX9ZbaxvxnIUwLLd3ygkrAoGBAKQaw42uVkCdvPr/DQOT -d9I4erxO9zGJYQmU8bjtsZz9VJR89QWIQPIT7C3/zuB9F42zKxZcMXwQGo2EddAc -3b6mSRtgmwJEW10W7BmTRrZa4y3RcFqxSjoHR6pdLEyYL01woy0taqnb7H/yp5aK -VghfxkwllXEyxxXrko5FnpdNAoGBANeJLBunz2BxrnW+doJhZDnytFya4nk6TbKU -12FaNoEL4PCh+12kGtogSwS74eg6m/citT2mI9gKpHrYcOaT4qmeo4uEj+nH6Eyv -Gzi0wCHFZMr/pSC92/teyc+uKZo4Y1ugFq6w+Tt8GB7BERiisR+bji8XSTkRFemn -+MIIUFFDAoGAM8Va2Q5aTUkfg2mYlNLqT2tUAXVEhbmzjPA6laSo25PQEYWmX7vj -hiU0DPCDJQ/PlPI23xYtDDLNk83Zbx+Oj29GO5pawJY9NvFI8n60EFXfLbP1nEdG -j077QZNZOKfcgJirWi3+RrHSAK4tFftCe7rkV8ZmlMRBY3SDxzKOGcc= ------END RSA PRIVATE KEY----- diff --git a/Godeps/_workspace/src/github.com/gocql/gocql/testdata/pki/gocql.crt b/Godeps/_workspace/src/github.com/gocql/gocql/testdata/pki/gocql.crt deleted file mode 100644 index 22bf19f56..000000000 --- a/Godeps/_workspace/src/github.com/gocql/gocql/testdata/pki/gocql.crt +++ /dev/null @@ -1,83 +0,0 @@ -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 1 (0x1) - Signature Algorithm: sha256WithRSAEncryption - Issuer: CN=cassandra - Validity - Not Before: Sep 19 21:18:33 2014 GMT - Not After : Sep 16 21:18:33 2024 GMT - Subject: CN=gocql - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - RSA Public Key: (2048 bit) - Modulus (2048 bit): - 00:ae:e9:fa:9e:fd:e2:69:85:1d:08:0f:35:68:bc: - 63:7b:92:50:7f:73:50:fc:42:43:35:06:b3:5c:9e: - 27:1e:16:05:69:ec:88:d5:9c:4f:ef:e8:13:69:7a: - b5:b3:7f:66:6d:14:00:2e:d6:af:5b:ff:2c:90:91: - a6:11:07:72:5e:b0:37:c0:6d:ff:7b:76:2b:fe:de: - 4c:d2:8d:ce:43:3b:1a:c4:1d:de:b6:d8:26:08:25: - 89:59:a1:4b:94:a3:57:9e:19:46:28:6e:97:11:7c: - e6:b7:41:96:8f:42:dd:66:da:86:d2:53:dd:d8:f5: - 20:cd:24:8b:0f:ab:df:c4:10:b2:64:20:1d:e0:0f: - f4:2d:f6:ca:94:be:83:ac:3e:a8:4a:77:b6:08:97: - 3a:7e:7b:e0:3e:ab:68:cf:ee:f6:a1:8e:bf:ec:be: - 06:d1:ad:6c:ed:4f:35:d1:04:97:08:33:b1:65:5b: - 61:32:8d:4b:f0:30:35:4b:8b:6b:06:f2:1a:72:8c: - 69:bd:f3:b2:c4:a4:a4:70:45:e3:67:a2:7a:9f:2e: - cb:28:2d:9f:68:03:f1:c7:d9:4f:83:c9:3d:8c:34: - 04:0a:3b:13:87:92:e1:f7:e3:79:7e:ab:c0:25:b1: - e5:38:09:44:3e:31:df:12:d4:dc:7b:0e:35:bf:ee: - 25:5f - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: - CA:FALSE - X509v3 Subject Key Identifier: - 9F:F1:B2:C4:82:34:D0:2F:FF:E9:7F:19:F1:3B:51:57:BF:E8:95:BB - X509v3 Authority Key Identifier: - keyid:8C:7C:E7:D2:76:05:89:71:1A:23:5B:D4:59:B4:51:E2:5C:0A:5C:E8 - DirName:/CN=cassandra - serial:82:9B:01:78:1E:9B:0B:23 - - X509v3 Extended Key Usage: - TLS Web Client Authentication - X509v3 Key Usage: - Digital Signature - Signature Algorithm: sha256WithRSAEncryption - 12:aa:1b:a6:58:27:52:32:c9:46:19:32:d3:69:ae:95:ad:23: - 55:ad:12:65:da:2c:4c:72:f3:29:bd:2b:5a:97:3b:b7:68:8b: - 68:80:77:55:e6:32:81:f1:f5:20:54:ba:0e:2b:86:90:d8:44: - cf:f2:9f:ec:4d:39:67:4e:36:6c:9b:49:4a:80:e6:c1:ed:a4: - 41:39:19:16:d2:88:df:17:0c:46:5a:b9:88:53:f5:67:19:f0: - 1f:9a:51:40:1b:40:12:bc:57:db:de:dd:d3:f5:a8:93:68:30: - ac:ba:4e:ee:6b:af:f8:13:3d:11:1a:fa:90:93:d0:68:ce:77: - 5f:85:8b:a4:95:2a:4c:25:7b:53:9c:44:43:b1:d9:fe:0c:83: - b8:19:2a:88:cc:d8:d1:d9:b3:04:eb:45:9b:30:5e:cb:61:e0: - e1:88:23:9c:b0:34:79:62:82:0d:f8:10:ed:96:bb:a0:fd:0d: - 02:cb:c5:d3:47:1f:35:a7:e3:39:31:56:d5:b3:eb:2f:93:8f: - 18:b4:b7:3c:00:03:a7:b4:1c:17:72:91:7e:b6:f6:36:17:3d: - f6:54:3b:87:84:d1:9b:43:d1:88:42:64:20:7a:e3:cc:f7:05: - 98:0e:1c:51:da:20:b7:9b:49:88:e8:c6:e1:de:0d:f5:56:4f: - 79:41:d0:7f ------BEGIN CERTIFICATE----- -MIIDNTCCAh2gAwIBAgIBATANBgkqhkiG9w0BAQsFADAUMRIwEAYDVQQDEwljYXNz -YW5kcmEwHhcNMTQwOTE5MjExODMzWhcNMjQwOTE2MjExODMzWjAQMQ4wDAYDVQQD -EwVnb2NxbDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAK7p+p794mmF -HQgPNWi8Y3uSUH9zUPxCQzUGs1yeJx4WBWnsiNWcT+/oE2l6tbN/Zm0UAC7Wr1v/ -LJCRphEHcl6wN8Bt/3t2K/7eTNKNzkM7GsQd3rbYJggliVmhS5SjV54ZRihulxF8 -5rdBlo9C3WbahtJT3dj1IM0kiw+r38QQsmQgHeAP9C32ypS+g6w+qEp3tgiXOn57 -4D6raM/u9qGOv+y+BtGtbO1PNdEElwgzsWVbYTKNS/AwNUuLawbyGnKMab3zssSk -pHBF42eiep8uyygtn2gD8cfZT4PJPYw0BAo7E4eS4ffjeX6rwCWx5TgJRD4x3xLU -3HsONb/uJV8CAwEAAaOBlTCBkjAJBgNVHRMEAjAAMB0GA1UdDgQWBBSf8bLEgjTQ -L//pfxnxO1FXv+iVuzBEBgNVHSMEPTA7gBSMfOfSdgWJcRojW9RZtFHiXApc6KEY -pBYwFDESMBAGA1UEAxMJY2Fzc2FuZHJhggkAgpsBeB6bCyMwEwYDVR0lBAwwCgYI -KwYBBQUHAwIwCwYDVR0PBAQDAgeAMA0GCSqGSIb3DQEBCwUAA4IBAQASqhumWCdS -MslGGTLTaa6VrSNVrRJl2ixMcvMpvStalzu3aItogHdV5jKB8fUgVLoOK4aQ2ETP -8p/sTTlnTjZsm0lKgObB7aRBORkW0ojfFwxGWrmIU/VnGfAfmlFAG0ASvFfb3t3T -9aiTaDCsuk7ua6/4Ez0RGvqQk9BozndfhYuklSpMJXtTnERDsdn+DIO4GSqIzNjR -2bME60WbMF7LYeDhiCOcsDR5YoIN+BDtlrug/Q0Cy8XTRx81p+M5MVbVs+svk48Y -tLc8AAOntBwXcpF+tvY2Fz32VDuHhNGbQ9GIQmQgeuPM9wWYDhxR2iC3m0mI6Mbh -3g31Vk95QdB/ ------END CERTIFICATE----- diff --git a/Godeps/_workspace/src/github.com/gocql/gocql/testdata/pki/gocql.key b/Godeps/_workspace/src/github.com/gocql/gocql/testdata/pki/gocql.key deleted file mode 100644 index 0d701f43e..000000000 --- a/Godeps/_workspace/src/github.com/gocql/gocql/testdata/pki/gocql.key +++ /dev/null @@ -1,27 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIIEpAIBAAKCAQEArun6nv3iaYUdCA81aLxje5JQf3NQ/EJDNQazXJ4nHhYFaeyI -1ZxP7+gTaXq1s39mbRQALtavW/8skJGmEQdyXrA3wG3/e3Yr/t5M0o3OQzsaxB3e -ttgmCCWJWaFLlKNXnhlGKG6XEXzmt0GWj0LdZtqG0lPd2PUgzSSLD6vfxBCyZCAd -4A/0LfbKlL6DrD6oSne2CJc6fnvgPqtoz+72oY6/7L4G0a1s7U810QSXCDOxZVth -Mo1L8DA1S4trBvIacoxpvfOyxKSkcEXjZ6J6ny7LKC2faAPxx9lPg8k9jDQECjsT -h5Lh9+N5fqvAJbHlOAlEPjHfEtTcew41v+4lXwIDAQABAoIBAQCCP9XSwzfwX6Fo -uPqKjY5/HEs5PQPXdPha6ixyEYsLilZptCuI9adI/MZHy4q2qW36V+Ry/IcEuJXU -6cCB+cue2xYJA2A17Z+BYMRQHiy0P7UEyUFpYrefZWRMDCIeAyxhnGxz+zYfXaTo -Xbzh3WbFCoFO6gjPYGoWmNm8x74PXyunNaMa/gWFECX5MMBXoOk5xSFGbHzI2Cds -iT7sdCQJVbBs7yidYwNqPWQuOwrskFinPIFSc7bZ0Sx9wO3XTIrQFCE94v/AN6yR -9Q37ida54g5tgtoeg/5EGsUM++i4wqJVoT3tWUHv1jBozO4Lm65uWR/1HcrusVnr -x0TM9SaBAoGBAOMeaZdUrCJXnIiSoqCGDvZmylTAeOo6n2RAiviOYxVB4GP/SSjh -8VeddFhYT1GCmZ+YjIXnRWK+dSqVukzCuf5xW5mWY7PDNGZe2P6O78lXnY4cb8Nc -Uo9/S2aPnNmNHL2TYVBYUiZj+t2azIQEFvRth4Vu/AHRUG41/USxpwm/AoGBAMUo -GX0xgSFAVpHnTLdzWrHNRrzHgYN8ywPKFgNOASvdgW0BFoqXEvVGc1Ak6uW82m1/ -L9ChOzWjCY7CoT+LPmdUVyGT9/UAPtWeLfo8Owl4tG91jQjePmJFvLoXErryCFRt -SOOvCsTTTq2gN3PREHxY3dj2kJqaCBLCEzx3cYxhAoGBAIUxdrc6/t/9BV3KsPj2 -5Zt3WL0vSzoCOyut9lIiHtV+lrvOIPeK2eCKBIsy7wFcV/+SlQaKRNTN4SSiPml5 -4V3o2NFPsxTfK8HFafiPluw7J7kJ0Dl/0SM6gduZ6WBkMzCyV+WohjTheWOwvrPF -OjkKaunD1qKyQDsCCo/Yp589AoGAdKgnfNZf68bf8nEECcBtt6sY4fbCgYTDszhO -EiKDuurT/CWaquJ9SzgmXxOZEdrO+9838aCVIkWYECrFso23nPhgnfOp0gQVKdzw -o5Ij9JTBXvoVO1wVWZyd8RZZ9Nflad9IM8CNBK1rbnzQkuzvbkQ+8HPkWDYv9Ll1 -HGAohcECgYBQeirIumumj1B17WD/KmNe0U0qCHHp+oSW4W2r7pjlEVZzeQmggX4O -anbEngyQaZKeUiUOj9snBDmzLv7S+j5p7Us4d1fbp70sCKuK6tcAnROU8gK8IGiI -I01ypD8Z1Mb556qek56eRWlr71sy6wI1lbQa856cUBvePajUOKsKsw== ------END RSA PRIVATE KEY----- diff --git a/Godeps/_workspace/src/github.com/gocql/gocql/token.go b/Godeps/_workspace/src/github.com/gocql/gocql/token.go index 00541707d..d796683d3 100644 --- a/Godeps/_workspace/src/github.com/gocql/gocql/token.go +++ b/Godeps/_workspace/src/github.com/gocql/gocql/token.go @@ -12,7 +12,6 @@ import ( "sort" "strconv" "strings" - "unsafe" ) // a token partitioner @@ -42,138 +41,6 @@ func (p murmur3Partitioner) Hash(partitionKey []byte) token { } // murmur3 little-endian, 128-bit hash, but returns only h1 -func murmur3H1(data []byte) uint64 { - length := len(data) - - var h1, h2, k1, k2 uint64 - - const ( - c1 = 0x87c37b91114253d5 - c2 = 0x4cf5ad432745937f - ) - - // body - nBlocks := length / 16 - for i := 0; i < nBlocks; i++ { - block := (*[2]uint64)(unsafe.Pointer(&data[i*16])) - - k1 = block[0] - k2 = block[1] - - k1 *= c1 - k1 = (k1 << 31) | (k1 >> 33) // ROTL64(k1, 31) - k1 *= c2 - h1 ^= k1 - - h1 = (h1 << 27) | (h1 >> 37) // ROTL64(h1, 27) - h1 += h2 - h1 = h1*5 + 0x52dce729 - - k2 *= c2 - k2 = (k2 << 33) | (k2 >> 31) // ROTL64(k2, 33) - k2 *= c1 - h2 ^= k2 - - h2 = (h2 << 31) | (h2 >> 33) // ROTL64(h2, 31) - h2 += h1 - h2 = h2*5 + 0x38495ab5 - } - - // tail - tail := data[nBlocks*16:] - k1 = 0 - k2 = 0 - switch length & 15 { - case 15: - k2 ^= uint64(tail[14]) << 48 - fallthrough - case 14: - k2 ^= uint64(tail[13]) << 40 - fallthrough - case 13: - k2 ^= uint64(tail[12]) << 32 - fallthrough - case 12: - k2 ^= uint64(tail[11]) << 24 - fallthrough - case 11: - k2 ^= uint64(tail[10]) << 16 - fallthrough - case 10: - k2 ^= uint64(tail[9]) << 8 - fallthrough - case 9: - k2 ^= uint64(tail[8]) - - k2 *= c2 - k2 = (k2 << 33) | (k2 >> 31) // ROTL64(k2, 33) - k2 *= c1 - h2 ^= k2 - - fallthrough - case 8: - k1 ^= uint64(tail[7]) << 56 - fallthrough - case 7: - k1 ^= uint64(tail[6]) << 48 - fallthrough - case 6: - k1 ^= uint64(tail[5]) << 40 - fallthrough - case 5: - k1 ^= uint64(tail[4]) << 32 - fallthrough - case 4: - k1 ^= uint64(tail[3]) << 24 - fallthrough - case 3: - k1 ^= uint64(tail[2]) << 16 - fallthrough - case 2: - k1 ^= uint64(tail[1]) << 8 - fallthrough - case 1: - k1 ^= uint64(tail[0]) - - k1 *= c1 - k1 = (k1 << 31) | (k1 >> 33) // ROTL64(k1, 31) - k1 *= c2 - h1 ^= k1 - } - - h1 ^= uint64(length) - h2 ^= uint64(length) - - h1 += h2 - h2 += h1 - - // finalizer - const ( - fmix1 = 0xff51afd7ed558ccd - fmix2 = 0xc4ceb9fe1a85ec53 - ) - - // fmix64(h1) - h1 ^= h1 >> 33 - h1 *= fmix1 - h1 ^= h1 >> 33 - h1 *= fmix2 - h1 ^= h1 >> 33 - - // fmix64(h2) - h2 ^= h2 >> 33 - h2 *= fmix1 - h2 ^= h2 >> 33 - h2 *= fmix2 - h2 ^= h2 >> 33 - - h1 += h2 - // the following is extraneous since h2 is discarded - // h2 += h1 - - return h1 -} - func (p murmur3Partitioner) ParseString(str string) token { val, _ := strconv.ParseInt(str, 10, 64) return murmur3Token(val) diff --git a/Godeps/_workspace/src/github.com/gocql/gocql/token_test.go b/Godeps/_workspace/src/github.com/gocql/gocql/token_test.go deleted file mode 100644 index c17585ed4..000000000 --- a/Godeps/_workspace/src/github.com/gocql/gocql/token_test.go +++ /dev/null @@ -1,474 +0,0 @@ -// Copyright (c) 2015 The gocql 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 gocql - -import ( - "bytes" - "math/big" - "sort" - "strconv" - "testing" -) - -// Test the implementation of murmur3 -func TestMurmur3H1(t *testing.T) { - // these examples are based on adding a index number to a sample string in - // a loop. The expected values were generated by the java datastax murmur3 - // implementation. The number of examples here of increasing lengths ensure - // test coverage of all tail-length branches in the murmur3 algorithm - seriesExpected := [...]uint64{ - 0x0000000000000000, // "" - 0x2ac9debed546a380, // "0" - 0x649e4eaa7fc1708e, // "01" - 0xce68f60d7c353bdb, // "012" - 0x0f95757ce7f38254, // "0123" - 0x0f04e459497f3fc1, // "01234" - 0x88c0a92586be0a27, // "012345" - 0x13eb9fb82606f7a6, // "0123456" - 0x8236039b7387354d, // "01234567" - 0x4c1e87519fe738ba, // "012345678" - 0x3f9652ac3effeb24, // "0123456789" - 0x3f33760ded9006c6, // "01234567890" - 0xaed70a6631854cb1, // "012345678901" - 0x8a299a8f8e0e2da7, // "0123456789012" - 0x624b675c779249a6, // "01234567890123" - 0xa4b203bb1d90b9a3, // "012345678901234" - 0xa3293ad698ecb99a, // "0123456789012345" - 0xbc740023dbd50048, // "01234567890123456" - 0x3fe5ab9837d25cdd, // "012345678901234567" - 0x2d0338c1ca87d132, // "0123456789012345678" - } - sample := "" - for i, expected := range seriesExpected { - assertMurmur3H1(t, []byte(sample), expected) - - sample = sample + strconv.Itoa(i%10) - } - - // Here are some test examples from other driver implementations - assertMurmur3H1(t, []byte("hello"), 0xcbd8a7b341bd9b02) - assertMurmur3H1(t, []byte("hello, world"), 0x342fac623a5ebc8e) - assertMurmur3H1(t, []byte("19 Jan 2038 at 3:14:07 AM"), 0xb89e5988b737affc) - assertMurmur3H1(t, []byte("The quick brown fox jumps over the lazy dog."), 0xcd99481f9ee902c9) -} - -// helper function for testing the murmur3 implementation -func assertMurmur3H1(t *testing.T, data []byte, expected uint64) { - actual := murmur3H1(data) - if actual != expected { - t.Errorf("Expected h1 = %x for data = %x, but was %x", expected, data, actual) - } -} - -// Benchmark of the performance of the murmur3 implementation -func BenchmarkMurmur3H1(b *testing.B) { - var h1 uint64 - var data [1024]byte - for i := 0; i < 1024; i++ { - data[i] = byte(i) - } - for i := 0; i < b.N; i++ { - b.ResetTimer() - h1 = murmur3H1(data[:]) - _ = murmur3Token(int64(h1)) - } -} - -// Tests of the murmur3Patitioner -func TestMurmur3Partitioner(t *testing.T) { - token := murmur3Partitioner{}.ParseString("-1053604476080545076") - - if "-1053604476080545076" != token.String() { - t.Errorf("Expected '-1053604476080545076' but was '%s'", token) - } - - // at least verify that the partitioner - // doesn't return nil - pk, _ := marshalInt(nil, 1) - token = murmur3Partitioner{}.Hash(pk) - if token == nil { - t.Fatal("token was nil") - } -} - -// Tests of the murmur3Token -func TestMurmur3Token(t *testing.T) { - if murmur3Token(42).Less(murmur3Token(42)) { - t.Errorf("Expected Less to return false, but was true") - } - if !murmur3Token(-42).Less(murmur3Token(42)) { - t.Errorf("Expected Less to return true, but was false") - } - if murmur3Token(42).Less(murmur3Token(-42)) { - t.Errorf("Expected Less to return false, but was true") - } -} - -// Tests of the orderedPartitioner -func TestOrderedPartitioner(t *testing.T) { - // at least verify that the partitioner - // doesn't return nil - p := orderedPartitioner{} - pk, _ := marshalInt(nil, 1) - token := p.Hash(pk) - if token == nil { - t.Fatal("token was nil") - } - - str := token.String() - parsedToken := p.ParseString(str) - - if !bytes.Equal([]byte(token.(orderedToken)), []byte(parsedToken.(orderedToken))) { - t.Errorf("Failed to convert to and from a string %s expected %x but was %x", - str, - []byte(token.(orderedToken)), - []byte(parsedToken.(orderedToken)), - ) - } -} - -// Tests of the orderedToken -func TestOrderedToken(t *testing.T) { - if orderedToken([]byte{0, 0, 4, 2}).Less(orderedToken([]byte{0, 0, 4, 2})) { - t.Errorf("Expected Less to return false, but was true") - } - if !orderedToken([]byte{0, 0, 3}).Less(orderedToken([]byte{0, 0, 4, 2})) { - t.Errorf("Expected Less to return true, but was false") - } - if orderedToken([]byte{0, 0, 4, 2}).Less(orderedToken([]byte{0, 0, 3})) { - t.Errorf("Expected Less to return false, but was true") - } -} - -// Tests of the randomPartitioner -func TestRandomPartitioner(t *testing.T) { - // at least verify that the partitioner - // doesn't return nil - p := randomPartitioner{} - pk, _ := marshalInt(nil, 1) - token := p.Hash(pk) - if token == nil { - t.Fatal("token was nil") - } - - str := token.String() - parsedToken := p.ParseString(str) - - if (*big.Int)(token.(*randomToken)).Cmp((*big.Int)(parsedToken.(*randomToken))) != 0 { - t.Errorf("Failed to convert to and from a string %s expected %v but was %v", - str, - token, - parsedToken, - ) - } -} - -// Tests of the randomToken -func TestRandomToken(t *testing.T) { - if ((*randomToken)(big.NewInt(42))).Less((*randomToken)(big.NewInt(42))) { - t.Errorf("Expected Less to return false, but was true") - } - if !((*randomToken)(big.NewInt(41))).Less((*randomToken)(big.NewInt(42))) { - t.Errorf("Expected Less to return true, but was false") - } - if ((*randomToken)(big.NewInt(42))).Less((*randomToken)(big.NewInt(41))) { - t.Errorf("Expected Less to return false, but was true") - } -} - -type intToken int - -func (i intToken) String() string { - return strconv.Itoa(int(i)) -} - -func (i intToken) Less(token token) bool { - return i < token.(intToken) -} - -// Test of the token ring implementation based on example at the start of this -// page of documentation: -// http://www.datastax.com/docs/0.8/cluster_architecture/partitioning -func TestIntTokenRing(t *testing.T) { - host0 := &HostInfo{} - host25 := &HostInfo{} - host50 := &HostInfo{} - host75 := &HostInfo{} - ring := &tokenRing{ - partitioner: nil, - // these tokens and hosts are out of order to test sorting - tokens: []token{ - intToken(0), - intToken(50), - intToken(75), - intToken(25), - }, - hosts: []*HostInfo{ - host0, - host50, - host75, - host25, - }, - } - - sort.Sort(ring) - - if ring.GetHostForToken(intToken(0)) != host0 { - t.Error("Expected host 0 for token 0") - } - if ring.GetHostForToken(intToken(1)) != host25 { - t.Error("Expected host 25 for token 1") - } - if ring.GetHostForToken(intToken(24)) != host25 { - t.Error("Expected host 25 for token 24") - } - if ring.GetHostForToken(intToken(25)) != host25 { - t.Error("Expected host 25 for token 25") - } - if ring.GetHostForToken(intToken(26)) != host50 { - t.Error("Expected host 50 for token 26") - } - if ring.GetHostForToken(intToken(49)) != host50 { - t.Error("Expected host 50 for token 49") - } - if ring.GetHostForToken(intToken(50)) != host50 { - t.Error("Expected host 50 for token 50") - } - if ring.GetHostForToken(intToken(51)) != host75 { - t.Error("Expected host 75 for token 51") - } - if ring.GetHostForToken(intToken(74)) != host75 { - t.Error("Expected host 75 for token 74") - } - if ring.GetHostForToken(intToken(75)) != host75 { - t.Error("Expected host 75 for token 75") - } - if ring.GetHostForToken(intToken(76)) != host0 { - t.Error("Expected host 0 for token 76") - } - if ring.GetHostForToken(intToken(99)) != host0 { - t.Error("Expected host 0 for token 99") - } - if ring.GetHostForToken(intToken(100)) != host0 { - t.Error("Expected host 0 for token 100") - } -} - -// Test for the behavior of a nil pointer to tokenRing -func TestNilTokenRing(t *testing.T) { - var ring *tokenRing = nil - - if ring.GetHostForToken(nil) != nil { - t.Error("Expected nil for nil token ring") - } - if ring.GetHostForPartitionKey(nil) != nil { - t.Error("Expected nil for nil token ring") - } -} - -// Test of the recognition of the partitioner class -func TestUnknownTokenRing(t *testing.T) { - _, err := newTokenRing("UnknownPartitioner", nil) - if err == nil { - t.Error("Expected error for unknown partitioner value, but was nil") - } -} - -// Test of the tokenRing with the Murmur3Partitioner -func TestMurmur3TokenRing(t *testing.T) { - // Note, strings are parsed directly to int64, they are not murmur3 hashed - var hosts []HostInfo = []HostInfo{ - HostInfo{ - Peer: "0", - Tokens: []string{"0"}, - }, - HostInfo{ - Peer: "1", - Tokens: []string{"25"}, - }, - HostInfo{ - Peer: "2", - Tokens: []string{"50"}, - }, - HostInfo{ - Peer: "3", - Tokens: []string{"75"}, - }, - } - ring, err := newTokenRing("Murmur3Partitioner", hosts) - if err != nil { - t.Fatalf("Failed to create token ring due to error: %v", err) - } - - p := murmur3Partitioner{} - - var actual *HostInfo - actual = ring.GetHostForToken(p.ParseString("0")) - if actual.Peer != "0" { - t.Errorf("Expected peer 0 for token \"0\", but was %s", actual.Peer) - } - - actual = ring.GetHostForToken(p.ParseString("25")) - if actual.Peer != "1" { - t.Errorf("Expected peer 1 for token \"25\", but was %s", actual.Peer) - } - - actual = ring.GetHostForToken(p.ParseString("50")) - if actual.Peer != "2" { - t.Errorf("Expected peer 2 for token \"50\", but was %s", actual.Peer) - } - - actual = ring.GetHostForToken(p.ParseString("75")) - if actual.Peer != "3" { - t.Errorf("Expected peer 3 for token \"01\", but was %s", actual.Peer) - } - - actual = ring.GetHostForToken(p.ParseString("12")) - if actual.Peer != "1" { - t.Errorf("Expected peer 1 for token \"12\", but was %s", actual.Peer) - } - - actual = ring.GetHostForToken(p.ParseString("24324545443332")) - if actual.Peer != "0" { - t.Errorf("Expected peer 0 for token \"24324545443332\", but was %s", actual.Peer) - } -} - -// Test of the tokenRing with the OrderedPartitioner -func TestOrderedTokenRing(t *testing.T) { - // Tokens here more or less are similar layout to the int tokens above due - // to each numeric character translating to a consistently offset byte. - var hosts []HostInfo = []HostInfo{ - HostInfo{ - Peer: "0", - Tokens: []string{ - "00", - }, - }, - HostInfo{ - Peer: "1", - Tokens: []string{ - "25", - }, - }, - HostInfo{ - Peer: "2", - Tokens: []string{ - "50", - }, - }, - HostInfo{ - Peer: "3", - Tokens: []string{ - "75", - }, - }, - } - ring, err := newTokenRing("OrderedPartitioner", hosts) - if err != nil { - t.Fatalf("Failed to create token ring due to error: %v", err) - } - - p := orderedPartitioner{} - - var actual *HostInfo - actual = ring.GetHostForToken(p.ParseString("0")) - if actual.Peer != "0" { - t.Errorf("Expected peer 0 for token \"0\", but was %s", actual.Peer) - } - - actual = ring.GetHostForToken(p.ParseString("25")) - if actual.Peer != "1" { - t.Errorf("Expected peer 1 for token \"25\", but was %s", actual.Peer) - } - - actual = ring.GetHostForToken(p.ParseString("50")) - if actual.Peer != "2" { - t.Errorf("Expected peer 2 for token \"50\", but was %s", actual.Peer) - } - - actual = ring.GetHostForToken(p.ParseString("75")) - if actual.Peer != "3" { - t.Errorf("Expected peer 3 for token \"01\", but was %s", actual.Peer) - } - - actual = ring.GetHostForToken(p.ParseString("12")) - if actual.Peer != "1" { - t.Errorf("Expected peer 1 for token \"12\", but was %s", actual.Peer) - } - - actual = ring.GetHostForToken(p.ParseString("24324545443332")) - if actual.Peer != "1" { - t.Errorf("Expected peer 1 for token \"24324545443332\", but was %s", actual.Peer) - } -} - -// Test of the tokenRing with the RandomPartitioner -func TestRandomTokenRing(t *testing.T) { - // String tokens are parsed into big.Int in base 10 - var hosts []HostInfo = []HostInfo{ - HostInfo{ - Peer: "0", - Tokens: []string{ - "00", - }, - }, - HostInfo{ - Peer: "1", - Tokens: []string{ - "25", - }, - }, - HostInfo{ - Peer: "2", - Tokens: []string{ - "50", - }, - }, - HostInfo{ - Peer: "3", - Tokens: []string{ - "75", - }, - }, - } - ring, err := newTokenRing("RandomPartitioner", hosts) - if err != nil { - t.Fatalf("Failed to create token ring due to error: %v", err) - } - - p := randomPartitioner{} - - var actual *HostInfo - actual = ring.GetHostForToken(p.ParseString("0")) - if actual.Peer != "0" { - t.Errorf("Expected peer 0 for token \"0\", but was %s", actual.Peer) - } - - actual = ring.GetHostForToken(p.ParseString("25")) - if actual.Peer != "1" { - t.Errorf("Expected peer 1 for token \"25\", but was %s", actual.Peer) - } - - actual = ring.GetHostForToken(p.ParseString("50")) - if actual.Peer != "2" { - t.Errorf("Expected peer 2 for token \"50\", but was %s", actual.Peer) - } - - actual = ring.GetHostForToken(p.ParseString("75")) - if actual.Peer != "3" { - t.Errorf("Expected peer 3 for token \"01\", but was %s", actual.Peer) - } - - actual = ring.GetHostForToken(p.ParseString("12")) - if actual.Peer != "1" { - t.Errorf("Expected peer 1 for token \"12\", but was %s", actual.Peer) - } - - actual = ring.GetHostForToken(p.ParseString("24324545443332")) - if actual.Peer != "0" { - t.Errorf("Expected peer 0 for token \"24324545443332\", but was %s", actual.Peer) - } -} diff --git a/Godeps/_workspace/src/github.com/gocql/gocql/topology_test.go b/Godeps/_workspace/src/github.com/gocql/gocql/topology_test.go deleted file mode 100644 index 8384824ab..000000000 --- a/Godeps/_workspace/src/github.com/gocql/gocql/topology_test.go +++ /dev/null @@ -1,51 +0,0 @@ -// +build all unit - -package gocql - -import ( - "testing" -) - -// fakeNode is used as a simple structure to test the RoundRobin API -type fakeNode struct { - conn *Conn - closed bool -} - -// Pick is needed to satisfy the Node interface -func (n *fakeNode) Pick(qry *Query) *Conn { - if n.conn == nil { - n.conn = &Conn{} - } - return n.conn -} - -//Close is needed to satisfy the Node interface -func (n *fakeNode) Close() { - n.closed = true -} - -//TestRoundRobinAPI tests the exported methods of the RoundRobin struct -//to make sure the API behaves accordingly. -func TestRoundRobinAPI(t *testing.T) { - node := &fakeNode{} - rr := NewRoundRobin() - rr.AddNode(node) - - if rr.Size() != 1 { - t.Fatalf("expected size to be 1, got %v", rr.Size()) - } - - if c := rr.Pick(nil); c != node.conn { - t.Fatalf("expected conn %v, got %v", node.conn, c) - } - - rr.Close() - if rr.pool != nil { - t.Fatalf("expected rr.pool to be nil, got %v", rr.pool) - } - - if !node.closed { - t.Fatal("expected node.closed to be true, got false") - } -} diff --git a/Godeps/_workspace/src/github.com/gocql/gocql/tuple_test.go b/Godeps/_workspace/src/github.com/gocql/gocql/tuple_test.go deleted file mode 100644 index bf94191f6..000000000 --- a/Godeps/_workspace/src/github.com/gocql/gocql/tuple_test.go +++ /dev/null @@ -1,51 +0,0 @@ -// +build all integration - -package gocql - -import "testing" - -func TestTupleSimple(t *testing.T) { - if *flagProto < protoVersion3 { - t.Skip("tuple types are only available of proto>=3") - } - - session := createSession(t) - defer session.Close() - - err := createTable(session, `CREATE TABLE tuple_test( - id int, - coord frozen>, - - primary key(id))`) - if err != nil { - t.Fatal(err) - } - - err = session.Query("INSERT INTO tuple_test(id, coord) VALUES(?, (?, ?))", 1, 100, -100).Exec() - if err != nil { - t.Fatal(err) - } - - var ( - id int - coord struct { - x int - y int - } - ) - - iter := session.Query("SELECT id, coord FROM tuple_test WHERE id=?", 1) - if err := iter.Scan(&id, &coord.x, &coord.y); err != nil { - t.Fatal(err) - } - - if id != 1 { - t.Errorf("expected to get id=1 got: %v", id) - } - if coord.x != 100 { - t.Errorf("expected to get coord.x=100 got: %v", coord.x) - } - if coord.y != -100 { - t.Errorf("expected to get coord.y=-100 got: %v", coord.y) - } -} diff --git a/Godeps/_workspace/src/github.com/gocql/gocql/udt_test.go b/Godeps/_workspace/src/github.com/gocql/gocql/udt_test.go deleted file mode 100644 index 1e0a9fcd1..000000000 --- a/Godeps/_workspace/src/github.com/gocql/gocql/udt_test.go +++ /dev/null @@ -1,254 +0,0 @@ -// +build all integration - -package gocql - -import ( - "fmt" - "strings" - "testing" -) - -type position struct { - Lat int `cql:"lat"` - Lon int `cql:"lon"` - Padding string `json:"padding"` -} - -// NOTE: due to current implementation details it is not currently possible to use -// a pointer receiver type for the UDTMarshaler interface to handle UDT's -func (p position) MarshalUDT(name string, info TypeInfo) ([]byte, error) { - switch name { - case "lat": - return Marshal(info, p.Lat) - case "lon": - return Marshal(info, p.Lon) - case "padding": - return Marshal(info, p.Padding) - default: - return nil, fmt.Errorf("unknown column for position: %q", name) - } -} - -func (p *position) UnmarshalUDT(name string, info TypeInfo, data []byte) error { - switch name { - case "lat": - return Unmarshal(info, data, &p.Lat) - case "lon": - return Unmarshal(info, data, &p.Lon) - case "padding": - return Unmarshal(info, data, &p.Padding) - default: - return fmt.Errorf("unknown column for position: %q", name) - } -} - -func TestUDT_Marshaler(t *testing.T) { - if *flagProto < protoVersion3 { - t.Skip("UDT are only available on protocol >= 3") - } - - session := createSession(t) - defer session.Close() - - err := createTable(session, `CREATE TYPE position( - lat int, - lon int, - padding text);`) - if err != nil { - t.Fatal(err) - } - - err = createTable(session, `CREATE TABLE houses( - id int, - name text, - loc frozen, - - primary key(id) - );`) - if err != nil { - t.Fatal(err) - } - - const ( - expLat = -1 - expLon = 2 - ) - pad := strings.Repeat("X", 1000) - - err = session.Query("INSERT INTO houses(id, name, loc) VALUES(?, ?, ?)", 1, "test", &position{expLat, expLon, pad}).Exec() - if err != nil { - t.Fatal(err) - } - - pos := &position{} - - err = session.Query("SELECT loc FROM houses WHERE id = ?", 1).Scan(pos) - if err != nil { - t.Fatal(err) - } - - if pos.Lat != expLat { - t.Errorf("expeceted lat to be be %d got %d", expLat, pos.Lat) - } - if pos.Lon != expLon { - t.Errorf("expeceted lon to be be %d got %d", expLon, pos.Lon) - } - if pos.Padding != pad { - t.Errorf("expected to get padding %q got %q\n", pad, pos.Padding) - } -} - -func TestUDT_Reflect(t *testing.T) { - if *flagProto < protoVersion3 { - t.Skip("UDT are only available on protocol >= 3") - } - - // Uses reflection instead of implementing the marshaling type - session := createSession(t) - defer session.Close() - - err := createTable(session, `CREATE TYPE horse( - name text, - owner text);`) - if err != nil { - t.Fatal(err) - } - - err = createTable(session, `CREATE TABLE horse_race( - position int, - horse frozen, - - primary key(position) - );`) - if err != nil { - t.Fatal(err) - } - - type horse struct { - Name string `cql:"name"` - Owner string `cql:"owner"` - } - - insertedHorse := &horse{ - Name: "pony", - Owner: "jim", - } - - err = session.Query("INSERT INTO horse_race(position, horse) VALUES(?, ?)", 1, insertedHorse).Exec() - if err != nil { - t.Fatal(err) - } - - retrievedHorse := &horse{} - err = session.Query("SELECT horse FROM horse_race WHERE position = ?", 1).Scan(retrievedHorse) - if err != nil { - t.Fatal(err) - } - - if *retrievedHorse != *insertedHorse { - t.Fatal("exepcted to get %+v got %+v", insertedHorse, retrievedHorse) - } -} - -func TestUDT_Proto2error(t *testing.T) { - if *flagProto < protoVersion3 { - t.Skip("UDT are only available on protocol >= 3") - } - - cluster := createCluster() - cluster.ProtoVersion = 2 - cluster.Keyspace = "gocql_test" - - // Uses reflection instead of implementing the marshaling type - session, err := cluster.CreateSession() - if err != nil { - t.Fatal(err) - } - defer session.Close() - - err = createTable(session, `CREATE TYPE fish( - name text, - owner text);`) - if err != nil { - t.Fatal(err) - } - - err = createTable(session, `CREATE TABLE fish_race( - position int, - fish frozen, - - primary key(position) - );`) - if err != nil { - t.Fatal(err) - } - - type fish struct { - Name string `cql:"name"` - Owner string `cql:"owner"` - } - - insertedFish := &fish{ - Name: "pony", - Owner: "jim", - } - - err = session.Query("INSERT INTO fish_race(position, fish) VALUES(?, ?)", 1, insertedFish).Exec() - if err != ErrorUDTUnavailable { - t.Fatalf("expected to get %v got %v", ErrorUDTUnavailable, err) - } -} - -func TestUDT_NullObject(t *testing.T) { - if *flagProto < protoVersion3 { - t.Skip("UDT are only available on protocol >= 3") - } - - session := createSession(t) - defer session.Close() - - err := createTable(session, `CREATE TYPE udt_null_type( - name text, - owner text);`) - if err != nil { - t.Fatal(err) - } - - err = createTable(session, `CREATE TABLE udt_null_table( - id uuid, - udt_col frozen, - - primary key(id) - );`) - if err != nil { - t.Fatal(err) - } - - type col struct { - Name string `cql:"name"` - Owner string `cql:"owner"` - } - - id := TimeUUID() - err = session.Query("INSERT INTO udt_null_table(id) VALUES(?)", id).Exec() - if err != nil { - t.Fatal(err) - } - - readCol := &col{ - Name: "temp", - Owner: "temp", - } - - err = session.Query("SELECT udt_col FROM udt_null_table WHERE id = ?", id).Scan(readCol) - if err != nil { - t.Fatal(err) - } - - if readCol.Name != "" { - t.Errorf("expected empty string to be returned for null udt: got %q", readCol.Name) - } - if readCol.Owner != "" { - t.Errorf("expected empty string to be returned for null udt: got %q", readCol.Owner) - } -} diff --git a/Godeps/_workspace/src/github.com/gocql/gocql/uuid_test.go b/Godeps/_workspace/src/github.com/gocql/gocql/uuid_test.go deleted file mode 100644 index ec6a69ff9..000000000 --- a/Godeps/_workspace/src/github.com/gocql/gocql/uuid_test.go +++ /dev/null @@ -1,197 +0,0 @@ -// +build all unit - -package gocql - -import ( - "bytes" - "strings" - "testing" - "time" -) - -func TestUUIDNil(t *testing.T) { - var uuid UUID - want, got := "00000000-0000-0000-0000-000000000000", uuid.String() - if want != got { - t.Fatalf("TestNil: expected %q got %q", want, got) - } -} - -var testsUUID = []struct { - input string - variant int - version int -}{ - {"b4f00409-cef8-4822-802c-deb20704c365", VariantIETF, 4}, - {"B4F00409-CEF8-4822-802C-DEB20704C365", VariantIETF, 4}, //Use capital letters - {"f81d4fae-7dec-11d0-a765-00a0c91e6bf6", VariantIETF, 1}, - {"00000000-7dec-11d0-a765-00a0c91e6bf6", VariantIETF, 1}, - {"3051a8d7-aea7-1801-e0bf-bc539dd60cf3", VariantFuture, 1}, - {"3051a8d7-aea7-2801-e0bf-bc539dd60cf3", VariantFuture, 2}, - {"3051a8d7-aea7-3801-e0bf-bc539dd60cf3", VariantFuture, 3}, - {"3051a8d7-aea7-4801-e0bf-bc539dd60cf3", VariantFuture, 4}, - {"3051a8d7-aea7-3801-e0bf-bc539dd60cf3", VariantFuture, 5}, - {"d0e817e1-e4b1-1801-3fe6-b4b60ccecf9d", VariantNCSCompat, 0}, - {"d0e817e1-e4b1-1801-bfe6-b4b60ccecf9d", VariantIETF, 1}, - {"d0e817e1-e4b1-1801-dfe6-b4b60ccecf9d", VariantMicrosoft, 0}, - {"d0e817e1-e4b1-1801-ffe6-b4b60ccecf9d", VariantFuture, 0}, -} - -func TestPredefinedUUID(t *testing.T) { - for i := range testsUUID { - uuid, err := ParseUUID(testsUUID[i].input) - if err != nil { - t.Errorf("ParseUUID #%d: %v", i, err) - continue - } - - if str := uuid.String(); str != strings.ToLower(testsUUID[i].input) { - t.Errorf("String #%d: expected %q got %q", i, testsUUID[i].input, str) - continue - } - - if variant := uuid.Variant(); variant != testsUUID[i].variant { - t.Errorf("Variant #%d: expected %d got %d", i, testsUUID[i].variant, variant) - } - - if testsUUID[i].variant == VariantIETF { - if version := uuid.Version(); version != testsUUID[i].version { - t.Errorf("Version #%d: expected %d got %d", i, testsUUID[i].version, version) - } - } - - json, err := uuid.MarshalJSON() - if err != nil { - t.Errorf("MarshalJSON #%d: %v", i, err) - } - expectedJson := `"` + strings.ToLower(testsUUID[i].input) + `"` - if string(json) != expectedJson { - t.Errorf("MarshalJSON #%d: expected %v got %v", i, expectedJson, string(json)) - } - - var unmarshaled UUID - err = unmarshaled.UnmarshalJSON(json) - if err != nil { - t.Errorf("UnmarshalJSON #%d: %v", i, err) - } - if unmarshaled != uuid { - t.Errorf("UnmarshalJSON #%d: expected %v got %v", i, uuid, unmarshaled) - } - } -} - -func TestInvalidUUIDCharacter(t *testing.T) { - _, err := ParseUUID("z4f00409-cef8-4822-802c-deb20704c365") - if err == nil || !strings.Contains(err.Error(), "invalid UUID") { - t.Fatalf("expected invalid UUID error, got '%v' ", err) - } -} - -func TestInvalidUUIDLength(t *testing.T) { - _, err := ParseUUID("4f00") - if err == nil || !strings.Contains(err.Error(), "invalid UUID") { - t.Fatalf("expected invalid UUID error, got '%v' ", err) - } - - _, err = UUIDFromBytes(TimeUUID().Bytes()[:15]) - if err == nil || err.Error() != "UUIDs must be exactly 16 bytes long" { - t.Fatalf("expected error '%v', got '%v'", "UUIDs must be exactly 16 bytes long", err) - } -} - -func TestRandomUUID(t *testing.T) { - for i := 0; i < 20; i++ { - uuid, err := RandomUUID() - if err != nil { - t.Errorf("RandomUUID: %v", err) - } - if variant := uuid.Variant(); variant != VariantIETF { - t.Errorf("wrong variant. expected %d got %d", VariantIETF, variant) - } - if version := uuid.Version(); version != 4 { - t.Errorf("wrong version. expected %d got %d", 4, version) - } - } -} - -func TestRandomUUIDInvalidAPICalls(t *testing.T) { - uuid, err := RandomUUID() - if err != nil { - t.Fatalf("unexpected error %v", err) - } - - if node := uuid.Node(); node != nil { - t.Fatalf("expected nil, got %v", node) - } - - if stamp := uuid.Timestamp(); stamp != 0 { - t.Fatalf("expceted 0, got %v", stamp) - } - zeroT := time.Time{} - if to := uuid.Time(); to != zeroT { - t.Fatalf("expected %v, got %v", zeroT, to) - } -} - -func TestUUIDFromTime(t *testing.T) { - date := time.Date(1982, 5, 5, 12, 34, 56, 400, time.UTC) - uuid := UUIDFromTime(date) - - if uuid.Time() != date { - t.Errorf("embedded time incorrect. Expected %v got %v", date, uuid.Time()) - } -} - -func TestParseUUID(t *testing.T) { - uuid, _ := ParseUUID("486f3a88-775b-11e3-ae07-d231feb1dc81") - if uuid.Time() != time.Date(2014, 1, 7, 5, 19, 29, 222516000, time.UTC) { - t.Errorf("Expected date of 1/7/2014 at 5:19:29.222516, got %v", uuid.Time()) - } -} - -func TestTimeUUID(t *testing.T) { - var node []byte - timestamp := int64(0) - for i := 0; i < 20; i++ { - uuid := TimeUUID() - - if variant := uuid.Variant(); variant != VariantIETF { - t.Errorf("wrong variant. expected %d got %d", VariantIETF, variant) - } - if version := uuid.Version(); version != 1 { - t.Errorf("wrong version. expected %d got %d", 1, version) - } - - if n := uuid.Node(); !bytes.Equal(n, node) && i > 0 { - t.Errorf("wrong node. expected %x, got %x", node, n) - } else if i == 0 { - node = n - } - - ts := uuid.Timestamp() - if ts < timestamp { - t.Errorf("timestamps must grow") - } - timestamp = ts - } -} - -func TestUnmarshalJSON(t *testing.T) { - var withHyphens, withoutHypens, tooLong UUID - - withHyphens.UnmarshalJSON([]byte(`"486f3a88-775b-11e3-ae07-d231feb1dc81"`)) - if withHyphens.Time().Truncate(time.Second) != time.Date(2014, 1, 7, 5, 19, 29, 0, time.UTC) { - t.Errorf("Expected date of 1/7/2014 at 5:19:29, got %v", withHyphens.Time()) - } - - withoutHypens.UnmarshalJSON([]byte(`"486f3a88775b11e3ae07d231feb1dc81"`)) - if withoutHypens.Time().Truncate(time.Second) != time.Date(2014, 1, 7, 5, 19, 29, 0, time.UTC) { - t.Errorf("Expected date of 1/7/2014 at 5:19:29, got %v", withoutHypens.Time()) - } - - err := tooLong.UnmarshalJSON([]byte(`"486f3a88-775b-11e3-ae07-d231feb1dc81486f3a88"`)) - if err == nil { - t.Errorf("no error for invalid JSON UUID") - } - -} diff --git a/Godeps/_workspace/src/github.com/gocql/gocql/wiki_test.go b/Godeps/_workspace/src/github.com/gocql/gocql/wiki_test.go deleted file mode 100644 index bfc509094..000000000 --- a/Godeps/_workspace/src/github.com/gocql/gocql/wiki_test.go +++ /dev/null @@ -1,274 +0,0 @@ -// +build all integration - -package gocql - -import ( - "fmt" - "reflect" - "sort" - "gopkg.in/inf.v0" - "testing" - "time" -) - -type WikiPage struct { - Title string - RevId UUID - Body string - Views int64 - Protected bool - Modified time.Time - Rating *inf.Dec - Tags []string - Attachments map[string]WikiAttachment -} - -type WikiAttachment []byte - -var wikiTestData = []*WikiPage{ - &WikiPage{ - Title: "Frontpage", - RevId: TimeUUID(), - Body: "Welcome to this wiki page!", - Rating: inf.NewDec(131, 3), - Modified: time.Date(2013, time.August, 13, 9, 52, 3, 0, time.UTC), - Tags: []string{"start", "important", "test"}, - Attachments: map[string]WikiAttachment{ - "logo": WikiAttachment("\x00company logo\x00"), - "favicon": WikiAttachment("favicon.ico"), - }, - }, - &WikiPage{ - Title: "Foobar", - RevId: TimeUUID(), - Body: "foo::Foo f = new foo::Foo(foo::Foo::INIT);", - Modified: time.Date(2013, time.August, 13, 9, 52, 3, 0, time.UTC), - }, -} - -type WikiTest struct { - session *Session - tb testing.TB -} - -func (w *WikiTest) CreateSchema() { - - if err := w.session.Query(`DROP TABLE wiki_page`).Exec(); err != nil && err.Error() != "unconfigured columnfamily wiki_page" { - w.tb.Fatal("CreateSchema:", err) - } - err := createTable(w.session, `CREATE TABLE wiki_page ( - title varchar, - revid timeuuid, - body varchar, - views bigint, - protected boolean, - modified timestamp, - rating decimal, - tags set, - attachments map, - PRIMARY KEY (title, revid) - )`) - if *clusterSize > 1 { - // wait for table definition to propogate - time.Sleep(250 * time.Millisecond) - } - if err != nil { - w.tb.Fatal("CreateSchema:", err) - } -} - -func (w *WikiTest) CreatePages(n int) { - var page WikiPage - t0 := time.Now() - for i := 0; i < n; i++ { - page.Title = fmt.Sprintf("generated_%d", (i&16)+1) - page.Modified = t0.Add(time.Duration(i-n) * time.Minute) - page.RevId = UUIDFromTime(page.Modified) - page.Body = fmt.Sprintf("text %d", i) - if err := w.InsertPage(&page); err != nil { - w.tb.Error("CreatePages:", err) - } - } -} - -func (w *WikiTest) InsertPage(page *WikiPage) error { - return w.session.Query(`INSERT INTO wiki_page - (title, revid, body, views, protected, modified, rating, tags, attachments) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, - page.Title, page.RevId, page.Body, page.Views, page.Protected, - page.Modified, page.Rating, page.Tags, page.Attachments).Exec() -} - -func (w *WikiTest) SelectPage(page *WikiPage, title string, revid UUID) error { - return w.session.Query(`SELECT title, revid, body, views, protected, - modified,tags, attachments, rating - FROM wiki_page WHERE title = ? AND revid = ? LIMIT 1`, - title, revid).Scan(&page.Title, &page.RevId, - &page.Body, &page.Views, &page.Protected, &page.Modified, &page.Tags, - &page.Attachments, &page.Rating) -} - -func (w *WikiTest) GetPageCount() int { - var count int - if err := w.session.Query(`SELECT COUNT(*) FROM wiki_page`).Scan(&count); err != nil { - w.tb.Error("GetPageCount", err) - } - return count -} - -func TestWikiCreateSchema(t *testing.T) { - session := createSession(t) - defer session.Close() - - w := WikiTest{session, t} - w.CreateSchema() -} - -func BenchmarkWikiCreateSchema(b *testing.B) { - b.StopTimer() - session := createSession(b) - defer func() { - b.StopTimer() - session.Close() - }() - w := WikiTest{session, b} - b.StartTimer() - - for i := 0; i < b.N; i++ { - w.CreateSchema() - } -} - -func TestWikiCreatePages(t *testing.T) { - session := createSession(t) - defer session.Close() - - w := WikiTest{session, t} - w.CreateSchema() - numPages := 5 - w.CreatePages(numPages) - if count := w.GetPageCount(); count != numPages { - t.Errorf("expected %d pages, got %d pages.", numPages, count) - } -} - -func BenchmarkWikiCreatePages(b *testing.B) { - b.StopTimer() - session := createSession(b) - defer func() { - b.StopTimer() - session.Close() - }() - w := WikiTest{session, b} - w.CreateSchema() - b.StartTimer() - - w.CreatePages(b.N) -} - -func BenchmarkWikiSelectAllPages(b *testing.B) { - b.StopTimer() - session := createSession(b) - defer func() { - b.StopTimer() - session.Close() - }() - w := WikiTest{session, b} - w.CreateSchema() - w.CreatePages(100) - b.StartTimer() - - var page WikiPage - for i := 0; i < b.N; i++ { - iter := session.Query(`SELECT title, revid, body, views, protected, - modified, tags, attachments, rating - FROM wiki_page`).Iter() - for iter.Scan(&page.Title, &page.RevId, &page.Body, &page.Views, - &page.Protected, &page.Modified, &page.Tags, &page.Attachments, - &page.Rating) { - // pass - } - if err := iter.Close(); err != nil { - b.Error(err) - } - } -} - -func BenchmarkWikiSelectSinglePage(b *testing.B) { - b.StopTimer() - session := createSession(b) - defer func() { - b.StopTimer() - session.Close() - }() - w := WikiTest{session, b} - w.CreateSchema() - pages := make([]WikiPage, 100) - w.CreatePages(len(pages)) - iter := session.Query(`SELECT title, revid FROM wiki_page`).Iter() - for i := 0; i < len(pages); i++ { - if !iter.Scan(&pages[i].Title, &pages[i].RevId) { - pages = pages[:i] - break - } - } - if err := iter.Close(); err != nil { - b.Error(err) - } - b.StartTimer() - - var page WikiPage - for i := 0; i < b.N; i++ { - p := &pages[i%len(pages)] - if err := w.SelectPage(&page, p.Title, p.RevId); err != nil { - b.Error(err) - } - } -} - -func BenchmarkWikiSelectPageCount(b *testing.B) { - b.StopTimer() - session := createSession(b) - defer func() { - b.StopTimer() - session.Close() - }() - w := WikiTest{session, b} - w.CreateSchema() - numPages := 10 - w.CreatePages(numPages) - b.StartTimer() - for i := 0; i < b.N; i++ { - if count := w.GetPageCount(); count != numPages { - b.Errorf("expected %d pages, got %d pages.", numPages, count) - } - } -} - -func TestWikiTypicalCRUD(t *testing.T) { - session := createSession(t) - defer session.Close() - - w := WikiTest{session, t} - w.CreateSchema() - for _, page := range wikiTestData { - if err := w.InsertPage(page); err != nil { - t.Error("InsertPage:", err) - } - } - if count := w.GetPageCount(); count != len(wikiTestData) { - t.Errorf("count: expected %d, got %d\n", len(wikiTestData), count) - } - for _, original := range wikiTestData { - page := new(WikiPage) - if err := w.SelectPage(page, original.Title, original.RevId); err != nil { - t.Error("SelectPage:", err) - continue - } - sort.Sort(sort.StringSlice(page.Tags)) - sort.Sort(sort.StringSlice(original.Tags)) - if !reflect.DeepEqual(page, original) { - t.Errorf("page: expected %#v, got %#v\n", original, page) - } - } -} diff --git a/Godeps/_workspace/src/github.com/golang/snappy/snappy_test.go b/Godeps/_workspace/src/github.com/golang/snappy/snappy_test.go deleted file mode 100644 index f8188f11e..000000000 --- a/Godeps/_workspace/src/github.com/golang/snappy/snappy_test.go +++ /dev/null @@ -1,377 +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" - "flag" - "fmt" - "io" - "io/ioutil" - "math/rand" - "net/http" - "os" - "path/filepath" - "strings" - "testing" -) - -var ( - download = flag.Bool("download", false, "If true, download any missing files before running benchmarks") - testdata = flag.String("testdata", "testdata", "Directory containing the test data") -) - -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 !bytes.Equal(b, d) { - return fmt.Errorf("roundtrip mismatch:\n\twant %v\n\tgot %v", b, d) - } - 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(27354294)) - for n := 1; n < 20000; n += 23 { - b := make([]byte, n) - for i := range b { - b[i] = uint8(rng.Uint32()) - } - 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) { - data := []byte("\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x00") - if _, err := DecodedLen(data); err != ErrCorrupt { - t.Errorf("DecodedLen: got %v, want ErrCorrupt", err) - } - if _, err := Decode(nil, data); err != ErrCorrupt { - t.Errorf("Decode: got %v, want ErrCorrupt", err) - } - - // The encoded varint overflows 32 bits - data = []byte("\xff\xff\xff\xff\xff\x00") - - if _, err := DecodedLen(data); err != ErrCorrupt { - t.Errorf("DecodedLen: got %v, want ErrCorrupt", err) - } - if _, err := Decode(nil, data); err != ErrCorrupt { - t.Errorf("Decode: got %v, want ErrCorrupt", err) - } -} - -func cmp(a, b []byte) error { - 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 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 maxUncompressedChunkLen (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 TestReaderReset(t *testing.T) { - gold := bytes.Repeat([]byte("All that is gold does not glitter,\n"), 10000) - buf := new(bytes.Buffer) - if _, err := NewWriter(buf).Write(gold); err != nil { - t.Fatalf("Write: %v", err) - } - encoded, invalid, partial := buf.String(), "invalid", "partial" - r := NewReader(nil) - for i, s := range []string{encoded, invalid, partial, encoded, partial, invalid, encoded, encoded} { - if s == partial { - r.Reset(strings.NewReader(encoded)) - if _, err := r.Read(make([]byte, 101)); err != nil { - t.Errorf("#%d: %v", i, err) - continue - } - continue - } - r.Reset(strings.NewReader(s)) - got, err := ioutil.ReadAll(r) - switch s { - case encoded: - if err != nil { - t.Errorf("#%d: %v", i, err) - continue - } - if err := cmp(got, gold); err != nil { - t.Errorf("#%d: %v", i, err) - continue - } - case invalid: - if err == nil { - t.Errorf("#%d: got nil error, want non-nil", i) - continue - } - } - } -} - -func TestWriterReset(t *testing.T) { - gold := bytes.Repeat([]byte("Not all those who wander are lost;\n"), 10000) - var gots, wants [][]byte - const n = 20 - w, failed := NewWriter(nil), false - for i := 0; i <= n; i++ { - buf := new(bytes.Buffer) - w.Reset(buf) - want := gold[:len(gold)*i/n] - if _, err := w.Write(want); err != nil { - t.Errorf("#%d: Write: %v", i, err) - failed = true - continue - } - got, err := ioutil.ReadAll(NewReader(buf)) - if err != nil { - t.Errorf("#%d: ReadAll: %v", i, err) - failed = true - continue - } - gots = append(gots, got) - wants = append(wants, want) - } - if failed { - return - } - for i := range gots { - if err := cmp(gots[i], wants[i]); err != nil { - t.Errorf("#%d: %v", i, err) - } - } -} - -func benchDecode(b *testing.B, src []byte) { - encoded := Encode(nil, src) - // Bandwidth is in amount of uncompressed data. - b.SetBytes(int64(len(src))) - b.ResetTimer() - for i := 0; i < b.N; i++ { - Decode(src, encoded) - } -} - -func benchEncode(b *testing.B, src []byte) { - // Bandwidth is in amount of uncompressed data. - b.SetBytes(int64(len(src))) - dst := make([]byte, MaxEncodedLen(len(src))) - b.ResetTimer() - for i := 0; i < b.N; i++ { - Encode(dst, src) - } -} - -func readFile(b testing.TB, filename string) []byte { - src, err := ioutil.ReadFile(filename) - if err != nil { - b.Skipf("skipping benchmark: %v", err) - } - if len(src) == 0 { - b.Fatalf("%s has zero length", filename) - } - return src -} - -// expand returns a slice of length n containing repeated copies of src. -func expand(src []byte, n int) []byte { - dst := make([]byte, n) - for x := dst; len(x) > 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 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 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) } - -// 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 -}{ - {"html", "html"}, - {"urls", "urls.10K"}, - {"jpg", "fireworks.jpeg"}, - {"jpg_200", "fireworks.jpeg"}, - {"pdf", "paper-100k.pdf"}, - {"html4", "html_x_4"}, - {"txt1", "alice29.txt"}, - {"txt2", "asyoulik.txt"}, - {"txt3", "lcet10.txt"}, - {"txt4", "plrabn12.txt"}, - {"pb", "geo.protodata"}, - {"gaviota", "kppkn.gtb"}, -} - -// The test data files are present at this canonical URL. -const baseURL = "https://raw.githubusercontent.com/google/snappy/master/testdata/" - -func downloadTestdata(b *testing.B, basename string) (errRet error) { - filename := filepath.Join(*testdata, basename) - if stat, err := os.Stat(filename); err == nil && stat.Size() != 0 { - return nil - } - - if !*download { - b.Skipf("test data not found; skipping benchmark without the -download flag") - } - // Download the official snappy C++ implementation reference test data - // files for benchmarking. - if err := os.Mkdir(*testdata, 0777); err != nil && !os.IsExist(err) { - return fmt.Errorf("failed to create testdata: %s", 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 := baseURL + 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, n int, decode bool) { - if err := downloadTestdata(b, testFiles[n].filename); err != nil { - b.Fatalf("failed to download testdata: %s", err) - } - data := readFile(b, filepath.Join(*testdata, testFiles[n].filename)) - 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) } diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/activity_events.go b/Godeps/_workspace/src/github.com/google/go-github/github/activity_events.go index b8a5e66b9..2a40d3e00 100644 --- a/Godeps/_workspace/src/github.com/google/go-github/github/activity_events.go +++ b/Godeps/_workspace/src/github.com/google/go-github/github/activity_events.go @@ -249,11 +249,11 @@ func (s *ActivityService) ListEventsPerformedByUser(user string, publicOnly bool return *events, resp, err } -// ListEventsRecievedByUser lists the events recieved by a user. If publicOnly is +// ListEventsReceivedByUser lists the events received by a user. If publicOnly is // true, only public events will be returned. // // GitHub API docs: http://developer.github.com/v3/activity/events/#list-events-that-a-user-has-received -func (s *ActivityService) ListEventsRecievedByUser(user string, publicOnly bool, opt *ListOptions) ([]Event, *Response, error) { +func (s *ActivityService) ListEventsReceivedByUser(user string, publicOnly bool, opt *ListOptions) ([]Event, *Response, error) { var u string if publicOnly { u = fmt.Sprintf("users/%v/received_events/public", user) diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/activity_events_test.go b/Godeps/_workspace/src/github.com/google/go-github/github/activity_events_test.go deleted file mode 100644 index 1541f5e9f..000000000 --- a/Godeps/_workspace/src/github.com/google/go-github/github/activity_events_test.go +++ /dev/null @@ -1,305 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestActivityService_ListEvents(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/events", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "page": "2", - }) - fmt.Fprint(w, `[{"id":"1"},{"id":"2"}]`) - }) - - opt := &ListOptions{Page: 2} - events, _, err := client.Activity.ListEvents(opt) - if err != nil { - t.Errorf("Activities.ListEvents returned error: %v", err) - } - - want := []Event{{ID: String("1")}, {ID: String("2")}} - if !reflect.DeepEqual(events, want) { - t.Errorf("Activities.ListEvents returned %+v, want %+v", events, want) - } -} - -func TestActivityService_ListRepositoryEvents(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/events", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "page": "2", - }) - fmt.Fprint(w, `[{"id":"1"},{"id":"2"}]`) - }) - - opt := &ListOptions{Page: 2} - events, _, err := client.Activity.ListRepositoryEvents("o", "r", opt) - if err != nil { - t.Errorf("Activities.ListRepositoryEvents returned error: %v", err) - } - - want := []Event{{ID: String("1")}, {ID: String("2")}} - if !reflect.DeepEqual(events, want) { - t.Errorf("Activities.ListRepositoryEvents returned %+v, want %+v", events, want) - } -} - -func TestActivityService_ListRepositoryEvents_invalidOwner(t *testing.T) { - _, _, err := client.Activity.ListRepositoryEvents("%", "%", nil) - testURLParseError(t, err) -} - -func TestActivityService_ListIssueEventsForRepository(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/issues/events", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "page": "2", - }) - fmt.Fprint(w, `[{"id":"1"},{"id":"2"}]`) - }) - - opt := &ListOptions{Page: 2} - events, _, err := client.Activity.ListIssueEventsForRepository("o", "r", opt) - if err != nil { - t.Errorf("Activities.ListIssueEventsForRepository returned error: %v", err) - } - - want := []Event{{ID: String("1")}, {ID: String("2")}} - if !reflect.DeepEqual(events, want) { - t.Errorf("Activities.ListIssueEventsForRepository returned %+v, want %+v", events, want) - } -} - -func TestActivityService_ListIssueEventsForRepository_invalidOwner(t *testing.T) { - _, _, err := client.Activity.ListIssueEventsForRepository("%", "%", nil) - testURLParseError(t, err) -} - -func TestActivityService_ListEventsForRepoNetwork(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/networks/o/r/events", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "page": "2", - }) - fmt.Fprint(w, `[{"id":"1"},{"id":"2"}]`) - }) - - opt := &ListOptions{Page: 2} - events, _, err := client.Activity.ListEventsForRepoNetwork("o", "r", opt) - if err != nil { - t.Errorf("Activities.ListEventsForRepoNetwork returned error: %v", err) - } - - want := []Event{{ID: String("1")}, {ID: String("2")}} - if !reflect.DeepEqual(events, want) { - t.Errorf("Activities.ListEventsForRepoNetwork returned %+v, want %+v", events, want) - } -} - -func TestActivityService_ListEventsForRepoNetwork_invalidOwner(t *testing.T) { - _, _, err := client.Activity.ListEventsForRepoNetwork("%", "%", nil) - testURLParseError(t, err) -} - -func TestActivityService_ListEventsForOrganization(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/orgs/o/events", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "page": "2", - }) - fmt.Fprint(w, `[{"id":"1"},{"id":"2"}]`) - }) - - opt := &ListOptions{Page: 2} - events, _, err := client.Activity.ListEventsForOrganization("o", opt) - if err != nil { - t.Errorf("Activities.ListEventsForOrganization returned error: %v", err) - } - - want := []Event{{ID: String("1")}, {ID: String("2")}} - if !reflect.DeepEqual(events, want) { - t.Errorf("Activities.ListEventsForOrganization returned %+v, want %+v", events, want) - } -} - -func TestActivityService_ListEventsForOrganization_invalidOrg(t *testing.T) { - _, _, err := client.Activity.ListEventsForOrganization("%", nil) - testURLParseError(t, err) -} - -func TestActivityService_ListEventsPerformedByUser_all(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/users/u/events", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "page": "2", - }) - fmt.Fprint(w, `[{"id":"1"},{"id":"2"}]`) - }) - - opt := &ListOptions{Page: 2} - events, _, err := client.Activity.ListEventsPerformedByUser("u", false, opt) - if err != nil { - t.Errorf("Events.ListPerformedByUser returned error: %v", err) - } - - want := []Event{{ID: String("1")}, {ID: String("2")}} - if !reflect.DeepEqual(events, want) { - t.Errorf("Events.ListPerformedByUser returned %+v, want %+v", events, want) - } -} - -func TestActivityService_ListEventsPerformedByUser_publicOnly(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/users/u/events/public", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `[{"id":"1"},{"id":"2"}]`) - }) - - events, _, err := client.Activity.ListEventsPerformedByUser("u", true, nil) - if err != nil { - t.Errorf("Events.ListPerformedByUser returned error: %v", err) - } - - want := []Event{{ID: String("1")}, {ID: String("2")}} - if !reflect.DeepEqual(events, want) { - t.Errorf("Events.ListPerformedByUser returned %+v, want %+v", events, want) - } -} - -func TestActivityService_ListEventsPerformedByUser_invalidUser(t *testing.T) { - _, _, err := client.Activity.ListEventsPerformedByUser("%", false, nil) - testURLParseError(t, err) -} - -func TestActivityService_ListEventsRecievedByUser_all(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/users/u/received_events", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "page": "2", - }) - fmt.Fprint(w, `[{"id":"1"},{"id":"2"}]`) - }) - - opt := &ListOptions{Page: 2} - events, _, err := client.Activity.ListEventsRecievedByUser("u", false, opt) - if err != nil { - t.Errorf("Events.ListRecievedByUser returned error: %v", err) - } - - want := []Event{{ID: String("1")}, {ID: String("2")}} - if !reflect.DeepEqual(events, want) { - t.Errorf("Events.ListRecievedUser returned %+v, want %+v", events, want) - } -} - -func TestActivityService_ListEventsRecievedByUser_publicOnly(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/users/u/received_events/public", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `[{"id":"1"},{"id":"2"}]`) - }) - - events, _, err := client.Activity.ListEventsRecievedByUser("u", true, nil) - if err != nil { - t.Errorf("Events.ListRecievedByUser returned error: %v", err) - } - - want := []Event{{ID: String("1")}, {ID: String("2")}} - if !reflect.DeepEqual(events, want) { - t.Errorf("Events.ListRecievedByUser returned %+v, want %+v", events, want) - } -} - -func TestActivityService_ListEventsRecievedByUser_invalidUser(t *testing.T) { - _, _, err := client.Activity.ListEventsRecievedByUser("%", false, nil) - testURLParseError(t, err) -} - -func TestActivityService_ListUserEventsForOrganization(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/users/u/events/orgs/o", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "page": "2", - }) - fmt.Fprint(w, `[{"id":"1"},{"id":"2"}]`) - }) - - opt := &ListOptions{Page: 2} - events, _, err := client.Activity.ListUserEventsForOrganization("o", "u", opt) - if err != nil { - t.Errorf("Activities.ListUserEventsForOrganization returned error: %v", err) - } - - want := []Event{{ID: String("1")}, {ID: String("2")}} - if !reflect.DeepEqual(events, want) { - t.Errorf("Activities.ListUserEventsForOrganization returned %+v, want %+v", events, want) - } -} - -func TestActivity_EventPayload_typed(t *testing.T) { - raw := []byte(`{"type": "PushEvent","payload":{"push_id": 1}}`) - var event *Event - if err := json.Unmarshal(raw, &event); err != nil { - t.Fatalf("Unmarshal Event returned error: %v", err) - } - - want := &PushEvent{PushID: Int(1)} - if !reflect.DeepEqual(event.Payload(), want) { - t.Errorf("Event Payload returned %+v, want %+v", event.Payload(), want) - } -} - -// TestEvent_Payload_untyped checks that unrecognized events are parsed to an -// interface{} value (instead of being discarded or throwing an error), for -// forward compatibility with new event types. -func TestActivity_EventPayload_untyped(t *testing.T) { - raw := []byte(`{"type": "UnrecognizedEvent","payload":{"field": "val"}}`) - var event *Event - if err := json.Unmarshal(raw, &event); err != nil { - t.Fatalf("Unmarshal Event returned error: %v", err) - } - - want := map[string]interface{}{"field": "val"} - if !reflect.DeepEqual(event.Payload(), want) { - t.Errorf("Event Payload returned %+v, want %+v", event.Payload(), want) - } -} diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/activity_notifications.go b/Godeps/_workspace/src/github.com/google/go-github/github/activity_notifications.go index 786df98a9..290b95427 100644 --- a/Godeps/_workspace/src/github.com/google/go-github/github/activity_notifications.go +++ b/Godeps/_workspace/src/github.com/google/go-github/github/activity_notifications.go @@ -41,6 +41,7 @@ type NotificationListOptions struct { All bool `url:"all,omitempty"` Participating bool `url:"participating,omitempty"` Since time.Time `url:"since,omitempty"` + Before time.Time `url:"before,omitempty"` } // ListNotifications lists all notifications for the authenticated user. diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/activity_notifications_test.go b/Godeps/_workspace/src/github.com/google/go-github/github/activity_notifications_test.go deleted file mode 100644 index 829e118e9..000000000 --- a/Godeps/_workspace/src/github.com/google/go-github/github/activity_notifications_test.go +++ /dev/null @@ -1,203 +0,0 @@ -// Copyright 2014 The go-github 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 github - -import ( - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" - "time" -) - -func TestActivityService_ListNotification(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/notifications", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "all": "true", - "participating": "true", - "since": "2006-01-02T15:04:05Z", - }) - - fmt.Fprint(w, `[{"id":"1", "subject":{"title":"t"}}]`) - }) - - opt := &NotificationListOptions{ - All: true, - Participating: true, - Since: time.Date(2006, 01, 02, 15, 04, 05, 0, time.UTC), - } - notifications, _, err := client.Activity.ListNotifications(opt) - if err != nil { - t.Errorf("Activity.ListNotifications returned error: %v", err) - } - - want := []Notification{{ID: String("1"), Subject: &NotificationSubject{Title: String("t")}}} - if !reflect.DeepEqual(notifications, want) { - t.Errorf("Activity.ListNotifications returned %+v, want %+v", notifications, want) - } -} - -func TestActivityService_ListRepositoryNotification(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/notifications", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `[{"id":"1"}]`) - }) - - notifications, _, err := client.Activity.ListRepositoryNotifications("o", "r", nil) - if err != nil { - t.Errorf("Activity.ListRepositoryNotifications returned error: %v", err) - } - - want := []Notification{{ID: String("1")}} - if !reflect.DeepEqual(notifications, want) { - t.Errorf("Activity.ListRepositoryNotifications returned %+v, want %+v", notifications, want) - } -} - -func TestActivityService_MarkNotificationsRead(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/notifications", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "PUT") - testFormValues(t, r, values{ - "last_read_at": "2006-01-02T15:04:05Z", - }) - - w.WriteHeader(http.StatusResetContent) - }) - - _, err := client.Activity.MarkNotificationsRead(time.Date(2006, 01, 02, 15, 04, 05, 0, time.UTC)) - if err != nil { - t.Errorf("Activity.MarkNotificationsRead returned error: %v", err) - } -} - -func TestActivityService_MarkRepositoryNotificationsRead(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/notifications", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "PUT") - testFormValues(t, r, values{ - "last_read_at": "2006-01-02T15:04:05Z", - }) - - w.WriteHeader(http.StatusResetContent) - }) - - _, err := client.Activity.MarkRepositoryNotificationsRead("o", "r", time.Date(2006, 01, 02, 15, 04, 05, 0, time.UTC)) - if err != nil { - t.Errorf("Activity.MarkRepositoryNotificationsRead returned error: %v", err) - } -} - -func TestActivityService_GetThread(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/notifications/threads/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"id":"1"}`) - }) - - notification, _, err := client.Activity.GetThread("1") - if err != nil { - t.Errorf("Activity.GetThread returned error: %v", err) - } - - want := &Notification{ID: String("1")} - if !reflect.DeepEqual(notification, want) { - t.Errorf("Activity.GetThread returned %+v, want %+v", notification, want) - } -} - -func TestActivityService_MarkThreadRead(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/notifications/threads/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "PATCH") - w.WriteHeader(http.StatusResetContent) - }) - - _, err := client.Activity.MarkThreadRead("1") - if err != nil { - t.Errorf("Activity.MarkThreadRead returned error: %v", err) - } -} - -func TestActivityService_GetThreadSubscription(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/notifications/threads/1/subscription", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"subscribed":true}`) - }) - - sub, _, err := client.Activity.GetThreadSubscription("1") - if err != nil { - t.Errorf("Activity.GetThreadSubscription returned error: %v", err) - } - - want := &Subscription{Subscribed: Bool(true)} - if !reflect.DeepEqual(sub, want) { - t.Errorf("Activity.GetThreadSubscription returned %+v, want %+v", sub, want) - } -} - -func TestActivityService_SetThreadSubscription(t *testing.T) { - setup() - defer teardown() - - input := &Subscription{Subscribed: Bool(true)} - - mux.HandleFunc("/notifications/threads/1/subscription", func(w http.ResponseWriter, r *http.Request) { - v := new(Subscription) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "PUT") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"ignored":true}`) - }) - - sub, _, err := client.Activity.SetThreadSubscription("1", input) - if err != nil { - t.Errorf("Activity.SetThreadSubscription returned error: %v", err) - } - - want := &Subscription{Ignored: Bool(true)} - if !reflect.DeepEqual(sub, want) { - t.Errorf("Activity.SetThreadSubscription returned %+v, want %+v", sub, want) - } -} - -func TestActivityService_DeleteThreadSubscription(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/notifications/threads/1/subscription", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - w.WriteHeader(http.StatusNoContent) - }) - - _, err := client.Activity.DeleteThreadSubscription("1") - if err != nil { - t.Errorf("Activity.DeleteThreadSubscription returned error: %v", err) - } -} diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/activity_star_test.go b/Godeps/_workspace/src/github.com/google/go-github/github/activity_star_test.go deleted file mode 100644 index eb2c4055e..000000000 --- a/Godeps/_workspace/src/github.com/google/go-github/github/activity_star_test.go +++ /dev/null @@ -1,170 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "fmt" - "net/http" - "reflect" - "testing" - "time" -) - -func TestActivityService_ListStargazers(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/stargazers", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "page": "2", - }) - - fmt.Fprint(w, `[{"id":1}]`) - }) - - stargazers, _, err := client.Activity.ListStargazers("o", "r", &ListOptions{Page: 2}) - if err != nil { - t.Errorf("Activity.ListStargazers returned error: %v", err) - } - - want := []User{{ID: Int(1)}} - if !reflect.DeepEqual(stargazers, want) { - t.Errorf("Activity.ListStargazers returned %+v, want %+v", stargazers, want) - } -} - -func TestActivityService_ListStarred_authenticatedUser(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/user/starred", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeStarringPreview) - fmt.Fprint(w, `[{"starred_at":"2002-02-10T15:30:00Z","repo":{"id":1}}]`) - }) - - repos, _, err := client.Activity.ListStarred("", nil) - if err != nil { - t.Errorf("Activity.ListStarred returned error: %v", err) - } - - want := []StarredRepository{{StarredAt: &Timestamp{time.Date(2002, time.February, 10, 15, 30, 0, 0, time.UTC)}, Repository: &Repository{ID: Int(1)}}} - if !reflect.DeepEqual(repos, want) { - t.Errorf("Activity.ListStarred returned %+v, want %+v", repos, want) - } -} - -func TestActivityService_ListStarred_specifiedUser(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/users/u/starred", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeStarringPreview) - testFormValues(t, r, values{ - "sort": "created", - "direction": "asc", - "page": "2", - }) - fmt.Fprint(w, `[{"starred_at":"2002-02-10T15:30:00Z","repo":{"id":2}}]`) - }) - - opt := &ActivityListStarredOptions{"created", "asc", ListOptions{Page: 2}} - repos, _, err := client.Activity.ListStarred("u", opt) - if err != nil { - t.Errorf("Activity.ListStarred returned error: %v", err) - } - - want := []StarredRepository{{StarredAt: &Timestamp{time.Date(2002, time.February, 10, 15, 30, 0, 0, time.UTC)}, Repository: &Repository{ID: Int(2)}}} - if !reflect.DeepEqual(repos, want) { - t.Errorf("Activity.ListStarred returned %+v, want %+v", repos, want) - } -} - -func TestActivityService_ListStarred_invalidUser(t *testing.T) { - _, _, err := client.Activity.ListStarred("%", nil) - testURLParseError(t, err) -} - -func TestActivityService_IsStarred_hasStar(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/user/starred/o/r", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - w.WriteHeader(http.StatusNoContent) - }) - - star, _, err := client.Activity.IsStarred("o", "r") - if err != nil { - t.Errorf("Activity.IsStarred returned error: %v", err) - } - if want := true; star != want { - t.Errorf("Activity.IsStarred returned %+v, want %+v", star, want) - } -} - -func TestActivityService_IsStarred_noStar(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/user/starred/o/r", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - w.WriteHeader(http.StatusNotFound) - }) - - star, _, err := client.Activity.IsStarred("o", "r") - if err != nil { - t.Errorf("Activity.IsStarred returned error: %v", err) - } - if want := false; star != want { - t.Errorf("Activity.IsStarred returned %+v, want %+v", star, want) - } -} - -func TestActivityService_IsStarred_invalidID(t *testing.T) { - _, _, err := client.Activity.IsStarred("%", "%") - testURLParseError(t, err) -} - -func TestActivityService_Star(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/user/starred/o/r", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "PUT") - }) - - _, err := client.Activity.Star("o", "r") - if err != nil { - t.Errorf("Activity.Star returned error: %v", err) - } -} - -func TestActivityService_Star_invalidID(t *testing.T) { - _, err := client.Activity.Star("%", "%") - testURLParseError(t, err) -} - -func TestActivityService_Unstar(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/user/starred/o/r", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - }) - - _, err := client.Activity.Unstar("o", "r") - if err != nil { - t.Errorf("Activity.Unstar returned error: %v", err) - } -} - -func TestActivityService_Unstar_invalidID(t *testing.T) { - _, err := client.Activity.Unstar("%", "%") - testURLParseError(t, err) -} diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/activity_watching_test.go b/Godeps/_workspace/src/github.com/google/go-github/github/activity_watching_test.go deleted file mode 100644 index 8046ee217..000000000 --- a/Godeps/_workspace/src/github.com/google/go-github/github/activity_watching_test.go +++ /dev/null @@ -1,177 +0,0 @@ -// Copyright 2014 The go-github 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 github - -import ( - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestActivityService_ListWatchers(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/subscribers", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "page": "2", - }) - - fmt.Fprint(w, `[{"id":1}]`) - }) - - watchers, _, err := client.Activity.ListWatchers("o", "r", &ListOptions{Page: 2}) - if err != nil { - t.Errorf("Activity.ListWatchers returned error: %v", err) - } - - want := []User{{ID: Int(1)}} - if !reflect.DeepEqual(watchers, want) { - t.Errorf("Activity.ListWatchers returned %+v, want %+v", watchers, want) - } -} - -func TestActivityService_ListWatched_authenticatedUser(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/user/subscriptions", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `[{"id":1}]`) - }) - - watched, _, err := client.Activity.ListWatched("") - if err != nil { - t.Errorf("Activity.ListWatched returned error: %v", err) - } - - want := []Repository{{ID: Int(1)}} - if !reflect.DeepEqual(watched, want) { - t.Errorf("Activity.ListWatched returned %+v, want %+v", watched, want) - } -} - -func TestActivityService_ListWatched_specifiedUser(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/users/u/subscriptions", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `[{"id":1}]`) - }) - - watched, _, err := client.Activity.ListWatched("u") - if err != nil { - t.Errorf("Activity.ListWatched returned error: %v", err) - } - - want := []Repository{{ID: Int(1)}} - if !reflect.DeepEqual(watched, want) { - t.Errorf("Activity.ListWatched returned %+v, want %+v", watched, want) - } -} - -func TestActivityService_GetRepositorySubscription_true(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/subscription", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"subscribed":true}`) - }) - - sub, _, err := client.Activity.GetRepositorySubscription("o", "r") - if err != nil { - t.Errorf("Activity.GetRepositorySubscription returned error: %v", err) - } - - want := &Subscription{Subscribed: Bool(true)} - if !reflect.DeepEqual(sub, want) { - t.Errorf("Activity.GetRepositorySubscription returned %+v, want %+v", sub, want) - } -} - -func TestActivityService_GetRepositorySubscription_false(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/subscription", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - w.WriteHeader(http.StatusNotFound) - }) - - sub, _, err := client.Activity.GetRepositorySubscription("o", "r") - if err != nil { - t.Errorf("Activity.GetRepositorySubscription returned error: %v", err) - } - - var want *Subscription - if !reflect.DeepEqual(sub, want) { - t.Errorf("Activity.GetRepositorySubscription returned %+v, want %+v", sub, want) - } -} - -func TestActivityService_GetRepositorySubscription_error(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/subscription", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - w.WriteHeader(http.StatusBadRequest) - }) - - _, _, err := client.Activity.GetRepositorySubscription("o", "r") - if err == nil { - t.Errorf("Expected HTTP 400 response") - } -} - -func TestActivityService_SetRepositorySubscription(t *testing.T) { - setup() - defer teardown() - - input := &Subscription{Subscribed: Bool(true)} - - mux.HandleFunc("/repos/o/r/subscription", func(w http.ResponseWriter, r *http.Request) { - v := new(Subscription) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "PUT") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"ignored":true}`) - }) - - sub, _, err := client.Activity.SetRepositorySubscription("o", "r", input) - if err != nil { - t.Errorf("Activity.SetRepositorySubscription returned error: %v", err) - } - - want := &Subscription{Ignored: Bool(true)} - if !reflect.DeepEqual(sub, want) { - t.Errorf("Activity.SetRepositorySubscription returned %+v, want %+v", sub, want) - } -} - -func TestActivityService_DeleteRepositorySubscription(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/subscription", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - w.WriteHeader(http.StatusNoContent) - }) - - _, err := client.Activity.DeleteRepositorySubscription("o", "r") - if err != nil { - t.Errorf("Activity.DeleteRepositorySubscription returned error: %v", err) - } -} diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/gists_comments_test.go b/Godeps/_workspace/src/github.com/google/go-github/github/gists_comments_test.go deleted file mode 100644 index b2bbf23f7..000000000 --- a/Godeps/_workspace/src/github.com/google/go-github/github/gists_comments_test.go +++ /dev/null @@ -1,155 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestGistsService_ListComments(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/gists/1/comments", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"page": "2"}) - fmt.Fprint(w, `[{"id": 1}]`) - }) - - opt := &ListOptions{Page: 2} - comments, _, err := client.Gists.ListComments("1", opt) - - if err != nil { - t.Errorf("Gists.Comments returned error: %v", err) - } - - want := []GistComment{{ID: Int(1)}} - if !reflect.DeepEqual(comments, want) { - t.Errorf("Gists.ListComments returned %+v, want %+v", comments, want) - } -} - -func TestGistsService_ListComments_invalidID(t *testing.T) { - _, _, err := client.Gists.ListComments("%", nil) - testURLParseError(t, err) -} - -func TestGistsService_GetComment(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/gists/1/comments/2", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"id": 1}`) - }) - - comment, _, err := client.Gists.GetComment("1", 2) - - if err != nil { - t.Errorf("Gists.GetComment returned error: %v", err) - } - - want := &GistComment{ID: Int(1)} - if !reflect.DeepEqual(comment, want) { - t.Errorf("Gists.GetComment returned %+v, want %+v", comment, want) - } -} - -func TestGistsService_GetComment_invalidID(t *testing.T) { - _, _, err := client.Gists.GetComment("%", 1) - testURLParseError(t, err) -} - -func TestGistsService_CreateComment(t *testing.T) { - setup() - defer teardown() - - input := &GistComment{ID: Int(1), Body: String("b")} - - mux.HandleFunc("/gists/1/comments", func(w http.ResponseWriter, r *http.Request) { - v := new(GistComment) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "POST") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"id":1}`) - }) - - comment, _, err := client.Gists.CreateComment("1", input) - if err != nil { - t.Errorf("Gists.CreateComment returned error: %v", err) - } - - want := &GistComment{ID: Int(1)} - if !reflect.DeepEqual(comment, want) { - t.Errorf("Gists.CreateComment returned %+v, want %+v", comment, want) - } -} - -func TestGistsService_CreateComment_invalidID(t *testing.T) { - _, _, err := client.Gists.CreateComment("%", nil) - testURLParseError(t, err) -} - -func TestGistsService_EditComment(t *testing.T) { - setup() - defer teardown() - - input := &GistComment{ID: Int(1), Body: String("b")} - - mux.HandleFunc("/gists/1/comments/2", func(w http.ResponseWriter, r *http.Request) { - v := new(GistComment) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "PATCH") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"id":1}`) - }) - - comment, _, err := client.Gists.EditComment("1", 2, input) - if err != nil { - t.Errorf("Gists.EditComment returned error: %v", err) - } - - want := &GistComment{ID: Int(1)} - if !reflect.DeepEqual(comment, want) { - t.Errorf("Gists.EditComment returned %+v, want %+v", comment, want) - } -} - -func TestGistsService_EditComment_invalidID(t *testing.T) { - _, _, err := client.Gists.EditComment("%", 1, nil) - testURLParseError(t, err) -} - -func TestGistsService_DeleteComment(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/gists/1/comments/2", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - }) - - _, err := client.Gists.DeleteComment("1", 2) - if err != nil { - t.Errorf("Gists.Delete returned error: %v", err) - } -} - -func TestGistsService_DeleteComment_invalidID(t *testing.T) { - _, err := client.Gists.DeleteComment("%", 1) - testURLParseError(t, err) -} diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/gists_test.go b/Godeps/_workspace/src/github.com/google/go-github/github/gists_test.go deleted file mode 100644 index 573120129..000000000 --- a/Godeps/_workspace/src/github.com/google/go-github/github/gists_test.go +++ /dev/null @@ -1,411 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" - "time" -) - -func TestGistsService_List_specifiedUser(t *testing.T) { - setup() - defer teardown() - - since := "2013-01-01T00:00:00Z" - - mux.HandleFunc("/users/u/gists", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "since": since, - }) - fmt.Fprint(w, `[{"id": "1"}]`) - }) - - opt := &GistListOptions{Since: time.Date(2013, time.January, 1, 0, 0, 0, 0, time.UTC)} - gists, _, err := client.Gists.List("u", opt) - - if err != nil { - t.Errorf("Gists.List returned error: %v", err) - } - - want := []Gist{{ID: String("1")}} - if !reflect.DeepEqual(gists, want) { - t.Errorf("Gists.List returned %+v, want %+v", gists, want) - } -} - -func TestGistsService_List_authenticatedUser(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/gists", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `[{"id": "1"}]`) - }) - - gists, _, err := client.Gists.List("", nil) - if err != nil { - t.Errorf("Gists.List returned error: %v", err) - } - - want := []Gist{{ID: String("1")}} - if !reflect.DeepEqual(gists, want) { - t.Errorf("Gists.List returned %+v, want %+v", gists, want) - } -} - -func TestGistsService_List_invalidUser(t *testing.T) { - _, _, err := client.Gists.List("%", nil) - testURLParseError(t, err) -} - -func TestGistsService_ListAll(t *testing.T) { - setup() - defer teardown() - - since := "2013-01-01T00:00:00Z" - - mux.HandleFunc("/gists/public", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "since": since, - }) - fmt.Fprint(w, `[{"id": "1"}]`) - }) - - opt := &GistListOptions{Since: time.Date(2013, time.January, 1, 0, 0, 0, 0, time.UTC)} - gists, _, err := client.Gists.ListAll(opt) - - if err != nil { - t.Errorf("Gists.ListAll returned error: %v", err) - } - - want := []Gist{{ID: String("1")}} - if !reflect.DeepEqual(gists, want) { - t.Errorf("Gists.ListAll returned %+v, want %+v", gists, want) - } -} - -func TestGistsService_ListStarred(t *testing.T) { - setup() - defer teardown() - - since := "2013-01-01T00:00:00Z" - - mux.HandleFunc("/gists/starred", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "since": since, - }) - fmt.Fprint(w, `[{"id": "1"}]`) - }) - - opt := &GistListOptions{Since: time.Date(2013, time.January, 1, 0, 0, 0, 0, time.UTC)} - gists, _, err := client.Gists.ListStarred(opt) - - if err != nil { - t.Errorf("Gists.ListStarred returned error: %v", err) - } - - want := []Gist{{ID: String("1")}} - if !reflect.DeepEqual(gists, want) { - t.Errorf("Gists.ListStarred returned %+v, want %+v", gists, want) - } -} - -func TestGistsService_Get(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/gists/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"id": "1"}`) - }) - - gist, _, err := client.Gists.Get("1") - - if err != nil { - t.Errorf("Gists.Get returned error: %v", err) - } - - want := &Gist{ID: String("1")} - if !reflect.DeepEqual(gist, want) { - t.Errorf("Gists.Get returned %+v, want %+v", gist, want) - } -} - -func TestGistsService_Get_invalidID(t *testing.T) { - _, _, err := client.Gists.Get("%") - testURLParseError(t, err) -} - -func TestGistsService_GetRevision(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/gists/1/s", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"id": "1"}`) - }) - - gist, _, err := client.Gists.GetRevision("1", "s") - - if err != nil { - t.Errorf("Gists.Get returned error: %v", err) - } - - want := &Gist{ID: String("1")} - if !reflect.DeepEqual(gist, want) { - t.Errorf("Gists.Get returned %+v, want %+v", gist, want) - } -} - -func TestGistsService_GetRevision_invalidID(t *testing.T) { - _, _, err := client.Gists.GetRevision("%", "%") - testURLParseError(t, err) -} - -func TestGistsService_Create(t *testing.T) { - setup() - defer teardown() - - input := &Gist{ - Description: String("Gist description"), - Public: Bool(false), - Files: map[GistFilename]GistFile{ - "test.txt": {Content: String("Gist file content")}, - }, - } - - mux.HandleFunc("/gists", func(w http.ResponseWriter, r *http.Request) { - v := new(Gist) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "POST") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, - ` - { - "id": "1", - "description": "Gist description", - "public": false, - "files": { - "test.txt": { - "filename": "test.txt" - } - } - }`) - }) - - gist, _, err := client.Gists.Create(input) - if err != nil { - t.Errorf("Gists.Create returned error: %v", err) - } - - want := &Gist{ - ID: String("1"), - Description: String("Gist description"), - Public: Bool(false), - Files: map[GistFilename]GistFile{ - "test.txt": {Filename: String("test.txt")}, - }, - } - if !reflect.DeepEqual(gist, want) { - t.Errorf("Gists.Create returned %+v, want %+v", gist, want) - } -} - -func TestGistsService_Edit(t *testing.T) { - setup() - defer teardown() - - input := &Gist{ - Description: String("New description"), - Files: map[GistFilename]GistFile{ - "new.txt": {Content: String("new file content")}, - }, - } - - mux.HandleFunc("/gists/1", func(w http.ResponseWriter, r *http.Request) { - v := new(Gist) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "PATCH") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, - ` - { - "id": "1", - "description": "new description", - "public": false, - "files": { - "test.txt": { - "filename": "test.txt" - }, - "new.txt": { - "filename": "new.txt" - } - } - }`) - }) - - gist, _, err := client.Gists.Edit("1", input) - if err != nil { - t.Errorf("Gists.Edit returned error: %v", err) - } - - want := &Gist{ - ID: String("1"), - Description: String("new description"), - Public: Bool(false), - Files: map[GistFilename]GistFile{ - "test.txt": {Filename: String("test.txt")}, - "new.txt": {Filename: String("new.txt")}, - }, - } - if !reflect.DeepEqual(gist, want) { - t.Errorf("Gists.Edit returned %+v, want %+v", gist, want) - } -} - -func TestGistsService_Edit_invalidID(t *testing.T) { - _, _, err := client.Gists.Edit("%", nil) - testURLParseError(t, err) -} - -func TestGistsService_Delete(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/gists/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - }) - - _, err := client.Gists.Delete("1") - if err != nil { - t.Errorf("Gists.Delete returned error: %v", err) - } -} - -func TestGistsService_Delete_invalidID(t *testing.T) { - _, err := client.Gists.Delete("%") - testURLParseError(t, err) -} - -func TestGistsService_Star(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/gists/1/star", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "PUT") - }) - - _, err := client.Gists.Star("1") - if err != nil { - t.Errorf("Gists.Star returned error: %v", err) - } -} - -func TestGistsService_Star_invalidID(t *testing.T) { - _, err := client.Gists.Star("%") - testURLParseError(t, err) -} - -func TestGistsService_Unstar(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/gists/1/star", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - }) - - _, err := client.Gists.Unstar("1") - if err != nil { - t.Errorf("Gists.Unstar returned error: %v", err) - } -} - -func TestGistsService_Unstar_invalidID(t *testing.T) { - _, err := client.Gists.Unstar("%") - testURLParseError(t, err) -} - -func TestGistsService_IsStarred_hasStar(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/gists/1/star", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - w.WriteHeader(http.StatusNoContent) - }) - - star, _, err := client.Gists.IsStarred("1") - if err != nil { - t.Errorf("Gists.Starred returned error: %v", err) - } - if want := true; star != want { - t.Errorf("Gists.Starred returned %+v, want %+v", star, want) - } -} - -func TestGistsService_IsStarred_noStar(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/gists/1/star", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - w.WriteHeader(http.StatusNotFound) - }) - - star, _, err := client.Gists.IsStarred("1") - if err != nil { - t.Errorf("Gists.Starred returned error: %v", err) - } - if want := false; star != want { - t.Errorf("Gists.Starred returned %+v, want %+v", star, want) - } -} - -func TestGistsService_IsStarred_invalidID(t *testing.T) { - _, _, err := client.Gists.IsStarred("%") - testURLParseError(t, err) -} - -func TestGistsService_Fork(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/gists/1/forks", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "POST") - fmt.Fprint(w, `{"id": "2"}`) - }) - - gist, _, err := client.Gists.Fork("1") - - if err != nil { - t.Errorf("Gists.Fork returned error: %v", err) - } - - want := &Gist{ID: String("2")} - if !reflect.DeepEqual(gist, want) { - t.Errorf("Gists.Fork returned %+v, want %+v", gist, want) - } -} - -func TestGistsService_Fork_invalidID(t *testing.T) { - _, _, err := client.Gists.Fork("%") - testURLParseError(t, err) -} diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/git_blobs_test.go b/Godeps/_workspace/src/github.com/google/go-github/github/git_blobs_test.go deleted file mode 100644 index 994549f2c..000000000 --- a/Godeps/_workspace/src/github.com/google/go-github/github/git_blobs_test.go +++ /dev/null @@ -1,92 +0,0 @@ -package github - -import ( - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestGitService_GetBlob(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/git/blobs/s", func(w http.ResponseWriter, r *http.Request) { - if m := "GET"; m != r.Method { - t.Errorf("Request method = %v, want %v", r.Method, m) - } - fmt.Fprint(w, `{ - "sha": "s", - "content": "blob content" - }`) - }) - - blob, _, err := client.Git.GetBlob("o", "r", "s") - if err != nil { - t.Errorf("Git.GetBlob returned error: %v", err) - } - - want := Blob{ - SHA: String("s"), - Content: String("blob content"), - } - - if !reflect.DeepEqual(*blob, want) { - t.Errorf("Blob.Get returned %+v, want %+v", *blob, want) - } -} - -func TestGitService_GetBlob_invalidOwner(t *testing.T) { - _, _, err := client.Git.GetBlob("%", "%", "%") - testURLParseError(t, err) -} - -func TestGitService_CreateBlob(t *testing.T) { - setup() - defer teardown() - - input := &Blob{ - SHA: String("s"), - Content: String("blob content"), - Encoding: String("utf-8"), - Size: Int(12), - } - - mux.HandleFunc("/repos/o/r/git/blobs", func(w http.ResponseWriter, r *http.Request) { - v := new(Blob) - json.NewDecoder(r.Body).Decode(v) - - if m := "POST"; m != r.Method { - t.Errorf("Request method = %v, want %v", r.Method, m) - } - - want := input - if !reflect.DeepEqual(v, want) { - t.Errorf("Git.CreateBlob request body: %+v, want %+v", v, want) - } - - fmt.Fprint(w, `{ - "sha": "s", - "content": "blob content", - "encoding": "utf-8", - "size": 12 - }`) - }) - - blob, _, err := client.Git.CreateBlob("o", "r", input) - if err != nil { - t.Errorf("Git.CreateBlob returned error: %v", err) - } - - want := input - - if !reflect.DeepEqual(*blob, *want) { - t.Errorf("Git.CreateBlob returned %+v, want %+v", *blob, *want) - } -} - -func TestGitService_CreateBlob_invalidOwner(t *testing.T) { - _, _, err := client.Git.CreateBlob("%", "%", &Blob{}) - testURLParseError(t, err) -} diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/git_commits_test.go b/Godeps/_workspace/src/github.com/google/go-github/github/git_commits_test.go deleted file mode 100644 index 538f52360..000000000 --- a/Godeps/_workspace/src/github.com/google/go-github/github/git_commits_test.go +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestGitService_GetCommit(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/git/commits/s", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"sha":"s","message":"m","author":{"name":"n"}}`) - }) - - commit, _, err := client.Git.GetCommit("o", "r", "s") - if err != nil { - t.Errorf("Git.GetCommit returned error: %v", err) - } - - want := &Commit{SHA: String("s"), Message: String("m"), Author: &CommitAuthor{Name: String("n")}} - if !reflect.DeepEqual(commit, want) { - t.Errorf("Git.GetCommit returned %+v, want %+v", commit, want) - } -} - -func TestGitService_GetCommit_invalidOwner(t *testing.T) { - _, _, err := client.Git.GetCommit("%", "%", "%") - testURLParseError(t, err) -} - -func TestGitService_CreateCommit(t *testing.T) { - setup() - defer teardown() - - input := &Commit{ - Message: String("m"), - Tree: &Tree{SHA: String("t")}, - Parents: []Commit{{SHA: String("p")}}, - } - - mux.HandleFunc("/repos/o/r/git/commits", func(w http.ResponseWriter, r *http.Request) { - v := new(createCommit) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "POST") - - want := &createCommit{ - Message: input.Message, - Tree: String("t"), - Parents: []string{"p"}, - } - if !reflect.DeepEqual(v, want) { - t.Errorf("Request body = %+v, want %+v", v, want) - } - fmt.Fprint(w, `{"sha":"s"}`) - }) - - commit, _, err := client.Git.CreateCommit("o", "r", input) - if err != nil { - t.Errorf("Git.CreateCommit returned error: %v", err) - } - - want := &Commit{SHA: String("s")} - if !reflect.DeepEqual(commit, want) { - t.Errorf("Git.CreateCommit returned %+v, want %+v", commit, want) - } -} - -func TestGitService_CreateCommit_invalidOwner(t *testing.T) { - _, _, err := client.Git.CreateCommit("%", "%", nil) - testURLParseError(t, err) -} diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/git_refs_test.go b/Godeps/_workspace/src/github.com/google/go-github/github/git_refs_test.go deleted file mode 100644 index e66bf54af..000000000 --- a/Godeps/_workspace/src/github.com/google/go-github/github/git_refs_test.go +++ /dev/null @@ -1,280 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestGitService_GetRef(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/git/refs/heads/b", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, ` - { - "ref": "refs/heads/b", - "url": "https://api.github.com/repos/o/r/git/refs/heads/b", - "object": { - "type": "commit", - "sha": "aa218f56b14c9653891f9e74264a383fa43fefbd", - "url": "https://api.github.com/repos/o/r/git/commits/aa218f56b14c9653891f9e74264a383fa43fefbd" - } - }`) - }) - - ref, _, err := client.Git.GetRef("o", "r", "refs/heads/b") - if err != nil { - t.Errorf("Git.GetRef returned error: %v", err) - } - - want := &Reference{ - Ref: String("refs/heads/b"), - URL: String("https://api.github.com/repos/o/r/git/refs/heads/b"), - Object: &GitObject{ - Type: String("commit"), - SHA: String("aa218f56b14c9653891f9e74264a383fa43fefbd"), - URL: String("https://api.github.com/repos/o/r/git/commits/aa218f56b14c9653891f9e74264a383fa43fefbd"), - }, - } - if !reflect.DeepEqual(ref, want) { - t.Errorf("Git.GetRef returned %+v, want %+v", ref, want) - } - - // without 'refs/' prefix - if _, _, err := client.Git.GetRef("o", "r", "heads/b"); err != nil { - t.Errorf("Git.GetRef returned error: %v", err) - } -} - -func TestGitService_ListRefs(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/git/refs", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, ` - [ - { - "ref": "refs/heads/branchA", - "url": "https://api.github.com/repos/o/r/git/refs/heads/branchA", - "object": { - "type": "commit", - "sha": "aa218f56b14c9653891f9e74264a383fa43fefbd", - "url": "https://api.github.com/repos/o/r/git/commits/aa218f56b14c9653891f9e74264a383fa43fefbd" - } - }, - { - "ref": "refs/heads/branchB", - "url": "https://api.github.com/repos/o/r/git/refs/heads/branchB", - "object": { - "type": "commit", - "sha": "aa218f56b14c9653891f9e74264a383fa43fefbd", - "url": "https://api.github.com/repos/o/r/git/commits/aa218f56b14c9653891f9e74264a383fa43fefbd" - } - } - ]`) - }) - - refs, _, err := client.Git.ListRefs("o", "r", nil) - if err != nil { - t.Errorf("Git.ListRefs returned error: %v", err) - } - - want := []Reference{ - { - Ref: String("refs/heads/branchA"), - URL: String("https://api.github.com/repos/o/r/git/refs/heads/branchA"), - Object: &GitObject{ - Type: String("commit"), - SHA: String("aa218f56b14c9653891f9e74264a383fa43fefbd"), - URL: String("https://api.github.com/repos/o/r/git/commits/aa218f56b14c9653891f9e74264a383fa43fefbd"), - }, - }, - { - Ref: String("refs/heads/branchB"), - URL: String("https://api.github.com/repos/o/r/git/refs/heads/branchB"), - Object: &GitObject{ - Type: String("commit"), - SHA: String("aa218f56b14c9653891f9e74264a383fa43fefbd"), - URL: String("https://api.github.com/repos/o/r/git/commits/aa218f56b14c9653891f9e74264a383fa43fefbd"), - }, - }, - } - if !reflect.DeepEqual(refs, want) { - t.Errorf("Git.ListRefs returned %+v, want %+v", refs, want) - } -} - -func TestGitService_ListRefs_options(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/git/refs/t", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"page": "2"}) - fmt.Fprint(w, `[{"ref": "r"}]`) - }) - - opt := &ReferenceListOptions{Type: "t", ListOptions: ListOptions{Page: 2}} - refs, _, err := client.Git.ListRefs("o", "r", opt) - if err != nil { - t.Errorf("Git.ListRefs returned error: %v", err) - } - - want := []Reference{{Ref: String("r")}} - if !reflect.DeepEqual(refs, want) { - t.Errorf("Git.ListRefs returned %+v, want %+v", refs, want) - } -} - -func TestGitService_CreateRef(t *testing.T) { - setup() - defer teardown() - - args := &createRefRequest{ - Ref: String("refs/heads/b"), - SHA: String("aa218f56b14c9653891f9e74264a383fa43fefbd"), - } - - mux.HandleFunc("/repos/o/r/git/refs", func(w http.ResponseWriter, r *http.Request) { - v := new(createRefRequest) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "POST") - if !reflect.DeepEqual(v, args) { - t.Errorf("Request body = %+v, want %+v", v, args) - } - fmt.Fprint(w, ` - { - "ref": "refs/heads/b", - "url": "https://api.github.com/repos/o/r/git/refs/heads/b", - "object": { - "type": "commit", - "sha": "aa218f56b14c9653891f9e74264a383fa43fefbd", - "url": "https://api.github.com/repos/o/r/git/commits/aa218f56b14c9653891f9e74264a383fa43fefbd" - } - }`) - }) - - ref, _, err := client.Git.CreateRef("o", "r", &Reference{ - Ref: String("refs/heads/b"), - Object: &GitObject{ - SHA: String("aa218f56b14c9653891f9e74264a383fa43fefbd"), - }, - }) - if err != nil { - t.Errorf("Git.CreateRef returned error: %v", err) - } - - want := &Reference{ - Ref: String("refs/heads/b"), - URL: String("https://api.github.com/repos/o/r/git/refs/heads/b"), - Object: &GitObject{ - Type: String("commit"), - SHA: String("aa218f56b14c9653891f9e74264a383fa43fefbd"), - URL: String("https://api.github.com/repos/o/r/git/commits/aa218f56b14c9653891f9e74264a383fa43fefbd"), - }, - } - if !reflect.DeepEqual(ref, want) { - t.Errorf("Git.CreateRef returned %+v, want %+v", ref, want) - } - - // without 'refs/' prefix - _, _, err = client.Git.CreateRef("o", "r", &Reference{ - Ref: String("heads/b"), - Object: &GitObject{ - SHA: String("aa218f56b14c9653891f9e74264a383fa43fefbd"), - }, - }) - if err != nil { - t.Errorf("Git.CreateRef returned error: %v", err) - } -} - -func TestGitService_UpdateRef(t *testing.T) { - setup() - defer teardown() - - args := &updateRefRequest{ - SHA: String("aa218f56b14c9653891f9e74264a383fa43fefbd"), - Force: Bool(true), - } - - mux.HandleFunc("/repos/o/r/git/refs/heads/b", func(w http.ResponseWriter, r *http.Request) { - v := new(updateRefRequest) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "PATCH") - if !reflect.DeepEqual(v, args) { - t.Errorf("Request body = %+v, want %+v", v, args) - } - fmt.Fprint(w, ` - { - "ref": "refs/heads/b", - "url": "https://api.github.com/repos/o/r/git/refs/heads/b", - "object": { - "type": "commit", - "sha": "aa218f56b14c9653891f9e74264a383fa43fefbd", - "url": "https://api.github.com/repos/o/r/git/commits/aa218f56b14c9653891f9e74264a383fa43fefbd" - } - }`) - }) - - ref, _, err := client.Git.UpdateRef("o", "r", &Reference{ - Ref: String("refs/heads/b"), - Object: &GitObject{SHA: String("aa218f56b14c9653891f9e74264a383fa43fefbd")}, - }, true) - if err != nil { - t.Errorf("Git.UpdateRef returned error: %v", err) - } - - want := &Reference{ - Ref: String("refs/heads/b"), - URL: String("https://api.github.com/repos/o/r/git/refs/heads/b"), - Object: &GitObject{ - Type: String("commit"), - SHA: String("aa218f56b14c9653891f9e74264a383fa43fefbd"), - URL: String("https://api.github.com/repos/o/r/git/commits/aa218f56b14c9653891f9e74264a383fa43fefbd"), - }, - } - if !reflect.DeepEqual(ref, want) { - t.Errorf("Git.UpdateRef returned %+v, want %+v", ref, want) - } - - // without 'refs/' prefix - _, _, err = client.Git.UpdateRef("o", "r", &Reference{ - Ref: String("heads/b"), - Object: &GitObject{SHA: String("aa218f56b14c9653891f9e74264a383fa43fefbd")}, - }, true) - if err != nil { - t.Errorf("Git.UpdateRef returned error: %v", err) - } -} - -func TestGitService_DeleteRef(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/git/refs/heads/b", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - }) - - _, err := client.Git.DeleteRef("o", "r", "refs/heads/b") - if err != nil { - t.Errorf("Git.DeleteRef returned error: %v", err) - } - - // without 'refs/' prefix - if _, err := client.Git.DeleteRef("o", "r", "heads/b"); err != nil { - t.Errorf("Git.DeleteRef returned error: %v", err) - } -} diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/git_tags_test.go b/Godeps/_workspace/src/github.com/google/go-github/github/git_tags_test.go deleted file mode 100644 index fb41bf38e..000000000 --- a/Godeps/_workspace/src/github.com/google/go-github/github/git_tags_test.go +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestGitService_GetTag(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/git/tags/s", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - - fmt.Fprint(w, `{"tag": "t"}`) - }) - - tag, _, err := client.Git.GetTag("o", "r", "s") - - if err != nil { - t.Errorf("Git.GetTag returned error: %v", err) - } - - want := &Tag{Tag: String("t")} - if !reflect.DeepEqual(tag, want) { - t.Errorf("Git.GetTag returned %+v, want %+v", tag, want) - } -} - -func TestGitService_CreateTag(t *testing.T) { - setup() - defer teardown() - - input := &createTagRequest{Tag: String("t"), Object: String("s")} - - mux.HandleFunc("/repos/o/r/git/tags", func(w http.ResponseWriter, r *http.Request) { - v := new(createTagRequest) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "POST") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"tag": "t"}`) - }) - - tag, _, err := client.Git.CreateTag("o", "r", &Tag{ - Tag: input.Tag, - Object: &GitObject{SHA: input.Object}, - }) - if err != nil { - t.Errorf("Git.CreateTag returned error: %v", err) - } - - want := &Tag{Tag: String("t")} - if !reflect.DeepEqual(tag, want) { - t.Errorf("Git.GetTag returned %+v, want %+v", tag, want) - } -} diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/git_trees_test.go b/Godeps/_workspace/src/github.com/google/go-github/github/git_trees_test.go deleted file mode 100644 index 99ec4f34c..000000000 --- a/Godeps/_workspace/src/github.com/google/go-github/github/git_trees_test.go +++ /dev/null @@ -1,189 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestGitService_GetTree(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/git/trees/s", func(w http.ResponseWriter, r *http.Request) { - if m := "GET"; m != r.Method { - t.Errorf("Request method = %v, want %v", r.Method, m) - } - fmt.Fprint(w, `{ - "sha": "s", - "tree": [ { "type": "blob" } ] - }`) - }) - - tree, _, err := client.Git.GetTree("o", "r", "s", true) - if err != nil { - t.Errorf("Git.GetTree returned error: %v", err) - } - - want := Tree{ - SHA: String("s"), - Entries: []TreeEntry{ - { - Type: String("blob"), - }, - }, - } - if !reflect.DeepEqual(*tree, want) { - t.Errorf("Tree.Get returned %+v, want %+v", *tree, want) - } -} - -func TestGitService_GetTree_invalidOwner(t *testing.T) { - _, _, err := client.Git.GetTree("%", "%", "%", false) - testURLParseError(t, err) -} - -func TestGitService_CreateTree(t *testing.T) { - setup() - defer teardown() - - input := []TreeEntry{ - { - Path: String("file.rb"), - Mode: String("100644"), - Type: String("blob"), - SHA: String("7c258a9869f33c1e1e1f74fbb32f07c86cb5a75b"), - }, - } - - mux.HandleFunc("/repos/o/r/git/trees", func(w http.ResponseWriter, r *http.Request) { - v := new(createTree) - json.NewDecoder(r.Body).Decode(v) - - if m := "POST"; m != r.Method { - t.Errorf("Request method = %v, want %v", r.Method, m) - } - - want := &createTree{ - BaseTree: "b", - Entries: input, - } - if !reflect.DeepEqual(v, want) { - t.Errorf("Git.CreateTree request body: %+v, want %+v", v, want) - } - - fmt.Fprint(w, `{ - "sha": "cd8274d15fa3ae2ab983129fb037999f264ba9a7", - "tree": [ - { - "path": "file.rb", - "mode": "100644", - "type": "blob", - "size": 132, - "sha": "7c258a9869f33c1e1e1f74fbb32f07c86cb5a75b" - } - ] - }`) - }) - - tree, _, err := client.Git.CreateTree("o", "r", "b", input) - if err != nil { - t.Errorf("Git.CreateTree returned error: %v", err) - } - - want := Tree{ - String("cd8274d15fa3ae2ab983129fb037999f264ba9a7"), - []TreeEntry{ - { - Path: String("file.rb"), - Mode: String("100644"), - Type: String("blob"), - Size: Int(132), - SHA: String("7c258a9869f33c1e1e1f74fbb32f07c86cb5a75b"), - }, - }, - } - - if !reflect.DeepEqual(*tree, want) { - t.Errorf("Git.CreateTree returned %+v, want %+v", *tree, want) - } -} - -func TestGitService_CreateTree_Content(t *testing.T) { - setup() - defer teardown() - - input := []TreeEntry{ - { - Path: String("content.md"), - Mode: String("100644"), - Content: String("file content"), - }, - } - - mux.HandleFunc("/repos/o/r/git/trees", func(w http.ResponseWriter, r *http.Request) { - v := new(createTree) - json.NewDecoder(r.Body).Decode(v) - - if m := "POST"; m != r.Method { - t.Errorf("Request method = %v, want %v", r.Method, m) - } - - want := &createTree{ - BaseTree: "b", - Entries: input, - } - if !reflect.DeepEqual(v, want) { - t.Errorf("Git.CreateTree request body: %+v, want %+v", v, want) - } - - fmt.Fprint(w, `{ - "sha": "5c6780ad2c68743383b740fd1dab6f6a33202b11", - "url": "https://api.github.com/repos/o/r/git/trees/5c6780ad2c68743383b740fd1dab6f6a33202b11", - "tree": [ - { - "mode": "100644", - "type": "blob", - "sha": "aad8feacf6f8063150476a7b2bd9770f2794c08b", - "path": "content.md", - "size": 12, - "url": "https://api.github.com/repos/o/r/git/blobs/aad8feacf6f8063150476a7b2bd9770f2794c08b" - } - ] - }`) - }) - - tree, _, err := client.Git.CreateTree("o", "r", "b", input) - if err != nil { - t.Errorf("Git.CreateTree returned error: %v", err) - } - - want := Tree{ - String("5c6780ad2c68743383b740fd1dab6f6a33202b11"), - []TreeEntry{ - { - Path: String("content.md"), - Mode: String("100644"), - Type: String("blob"), - Size: Int(12), - SHA: String("aad8feacf6f8063150476a7b2bd9770f2794c08b"), - }, - }, - } - - if !reflect.DeepEqual(*tree, want) { - t.Errorf("Git.CreateTree returned %+v, want %+v", *tree, want) - } -} - -func TestGitService_CreateTree_invalidOwner(t *testing.T) { - _, _, err := client.Git.CreateTree("%", "%", "", nil) - testURLParseError(t, err) -} diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/github.go b/Godeps/_workspace/src/github.com/google/go-github/github/github.go index 737c17cc3..30b839059 100644 --- a/Godeps/_workspace/src/github.com/google/go-github/github/github.go +++ b/Godeps/_workspace/src/github.com/google/go-github/github/github.go @@ -66,7 +66,7 @@ type Client struct { // Rate specifies the current rate limit for the client as determined by the // most recent API call. If the client is used in a multi-user application, - // this rate may not always be up-to-date. Call RateLimit() to check the + // this rate may not always be up-to-date. Call RateLimits() to check the // current rate. Rate Rate diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/github_test.go b/Godeps/_workspace/src/github.com/google/go-github/github/github_test.go deleted file mode 100644 index 05c817b65..000000000 --- a/Godeps/_workspace/src/github.com/google/go-github/github/github_test.go +++ /dev/null @@ -1,679 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "bytes" - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "net/http/httptest" - "net/url" - "os" - "path" - "reflect" - "strings" - "testing" - "time" -) - -var ( - // mux is the HTTP request multiplexer used with the test server. - mux *http.ServeMux - - // client is the GitHub client being tested. - client *Client - - // server is a test HTTP server used to provide mock API responses. - server *httptest.Server -) - -// setup sets up a test HTTP server along with a github.Client that is -// configured to talk to that test server. Tests should register handlers on -// mux which provide mock responses for the API method being tested. -func setup() { - // test server - mux = http.NewServeMux() - server = httptest.NewServer(mux) - - // github client configured to use test server - client = NewClient(nil) - url, _ := url.Parse(server.URL) - client.BaseURL = url - client.UploadURL = url -} - -// teardown closes the test HTTP server. -func teardown() { - server.Close() -} - -// openTestFile creates a new file with the given name and content for testing. -// In order to ensure the exact file name, this function will create a new temp -// directory, and create the file in that directory. It is the caller's -// responsibility to remove the directy and its contents when no longer needed. -func openTestFile(name, content string) (file *os.File, dir string, err error) { - dir, err = ioutil.TempDir("", "go-github") - if err != nil { - return nil, dir, err - } - - file, err = os.OpenFile(path.Join(dir, name), os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600) - if err != nil { - return nil, dir, err - } - - fmt.Fprint(file, content) - - // close and re-open the file to keep file.Stat() happy - file.Close() - file, err = os.Open(file.Name()) - if err != nil { - return nil, dir, err - } - - return file, dir, err -} - -func testMethod(t *testing.T, r *http.Request, want string) { - if got := r.Method; got != want { - t.Errorf("Request method: %v, want %v", got, want) - } -} - -type values map[string]string - -func testFormValues(t *testing.T, r *http.Request, values values) { - want := url.Values{} - for k, v := range values { - want.Add(k, v) - } - - r.ParseForm() - if got := r.Form; !reflect.DeepEqual(got, want) { - t.Errorf("Request parameters: %v, want %v", got, want) - } -} - -func testHeader(t *testing.T, r *http.Request, header string, want string) { - if got := r.Header.Get(header); got != want { - t.Errorf("Header.Get(%q) returned %s, want %s", header, got, want) - } -} - -func testURLParseError(t *testing.T, err error) { - if err == nil { - t.Errorf("Expected error to be returned") - } - if err, ok := err.(*url.Error); !ok || err.Op != "parse" { - t.Errorf("Expected URL parse error, got %+v", err) - } -} - -func testBody(t *testing.T, r *http.Request, want string) { - b, err := ioutil.ReadAll(r.Body) - if err != nil { - t.Errorf("Error reading request body: %v", err) - } - if got := string(b); got != want { - t.Errorf("request Body is %s, want %s", got, want) - } -} - -// Helper function to test that a value is marshalled to JSON as expected. -func testJSONMarshal(t *testing.T, v interface{}, want string) { - j, err := json.Marshal(v) - if err != nil { - t.Errorf("Unable to marshal JSON for %v", v) - } - - w := new(bytes.Buffer) - err = json.Compact(w, []byte(want)) - if err != nil { - t.Errorf("String is not valid json: %s", want) - } - - if w.String() != string(j) { - t.Errorf("json.Marshal(%q) returned %s, want %s", v, j, w) - } - - // now go the other direction and make sure things unmarshal as expected - u := reflect.ValueOf(v).Interface() - if err := json.Unmarshal([]byte(want), u); err != nil { - t.Errorf("Unable to unmarshal JSON for %v", want) - } - - if !reflect.DeepEqual(v, u) { - t.Errorf("json.Unmarshal(%q) returned %s, want %s", want, u, v) - } -} - -func TestNewClient(t *testing.T) { - c := NewClient(nil) - - if got, want := c.BaseURL.String(), defaultBaseURL; got != want { - t.Errorf("NewClient BaseURL is %v, want %v", got, want) - } - if got, want := c.UserAgent, userAgent; got != want { - t.Errorf("NewClient UserAgent is %v, want %v", got, want) - } -} - -func TestNewRequest(t *testing.T) { - c := NewClient(nil) - - inURL, outURL := "/foo", defaultBaseURL+"foo" - inBody, outBody := &User{Login: String("l")}, `{"login":"l"}`+"\n" - req, _ := c.NewRequest("GET", inURL, inBody) - - // test that relative URL was expanded - if got, want := req.URL.String(), outURL; got != want { - t.Errorf("NewRequest(%q) URL is %v, want %v", inURL, got, want) - } - - // test that body was JSON encoded - body, _ := ioutil.ReadAll(req.Body) - if got, want := string(body), outBody; got != want { - t.Errorf("NewRequest(%q) Body is %v, want %v", inBody, got, want) - } - - // test that default user-agent is attached to the request - if got, want := req.Header.Get("User-Agent"), c.UserAgent; got != want { - t.Errorf("NewRequest() User-Agent is %v, want %v", got, want) - } -} - -func TestNewRequest_invalidJSON(t *testing.T) { - c := NewClient(nil) - - type T struct { - A map[int]interface{} - } - _, err := c.NewRequest("GET", "/", &T{}) - - if err == nil { - t.Error("Expected error to be returned.") - } - if err, ok := err.(*json.UnsupportedTypeError); !ok { - t.Errorf("Expected a JSON error; got %#v.", err) - } -} - -func TestNewRequest_badURL(t *testing.T) { - c := NewClient(nil) - _, err := c.NewRequest("GET", ":", nil) - testURLParseError(t, err) -} - -// ensure that no User-Agent header is set if the client's UserAgent is empty. -// This caused a problem with Google's internal http client. -func TestNewRequest_emptyUserAgent(t *testing.T) { - c := NewClient(nil) - c.UserAgent = "" - req, err := c.NewRequest("GET", "/", nil) - if err != nil { - t.Fatalf("NewRequest returned unexpected error: %v", err) - } - if _, ok := req.Header["User-Agent"]; ok { - t.Fatal("constructed request contains unexpected User-Agent header") - } -} - -// If a nil body is passed to github.NewRequest, make sure that nil is also -// passed to http.NewRequest. In most cases, passing an io.Reader that returns -// no content is fine, since there is no difference between an HTTP request -// body that is an empty string versus one that is not set at all. However in -// certain cases, intermediate systems may treat these differently resulting in -// subtle errors. -func TestNewRequest_emptyBody(t *testing.T) { - c := NewClient(nil) - req, err := c.NewRequest("GET", "/", nil) - if err != nil { - t.Fatalf("NewRequest returned unexpected error: %v", err) - } - if req.Body != nil { - t.Fatalf("constructed request contains a non-nil Body") - } -} - -func TestResponse_populatePageValues(t *testing.T) { - r := http.Response{ - Header: http.Header{ - "Link": {`; rel="first",` + - ` ; rel="prev",` + - ` ; rel="next",` + - ` ; rel="last"`, - }, - }, - } - - response := newResponse(&r) - if got, want := response.FirstPage, 1; got != want { - t.Errorf("response.FirstPage: %v, want %v", got, want) - } - if got, want := response.PrevPage, 2; want != got { - t.Errorf("response.PrevPage: %v, want %v", got, want) - } - if got, want := response.NextPage, 4; want != got { - t.Errorf("response.NextPage: %v, want %v", got, want) - } - if got, want := response.LastPage, 5; want != got { - t.Errorf("response.LastPage: %v, want %v", got, want) - } -} - -func TestResponse_populatePageValues_invalid(t *testing.T) { - r := http.Response{ - Header: http.Header{ - "Link": {`,` + - `; rel="first",` + - `https://api.github.com/?page=2; rel="prev",` + - `; rel="next",` + - `; rel="last"`, - }, - }, - } - - response := newResponse(&r) - if got, want := response.FirstPage, 0; got != want { - t.Errorf("response.FirstPage: %v, want %v", got, want) - } - if got, want := response.PrevPage, 0; got != want { - t.Errorf("response.PrevPage: %v, want %v", got, want) - } - if got, want := response.NextPage, 0; got != want { - t.Errorf("response.NextPage: %v, want %v", got, want) - } - if got, want := response.LastPage, 0; got != want { - t.Errorf("response.LastPage: %v, want %v", got, want) - } - - // more invalid URLs - r = http.Response{ - Header: http.Header{ - "Link": {`; rel="first"`}, - }, - } - - response = newResponse(&r) - if got, want := response.FirstPage, 0; got != want { - t.Errorf("response.FirstPage: %v, want %v", got, want) - } -} - -func TestDo(t *testing.T) { - setup() - defer teardown() - - type foo struct { - A string - } - - mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - if m := "GET"; m != r.Method { - t.Errorf("Request method = %v, want %v", r.Method, m) - } - fmt.Fprint(w, `{"A":"a"}`) - }) - - req, _ := client.NewRequest("GET", "/", nil) - body := new(foo) - client.Do(req, body) - - want := &foo{"a"} - if !reflect.DeepEqual(body, want) { - t.Errorf("Response body = %v, want %v", body, want) - } -} - -func TestDo_httpError(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - http.Error(w, "Bad Request", 400) - }) - - req, _ := client.NewRequest("GET", "/", nil) - _, err := client.Do(req, nil) - - if err == nil { - t.Error("Expected HTTP 400 error.") - } -} - -// Test handling of an error caused by the internal http client's Do() -// function. A redirect loop is pretty unlikely to occur within the GitHub -// API, but does allow us to exercise the right code path. -func TestDo_redirectLoop(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - http.Redirect(w, r, "/", http.StatusFound) - }) - - req, _ := client.NewRequest("GET", "/", nil) - _, err := client.Do(req, nil) - - if err == nil { - t.Error("Expected error to be returned.") - } - if err, ok := err.(*url.Error); !ok { - t.Errorf("Expected a URL error; got %#v.", err) - } -} - -func TestDo_rateLimit(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - w.Header().Add(headerRateLimit, "60") - w.Header().Add(headerRateRemaining, "59") - w.Header().Add(headerRateReset, "1372700873") - }) - - if got, want := client.Rate.Limit, 0; got != want { - t.Errorf("Client rate limit = %v, want %v", got, want) - } - if got, want := client.Rate.Limit, 0; got != want { - t.Errorf("Client rate remaining = %v, got %v", got, want) - } - if !client.Rate.Reset.IsZero() { - t.Errorf("Client rate reset not initialized to zero value") - } - - req, _ := client.NewRequest("GET", "/", nil) - client.Do(req, nil) - - if got, want := client.Rate.Limit, 60; got != want { - t.Errorf("Client rate limit = %v, want %v", got, want) - } - if got, want := client.Rate.Remaining, 59; got != want { - t.Errorf("Client rate remaining = %v, want %v", got, want) - } - reset := time.Date(2013, 7, 1, 17, 47, 53, 0, time.UTC) - if client.Rate.Reset.UTC() != reset { - t.Errorf("Client rate reset = %v, want %v", client.Rate.Reset, reset) - } -} - -// ensure rate limit is still parsed, even for error responses -func TestDo_rateLimit_errorResponse(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - w.Header().Add(headerRateLimit, "60") - w.Header().Add(headerRateRemaining, "59") - w.Header().Add(headerRateReset, "1372700873") - http.Error(w, "Bad Request", 400) - }) - - req, _ := client.NewRequest("GET", "/", nil) - client.Do(req, nil) - - if got, want := client.Rate.Limit, 60; got != want { - t.Errorf("Client rate limit = %v, want %v", got, want) - } - if got, want := client.Rate.Remaining, 59; got != want { - t.Errorf("Client rate remaining = %v, want %v", got, want) - } - reset := time.Date(2013, 7, 1, 17, 47, 53, 0, time.UTC) - if client.Rate.Reset.UTC() != reset { - t.Errorf("Client rate reset = %v, want %v", client.Rate.Reset, reset) - } -} - -func TestSanitizeURL(t *testing.T) { - tests := []struct { - in, want string - }{ - {"/?a=b", "/?a=b"}, - {"/?a=b&client_secret=secret", "/?a=b&client_secret=REDACTED"}, - {"/?a=b&client_id=id&client_secret=secret", "/?a=b&client_id=id&client_secret=REDACTED"}, - } - - for _, tt := range tests { - inURL, _ := url.Parse(tt.in) - want, _ := url.Parse(tt.want) - - if got := sanitizeURL(inURL); !reflect.DeepEqual(got, want) { - t.Errorf("sanitizeURL(%v) returned %v, want %v", tt.in, got, want) - } - } -} - -func TestCheckResponse(t *testing.T) { - res := &http.Response{ - Request: &http.Request{}, - StatusCode: http.StatusBadRequest, - Body: ioutil.NopCloser(strings.NewReader(`{"message":"m", - "errors": [{"resource": "r", "field": "f", "code": "c"}]}`)), - } - err := CheckResponse(res).(*ErrorResponse) - - if err == nil { - t.Errorf("Expected error response.") - } - - want := &ErrorResponse{ - Response: res, - Message: "m", - Errors: []Error{{Resource: "r", Field: "f", Code: "c"}}, - } - if !reflect.DeepEqual(err, want) { - t.Errorf("Error = %#v, want %#v", err, want) - } -} - -// ensure that we properly handle API errors that do not contain a response body -func TestCheckResponse_noBody(t *testing.T) { - res := &http.Response{ - Request: &http.Request{}, - StatusCode: http.StatusBadRequest, - Body: ioutil.NopCloser(strings.NewReader("")), - } - err := CheckResponse(res).(*ErrorResponse) - - if err == nil { - t.Errorf("Expected error response.") - } - - want := &ErrorResponse{ - Response: res, - } - if !reflect.DeepEqual(err, want) { - t.Errorf("Error = %#v, want %#v", err, want) - } -} - -func TestParseBooleanResponse_true(t *testing.T) { - result, err := parseBoolResponse(nil) - - if err != nil { - t.Errorf("parseBoolResponse returned error: %+v", err) - } - - if want := true; result != want { - t.Errorf("parseBoolResponse returned %+v, want: %+v", result, want) - } -} - -func TestParseBooleanResponse_false(t *testing.T) { - v := &ErrorResponse{Response: &http.Response{StatusCode: http.StatusNotFound}} - result, err := parseBoolResponse(v) - - if err != nil { - t.Errorf("parseBoolResponse returned error: %+v", err) - } - - if want := false; result != want { - t.Errorf("parseBoolResponse returned %+v, want: %+v", result, want) - } -} - -func TestParseBooleanResponse_error(t *testing.T) { - v := &ErrorResponse{Response: &http.Response{StatusCode: http.StatusBadRequest}} - result, err := parseBoolResponse(v) - - if err == nil { - t.Errorf("Expected error to be returned.") - } - - if want := false; result != want { - t.Errorf("parseBoolResponse returned %+v, want: %+v", result, want) - } -} - -func TestErrorResponse_Error(t *testing.T) { - res := &http.Response{Request: &http.Request{}} - err := ErrorResponse{Message: "m", Response: res} - if err.Error() == "" { - t.Errorf("Expected non-empty ErrorResponse.Error()") - } -} - -func TestError_Error(t *testing.T) { - err := Error{} - if err.Error() == "" { - t.Errorf("Expected non-empty Error.Error()") - } -} - -func TestRateLimit(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/rate_limit", func(w http.ResponseWriter, r *http.Request) { - if m := "GET"; m != r.Method { - t.Errorf("Request method = %v, want %v", r.Method, m) - } - //fmt.Fprint(w, `{"resources":{"core": {"limit":2,"remaining":1,"reset":1372700873}}}`) - fmt.Fprint(w, `{"resources":{ - "core": {"limit":2,"remaining":1,"reset":1372700873}, - "search": {"limit":3,"remaining":2,"reset":1372700874} - }}`) - }) - - rate, _, err := client.RateLimit() - if err != nil { - t.Errorf("Rate limit returned error: %v", err) - } - - want := &Rate{ - Limit: 2, - Remaining: 1, - Reset: Timestamp{time.Date(2013, 7, 1, 17, 47, 53, 0, time.UTC).Local()}, - } - if !reflect.DeepEqual(rate, want) { - t.Errorf("RateLimit returned %+v, want %+v", rate, want) - } -} - -func TestRateLimits(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/rate_limit", func(w http.ResponseWriter, r *http.Request) { - if m := "GET"; m != r.Method { - t.Errorf("Request method = %v, want %v", r.Method, m) - } - fmt.Fprint(w, `{"resources":{ - "core": {"limit":2,"remaining":1,"reset":1372700873}, - "search": {"limit":3,"remaining":2,"reset":1372700874} - }}`) - }) - - rate, _, err := client.RateLimits() - if err != nil { - t.Errorf("RateLimits returned error: %v", err) - } - - want := &RateLimits{ - Core: &Rate{ - Limit: 2, - Remaining: 1, - Reset: Timestamp{time.Date(2013, 7, 1, 17, 47, 53, 0, time.UTC).Local()}, - }, - Search: &Rate{ - Limit: 3, - Remaining: 2, - Reset: Timestamp{time.Date(2013, 7, 1, 17, 47, 54, 0, time.UTC).Local()}, - }, - } - if !reflect.DeepEqual(rate, want) { - t.Errorf("RateLimits returned %+v, want %+v", rate, want) - } -} - -func TestUnauthenticatedRateLimitedTransport(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - var v, want string - q := r.URL.Query() - if v, want = q.Get("client_id"), "id"; v != want { - t.Errorf("OAuth Client ID = %v, want %v", v, want) - } - if v, want = q.Get("client_secret"), "secret"; v != want { - t.Errorf("OAuth Client Secret = %v, want %v", v, want) - } - }) - - tp := &UnauthenticatedRateLimitedTransport{ - ClientID: "id", - ClientSecret: "secret", - } - unauthedClient := NewClient(tp.Client()) - unauthedClient.BaseURL = client.BaseURL - req, _ := unauthedClient.NewRequest("GET", "/", nil) - unauthedClient.Do(req, nil) -} - -func TestUnauthenticatedRateLimitedTransport_missingFields(t *testing.T) { - // missing ClientID - tp := &UnauthenticatedRateLimitedTransport{ - ClientSecret: "secret", - } - _, err := tp.RoundTrip(nil) - if err == nil { - t.Errorf("Expected error to be returned") - } - - // missing ClientSecret - tp = &UnauthenticatedRateLimitedTransport{ - ClientID: "id", - } - _, err = tp.RoundTrip(nil) - if err == nil { - t.Errorf("Expected error to be returned") - } -} - -func TestUnauthenticatedRateLimitedTransport_transport(t *testing.T) { - // default transport - tp := &UnauthenticatedRateLimitedTransport{ - ClientID: "id", - ClientSecret: "secret", - } - if tp.transport() != http.DefaultTransport { - t.Errorf("Expected http.DefaultTransport to be used.") - } - - // custom transport - tp = &UnauthenticatedRateLimitedTransport{ - ClientID: "id", - ClientSecret: "secret", - Transport: &http.Transport{}, - } - if tp.transport() == http.DefaultTransport { - t.Errorf("Expected custom transport to be used.") - } -} diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/gitignore_test.go b/Godeps/_workspace/src/github.com/google/go-github/github/gitignore_test.go deleted file mode 100644 index 6d49d00fa..000000000 --- a/Godeps/_workspace/src/github.com/google/go-github/github/gitignore_test.go +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestGitignoresService_List(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/gitignore/templates", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `["C", "Go"]`) - }) - - available, _, err := client.Gitignores.List() - if err != nil { - t.Errorf("Gitignores.List returned error: %v", err) - } - - want := []string{"C", "Go"} - if !reflect.DeepEqual(available, want) { - t.Errorf("Gitignores.List returned %+v, want %+v", available, want) - } -} - -func TestGitignoresService_Get(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/gitignore/templates/name", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"name":"Name","source":"template source"}`) - }) - - gitignore, _, err := client.Gitignores.Get("name") - if err != nil { - t.Errorf("Gitignores.List returned error: %v", err) - } - - want := &Gitignore{Name: String("Name"), Source: String("template source")} - if !reflect.DeepEqual(gitignore, want) { - t.Errorf("Gitignores.Get returned %+v, want %+v", gitignore, want) - } -} - -func TestGitignoresService_Get_invalidTemplate(t *testing.T) { - _, _, err := client.Gitignores.Get("%") - testURLParseError(t, err) -} diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/issues_assignees_test.go b/Godeps/_workspace/src/github.com/google/go-github/github/issues_assignees_test.go deleted file mode 100644 index 63e024d31..000000000 --- a/Godeps/_workspace/src/github.com/google/go-github/github/issues_assignees_test.go +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestIssuesService_ListAssignees(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/assignees", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"page": "2"}) - fmt.Fprint(w, `[{"id":1}]`) - }) - - opt := &ListOptions{Page: 2} - assignees, _, err := client.Issues.ListAssignees("o", "r", opt) - if err != nil { - t.Errorf("Issues.List returned error: %v", err) - } - - want := []User{{ID: Int(1)}} - if !reflect.DeepEqual(assignees, want) { - t.Errorf("Issues.ListAssignees returned %+v, want %+v", assignees, want) - } -} - -func TestIssuesService_ListAssignees_invalidOwner(t *testing.T) { - _, _, err := client.Issues.ListAssignees("%", "r", nil) - testURLParseError(t, err) -} - -func TestIssuesService_IsAssignee_true(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/assignees/u", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - }) - - assignee, _, err := client.Issues.IsAssignee("o", "r", "u") - if err != nil { - t.Errorf("Issues.IsAssignee returned error: %v", err) - } - if want := true; assignee != want { - t.Errorf("Issues.IsAssignee returned %+v, want %+v", assignee, want) - } -} - -func TestIssuesService_IsAssignee_false(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/assignees/u", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - w.WriteHeader(http.StatusNotFound) - }) - - assignee, _, err := client.Issues.IsAssignee("o", "r", "u") - if err != nil { - t.Errorf("Issues.IsAssignee returned error: %v", err) - } - if want := false; assignee != want { - t.Errorf("Issues.IsAssignee returned %+v, want %+v", assignee, want) - } -} - -func TestIssuesService_IsAssignee_error(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/assignees/u", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - http.Error(w, "BadRequest", http.StatusBadRequest) - }) - - assignee, _, err := client.Issues.IsAssignee("o", "r", "u") - if err == nil { - t.Errorf("Expected HTTP 400 response") - } - if want := false; assignee != want { - t.Errorf("Issues.IsAssignee returned %+v, want %+v", assignee, want) - } -} - -func TestIssuesService_IsAssignee_invalidOwner(t *testing.T) { - _, _, err := client.Issues.IsAssignee("%", "r", "u") - testURLParseError(t, err) -} diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/issues_comments_test.go b/Godeps/_workspace/src/github.com/google/go-github/github/issues_comments_test.go deleted file mode 100644 index 697f4380f..000000000 --- a/Godeps/_workspace/src/github.com/google/go-github/github/issues_comments_test.go +++ /dev/null @@ -1,184 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" - "time" -) - -func TestIssuesService_ListComments_allIssues(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/issues/comments", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "sort": "updated", - "direction": "desc", - "since": "2002-02-10T15:30:00Z", - "page": "2", - }) - fmt.Fprint(w, `[{"id":1}]`) - }) - - opt := &IssueListCommentsOptions{ - Sort: "updated", - Direction: "desc", - Since: time.Date(2002, time.February, 10, 15, 30, 0, 0, time.UTC), - ListOptions: ListOptions{Page: 2}, - } - comments, _, err := client.Issues.ListComments("o", "r", 0, opt) - if err != nil { - t.Errorf("Issues.ListComments returned error: %v", err) - } - - want := []IssueComment{{ID: Int(1)}} - if !reflect.DeepEqual(comments, want) { - t.Errorf("Issues.ListComments returned %+v, want %+v", comments, want) - } -} - -func TestIssuesService_ListComments_specificIssue(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/issues/1/comments", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `[{"id":1}]`) - }) - - comments, _, err := client.Issues.ListComments("o", "r", 1, nil) - if err != nil { - t.Errorf("Issues.ListComments returned error: %v", err) - } - - want := []IssueComment{{ID: Int(1)}} - if !reflect.DeepEqual(comments, want) { - t.Errorf("Issues.ListComments returned %+v, want %+v", comments, want) - } -} - -func TestIssuesService_ListComments_invalidOwner(t *testing.T) { - _, _, err := client.Issues.ListComments("%", "r", 1, nil) - testURLParseError(t, err) -} - -func TestIssuesService_GetComment(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/issues/comments/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"id":1}`) - }) - - comment, _, err := client.Issues.GetComment("o", "r", 1) - if err != nil { - t.Errorf("Issues.GetComment returned error: %v", err) - } - - want := &IssueComment{ID: Int(1)} - if !reflect.DeepEqual(comment, want) { - t.Errorf("Issues.GetComment returned %+v, want %+v", comment, want) - } -} - -func TestIssuesService_GetComment_invalidOrg(t *testing.T) { - _, _, err := client.Issues.GetComment("%", "r", 1) - testURLParseError(t, err) -} - -func TestIssuesService_CreateComment(t *testing.T) { - setup() - defer teardown() - - input := &IssueComment{Body: String("b")} - - mux.HandleFunc("/repos/o/r/issues/1/comments", func(w http.ResponseWriter, r *http.Request) { - v := new(IssueComment) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "POST") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"id":1}`) - }) - - comment, _, err := client.Issues.CreateComment("o", "r", 1, input) - if err != nil { - t.Errorf("Issues.CreateComment returned error: %v", err) - } - - want := &IssueComment{ID: Int(1)} - if !reflect.DeepEqual(comment, want) { - t.Errorf("Issues.CreateComment returned %+v, want %+v", comment, want) - } -} - -func TestIssuesService_CreateComment_invalidOrg(t *testing.T) { - _, _, err := client.Issues.CreateComment("%", "r", 1, nil) - testURLParseError(t, err) -} - -func TestIssuesService_EditComment(t *testing.T) { - setup() - defer teardown() - - input := &IssueComment{Body: String("b")} - - mux.HandleFunc("/repos/o/r/issues/comments/1", func(w http.ResponseWriter, r *http.Request) { - v := new(IssueComment) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "PATCH") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"id":1}`) - }) - - comment, _, err := client.Issues.EditComment("o", "r", 1, input) - if err != nil { - t.Errorf("Issues.EditComment returned error: %v", err) - } - - want := &IssueComment{ID: Int(1)} - if !reflect.DeepEqual(comment, want) { - t.Errorf("Issues.EditComment returned %+v, want %+v", comment, want) - } -} - -func TestIssuesService_EditComment_invalidOwner(t *testing.T) { - _, _, err := client.Issues.EditComment("%", "r", 1, nil) - testURLParseError(t, err) -} - -func TestIssuesService_DeleteComment(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/issues/comments/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - }) - - _, err := client.Issues.DeleteComment("o", "r", 1) - if err != nil { - t.Errorf("Issues.DeleteComments returned error: %v", err) - } -} - -func TestIssuesService_DeleteComment_invalidOwner(t *testing.T) { - _, err := client.Issues.DeleteComment("%", "r", 1) - testURLParseError(t, err) -} diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/issues_events_test.go b/Godeps/_workspace/src/github.com/google/go-github/github/issues_events_test.go deleted file mode 100644 index f90b64a71..000000000 --- a/Godeps/_workspace/src/github.com/google/go-github/github/issues_events_test.go +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright 2014 The go-github 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 github - -import ( - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestIssuesService_ListIssueEvents(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/issues/1/events", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "page": "1", - "per_page": "2", - }) - fmt.Fprint(w, `[{"id":1}]`) - }) - - opt := &ListOptions{Page: 1, PerPage: 2} - events, _, err := client.Issues.ListIssueEvents("o", "r", 1, opt) - - if err != nil { - t.Errorf("Issues.ListIssueEvents returned error: %v", err) - } - - want := []IssueEvent{{ID: Int(1)}} - if !reflect.DeepEqual(events, want) { - t.Errorf("Issues.ListIssueEvents returned %+v, want %+v", events, want) - } -} - -func TestIssuesService_ListRepositoryEvents(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/issues/events", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "page": "1", - "per_page": "2", - }) - fmt.Fprint(w, `[{"id":1}]`) - }) - - opt := &ListOptions{Page: 1, PerPage: 2} - events, _, err := client.Issues.ListRepositoryEvents("o", "r", opt) - - if err != nil { - t.Errorf("Issues.ListRepositoryEvents returned error: %v", err) - } - - want := []IssueEvent{{ID: Int(1)}} - if !reflect.DeepEqual(events, want) { - t.Errorf("Issues.ListRepositoryEvents returned %+v, want %+v", events, want) - } -} - -func TestIssuesService_GetEvent(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/issues/events/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"id":1}`) - }) - - event, _, err := client.Issues.GetEvent("o", "r", 1) - - if err != nil { - t.Errorf("Issues.GetEvent returned error: %v", err) - } - - want := &IssueEvent{ID: Int(1)} - if !reflect.DeepEqual(event, want) { - t.Errorf("Issues.GetEvent returned %+v, want %+v", event, want) - } -} diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/issues_labels_test.go b/Godeps/_workspace/src/github.com/google/go-github/github/issues_labels_test.go deleted file mode 100644 index 2243eb0ee..000000000 --- a/Godeps/_workspace/src/github.com/google/go-github/github/issues_labels_test.go +++ /dev/null @@ -1,313 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestIssuesService_ListLabels(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/labels", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"page": "2"}) - fmt.Fprint(w, `[{"name": "a"},{"name": "b"}]`) - }) - - opt := &ListOptions{Page: 2} - labels, _, err := client.Issues.ListLabels("o", "r", opt) - if err != nil { - t.Errorf("Issues.ListLabels returned error: %v", err) - } - - want := []Label{{Name: String("a")}, {Name: String("b")}} - if !reflect.DeepEqual(labels, want) { - t.Errorf("Issues.ListLabels returned %+v, want %+v", labels, want) - } -} - -func TestIssuesService_ListLabels_invalidOwner(t *testing.T) { - _, _, err := client.Issues.ListLabels("%", "%", nil) - testURLParseError(t, err) -} - -func TestIssuesService_GetLabel(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/labels/n", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"url":"u", "name": "n", "color": "c"}`) - }) - - label, _, err := client.Issues.GetLabel("o", "r", "n") - if err != nil { - t.Errorf("Issues.GetLabel returned error: %v", err) - } - - want := &Label{URL: String("u"), Name: String("n"), Color: String("c")} - if !reflect.DeepEqual(label, want) { - t.Errorf("Issues.GetLabel returned %+v, want %+v", label, want) - } -} - -func TestIssuesService_GetLabel_invalidOwner(t *testing.T) { - _, _, err := client.Issues.GetLabel("%", "%", "%") - testURLParseError(t, err) -} - -func TestIssuesService_CreateLabel(t *testing.T) { - setup() - defer teardown() - - input := &Label{Name: String("n")} - - mux.HandleFunc("/repos/o/r/labels", func(w http.ResponseWriter, r *http.Request) { - v := new(Label) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "POST") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"url":"u"}`) - }) - - label, _, err := client.Issues.CreateLabel("o", "r", input) - if err != nil { - t.Errorf("Issues.CreateLabel returned error: %v", err) - } - - want := &Label{URL: String("u")} - if !reflect.DeepEqual(label, want) { - t.Errorf("Issues.CreateLabel returned %+v, want %+v", label, want) - } -} - -func TestIssuesService_CreateLabel_invalidOwner(t *testing.T) { - _, _, err := client.Issues.CreateLabel("%", "%", nil) - testURLParseError(t, err) -} - -func TestIssuesService_EditLabel(t *testing.T) { - setup() - defer teardown() - - input := &Label{Name: String("z")} - - mux.HandleFunc("/repos/o/r/labels/n", func(w http.ResponseWriter, r *http.Request) { - v := new(Label) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "PATCH") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"url":"u"}`) - }) - - label, _, err := client.Issues.EditLabel("o", "r", "n", input) - if err != nil { - t.Errorf("Issues.EditLabel returned error: %v", err) - } - - want := &Label{URL: String("u")} - if !reflect.DeepEqual(label, want) { - t.Errorf("Issues.EditLabel returned %+v, want %+v", label, want) - } -} - -func TestIssuesService_EditLabel_invalidOwner(t *testing.T) { - _, _, err := client.Issues.EditLabel("%", "%", "%", nil) - testURLParseError(t, err) -} - -func TestIssuesService_DeleteLabel(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/labels/n", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - }) - - _, err := client.Issues.DeleteLabel("o", "r", "n") - if err != nil { - t.Errorf("Issues.DeleteLabel returned error: %v", err) - } -} - -func TestIssuesService_DeleteLabel_invalidOwner(t *testing.T) { - _, err := client.Issues.DeleteLabel("%", "%", "%") - testURLParseError(t, err) -} - -func TestIssuesService_ListLabelsByIssue(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/issues/1/labels", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"page": "2"}) - fmt.Fprint(w, `[{"name": "a"},{"name": "b"}]`) - }) - - opt := &ListOptions{Page: 2} - labels, _, err := client.Issues.ListLabelsByIssue("o", "r", 1, opt) - if err != nil { - t.Errorf("Issues.ListLabelsByIssue returned error: %v", err) - } - - want := []Label{{Name: String("a")}, {Name: String("b")}} - if !reflect.DeepEqual(labels, want) { - t.Errorf("Issues.ListLabelsByIssue returned %+v, want %+v", labels, want) - } -} - -func TestIssuesService_ListLabelsByIssue_invalidOwner(t *testing.T) { - _, _, err := client.Issues.ListLabelsByIssue("%", "%", 1, nil) - testURLParseError(t, err) -} - -func TestIssuesService_AddLabelsToIssue(t *testing.T) { - setup() - defer teardown() - - input := []string{"a", "b"} - - mux.HandleFunc("/repos/o/r/issues/1/labels", func(w http.ResponseWriter, r *http.Request) { - v := new([]string) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "POST") - if !reflect.DeepEqual(*v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `[{"url":"u"}]`) - }) - - labels, _, err := client.Issues.AddLabelsToIssue("o", "r", 1, input) - if err != nil { - t.Errorf("Issues.AddLabelsToIssue returned error: %v", err) - } - - want := []Label{{URL: String("u")}} - if !reflect.DeepEqual(labels, want) { - t.Errorf("Issues.AddLabelsToIssue returned %+v, want %+v", labels, want) - } -} - -func TestIssuesService_AddLabelsToIssue_invalidOwner(t *testing.T) { - _, _, err := client.Issues.AddLabelsToIssue("%", "%", 1, nil) - testURLParseError(t, err) -} - -func TestIssuesService_RemoveLabelForIssue(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/issues/1/labels/l", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - }) - - _, err := client.Issues.RemoveLabelForIssue("o", "r", 1, "l") - if err != nil { - t.Errorf("Issues.RemoveLabelForIssue returned error: %v", err) - } -} - -func TestIssuesService_RemoveLabelForIssue_invalidOwner(t *testing.T) { - _, err := client.Issues.RemoveLabelForIssue("%", "%", 1, "%") - testURLParseError(t, err) -} - -func TestIssuesService_ReplaceLabelsForIssue(t *testing.T) { - setup() - defer teardown() - - input := []string{"a", "b"} - - mux.HandleFunc("/repos/o/r/issues/1/labels", func(w http.ResponseWriter, r *http.Request) { - v := new([]string) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "PUT") - if !reflect.DeepEqual(*v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `[{"url":"u"}]`) - }) - - labels, _, err := client.Issues.ReplaceLabelsForIssue("o", "r", 1, input) - if err != nil { - t.Errorf("Issues.ReplaceLabelsForIssue returned error: %v", err) - } - - want := []Label{{URL: String("u")}} - if !reflect.DeepEqual(labels, want) { - t.Errorf("Issues.ReplaceLabelsForIssue returned %+v, want %+v", labels, want) - } -} - -func TestIssuesService_ReplaceLabelsForIssue_invalidOwner(t *testing.T) { - _, _, err := client.Issues.ReplaceLabelsForIssue("%", "%", 1, nil) - testURLParseError(t, err) -} - -func TestIssuesService_RemoveLabelsForIssue(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/issues/1/labels", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - }) - - _, err := client.Issues.RemoveLabelsForIssue("o", "r", 1) - if err != nil { - t.Errorf("Issues.RemoveLabelsForIssue returned error: %v", err) - } -} - -func TestIssuesService_RemoveLabelsForIssue_invalidOwner(t *testing.T) { - _, err := client.Issues.RemoveLabelsForIssue("%", "%", 1) - testURLParseError(t, err) -} - -func TestIssuesService_ListLabelsForMilestone(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/milestones/1/labels", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"page": "2"}) - fmt.Fprint(w, `[{"name": "a"},{"name": "b"}]`) - }) - - opt := &ListOptions{Page: 2} - labels, _, err := client.Issues.ListLabelsForMilestone("o", "r", 1, opt) - if err != nil { - t.Errorf("Issues.ListLabelsForMilestone returned error: %v", err) - } - - want := []Label{{Name: String("a")}, {Name: String("b")}} - if !reflect.DeepEqual(labels, want) { - t.Errorf("Issues.ListLabelsForMilestone returned %+v, want %+v", labels, want) - } -} - -func TestIssuesService_ListLabelsForMilestone_invalidOwner(t *testing.T) { - _, _, err := client.Issues.ListLabelsForMilestone("%", "%", 1, nil) - testURLParseError(t, err) -} diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/issues_milestones.go b/Godeps/_workspace/src/github.com/google/go-github/github/issues_milestones.go index d5fd8aecc..cbd79200e 100644 --- a/Godeps/_workspace/src/github.com/google/go-github/github/issues_milestones.go +++ b/Godeps/_workspace/src/github.com/google/go-github/github/issues_milestones.go @@ -49,7 +49,7 @@ type MilestoneListOptions struct { // // GitHub API docs: https://developer.github.com/v3/issues/milestones/#list-milestones-for-a-repository func (s *IssuesService) ListMilestones(owner string, repo string, opt *MilestoneListOptions) ([]Milestone, *Response, error) { - u := fmt.Sprintf("/repos/%v/%v/milestones", owner, repo) + u := fmt.Sprintf("repos/%v/%v/milestones", owner, repo) u, err := addOptions(u, opt) if err != nil { return nil, nil, err @@ -73,7 +73,7 @@ func (s *IssuesService) ListMilestones(owner string, repo string, opt *Milestone // // GitHub API docs: https://developer.github.com/v3/issues/milestones/#get-a-single-milestone func (s *IssuesService) GetMilestone(owner string, repo string, number int) (*Milestone, *Response, error) { - u := fmt.Sprintf("/repos/%v/%v/milestones/%d", owner, repo, number) + u := fmt.Sprintf("repos/%v/%v/milestones/%d", owner, repo, number) req, err := s.client.NewRequest("GET", u, nil) if err != nil { return nil, nil, err @@ -92,7 +92,7 @@ func (s *IssuesService) GetMilestone(owner string, repo string, number int) (*Mi // // GitHub API docs: https://developer.github.com/v3/issues/milestones/#create-a-milestone func (s *IssuesService) CreateMilestone(owner string, repo string, milestone *Milestone) (*Milestone, *Response, error) { - u := fmt.Sprintf("/repos/%v/%v/milestones", owner, repo) + u := fmt.Sprintf("repos/%v/%v/milestones", owner, repo) req, err := s.client.NewRequest("POST", u, milestone) if err != nil { return nil, nil, err diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/issues_milestones_test.go b/Godeps/_workspace/src/github.com/google/go-github/github/issues_milestones_test.go deleted file mode 100644 index 817fffedd..000000000 --- a/Godeps/_workspace/src/github.com/google/go-github/github/issues_milestones_test.go +++ /dev/null @@ -1,157 +0,0 @@ -// Copyright 2014 The go-github 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 github - -import ( - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestIssuesService_ListMilestones(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/milestones", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "state": "closed", - "sort": "due_date", - "direction": "asc", - }) - fmt.Fprint(w, `[{"number":1}]`) - }) - - opt := &MilestoneListOptions{"closed", "due_date", "asc"} - milestones, _, err := client.Issues.ListMilestones("o", "r", opt) - if err != nil { - t.Errorf("IssuesService.ListMilestones returned error: %v", err) - } - - want := []Milestone{{Number: Int(1)}} - if !reflect.DeepEqual(milestones, want) { - t.Errorf("IssuesService.ListMilestones returned %+v, want %+v", milestones, want) - } -} - -func TestIssuesService_ListMilestones_invalidOwner(t *testing.T) { - _, _, err := client.Issues.ListMilestones("%", "r", nil) - testURLParseError(t, err) -} - -func TestIssuesService_GetMilestone(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/milestones/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"number":1}`) - }) - - milestone, _, err := client.Issues.GetMilestone("o", "r", 1) - if err != nil { - t.Errorf("IssuesService.GetMilestone returned error: %v", err) - } - - want := &Milestone{Number: Int(1)} - if !reflect.DeepEqual(milestone, want) { - t.Errorf("IssuesService.GetMilestone returned %+v, want %+v", milestone, want) - } -} - -func TestIssuesService_GetMilestone_invalidOwner(t *testing.T) { - _, _, err := client.Issues.GetMilestone("%", "r", 1) - testURLParseError(t, err) -} - -func TestIssuesService_CreateMilestone(t *testing.T) { - setup() - defer teardown() - - input := &Milestone{Title: String("t")} - - mux.HandleFunc("/repos/o/r/milestones", func(w http.ResponseWriter, r *http.Request) { - v := new(Milestone) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "POST") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"number":1}`) - }) - - milestone, _, err := client.Issues.CreateMilestone("o", "r", input) - if err != nil { - t.Errorf("IssuesService.CreateMilestone returned error: %v", err) - } - - want := &Milestone{Number: Int(1)} - if !reflect.DeepEqual(milestone, want) { - t.Errorf("IssuesService.CreateMilestone returned %+v, want %+v", milestone, want) - } -} - -func TestIssuesService_CreateMilestone_invalidOwner(t *testing.T) { - _, _, err := client.Issues.CreateMilestone("%", "r", nil) - testURLParseError(t, err) -} - -func TestIssuesService_EditMilestone(t *testing.T) { - setup() - defer teardown() - - input := &Milestone{Title: String("t")} - - mux.HandleFunc("/repos/o/r/milestones/1", func(w http.ResponseWriter, r *http.Request) { - v := new(Milestone) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "PATCH") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"number":1}`) - }) - - milestone, _, err := client.Issues.EditMilestone("o", "r", 1, input) - if err != nil { - t.Errorf("IssuesService.EditMilestone returned error: %v", err) - } - - want := &Milestone{Number: Int(1)} - if !reflect.DeepEqual(milestone, want) { - t.Errorf("IssuesService.EditMilestone returned %+v, want %+v", milestone, want) - } -} - -func TestIssuesService_EditMilestone_invalidOwner(t *testing.T) { - _, _, err := client.Issues.EditMilestone("%", "r", 1, nil) - testURLParseError(t, err) -} - -func TestIssuesService_DeleteMilestone(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/milestones/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - }) - - _, err := client.Issues.DeleteMilestone("o", "r", 1) - if err != nil { - t.Errorf("IssuesService.DeleteMilestone returned error: %v", err) - } -} - -func TestIssuesService_DeleteMilestone_invalidOwner(t *testing.T) { - _, err := client.Issues.DeleteMilestone("%", "r", 1) - testURLParseError(t, err) -} diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/issues_test.go b/Godeps/_workspace/src/github.com/google/go-github/github/issues_test.go deleted file mode 100644 index f69efd399..000000000 --- a/Godeps/_workspace/src/github.com/google/go-github/github/issues_test.go +++ /dev/null @@ -1,242 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" - "time" -) - -func TestIssuesService_List_all(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/issues", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "filter": "all", - "state": "closed", - "labels": "a,b", - "sort": "updated", - "direction": "asc", - "since": "2002-02-10T15:30:00Z", - "page": "1", - "per_page": "2", - }) - fmt.Fprint(w, `[{"number":1}]`) - }) - - opt := &IssueListOptions{ - "all", "closed", []string{"a", "b"}, "updated", "asc", - time.Date(2002, time.February, 10, 15, 30, 0, 0, time.UTC), - ListOptions{Page: 1, PerPage: 2}, - } - issues, _, err := client.Issues.List(true, opt) - - if err != nil { - t.Errorf("Issues.List returned error: %v", err) - } - - want := []Issue{{Number: Int(1)}} - if !reflect.DeepEqual(issues, want) { - t.Errorf("Issues.List returned %+v, want %+v", issues, want) - } -} - -func TestIssuesService_List_owned(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/user/issues", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `[{"number":1}]`) - }) - - issues, _, err := client.Issues.List(false, nil) - if err != nil { - t.Errorf("Issues.List returned error: %v", err) - } - - want := []Issue{{Number: Int(1)}} - if !reflect.DeepEqual(issues, want) { - t.Errorf("Issues.List returned %+v, want %+v", issues, want) - } -} - -func TestIssuesService_ListByOrg(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/orgs/o/issues", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `[{"number":1}]`) - }) - - issues, _, err := client.Issues.ListByOrg("o", nil) - if err != nil { - t.Errorf("Issues.ListByOrg returned error: %v", err) - } - - want := []Issue{{Number: Int(1)}} - if !reflect.DeepEqual(issues, want) { - t.Errorf("Issues.List returned %+v, want %+v", issues, want) - } -} - -func TestIssuesService_ListByOrg_invalidOrg(t *testing.T) { - _, _, err := client.Issues.ListByOrg("%", nil) - testURLParseError(t, err) -} - -func TestIssuesService_ListByRepo(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/issues", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "milestone": "*", - "state": "closed", - "assignee": "a", - "creator": "c", - "mentioned": "m", - "labels": "a,b", - "sort": "updated", - "direction": "asc", - "since": "2002-02-10T15:30:00Z", - }) - fmt.Fprint(w, `[{"number":1}]`) - }) - - opt := &IssueListByRepoOptions{ - "*", "closed", "a", "c", "m", []string{"a", "b"}, "updated", "asc", - time.Date(2002, time.February, 10, 15, 30, 0, 0, time.UTC), - ListOptions{0, 0}, - } - issues, _, err := client.Issues.ListByRepo("o", "r", opt) - if err != nil { - t.Errorf("Issues.ListByOrg returned error: %v", err) - } - - want := []Issue{{Number: Int(1)}} - if !reflect.DeepEqual(issues, want) { - t.Errorf("Issues.List returned %+v, want %+v", issues, want) - } -} - -func TestIssuesService_ListByRepo_invalidOwner(t *testing.T) { - _, _, err := client.Issues.ListByRepo("%", "r", nil) - testURLParseError(t, err) -} - -func TestIssuesService_Get(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/issues/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"number":1, "labels": [{"url": "u", "name": "n", "color": "c"}]}`) - }) - - issue, _, err := client.Issues.Get("o", "r", 1) - if err != nil { - t.Errorf("Issues.Get returned error: %v", err) - } - - want := &Issue{ - Number: Int(1), - Labels: []Label{{ - URL: String("u"), - Name: String("n"), - Color: String("c"), - }}, - } - if !reflect.DeepEqual(issue, want) { - t.Errorf("Issues.Get returned %+v, want %+v", issue, want) - } -} - -func TestIssuesService_Get_invalidOwner(t *testing.T) { - _, _, err := client.Issues.Get("%", "r", 1) - testURLParseError(t, err) -} - -func TestIssuesService_Create(t *testing.T) { - setup() - defer teardown() - - input := &IssueRequest{ - Title: String("t"), - Body: String("b"), - Assignee: String("a"), - Labels: &[]string{"l1", "l2"}, - } - - mux.HandleFunc("/repos/o/r/issues", func(w http.ResponseWriter, r *http.Request) { - v := new(IssueRequest) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "POST") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"number":1}`) - }) - - issue, _, err := client.Issues.Create("o", "r", input) - if err != nil { - t.Errorf("Issues.Create returned error: %v", err) - } - - want := &Issue{Number: Int(1)} - if !reflect.DeepEqual(issue, want) { - t.Errorf("Issues.Create returned %+v, want %+v", issue, want) - } -} - -func TestIssuesService_Create_invalidOwner(t *testing.T) { - _, _, err := client.Issues.Create("%", "r", nil) - testURLParseError(t, err) -} - -func TestIssuesService_Edit(t *testing.T) { - setup() - defer teardown() - - input := &IssueRequest{Title: String("t")} - - mux.HandleFunc("/repos/o/r/issues/1", func(w http.ResponseWriter, r *http.Request) { - v := new(IssueRequest) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "PATCH") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"number":1}`) - }) - - issue, _, err := client.Issues.Edit("o", "r", 1, input) - if err != nil { - t.Errorf("Issues.Edit returned error: %v", err) - } - - want := &Issue{Number: Int(1)} - if !reflect.DeepEqual(issue, want) { - t.Errorf("Issues.Edit returned %+v, want %+v", issue, want) - } -} - -func TestIssuesService_Edit_invalidOwner(t *testing.T) { - _, _, err := client.Issues.Edit("%", "r", 1, nil) - testURLParseError(t, err) -} diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/licenses_test.go b/Godeps/_workspace/src/github.com/google/go-github/github/licenses_test.go deleted file mode 100644 index dfecfebbb..000000000 --- a/Godeps/_workspace/src/github.com/google/go-github/github/licenses_test.go +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestLicensesService_List(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/licenses", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeLicensesPreview) - fmt.Fprint(w, `[{"key":"mit","name":"MIT","url":"https://api.github.com/licenses/mit"}]`) - }) - - licenses, _, err := client.Licenses.List() - if err != nil { - t.Errorf("Licenses.List returned error: %v", err) - } - - want := []License{{ - Key: String("mit"), - Name: String("MIT"), - URL: String("https://api.github.com/licenses/mit"), - }} - if !reflect.DeepEqual(licenses, want) { - t.Errorf("Licenses.List returned %+v, want %+v", licenses, want) - } -} - -func TestLicensesService_Get(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/licenses/mit", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeLicensesPreview) - fmt.Fprint(w, `{"key":"mit","name":"MIT"}`) - }) - - license, _, err := client.Licenses.Get("mit") - if err != nil { - t.Errorf("Licenses.Get returned error: %v", err) - } - - want := &License{Key: String("mit"), Name: String("MIT")} - if !reflect.DeepEqual(license, want) { - t.Errorf("Licenses.Get returned %+v, want %+v", license, want) - } -} - -func TestLicensesService_Get_invalidTemplate(t *testing.T) { - _, _, err := client.Licenses.Get("%") - testURLParseError(t, err) -} diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/misc_test.go b/Godeps/_workspace/src/github.com/google/go-github/github/misc_test.go deleted file mode 100644 index 8ca58d251..000000000 --- a/Godeps/_workspace/src/github.com/google/go-github/github/misc_test.go +++ /dev/null @@ -1,170 +0,0 @@ -// Copyright 2014 The go-github 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 github - -import ( - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestMarkdown(t *testing.T) { - setup() - defer teardown() - - input := &markdownRequest{ - Text: String("# text #"), - Mode: String("gfm"), - Context: String("google/go-github"), - } - mux.HandleFunc("/markdown", func(w http.ResponseWriter, r *http.Request) { - v := new(markdownRequest) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "POST") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - fmt.Fprint(w, `

text

`) - }) - - md, _, err := client.Markdown("# text #", &MarkdownOptions{ - Mode: "gfm", - Context: "google/go-github", - }) - if err != nil { - t.Errorf("Markdown returned error: %v", err) - } - - if want := "

text

"; want != md { - t.Errorf("Markdown returned %+v, want %+v", md, want) - } -} - -func TestListEmojis(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/emojis", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"+1": "+1.png"}`) - }) - - emoji, _, err := client.ListEmojis() - if err != nil { - t.Errorf("ListEmojis returned error: %v", err) - } - - want := map[string]string{"+1": "+1.png"} - if !reflect.DeepEqual(want, emoji) { - t.Errorf("ListEmojis returned %+v, want %+v", emoji, want) - } -} - -func TestAPIMeta(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/meta", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"hooks":["h"], "git":["g"], "pages":["p"], "verifiable_password_authentication": true}`) - }) - - meta, _, err := client.APIMeta() - if err != nil { - t.Errorf("APIMeta returned error: %v", err) - } - - want := &APIMeta{ - Hooks: []string{"h"}, - Git: []string{"g"}, - Pages: []string{"p"}, - VerifiablePasswordAuthentication: Bool(true), - } - if !reflect.DeepEqual(want, meta) { - t.Errorf("APIMeta returned %+v, want %+v", meta, want) - } -} - -func TestOctocat(t *testing.T) { - setup() - defer teardown() - - input := "input" - output := "sample text" - - mux.HandleFunc("/octocat", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"s": input}) - w.Header().Set("Content-Type", "application/octocat-stream") - fmt.Fprint(w, output) - }) - - got, _, err := client.Octocat(input) - if err != nil { - t.Errorf("Octocat returned error: %v", err) - } - - if want := output; got != want { - t.Errorf("Octocat returned %+v, want %+v", got, want) - } -} - -func TestZen(t *testing.T) { - setup() - defer teardown() - - output := "sample text" - - mux.HandleFunc("/zen", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - w.Header().Set("Content-Type", "text/plain;charset=utf-8") - fmt.Fprint(w, output) - }) - - got, _, err := client.Zen() - if err != nil { - t.Errorf("Zen returned error: %v", err) - } - - if want := output; got != want { - t.Errorf("Zen returned %+v, want %+v", got, want) - } -} - -func TestRepositoriesService_ListServiceHooks(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/hooks", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `[{ - "name":"n", - "events":["e"], - "supported_events":["s"], - "schema":[ - ["a", "b"] - ] - }]`) - }) - - hooks, _, err := client.Repositories.ListServiceHooks() - if err != nil { - t.Errorf("Repositories.ListHooks returned error: %v", err) - } - - want := []ServiceHook{{ - Name: String("n"), - Events: []string{"e"}, - SupportedEvents: []string{"s"}, - Schema: [][]string{{"a", "b"}}, - }} - if !reflect.DeepEqual(hooks, want) { - t.Errorf("Repositories.ListServiceHooks returned %+v, want %+v", hooks, want) - } -} diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/orgs_hooks_test.go b/Godeps/_workspace/src/github.com/google/go-github/github/orgs_hooks_test.go deleted file mode 100644 index 1ebc07d5a..000000000 --- a/Godeps/_workspace/src/github.com/google/go-github/github/orgs_hooks_test.go +++ /dev/null @@ -1,134 +0,0 @@ -// Copyright 2015 The go-github 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 github - -import ( - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestOrganizationsService_ListHooks(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/orgs/o/hooks", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"page": "2"}) - fmt.Fprint(w, `[{"id":1}, {"id":2}]`) - }) - - opt := &ListOptions{Page: 2} - - hooks, _, err := client.Organizations.ListHooks("o", opt) - if err != nil { - t.Errorf("Organizations.ListHooks returned error: %v", err) - } - - want := []Hook{{ID: Int(1)}, {ID: Int(2)}} - if !reflect.DeepEqual(hooks, want) { - t.Errorf("Organizations.ListHooks returned %+v, want %+v", hooks, want) - } -} - -func TestOrganizationsService_ListHooks_invalidOrg(t *testing.T) { - _, _, err := client.Organizations.ListHooks("%", nil) - testURLParseError(t, err) -} - -func TestOrganizationsService_GetHook(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/orgs/o/hooks/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"id":1}`) - }) - - hook, _, err := client.Organizations.GetHook("o", 1) - if err != nil { - t.Errorf("Organizations.GetHook returned error: %v", err) - } - - want := &Hook{ID: Int(1)} - if !reflect.DeepEqual(hook, want) { - t.Errorf("Organizations.GetHook returned %+v, want %+v", hook, want) - } -} - -func TestOrganizationsService_GetHook_invalidOrg(t *testing.T) { - _, _, err := client.Organizations.GetHook("%", 1) - testURLParseError(t, err) -} - -func TestOrganizationsService_EditHook(t *testing.T) { - setup() - defer teardown() - - input := &Hook{Name: String("t")} - - mux.HandleFunc("/orgs/o/hooks/1", func(w http.ResponseWriter, r *http.Request) { - v := new(Hook) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "PATCH") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"id":1}`) - }) - - hook, _, err := client.Organizations.EditHook("o", 1, input) - if err != nil { - t.Errorf("Organizations.EditHook returned error: %v", err) - } - - want := &Hook{ID: Int(1)} - if !reflect.DeepEqual(hook, want) { - t.Errorf("Organizations.EditHook returned %+v, want %+v", hook, want) - } -} - -func TestOrganizationsService_EditHook_invalidOrg(t *testing.T) { - _, _, err := client.Organizations.EditHook("%", 1, nil) - testURLParseError(t, err) -} - -func TestOrganizationsService_PingHook(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/orgs/o/hooks/1/pings", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "POST") - }) - - _, err := client.Organizations.PingHook("o", 1) - if err != nil { - t.Errorf("Organizations.PingHook returned error: %v", err) - } -} - -func TestOrganizationsService_DeleteHook(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/orgs/o/hooks/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - }) - - _, err := client.Organizations.DeleteHook("o", 1) - if err != nil { - t.Errorf("Organizations.DeleteHook returned error: %v", err) - } -} - -func TestOrganizationsService_DeleteHook_invalidOrg(t *testing.T) { - _, err := client.Organizations.DeleteHook("%", 1) - testURLParseError(t, err) -} diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/orgs_members_test.go b/Godeps/_workspace/src/github.com/google/go-github/github/orgs_members_test.go deleted file mode 100644 index 973e3aa8b..000000000 --- a/Godeps/_workspace/src/github.com/google/go-github/github/orgs_members_test.go +++ /dev/null @@ -1,356 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestOrganizationsService_ListMembers(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/orgs/o/members", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeOrgPermissionPreview) - testFormValues(t, r, values{ - "filter": "2fa_disabled", - "role": "admin", - "page": "2", - }) - fmt.Fprint(w, `[{"id":1}]`) - }) - - opt := &ListMembersOptions{ - PublicOnly: false, - Filter: "2fa_disabled", - Role: "admin", - ListOptions: ListOptions{Page: 2}, - } - members, _, err := client.Organizations.ListMembers("o", opt) - if err != nil { - t.Errorf("Organizations.ListMembers returned error: %v", err) - } - - want := []User{{ID: Int(1)}} - if !reflect.DeepEqual(members, want) { - t.Errorf("Organizations.ListMembers returned %+v, want %+v", members, want) - } -} - -func TestOrganizationsService_ListMembers_invalidOrg(t *testing.T) { - _, _, err := client.Organizations.ListMembers("%", nil) - testURLParseError(t, err) -} - -func TestOrganizationsService_ListMembers_public(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/orgs/o/public_members", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `[{"id":1}]`) - }) - - opt := &ListMembersOptions{PublicOnly: true} - members, _, err := client.Organizations.ListMembers("o", opt) - if err != nil { - t.Errorf("Organizations.ListMembers returned error: %v", err) - } - - want := []User{{ID: Int(1)}} - if !reflect.DeepEqual(members, want) { - t.Errorf("Organizations.ListMembers returned %+v, want %+v", members, want) - } -} - -func TestOrganizationsService_IsMember(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/orgs/o/members/u", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - w.WriteHeader(http.StatusNoContent) - }) - - member, _, err := client.Organizations.IsMember("o", "u") - if err != nil { - t.Errorf("Organizations.IsMember returned error: %v", err) - } - if want := true; member != want { - t.Errorf("Organizations.IsMember returned %+v, want %+v", member, want) - } -} - -// ensure that a 404 response is interpreted as "false" and not an error -func TestOrganizationsService_IsMember_notMember(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/orgs/o/members/u", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - w.WriteHeader(http.StatusNotFound) - }) - - member, _, err := client.Organizations.IsMember("o", "u") - if err != nil { - t.Errorf("Organizations.IsMember returned error: %+v", err) - } - if want := false; member != want { - t.Errorf("Organizations.IsMember returned %+v, want %+v", member, want) - } -} - -// ensure that a 400 response is interpreted as an actual error, and not simply -// as "false" like the above case of a 404 -func TestOrganizationsService_IsMember_error(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/orgs/o/members/u", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - http.Error(w, "BadRequest", http.StatusBadRequest) - }) - - member, _, err := client.Organizations.IsMember("o", "u") - if err == nil { - t.Errorf("Expected HTTP 400 response") - } - if want := false; member != want { - t.Errorf("Organizations.IsMember returned %+v, want %+v", member, want) - } -} - -func TestOrganizationsService_IsMember_invalidOrg(t *testing.T) { - _, _, err := client.Organizations.IsMember("%", "u") - testURLParseError(t, err) -} - -func TestOrganizationsService_IsPublicMember(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/orgs/o/public_members/u", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - w.WriteHeader(http.StatusNoContent) - }) - - member, _, err := client.Organizations.IsPublicMember("o", "u") - if err != nil { - t.Errorf("Organizations.IsPublicMember returned error: %v", err) - } - if want := true; member != want { - t.Errorf("Organizations.IsPublicMember returned %+v, want %+v", member, want) - } -} - -// ensure that a 404 response is interpreted as "false" and not an error -func TestOrganizationsService_IsPublicMember_notMember(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/orgs/o/public_members/u", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - w.WriteHeader(http.StatusNotFound) - }) - - member, _, err := client.Organizations.IsPublicMember("o", "u") - if err != nil { - t.Errorf("Organizations.IsPublicMember returned error: %v", err) - } - if want := false; member != want { - t.Errorf("Organizations.IsPublicMember returned %+v, want %+v", member, want) - } -} - -// ensure that a 400 response is interpreted as an actual error, and not simply -// as "false" like the above case of a 404 -func TestOrganizationsService_IsPublicMember_error(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/orgs/o/public_members/u", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - http.Error(w, "BadRequest", http.StatusBadRequest) - }) - - member, _, err := client.Organizations.IsPublicMember("o", "u") - if err == nil { - t.Errorf("Expected HTTP 400 response") - } - if want := false; member != want { - t.Errorf("Organizations.IsPublicMember returned %+v, want %+v", member, want) - } -} - -func TestOrganizationsService_IsPublicMember_invalidOrg(t *testing.T) { - _, _, err := client.Organizations.IsPublicMember("%", "u") - testURLParseError(t, err) -} - -func TestOrganizationsService_RemoveMember(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/orgs/o/members/u", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - }) - - _, err := client.Organizations.RemoveMember("o", "u") - if err != nil { - t.Errorf("Organizations.RemoveMember returned error: %v", err) - } -} - -func TestOrganizationsService_RemoveMember_invalidOrg(t *testing.T) { - _, err := client.Organizations.RemoveMember("%", "u") - testURLParseError(t, err) -} - -func TestOrganizationsService_ListOrgMemberships(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/user/memberships/orgs", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "state": "active", - "page": "2", - }) - fmt.Fprint(w, `[{"url":"u"}]`) - }) - - opt := &ListOrgMembershipsOptions{ - State: "active", - ListOptions: ListOptions{Page: 2}, - } - memberships, _, err := client.Organizations.ListOrgMemberships(opt) - if err != nil { - t.Errorf("Organizations.ListOrgMemberships returned error: %v", err) - } - - want := []Membership{{URL: String("u")}} - if !reflect.DeepEqual(memberships, want) { - t.Errorf("Organizations.ListOrgMemberships returned %+v, want %+v", memberships, want) - } -} - -func TestOrganizationsService_GetOrgMembership_AuthenticatedUser(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/user/memberships/orgs/o", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"url":"u"}`) - }) - - membership, _, err := client.Organizations.GetOrgMembership("", "o") - if err != nil { - t.Errorf("Organizations.GetOrgMembership returned error: %v", err) - } - - want := &Membership{URL: String("u")} - if !reflect.DeepEqual(membership, want) { - t.Errorf("Organizations.GetOrgMembership returned %+v, want %+v", membership, want) - } -} - -func TestOrganizationsService_GetOrgMembership_SpecifiedUser(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/orgs/o/memberships/u", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"url":"u"}`) - }) - - membership, _, err := client.Organizations.GetOrgMembership("u", "o") - if err != nil { - t.Errorf("Organizations.GetOrgMembership returned error: %v", err) - } - - want := &Membership{URL: String("u")} - if !reflect.DeepEqual(membership, want) { - t.Errorf("Organizations.GetOrgMembership returned %+v, want %+v", membership, want) - } -} - -func TestOrganizationsService_EditOrgMembership_AuthenticatedUser(t *testing.T) { - setup() - defer teardown() - - input := &Membership{State: String("active")} - - mux.HandleFunc("/user/memberships/orgs/o", func(w http.ResponseWriter, r *http.Request) { - v := new(Membership) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "PATCH") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"url":"u"}`) - }) - - membership, _, err := client.Organizations.EditOrgMembership("", "o", input) - if err != nil { - t.Errorf("Organizations.EditOrgMembership returned error: %v", err) - } - - want := &Membership{URL: String("u")} - if !reflect.DeepEqual(membership, want) { - t.Errorf("Organizations.EditOrgMembership returned %+v, want %+v", membership, want) - } -} - -func TestOrganizationsService_EditOrgMembership_SpecifiedUser(t *testing.T) { - setup() - defer teardown() - - input := &Membership{State: String("active")} - - mux.HandleFunc("/orgs/o/memberships/u", func(w http.ResponseWriter, r *http.Request) { - v := new(Membership) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "PATCH") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"url":"u"}`) - }) - - membership, _, err := client.Organizations.EditOrgMembership("u", "o", input) - if err != nil { - t.Errorf("Organizations.EditOrgMembership returned error: %v", err) - } - - want := &Membership{URL: String("u")} - if !reflect.DeepEqual(membership, want) { - t.Errorf("Organizations.EditOrgMembership returned %+v, want %+v", membership, want) - } -} - -func TestOrganizationsService_RemoveOrgMembership(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/orgs/o/memberships/u", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - w.WriteHeader(http.StatusNoContent) - }) - - _, err := client.Organizations.RemoveOrgMembership("u", "o") - if err != nil { - t.Errorf("Organizations.RemoveOrgMembership returned error: %v", err) - } -} diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/orgs_teams_test.go b/Godeps/_workspace/src/github.com/google/go-github/github/orgs_teams_test.go deleted file mode 100644 index a258137ad..000000000 --- a/Godeps/_workspace/src/github.com/google/go-github/github/orgs_teams_test.go +++ /dev/null @@ -1,506 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestOrganizationsService_ListTeams(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/orgs/o/teams", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"page": "2"}) - fmt.Fprint(w, `[{"id":1}]`) - }) - - opt := &ListOptions{Page: 2} - teams, _, err := client.Organizations.ListTeams("o", opt) - if err != nil { - t.Errorf("Organizations.ListTeams returned error: %v", err) - } - - want := []Team{{ID: Int(1)}} - if !reflect.DeepEqual(teams, want) { - t.Errorf("Organizations.ListTeams returned %+v, want %+v", teams, want) - } -} - -func TestOrganizationsService_ListTeams_invalidOrg(t *testing.T) { - _, _, err := client.Organizations.ListTeams("%", nil) - testURLParseError(t, err) -} - -func TestOrganizationsService_GetTeam(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/teams/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"id":1, "name":"n", "url":"u", "slug": "s", "permission":"p"}`) - }) - - team, _, err := client.Organizations.GetTeam(1) - if err != nil { - t.Errorf("Organizations.GetTeam returned error: %v", err) - } - - want := &Team{ID: Int(1), Name: String("n"), URL: String("u"), Slug: String("s"), Permission: String("p")} - if !reflect.DeepEqual(team, want) { - t.Errorf("Organizations.GetTeam returned %+v, want %+v", team, want) - } -} - -func TestOrganizationsService_CreateTeam(t *testing.T) { - setup() - defer teardown() - - input := &Team{Name: String("n"), Privacy: String("closed")} - - mux.HandleFunc("/orgs/o/teams", func(w http.ResponseWriter, r *http.Request) { - v := new(Team) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "POST") - testHeader(t, r, "Accept", mediaTypeOrgPermissionPreview) - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"id":1}`) - }) - - team, _, err := client.Organizations.CreateTeam("o", input) - if err != nil { - t.Errorf("Organizations.CreateTeam returned error: %v", err) - } - - want := &Team{ID: Int(1)} - if !reflect.DeepEqual(team, want) { - t.Errorf("Organizations.CreateTeam returned %+v, want %+v", team, want) - } -} - -func TestOrganizationsService_CreateTeam_invalidOrg(t *testing.T) { - _, _, err := client.Organizations.CreateTeam("%", nil) - testURLParseError(t, err) -} - -func TestOrganizationsService_EditTeam(t *testing.T) { - setup() - defer teardown() - - input := &Team{Name: String("n"), Privacy: String("closed")} - - mux.HandleFunc("/teams/1", func(w http.ResponseWriter, r *http.Request) { - v := new(Team) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "PATCH") - testHeader(t, r, "Accept", mediaTypeOrgPermissionPreview) - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"id":1}`) - }) - - team, _, err := client.Organizations.EditTeam(1, input) - if err != nil { - t.Errorf("Organizations.EditTeam returned error: %v", err) - } - - want := &Team{ID: Int(1)} - if !reflect.DeepEqual(team, want) { - t.Errorf("Organizations.EditTeam returned %+v, want %+v", team, want) - } -} - -func TestOrganizationsService_DeleteTeam(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/teams/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - }) - - _, err := client.Organizations.DeleteTeam(1) - if err != nil { - t.Errorf("Organizations.DeleteTeam returned error: %v", err) - } -} - -func TestOrganizationsService_ListTeamMembers(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/teams/1/members", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeOrgPermissionPreview) - testFormValues(t, r, values{"role": "member", "page": "2"}) - fmt.Fprint(w, `[{"id":1}]`) - }) - - opt := &OrganizationListTeamMembersOptions{Role: "member", ListOptions: ListOptions{Page: 2}} - members, _, err := client.Organizations.ListTeamMembers(1, opt) - if err != nil { - t.Errorf("Organizations.ListTeamMembers returned error: %v", err) - } - - want := []User{{ID: Int(1)}} - if !reflect.DeepEqual(members, want) { - t.Errorf("Organizations.ListTeamMembers returned %+v, want %+v", members, want) - } -} - -func TestOrganizationsService_IsTeamMember_true(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/teams/1/members/u", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - }) - - member, _, err := client.Organizations.IsTeamMember(1, "u") - if err != nil { - t.Errorf("Organizations.IsTeamMember returned error: %v", err) - } - if want := true; member != want { - t.Errorf("Organizations.IsTeamMember returned %+v, want %+v", member, want) - } -} - -// ensure that a 404 response is interpreted as "false" and not an error -func TestOrganizationsService_IsTeamMember_false(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/teams/1/members/u", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - w.WriteHeader(http.StatusNotFound) - }) - - member, _, err := client.Organizations.IsTeamMember(1, "u") - if err != nil { - t.Errorf("Organizations.IsTeamMember returned error: %+v", err) - } - if want := false; member != want { - t.Errorf("Organizations.IsTeamMember returned %+v, want %+v", member, want) - } -} - -// ensure that a 400 response is interpreted as an actual error, and not simply -// as "false" like the above case of a 404 -func TestOrganizationsService_IsTeamMember_error(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/teams/1/members/u", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - http.Error(w, "BadRequest", http.StatusBadRequest) - }) - - member, _, err := client.Organizations.IsTeamMember(1, "u") - if err == nil { - t.Errorf("Expected HTTP 400 response") - } - if want := false; member != want { - t.Errorf("Organizations.IsTeamMember returned %+v, want %+v", member, want) - } -} - -func TestOrganizationsService_IsTeamMember_invalidUser(t *testing.T) { - _, _, err := client.Organizations.IsTeamMember(1, "%") - testURLParseError(t, err) -} - -func TestOrganizationsService_PublicizeMembership(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/orgs/o/public_members/u", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "PUT") - w.WriteHeader(http.StatusNoContent) - }) - - _, err := client.Organizations.PublicizeMembership("o", "u") - if err != nil { - t.Errorf("Organizations.PublicizeMembership returned error: %v", err) - } -} - -func TestOrganizationsService_PublicizeMembership_invalidOrg(t *testing.T) { - _, err := client.Organizations.PublicizeMembership("%", "u") - testURLParseError(t, err) -} - -func TestOrganizationsService_ConcealMembership(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/orgs/o/public_members/u", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - w.WriteHeader(http.StatusNoContent) - }) - - _, err := client.Organizations.ConcealMembership("o", "u") - if err != nil { - t.Errorf("Organizations.ConcealMembership returned error: %v", err) - } -} - -func TestOrganizationsService_ConcealMembership_invalidOrg(t *testing.T) { - _, err := client.Organizations.ConcealMembership("%", "u") - testURLParseError(t, err) -} - -func TestOrganizationsService_ListTeamRepos(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/teams/1/repos", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"page": "2"}) - fmt.Fprint(w, `[{"id":1}]`) - }) - - opt := &ListOptions{Page: 2} - members, _, err := client.Organizations.ListTeamRepos(1, opt) - if err != nil { - t.Errorf("Organizations.ListTeamRepos returned error: %v", err) - } - - want := []Repository{{ID: Int(1)}} - if !reflect.DeepEqual(members, want) { - t.Errorf("Organizations.ListTeamRepos returned %+v, want %+v", members, want) - } -} - -func TestOrganizationsService_IsTeamRepo_true(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/teams/1/repos/o/r", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeOrgPermissionRepoPreview) - fmt.Fprint(w, `{"id":1}`) - }) - - repo, _, err := client.Organizations.IsTeamRepo(1, "o", "r") - if err != nil { - t.Errorf("Organizations.IsTeamRepo returned error: %v", err) - } - - want := &Repository{ID: Int(1)} - if !reflect.DeepEqual(repo, want) { - t.Errorf("Organizations.IsTeamRepo returned %+v, want %+v", repo, want) - } -} - -func TestOrganizationsService_IsTeamRepo_false(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/teams/1/repos/o/r", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - w.WriteHeader(http.StatusNotFound) - }) - - repo, resp, err := client.Organizations.IsTeamRepo(1, "o", "r") - if err == nil { - t.Errorf("Expected HTTP 404 response") - } - if got, want := resp.Response.StatusCode, http.StatusNotFound; got != want { - t.Errorf("Organizations.IsTeamRepo returned status %d, want %d", got, want) - } - if repo != nil { - t.Errorf("Organizations.IsTeamRepo returned %+v, want nil", repo) - } -} - -func TestOrganizationsService_IsTeamRepo_error(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/teams/1/repos/o/r", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - http.Error(w, "BadRequest", http.StatusBadRequest) - }) - - repo, resp, err := client.Organizations.IsTeamRepo(1, "o", "r") - if err == nil { - t.Errorf("Expected HTTP 400 response") - } - if got, want := resp.Response.StatusCode, http.StatusBadRequest; got != want { - t.Errorf("Organizations.IsTeamRepo returned status %d, want %d", got, want) - } - if repo != nil { - t.Errorf("Organizations.IsTeamRepo returned %+v, want nil", repo) - } -} - -func TestOrganizationsService_IsTeamRepo_invalidOwner(t *testing.T) { - _, _, err := client.Organizations.IsTeamRepo(1, "%", "r") - testURLParseError(t, err) -} - -func TestOrganizationsService_AddTeamRepo(t *testing.T) { - setup() - defer teardown() - - opt := &OrganizationAddTeamRepoOptions{Permission: "admin"} - - mux.HandleFunc("/teams/1/repos/o/r", func(w http.ResponseWriter, r *http.Request) { - v := new(OrganizationAddTeamRepoOptions) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "PUT") - testHeader(t, r, "Accept", mediaTypeOrgPermissionPreview) - if !reflect.DeepEqual(v, opt) { - t.Errorf("Request body = %+v, want %+v", v, opt) - } - - w.WriteHeader(http.StatusNoContent) - }) - - _, err := client.Organizations.AddTeamRepo(1, "o", "r", opt) - if err != nil { - t.Errorf("Organizations.AddTeamRepo returned error: %v", err) - } -} - -func TestOrganizationsService_AddTeamRepo_noAccess(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/teams/1/repos/o/r", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "PUT") - w.WriteHeader(422) - }) - - _, err := client.Organizations.AddTeamRepo(1, "o", "r", nil) - if err == nil { - t.Errorf("Expcted error to be returned") - } -} - -func TestOrganizationsService_AddTeamRepo_invalidOwner(t *testing.T) { - _, err := client.Organizations.AddTeamRepo(1, "%", "r", nil) - testURLParseError(t, err) -} - -func TestOrganizationsService_RemoveTeamRepo(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/teams/1/repos/o/r", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - w.WriteHeader(http.StatusNoContent) - }) - - _, err := client.Organizations.RemoveTeamRepo(1, "o", "r") - if err != nil { - t.Errorf("Organizations.RemoveTeamRepo returned error: %v", err) - } -} - -func TestOrganizationsService_RemoveTeamRepo_invalidOwner(t *testing.T) { - _, err := client.Organizations.RemoveTeamRepo(1, "%", "r") - testURLParseError(t, err) -} - -func TestOrganizationsService_GetTeamMembership(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/teams/1/memberships/u", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"url":"u", "state":"active"}`) - }) - - membership, _, err := client.Organizations.GetTeamMembership(1, "u") - if err != nil { - t.Errorf("Organizations.GetTeamMembership returned error: %v", err) - } - - want := &Membership{URL: String("u"), State: String("active")} - if !reflect.DeepEqual(membership, want) { - t.Errorf("Organizations.GetTeamMembership returned %+v, want %+v", membership, want) - } -} - -func TestOrganizationsService_AddTeamMembership(t *testing.T) { - setup() - defer teardown() - - opt := &OrganizationAddTeamMembershipOptions{Role: "maintainer"} - - mux.HandleFunc("/teams/1/memberships/u", func(w http.ResponseWriter, r *http.Request) { - v := new(OrganizationAddTeamMembershipOptions) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "PUT") - testHeader(t, r, "Accept", mediaTypeOrgPermissionPreview) - if !reflect.DeepEqual(v, opt) { - t.Errorf("Request body = %+v, want %+v", v, opt) - } - - fmt.Fprint(w, `{"url":"u", "state":"pending"}`) - }) - - membership, _, err := client.Organizations.AddTeamMembership(1, "u", opt) - if err != nil { - t.Errorf("Organizations.AddTeamMembership returned error: %v", err) - } - - want := &Membership{URL: String("u"), State: String("pending")} - if !reflect.DeepEqual(membership, want) { - t.Errorf("Organizations.AddTeamMembership returned %+v, want %+v", membership, want) - } -} - -func TestOrganizationsService_RemoveTeamMembership(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/teams/1/memberships/u", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - w.WriteHeader(http.StatusNoContent) - }) - - _, err := client.Organizations.RemoveTeamMembership(1, "u") - if err != nil { - t.Errorf("Organizations.RemoveTeamMembership returned error: %v", err) - } -} - -func TestOrganizationsService_ListUserTeams(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/user/teams", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"page": "1"}) - fmt.Fprint(w, `[{"id":1}]`) - }) - - opt := &ListOptions{Page: 1} - teams, _, err := client.Organizations.ListUserTeams(opt) - if err != nil { - t.Errorf("Organizations.ListUserTeams returned error: %v", err) - } - - want := []Team{{ID: Int(1)}} - if !reflect.DeepEqual(teams, want) { - t.Errorf("Organizations.ListUserTeams returned %+v, want %+v", teams, want) - } -} diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/orgs_test.go b/Godeps/_workspace/src/github.com/google/go-github/github/orgs_test.go deleted file mode 100644 index 84ebc5468..000000000 --- a/Godeps/_workspace/src/github.com/google/go-github/github/orgs_test.go +++ /dev/null @@ -1,120 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestOrganizationsService_List_authenticatedUser(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/user/orgs", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `[{"id":1},{"id":2}]`) - }) - - orgs, _, err := client.Organizations.List("", nil) - if err != nil { - t.Errorf("Organizations.List returned error: %v", err) - } - - want := []Organization{{ID: Int(1)}, {ID: Int(2)}} - if !reflect.DeepEqual(orgs, want) { - t.Errorf("Organizations.List returned %+v, want %+v", orgs, want) - } -} - -func TestOrganizationsService_List_specifiedUser(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/users/u/orgs", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"page": "2"}) - fmt.Fprint(w, `[{"id":1},{"id":2}]`) - }) - - opt := &ListOptions{Page: 2} - orgs, _, err := client.Organizations.List("u", opt) - if err != nil { - t.Errorf("Organizations.List returned error: %v", err) - } - - want := []Organization{{ID: Int(1)}, {ID: Int(2)}} - if !reflect.DeepEqual(orgs, want) { - t.Errorf("Organizations.List returned %+v, want %+v", orgs, want) - } -} - -func TestOrganizationsService_List_invalidUser(t *testing.T) { - _, _, err := client.Organizations.List("%", nil) - testURLParseError(t, err) -} - -func TestOrganizationsService_Get(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/orgs/o", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"id":1, "login":"l", "url":"u", "avatar_url": "a", "location":"l"}`) - }) - - org, _, err := client.Organizations.Get("o") - if err != nil { - t.Errorf("Organizations.Get returned error: %v", err) - } - - want := &Organization{ID: Int(1), Login: String("l"), URL: String("u"), AvatarURL: String("a"), Location: String("l")} - if !reflect.DeepEqual(org, want) { - t.Errorf("Organizations.Get returned %+v, want %+v", org, want) - } -} - -func TestOrganizationsService_Get_invalidOrg(t *testing.T) { - _, _, err := client.Organizations.Get("%") - testURLParseError(t, err) -} - -func TestOrganizationsService_Edit(t *testing.T) { - setup() - defer teardown() - - input := &Organization{Login: String("l")} - - mux.HandleFunc("/orgs/o", func(w http.ResponseWriter, r *http.Request) { - v := new(Organization) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "PATCH") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"id":1}`) - }) - - org, _, err := client.Organizations.Edit("o", input) - if err != nil { - t.Errorf("Organizations.Edit returned error: %v", err) - } - - want := &Organization{ID: Int(1)} - if !reflect.DeepEqual(org, want) { - t.Errorf("Organizations.Edit returned %+v, want %+v", org, want) - } -} - -func TestOrganizationsService_Edit_invalidOrg(t *testing.T) { - _, _, err := client.Organizations.Edit("%", nil) - testURLParseError(t, err) -} diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/pulls_comments.go b/Godeps/_workspace/src/github.com/google/go-github/github/pulls_comments.go index 35c7241b9..f165d5fc6 100644 --- a/Godeps/_workspace/src/github.com/google/go-github/github/pulls_comments.go +++ b/Godeps/_workspace/src/github.com/google/go-github/github/pulls_comments.go @@ -12,14 +12,17 @@ import ( // PullRequestComment represents a comment left on a pull request. type PullRequestComment struct { - ID *int `json:"id,omitempty"` - Body *string `json:"body,omitempty"` - Path *string `json:"path,omitempty"` - Position *int `json:"position,omitempty"` - CommitID *string `json:"commit_id,omitempty"` - User *User `json:"user,omitempty"` - CreatedAt *time.Time `json:"created_at,omitempty"` - UpdatedAt *time.Time `json:"updated_at,omitempty"` + ID *int `json:"id,omitempty"` + Body *string `json:"body,omitempty"` + Path *string `json:"path,omitempty"` + DiffHunk *string `json:"diff_hunk,omitempty"` + Position *int `json:"position,omitempty"` + OriginalPosition *int `json:"original_position,omitempty"` + CommitID *string `json:"commit_id,omitempty"` + OriginalCommitID *string `json:"original_commit_id,omitempty"` + User *User `json:"user,omitempty"` + CreatedAt *time.Time `json:"created_at,omitempty"` + UpdatedAt *time.Time `json:"updated_at,omitempty"` } func (p PullRequestComment) String() string { diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/pulls_comments_test.go b/Godeps/_workspace/src/github.com/google/go-github/github/pulls_comments_test.go deleted file mode 100644 index 7885ab158..000000000 --- a/Godeps/_workspace/src/github.com/google/go-github/github/pulls_comments_test.go +++ /dev/null @@ -1,189 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" - "time" -) - -func TestPullRequestsService_ListComments_allPulls(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/pulls/comments", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "sort": "updated", - "direction": "desc", - "since": "2002-02-10T15:30:00Z", - "page": "2", - }) - fmt.Fprint(w, `[{"id":1}]`) - }) - - opt := &PullRequestListCommentsOptions{ - Sort: "updated", - Direction: "desc", - Since: time.Date(2002, time.February, 10, 15, 30, 0, 0, time.UTC), - ListOptions: ListOptions{Page: 2}, - } - pulls, _, err := client.PullRequests.ListComments("o", "r", 0, opt) - - if err != nil { - t.Errorf("PullRequests.ListComments returned error: %v", err) - } - - want := []PullRequestComment{{ID: Int(1)}} - if !reflect.DeepEqual(pulls, want) { - t.Errorf("PullRequests.ListComments returned %+v, want %+v", pulls, want) - } -} - -func TestPullRequestsService_ListComments_specificPull(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/pulls/1/comments", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `[{"id":1}]`) - }) - - pulls, _, err := client.PullRequests.ListComments("o", "r", 1, nil) - - if err != nil { - t.Errorf("PullRequests.ListComments returned error: %v", err) - } - - want := []PullRequestComment{{ID: Int(1)}} - if !reflect.DeepEqual(pulls, want) { - t.Errorf("PullRequests.ListComments returned %+v, want %+v", pulls, want) - } -} - -func TestPullRequestsService_ListComments_invalidOwner(t *testing.T) { - _, _, err := client.PullRequests.ListComments("%", "r", 1, nil) - testURLParseError(t, err) -} - -func TestPullRequestsService_GetComment(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/pulls/comments/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"id":1}`) - }) - - comment, _, err := client.PullRequests.GetComment("o", "r", 1) - - if err != nil { - t.Errorf("PullRequests.GetComment returned error: %v", err) - } - - want := &PullRequestComment{ID: Int(1)} - if !reflect.DeepEqual(comment, want) { - t.Errorf("PullRequests.GetComment returned %+v, want %+v", comment, want) - } -} - -func TestPullRequestsService_GetComment_invalidOwner(t *testing.T) { - _, _, err := client.PullRequests.GetComment("%", "r", 1) - testURLParseError(t, err) -} - -func TestPullRequestsService_CreateComment(t *testing.T) { - setup() - defer teardown() - - input := &PullRequestComment{Body: String("b")} - - mux.HandleFunc("/repos/o/r/pulls/1/comments", func(w http.ResponseWriter, r *http.Request) { - v := new(PullRequestComment) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "POST") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"id":1}`) - }) - - comment, _, err := client.PullRequests.CreateComment("o", "r", 1, input) - - if err != nil { - t.Errorf("PullRequests.CreateComment returned error: %v", err) - } - - want := &PullRequestComment{ID: Int(1)} - if !reflect.DeepEqual(comment, want) { - t.Errorf("PullRequests.CreateComment returned %+v, want %+v", comment, want) - } -} - -func TestPullRequestsService_CreateComment_invalidOwner(t *testing.T) { - _, _, err := client.PullRequests.CreateComment("%", "r", 1, nil) - testURLParseError(t, err) -} - -func TestPullRequestsService_EditComment(t *testing.T) { - setup() - defer teardown() - - input := &PullRequestComment{Body: String("b")} - - mux.HandleFunc("/repos/o/r/pulls/comments/1", func(w http.ResponseWriter, r *http.Request) { - v := new(PullRequestComment) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "PATCH") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"id":1}`) - }) - - comment, _, err := client.PullRequests.EditComment("o", "r", 1, input) - - if err != nil { - t.Errorf("PullRequests.EditComment returned error: %v", err) - } - - want := &PullRequestComment{ID: Int(1)} - if !reflect.DeepEqual(comment, want) { - t.Errorf("PullRequests.EditComment returned %+v, want %+v", comment, want) - } -} - -func TestPullRequestsService_EditComment_invalidOwner(t *testing.T) { - _, _, err := client.PullRequests.EditComment("%", "r", 1, nil) - testURLParseError(t, err) -} - -func TestPullRequestsService_DeleteComment(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/pulls/comments/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - }) - - _, err := client.PullRequests.DeleteComment("o", "r", 1) - if err != nil { - t.Errorf("PullRequests.DeleteComment returned error: %v", err) - } -} - -func TestPullRequestsService_DeleteComment_invalidOwner(t *testing.T) { - _, err := client.PullRequests.DeleteComment("%", "r", 1) - testURLParseError(t, err) -} diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/pulls_test.go b/Godeps/_workspace/src/github.com/google/go-github/github/pulls_test.go deleted file mode 100644 index 6ac0ddb17..000000000 --- a/Godeps/_workspace/src/github.com/google/go-github/github/pulls_test.go +++ /dev/null @@ -1,365 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestPullRequestsService_List(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/pulls", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "state": "closed", - "head": "h", - "base": "b", - "sort": "created", - "direction": "desc", - "page": "2", - }) - fmt.Fprint(w, `[{"number":1}]`) - }) - - opt := &PullRequestListOptions{"closed", "h", "b", "created", "desc", ListOptions{Page: 2}} - pulls, _, err := client.PullRequests.List("o", "r", opt) - - if err != nil { - t.Errorf("PullRequests.List returned error: %v", err) - } - - want := []PullRequest{{Number: Int(1)}} - if !reflect.DeepEqual(pulls, want) { - t.Errorf("PullRequests.List returned %+v, want %+v", pulls, want) - } -} - -func TestPullRequestsService_List_invalidOwner(t *testing.T) { - _, _, err := client.PullRequests.List("%", "r", nil) - testURLParseError(t, err) -} - -func TestPullRequestsService_Get(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/pulls/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"number":1}`) - }) - - pull, _, err := client.PullRequests.Get("o", "r", 1) - - if err != nil { - t.Errorf("PullRequests.Get returned error: %v", err) - } - - want := &PullRequest{Number: Int(1)} - if !reflect.DeepEqual(pull, want) { - t.Errorf("PullRequests.Get returned %+v, want %+v", pull, want) - } -} - -func TestPullRequestsService_Get_headAndBase(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/pulls/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"number":1,"head":{"ref":"r2","repo":{"id":2}},"base":{"ref":"r1","repo":{"id":1}}}`) - }) - - pull, _, err := client.PullRequests.Get("o", "r", 1) - - if err != nil { - t.Errorf("PullRequests.Get returned error: %v", err) - } - - want := &PullRequest{ - Number: Int(1), - Head: &PullRequestBranch{ - Ref: String("r2"), - Repo: &Repository{ID: Int(2)}, - }, - Base: &PullRequestBranch{ - Ref: String("r1"), - Repo: &Repository{ID: Int(1)}, - }, - } - if !reflect.DeepEqual(pull, want) { - t.Errorf("PullRequests.Get returned %+v, want %+v", pull, want) - } -} - -func TestPullRequestService_Get_DiffURLAndPatchURL(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/pulls/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"number":1, - "diff_url": "https://github.com/octocat/Hello-World/pull/1347.diff", - "patch_url": "https://github.com/octocat/Hello-World/pull/1347.patch"}`) - }) - - pull, _, err := client.PullRequests.Get("o", "r", 1) - - if err != nil { - t.Errorf("PullRequests.Get returned error: %v", err) - } - - want := &PullRequest{Number: Int(1), DiffURL: String("https://github.com/octocat/Hello-World/pull/1347.diff"), PatchURL: String("https://github.com/octocat/Hello-World/pull/1347.patch")} - if !reflect.DeepEqual(pull, want) { - t.Errorf("PullRequests.Get returned %+v, want %+v", pull, want) - } -} - -func TestPullRequestsService_Get_invalidOwner(t *testing.T) { - _, _, err := client.PullRequests.Get("%", "r", 1) - testURLParseError(t, err) -} - -func TestPullRequestsService_Create(t *testing.T) { - setup() - defer teardown() - - input := &NewPullRequest{Title: String("t")} - - mux.HandleFunc("/repos/o/r/pulls", func(w http.ResponseWriter, r *http.Request) { - v := new(NewPullRequest) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "POST") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"number":1}`) - }) - - pull, _, err := client.PullRequests.Create("o", "r", input) - if err != nil { - t.Errorf("PullRequests.Create returned error: %v", err) - } - - want := &PullRequest{Number: Int(1)} - if !reflect.DeepEqual(pull, want) { - t.Errorf("PullRequests.Create returned %+v, want %+v", pull, want) - } -} - -func TestPullRequestsService_Create_invalidOwner(t *testing.T) { - _, _, err := client.PullRequests.Create("%", "r", nil) - testURLParseError(t, err) -} - -func TestPullRequestsService_Edit(t *testing.T) { - setup() - defer teardown() - - input := &PullRequest{Title: String("t")} - - mux.HandleFunc("/repos/o/r/pulls/1", func(w http.ResponseWriter, r *http.Request) { - v := new(PullRequest) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "PATCH") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"number":1}`) - }) - - pull, _, err := client.PullRequests.Edit("o", "r", 1, input) - if err != nil { - t.Errorf("PullRequests.Edit returned error: %v", err) - } - - want := &PullRequest{Number: Int(1)} - if !reflect.DeepEqual(pull, want) { - t.Errorf("PullRequests.Edit returned %+v, want %+v", pull, want) - } -} - -func TestPullRequestsService_Edit_invalidOwner(t *testing.T) { - _, _, err := client.PullRequests.Edit("%", "r", 1, nil) - testURLParseError(t, err) -} - -func TestPullRequestsService_ListCommits(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/pulls/1/commits", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"page": "2"}) - fmt.Fprint(w, ` - [ - { - "sha": "3", - "parents": [ - { - "sha": "2" - } - ] - }, - { - "sha": "2", - "parents": [ - { - "sha": "1" - } - ] - } - ]`) - }) - - opt := &ListOptions{Page: 2} - commits, _, err := client.PullRequests.ListCommits("o", "r", 1, opt) - if err != nil { - t.Errorf("PullRequests.ListCommits returned error: %v", err) - } - - want := []RepositoryCommit{ - { - SHA: String("3"), - Parents: []Commit{ - { - SHA: String("2"), - }, - }, - }, - { - SHA: String("2"), - Parents: []Commit{ - { - SHA: String("1"), - }, - }, - }, - } - if !reflect.DeepEqual(commits, want) { - t.Errorf("PullRequests.ListCommits returned %+v, want %+v", commits, want) - } -} - -func TestPullRequestsService_ListFiles(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/pulls/1/files", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"page": "2"}) - fmt.Fprint(w, ` - [ - { - "sha": "6dcb09b5b57875f334f61aebed695e2e4193db5e", - "filename": "file1.txt", - "status": "added", - "additions": 103, - "deletions": 21, - "changes": 124, - "patch": "@@ -132,7 +132,7 @@ module Test @@ -1000,7 +1000,7 @@ module Test" - }, - { - "sha": "f61aebed695e2e4193db5e6dcb09b5b57875f334", - "filename": "file2.txt", - "status": "modified", - "additions": 5, - "deletions": 3, - "changes": 103, - "patch": "@@ -132,7 +132,7 @@ module Test @@ -1000,7 +1000,7 @@ module Test" - } - ]`) - }) - - opt := &ListOptions{Page: 2} - commitFiles, _, err := client.PullRequests.ListFiles("o", "r", 1, opt) - if err != nil { - t.Errorf("PullRequests.ListFiles returned error: %v", err) - } - - want := []CommitFile{ - { - SHA: String("6dcb09b5b57875f334f61aebed695e2e4193db5e"), - Filename: String("file1.txt"), - Additions: Int(103), - Deletions: Int(21), - Changes: Int(124), - Status: String("added"), - Patch: String("@@ -132,7 +132,7 @@ module Test @@ -1000,7 +1000,7 @@ module Test"), - }, - { - SHA: String("f61aebed695e2e4193db5e6dcb09b5b57875f334"), - Filename: String("file2.txt"), - Additions: Int(5), - Deletions: Int(3), - Changes: Int(103), - Status: String("modified"), - Patch: String("@@ -132,7 +132,7 @@ module Test @@ -1000,7 +1000,7 @@ module Test"), - }, - } - - if !reflect.DeepEqual(commitFiles, want) { - t.Errorf("PullRequests.ListFiles returned %+v, want %+v", commitFiles, want) - } -} - -func TestPullRequestsService_IsMerged(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/pulls/1/merge", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - w.WriteHeader(http.StatusNoContent) - }) - - isMerged, _, err := client.PullRequests.IsMerged("o", "r", 1) - if err != nil { - t.Errorf("PullRequests.IsMerged returned error: %v", err) - } - - want := true - if !reflect.DeepEqual(isMerged, want) { - t.Errorf("PullRequests.IsMerged returned %+v, want %+v", isMerged, want) - } -} - -func TestPullRequestsService_Merge(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/pulls/1/merge", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "PUT") - fmt.Fprint(w, ` - { - "sha": "6dcb09b5b57875f334f61aebed695e2e4193db5e", - "merged": true, - "message": "Pull Request successfully merged" - }`) - }) - - merge, _, err := client.PullRequests.Merge("o", "r", 1, "merging pull request") - if err != nil { - t.Errorf("PullRequests.Merge returned error: %v", err) - } - - want := &PullRequestMergeResult{ - SHA: String("6dcb09b5b57875f334f61aebed695e2e4193db5e"), - Merged: Bool(true), - Message: String("Pull Request successfully merged"), - } - if !reflect.DeepEqual(merge, want) { - t.Errorf("PullRequests.Merge returned %+v, want %+v", merge, want) - } -} diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/repos_collaborators_test.go b/Godeps/_workspace/src/github.com/google/go-github/github/repos_collaborators_test.go deleted file mode 100644 index ee6c4989e..000000000 --- a/Godeps/_workspace/src/github.com/google/go-github/github/repos_collaborators_test.go +++ /dev/null @@ -1,135 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestRepositoriesService_ListCollaborators(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/collaborators", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeOrgPermissionPreview) - testFormValues(t, r, values{"page": "2"}) - fmt.Fprintf(w, `[{"id":1}, {"id":2}]`) - }) - - opt := &ListOptions{Page: 2} - users, _, err := client.Repositories.ListCollaborators("o", "r", opt) - if err != nil { - t.Errorf("Repositories.ListCollaborators returned error: %v", err) - } - - want := []User{{ID: Int(1)}, {ID: Int(2)}} - if !reflect.DeepEqual(users, want) { - t.Errorf("Repositories.ListCollaborators returned %+v, want %+v", users, want) - } -} - -func TestRepositoriesService_ListCollaborators_invalidOwner(t *testing.T) { - _, _, err := client.Repositories.ListCollaborators("%", "%", nil) - testURLParseError(t, err) -} - -func TestRepositoriesService_IsCollaborator_True(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/collaborators/u", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - w.WriteHeader(http.StatusNoContent) - }) - - isCollab, _, err := client.Repositories.IsCollaborator("o", "r", "u") - if err != nil { - t.Errorf("Repositories.IsCollaborator returned error: %v", err) - } - - if !isCollab { - t.Errorf("Repositories.IsCollaborator returned false, want true") - } -} - -func TestRepositoriesService_IsCollaborator_False(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/collaborators/u", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - w.WriteHeader(http.StatusNotFound) - }) - - isCollab, _, err := client.Repositories.IsCollaborator("o", "r", "u") - if err != nil { - t.Errorf("Repositories.IsCollaborator returned error: %v", err) - } - - if isCollab { - t.Errorf("Repositories.IsCollaborator returned true, want false") - } -} - -func TestRepositoriesService_IsCollaborator_invalidUser(t *testing.T) { - _, _, err := client.Repositories.IsCollaborator("%", "%", "%") - testURLParseError(t, err) -} - -func TestRepositoriesService_AddCollaborator(t *testing.T) { - setup() - defer teardown() - - opt := &RepositoryAddCollaboratorOptions{Permission: "admin"} - - mux.HandleFunc("/repos/o/r/collaborators/u", func(w http.ResponseWriter, r *http.Request) { - v := new(RepositoryAddCollaboratorOptions) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "PUT") - testHeader(t, r, "Accept", mediaTypeOrgPermissionPreview) - if !reflect.DeepEqual(v, opt) { - t.Errorf("Request body = %+v, want %+v", v, opt) - } - - w.WriteHeader(http.StatusNoContent) - }) - - _, err := client.Repositories.AddCollaborator("o", "r", "u", opt) - if err != nil { - t.Errorf("Repositories.AddCollaborator returned error: %v", err) - } -} - -func TestRepositoriesService_AddCollaborator_invalidUser(t *testing.T) { - _, err := client.Repositories.AddCollaborator("%", "%", "%", nil) - testURLParseError(t, err) -} - -func TestRepositoriesService_RemoveCollaborator(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/collaborators/u", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - w.WriteHeader(http.StatusNoContent) - }) - - _, err := client.Repositories.RemoveCollaborator("o", "r", "u") - if err != nil { - t.Errorf("Repositories.RemoveCollaborator returned error: %v", err) - } -} - -func TestRepositoriesService_RemoveCollaborator_invalidUser(t *testing.T) { - _, err := client.Repositories.RemoveCollaborator("%", "%", "%") - testURLParseError(t, err) -} diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/repos_comments_test.go b/Godeps/_workspace/src/github.com/google/go-github/github/repos_comments_test.go deleted file mode 100644 index b5a8786a9..000000000 --- a/Godeps/_workspace/src/github.com/google/go-github/github/repos_comments_test.go +++ /dev/null @@ -1,180 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestRepositoriesService_ListComments(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/comments", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"page": "2"}) - fmt.Fprint(w, `[{"id":1}, {"id":2}]`) - }) - - opt := &ListOptions{Page: 2} - comments, _, err := client.Repositories.ListComments("o", "r", opt) - if err != nil { - t.Errorf("Repositories.ListComments returned error: %v", err) - } - - want := []RepositoryComment{{ID: Int(1)}, {ID: Int(2)}} - if !reflect.DeepEqual(comments, want) { - t.Errorf("Repositories.ListComments returned %+v, want %+v", comments, want) - } -} - -func TestRepositoriesService_ListComments_invalidOwner(t *testing.T) { - _, _, err := client.Repositories.ListComments("%", "%", nil) - testURLParseError(t, err) -} - -func TestRepositoriesService_ListCommitComments(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/commits/s/comments", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"page": "2"}) - fmt.Fprint(w, `[{"id":1}, {"id":2}]`) - }) - - opt := &ListOptions{Page: 2} - comments, _, err := client.Repositories.ListCommitComments("o", "r", "s", opt) - if err != nil { - t.Errorf("Repositories.ListCommitComments returned error: %v", err) - } - - want := []RepositoryComment{{ID: Int(1)}, {ID: Int(2)}} - if !reflect.DeepEqual(comments, want) { - t.Errorf("Repositories.ListCommitComments returned %+v, want %+v", comments, want) - } -} - -func TestRepositoriesService_ListCommitComments_invalidOwner(t *testing.T) { - _, _, err := client.Repositories.ListCommitComments("%", "%", "%", nil) - testURLParseError(t, err) -} - -func TestRepositoriesService_CreateComment(t *testing.T) { - setup() - defer teardown() - - input := &RepositoryComment{Body: String("b")} - - mux.HandleFunc("/repos/o/r/commits/s/comments", func(w http.ResponseWriter, r *http.Request) { - v := new(RepositoryComment) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "POST") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"id":1}`) - }) - - comment, _, err := client.Repositories.CreateComment("o", "r", "s", input) - if err != nil { - t.Errorf("Repositories.CreateComment returned error: %v", err) - } - - want := &RepositoryComment{ID: Int(1)} - if !reflect.DeepEqual(comment, want) { - t.Errorf("Repositories.CreateComment returned %+v, want %+v", comment, want) - } -} - -func TestRepositoriesService_CreateComment_invalidOwner(t *testing.T) { - _, _, err := client.Repositories.CreateComment("%", "%", "%", nil) - testURLParseError(t, err) -} - -func TestRepositoriesService_GetComment(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/comments/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"id":1}`) - }) - - comment, _, err := client.Repositories.GetComment("o", "r", 1) - if err != nil { - t.Errorf("Repositories.GetComment returned error: %v", err) - } - - want := &RepositoryComment{ID: Int(1)} - if !reflect.DeepEqual(comment, want) { - t.Errorf("Repositories.GetComment returned %+v, want %+v", comment, want) - } -} - -func TestRepositoriesService_GetComment_invalidOwner(t *testing.T) { - _, _, err := client.Repositories.GetComment("%", "%", 1) - testURLParseError(t, err) -} - -func TestRepositoriesService_UpdateComment(t *testing.T) { - setup() - defer teardown() - - input := &RepositoryComment{Body: String("b")} - - mux.HandleFunc("/repos/o/r/comments/1", func(w http.ResponseWriter, r *http.Request) { - v := new(RepositoryComment) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "PATCH") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"id":1}`) - }) - - comment, _, err := client.Repositories.UpdateComment("o", "r", 1, input) - if err != nil { - t.Errorf("Repositories.UpdateComment returned error: %v", err) - } - - want := &RepositoryComment{ID: Int(1)} - if !reflect.DeepEqual(comment, want) { - t.Errorf("Repositories.UpdateComment returned %+v, want %+v", comment, want) - } -} - -func TestRepositoriesService_UpdateComment_invalidOwner(t *testing.T) { - _, _, err := client.Repositories.UpdateComment("%", "%", 1, nil) - testURLParseError(t, err) -} - -func TestRepositoriesService_DeleteComment(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/comments/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - }) - - _, err := client.Repositories.DeleteComment("o", "r", 1) - if err != nil { - t.Errorf("Repositories.DeleteComment returned error: %v", err) - } -} - -func TestRepositoriesService_DeleteComment_invalidOwner(t *testing.T) { - _, err := client.Repositories.DeleteComment("%", "%", 1) - testURLParseError(t, err) -} diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/repos_commits_test.go b/Godeps/_workspace/src/github.com/google/go-github/github/repos_commits_test.go deleted file mode 100644 index 56ba8a5e0..000000000 --- a/Godeps/_workspace/src/github.com/google/go-github/github/repos_commits_test.go +++ /dev/null @@ -1,191 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "fmt" - "net/http" - "reflect" - "testing" - "time" -) - -func TestRepositoriesService_ListCommits(t *testing.T) { - setup() - defer teardown() - - // given - mux.HandleFunc("/repos/o/r/commits", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, - values{ - "sha": "s", - "path": "p", - "author": "a", - "since": "2013-08-01T00:00:00Z", - "until": "2013-09-03T00:00:00Z", - }) - fmt.Fprintf(w, `[{"sha": "s"}]`) - }) - - opt := &CommitsListOptions{ - SHA: "s", - Path: "p", - Author: "a", - Since: time.Date(2013, time.August, 1, 0, 0, 0, 0, time.UTC), - Until: time.Date(2013, time.September, 3, 0, 0, 0, 0, time.UTC), - } - commits, _, err := client.Repositories.ListCommits("o", "r", opt) - if err != nil { - t.Errorf("Repositories.ListCommits returned error: %v", err) - } - - want := []RepositoryCommit{{SHA: String("s")}} - if !reflect.DeepEqual(commits, want) { - t.Errorf("Repositories.ListCommits returned %+v, want %+v", commits, want) - } -} - -func TestRepositoriesService_GetCommit(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/commits/s", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprintf(w, `{ - "sha": "s", - "commit": { "message": "m" }, - "author": { "login": "l" }, - "committer": { "login": "l" }, - "parents": [ { "sha": "s" } ], - "stats": { "additions": 104, "deletions": 4, "total": 108 }, - "files": [ - { - "filename": "f", - "additions": 10, - "deletions": 2, - "changes": 12, - "status": "s", - "raw_url": "r", - "blob_url": "b", - "patch": "p" - } - ] - }`) - }) - - commit, _, err := client.Repositories.GetCommit("o", "r", "s") - if err != nil { - t.Errorf("Repositories.GetCommit returned error: %v", err) - } - - want := &RepositoryCommit{ - SHA: String("s"), - Commit: &Commit{ - Message: String("m"), - }, - Author: &User{ - Login: String("l"), - }, - Committer: &User{ - Login: String("l"), - }, - Parents: []Commit{ - { - SHA: String("s"), - }, - }, - Stats: &CommitStats{ - Additions: Int(104), - Deletions: Int(4), - Total: Int(108), - }, - Files: []CommitFile{ - { - Filename: String("f"), - Additions: Int(10), - Deletions: Int(2), - Changes: Int(12), - Status: String("s"), - Patch: String("p"), - }, - }, - } - if !reflect.DeepEqual(commit, want) { - t.Errorf("Repositories.GetCommit returned \n%+v, want \n%+v", commit, want) - } -} - -func TestRepositoriesService_CompareCommits(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/compare/b...h", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprintf(w, `{ - "base_commit": { - "sha": "s", - "commit": { - "author": { "name": "n" }, - "committer": { "name": "n" }, - "message": "m", - "tree": { "sha": "t" } - }, - "author": { "login": "n" }, - "committer": { "login": "l" }, - "parents": [ { "sha": "s" } ] - }, - "status": "s", - "ahead_by": 1, - "behind_by": 2, - "total_commits": 1, - "commits": [ - { - "sha": "s", - "commit": { "author": { "name": "n" } }, - "author": { "login": "l" }, - "committer": { "login": "l" }, - "parents": [ { "sha": "s" } ] - } - ], - "files": [ { "filename": "f" } ] - }`) - }) - - got, _, err := client.Repositories.CompareCommits("o", "r", "b", "h") - if err != nil { - t.Errorf("Repositories.CompareCommits returned error: %v", err) - } - - want := &CommitsComparison{ - Status: String("s"), - AheadBy: Int(1), - BehindBy: Int(2), - TotalCommits: Int(1), - BaseCommit: &RepositoryCommit{ - Commit: &Commit{ - Author: &CommitAuthor{Name: String("n")}, - }, - Author: &User{Login: String("l")}, - Committer: &User{Login: String("l")}, - Message: String("m"), - }, - Commits: []RepositoryCommit{ - { - SHA: String("s"), - }, - }, - Files: []CommitFile{ - { - Filename: String("f"), - }, - }, - } - - if reflect.DeepEqual(got, want) { - t.Errorf("Repositories.CompareCommits returned \n%+v, want \n%+v", got, want) - } -} diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/repos_contents_test.go b/Godeps/_workspace/src/github.com/google/go-github/github/repos_contents_test.go deleted file mode 100644 index 8ab3ecdae..000000000 --- a/Godeps/_workspace/src/github.com/google/go-github/github/repos_contents_test.go +++ /dev/null @@ -1,304 +0,0 @@ -package github - -import ( - "fmt" - "io/ioutil" - "net/http" - "reflect" - "testing" -) - -func TestDecode(t *testing.T) { - setup() - defer teardown() - r := RepositoryContent{Encoding: String("base64"), Content: String("aGVsbG8=")} - o, err := r.Decode() - if err != nil { - t.Errorf("Failed to decode content.") - } - want := "hello" - if string(o) != want { - t.Errorf("RepositoryContent.Decode returned %+v, want %+v", string(o), want) - } -} - -func TestDecodeBadEncoding(t *testing.T) { - setup() - defer teardown() - r := RepositoryContent{Encoding: String("bad")} - _, err := r.Decode() - if err == nil { - t.Errorf("Should fail to decode non-base64") - } -} - -func TestRepositoriesService_GetReadme(t *testing.T) { - setup() - defer teardown() - mux.HandleFunc("/repos/o/r/readme", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{ - "type": "file", - "encoding": "base64", - "size": 5362, - "name": "README.md", - "path": "README.md" - }`) - }) - readme, _, err := client.Repositories.GetReadme("o", "r", &RepositoryContentGetOptions{}) - if err != nil { - t.Errorf("Repositories.GetReadme returned error: %v", err) - } - want := &RepositoryContent{Type: String("file"), Name: String("README.md"), Size: Int(5362), Encoding: String("base64"), Path: String("README.md")} - if !reflect.DeepEqual(readme, want) { - t.Errorf("Repositories.GetReadme returned %+v, want %+v", readme, want) - } -} - -func TestRepositoriesService_DownloadContents_Success(t *testing.T) { - setup() - defer teardown() - mux.HandleFunc("/repos/o/r/contents/d", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `[{ - "type": "file", - "name": "f", - "download_url": "`+server.URL+`/download/f" - }]`) - }) - mux.HandleFunc("/download/f", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, "foo") - }) - - r, err := client.Repositories.DownloadContents("o", "r", "d/f", nil) - if err != nil { - t.Errorf("Repositories.DownloadContents returned error: %v", err) - } - - bytes, err := ioutil.ReadAll(r) - if err != nil { - t.Errorf("Error reading response body: %v", err) - } - r.Close() - - if got, want := string(bytes), "foo"; got != want { - t.Errorf("Repositories.DownloadContents returned %v, want %v", got, want) - } -} - -func TestRepositoriesService_DownloadContents_NoDownloadURL(t *testing.T) { - setup() - defer teardown() - mux.HandleFunc("/repos/o/r/contents/d", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `[{ - "type": "file", - "name": "f", - }]`) - }) - - _, err := client.Repositories.DownloadContents("o", "r", "d/f", nil) - if err == nil { - t.Errorf("Repositories.DownloadContents did not return expected error") - } -} - -func TestRepositoriesService_DownloadContents_NoFile(t *testing.T) { - setup() - defer teardown() - mux.HandleFunc("/repos/o/r/contents/d", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `[]`) - }) - - _, err := client.Repositories.DownloadContents("o", "r", "d/f", nil) - if err == nil { - t.Errorf("Repositories.DownloadContents did not return expected error") - } -} - -func TestRepositoriesService_GetContents_File(t *testing.T) { - setup() - defer teardown() - mux.HandleFunc("/repos/o/r/contents/p", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{ - "type": "file", - "encoding": "base64", - "size": 20678, - "name": "LICENSE", - "path": "LICENSE" - }`) - }) - fileContents, _, _, err := client.Repositories.GetContents("o", "r", "p", &RepositoryContentGetOptions{}) - if err != nil { - t.Errorf("Repositories.GetContents returned error: %v", err) - } - want := &RepositoryContent{Type: String("file"), Name: String("LICENSE"), Size: Int(20678), Encoding: String("base64"), Path: String("LICENSE")} - if !reflect.DeepEqual(fileContents, want) { - t.Errorf("Repositories.GetContents returned %+v, want %+v", fileContents, want) - } -} - -func TestRepositoriesService_GetContents_Directory(t *testing.T) { - setup() - defer teardown() - mux.HandleFunc("/repos/o/r/contents/p", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `[{ - "type": "dir", - "name": "lib", - "path": "lib" - }, - { - "type": "file", - "size": 20678, - "name": "LICENSE", - "path": "LICENSE" - }]`) - }) - _, directoryContents, _, err := client.Repositories.GetContents("o", "r", "p", &RepositoryContentGetOptions{}) - if err != nil { - t.Errorf("Repositories.GetContents returned error: %v", err) - } - want := []*RepositoryContent{{Type: String("dir"), Name: String("lib"), Path: String("lib")}, - {Type: String("file"), Name: String("LICENSE"), Size: Int(20678), Path: String("LICENSE")}} - if !reflect.DeepEqual(directoryContents, want) { - t.Errorf("Repositories.GetContents_Directory returned %+v, want %+v", directoryContents, want) - } -} - -func TestRepositoriesService_CreateFile(t *testing.T) { - setup() - defer teardown() - mux.HandleFunc("/repos/o/r/contents/p", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "PUT") - fmt.Fprint(w, `{ - "content":{ - "name":"p" - }, - "commit":{ - "message":"m", - "sha":"f5f369044773ff9c6383c087466d12adb6fa0828" - } - }`) - }) - message := "m" - content := []byte("c") - repositoryContentsOptions := &RepositoryContentFileOptions{ - Message: &message, - Content: content, - Committer: &CommitAuthor{Name: String("n"), Email: String("e")}, - } - createResponse, _, err := client.Repositories.CreateFile("o", "r", "p", repositoryContentsOptions) - if err != nil { - t.Errorf("Repositories.CreateFile returned error: %v", err) - } - want := &RepositoryContentResponse{ - Content: &RepositoryContent{Name: String("p")}, - Commit: Commit{ - Message: String("m"), - SHA: String("f5f369044773ff9c6383c087466d12adb6fa0828"), - }, - } - if !reflect.DeepEqual(createResponse, want) { - t.Errorf("Repositories.CreateFile returned %+v, want %+v", createResponse, want) - } -} - -func TestRepositoriesService_UpdateFile(t *testing.T) { - setup() - defer teardown() - mux.HandleFunc("/repos/o/r/contents/p", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "PUT") - fmt.Fprint(w, `{ - "content":{ - "name":"p" - }, - "commit":{ - "message":"m", - "sha":"f5f369044773ff9c6383c087466d12adb6fa0828" - } - }`) - }) - message := "m" - content := []byte("c") - sha := "f5f369044773ff9c6383c087466d12adb6fa0828" - repositoryContentsOptions := &RepositoryContentFileOptions{ - Message: &message, - Content: content, - SHA: &sha, - Committer: &CommitAuthor{Name: String("n"), Email: String("e")}, - } - updateResponse, _, err := client.Repositories.UpdateFile("o", "r", "p", repositoryContentsOptions) - if err != nil { - t.Errorf("Repositories.UpdateFile returned error: %v", err) - } - want := &RepositoryContentResponse{ - Content: &RepositoryContent{Name: String("p")}, - Commit: Commit{ - Message: String("m"), - SHA: String("f5f369044773ff9c6383c087466d12adb6fa0828"), - }, - } - if !reflect.DeepEqual(updateResponse, want) { - t.Errorf("Repositories.UpdateFile returned %+v, want %+v", updateResponse, want) - } -} - -func TestRepositoriesService_DeleteFile(t *testing.T) { - setup() - defer teardown() - mux.HandleFunc("/repos/o/r/contents/p", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - fmt.Fprint(w, `{ - "content": null, - "commit":{ - "message":"m", - "sha":"f5f369044773ff9c6383c087466d12adb6fa0828" - } - }`) - }) - message := "m" - sha := "f5f369044773ff9c6383c087466d12adb6fa0828" - repositoryContentsOptions := &RepositoryContentFileOptions{ - Message: &message, - SHA: &sha, - Committer: &CommitAuthor{Name: String("n"), Email: String("e")}, - } - deleteResponse, _, err := client.Repositories.DeleteFile("o", "r", "p", repositoryContentsOptions) - if err != nil { - t.Errorf("Repositories.DeleteFile returned error: %v", err) - } - want := &RepositoryContentResponse{ - Content: nil, - Commit: Commit{ - Message: String("m"), - SHA: String("f5f369044773ff9c6383c087466d12adb6fa0828"), - }, - } - if !reflect.DeepEqual(deleteResponse, want) { - t.Errorf("Repositories.DeleteFile returned %+v, want %+v", deleteResponse, want) - } -} - -func TestRepositoriesService_GetArchiveLink(t *testing.T) { - setup() - defer teardown() - mux.HandleFunc("/repos/o/r/tarball", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - http.Redirect(w, r, "http://github.com/a", http.StatusFound) - }) - url, resp, err := client.Repositories.GetArchiveLink("o", "r", Tarball, &RepositoryContentGetOptions{}) - if err != nil { - t.Errorf("Repositories.GetArchiveLink returned error: %v", err) - } - if resp.StatusCode != http.StatusFound { - t.Errorf("Repositories.GetArchiveLink returned status: %d, want %d", resp.StatusCode, http.StatusFound) - } - want := "http://github.com/a" - if url.String() != want { - t.Errorf("Repositories.GetArchiveLink returned %+v, want %+v", url.String(), want) - } -} diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/repos_deployments_test.go b/Godeps/_workspace/src/github.com/google/go-github/github/repos_deployments_test.go deleted file mode 100644 index 161a07ccd..000000000 --- a/Godeps/_workspace/src/github.com/google/go-github/github/repos_deployments_test.go +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright 2014 The go-github 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 github - -import ( - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestRepositoriesService_ListDeployments(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/deployments", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"environment": "test"}) - fmt.Fprint(w, `[{"id":1}, {"id":2}]`) - }) - - opt := &DeploymentsListOptions{Environment: "test"} - deployments, _, err := client.Repositories.ListDeployments("o", "r", opt) - if err != nil { - t.Errorf("Repositories.ListDeployments returned error: %v", err) - } - - want := []Deployment{{ID: Int(1)}, {ID: Int(2)}} - if !reflect.DeepEqual(deployments, want) { - t.Errorf("Repositories.ListDeployments returned %+v, want %+v", deployments, want) - } -} - -func TestRepositoriesService_CreateDeployment(t *testing.T) { - setup() - defer teardown() - - input := &DeploymentRequest{Ref: String("1111"), Task: String("deploy")} - - mux.HandleFunc("/repos/o/r/deployments", func(w http.ResponseWriter, r *http.Request) { - v := new(DeploymentRequest) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "POST") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"ref": "1111", "task": "deploy"}`) - }) - - deployment, _, err := client.Repositories.CreateDeployment("o", "r", input) - if err != nil { - t.Errorf("Repositories.CreateDeployment returned error: %v", err) - } - - want := &Deployment{Ref: String("1111"), Task: String("deploy")} - if !reflect.DeepEqual(deployment, want) { - t.Errorf("Repositories.CreateDeployment returned %+v, want %+v", deployment, want) - } -} - -func TestRepositoriesService_ListDeploymentStatuses(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/deployments/1/statuses", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"page": "2"}) - fmt.Fprint(w, `[{"id":1}, {"id":2}]`) - }) - - opt := &ListOptions{Page: 2} - statutses, _, err := client.Repositories.ListDeploymentStatuses("o", "r", 1, opt) - if err != nil { - t.Errorf("Repositories.ListDeploymentStatuses returned error: %v", err) - } - - want := []DeploymentStatus{{ID: Int(1)}, {ID: Int(2)}} - if !reflect.DeepEqual(statutses, want) { - t.Errorf("Repositories.ListDeploymentStatuses returned %+v, want %+v", statutses, want) - } -} diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/repos_forks_test.go b/Godeps/_workspace/src/github.com/google/go-github/github/repos_forks_test.go deleted file mode 100644 index 965a06639..000000000 --- a/Godeps/_workspace/src/github.com/google/go-github/github/repos_forks_test.go +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestRepositoriesService_ListForks(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/forks", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "sort": "newest", - "page": "3", - }) - fmt.Fprint(w, `[{"id":1},{"id":2}]`) - }) - - opt := &RepositoryListForksOptions{ - Sort: "newest", - ListOptions: ListOptions{Page: 3}, - } - repos, _, err := client.Repositories.ListForks("o", "r", opt) - if err != nil { - t.Errorf("Repositories.ListForks returned error: %v", err) - } - - want := []Repository{{ID: Int(1)}, {ID: Int(2)}} - if !reflect.DeepEqual(repos, want) { - t.Errorf("Repositories.ListForks returned %+v, want %+v", repos, want) - } -} - -func TestRepositoriesService_ListForks_invalidOwner(t *testing.T) { - _, _, err := client.Repositories.ListForks("%", "r", nil) - testURLParseError(t, err) -} - -func TestRepositoriesService_CreateFork(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/forks", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "POST") - testFormValues(t, r, values{"organization": "o"}) - fmt.Fprint(w, `{"id":1}`) - }) - - opt := &RepositoryCreateForkOptions{Organization: "o"} - repo, _, err := client.Repositories.CreateFork("o", "r", opt) - if err != nil { - t.Errorf("Repositories.CreateFork returned error: %v", err) - } - - want := &Repository{ID: Int(1)} - if !reflect.DeepEqual(repo, want) { - t.Errorf("Repositories.CreateFork returned %+v, want %+v", repo, want) - } -} - -func TestRepositoriesService_CreateFork_invalidOwner(t *testing.T) { - _, _, err := client.Repositories.CreateFork("%", "r", nil) - testURLParseError(t, err) -} diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/repos_hooks_test.go b/Godeps/_workspace/src/github.com/google/go-github/github/repos_hooks_test.go deleted file mode 100644 index c163a26b2..000000000 --- a/Godeps/_workspace/src/github.com/google/go-github/github/repos_hooks_test.go +++ /dev/null @@ -1,187 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestRepositoriesService_CreateHook(t *testing.T) { - setup() - defer teardown() - - input := &Hook{Name: String("t")} - - mux.HandleFunc("/repos/o/r/hooks", func(w http.ResponseWriter, r *http.Request) { - v := new(Hook) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "POST") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"id":1}`) - }) - - hook, _, err := client.Repositories.CreateHook("o", "r", input) - if err != nil { - t.Errorf("Repositories.CreateHook returned error: %v", err) - } - - want := &Hook{ID: Int(1)} - if !reflect.DeepEqual(hook, want) { - t.Errorf("Repositories.CreateHook returned %+v, want %+v", hook, want) - } -} - -func TestRepositoriesService_CreateHook_invalidOwner(t *testing.T) { - _, _, err := client.Repositories.CreateHook("%", "%", nil) - testURLParseError(t, err) -} - -func TestRepositoriesService_ListHooks(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/hooks", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"page": "2"}) - fmt.Fprint(w, `[{"id":1}, {"id":2}]`) - }) - - opt := &ListOptions{Page: 2} - - hooks, _, err := client.Repositories.ListHooks("o", "r", opt) - if err != nil { - t.Errorf("Repositories.ListHooks returned error: %v", err) - } - - want := []Hook{{ID: Int(1)}, {ID: Int(2)}} - if !reflect.DeepEqual(hooks, want) { - t.Errorf("Repositories.ListHooks returned %+v, want %+v", hooks, want) - } -} - -func TestRepositoriesService_ListHooks_invalidOwner(t *testing.T) { - _, _, err := client.Repositories.ListHooks("%", "%", nil) - testURLParseError(t, err) -} - -func TestRepositoriesService_GetHook(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/hooks/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"id":1}`) - }) - - hook, _, err := client.Repositories.GetHook("o", "r", 1) - if err != nil { - t.Errorf("Repositories.GetHook returned error: %v", err) - } - - want := &Hook{ID: Int(1)} - if !reflect.DeepEqual(hook, want) { - t.Errorf("Repositories.GetHook returned %+v, want %+v", hook, want) - } -} - -func TestRepositoriesService_GetHook_invalidOwner(t *testing.T) { - _, _, err := client.Repositories.GetHook("%", "%", 1) - testURLParseError(t, err) -} - -func TestRepositoriesService_EditHook(t *testing.T) { - setup() - defer teardown() - - input := &Hook{Name: String("t")} - - mux.HandleFunc("/repos/o/r/hooks/1", func(w http.ResponseWriter, r *http.Request) { - v := new(Hook) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "PATCH") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"id":1}`) - }) - - hook, _, err := client.Repositories.EditHook("o", "r", 1, input) - if err != nil { - t.Errorf("Repositories.EditHook returned error: %v", err) - } - - want := &Hook{ID: Int(1)} - if !reflect.DeepEqual(hook, want) { - t.Errorf("Repositories.EditHook returned %+v, want %+v", hook, want) - } -} - -func TestRepositoriesService_EditHook_invalidOwner(t *testing.T) { - _, _, err := client.Repositories.EditHook("%", "%", 1, nil) - testURLParseError(t, err) -} - -func TestRepositoriesService_DeleteHook(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/hooks/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - }) - - _, err := client.Repositories.DeleteHook("o", "r", 1) - if err != nil { - t.Errorf("Repositories.DeleteHook returned error: %v", err) - } -} - -func TestRepositoriesService_DeleteHook_invalidOwner(t *testing.T) { - _, err := client.Repositories.DeleteHook("%", "%", 1) - testURLParseError(t, err) -} - -func TestRepositoriesService_PingHook(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/hooks/1/pings", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "POST") - }) - - _, err := client.Repositories.PingHook("o", "r", 1) - if err != nil { - t.Errorf("Repositories.PingHook returned error: %v", err) - } -} - -func TestRepositoriesService_TestHook(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/hooks/1/tests", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "POST") - }) - - _, err := client.Repositories.TestHook("o", "r", 1) - if err != nil { - t.Errorf("Repositories.TestHook returned error: %v", err) - } -} - -func TestRepositoriesService_TestHook_invalidOwner(t *testing.T) { - _, err := client.Repositories.TestHook("%", "%", 1) - testURLParseError(t, err) -} diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/repos_keys_test.go b/Godeps/_workspace/src/github.com/google/go-github/github/repos_keys_test.go deleted file mode 100644 index dcf6c55e4..000000000 --- a/Godeps/_workspace/src/github.com/google/go-github/github/repos_keys_test.go +++ /dev/null @@ -1,153 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestRepositoriesService_ListKeys(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/keys", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"page": "2"}) - fmt.Fprint(w, `[{"id":1}]`) - }) - - opt := &ListOptions{Page: 2} - keys, _, err := client.Repositories.ListKeys("o", "r", opt) - if err != nil { - t.Errorf("Repositories.ListKeys returned error: %v", err) - } - - want := []Key{{ID: Int(1)}} - if !reflect.DeepEqual(keys, want) { - t.Errorf("Repositories.ListKeys returned %+v, want %+v", keys, want) - } -} - -func TestRepositoriesService_ListKeys_invalidOwner(t *testing.T) { - _, _, err := client.Repositories.ListKeys("%", "%", nil) - testURLParseError(t, err) -} - -func TestRepositoriesService_GetKey(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/keys/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"id":1}`) - }) - - key, _, err := client.Repositories.GetKey("o", "r", 1) - if err != nil { - t.Errorf("Repositories.GetKey returned error: %v", err) - } - - want := &Key{ID: Int(1)} - if !reflect.DeepEqual(key, want) { - t.Errorf("Repositories.GetKey returned %+v, want %+v", key, want) - } -} - -func TestRepositoriesService_GetKey_invalidOwner(t *testing.T) { - _, _, err := client.Repositories.GetKey("%", "%", 1) - testURLParseError(t, err) -} - -func TestRepositoriesService_CreateKey(t *testing.T) { - setup() - defer teardown() - - input := &Key{Key: String("k"), Title: String("t")} - - mux.HandleFunc("/repos/o/r/keys", func(w http.ResponseWriter, r *http.Request) { - v := new(Key) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "POST") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"id":1}`) - }) - - key, _, err := client.Repositories.CreateKey("o", "r", input) - if err != nil { - t.Errorf("Repositories.GetKey returned error: %v", err) - } - - want := &Key{ID: Int(1)} - if !reflect.DeepEqual(key, want) { - t.Errorf("Repositories.GetKey returned %+v, want %+v", key, want) - } -} - -func TestRepositoriesService_CreateKey_invalidOwner(t *testing.T) { - _, _, err := client.Repositories.CreateKey("%", "%", nil) - testURLParseError(t, err) -} - -func TestRepositoriesService_EditKey(t *testing.T) { - setup() - defer teardown() - - input := &Key{Key: String("k"), Title: String("t")} - - mux.HandleFunc("/repos/o/r/keys/1", func(w http.ResponseWriter, r *http.Request) { - v := new(Key) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "PATCH") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"id":1}`) - }) - - key, _, err := client.Repositories.EditKey("o", "r", 1, input) - if err != nil { - t.Errorf("Repositories.EditKey returned error: %v", err) - } - - want := &Key{ID: Int(1)} - if !reflect.DeepEqual(key, want) { - t.Errorf("Repositories.EditKey returned %+v, want %+v", key, want) - } -} - -func TestRepositoriesService_EditKey_invalidOwner(t *testing.T) { - _, _, err := client.Repositories.EditKey("%", "%", 1, nil) - testURLParseError(t, err) -} - -func TestRepositoriesService_DeleteKey(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/keys/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - }) - - _, err := client.Repositories.DeleteKey("o", "r", 1) - if err != nil { - t.Errorf("Repositories.DeleteKey returned error: %v", err) - } -} - -func TestRepositoriesService_DeleteKey_invalidOwner(t *testing.T) { - _, err := client.Repositories.DeleteKey("%", "%", 1) - testURLParseError(t, err) -} diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/repos_merging_test.go b/Godeps/_workspace/src/github.com/google/go-github/github/repos_merging_test.go deleted file mode 100644 index 166c5e520..000000000 --- a/Godeps/_workspace/src/github.com/google/go-github/github/repos_merging_test.go +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright 2014 The go-github 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 github - -import ( - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestRepositoriesService_Merge(t *testing.T) { - setup() - defer teardown() - - input := &RepositoryMergeRequest{ - Base: String("b"), - Head: String("h"), - CommitMessage: String("c"), - } - - mux.HandleFunc("/repos/o/r/merges", func(w http.ResponseWriter, r *http.Request) { - v := new(RepositoryMergeRequest) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "POST") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"sha":"s"}`) - }) - - commit, _, err := client.Repositories.Merge("o", "r", input) - if err != nil { - t.Errorf("Repositories.Merge returned error: %v", err) - } - - want := &RepositoryCommit{SHA: String("s")} - if !reflect.DeepEqual(commit, want) { - t.Errorf("Repositories.Merge returned %+v, want %+v", commit, want) - } -} diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/repos_pages_test.go b/Godeps/_workspace/src/github.com/google/go-github/github/repos_pages_test.go deleted file mode 100644 index 4cbc43a17..000000000 --- a/Godeps/_workspace/src/github.com/google/go-github/github/repos_pages_test.go +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright 2014 The go-github 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 github - -import ( - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestRepositoriesService_GetPagesInfo(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/pages", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"url":"u","status":"s","cname":"c","custom_404":false}`) - }) - - page, _, err := client.Repositories.GetPagesInfo("o", "r") - if err != nil { - t.Errorf("Repositories.GetPagesInfo returned error: %v", err) - } - - want := &Pages{URL: String("u"), Status: String("s"), CNAME: String("c"), Custom404: Bool(false)} - if !reflect.DeepEqual(page, want) { - t.Errorf("Repositories.GetPagesInfo returned %+v, want %+v", page, want) - } -} - -func TestRepositoriesService_ListPagesBuilds(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/pages/builds", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `[{"url":"u","status":"s","commit":"c"}]`) - }) - - pages, _, err := client.Repositories.ListPagesBuilds("o", "r") - if err != nil { - t.Errorf("Repositories.ListPagesBuilds returned error: %v", err) - } - - want := []PagesBuild{{URL: String("u"), Status: String("s"), Commit: String("c")}} - if !reflect.DeepEqual(pages, want) { - t.Errorf("Repositories.ListPagesBuilds returned %+v, want %+v", pages, want) - } -} - -func TestRepositoriesService_GetLatestPagesBuild(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/pages/builds/latest", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"url":"u","status":"s","commit":"c"}`) - }) - - build, _, err := client.Repositories.GetLatestPagesBuild("o", "r") - if err != nil { - t.Errorf("Repositories.GetLatestPagesBuild returned error: %v", err) - } - - want := &PagesBuild{URL: String("u"), Status: String("s"), Commit: String("c")} - if !reflect.DeepEqual(build, want) { - t.Errorf("Repositories.GetLatestPagesBuild returned %+v, want %+v", build, want) - } -} diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/repos_releases_test.go b/Godeps/_workspace/src/github.com/google/go-github/github/repos_releases_test.go deleted file mode 100644 index 21808b7e6..000000000 --- a/Godeps/_workspace/src/github.com/google/go-github/github/repos_releases_test.go +++ /dev/null @@ -1,277 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "encoding/json" - "fmt" - "net/http" - "os" - "reflect" - "testing" -) - -func TestRepositoriesService_ListReleases(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/releases", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"page": "2"}) - fmt.Fprint(w, `[{"id":1}]`) - }) - - opt := &ListOptions{Page: 2} - releases, _, err := client.Repositories.ListReleases("o", "r", opt) - if err != nil { - t.Errorf("Repositories.ListReleases returned error: %v", err) - } - want := []RepositoryRelease{{ID: Int(1)}} - if !reflect.DeepEqual(releases, want) { - t.Errorf("Repositories.ListReleases returned %+v, want %+v", releases, want) - } -} - -func TestRepositoriesService_GetRelease(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/releases/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"id":1}`) - }) - - release, resp, err := client.Repositories.GetRelease("o", "r", 1) - if err != nil { - t.Errorf("Repositories.GetRelease returned error: %v\n%v", err, resp.Body) - } - - want := &RepositoryRelease{ID: Int(1)} - if !reflect.DeepEqual(release, want) { - t.Errorf("Repositories.GetRelease returned %+v, want %+v", release, want) - } -} - -func TestRepositoriesService_GetLatestRelease(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/releases/latest", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"id":3}`) - }) - - release, resp, err := client.Repositories.GetLatestRelease("o", "r") - if err != nil { - t.Errorf("Repositories.GetLatestRelease returned error: %v\n%v", err, resp.Body) - } - - want := &RepositoryRelease{ID: Int(3)} - if !reflect.DeepEqual(release, want) { - t.Errorf("Repositories.GetLatestRelease returned %+v, want %+v", release, want) - } -} - -func TestRepositoriesService_GetReleaseByTag(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/releases/tags/foo", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"id":13}`) - }) - - release, resp, err := client.Repositories.GetReleaseByTag("o", "r", "foo") - if err != nil { - t.Errorf("Repositories.GetReleaseByTag returned error: %v\n%v", err, resp.Body) - } - - want := &RepositoryRelease{ID: Int(13)} - if !reflect.DeepEqual(release, want) { - t.Errorf("Repositories.GetReleaseByTag returned %+v, want %+v", release, want) - } -} - -func TestRepositoriesService_CreateRelease(t *testing.T) { - setup() - defer teardown() - - input := &RepositoryRelease{Name: String("v1.0")} - - mux.HandleFunc("/repos/o/r/releases", func(w http.ResponseWriter, r *http.Request) { - v := new(RepositoryRelease) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "POST") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - fmt.Fprint(w, `{"id":1}`) - }) - - release, _, err := client.Repositories.CreateRelease("o", "r", input) - if err != nil { - t.Errorf("Repositories.CreateRelease returned error: %v", err) - } - - want := &RepositoryRelease{ID: Int(1)} - if !reflect.DeepEqual(release, want) { - t.Errorf("Repositories.CreateRelease returned %+v, want %+v", release, want) - } -} - -func TestRepositoriesService_EditRelease(t *testing.T) { - setup() - defer teardown() - - input := &RepositoryRelease{Name: String("n")} - - mux.HandleFunc("/repos/o/r/releases/1", func(w http.ResponseWriter, r *http.Request) { - v := new(RepositoryRelease) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "PATCH") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - fmt.Fprint(w, `{"id":1}`) - }) - - release, _, err := client.Repositories.EditRelease("o", "r", 1, input) - if err != nil { - t.Errorf("Repositories.EditRelease returned error: %v", err) - } - want := &RepositoryRelease{ID: Int(1)} - if !reflect.DeepEqual(release, want) { - t.Errorf("Repositories.EditRelease returned = %+v, want %+v", release, want) - } -} - -func TestRepositoriesService_DeleteRelease(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/releases/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - }) - - _, err := client.Repositories.DeleteRelease("o", "r", 1) - if err != nil { - t.Errorf("Repositories.DeleteRelease returned error: %v", err) - } -} - -func TestRepositoriesService_ListReleaseAssets(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/releases/1/assets", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"page": "2"}) - fmt.Fprint(w, `[{"id":1}]`) - }) - - opt := &ListOptions{Page: 2} - assets, _, err := client.Repositories.ListReleaseAssets("o", "r", 1, opt) - if err != nil { - t.Errorf("Repositories.ListReleaseAssets returned error: %v", err) - } - want := []ReleaseAsset{{ID: Int(1)}} - if !reflect.DeepEqual(assets, want) { - t.Errorf("Repositories.ListReleaseAssets returned %+v, want %+v", assets, want) - } -} - -func TestRepositoriesService_GetReleaseAsset(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/releases/assets/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"id":1}`) - }) - - asset, _, err := client.Repositories.GetReleaseAsset("o", "r", 1) - if err != nil { - t.Errorf("Repositories.GetReleaseAsset returned error: %v", err) - } - want := &ReleaseAsset{ID: Int(1)} - if !reflect.DeepEqual(asset, want) { - t.Errorf("Repositories.GetReleaseAsset returned %+v, want %+v", asset, want) - } -} - -func TestRepositoriesService_EditReleaseAsset(t *testing.T) { - setup() - defer teardown() - - input := &ReleaseAsset{Name: String("n")} - - mux.HandleFunc("/repos/o/r/releases/assets/1", func(w http.ResponseWriter, r *http.Request) { - v := new(ReleaseAsset) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "PATCH") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - fmt.Fprint(w, `{"id":1}`) - }) - - asset, _, err := client.Repositories.EditReleaseAsset("o", "r", 1, input) - if err != nil { - t.Errorf("Repositories.EditReleaseAsset returned error: %v", err) - } - want := &ReleaseAsset{ID: Int(1)} - if !reflect.DeepEqual(asset, want) { - t.Errorf("Repositories.EditReleaseAsset returned = %+v, want %+v", asset, want) - } -} - -func TestRepositoriesService_DeleteReleaseAsset(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/releases/assets/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - }) - - _, err := client.Repositories.DeleteReleaseAsset("o", "r", 1) - if err != nil { - t.Errorf("Repositories.DeleteReleaseAsset returned error: %v", err) - } -} - -func TestRepositoriesService_UploadReleaseAsset(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/releases/1/assets", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "POST") - testHeader(t, r, "Content-Type", "text/plain; charset=utf-8") - testHeader(t, r, "Content-Length", "12") - testFormValues(t, r, values{"name": "n"}) - testBody(t, r, "Upload me !\n") - - fmt.Fprintf(w, `{"id":1}`) - }) - - file, dir, err := openTestFile("upload.txt", "Upload me !\n") - if err != nil { - t.Fatalf("Unable to create temp file: %v", err) - } - defer os.RemoveAll(dir) - - opt := &UploadOptions{Name: "n"} - asset, _, err := client.Repositories.UploadReleaseAsset("o", "r", 1, opt, file) - if err != nil { - t.Errorf("Repositories.UploadReleaseAssert returned error: %v", err) - } - want := &ReleaseAsset{ID: Int(1)} - if !reflect.DeepEqual(asset, want) { - t.Errorf("Repositories.UploadReleaseAssert returned %+v, want %+v", asset, want) - } -} diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/repos_stats_test.go b/Godeps/_workspace/src/github.com/google/go-github/github/repos_stats_test.go deleted file mode 100644 index 3f9fab5ca..000000000 --- a/Godeps/_workspace/src/github.com/google/go-github/github/repos_stats_test.go +++ /dev/null @@ -1,210 +0,0 @@ -// Copyright 2014 The go-github 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 github - -import ( - "fmt" - "net/http" - "reflect" - "testing" - "time" -) - -func TestRepositoriesService_ListContributorsStats(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/stats/contributors", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - - fmt.Fprint(w, ` -[ - { - "author": { - "id": 1 - }, - "total": 135, - "weeks": [ - { - "w": 1367712000, - "a": 6898, - "d": 77, - "c": 10 - } - ] - } -] -`) - }) - - stats, _, err := client.Repositories.ListContributorsStats("o", "r") - if err != nil { - t.Errorf("RepositoriesService.ListContributorsStats returned error: %v", err) - } - - want := []ContributorStats{ - { - Author: &Contributor{ - ID: Int(1), - }, - Total: Int(135), - Weeks: []WeeklyStats{ - { - Week: &Timestamp{time.Date(2013, 05, 05, 00, 00, 00, 0, time.UTC).Local()}, - Additions: Int(6898), - Deletions: Int(77), - Commits: Int(10), - }, - }, - }, - } - - if !reflect.DeepEqual(stats, want) { - t.Errorf("RepositoriesService.ListContributorsStats returned %+v, want %+v", stats, want) - } -} - -func TestRepositoriesService_ListCommitActivity(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/stats/commit_activity", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - - fmt.Fprint(w, ` -[ - { - "days": [0, 3, 26, 20, 39, 1, 0], - "total": 89, - "week": 1336280400 - } -] -`) - }) - - activity, _, err := client.Repositories.ListCommitActivity("o", "r") - if err != nil { - t.Errorf("RepositoriesService.ListCommitActivity returned error: %v", err) - } - - want := []WeeklyCommitActivity{ - { - Days: []int{0, 3, 26, 20, 39, 1, 0}, - Total: Int(89), - Week: &Timestamp{time.Date(2012, 05, 06, 05, 00, 00, 0, time.UTC).Local()}, - }, - } - - if !reflect.DeepEqual(activity, want) { - t.Errorf("RepositoriesService.ListCommitActivity returned %+v, want %+v", activity, want) - } -} - -func TestRepositoriesService_ListCodeFrequency(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/stats/code_frequency", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - - fmt.Fprint(w, `[[1302998400, 1124, -435]]`) - }) - - code, _, err := client.Repositories.ListCodeFrequency("o", "r") - if err != nil { - t.Errorf("RepositoriesService.ListCodeFrequency returned error: %v", err) - } - - want := []WeeklyStats{{ - Week: &Timestamp{time.Date(2011, 04, 17, 00, 00, 00, 0, time.UTC).Local()}, - Additions: Int(1124), - Deletions: Int(-435), - }} - - if !reflect.DeepEqual(code, want) { - t.Errorf("RepositoriesService.ListCodeFrequency returned %+v, want %+v", code, want) - } -} - -func TestRepositoriesService_Participation(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/stats/participation", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - - fmt.Fprint(w, ` -{ - "all": [ - 11,21,15,2,8,1,8,23,17,21,11,10,33, - 91,38,34,22,23,32,3,43,87,71,18,13,5, - 13,16,66,27,12,45,110,117,13,8,18,9,19, - 26,39,12,20,31,46,91,45,10,24,9,29,7 - ], - "owner": [ - 3,2,3,0,2,0,5,14,7,9,1,5,0, - 48,19,2,0,1,10,2,23,40,35,8,8,2, - 10,6,30,0,2,9,53,104,3,3,10,4,7, - 11,21,4,4,22,26,63,11,2,14,1,10,3 - ] -} -`) - }) - - participation, _, err := client.Repositories.ListParticipation("o", "r") - if err != nil { - t.Errorf("RepositoriesService.ListParticipation returned error: %v", err) - } - - want := &RepositoryParticipation{ - All: []int{ - 11, 21, 15, 2, 8, 1, 8, 23, 17, 21, 11, 10, 33, - 91, 38, 34, 22, 23, 32, 3, 43, 87, 71, 18, 13, 5, - 13, 16, 66, 27, 12, 45, 110, 117, 13, 8, 18, 9, 19, - 26, 39, 12, 20, 31, 46, 91, 45, 10, 24, 9, 29, 7, - }, - Owner: []int{ - 3, 2, 3, 0, 2, 0, 5, 14, 7, 9, 1, 5, 0, - 48, 19, 2, 0, 1, 10, 2, 23, 40, 35, 8, 8, 2, - 10, 6, 30, 0, 2, 9, 53, 104, 3, 3, 10, 4, 7, - 11, 21, 4, 4, 22, 26, 63, 11, 2, 14, 1, 10, 3, - }, - } - - if !reflect.DeepEqual(participation, want) { - t.Errorf("RepositoriesService.ListParticipation returned %+v, want %+v", participation, want) - } -} - -func TestRepositoriesService_ListPunchCard(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/stats/punch_card", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - - fmt.Fprint(w, `[ - [0, 0, 5], - [0, 1, 43], - [0, 2, 21] - ]`) - }) - - card, _, err := client.Repositories.ListPunchCard("o", "r") - if err != nil { - t.Errorf("RepositoriesService.ListPunchCard returned error: %v", err) - } - - want := []PunchCard{ - {Day: Int(0), Hour: Int(0), Commits: Int(5)}, - {Day: Int(0), Hour: Int(1), Commits: Int(43)}, - {Day: Int(0), Hour: Int(2), Commits: Int(21)}, - } - - if !reflect.DeepEqual(card, want) { - t.Errorf("RepositoriesService.ListPunchCard returned %+v, want %+v", card, want) - } -} diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/repos_statuses_test.go b/Godeps/_workspace/src/github.com/google/go-github/github/repos_statuses_test.go deleted file mode 100644 index 8b230528c..000000000 --- a/Godeps/_workspace/src/github.com/google/go-github/github/repos_statuses_test.go +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestRepositoriesService_ListStatuses(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/commits/r/statuses", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"page": "2"}) - fmt.Fprint(w, `[{"id":1}]`) - }) - - opt := &ListOptions{Page: 2} - statuses, _, err := client.Repositories.ListStatuses("o", "r", "r", opt) - if err != nil { - t.Errorf("Repositories.ListStatuses returned error: %v", err) - } - - want := []RepoStatus{{ID: Int(1)}} - if !reflect.DeepEqual(statuses, want) { - t.Errorf("Repositories.ListStatuses returned %+v, want %+v", statuses, want) - } -} - -func TestRepositoriesService_ListStatuses_invalidOwner(t *testing.T) { - _, _, err := client.Repositories.ListStatuses("%", "r", "r", nil) - testURLParseError(t, err) -} - -func TestRepositoriesService_CreateStatus(t *testing.T) { - setup() - defer teardown() - - input := &RepoStatus{State: String("s"), TargetURL: String("t"), Description: String("d")} - - mux.HandleFunc("/repos/o/r/statuses/r", func(w http.ResponseWriter, r *http.Request) { - v := new(RepoStatus) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "POST") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - fmt.Fprint(w, `{"id":1}`) - }) - - status, _, err := client.Repositories.CreateStatus("o", "r", "r", input) - if err != nil { - t.Errorf("Repositories.CreateStatus returned error: %v", err) - } - - want := &RepoStatus{ID: Int(1)} - if !reflect.DeepEqual(status, want) { - t.Errorf("Repositories.CreateStatus returned %+v, want %+v", status, want) - } -} - -func TestRepositoriesService_CreateStatus_invalidOwner(t *testing.T) { - _, _, err := client.Repositories.CreateStatus("%", "r", "r", nil) - testURLParseError(t, err) -} - -func TestRepositoriesService_GetCombinedStatus(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/commits/r/status", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"page": "2"}) - fmt.Fprint(w, `{"state":"success", "statuses":[{"id":1}]}`) - }) - - opt := &ListOptions{Page: 2} - status, _, err := client.Repositories.GetCombinedStatus("o", "r", "r", opt) - if err != nil { - t.Errorf("Repositories.GetCombinedStatus returned error: %v", err) - } - - want := &CombinedStatus{State: String("success"), Statuses: []RepoStatus{{ID: Int(1)}}} - if !reflect.DeepEqual(status, want) { - t.Errorf("Repositories.GetCombinedStatus returned %+v, want %+v", status, want) - } -} diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/repos_test.go b/Godeps/_workspace/src/github.com/google/go-github/github/repos_test.go deleted file mode 100644 index 6e98e2845..000000000 --- a/Godeps/_workspace/src/github.com/google/go-github/github/repos_test.go +++ /dev/null @@ -1,409 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestRepositoriesService_List_authenticatedUser(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/user/repos", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeLicensesPreview) - fmt.Fprint(w, `[{"id":1},{"id":2}]`) - }) - - repos, _, err := client.Repositories.List("", nil) - if err != nil { - t.Errorf("Repositories.List returned error: %v", err) - } - - want := []Repository{{ID: Int(1)}, {ID: Int(2)}} - if !reflect.DeepEqual(repos, want) { - t.Errorf("Repositories.List returned %+v, want %+v", repos, want) - } -} - -func TestRepositoriesService_List_specifiedUser(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/users/u/repos", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeLicensesPreview) - testFormValues(t, r, values{ - "type": "owner", - "sort": "created", - "direction": "asc", - "page": "2", - }) - fmt.Fprint(w, `[{"id":1}]`) - }) - - opt := &RepositoryListOptions{"owner", "created", "asc", ListOptions{Page: 2}} - repos, _, err := client.Repositories.List("u", opt) - if err != nil { - t.Errorf("Repositories.List returned error: %v", err) - } - - want := []Repository{{ID: Int(1)}} - if !reflect.DeepEqual(repos, want) { - t.Errorf("Repositories.List returned %+v, want %+v", repos, want) - } -} - -func TestRepositoriesService_List_invalidUser(t *testing.T) { - _, _, err := client.Repositories.List("%", nil) - testURLParseError(t, err) -} - -func TestRepositoriesService_ListByOrg(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/orgs/o/repos", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeLicensesPreview) - testFormValues(t, r, values{ - "type": "forks", - "page": "2", - }) - fmt.Fprint(w, `[{"id":1}]`) - }) - - opt := &RepositoryListByOrgOptions{"forks", ListOptions{Page: 2}} - repos, _, err := client.Repositories.ListByOrg("o", opt) - if err != nil { - t.Errorf("Repositories.ListByOrg returned error: %v", err) - } - - want := []Repository{{ID: Int(1)}} - if !reflect.DeepEqual(repos, want) { - t.Errorf("Repositories.ListByOrg returned %+v, want %+v", repos, want) - } -} - -func TestRepositoriesService_ListByOrg_invalidOrg(t *testing.T) { - _, _, err := client.Repositories.ListByOrg("%", nil) - testURLParseError(t, err) -} - -func TestRepositoriesService_ListAll(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repositories", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "since": "1", - "page": "2", - "per_page": "3", - }) - fmt.Fprint(w, `[{"id":1}]`) - }) - - opt := &RepositoryListAllOptions{1, ListOptions{2, 3}} - repos, _, err := client.Repositories.ListAll(opt) - if err != nil { - t.Errorf("Repositories.ListAll returned error: %v", err) - } - - want := []Repository{{ID: Int(1)}} - if !reflect.DeepEqual(repos, want) { - t.Errorf("Repositories.ListAll returned %+v, want %+v", repos, want) - } -} - -func TestRepositoriesService_Create_user(t *testing.T) { - setup() - defer teardown() - - input := &Repository{Name: String("n")} - - mux.HandleFunc("/user/repos", func(w http.ResponseWriter, r *http.Request) { - v := new(Repository) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "POST") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"id":1}`) - }) - - repo, _, err := client.Repositories.Create("", input) - if err != nil { - t.Errorf("Repositories.Create returned error: %v", err) - } - - want := &Repository{ID: Int(1)} - if !reflect.DeepEqual(repo, want) { - t.Errorf("Repositories.Create returned %+v, want %+v", repo, want) - } -} - -func TestRepositoriesService_Create_org(t *testing.T) { - setup() - defer teardown() - - input := &Repository{Name: String("n")} - - mux.HandleFunc("/orgs/o/repos", func(w http.ResponseWriter, r *http.Request) { - v := new(Repository) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "POST") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"id":1}`) - }) - - repo, _, err := client.Repositories.Create("o", input) - if err != nil { - t.Errorf("Repositories.Create returned error: %v", err) - } - - want := &Repository{ID: Int(1)} - if !reflect.DeepEqual(repo, want) { - t.Errorf("Repositories.Create returned %+v, want %+v", repo, want) - } -} - -func TestRepositoriesService_Create_invalidOrg(t *testing.T) { - _, _, err := client.Repositories.Create("%", nil) - testURLParseError(t, err) -} - -func TestRepositoriesService_Get(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeLicensesPreview) - fmt.Fprint(w, `{"id":1,"name":"n","description":"d","owner":{"login":"l"},"license":{"key":"mit"}}`) - }) - - repo, _, err := client.Repositories.Get("o", "r") - if err != nil { - t.Errorf("Repositories.Get returned error: %v", err) - } - - want := &Repository{ID: Int(1), Name: String("n"), Description: String("d"), Owner: &User{Login: String("l")}, License: &License{Key: String("mit")}} - if !reflect.DeepEqual(repo, want) { - t.Errorf("Repositories.Get returned %+v, want %+v", repo, want) - } -} - -func TestRepositoriesService_Edit(t *testing.T) { - setup() - defer teardown() - - i := true - input := &Repository{HasIssues: &i} - - mux.HandleFunc("/repos/o/r", func(w http.ResponseWriter, r *http.Request) { - v := new(Repository) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "PATCH") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - fmt.Fprint(w, `{"id":1}`) - }) - - repo, _, err := client.Repositories.Edit("o", "r", input) - if err != nil { - t.Errorf("Repositories.Edit returned error: %v", err) - } - - want := &Repository{ID: Int(1)} - if !reflect.DeepEqual(repo, want) { - t.Errorf("Repositories.Edit returned %+v, want %+v", repo, want) - } -} - -func TestRepositoriesService_Delete(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - }) - - _, err := client.Repositories.Delete("o", "r") - if err != nil { - t.Errorf("Repositories.Delete returned error: %v", err) - } -} - -func TestRepositoriesService_Get_invalidOwner(t *testing.T) { - _, _, err := client.Repositories.Get("%", "r") - testURLParseError(t, err) -} - -func TestRepositoriesService_Edit_invalidOwner(t *testing.T) { - _, _, err := client.Repositories.Edit("%", "r", nil) - testURLParseError(t, err) -} - -func TestRepositoriesService_ListContributors(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/contributors", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "anon": "true", - "page": "2", - }) - fmt.Fprint(w, `[{"contributions":42}]`) - }) - - opts := &ListContributorsOptions{Anon: "true", ListOptions: ListOptions{Page: 2}} - contributors, _, err := client.Repositories.ListContributors("o", "r", opts) - - if err != nil { - t.Errorf("Repositories.ListContributors returned error: %v", err) - } - - want := []Contributor{{Contributions: Int(42)}} - if !reflect.DeepEqual(contributors, want) { - t.Errorf("Repositories.ListContributors returned %+v, want %+v", contributors, want) - } -} - -func TestRepositoriesService_ListLanguages(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/languages", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"go":1}`) - }) - - languages, _, err := client.Repositories.ListLanguages("o", "r") - if err != nil { - t.Errorf("Repositories.ListLanguages returned error: %v", err) - } - - want := map[string]int{"go": 1} - if !reflect.DeepEqual(languages, want) { - t.Errorf("Repositories.ListLanguages returned %+v, want %+v", languages, want) - } -} - -func TestRepositoriesService_ListTeams(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/teams", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"page": "2"}) - fmt.Fprint(w, `[{"id":1}]`) - }) - - opt := &ListOptions{Page: 2} - teams, _, err := client.Repositories.ListTeams("o", "r", opt) - if err != nil { - t.Errorf("Repositories.ListTeams returned error: %v", err) - } - - want := []Team{{ID: Int(1)}} - if !reflect.DeepEqual(teams, want) { - t.Errorf("Repositories.ListTeams returned %+v, want %+v", teams, want) - } -} - -func TestRepositoriesService_ListTags(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/tags", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"page": "2"}) - fmt.Fprint(w, `[{"name":"n", "commit" : {"sha" : "s", "url" : "u"}, "zipball_url": "z", "tarball_url": "t"}]`) - }) - - opt := &ListOptions{Page: 2} - tags, _, err := client.Repositories.ListTags("o", "r", opt) - if err != nil { - t.Errorf("Repositories.ListTags returned error: %v", err) - } - - want := []RepositoryTag{ - { - Name: String("n"), - Commit: &Commit{ - SHA: String("s"), - URL: String("u"), - }, - ZipballURL: String("z"), - TarballURL: String("t"), - }, - } - if !reflect.DeepEqual(tags, want) { - t.Errorf("Repositories.ListTags returned %+v, want %+v", tags, want) - } -} - -func TestRepositoriesService_ListBranches(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/branches", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"page": "2"}) - fmt.Fprint(w, `[{"name":"master", "commit" : {"sha" : "a57781", "url" : "https://api.github.com/repos/o/r/commits/a57781"}}]`) - }) - - opt := &ListOptions{Page: 2} - branches, _, err := client.Repositories.ListBranches("o", "r", opt) - if err != nil { - t.Errorf("Repositories.ListBranches returned error: %v", err) - } - - want := []Branch{{Name: String("master"), Commit: &Commit{SHA: String("a57781"), URL: String("https://api.github.com/repos/o/r/commits/a57781")}}} - if !reflect.DeepEqual(branches, want) { - t.Errorf("Repositories.ListBranches returned %+v, want %+v", branches, want) - } -} - -func TestRepositoriesService_GetBranch(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/branches/b", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"name":"n", "commit":{"sha":"s"}}`) - }) - - branch, _, err := client.Repositories.GetBranch("o", "r", "b") - if err != nil { - t.Errorf("Repositories.GetBranch returned error: %v", err) - } - - want := &Branch{Name: String("n"), Commit: &Commit{SHA: String("s")}} - if !reflect.DeepEqual(branch, want) { - t.Errorf("Repositories.GetBranch returned %+v, want %+v", branch, want) - } -} - -func TestRepositoriesService_ListLanguages_invalidOwner(t *testing.T) { - _, _, err := client.Repositories.ListLanguages("%", "%") - testURLParseError(t, err) -} diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/search_test.go b/Godeps/_workspace/src/github.com/google/go-github/github/search_test.go deleted file mode 100644 index 3cfd16243..000000000 --- a/Godeps/_workspace/src/github.com/google/go-github/github/search_test.go +++ /dev/null @@ -1,196 +0,0 @@ -package github - -import ( - "fmt" - "net/http" - "reflect" - - "testing" -) - -func TestSearchService_Repositories(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/search/repositories", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "q": "blah", - "sort": "forks", - "order": "desc", - "page": "2", - "per_page": "2", - }) - - fmt.Fprint(w, `{"total_count": 4, "items": [{"id":1},{"id":2}]}`) - }) - - opts := &SearchOptions{Sort: "forks", Order: "desc", ListOptions: ListOptions{Page: 2, PerPage: 2}} - result, _, err := client.Search.Repositories("blah", opts) - if err != nil { - t.Errorf("Search.Repositories returned error: %v", err) - } - - want := &RepositoriesSearchResult{ - Total: Int(4), - Repositories: []Repository{{ID: Int(1)}, {ID: Int(2)}}, - } - if !reflect.DeepEqual(result, want) { - t.Errorf("Search.Repositories returned %+v, want %+v", result, want) - } -} - -func TestSearchService_Issues(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/search/issues", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "q": "blah", - "sort": "forks", - "order": "desc", - "page": "2", - "per_page": "2", - }) - - fmt.Fprint(w, `{"total_count": 4, "items": [{"number":1},{"number":2}]}`) - }) - - opts := &SearchOptions{Sort: "forks", Order: "desc", ListOptions: ListOptions{Page: 2, PerPage: 2}} - result, _, err := client.Search.Issues("blah", opts) - if err != nil { - t.Errorf("Search.Issues returned error: %v", err) - } - - want := &IssuesSearchResult{ - Total: Int(4), - Issues: []Issue{{Number: Int(1)}, {Number: Int(2)}}, - } - if !reflect.DeepEqual(result, want) { - t.Errorf("Search.Issues returned %+v, want %+v", result, want) - } -} - -func TestSearchService_Users(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/search/users", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "q": "blah", - "sort": "forks", - "order": "desc", - "page": "2", - "per_page": "2", - }) - - fmt.Fprint(w, `{"total_count": 4, "items": [{"id":1},{"id":2}]}`) - }) - - opts := &SearchOptions{Sort: "forks", Order: "desc", ListOptions: ListOptions{Page: 2, PerPage: 2}} - result, _, err := client.Search.Users("blah", opts) - if err != nil { - t.Errorf("Search.Issues returned error: %v", err) - } - - want := &UsersSearchResult{ - Total: Int(4), - Users: []User{{ID: Int(1)}, {ID: Int(2)}}, - } - if !reflect.DeepEqual(result, want) { - t.Errorf("Search.Users returned %+v, want %+v", result, want) - } -} - -func TestSearchService_Code(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/search/code", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "q": "blah", - "sort": "forks", - "order": "desc", - "page": "2", - "per_page": "2", - }) - - fmt.Fprint(w, `{"total_count": 4, "items": [{"name":"1"},{"name":"2"}]}`) - }) - - opts := &SearchOptions{Sort: "forks", Order: "desc", ListOptions: ListOptions{Page: 2, PerPage: 2}} - result, _, err := client.Search.Code("blah", opts) - if err != nil { - t.Errorf("Search.Code returned error: %v", err) - } - - want := &CodeSearchResult{ - Total: Int(4), - CodeResults: []CodeResult{{Name: String("1")}, {Name: String("2")}}, - } - if !reflect.DeepEqual(result, want) { - t.Errorf("Search.Code returned %+v, want %+v", result, want) - } -} - -func TestSearchService_CodeTextMatch(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/search/code", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - - textMatchResponse := ` - { - "total_count": 1, - "items": [ - { - "name":"gopher1", - "text_matches": [ - { - "fragment": "I'm afraid my friend what you have found\nIs a gopher who lives to feed", - "matches": [ - { - "text": "gopher", - "indices": [ - 14, - 21 - ] - } - ] - } - ] - } - ] - } - ` - - fmt.Fprint(w, textMatchResponse) - }) - - opts := &SearchOptions{Sort: "forks", Order: "desc", ListOptions: ListOptions{Page: 2, PerPage: 2}, TextMatch: true} - result, _, err := client.Search.Code("blah", opts) - if err != nil { - t.Errorf("Search.Code returned error: %v", err) - } - - wantedCodeResult := CodeResult{ - Name: String("gopher1"), - TextMatches: []TextMatch{{ - Fragment: String("I'm afraid my friend what you have found\nIs a gopher who lives to feed"), - Matches: []Match{{Text: String("gopher"), Indices: []int{14, 21}}}, - }, - }, - } - - want := &CodeSearchResult{ - Total: Int(1), - CodeResults: []CodeResult{wantedCodeResult}, - } - if !reflect.DeepEqual(result, want) { - t.Errorf("Search.Code returned %+v, want %+v", result, want) - } -} diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/strings_test.go b/Godeps/_workspace/src/github.com/google/go-github/github/strings_test.go deleted file mode 100644 index a393eb6cf..000000000 --- a/Godeps/_workspace/src/github.com/google/go-github/github/strings_test.go +++ /dev/null @@ -1,137 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "fmt" - "testing" - "time" -) - -func TestStringify(t *testing.T) { - var nilPointer *string - - var tests = []struct { - in interface{} - out string - }{ - // basic types - {"foo", `"foo"`}, - {123, `123`}, - {1.5, `1.5`}, - {false, `false`}, - { - []string{"a", "b"}, - `["a" "b"]`, - }, - { - struct { - A []string - }{nil}, - // nil slice is skipped - `{}`, - }, - { - struct { - A string - }{"foo"}, - // structs not of a named type get no prefix - `{A:"foo"}`, - }, - - // pointers - {nilPointer, ``}, - {String("foo"), `"foo"`}, - {Int(123), `123`}, - {Bool(false), `false`}, - { - []*string{String("a"), String("b")}, - `["a" "b"]`, - }, - - // actual GitHub structs - { - Timestamp{time.Date(2006, 01, 02, 15, 04, 05, 0, time.UTC)}, - `github.Timestamp{2006-01-02 15:04:05 +0000 UTC}`, - }, - { - &Timestamp{time.Date(2006, 01, 02, 15, 04, 05, 0, time.UTC)}, - `github.Timestamp{2006-01-02 15:04:05 +0000 UTC}`, - }, - { - User{ID: Int(123), Name: String("n")}, - `github.User{ID:123, Name:"n"}`, - }, - { - Repository{Owner: &User{ID: Int(123)}}, - `github.Repository{Owner:github.User{ID:123}}`, - }, - } - - for i, tt := range tests { - s := Stringify(tt.in) - if s != tt.out { - t.Errorf("%d. Stringify(%q) => %q, want %q", i, tt.in, s, tt.out) - } - } -} - -// Directly test the String() methods on various GitHub types. We don't do an -// exaustive test of all the various field types, since TestStringify() above -// takes care of that. Rather, we just make sure that Stringify() is being -// used to build the strings, which we do by verifying that pointers are -// stringified as their underlying value. -func TestString(t *testing.T) { - var tests = []struct { - in interface{} - out string - }{ - {CodeResult{Name: String("n")}, `github.CodeResult{Name:"n"}`}, - {CommitAuthor{Name: String("n")}, `github.CommitAuthor{Name:"n"}`}, - {CommitFile{SHA: String("s")}, `github.CommitFile{SHA:"s"}`}, - {CommitStats{Total: Int(1)}, `github.CommitStats{Total:1}`}, - {CommitsComparison{TotalCommits: Int(1)}, `github.CommitsComparison{TotalCommits:1}`}, - {Commit{SHA: String("s")}, `github.Commit{SHA:"s"}`}, - {Event{ID: String("1")}, `github.Event{ID:"1"}`}, - {GistComment{ID: Int(1)}, `github.GistComment{ID:1}`}, - {GistFile{Size: Int(1)}, `github.GistFile{Size:1}`}, - {Gist{ID: String("1")}, `github.Gist{ID:"1", Files:map[]}`}, - {GitObject{SHA: String("s")}, `github.GitObject{SHA:"s"}`}, - {Gitignore{Name: String("n")}, `github.Gitignore{Name:"n"}`}, - {Hook{ID: Int(1)}, `github.Hook{Config:map[], ID:1}`}, - {IssueComment{ID: Int(1)}, `github.IssueComment{ID:1}`}, - {Issue{Number: Int(1)}, `github.Issue{Number:1}`}, - {Key{ID: Int(1)}, `github.Key{ID:1}`}, - {Label{Name: String("l")}, "l"}, - {Organization{ID: Int(1)}, `github.Organization{ID:1}`}, - {PullRequestComment{ID: Int(1)}, `github.PullRequestComment{ID:1}`}, - {PullRequest{Number: Int(1)}, `github.PullRequest{Number:1}`}, - {PushEventCommit{SHA: String("s")}, `github.PushEventCommit{SHA:"s"}`}, - {PushEvent{PushID: Int(1)}, `github.PushEvent{PushID:1}`}, - {Reference{Ref: String("r")}, `github.Reference{Ref:"r"}`}, - {ReleaseAsset{ID: Int(1)}, `github.ReleaseAsset{ID:1}`}, - {RepoStatus{ID: Int(1)}, `github.RepoStatus{ID:1}`}, - {RepositoryComment{ID: Int(1)}, `github.RepositoryComment{ID:1}`}, - {RepositoryCommit{SHA: String("s")}, `github.RepositoryCommit{SHA:"s"}`}, - {RepositoryContent{Name: String("n")}, `github.RepositoryContent{Name:"n"}`}, - {RepositoryRelease{ID: Int(1)}, `github.RepositoryRelease{ID:1}`}, - {Repository{ID: Int(1)}, `github.Repository{ID:1}`}, - {Team{ID: Int(1)}, `github.Team{ID:1}`}, - {TreeEntry{SHA: String("s")}, `github.TreeEntry{SHA:"s"}`}, - {Tree{SHA: String("s")}, `github.Tree{SHA:"s"}`}, - {User{ID: Int(1)}, `github.User{ID:1}`}, - {WebHookAuthor{Name: String("n")}, `github.WebHookAuthor{Name:"n"}`}, - {WebHookCommit{ID: String("1")}, `github.WebHookCommit{ID:"1"}`}, - {WebHookPayload{Ref: String("r")}, `github.WebHookPayload{Ref:"r"}`}, - } - - for i, tt := range tests { - s := tt.in.(fmt.Stringer).String() - if s != tt.out { - t.Errorf("%d. String() => %q, want %q", i, tt.in, tt.out) - } - } -} diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/timestamp_test.go b/Godeps/_workspace/src/github.com/google/go-github/github/timestamp_test.go deleted file mode 100644 index 12376c51a..000000000 --- a/Godeps/_workspace/src/github.com/google/go-github/github/timestamp_test.go +++ /dev/null @@ -1,181 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "encoding/json" - "fmt" - "testing" - "time" -) - -const ( - emptyTimeStr = `"0001-01-01T00:00:00Z"` - referenceTimeStr = `"2006-01-02T15:04:05Z"` - referenceUnixTimeStr = `1136214245` -) - -var ( - referenceTime = time.Date(2006, 01, 02, 15, 04, 05, 0, time.UTC) - unixOrigin = time.Unix(0, 0).In(time.UTC) -) - -func TestTimestamp_Marshal(t *testing.T) { - testCases := []struct { - desc string - data Timestamp - want string - wantErr bool - equal bool - }{ - {"Reference", Timestamp{referenceTime}, referenceTimeStr, false, true}, - {"Empty", Timestamp{}, emptyTimeStr, false, true}, - {"Mismatch", Timestamp{}, referenceTimeStr, false, false}, - } - for _, tc := range testCases { - out, err := json.Marshal(tc.data) - if gotErr := err != nil; gotErr != tc.wantErr { - t.Errorf("%s: gotErr=%v, wantErr=%v, err=%v", tc.desc, gotErr, tc.wantErr, err) - } - got := string(out) - equal := got == tc.want - if (got == tc.want) != tc.equal { - t.Errorf("%s: got=%s, want=%s, equal=%v, want=%v", tc.desc, got, tc.want, equal, tc.equal) - } - } -} - -func TestTimestamp_Unmarshal(t *testing.T) { - testCases := []struct { - desc string - data string - want Timestamp - wantErr bool - equal bool - }{ - {"Reference", referenceTimeStr, Timestamp{referenceTime}, false, true}, - {"ReferenceUnix", `1136214245`, Timestamp{referenceTime}, false, true}, - {"Empty", emptyTimeStr, Timestamp{}, false, true}, - {"UnixStart", `0`, Timestamp{unixOrigin}, false, true}, - {"Mismatch", referenceTimeStr, Timestamp{}, false, false}, - {"MismatchUnix", `0`, Timestamp{}, false, false}, - {"Invalid", `"asdf"`, Timestamp{referenceTime}, true, false}, - } - for _, tc := range testCases { - var got Timestamp - err := json.Unmarshal([]byte(tc.data), &got) - if gotErr := err != nil; gotErr != tc.wantErr { - t.Errorf("%s: gotErr=%v, wantErr=%v, err=%v", tc.desc, gotErr, tc.wantErr, err) - continue - } - equal := got.Equal(tc.want) - if equal != tc.equal { - t.Errorf("%s: got=%#v, want=%#v, equal=%v, want=%v", tc.desc, got, tc.want, equal, tc.equal) - } - } -} - -func TestTimstamp_MarshalReflexivity(t *testing.T) { - testCases := []struct { - desc string - data Timestamp - }{ - {"Reference", Timestamp{referenceTime}}, - {"Empty", Timestamp{}}, - } - for _, tc := range testCases { - data, err := json.Marshal(tc.data) - if err != nil { - t.Errorf("%s: Marshal err=%v", tc.desc, err) - } - var got Timestamp - err = json.Unmarshal(data, &got) - if !got.Equal(tc.data) { - t.Errorf("%s: %+v != %+v", tc.desc, got, data) - } - } -} - -type WrappedTimestamp struct { - A int - Time Timestamp -} - -func TestWrappedTimstamp_Marshal(t *testing.T) { - testCases := []struct { - desc string - data WrappedTimestamp - want string - wantErr bool - equal bool - }{ - {"Reference", WrappedTimestamp{0, Timestamp{referenceTime}}, fmt.Sprintf(`{"A":0,"Time":%s}`, referenceTimeStr), false, true}, - {"Empty", WrappedTimestamp{}, fmt.Sprintf(`{"A":0,"Time":%s}`, emptyTimeStr), false, true}, - {"Mismatch", WrappedTimestamp{}, fmt.Sprintf(`{"A":0,"Time":%s}`, referenceTimeStr), false, false}, - } - for _, tc := range testCases { - out, err := json.Marshal(tc.data) - if gotErr := err != nil; gotErr != tc.wantErr { - t.Errorf("%s: gotErr=%v, wantErr=%v, err=%v", tc.desc, gotErr, tc.wantErr, err) - } - got := string(out) - equal := got == tc.want - if equal != tc.equal { - t.Errorf("%s: got=%s, want=%s, equal=%v, want=%v", tc.desc, got, tc.want, equal, tc.equal) - } - } -} - -func TestWrappedTimstamp_Unmarshal(t *testing.T) { - testCases := []struct { - desc string - data string - want WrappedTimestamp - wantErr bool - equal bool - }{ - {"Reference", referenceTimeStr, WrappedTimestamp{0, Timestamp{referenceTime}}, false, true}, - {"ReferenceUnix", referenceUnixTimeStr, WrappedTimestamp{0, Timestamp{referenceTime}}, false, true}, - {"Empty", emptyTimeStr, WrappedTimestamp{0, Timestamp{}}, false, true}, - {"UnixStart", `0`, WrappedTimestamp{0, Timestamp{unixOrigin}}, false, true}, - {"Mismatch", referenceTimeStr, WrappedTimestamp{0, Timestamp{}}, false, false}, - {"MismatchUnix", `0`, WrappedTimestamp{0, Timestamp{}}, false, false}, - {"Invalid", `"asdf"`, WrappedTimestamp{0, Timestamp{referenceTime}}, true, false}, - } - for _, tc := range testCases { - var got Timestamp - err := json.Unmarshal([]byte(tc.data), &got) - if gotErr := err != nil; gotErr != tc.wantErr { - t.Errorf("%s: gotErr=%v, wantErr=%v, err=%v", tc.desc, gotErr, tc.wantErr, err) - continue - } - equal := got.Time.Equal(tc.want.Time.Time) - if equal != tc.equal { - t.Errorf("%s: got=%#v, want=%#v, equal=%v, want=%v", tc.desc, got, tc.want, equal, tc.equal) - } - } -} - -func TestWrappedTimstamp_MarshalReflexivity(t *testing.T) { - testCases := []struct { - desc string - data WrappedTimestamp - }{ - {"Reference", WrappedTimestamp{0, Timestamp{referenceTime}}}, - {"Empty", WrappedTimestamp{0, Timestamp{}}}, - } - for _, tc := range testCases { - bytes, err := json.Marshal(tc.data) - if err != nil { - t.Errorf("%s: Marshal err=%v", tc.desc, err) - } - var got WrappedTimestamp - err = json.Unmarshal(bytes, &got) - if !got.Time.Equal(tc.data.Time) { - t.Errorf("%s: %+v != %+v", tc.desc, got, tc.data) - } - } -} diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/users.go b/Godeps/_workspace/src/github.com/google/go-github/github/users.go index 95cca6b70..a041bbf98 100644 --- a/Godeps/_workspace/src/github.com/google/go-github/github/users.go +++ b/Godeps/_workspace/src/github.com/google/go-github/github/users.go @@ -113,7 +113,7 @@ func (s *UsersService) Edit(user *User) (*User, *Response, error) { return uResp, resp, err } -// UserListOptions specifies optional parameters to the UsersService.List +// UserListOptions specifies optional parameters to the UsersService.ListAll // method. type UserListOptions struct { // ID of the last user seen diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/users_administration_test.go b/Godeps/_workspace/src/github.com/google/go-github/github/users_administration_test.go deleted file mode 100644 index d415f4d4a..000000000 --- a/Godeps/_workspace/src/github.com/google/go-github/github/users_administration_test.go +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright 2014 The go-github 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 github - -import ( - "net/http" - "testing" -) - -func TestUsersService_PromoteSiteAdmin(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/users/u/site_admin", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "PUT") - w.WriteHeader(http.StatusNoContent) - }) - - _, err := client.Users.PromoteSiteAdmin("u") - if err != nil { - t.Errorf("Users.PromoteSiteAdmin returned error: %v", err) - } -} - -func TestUsersService_DemoteSiteAdmin(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/users/u/site_admin", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - w.WriteHeader(http.StatusNoContent) - }) - - _, err := client.Users.DemoteSiteAdmin("u") - if err != nil { - t.Errorf("Users.DemoteSiteAdmin returned error: %v", err) - } -} - -func TestUsersService_Suspend(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/users/u/suspended", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "PUT") - w.WriteHeader(http.StatusNoContent) - }) - - _, err := client.Users.Suspend("u") - if err != nil { - t.Errorf("Users.Suspend returned error: %v", err) - } -} - -func TestUsersService_Unsuspend(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/users/u/suspended", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - w.WriteHeader(http.StatusNoContent) - }) - - _, err := client.Users.Unsuspend("u") - if err != nil { - t.Errorf("Users.Unsuspend returned error: %v", err) - } -} diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/users_emails_test.go b/Godeps/_workspace/src/github.com/google/go-github/github/users_emails_test.go deleted file mode 100644 index 7eb650860..000000000 --- a/Godeps/_workspace/src/github.com/google/go-github/github/users_emails_test.go +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestUsersService_ListEmails(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/user/emails", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"page": "2"}) - fmt.Fprint(w, `[{ - "email": "user@example.com", - "verified": false, - "primary": true - }]`) - }) - - opt := &ListOptions{Page: 2} - emails, _, err := client.Users.ListEmails(opt) - if err != nil { - t.Errorf("Users.ListEmails returned error: %v", err) - } - - want := []UserEmail{{Email: String("user@example.com"), Verified: Bool(false), Primary: Bool(true)}} - if !reflect.DeepEqual(emails, want) { - t.Errorf("Users.ListEmails returned %+v, want %+v", emails, want) - } -} - -func TestUsersService_AddEmails(t *testing.T) { - setup() - defer teardown() - - input := []string{"new@example.com"} - - mux.HandleFunc("/user/emails", func(w http.ResponseWriter, r *http.Request) { - v := new([]string) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "POST") - if !reflect.DeepEqual(*v, input) { - t.Errorf("Request body = %+v, want %+v", *v, input) - } - - fmt.Fprint(w, `[{"email":"old@example.com"}, {"email":"new@example.com"}]`) - }) - - emails, _, err := client.Users.AddEmails(input) - if err != nil { - t.Errorf("Users.AddEmails returned error: %v", err) - } - - want := []UserEmail{ - {Email: String("old@example.com")}, - {Email: String("new@example.com")}, - } - if !reflect.DeepEqual(emails, want) { - t.Errorf("Users.AddEmails returned %+v, want %+v", emails, want) - } -} - -func TestUsersService_DeleteEmails(t *testing.T) { - setup() - defer teardown() - - input := []string{"user@example.com"} - - mux.HandleFunc("/user/emails", func(w http.ResponseWriter, r *http.Request) { - v := new([]string) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "DELETE") - if !reflect.DeepEqual(*v, input) { - t.Errorf("Request body = %+v, want %+v", *v, input) - } - }) - - _, err := client.Users.DeleteEmails(input) - if err != nil { - t.Errorf("Users.DeleteEmails returned error: %v", err) - } -} diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/users_followers_test.go b/Godeps/_workspace/src/github.com/google/go-github/github/users_followers_test.go deleted file mode 100644 index f4d24578e..000000000 --- a/Godeps/_workspace/src/github.com/google/go-github/github/users_followers_test.go +++ /dev/null @@ -1,222 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestUsersService_ListFollowers_authenticatedUser(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/user/followers", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"page": "2"}) - fmt.Fprint(w, `[{"id":1}]`) - }) - - opt := &ListOptions{Page: 2} - users, _, err := client.Users.ListFollowers("", opt) - if err != nil { - t.Errorf("Users.ListFollowers returned error: %v", err) - } - - want := []User{{ID: Int(1)}} - if !reflect.DeepEqual(users, want) { - t.Errorf("Users.ListFollowers returned %+v, want %+v", users, want) - } -} - -func TestUsersService_ListFollowers_specifiedUser(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/users/u/followers", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `[{"id":1}]`) - }) - - users, _, err := client.Users.ListFollowers("u", nil) - if err != nil { - t.Errorf("Users.ListFollowers returned error: %v", err) - } - - want := []User{{ID: Int(1)}} - if !reflect.DeepEqual(users, want) { - t.Errorf("Users.ListFollowers returned %+v, want %+v", users, want) - } -} - -func TestUsersService_ListFollowers_invalidUser(t *testing.T) { - _, _, err := client.Users.ListFollowers("%", nil) - testURLParseError(t, err) -} - -func TestUsersService_ListFollowing_authenticatedUser(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/user/following", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"page": "2"}) - fmt.Fprint(w, `[{"id":1}]`) - }) - - opts := &ListOptions{Page: 2} - users, _, err := client.Users.ListFollowing("", opts) - if err != nil { - t.Errorf("Users.ListFollowing returned error: %v", err) - } - - want := []User{{ID: Int(1)}} - if !reflect.DeepEqual(users, want) { - t.Errorf("Users.ListFollowing returned %+v, want %+v", users, want) - } -} - -func TestUsersService_ListFollowing_specifiedUser(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/users/u/following", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `[{"id":1}]`) - }) - - users, _, err := client.Users.ListFollowing("u", nil) - if err != nil { - t.Errorf("Users.ListFollowing returned error: %v", err) - } - - want := []User{{ID: Int(1)}} - if !reflect.DeepEqual(users, want) { - t.Errorf("Users.ListFollowing returned %+v, want %+v", users, want) - } -} - -func TestUsersService_ListFollowing_invalidUser(t *testing.T) { - _, _, err := client.Users.ListFollowing("%", nil) - testURLParseError(t, err) -} - -func TestUsersService_IsFollowing_authenticatedUser(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/user/following/t", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - w.WriteHeader(http.StatusNoContent) - }) - - following, _, err := client.Users.IsFollowing("", "t") - if err != nil { - t.Errorf("Users.IsFollowing returned error: %v", err) - } - if want := true; following != want { - t.Errorf("Users.IsFollowing returned %+v, want %+v", following, want) - } -} - -func TestUsersService_IsFollowing_specifiedUser(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/users/u/following/t", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - w.WriteHeader(http.StatusNoContent) - }) - - following, _, err := client.Users.IsFollowing("u", "t") - if err != nil { - t.Errorf("Users.IsFollowing returned error: %v", err) - } - if want := true; following != want { - t.Errorf("Users.IsFollowing returned %+v, want %+v", following, want) - } -} - -func TestUsersService_IsFollowing_false(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/users/u/following/t", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - w.WriteHeader(http.StatusNotFound) - }) - - following, _, err := client.Users.IsFollowing("u", "t") - if err != nil { - t.Errorf("Users.IsFollowing returned error: %v", err) - } - if want := false; following != want { - t.Errorf("Users.IsFollowing returned %+v, want %+v", following, want) - } -} - -func TestUsersService_IsFollowing_error(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/users/u/following/t", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - http.Error(w, "BadRequest", http.StatusBadRequest) - }) - - following, _, err := client.Users.IsFollowing("u", "t") - if err == nil { - t.Errorf("Expected HTTP 400 response") - } - if want := false; following != want { - t.Errorf("Users.IsFollowing returned %+v, want %+v", following, want) - } -} - -func TestUsersService_IsFollowing_invalidUser(t *testing.T) { - _, _, err := client.Users.IsFollowing("%", "%") - testURLParseError(t, err) -} - -func TestUsersService_Follow(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/user/following/u", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "PUT") - }) - - _, err := client.Users.Follow("u") - if err != nil { - t.Errorf("Users.Follow returned error: %v", err) - } -} - -func TestUsersService_Follow_invalidUser(t *testing.T) { - _, err := client.Users.Follow("%") - testURLParseError(t, err) -} - -func TestUsersService_Unfollow(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/user/following/u", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - }) - - _, err := client.Users.Unfollow("u") - if err != nil { - t.Errorf("Users.Follow returned error: %v", err) - } -} - -func TestUsersService_Unfollow_invalidUser(t *testing.T) { - _, err := client.Users.Unfollow("%") - testURLParseError(t, err) -} diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/users_keys_test.go b/Godeps/_workspace/src/github.com/google/go-github/github/users_keys_test.go deleted file mode 100644 index e47afd71d..000000000 --- a/Godeps/_workspace/src/github.com/google/go-github/github/users_keys_test.go +++ /dev/null @@ -1,124 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestUsersService_ListKeys_authenticatedUser(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/user/keys", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"page": "2"}) - fmt.Fprint(w, `[{"id":1}]`) - }) - - opt := &ListOptions{Page: 2} - keys, _, err := client.Users.ListKeys("", opt) - if err != nil { - t.Errorf("Users.ListKeys returned error: %v", err) - } - - want := []Key{{ID: Int(1)}} - if !reflect.DeepEqual(keys, want) { - t.Errorf("Users.ListKeys returned %+v, want %+v", keys, want) - } -} - -func TestUsersService_ListKeys_specifiedUser(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/users/u/keys", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `[{"id":1}]`) - }) - - keys, _, err := client.Users.ListKeys("u", nil) - if err != nil { - t.Errorf("Users.ListKeys returned error: %v", err) - } - - want := []Key{{ID: Int(1)}} - if !reflect.DeepEqual(keys, want) { - t.Errorf("Users.ListKeys returned %+v, want %+v", keys, want) - } -} - -func TestUsersService_ListKeys_invalidUser(t *testing.T) { - _, _, err := client.Users.ListKeys("%", nil) - testURLParseError(t, err) -} - -func TestUsersService_GetKey(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/user/keys/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"id":1}`) - }) - - key, _, err := client.Users.GetKey(1) - if err != nil { - t.Errorf("Users.GetKey returned error: %v", err) - } - - want := &Key{ID: Int(1)} - if !reflect.DeepEqual(key, want) { - t.Errorf("Users.GetKey returned %+v, want %+v", key, want) - } -} - -func TestUsersService_CreateKey(t *testing.T) { - setup() - defer teardown() - - input := &Key{Key: String("k"), Title: String("t")} - - mux.HandleFunc("/user/keys", func(w http.ResponseWriter, r *http.Request) { - v := new(Key) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "POST") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"id":1}`) - }) - - key, _, err := client.Users.CreateKey(input) - if err != nil { - t.Errorf("Users.GetKey returned error: %v", err) - } - - want := &Key{ID: Int(1)} - if !reflect.DeepEqual(key, want) { - t.Errorf("Users.GetKey returned %+v, want %+v", key, want) - } -} - -func TestUsersService_DeleteKey(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/user/keys/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - }) - - _, err := client.Users.DeleteKey(1) - if err != nil { - t.Errorf("Users.DeleteKey returned error: %v", err) - } -} diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/users_test.go b/Godeps/_workspace/src/github.com/google/go-github/github/users_test.go deleted file mode 100644 index 15ea3e83a..000000000 --- a/Godeps/_workspace/src/github.com/google/go-github/github/users_test.go +++ /dev/null @@ -1,150 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestUser_marshall(t *testing.T) { - testJSONMarshal(t, &User{}, "{}") - - u := &User{ - Login: String("l"), - ID: Int(1), - URL: String("u"), - AvatarURL: String("a"), - GravatarID: String("g"), - Name: String("n"), - Company: String("c"), - Blog: String("b"), - Location: String("l"), - Email: String("e"), - Hireable: Bool(true), - PublicRepos: Int(1), - Followers: Int(1), - Following: Int(1), - CreatedAt: &Timestamp{referenceTime}, - } - want := `{ - "login": "l", - "id": 1, - "avatar_url": "a", - "gravatar_id": "g", - "name": "n", - "company": "c", - "blog": "b", - "location": "l", - "email": "e", - "hireable": true, - "public_repos": 1, - "followers": 1, - "following": 1, - "created_at": ` + referenceTimeStr + `, - "url": "u" - }` - testJSONMarshal(t, u, want) -} - -func TestUsersService_Get_authenticatedUser(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/user", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"id":1}`) - }) - - user, _, err := client.Users.Get("") - if err != nil { - t.Errorf("Users.Get returned error: %v", err) - } - - want := &User{ID: Int(1)} - if !reflect.DeepEqual(user, want) { - t.Errorf("Users.Get returned %+v, want %+v", user, want) - } -} - -func TestUsersService_Get_specifiedUser(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/users/u", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"id":1}`) - }) - - user, _, err := client.Users.Get("u") - if err != nil { - t.Errorf("Users.Get returned error: %v", err) - } - - want := &User{ID: Int(1)} - if !reflect.DeepEqual(user, want) { - t.Errorf("Users.Get returned %+v, want %+v", user, want) - } -} - -func TestUsersService_Get_invalidUser(t *testing.T) { - _, _, err := client.Users.Get("%") - testURLParseError(t, err) -} - -func TestUsersService_Edit(t *testing.T) { - setup() - defer teardown() - - input := &User{Name: String("n")} - - mux.HandleFunc("/user", func(w http.ResponseWriter, r *http.Request) { - v := new(User) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "PATCH") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"id":1}`) - }) - - user, _, err := client.Users.Edit(input) - if err != nil { - t.Errorf("Users.Edit returned error: %v", err) - } - - want := &User{ID: Int(1)} - if !reflect.DeepEqual(user, want) { - t.Errorf("Users.Edit returned %+v, want %+v", user, want) - } -} - -func TestUsersService_ListAll(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/users", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"since": "1"}) - fmt.Fprint(w, `[{"id":2}]`) - }) - - opt := &UserListOptions{1} - users, _, err := client.Users.ListAll(opt) - if err != nil { - t.Errorf("Users.Get returned error: %v", err) - } - - want := []User{{ID: Int(2)}} - if !reflect.DeepEqual(users, want) { - t.Errorf("Users.ListAll returned %+v, want %+v", users, want) - } -} diff --git a/Godeps/_workspace/src/github.com/google/go-querystring/query/encode_test.go b/Godeps/_workspace/src/github.com/google/go-querystring/query/encode_test.go deleted file mode 100644 index 09efb0f5b..000000000 --- a/Godeps/_workspace/src/github.com/google/go-querystring/query/encode_test.go +++ /dev/null @@ -1,286 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package query - -import ( - "fmt" - "net/url" - "reflect" - "testing" - "time" -) - -type Nested struct { - A SubNested `url:"a"` - B *SubNested `url:"b"` - Ptr *SubNested `url:"ptr,omitempty"` -} - -type SubNested struct { - Value string `url:"value"` -} - -func TestValues_types(t *testing.T) { - str := "string" - strPtr := &str - - tests := []struct { - in interface{} - want url.Values - }{ - { - // basic primitives - struct { - A string - B int - C uint - D float32 - E bool - }{}, - url.Values{ - "A": {""}, - "B": {"0"}, - "C": {"0"}, - "D": {"0"}, - "E": {"false"}, - }, - }, - { - // pointers - struct { - A *string - B *int - C **string - }{A: strPtr, C: &strPtr}, - url.Values{ - "A": {str}, - "B": {""}, - "C": {str}, - }, - }, - { - // slices and arrays - struct { - A []string - B []string `url:",comma"` - C []string `url:",space"` - D [2]string - E [2]string `url:",comma"` - F [2]string `url:",space"` - G []*string `url:",space"` - H []bool `url:",int,space"` - I []string `url:",brackets"` - }{ - A: []string{"a", "b"}, - B: []string{"a", "b"}, - C: []string{"a", "b"}, - D: [2]string{"a", "b"}, - E: [2]string{"a", "b"}, - F: [2]string{"a", "b"}, - G: []*string{&str, &str}, - H: []bool{true, false}, - I: []string{"a", "b"}, - }, - url.Values{ - "A": {"a", "b"}, - "B": {"a,b"}, - "C": {"a b"}, - "D": {"a", "b"}, - "E": {"a,b"}, - "F": {"a b"}, - "G": {"string string"}, - "H": {"1 0"}, - "I[]": {"a", "b"}, - }, - }, - { - // other types - struct { - A time.Time - B time.Time `url:",unix"` - C bool `url:",int"` - D bool `url:",int"` - }{ - A: time.Date(2000, 1, 1, 12, 34, 56, 0, time.UTC), - B: time.Date(2000, 1, 1, 12, 34, 56, 0, time.UTC), - C: true, - D: false, - }, - url.Values{ - "A": {"2000-01-01T12:34:56Z"}, - "B": {"946730096"}, - "C": {"1"}, - "D": {"0"}, - }, - }, - { - struct { - Nest Nested `url:"nest"` - }{ - Nested{ - A: SubNested{ - Value: "that", - }, - }, - }, - url.Values{ - "nest[a][value]": {"that"}, - "nest[b]": {""}, - }, - }, - { - struct { - Nest Nested `url:"nest"` - }{ - Nested{ - Ptr: &SubNested{ - Value: "that", - }, - }, - }, - url.Values{ - "nest[a][value]": {""}, - "nest[b]": {""}, - "nest[ptr][value]": {"that"}, - }, - }, - { - nil, - url.Values{}, - }, - } - - for i, tt := range tests { - v, err := Values(tt.in) - if err != nil { - t.Errorf("%d. Values(%q) returned error: %v", i, tt.in, err) - } - - if !reflect.DeepEqual(tt.want, v) { - t.Errorf("%d. Values(%q) returned %v, want %v", i, tt.in, v, tt.want) - } - } -} - -func TestValues_omitEmpty(t *testing.T) { - str := "" - s := struct { - a string - A string - B string `url:",omitempty"` - C string `url:"-"` - D string `url:"omitempty"` // actually named omitempty, not an option - E *string `url:",omitempty"` - }{E: &str} - - v, err := Values(s) - if err != nil { - t.Errorf("Values(%q) returned error: %v", s, err) - } - - want := url.Values{ - "A": {""}, - "omitempty": {""}, - "E": {""}, // E is included because the pointer is not empty, even though the string being pointed to is - } - if !reflect.DeepEqual(want, v) { - t.Errorf("Values(%q) returned %v, want %v", s, v, want) - } -} - -type A struct { - B -} - -type B struct { - C string -} - -type D struct { - B - C string -} - -func TestValues_embeddedStructs(t *testing.T) { - tests := []struct { - in interface{} - want url.Values - }{ - { - A{B{C: "foo"}}, - url.Values{"C": {"foo"}}, - }, - { - D{B: B{C: "bar"}, C: "foo"}, - url.Values{"C": {"foo", "bar"}}, - }, - } - - for i, tt := range tests { - v, err := Values(tt.in) - if err != nil { - t.Errorf("%d. Values(%q) returned error: %v", i, tt.in, err) - } - - if !reflect.DeepEqual(tt.want, v) { - t.Errorf("%d. Values(%q) returned %v, want %v", i, tt.in, v, tt.want) - } - } -} - -func TestValues_invalidInput(t *testing.T) { - _, err := Values("") - if err == nil { - t.Errorf("expected Values() to return an error on invalid input") - } -} - -type EncodedArgs []string - -func (m EncodedArgs) EncodeValues(key string, v *url.Values) error { - for i, arg := range m { - v.Set(fmt.Sprintf("%s.%d", key, i), arg) - } - return nil -} - -func TestValues_Marshaler(t *testing.T) { - s := struct { - Args EncodedArgs `url:"arg"` - }{[]string{"a", "b", "c"}} - v, err := Values(s) - if err != nil { - t.Errorf("Values(%q) returned error: %v", s, err) - } - - want := url.Values{ - "arg.0": {"a"}, - "arg.1": {"b"}, - "arg.2": {"c"}, - } - if !reflect.DeepEqual(want, v) { - t.Errorf("Values(%q) returned %v, want %v", s, v, want) - } -} - -func TestTagParsing(t *testing.T) { - name, opts := parseTag("field,foobar,foo") - if name != "field" { - t.Fatalf("name = %q, want field", name) - } - for _, tt := range []struct { - opt string - want bool - }{ - {"foobar", true}, - {"foo", true}, - {"bar", false}, - {"field", false}, - } { - if opts.Contains(tt.opt) != tt.want { - t.Errorf("Contains(%q) = %v", tt.opt, !tt.want) - } - } -} diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/api/acl_test.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/acl_test.go deleted file mode 100644 index 2a5207a6e..000000000 --- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/acl_test.go +++ /dev/null @@ -1,128 +0,0 @@ -package api - -import ( - "testing" -) - -func TestACL_CreateDestroy(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 TestACL_CloneDestroy(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 TestACL_Info(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 TestACL_List(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) - } -} diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/api/agent_test.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/agent_test.go deleted file mode 100644 index 358c12a6c..000000000 --- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/agent_test.go +++ /dev/null @@ -1,524 +0,0 @@ -package api - -import ( - "strings" - "testing" -) - -func TestAgent_Self(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 TestAgent_Members(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 TestAgent_Services(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 != "critical" { - t.Fatalf("Bad: %#v", chk) - } - - if err := agent.ServiceDeregister("foo"); err != nil { - t.Fatalf("err: %v", err) - } -} - -func TestAgent_Services_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: "passing", - }, - } - 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 != "passing" { - t.Fatalf("Bad: %#v", chk) - } - if err := agent.ServiceDeregister("foo"); err != nil { - t.Fatalf("err: %v", err) - } -} - -func TestAgent_Services_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 TestAgent_ServiceAddress(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 TestAgent_Services_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 TestAgent_SetTTLStatus(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) - } - - if err := agent.WarnTTL("service:foo", "test"); err != nil { - t.Fatalf("err: %v", err) - } - - 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 != "warning" { - t.Fatalf("Bad: %#v", chk) - } - if chk.Output != "test" { - t.Fatalf("Bad: %#v", chk) - } - - if err := agent.ServiceDeregister("foo"); err != nil { - t.Fatalf("err: %v", err) - } -} - -func TestAgent_Checks(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 != "critical" { - t.Fatalf("check not critical: %v", chk) - } - - if err := agent.CheckDeregister("foo"); err != nil { - t.Fatalf("err: %v", err) - } -} - -func TestAgent_CheckStartPassing(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - agent := c.Agent() - - reg := &AgentCheckRegistration{ - Name: "foo", - AgentServiceCheck: AgentServiceCheck{ - Status: "passing", - }, - } - 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 != "passing" { - t.Fatalf("check not passing: %v", chk) - } - - if err := agent.CheckDeregister("foo"); err != nil { - t.Fatalf("err: %v", err) - } -} - -func TestAgent_Checks_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" - 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 TestAgent_Join(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 TestAgent_ForceLeave(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 TestServiceMaintenance(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 != "critical" || 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 TestNodeMaintenance(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 != "critical" || 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") - } - } -} diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/api/api.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/api.go index 8fe2ead04..b0b712834 100644 --- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/api.go +++ b/Godeps/_workspace/src/github.com/hashicorp/consul/api/api.go @@ -36,7 +36,7 @@ type QueryOptions struct { WaitIndex uint64 // WaitTime is used to bound the duration of a wait. - // Defaults to that of the Config, but can be overriden. + // Defaults to that of the Config, but can be overridden. WaitTime time.Duration // Token is used to provide a per-request ACL token diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/api/api_test.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/api_test.go deleted file mode 100644 index 56f9494f8..000000000 --- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/api_test.go +++ /dev/null @@ -1,252 +0,0 @@ -package api - -import ( - crand "crypto/rand" - "fmt" - "io/ioutil" - "net/http" - "os" - "path/filepath" - "runtime" - "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 := testutil.NewTestServerConfig(t, cb2) - 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 TestDefaultConfig_env(t *testing.T) { - t.Parallel() - addr := "1.2.3.4:5678" - token := "abcd1234" - auth := "username:password" - - os.Setenv("CONSUL_HTTP_ADDR", addr) - defer os.Setenv("CONSUL_HTTP_ADDR", "") - os.Setenv("CONSUL_HTTP_TOKEN", token) - defer os.Setenv("CONSUL_HTTP_TOKEN", "") - os.Setenv("CONSUL_HTTP_AUTH", auth) - defer os.Setenv("CONSUL_HTTP_AUTH", "") - os.Setenv("CONSUL_HTTP_SSL", "1") - defer os.Setenv("CONSUL_HTTP_SSL", "") - os.Setenv("CONSUL_HTTP_SSL_VERIFY", "0") - defer os.Setenv("CONSUL_HTTP_SSL_VERIFY", "") - - config := DefaultConfig() - - 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.HttpClient.Transport.(*http.Transport).TLSClientConfig.InsecureSkipVerify { - t.Errorf("expected SSL verification to be off") - } -} - -func TestSetQueryOptions(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", - } - 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.params.Get("token") != "12345" { - t.Fatalf("bad: %v", r.params) - } -} - -func TestSetWriteOptions(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.params.Get("token") != "23456" { - t.Fatalf("bad: %v", r.params) - } -} - -func TestRequestToHTTP(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 TestParseQueryMeta(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") - - 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) - } -} - -func TestAPI_UnixSocket(t *testing.T) { - t.Parallel() - if runtime.GOOS == "windows" { - t.SkipNow() - } - - tempDir, err := ioutil.TempDir("", "consul") - if err != nil { - t.Fatalf("err: %s", err) - } - 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) - } -} diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/api/catalog_test.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/catalog_test.go deleted file mode 100644 index bb8be25b0..000000000 --- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/catalog_test.go +++ /dev/null @@ -1,279 +0,0 @@ -package api - -import ( - "fmt" - "testing" - - "github.com/hashicorp/consul/testutil" -) - -func TestCatalog_Datacenters(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - catalog := c.Catalog() - - testutil.WaitForResult(func() (bool, error) { - datacenters, err := catalog.Datacenters() - if err != nil { - return false, err - } - - if len(datacenters) == 0 { - return false, fmt.Errorf("Bad: %v", datacenters) - } - - return true, nil - }, func(err error) { - t.Fatalf("err: %s", err) - }) -} - -func TestCatalog_Nodes(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - catalog := c.Catalog() - - testutil.WaitForResult(func() (bool, error) { - nodes, meta, err := catalog.Nodes(nil) - if err != nil { - return false, err - } - - if meta.LastIndex == 0 { - return false, fmt.Errorf("Bad: %v", meta) - } - - if len(nodes) == 0 { - return false, fmt.Errorf("Bad: %v", nodes) - } - - return true, nil - }, func(err error) { - t.Fatalf("err: %s", err) - }) -} - -func TestCatalog_Services(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - catalog := c.Catalog() - - testutil.WaitForResult(func() (bool, error) { - services, meta, err := catalog.Services(nil) - if err != nil { - return false, err - } - - if meta.LastIndex == 0 { - return false, fmt.Errorf("Bad: %v", meta) - } - - if len(services) == 0 { - return false, fmt.Errorf("Bad: %v", services) - } - - return true, nil - }, func(err error) { - t.Fatalf("err: %s", err) - }) -} - -func TestCatalog_Service(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - catalog := c.Catalog() - - testutil.WaitForResult(func() (bool, error) { - services, meta, err := catalog.Service("consul", "", nil) - if err != nil { - return false, err - } - - if meta.LastIndex == 0 { - return false, fmt.Errorf("Bad: %v", meta) - } - - if len(services) == 0 { - return false, fmt.Errorf("Bad: %v", services) - } - - return true, nil - }, func(err error) { - t.Fatalf("err: %s", err) - }) -} - -func TestCatalog_Node(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - catalog := c.Catalog() - name, _ := c.Agent().NodeName() - - testutil.WaitForResult(func() (bool, error) { - info, meta, err := catalog.Node(name, nil) - if err != nil { - return false, err - } - - if meta.LastIndex == 0 { - return false, fmt.Errorf("Bad: %v", meta) - } - if len(info.Services) == 0 { - return false, fmt.Errorf("Bad: %v", info) - } - - return true, nil - }, func(err error) { - t.Fatalf("err: %s", err) - }) -} - -func TestCatalog_Registration(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: "passing", - ServiceID: "redis1", - } - - reg := &CatalogRegistration{ - Datacenter: "dc1", - Node: "foobar", - Address: "192.168.10.10", - Service: service, - Check: check, - } - - testutil.WaitForResult(func() (bool, error) { - if _, err := catalog.Register(reg, nil); err != nil { - return false, err - } - - node, _, err := catalog.Node("foobar", nil) - if err != nil { - return false, err - } - - if _, ok := node.Services["redis1"]; !ok { - return false, fmt.Errorf("missing service: redis1") - } - - health, _, err := c.Health().Node("foobar", nil) - if err != nil { - return false, err - } - - if health[0].CheckID != "service:redis1" { - return false, fmt.Errorf("missing checkid service:redis1") - } - - return true, nil - }, func(err error) { - t.Fatalf("err: %s", err) - }) - - // 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) - } - - testutil.WaitForResult(func() (bool, error) { - node, _, err := catalog.Node("foobar", nil) - if err != nil { - return false, err - } - - if _, ok := node.Services["redis1"]; ok { - return false, fmt.Errorf("ServiceID:redis1 is not deregistered") - } - - return true, nil - }, func(err error) { - t.Fatalf("err: %s", err) - }) - - // 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) - } - - testutil.WaitForResult(func() (bool, error) { - health, _, err := c.Health().Node("foobar", nil) - if err != nil { - return false, err - } - - if len(health) != 0 { - return false, fmt.Errorf("CheckID:service:redis1 is not deregistered") - } - - return true, nil - }, func(err error) { - t.Fatalf("err: %s", err) - }) - - // 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) - } - - testutil.WaitForResult(func() (bool, error) { - node, _, err := catalog.Node("foobar", nil) - if err != nil { - return false, err - } - - if node != nil { - return false, fmt.Errorf("node is not deregistered: %v", node) - } - - return true, nil - }, func(err error) { - t.Fatalf("err: %s", err) - }) -} diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/api/event_test.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/event_test.go deleted file mode 100644 index 1ca92e233..000000000 --- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/event_test.go +++ /dev/null @@ -1,49 +0,0 @@ -package api - -import ( - "testing" - - "github.com/hashicorp/consul/testutil" -) - -func TestEvent_FireList(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 - testutil.WaitForResult(func() (bool, error) { - events, qm, err = event.List("", nil) - if err != nil { - t.Fatalf("err: %v", err) - } - return len(events) > 0, err - }, func(err error) { - t.Fatalf("err: %#v", 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/Godeps/_workspace/src/github.com/hashicorp/consul/api/health.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/health.go index 02b161e28..1a273e087 100644 --- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/health.go +++ b/Godeps/_workspace/src/github.com/hashicorp/consul/api/health.go @@ -104,7 +104,7 @@ func (h *Health) Service(service, tag string, passingOnly bool, q *QueryOptions) return out, qm, nil } -// State is used to retreive all the checks in a given state. +// State is used to retrieve all the checks in a given state. // The wildcard "any" state can also be used for all checks. func (h *Health) State(state string, q *QueryOptions) ([]*HealthCheck, *QueryMeta, error) { switch state { diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/api/health_test.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/health_test.go deleted file mode 100644 index d80a4693a..000000000 --- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/health_test.go +++ /dev/null @@ -1,125 +0,0 @@ -package api - -import ( - "fmt" - "testing" - - "github.com/hashicorp/consul/testutil" -) - -func TestHealth_Node(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) - - testutil.WaitForResult(func() (bool, error) { - checks, meta, err := health.Node(name, nil) - if err != nil { - return false, err - } - if meta.LastIndex == 0 { - return false, fmt.Errorf("bad: %v", meta) - } - if len(checks) == 0 { - return false, fmt.Errorf("bad: %v", checks) - } - return true, nil - }, func(err error) { - t.Fatalf("err: %s", err) - }) -} - -func TestHealth_Checks(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - 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") - - testutil.WaitForResult(func() (bool, error) { - checks, meta, err := health.Checks("foo", nil) - if err != nil { - return false, err - } - if meta.LastIndex == 0 { - return false, fmt.Errorf("bad: %v", meta) - } - if len(checks) == 0 { - return false, fmt.Errorf("Bad: %v", checks) - } - return true, nil - }, func(err error) { - t.Fatalf("err: %s", err) - }) -} - -func TestHealth_Service(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - health := c.Health() - - testutil.WaitForResult(func() (bool, error) { - // consul service should always exist... - checks, meta, err := health.Service("consul", "", true, nil) - if err != nil { - return false, err - } - if meta.LastIndex == 0 { - return false, fmt.Errorf("bad: %v", meta) - } - if len(checks) == 0 { - return false, fmt.Errorf("Bad: %v", checks) - } - return true, nil - }, func(err error) { - t.Fatalf("err: %s", err) - }) -} - -func TestHealth_State(t *testing.T) { - t.Parallel() - c, s := makeClient(t) - defer s.Stop() - - health := c.Health() - - testutil.WaitForResult(func() (bool, error) { - checks, meta, err := health.State("any", nil) - if err != nil { - return false, err - } - if meta.LastIndex == 0 { - return false, fmt.Errorf("bad: %v", meta) - } - if len(checks) == 0 { - return false, fmt.Errorf("Bad: %v", checks) - } - return true, nil - }, func(err error) { - t.Fatalf("err: %s", err) - }) -} diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/api/kv.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/kv.go index c1a8923be..688b3a09d 100644 --- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/kv.go +++ b/Godeps/_workspace/src/github.com/hashicorp/consul/api/kv.go @@ -143,7 +143,7 @@ func (k *KV) CAS(p *KVPair, q *WriteOptions) (bool, *WriteMeta, error) { return k.put(p.Key, params, p.Value, q) } -// Acquire is used for a lock acquisiiton operation. The Key, +// Acquire is used for a lock acquisition operation. The Key, // Flags, Value and Session are respected. Returns true // on success or false on failures. func (k *KV) Acquire(p *KVPair, q *WriteOptions) (bool, *WriteMeta, error) { diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/api/kv_test.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/kv_test.go deleted file mode 100644 index 758595d89..000000000 --- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/kv_test.go +++ /dev/null @@ -1,447 +0,0 @@ -package api - -import ( - "bytes" - "path" - "testing" - "time" -) - -func TestClientPutGetDelete(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 TestClient_List_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 TestClient_DeleteCAS(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 TestClient_CAS(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 TestClient_WatchGet(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") - 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) - } - }() - - // 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) - } -} - -func TestClient_WatchList(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") - 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) - } - }() - - // 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) - } - -} - -func TestClient_Keys_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 TestClient_AcquireRelease(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) - } -} diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/api/lock_test.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/lock_test.go deleted file mode 100644 index 0a8fa5172..000000000 --- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/lock_test.go +++ /dev/null @@ -1,363 +0,0 @@ -package api - -import ( - "log" - "sync" - "testing" - "time" -) - -func TestLock_LockUnlock(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 loose leadership - select { - case <-leaderCh: - case <-time.After(time.Second): - t.Fatalf("should not be leader") - } -} - -func TestLock_ForceInvalidate(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 TestLock_DeleteKey(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 key, simulate an operator intervention - kv := c.KV() - kv.Delete("test/lock", nil) - }() - - // Should loose leadership - select { - case <-leaderCh: - case <-time.After(time.Second): - t.Fatalf("should not be leader") - } -} - -func TestLock_Contend(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 TestLock_Destroy(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 relese - 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 TestLock_Conflict(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 TestLock_ReclaimLock(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") - } -} diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/api/semaphore.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/semaphore.go index ff4c2058c..4e70be2e7 100644 --- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/semaphore.go +++ b/Godeps/_workspace/src/github.com/hashicorp/consul/api/semaphore.go @@ -66,7 +66,7 @@ type SemaphoreOptions struct { Prefix string // Must be set and have write permissions Limit int // Must be set, and be positive Value []byte // Optional, value to associate with the contender entry - Session string // OPtional, created if not specified + Session string // Optional, created if not specified SessionName string // Optional, defaults to DefaultLockSessionName SessionTTL string // Optional, defaults to DefaultLockSessionTTL } @@ -123,7 +123,7 @@ func (c *Client) SemaphoreOpts(opts *SemaphoreOptions) (*Semaphore, error) { } // Acquire attempts to reserve a slot in the semaphore, blocking until -// success, interrupted via the stopCh or an error is encounted. +// success, interrupted via the stopCh or an error is encountered. // Providing a non-nil stopCh can be used to abort the attempt. // On success, a channel is returned that represents our slot. // This channel could be closed at any time due to session invalidation, diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/api/semaphore_test.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/semaphore_test.go deleted file mode 100644 index 5e5e53588..000000000 --- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/semaphore_test.go +++ /dev/null @@ -1,313 +0,0 @@ -package api - -import ( - "log" - "sync" - "testing" - "time" -) - -func TestSemaphore_AcquireRelease(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 TestSemaphore_ForceInvalidate(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 TestSemaphore_DeleteKey(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 TestSemaphore_Contend(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 TestSemaphore_BadLimit(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 TestSemaphore_Destroy(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 TestSemaphore_Conflict(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) - } -} diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/api/session.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/session.go index a99da511d..574738127 100644 --- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/session.go +++ b/Godeps/_workspace/src/github.com/hashicorp/consul/api/session.go @@ -102,7 +102,7 @@ func (s *Session) create(obj interface{}, q *WriteOptions) (string, *WriteMeta, return out.ID, wm, nil } -// Destroy invalides a given session +// Destroy invalidates a given session func (s *Session) Destroy(id string, q *WriteOptions) (*WriteMeta, error) { wm, err := s.c.write("/v1/session/destroy/"+id, nil, nil, q) if err != nil { diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/api/session_test.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/session_test.go deleted file mode 100644 index c503c21a0..000000000 --- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/session_test.go +++ /dev/null @@ -1,205 +0,0 @@ -package api - -import ( - "testing" -) - -func TestSession_CreateDestroy(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 TestSession_CreateRenewDestroy(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 TestSession_Info(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 TestSession_Node(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 TestSession_List(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/Godeps/_workspace/src/github.com/hashicorp/consul/api/status_test.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/status_test.go deleted file mode 100644 index 62dc1550f..000000000 --- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/status_test.go +++ /dev/null @@ -1,37 +0,0 @@ -package api - -import ( - "testing" -) - -func TestStatusLeader(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 TestStatusPeers(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/Godeps/_workspace/src/github.com/hashicorp/errwrap/errwrap_test.go b/Godeps/_workspace/src/github.com/hashicorp/errwrap/errwrap_test.go deleted file mode 100644 index 5ae5f8e3c..000000000 --- a/Godeps/_workspace/src/github.com/hashicorp/errwrap/errwrap_test.go +++ /dev/null @@ -1,94 +0,0 @@ -package errwrap - -import ( - "fmt" - "testing" -) - -func TestWrappedError_impl(t *testing.T) { - var _ error = new(wrappedError) -} - -func TestGetAll(t *testing.T) { - cases := []struct { - Err error - Msg string - Len int - }{ - {}, - { - fmt.Errorf("foo"), - "foo", - 1, - }, - { - fmt.Errorf("bar"), - "foo", - 0, - }, - { - Wrapf("bar", fmt.Errorf("foo")), - "foo", - 1, - }, - { - Wrapf("{{err}}", fmt.Errorf("foo")), - "foo", - 2, - }, - { - Wrapf("bar", Wrapf("baz", fmt.Errorf("foo"))), - "foo", - 1, - }, - } - - for i, tc := range cases { - actual := GetAll(tc.Err, tc.Msg) - if len(actual) != tc.Len { - t.Fatalf("%d: bad: %#v", i, actual) - } - for _, v := range actual { - if v.Error() != tc.Msg { - t.Fatalf("%d: bad: %#v", i, actual) - } - } - } -} - -func TestGetAllType(t *testing.T) { - cases := []struct { - Err error - Type interface{} - Len int - }{ - {}, - { - fmt.Errorf("foo"), - "foo", - 0, - }, - { - fmt.Errorf("bar"), - fmt.Errorf("foo"), - 1, - }, - { - Wrapf("bar", fmt.Errorf("foo")), - fmt.Errorf("baz"), - 2, - }, - { - Wrapf("bar", Wrapf("baz", fmt.Errorf("foo"))), - Wrapf("", nil), - 0, - }, - } - - for i, tc := range cases { - actual := GetAllType(tc.Err, tc.Type) - if len(actual) != tc.Len { - t.Fatalf("%d: bad: %#v", i, actual) - } - } -} diff --git a/Godeps/_workspace/src/github.com/hashicorp/go-multierror/append.go b/Godeps/_workspace/src/github.com/hashicorp/go-multierror/append.go index 8d22ee7a0..00afa9b35 100644 --- a/Godeps/_workspace/src/github.com/hashicorp/go-multierror/append.go +++ b/Godeps/_workspace/src/github.com/hashicorp/go-multierror/append.go @@ -14,7 +14,16 @@ func Append(err error, errs ...error) *Error { err = new(Error) } - err.Errors = append(err.Errors, errs...) + // Go through each error and flatten + for _, e := range errs { + switch e := e.(type) { + case *Error: + err.Errors = append(err.Errors, e.Errors...) + default: + err.Errors = append(err.Errors, e) + } + } + return err default: newErrs := make([]error, 0, len(errs)+1) @@ -23,8 +32,6 @@ func Append(err error, errs ...error) *Error { } newErrs = append(newErrs, errs...) - return &Error{ - Errors: newErrs, - } + return Append(&Error{}, newErrs...) } } diff --git a/Godeps/_workspace/src/github.com/hashicorp/go-multierror/append_test.go b/Godeps/_workspace/src/github.com/hashicorp/go-multierror/append_test.go deleted file mode 100644 index 1fe8a4c25..000000000 --- a/Godeps/_workspace/src/github.com/hashicorp/go-multierror/append_test.go +++ /dev/null @@ -1,45 +0,0 @@ -package multierror - -import ( - "errors" - "testing" -) - -func TestAppend_Error(t *testing.T) { - original := &Error{ - Errors: []error{errors.New("foo")}, - } - - result := Append(original, errors.New("bar")) - if len(result.Errors) != 2 { - t.Fatalf("wrong len: %d", len(result.Errors)) - } - - original = &Error{} - result = Append(original, errors.New("bar")) - if len(result.Errors) != 1 { - t.Fatalf("wrong len: %d", len(result.Errors)) - } - - // Test when a typed nil is passed - var e *Error - result = Append(e, errors.New("baz")) - if len(result.Errors) != 1 { - t.Fatalf("wrong len: %d", len(result.Errors)) - } -} - -func TestAppend_NilError(t *testing.T) { - var err error - result := Append(err, errors.New("bar")) - if len(result.Errors) != 1 { - t.Fatalf("wrong len: %d", len(result.Errors)) - } -} -func TestAppend_NonError(t *testing.T) { - original := errors.New("foo") - result := Append(original, errors.New("bar")) - if len(result.Errors) != 2 { - t.Fatalf("wrong len: %d", len(result.Errors)) - } -} diff --git a/Godeps/_workspace/src/github.com/hashicorp/go-multierror/flatten_test.go b/Godeps/_workspace/src/github.com/hashicorp/go-multierror/flatten_test.go deleted file mode 100644 index 75218f103..000000000 --- a/Godeps/_workspace/src/github.com/hashicorp/go-multierror/flatten_test.go +++ /dev/null @@ -1,48 +0,0 @@ -package multierror - -import ( - "errors" - "fmt" - "reflect" - "strings" - "testing" -) - -func TestFlatten(t *testing.T) { - original := &Error{ - Errors: []error{ - errors.New("one"), - &Error{ - Errors: []error{ - errors.New("two"), - &Error{ - Errors: []error{ - errors.New("three"), - }, - }, - }, - }, - }, - } - - expected := strings.TrimSpace(` -3 error(s) occurred: - -* one -* two -* three - `) - actual := fmt.Sprintf("%s", Flatten(original)) - - if expected != actual { - t.Fatalf("expected: %s, got: %s", expected, actual) - } -} - -func TestFlatten_nonError(t *testing.T) { - err := errors.New("foo") - actual := Flatten(err) - if !reflect.DeepEqual(actual, err) { - t.Fatalf("bad: %#v", actual) - } -} diff --git a/Godeps/_workspace/src/github.com/hashicorp/go-multierror/format_test.go b/Godeps/_workspace/src/github.com/hashicorp/go-multierror/format_test.go deleted file mode 100644 index d7cee5d7d..000000000 --- a/Godeps/_workspace/src/github.com/hashicorp/go-multierror/format_test.go +++ /dev/null @@ -1,23 +0,0 @@ -package multierror - -import ( - "errors" - "testing" -) - -func TestListFormatFunc(t *testing.T) { - expected := `2 error(s) occurred: - -* foo -* bar` - - errors := []error{ - errors.New("foo"), - errors.New("bar"), - } - - actual := ListFormatFunc(errors) - if actual != expected { - t.Fatalf("bad: %#v", actual) - } -} diff --git a/Godeps/_workspace/src/github.com/hashicorp/go-multierror/multierror_test.go b/Godeps/_workspace/src/github.com/hashicorp/go-multierror/multierror_test.go deleted file mode 100644 index 3e78079c0..000000000 --- a/Godeps/_workspace/src/github.com/hashicorp/go-multierror/multierror_test.go +++ /dev/null @@ -1,70 +0,0 @@ -package multierror - -import ( - "errors" - "reflect" - "testing" -) - -func TestError_Impl(t *testing.T) { - var _ error = new(Error) -} - -func TestErrorError_custom(t *testing.T) { - errors := []error{ - errors.New("foo"), - errors.New("bar"), - } - - fn := func(es []error) string { - return "foo" - } - - multi := &Error{Errors: errors, ErrorFormat: fn} - if multi.Error() != "foo" { - t.Fatalf("bad: %s", multi.Error()) - } -} - -func TestErrorError_default(t *testing.T) { - expected := `2 error(s) occurred: - -* foo -* bar` - - errors := []error{ - errors.New("foo"), - errors.New("bar"), - } - - multi := &Error{Errors: errors} - if multi.Error() != expected { - t.Fatalf("bad: %s", multi.Error()) - } -} - -func TestErrorErrorOrNil(t *testing.T) { - err := new(Error) - if err.ErrorOrNil() != nil { - t.Fatalf("bad: %#v", err.ErrorOrNil()) - } - - err.Errors = []error{errors.New("foo")} - if v := err.ErrorOrNil(); v == nil { - t.Fatal("should not be nil") - } else if !reflect.DeepEqual(v, err) { - t.Fatalf("bad: %#v", v) - } -} - -func TestErrorWrappedErrors(t *testing.T) { - errors := []error{ - errors.New("foo"), - errors.New("bar"), - } - - multi := &Error{Errors: errors} - if !reflect.DeepEqual(multi.Errors, multi.WrappedErrors()) { - t.Fatalf("bad: %s", multi.WrappedErrors()) - } -} diff --git a/Godeps/_workspace/src/github.com/hashicorp/go-multierror/prefix.go b/Godeps/_workspace/src/github.com/hashicorp/go-multierror/prefix.go new file mode 100644 index 000000000..5c477abe4 --- /dev/null +++ b/Godeps/_workspace/src/github.com/hashicorp/go-multierror/prefix.go @@ -0,0 +1,37 @@ +package multierror + +import ( + "fmt" + + "github.com/hashicorp/errwrap" +) + +// Prefix is a helper function that will prefix some text +// to the given error. If the error is a multierror.Error, then +// it will be prefixed to each wrapped error. +// +// This is useful to use when appending multiple multierrors +// together in order to give better scoping. +func Prefix(err error, prefix string) error { + if err == nil { + return nil + } + + format := fmt.Sprintf("%s {{err}}", prefix) + switch err := err.(type) { + case *Error: + // Typed nils can reach here, so initialize if we are nil + if err == nil { + err = new(Error) + } + + // Wrap each of the errors + for i, e := range err.Errors { + err.Errors[i] = errwrap.Wrapf(format, e) + } + + return err + default: + return errwrap.Wrapf(format, err) + } +} diff --git a/Godeps/_workspace/src/github.com/hashicorp/golang-lru/lru_test.go b/Godeps/_workspace/src/github.com/hashicorp/golang-lru/lru_test.go deleted file mode 100644 index aeca7b7c4..000000000 --- a/Godeps/_workspace/src/github.com/hashicorp/golang-lru/lru_test.go +++ /dev/null @@ -1,157 +0,0 @@ -package lru - -import "testing" - -func TestLRU(t *testing.T) { - evictCounter := 0 - onEvicted := func(k interface{}, v interface{}) { - if k != v { - t.Fatalf("Evict values not equal (%v!=%v)", k, v) - } - evictCounter += 1 - } - l, err := NewWithEvict(128, onEvicted) - if err != nil { - t.Fatalf("err: %v", err) - } - - for i := 0; i < 256; i++ { - l.Add(i, i) - } - if l.Len() != 128 { - t.Fatalf("bad len: %v", l.Len()) - } - - if evictCounter != 128 { - t.Fatalf("bad evict count: %v", evictCounter) - } - - for i, k := range l.Keys() { - if v, ok := l.Get(k); !ok || v != k || v != i+128 { - t.Fatalf("bad key: %v", k) - } - } - for i := 0; i < 128; i++ { - _, ok := l.Get(i) - if ok { - t.Fatalf("should be evicted") - } - } - for i := 128; i < 256; i++ { - _, ok := l.Get(i) - if !ok { - t.Fatalf("should not be evicted") - } - } - for i := 128; i < 192; i++ { - l.Remove(i) - _, ok := l.Get(i) - if ok { - t.Fatalf("should be deleted") - } - } - - l.Get(192) // expect 192 to be last key in l.Keys() - - for i, k := range l.Keys() { - if (i < 63 && k != i+193) || (i == 63 && k != 192) { - t.Fatalf("out of order key: %v", k) - } - } - - l.Purge() - if l.Len() != 0 { - t.Fatalf("bad len: %v", l.Len()) - } - if _, ok := l.Get(200); ok { - t.Fatalf("should contain nothing") - } -} - -// test that Add returns true/false if an eviction occured -func TestLRUAdd(t *testing.T) { - evictCounter := 0 - onEvicted := func(k interface{}, v interface{}) { - evictCounter += 1 - } - - l, err := NewWithEvict(1, onEvicted) - if err != nil { - t.Fatalf("err: %v", err) - } - - if l.Add(1, 1) == true || evictCounter != 0 { - t.Errorf("should not have an eviction") - } - if l.Add(2, 2) == false || evictCounter != 1 { - t.Errorf("should have an eviction") - } -} - -// test that Contains doesn't update recent-ness -func TestLRUContains(t *testing.T) { - l, err := New(2) - if err != nil { - t.Fatalf("err: %v", err) - } - - l.Add(1, 1) - l.Add(2, 2) - if !l.Contains(1) { - t.Errorf("1 should be contained") - } - - l.Add(3, 3) - if l.Contains(1) { - t.Errorf("Contains should not have updated recent-ness of 1") - } -} - -// test that Contains doesn't update recent-ness -func TestLRUContainsOrAdd(t *testing.T) { - l, err := New(2) - if err != nil { - t.Fatalf("err: %v", err) - } - - l.Add(1, 1) - l.Add(2, 2) - contains, evict := l.ContainsOrAdd(1, 1) - if !contains { - t.Errorf("1 should be contained") - } - if evict { - t.Errorf("nothing should be evicted here") - } - - l.Add(3, 3) - contains, evict = l.ContainsOrAdd(1, 1) - if contains { - t.Errorf("1 should not have been contained") - } - if !evict { - t.Errorf("an eviction should have occurred") - } - if !l.Contains(1) { - t.Errorf("now 1 should be contained") - } -} - -// test that Peek doesn't update recent-ness -func TestLRUPeek(t *testing.T) { - l, err := New(2) - if err != nil { - t.Fatalf("err: %v", err) - } - - l.Add(1, 1) - l.Add(2, 2) - if v, ok := l.Peek(1); !ok || v != 1 { - t.Errorf("1 should be set to 1: %v, %v", v, ok) - } - - l.Add(3, 3) - if l.Contains(1) { - t.Errorf("should not have updated recent-ness of 1") - } -} diff --git a/Godeps/_workspace/src/github.com/hashicorp/hcl/decoder_test.go b/Godeps/_workspace/src/github.com/hashicorp/hcl/decoder_test.go deleted file mode 100644 index a71163b19..000000000 --- a/Godeps/_workspace/src/github.com/hashicorp/hcl/decoder_test.go +++ /dev/null @@ -1,481 +0,0 @@ -package hcl - -import ( - "io/ioutil" - "path/filepath" - "reflect" - "testing" -) - -func TestDecode_interface(t *testing.T) { - cases := []struct { - File string - Err bool - Out interface{} - }{ - { - "basic.hcl", - false, - map[string]interface{}{ - "foo": "bar", - "bar": "${file(\"bing/bong.txt\")}", - }, - }, - { - "basic_squish.hcl", - false, - map[string]interface{}{ - "foo": "bar", - "bar": "${file(\"bing/bong.txt\")}", - "foo-bar": "baz", - }, - }, - { - "empty.hcl", - false, - map[string]interface{}{ - "resource": []map[string]interface{}{ - map[string]interface{}{ - "foo": []map[string]interface{}{ - map[string]interface{}{}, - }, - }, - }, - }, - }, - { - "escape.hcl", - false, - map[string]interface{}{ - "foo": "bar\"baz\\n", - }, - }, - { - "float.hcl", - false, - map[string]interface{}{ - "a": 1.02, - }, - }, - { - "multiline_bad.hcl", - false, - map[string]interface{}{"foo": "bar\nbaz\n"}, - }, - { - "multiline.json", - false, - map[string]interface{}{"foo": "bar\nbaz"}, - }, - { - "scientific.json", - false, - map[string]interface{}{ - "a": 1e-10, - "b": 1e+10, - "c": 1e10, - "d": 1.2e-10, - "e": 1.2e+10, - "f": 1.2e10, - }, - }, - { - "scientific.hcl", - false, - map[string]interface{}{ - "a": 1e-10, - "b": 1e+10, - "c": 1e10, - "d": 1.2e-10, - "e": 1.2e+10, - "f": 1.2e10, - }, - }, - { - "terraform_heroku.hcl", - false, - map[string]interface{}{ - "name": "terraform-test-app", - "config_vars": []map[string]interface{}{ - map[string]interface{}{ - "FOO": "bar", - }, - }, - }, - }, - { - "structure_multi.hcl", - false, - map[string]interface{}{ - "foo": []map[string]interface{}{ - map[string]interface{}{ - "baz": []map[string]interface{}{ - map[string]interface{}{"key": 7}, - }, - }, - map[string]interface{}{ - "bar": []map[string]interface{}{ - map[string]interface{}{"key": 12}, - }, - }, - }, - }, - }, - { - "structure_multi.json", - false, - map[string]interface{}{ - "foo": []map[string]interface{}{ - map[string]interface{}{ - "baz": []map[string]interface{}{ - map[string]interface{}{"key": 7}, - }, - "bar": []map[string]interface{}{ - map[string]interface{}{"key": 12}, - }, - }, - }, - }, - }, - { - "structure_list.hcl", - false, - map[string]interface{}{ - "foo": []map[string]interface{}{ - map[string]interface{}{ - "key": 7, - }, - map[string]interface{}{ - "key": 12, - }, - }, - }, - }, - { - "structure_list.json", - false, - map[string]interface{}{ - "foo": []interface{}{ - map[string]interface{}{ - "key": 7, - }, - map[string]interface{}{ - "key": 12, - }, - }, - }, - }, - { - "structure_list_deep.json", - false, - map[string]interface{}{ - "bar": []map[string]interface{}{ - map[string]interface{}{ - "foo": []map[string]interface{}{ - map[string]interface{}{ - "name": "terraform_example", - "ingress": []interface{}{ - map[string]interface{}{ - "from_port": 22, - }, - map[string]interface{}{ - "from_port": 80, - }, - }, - }, - }, - }, - }, - }, - }, - - { - "nested_block_comment.hcl", - false, - map[string]interface{}{ - "bar": "value", - }, - }, - - { - "unterminated_block_comment.hcl", - true, - nil, - }, - } - - for _, tc := range cases { - d, err := ioutil.ReadFile(filepath.Join(fixtureDir, tc.File)) - if err != nil { - t.Fatalf("err: %s", err) - } - - var out interface{} - err = Decode(&out, string(d)) - if (err != nil) != tc.Err { - t.Fatalf("Input: %s\n\nError: %s", tc.File, err) - } - - if !reflect.DeepEqual(out, tc.Out) { - t.Fatalf("Input: %s\n\nActual: %#v\n\nExpected: %#v", tc.File, out, tc.Out) - } - } -} - -func TestDecode_equal(t *testing.T) { - cases := []struct { - One, Two string - }{ - { - "basic.hcl", - "basic.json", - }, - { - "float.hcl", - "float.json", - }, - /* - { - "structure.hcl", - "structure.json", - }, - */ - { - "structure.hcl", - "structure_flat.json", - }, - { - "terraform_heroku.hcl", - "terraform_heroku.json", - }, - } - - for _, tc := range cases { - p1 := filepath.Join(fixtureDir, tc.One) - p2 := filepath.Join(fixtureDir, tc.Two) - - d1, err := ioutil.ReadFile(p1) - if err != nil { - t.Fatalf("err: %s", err) - } - - d2, err := ioutil.ReadFile(p2) - if err != nil { - t.Fatalf("err: %s", err) - } - - var i1, i2 interface{} - err = Decode(&i1, string(d1)) - if err != nil { - t.Fatalf("err: %s", err) - } - - err = Decode(&i2, string(d2)) - if err != nil { - t.Fatalf("err: %s", err) - } - - if !reflect.DeepEqual(i1, i2) { - t.Fatalf( - "%s != %s\n\n%#v\n\n%#v", - tc.One, tc.Two, - i1, i2) - } - } -} - -func TestDecode_flatMap(t *testing.T) { - var val map[string]map[string]string - - err := Decode(&val, testReadFile(t, "structure_flatmap.hcl")) - if err != nil { - t.Fatalf("err: %s", err) - } - - expected := map[string]map[string]string{ - "foo": map[string]string{ - "foo": "bar", - "key": "7", - }, - } - - if !reflect.DeepEqual(val, expected) { - t.Fatalf("Actual: %#v\n\nExpected: %#v", val, expected) - } -} - -func TestDecode_structure(t *testing.T) { - type V struct { - Key int - Foo string - } - - var actual V - - err := Decode(&actual, testReadFile(t, "flat.hcl")) - if err != nil { - t.Fatalf("err: %s", err) - } - - expected := V{ - Key: 7, - Foo: "bar", - } - - if !reflect.DeepEqual(actual, expected) { - t.Fatalf("Actual: %#v\n\nExpected: %#v", actual, expected) - } -} - -func TestDecode_structurePtr(t *testing.T) { - type V struct { - Key int - Foo string - } - - var actual *V - - err := Decode(&actual, testReadFile(t, "flat.hcl")) - if err != nil { - t.Fatalf("err: %s", err) - } - - expected := &V{ - Key: 7, - Foo: "bar", - } - - if !reflect.DeepEqual(actual, expected) { - t.Fatalf("Actual: %#v\n\nExpected: %#v", actual, expected) - } -} - -func TestDecode_structureArray(t *testing.T) { - // This test is extracted from a failure in Consul (consul.io), - // hence the interesting structure naming. - - type KeyPolicyType string - - type KeyPolicy struct { - Prefix string `hcl:",key"` - Policy KeyPolicyType - } - - type Policy struct { - Keys []KeyPolicy `hcl:"key,expand"` - } - - expected := Policy{ - Keys: []KeyPolicy{ - KeyPolicy{ - Prefix: "", - Policy: "read", - }, - KeyPolicy{ - Prefix: "foo/", - Policy: "write", - }, - KeyPolicy{ - Prefix: "foo/bar/", - Policy: "read", - }, - KeyPolicy{ - Prefix: "foo/bar/baz", - Policy: "deny", - }, - }, - } - - files := []string{ - "decode_policy.hcl", - "decode_policy.json", - } - - for _, f := range files { - var actual Policy - - err := Decode(&actual, testReadFile(t, f)) - if err != nil { - t.Fatalf("err: %s", err) - } - - if !reflect.DeepEqual(actual, expected) { - t.Fatalf("Input: %s\n\nActual: %#v\n\nExpected: %#v", f, actual, expected) - } - } -} - -func TestDecode_structureMap(t *testing.T) { - // This test is extracted from a failure in Terraform (terraform.io), - // hence the interesting structure naming. - - type hclVariable struct { - Default interface{} - Description string - Fields []string `hcl:",decodedFields"` - } - - type rawConfig struct { - Variable map[string]hclVariable - } - - expected := rawConfig{ - Variable: map[string]hclVariable{ - "foo": hclVariable{ - Default: "bar", - Description: "bar", - Fields: []string{"Default", "Description"}, - }, - - "amis": hclVariable{ - Default: []map[string]interface{}{ - map[string]interface{}{ - "east": "foo", - }, - }, - Fields: []string{"Default"}, - }, - }, - } - - files := []string{ - "decode_tf_variable.hcl", - "decode_tf_variable.json", - } - - for _, f := range files { - var actual rawConfig - - err := Decode(&actual, testReadFile(t, f)) - if err != nil { - t.Fatalf("Input: %s\n\nerr: %s", f, err) - } - - if !reflect.DeepEqual(actual, expected) { - t.Fatalf("Input: %s\n\nActual: %#v\n\nExpected: %#v", f, actual, expected) - } - } -} - -func TestDecode_interfaceNonPointer(t *testing.T) { - var value interface{} - err := Decode(value, testReadFile(t, "basic_int_string.hcl")) - if err == nil { - t.Fatal("should error") - } -} - -func TestDecode_intString(t *testing.T) { - var value struct { - Count int - } - - err := Decode(&value, testReadFile(t, "basic_int_string.hcl")) - if err != nil { - t.Fatalf("err: %s", err) - } - - if value.Count != 3 { - t.Fatalf("bad: %#v", value.Count) - } -} diff --git a/Godeps/_workspace/src/github.com/hashicorp/hcl/hcl/hcl_test.go b/Godeps/_workspace/src/github.com/hashicorp/hcl/hcl/hcl_test.go deleted file mode 100644 index dfefd28b3..000000000 --- a/Godeps/_workspace/src/github.com/hashicorp/hcl/hcl/hcl_test.go +++ /dev/null @@ -1,4 +0,0 @@ -package hcl - -// This is the directory where our test fixtures are. -const fixtureDir = "./test-fixtures" diff --git a/Godeps/_workspace/src/github.com/hashicorp/hcl/hcl/lex.go b/Godeps/_workspace/src/github.com/hashicorp/hcl/hcl/lex.go index c14165956..54eb1c8ab 100644 --- a/Godeps/_workspace/src/github.com/hashicorp/hcl/hcl/lex.go +++ b/Godeps/_workspace/src/github.com/hashicorp/hcl/hcl/lex.go @@ -85,7 +85,7 @@ func (x *hclLex) Lex(yylval *hclSymType) int { case '-': return MINUS case ',': - return x.lexComma() + return COMMA case '=': return EQUAL case '[': @@ -166,27 +166,6 @@ func (x *hclLex) consumeComment(c rune) bool { } } -// lexComma reads the comma -func (x *hclLex) lexComma() int { - for { - c := x.peek() - - // Consume space - if unicode.IsSpace(c) { - x.next() - continue - } - - if c == ']' { - return COMMAEND - } - - break - } - - return COMMA -} - // lexId lexes an identifier func (x *hclLex) lexId(yylval *hclSymType) int { var b bytes.Buffer diff --git a/Godeps/_workspace/src/github.com/hashicorp/hcl/hcl/lex_test.go b/Godeps/_workspace/src/github.com/hashicorp/hcl/hcl/lex_test.go deleted file mode 100644 index dcdd9b375..000000000 --- a/Godeps/_workspace/src/github.com/hashicorp/hcl/hcl/lex_test.go +++ /dev/null @@ -1,95 +0,0 @@ -package hcl - -import ( - "io/ioutil" - "path/filepath" - "reflect" - "testing" -) - -func TestLex(t *testing.T) { - cases := []struct { - Input string - Output []int - }{ - { - "comment.hcl", - []int{IDENTIFIER, EQUAL, STRING, lexEOF}, - }, - { - "comment_single.hcl", - []int{lexEOF}, - }, - { - "complex_key.hcl", - []int{IDENTIFIER, EQUAL, STRING, lexEOF}, - }, - { - "multiple.hcl", - []int{ - IDENTIFIER, EQUAL, STRING, - IDENTIFIER, EQUAL, NUMBER, - lexEOF, - }, - }, - { - "list.hcl", - []int{ - IDENTIFIER, EQUAL, LEFTBRACKET, - NUMBER, COMMA, NUMBER, COMMA, STRING, - RIGHTBRACKET, lexEOF, - }, - }, - { - "old.hcl", - []int{IDENTIFIER, EQUAL, LEFTBRACE, STRING, lexEOF}, - }, - { - "structure_basic.hcl", - []int{ - IDENTIFIER, LEFTBRACE, - IDENTIFIER, EQUAL, NUMBER, - STRING, EQUAL, NUMBER, - STRING, EQUAL, NUMBER, - RIGHTBRACE, lexEOF, - }, - }, - { - "structure.hcl", - []int{ - IDENTIFIER, IDENTIFIER, STRING, LEFTBRACE, - IDENTIFIER, EQUAL, NUMBER, - IDENTIFIER, EQUAL, STRING, - RIGHTBRACE, lexEOF, - }, - }, - } - - for _, tc := range cases { - d, err := ioutil.ReadFile(filepath.Join(fixtureDir, tc.Input)) - if err != nil { - t.Fatalf("err: %s", err) - } - - l := &hclLex{Input: string(d)} - var actual []int - for { - token := l.Lex(new(hclSymType)) - actual = append(actual, token) - - if token == lexEOF { - break - } - - if len(actual) > 500 { - t.Fatalf("Input:%s\n\nExausted.", tc.Input) - } - } - - if !reflect.DeepEqual(actual, tc.Output) { - t.Fatalf( - "Input: %s\n\nBad: %#v\n\nExpected: %#v", - tc.Input, actual, tc.Output) - } - } -} diff --git a/Godeps/_workspace/src/github.com/hashicorp/hcl/hcl/parse.y b/Godeps/_workspace/src/github.com/hashicorp/hcl/hcl/parse.y index 4f42d3456..6144a87ab 100644 --- a/Godeps/_workspace/src/github.com/hashicorp/hcl/hcl/parse.y +++ b/Godeps/_workspace/src/github.com/hashicorp/hcl/hcl/parse.y @@ -29,7 +29,7 @@ import ( %token BOOL %token FLOAT %token NUMBER -%token COMMA COMMAEND IDENTIFIER EQUAL NEWLINE STRING MINUS +%token COMMA IDENTIFIER EQUAL NEWLINE STRING MINUS %token LEFTBRACE RIGHTBRACE LEFTBRACKET RIGHTBRACKET PERIOD %token EPLUS EMINUS @@ -152,6 +152,10 @@ list: { $$ = $2 } +| LEFTBRACKET listitems COMMA RIGHTBRACKET + { + $$ = $2 + } | LEFTBRACKET RIGHTBRACKET { $$ = nil @@ -166,10 +170,6 @@ listitems: { $$ = append($1, $3) } -| listitems COMMAEND - { - $$ = $1 - } listitem: number diff --git a/Godeps/_workspace/src/github.com/hashicorp/hcl/hcl/parse_test.go b/Godeps/_workspace/src/github.com/hashicorp/hcl/hcl/parse_test.go deleted file mode 100644 index ea3047ba6..000000000 --- a/Godeps/_workspace/src/github.com/hashicorp/hcl/hcl/parse_test.go +++ /dev/null @@ -1,75 +0,0 @@ -package hcl - -import ( - "io/ioutil" - "path/filepath" - "testing" -) - -func TestParse(t *testing.T) { - cases := []struct { - Name string - Err bool - }{ - { - "assign_colon.hcl", - true, - }, - { - "comment.hcl", - false, - }, - { - "comment_single.hcl", - false, - }, - { - "empty.hcl", - false, - }, - { - "list_comma.hcl", - false, - }, - { - "multiple.hcl", - false, - }, - { - "structure.hcl", - false, - }, - { - "structure_basic.hcl", - false, - }, - { - "structure_empty.hcl", - false, - }, - { - "complex.hcl", - false, - }, - { - "assign_deep.hcl", - true, - }, - { - "types.hcl", - false, - }, - } - - for _, tc := range cases { - d, err := ioutil.ReadFile(filepath.Join(fixtureDir, tc.Name)) - if err != nil { - t.Fatalf("err: %s", err) - } - - _, err = Parse(string(d)) - if (err != nil) != tc.Err { - t.Fatalf("Input: %s\n\nError: %s", tc.Name, err) - } - } -} diff --git a/Godeps/_workspace/src/github.com/hashicorp/hcl/hcl/y.go b/Godeps/_workspace/src/github.com/hashicorp/hcl/hcl/y.go index f139a2477..f3ae8f29f 100644 --- a/Godeps/_workspace/src/github.com/hashicorp/hcl/hcl/y.go +++ b/Godeps/_workspace/src/github.com/hashicorp/hcl/hcl/y.go @@ -24,26 +24,27 @@ const BOOL = 57346 const FLOAT = 57347 const NUMBER = 57348 const COMMA = 57349 -const COMMAEND = 57350 -const IDENTIFIER = 57351 -const EQUAL = 57352 -const NEWLINE = 57353 -const STRING = 57354 -const MINUS = 57355 -const LEFTBRACE = 57356 -const RIGHTBRACE = 57357 -const LEFTBRACKET = 57358 -const RIGHTBRACKET = 57359 -const PERIOD = 57360 -const EPLUS = 57361 -const EMINUS = 57362 +const IDENTIFIER = 57350 +const EQUAL = 57351 +const NEWLINE = 57352 +const STRING = 57353 +const MINUS = 57354 +const LEFTBRACE = 57355 +const RIGHTBRACE = 57356 +const LEFTBRACKET = 57357 +const RIGHTBRACKET = 57358 +const PERIOD = 57359 +const EPLUS = 57360 +const EMINUS = 57361 -var hclToknames = []string{ +var hclToknames = [...]string{ + "$end", + "error", + "$unk", "BOOL", "FLOAT", "NUMBER", "COMMA", - "COMMAEND", "IDENTIFIER", "EQUAL", "NEWLINE", @@ -57,7 +58,7 @@ var hclToknames = []string{ "EPLUS", "EMINUS", } -var hclStatenames = []string{} +var hclStatenames = [...]string{} const hclEofCode = 1 const hclErrCode = 2 @@ -66,15 +67,15 @@ const hclMaxDepth = 200 //line parse.y:259 //line yacctab:1 -var hclExca = []int{ +var hclExca = [...]int{ -1, 1, 1, -1, -2, 0, -1, 6, - 10, 7, + 9, 7, -2, 17, -1, 7, - 10, 8, + 9, 8, -2, 18, } @@ -84,92 +85,120 @@ const hclPrivate = 57344 var hclTokenNames []string var hclStates []string -const hclLast = 62 +const hclLast = 64 -var hclAct = []int{ +var hclAct = [...]int{ 35, 3, 21, 22, 9, 30, 31, 29, 17, 26, - 25, 26, 25, 10, 26, 25, 18, 24, 13, 24, - 23, 37, 24, 44, 45, 42, 34, 38, 39, 9, - 32, 6, 6, 43, 7, 7, 2, 40, 28, 26, - 25, 6, 41, 11, 7, 46, 37, 24, 14, 36, - 27, 15, 5, 13, 19, 1, 4, 8, 33, 20, - 16, 12, + 25, 11, 44, 26, 25, 18, 24, 13, 10, 23, + 24, 43, 19, 2, 42, 26, 25, 38, 39, 9, + 32, 37, 24, 26, 25, 6, 45, 27, 7, 37, + 24, 40, 36, 6, 34, 46, 7, 14, 6, 28, + 15, 7, 13, 16, 5, 41, 1, 4, 8, 33, + 20, 0, 0, 12, } -var hclPact = []int{ +var hclPact = [...]int{ - 32, -1000, 32, -1000, 3, -1000, -1000, -1000, 39, -1000, - 4, -1000, -1000, 23, -1000, -1000, -1000, -1000, -1000, -1000, - -1000, -14, -14, 9, 6, -1000, -1000, 22, -1000, -1000, - 36, 19, -1000, 16, -1000, -1000, -1000, -1000, -1000, -1000, - -1000, -1000, -1000, -1000, 34, -1000, -1000, + 40, -1000, 40, -1000, 9, -1000, -1000, -1000, 39, -1000, + 4, -1000, -1000, 35, -1000, -1000, -1000, -1000, -1000, -1000, + -1000, -13, -13, 28, 8, -1000, -1000, 27, -1000, -1000, + 49, 18, -1000, 5, -1000, -1000, -1000, -1000, -1000, -1000, + -1000, -1000, -1000, -1000, 20, -1000, -1000, } -var hclPgo = []int{ +var hclPgo = [...]int{ - 0, 3, 2, 59, 58, 36, 52, 49, 43, 1, - 0, 57, 7, 56, 55, + 0, 3, 2, 60, 59, 23, 54, 42, 11, 1, + 0, 58, 7, 57, 56, } -var hclR1 = []int{ +var hclR1 = [...]int{ 0, 14, 14, 5, 5, 8, 8, 13, 13, 9, 9, 9, 9, 9, 9, 6, 6, 11, 11, 3, - 3, 4, 4, 4, 10, 10, 7, 7, 7, 7, + 3, 3, 4, 4, 10, 10, 7, 7, 7, 7, 2, 2, 1, 1, 12, 12, } -var hclR2 = []int{ +var hclR2 = [...]int{ 0, 0, 1, 1, 2, 3, 2, 1, 1, 3, 3, 3, 3, 3, 1, 2, 2, 1, 1, 3, - 2, 1, 3, 2, 1, 1, 1, 1, 2, 2, + 4, 2, 1, 3, 1, 1, 1, 1, 2, 2, 2, 1, 2, 1, 2, 2, } -var hclChk = []int{ +var hclChk = [...]int{ - -1000, -14, -5, -9, -13, -6, 9, 12, -11, -9, - 10, -8, -6, 14, 9, 12, -7, 4, 12, -8, - -3, -2, -1, 16, 13, 6, 5, -5, 15, -12, - 19, 20, -12, -4, 17, -10, -7, 12, -2, -1, - 15, 6, 6, 17, 7, 8, -10, + -1000, -14, -5, -9, -13, -6, 8, 11, -11, -9, + 9, -8, -6, 13, 8, 11, -7, 4, 11, -8, + -3, -2, -1, 15, 12, 6, 5, -5, 14, -12, + 18, 19, -12, -4, 16, -10, -7, 11, -2, -1, + 14, 6, 6, 16, 7, 16, -10, } -var hclDef = []int{ +var hclDef = [...]int{ 1, -2, 2, 3, 0, 14, -2, -2, 0, 4, 0, 15, 16, 0, 17, 18, 9, 10, 11, 12, 13, 26, 27, 0, 0, 31, 33, 0, 6, 28, - 0, 0, 29, 0, 20, 21, 24, 25, 30, 32, - 5, 34, 35, 19, 0, 23, 22, + 0, 0, 29, 0, 21, 22, 24, 25, 30, 32, + 5, 34, 35, 19, 0, 20, 23, } -var hclTok1 = []int{ +var hclTok1 = [...]int{ 1, } -var hclTok2 = []int{ +var hclTok2 = [...]int{ 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, - 12, 13, 14, 15, 16, 17, 18, 19, 20, + 12, 13, 14, 15, 16, 17, 18, 19, } -var hclTok3 = []int{ +var hclTok3 = [...]int{ 0, } +var hclErrorMessages = [...]struct { + state int + token int + msg string +}{} + //line yaccpar:1 /* parser for yacc output */ -var hclDebug = 0 +var ( + hclDebug = 0 + hclErrorVerbose = false +) type hclLexer interface { Lex(lval *hclSymType) int Error(s string) } +type hclParser interface { + Parse(hclLexer) int + Lookahead() int +} + +type hclParserImpl struct { + lookahead func() int +} + +func (p *hclParserImpl) Lookahead() int { + return p.lookahead() +} + +func hclNewParser() hclParser { + p := &hclParserImpl{ + lookahead: func() int { return -1 }, + } + return p +} + const hclFlag = -1000 func hclTokname(c int) string { - // 4 is TOKSTART above - if c >= 4 && c-4 < len(hclToknames) { - if hclToknames[c-4] != "" { - return hclToknames[c-4] + if c >= 1 && c-1 < len(hclToknames) { + if hclToknames[c-1] != "" { + return hclToknames[c-1] } } return __yyfmt__.Sprintf("tok-%v", c) @@ -184,51 +213,129 @@ func hclStatname(s int) string { return __yyfmt__.Sprintf("state-%v", s) } -func hcllex1(lex hclLexer, lval *hclSymType) int { - c := 0 - char := lex.Lex(lval) +func hclErrorMessage(state, lookAhead int) string { + const TOKSTART = 4 + + if !hclErrorVerbose { + return "syntax error" + } + + for _, e := range hclErrorMessages { + if e.state == state && e.token == lookAhead { + return "syntax error: " + e.msg + } + } + + res := "syntax error: unexpected " + hclTokname(lookAhead) + + // To match Bison, suggest at most four expected tokens. + expected := make([]int, 0, 4) + + // Look for shiftable tokens. + base := hclPact[state] + for tok := TOKSTART; tok-1 < len(hclToknames); tok++ { + if n := base + tok; n >= 0 && n < hclLast && hclChk[hclAct[n]] == tok { + if len(expected) == cap(expected) { + return res + } + expected = append(expected, tok) + } + } + + if hclDef[state] == -2 { + i := 0 + for hclExca[i] != -1 || hclExca[i+1] != state { + i += 2 + } + + // Look for tokens that we accept or reduce. + for i += 2; hclExca[i] >= 0; i += 2 { + tok := hclExca[i] + if tok < TOKSTART || hclExca[i+1] == 0 { + continue + } + if len(expected) == cap(expected) { + return res + } + expected = append(expected, tok) + } + + // If the default action is to accept or reduce, give up. + if hclExca[i+1] != 0 { + return res + } + } + + for i, tok := range expected { + if i == 0 { + res += ", expecting " + } else { + res += " or " + } + res += hclTokname(tok) + } + return res +} + +func hcllex1(lex hclLexer, lval *hclSymType) (char, token int) { + token = 0 + char = lex.Lex(lval) if char <= 0 { - c = hclTok1[0] + token = hclTok1[0] goto out } if char < len(hclTok1) { - c = hclTok1[char] + token = hclTok1[char] goto out } if char >= hclPrivate { if char < hclPrivate+len(hclTok2) { - c = hclTok2[char-hclPrivate] + token = hclTok2[char-hclPrivate] goto out } } for i := 0; i < len(hclTok3); i += 2 { - c = hclTok3[i+0] - if c == char { - c = hclTok3[i+1] + token = hclTok3[i+0] + if token == char { + token = hclTok3[i+1] goto out } } out: - if c == 0 { - c = hclTok2[1] /* unknown char */ + if token == 0 { + token = hclTok2[1] /* unknown char */ } if hclDebug >= 3 { - __yyfmt__.Printf("lex %s(%d)\n", hclTokname(c), uint(char)) + __yyfmt__.Printf("lex %s(%d)\n", hclTokname(token), uint(char)) } - return c + return char, token } func hclParse(hcllex hclLexer) int { + return hclNewParser().Parse(hcllex) +} + +func (hclrcvr *hclParserImpl) Parse(hcllex hclLexer) int { var hcln int var hcllval hclSymType var hclVAL hclSymType + var hclDollar []hclSymType + _ = hclDollar // silence set and not used hclS := make([]hclSymType, hclMaxDepth) Nerrs := 0 /* number of errors */ Errflag := 0 /* error recovery flag */ hclstate := 0 hclchar := -1 + hcltoken := -1 // hclchar translated into internal numbering + hclrcvr.lookahead = func() int { return hclchar } + defer func() { + // Make sure we report no lookahead when not parsing. + hclstate = -1 + hclchar = -1 + hcltoken = -1 + }() hclp := -1 goto hclstack @@ -241,7 +348,7 @@ ret1: hclstack: /* put a state and value onto the stack */ if hclDebug >= 4 { - __yyfmt__.Printf("char %v in %v\n", hclTokname(hclchar), hclStatname(hclstate)) + __yyfmt__.Printf("char %v in %v\n", hclTokname(hcltoken), hclStatname(hclstate)) } hclp++ @@ -259,15 +366,16 @@ hclnewstate: goto hcldefault /* simple state */ } if hclchar < 0 { - hclchar = hcllex1(hcllex, &hcllval) + hclchar, hcltoken = hcllex1(hcllex, &hcllval) } - hcln += hclchar + hcln += hcltoken if hcln < 0 || hcln >= hclLast { goto hcldefault } hcln = hclAct[hcln] - if hclChk[hcln] == hclchar { /* valid shift */ + if hclChk[hcln] == hcltoken { /* valid shift */ hclchar = -1 + hcltoken = -1 hclVAL = hcllval hclstate = hcln if Errflag > 0 { @@ -281,7 +389,7 @@ hcldefault: hcln = hclDef[hclstate] if hcln == -2 { if hclchar < 0 { - hclchar = hcllex1(hcllex, &hcllval) + hclchar, hcltoken = hcllex1(hcllex, &hcllval) } /* look through exception table */ @@ -294,7 +402,7 @@ hcldefault: } for xi += 2; ; xi += 2 { hcln = hclExca[xi+0] - if hcln < 0 || hcln == hclchar { + if hcln < 0 || hcln == hcltoken { break } } @@ -307,11 +415,11 @@ hcldefault: /* error ... attempt to resume parsing */ switch Errflag { case 0: /* brand new error */ - hcllex.Error("syntax error") + hcllex.Error(hclErrorMessage(hclstate, hcltoken)) Nerrs++ if hclDebug >= 1 { __yyfmt__.Printf("%s", hclStatname(hclstate)) - __yyfmt__.Printf(" saw %s\n", hclTokname(hclchar)) + __yyfmt__.Printf(" saw %s\n", hclTokname(hcltoken)) } fallthrough @@ -339,12 +447,13 @@ hcldefault: case 3: /* no shift yet; clobber input char */ if hclDebug >= 2 { - __yyfmt__.Printf("error recovery discards %s\n", hclTokname(hclchar)) + __yyfmt__.Printf("error recovery discards %s\n", hclTokname(hcltoken)) } - if hclchar == hclEofCode { + if hcltoken == hclEofCode { goto ret1 } hclchar = -1 + hcltoken = -1 goto hclnewstate /* try again in the same state */ } } @@ -359,6 +468,13 @@ hcldefault: _ = hclpt // guard against "declared and not used" hclp -= hclR2[hcln] + // hclp is now the index of $0. Perform the default action. Iff the + // reduced production is ε, $1 is possibly out of range. + if hclp+1 >= len(hclS) { + nyys := make([]hclSymType, len(hclS)*2) + copy(nyys, hclS) + hclS = nyys + } hclVAL = hclS[hclp+1] /* consult goto table to find next state */ @@ -378,37 +494,43 @@ hcldefault: switch hclnt { case 1: + hclDollar = hclS[hclpt-0 : hclpt+1] //line parse.y:39 { hclResult = &Object{Type: ValueTypeObject} } case 2: + hclDollar = hclS[hclpt-1 : hclpt+1] //line parse.y:43 { hclResult = &Object{ Type: ValueTypeObject, - Value: ObjectList(hclS[hclpt-0].objlist).Flat(), + Value: ObjectList(hclDollar[1].objlist).Flat(), } } case 3: + hclDollar = hclS[hclpt-1 : hclpt+1] //line parse.y:52 { - hclVAL.objlist = []*Object{hclS[hclpt-0].obj} + hclVAL.objlist = []*Object{hclDollar[1].obj} } case 4: + hclDollar = hclS[hclpt-2 : hclpt+1] //line parse.y:56 { - hclVAL.objlist = append(hclS[hclpt-1].objlist, hclS[hclpt-0].obj) + hclVAL.objlist = append(hclDollar[1].objlist, hclDollar[2].obj) } case 5: + hclDollar = hclS[hclpt-3 : hclpt+1] //line parse.y:62 { hclVAL.obj = &Object{ Type: ValueTypeObject, - Value: ObjectList(hclS[hclpt-1].objlist).Flat(), + Value: ObjectList(hclDollar[2].objlist).Flat(), } } case 6: + hclDollar = hclS[hclpt-2 : hclpt+1] //line parse.y:69 { hclVAL.obj = &Object{ @@ -416,142 +538,164 @@ hcldefault: } } case 7: + hclDollar = hclS[hclpt-1 : hclpt+1] //line parse.y:77 { - hclVAL.str = hclS[hclpt-0].str + hclVAL.str = hclDollar[1].str } case 8: + hclDollar = hclS[hclpt-1 : hclpt+1] //line parse.y:81 { - hclVAL.str = hclS[hclpt-0].str + hclVAL.str = hclDollar[1].str } case 9: + hclDollar = hclS[hclpt-3 : hclpt+1] //line parse.y:87 { - hclVAL.obj = hclS[hclpt-0].obj - hclVAL.obj.Key = hclS[hclpt-2].str + hclVAL.obj = hclDollar[3].obj + hclVAL.obj.Key = hclDollar[1].str } case 10: + hclDollar = hclS[hclpt-3 : hclpt+1] //line parse.y:92 { hclVAL.obj = &Object{ - Key: hclS[hclpt-2].str, + Key: hclDollar[1].str, Type: ValueTypeBool, - Value: hclS[hclpt-0].b, + Value: hclDollar[3].b, } } case 11: + hclDollar = hclS[hclpt-3 : hclpt+1] //line parse.y:100 { hclVAL.obj = &Object{ - Key: hclS[hclpt-2].str, + Key: hclDollar[1].str, Type: ValueTypeString, - Value: hclS[hclpt-0].str, + Value: hclDollar[3].str, } } case 12: + hclDollar = hclS[hclpt-3 : hclpt+1] //line parse.y:108 { - hclS[hclpt-0].obj.Key = hclS[hclpt-2].str - hclVAL.obj = hclS[hclpt-0].obj + hclDollar[3].obj.Key = hclDollar[1].str + hclVAL.obj = hclDollar[3].obj } case 13: + hclDollar = hclS[hclpt-3 : hclpt+1] //line parse.y:113 { hclVAL.obj = &Object{ - Key: hclS[hclpt-2].str, + Key: hclDollar[1].str, Type: ValueTypeList, - Value: hclS[hclpt-0].objlist, + Value: hclDollar[3].objlist, } } case 14: + hclDollar = hclS[hclpt-1 : hclpt+1] //line parse.y:121 { - hclVAL.obj = hclS[hclpt-0].obj + hclVAL.obj = hclDollar[1].obj } case 15: + hclDollar = hclS[hclpt-2 : hclpt+1] //line parse.y:127 { - hclS[hclpt-0].obj.Key = hclS[hclpt-1].str - hclVAL.obj = hclS[hclpt-0].obj + hclDollar[2].obj.Key = hclDollar[1].str + hclVAL.obj = hclDollar[2].obj } case 16: + hclDollar = hclS[hclpt-2 : hclpt+1] //line parse.y:132 { hclVAL.obj = &Object{ - Key: hclS[hclpt-1].str, + Key: hclDollar[1].str, Type: ValueTypeObject, - Value: []*Object{hclS[hclpt-0].obj}, + Value: []*Object{hclDollar[2].obj}, } } case 17: + hclDollar = hclS[hclpt-1 : hclpt+1] //line parse.y:142 { - hclVAL.str = hclS[hclpt-0].str + hclVAL.str = hclDollar[1].str } case 18: + hclDollar = hclS[hclpt-1 : hclpt+1] //line parse.y:146 { - hclVAL.str = hclS[hclpt-0].str + hclVAL.str = hclDollar[1].str } case 19: + hclDollar = hclS[hclpt-3 : hclpt+1] //line parse.y:152 { - hclVAL.objlist = hclS[hclpt-1].objlist + hclVAL.objlist = hclDollar[2].objlist } case 20: + hclDollar = hclS[hclpt-4 : hclpt+1] //line parse.y:156 + { + hclVAL.objlist = hclDollar[2].objlist + } + case 21: + hclDollar = hclS[hclpt-2 : hclpt+1] + //line parse.y:160 { hclVAL.objlist = nil } - case 21: - //line parse.y:162 - { - hclVAL.objlist = []*Object{hclS[hclpt-0].obj} - } case 22: + hclDollar = hclS[hclpt-1 : hclpt+1] //line parse.y:166 { - hclVAL.objlist = append(hclS[hclpt-2].objlist, hclS[hclpt-0].obj) + hclVAL.objlist = []*Object{hclDollar[1].obj} } case 23: + hclDollar = hclS[hclpt-3 : hclpt+1] //line parse.y:170 { - hclVAL.objlist = hclS[hclpt-1].objlist + hclVAL.objlist = append(hclDollar[1].objlist, hclDollar[3].obj) } case 24: + hclDollar = hclS[hclpt-1 : hclpt+1] //line parse.y:176 { - hclVAL.obj = hclS[hclpt-0].obj + hclVAL.obj = hclDollar[1].obj } case 25: + hclDollar = hclS[hclpt-1 : hclpt+1] //line parse.y:180 { hclVAL.obj = &Object{ Type: ValueTypeString, - Value: hclS[hclpt-0].str, + Value: hclDollar[1].str, } } case 26: + hclDollar = hclS[hclpt-1 : hclpt+1] //line parse.y:189 { hclVAL.obj = &Object{ Type: ValueTypeInt, - Value: hclS[hclpt-0].num, + Value: hclDollar[1].num, } } case 27: + hclDollar = hclS[hclpt-1 : hclpt+1] //line parse.y:196 { hclVAL.obj = &Object{ Type: ValueTypeFloat, - Value: hclS[hclpt-0].f, + Value: hclDollar[1].f, } } case 28: + hclDollar = hclS[hclpt-2 : hclpt+1] //line parse.y:203 { - fs := fmt.Sprintf("%d%s", hclS[hclpt-1].num, hclS[hclpt-0].str) + fs := fmt.Sprintf("%d%s", hclDollar[1].num, hclDollar[2].str) f, err := strconv.ParseFloat(fs, 64) if err != nil { panic(err) @@ -563,9 +707,10 @@ hcldefault: } } case 29: + hclDollar = hclS[hclpt-2 : hclpt+1] //line parse.y:216 { - fs := fmt.Sprintf("%f%s", hclS[hclpt-1].f, hclS[hclpt-0].str) + fs := fmt.Sprintf("%f%s", hclDollar[1].f, hclDollar[2].str) f, err := strconv.ParseFloat(fs, 64) if err != nil { panic(err) @@ -577,34 +722,40 @@ hcldefault: } } case 30: + hclDollar = hclS[hclpt-2 : hclpt+1] //line parse.y:231 { - hclVAL.num = hclS[hclpt-0].num * -1 + hclVAL.num = hclDollar[2].num * -1 } case 31: + hclDollar = hclS[hclpt-1 : hclpt+1] //line parse.y:235 { - hclVAL.num = hclS[hclpt-0].num + hclVAL.num = hclDollar[1].num } case 32: + hclDollar = hclS[hclpt-2 : hclpt+1] //line parse.y:241 { - hclVAL.f = hclS[hclpt-0].f * -1 + hclVAL.f = hclDollar[2].f * -1 } case 33: + hclDollar = hclS[hclpt-1 : hclpt+1] //line parse.y:245 { - hclVAL.f = hclS[hclpt-0].f + hclVAL.f = hclDollar[1].f } case 34: + hclDollar = hclS[hclpt-2 : hclpt+1] //line parse.y:251 { - hclVAL.str = "e" + strconv.FormatInt(int64(hclS[hclpt-0].num), 10) + hclVAL.str = "e" + strconv.FormatInt(int64(hclDollar[2].num), 10) } case 35: + hclDollar = hclS[hclpt-2 : hclpt+1] //line parse.y:255 { - hclVAL.str = "e-" + strconv.FormatInt(int64(hclS[hclpt-0].num), 10) + hclVAL.str = "e-" + strconv.FormatInt(int64(hclDollar[2].num), 10) } } goto hclstack /* stack new state and value */ diff --git a/Godeps/_workspace/src/github.com/hashicorp/hcl/hcl_test.go b/Godeps/_workspace/src/github.com/hashicorp/hcl/hcl_test.go deleted file mode 100644 index 31dff7c9e..000000000 --- a/Godeps/_workspace/src/github.com/hashicorp/hcl/hcl_test.go +++ /dev/null @@ -1,19 +0,0 @@ -package hcl - -import ( - "io/ioutil" - "path/filepath" - "testing" -) - -// This is the directory where our test fixtures are. -const fixtureDir = "./test-fixtures" - -func testReadFile(t *testing.T, n string) string { - d, err := ioutil.ReadFile(filepath.Join(fixtureDir, n)) - if err != nil { - t.Fatalf("err: %s", err) - } - - return string(d) -} diff --git a/Godeps/_workspace/src/github.com/hashicorp/hcl/json/json_test.go b/Godeps/_workspace/src/github.com/hashicorp/hcl/json/json_test.go deleted file mode 100644 index 418582b4c..000000000 --- a/Godeps/_workspace/src/github.com/hashicorp/hcl/json/json_test.go +++ /dev/null @@ -1,4 +0,0 @@ -package json - -// This is the directory where our test fixtures are. -const fixtureDir = "./test-fixtures" diff --git a/Godeps/_workspace/src/github.com/hashicorp/hcl/json/lex_test.go b/Godeps/_workspace/src/github.com/hashicorp/hcl/json/lex_test.go deleted file mode 100644 index f573fba1b..000000000 --- a/Godeps/_workspace/src/github.com/hashicorp/hcl/json/lex_test.go +++ /dev/null @@ -1,78 +0,0 @@ -package json - -import ( - "io/ioutil" - "path/filepath" - "reflect" - "testing" -) - -func TestLexJson(t *testing.T) { - cases := []struct { - Input string - Output []int - }{ - { - "basic.json", - []int{ - LEFTBRACE, - STRING, COLON, STRING, - RIGHTBRACE, - lexEOF, - }, - }, - { - "array.json", - []int{ - LEFTBRACE, - STRING, COLON, LEFTBRACKET, - NUMBER, COMMA, NUMBER, COMMA, STRING, - RIGHTBRACKET, COMMA, - STRING, COLON, STRING, - RIGHTBRACE, - lexEOF, - }, - }, - { - "object.json", - []int{ - LEFTBRACE, - STRING, COLON, LEFTBRACE, - STRING, COLON, LEFTBRACKET, - NUMBER, COMMA, NUMBER, - RIGHTBRACKET, - RIGHTBRACE, - RIGHTBRACE, - lexEOF, - }, - }, - } - - for _, tc := range cases { - d, err := ioutil.ReadFile(filepath.Join(fixtureDir, tc.Input)) - if err != nil { - t.Fatalf("err: %s", err) - } - - l := &jsonLex{Input: string(d)} - var actual []int - for { - token := l.Lex(new(jsonSymType)) - actual = append(actual, token) - - if token == lexEOF { - break - } - - if len(actual) > 500 { - t.Fatalf("Input:%s\n\nExausted.", tc.Input) - } - } - - if !reflect.DeepEqual(actual, tc.Output) { - t.Fatalf( - "Input: %s\n\nBad: %#v\n\nExpected: %#v", - tc.Input, actual, tc.Output) - } - } -} diff --git a/Godeps/_workspace/src/github.com/hashicorp/hcl/json/parse_test.go b/Godeps/_workspace/src/github.com/hashicorp/hcl/json/parse_test.go deleted file mode 100644 index 806acb9ab..000000000 --- a/Godeps/_workspace/src/github.com/hashicorp/hcl/json/parse_test.go +++ /dev/null @@ -1,43 +0,0 @@ -package json - -import ( - "io/ioutil" - "path/filepath" - "testing" -) - -func TestParse(t *testing.T) { - cases := []struct { - Name string - Err bool - }{ - { - "basic.json", - false, - }, - { - "object.json", - false, - }, - { - "array.json", - false, - }, - { - "types.json", - false, - }, - } - - for _, tc := range cases { - d, err := ioutil.ReadFile(filepath.Join(fixtureDir, tc.Name)) - if err != nil { - t.Fatalf("err: %s", err) - } - - _, err = Parse(string(d)) - if (err != nil) != tc.Err { - t.Fatalf("Input: %s\n\nError: %s", tc.Name, err) - } - } -} diff --git a/Godeps/_workspace/src/github.com/hashicorp/hcl/json/y.go b/Godeps/_workspace/src/github.com/hashicorp/hcl/json/y.go index 075270a99..a57649e52 100644 --- a/Godeps/_workspace/src/github.com/hashicorp/hcl/json/y.go +++ b/Godeps/_workspace/src/github.com/hashicorp/hcl/json/y.go @@ -41,7 +41,10 @@ const PERIOD = 57362 const EPLUS = 57363 const EMINUS = 57364 -var jsonToknames = []string{ +var jsonToknames = [...]string{ + "$end", + "error", + "$unk", "FLOAT", "NUMBER", "COLON", @@ -62,7 +65,7 @@ var jsonToknames = []string{ "EPLUS", "EMINUS", } -var jsonStatenames = []string{} +var jsonStatenames = [...]string{} const jsonEofCode = 1 const jsonErrCode = 2 @@ -71,7 +74,7 @@ const jsonMaxDepth = 200 //line parse.y:210 //line yacctab:1 -var jsonExca = []int{ +var jsonExca = [...]int{ -1, 1, 1, -1, -2, 0, @@ -85,7 +88,7 @@ var jsonStates []string const jsonLast = 53 -var jsonAct = []int{ +var jsonAct = [...]int{ 12, 25, 24, 3, 20, 27, 28, 7, 13, 3, 21, 22, 30, 17, 18, 19, 23, 25, 24, 26, @@ -94,76 +97,104 @@ var jsonAct = []int{ 5, 29, 6, 8, 37, 15, 2, 1, 4, 31, 16, 14, 11, } -var jsonPact = []int{ +var jsonPact = [...]int{ -9, -1000, -1000, 27, 30, -1000, -1000, 20, -1000, -4, 13, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -16, -16, -3, 16, -1000, -1000, -1000, 28, 17, -1000, -1000, 29, -1000, -1000, -1000, -1000, -1000, -1000, 13, -1000, } -var jsonPgo = []int{ +var jsonPgo = [...]int{ 0, 10, 4, 51, 45, 42, 0, 50, 49, 48, 19, 47, } -var jsonR1 = []int{ +var jsonR1 = [...]int{ 0, 11, 4, 4, 9, 9, 5, 6, 6, 6, 6, 6, 6, 6, 7, 7, 8, 8, 3, 3, 3, 3, 2, 2, 1, 1, 10, 10, } -var jsonR2 = []int{ +var jsonR2 = [...]int{ 0, 1, 3, 2, 1, 3, 3, 1, 1, 1, 1, 1, 1, 1, 2, 3, 1, 3, 1, 1, 2, 2, 2, 1, 2, 1, 2, 2, } -var jsonChk = []int{ +var jsonChk = [...]int{ -1000, -11, -4, 12, -9, 13, -5, 11, 13, 7, 6, -5, -6, 11, -3, -4, -7, 16, 17, 18, -2, -1, 14, 19, 5, 4, -10, 21, 22, -10, 15, -8, -6, -2, -1, 5, 5, 15, 7, -6, } -var jsonDef = []int{ +var jsonDef = [...]int{ 0, -2, 1, 0, 0, 3, 4, 0, 2, 0, 0, 5, 6, 7, 8, 9, 10, 11, 12, 13, 18, 19, 0, 0, 23, 25, 20, 0, 0, 21, 14, 0, 16, 22, 24, 26, 27, 15, 0, 17, } -var jsonTok1 = []int{ +var jsonTok1 = [...]int{ 1, } -var jsonTok2 = []int{ +var jsonTok2 = [...]int{ 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, } -var jsonTok3 = []int{ +var jsonTok3 = [...]int{ 0, } +var jsonErrorMessages = [...]struct { + state int + token int + msg string +}{} + //line yaccpar:1 /* parser for yacc output */ -var jsonDebug = 0 +var ( + jsonDebug = 0 + jsonErrorVerbose = false +) type jsonLexer interface { Lex(lval *jsonSymType) int Error(s string) } +type jsonParser interface { + Parse(jsonLexer) int + Lookahead() int +} + +type jsonParserImpl struct { + lookahead func() int +} + +func (p *jsonParserImpl) Lookahead() int { + return p.lookahead() +} + +func jsonNewParser() jsonParser { + p := &jsonParserImpl{ + lookahead: func() int { return -1 }, + } + return p +} + const jsonFlag = -1000 func jsonTokname(c int) string { - // 4 is TOKSTART above - if c >= 4 && c-4 < len(jsonToknames) { - if jsonToknames[c-4] != "" { - return jsonToknames[c-4] + if c >= 1 && c-1 < len(jsonToknames) { + if jsonToknames[c-1] != "" { + return jsonToknames[c-1] } } return __yyfmt__.Sprintf("tok-%v", c) @@ -178,51 +209,129 @@ func jsonStatname(s int) string { return __yyfmt__.Sprintf("state-%v", s) } -func jsonlex1(lex jsonLexer, lval *jsonSymType) int { - c := 0 - char := lex.Lex(lval) +func jsonErrorMessage(state, lookAhead int) string { + const TOKSTART = 4 + + if !jsonErrorVerbose { + return "syntax error" + } + + for _, e := range jsonErrorMessages { + if e.state == state && e.token == lookAhead { + return "syntax error: " + e.msg + } + } + + res := "syntax error: unexpected " + jsonTokname(lookAhead) + + // To match Bison, suggest at most four expected tokens. + expected := make([]int, 0, 4) + + // Look for shiftable tokens. + base := jsonPact[state] + for tok := TOKSTART; tok-1 < len(jsonToknames); tok++ { + if n := base + tok; n >= 0 && n < jsonLast && jsonChk[jsonAct[n]] == tok { + if len(expected) == cap(expected) { + return res + } + expected = append(expected, tok) + } + } + + if jsonDef[state] == -2 { + i := 0 + for jsonExca[i] != -1 || jsonExca[i+1] != state { + i += 2 + } + + // Look for tokens that we accept or reduce. + for i += 2; jsonExca[i] >= 0; i += 2 { + tok := jsonExca[i] + if tok < TOKSTART || jsonExca[i+1] == 0 { + continue + } + if len(expected) == cap(expected) { + return res + } + expected = append(expected, tok) + } + + // If the default action is to accept or reduce, give up. + if jsonExca[i+1] != 0 { + return res + } + } + + for i, tok := range expected { + if i == 0 { + res += ", expecting " + } else { + res += " or " + } + res += jsonTokname(tok) + } + return res +} + +func jsonlex1(lex jsonLexer, lval *jsonSymType) (char, token int) { + token = 0 + char = lex.Lex(lval) if char <= 0 { - c = jsonTok1[0] + token = jsonTok1[0] goto out } if char < len(jsonTok1) { - c = jsonTok1[char] + token = jsonTok1[char] goto out } if char >= jsonPrivate { if char < jsonPrivate+len(jsonTok2) { - c = jsonTok2[char-jsonPrivate] + token = jsonTok2[char-jsonPrivate] goto out } } for i := 0; i < len(jsonTok3); i += 2 { - c = jsonTok3[i+0] - if c == char { - c = jsonTok3[i+1] + token = jsonTok3[i+0] + if token == char { + token = jsonTok3[i+1] goto out } } out: - if c == 0 { - c = jsonTok2[1] /* unknown char */ + if token == 0 { + token = jsonTok2[1] /* unknown char */ } if jsonDebug >= 3 { - __yyfmt__.Printf("lex %s(%d)\n", jsonTokname(c), uint(char)) + __yyfmt__.Printf("lex %s(%d)\n", jsonTokname(token), uint(char)) } - return c + return char, token } func jsonParse(jsonlex jsonLexer) int { + return jsonNewParser().Parse(jsonlex) +} + +func (jsonrcvr *jsonParserImpl) Parse(jsonlex jsonLexer) int { var jsonn int var jsonlval jsonSymType var jsonVAL jsonSymType + var jsonDollar []jsonSymType + _ = jsonDollar // silence set and not used jsonS := make([]jsonSymType, jsonMaxDepth) Nerrs := 0 /* number of errors */ Errflag := 0 /* error recovery flag */ jsonstate := 0 jsonchar := -1 + jsontoken := -1 // jsonchar translated into internal numbering + jsonrcvr.lookahead = func() int { return jsonchar } + defer func() { + // Make sure we report no lookahead when not parsing. + jsonstate = -1 + jsonchar = -1 + jsontoken = -1 + }() jsonp := -1 goto jsonstack @@ -235,7 +344,7 @@ ret1: jsonstack: /* put a state and value onto the stack */ if jsonDebug >= 4 { - __yyfmt__.Printf("char %v in %v\n", jsonTokname(jsonchar), jsonStatname(jsonstate)) + __yyfmt__.Printf("char %v in %v\n", jsonTokname(jsontoken), jsonStatname(jsonstate)) } jsonp++ @@ -253,15 +362,16 @@ jsonnewstate: goto jsondefault /* simple state */ } if jsonchar < 0 { - jsonchar = jsonlex1(jsonlex, &jsonlval) + jsonchar, jsontoken = jsonlex1(jsonlex, &jsonlval) } - jsonn += jsonchar + jsonn += jsontoken if jsonn < 0 || jsonn >= jsonLast { goto jsondefault } jsonn = jsonAct[jsonn] - if jsonChk[jsonn] == jsonchar { /* valid shift */ + if jsonChk[jsonn] == jsontoken { /* valid shift */ jsonchar = -1 + jsontoken = -1 jsonVAL = jsonlval jsonstate = jsonn if Errflag > 0 { @@ -275,7 +385,7 @@ jsondefault: jsonn = jsonDef[jsonstate] if jsonn == -2 { if jsonchar < 0 { - jsonchar = jsonlex1(jsonlex, &jsonlval) + jsonchar, jsontoken = jsonlex1(jsonlex, &jsonlval) } /* look through exception table */ @@ -288,7 +398,7 @@ jsondefault: } for xi += 2; ; xi += 2 { jsonn = jsonExca[xi+0] - if jsonn < 0 || jsonn == jsonchar { + if jsonn < 0 || jsonn == jsontoken { break } } @@ -301,11 +411,11 @@ jsondefault: /* error ... attempt to resume parsing */ switch Errflag { case 0: /* brand new error */ - jsonlex.Error("syntax error") + jsonlex.Error(jsonErrorMessage(jsonstate, jsontoken)) Nerrs++ if jsonDebug >= 1 { __yyfmt__.Printf("%s", jsonStatname(jsonstate)) - __yyfmt__.Printf(" saw %s\n", jsonTokname(jsonchar)) + __yyfmt__.Printf(" saw %s\n", jsonTokname(jsontoken)) } fallthrough @@ -333,12 +443,13 @@ jsondefault: case 3: /* no shift yet; clobber input char */ if jsonDebug >= 2 { - __yyfmt__.Printf("error recovery discards %s\n", jsonTokname(jsonchar)) + __yyfmt__.Printf("error recovery discards %s\n", jsonTokname(jsontoken)) } - if jsonchar == jsonEofCode { + if jsontoken == jsonEofCode { goto ret1 } jsonchar = -1 + jsontoken = -1 goto jsonnewstate /* try again in the same state */ } } @@ -353,6 +464,13 @@ jsondefault: _ = jsonpt // guard against "declared and not used" jsonp -= jsonR2[jsonn] + // jsonp is now the index of $0. Perform the default action. Iff the + // reduced production is ε, $1 is possibly out of range. + if jsonp+1 >= len(jsonS) { + nyys := make([]jsonSymType, len(jsonS)*2) + copy(nyys, jsonS) + jsonS = nyys + } jsonVAL = jsonS[jsonp+1] /* consult goto table to find next state */ @@ -372,66 +490,77 @@ jsondefault: switch jsonnt { case 1: + jsonDollar = jsonS[jsonpt-1 : jsonpt+1] //line parse.y:39 { - jsonResult = jsonS[jsonpt-0].obj + jsonResult = jsonDollar[1].obj } case 2: + jsonDollar = jsonS[jsonpt-3 : jsonpt+1] //line parse.y:45 { jsonVAL.obj = &hcl.Object{ Type: hcl.ValueTypeObject, - Value: hcl.ObjectList(jsonS[jsonpt-1].objlist).Flat(), + Value: hcl.ObjectList(jsonDollar[2].objlist).Flat(), } } case 3: + jsonDollar = jsonS[jsonpt-2 : jsonpt+1] //line parse.y:52 { jsonVAL.obj = &hcl.Object{Type: hcl.ValueTypeObject} } case 4: + jsonDollar = jsonS[jsonpt-1 : jsonpt+1] //line parse.y:58 { - jsonVAL.objlist = []*hcl.Object{jsonS[jsonpt-0].obj} + jsonVAL.objlist = []*hcl.Object{jsonDollar[1].obj} } case 5: + jsonDollar = jsonS[jsonpt-3 : jsonpt+1] //line parse.y:62 { - jsonVAL.objlist = append(jsonS[jsonpt-2].objlist, jsonS[jsonpt-0].obj) + jsonVAL.objlist = append(jsonDollar[1].objlist, jsonDollar[3].obj) } case 6: + jsonDollar = jsonS[jsonpt-3 : jsonpt+1] //line parse.y:68 { - jsonS[jsonpt-0].obj.Key = jsonS[jsonpt-2].str - jsonVAL.obj = jsonS[jsonpt-0].obj + jsonDollar[3].obj.Key = jsonDollar[1].str + jsonVAL.obj = jsonDollar[3].obj } case 7: + jsonDollar = jsonS[jsonpt-1 : jsonpt+1] //line parse.y:75 { jsonVAL.obj = &hcl.Object{ Type: hcl.ValueTypeString, - Value: jsonS[jsonpt-0].str, + Value: jsonDollar[1].str, } } case 8: + jsonDollar = jsonS[jsonpt-1 : jsonpt+1] //line parse.y:82 { - jsonVAL.obj = jsonS[jsonpt-0].obj + jsonVAL.obj = jsonDollar[1].obj } case 9: + jsonDollar = jsonS[jsonpt-1 : jsonpt+1] //line parse.y:86 { - jsonVAL.obj = jsonS[jsonpt-0].obj + jsonVAL.obj = jsonDollar[1].obj } case 10: + jsonDollar = jsonS[jsonpt-1 : jsonpt+1] //line parse.y:90 { jsonVAL.obj = &hcl.Object{ Type: hcl.ValueTypeList, - Value: jsonS[jsonpt-0].objlist, + Value: jsonDollar[1].objlist, } } case 11: + jsonDollar = jsonS[jsonpt-1 : jsonpt+1] //line parse.y:97 { jsonVAL.obj = &hcl.Object{ @@ -440,6 +569,7 @@ jsondefault: } } case 12: + jsonDollar = jsonS[jsonpt-1 : jsonpt+1] //line parse.y:104 { jsonVAL.obj = &hcl.Object{ @@ -448,6 +578,7 @@ jsondefault: } } case 13: + jsonDollar = jsonS[jsonpt-1 : jsonpt+1] //line parse.y:111 { jsonVAL.obj = &hcl.Object{ @@ -456,45 +587,52 @@ jsondefault: } } case 14: + jsonDollar = jsonS[jsonpt-2 : jsonpt+1] //line parse.y:120 { jsonVAL.objlist = nil } case 15: + jsonDollar = jsonS[jsonpt-3 : jsonpt+1] //line parse.y:124 { - jsonVAL.objlist = jsonS[jsonpt-1].objlist + jsonVAL.objlist = jsonDollar[2].objlist } case 16: + jsonDollar = jsonS[jsonpt-1 : jsonpt+1] //line parse.y:130 { - jsonVAL.objlist = []*hcl.Object{jsonS[jsonpt-0].obj} + jsonVAL.objlist = []*hcl.Object{jsonDollar[1].obj} } case 17: + jsonDollar = jsonS[jsonpt-3 : jsonpt+1] //line parse.y:134 { - jsonVAL.objlist = append(jsonS[jsonpt-2].objlist, jsonS[jsonpt-0].obj) + jsonVAL.objlist = append(jsonDollar[1].objlist, jsonDollar[3].obj) } case 18: + jsonDollar = jsonS[jsonpt-1 : jsonpt+1] //line parse.y:140 { jsonVAL.obj = &hcl.Object{ Type: hcl.ValueTypeInt, - Value: jsonS[jsonpt-0].num, + Value: jsonDollar[1].num, } } case 19: + jsonDollar = jsonS[jsonpt-1 : jsonpt+1] //line parse.y:147 { jsonVAL.obj = &hcl.Object{ Type: hcl.ValueTypeFloat, - Value: jsonS[jsonpt-0].f, + Value: jsonDollar[1].f, } } case 20: + jsonDollar = jsonS[jsonpt-2 : jsonpt+1] //line parse.y:154 { - fs := fmt.Sprintf("%d%s", jsonS[jsonpt-1].num, jsonS[jsonpt-0].str) + fs := fmt.Sprintf("%d%s", jsonDollar[1].num, jsonDollar[2].str) f, err := strconv.ParseFloat(fs, 64) if err != nil { panic(err) @@ -506,9 +644,10 @@ jsondefault: } } case 21: + jsonDollar = jsonS[jsonpt-2 : jsonpt+1] //line parse.y:167 { - fs := fmt.Sprintf("%f%s", jsonS[jsonpt-1].f, jsonS[jsonpt-0].str) + fs := fmt.Sprintf("%f%s", jsonDollar[1].f, jsonDollar[2].str) f, err := strconv.ParseFloat(fs, 64) if err != nil { panic(err) @@ -520,34 +659,40 @@ jsondefault: } } case 22: + jsonDollar = jsonS[jsonpt-2 : jsonpt+1] //line parse.y:182 { - jsonVAL.num = jsonS[jsonpt-0].num * -1 + jsonVAL.num = jsonDollar[2].num * -1 } case 23: + jsonDollar = jsonS[jsonpt-1 : jsonpt+1] //line parse.y:186 { - jsonVAL.num = jsonS[jsonpt-0].num + jsonVAL.num = jsonDollar[1].num } case 24: + jsonDollar = jsonS[jsonpt-2 : jsonpt+1] //line parse.y:192 { - jsonVAL.f = jsonS[jsonpt-0].f * -1 + jsonVAL.f = jsonDollar[2].f * -1 } case 25: + jsonDollar = jsonS[jsonpt-1 : jsonpt+1] //line parse.y:196 { - jsonVAL.f = jsonS[jsonpt-0].f + jsonVAL.f = jsonDollar[1].f } case 26: + jsonDollar = jsonS[jsonpt-2 : jsonpt+1] //line parse.y:202 { - jsonVAL.str = "e" + strconv.FormatInt(int64(jsonS[jsonpt-0].num), 10) + jsonVAL.str = "e" + strconv.FormatInt(int64(jsonDollar[2].num), 10) } case 27: + jsonDollar = jsonS[jsonpt-2 : jsonpt+1] //line parse.y:206 { - jsonVAL.str = "e-" + strconv.FormatInt(int64(jsonS[jsonpt-0].num), 10) + jsonVAL.str = "e-" + strconv.FormatInt(int64(jsonDollar[2].num), 10) } } goto jsonstack /* stack new state and value */ diff --git a/Godeps/_workspace/src/github.com/hashicorp/hcl/lex_test.go b/Godeps/_workspace/src/github.com/hashicorp/hcl/lex_test.go deleted file mode 100644 index f7ee37886..000000000 --- a/Godeps/_workspace/src/github.com/hashicorp/hcl/lex_test.go +++ /dev/null @@ -1,37 +0,0 @@ -package hcl - -import ( - "testing" -) - -func TestLexMode(t *testing.T) { - cases := []struct { - Input string - Mode lexModeValue - }{ - { - "", - lexModeHcl, - }, - { - "foo", - lexModeHcl, - }, - { - "{}", - lexModeJson, - }, - { - " {}", - lexModeJson, - }, - } - - for i, tc := range cases { - actual := lexMode(tc.Input) - - if actual != tc.Mode { - t.Fatalf("%d: %#v", i, actual) - } - } -} diff --git a/Godeps/_workspace/src/github.com/hashicorp/logutils/level_benchmark_test.go b/Godeps/_workspace/src/github.com/hashicorp/logutils/level_benchmark_test.go deleted file mode 100644 index 3c2caf70e..000000000 --- a/Godeps/_workspace/src/github.com/hashicorp/logutils/level_benchmark_test.go +++ /dev/null @@ -1,37 +0,0 @@ -package logutils - -import ( - "io/ioutil" - "testing" -) - -var messages [][]byte - -func init() { - messages = [][]byte{ - []byte("[TRACE] foo"), - []byte("[DEBUG] foo"), - []byte("[INFO] foo"), - []byte("[WARN] foo"), - []byte("[ERROR] foo"), - } -} - -func BenchmarkDiscard(b *testing.B) { - for i := 0; i < b.N; i++ { - ioutil.Discard.Write(messages[i%len(messages)]) - } -} - -func BenchmarkLevelFilter(b *testing.B) { - filter := &LevelFilter{ - Levels: []LogLevel{"TRACE", "DEBUG", "INFO", "WARN", "ERROR"}, - MinLevel: "WARN", - Writer: ioutil.Discard, - } - - b.ResetTimer() - for i := 0; i < b.N; i++ { - filter.Write(messages[i%len(messages)]) - } -} diff --git a/Godeps/_workspace/src/github.com/hashicorp/logutils/level_test.go b/Godeps/_workspace/src/github.com/hashicorp/logutils/level_test.go deleted file mode 100644 index f6b6ac3c3..000000000 --- a/Godeps/_workspace/src/github.com/hashicorp/logutils/level_test.go +++ /dev/null @@ -1,94 +0,0 @@ -package logutils - -import ( - "bytes" - "io" - "log" - "testing" -) - -func TestLevelFilter_impl(t *testing.T) { - var _ io.Writer = new(LevelFilter) -} - -func TestLevelFilter(t *testing.T) { - buf := new(bytes.Buffer) - filter := &LevelFilter{ - Levels: []LogLevel{"DEBUG", "WARN", "ERROR"}, - MinLevel: "WARN", - Writer: buf, - } - - logger := log.New(filter, "", 0) - logger.Print("[WARN] foo") - logger.Println("[ERROR] bar") - logger.Println("[DEBUG] baz") - logger.Println("[WARN] buzz") - - result := buf.String() - expected := "[WARN] foo\n[ERROR] bar\n[WARN] buzz\n" - if result != expected { - t.Fatalf("bad: %#v", result) - } -} - -func TestLevelFilterCheck(t *testing.T) { - filter := &LevelFilter{ - Levels: []LogLevel{"DEBUG", "WARN", "ERROR"}, - MinLevel: "WARN", - Writer: nil, - } - - testCases := []struct { - line string - check bool - }{ - {"[WARN] foo\n", true}, - {"[ERROR] bar\n", true}, - {"[DEBUG] baz\n", false}, - {"[WARN] buzz\n", true}, - } - - for _, testCase := range testCases { - result := filter.Check([]byte(testCase.line)) - if result != testCase.check { - t.Errorf("Fail: %s", testCase.line) - } - } -} - -func TestLevelFilter_SetMinLevel(t *testing.T) { - filter := &LevelFilter{ - Levels: []LogLevel{"DEBUG", "WARN", "ERROR"}, - MinLevel: "ERROR", - Writer: nil, - } - - testCases := []struct { - line string - checkBefore bool - checkAfter bool - }{ - {"[WARN] foo\n", false, true}, - {"[ERROR] bar\n", true, true}, - {"[DEBUG] baz\n", false, false}, - {"[WARN] buzz\n", false, true}, - } - - for _, testCase := range testCases { - result := filter.Check([]byte(testCase.line)) - if result != testCase.checkBefore { - t.Errorf("Fail: %s", testCase.line) - } - } - - // Update the minimum level to WARN - filter.SetMinLevel("WARN") - - for _, testCase := range testCases { - result := filter.Check([]byte(testCase.line)) - if result != testCase.checkAfter { - t.Errorf("Fail: %s", testCase.line) - } - } -} diff --git a/Godeps/_workspace/src/github.com/kardianos/osext/osext_test.go b/Godeps/_workspace/src/github.com/kardianos/osext/osext_test.go deleted file mode 100644 index 77ccc28e9..000000000 --- a/Godeps/_workspace/src/github.com/kardianos/osext/osext_test.go +++ /dev/null @@ -1,203 +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. - -// +build darwin linux freebsd netbsd windows - -package osext - -import ( - "bytes" - "fmt" - "io" - "os" - "os/exec" - "path/filepath" - "runtime" - "testing" -) - -const ( - executableEnvVar = "OSTEST_OUTPUT_EXECUTABLE" - - executableEnvValueMatch = "match" - executableEnvValueDelete = "delete" -) - -func TestPrintExecutable(t *testing.T) { - ef, err := Executable() - if err != nil { - t.Fatalf("Executable failed: %v", err) - } - t.Log("Executable:", ef) -} -func TestPrintExecutableFolder(t *testing.T) { - ef, err := ExecutableFolder() - if err != nil { - t.Fatalf("ExecutableFolder failed: %v", err) - } - t.Log("Executable Folder:", ef) -} -func TestExecutableFolder(t *testing.T) { - ef, err := ExecutableFolder() - if err != nil { - t.Fatalf("ExecutableFolder failed: %v", err) - } - if ef[len(ef)-1] == filepath.Separator { - t.Fatal("ExecutableFolder ends with a trailing slash.") - } -} -func TestExecutableMatch(t *testing.T) { - ep, err := Executable() - if err != nil { - t.Fatalf("Executable failed: %v", err) - } - - // fullpath to be of the form "dir/prog". - dir := filepath.Dir(filepath.Dir(ep)) - fullpath, err := filepath.Rel(dir, ep) - if err != nil { - t.Fatalf("filepath.Rel: %v", err) - } - // Make child start with a relative program path. - // Alter argv[0] for child to verify getting real path without argv[0]. - cmd := &exec.Cmd{ - Dir: dir, - Path: fullpath, - Env: []string{fmt.Sprintf("%s=%s", executableEnvVar, executableEnvValueMatch)}, - } - out, err := cmd.CombinedOutput() - if err != nil { - t.Fatalf("exec(self) failed: %v", err) - } - outs := string(out) - if !filepath.IsAbs(outs) { - t.Fatalf("Child returned %q, want an absolute path", out) - } - if !sameFile(outs, ep) { - t.Fatalf("Child returned %q, not the same file as %q", out, ep) - } -} - -func TestExecutableDelete(t *testing.T) { - if runtime.GOOS != "linux" { - t.Skip() - } - fpath, err := Executable() - if err != nil { - t.Fatalf("Executable failed: %v", err) - } - - r, w := io.Pipe() - stderrBuff := &bytes.Buffer{} - stdoutBuff := &bytes.Buffer{} - cmd := &exec.Cmd{ - Path: fpath, - Env: []string{fmt.Sprintf("%s=%s", executableEnvVar, executableEnvValueDelete)}, - Stdin: r, - Stderr: stderrBuff, - Stdout: stdoutBuff, - } - err = cmd.Start() - if err != nil { - t.Fatalf("exec(self) start failed: %v", err) - } - - tempPath := fpath + "_copy" - _ = os.Remove(tempPath) - - err = copyFile(tempPath, fpath) - if err != nil { - t.Fatalf("copy file failed: %v", err) - } - err = os.Remove(fpath) - if err != nil { - t.Fatalf("remove running test file failed: %v", err) - } - err = os.Rename(tempPath, fpath) - if err != nil { - t.Fatalf("rename copy to previous name failed: %v", err) - } - - w.Write([]byte{0}) - w.Close() - - err = cmd.Wait() - if err != nil { - t.Fatalf("exec wait failed: %v", err) - } - - childPath := stderrBuff.String() - if !filepath.IsAbs(childPath) { - t.Fatalf("Child returned %q, want an absolute path", childPath) - } - if !sameFile(childPath, fpath) { - t.Fatalf("Child returned %q, not the same file as %q", childPath, fpath) - } -} - -func sameFile(fn1, fn2 string) bool { - fi1, err := os.Stat(fn1) - if err != nil { - return false - } - fi2, err := os.Stat(fn2) - if err != nil { - return false - } - return os.SameFile(fi1, fi2) -} -func copyFile(dest, src string) error { - df, err := os.Create(dest) - if err != nil { - return err - } - defer df.Close() - - sf, err := os.Open(src) - if err != nil { - return err - } - defer sf.Close() - - _, err = io.Copy(df, sf) - return err -} - -func TestMain(m *testing.M) { - env := os.Getenv(executableEnvVar) - switch env { - case "": - os.Exit(m.Run()) - case executableEnvValueMatch: - // First chdir to another path. - dir := "/" - if runtime.GOOS == "windows" { - dir = filepath.VolumeName(".") - } - os.Chdir(dir) - if ep, err := Executable(); err != nil { - fmt.Fprint(os.Stderr, "ERROR: ", err) - } else { - fmt.Fprint(os.Stderr, ep) - } - case executableEnvValueDelete: - bb := make([]byte, 1) - var err error - n, err := os.Stdin.Read(bb) - if err != nil { - fmt.Fprint(os.Stderr, "ERROR: ", err) - os.Exit(2) - } - if n != 1 { - fmt.Fprint(os.Stderr, "ERROR: n != 1, n == ", n) - os.Exit(2) - } - if ep, err := Executable(); err != nil { - fmt.Fprint(os.Stderr, "ERROR: ", err) - } else { - fmt.Fprint(os.Stderr, ep) - } - } - os.Exit(0) -} diff --git a/Godeps/_workspace/src/github.com/lib/pq/bench_test.go b/Godeps/_workspace/src/github.com/lib/pq/bench_test.go deleted file mode 100644 index e71f41d06..000000000 --- a/Godeps/_workspace/src/github.com/lib/pq/bench_test.go +++ /dev/null @@ -1,435 +0,0 @@ -// +build go1.1 - -package pq - -import ( - "bufio" - "bytes" - "database/sql" - "database/sql/driver" - "io" - "math/rand" - "net" - "runtime" - "strconv" - "strings" - "sync" - "testing" - "time" - - "github.com/lib/pq/oid" -) - -var ( - selectStringQuery = "SELECT '" + strings.Repeat("0123456789", 10) + "'" - selectSeriesQuery = "SELECT generate_series(1, 100)" -) - -func BenchmarkSelectString(b *testing.B) { - var result string - benchQuery(b, selectStringQuery, &result) -} - -func BenchmarkSelectSeries(b *testing.B) { - var result int - benchQuery(b, selectSeriesQuery, &result) -} - -func benchQuery(b *testing.B, query string, result interface{}) { - b.StopTimer() - db := openTestConn(b) - defer db.Close() - b.StartTimer() - - for i := 0; i < b.N; i++ { - benchQueryLoop(b, db, query, result) - } -} - -func benchQueryLoop(b *testing.B, db *sql.DB, query string, result interface{}) { - rows, err := db.Query(query) - if err != nil { - b.Fatal(err) - } - defer rows.Close() - for rows.Next() { - err = rows.Scan(result) - if err != nil { - b.Fatal("failed to scan", err) - } - } -} - -// reading from circularConn yields content[:prefixLen] once, followed by -// content[prefixLen:] over and over again. It never returns EOF. -type circularConn struct { - content string - prefixLen int - pos int - net.Conn // for all other net.Conn methods that will never be called -} - -func (r *circularConn) Read(b []byte) (n int, err error) { - n = copy(b, r.content[r.pos:]) - r.pos += n - if r.pos >= len(r.content) { - r.pos = r.prefixLen - } - return -} - -func (r *circularConn) Write(b []byte) (n int, err error) { return len(b), nil } - -func (r *circularConn) Close() error { return nil } - -func fakeConn(content string, prefixLen int) *conn { - c := &circularConn{content: content, prefixLen: prefixLen} - return &conn{buf: bufio.NewReader(c), c: c} -} - -// This benchmark is meant to be the same as BenchmarkSelectString, but takes -// out some of the factors this package can't control. The numbers are less noisy, -// but also the costs of network communication aren't accurately represented. -func BenchmarkMockSelectString(b *testing.B) { - b.StopTimer() - // taken from a recorded run of BenchmarkSelectString - // See: http://www.postgresql.org/docs/current/static/protocol-message-formats.html - const response = "1\x00\x00\x00\x04" + - "t\x00\x00\x00\x06\x00\x00" + - "T\x00\x00\x00!\x00\x01?column?\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\xc1\xff\xfe\xff\xff\xff\xff\x00\x00" + - "Z\x00\x00\x00\x05I" + - "2\x00\x00\x00\x04" + - "D\x00\x00\x00n\x00\x01\x00\x00\x00d0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789" + - "C\x00\x00\x00\rSELECT 1\x00" + - "Z\x00\x00\x00\x05I" + - "3\x00\x00\x00\x04" + - "Z\x00\x00\x00\x05I" - c := fakeConn(response, 0) - b.StartTimer() - - for i := 0; i < b.N; i++ { - benchMockQuery(b, c, selectStringQuery) - } -} - -var seriesRowData = func() string { - var buf bytes.Buffer - for i := 1; i <= 100; i++ { - digits := byte(2) - if i >= 100 { - digits = 3 - } else if i < 10 { - digits = 1 - } - buf.WriteString("D\x00\x00\x00") - buf.WriteByte(10 + digits) - buf.WriteString("\x00\x01\x00\x00\x00") - buf.WriteByte(digits) - buf.WriteString(strconv.Itoa(i)) - } - return buf.String() -}() - -func BenchmarkMockSelectSeries(b *testing.B) { - b.StopTimer() - var response = "1\x00\x00\x00\x04" + - "t\x00\x00\x00\x06\x00\x00" + - "T\x00\x00\x00!\x00\x01?column?\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\xc1\xff\xfe\xff\xff\xff\xff\x00\x00" + - "Z\x00\x00\x00\x05I" + - "2\x00\x00\x00\x04" + - seriesRowData + - "C\x00\x00\x00\x0fSELECT 100\x00" + - "Z\x00\x00\x00\x05I" + - "3\x00\x00\x00\x04" + - "Z\x00\x00\x00\x05I" - c := fakeConn(response, 0) - b.StartTimer() - - for i := 0; i < b.N; i++ { - benchMockQuery(b, c, selectSeriesQuery) - } -} - -func benchMockQuery(b *testing.B, c *conn, query string) { - stmt, err := c.Prepare(query) - if err != nil { - b.Fatal(err) - } - defer stmt.Close() - rows, err := stmt.Query(nil) - if err != nil { - b.Fatal(err) - } - defer rows.Close() - var dest [1]driver.Value - for { - if err := rows.Next(dest[:]); err != nil { - if err == io.EOF { - break - } - b.Fatal(err) - } - } -} - -func BenchmarkPreparedSelectString(b *testing.B) { - var result string - benchPreparedQuery(b, selectStringQuery, &result) -} - -func BenchmarkPreparedSelectSeries(b *testing.B) { - var result int - benchPreparedQuery(b, selectSeriesQuery, &result) -} - -func benchPreparedQuery(b *testing.B, query string, result interface{}) { - b.StopTimer() - db := openTestConn(b) - defer db.Close() - stmt, err := db.Prepare(query) - if err != nil { - b.Fatal(err) - } - defer stmt.Close() - b.StartTimer() - - for i := 0; i < b.N; i++ { - benchPreparedQueryLoop(b, db, stmt, result) - } -} - -func benchPreparedQueryLoop(b *testing.B, db *sql.DB, stmt *sql.Stmt, result interface{}) { - rows, err := stmt.Query() - if err != nil { - b.Fatal(err) - } - if !rows.Next() { - rows.Close() - b.Fatal("no rows") - } - defer rows.Close() - for rows.Next() { - err = rows.Scan(&result) - if err != nil { - b.Fatal("failed to scan") - } - } -} - -// See the comment for BenchmarkMockSelectString. -func BenchmarkMockPreparedSelectString(b *testing.B) { - b.StopTimer() - const parseResponse = "1\x00\x00\x00\x04" + - "t\x00\x00\x00\x06\x00\x00" + - "T\x00\x00\x00!\x00\x01?column?\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\xc1\xff\xfe\xff\xff\xff\xff\x00\x00" + - "Z\x00\x00\x00\x05I" - const responses = parseResponse + - "2\x00\x00\x00\x04" + - "D\x00\x00\x00n\x00\x01\x00\x00\x00d0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789" + - "C\x00\x00\x00\rSELECT 1\x00" + - "Z\x00\x00\x00\x05I" - c := fakeConn(responses, len(parseResponse)) - - stmt, err := c.Prepare(selectStringQuery) - if err != nil { - b.Fatal(err) - } - b.StartTimer() - - for i := 0; i < b.N; i++ { - benchPreparedMockQuery(b, c, stmt) - } -} - -func BenchmarkMockPreparedSelectSeries(b *testing.B) { - b.StopTimer() - const parseResponse = "1\x00\x00\x00\x04" + - "t\x00\x00\x00\x06\x00\x00" + - "T\x00\x00\x00!\x00\x01?column?\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\xc1\xff\xfe\xff\xff\xff\xff\x00\x00" + - "Z\x00\x00\x00\x05I" - var responses = parseResponse + - "2\x00\x00\x00\x04" + - seriesRowData + - "C\x00\x00\x00\x0fSELECT 100\x00" + - "Z\x00\x00\x00\x05I" - c := fakeConn(responses, len(parseResponse)) - - stmt, err := c.Prepare(selectSeriesQuery) - if err != nil { - b.Fatal(err) - } - b.StartTimer() - - for i := 0; i < b.N; i++ { - benchPreparedMockQuery(b, c, stmt) - } -} - -func benchPreparedMockQuery(b *testing.B, c *conn, stmt driver.Stmt) { - rows, err := stmt.Query(nil) - if err != nil { - b.Fatal(err) - } - defer rows.Close() - var dest [1]driver.Value - for { - if err := rows.Next(dest[:]); err != nil { - if err == io.EOF { - break - } - b.Fatal(err) - } - } -} - -func BenchmarkEncodeInt64(b *testing.B) { - for i := 0; i < b.N; i++ { - encode(¶meterStatus{}, int64(1234), oid.T_int8) - } -} - -func BenchmarkEncodeFloat64(b *testing.B) { - for i := 0; i < b.N; i++ { - encode(¶meterStatus{}, 3.14159, oid.T_float8) - } -} - -var testByteString = []byte("abcdefghijklmnopqrstuvwxyz") - -func BenchmarkEncodeByteaHex(b *testing.B) { - for i := 0; i < b.N; i++ { - encode(¶meterStatus{serverVersion: 90000}, testByteString, oid.T_bytea) - } -} -func BenchmarkEncodeByteaEscape(b *testing.B) { - for i := 0; i < b.N; i++ { - encode(¶meterStatus{serverVersion: 84000}, testByteString, oid.T_bytea) - } -} - -func BenchmarkEncodeBool(b *testing.B) { - for i := 0; i < b.N; i++ { - encode(¶meterStatus{}, true, oid.T_bool) - } -} - -var testTimestamptz = time.Date(2001, time.January, 1, 0, 0, 0, 0, time.Local) - -func BenchmarkEncodeTimestamptz(b *testing.B) { - for i := 0; i < b.N; i++ { - encode(¶meterStatus{}, testTimestamptz, oid.T_timestamptz) - } -} - -var testIntBytes = []byte("1234") - -func BenchmarkDecodeInt64(b *testing.B) { - for i := 0; i < b.N; i++ { - decode(¶meterStatus{}, testIntBytes, oid.T_int8, formatText) - } -} - -var testFloatBytes = []byte("3.14159") - -func BenchmarkDecodeFloat64(b *testing.B) { - for i := 0; i < b.N; i++ { - decode(¶meterStatus{}, testFloatBytes, oid.T_float8, formatText) - } -} - -var testBoolBytes = []byte{'t'} - -func BenchmarkDecodeBool(b *testing.B) { - for i := 0; i < b.N; i++ { - decode(¶meterStatus{}, testBoolBytes, oid.T_bool, formatText) - } -} - -func TestDecodeBool(t *testing.T) { - db := openTestConn(t) - rows, err := db.Query("select true") - if err != nil { - t.Fatal(err) - } - rows.Close() -} - -var testTimestamptzBytes = []byte("2013-09-17 22:15:32.360754-07") - -func BenchmarkDecodeTimestamptz(b *testing.B) { - for i := 0; i < b.N; i++ { - decode(¶meterStatus{}, testTimestamptzBytes, oid.T_timestamptz, formatText) - } -} - -func BenchmarkDecodeTimestamptzMultiThread(b *testing.B) { - oldProcs := runtime.GOMAXPROCS(0) - defer runtime.GOMAXPROCS(oldProcs) - runtime.GOMAXPROCS(runtime.NumCPU()) - globalLocationCache = newLocationCache() - - f := func(wg *sync.WaitGroup, loops int) { - defer wg.Done() - for i := 0; i < loops; i++ { - decode(¶meterStatus{}, testTimestamptzBytes, oid.T_timestamptz, formatText) - } - } - - wg := &sync.WaitGroup{} - b.ResetTimer() - for j := 0; j < 10; j++ { - wg.Add(1) - go f(wg, b.N/10) - } - wg.Wait() -} - -func BenchmarkLocationCache(b *testing.B) { - globalLocationCache = newLocationCache() - for i := 0; i < b.N; i++ { - globalLocationCache.getLocation(rand.Intn(10000)) - } -} - -func BenchmarkLocationCacheMultiThread(b *testing.B) { - oldProcs := runtime.GOMAXPROCS(0) - defer runtime.GOMAXPROCS(oldProcs) - runtime.GOMAXPROCS(runtime.NumCPU()) - globalLocationCache = newLocationCache() - - f := func(wg *sync.WaitGroup, loops int) { - defer wg.Done() - for i := 0; i < loops; i++ { - globalLocationCache.getLocation(rand.Intn(10000)) - } - } - - wg := &sync.WaitGroup{} - b.ResetTimer() - for j := 0; j < 10; j++ { - wg.Add(1) - go f(wg, b.N/10) - } - wg.Wait() -} - -// Stress test the performance of parsing results from the wire. -func BenchmarkResultParsing(b *testing.B) { - b.StopTimer() - - db := openTestConn(b) - defer db.Close() - _, err := db.Exec("BEGIN") - if err != nil { - b.Fatal(err) - } - - b.StartTimer() - for i := 0; i < b.N; i++ { - res, err := db.Query("SELECT generate_series(1, 50000)") - if err != nil { - b.Fatal(err) - } - res.Close() - } -} diff --git a/Godeps/_workspace/src/github.com/lib/pq/conn_test.go b/Godeps/_workspace/src/github.com/lib/pq/conn_test.go deleted file mode 100644 index af07e5596..000000000 --- a/Godeps/_workspace/src/github.com/lib/pq/conn_test.go +++ /dev/null @@ -1,1306 +0,0 @@ -package pq - -import ( - "database/sql" - "database/sql/driver" - "fmt" - "io" - "os" - "reflect" - "strings" - "testing" - "time" -) - -type Fatalistic interface { - Fatal(args ...interface{}) -} - -func forceBinaryParameters() bool { - bp := os.Getenv("PQTEST_BINARY_PARAMETERS") - if bp == "yes" { - return true - } else if bp == "" || bp == "no" { - return false - } else { - panic("unexpected value for PQTEST_BINARY_PARAMETERS") - } -} - -func openTestConnConninfo(conninfo string) (*sql.DB, error) { - defaultTo := func(envvar string, value string) { - if os.Getenv(envvar) == "" { - os.Setenv(envvar, value) - } - } - defaultTo("PGDATABASE", "pqgotest") - defaultTo("PGSSLMODE", "disable") - defaultTo("PGCONNECT_TIMEOUT", "20") - - if forceBinaryParameters() && - !strings.HasPrefix(conninfo, "postgres://") && - !strings.HasPrefix(conninfo, "postgresql://") { - conninfo = conninfo + " binary_parameters=yes" - } - - return sql.Open("postgres", conninfo) -} - -func openTestConn(t Fatalistic) *sql.DB { - conn, err := openTestConnConninfo("") - if err != nil { - t.Fatal(err) - } - - return conn -} - -func getServerVersion(t *testing.T, db *sql.DB) int { - var version int - err := db.QueryRow("SHOW server_version_num").Scan(&version) - if err != nil { - t.Fatal(err) - } - return version -} - -func TestReconnect(t *testing.T) { - db1 := openTestConn(t) - defer db1.Close() - tx, err := db1.Begin() - if err != nil { - t.Fatal(err) - } - var pid1 int - err = tx.QueryRow("SELECT pg_backend_pid()").Scan(&pid1) - if err != nil { - t.Fatal(err) - } - db2 := openTestConn(t) - defer db2.Close() - _, err = db2.Exec("SELECT pg_terminate_backend($1)", pid1) - if err != nil { - t.Fatal(err) - } - // The rollback will probably "fail" because we just killed - // its connection above - _ = tx.Rollback() - - const expected int = 42 - var result int - err = db1.QueryRow(fmt.Sprintf("SELECT %d", expected)).Scan(&result) - if err != nil { - t.Fatal(err) - } - if result != expected { - t.Errorf("got %v; expected %v", result, expected) - } -} - -func TestCommitInFailedTransaction(t *testing.T) { - db := openTestConn(t) - defer db.Close() - - txn, err := db.Begin() - if err != nil { - t.Fatal(err) - } - rows, err := txn.Query("SELECT error") - if err == nil { - rows.Close() - t.Fatal("expected failure") - } - err = txn.Commit() - if err != ErrInFailedTransaction { - t.Fatalf("expected ErrInFailedTransaction; got %#v", err) - } -} - -func TestOpenURL(t *testing.T) { - testURL := func(url string) { - db, err := openTestConnConninfo(url) - if err != nil { - t.Fatal(err) - } - defer db.Close() - // database/sql might not call our Open at all unless we do something with - // the connection - txn, err := db.Begin() - if err != nil { - t.Fatal(err) - } - txn.Rollback() - } - testURL("postgres://") - testURL("postgresql://") -} - -func TestExec(t *testing.T) { - db := openTestConn(t) - defer db.Close() - - _, err := db.Exec("CREATE TEMP TABLE temp (a int)") - if err != nil { - t.Fatal(err) - } - - r, err := db.Exec("INSERT INTO temp VALUES (1)") - if err != nil { - t.Fatal(err) - } - - if n, _ := r.RowsAffected(); n != 1 { - t.Fatalf("expected 1 row affected, not %d", n) - } - - r, err = db.Exec("INSERT INTO temp VALUES ($1), ($2), ($3)", 1, 2, 3) - if err != nil { - t.Fatal(err) - } - - if n, _ := r.RowsAffected(); n != 3 { - t.Fatalf("expected 3 rows affected, not %d", n) - } - - // SELECT doesn't send the number of returned rows in the command tag - // before 9.0 - if getServerVersion(t, db) >= 90000 { - r, err = db.Exec("SELECT g FROM generate_series(1, 2) g") - if err != nil { - t.Fatal(err) - } - if n, _ := r.RowsAffected(); n != 2 { - t.Fatalf("expected 2 rows affected, not %d", n) - } - - r, err = db.Exec("SELECT g FROM generate_series(1, $1) g", 3) - if err != nil { - t.Fatal(err) - } - if n, _ := r.RowsAffected(); n != 3 { - t.Fatalf("expected 3 rows affected, not %d", n) - } - } -} - -func TestStatment(t *testing.T) { - db := openTestConn(t) - defer db.Close() - - st, err := db.Prepare("SELECT 1") - if err != nil { - t.Fatal(err) - } - - st1, err := db.Prepare("SELECT 2") - if err != nil { - t.Fatal(err) - } - - r, err := st.Query() - if err != nil { - t.Fatal(err) - } - defer r.Close() - - if !r.Next() { - t.Fatal("expected row") - } - - var i int - err = r.Scan(&i) - if err != nil { - t.Fatal(err) - } - - if i != 1 { - t.Fatalf("expected 1, got %d", i) - } - - // st1 - - r1, err := st1.Query() - if err != nil { - t.Fatal(err) - } - defer r1.Close() - - if !r1.Next() { - if r.Err() != nil { - t.Fatal(r1.Err()) - } - t.Fatal("expected row") - } - - err = r1.Scan(&i) - if err != nil { - t.Fatal(err) - } - - if i != 2 { - t.Fatalf("expected 2, got %d", i) - } -} - -func TestRowsCloseBeforeDone(t *testing.T) { - db := openTestConn(t) - defer db.Close() - - r, err := db.Query("SELECT 1") - if err != nil { - t.Fatal(err) - } - - err = r.Close() - if err != nil { - t.Fatal(err) - } - - if r.Next() { - t.Fatal("unexpected row") - } - - if r.Err() != nil { - t.Fatal(r.Err()) - } -} - -func TestParameterCountMismatch(t *testing.T) { - db := openTestConn(t) - defer db.Close() - - var notused int - err := db.QueryRow("SELECT false", 1).Scan(¬used) - if err == nil { - t.Fatal("expected err") - } - // make sure we clean up correctly - err = db.QueryRow("SELECT 1").Scan(¬used) - if err != nil { - t.Fatal(err) - } - - err = db.QueryRow("SELECT $1").Scan(¬used) - if err == nil { - t.Fatal("expected err") - } - // make sure we clean up correctly - err = db.QueryRow("SELECT 1").Scan(¬used) - if err != nil { - t.Fatal(err) - } -} - -// Test that EmptyQueryResponses are handled correctly. -func TestEmptyQuery(t *testing.T) { - db := openTestConn(t) - defer db.Close() - - _, err := db.Exec("") - if err != nil { - t.Fatal(err) - } - rows, err := db.Query("") - if err != nil { - t.Fatal(err) - } - cols, err := rows.Columns() - if err != nil { - t.Fatal(err) - } - if len(cols) != 0 { - t.Fatalf("unexpected number of columns %d in response to an empty query", len(cols)) - } - if rows.Next() { - t.Fatal("unexpected row") - } - if rows.Err() != nil { - t.Fatal(rows.Err()) - } - - stmt, err := db.Prepare("") - if err != nil { - t.Fatal(err) - } - _, err = stmt.Exec() - if err != nil { - t.Fatal(err) - } - rows, err = stmt.Query() - if err != nil { - t.Fatal(err) - } - cols, err = rows.Columns() - if err != nil { - t.Fatal(err) - } - if len(cols) != 0 { - t.Fatalf("unexpected number of columns %d in response to an empty query", len(cols)) - } - if rows.Next() { - t.Fatal("unexpected row") - } - if rows.Err() != nil { - t.Fatal(rows.Err()) - } -} - -func TestEncodeDecode(t *testing.T) { - db := openTestConn(t) - defer db.Close() - - q := ` - SELECT - E'\\000\\001\\002'::bytea, - 'foobar'::text, - NULL::integer, - '2000-1-1 01:02:03.04-7'::timestamptz, - 0::boolean, - 123, - -321, - 3.14::float8 - WHERE - E'\\000\\001\\002'::bytea = $1 - AND 'foobar'::text = $2 - AND $3::integer is NULL - ` - // AND '2000-1-1 12:00:00.000000-7'::timestamp = $3 - - exp1 := []byte{0, 1, 2} - exp2 := "foobar" - - r, err := db.Query(q, exp1, exp2, nil) - if err != nil { - t.Fatal(err) - } - defer r.Close() - - if !r.Next() { - if r.Err() != nil { - t.Fatal(r.Err()) - } - t.Fatal("expected row") - } - - var got1 []byte - var got2 string - var got3 = sql.NullInt64{Valid: true} - var got4 time.Time - var got5, got6, got7, got8 interface{} - - err = r.Scan(&got1, &got2, &got3, &got4, &got5, &got6, &got7, &got8) - if err != nil { - t.Fatal(err) - } - - if !reflect.DeepEqual(exp1, got1) { - t.Errorf("expected %q byte: %q", exp1, got1) - } - - if !reflect.DeepEqual(exp2, got2) { - t.Errorf("expected %q byte: %q", exp2, got2) - } - - if got3.Valid { - t.Fatal("expected invalid") - } - - if got4.Year() != 2000 { - t.Fatal("wrong year") - } - - if got5 != false { - t.Fatalf("expected false, got %q", got5) - } - - if got6 != int64(123) { - t.Fatalf("expected 123, got %d", got6) - } - - if got7 != int64(-321) { - t.Fatalf("expected -321, got %d", got7) - } - - if got8 != float64(3.14) { - t.Fatalf("expected 3.14, got %f", got8) - } -} - -func TestNoData(t *testing.T) { - db := openTestConn(t) - defer db.Close() - - st, err := db.Prepare("SELECT 1 WHERE true = false") - if err != nil { - t.Fatal(err) - } - defer st.Close() - - r, err := st.Query() - if err != nil { - t.Fatal(err) - } - defer r.Close() - - if r.Next() { - if r.Err() != nil { - t.Fatal(r.Err()) - } - t.Fatal("unexpected row") - } - - _, err = db.Query("SELECT * FROM nonexistenttable WHERE age=$1", 20) - if err == nil { - t.Fatal("Should have raised an error on non existent table") - } - - _, err = db.Query("SELECT * FROM nonexistenttable") - if err == nil { - t.Fatal("Should have raised an error on non existent table") - } -} - -func TestErrorDuringStartup(t *testing.T) { - // Don't use the normal connection setup, this is intended to - // blow up in the startup packet from a non-existent user. - db, err := openTestConnConninfo("user=thisuserreallydoesntexist") - if err != nil { - t.Fatal(err) - } - defer db.Close() - - _, err = db.Begin() - if err == nil { - t.Fatal("expected error") - } - - e, ok := err.(*Error) - if !ok { - t.Fatalf("expected Error, got %#v", err) - } else if e.Code.Name() != "invalid_authorization_specification" && e.Code.Name() != "invalid_password" { - t.Fatalf("expected invalid_authorization_specification or invalid_password, got %s (%+v)", e.Code.Name(), err) - } -} - -func TestBadConn(t *testing.T) { - var err error - - cn := conn{} - func() { - defer cn.errRecover(&err) - panic(io.EOF) - }() - if err != driver.ErrBadConn { - t.Fatalf("expected driver.ErrBadConn, got: %#v", err) - } - if !cn.bad { - t.Fatalf("expected cn.bad") - } - - cn = conn{} - func() { - defer cn.errRecover(&err) - e := &Error{Severity: Efatal} - panic(e) - }() - if err != driver.ErrBadConn { - t.Fatalf("expected driver.ErrBadConn, got: %#v", err) - } - if !cn.bad { - t.Fatalf("expected cn.bad") - } -} - -func TestErrorOnExec(t *testing.T) { - db := openTestConn(t) - defer db.Close() - - txn, err := db.Begin() - if err != nil { - t.Fatal(err) - } - defer txn.Rollback() - - _, err = txn.Exec("CREATE TEMPORARY TABLE foo(f1 int PRIMARY KEY)") - if err != nil { - t.Fatal(err) - } - - _, err = txn.Exec("INSERT INTO foo VALUES (0), (0)") - if err == nil { - t.Fatal("Should have raised error") - } - - e, ok := err.(*Error) - if !ok { - t.Fatalf("expected Error, got %#v", err) - } else if e.Code.Name() != "unique_violation" { - t.Fatalf("expected unique_violation, got %s (%+v)", e.Code.Name(), err) - } -} - -func TestErrorOnQuery(t *testing.T) { - db := openTestConn(t) - defer db.Close() - - txn, err := db.Begin() - if err != nil { - t.Fatal(err) - } - defer txn.Rollback() - - _, err = txn.Exec("CREATE TEMPORARY TABLE foo(f1 int PRIMARY KEY)") - if err != nil { - t.Fatal(err) - } - - _, err = txn.Query("INSERT INTO foo VALUES (0), (0)") - if err == nil { - t.Fatal("Should have raised error") - } - - e, ok := err.(*Error) - if !ok { - t.Fatalf("expected Error, got %#v", err) - } else if e.Code.Name() != "unique_violation" { - t.Fatalf("expected unique_violation, got %s (%+v)", e.Code.Name(), err) - } -} - -func TestErrorOnQueryRowSimpleQuery(t *testing.T) { - db := openTestConn(t) - defer db.Close() - - txn, err := db.Begin() - if err != nil { - t.Fatal(err) - } - defer txn.Rollback() - - _, err = txn.Exec("CREATE TEMPORARY TABLE foo(f1 int PRIMARY KEY)") - if err != nil { - t.Fatal(err) - } - - var v int - err = txn.QueryRow("INSERT INTO foo VALUES (0), (0)").Scan(&v) - if err == nil { - t.Fatal("Should have raised error") - } - - e, ok := err.(*Error) - if !ok { - t.Fatalf("expected Error, got %#v", err) - } else if e.Code.Name() != "unique_violation" { - t.Fatalf("expected unique_violation, got %s (%+v)", e.Code.Name(), err) - } -} - -// Test the QueryRow bug workarounds in stmt.exec() and simpleQuery() -func TestQueryRowBugWorkaround(t *testing.T) { - db := openTestConn(t) - defer db.Close() - - // stmt.exec() - _, err := db.Exec("CREATE TEMP TABLE notnulltemp (a varchar(10) not null)") - if err != nil { - t.Fatal(err) - } - - var a string - err = db.QueryRow("INSERT INTO notnulltemp(a) values($1) RETURNING a", nil).Scan(&a) - if err == sql.ErrNoRows { - t.Fatalf("expected constraint violation error; got: %v", err) - } - pge, ok := err.(*Error) - if !ok { - t.Fatalf("expected *Error; got: %#v", err) - } - if pge.Code.Name() != "not_null_violation" { - t.Fatalf("expected not_null_violation; got: %s (%+v)", pge.Code.Name(), err) - } - - // Test workaround in simpleQuery() - tx, err := db.Begin() - if err != nil { - t.Fatalf("unexpected error %s in Begin", err) - } - defer tx.Rollback() - - _, err = tx.Exec("SET LOCAL check_function_bodies TO FALSE") - if err != nil { - t.Fatalf("could not disable check_function_bodies: %s", err) - } - _, err = tx.Exec(` -CREATE OR REPLACE FUNCTION bad_function() -RETURNS integer --- hack to prevent the function from being inlined -SET check_function_bodies TO TRUE -AS $$ - SELECT text 'bad' -$$ LANGUAGE sql`) - if err != nil { - t.Fatalf("could not create function: %s", err) - } - - err = tx.QueryRow("SELECT * FROM bad_function()").Scan(&a) - if err == nil { - t.Fatalf("expected error") - } - pge, ok = err.(*Error) - if !ok { - t.Fatalf("expected *Error; got: %#v", err) - } - if pge.Code.Name() != "invalid_function_definition" { - t.Fatalf("expected invalid_function_definition; got: %s (%+v)", pge.Code.Name(), err) - } - - err = tx.Rollback() - if err != nil { - t.Fatalf("unexpected error %s in Rollback", err) - } - - // Also test that simpleQuery()'s workaround works when the query fails - // after a row has been received. - rows, err := db.Query(` -select - (select generate_series(1, ss.i)) -from (select gs.i - from generate_series(1, 2) gs(i) - order by gs.i limit 2) ss`) - if err != nil { - t.Fatalf("query failed: %s", err) - } - if !rows.Next() { - t.Fatalf("expected at least one result row; got %s", rows.Err()) - } - var i int - err = rows.Scan(&i) - if err != nil { - t.Fatalf("rows.Scan() failed: %s", err) - } - if i != 1 { - t.Fatalf("unexpected value for i: %d", i) - } - if rows.Next() { - t.Fatalf("unexpected row") - } - pge, ok = rows.Err().(*Error) - if !ok { - t.Fatalf("expected *Error; got: %#v", err) - } - if pge.Code.Name() != "cardinality_violation" { - t.Fatalf("expected cardinality_violation; got: %s (%+v)", pge.Code.Name(), rows.Err()) - } -} - -func TestSimpleQuery(t *testing.T) { - db := openTestConn(t) - defer db.Close() - - r, err := db.Query("select 1") - if err != nil { - t.Fatal(err) - } - defer r.Close() - - if !r.Next() { - t.Fatal("expected row") - } -} - -func TestBindError(t *testing.T) { - db := openTestConn(t) - defer db.Close() - - _, err := db.Exec("create temp table test (i integer)") - if err != nil { - t.Fatal(err) - } - - _, err = db.Query("select * from test where i=$1", "hhh") - if err == nil { - t.Fatal("expected an error") - } - - // Should not get error here - r, err := db.Query("select * from test where i=$1", 1) - if err != nil { - t.Fatal(err) - } - defer r.Close() -} - -func TestParseErrorInExtendedQuery(t *testing.T) { - db := openTestConn(t) - defer db.Close() - - rows, err := db.Query("PARSE_ERROR $1", 1) - if err == nil { - t.Fatal("expected error") - } - - rows, err = db.Query("SELECT 1") - if err != nil { - t.Fatal(err) - } - rows.Close() -} - -// TestReturning tests that an INSERT query using the RETURNING clause returns a row. -func TestReturning(t *testing.T) { - db := openTestConn(t) - defer db.Close() - - _, err := db.Exec("CREATE TEMP TABLE distributors (did integer default 0, dname text)") - if err != nil { - t.Fatal(err) - } - - rows, err := db.Query("INSERT INTO distributors (did, dname) VALUES (DEFAULT, 'XYZ Widgets') " + - "RETURNING did;") - if err != nil { - t.Fatal(err) - } - if !rows.Next() { - t.Fatal("no rows") - } - var did int - err = rows.Scan(&did) - if err != nil { - t.Fatal(err) - } - if did != 0 { - t.Fatalf("bad value for did: got %d, want %d", did, 0) - } - - if rows.Next() { - t.Fatal("unexpected next row") - } - err = rows.Err() - if err != nil { - t.Fatal(err) - } -} - -func TestIssue186(t *testing.T) { - db := openTestConn(t) - defer db.Close() - - // Exec() a query which returns results - _, err := db.Exec("VALUES (1), (2), (3)") - if err != nil { - t.Fatal(err) - } - - _, err = db.Exec("VALUES ($1), ($2), ($3)", 1, 2, 3) - if err != nil { - t.Fatal(err) - } - - // Query() a query which doesn't return any results - txn, err := db.Begin() - if err != nil { - t.Fatal(err) - } - defer txn.Rollback() - - rows, err := txn.Query("CREATE TEMP TABLE foo(f1 int)") - if err != nil { - t.Fatal(err) - } - if err = rows.Close(); err != nil { - t.Fatal(err) - } - - // small trick to get NoData from a parameterized query - _, err = txn.Exec("CREATE RULE nodata AS ON INSERT TO foo DO INSTEAD NOTHING") - if err != nil { - t.Fatal(err) - } - rows, err = txn.Query("INSERT INTO foo VALUES ($1)", 1) - if err != nil { - t.Fatal(err) - } - if err = rows.Close(); err != nil { - t.Fatal(err) - } -} - -func TestIssue196(t *testing.T) { - db := openTestConn(t) - defer db.Close() - - row := db.QueryRow("SELECT float4 '0.10000122' = $1, float8 '35.03554004971999' = $2", - float32(0.10000122), float64(35.03554004971999)) - - var float4match, float8match bool - err := row.Scan(&float4match, &float8match) - if err != nil { - t.Fatal(err) - } - if !float4match { - t.Errorf("Expected float4 fidelity to be maintained; got no match") - } - if !float8match { - t.Errorf("Expected float8 fidelity to be maintained; got no match") - } -} - -// Test that any CommandComplete messages sent before the query results are -// ignored. -func TestIssue282(t *testing.T) { - db := openTestConn(t) - defer db.Close() - - var search_path string - err := db.QueryRow(` - SET LOCAL search_path TO pg_catalog; - SET LOCAL search_path TO pg_catalog; - SHOW search_path`).Scan(&search_path) - if err != nil { - t.Fatal(err) - } - if search_path != "pg_catalog" { - t.Fatalf("unexpected search_path %s", search_path) - } -} - -func TestReadFloatPrecision(t *testing.T) { - db := openTestConn(t) - defer db.Close() - - row := db.QueryRow("SELECT float4 '0.10000122', float8 '35.03554004971999'") - var float4val float32 - var float8val float64 - err := row.Scan(&float4val, &float8val) - if err != nil { - t.Fatal(err) - } - if float4val != float32(0.10000122) { - t.Errorf("Expected float4 fidelity to be maintained; got no match") - } - if float8val != float64(35.03554004971999) { - t.Errorf("Expected float8 fidelity to be maintained; got no match") - } -} - -func TestXactMultiStmt(t *testing.T) { - // minified test case based on bug reports from - // pico303@gmail.com and rangelspam@gmail.com - t.Skip("Skipping failing test") - db := openTestConn(t) - defer db.Close() - - tx, err := db.Begin() - if err != nil { - t.Fatal(err) - } - defer tx.Commit() - - rows, err := tx.Query("select 1") - if err != nil { - t.Fatal(err) - } - - if rows.Next() { - var val int32 - if err = rows.Scan(&val); err != nil { - t.Fatal(err) - } - } else { - t.Fatal("Expected at least one row in first query in xact") - } - - rows2, err := tx.Query("select 2") - if err != nil { - t.Fatal(err) - } - - if rows2.Next() { - var val2 int32 - if err := rows2.Scan(&val2); err != nil { - t.Fatal(err) - } - } else { - t.Fatal("Expected at least one row in second query in xact") - } - - if err = rows.Err(); err != nil { - t.Fatal(err) - } - - if err = rows2.Err(); err != nil { - t.Fatal(err) - } - - if err = tx.Commit(); err != nil { - t.Fatal(err) - } -} - -var envParseTests = []struct { - Expected map[string]string - Env []string -}{ - { - Env: []string{"PGDATABASE=hello", "PGUSER=goodbye"}, - Expected: map[string]string{"dbname": "hello", "user": "goodbye"}, - }, - { - Env: []string{"PGDATESTYLE=ISO, MDY"}, - Expected: map[string]string{"datestyle": "ISO, MDY"}, - }, - { - Env: []string{"PGCONNECT_TIMEOUT=30"}, - Expected: map[string]string{"connect_timeout": "30"}, - }, -} - -func TestParseEnviron(t *testing.T) { - for i, tt := range envParseTests { - results := parseEnviron(tt.Env) - if !reflect.DeepEqual(tt.Expected, results) { - t.Errorf("%d: Expected: %#v Got: %#v", i, tt.Expected, results) - } - } -} - -func TestParseComplete(t *testing.T) { - tpc := func(commandTag string, command string, affectedRows int64, shouldFail bool) { - defer func() { - if p := recover(); p != nil { - if !shouldFail { - t.Error(p) - } - } - }() - cn := &conn{} - res, c := cn.parseComplete(commandTag) - if c != command { - t.Errorf("Expected %v, got %v", command, c) - } - n, err := res.RowsAffected() - if err != nil { - t.Fatal(err) - } - if n != affectedRows { - t.Errorf("Expected %d, got %d", affectedRows, n) - } - } - - tpc("ALTER TABLE", "ALTER TABLE", 0, false) - tpc("INSERT 0 1", "INSERT", 1, false) - tpc("UPDATE 100", "UPDATE", 100, false) - tpc("SELECT 100", "SELECT", 100, false) - tpc("FETCH 100", "FETCH", 100, false) - // allow COPY (and others) without row count - tpc("COPY", "COPY", 0, false) - // don't fail on command tags we don't recognize - tpc("UNKNOWNCOMMANDTAG", "UNKNOWNCOMMANDTAG", 0, false) - - // failure cases - tpc("INSERT 1", "", 0, true) // missing oid - tpc("UPDATE 0 1", "", 0, true) // too many numbers - tpc("SELECT foo", "", 0, true) // invalid row count -} - -func TestExecerInterface(t *testing.T) { - // Gin up a straw man private struct just for the type check - cn := &conn{c: nil} - var cni interface{} = cn - - _, ok := cni.(driver.Execer) - if !ok { - t.Fatal("Driver doesn't implement Execer") - } -} - -func TestNullAfterNonNull(t *testing.T) { - db := openTestConn(t) - defer db.Close() - - r, err := db.Query("SELECT 9::integer UNION SELECT NULL::integer") - if err != nil { - t.Fatal(err) - } - - var n sql.NullInt64 - - if !r.Next() { - if r.Err() != nil { - t.Fatal(err) - } - t.Fatal("expected row") - } - - if err := r.Scan(&n); err != nil { - t.Fatal(err) - } - - if n.Int64 != 9 { - t.Fatalf("expected 2, not %d", n.Int64) - } - - if !r.Next() { - if r.Err() != nil { - t.Fatal(err) - } - t.Fatal("expected row") - } - - if err := r.Scan(&n); err != nil { - t.Fatal(err) - } - - if n.Valid { - t.Fatal("expected n to be invalid") - } - - if n.Int64 != 0 { - t.Fatalf("expected n to 2, not %d", n.Int64) - } -} - -func Test64BitErrorChecking(t *testing.T) { - defer func() { - if err := recover(); err != nil { - t.Fatal("panic due to 0xFFFFFFFF != -1 " + - "when int is 64 bits") - } - }() - - db := openTestConn(t) - defer db.Close() - - r, err := db.Query(`SELECT * -FROM (VALUES (0::integer, NULL::text), (1, 'test string')) AS t;`) - - if err != nil { - t.Fatal(err) - } - - defer r.Close() - - for r.Next() { - } -} - -func TestCommit(t *testing.T) { - db := openTestConn(t) - defer db.Close() - - _, err := db.Exec("CREATE TEMP TABLE temp (a int)") - if err != nil { - t.Fatal(err) - } - sqlInsert := "INSERT INTO temp VALUES (1)" - sqlSelect := "SELECT * FROM temp" - tx, err := db.Begin() - if err != nil { - t.Fatal(err) - } - _, err = tx.Exec(sqlInsert) - if err != nil { - t.Fatal(err) - } - err = tx.Commit() - if err != nil { - t.Fatal(err) - } - var i int - err = db.QueryRow(sqlSelect).Scan(&i) - if err != nil { - t.Fatal(err) - } - if i != 1 { - t.Fatalf("expected 1, got %d", i) - } -} - -func TestErrorClass(t *testing.T) { - db := openTestConn(t) - defer db.Close() - - _, err := db.Query("SELECT int 'notint'") - if err == nil { - t.Fatal("expected error") - } - pge, ok := err.(*Error) - if !ok { - t.Fatalf("expected *pq.Error, got %#+v", err) - } - if pge.Code.Class() != "22" { - t.Fatalf("expected class 28, got %v", pge.Code.Class()) - } - if pge.Code.Class().Name() != "data_exception" { - t.Fatalf("expected data_exception, got %v", pge.Code.Class().Name()) - } -} - -func TestParseOpts(t *testing.T) { - tests := []struct { - in string - expected values - valid bool - }{ - {"dbname=hello user=goodbye", values{"dbname": "hello", "user": "goodbye"}, true}, - {"dbname=hello user=goodbye ", values{"dbname": "hello", "user": "goodbye"}, true}, - {"dbname = hello user=goodbye", values{"dbname": "hello", "user": "goodbye"}, true}, - {"dbname=hello user =goodbye", values{"dbname": "hello", "user": "goodbye"}, true}, - {"dbname=hello user= goodbye", values{"dbname": "hello", "user": "goodbye"}, true}, - {"host=localhost password='correct horse battery staple'", values{"host": "localhost", "password": "correct horse battery staple"}, true}, - {"dbname=データベース password=パスワード", values{"dbname": "データベース", "password": "パスワード"}, true}, - {"dbname=hello user=''", values{"dbname": "hello", "user": ""}, true}, - {"user='' dbname=hello", values{"dbname": "hello", "user": ""}, true}, - // The last option value is an empty string if there's no non-whitespace after its = - {"dbname=hello user= ", values{"dbname": "hello", "user": ""}, true}, - - // The parser ignores spaces after = and interprets the next set of non-whitespace characters as the value. - {"user= password=foo", values{"user": "password=foo"}, true}, - - // Backslash escapes next char - {`user=a\ \'\\b`, values{"user": `a '\b`}, true}, - {`user='a \'b'`, values{"user": `a 'b`}, true}, - - // Incomplete escape - {`user=x\`, values{}, false}, - - // No '=' after the key - {"postgre://marko@internet", values{}, false}, - {"dbname user=goodbye", values{}, false}, - {"user=foo blah", values{}, false}, - {"user=foo blah ", values{}, false}, - - // Unterminated quoted value - {"dbname=hello user='unterminated", values{}, false}, - } - - for _, test := range tests { - o := make(values) - err := parseOpts(test.in, o) - - switch { - case err != nil && test.valid: - t.Errorf("%q got unexpected error: %s", test.in, err) - case err == nil && test.valid && !reflect.DeepEqual(test.expected, o): - t.Errorf("%q got: %#v want: %#v", test.in, o, test.expected) - case err == nil && !test.valid: - t.Errorf("%q expected an error", test.in) - } - } -} - -func TestRuntimeParameters(t *testing.T) { - type RuntimeTestResult int - const ( - ResultUnknown RuntimeTestResult = iota - ResultSuccess - ResultError // other error - ) - - tests := []struct { - conninfo string - param string - expected string - expectedOutcome RuntimeTestResult - }{ - // invalid parameter - {"DOESNOTEXIST=foo", "", "", ResultError}, - // we can only work with a specific value for these two - {"client_encoding=SQL_ASCII", "", "", ResultError}, - {"datestyle='ISO, YDM'", "", "", ResultError}, - // "options" should work exactly as it does in libpq - {"options='-c search_path=pqgotest'", "search_path", "pqgotest", ResultSuccess}, - // pq should override client_encoding in this case - {"options='-c client_encoding=SQL_ASCII'", "client_encoding", "UTF8", ResultSuccess}, - // allow client_encoding to be set explicitly - {"client_encoding=UTF8", "client_encoding", "UTF8", ResultSuccess}, - // test a runtime parameter not supported by libpq - {"work_mem='139kB'", "work_mem", "139kB", ResultSuccess}, - // test fallback_application_name - {"application_name=foo fallback_application_name=bar", "application_name", "foo", ResultSuccess}, - {"application_name='' fallback_application_name=bar", "application_name", "", ResultSuccess}, - {"fallback_application_name=bar", "application_name", "bar", ResultSuccess}, - } - - for _, test := range tests { - db, err := openTestConnConninfo(test.conninfo) - if err != nil { - t.Fatal(err) - } - - // application_name didn't exist before 9.0 - if test.param == "application_name" && getServerVersion(t, db) < 90000 { - db.Close() - continue - } - - tryGetParameterValue := func() (value string, outcome RuntimeTestResult) { - defer db.Close() - row := db.QueryRow("SELECT current_setting($1)", test.param) - err = row.Scan(&value) - if err != nil { - return "", ResultError - } - return value, ResultSuccess - } - - value, outcome := tryGetParameterValue() - if outcome != test.expectedOutcome && outcome == ResultError { - t.Fatalf("%v: unexpected error: %v", test.conninfo, err) - } - if outcome != test.expectedOutcome { - t.Fatalf("unexpected outcome %v (was expecting %v) for conninfo \"%s\"", - outcome, test.expectedOutcome, test.conninfo) - } - if value != test.expected { - t.Fatalf("bad value for %s: got %s, want %s with conninfo \"%s\"", - test.param, value, test.expected, test.conninfo) - } - } -} - -func TestIsUTF8(t *testing.T) { - var cases = []struct { - name string - want bool - }{ - {"unicode", true}, - {"utf-8", true}, - {"utf_8", true}, - {"UTF-8", true}, - {"UTF8", true}, - {"utf8", true}, - {"u n ic_ode", true}, - {"ut_f%8", true}, - {"ubf8", false}, - {"punycode", false}, - } - - for _, test := range cases { - if g := isUTF8(test.name); g != test.want { - t.Errorf("isUTF8(%q) = %v want %v", test.name, g, test.want) - } - } -} - -func TestQuoteIdentifier(t *testing.T) { - var cases = []struct { - input string - want string - }{ - {`foo`, `"foo"`}, - {`foo bar baz`, `"foo bar baz"`}, - {`foo"bar`, `"foo""bar"`}, - {"foo\x00bar", `"foo"`}, - {"\x00foo", `""`}, - } - - for _, test := range cases { - got := QuoteIdentifier(test.input) - if got != test.want { - t.Errorf("QuoteIdentifier(%q) = %v want %v", test.input, got, test.want) - } - } -} diff --git a/Godeps/_workspace/src/github.com/lib/pq/copy_test.go b/Godeps/_workspace/src/github.com/lib/pq/copy_test.go deleted file mode 100644 index 6af4c9c76..000000000 --- a/Godeps/_workspace/src/github.com/lib/pq/copy_test.go +++ /dev/null @@ -1,462 +0,0 @@ -package pq - -import ( - "bytes" - "database/sql" - "strings" - "testing" -) - -func TestCopyInStmt(t *testing.T) { - var stmt string - stmt = CopyIn("table name") - if stmt != `COPY "table name" () FROM STDIN` { - t.Fatal(stmt) - } - - stmt = CopyIn("table name", "column 1", "column 2") - if stmt != `COPY "table name" ("column 1", "column 2") FROM STDIN` { - t.Fatal(stmt) - } - - stmt = CopyIn(`table " name """`, `co"lumn""`) - if stmt != `COPY "table "" name """"""" ("co""lumn""""") FROM STDIN` { - t.Fatal(stmt) - } -} - -func TestCopyInSchemaStmt(t *testing.T) { - var stmt string - stmt = CopyInSchema("schema name", "table name") - if stmt != `COPY "schema name"."table name" () FROM STDIN` { - t.Fatal(stmt) - } - - stmt = CopyInSchema("schema name", "table name", "column 1", "column 2") - if stmt != `COPY "schema name"."table name" ("column 1", "column 2") FROM STDIN` { - t.Fatal(stmt) - } - - stmt = CopyInSchema(`schema " name """`, `table " name """`, `co"lumn""`) - if stmt != `COPY "schema "" name """"""".`+ - `"table "" name """"""" ("co""lumn""""") FROM STDIN` { - t.Fatal(stmt) - } -} - -func TestCopyInMultipleValues(t *testing.T) { - db := openTestConn(t) - defer db.Close() - - txn, err := db.Begin() - if err != nil { - t.Fatal(err) - } - defer txn.Rollback() - - _, err = txn.Exec("CREATE TEMP TABLE temp (a int, b varchar)") - if err != nil { - t.Fatal(err) - } - - stmt, err := txn.Prepare(CopyIn("temp", "a", "b")) - if err != nil { - t.Fatal(err) - } - - longString := strings.Repeat("#", 500) - - for i := 0; i < 500; i++ { - _, err = stmt.Exec(int64(i), longString) - if err != nil { - t.Fatal(err) - } - } - - _, err = stmt.Exec() - if err != nil { - t.Fatal(err) - } - - err = stmt.Close() - if err != nil { - t.Fatal(err) - } - - var num int - err = txn.QueryRow("SELECT COUNT(*) FROM temp").Scan(&num) - if err != nil { - t.Fatal(err) - } - - if num != 500 { - t.Fatalf("expected 500 items, not %d", num) - } -} - -func TestCopyInRaiseStmtTrigger(t *testing.T) { - db := openTestConn(t) - defer db.Close() - - if getServerVersion(t, db) < 90000 { - var exists int - err := db.QueryRow("SELECT 1 FROM pg_language WHERE lanname = 'plpgsql'").Scan(&exists) - if err == sql.ErrNoRows { - t.Skip("language PL/PgSQL does not exist; skipping TestCopyInRaiseStmtTrigger") - } else if err != nil { - t.Fatal(err) - } - } - - txn, err := db.Begin() - if err != nil { - t.Fatal(err) - } - defer txn.Rollback() - - _, err = txn.Exec("CREATE TEMP TABLE temp (a int, b varchar)") - if err != nil { - t.Fatal(err) - } - - _, err = txn.Exec(` - CREATE OR REPLACE FUNCTION pg_temp.temptest() - RETURNS trigger AS - $BODY$ begin - raise notice 'Hello world'; - return new; - end $BODY$ - LANGUAGE plpgsql`) - if err != nil { - t.Fatal(err) - } - - _, err = txn.Exec(` - CREATE TRIGGER temptest_trigger - BEFORE INSERT - ON temp - FOR EACH ROW - EXECUTE PROCEDURE pg_temp.temptest()`) - if err != nil { - t.Fatal(err) - } - - stmt, err := txn.Prepare(CopyIn("temp", "a", "b")) - if err != nil { - t.Fatal(err) - } - - longString := strings.Repeat("#", 500) - - _, err = stmt.Exec(int64(1), longString) - if err != nil { - t.Fatal(err) - } - - _, err = stmt.Exec() - if err != nil { - t.Fatal(err) - } - - err = stmt.Close() - if err != nil { - t.Fatal(err) - } - - var num int - err = txn.QueryRow("SELECT COUNT(*) FROM temp").Scan(&num) - if err != nil { - t.Fatal(err) - } - - if num != 1 { - t.Fatalf("expected 1 items, not %d", num) - } -} - -func TestCopyInTypes(t *testing.T) { - db := openTestConn(t) - defer db.Close() - - txn, err := db.Begin() - if err != nil { - t.Fatal(err) - } - defer txn.Rollback() - - _, err = txn.Exec("CREATE TEMP TABLE temp (num INTEGER, text VARCHAR, blob BYTEA, nothing VARCHAR)") - if err != nil { - t.Fatal(err) - } - - stmt, err := txn.Prepare(CopyIn("temp", "num", "text", "blob", "nothing")) - if err != nil { - t.Fatal(err) - } - - _, err = stmt.Exec(int64(1234567890), "Héllö\n ☃!\r\t\\", []byte{0, 255, 9, 10, 13}, nil) - if err != nil { - t.Fatal(err) - } - - _, err = stmt.Exec() - if err != nil { - t.Fatal(err) - } - - err = stmt.Close() - if err != nil { - t.Fatal(err) - } - - var num int - var text string - var blob []byte - var nothing sql.NullString - - err = txn.QueryRow("SELECT * FROM temp").Scan(&num, &text, &blob, ¬hing) - if err != nil { - t.Fatal(err) - } - - if num != 1234567890 { - t.Fatal("unexpected result", num) - } - if text != "Héllö\n ☃!\r\t\\" { - t.Fatal("unexpected result", text) - } - if bytes.Compare(blob, []byte{0, 255, 9, 10, 13}) != 0 { - t.Fatal("unexpected result", blob) - } - if nothing.Valid { - t.Fatal("unexpected result", nothing.String) - } -} - -func TestCopyInWrongType(t *testing.T) { - db := openTestConn(t) - defer db.Close() - - txn, err := db.Begin() - if err != nil { - t.Fatal(err) - } - defer txn.Rollback() - - _, err = txn.Exec("CREATE TEMP TABLE temp (num INTEGER)") - if err != nil { - t.Fatal(err) - } - - stmt, err := txn.Prepare(CopyIn("temp", "num")) - if err != nil { - t.Fatal(err) - } - defer stmt.Close() - - _, err = stmt.Exec("Héllö\n ☃!\r\t\\") - if err != nil { - t.Fatal(err) - } - - _, err = stmt.Exec() - if err == nil { - t.Fatal("expected error") - } - if pge := err.(*Error); pge.Code.Name() != "invalid_text_representation" { - t.Fatalf("expected 'invalid input syntax for integer' error, got %s (%+v)", pge.Code.Name(), pge) - } -} - -func TestCopyOutsideOfTxnError(t *testing.T) { - db := openTestConn(t) - defer db.Close() - - _, err := db.Prepare(CopyIn("temp", "num")) - if err == nil { - t.Fatal("COPY outside of transaction did not return an error") - } - if err != errCopyNotSupportedOutsideTxn { - t.Fatalf("expected %s, got %s", err, err.Error()) - } -} - -func TestCopyInBinaryError(t *testing.T) { - db := openTestConn(t) - defer db.Close() - - txn, err := db.Begin() - if err != nil { - t.Fatal(err) - } - defer txn.Rollback() - - _, err = txn.Exec("CREATE TEMP TABLE temp (num INTEGER)") - if err != nil { - t.Fatal(err) - } - _, err = txn.Prepare("COPY temp (num) FROM STDIN WITH binary") - if err != errBinaryCopyNotSupported { - t.Fatalf("expected %s, got %+v", errBinaryCopyNotSupported, err) - } - // check that the protocol is in a valid state - err = txn.Rollback() - if err != nil { - t.Fatal(err) - } -} - -func TestCopyFromError(t *testing.T) { - db := openTestConn(t) - defer db.Close() - - txn, err := db.Begin() - if err != nil { - t.Fatal(err) - } - defer txn.Rollback() - - _, err = txn.Exec("CREATE TEMP TABLE temp (num INTEGER)") - if err != nil { - t.Fatal(err) - } - _, err = txn.Prepare("COPY temp (num) TO STDOUT") - if err != errCopyToNotSupported { - t.Fatalf("expected %s, got %+v", errCopyToNotSupported, err) - } - // check that the protocol is in a valid state - err = txn.Rollback() - if err != nil { - t.Fatal(err) - } -} - -func TestCopySyntaxError(t *testing.T) { - db := openTestConn(t) - defer db.Close() - - txn, err := db.Begin() - if err != nil { - t.Fatal(err) - } - defer txn.Rollback() - - _, err = txn.Prepare("COPY ") - if err == nil { - t.Fatal("expected error") - } - if pge := err.(*Error); pge.Code.Name() != "syntax_error" { - t.Fatalf("expected syntax error, got %s (%+v)", pge.Code.Name(), pge) - } - // check that the protocol is in a valid state - err = txn.Rollback() - if err != nil { - t.Fatal(err) - } -} - -// Tests for connection errors in copyin.resploop() -func TestCopyRespLoopConnectionError(t *testing.T) { - db := openTestConn(t) - defer db.Close() - - txn, err := db.Begin() - if err != nil { - t.Fatal(err) - } - defer txn.Rollback() - - var pid int - err = txn.QueryRow("SELECT pg_backend_pid()").Scan(&pid) - if err != nil { - t.Fatal(err) - } - - _, err = txn.Exec("CREATE TEMP TABLE temp (a int)") - if err != nil { - t.Fatal(err) - } - - stmt, err := txn.Prepare(CopyIn("temp", "a")) - if err != nil { - t.Fatal(err) - } - - _, err = db.Exec("SELECT pg_terminate_backend($1)", pid) - if err != nil { - t.Fatal(err) - } - - if getServerVersion(t, db) < 90500 { - // We have to try and send something over, since postgres before - // version 9.5 won't process SIGTERMs while it's waiting for - // CopyData/CopyEnd messages; see tcop/postgres.c. - _, err = stmt.Exec(1) - if err != nil { - t.Fatal(err) - } - } - _, err = stmt.Exec() - if err == nil { - t.Fatalf("expected error") - } - pge, ok := err.(*Error) - if !ok { - t.Fatalf("expected *pq.Error, got %+#v", err) - } else if pge.Code.Name() != "admin_shutdown" { - t.Fatalf("expected admin_shutdown, got %s", pge.Code.Name()) - } - - err = stmt.Close() - if err != nil { - t.Fatal(err) - } -} - -func BenchmarkCopyIn(b *testing.B) { - db := openTestConn(b) - defer db.Close() - - txn, err := db.Begin() - if err != nil { - b.Fatal(err) - } - defer txn.Rollback() - - _, err = txn.Exec("CREATE TEMP TABLE temp (a int, b varchar)") - if err != nil { - b.Fatal(err) - } - - stmt, err := txn.Prepare(CopyIn("temp", "a", "b")) - if err != nil { - b.Fatal(err) - } - - for i := 0; i < b.N; i++ { - _, err = stmt.Exec(int64(i), "hello world!") - if err != nil { - b.Fatal(err) - } - } - - _, err = stmt.Exec() - if err != nil { - b.Fatal(err) - } - - err = stmt.Close() - if err != nil { - b.Fatal(err) - } - - var num int - err = txn.QueryRow("SELECT COUNT(*) FROM temp").Scan(&num) - if err != nil { - b.Fatal(err) - } - - if num != b.N { - b.Fatalf("expected %d items, not %d", b.N, num) - } -} diff --git a/Godeps/_workspace/src/github.com/lib/pq/encode_test.go b/Godeps/_workspace/src/github.com/lib/pq/encode_test.go deleted file mode 100644 index 97b663886..000000000 --- a/Godeps/_workspace/src/github.com/lib/pq/encode_test.go +++ /dev/null @@ -1,719 +0,0 @@ -package pq - -import ( - "bytes" - "database/sql" - "fmt" - "testing" - "time" - - "github.com/lib/pq/oid" -) - -func TestScanTimestamp(t *testing.T) { - var nt NullTime - tn := time.Now() - nt.Scan(tn) - if !nt.Valid { - t.Errorf("Expected Valid=false") - } - if nt.Time != tn { - t.Errorf("Time value mismatch") - } -} - -func TestScanNilTimestamp(t *testing.T) { - var nt NullTime - nt.Scan(nil) - if nt.Valid { - t.Errorf("Expected Valid=false") - } -} - -var timeTests = []struct { - str string - timeval time.Time -}{ - {"22001-02-03", time.Date(22001, time.February, 3, 0, 0, 0, 0, time.FixedZone("", 0))}, - {"2001-02-03", time.Date(2001, time.February, 3, 0, 0, 0, 0, time.FixedZone("", 0))}, - {"2001-02-03 04:05:06", time.Date(2001, time.February, 3, 4, 5, 6, 0, time.FixedZone("", 0))}, - {"2001-02-03 04:05:06.000001", time.Date(2001, time.February, 3, 4, 5, 6, 1000, time.FixedZone("", 0))}, - {"2001-02-03 04:05:06.00001", time.Date(2001, time.February, 3, 4, 5, 6, 10000, time.FixedZone("", 0))}, - {"2001-02-03 04:05:06.0001", time.Date(2001, time.February, 3, 4, 5, 6, 100000, time.FixedZone("", 0))}, - {"2001-02-03 04:05:06.001", time.Date(2001, time.February, 3, 4, 5, 6, 1000000, time.FixedZone("", 0))}, - {"2001-02-03 04:05:06.01", time.Date(2001, time.February, 3, 4, 5, 6, 10000000, time.FixedZone("", 0))}, - {"2001-02-03 04:05:06.1", time.Date(2001, time.February, 3, 4, 5, 6, 100000000, time.FixedZone("", 0))}, - {"2001-02-03 04:05:06.12", time.Date(2001, time.February, 3, 4, 5, 6, 120000000, time.FixedZone("", 0))}, - {"2001-02-03 04:05:06.123", time.Date(2001, time.February, 3, 4, 5, 6, 123000000, time.FixedZone("", 0))}, - {"2001-02-03 04:05:06.1234", time.Date(2001, time.February, 3, 4, 5, 6, 123400000, time.FixedZone("", 0))}, - {"2001-02-03 04:05:06.12345", time.Date(2001, time.February, 3, 4, 5, 6, 123450000, time.FixedZone("", 0))}, - {"2001-02-03 04:05:06.123456", time.Date(2001, time.February, 3, 4, 5, 6, 123456000, time.FixedZone("", 0))}, - {"2001-02-03 04:05:06.123-07", time.Date(2001, time.February, 3, 4, 5, 6, 123000000, - time.FixedZone("", -7*60*60))}, - {"2001-02-03 04:05:06-07", time.Date(2001, time.February, 3, 4, 5, 6, 0, - time.FixedZone("", -7*60*60))}, - {"2001-02-03 04:05:06-07:42", time.Date(2001, time.February, 3, 4, 5, 6, 0, - time.FixedZone("", -(7*60*60+42*60)))}, - {"2001-02-03 04:05:06-07:30:09", time.Date(2001, time.February, 3, 4, 5, 6, 0, - time.FixedZone("", -(7*60*60+30*60+9)))}, - {"2001-02-03 04:05:06+07", time.Date(2001, time.February, 3, 4, 5, 6, 0, - time.FixedZone("", 7*60*60))}, - {"0011-02-03 04:05:06 BC", time.Date(-10, time.February, 3, 4, 5, 6, 0, time.FixedZone("", 0))}, - {"0011-02-03 04:05:06.123 BC", time.Date(-10, time.February, 3, 4, 5, 6, 123000000, time.FixedZone("", 0))}, - {"0011-02-03 04:05:06.123-07 BC", time.Date(-10, time.February, 3, 4, 5, 6, 123000000, - time.FixedZone("", -7*60*60))}, - {"0001-02-03 04:05:06.123", time.Date(1, time.February, 3, 4, 5, 6, 123000000, time.FixedZone("", 0))}, - {"0001-02-03 04:05:06.123 BC", time.Date(1, time.February, 3, 4, 5, 6, 123000000, time.FixedZone("", 0)).AddDate(-1, 0, 0)}, - {"0001-02-03 04:05:06.123 BC", time.Date(0, time.February, 3, 4, 5, 6, 123000000, time.FixedZone("", 0))}, - {"0002-02-03 04:05:06.123 BC", time.Date(0, time.February, 3, 4, 5, 6, 123000000, time.FixedZone("", 0)).AddDate(-1, 0, 0)}, - {"0002-02-03 04:05:06.123 BC", time.Date(-1, time.February, 3, 4, 5, 6, 123000000, time.FixedZone("", 0))}, - {"12345-02-03 04:05:06.1", time.Date(12345, time.February, 3, 4, 5, 6, 100000000, time.FixedZone("", 0))}, - {"123456-02-03 04:05:06.1", time.Date(123456, time.February, 3, 4, 5, 6, 100000000, time.FixedZone("", 0))}, -} - -// Helper function for the two tests below -func tryParse(str string) (t time.Time, err error) { - defer func() { - if p := recover(); p != nil { - err = fmt.Errorf("%v", p) - return - } - }() - i := parseTs(nil, str) - t, ok := i.(time.Time) - if !ok { - err = fmt.Errorf("Not a time.Time type, got %#v", i) - } - return -} - -// Test that parsing the string results in the expected value. -func TestParseTs(t *testing.T) { - for i, tt := range timeTests { - val, err := tryParse(tt.str) - if err != nil { - t.Errorf("%d: got error: %v", i, err) - } else if val.String() != tt.timeval.String() { - t.Errorf("%d: expected to parse %q into %q; got %q", - i, tt.str, tt.timeval, val) - } - } -} - -// Now test that sending the value into the database and parsing it back -// returns the same time.Time value. -func TestEncodeAndParseTs(t *testing.T) { - db, err := openTestConnConninfo("timezone='Etc/UTC'") - if err != nil { - t.Fatal(err) - } - defer db.Close() - - for i, tt := range timeTests { - var dbstr string - err = db.QueryRow("SELECT ($1::timestamptz)::text", tt.timeval).Scan(&dbstr) - if err != nil { - t.Errorf("%d: could not send value %q to the database: %s", i, tt.timeval, err) - continue - } - - val, err := tryParse(dbstr) - if err != nil { - t.Errorf("%d: could not parse value %q: %s", i, dbstr, err) - continue - } - val = val.In(tt.timeval.Location()) - if val.String() != tt.timeval.String() { - t.Errorf("%d: expected to parse %q into %q; got %q", i, dbstr, tt.timeval, val) - } - } -} - -var formatTimeTests = []struct { - time time.Time - expected string -}{ - {time.Time{}, "0001-01-01T00:00:00Z"}, - {time.Date(2001, time.February, 3, 4, 5, 6, 123456789, time.FixedZone("", 0)), "2001-02-03T04:05:06.123456789Z"}, - {time.Date(2001, time.February, 3, 4, 5, 6, 123456789, time.FixedZone("", 2*60*60)), "2001-02-03T04:05:06.123456789+02:00"}, - {time.Date(2001, time.February, 3, 4, 5, 6, 123456789, time.FixedZone("", -6*60*60)), "2001-02-03T04:05:06.123456789-06:00"}, - {time.Date(2001, time.February, 3, 4, 5, 6, 0, time.FixedZone("", -(7*60*60+30*60+9))), "2001-02-03T04:05:06-07:30:09"}, - - {time.Date(1, time.February, 3, 4, 5, 6, 123456789, time.FixedZone("", 0)), "0001-02-03T04:05:06.123456789Z"}, - {time.Date(1, time.February, 3, 4, 5, 6, 123456789, time.FixedZone("", 2*60*60)), "0001-02-03T04:05:06.123456789+02:00"}, - {time.Date(1, time.February, 3, 4, 5, 6, 123456789, time.FixedZone("", -6*60*60)), "0001-02-03T04:05:06.123456789-06:00"}, - - {time.Date(0, time.February, 3, 4, 5, 6, 123456789, time.FixedZone("", 0)), "0001-02-03T04:05:06.123456789Z BC"}, - {time.Date(0, time.February, 3, 4, 5, 6, 123456789, time.FixedZone("", 2*60*60)), "0001-02-03T04:05:06.123456789+02:00 BC"}, - {time.Date(0, time.February, 3, 4, 5, 6, 123456789, time.FixedZone("", -6*60*60)), "0001-02-03T04:05:06.123456789-06:00 BC"}, - - {time.Date(1, time.February, 3, 4, 5, 6, 0, time.FixedZone("", -(7*60*60+30*60+9))), "0001-02-03T04:05:06-07:30:09"}, - {time.Date(0, time.February, 3, 4, 5, 6, 0, time.FixedZone("", -(7*60*60+30*60+9))), "0001-02-03T04:05:06-07:30:09 BC"}, -} - -func TestFormatTs(t *testing.T) { - for i, tt := range formatTimeTests { - val := string(formatTs(tt.time)) - if val != tt.expected { - t.Errorf("%d: incorrect time format %q, want %q", i, val, tt.expected) - } - } -} - -func TestTimestampWithTimeZone(t *testing.T) { - db := openTestConn(t) - defer db.Close() - - tx, err := db.Begin() - if err != nil { - t.Fatal(err) - } - defer tx.Rollback() - - // try several different locations, all included in Go's zoneinfo.zip - for _, locName := range []string{ - "UTC", - "America/Chicago", - "America/New_York", - "Australia/Darwin", - "Australia/Perth", - } { - loc, err := time.LoadLocation(locName) - if err != nil { - t.Logf("Could not load time zone %s - skipping", locName) - continue - } - - // Postgres timestamps have a resolution of 1 microsecond, so don't - // use the full range of the Nanosecond argument - refTime := time.Date(2012, 11, 6, 10, 23, 42, 123456000, loc) - - for _, pgTimeZone := range []string{"US/Eastern", "Australia/Darwin"} { - // Switch Postgres's timezone to test different output timestamp formats - _, err = tx.Exec(fmt.Sprintf("set time zone '%s'", pgTimeZone)) - if err != nil { - t.Fatal(err) - } - - var gotTime time.Time - row := tx.QueryRow("select $1::timestamp with time zone", refTime) - err = row.Scan(&gotTime) - if err != nil { - t.Fatal(err) - } - - if !refTime.Equal(gotTime) { - t.Errorf("timestamps not equal: %s != %s", refTime, gotTime) - } - - // check that the time zone is set correctly based on TimeZone - pgLoc, err := time.LoadLocation(pgTimeZone) - if err != nil { - t.Logf("Could not load time zone %s - skipping", pgLoc) - continue - } - translated := refTime.In(pgLoc) - if translated.String() != gotTime.String() { - t.Errorf("timestamps not equal: %s != %s", translated, gotTime) - } - } - } -} - -func TestTimestampWithOutTimezone(t *testing.T) { - db := openTestConn(t) - defer db.Close() - - test := func(ts, pgts string) { - r, err := db.Query("SELECT $1::timestamp", pgts) - if err != nil { - t.Fatalf("Could not run query: %v", err) - } - - n := r.Next() - - if n != true { - t.Fatal("Expected at least one row") - } - - var result time.Time - err = r.Scan(&result) - if err != nil { - t.Fatalf("Did not expect error scanning row: %v", err) - } - - expected, err := time.Parse(time.RFC3339, ts) - if err != nil { - t.Fatalf("Could not parse test time literal: %v", err) - } - - if !result.Equal(expected) { - t.Fatalf("Expected time to match %v: got mismatch %v", - expected, result) - } - - n = r.Next() - if n != false { - t.Fatal("Expected only one row") - } - } - - test("2000-01-01T00:00:00Z", "2000-01-01T00:00:00") - - // Test higher precision time - test("2013-01-04T20:14:58.80033Z", "2013-01-04 20:14:58.80033") -} - -func TestInfinityTimestamp(t *testing.T) { - db := openTestConn(t) - defer db.Close() - var err error - var resultT time.Time - - expectedError := fmt.Errorf(`sql: Scan error on column index 0: unsupported driver -> Scan pair: []uint8 -> *time.Time`) - type testCases []struct { - Query string - Param string - ExpectedErr error - ExpectedVal interface{} - } - tc := testCases{ - {"SELECT $1::timestamp", "-infinity", expectedError, "-infinity"}, - {"SELECT $1::timestamptz", "-infinity", expectedError, "-infinity"}, - {"SELECT $1::timestamp", "infinity", expectedError, "infinity"}, - {"SELECT $1::timestamptz", "infinity", expectedError, "infinity"}, - } - // try to assert []byte to time.Time - for _, q := range tc { - err = db.QueryRow(q.Query, q.Param).Scan(&resultT) - if err.Error() != q.ExpectedErr.Error() { - t.Errorf("Scanning -/+infinity, expected error, %q, got %q", q.ExpectedErr, err) - } - } - // yield []byte - for _, q := range tc { - var resultI interface{} - err = db.QueryRow(q.Query, q.Param).Scan(&resultI) - if err != nil { - t.Errorf("Scanning -/+infinity, expected no error, got %q", err) - } - result, ok := resultI.([]byte) - if !ok { - t.Errorf("Scanning -/+infinity, expected []byte, got %#v", resultI) - } - if string(result) != q.ExpectedVal { - t.Errorf("Scanning -/+infinity, expected %q, got %q", q.ExpectedVal, result) - } - } - - y1500 := time.Date(1500, time.January, 1, 0, 0, 0, 0, time.UTC) - y2500 := time.Date(2500, time.January, 1, 0, 0, 0, 0, time.UTC) - EnableInfinityTs(y1500, y2500) - - err = db.QueryRow("SELECT $1::timestamp", "infinity").Scan(&resultT) - if err != nil { - t.Errorf("Scanning infinity, expected no error, got %q", err) - } - if !resultT.Equal(y2500) { - t.Errorf("Scanning infinity, expected %q, got %q", y2500, resultT) - } - - err = db.QueryRow("SELECT $1::timestamptz", "infinity").Scan(&resultT) - if err != nil { - t.Errorf("Scanning infinity, expected no error, got %q", err) - } - if !resultT.Equal(y2500) { - t.Errorf("Scanning Infinity, expected time %q, got %q", y2500, resultT.String()) - } - - err = db.QueryRow("SELECT $1::timestamp", "-infinity").Scan(&resultT) - if err != nil { - t.Errorf("Scanning -infinity, expected no error, got %q", err) - } - if !resultT.Equal(y1500) { - t.Errorf("Scanning -infinity, expected time %q, got %q", y1500, resultT.String()) - } - - err = db.QueryRow("SELECT $1::timestamptz", "-infinity").Scan(&resultT) - if err != nil { - t.Errorf("Scanning -infinity, expected no error, got %q", err) - } - if !resultT.Equal(y1500) { - t.Errorf("Scanning -infinity, expected time %q, got %q", y1500, resultT.String()) - } - - y_1500 := time.Date(-1500, time.January, 1, 0, 0, 0, 0, time.UTC) - y11500 := time.Date(11500, time.January, 1, 0, 0, 0, 0, time.UTC) - var s string - err = db.QueryRow("SELECT $1::timestamp::text", y_1500).Scan(&s) - if err != nil { - t.Errorf("Encoding -infinity, expected no error, got %q", err) - } - if s != "-infinity" { - t.Errorf("Encoding -infinity, expected %q, got %q", "-infinity", s) - } - err = db.QueryRow("SELECT $1::timestamptz::text", y_1500).Scan(&s) - if err != nil { - t.Errorf("Encoding -infinity, expected no error, got %q", err) - } - if s != "-infinity" { - t.Errorf("Encoding -infinity, expected %q, got %q", "-infinity", s) - } - - err = db.QueryRow("SELECT $1::timestamp::text", y11500).Scan(&s) - if err != nil { - t.Errorf("Encoding infinity, expected no error, got %q", err) - } - if s != "infinity" { - t.Errorf("Encoding infinity, expected %q, got %q", "infinity", s) - } - err = db.QueryRow("SELECT $1::timestamptz::text", y11500).Scan(&s) - if err != nil { - t.Errorf("Encoding infinity, expected no error, got %q", err) - } - if s != "infinity" { - t.Errorf("Encoding infinity, expected %q, got %q", "infinity", s) - } - - disableInfinityTs() - - var panicErrorString string - func() { - defer func() { - panicErrorString, _ = recover().(string) - }() - EnableInfinityTs(y2500, y1500) - }() - if panicErrorString != infinityTsNegativeMustBeSmaller { - t.Errorf("Expected error, %q, got %q", infinityTsNegativeMustBeSmaller, panicErrorString) - } -} - -func TestStringWithNul(t *testing.T) { - db := openTestConn(t) - defer db.Close() - - hello0world := string("hello\x00world") - _, err := db.Query("SELECT $1::text", &hello0world) - if err == nil { - t.Fatal("Postgres accepts a string with nul in it; " + - "injection attacks may be plausible") - } -} - -func TestByteSliceToText(t *testing.T) { - db := openTestConn(t) - defer db.Close() - - b := []byte("hello world") - row := db.QueryRow("SELECT $1::text", b) - - var result []byte - err := row.Scan(&result) - if err != nil { - t.Fatal(err) - } - - if string(result) != string(b) { - t.Fatalf("expected %v but got %v", b, result) - } -} - -func TestStringToBytea(t *testing.T) { - db := openTestConn(t) - defer db.Close() - - b := "hello world" - row := db.QueryRow("SELECT $1::bytea", b) - - var result []byte - err := row.Scan(&result) - if err != nil { - t.Fatal(err) - } - - if !bytes.Equal(result, []byte(b)) { - t.Fatalf("expected %v but got %v", b, result) - } -} - -func TestTextByteSliceToUUID(t *testing.T) { - db := openTestConn(t) - defer db.Close() - - b := []byte("a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11") - row := db.QueryRow("SELECT $1::uuid", b) - - var result string - err := row.Scan(&result) - if forceBinaryParameters() { - pqErr := err.(*Error) - if pqErr == nil { - t.Errorf("Expected to get error") - } else if pqErr.Code != "22P03" { - t.Fatalf("Expected to get invalid binary encoding error (22P03), got %s", pqErr.Code) - } - } else { - if err != nil { - t.Fatal(err) - } - - if result != string(b) { - t.Fatalf("expected %v but got %v", b, result) - } - } -} - -func TestBinaryByteSlicetoUUID(t *testing.T) { - db := openTestConn(t) - defer db.Close() - - b := []byte{'\xa0','\xee','\xbc','\x99', - '\x9c', '\x0b', - '\x4e', '\xf8', - '\xbb', '\x00', '\x6b', - '\xb9', '\xbd', '\x38', '\x0a', '\x11'} - row := db.QueryRow("SELECT $1::uuid", b) - - var result string - err := row.Scan(&result) - if forceBinaryParameters() { - if err != nil { - t.Fatal(err) - } - - if result != string("a0eebc99-9c0b-4ef8-bb00-6bb9bd380a11") { - t.Fatalf("expected %v but got %v", b, result) - } - } else { - pqErr := err.(*Error) - if pqErr == nil { - t.Errorf("Expected to get error") - } else if pqErr.Code != "22021" { - t.Fatalf("Expected to get invalid byte sequence for encoding error (22021), got %s", pqErr.Code) - } - } -} - -func TestStringToUUID(t *testing.T) { - db := openTestConn(t) - defer db.Close() - - s := "a0eebc99-9c0b-4ef8-bb00-6bb9bd380a11" - row := db.QueryRow("SELECT $1::uuid", s) - - var result string - err := row.Scan(&result) - if err != nil { - t.Fatal(err) - } - - if result != s { - t.Fatalf("expected %v but got %v", s, result) - } -} - -func TestTextByteSliceToInt(t *testing.T) { - db := openTestConn(t) - defer db.Close() - - expected := 12345678 - b := []byte(fmt.Sprintf("%d", expected)) - row := db.QueryRow("SELECT $1::int", b) - - var result int - err := row.Scan(&result) - if forceBinaryParameters() { - pqErr := err.(*Error) - if pqErr == nil { - t.Errorf("Expected to get error") - } else if pqErr.Code != "22P03" { - t.Fatalf("Expected to get invalid binary encoding error (22P03), got %s", pqErr.Code) - } - } else { - if err != nil { - t.Fatal(err) - } - if result != expected { - t.Fatalf("expected %v but got %v", expected, result) - } - } -} - -func TestBinaryByteSliceToInt(t *testing.T) { - db := openTestConn(t) - defer db.Close() - - expected := 12345678 - b := []byte{'\x00', '\xbc', '\x61', '\x4e'} - row := db.QueryRow("SELECT $1::int", b) - - var result int - err := row.Scan(&result) - if forceBinaryParameters() { - if err != nil { - t.Fatal(err) - } - if result != expected { - t.Fatalf("expected %v but got %v", expected, result) - } - } else { - pqErr := err.(*Error) - if pqErr == nil { - t.Errorf("Expected to get error") - } else if pqErr.Code != "22021" { - t.Fatalf("Expected to get invalid byte sequence for encoding error (22021), got %s", pqErr.Code) - } - } -} - -func TestByteaOutputFormatEncoding(t *testing.T) { - input := []byte("\\x\x00\x01\x02\xFF\xFEabcdefg0123") - want := []byte("\\x5c78000102fffe6162636465666730313233") - got := encode(¶meterStatus{serverVersion: 90000}, input, oid.T_bytea) - if !bytes.Equal(want, got) { - t.Errorf("invalid hex bytea output, got %v but expected %v", got, want) - } - - want = []byte("\\\\x\\000\\001\\002\\377\\376abcdefg0123") - got = encode(¶meterStatus{serverVersion: 84000}, input, oid.T_bytea) - if !bytes.Equal(want, got) { - t.Errorf("invalid escape bytea output, got %v but expected %v", got, want) - } -} - -func TestByteaOutputFormats(t *testing.T) { - db := openTestConn(t) - defer db.Close() - - if getServerVersion(t, db) < 90000 { - // skip - return - } - - testByteaOutputFormat := func(f string, usePrepared bool) { - expectedData := []byte("\x5c\x78\x00\xff\x61\x62\x63\x01\x08") - sqlQuery := "SELECT decode('5c7800ff6162630108', 'hex')" - - var data []byte - - // use a txn to avoid relying on getting the same connection - txn, err := db.Begin() - if err != nil { - t.Fatal(err) - } - defer txn.Rollback() - - _, err = txn.Exec("SET LOCAL bytea_output TO " + f) - if err != nil { - t.Fatal(err) - } - var rows *sql.Rows - var stmt *sql.Stmt - if usePrepared { - stmt, err = txn.Prepare(sqlQuery) - if err != nil { - t.Fatal(err) - } - rows, err = stmt.Query() - } else { - // use Query; QueryRow would hide the actual error - rows, err = txn.Query(sqlQuery) - } - if err != nil { - t.Fatal(err) - } - if !rows.Next() { - if rows.Err() != nil { - t.Fatal(rows.Err()) - } - t.Fatal("shouldn't happen") - } - err = rows.Scan(&data) - if err != nil { - t.Fatal(err) - } - err = rows.Close() - if err != nil { - t.Fatal(err) - } - if stmt != nil { - err = stmt.Close() - if err != nil { - t.Fatal(err) - } - } - if !bytes.Equal(data, expectedData) { - t.Errorf("unexpected bytea value %v for format %s; expected %v", data, f, expectedData) - } - } - - testByteaOutputFormat("hex", false) - testByteaOutputFormat("escape", false) - testByteaOutputFormat("hex", true) - testByteaOutputFormat("escape", true) -} - -func TestAppendEncodedText(t *testing.T) { - var buf []byte - - buf = appendEncodedText(¶meterStatus{serverVersion: 90000}, buf, int64(10)) - buf = append(buf, '\t') - buf = appendEncodedText(¶meterStatus{serverVersion: 90000}, buf, 42.0000000001) - buf = append(buf, '\t') - buf = appendEncodedText(¶meterStatus{serverVersion: 90000}, buf, "hello\tworld") - buf = append(buf, '\t') - buf = appendEncodedText(¶meterStatus{serverVersion: 90000}, buf, []byte{0, 128, 255}) - - if string(buf) != "10\t42.0000000001\thello\\tworld\t\\\\x0080ff" { - t.Fatal(string(buf)) - } -} - -func TestAppendEscapedText(t *testing.T) { - if esc := appendEscapedText(nil, "hallo\tescape"); string(esc) != "hallo\\tescape" { - t.Fatal(string(esc)) - } - if esc := appendEscapedText(nil, "hallo\\tescape\n"); string(esc) != "hallo\\\\tescape\\n" { - t.Fatal(string(esc)) - } - if esc := appendEscapedText(nil, "\n\r\t\f"); string(esc) != "\\n\\r\\t\f" { - t.Fatal(string(esc)) - } -} - -func TestAppendEscapedTextExistingBuffer(t *testing.T) { - var buf []byte - buf = []byte("123\t") - if esc := appendEscapedText(buf, "hallo\tescape"); string(esc) != "123\thallo\\tescape" { - t.Fatal(string(esc)) - } - buf = []byte("123\t") - if esc := appendEscapedText(buf, "hallo\\tescape\n"); string(esc) != "123\thallo\\\\tescape\\n" { - t.Fatal(string(esc)) - } - buf = []byte("123\t") - if esc := appendEscapedText(buf, "\n\r\t\f"); string(esc) != "123\t\\n\\r\\t\f" { - t.Fatal(string(esc)) - } -} - -func BenchmarkAppendEscapedText(b *testing.B) { - longString := "" - for i := 0; i < 100; i++ { - longString += "123456789\n" - } - for i := 0; i < b.N; i++ { - appendEscapedText(nil, longString) - } -} - -func BenchmarkAppendEscapedTextNoEscape(b *testing.B) { - longString := "" - for i := 0; i < 100; i++ { - longString += "1234567890" - } - for i := 0; i < b.N; i++ { - appendEscapedText(nil, longString) - } -} diff --git a/Godeps/_workspace/src/github.com/lib/pq/hstore/hstore_test.go b/Godeps/_workspace/src/github.com/lib/pq/hstore/hstore_test.go deleted file mode 100644 index c9c108fc3..000000000 --- a/Godeps/_workspace/src/github.com/lib/pq/hstore/hstore_test.go +++ /dev/null @@ -1,148 +0,0 @@ -package hstore - -import ( - "database/sql" - "os" - "testing" - - _ "github.com/lib/pq" -) - -type Fatalistic interface { - Fatal(args ...interface{}) -} - -func openTestConn(t Fatalistic) *sql.DB { - datname := os.Getenv("PGDATABASE") - sslmode := os.Getenv("PGSSLMODE") - - if datname == "" { - os.Setenv("PGDATABASE", "pqgotest") - } - - if sslmode == "" { - os.Setenv("PGSSLMODE", "disable") - } - - conn, err := sql.Open("postgres", "") - if err != nil { - t.Fatal(err) - } - - return conn -} - -func TestHstore(t *testing.T) { - db := openTestConn(t) - defer db.Close() - - // quitely create hstore if it doesn't exist - _, err := db.Exec("CREATE EXTENSION IF NOT EXISTS hstore") - if err != nil { - t.Skipf("Skipping hstore tests - hstore extension create failed: %s", err.Error()) - } - - hs := Hstore{} - - // test for null-valued hstores - err = db.QueryRow("SELECT NULL::hstore").Scan(&hs) - if err != nil { - t.Fatal(err) - } - if hs.Map != nil { - t.Fatalf("expected null map") - } - - err = db.QueryRow("SELECT $1::hstore", hs).Scan(&hs) - if err != nil { - t.Fatalf("re-query null map failed: %s", err.Error()) - } - if hs.Map != nil { - t.Fatalf("expected null map") - } - - // test for empty hstores - err = db.QueryRow("SELECT ''::hstore").Scan(&hs) - if err != nil { - t.Fatal(err) - } - if hs.Map == nil { - t.Fatalf("expected empty map, got null map") - } - if len(hs.Map) != 0 { - t.Fatalf("expected empty map, got len(map)=%d", len(hs.Map)) - } - - err = db.QueryRow("SELECT $1::hstore", hs).Scan(&hs) - if err != nil { - t.Fatalf("re-query empty map failed: %s", err.Error()) - } - if hs.Map == nil { - t.Fatalf("expected empty map, got null map") - } - if len(hs.Map) != 0 { - t.Fatalf("expected empty map, got len(map)=%d", len(hs.Map)) - } - - // a few example maps to test out - hsOnePair := Hstore{ - Map: map[string]sql.NullString{ - "key1": {"value1", true}, - }, - } - - hsThreePairs := Hstore{ - Map: map[string]sql.NullString{ - "key1": {"value1", true}, - "key2": {"value2", true}, - "key3": {"value3", true}, - }, - } - - hsSmorgasbord := Hstore{ - Map: map[string]sql.NullString{ - "nullstring": {"NULL", true}, - "actuallynull": {"", false}, - "NULL": {"NULL string key", true}, - "withbracket": {"value>42", true}, - "withequal": {"value=42", true}, - `"withquotes1"`: {`this "should" be fine`, true}, - `"withquotes"2"`: {`this "should\" also be fine`, true}, - "embedded1": {"value1=>x1", true}, - "embedded2": {`"value2"=>x2`, true}, - "withnewlines": {"\n\nvalue\t=>2", true}, - "<>": {`this, "should,\" also, => be fine`, true}, - }, - } - - // test encoding in query params, then decoding during Scan - testBidirectional := func(h Hstore) { - err = db.QueryRow("SELECT $1::hstore", h).Scan(&hs) - if err != nil { - t.Fatalf("re-query %d-pair map failed: %s", len(h.Map), err.Error()) - } - if hs.Map == nil { - t.Fatalf("expected %d-pair map, got null map", len(h.Map)) - } - if len(hs.Map) != len(h.Map) { - t.Fatalf("expected %d-pair map, got len(map)=%d", len(h.Map), len(hs.Map)) - } - - for key, val := range hs.Map { - otherval, found := h.Map[key] - if !found { - t.Fatalf(" key '%v' not found in %d-pair map", key, len(h.Map)) - } - if otherval.Valid != val.Valid { - t.Fatalf(" value %v <> %v in %d-pair map", otherval, val, len(h.Map)) - } - if otherval.String != val.String { - t.Fatalf(" value '%v' <> '%v' in %d-pair map", otherval.String, val.String, len(h.Map)) - } - } - } - - testBidirectional(hsOnePair) - testBidirectional(hsThreePairs) - testBidirectional(hsSmorgasbord) -} diff --git a/Godeps/_workspace/src/github.com/lib/pq/notify_test.go b/Godeps/_workspace/src/github.com/lib/pq/notify_test.go deleted file mode 100644 index fe8941a4e..000000000 --- a/Godeps/_workspace/src/github.com/lib/pq/notify_test.go +++ /dev/null @@ -1,574 +0,0 @@ -package pq - -import ( - "errors" - "fmt" - "io" - "os" - "runtime" - "sync" - "sync/atomic" - "testing" - "time" -) - -var errNilNotification = errors.New("nil notification") - -func expectNotification(t *testing.T, ch <-chan *Notification, relname string, extra string) error { - select { - case n := <-ch: - if n == nil { - return errNilNotification - } - if n.Channel != relname || n.Extra != extra { - return fmt.Errorf("unexpected notification %v", n) - } - return nil - case <-time.After(1500 * time.Millisecond): - return fmt.Errorf("timeout") - } -} - -func expectNoNotification(t *testing.T, ch <-chan *Notification) error { - select { - case n := <-ch: - return fmt.Errorf("unexpected notification %v", n) - case <-time.After(100 * time.Millisecond): - return nil - } -} - -func expectEvent(t *testing.T, eventch <-chan ListenerEventType, et ListenerEventType) error { - select { - case e := <-eventch: - if e != et { - return fmt.Errorf("unexpected event %v", e) - } - return nil - case <-time.After(1500 * time.Millisecond): - panic("expectEvent timeout") - } -} - -func expectNoEvent(t *testing.T, eventch <-chan ListenerEventType) error { - select { - case e := <-eventch: - return fmt.Errorf("unexpected event %v", e) - case <-time.After(100 * time.Millisecond): - return nil - } -} - -func newTestListenerConn(t *testing.T) (*ListenerConn, <-chan *Notification) { - datname := os.Getenv("PGDATABASE") - sslmode := os.Getenv("PGSSLMODE") - - if datname == "" { - os.Setenv("PGDATABASE", "pqgotest") - } - - if sslmode == "" { - os.Setenv("PGSSLMODE", "disable") - } - - notificationChan := make(chan *Notification) - l, err := NewListenerConn("", notificationChan) - if err != nil { - t.Fatal(err) - } - - return l, notificationChan -} - -func TestNewListenerConn(t *testing.T) { - l, _ := newTestListenerConn(t) - - defer l.Close() -} - -func TestConnListen(t *testing.T) { - l, channel := newTestListenerConn(t) - - defer l.Close() - - db := openTestConn(t) - defer db.Close() - - ok, err := l.Listen("notify_test") - if !ok || err != nil { - t.Fatal(err) - } - - _, err = db.Exec("NOTIFY notify_test") - if err != nil { - t.Fatal(err) - } - - err = expectNotification(t, channel, "notify_test", "") - if err != nil { - t.Fatal(err) - } -} - -func TestConnUnlisten(t *testing.T) { - l, channel := newTestListenerConn(t) - - defer l.Close() - - db := openTestConn(t) - defer db.Close() - - ok, err := l.Listen("notify_test") - if !ok || err != nil { - t.Fatal(err) - } - - _, err = db.Exec("NOTIFY notify_test") - - err = expectNotification(t, channel, "notify_test", "") - if err != nil { - t.Fatal(err) - } - - ok, err = l.Unlisten("notify_test") - if !ok || err != nil { - t.Fatal(err) - } - - _, err = db.Exec("NOTIFY notify_test") - if err != nil { - t.Fatal(err) - } - - err = expectNoNotification(t, channel) - if err != nil { - t.Fatal(err) - } -} - -func TestConnUnlistenAll(t *testing.T) { - l, channel := newTestListenerConn(t) - - defer l.Close() - - db := openTestConn(t) - defer db.Close() - - ok, err := l.Listen("notify_test") - if !ok || err != nil { - t.Fatal(err) - } - - _, err = db.Exec("NOTIFY notify_test") - - err = expectNotification(t, channel, "notify_test", "") - if err != nil { - t.Fatal(err) - } - - ok, err = l.UnlistenAll() - if !ok || err != nil { - t.Fatal(err) - } - - _, err = db.Exec("NOTIFY notify_test") - if err != nil { - t.Fatal(err) - } - - err = expectNoNotification(t, channel) - if err != nil { - t.Fatal(err) - } -} - -func TestConnClose(t *testing.T) { - l, _ := newTestListenerConn(t) - defer l.Close() - - err := l.Close() - if err != nil { - t.Fatal(err) - } - err = l.Close() - if err != errListenerConnClosed { - t.Fatalf("expected errListenerConnClosed; got %v", err) - } -} - -func TestConnPing(t *testing.T) { - l, _ := newTestListenerConn(t) - defer l.Close() - err := l.Ping() - if err != nil { - t.Fatal(err) - } - err = l.Close() - if err != nil { - t.Fatal(err) - } - err = l.Ping() - if err != errListenerConnClosed { - t.Fatalf("expected errListenerConnClosed; got %v", err) - } -} - -// Test for deadlock where a query fails while another one is queued -func TestConnExecDeadlock(t *testing.T) { - l, _ := newTestListenerConn(t) - defer l.Close() - - var wg sync.WaitGroup - wg.Add(2) - - go func() { - l.ExecSimpleQuery("SELECT pg_sleep(60)") - wg.Done() - }() - runtime.Gosched() - go func() { - l.ExecSimpleQuery("SELECT 1") - wg.Done() - }() - // give the two goroutines some time to get into position - runtime.Gosched() - // calls Close on the net.Conn; equivalent to a network failure - l.Close() - - var done int32 = 0 - go func() { - time.Sleep(10 * time.Second) - if atomic.LoadInt32(&done) != 1 { - panic("timed out") - } - }() - wg.Wait() - atomic.StoreInt32(&done, 1) -} - -// Test for ListenerConn being closed while a slow query is executing -func TestListenerConnCloseWhileQueryIsExecuting(t *testing.T) { - l, _ := newTestListenerConn(t) - defer l.Close() - - var wg sync.WaitGroup - wg.Add(1) - - go func() { - sent, err := l.ExecSimpleQuery("SELECT pg_sleep(60)") - if sent { - panic("expected sent=false") - } - // could be any of a number of errors - if err == nil { - panic("expected error") - } - wg.Done() - }() - // give the above goroutine some time to get into position - runtime.Gosched() - err := l.Close() - if err != nil { - t.Fatal(err) - } - var done int32 = 0 - go func() { - time.Sleep(10 * time.Second) - if atomic.LoadInt32(&done) != 1 { - panic("timed out") - } - }() - wg.Wait() - atomic.StoreInt32(&done, 1) -} - -func TestNotifyExtra(t *testing.T) { - db := openTestConn(t) - defer db.Close() - - if getServerVersion(t, db) < 90000 { - t.Skip("skipping NOTIFY payload test since the server does not appear to support it") - } - - l, channel := newTestListenerConn(t) - defer l.Close() - - ok, err := l.Listen("notify_test") - if !ok || err != nil { - t.Fatal(err) - } - - _, err = db.Exec("NOTIFY notify_test, 'something'") - if err != nil { - t.Fatal(err) - } - - err = expectNotification(t, channel, "notify_test", "something") - if err != nil { - t.Fatal(err) - } -} - -// create a new test listener and also set the timeouts -func newTestListenerTimeout(t *testing.T, min time.Duration, max time.Duration) (*Listener, <-chan ListenerEventType) { - datname := os.Getenv("PGDATABASE") - sslmode := os.Getenv("PGSSLMODE") - - if datname == "" { - os.Setenv("PGDATABASE", "pqgotest") - } - - if sslmode == "" { - os.Setenv("PGSSLMODE", "disable") - } - - eventch := make(chan ListenerEventType, 16) - l := NewListener("", min, max, func(t ListenerEventType, err error) { eventch <- t }) - err := expectEvent(t, eventch, ListenerEventConnected) - if err != nil { - t.Fatal(err) - } - return l, eventch -} - -func newTestListener(t *testing.T) (*Listener, <-chan ListenerEventType) { - return newTestListenerTimeout(t, time.Hour, time.Hour) -} - -func TestListenerListen(t *testing.T) { - l, _ := newTestListener(t) - defer l.Close() - - db := openTestConn(t) - defer db.Close() - - err := l.Listen("notify_listen_test") - if err != nil { - t.Fatal(err) - } - - _, err = db.Exec("NOTIFY notify_listen_test") - if err != nil { - t.Fatal(err) - } - - err = expectNotification(t, l.Notify, "notify_listen_test", "") - if err != nil { - t.Fatal(err) - } -} - -func TestListenerUnlisten(t *testing.T) { - l, _ := newTestListener(t) - defer l.Close() - - db := openTestConn(t) - defer db.Close() - - err := l.Listen("notify_listen_test") - if err != nil { - t.Fatal(err) - } - - _, err = db.Exec("NOTIFY notify_listen_test") - if err != nil { - t.Fatal(err) - } - - err = l.Unlisten("notify_listen_test") - if err != nil { - t.Fatal(err) - } - - err = expectNotification(t, l.Notify, "notify_listen_test", "") - if err != nil { - t.Fatal(err) - } - - _, err = db.Exec("NOTIFY notify_listen_test") - if err != nil { - t.Fatal(err) - } - - err = expectNoNotification(t, l.Notify) - if err != nil { - t.Fatal(err) - } -} - -func TestListenerUnlistenAll(t *testing.T) { - l, _ := newTestListener(t) - defer l.Close() - - db := openTestConn(t) - defer db.Close() - - err := l.Listen("notify_listen_test") - if err != nil { - t.Fatal(err) - } - - _, err = db.Exec("NOTIFY notify_listen_test") - if err != nil { - t.Fatal(err) - } - - err = l.UnlistenAll() - if err != nil { - t.Fatal(err) - } - - err = expectNotification(t, l.Notify, "notify_listen_test", "") - if err != nil { - t.Fatal(err) - } - - _, err = db.Exec("NOTIFY notify_listen_test") - if err != nil { - t.Fatal(err) - } - - err = expectNoNotification(t, l.Notify) - if err != nil { - t.Fatal(err) - } -} - -func TestListenerFailedQuery(t *testing.T) { - l, eventch := newTestListener(t) - defer l.Close() - - db := openTestConn(t) - defer db.Close() - - err := l.Listen("notify_listen_test") - if err != nil { - t.Fatal(err) - } - - _, err = db.Exec("NOTIFY notify_listen_test") - if err != nil { - t.Fatal(err) - } - - err = expectNotification(t, l.Notify, "notify_listen_test", "") - if err != nil { - t.Fatal(err) - } - - // shouldn't cause a disconnect - ok, err := l.cn.ExecSimpleQuery("SELECT error") - if !ok { - t.Fatalf("could not send query to server: %v", err) - } - _, ok = err.(PGError) - if !ok { - t.Fatalf("unexpected error %v", err) - } - err = expectNoEvent(t, eventch) - if err != nil { - t.Fatal(err) - } - - // should still work - _, err = db.Exec("NOTIFY notify_listen_test") - if err != nil { - t.Fatal(err) - } - - err = expectNotification(t, l.Notify, "notify_listen_test", "") - if err != nil { - t.Fatal(err) - } -} - -func TestListenerReconnect(t *testing.T) { - l, eventch := newTestListenerTimeout(t, 20*time.Millisecond, time.Hour) - defer l.Close() - - db := openTestConn(t) - defer db.Close() - - err := l.Listen("notify_listen_test") - if err != nil { - t.Fatal(err) - } - - _, err = db.Exec("NOTIFY notify_listen_test") - if err != nil { - t.Fatal(err) - } - - err = expectNotification(t, l.Notify, "notify_listen_test", "") - if err != nil { - t.Fatal(err) - } - - // kill the connection and make sure it comes back up - ok, err := l.cn.ExecSimpleQuery("SELECT pg_terminate_backend(pg_backend_pid())") - if ok { - t.Fatalf("could not kill the connection: %v", err) - } - if err != io.EOF { - t.Fatalf("unexpected error %v", err) - } - err = expectEvent(t, eventch, ListenerEventDisconnected) - if err != nil { - t.Fatal(err) - } - err = expectEvent(t, eventch, ListenerEventReconnected) - if err != nil { - t.Fatal(err) - } - - // should still work - _, err = db.Exec("NOTIFY notify_listen_test") - if err != nil { - t.Fatal(err) - } - - // should get nil after Reconnected - err = expectNotification(t, l.Notify, "", "") - if err != errNilNotification { - t.Fatal(err) - } - - err = expectNotification(t, l.Notify, "notify_listen_test", "") - if err != nil { - t.Fatal(err) - } -} - -func TestListenerClose(t *testing.T) { - l, _ := newTestListenerTimeout(t, 20*time.Millisecond, time.Hour) - defer l.Close() - - err := l.Close() - if err != nil { - t.Fatal(err) - } - err = l.Close() - if err != errListenerClosed { - t.Fatalf("expected errListenerClosed; got %v", err) - } -} - -func TestListenerPing(t *testing.T) { - l, _ := newTestListenerTimeout(t, 20*time.Millisecond, time.Hour) - defer l.Close() - - err := l.Ping() - if err != nil { - t.Fatal(err) - } - - err = l.Close() - if err != nil { - t.Fatal(err) - } - - err = l.Ping() - if err != errListenerClosed { - t.Fatalf("expected errListenerClosed; got %v", err) - } -} diff --git a/Godeps/_workspace/src/github.com/lib/pq/ssl_test.go b/Godeps/_workspace/src/github.com/lib/pq/ssl_test.go deleted file mode 100644 index 932b336f5..000000000 --- a/Godeps/_workspace/src/github.com/lib/pq/ssl_test.go +++ /dev/null @@ -1,226 +0,0 @@ -package pq - -// This file contains SSL tests - -import ( - _ "crypto/sha256" - "crypto/x509" - "database/sql" - "fmt" - "os" - "path/filepath" - "testing" -) - -func maybeSkipSSLTests(t *testing.T) { - // Require some special variables for testing certificates - if os.Getenv("PQSSLCERTTEST_PATH") == "" { - t.Skip("PQSSLCERTTEST_PATH not set, skipping SSL tests") - } - - value := os.Getenv("PQGOSSLTESTS") - if value == "" || value == "0" { - t.Skip("PQGOSSLTESTS not enabled, skipping SSL tests") - } else if value != "1" { - t.Fatalf("unexpected value %q for PQGOSSLTESTS", value) - } -} - -func openSSLConn(t *testing.T, conninfo string) (*sql.DB, error) { - db, err := openTestConnConninfo(conninfo) - if err != nil { - // should never fail - t.Fatal(err) - } - // Do something with the connection to see whether it's working or not. - tx, err := db.Begin() - if err == nil { - return db, tx.Rollback() - } - _ = db.Close() - return nil, err -} - -func checkSSLSetup(t *testing.T, conninfo string) { - db, err := openSSLConn(t, conninfo) - if err == nil { - db.Close() - t.Fatalf("expected error with conninfo=%q", conninfo) - } -} - -// Connect over SSL and run a simple query to test the basics -func TestSSLConnection(t *testing.T) { - maybeSkipSSLTests(t) - // Environment sanity check: should fail without SSL - checkSSLSetup(t, "sslmode=disable user=pqgossltest") - - db, err := openSSLConn(t, "sslmode=require user=pqgossltest") - if err != nil { - t.Fatal(err) - } - rows, err := db.Query("SELECT 1") - if err != nil { - t.Fatal(err) - } - rows.Close() -} - -// Test sslmode=verify-full -func TestSSLVerifyFull(t *testing.T) { - maybeSkipSSLTests(t) - // Environment sanity check: should fail without SSL - checkSSLSetup(t, "sslmode=disable user=pqgossltest") - - // Not OK according to the system CA - _, err := openSSLConn(t, "host=postgres sslmode=verify-full user=pqgossltest") - if err == nil { - t.Fatal("expected error") - } - _, ok := err.(x509.UnknownAuthorityError) - if !ok { - t.Fatalf("expected x509.UnknownAuthorityError, got %#+v", err) - } - - rootCertPath := filepath.Join(os.Getenv("PQSSLCERTTEST_PATH"), "root.crt") - rootCert := "sslrootcert=" + rootCertPath + " " - // No match on Common Name - _, err = openSSLConn(t, rootCert+"host=127.0.0.1 sslmode=verify-full user=pqgossltest") - if err == nil { - t.Fatal("expected error") - } - _, ok = err.(x509.HostnameError) - if !ok { - t.Fatalf("expected x509.HostnameError, got %#+v", err) - } - // OK - _, err = openSSLConn(t, rootCert+"host=postgres sslmode=verify-full user=pqgossltest") - if err != nil { - t.Fatal(err) - } -} - -// Test sslmode=verify-ca -func TestSSLVerifyCA(t *testing.T) { - maybeSkipSSLTests(t) - // Environment sanity check: should fail without SSL - checkSSLSetup(t, "sslmode=disable user=pqgossltest") - - // Not OK according to the system CA - _, err := openSSLConn(t, "host=postgres sslmode=verify-ca user=pqgossltest") - if err == nil { - t.Fatal("expected error") - } - _, ok := err.(x509.UnknownAuthorityError) - if !ok { - t.Fatalf("expected x509.UnknownAuthorityError, got %#+v", err) - } - - rootCertPath := filepath.Join(os.Getenv("PQSSLCERTTEST_PATH"), "root.crt") - rootCert := "sslrootcert=" + rootCertPath + " " - // No match on Common Name, but that's OK - _, err = openSSLConn(t, rootCert+"host=127.0.0.1 sslmode=verify-ca user=pqgossltest") - if err != nil { - t.Fatal(err) - } - // Everything OK - _, err = openSSLConn(t, rootCert+"host=postgres sslmode=verify-ca user=pqgossltest") - if err != nil { - t.Fatal(err) - } -} - -func getCertConninfo(t *testing.T, source string) string { - var sslkey string - var sslcert string - - certpath := os.Getenv("PQSSLCERTTEST_PATH") - - switch source { - case "missingkey": - sslkey = "/tmp/filedoesnotexist" - sslcert = filepath.Join(certpath, "postgresql.crt") - case "missingcert": - sslkey = filepath.Join(certpath, "postgresql.key") - sslcert = "/tmp/filedoesnotexist" - case "certtwice": - sslkey = filepath.Join(certpath, "postgresql.crt") - sslcert = filepath.Join(certpath, "postgresql.crt") - case "valid": - sslkey = filepath.Join(certpath, "postgresql.key") - sslcert = filepath.Join(certpath, "postgresql.crt") - default: - t.Fatalf("invalid source %q", source) - } - return fmt.Sprintf("sslmode=require user=pqgosslcert sslkey=%s sslcert=%s", sslkey, sslcert) -} - -// Authenticate over SSL using client certificates -func TestSSLClientCertificates(t *testing.T) { - maybeSkipSSLTests(t) - // Environment sanity check: should fail without SSL - checkSSLSetup(t, "sslmode=disable user=pqgossltest") - - // Should also fail without a valid certificate - db, err := openSSLConn(t, "sslmode=require user=pqgosslcert") - if err == nil { - db.Close() - t.Fatal("expected error") - } - pge, ok := err.(*Error) - if !ok { - t.Fatal("expected pq.Error") - } - if pge.Code.Name() != "invalid_authorization_specification" { - t.Fatalf("unexpected error code %q", pge.Code.Name()) - } - - // Should work - db, err = openSSLConn(t, getCertConninfo(t, "valid")) - if err != nil { - t.Fatal(err) - } - rows, err := db.Query("SELECT 1") - if err != nil { - t.Fatal(err) - } - rows.Close() -} - -// Test errors with ssl certificates -func TestSSLClientCertificatesMissingFiles(t *testing.T) { - maybeSkipSSLTests(t) - // Environment sanity check: should fail without SSL - checkSSLSetup(t, "sslmode=disable user=pqgossltest") - - // Key missing, should fail - _, err := openSSLConn(t, getCertConninfo(t, "missingkey")) - if err == nil { - t.Fatal("expected error") - } - // should be a PathError - _, ok := err.(*os.PathError) - if !ok { - t.Fatalf("expected PathError, got %#+v", err) - } - - // Cert missing, should fail - _, err = openSSLConn(t, getCertConninfo(t, "missingcert")) - if err == nil { - t.Fatal("expected error") - } - // should be a PathError - _, ok = err.(*os.PathError) - if !ok { - t.Fatalf("expected PathError, got %#+v", err) - } - - // Key has wrong permissions, should fail - _, err = openSSLConn(t, getCertConninfo(t, "certtwice")) - if err == nil { - t.Fatal("expected error") - } - if err != ErrSSLKeyHasWorldPermissions { - t.Fatalf("expected ErrSSLKeyHasWorldPermissions, got %#+v", err) - } -} diff --git a/Godeps/_workspace/src/github.com/lib/pq/url_test.go b/Godeps/_workspace/src/github.com/lib/pq/url_test.go deleted file mode 100644 index 29f4a7c75..000000000 --- a/Godeps/_workspace/src/github.com/lib/pq/url_test.go +++ /dev/null @@ -1,54 +0,0 @@ -package pq - -import ( - "testing" -) - -func TestSimpleParseURL(t *testing.T) { - expected := "host=hostname.remote" - str, err := ParseURL("postgres://hostname.remote") - if err != nil { - t.Fatal(err) - } - - if str != expected { - t.Fatalf("unexpected result from ParseURL:\n+ %v\n- %v", str, expected) - } -} - -func TestFullParseURL(t *testing.T) { - expected := `dbname=database host=hostname.remote password=top\ secret port=1234 user=username` - str, err := ParseURL("postgres://username:top%20secret@hostname.remote:1234/database") - if err != nil { - t.Fatal(err) - } - - if str != expected { - t.Fatalf("unexpected result from ParseURL:\n+ %s\n- %s", str, expected) - } -} - -func TestInvalidProtocolParseURL(t *testing.T) { - _, err := ParseURL("http://hostname.remote") - switch err { - case nil: - t.Fatal("Expected an error from parsing invalid protocol") - default: - msg := "invalid connection protocol: http" - if err.Error() != msg { - t.Fatalf("Unexpected error message:\n+ %s\n- %s", - err.Error(), msg) - } - } -} - -func TestMinimalURL(t *testing.T) { - cs, err := ParseURL("postgres://") - if err != nil { - t.Fatal(err) - } - - if cs != "" { - t.Fatalf("expected blank connection string, got: %q", cs) - } -} diff --git a/Godeps/_workspace/src/github.com/mitchellh/cli/cli_test.go b/Godeps/_workspace/src/github.com/mitchellh/cli/cli_test.go deleted file mode 100644 index 8b0af00e0..000000000 --- a/Godeps/_workspace/src/github.com/mitchellh/cli/cli_test.go +++ /dev/null @@ -1,252 +0,0 @@ -package cli - -import ( - "bytes" - "reflect" - "strings" - "testing" -) - -func TestCLIIsHelp(t *testing.T) { - testCases := []struct { - args []string - isHelp bool - }{ - {[]string{"-h"}, true}, - {[]string{"-help"}, true}, - {[]string{"--help"}, true}, - {[]string{"-h", "foo"}, true}, - {[]string{"foo", "bar"}, false}, - {[]string{"-v", "bar"}, false}, - {[]string{"foo", "-h"}, false}, - {[]string{"foo", "-help"}, false}, - {[]string{"foo", "--help"}, false}, - } - - for _, testCase := range testCases { - cli := &CLI{Args: testCase.args} - result := cli.IsHelp() - - if result != testCase.isHelp { - t.Errorf("Expected '%#v'. Args: %#v", testCase.isHelp, testCase.args) - } - } -} - -func TestCLIIsVersion(t *testing.T) { - testCases := []struct { - args []string - isVersion bool - }{ - {[]string{"-v"}, true}, - {[]string{"-version"}, true}, - {[]string{"--version"}, true}, - {[]string{"-v", "foo"}, true}, - {[]string{"foo", "bar"}, false}, - {[]string{"-h", "bar"}, false}, - {[]string{"foo", "-v"}, false}, - {[]string{"foo", "-version"}, false}, - {[]string{"foo", "--version"}, false}, - } - - for _, testCase := range testCases { - cli := &CLI{Args: testCase.args} - result := cli.IsVersion() - - if result != testCase.isVersion { - t.Errorf("Expected '%#v'. Args: %#v", testCase.isVersion, testCase.args) - } - } -} - -func TestCLIRun(t *testing.T) { - command := new(MockCommand) - cli := &CLI{ - Args: []string{"foo", "-bar", "-baz"}, - Commands: map[string]CommandFactory{ - "foo": func() (Command, error) { - return command, nil - }, - }, - } - - exitCode, err := cli.Run() - if err != nil { - t.Fatalf("err: %s", err) - } - - if exitCode != command.RunResult { - t.Fatalf("bad: %d", exitCode) - } - - if !command.RunCalled { - t.Fatalf("run should be called") - } - - if !reflect.DeepEqual(command.RunArgs, []string{"-bar", "-baz"}) { - t.Fatalf("bad args: %#v", command.RunArgs) - } -} - -func TestCLIRun_blank(t *testing.T) { - command := new(MockCommand) - cli := &CLI{ - Args: []string{"", "foo", "-bar", "-baz"}, - Commands: map[string]CommandFactory{ - "foo": func() (Command, error) { - return command, nil - }, - }, - } - - exitCode, err := cli.Run() - if err != nil { - t.Fatalf("err: %s", err) - } - - if exitCode != command.RunResult { - t.Fatalf("bad: %d", exitCode) - } - - if !command.RunCalled { - t.Fatalf("run should be called") - } - - if !reflect.DeepEqual(command.RunArgs, []string{"-bar", "-baz"}) { - t.Fatalf("bad args: %#v", command.RunArgs) - } -} - -func TestCLIRun_default(t *testing.T) { - commandBar := new(MockCommand) - commandBar.RunResult = 42 - - cli := &CLI{ - Args: []string{"-bar", "-baz"}, - Commands: map[string]CommandFactory{ - "": func() (Command, error) { - return commandBar, nil - }, - "foo": func() (Command, error) { - return new(MockCommand), nil - }, - }, - } - - exitCode, err := cli.Run() - if err != nil { - t.Fatalf("err: %s", err) - } - - if exitCode != commandBar.RunResult { - t.Fatalf("bad: %d", exitCode) - } - - if !commandBar.RunCalled { - t.Fatalf("run should be called") - } - - if !reflect.DeepEqual(commandBar.RunArgs, []string{"-bar", "-baz"}) { - t.Fatalf("bad args: %#v", commandBar.RunArgs) - } -} - -func TestCLIRun_printHelp(t *testing.T) { - testCases := [][]string{ - {}, - {"-h"}, - {"i-dont-exist"}, - {"-bad-flag", "foo"}, - } - - for _, testCase := range testCases { - buf := new(bytes.Buffer) - helpText := "foo" - - cli := &CLI{ - Args: testCase, - Commands: map[string]CommandFactory{ - "foo": func() (Command, error) { - return new(MockCommand), nil - }, - }, - HelpFunc: func(map[string]CommandFactory) string { - return helpText - }, - HelpWriter: buf, - } - - code, err := cli.Run() - if err != nil { - t.Errorf("Args: %#v. Error: %s", testCase, err) - continue - } - - if code != 1 { - t.Errorf("Args: %#v. Code: %d", testCase, code) - continue - } - - if !strings.Contains(buf.String(), helpText) { - t.Errorf("Args: %#v. Text: %v", testCase, buf.String()) - } - } -} - -func TestCLIRun_printCommandHelp(t *testing.T) { - testCases := [][]string{ - {"--help", "foo"}, - {"-h", "foo"}, - } - - for _, args := range testCases { - command := &MockCommand{ - HelpText: "donuts", - } - - buf := new(bytes.Buffer) - cli := &CLI{ - Args: args, - Commands: map[string]CommandFactory{ - "foo": func() (Command, error) { - return command, nil - }, - }, - HelpWriter: buf, - } - - exitCode, err := cli.Run() - if err != nil { - t.Fatalf("err: %s", err) - } - - if exitCode != 1 { - t.Fatalf("bad exit code: %d", exitCode) - } - - if buf.String() != (command.HelpText + "\n") { - t.Fatalf("bad: %#v", buf.String()) - } - } -} - -func TestCLISubcommand(t *testing.T) { - testCases := []struct { - args []string - subcommand string - }{ - {[]string{"bar"}, "bar"}, - {[]string{"foo", "-h"}, "foo"}, - {[]string{"-h", "bar"}, "bar"}, - } - - for _, testCase := range testCases { - cli := &CLI{Args: testCase.args} - result := cli.Subcommand() - - if result != testCase.subcommand { - t.Errorf("Expected %#v, got %#v. Args: %#v", - testCase.subcommand, result, testCase.args) - } - } -} diff --git a/Godeps/_workspace/src/github.com/mitchellh/cli/command_mock_test.go b/Godeps/_workspace/src/github.com/mitchellh/cli/command_mock_test.go deleted file mode 100644 index 241f33939..000000000 --- a/Godeps/_workspace/src/github.com/mitchellh/cli/command_mock_test.go +++ /dev/null @@ -1,9 +0,0 @@ -package cli - -import ( - "testing" -) - -func TestMockCommand_implements(t *testing.T) { - var _ Command = new(MockCommand) -} diff --git a/Godeps/_workspace/src/github.com/mitchellh/cli/ui_colored_test.go b/Godeps/_workspace/src/github.com/mitchellh/cli/ui_colored_test.go deleted file mode 100644 index 35bbbf589..000000000 --- a/Godeps/_workspace/src/github.com/mitchellh/cli/ui_colored_test.go +++ /dev/null @@ -1,74 +0,0 @@ -package cli - -import ( - "testing" -) - -func TestColoredUi_impl(t *testing.T) { - var _ Ui = new(ColoredUi) -} - -func TestColoredUi_noColor(t *testing.T) { - mock := new(MockUi) - ui := &ColoredUi{ - ErrorColor: UiColorNone, - Ui: mock, - } - ui.Error("foo") - - if mock.ErrorWriter.String() != "foo\n" { - t.Fatalf("bad: %#v", mock.ErrorWriter.String()) - } -} - -func TestColoredUi_Error(t *testing.T) { - mock := new(MockUi) - ui := &ColoredUi{ - ErrorColor: UiColor{Code: 33}, - Ui: mock, - } - ui.Error("foo") - - if mock.ErrorWriter.String() != "\033[0;33mfoo\033[0m\n" { - t.Fatalf("bad: %#v", mock.ErrorWriter.String()) - } -} - -func TestColoredUi_Info(t *testing.T) { - mock := new(MockUi) - ui := &ColoredUi{ - InfoColor: UiColor{Code: 33}, - Ui: mock, - } - ui.Info("foo") - - if mock.OutputWriter.String() != "\033[0;33mfoo\033[0m\n" { - t.Fatalf("bad: %#v %#v", mock.OutputWriter.String()) - } -} - -func TestColoredUi_Output(t *testing.T) { - mock := new(MockUi) - ui := &ColoredUi{ - OutputColor: UiColor{Code: 33}, - Ui: mock, - } - ui.Output("foo") - - if mock.OutputWriter.String() != "\033[0;33mfoo\033[0m\n" { - t.Fatalf("bad: %#v %#v", mock.OutputWriter.String()) - } -} - -func TestColoredUi_Warn(t *testing.T) { - mock := new(MockUi) - ui := &ColoredUi{ - WarnColor: UiColor{Code: 33}, - Ui: mock, - } - ui.Warn("foo") - - if mock.ErrorWriter.String() != "\033[0;33mfoo\033[0m\n" { - t.Fatalf("bad: %#v %#v", mock.ErrorWriter.String()) - } -} diff --git a/Godeps/_workspace/src/github.com/mitchellh/cli/ui_concurrent_test.go b/Godeps/_workspace/src/github.com/mitchellh/cli/ui_concurrent_test.go deleted file mode 100644 index d03e49809..000000000 --- a/Godeps/_workspace/src/github.com/mitchellh/cli/ui_concurrent_test.go +++ /dev/null @@ -1,9 +0,0 @@ -package cli - -import ( - "testing" -) - -func TestConcurrentUi_impl(t *testing.T) { - var _ Ui = new(ConcurrentUi) -} diff --git a/Godeps/_workspace/src/github.com/mitchellh/cli/ui_mock_test.go b/Godeps/_workspace/src/github.com/mitchellh/cli/ui_mock_test.go deleted file mode 100644 index 4cce0bef4..000000000 --- a/Godeps/_workspace/src/github.com/mitchellh/cli/ui_mock_test.go +++ /dev/null @@ -1,9 +0,0 @@ -package cli - -import ( - "testing" -) - -func TestMockUi_implements(t *testing.T) { - var _ Ui = new(MockUi) -} diff --git a/Godeps/_workspace/src/github.com/mitchellh/cli/ui_test.go b/Godeps/_workspace/src/github.com/mitchellh/cli/ui_test.go deleted file mode 100644 index ac795ba84..000000000 --- a/Godeps/_workspace/src/github.com/mitchellh/cli/ui_test.go +++ /dev/null @@ -1,162 +0,0 @@ -package cli - -import ( - "bytes" - "io" - "testing" -) - -func TestBasicUi_implements(t *testing.T) { - var _ Ui = new(BasicUi) -} - -func TestBasicUi_Ask(t *testing.T) { - in_r, in_w := io.Pipe() - defer in_r.Close() - defer in_w.Close() - - writer := new(bytes.Buffer) - ui := &BasicUi{ - Reader: in_r, - Writer: writer, - } - - go in_w.Write([]byte("foo bar\nbaz\n")) - - result, err := ui.Ask("Name?") - if err != nil { - t.Fatalf("err: %s", err) - } - - if writer.String() != "Name? " { - t.Fatalf("bad: %#v", writer.String()) - } - - if result != "foo bar" { - t.Fatalf("bad: %#v", result) - } -} - -func TestBasicUi_AskSecret(t *testing.T) { - in_r, in_w := io.Pipe() - defer in_r.Close() - defer in_w.Close() - - writer := new(bytes.Buffer) - ui := &BasicUi{ - Reader: in_r, - Writer: writer, - } - - go in_w.Write([]byte("foo bar\nbaz\n")) - - result, err := ui.AskSecret("Name?") - if err != nil { - t.Fatalf("err: %s", err) - } - - if writer.String() != "Name? " { - t.Fatalf("bad: %#v", writer.String()) - } - - if result != "foo bar" { - t.Fatalf("bad: %#v", result) - } -} - -func TestBasicUi_Error(t *testing.T) { - writer := new(bytes.Buffer) - ui := &BasicUi{Writer: writer} - ui.Error("HELLO") - - if writer.String() != "HELLO\n" { - t.Fatalf("bad: %s", writer.String()) - } -} - -func TestBasicUi_Error_ErrorWriter(t *testing.T) { - writer := new(bytes.Buffer) - ewriter := new(bytes.Buffer) - ui := &BasicUi{Writer: writer, ErrorWriter: ewriter} - ui.Error("HELLO") - - if ewriter.String() != "HELLO\n" { - t.Fatalf("bad: %s", ewriter.String()) - } -} - -func TestBasicUi_Output(t *testing.T) { - writer := new(bytes.Buffer) - ui := &BasicUi{Writer: writer} - ui.Output("HELLO") - - if writer.String() != "HELLO\n" { - t.Fatalf("bad: %s", writer.String()) - } -} - -func TestBasicUi_Warn(t *testing.T) { - writer := new(bytes.Buffer) - ui := &BasicUi{Writer: writer} - ui.Warn("HELLO") - - if writer.String() != "HELLO\n" { - t.Fatalf("bad: %s", writer.String()) - } -} - -func TestPrefixedUi_implements(t *testing.T) { - var _ Ui = new(PrefixedUi) -} - -func TestPrefixedUiError(t *testing.T) { - ui := new(MockUi) - p := &PrefixedUi{ - ErrorPrefix: "foo", - Ui: ui, - } - - p.Error("bar") - if ui.ErrorWriter.String() != "foobar\n" { - t.Fatalf("bad: %s", ui.ErrorWriter.String()) - } -} - -func TestPrefixedUiInfo(t *testing.T) { - ui := new(MockUi) - p := &PrefixedUi{ - InfoPrefix: "foo", - Ui: ui, - } - - p.Info("bar") - if ui.OutputWriter.String() != "foobar\n" { - t.Fatalf("bad: %s", ui.OutputWriter.String()) - } -} - -func TestPrefixedUiOutput(t *testing.T) { - ui := new(MockUi) - p := &PrefixedUi{ - OutputPrefix: "foo", - Ui: ui, - } - - p.Output("bar") - if ui.OutputWriter.String() != "foobar\n" { - t.Fatalf("bad: %s", ui.OutputWriter.String()) - } -} - -func TestPrefixedUiWarn(t *testing.T) { - ui := new(MockUi) - p := &PrefixedUi{ - WarnPrefix: "foo", - Ui: ui, - } - - p.Warn("bar") - if ui.ErrorWriter.String() != "foobar\n" { - t.Fatalf("bad: %s", ui.ErrorWriter.String()) - } -} diff --git a/Godeps/_workspace/src/github.com/mitchellh/cli/ui_writer_test.go b/Godeps/_workspace/src/github.com/mitchellh/cli/ui_writer_test.go deleted file mode 100644 index 62da6e3a9..000000000 --- a/Godeps/_workspace/src/github.com/mitchellh/cli/ui_writer_test.go +++ /dev/null @@ -1,24 +0,0 @@ -package cli - -import ( - "io" - "testing" -) - -func TestUiWriter_impl(t *testing.T) { - var _ io.Writer = new(UiWriter) -} - -func TestUiWriter(t *testing.T) { - ui := new(MockUi) - w := &UiWriter{ - Ui: ui, - } - - w.Write([]byte("foo\n")) - w.Write([]byte("bar\n")) - - if ui.OutputWriter.String() != "foo\nbar\n" { - t.Fatalf("bad: %s", ui.OutputWriter.String()) - } -} diff --git a/Godeps/_workspace/src/github.com/mitchellh/copystructure/copier_time_test.go b/Godeps/_workspace/src/github.com/mitchellh/copystructure/copier_time_test.go deleted file mode 100644 index 5506a0ff1..000000000 --- a/Godeps/_workspace/src/github.com/mitchellh/copystructure/copier_time_test.go +++ /dev/null @@ -1,17 +0,0 @@ -package copystructure - -import ( - "testing" - "time" -) - -func TestTimeCopier(t *testing.T) { - v := time.Now().UTC() - result, err := timeCopier(v) - if err != nil { - t.Fatalf("err: %s", err) - } - if result.(time.Time) != v { - t.Fatalf("bad: %#v\n\n%#v", v, result) - } -} diff --git a/Godeps/_workspace/src/github.com/mitchellh/copystructure/copystructure_examples_test.go b/Godeps/_workspace/src/github.com/mitchellh/copystructure/copystructure_examples_test.go deleted file mode 100644 index e094b8626..000000000 --- a/Godeps/_workspace/src/github.com/mitchellh/copystructure/copystructure_examples_test.go +++ /dev/null @@ -1,22 +0,0 @@ -package copystructure - -import ( - "fmt" -) - -func ExampleCopy() { - input := map[string]interface{}{ - "bob": map[string]interface{}{ - "emails": []string{"a", "b"}, - }, - } - - dup, err := Copy(input) - if err != nil { - panic(err) - } - - fmt.Printf("%#v", dup) - // Output: - // map[string]interface {}{"bob":map[string]interface {}{"emails":[]string{"a", "b"}}} -} diff --git a/Godeps/_workspace/src/github.com/mitchellh/copystructure/copystructure_test.go b/Godeps/_workspace/src/github.com/mitchellh/copystructure/copystructure_test.go deleted file mode 100644 index 2d18fab1d..000000000 --- a/Godeps/_workspace/src/github.com/mitchellh/copystructure/copystructure_test.go +++ /dev/null @@ -1,175 +0,0 @@ -package copystructure - -import ( - "reflect" - "testing" - "time" -) - -func TestCopy_complex(t *testing.T) { - v := map[string]interface{}{ - "foo": []string{"a", "b"}, - "bar": "baz", - } - - result, err := Copy(v) - if err != nil { - t.Fatalf("err: %s", err) - } - - if !reflect.DeepEqual(result, v) { - t.Fatalf("bad: %#v", result) - } -} - -func TestCopy_primitive(t *testing.T) { - cases := []interface{}{ - 42, - "foo", - 1.2, - } - - for _, tc := range cases { - result, err := Copy(tc) - if err != nil { - t.Fatalf("err: %s", err) - } - if result != tc { - t.Fatalf("bad: %#v", result) - } - } -} - -func TestCopy_primitivePtr(t *testing.T) { - cases := []interface{}{ - 42, - "foo", - 1.2, - } - - for _, tc := range cases { - result, err := Copy(&tc) - if err != nil { - t.Fatalf("err: %s", err) - } - - if !reflect.DeepEqual(result, &tc) { - t.Fatalf("bad: %#v", result) - } - } -} - -func TestCopy_map(t *testing.T) { - v := map[string]interface{}{ - "bar": "baz", - } - - result, err := Copy(v) - if err != nil { - t.Fatalf("err: %s", err) - } - - if !reflect.DeepEqual(result, v) { - t.Fatalf("bad: %#v", result) - } -} - -func TestCopy_slice(t *testing.T) { - v := []string{"bar", "baz"} - - result, err := Copy(v) - if err != nil { - t.Fatalf("err: %s", err) - } - - if !reflect.DeepEqual(result, v) { - t.Fatalf("bad: %#v", result) - } -} - -func TestCopy_struct(t *testing.T) { - type test struct { - Value string - } - - v := test{Value: "foo"} - - result, err := Copy(v) - if err != nil { - t.Fatalf("err: %s", err) - } - - if !reflect.DeepEqual(result, v) { - t.Fatalf("bad: %#v", result) - } -} - -func TestCopy_structPtr(t *testing.T) { - type test struct { - Value string - } - - v := &test{Value: "foo"} - - result, err := Copy(v) - if err != nil { - t.Fatalf("err: %s", err) - } - - if !reflect.DeepEqual(result, v) { - t.Fatalf("bad: %#v", result) - } -} - -func TestCopy_structNil(t *testing.T) { - type test struct { - Value string - } - - var v *test - result, err := Copy(v) - if err != nil { - t.Fatalf("err: %s", err) - } - if v, ok := result.(*test); !ok { - t.Fatalf("bad: %#v", result) - } else if v != nil { - t.Fatalf("bad: %#v", v) - } -} - -func TestCopy_structNested(t *testing.T) { - type TestInner struct{} - - type Test struct { - Test *TestInner - } - - v := Test{} - - result, err := Copy(v) - if err != nil { - t.Fatalf("err: %s", err) - } - - if !reflect.DeepEqual(result, v) { - t.Fatalf("bad: %#v", result) - } -} - -func TestCopy_time(t *testing.T) { - type test struct { - Value time.Time - } - - v := test{Value: time.Now().UTC()} - - result, err := Copy(v) - if err != nil { - t.Fatalf("err: %s", err) - } - - if !reflect.DeepEqual(result, v) { - t.Fatalf("bad: %#v", result) - } -} diff --git a/Godeps/_workspace/src/github.com/mitchellh/go-homedir/homedir.go b/Godeps/_workspace/src/github.com/mitchellh/go-homedir/homedir.go index 051f1116c..ed920dec2 100644 --- a/Godeps/_workspace/src/github.com/mitchellh/go-homedir/homedir.go +++ b/Godeps/_workspace/src/github.com/mitchellh/go-homedir/homedir.go @@ -8,19 +8,47 @@ import ( "path/filepath" "runtime" "strings" + "sync" ) +// DisableCache will disable caching of the home directory. Caching is enabled +// by default. +var DisableCache bool + +var homedirCache string +var cacheLock sync.RWMutex + // Dir returns the home directory for the executing user. // // This uses an OS-specific method for discovering the home directory. // An error is returned if a home directory cannot be detected. func Dir() (string, error) { - if runtime.GOOS == "windows" { - return dirWindows() + if !DisableCache { + cacheLock.RLock() + cached := homedirCache + cacheLock.RUnlock() + if cached != "" { + return cached, nil + } } - // Unix-like system, so just assume Unix - return dirUnix() + cacheLock.Lock() + defer cacheLock.Unlock() + + var result string + var err error + if runtime.GOOS == "windows" { + result, err = dirWindows() + } else { + // Unix-like system, so just assume Unix + result, err = dirUnix() + } + + if err != nil { + return "", err + } + homedirCache = result + return result, nil } // Expand expands the path to include the home directory if the path diff --git a/Godeps/_workspace/src/github.com/mitchellh/go-homedir/homedir_test.go b/Godeps/_workspace/src/github.com/mitchellh/go-homedir/homedir_test.go deleted file mode 100644 index ddc24ee0a..000000000 --- a/Godeps/_workspace/src/github.com/mitchellh/go-homedir/homedir_test.go +++ /dev/null @@ -1,98 +0,0 @@ -package homedir - -import ( - "fmt" - "os" - "os/user" - "testing" -) - -func patchEnv(key, value string) func() { - bck := os.Getenv(key) - deferFunc := func() { - os.Setenv(key, bck) - } - - os.Setenv(key, value) - return deferFunc -} - -func TestDir(t *testing.T) { - u, err := user.Current() - if err != nil { - t.Fatalf("err: %s", err) - } - - dir, err := Dir() - if err != nil { - t.Fatalf("err: %s", err) - } - - if u.HomeDir != dir { - t.Fatalf("%#v != %#v", u.HomeDir, dir) - } -} - -func TestExpand(t *testing.T) { - u, err := user.Current() - if err != nil { - t.Fatalf("err: %s", err) - } - - cases := []struct { - Input string - Output string - Err bool - }{ - { - "/foo", - "/foo", - false, - }, - - { - "~/foo", - fmt.Sprintf("%s/foo", u.HomeDir), - false, - }, - - { - "", - "", - false, - }, - - { - "~", - u.HomeDir, - false, - }, - - { - "~foo/foo", - "", - true, - }, - } - - for _, tc := range cases { - actual, err := Expand(tc.Input) - if (err != nil) != tc.Err { - t.Fatalf("Input: %#v\n\nErr: %s", tc.Input, err) - } - - if actual != tc.Output { - t.Fatalf("Input: %#v\n\nOutput: %#v", tc.Input, actual) - } - } - - defer patchEnv("HOME", "/custom/path/")() - expected := "/custom/path/foo/bar" - actual, err := Expand("~/foo/bar") - - if err != nil { - t.Errorf("No error is expected, got: %v", err) - } else if actual != "/custom/path/foo/bar" { - t.Errorf("Expected: %v; actual: %v", expected, actual) - } -} diff --git a/Godeps/_workspace/src/github.com/mitchellh/mapstructure/decode_hooks_test.go b/Godeps/_workspace/src/github.com/mitchellh/mapstructure/decode_hooks_test.go deleted file mode 100644 index 53289afcf..000000000 --- a/Godeps/_workspace/src/github.com/mitchellh/mapstructure/decode_hooks_test.go +++ /dev/null @@ -1,229 +0,0 @@ -package mapstructure - -import ( - "errors" - "reflect" - "testing" - "time" -) - -func TestComposeDecodeHookFunc(t *testing.T) { - f1 := func( - f reflect.Kind, - t reflect.Kind, - data interface{}) (interface{}, error) { - return data.(string) + "foo", nil - } - - f2 := func( - f reflect.Kind, - t reflect.Kind, - data interface{}) (interface{}, error) { - return data.(string) + "bar", nil - } - - f := ComposeDecodeHookFunc(f1, f2) - - result, err := DecodeHookExec( - f, reflect.TypeOf(""), reflect.TypeOf([]byte("")), "") - if err != nil { - t.Fatalf("bad: %s", err) - } - if result.(string) != "foobar" { - t.Fatalf("bad: %#v", result) - } -} - -func TestComposeDecodeHookFunc_err(t *testing.T) { - f1 := func(reflect.Kind, reflect.Kind, interface{}) (interface{}, error) { - return nil, errors.New("foo") - } - - f2 := func(reflect.Kind, reflect.Kind, interface{}) (interface{}, error) { - panic("NOPE") - } - - f := ComposeDecodeHookFunc(f1, f2) - - _, err := DecodeHookExec( - f, reflect.TypeOf(""), reflect.TypeOf([]byte("")), 42) - if err.Error() != "foo" { - t.Fatalf("bad: %s", err) - } -} - -func TestComposeDecodeHookFunc_kinds(t *testing.T) { - var f2From reflect.Kind - - f1 := func( - f reflect.Kind, - t reflect.Kind, - data interface{}) (interface{}, error) { - return int(42), nil - } - - f2 := func( - f reflect.Kind, - t reflect.Kind, - data interface{}) (interface{}, error) { - f2From = f - return data, nil - } - - f := ComposeDecodeHookFunc(f1, f2) - - _, err := DecodeHookExec( - f, reflect.TypeOf(""), reflect.TypeOf([]byte("")), "") - if err != nil { - t.Fatalf("bad: %s", err) - } - if f2From != reflect.Int { - t.Fatalf("bad: %#v", f2From) - } -} - -func TestStringToSliceHookFunc(t *testing.T) { - f := StringToSliceHookFunc(",") - - strType := reflect.TypeOf("") - sliceType := reflect.TypeOf([]byte("")) - cases := []struct { - f, t reflect.Type - data interface{} - result interface{} - err bool - }{ - {sliceType, sliceType, 42, 42, false}, - {strType, strType, 42, 42, false}, - { - strType, - sliceType, - "foo,bar,baz", - []string{"foo", "bar", "baz"}, - false, - }, - { - strType, - sliceType, - "", - []string{}, - false, - }, - } - - for i, tc := range cases { - actual, err := DecodeHookExec(f, tc.f, tc.t, tc.data) - if tc.err != (err != nil) { - t.Fatalf("case %d: expected err %#v", i, tc.err) - } - if !reflect.DeepEqual(actual, tc.result) { - t.Fatalf( - "case %d: expected %#v, got %#v", - i, tc.result, actual) - } - } -} - -func TestStringToTimeDurationHookFunc(t *testing.T) { - f := StringToTimeDurationHookFunc() - - strType := reflect.TypeOf("") - timeType := reflect.TypeOf(time.Duration(5)) - cases := []struct { - f, t reflect.Type - data interface{} - result interface{} - err bool - }{ - {strType, timeType, "5s", 5 * time.Second, false}, - {strType, timeType, "5", time.Duration(0), true}, - {strType, strType, "5", "5", false}, - } - - for i, tc := range cases { - actual, err := DecodeHookExec(f, tc.f, tc.t, tc.data) - if tc.err != (err != nil) { - t.Fatalf("case %d: expected err %#v", i, tc.err) - } - if !reflect.DeepEqual(actual, tc.result) { - t.Fatalf( - "case %d: expected %#v, got %#v", - i, tc.result, actual) - } - } -} - -func TestWeaklyTypedHook(t *testing.T) { - var f DecodeHookFunc = WeaklyTypedHook - - boolType := reflect.TypeOf(true) - strType := reflect.TypeOf("") - sliceType := reflect.TypeOf([]byte("")) - cases := []struct { - f, t reflect.Type - data interface{} - result interface{} - err bool - }{ - // TO STRING - { - boolType, - strType, - false, - "0", - false, - }, - - { - boolType, - strType, - true, - "1", - false, - }, - - { - reflect.TypeOf(float32(1)), - strType, - float32(7), - "7", - false, - }, - - { - reflect.TypeOf(int(1)), - strType, - int(7), - "7", - false, - }, - - { - sliceType, - strType, - []uint8("foo"), - "foo", - false, - }, - - { - reflect.TypeOf(uint(1)), - strType, - uint(7), - "7", - false, - }, - } - - for i, tc := range cases { - actual, err := DecodeHookExec(f, tc.f, tc.t, tc.data) - if tc.err != (err != nil) { - t.Fatalf("case %d: expected err %#v", i, tc.err) - } - if !reflect.DeepEqual(actual, tc.result) { - t.Fatalf( - "case %d: expected %#v, got %#v", - i, tc.result, actual) - } - } -} diff --git a/Godeps/_workspace/src/github.com/mitchellh/mapstructure/mapstructure_benchmark_test.go b/Godeps/_workspace/src/github.com/mitchellh/mapstructure/mapstructure_benchmark_test.go deleted file mode 100644 index 41d2a41f7..000000000 --- a/Godeps/_workspace/src/github.com/mitchellh/mapstructure/mapstructure_benchmark_test.go +++ /dev/null @@ -1,279 +0,0 @@ -package mapstructure - -import ( - "encoding/json" - "testing" -) - -func Benchmark_Decode(b *testing.B) { - type Person struct { - Name string - Age int - Emails []string - Extra map[string]string - } - - input := map[string]interface{}{ - "name": "Mitchell", - "age": 91, - "emails": []string{"one", "two", "three"}, - "extra": map[string]string{ - "twitter": "mitchellh", - }, - } - - var result Person - for i := 0; i < b.N; i++ { - Decode(input, &result) - } -} - -// decodeViaJSON takes the map data and passes it through encoding/json to convert it into the -// given Go native structure pointed to by v. v must be a pointer to a struct. -func decodeViaJSON(data interface{}, v interface{}) error { - // Perform the task by simply marshalling the input into JSON, - // then unmarshalling it into target native Go struct. - b, err := json.Marshal(data) - if err != nil { - return err - } - return json.Unmarshal(b, v) -} - -func Benchmark_DecodeViaJSON(b *testing.B) { - type Person struct { - Name string - Age int - Emails []string - Extra map[string]string - } - - input := map[string]interface{}{ - "name": "Mitchell", - "age": 91, - "emails": []string{"one", "two", "three"}, - "extra": map[string]string{ - "twitter": "mitchellh", - }, - } - - var result Person - for i := 0; i < b.N; i++ { - decodeViaJSON(input, &result) - } -} - -func Benchmark_DecodeBasic(b *testing.B) { - input := map[string]interface{}{ - "vstring": "foo", - "vint": 42, - "Vuint": 42, - "vbool": true, - "Vfloat": 42.42, - "vsilent": true, - "vdata": 42, - } - - var result Basic - for i := 0; i < b.N; i++ { - Decode(input, &result) - } -} - -func Benchmark_DecodeEmbedded(b *testing.B) { - input := map[string]interface{}{ - "vstring": "foo", - "Basic": map[string]interface{}{ - "vstring": "innerfoo", - }, - "vunique": "bar", - } - - var result Embedded - for i := 0; i < b.N; i++ { - Decode(input, &result) - } -} - -func Benchmark_DecodeTypeConversion(b *testing.B) { - input := map[string]interface{}{ - "IntToFloat": 42, - "IntToUint": 42, - "IntToBool": 1, - "IntToString": 42, - "UintToInt": 42, - "UintToFloat": 42, - "UintToBool": 42, - "UintToString": 42, - "BoolToInt": true, - "BoolToUint": true, - "BoolToFloat": true, - "BoolToString": true, - "FloatToInt": 42.42, - "FloatToUint": 42.42, - "FloatToBool": 42.42, - "FloatToString": 42.42, - "StringToInt": "42", - "StringToUint": "42", - "StringToBool": "1", - "StringToFloat": "42.42", - "SliceToMap": []interface{}{}, - "MapToSlice": map[string]interface{}{}, - } - - var resultStrict TypeConversionResult - for i := 0; i < b.N; i++ { - Decode(input, &resultStrict) - } -} - -func Benchmark_DecodeMap(b *testing.B) { - input := map[string]interface{}{ - "vfoo": "foo", - "vother": map[interface{}]interface{}{ - "foo": "foo", - "bar": "bar", - }, - } - - var result Map - for i := 0; i < b.N; i++ { - Decode(input, &result) - } -} - -func Benchmark_DecodeMapOfStruct(b *testing.B) { - input := map[string]interface{}{ - "value": map[string]interface{}{ - "foo": map[string]string{"vstring": "one"}, - "bar": map[string]string{"vstring": "two"}, - }, - } - - var result MapOfStruct - for i := 0; i < b.N; i++ { - Decode(input, &result) - } -} - -func Benchmark_DecodeSlice(b *testing.B) { - input := map[string]interface{}{ - "vfoo": "foo", - "vbar": []string{"foo", "bar", "baz"}, - } - - var result Slice - for i := 0; i < b.N; i++ { - Decode(input, &result) - } -} - -func Benchmark_DecodeSliceOfStruct(b *testing.B) { - input := map[string]interface{}{ - "value": []map[string]interface{}{ - {"vstring": "one"}, - {"vstring": "two"}, - }, - } - - var result SliceOfStruct - for i := 0; i < b.N; i++ { - Decode(input, &result) - } -} - -func Benchmark_DecodeWeaklyTypedInput(b *testing.B) { - type Person struct { - Name string - Age int - Emails []string - } - - // This input can come from anywhere, but typically comes from - // something like decoding JSON, generated by a weakly typed language - // such as PHP. - input := map[string]interface{}{ - "name": 123, // number => string - "age": "42", // string => number - "emails": map[string]interface{}{}, // empty map => empty array - } - - var result Person - config := &DecoderConfig{ - WeaklyTypedInput: true, - Result: &result, - } - - decoder, err := NewDecoder(config) - if err != nil { - panic(err) - } - - for i := 0; i < b.N; i++ { - decoder.Decode(input) - } -} - -func Benchmark_DecodeMetadata(b *testing.B) { - type Person struct { - Name string - Age int - } - - input := map[string]interface{}{ - "name": "Mitchell", - "age": 91, - "email": "foo@bar.com", - } - - var md Metadata - var result Person - config := &DecoderConfig{ - Metadata: &md, - Result: &result, - } - - decoder, err := NewDecoder(config) - if err != nil { - panic(err) - } - - for i := 0; i < b.N; i++ { - decoder.Decode(input) - } -} - -func Benchmark_DecodeMetadataEmbedded(b *testing.B) { - input := map[string]interface{}{ - "vstring": "foo", - "vunique": "bar", - } - - var md Metadata - var result EmbeddedSquash - config := &DecoderConfig{ - Metadata: &md, - Result: &result, - } - - decoder, err := NewDecoder(config) - if err != nil { - b.Fatalf("err: %s", err) - } - - for i := 0; i < b.N; i++ { - decoder.Decode(input) - } -} - -func Benchmark_DecodeTagged(b *testing.B) { - input := map[string]interface{}{ - "foo": "bar", - "bar": "value", - } - - var result Tagged - for i := 0; i < b.N; i++ { - Decode(input, &result) - } -} diff --git a/Godeps/_workspace/src/github.com/mitchellh/mapstructure/mapstructure_bugs_test.go b/Godeps/_workspace/src/github.com/mitchellh/mapstructure/mapstructure_bugs_test.go deleted file mode 100644 index 7054f1ac9..000000000 --- a/Godeps/_workspace/src/github.com/mitchellh/mapstructure/mapstructure_bugs_test.go +++ /dev/null @@ -1,47 +0,0 @@ -package mapstructure - -import "testing" - -// GH-1 -func TestDecode_NilValue(t *testing.T) { - input := map[string]interface{}{ - "vfoo": nil, - "vother": nil, - } - - var result Map - err := Decode(input, &result) - if err != nil { - t.Fatalf("should not error: %s", err) - } - - if result.Vfoo != "" { - t.Fatalf("value should be default: %s", result.Vfoo) - } - - if result.Vother != nil { - t.Fatalf("Vother should be nil: %s", result.Vother) - } -} - -// GH-10 -func TestDecode_mapInterfaceInterface(t *testing.T) { - input := map[interface{}]interface{}{ - "vfoo": nil, - "vother": nil, - } - - var result Map - err := Decode(input, &result) - if err != nil { - t.Fatalf("should not error: %s", err) - } - - if result.Vfoo != "" { - t.Fatalf("value should be default: %s", result.Vfoo) - } - - if result.Vother != nil { - t.Fatalf("Vother should be nil: %s", result.Vother) - } -} diff --git a/Godeps/_workspace/src/github.com/mitchellh/mapstructure/mapstructure_examples_test.go b/Godeps/_workspace/src/github.com/mitchellh/mapstructure/mapstructure_examples_test.go deleted file mode 100644 index f17c214a8..000000000 --- a/Godeps/_workspace/src/github.com/mitchellh/mapstructure/mapstructure_examples_test.go +++ /dev/null @@ -1,203 +0,0 @@ -package mapstructure - -import ( - "fmt" -) - -func ExampleDecode() { - type Person struct { - Name string - Age int - Emails []string - Extra map[string]string - } - - // This input can come from anywhere, but typically comes from - // something like decoding JSON where we're not quite sure of the - // struct initially. - input := map[string]interface{}{ - "name": "Mitchell", - "age": 91, - "emails": []string{"one", "two", "three"}, - "extra": map[string]string{ - "twitter": "mitchellh", - }, - } - - var result Person - err := Decode(input, &result) - if err != nil { - panic(err) - } - - fmt.Printf("%#v", result) - // Output: - // mapstructure.Person{Name:"Mitchell", Age:91, Emails:[]string{"one", "two", "three"}, Extra:map[string]string{"twitter":"mitchellh"}} -} - -func ExampleDecode_errors() { - type Person struct { - Name string - Age int - Emails []string - Extra map[string]string - } - - // This input can come from anywhere, but typically comes from - // something like decoding JSON where we're not quite sure of the - // struct initially. - input := map[string]interface{}{ - "name": 123, - "age": "bad value", - "emails": []int{1, 2, 3}, - } - - var result Person - err := Decode(input, &result) - if err == nil { - panic("should have an error") - } - - fmt.Println(err.Error()) - // Output: - // 5 error(s) decoding: - // - // * 'Age' expected type 'int', got unconvertible type 'string' - // * 'Emails[0]' expected type 'string', got unconvertible type 'int' - // * 'Emails[1]' expected type 'string', got unconvertible type 'int' - // * 'Emails[2]' expected type 'string', got unconvertible type 'int' - // * 'Name' expected type 'string', got unconvertible type 'int' -} - -func ExampleDecode_metadata() { - type Person struct { - Name string - Age int - } - - // This input can come from anywhere, but typically comes from - // something like decoding JSON where we're not quite sure of the - // struct initially. - input := map[string]interface{}{ - "name": "Mitchell", - "age": 91, - "email": "foo@bar.com", - } - - // For metadata, we make a more advanced DecoderConfig so we can - // more finely configure the decoder that is used. In this case, we - // just tell the decoder we want to track metadata. - var md Metadata - var result Person - config := &DecoderConfig{ - Metadata: &md, - Result: &result, - } - - decoder, err := NewDecoder(config) - if err != nil { - panic(err) - } - - if err := decoder.Decode(input); err != nil { - panic(err) - } - - fmt.Printf("Unused keys: %#v", md.Unused) - // Output: - // Unused keys: []string{"email"} -} - -func ExampleDecode_weaklyTypedInput() { - type Person struct { - Name string - Age int - Emails []string - } - - // This input can come from anywhere, but typically comes from - // something like decoding JSON, generated by a weakly typed language - // such as PHP. - input := map[string]interface{}{ - "name": 123, // number => string - "age": "42", // string => number - "emails": map[string]interface{}{}, // empty map => empty array - } - - var result Person - config := &DecoderConfig{ - WeaklyTypedInput: true, - Result: &result, - } - - decoder, err := NewDecoder(config) - if err != nil { - panic(err) - } - - err = decoder.Decode(input) - if err != nil { - panic(err) - } - - fmt.Printf("%#v", result) - // Output: mapstructure.Person{Name:"123", Age:42, Emails:[]string{}} -} - -func ExampleDecode_tags() { - // Note that the mapstructure tags defined in the struct type - // can indicate which fields the values are mapped to. - type Person struct { - Name string `mapstructure:"person_name"` - Age int `mapstructure:"person_age"` - } - - input := map[string]interface{}{ - "person_name": "Mitchell", - "person_age": 91, - } - - var result Person - err := Decode(input, &result) - if err != nil { - panic(err) - } - - fmt.Printf("%#v", result) - // Output: - // mapstructure.Person{Name:"Mitchell", Age:91} -} - -func ExampleDecode_embeddedStruct() { - // Squashing multiple embedded structs is allowed using the squash tag. - // This is demonstrated by creating a composite struct of multiple types - // and decoding into it. In this case, a person can carry with it both - // a Family and a Location, as well as their own FirstName. - type Family struct { - LastName string - } - type Location struct { - City string - } - type Person struct { - Family `mapstructure:",squash"` - Location `mapstructure:",squash"` - FirstName string - } - - input := map[string]interface{}{ - "FirstName": "Mitchell", - "LastName": "Hashimoto", - "City": "San Francisco", - } - - var result Person - err := Decode(input, &result) - if err != nil { - panic(err) - } - - fmt.Printf("%s %s, %s", result.FirstName, result.LastName, result.City) - // Output: - // Mitchell Hashimoto, San Francisco -} diff --git a/Godeps/_workspace/src/github.com/mitchellh/mapstructure/mapstructure_test.go b/Godeps/_workspace/src/github.com/mitchellh/mapstructure/mapstructure_test.go deleted file mode 100644 index 8a27647b5..000000000 --- a/Godeps/_workspace/src/github.com/mitchellh/mapstructure/mapstructure_test.go +++ /dev/null @@ -1,999 +0,0 @@ -package mapstructure - -import ( - "reflect" - "sort" - "testing" -) - -type Basic struct { - Vstring string - Vint int - Vuint uint - Vbool bool - Vfloat float64 - Vextra string - vsilent bool - Vdata interface{} -} - -type BasicSquash struct { - Test Basic `mapstructure:",squash"` -} - -type Embedded struct { - Basic - Vunique string -} - -type EmbeddedPointer struct { - *Basic - Vunique string -} - -type EmbeddedSquash struct { - Basic `mapstructure:",squash"` - Vunique string -} - -type Map struct { - Vfoo string - Vother map[string]string -} - -type MapOfStruct struct { - Value map[string]Basic -} - -type Nested struct { - Vfoo string - Vbar Basic -} - -type NestedPointer struct { - Vfoo string - Vbar *Basic -} - -type Slice struct { - Vfoo string - Vbar []string -} - -type SliceOfStruct struct { - Value []Basic -} - -type Tagged struct { - Extra string `mapstructure:"bar,what,what"` - Value string `mapstructure:"foo"` -} - -type TypeConversionResult struct { - IntToFloat float32 - IntToUint uint - IntToBool bool - IntToString string - UintToInt int - UintToFloat float32 - UintToBool bool - UintToString string - BoolToInt int - BoolToUint uint - BoolToFloat float32 - BoolToString string - FloatToInt int - FloatToUint uint - FloatToBool bool - FloatToString string - SliceUint8ToString string - StringToInt int - StringToUint uint - StringToBool bool - StringToFloat float32 - SliceToMap map[string]interface{} - MapToSlice []interface{} -} - -func TestBasicTypes(t *testing.T) { - t.Parallel() - - input := map[string]interface{}{ - "vstring": "foo", - "vint": 42, - "Vuint": 42, - "vbool": true, - "Vfloat": 42.42, - "vsilent": true, - "vdata": 42, - } - - var result Basic - err := Decode(input, &result) - if err != nil { - t.Errorf("got an err: %s", err.Error()) - t.FailNow() - } - - if result.Vstring != "foo" { - t.Errorf("vstring value should be 'foo': %#v", result.Vstring) - } - - if result.Vint != 42 { - t.Errorf("vint value should be 42: %#v", result.Vint) - } - - if result.Vuint != 42 { - t.Errorf("vuint value should be 42: %#v", result.Vuint) - } - - if result.Vbool != true { - t.Errorf("vbool value should be true: %#v", result.Vbool) - } - - if result.Vfloat != 42.42 { - t.Errorf("vfloat value should be 42.42: %#v", result.Vfloat) - } - - if result.Vextra != "" { - t.Errorf("vextra value should be empty: %#v", result.Vextra) - } - - if result.vsilent != false { - t.Error("vsilent should not be set, it is unexported") - } - - if result.Vdata != 42 { - t.Error("vdata should be valid") - } -} - -func TestBasic_IntWithFloat(t *testing.T) { - t.Parallel() - - input := map[string]interface{}{ - "vint": float64(42), - } - - var result Basic - err := Decode(input, &result) - if err != nil { - t.Fatalf("got an err: %s", err) - } -} - -func TestBasic_Merge(t *testing.T) { - t.Parallel() - - input := map[string]interface{}{ - "vint": 42, - } - - var result Basic - result.Vuint = 100 - err := Decode(input, &result) - if err != nil { - t.Fatalf("got an err: %s", err) - } - - expected := Basic{ - Vint: 42, - Vuint: 100, - } - if !reflect.DeepEqual(result, expected) { - t.Fatalf("bad: %#v", result) - } -} - -func TestDecode_BasicSquash(t *testing.T) { - t.Parallel() - - input := map[string]interface{}{ - "vstring": "foo", - } - - var result BasicSquash - err := Decode(input, &result) - if err != nil { - t.Fatalf("got an err: %s", err.Error()) - } - - if result.Test.Vstring != "foo" { - t.Errorf("vstring value should be 'foo': %#v", result.Test.Vstring) - } -} - -func TestDecode_Embedded(t *testing.T) { - t.Parallel() - - input := map[string]interface{}{ - "vstring": "foo", - "Basic": map[string]interface{}{ - "vstring": "innerfoo", - }, - "vunique": "bar", - } - - var result Embedded - err := Decode(input, &result) - if err != nil { - t.Fatalf("got an err: %s", err.Error()) - } - - if result.Vstring != "innerfoo" { - t.Errorf("vstring value should be 'innerfoo': %#v", result.Vstring) - } - - if result.Vunique != "bar" { - t.Errorf("vunique value should be 'bar': %#v", result.Vunique) - } -} - -func TestDecode_EmbeddedPointer(t *testing.T) { - t.Parallel() - - input := map[string]interface{}{ - "vstring": "foo", - "Basic": map[string]interface{}{ - "vstring": "innerfoo", - }, - "vunique": "bar", - } - - var result EmbeddedPointer - err := Decode(input, &result) - if err == nil { - t.Fatal("should get error") - } -} - -func TestDecode_EmbeddedSquash(t *testing.T) { - t.Parallel() - - input := map[string]interface{}{ - "vstring": "foo", - "vunique": "bar", - } - - var result EmbeddedSquash - err := Decode(input, &result) - if err != nil { - t.Fatalf("got an err: %s", err.Error()) - } - - if result.Vstring != "foo" { - t.Errorf("vstring value should be 'foo': %#v", result.Vstring) - } - - if result.Vunique != "bar" { - t.Errorf("vunique value should be 'bar': %#v", result.Vunique) - } -} - -func TestDecode_DecodeHook(t *testing.T) { - t.Parallel() - - input := map[string]interface{}{ - "vint": "WHAT", - } - - decodeHook := func(from reflect.Kind, to reflect.Kind, v interface{}) (interface{}, error) { - if from == reflect.String && to != reflect.String { - return 5, nil - } - - return v, nil - } - - var result Basic - config := &DecoderConfig{ - DecodeHook: decodeHook, - Result: &result, - } - - decoder, err := NewDecoder(config) - if err != nil { - t.Fatalf("err: %s", err) - } - - err = decoder.Decode(input) - if err != nil { - t.Fatalf("got an err: %s", err) - } - - if result.Vint != 5 { - t.Errorf("vint should be 5: %#v", result.Vint) - } -} - -func TestDecode_DecodeHookType(t *testing.T) { - t.Parallel() - - input := map[string]interface{}{ - "vint": "WHAT", - } - - decodeHook := func(from reflect.Type, to reflect.Type, v interface{}) (interface{}, error) { - if from.Kind() == reflect.String && - to.Kind() != reflect.String { - return 5, nil - } - - return v, nil - } - - var result Basic - config := &DecoderConfig{ - DecodeHook: decodeHook, - Result: &result, - } - - decoder, err := NewDecoder(config) - if err != nil { - t.Fatalf("err: %s", err) - } - - err = decoder.Decode(input) - if err != nil { - t.Fatalf("got an err: %s", err) - } - - if result.Vint != 5 { - t.Errorf("vint should be 5: %#v", result.Vint) - } -} - -func TestDecode_Nil(t *testing.T) { - t.Parallel() - - var input interface{} = nil - result := Basic{ - Vstring: "foo", - } - - err := Decode(input, &result) - if err != nil { - t.Fatalf("err: %s", err) - } - - if result.Vstring != "foo" { - t.Fatalf("bad: %#v", result.Vstring) - } -} - -func TestDecode_NonStruct(t *testing.T) { - t.Parallel() - - input := map[string]interface{}{ - "foo": "bar", - "bar": "baz", - } - - var result map[string]string - err := Decode(input, &result) - if err != nil { - t.Fatalf("err: %s", err) - } - - if result["foo"] != "bar" { - t.Fatal("foo is not bar") - } -} - -func TestDecode_StructMatch(t *testing.T) { - t.Parallel() - - input := map[string]interface{}{ - "vbar": Basic{ - Vstring: "foo", - }, - } - - var result Nested - err := Decode(input, &result) - if err != nil { - t.Fatalf("got an err: %s", err.Error()) - } - - if result.Vbar.Vstring != "foo" { - t.Errorf("bad: %#v", result) - } -} - -func TestDecode_TypeConversion(t *testing.T) { - input := map[string]interface{}{ - "IntToFloat": 42, - "IntToUint": 42, - "IntToBool": 1, - "IntToString": 42, - "UintToInt": 42, - "UintToFloat": 42, - "UintToBool": 42, - "UintToString": 42, - "BoolToInt": true, - "BoolToUint": true, - "BoolToFloat": true, - "BoolToString": true, - "FloatToInt": 42.42, - "FloatToUint": 42.42, - "FloatToBool": 42.42, - "FloatToString": 42.42, - "SliceUint8ToString": []uint8("foo"), - "StringToInt": "42", - "StringToUint": "42", - "StringToBool": "1", - "StringToFloat": "42.42", - "SliceToMap": []interface{}{}, - "MapToSlice": map[string]interface{}{}, - } - - expectedResultStrict := TypeConversionResult{ - IntToFloat: 42.0, - IntToUint: 42, - UintToInt: 42, - UintToFloat: 42, - BoolToInt: 0, - BoolToUint: 0, - BoolToFloat: 0, - FloatToInt: 42, - FloatToUint: 42, - } - - expectedResultWeak := TypeConversionResult{ - IntToFloat: 42.0, - IntToUint: 42, - IntToBool: true, - IntToString: "42", - UintToInt: 42, - UintToFloat: 42, - UintToBool: true, - UintToString: "42", - BoolToInt: 1, - BoolToUint: 1, - BoolToFloat: 1, - BoolToString: "1", - FloatToInt: 42, - FloatToUint: 42, - FloatToBool: true, - FloatToString: "42.42", - SliceUint8ToString: "foo", - StringToInt: 42, - StringToUint: 42, - StringToBool: true, - StringToFloat: 42.42, - SliceToMap: map[string]interface{}{}, - MapToSlice: []interface{}{}, - } - - // Test strict type conversion - var resultStrict TypeConversionResult - err := Decode(input, &resultStrict) - if err == nil { - t.Errorf("should return an error") - } - if !reflect.DeepEqual(resultStrict, expectedResultStrict) { - t.Errorf("expected %v, got: %v", expectedResultStrict, resultStrict) - } - - // Test weak type conversion - var decoder *Decoder - var resultWeak TypeConversionResult - - config := &DecoderConfig{ - WeaklyTypedInput: true, - Result: &resultWeak, - } - - decoder, err = NewDecoder(config) - if err != nil { - t.Fatalf("err: %s", err) - } - - err = decoder.Decode(input) - if err != nil { - t.Fatalf("got an err: %s", err) - } - - if !reflect.DeepEqual(resultWeak, expectedResultWeak) { - t.Errorf("expected \n%#v, got: \n%#v", expectedResultWeak, resultWeak) - } -} - -func TestDecoder_ErrorUnused(t *testing.T) { - t.Parallel() - - input := map[string]interface{}{ - "vstring": "hello", - "foo": "bar", - } - - var result Basic - config := &DecoderConfig{ - ErrorUnused: true, - Result: &result, - } - - decoder, err := NewDecoder(config) - if err != nil { - t.Fatalf("err: %s", err) - } - - err = decoder.Decode(input) - if err == nil { - t.Fatal("expected error") - } -} - -func TestMap(t *testing.T) { - t.Parallel() - - input := map[string]interface{}{ - "vfoo": "foo", - "vother": map[interface{}]interface{}{ - "foo": "foo", - "bar": "bar", - }, - } - - var result Map - err := Decode(input, &result) - if err != nil { - t.Fatalf("got an error: %s", err) - } - - if result.Vfoo != "foo" { - t.Errorf("vfoo value should be 'foo': %#v", result.Vfoo) - } - - if result.Vother == nil { - t.Fatal("vother should not be nil") - } - - if len(result.Vother) != 2 { - t.Error("vother should have two items") - } - - if result.Vother["foo"] != "foo" { - t.Errorf("'foo' key should be foo, got: %#v", result.Vother["foo"]) - } - - if result.Vother["bar"] != "bar" { - t.Errorf("'bar' key should be bar, got: %#v", result.Vother["bar"]) - } -} - -func TestMapMerge(t *testing.T) { - t.Parallel() - - input := map[string]interface{}{ - "vfoo": "foo", - "vother": map[interface{}]interface{}{ - "foo": "foo", - "bar": "bar", - }, - } - - var result Map - result.Vother = map[string]string{"hello": "world"} - err := Decode(input, &result) - if err != nil { - t.Fatalf("got an error: %s", err) - } - - if result.Vfoo != "foo" { - t.Errorf("vfoo value should be 'foo': %#v", result.Vfoo) - } - - expected := map[string]string{ - "foo": "foo", - "bar": "bar", - "hello": "world", - } - if !reflect.DeepEqual(result.Vother, expected) { - t.Errorf("bad: %#v", result.Vother) - } -} - -func TestMapOfStruct(t *testing.T) { - t.Parallel() - - input := map[string]interface{}{ - "value": map[string]interface{}{ - "foo": map[string]string{"vstring": "one"}, - "bar": map[string]string{"vstring": "two"}, - }, - } - - var result MapOfStruct - err := Decode(input, &result) - if err != nil { - t.Fatalf("got an err: %s", err) - } - - if result.Value == nil { - t.Fatal("value should not be nil") - } - - if len(result.Value) != 2 { - t.Error("value should have two items") - } - - if result.Value["foo"].Vstring != "one" { - t.Errorf("foo value should be 'one', got: %s", result.Value["foo"].Vstring) - } - - if result.Value["bar"].Vstring != "two" { - t.Errorf("bar value should be 'two', got: %s", result.Value["bar"].Vstring) - } -} - -func TestNestedType(t *testing.T) { - t.Parallel() - - input := map[string]interface{}{ - "vfoo": "foo", - "vbar": map[string]interface{}{ - "vstring": "foo", - "vint": 42, - "vbool": true, - }, - } - - var result Nested - err := Decode(input, &result) - if err != nil { - t.Fatalf("got an err: %s", err.Error()) - } - - if result.Vfoo != "foo" { - t.Errorf("vfoo value should be 'foo': %#v", result.Vfoo) - } - - if result.Vbar.Vstring != "foo" { - t.Errorf("vstring value should be 'foo': %#v", result.Vbar.Vstring) - } - - if result.Vbar.Vint != 42 { - t.Errorf("vint value should be 42: %#v", result.Vbar.Vint) - } - - if result.Vbar.Vbool != true { - t.Errorf("vbool value should be true: %#v", result.Vbar.Vbool) - } - - if result.Vbar.Vextra != "" { - t.Errorf("vextra value should be empty: %#v", result.Vbar.Vextra) - } -} - -func TestNestedTypePointer(t *testing.T) { - t.Parallel() - - input := map[string]interface{}{ - "vfoo": "foo", - "vbar": &map[string]interface{}{ - "vstring": "foo", - "vint": 42, - "vbool": true, - }, - } - - var result NestedPointer - err := Decode(input, &result) - if err != nil { - t.Fatalf("got an err: %s", err.Error()) - } - - if result.Vfoo != "foo" { - t.Errorf("vfoo value should be 'foo': %#v", result.Vfoo) - } - - if result.Vbar.Vstring != "foo" { - t.Errorf("vstring value should be 'foo': %#v", result.Vbar.Vstring) - } - - if result.Vbar.Vint != 42 { - t.Errorf("vint value should be 42: %#v", result.Vbar.Vint) - } - - if result.Vbar.Vbool != true { - t.Errorf("vbool value should be true: %#v", result.Vbar.Vbool) - } - - if result.Vbar.Vextra != "" { - t.Errorf("vextra value should be empty: %#v", result.Vbar.Vextra) - } -} - -func TestSlice(t *testing.T) { - t.Parallel() - - inputStringSlice := map[string]interface{}{ - "vfoo": "foo", - "vbar": []string{"foo", "bar", "baz"}, - } - - inputStringSlicePointer := map[string]interface{}{ - "vfoo": "foo", - "vbar": &[]string{"foo", "bar", "baz"}, - } - - outputStringSlice := &Slice{ - "foo", - []string{"foo", "bar", "baz"}, - } - - testSliceInput(t, inputStringSlice, outputStringSlice) - testSliceInput(t, inputStringSlicePointer, outputStringSlice) -} - -func TestInvalidSlice(t *testing.T) { - t.Parallel() - - input := map[string]interface{}{ - "vfoo": "foo", - "vbar": 42, - } - - result := Slice{} - err := Decode(input, &result) - if err == nil { - t.Errorf("expected failure") - } -} - -func TestSliceOfStruct(t *testing.T) { - t.Parallel() - - input := map[string]interface{}{ - "value": []map[string]interface{}{ - {"vstring": "one"}, - {"vstring": "two"}, - }, - } - - var result SliceOfStruct - err := Decode(input, &result) - if err != nil { - t.Fatalf("got unexpected error: %s", err) - } - - if len(result.Value) != 2 { - t.Fatalf("expected two values, got %d", len(result.Value)) - } - - if result.Value[0].Vstring != "one" { - t.Errorf("first value should be 'one', got: %s", result.Value[0].Vstring) - } - - if result.Value[1].Vstring != "two" { - t.Errorf("second value should be 'two', got: %s", result.Value[1].Vstring) - } -} - -func TestInvalidType(t *testing.T) { - t.Parallel() - - input := map[string]interface{}{ - "vstring": 42, - } - - var result Basic - err := Decode(input, &result) - if err == nil { - t.Fatal("error should exist") - } - - derr, ok := err.(*Error) - if !ok { - t.Fatalf("error should be kind of Error, instead: %#v", err) - } - - if derr.Errors[0] != "'Vstring' expected type 'string', got unconvertible type 'int'" { - t.Errorf("got unexpected error: %s", err) - } - - inputNegIntUint := map[string]interface{}{ - "vuint": -42, - } - - err = Decode(inputNegIntUint, &result) - if err == nil { - t.Fatal("error should exist") - } - - derr, ok = err.(*Error) - if !ok { - t.Fatalf("error should be kind of Error, instead: %#v", err) - } - - if derr.Errors[0] != "cannot parse 'Vuint', -42 overflows uint" { - t.Errorf("got unexpected error: %s", err) - } - - inputNegFloatUint := map[string]interface{}{ - "vuint": -42.0, - } - - err = Decode(inputNegFloatUint, &result) - if err == nil { - t.Fatal("error should exist") - } - - derr, ok = err.(*Error) - if !ok { - t.Fatalf("error should be kind of Error, instead: %#v", err) - } - - if derr.Errors[0] != "cannot parse 'Vuint', -42.000000 overflows uint" { - t.Errorf("got unexpected error: %s", err) - } -} - -func TestMetadata(t *testing.T) { - t.Parallel() - - input := map[string]interface{}{ - "vfoo": "foo", - "vbar": map[string]interface{}{ - "vstring": "foo", - "Vuint": 42, - "foo": "bar", - }, - "bar": "nil", - } - - var md Metadata - var result Nested - config := &DecoderConfig{ - Metadata: &md, - Result: &result, - } - - decoder, err := NewDecoder(config) - if err != nil { - t.Fatalf("err: %s", err) - } - - err = decoder.Decode(input) - if err != nil { - t.Fatalf("err: %s", err.Error()) - } - - expectedKeys := []string{"Vbar", "Vbar.Vstring", "Vbar.Vuint", "Vfoo"} - sort.Strings(md.Keys) - if !reflect.DeepEqual(md.Keys, expectedKeys) { - t.Fatalf("bad keys: %#v", md.Keys) - } - - expectedUnused := []string{"Vbar.foo", "bar"} - if !reflect.DeepEqual(md.Unused, expectedUnused) { - t.Fatalf("bad unused: %#v", md.Unused) - } -} - -func TestMetadata_Embedded(t *testing.T) { - t.Parallel() - - input := map[string]interface{}{ - "vstring": "foo", - "vunique": "bar", - } - - var md Metadata - var result EmbeddedSquash - config := &DecoderConfig{ - Metadata: &md, - Result: &result, - } - - decoder, err := NewDecoder(config) - if err != nil { - t.Fatalf("err: %s", err) - } - - err = decoder.Decode(input) - if err != nil { - t.Fatalf("err: %s", err.Error()) - } - - expectedKeys := []string{"Vstring", "Vunique"} - - sort.Strings(md.Keys) - if !reflect.DeepEqual(md.Keys, expectedKeys) { - t.Fatalf("bad keys: %#v", md.Keys) - } - - expectedUnused := []string{} - if !reflect.DeepEqual(md.Unused, expectedUnused) { - t.Fatalf("bad unused: %#v", md.Unused) - } -} - -func TestNonPtrValue(t *testing.T) { - t.Parallel() - - err := Decode(map[string]interface{}{}, Basic{}) - if err == nil { - t.Fatal("error should exist") - } - - if err.Error() != "result must be a pointer" { - t.Errorf("got unexpected error: %s", err) - } -} - -func TestTagged(t *testing.T) { - t.Parallel() - - input := map[string]interface{}{ - "foo": "bar", - "bar": "value", - } - - var result Tagged - err := Decode(input, &result) - if err != nil { - t.Fatalf("unexpected error: %s", err) - } - - if result.Value != "bar" { - t.Errorf("value should be 'bar', got: %#v", result.Value) - } - - if result.Extra != "value" { - t.Errorf("extra should be 'value', got: %#v", result.Extra) - } -} - -func TestWeakDecode(t *testing.T) { - t.Parallel() - - input := map[string]interface{}{ - "foo": "4", - "bar": "value", - } - - var result struct { - Foo int - Bar string - } - - if err := WeakDecode(input, &result); err != nil { - t.Fatalf("err: %s", err) - } - if result.Foo != 4 { - t.Fatalf("bad: %#v", result) - } - if result.Bar != "value" { - t.Fatalf("bad: %#v", result) - } -} - -func testSliceInput(t *testing.T, input map[string]interface{}, expected *Slice) { - var result Slice - err := Decode(input, &result) - if err != nil { - t.Fatalf("got error: %s", err) - } - - if result.Vfoo != expected.Vfoo { - t.Errorf("Vfoo expected '%s', got '%s'", expected.Vfoo, result.Vfoo) - } - - if result.Vbar == nil { - t.Fatalf("Vbar a slice, got '%#v'", result.Vbar) - } - - if len(result.Vbar) != len(expected.Vbar) { - t.Errorf("Vbar length should be %d, got %d", len(expected.Vbar), len(result.Vbar)) - } - - for i, v := range result.Vbar { - if v != expected.Vbar[i] { - t.Errorf( - "Vbar[%d] should be '%#v', got '%#v'", - i, expected.Vbar[i], v) - } - } -} diff --git a/Godeps/_workspace/src/github.com/mitchellh/reflectwalk/reflectwalk_test.go b/Godeps/_workspace/src/github.com/mitchellh/reflectwalk/reflectwalk_test.go deleted file mode 100644 index 4ec1066e7..000000000 --- a/Godeps/_workspace/src/github.com/mitchellh/reflectwalk/reflectwalk_test.go +++ /dev/null @@ -1,377 +0,0 @@ -package reflectwalk - -import ( - "reflect" - "testing" -) - -type TestEnterExitWalker struct { - Locs []Location -} - -func (t *TestEnterExitWalker) Enter(l Location) error { - if t.Locs == nil { - t.Locs = make([]Location, 0, 5) - } - - t.Locs = append(t.Locs, l) - return nil -} - -func (t *TestEnterExitWalker) Exit(l Location) error { - t.Locs = append(t.Locs, l) - return nil -} - -type TestPointerWalker struct { - Ps []bool -} - -func (t *TestPointerWalker) PointerEnter(v bool) error { - t.Ps = append(t.Ps, v) - return nil -} - -func (t *TestPointerWalker) PointerExit(v bool) error { - return nil -} - -type TestPrimitiveWalker struct { - Value reflect.Value -} - -func (t *TestPrimitiveWalker) Primitive(v reflect.Value) error { - t.Value = v - return nil -} - -type TestPrimitiveCountWalker struct { - Count int -} - -func (t *TestPrimitiveCountWalker) Primitive(v reflect.Value) error { - t.Count += 1 - return nil -} - -type TestPrimitiveReplaceWalker struct { - Value reflect.Value -} - -func (t *TestPrimitiveReplaceWalker) Primitive(v reflect.Value) error { - v.Set(reflect.ValueOf("bar")) - return nil -} - -type TestMapWalker struct { - MapVal reflect.Value - Keys []string - Values []string -} - -func (t *TestMapWalker) Map(m reflect.Value) error { - t.MapVal = m - return nil -} - -func (t *TestMapWalker) MapElem(m, k, v reflect.Value) error { - if t.Keys == nil { - t.Keys = make([]string, 0, 1) - t.Values = make([]string, 0, 1) - } - - t.Keys = append(t.Keys, k.Interface().(string)) - t.Values = append(t.Values, v.Interface().(string)) - return nil -} - -type TestSliceWalker struct { - Count int - SliceVal reflect.Value -} - -func (t *TestSliceWalker) Slice(v reflect.Value) error { - t.SliceVal = v - return nil -} - -func (t *TestSliceWalker) SliceElem(int, reflect.Value) error { - t.Count++ - return nil -} - -type TestStructWalker struct { - Fields []string -} - -func (t *TestStructWalker) Struct(v reflect.Value) error { - return nil -} - -func (t *TestStructWalker) StructField(sf reflect.StructField, v reflect.Value) error { - if t.Fields == nil { - t.Fields = make([]string, 0, 1) - } - - t.Fields = append(t.Fields, sf.Name) - return nil -} - -func TestTestStructs(t *testing.T) { - var raw interface{} - raw = new(TestEnterExitWalker) - if _, ok := raw.(EnterExitWalker); !ok { - t.Fatal("EnterExitWalker is bad") - } - - raw = new(TestPrimitiveWalker) - if _, ok := raw.(PrimitiveWalker); !ok { - t.Fatal("PrimitiveWalker is bad") - } - - raw = new(TestMapWalker) - if _, ok := raw.(MapWalker); !ok { - t.Fatal("MapWalker is bad") - } - - raw = new(TestSliceWalker) - if _, ok := raw.(SliceWalker); !ok { - t.Fatal("SliceWalker is bad") - } - - raw = new(TestStructWalker) - if _, ok := raw.(StructWalker); !ok { - t.Fatal("StructWalker is bad") - } -} - -func TestWalk_Basic(t *testing.T) { - w := new(TestPrimitiveWalker) - - type S struct { - Foo string - } - - data := &S{ - Foo: "foo", - } - - err := Walk(data, w) - if err != nil { - t.Fatalf("err: %s", err) - } - - if w.Value.Kind() != reflect.String { - t.Fatalf("bad: %#v", w.Value) - } -} - -func TestWalk_Basic_Replace(t *testing.T) { - w := new(TestPrimitiveReplaceWalker) - - type S struct { - Foo string - Bar []interface{} - } - - data := &S{ - Foo: "foo", - Bar: []interface{}{[]string{"what"}}, - } - - err := Walk(data, w) - if err != nil { - t.Fatalf("err: %s", err) - } - - if data.Foo != "bar" { - t.Fatalf("bad: %#v", data.Foo) - } - if data.Bar[0].([]string)[0] != "bar" { - t.Fatalf("bad: %#v", data.Bar) - } -} - -func TestWalk_EnterExit(t *testing.T) { - w := new(TestEnterExitWalker) - - type S struct { - A string - M map[string]string - } - - data := &S{ - A: "foo", - M: map[string]string{ - "a": "b", - }, - } - - err := Walk(data, w) - if err != nil { - t.Fatalf("err: %s", err) - } - - expected := []Location{ - WalkLoc, - Struct, - StructField, - StructField, - StructField, - Map, - MapKey, - MapKey, - MapValue, - MapValue, - Map, - StructField, - Struct, - WalkLoc, - } - if !reflect.DeepEqual(w.Locs, expected) { - t.Fatalf("Bad: %#v", w.Locs) - } -} - -func TestWalk_Interface(t *testing.T) { - w := new(TestPrimitiveCountWalker) - - type S struct { - Foo string - Bar []interface{} - } - - var data interface{} = &S{ - Foo: "foo", - Bar: []interface{}{[]string{"bar", "what"}, "baz"}, - } - - err := Walk(data, w) - if err != nil { - t.Fatalf("err: %s", err) - } - - if w.Count != 4 { - t.Fatalf("bad: %#v", w.Count) - } -} - -func TestWalk_Interface_nil(t *testing.T) { - w := new(TestPrimitiveCountWalker) - - type S struct { - Bar interface{} - } - - var data interface{} = &S{} - - err := Walk(data, w) - if err != nil { - t.Fatalf("err: %s", err) - } -} - -func TestWalk_Map(t *testing.T) { - w := new(TestMapWalker) - - type S struct { - Foo map[string]string - } - - data := &S{ - Foo: map[string]string{ - "foo": "foov", - "bar": "barv", - }, - } - - err := Walk(data, w) - if err != nil { - t.Fatalf("err: %s", err) - } - - if !reflect.DeepEqual(w.MapVal.Interface(), data.Foo) { - t.Fatalf("Bad: %#v", w.MapVal.Interface()) - } - - expectedK := []string{"foo", "bar"} - if !reflect.DeepEqual(w.Keys, expectedK) { - t.Fatalf("Bad keys: %#v", w.Keys) - } - - expectedV := []string{"foov", "barv"} - if !reflect.DeepEqual(w.Values, expectedV) { - t.Fatalf("Bad values: %#v", w.Values) - } -} - -func TestWalk_Pointer(t *testing.T) { - w := new(TestPointerWalker) - - type S struct { - Foo string - } - - data := &S{ - Foo: "foo", - } - - err := Walk(data, w) - if err != nil { - t.Fatalf("err: %s", err) - } - - expected := []bool{true, false} - if !reflect.DeepEqual(w.Ps, expected) { - t.Fatalf("bad: %#v", w.Ps) - } -} - -func TestWalk_Slice(t *testing.T) { - w := new(TestSliceWalker) - - type S struct { - Foo []string - } - - data := &S{ - Foo: []string{"a", "b", "c"}, - } - - err := Walk(data, w) - if err != nil { - t.Fatalf("err: %s", err) - } - - if !reflect.DeepEqual(w.SliceVal.Interface(), data.Foo) { - t.Fatalf("bad: %#v", w.SliceVal.Interface()) - } - - if w.Count != 3 { - t.Fatalf("Bad count: %d", w.Count) - } -} - -func TestWalk_Struct(t *testing.T) { - w := new(TestStructWalker) - - type S struct { - Foo string - Bar string - } - - data := &S{ - Foo: "foo", - Bar: "bar", - } - - err := Walk(data, w) - if err != nil { - t.Fatalf("err: %s", err) - } - - expected := []string{"Foo", "Bar"} - if !reflect.DeepEqual(w.Fields, expected) { - t.Fatalf("bad: %#v", w.Fields) - } -} diff --git a/Godeps/_workspace/src/github.com/ryanuber/columnize/README.md b/Godeps/_workspace/src/github.com/ryanuber/columnize/README.md index 99ced806a..6852911fc 100644 --- a/Godeps/_workspace/src/github.com/ryanuber/columnize/README.md +++ b/Godeps/_workspace/src/github.com/ryanuber/columnize/README.md @@ -54,11 +54,13 @@ config := columnize.DefaultConfig() config.Delim = "|" config.Glue = " " config.Prefix = "" +config.Empty = "" ``` * `Delim` is the string by which columns of **input** are delimited * `Glue` is the string by which columns of **output** are delimited * `Prefix` is a string by which each line of **output** is prefixed +* `Empty` is a string used to replace blank values found in output You can then pass the `Config` in using the `Format` method (signature below) to have text formatted to your liking. diff --git a/Godeps/_workspace/src/github.com/ryanuber/columnize/columnize.go b/Godeps/_workspace/src/github.com/ryanuber/columnize/columnize.go index 664c14e05..d87785940 100644 --- a/Godeps/_workspace/src/github.com/ryanuber/columnize/columnize.go +++ b/Godeps/_workspace/src/github.com/ryanuber/columnize/columnize.go @@ -14,6 +14,9 @@ type Config struct { // The string by which columns of output will be prefixed. Prefix string + + // A replacement string to replace empty fields + Empty string } // Returns a Config with default values. @@ -27,21 +30,25 @@ func DefaultConfig() *Config { // Returns a list of elements, each representing a single item which will // belong to a column of output. -func getElementsFromLine(line string, delim string) []interface{} { +func getElementsFromLine(config *Config, line string) []interface{} { elements := make([]interface{}, 0) - for _, field := range strings.Split(line, delim) { - elements = append(elements, strings.TrimSpace(field)) + for _, field := range strings.Split(line, config.Delim) { + value := strings.TrimSpace(field) + if value == "" && config.Empty != "" { + value = config.Empty + } + elements = append(elements, value) } return elements } // Examines a list of strings and determines how wide each column should be // considering all of the elements that need to be printed within it. -func getWidthsFromLines(lines []string, delim string) []int { +func getWidthsFromLines(config *Config, lines []string) []int { var widths []int for _, line := range lines { - elems := getElementsFromLine(line, delim) + elems := getElementsFromLine(config, line) for i := 0; i < len(elems); i++ { l := len(elems[i].(string)) if len(widths) <= i { @@ -91,6 +98,9 @@ func MergeConfig(a, b *Config) *Config { if b.Prefix != "" { result.Prefix = b.Prefix } + if b.Empty != "" { + result.Empty = b.Empty + } return &result } @@ -101,11 +111,11 @@ func Format(lines []string, config *Config) string { var result string conf := MergeConfig(DefaultConfig(), config) - widths := getWidthsFromLines(lines, conf.Delim) + widths := getWidthsFromLines(conf, lines) // Create the formatted output using the format string for _, line := range lines { - elems := getElementsFromLine(line, conf.Delim) + elems := getElementsFromLine(conf, line) stringfmt := conf.getStringFormat(widths, len(elems)) result += fmt.Sprintf(stringfmt, elems...) } diff --git a/Godeps/_workspace/src/github.com/ryanuber/columnize/columnize_test.go b/Godeps/_workspace/src/github.com/ryanuber/columnize/columnize_test.go deleted file mode 100644 index 926ecde59..000000000 --- a/Godeps/_workspace/src/github.com/ryanuber/columnize/columnize_test.go +++ /dev/null @@ -1,224 +0,0 @@ -package columnize - -import "testing" - -func TestListOfStringsInput(t *testing.T) { - input := []string{ - "Column A | Column B | Column C", - "x | y | z", - } - - config := DefaultConfig() - output := Format(input, config) - - expected := "Column A Column B Column C\n" - expected += "x y z" - - if output != expected { - t.Fatalf("\nexpected:\n%s\n\ngot:\n%s", expected, output) - } -} - -func TestEmptyLinesOutput(t *testing.T) { - input := []string{ - "Column A | Column B | Column C", - "", - "x | y | z", - } - - config := DefaultConfig() - output := Format(input, config) - - expected := "Column A Column B Column C\n" - expected += "\n" - expected += "x y z" - - if output != expected { - t.Fatalf("\nexpected:\n%s\n\ngot:\n%s", expected, output) - } -} - -func TestLeadingSpacePreserved(t *testing.T) { - input := []string{ - "| Column B | Column C", - "x | y | z", - } - - config := DefaultConfig() - output := Format(input, config) - - expected := " Column B Column C\n" - expected += "x y z" - - if output != expected { - t.Fatalf("\nexpected:\n%s\n\ngot:\n%s", expected, output) - } -} - -func TestColumnWidthCalculator(t *testing.T) { - input := []string{ - "Column A | Column B | Column C", - "Longer than A | Longer than B | Longer than C", - "short | short | short", - } - - config := DefaultConfig() - output := Format(input, config) - - expected := "Column A Column B Column C\n" - expected += "Longer than A Longer than B Longer than C\n" - expected += "short short short" - - if output != expected { - t.Fatalf("\nexpected:\n%s\n\ngot:\n%s", expected, output) - } -} - -func TestVariedInputSpacing(t *testing.T) { - input := []string{ - "Column A |Column B| Column C", - "x|y| z", - } - - config := DefaultConfig() - output := Format(input, config) - - expected := "Column A Column B Column C\n" - expected += "x y z" - - if output != expected { - t.Fatalf("\nexpected:\n%s\n\ngot:\n%s", expected, output) - } -} - -func TestUnmatchedColumnCounts(t *testing.T) { - input := []string{ - "Column A | Column B | Column C", - "Value A | Value B", - "Value A | Value B | Value C | Value D", - } - - config := DefaultConfig() - output := Format(input, config) - - expected := "Column A Column B Column C\n" - expected += "Value A Value B\n" - expected += "Value A Value B Value C Value D" - - if output != expected { - t.Fatalf("\nexpected:\n%s\n\ngot:\n%s", expected, output) - } -} - -func TestAlternateDelimiter(t *testing.T) { - input := []string{ - "Column | A % Column | B % Column | C", - "Value A % Value B % Value C", - } - - config := DefaultConfig() - config.Delim = "%" - output := Format(input, config) - - expected := "Column | A Column | B Column | C\n" - expected += "Value A Value B Value C" - - if output != expected { - t.Fatalf("\nexpected:\n%s\n\ngot:\n%s", expected, output) - } -} - -func TestAlternateSpacingString(t *testing.T) { - input := []string{ - "Column A | Column B | Column C", - "x | y | z", - } - - config := DefaultConfig() - config.Glue = " " - output := Format(input, config) - - expected := "Column A Column B Column C\n" - expected += "x y z" - - if output != expected { - t.Fatalf("\nexpected:\n%s\n\ngot:\n%s", expected, output) - } -} - -func TestSimpleFormat(t *testing.T) { - input := []string{ - "Column A | Column B | Column C", - "x | y | z", - } - - output := SimpleFormat(input) - - expected := "Column A Column B Column C\n" - expected += "x y z" - - if output != expected { - t.Fatalf("\nexpected:\n%s\n\ngot:\n%s", expected, output) - } -} - -func TestAlternatePrefixString(t *testing.T) { - input := []string{ - "Column A | Column B | Column C", - "x | y | z", - } - - config := DefaultConfig() - config.Prefix = " " - output := Format(input, config) - - expected := " Column A Column B Column C\n" - expected += " x y z" - - if output != expected { - t.Fatalf("\nexpected:\n%s\n\ngot:\n%s", expected, output) - } -} - -func TestEmptyConfigValues(t *testing.T) { - input := []string{ - "Column A | Column B | Column C", - "x | y | z", - } - - config := Config{} - output := Format(input, &config) - - expected := "Column A Column B Column C\n" - expected += "x y z" - - if output != expected { - t.Fatalf("\nexpected:\n%s\n\ngot:\n%s", expected, output) - } -} - -func TestMergeConfig(t *testing.T) { - conf1 := &Config{Delim: "a", Glue: "a", Prefix: "a"} - conf2 := &Config{Delim: "b", Glue: "b", Prefix: "b"} - conf3 := &Config{Delim: "c", Prefix: "c"} - - m := MergeConfig(conf1, conf2) - if m.Delim != "b" || m.Glue != "b" || m.Prefix != "b" { - t.Fatalf("bad: %#v", m) - } - - m = MergeConfig(conf1, conf3) - if m.Delim != "c" || m.Glue != "a" || m.Prefix != "c" { - t.Fatalf("bad: %#v", m) - } - - m = MergeConfig(conf1, nil) - if m.Delim != "a" || m.Glue != "a" || m.Prefix != "a" { - t.Fatalf("bad: %#v", m) - } - - m = MergeConfig(conf1, &Config{}) - if m.Delim != "a" || m.Glue != "a" || m.Prefix != "a" { - t.Fatalf("bad: %#v", m) - } -} diff --git a/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/cluster_test.go b/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/cluster_test.go deleted file mode 100644 index b8571734e..000000000 --- a/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/cluster_test.go +++ /dev/null @@ -1,166 +0,0 @@ -package zk - -import ( - "fmt" - "strings" - "testing" - "time" -) - -type logWriter struct { - t *testing.T - p string -} - -func (lw logWriter) Write(b []byte) (int, error) { - lw.t.Logf("%s%s", lw.p, string(b)) - return len(b), nil -} - -func TestBasicCluster(t *testing.T) { - ts, err := StartTestCluster(3, nil, logWriter{t: t, p: "[ZKERR] "}) - if err != nil { - t.Fatal(err) - } - defer ts.Stop() - zk1, err := ts.Connect(0) - if err != nil { - t.Fatalf("Connect returned error: %+v", err) - } - defer zk1.Close() - zk2, err := ts.Connect(1) - if err != nil { - t.Fatalf("Connect returned error: %+v", err) - } - defer zk2.Close() - - time.Sleep(time.Second * 5) - - if _, err := zk1.Create("/gozk-test", []byte("foo-cluster"), 0, WorldACL(PermAll)); err != nil { - t.Fatalf("Create failed on node 1: %+v", err) - } - if by, _, err := zk2.Get("/gozk-test"); err != nil { - t.Fatalf("Get failed on node 2: %+v", err) - } else if string(by) != "foo-cluster" { - t.Fatal("Wrong data for node 2") - } -} - -func TestClientClusterFailover(t *testing.T) { - ts, err := StartTestCluster(3, nil, logWriter{t: t, p: "[ZKERR] "}) - if err != nil { - t.Fatal(err) - } - defer ts.Stop() - zk, evCh, err := ts.ConnectAll() - if err != nil { - t.Fatalf("Connect returned error: %+v", err) - } - defer zk.Close() - - hasSession := make(chan string, 1) - go func() { - for ev := range evCh { - if ev.Type == EventSession && ev.State == StateHasSession { - select { - case hasSession <- ev.Server: - default: - } - } - } - }() - - waitSession := func() string { - select { - case srv := <-hasSession: - return srv - case <-time.After(time.Second * 8): - t.Fatal("Failed to connect and get a session") - } - return "" - } - - srv := waitSession() - if _, err := zk.Create("/gozk-test", []byte("foo-cluster"), 0, WorldACL(PermAll)); err != nil { - t.Fatalf("Create failed on node 1: %+v", err) - } - - stopped := false - for _, s := range ts.Servers { - if strings.HasSuffix(srv, fmt.Sprintf(":%d", s.Port)) { - s.Srv.Stop() - stopped = true - break - } - } - if !stopped { - t.Fatal("Failed to stop server") - } - - waitSession() - if by, _, err := zk.Get("/gozk-test"); err != nil { - t.Fatalf("Get failed on node 2: %+v", err) - } else if string(by) != "foo-cluster" { - t.Fatal("Wrong data for node 2") - } -} - -func TestWaitForClose(t *testing.T) { - ts, err := StartTestCluster(1, nil, logWriter{t: t, p: "[ZKERR] "}) - if err != nil { - t.Fatal(err) - } - defer ts.Stop() - zk, err := ts.Connect(0) - if err != nil { - t.Fatalf("Connect returned error: %+v", err) - } - timeout := time.After(30 * time.Second) -CONNECTED: - for { - select { - case ev := <-zk.eventChan: - if ev.State == StateConnected { - break CONNECTED - } - case <-timeout: - zk.Close() - t.Fatal("Timeout") - } - } - zk.Close() - for { - select { - case _, ok := <-zk.eventChan: - if !ok { - return - } - case <-timeout: - t.Fatal("Timeout") - } - } -} - -func TestBadSession(t *testing.T) { - ts, err := StartTestCluster(1, nil, logWriter{t: t, p: "[ZKERR] "}) - if err != nil { - t.Fatal(err) - } - defer ts.Stop() - zk, _, err := ts.ConnectAll() - if err != nil { - t.Fatalf("Connect returned error: %+v", err) - } - defer zk.Close() - - if err := zk.Delete("/gozk-test", -1); err != nil && err != ErrNoNode { - t.Fatalf("Delete returned error: %+v", err) - } - - zk.conn.Close() - time.Sleep(time.Millisecond * 100) - - if err := zk.Delete("/gozk-test", -1); err != nil && err != ErrNoNode { - t.Fatalf("Delete returned error: %+v", err) - } -} diff --git a/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/constants_test.go b/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/constants_test.go deleted file mode 100644 index 9fe6b04ce..000000000 --- a/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/constants_test.go +++ /dev/null @@ -1,24 +0,0 @@ -package zk - -import ( - "fmt" - "testing" -) - -func TestModeString(t *testing.T) { - if fmt.Sprintf("%v", ModeUnknown) != "unknown" { - t.Errorf("unknown value should be 'unknown'") - } - - if fmt.Sprintf("%v", ModeLeader) != "leader" { - t.Errorf("leader value should be 'leader'") - } - - if fmt.Sprintf("%v", ModeFollower) != "follower" { - t.Errorf("follower value should be 'follower'") - } - - if fmt.Sprintf("%v", ModeStandalone) != "standalone" { - t.Errorf("standlone value should be 'standalone'") - } -} diff --git a/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/flw_test.go b/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/flw_test.go deleted file mode 100644 index 63907268d..000000000 --- a/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/flw_test.go +++ /dev/null @@ -1,367 +0,0 @@ -package zk - -import ( - "net" - "testing" - "time" -) - -var ( - zkSrvrOut = `Zookeeper version: 3.4.6-1569965, built on 02/20/2014 09:09 GMT -Latency min/avg/max: 0/1/10 -Received: 4207 -Sent: 4220 -Connections: 81 -Outstanding: 1 -Zxid: 0x110a7a8f37 -Mode: leader -Node count: 306 -` - zkConsOut = ` /10.42.45.231:45361[1](queued=0,recved=9435,sent=9457,sid=0x94c2989e04716b5,lop=PING,est=1427238717217,to=20001,lcxid=0x55120915,lzxid=0xffffffffffffffff,lresp=1427259255908,llat=0,minlat=0,avglat=1,maxlat=17) - /10.55.33.98:34342[1](queued=0,recved=9338,sent=9350,sid=0x94c2989e0471731,lop=PING,est=1427238849319,to=20001,lcxid=0x55120944,lzxid=0xffffffffffffffff,lresp=1427259252294,llat=0,minlat=0,avglat=1,maxlat=18) - /10.44.145.114:46556[1](queued=0,recved=109253,sent=109617,sid=0x94c2989e0471709,lop=DELE,est=1427238791305,to=20001,lcxid=0x55139618,lzxid=0x110a7b187d,lresp=1427259257423,llat=2,minlat=0,avglat=1,maxlat=23) - -` -) - -func TestFLWRuok(t *testing.T) { - l, err := net.Listen("tcp", "127.0.0.1:2181") - - if err != nil { - t.Fatalf(err.Error()) - } - - go tcpServer(l, "") - - var oks []bool - var ok bool - - oks = FLWRuok([]string{"127.0.0.1"}, time.Second*10) - - // close the connection, and pause shortly - // to cheat around a race condition - l.Close() - time.Sleep(time.Millisecond * 1) - - if len(oks) == 0 { - t.Errorf("no values returned") - } - - ok = oks[0] - - if !ok { - t.Errorf("instance should be marked as OK") - } - - // - // Confirm that it also returns false for dead instances - // - l, err = net.Listen("tcp", "127.0.0.1:2181") - - if err != nil { - t.Fatalf(err.Error()) - } - - defer l.Close() - - go tcpServer(l, "dead") - - oks = FLWRuok([]string{"127.0.0.1"}, time.Second*10) - - if len(oks) == 0 { - t.Errorf("no values returned") - } - - ok = oks[0] - - if ok { - t.Errorf("instance should be marked as not OK") - } -} - -func TestFLWSrvr(t *testing.T) { - l, err := net.Listen("tcp", "127.0.0.1:2181") - - if err != nil { - t.Fatalf(err.Error()) - } - - defer l.Close() - - go tcpServer(l, "") - - var statsSlice []*ServerStats - var stats *ServerStats - var ok bool - - statsSlice, ok = FLWSrvr([]string{"127.0.0.1:2181"}, time.Second*10) - - if !ok { - t.Errorf("failure indicated on 'srvr' parsing") - } - - if len(statsSlice) == 0 { - t.Errorf("no *ServerStats instances returned") - } - - stats = statsSlice[0] - - if stats.Error != nil { - t.Fatalf("error seen in stats: %v", err.Error()) - } - - if stats.Sent != 4220 { - t.Errorf("Sent != 4220") - } - - if stats.Received != 4207 { - t.Errorf("Received != 4207") - } - - if stats.NodeCount != 306 { - t.Errorf("NodeCount != 306") - } - - if stats.MinLatency != 0 { - t.Errorf("MinLatency != 0") - } - - if stats.AvgLatency != 1 { - t.Errorf("AvgLatency != 1") - } - - if stats.MaxLatency != 10 { - t.Errorf("MaxLatency != 10") - } - - if stats.Connections != 81 { - t.Errorf("Connection != 81") - } - - if stats.Outstanding != 1 { - t.Errorf("Outstanding != 1") - } - - if stats.Epoch != 17 { - t.Errorf("Epoch != 17") - } - - if stats.Counter != 175804215 { - t.Errorf("Counter != 175804215") - } - - if stats.Mode != ModeLeader { - t.Errorf("Mode != ModeLeader") - } - - if stats.Version != "3.4.6-1569965" { - t.Errorf("Version expected: 3.4.6-1569965") - } - - buildTime, err := time.Parse("01/02/2006 15:04 MST", "02/20/2014 09:09 GMT") - - if !stats.BuildTime.Equal(buildTime) { - - } -} - -func TestFLWCons(t *testing.T) { - l, err := net.Listen("tcp", "127.0.0.1:2181") - - if err != nil { - t.Fatalf(err.Error()) - } - - defer l.Close() - - go tcpServer(l, "") - - var clients []*ServerClients - var ok bool - - clients, ok = FLWCons([]string{"127.0.0.1"}, time.Second*10) - - if !ok { - t.Errorf("failure indicated on 'cons' parsing") - } - - if len(clients) == 0 { - t.Errorf("no *ServerClients instances returned") - } - - results := []*ServerClient{ - &ServerClient{ - Queued: 0, - Received: 9435, - Sent: 9457, - SessionID: 669956116721374901, - LastOperation: "PING", - Established: time.Unix(1427238717217, 0), - Timeout: 20001, - Lcxid: 1427245333, - Lzxid: -1, - LastResponse: time.Unix(1427259255908, 0), - LastLatency: 0, - MinLatency: 0, - AvgLatency: 1, - MaxLatency: 17, - Addr: "10.42.45.231:45361", - }, - &ServerClient{ - Queued: 0, - Received: 9338, - Sent: 9350, - SessionID: 669956116721375025, - LastOperation: "PING", - Established: time.Unix(1427238849319, 0), - Timeout: 20001, - Lcxid: 1427245380, - Lzxid: -1, - LastResponse: time.Unix(1427259252294, 0), - LastLatency: 0, - MinLatency: 0, - AvgLatency: 1, - MaxLatency: 18, - Addr: "10.55.33.98:34342", - }, - &ServerClient{ - Queued: 0, - Received: 109253, - Sent: 109617, - SessionID: 669956116721374985, - LastOperation: "DELE", - Established: time.Unix(1427238791305, 0), - Timeout: 20001, - Lcxid: 1427346968, - Lzxid: 73190283389, - LastResponse: time.Unix(1427259257423, 0), - LastLatency: 2, - MinLatency: 0, - AvgLatency: 1, - MaxLatency: 23, - Addr: "10.44.145.114:46556", - }, - } - - for _, z := range clients { - if z.Error != nil { - t.Errorf("error seen: %v", err.Error()) - } - - for i, v := range z.Clients { - c := results[i] - - if v.Error != nil { - t.Errorf("client error seen: %v", err.Error()) - } - - if v.Queued != c.Queued { - t.Errorf("Queued value mismatch (%d/%d)", v.Queued, c.Queued) - } - - if v.Received != c.Received { - t.Errorf("Received value mismatch (%d/%d)", v.Received, c.Received) - } - - if v.Sent != c.Sent { - t.Errorf("Sent value mismatch (%d/%d)", v.Sent, c.Sent) - } - - if v.SessionID != c.SessionID { - t.Errorf("SessionID value mismatch (%d/%d)", v.SessionID, c.SessionID) - } - - if v.LastOperation != c.LastOperation { - t.Errorf("LastOperation value mismatch ('%v'/'%v')", v.LastOperation, c.LastOperation) - } - - if v.Timeout != c.Timeout { - t.Errorf("Timeout value mismatch (%d/%d)", v.Timeout, c.Timeout) - } - - if v.Lcxid != c.Lcxid { - t.Errorf("Lcxid value mismatch (%d/%d)", v.Lcxid, c.Lcxid) - } - - if v.Lzxid != c.Lzxid { - t.Errorf("Lzxid value mismatch (%d/%d)", v.Lzxid, c.Lzxid) - } - - if v.LastLatency != c.LastLatency { - t.Errorf("LastLatency value mismatch (%d/%d)", v.LastLatency, c.LastLatency) - } - - if v.MinLatency != c.MinLatency { - t.Errorf("MinLatency value mismatch (%d/%d)", v.MinLatency, c.MinLatency) - } - - if v.AvgLatency != c.AvgLatency { - t.Errorf("AvgLatency value mismatch (%d/%d)", v.AvgLatency, c.AvgLatency) - } - - if v.MaxLatency != c.MaxLatency { - t.Errorf("MaxLatency value mismatch (%d/%d)", v.MaxLatency, c.MaxLatency) - } - - if v.Addr != c.Addr { - t.Errorf("Addr value mismatch ('%v'/'%v')", v.Addr, c.Addr) - } - - if !c.Established.Equal(v.Established) { - t.Errorf("Established value mismatch (%v/%v)", c.Established, v.Established) - } - - if !c.LastResponse.Equal(v.LastResponse) { - t.Errorf("Established value mismatch (%v/%v)", c.LastResponse, v.LastResponse) - } - } - } -} - -func tcpServer(listener net.Listener, thing string) { - for { - conn, err := listener.Accept() - if err != nil { - return - } - go connHandler(conn, thing) - } -} - -func connHandler(conn net.Conn, thing string) { - defer conn.Close() - - data := make([]byte, 4) - - _, err := conn.Read(data) - - if err != nil { - return - } - - switch string(data) { - case "ruok": - switch thing { - case "dead": - return - default: - conn.Write([]byte("imok")) - } - case "srvr": - switch thing { - case "dead": - return - default: - conn.Write([]byte(zkSrvrOut)) - } - case "cons": - switch thing { - case "dead": - return - default: - conn.Write([]byte(zkConsOut)) - } - default: - conn.Write([]byte("This ZooKeeper instance is not currently serving requests.")) - } -} diff --git a/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/lock_test.go b/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/lock_test.go deleted file mode 100644 index 8a3478a33..000000000 --- a/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/lock_test.go +++ /dev/null @@ -1,94 +0,0 @@ -package zk - -import ( - "testing" - "time" -) - -func TestLock(t *testing.T) { - ts, err := StartTestCluster(1, nil, logWriter{t: t, p: "[ZKERR] "}) - if err != nil { - t.Fatal(err) - } - defer ts.Stop() - zk, _, err := ts.ConnectAll() - if err != nil { - t.Fatalf("Connect returned error: %+v", err) - } - defer zk.Close() - - acls := WorldACL(PermAll) - - l := NewLock(zk, "/test", acls) - if err := l.Lock(); err != nil { - t.Fatal(err) - } - if err := l.Unlock(); err != nil { - t.Fatal(err) - } - - val := make(chan int, 3) - - if err := l.Lock(); err != nil { - t.Fatal(err) - } - - l2 := NewLock(zk, "/test", acls) - go func() { - if err := l2.Lock(); err != nil { - t.Fatal(err) - } - val <- 2 - if err := l2.Unlock(); err != nil { - t.Fatal(err) - } - val <- 3 - }() - time.Sleep(time.Millisecond * 100) - - val <- 1 - if err := l.Unlock(); err != nil { - t.Fatal(err) - } - if x := <-val; x != 1 { - t.Fatalf("Expected 1 instead of %d", x) - } - if x := <-val; x != 2 { - t.Fatalf("Expected 2 instead of %d", x) - } - if x := <-val; x != 3 { - t.Fatalf("Expected 3 instead of %d", x) - } -} - -// This tests creating a lock with a path that's more than 1 node deep (e.g. "/test-multi-level/lock"), -// when a part of that path already exists (i.e. "/test-multi-level" node already exists). -func TestMultiLevelLock(t *testing.T) { - ts, err := StartTestCluster(1, nil, logWriter{t: t, p: "[ZKERR] "}) - if err != nil { - t.Fatal(err) - } - defer ts.Stop() - zk, _, err := ts.ConnectAll() - if err != nil { - t.Fatalf("Connect returned error: %+v", err) - } - defer zk.Close() - - acls := WorldACL(PermAll) - path := "/test-multi-level" - if p, err := zk.Create(path, []byte{1, 2, 3, 4}, 0, WorldACL(PermAll)); err != nil { - t.Fatalf("Create returned error: %+v", err) - } else if p != path { - t.Fatalf("Create returned different path '%s' != '%s'", p, path) - } - l := NewLock(zk, "/test-multi-level/lock", acls) - defer zk.Delete("/test-multi-level", -1) // Clean up what we've created for this test - defer zk.Delete("/test-multi-level/lock", -1) - if err := l.Lock(); err != nil { - t.Fatal(err) - } - if err := l.Unlock(); err != nil { - t.Fatal(err) - } -} diff --git a/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/structs_test.go b/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/structs_test.go deleted file mode 100644 index cafbbd95c..000000000 --- a/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/structs_test.go +++ /dev/null @@ -1,71 +0,0 @@ -package zk - -import ( - "reflect" - "testing" -) - -func TestEncodeDecodePacket(t *testing.T) { - encodeDecodeTest(t, &requestHeader{-2, 5}) - encodeDecodeTest(t, &connectResponse{1, 2, 3, nil}) - encodeDecodeTest(t, &connectResponse{1, 2, 3, []byte{4, 5, 6}}) - encodeDecodeTest(t, &getAclResponse{[]ACL{{12, "s", "anyone"}}, Stat{}}) - encodeDecodeTest(t, &getChildrenResponse{[]string{"foo", "bar"}}) - encodeDecodeTest(t, &pathWatchRequest{"path", true}) - encodeDecodeTest(t, &pathWatchRequest{"path", false}) - encodeDecodeTest(t, &CheckVersionRequest{"/", -1}) - encodeDecodeTest(t, &multiRequest{Ops: []multiRequestOp{{multiHeader{opCheck, false, -1}, &CheckVersionRequest{"/", -1}}}}) -} - -func encodeDecodeTest(t *testing.T, r interface{}) { - buf := make([]byte, 1024) - n, err := encodePacket(buf, r) - if err != nil { - t.Errorf("encodePacket returned non-nil error %+v\n", err) - return - } - t.Logf("%+v %x", r, buf[:n]) - r2 := reflect.New(reflect.ValueOf(r).Elem().Type()).Interface() - n2, err := decodePacket(buf[:n], r2) - if err != nil { - t.Errorf("decodePacket returned non-nil error %+v\n", err) - return - } - if n != n2 { - t.Errorf("sizes don't match: %d != %d", n, n2) - return - } - if !reflect.DeepEqual(r, r2) { - t.Errorf("results don't match: %+v != %+v", r, r2) - return - } -} - -func TestEncodeShortBuffer(t *testing.T) { - buf := make([]byte, 0) - _, err := encodePacket(buf, &requestHeader{1, 2}) - if err != ErrShortBuffer { - t.Errorf("encodePacket should return ErrShortBuffer on a short buffer instead of '%+v'", err) - return - } -} - -func TestDecodeShortBuffer(t *testing.T) { - buf := make([]byte, 0) - _, err := decodePacket(buf, &responseHeader{}) - if err != ErrShortBuffer { - t.Errorf("decodePacket should return ErrShortBuffer on a short buffer instead of '%+v'", err) - return - } -} - -func BenchmarkEncode(b *testing.B) { - buf := make([]byte, 4096) - st := &connectRequest{Passwd: []byte("1234567890")} - b.ReportAllocs() - for i := 0; i < b.N; i++ { - if _, err := encodePacket(buf, st); err != nil { - b.Fatal(err) - } - } -} diff --git a/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/util_test.go b/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/util_test.go deleted file mode 100644 index b56f77550..000000000 --- a/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/util_test.go +++ /dev/null @@ -1,17 +0,0 @@ -package zk - -import "testing" - -func TestFormatServers(t *testing.T) { - servers := []string{"127.0.0.1:2181", "127.0.0.42", "127.0.42.1:8811"} - r := []string{"127.0.0.1:2181", "127.0.0.42:2181", "127.0.42.1:8811"} - - var s []string - s = FormatServers(servers) - - for i := range s { - if s[i] != r[i] { - t.Errorf("%v should equal %v", s[i], r[i]) - } - } -} diff --git a/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/zk_test.go b/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/zk_test.go deleted file mode 100644 index fdbe51727..000000000 --- a/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/zk_test.go +++ /dev/null @@ -1,518 +0,0 @@ -package zk - -import ( - "fmt" - "io" - "net" - "strings" - "testing" - "time" - - "camlistore.org/pkg/throttle" -) - -func TestCreate(t *testing.T) { - ts, err := StartTestCluster(1, nil, logWriter{t: t, p: "[ZKERR] "}) - if err != nil { - t.Fatal(err) - } - defer ts.Stop() - zk, _, err := ts.ConnectAll() - if err != nil { - t.Fatalf("Connect returned error: %+v", err) - } - defer zk.Close() - - path := "/gozk-test" - - if err := zk.Delete(path, -1); err != nil && err != ErrNoNode { - t.Fatalf("Delete returned error: %+v", err) - } - if p, err := zk.Create(path, []byte{1, 2, 3, 4}, 0, WorldACL(PermAll)); err != nil { - t.Fatalf("Create returned error: %+v", err) - } else if p != path { - t.Fatalf("Create returned different path '%s' != '%s'", p, path) - } - if data, stat, err := zk.Get(path); err != nil { - t.Fatalf("Get returned error: %+v", err) - } else if stat == nil { - t.Fatal("Get returned nil stat") - } else if len(data) < 4 { - t.Fatal("Get returned wrong size data") - } -} - -func TestMulti(t *testing.T) { - ts, err := StartTestCluster(1, nil, logWriter{t: t, p: "[ZKERR] "}) - if err != nil { - t.Fatal(err) - } - defer ts.Stop() - zk, _, err := ts.ConnectAll() - if err != nil { - t.Fatalf("Connect returned error: %+v", err) - } - defer zk.Close() - - path := "/gozk-test" - - if err := zk.Delete(path, -1); err != nil && err != ErrNoNode { - t.Fatalf("Delete returned error: %+v", err) - } - ops := []interface{}{ - &CreateRequest{Path: path, Data: []byte{1, 2, 3, 4}, Acl: WorldACL(PermAll)}, - &SetDataRequest{Path: path, Data: []byte{1, 2, 3, 4}, Version: -1}, - } - if res, err := zk.Multi(ops...); err != nil { - t.Fatalf("Multi returned error: %+v", err) - } else if len(res) != 2 { - t.Fatalf("Expected 2 responses got %d", len(res)) - } else { - t.Logf("%+v", res) - } - if data, stat, err := zk.Get(path); err != nil { - t.Fatalf("Get returned error: %+v", err) - } else if stat == nil { - t.Fatal("Get returned nil stat") - } else if len(data) < 4 { - t.Fatal("Get returned wrong size data") - } -} - -func TestGetSetACL(t *testing.T) { - ts, err := StartTestCluster(1, nil, logWriter{t: t, p: "[ZKERR] "}) - if err != nil { - t.Fatal(err) - } - defer ts.Stop() - zk, _, err := ts.ConnectAll() - if err != nil { - t.Fatalf("Connect returned error: %+v", err) - } - defer zk.Close() - - if err := zk.AddAuth("digest", []byte("blah")); err != nil { - t.Fatalf("AddAuth returned error %+v", err) - } - - path := "/gozk-test" - - if err := zk.Delete(path, -1); err != nil && err != ErrNoNode { - t.Fatalf("Delete returned error: %+v", err) - } - if path, err := zk.Create(path, []byte{1, 2, 3, 4}, 0, WorldACL(PermAll)); err != nil { - t.Fatalf("Create returned error: %+v", err) - } else if path != "/gozk-test" { - t.Fatalf("Create returned different path '%s' != '/gozk-test'", path) - } - - expected := WorldACL(PermAll) - - if acl, stat, err := zk.GetACL(path); err != nil { - t.Fatalf("GetACL returned error %+v", err) - } else if stat == nil { - t.Fatalf("GetACL returned nil Stat") - } else if len(acl) != 1 || expected[0] != acl[0] { - t.Fatalf("GetACL mismatch expected %+v instead of %+v", expected, acl) - } - - expected = []ACL{{PermAll, "ip", "127.0.0.1"}} - - if stat, err := zk.SetACL(path, expected, -1); err != nil { - t.Fatalf("SetACL returned error %+v", err) - } else if stat == nil { - t.Fatalf("SetACL returned nil Stat") - } - - if acl, stat, err := zk.GetACL(path); err != nil { - t.Fatalf("GetACL returned error %+v", err) - } else if stat == nil { - t.Fatalf("GetACL returned nil Stat") - } else if len(acl) != 1 || expected[0] != acl[0] { - t.Fatalf("GetACL mismatch expected %+v instead of %+v", expected, acl) - } -} - -func TestAuth(t *testing.T) { - ts, err := StartTestCluster(1, nil, logWriter{t: t, p: "[ZKERR] "}) - if err != nil { - t.Fatal(err) - } - defer ts.Stop() - zk, _, err := ts.ConnectAll() - if err != nil { - t.Fatalf("Connect returned error: %+v", err) - } - defer zk.Close() - - path := "/gozk-digest-test" - if err := zk.Delete(path, -1); err != nil && err != ErrNoNode { - t.Fatalf("Delete returned error: %+v", err) - } - - acl := DigestACL(PermAll, "user", "password") - - if p, err := zk.Create(path, []byte{1, 2, 3, 4}, 0, acl); err != nil { - t.Fatalf("Create returned error: %+v", err) - } else if p != path { - t.Fatalf("Create returned different path '%s' != '%s'", p, path) - } - - if a, stat, err := zk.GetACL(path); err != nil { - t.Fatalf("GetACL returned error %+v", err) - } else if stat == nil { - t.Fatalf("GetACL returned nil Stat") - } else if len(a) != 1 || acl[0] != a[0] { - t.Fatalf("GetACL mismatch expected %+v instead of %+v", acl, a) - } - - if _, _, err := zk.Get(path); err != ErrNoAuth { - t.Fatalf("Get returned error %+v instead of ErrNoAuth", err) - } - - if err := zk.AddAuth("digest", []byte("user:password")); err != nil { - t.Fatalf("AddAuth returned error %+v", err) - } - - if data, stat, err := zk.Get(path); err != nil { - t.Fatalf("Get returned error %+v", err) - } else if stat == nil { - t.Fatalf("Get returned nil Stat") - } else if len(data) != 4 { - t.Fatalf("Get returned wrong data length") - } -} - -func TestChildWatch(t *testing.T) { - ts, err := StartTestCluster(1, nil, logWriter{t: t, p: "[ZKERR] "}) - if err != nil { - t.Fatal(err) - } - defer ts.Stop() - zk, _, err := ts.ConnectAll() - if err != nil { - t.Fatalf("Connect returned error: %+v", err) - } - defer zk.Close() - - if err := zk.Delete("/gozk-test", -1); err != nil && err != ErrNoNode { - t.Fatalf("Delete returned error: %+v", err) - } - - children, stat, childCh, err := zk.ChildrenW("/") - if err != nil { - t.Fatalf("Children returned error: %+v", err) - } else if stat == nil { - t.Fatal("Children returned nil stat") - } else if len(children) < 1 { - t.Fatal("Children should return at least 1 child") - } - - if path, err := zk.Create("/gozk-test", []byte{1, 2, 3, 4}, 0, WorldACL(PermAll)); err != nil { - t.Fatalf("Create returned error: %+v", err) - } else if path != "/gozk-test" { - t.Fatalf("Create returned different path '%s' != '/gozk-test'", path) - } - - select { - case ev := <-childCh: - if ev.Err != nil { - t.Fatalf("Child watcher error %+v", ev.Err) - } - if ev.Path != "/" { - t.Fatalf("Child watcher wrong path %s instead of %s", ev.Path, "/") - } - case _ = <-time.After(time.Second * 2): - t.Fatal("Child watcher timed out") - } - - // Delete of the watched node should trigger the watch - - children, stat, childCh, err = zk.ChildrenW("/gozk-test") - if err != nil { - t.Fatalf("Children returned error: %+v", err) - } else if stat == nil { - t.Fatal("Children returned nil stat") - } else if len(children) != 0 { - t.Fatal("Children should return 0 children") - } - - if err := zk.Delete("/gozk-test", -1); err != nil && err != ErrNoNode { - t.Fatalf("Delete returned error: %+v", err) - } - - select { - case ev := <-childCh: - if ev.Err != nil { - t.Fatalf("Child watcher error %+v", ev.Err) - } - if ev.Path != "/gozk-test" { - t.Fatalf("Child watcher wrong path %s instead of %s", ev.Path, "/") - } - case _ = <-time.After(time.Second * 2): - t.Fatal("Child watcher timed out") - } -} - -func TestSetWatchers(t *testing.T) { - ts, err := StartTestCluster(1, nil, logWriter{t: t, p: "[ZKERR] "}) - if err != nil { - t.Fatal(err) - } - defer ts.Stop() - zk, _, err := ts.ConnectAll() - if err != nil { - t.Fatalf("Connect returned error: %+v", err) - } - defer zk.Close() - - zk.reconnectDelay = time.Second - - zk2, _, err := ts.ConnectAll() - if err != nil { - t.Fatalf("Connect returned error: %+v", err) - } - defer zk2.Close() - - if err := zk.Delete("/gozk-test", -1); err != nil && err != ErrNoNode { - t.Fatalf("Delete returned error: %+v", err) - } - - testPath, err := zk.Create("/gozk-test-2", []byte{}, 0, WorldACL(PermAll)) - if err != nil { - t.Fatalf("Create returned: %+v", err) - } - - _, _, testEvCh, err := zk.GetW(testPath) - if err != nil { - t.Fatalf("GetW returned: %+v", err) - } - - children, stat, childCh, err := zk.ChildrenW("/") - if err != nil { - t.Fatalf("Children returned error: %+v", err) - } else if stat == nil { - t.Fatal("Children returned nil stat") - } else if len(children) < 1 { - t.Fatal("Children should return at least 1 child") - } - - zk.conn.Close() - if err := zk2.Delete(testPath, -1); err != nil && err != ErrNoNode { - t.Fatalf("Delete returned error: %+v", err) - } - time.Sleep(time.Millisecond * 100) - - if path, err := zk2.Create("/gozk-test", []byte{1, 2, 3, 4}, 0, WorldACL(PermAll)); err != nil { - t.Fatalf("Create returned error: %+v", err) - } else if path != "/gozk-test" { - t.Fatalf("Create returned different path '%s' != '/gozk-test'", path) - } - - select { - case ev := <-testEvCh: - if ev.Err != nil { - t.Fatalf("GetW watcher error %+v", ev.Err) - } - if ev.Path != testPath { - t.Fatalf("GetW watcher wrong path %s instead of %s", ev.Path, testPath) - } - case <-time.After(2 * time.Second): - t.Fatal("GetW watcher timed out") - } - - select { - case ev := <-childCh: - if ev.Err != nil { - t.Fatalf("Child watcher error %+v", ev.Err) - } - if ev.Path != "/" { - t.Fatalf("Child watcher wrong path %s instead of %s", ev.Path, "/") - } - case <-time.After(2 * time.Second): - t.Fatal("Child watcher timed out") - } -} - -func TestExpiringWatch(t *testing.T) { - ts, err := StartTestCluster(1, nil, logWriter{t: t, p: "[ZKERR] "}) - if err != nil { - t.Fatal(err) - } - defer ts.Stop() - zk, _, err := ts.ConnectAll() - if err != nil { - t.Fatalf("Connect returned error: %+v", err) - } - defer zk.Close() - - if err := zk.Delete("/gozk-test", -1); err != nil && err != ErrNoNode { - t.Fatalf("Delete returned error: %+v", err) - } - - children, stat, childCh, err := zk.ChildrenW("/") - if err != nil { - t.Fatalf("Children returned error: %+v", err) - } else if stat == nil { - t.Fatal("Children returned nil stat") - } else if len(children) < 1 { - t.Fatal("Children should return at least 1 child") - } - - zk.sessionID = 99999 - zk.conn.Close() - - select { - case ev := <-childCh: - if ev.Err != ErrSessionExpired { - t.Fatalf("Child watcher error %+v instead of expected ErrSessionExpired", ev.Err) - } - if ev.Path != "/" { - t.Fatalf("Child watcher wrong path %s instead of %s", ev.Path, "/") - } - case <-time.After(2 * time.Second): - t.Fatal("Child watcher timed out") - } -} - -func TestRequestFail(t *testing.T) { - // If connecting fails to all servers in the list then pending requests - // should be errored out so they don't hang forever. - - zk, _, err := Connect([]string{"127.0.0.1:32444"}, time.Second*15) - if err != nil { - t.Fatal(err) - } - defer zk.Close() - - ch := make(chan error) - go func() { - _, _, err := zk.Get("/blah") - ch <- err - }() - select { - case err := <-ch: - if err == nil { - t.Fatal("Expected non-nil error on failed request due to connection failure") - } - case <-time.After(time.Second * 2): - t.Fatal("Get hung when connection could not be made") - } -} - -func TestSlowServer(t *testing.T) { - ts, err := StartTestCluster(1, nil, logWriter{t: t, p: "[ZKERR] "}) - if err != nil { - t.Fatal(err) - } - defer ts.Stop() - - realAddr := fmt.Sprintf("127.0.0.1:%d", ts.Servers[0].Port) - proxyAddr, stopCh, err := startSlowProxy(t, - throttle.Rate{}, throttle.Rate{}, - realAddr, func(ln *throttle.Listener) { - if ln.Up.Latency == 0 { - ln.Up.Latency = time.Millisecond * 2000 - ln.Down.Latency = time.Millisecond * 2000 - } else { - ln.Up.Latency = 0 - ln.Down.Latency = 0 - } - }) - if err != nil { - t.Fatal(err) - } - defer close(stopCh) - - zk, _, err := Connect([]string{proxyAddr}, time.Millisecond*500) - if err != nil { - t.Fatal(err) - } - defer zk.Close() - - _, _, wch, err := zk.ChildrenW("/") - if err != nil { - t.Fatal(err) - } - - // Force a reconnect to get a throttled connection - zk.conn.Close() - - time.Sleep(time.Millisecond * 100) - - if err := zk.Delete("/gozk-test", -1); err == nil { - t.Fatal("Delete should have failed") - } - - // The previous request should have timed out causing the server to be disconnected and reconnected - - if _, err := zk.Create("/gozk-test", []byte{1, 2, 3, 4}, 0, WorldACL(PermAll)); err != nil { - t.Fatal(err) - } - - // Make sure event is still returned because the session should not have been affected - select { - case ev := <-wch: - t.Logf("Received event: %+v", ev) - case <-time.After(time.Second): - t.Fatal("Expected to receive a watch event") - } -} - -func startSlowProxy(t *testing.T, up, down throttle.Rate, upstream string, adj func(ln *throttle.Listener)) (string, chan bool, error) { - ln, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - return "", nil, err - } - tln := &throttle.Listener{ - Listener: ln, - Up: up, - Down: down, - } - stopCh := make(chan bool) - go func() { - <-stopCh - tln.Close() - }() - go func() { - for { - cn, err := tln.Accept() - if err != nil { - if !strings.Contains(err.Error(), "use of closed network connection") { - t.Fatalf("Accept failed: %s", err.Error()) - } - return - } - if adj != nil { - adj(tln) - } - go func(cn net.Conn) { - defer cn.Close() - upcn, err := net.Dial("tcp", upstream) - if err != nil { - t.Log(err) - return - } - // This will leave hanging goroutines util stopCh is closed - // but it doesn't matter in the context of running tests. - go func() { - <-stopCh - upcn.Close() - }() - go func() { - if _, err := io.Copy(upcn, cn); err != nil { - if !strings.Contains(err.Error(), "use of closed network connection") { - // log.Printf("Upstream write failed: %s", err.Error()) - } - } - }() - if _, err := io.Copy(cn, upcn); err != nil { - if !strings.Contains(err.Error(), "use of closed network connection") { - // log.Printf("Upstream read failed: %s", err.Error()) - } - } - }(cn) - } - }() - return ln.Addr().String(), stopCh, nil -} diff --git a/Godeps/_workspace/src/github.com/ugorji/go/codec/binc.go b/Godeps/_workspace/src/github.com/ugorji/go/codec/binc.go index 9dadb0a47..251609e65 100644 --- a/Godeps/_workspace/src/github.com/ugorji/go/codec/binc.go +++ b/Godeps/_workspace/src/github.com/ugorji/go/codec/binc.go @@ -69,7 +69,15 @@ func (e *bincEncDriver) IsBuiltinType(rt uintptr) bool { func (e *bincEncDriver) EncodeBuiltin(rt uintptr, v interface{}) { if rt == timeTypId { - bs := encodeTime(v.(time.Time)) + var bs []byte + switch x := v.(type) { + case time.Time: + bs = encodeTime(x) + case *time.Time: + bs = encodeTime(*x) + default: + e.e.errorf("binc error encoding builtin: expect time.Time, received %T", v) + } e.w.writen1(bincVdTimestamp<<4 | uint8(len(bs))) e.w.writeb(bs) } diff --git a/Godeps/_workspace/src/github.com/ugorji/go/codec/cbor_test.go b/Godeps/_workspace/src/github.com/ugorji/go/codec/cbor_test.go deleted file mode 100644 index 205dffa7d..000000000 --- a/Godeps/_workspace/src/github.com/ugorji/go/codec/cbor_test.go +++ /dev/null @@ -1,205 +0,0 @@ -// Copyright (c) 2012-2015 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -package codec - -import ( - "bufio" - "bytes" - "encoding/hex" - "math" - "os" - "regexp" - "strings" - "testing" -) - -func TestCborIndefiniteLength(t *testing.T) { - oldMapType := testCborH.MapType - defer func() { - testCborH.MapType = oldMapType - }() - testCborH.MapType = testMapStrIntfTyp - // var ( - // M1 map[string][]byte - // M2 map[uint64]bool - // L1 []interface{} - // S1 []string - // B1 []byte - // ) - var v, vv interface{} - // define it (v), encode it using indefinite lengths, decode it (vv), compare v to vv - v = map[string]interface{}{ - "one-byte-key": []byte{1, 2, 3, 4, 5, 6}, - "two-string-key": "two-value", - "three-list-key": []interface{}{true, false, uint64(1), int64(-1)}, - } - var buf bytes.Buffer - // buf.Reset() - e := NewEncoder(&buf, testCborH) - buf.WriteByte(cborBdIndefiniteMap) - //---- - buf.WriteByte(cborBdIndefiniteString) - e.MustEncode("one-") - e.MustEncode("byte-") - e.MustEncode("key") - buf.WriteByte(cborBdBreak) - - buf.WriteByte(cborBdIndefiniteBytes) - e.MustEncode([]byte{1, 2, 3}) - e.MustEncode([]byte{4, 5, 6}) - buf.WriteByte(cborBdBreak) - - //---- - buf.WriteByte(cborBdIndefiniteString) - e.MustEncode("two-") - e.MustEncode("string-") - e.MustEncode("key") - buf.WriteByte(cborBdBreak) - - buf.WriteByte(cborBdIndefiniteString) - e.MustEncode([]byte("two-")) // encode as bytes, to check robustness of code - e.MustEncode([]byte("value")) - buf.WriteByte(cborBdBreak) - - //---- - buf.WriteByte(cborBdIndefiniteString) - e.MustEncode("three-") - e.MustEncode("list-") - e.MustEncode("key") - buf.WriteByte(cborBdBreak) - - buf.WriteByte(cborBdIndefiniteArray) - e.MustEncode(true) - e.MustEncode(false) - e.MustEncode(uint64(1)) - e.MustEncode(int64(-1)) - buf.WriteByte(cborBdBreak) - - buf.WriteByte(cborBdBreak) // close map - - NewDecoderBytes(buf.Bytes(), testCborH).MustDecode(&vv) - if err := deepEqual(v, vv); err != nil { - logT(t, "-------- Before and After marshal do not match: Error: %v", err) - logT(t, " ....... GOLDEN: (%T) %#v", v, v) - logT(t, " ....... DECODED: (%T) %#v", vv, vv) - failT(t) - } -} - -type testCborGolden struct { - Base64 string `codec:"cbor"` - Hex string `codec:"hex"` - Roundtrip bool `codec:"roundtrip"` - Decoded interface{} `codec:"decoded"` - Diagnostic string `codec:"diagnostic"` - Skip bool `codec:"skip"` -} - -// Some tests are skipped because they include numbers outside the range of int64/uint64 -func doTestCborGoldens(t *testing.T) { - oldMapType := testCborH.MapType - defer func() { - testCborH.MapType = oldMapType - }() - testCborH.MapType = testMapStrIntfTyp - // decode test-cbor-goldens.json into a list of []*testCborGolden - // for each one, - // - decode hex into []byte bs - // - decode bs into interface{} v - // - compare both using deepequal - // - for any miss, record it - var gs []*testCborGolden - f, err := os.Open("test-cbor-goldens.json") - if err != nil { - logT(t, "error opening test-cbor-goldens.json: %v", err) - failT(t) - } - defer f.Close() - jh := new(JsonHandle) - jh.MapType = testMapStrIntfTyp - // d := NewDecoder(f, jh) - d := NewDecoder(bufio.NewReader(f), jh) - // err = d.Decode(&gs) - d.MustDecode(&gs) - if err != nil { - logT(t, "error json decoding test-cbor-goldens.json: %v", err) - failT(t) - } - - tagregex := regexp.MustCompile(`[\d]+\(.+?\)`) - hexregex := regexp.MustCompile(`h'([0-9a-fA-F]*)'`) - for i, g := range gs { - // fmt.Printf("%v, skip: %v, isTag: %v, %s\n", i, g.Skip, tagregex.MatchString(g.Diagnostic), g.Diagnostic) - // skip tags or simple or those with prefix, as we can't verify them. - if g.Skip || strings.HasPrefix(g.Diagnostic, "simple(") || tagregex.MatchString(g.Diagnostic) { - // fmt.Printf("%v: skipped\n", i) - logT(t, "[%v] skipping because skip=true OR unsupported simple value or Tag Value", i) - continue - } - // println("++++++++++++", i, "g.Diagnostic", g.Diagnostic) - if hexregex.MatchString(g.Diagnostic) { - // println(i, "g.Diagnostic matched hex") - if s2 := g.Diagnostic[2 : len(g.Diagnostic)-1]; s2 == "" { - g.Decoded = zeroByteSlice - } else if bs2, err2 := hex.DecodeString(s2); err2 == nil { - g.Decoded = bs2 - } - // fmt.Printf("%v: hex: %v\n", i, g.Decoded) - } - bs, err := hex.DecodeString(g.Hex) - if err != nil { - logT(t, "[%v] error hex decoding %s [%v]: %v", i, g.Hex, err) - failT(t) - } - var v interface{} - NewDecoderBytes(bs, testCborH).MustDecode(&v) - if _, ok := v.(RawExt); ok { - continue - } - // check the diagnostics to compare - switch g.Diagnostic { - case "Infinity": - b := math.IsInf(v.(float64), 1) - testCborError(t, i, math.Inf(1), v, nil, &b) - case "-Infinity": - b := math.IsInf(v.(float64), -1) - testCborError(t, i, math.Inf(-1), v, nil, &b) - case "NaN": - // println(i, "checking NaN") - b := math.IsNaN(v.(float64)) - testCborError(t, i, math.NaN(), v, nil, &b) - case "undefined": - b := v == nil - testCborError(t, i, nil, v, nil, &b) - default: - v0 := g.Decoded - // testCborCoerceJsonNumber(reflect.ValueOf(&v0)) - testCborError(t, i, v0, v, deepEqual(v0, v), nil) - } - } -} - -func testCborError(t *testing.T, i int, v0, v1 interface{}, err error, equal *bool) { - if err == nil && equal == nil { - // fmt.Printf("%v testCborError passed (err and equal nil)\n", i) - return - } - if err != nil { - logT(t, "[%v] deepEqual error: %v", i, err) - logT(t, " ....... GOLDEN: (%T) %#v", v0, v0) - logT(t, " ....... DECODED: (%T) %#v", v1, v1) - failT(t) - } - if equal != nil && !*equal { - logT(t, "[%v] values not equal", i) - logT(t, " ....... GOLDEN: (%T) %#v", v0, v0) - logT(t, " ....... DECODED: (%T) %#v", v1, v1) - failT(t) - } - // fmt.Printf("%v testCborError passed (checks passed)\n", i) -} - -func TestCborGoldens(t *testing.T) { - doTestCborGoldens(t) -} diff --git a/Godeps/_workspace/src/github.com/ugorji/go/codec/codec_test.go b/Godeps/_workspace/src/github.com/ugorji/go/codec/codec_test.go deleted file mode 100644 index cd93556f7..000000000 --- a/Godeps/_workspace/src/github.com/ugorji/go/codec/codec_test.go +++ /dev/null @@ -1,1117 +0,0 @@ -// Copyright (c) 2012-2015 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -package codec - -// Test works by using a slice of interfaces. -// It can test for encoding/decoding into/from a nil interface{} -// or passing the object to encode/decode into. -// -// There are basically 2 main tests here. -// First test internally encodes and decodes things and verifies that -// the artifact was as expected. -// Second test will use python msgpack to create a bunch of golden files, -// read those files, and compare them to what it should be. It then -// writes those files back out and compares the byte streams. -// -// Taken together, the tests are pretty extensive. -// -// The following manual tests must be done: -// - TestCodecUnderlyingType -// - Set fastpathEnabled to false and run tests (to ensure that regular reflection works). -// We don't want to use a variable there so that code is ellided. - -import ( - "bytes" - "encoding/gob" - "flag" - "fmt" - "io/ioutil" - "math" - "net" - "net/rpc" - "os" - "os/exec" - "path/filepath" - "reflect" - "runtime" - "strconv" - "sync/atomic" - "testing" - "time" -) - -func init() { - testInitFlags() - testPreInitFns = append(testPreInitFns, testInit) -} - -type testVerifyArg int - -const ( - testVerifyMapTypeSame testVerifyArg = iota - testVerifyMapTypeStrIntf - testVerifyMapTypeIntfIntf - // testVerifySliceIntf - testVerifyForPython -) - -const testSkipRPCTests = false - -var ( - testVerbose bool - testInitDebug bool - testUseIoEncDec bool - testStructToArray bool - testCanonical bool - testWriteNoSymbols bool - testSkipIntf bool - - skipVerifyVal interface{} = &(struct{}{}) - - testMapStrIntfTyp = reflect.TypeOf(map[string]interface{}(nil)) - - // For Go Time, do not use a descriptive timezone. - // It's unnecessary, and makes it harder to do a reflect.DeepEqual. - // The Offset already tells what the offset should be, if not on UTC and unknown zone name. - timeLoc = time.FixedZone("", -8*60*60) // UTC-08:00 //time.UTC-8 - timeToCompare1 = time.Date(2012, 2, 2, 2, 2, 2, 2000, timeLoc).UTC() - timeToCompare2 = time.Date(1900, 2, 2, 2, 2, 2, 2000, timeLoc).UTC() - timeToCompare3 = time.Unix(0, 270).UTC() // use value that must be encoded as uint64 for nanoseconds (for cbor/msgpack comparison) - //timeToCompare4 = time.Time{}.UTC() // does not work well with simple cbor time encoding (overflow) - timeToCompare4 = time.Unix(-2013855848, 4223).UTC() - - table []interface{} // main items we encode - tableVerify []interface{} // we verify encoded things against this after decode - tableTestNilVerify []interface{} // for nil interface, use this to verify (rules are different) - tablePythonVerify []interface{} // for verifying for python, since Python sometimes - // will encode a float32 as float64, or large int as uint - testRpcInt = new(TestRpcInt) -) - -func testInitFlags() { - // delete(testDecOpts.ExtFuncs, timeTyp) - flag.BoolVar(&testVerbose, "tv", false, "Test Verbose") - flag.BoolVar(&testInitDebug, "tg", false, "Test Init Debug") - flag.BoolVar(&testUseIoEncDec, "ti", false, "Use IO Reader/Writer for Marshal/Unmarshal") - flag.BoolVar(&testStructToArray, "ts", false, "Set StructToArray option") - flag.BoolVar(&testWriteNoSymbols, "tn", false, "Set NoSymbols option") - flag.BoolVar(&testCanonical, "tc", false, "Set Canonical option") - flag.BoolVar(&testSkipIntf, "tf", false, "Skip Interfaces") -} - -type TestABC struct { - A, B, C string -} - -type TestRpcInt struct { - i int -} - -func (r *TestRpcInt) Update(n int, res *int) error { r.i = n; *res = r.i; return nil } -func (r *TestRpcInt) Square(ignore int, res *int) error { *res = r.i * r.i; return nil } -func (r *TestRpcInt) Mult(n int, res *int) error { *res = r.i * n; return nil } -func (r *TestRpcInt) EchoStruct(arg TestABC, res *string) error { - *res = fmt.Sprintf("%#v", arg) - return nil -} -func (r *TestRpcInt) Echo123(args []string, res *string) error { - *res = fmt.Sprintf("%#v", args) - return nil -} - -type testUnixNanoTimeExt struct{} - -func (x testUnixNanoTimeExt) WriteExt(interface{}) []byte { panic("unsupported") } -func (x testUnixNanoTimeExt) ReadExt(interface{}, []byte) { panic("unsupported") } -func (x testUnixNanoTimeExt) ConvertExt(v interface{}) interface{} { - switch v2 := v.(type) { - case time.Time: - return v2.UTC().UnixNano() - case *time.Time: - return v2.UTC().UnixNano() - default: - panic(fmt.Sprintf("unsupported format for time conversion: expecting time.Time; got %T", v)) - } -} -func (x testUnixNanoTimeExt) UpdateExt(dest interface{}, v interface{}) { - // fmt.Printf("testUnixNanoTimeExt.UpdateExt: v: %v\n", v) - tt := dest.(*time.Time) - switch v2 := v.(type) { - case int64: - *tt = time.Unix(0, v2).UTC() - case uint64: - *tt = time.Unix(0, int64(v2)).UTC() - //case float64: - //case string: - default: - panic(fmt.Sprintf("unsupported format for time conversion: expecting int64/uint64; got %T", v)) - } - // fmt.Printf("testUnixNanoTimeExt.UpdateExt: v: %v, tt: %#v\n", v, tt) -} - -func testVerifyVal(v interface{}, arg testVerifyArg) (v2 interface{}) { - //for python msgpack, - // - all positive integers are unsigned 64-bit ints - // - all floats are float64 - switch iv := v.(type) { - case int8: - if iv >= 0 { - v2 = uint64(iv) - } else { - v2 = int64(iv) - } - case int16: - if iv >= 0 { - v2 = uint64(iv) - } else { - v2 = int64(iv) - } - case int32: - if iv >= 0 { - v2 = uint64(iv) - } else { - v2 = int64(iv) - } - case int64: - if iv >= 0 { - v2 = uint64(iv) - } else { - v2 = int64(iv) - } - case uint8: - v2 = uint64(iv) - case uint16: - v2 = uint64(iv) - case uint32: - v2 = uint64(iv) - case uint64: - v2 = uint64(iv) - case float32: - v2 = float64(iv) - case float64: - v2 = float64(iv) - case []interface{}: - m2 := make([]interface{}, len(iv)) - for j, vj := range iv { - m2[j] = testVerifyVal(vj, arg) - } - v2 = m2 - case map[string]bool: - switch arg { - case testVerifyMapTypeSame: - m2 := make(map[string]bool) - for kj, kv := range iv { - m2[kj] = kv - } - v2 = m2 - case testVerifyMapTypeStrIntf, testVerifyForPython: - m2 := make(map[string]interface{}) - for kj, kv := range iv { - m2[kj] = kv - } - v2 = m2 - case testVerifyMapTypeIntfIntf: - m2 := make(map[interface{}]interface{}) - for kj, kv := range iv { - m2[kj] = kv - } - v2 = m2 - } - case map[string]interface{}: - switch arg { - case testVerifyMapTypeSame: - m2 := make(map[string]interface{}) - for kj, kv := range iv { - m2[kj] = testVerifyVal(kv, arg) - } - v2 = m2 - case testVerifyMapTypeStrIntf, testVerifyForPython: - m2 := make(map[string]interface{}) - for kj, kv := range iv { - m2[kj] = testVerifyVal(kv, arg) - } - v2 = m2 - case testVerifyMapTypeIntfIntf: - m2 := make(map[interface{}]interface{}) - for kj, kv := range iv { - m2[kj] = testVerifyVal(kv, arg) - } - v2 = m2 - } - case map[interface{}]interface{}: - m2 := make(map[interface{}]interface{}) - for kj, kv := range iv { - m2[testVerifyVal(kj, arg)] = testVerifyVal(kv, arg) - } - v2 = m2 - case time.Time: - switch arg { - case testVerifyForPython: - if iv2 := iv.UnixNano(); iv2 >= 0 { - v2 = uint64(iv2) - } else { - v2 = int64(iv2) - } - default: - v2 = v - } - default: - v2 = v - } - return -} - -func testInit() { - gob.Register(new(TestStruc)) - if testInitDebug { - ts0 := newTestStruc(2, false, !testSkipIntf, false) - fmt.Printf("====> depth: %v, ts: %#v\n", 2, ts0) - } - - testJsonH.Canonical = testCanonical - testCborH.Canonical = testCanonical - testSimpleH.Canonical = testCanonical - testBincH.Canonical = testCanonical - testMsgpackH.Canonical = testCanonical - - testJsonH.StructToArray = testStructToArray - testCborH.StructToArray = testStructToArray - testSimpleH.StructToArray = testStructToArray - testBincH.StructToArray = testStructToArray - testMsgpackH.StructToArray = testStructToArray - - testMsgpackH.RawToString = true - - if testWriteNoSymbols { - testBincH.AsSymbols = AsSymbolNone - } else { - testBincH.AsSymbols = AsSymbolAll - } - - // testMsgpackH.AddExt(byteSliceTyp, 0, testMsgpackH.BinaryEncodeExt, testMsgpackH.BinaryDecodeExt) - // testMsgpackH.AddExt(timeTyp, 1, testMsgpackH.TimeEncodeExt, testMsgpackH.TimeDecodeExt) - timeEncExt := func(rv reflect.Value) (bs []byte, err error) { - switch v2 := rv.Interface().(type) { - case time.Time: - bs = encodeTime(v2) - case *time.Time: - bs = encodeTime(*v2) - default: - err = fmt.Errorf("unsupported format for time conversion: expecting time.Time; got %T", v2) - } - return - } - timeDecExt := func(rv reflect.Value, bs []byte) (err error) { - tt, err := decodeTime(bs) - if err == nil { - *(rv.Interface().(*time.Time)) = tt - } - return - } - - // add extensions for msgpack, simple for time.Time, so we can encode/decode same way. - testMsgpackH.AddExt(timeTyp, 1, timeEncExt, timeDecExt) - testSimpleH.AddExt(timeTyp, 1, timeEncExt, timeDecExt) - testCborH.SetExt(timeTyp, 1, &testUnixNanoTimeExt{}) - testJsonH.SetExt(timeTyp, 1, &testUnixNanoTimeExt{}) - - primitives := []interface{}{ - int8(-8), - int16(-1616), - int32(-32323232), - int64(-6464646464646464), - uint8(192), - uint16(1616), - uint32(32323232), - uint64(6464646464646464), - byte(192), - float32(-3232.0), - float64(-6464646464.0), - float32(3232.0), - float64(6464646464.0), - false, - true, - nil, - "someday", - "", - "bytestring", - timeToCompare1, - timeToCompare2, - timeToCompare3, - timeToCompare4, - } - mapsAndStrucs := []interface{}{ - map[string]bool{ - "true": true, - "false": false, - }, - map[string]interface{}{ - "true": "True", - "false": false, - "uint16(1616)": uint16(1616), - }, - //add a complex combo map in here. (map has list which has map) - //note that after the first thing, everything else should be generic. - map[string]interface{}{ - "list": []interface{}{ - int16(1616), - int32(32323232), - true, - float32(-3232.0), - map[string]interface{}{ - "TRUE": true, - "FALSE": false, - }, - []interface{}{true, false}, - }, - "int32": int32(32323232), - "bool": true, - "LONG STRING": "123456789012345678901234567890123456789012345678901234567890", - "SHORT STRING": "1234567890", - }, - map[interface{}]interface{}{ - true: "true", - uint8(138): false, - "false": uint8(200), - }, - newTestStruc(0, false, !testSkipIntf, false), - } - - table = []interface{}{} - table = append(table, primitives...) //0-19 are primitives - table = append(table, primitives) //20 is a list of primitives - table = append(table, mapsAndStrucs...) //21-24 are maps. 25 is a *struct - - tableVerify = make([]interface{}, len(table)) - tableTestNilVerify = make([]interface{}, len(table)) - tablePythonVerify = make([]interface{}, len(table)) - - lp := len(primitives) - av := tableVerify - for i, v := range table { - if i == lp+3 { - av[i] = skipVerifyVal - continue - } - //av[i] = testVerifyVal(v, testVerifyMapTypeSame) - switch v.(type) { - case []interface{}: - av[i] = testVerifyVal(v, testVerifyMapTypeSame) - case map[string]interface{}: - av[i] = testVerifyVal(v, testVerifyMapTypeSame) - case map[interface{}]interface{}: - av[i] = testVerifyVal(v, testVerifyMapTypeSame) - default: - av[i] = v - } - } - - av = tableTestNilVerify - for i, v := range table { - if i > lp+3 { - av[i] = skipVerifyVal - continue - } - av[i] = testVerifyVal(v, testVerifyMapTypeStrIntf) - } - - av = tablePythonVerify - for i, v := range table { - if i > lp+3 { - av[i] = skipVerifyVal - continue - } - av[i] = testVerifyVal(v, testVerifyForPython) - } - - tablePythonVerify = tablePythonVerify[:24] -} - -func testUnmarshal(v interface{}, data []byte, h Handle) (err error) { - if testUseIoEncDec { - NewDecoder(bytes.NewBuffer(data), h).MustDecode(v) - } else { - NewDecoderBytes(data, h).MustDecode(v) - } - return -} - -func testMarshal(v interface{}, h Handle) (bs []byte, err error) { - if testUseIoEncDec { - var buf bytes.Buffer - NewEncoder(&buf, h).MustEncode(v) - bs = buf.Bytes() - return - } - NewEncoderBytes(&bs, h).MustEncode(v) - return -} - -func testMarshalErr(v interface{}, h Handle, t *testing.T, name string) (bs []byte, err error) { - if bs, err = testMarshal(v, h); err != nil { - logT(t, "Error encoding %s: %v, Err: %v", name, v, err) - t.FailNow() - } - return -} - -func testUnmarshalErr(v interface{}, data []byte, h Handle, t *testing.T, name string) (err error) { - if err = testUnmarshal(v, data, h); err != nil { - logT(t, "Error Decoding into %s: %v, Err: %v", name, v, err) - t.FailNow() - } - return -} - -// doTestCodecTableOne allows us test for different variations based on arguments passed. -func doTestCodecTableOne(t *testing.T, testNil bool, h Handle, - vs []interface{}, vsVerify []interface{}) { - //if testNil, then just test for when a pointer to a nil interface{} is passed. It should work. - //Current setup allows us test (at least manually) the nil interface or typed interface. - logT(t, "================ TestNil: %v ================\n", testNil) - for i, v0 := range vs { - logT(t, "..............................................") - logT(t, " Testing: #%d:, %T, %#v\n", i, v0, v0) - b0, err := testMarshalErr(v0, h, t, "v0") - if err != nil { - continue - } - if h.isBinary() { - logT(t, " Encoded bytes: len: %v, %v\n", len(b0), b0) - } else { - logT(t, " Encoded string: len: %v, %v\n", len(string(b0)), string(b0)) - // println("########### encoded string: " + string(b0)) - } - var v1 interface{} - - if testNil { - err = testUnmarshal(&v1, b0, h) - } else { - if v0 != nil { - v0rt := reflect.TypeOf(v0) // ptr - rv1 := reflect.New(v0rt) - err = testUnmarshal(rv1.Interface(), b0, h) - v1 = rv1.Elem().Interface() - // v1 = reflect.Indirect(reflect.ValueOf(v1)).Interface() - } - } - - logT(t, " v1 returned: %T, %#v", v1, v1) - // if v1 != nil { - // logT(t, " v1 returned: %T, %#v", v1, v1) - // //we always indirect, because ptr to typed value may be passed (if not testNil) - // v1 = reflect.Indirect(reflect.ValueOf(v1)).Interface() - // } - if err != nil { - logT(t, "-------- Error: %v. Partial return: %v", err, v1) - failT(t) - continue - } - v0check := vsVerify[i] - if v0check == skipVerifyVal { - logT(t, " Nil Check skipped: Decoded: %T, %#v\n", v1, v1) - continue - } - - if err = deepEqual(v0check, v1); err == nil { - logT(t, "++++++++ Before and After marshal matched\n") - } else { - // logT(t, "-------- Before and After marshal do not match: Error: %v"+ - // " ====> GOLDEN: (%T) %#v, DECODED: (%T) %#v\n", err, v0check, v0check, v1, v1) - logT(t, "-------- Before and After marshal do not match: Error: %v", err) - logT(t, " ....... GOLDEN: (%T) %#v", v0check, v0check) - logT(t, " ....... DECODED: (%T) %#v", v1, v1) - failT(t) - } - } -} - -func testCodecTableOne(t *testing.T, h Handle) { - testOnce.Do(testInitAll) - // func TestMsgpackAllExperimental(t *testing.T) { - // dopts := testDecOpts(nil, nil, false, true, true), - - idxTime, numPrim, numMap := 19, 23, 4 - //println("#################") - switch v := h.(type) { - case *MsgpackHandle: - var oldWriteExt, oldRawToString bool - oldWriteExt, v.WriteExt = v.WriteExt, true - oldRawToString, v.RawToString = v.RawToString, true - doTestCodecTableOne(t, false, h, table, tableVerify) - v.WriteExt, v.RawToString = oldWriteExt, oldRawToString - case *JsonHandle: - //skip []interface{} containing time.Time, as it encodes as a number, but cannot decode back to time.Time. - //As there is no real support for extension tags in json, this must be skipped. - doTestCodecTableOne(t, false, h, table[:numPrim], tableVerify[:numPrim]) - doTestCodecTableOne(t, false, h, table[numPrim+1:], tableVerify[numPrim+1:]) - default: - doTestCodecTableOne(t, false, h, table, tableVerify) - } - // func TestMsgpackAll(t *testing.T) { - - // //skip []interface{} containing time.Time - // doTestCodecTableOne(t, false, h, table[:numPrim], tableVerify[:numPrim]) - // doTestCodecTableOne(t, false, h, table[numPrim+1:], tableVerify[numPrim+1:]) - // func TestMsgpackNilStringMap(t *testing.T) { - var oldMapType reflect.Type - v := h.getBasicHandle() - - oldMapType, v.MapType = v.MapType, testMapStrIntfTyp - - //skip time.Time, []interface{} containing time.Time, last map, and newStruc - doTestCodecTableOne(t, true, h, table[:idxTime], tableTestNilVerify[:idxTime]) - doTestCodecTableOne(t, true, h, table[numPrim+1:numPrim+numMap], tableTestNilVerify[numPrim+1:numPrim+numMap]) - - v.MapType = oldMapType - - // func TestMsgpackNilIntf(t *testing.T) { - - //do newTestStruc and last element of map - doTestCodecTableOne(t, true, h, table[numPrim+numMap:], tableTestNilVerify[numPrim+numMap:]) - //TODO? What is this one? - //doTestCodecTableOne(t, true, h, table[17:18], tableTestNilVerify[17:18]) -} - -func testCodecMiscOne(t *testing.T, h Handle) { - testOnce.Do(testInitAll) - b, err := testMarshalErr(32, h, t, "32") - // Cannot do this nil one, because faster type assertion decoding will panic - // var i *int32 - // if err = testUnmarshal(b, i, nil); err == nil { - // logT(t, "------- Expecting error because we cannot unmarshal to int32 nil ptr") - // t.FailNow() - // } - var i2 int32 = 0 - err = testUnmarshalErr(&i2, b, h, t, "int32-ptr") - if i2 != int32(32) { - logT(t, "------- didn't unmarshal to 32: Received: %d", i2) - t.FailNow() - } - - // func TestMsgpackDecodePtr(t *testing.T) { - ts := newTestStruc(0, false, !testSkipIntf, false) - b, err = testMarshalErr(ts, h, t, "pointer-to-struct") - if len(b) < 40 { - logT(t, "------- Size must be > 40. Size: %d", len(b)) - t.FailNow() - } - if h.isBinary() { - logT(t, "------- b: %v", b) - } else { - logT(t, "------- b: %s", b) - } - ts2 := new(TestStruc) - err = testUnmarshalErr(ts2, b, h, t, "pointer-to-struct") - if ts2.I64 != math.MaxInt64*2/3 { - logT(t, "------- Unmarshal wrong. Expect I64 = 64. Got: %v", ts2.I64) - t.FailNow() - } - - // func TestMsgpackIntfDecode(t *testing.T) { - m := map[string]int{"A": 2, "B": 3} - p := []interface{}{m} - bs, err := testMarshalErr(p, h, t, "p") - - m2 := map[string]int{} - p2 := []interface{}{m2} - err = testUnmarshalErr(&p2, bs, h, t, "&p2") - - if m2["A"] != 2 || m2["B"] != 3 { - logT(t, "m2 not as expected: expecting: %v, got: %v", m, m2) - t.FailNow() - } - // log("m: %v, m2: %v, p: %v, p2: %v", m, m2, p, p2) - checkEqualT(t, p, p2, "p=p2") - checkEqualT(t, m, m2, "m=m2") - if err = deepEqual(p, p2); err == nil { - logT(t, "p and p2 match") - } else { - logT(t, "Not Equal: %v. p: %v, p2: %v", err, p, p2) - t.FailNow() - } - if err = deepEqual(m, m2); err == nil { - logT(t, "m and m2 match") - } else { - logT(t, "Not Equal: %v. m: %v, m2: %v", err, m, m2) - t.FailNow() - } - - // func TestMsgpackDecodeStructSubset(t *testing.T) { - // test that we can decode a subset of the stream - mm := map[string]interface{}{"A": 5, "B": 99, "C": 333} - bs, err = testMarshalErr(mm, h, t, "mm") - type ttt struct { - A uint8 - C int32 - } - var t2 ttt - testUnmarshalErr(&t2, bs, h, t, "t2") - t3 := ttt{5, 333} - checkEqualT(t, t2, t3, "t2=t3") - - // println(">>>>>") - // test simple arrays, non-addressable arrays, slices - type tarr struct { - A int64 - B [3]int64 - C []byte - D [3]byte - } - var tarr0 = tarr{1, [3]int64{2, 3, 4}, []byte{4, 5, 6}, [3]byte{7, 8, 9}} - // test both pointer and non-pointer (value) - for _, tarr1 := range []interface{}{tarr0, &tarr0} { - bs, err = testMarshalErr(tarr1, h, t, "tarr1") - var tarr2 tarr - testUnmarshalErr(&tarr2, bs, h, t, "tarr2") - checkEqualT(t, tarr0, tarr2, "tarr0=tarr2") - // fmt.Printf(">>>> err: %v. tarr1: %v, tarr2: %v\n", err, tarr0, tarr2) - } - - // test byte array, even if empty (msgpack only) - if h == testMsgpackH { - type ystruct struct { - Anarray []byte - } - var ya = ystruct{} - testUnmarshalErr(&ya, []byte{0x91, 0x90}, h, t, "ya") - } -} - -func testCodecEmbeddedPointer(t *testing.T, h Handle) { - testOnce.Do(testInitAll) - type Z int - type A struct { - AnInt int - } - type B struct { - *Z - *A - MoreInt int - } - var z Z = 4 - x1 := &B{&z, &A{5}, 6} - bs, err := testMarshalErr(x1, h, t, "x1") - // fmt.Printf("buf: len(%v): %x\n", buf.Len(), buf.Bytes()) - var x2 = new(B) - err = testUnmarshalErr(x2, bs, h, t, "x2") - err = checkEqualT(t, x1, x2, "x1=x2") - _ = err -} - -func testCodecUnderlyingType(t *testing.T, h Handle) { - testOnce.Do(testInitAll) - // Manual Test. - // Run by hand, with accompanying print statements in fast-path.go - // to ensure that the fast functions are called. - type T1 map[string]string - v := T1{"1": "1s", "2": "2s"} - var bs []byte - var err error - NewEncoderBytes(&bs, h).MustEncode(v) - if err != nil { - logT(t, "Error during encode: %v", err) - failT(t) - } - var v2 T1 - NewDecoderBytes(bs, h).MustDecode(&v2) - if err != nil { - logT(t, "Error during decode: %v", err) - failT(t) - } -} - -func testCodecChan(t *testing.T, h Handle) { - // - send a slice []*int64 (sl1) into an chan (ch1) with cap > len(s1) - // - encode ch1 as a stream array - // - decode a chan (ch2), with cap > len(s1) from the stream array - // - receive from ch2 into slice sl2 - // - compare sl1 and sl2 - // - do this for codecs: json, cbor (covers all types) - sl1 := make([]*int64, 4) - for i := range sl1 { - var j int64 = int64(i) - sl1[i] = &j - } - ch1 := make(chan *int64, 4) - for _, j := range sl1 { - ch1 <- j - } - var bs []byte - NewEncoderBytes(&bs, h).MustEncode(ch1) - // if !h.isBinary() { - // fmt.Printf("before: len(ch1): %v, bs: %s\n", len(ch1), bs) - // } - // var ch2 chan *int64 // this will block if json, etc. - ch2 := make(chan *int64, 8) - NewDecoderBytes(bs, h).MustDecode(&ch2) - // logT(t, "Len(ch2): %v", len(ch2)) - // fmt.Printf("after: len(ch2): %v, ch2: %v\n", len(ch2), ch2) - close(ch2) - var sl2 []*int64 - for j := range ch2 { - sl2 = append(sl2, j) - } - if err := deepEqual(sl1, sl2); err != nil { - logT(t, "Not Match: %v; len: %v, %v", err, len(sl1), len(sl2)) - failT(t) - } -} - -func testCodecRpcOne(t *testing.T, rr Rpc, h Handle, doRequest bool, exitSleepMs time.Duration, -) (port int) { - testOnce.Do(testInitAll) - if testSkipRPCTests { - return - } - // rpc needs EOF, which is sent via a panic, and so must be recovered. - if !recoverPanicToErr { - logT(t, "EXPECTED. set recoverPanicToErr=true, since rpc needs EOF") - t.FailNow() - } - srv := rpc.NewServer() - srv.Register(testRpcInt) - ln, err := net.Listen("tcp", "127.0.0.1:0") - // log("listener: %v", ln.Addr()) - checkErrT(t, err) - port = (ln.Addr().(*net.TCPAddr)).Port - // var opts *DecoderOptions - // opts := testDecOpts - // opts.MapType = mapStrIntfTyp - // opts.RawToString = false - serverExitChan := make(chan bool, 1) - var serverExitFlag uint64 = 0 - serverFn := func() { - for { - conn1, err1 := ln.Accept() - // if err1 != nil { - // //fmt.Printf("accept err1: %v\n", err1) - // continue - // } - if atomic.LoadUint64(&serverExitFlag) == 1 { - serverExitChan <- true - conn1.Close() - return // exit serverFn goroutine - } - if err1 == nil { - var sc rpc.ServerCodec = rr.ServerCodec(conn1, h) - srv.ServeCodec(sc) - } - } - } - - clientFn := func(cc rpc.ClientCodec) { - cl := rpc.NewClientWithCodec(cc) - defer cl.Close() - // defer func() { println("##### client closing"); cl.Close() }() - var up, sq, mult int - var rstr string - // log("Calling client") - checkErrT(t, cl.Call("TestRpcInt.Update", 5, &up)) - // log("Called TestRpcInt.Update") - checkEqualT(t, testRpcInt.i, 5, "testRpcInt.i=5") - checkEqualT(t, up, 5, "up=5") - checkErrT(t, cl.Call("TestRpcInt.Square", 1, &sq)) - checkEqualT(t, sq, 25, "sq=25") - checkErrT(t, cl.Call("TestRpcInt.Mult", 20, &mult)) - checkEqualT(t, mult, 100, "mult=100") - checkErrT(t, cl.Call("TestRpcInt.EchoStruct", TestABC{"Aa", "Bb", "Cc"}, &rstr)) - checkEqualT(t, rstr, fmt.Sprintf("%#v", TestABC{"Aa", "Bb", "Cc"}), "rstr=") - checkErrT(t, cl.Call("TestRpcInt.Echo123", []string{"A1", "B2", "C3"}, &rstr)) - checkEqualT(t, rstr, fmt.Sprintf("%#v", []string{"A1", "B2", "C3"}), "rstr=") - } - - connFn := func() (bs net.Conn) { - // log("calling f1") - bs, err2 := net.Dial(ln.Addr().Network(), ln.Addr().String()) - //fmt.Printf("f1. bs: %v, err2: %v\n", bs, err2) - checkErrT(t, err2) - return - } - - exitFn := func() { - atomic.StoreUint64(&serverExitFlag, 1) - bs := connFn() - <-serverExitChan - bs.Close() - // serverExitChan <- true - } - - go serverFn() - runtime.Gosched() - //time.Sleep(100 * time.Millisecond) - if exitSleepMs == 0 { - defer ln.Close() - defer exitFn() - } - if doRequest { - bs := connFn() - cc := rr.ClientCodec(bs, h) - clientFn(cc) - } - if exitSleepMs != 0 { - go func() { - defer ln.Close() - time.Sleep(exitSleepMs) - exitFn() - }() - } - return -} - -// Comprehensive testing that generates data encoded from python handle (cbor, msgpack), -// and validates that our code can read and write it out accordingly. -// We keep this unexported here, and put actual test in ext_dep_test.go. -// This way, it can be excluded by excluding file completely. -func doTestPythonGenStreams(t *testing.T, name string, h Handle) { - logT(t, "TestPythonGenStreams-%v", name) - tmpdir, err := ioutil.TempDir("", "golang-"+name+"-test") - if err != nil { - logT(t, "-------- Unable to create temp directory\n") - t.FailNow() - } - defer os.RemoveAll(tmpdir) - logT(t, "tmpdir: %v", tmpdir) - cmd := exec.Command("python", "test.py", "testdata", tmpdir) - //cmd.Stdin = strings.NewReader("some input") - //cmd.Stdout = &out - var cmdout []byte - if cmdout, err = cmd.CombinedOutput(); err != nil { - logT(t, "-------- Error running test.py testdata. Err: %v", err) - logT(t, " %v", string(cmdout)) - t.FailNow() - } - - bh := h.getBasicHandle() - - oldMapType := bh.MapType - for i, v := range tablePythonVerify { - // if v == uint64(0) && h == testMsgpackH { - // v = int64(0) - // } - bh.MapType = oldMapType - //load up the golden file based on number - //decode it - //compare to in-mem object - //encode it again - //compare to output stream - logT(t, "..............................................") - logT(t, " Testing: #%d: %T, %#v\n", i, v, v) - var bss []byte - bss, err = ioutil.ReadFile(filepath.Join(tmpdir, strconv.Itoa(i)+"."+name+".golden")) - if err != nil { - logT(t, "-------- Error reading golden file: %d. Err: %v", i, err) - failT(t) - continue - } - bh.MapType = testMapStrIntfTyp - - var v1 interface{} - if err = testUnmarshal(&v1, bss, h); err != nil { - logT(t, "-------- Error decoding stream: %d: Err: %v", i, err) - failT(t) - continue - } - if v == skipVerifyVal { - continue - } - //no need to indirect, because we pass a nil ptr, so we already have the value - //if v1 != nil { v1 = reflect.Indirect(reflect.ValueOf(v1)).Interface() } - if err = deepEqual(v, v1); err == nil { - logT(t, "++++++++ Objects match: %T, %v", v, v) - } else { - logT(t, "-------- Objects do not match: %v. Source: %T. Decoded: %T", err, v, v1) - logT(t, "-------- GOLDEN: %#v", v) - // logT(t, "-------- DECODED: %#v <====> %#v", v1, reflect.Indirect(reflect.ValueOf(v1)).Interface()) - logT(t, "-------- DECODED: %#v <====> %#v", v1, reflect.Indirect(reflect.ValueOf(v1)).Interface()) - failT(t) - } - bsb, err := testMarshal(v1, h) - if err != nil { - logT(t, "Error encoding to stream: %d: Err: %v", i, err) - failT(t) - continue - } - if err = deepEqual(bsb, bss); err == nil { - logT(t, "++++++++ Bytes match") - } else { - logT(t, "???????? Bytes do not match. %v.", err) - xs := "--------" - if reflect.ValueOf(v).Kind() == reflect.Map { - xs = " " - logT(t, "%s It's a map. Ok that they don't match (dependent on ordering).", xs) - } else { - logT(t, "%s It's not a map. They should match.", xs) - failT(t) - } - logT(t, "%s FROM_FILE: %4d] %v", xs, len(bss), bss) - logT(t, "%s ENCODED: %4d] %v", xs, len(bsb), bsb) - } - } - bh.MapType = oldMapType -} - -// To test MsgpackSpecRpc, we test 3 scenarios: -// - Go Client to Go RPC Service (contained within TestMsgpackRpcSpec) -// - Go client to Python RPC Service (contained within doTestMsgpackRpcSpecGoClientToPythonSvc) -// - Python Client to Go RPC Service (contained within doTestMsgpackRpcSpecPythonClientToGoSvc) -// -// This allows us test the different calling conventions -// - Go Service requires only one argument -// - Python Service allows multiple arguments - -func doTestMsgpackRpcSpecGoClientToPythonSvc(t *testing.T) { - if testSkipRPCTests { - return - } - openPort := "6789" - cmd := exec.Command("python", "test.py", "rpc-server", openPort, "2") - checkErrT(t, cmd.Start()) - time.Sleep(100 * time.Millisecond) // time for python rpc server to start - bs, err2 := net.Dial("tcp", ":"+openPort) - checkErrT(t, err2) - cc := MsgpackSpecRpc.ClientCodec(bs, testMsgpackH) - cl := rpc.NewClientWithCodec(cc) - defer cl.Close() - var rstr string - checkErrT(t, cl.Call("EchoStruct", TestABC{"Aa", "Bb", "Cc"}, &rstr)) - //checkEqualT(t, rstr, "{'A': 'Aa', 'B': 'Bb', 'C': 'Cc'}") - var mArgs MsgpackSpecRpcMultiArgs = []interface{}{"A1", "B2", "C3"} - checkErrT(t, cl.Call("Echo123", mArgs, &rstr)) - checkEqualT(t, rstr, "1:A1 2:B2 3:C3", "rstr=") -} - -func doTestMsgpackRpcSpecPythonClientToGoSvc(t *testing.T) { - if testSkipRPCTests { - return - } - port := testCodecRpcOne(t, MsgpackSpecRpc, testMsgpackH, false, 1*time.Second) - //time.Sleep(1000 * time.Millisecond) - cmd := exec.Command("python", "test.py", "rpc-client-go-service", strconv.Itoa(port)) - var cmdout []byte - var err error - if cmdout, err = cmd.CombinedOutput(); err != nil { - logT(t, "-------- Error running test.py rpc-client-go-service. Err: %v", err) - logT(t, " %v", string(cmdout)) - t.FailNow() - } - checkEqualT(t, string(cmdout), - fmt.Sprintf("%#v\n%#v\n", []string{"A1", "B2", "C3"}, TestABC{"Aa", "Bb", "Cc"}), "cmdout=") -} - -func TestBincCodecsTable(t *testing.T) { - testCodecTableOne(t, testBincH) -} - -func TestBincCodecsMisc(t *testing.T) { - testCodecMiscOne(t, testBincH) -} - -func TestBincCodecsEmbeddedPointer(t *testing.T) { - testCodecEmbeddedPointer(t, testBincH) -} - -func TestSimpleCodecsTable(t *testing.T) { - testCodecTableOne(t, testSimpleH) -} - -func TestSimpleCodecsMisc(t *testing.T) { - testCodecMiscOne(t, testSimpleH) -} - -func TestSimpleCodecsEmbeddedPointer(t *testing.T) { - testCodecEmbeddedPointer(t, testSimpleH) -} - -func TestMsgpackCodecsTable(t *testing.T) { - testCodecTableOne(t, testMsgpackH) -} - -func TestMsgpackCodecsMisc(t *testing.T) { - testCodecMiscOne(t, testMsgpackH) -} - -func TestMsgpackCodecsEmbeddedPointer(t *testing.T) { - testCodecEmbeddedPointer(t, testMsgpackH) -} - -func TestCborCodecsTable(t *testing.T) { - testCodecTableOne(t, testCborH) -} - -func TestCborCodecsMisc(t *testing.T) { - testCodecMiscOne(t, testCborH) -} - -func TestCborCodecsEmbeddedPointer(t *testing.T) { - testCodecEmbeddedPointer(t, testCborH) -} - -func TestJsonCodecsTable(t *testing.T) { - testCodecTableOne(t, testJsonH) -} - -func TestJsonCodecsMisc(t *testing.T) { - testCodecMiscOne(t, testJsonH) -} - -func TestJsonCodecsEmbeddedPointer(t *testing.T) { - testCodecEmbeddedPointer(t, testJsonH) -} - -func TestJsonCodecChan(t *testing.T) { - testCodecChan(t, testJsonH) -} - -func TestCborCodecChan(t *testing.T) { - testCodecChan(t, testCborH) -} - -// ----- RPC ----- - -func TestBincRpcGo(t *testing.T) { - testCodecRpcOne(t, GoRpc, testBincH, true, 0) -} - -func TestSimpleRpcGo(t *testing.T) { - testCodecRpcOne(t, GoRpc, testSimpleH, true, 0) -} - -func TestMsgpackRpcGo(t *testing.T) { - testCodecRpcOne(t, GoRpc, testMsgpackH, true, 0) -} - -func TestCborRpcGo(t *testing.T) { - testCodecRpcOne(t, GoRpc, testCborH, true, 0) -} - -func TestJsonRpcGo(t *testing.T) { - testCodecRpcOne(t, GoRpc, testJsonH, true, 0) -} - -func TestMsgpackRpcSpec(t *testing.T) { - testCodecRpcOne(t, MsgpackSpecRpc, testMsgpackH, true, 0) -} - -func TestBincUnderlyingType(t *testing.T) { - testCodecUnderlyingType(t, testBincH) -} - -// TODO: -// Add Tests for: -// - decoding empty list/map in stream into a nil slice/map -// - binary(M|Unm)arsher support for time.Time (e.g. cbor encoding) -// - text(M|Unm)arshaler support for time.Time (e.g. json encoding) -// - non fast-path scenarios e.g. map[string]uint16, []customStruct. -// Expand cbor to include indefinite length stuff for this non-fast-path types. -// This may not be necessary, since we have the manual tests (fastpathEnabled=false) to test/validate with. -// - CodecSelfer -// Ensure it is called when (en|de)coding interface{} or reflect.Value (2 different codepaths). -// - interfaces: textMarshaler, binaryMarshaler, codecSelfer -// - struct tags: -// on anonymous fields, _struct (all fields), etc -// - codecgen of struct containing channels. -// -// Cleanup tests: -// - The are brittle in their handling of validation and skipping diff --git a/Godeps/_workspace/src/github.com/ugorji/go/codec/codecgen/gen.go b/Godeps/_workspace/src/github.com/ugorji/go/codec/codecgen/gen.go index 892df598f..8f4264356 100644 --- a/Godeps/_workspace/src/github.com/ugorji/go/codec/codecgen/gen.go +++ b/Godeps/_workspace/src/github.com/ugorji/go/codec/codecgen/gen.go @@ -14,6 +14,7 @@ import ( "go/build" "go/parser" "go/token" + "math/rand" "os" "os/exec" "path/filepath" @@ -23,6 +24,8 @@ import ( "time" ) +const genCodecPkg = "codec1978" // keep this in sync with codec.genCodecPkg + const genFrunMainTmpl = `//+build ignore package main @@ -69,7 +72,7 @@ func CodecGenTempWrite{{ .RandString }}() { var t{{ $index }} {{ . }} typs = append(typs, reflect.TypeOf(t{{ $index }})) {{ end }} - {{ if not .CodecPkgFiles }}{{ .CodecPkgName }}.{{ end }}Gen(&out, "{{ .BuildTag }}", "{{ .PackageName }}", {{ .UseUnsafe }}, typs...) + {{ if not .CodecPkgFiles }}{{ .CodecPkgName }}.{{ end }}Gen(&out, "{{ .BuildTag }}", "{{ .PackageName }}", "{{ .RandString }}", {{ .UseUnsafe }}, typs...) bout, err := format.Source(out.Bytes()) if err != nil { fout.Write(out.Bytes()) @@ -89,7 +92,7 @@ func CodecGenTempWrite{{ .RandString }}() { // Tool then executes: "go run __frun__" which creates fout. // fout contains Codec(En|De)codeSelf implementations for every type T. // -func Generate(outfile, buildTag, codecPkgPath string, useUnsafe bool, goRunTag string, +func Generate(outfile, buildTag, codecPkgPath string, uid int64, useUnsafe bool, goRunTag string, regexName *regexp.Regexp, deleteTempFile bool, infiles ...string) (err error) { // For each file, grab AST, find each type, and write a call to it. if len(infiles) == 0 { @@ -99,6 +102,13 @@ func Generate(outfile, buildTag, codecPkgPath string, useUnsafe bool, goRunTag s err = errors.New("outfile and codec package path cannot be blank") return } + if uid < 0 { + uid = -uid + } + if uid == 0 { + rr := rand.New(rand.NewSource(time.Now().UnixNano())) + uid = 101 + rr.Int63n(9777) + } // We have to parse dir for package, before opening the temp file for writing (else ImportDir fails). // Also, ImportDir(...) must take an absolute path. lastdir := filepath.Dir(outfile) @@ -123,12 +133,12 @@ func Generate(outfile, buildTag, codecPkgPath string, useUnsafe bool, goRunTag s UseUnsafe bool } tv := tmplT{ - CodecPkgName: "codec1978", + CodecPkgName: genCodecPkg, OutFile: outfile, CodecImportPath: codecPkgPath, BuildTag: buildTag, UseUnsafe: useUnsafe, - RandString: strconv.FormatInt(time.Now().UnixNano(), 10), + RandString: strconv.FormatInt(uid, 10), } tv.ImportPath = pkg.ImportPath if tv.ImportPath == tv.CodecImportPath { @@ -261,9 +271,9 @@ func main() { rt := flag.String("rt", "", "tags for go run") x := flag.Bool("x", false, "keep temp file") u := flag.Bool("u", false, "Use unsafe, e.g. to avoid unnecessary allocation on []byte->string") - + d := flag.Int64("d", 0, "random identifier for use in generated code") flag.Parse() - if err := Generate(*o, *t, *c, *u, *rt, + if err := Generate(*o, *t, *c, *d, *u, *rt, regexp.MustCompile(*r), !*x, flag.Args()...); err != nil { fmt.Fprintf(os.Stderr, "codecgen error: %v\n", err) os.Exit(1) diff --git a/Godeps/_workspace/src/github.com/ugorji/go/codec/codecgen_test.go b/Godeps/_workspace/src/github.com/ugorji/go/codec/codecgen_test.go deleted file mode 100644 index 2fdfd161d..000000000 --- a/Godeps/_workspace/src/github.com/ugorji/go/codec/codecgen_test.go +++ /dev/null @@ -1,22 +0,0 @@ -//+build x,codecgen - -package codec - -import ( - "fmt" - "testing" -) - -func TestCodecgenJson1(t *testing.T) { - const callCodecgenDirect bool = true - v := newTestStruc(2, false, !testSkipIntf, false) - var bs []byte - e := NewEncoderBytes(&bs, testJsonH) - if callCodecgenDirect { - v.CodecEncodeSelf(e) - e.w.atEndOfEncode() - } else { - e.MustEncode(v) - } - fmt.Printf("%s\n", bs) -} diff --git a/Godeps/_workspace/src/github.com/ugorji/go/codec/decode.go b/Godeps/_workspace/src/github.com/ugorji/go/codec/decode.go index a2e35d7a1..34eacc6ea 100644 --- a/Godeps/_workspace/src/github.com/ugorji/go/codec/decode.go +++ b/Godeps/_workspace/src/github.com/ugorji/go/codec/decode.go @@ -25,10 +25,6 @@ var ( // decReader abstracts the reading source, allowing implementations that can // read from an io.Reader or directly off a byte slice with zero-copying. type decReader interface { - // TODO: - // Add method to get num bytes read. - // This will be used to annotate errors, so user knows at what point the error occurred. - unreadn1() // readx will use the implementation scratch buffer if possible i.e. n < len(scratchbuf), OR @@ -38,6 +34,9 @@ type decReader interface { readb([]byte) readn1() uint8 readn1eof() (v uint8, eof bool) + numread() int // number of bytes read + track() + stopTrack() []byte } type decReaderByteScanner interface { @@ -79,20 +78,13 @@ type decDriver interface { // decodeExt(verifyTag bool, tag byte) (xtag byte, xbs []byte) ReadMapStart() int ReadArrayStart() int - ReadMapEnd() - ReadArrayEnd() - ReadArrayEntrySeparator() - ReadMapEntrySeparator() - ReadMapKVSeparator() + // ReadEnd registers the end of a map or array. + ReadEnd() } type decNoSeparator struct{} -func (_ decNoSeparator) ReadMapEnd() {} -func (_ decNoSeparator) ReadArrayEnd() {} -func (_ decNoSeparator) ReadArrayEntrySeparator() {} -func (_ decNoSeparator) ReadMapEntrySeparator() {} -func (_ decNoSeparator) ReadMapKVSeparator() {} +func (_ decNoSeparator) ReadEnd() {} type DecodeOptions struct { // MapType specifies type to use during schema-less decoding of a map in the stream. @@ -181,8 +173,15 @@ type ioDecReader struct { br decReaderByteScanner // temp byte array re-used internally for efficiency during read. // shares buffer with Decoder, so we keep size of struct within 8 words. - x *[scratchByteArrayLen]byte - bs ioDecByteScanner + x *[scratchByteArrayLen]byte + bs ioDecByteScanner + n int // num read + tr []byte // tracking bytes read + trb bool +} + +func (z *ioDecReader) numread() int { + return z.n } func (z *ioDecReader) readx(n int) (bs []byte) { @@ -197,6 +196,10 @@ func (z *ioDecReader) readx(n int) (bs []byte) { if _, err := io.ReadAtLeast(z.br, bs, n); err != nil { panic(err) } + z.n += len(bs) + if z.trb { + z.tr = append(z.tr, bs...) + } return } @@ -204,9 +207,14 @@ func (z *ioDecReader) readb(bs []byte) { if len(bs) == 0 { return } - if _, err := io.ReadAtLeast(z.br, bs, len(bs)); err != nil { + n, err := io.ReadAtLeast(z.br, bs, len(bs)) + z.n += n + if err != nil { panic(err) } + if z.trb { + z.tr = append(z.tr, bs...) + } } func (z *ioDecReader) readn1() (b uint8) { @@ -214,12 +222,20 @@ func (z *ioDecReader) readn1() (b uint8) { if err != nil { panic(err) } + z.n++ + if z.trb { + z.tr = append(z.tr, b) + } return b } func (z *ioDecReader) readn1eof() (b uint8, eof bool) { b, err := z.br.ReadByte() if err == nil { + z.n++ + if z.trb { + z.tr = append(z.tr, b) + } } else if err == io.EOF { eof = true } else { @@ -229,9 +245,28 @@ func (z *ioDecReader) readn1eof() (b uint8, eof bool) { } func (z *ioDecReader) unreadn1() { - if err := z.br.UnreadByte(); err != nil { + err := z.br.UnreadByte() + if err != nil { panic(err) } + z.n-- + if z.trb { + if l := len(z.tr) - 1; l >= 0 { + z.tr = z.tr[:l] + } + } +} + +func (z *ioDecReader) track() { + if z.tr != nil { + z.tr = z.tr[:0] + } + z.trb = true +} + +func (z *ioDecReader) stopTrack() (bs []byte) { + z.trb = false + return z.tr } // ------------------------------------ @@ -243,6 +278,11 @@ type bytesDecReader struct { b []byte // data c int // cursor a int // available + t int // track start +} + +func (z *bytesDecReader) numread() int { + return z.c } func (z *bytesDecReader) unreadn1() { @@ -298,6 +338,14 @@ func (z *bytesDecReader) readb(bs []byte) { copy(bs, z.readx(len(bs))) } +func (z *bytesDecReader) track() { + z.t = z.c +} + +func (z *bytesDecReader) stopTrack() (bs []byte) { + return z.b[z.t:z.c] +} + // ------------------------------------ type decFnInfoX struct { @@ -373,14 +421,20 @@ func (f decFnInfo) binaryUnmarshal(rv reflect.Value) { func (f decFnInfo) textUnmarshal(rv reflect.Value) { tm := f.getValueForUnmarshalInterface(rv, f.ti.tunmIndir).(encoding.TextUnmarshaler) fnerr := tm.UnmarshalText(f.dd.DecodeBytes(f.d.b[:], true, true)) - // fnerr := tm.UnmarshalText(f.dd.DecodeStringAsBytes(f.d.b[:])) + if fnerr != nil { + panic(fnerr) + } +} - // var fnerr error - // if sb, sbok := f.dd.(decDriverStringAsBytes); sbok { - // fnerr = tm.UnmarshalText(sb.decStringAsBytes(f.d.b[:0])) - // } else { - // fnerr = tm.UnmarshalText([]byte(f.dd.decodeString())) - // } +func (f decFnInfo) jsonUnmarshal(rv reflect.Value) { + tm := f.getValueForUnmarshalInterface(rv, f.ti.junmIndir).(jsonUnmarshaler) + // bs := f.dd.DecodeBytes(f.d.b[:], true, true) + // grab the bytes to be read, as UnmarshalJSON wants the full JSON to unmarshal it itself. + f.d.r.track() + f.d.swallow() + bs := f.d.r.stopTrack() + // fmt.Printf(">>>>>> REFLECTION JSON: %s\n", bs) + fnerr := tm.UnmarshalJSON(bs) if fnerr != nil { panic(fnerr) } @@ -438,6 +492,10 @@ func (f decFnInfo) kUint(rv reflect.Value) { rv.SetUint(f.dd.DecodeUint(uintBitsize)) } +func (f decFnInfo) kUintptr(rv reflect.Value) { + rv.SetUint(f.dd.DecodeUint(uintBitsize)) +} + func (f decFnInfo) kUint32(rv reflect.Value) { rv.SetUint(f.dd.DecodeUint(32)) } @@ -559,7 +617,7 @@ func (f decFnInfo) kStruct(rv reflect.Value) { if f.dd.IsContainerType(valueTypeMap) { containerLen := f.dd.ReadMapStart() if containerLen == 0 { - f.dd.ReadMapEnd() + f.dd.ReadEnd() return } tisfi := fti.sfi @@ -582,12 +640,8 @@ func (f decFnInfo) kStruct(rv reflect.Value) { } } else { for j := 0; !f.dd.CheckBreak(); j++ { - if j > 0 { - f.dd.ReadMapEntrySeparator() - } // rvkencname := f.dd.DecodeString() rvkencname := stringView(f.dd.DecodeBytes(f.d.b[:], true, true)) - f.dd.ReadMapKVSeparator() // rvksi := ti.getForEncName(rvkencname) if k := fti.indexForEncName(rvkencname); k > -1 { si := tisfi[k] @@ -600,12 +654,12 @@ func (f decFnInfo) kStruct(rv reflect.Value) { d.structFieldNotFound(-1, rvkencname) } } - f.dd.ReadMapEnd() + f.dd.ReadEnd() } } else if f.dd.IsContainerType(valueTypeArray) { containerLen := f.dd.ReadArrayStart() if containerLen == 0 { - f.dd.ReadArrayEnd() + f.dd.ReadEnd() return } // Not much gain from doing it two ways for array. @@ -619,30 +673,19 @@ func (f decFnInfo) kStruct(rv reflect.Value) { } else if f.dd.CheckBreak() { break } - if j > 0 { - f.dd.ReadArrayEntrySeparator() - } if f.dd.TryDecodeAsNil() { si.setToZeroValue(rv) } else { d.decodeValue(si.field(rv, true), decFn{}) } - // if si.i != -1 { - // d.decodeValue(rv.Field(int(si.i)), decFn{}) - // } else { - // d.decEmbeddedField(rv, si.is) - // } } if containerLen > len(fti.sfip) { // read remaining values and throw away for j := len(fti.sfip); j < containerLen; j++ { - if j > 0 { - f.dd.ReadArrayEntrySeparator() - } d.structFieldNotFound(j, "") } } - f.dd.ReadArrayEnd() + f.dd.ReadEnd() } else { f.d.error(onlyMapOrArrayCanDecodeIntoStructErr) return @@ -704,7 +747,7 @@ func (f decFnInfo) kSlice(rv reflect.Value) { if f.seq == seqTypeSlice && rvlen != 0 { rv.SetLen(0) } - // slh.End() // f.dd.ReadArrayEnd() + // f.dd.ReadEnd() return } @@ -777,9 +820,6 @@ func (f decFnInfo) kSlice(rv reflect.Value) { rvChanged = true } } - if j > 0 { - slh.Sep(j) - } if f.seq == seqTypeChan { rv0 := reflect.New(rtelem0).Elem() d.decodeValue(rv0, fn) @@ -812,6 +852,7 @@ func (f decFnInfo) kMap(rv reflect.Value) { } if containerLen == 0 { + // It is not length-prefix style container. They have no End marker. // f.dd.ReadMapEnd() return } @@ -851,9 +892,6 @@ func (f decFnInfo) kMap(rv reflect.Value) { } } else { for j := 0; !f.dd.CheckBreak(); j++ { - if j > 0 { - f.dd.ReadMapEntrySeparator() - } rvk := reflect.New(ktype).Elem() d.decodeValue(rvk, keyFn) @@ -868,11 +906,10 @@ func (f decFnInfo) kMap(rv reflect.Value) { if !rvv.IsValid() { rvv = reflect.New(vtype).Elem() } - f.dd.ReadMapKVSeparator() d.decodeValue(rvv, valFn) rv.SetMapIndex(rvk, rvv) } - f.dd.ReadMapEnd() + f.dd.ReadEnd() } } @@ -887,6 +924,8 @@ type Decoder struct { // Try to put things that go together to fit within a cache line (8 words). d decDriver + // NOTE: Decoder shouldn't call it's read methods, + // as the handler MAY need to do some coordination. r decReader //sa [32]rtidDecFn s []rtidDecFn @@ -896,6 +935,7 @@ type Decoder struct { hh Handle be bool // is binary encoding bytes bool // is bytes reader + js bool // is json handle ri ioDecReader f map[uintptr]decFn @@ -919,6 +959,7 @@ func NewDecoder(r io.Reader, h Handle) (d *Decoder) { d.ri.br = &d.ri.bs } d.r = &d.ri + _, d.js = h.(*JsonHandle) d.d = h.newDecDriver(d) return } @@ -931,6 +972,7 @@ func NewDecoderBytes(in []byte, h Handle) (d *Decoder) { d.rb.b = in d.rb.a = len(in) d.r = &d.rb + _, d.js = h.(*JsonHandle) d.d = h.newDecDriver(d) // d.d = h.newDecDriver(decReaderT{true, &d.rb, &d.ri}) return @@ -1014,14 +1056,10 @@ func (d *Decoder) swallow() { } else if dd.CheckBreak() { break } - if j > 0 { - dd.ReadMapEntrySeparator() - } d.swallow() - dd.ReadMapKVSeparator() d.swallow() } - dd.ReadMapEnd() + dd.ReadEnd() case dd.IsContainerType(valueTypeArray): containerLenS := dd.ReadArrayStart() clenGtEqualZero := containerLenS >= 0 @@ -1033,12 +1071,9 @@ func (d *Decoder) swallow() { } else if dd.CheckBreak() { break } - if j > 0 { - dd.ReadArrayEntrySeparator() - } d.swallow() } - dd.ReadArrayEnd() + dd.ReadEnd() case dd.IsContainerType(valueTypeBytes): dd.DecodeBytes(d.b[:], false, true) case dd.IsContainerType(valueTypeString): @@ -1272,6 +1307,10 @@ func (d *Decoder) getDecFn(rt reflect.Type, checkFastpath, checkCodecSelfer bool } else if supportMarshalInterfaces && d.be && ti.bunm { fi.decFnInfoX = &decFnInfoX{d: d, ti: ti} fn.f = (decFnInfo).binaryUnmarshal + } else if supportMarshalInterfaces && !d.be && d.js && ti.junm { + //If JSON, we should check JSONUnmarshal before textUnmarshal + fi.decFnInfoX = &decFnInfoX{d: d, ti: ti} + fn.f = (decFnInfo).jsonUnmarshal } else if supportMarshalInterfaces && !d.be && ti.tunm { fi.decFnInfoX = &decFnInfoX{d: d, ti: ti} fn.f = (decFnInfo).textUnmarshal @@ -1336,6 +1375,8 @@ func (d *Decoder) getDecFn(rt reflect.Type, checkFastpath, checkCodecSelfer bool fn.f = (decFnInfo).kUint16 // case reflect.Ptr: // fn.f = (decFnInfo).kPtr + case reflect.Uintptr: + fn.f = (decFnInfo).kUintptr case reflect.Interface: fi.decFnInfoX = &decFnInfoX{d: d, ti: ti} fn.f = (decFnInfo).kInterface @@ -1417,7 +1458,10 @@ func (d *Decoder) error(err error) { } func (d *Decoder) errorf(format string, params ...interface{}) { - err := fmt.Errorf(format, params...) + params2 := make([]interface{}, len(params)+1) + params2[0] = d.r.numread() + copy(params2[1:], params) + err := fmt.Errorf("[pos %d]: "+format, params2...) panic(err) } @@ -1444,30 +1488,10 @@ func (d *Decoder) decSliceHelperStart() (x decSliceHelper, clen int) { return } -func (x decSliceHelper) Sep(index int) { - if x.ct == valueTypeArray { - x.dd.ReadArrayEntrySeparator() - } else { - if index%2 == 0 { - x.dd.ReadMapEntrySeparator() - } else { - x.dd.ReadMapKVSeparator() - } - } -} - func (x decSliceHelper) End() { - if x.ct == valueTypeArray { - x.dd.ReadArrayEnd() - } else { - x.dd.ReadMapEnd() - } + x.dd.ReadEnd() } -// func decErr(format string, params ...interface{}) { -// doPanic(msgTagDec, format, params...) -// } - func decByteSlice(r decReader, clen int, bs []byte) (bsOut []byte) { if clen == 0 { return zeroByteSlice @@ -1516,37 +1540,5 @@ func detachZeroCopyBytes(isBytesReader bool, dest []byte, in []byte) (out []byte // d.ri.unreadn1() // } // } - -// func (d *Decoder) readb(b []byte) { -// if d.bytes { -// d.rb.readb(b) -// } else { -// d.ri.readb(b) -// } -// } - -// func (d *Decoder) readx(n int) []byte { -// if d.bytes { -// return d.rb.readx(n) -// } else { -// return d.ri.readx(n) -// } -// } - -// func (d *Decoder) readn1() uint8 { -// if d.bytes { -// return d.rb.readn1() -// } else { -// return d.ri.readn1() -// } -// } - -// func (d *Decoder) readn1eof() (v uint8, eof bool) { -// if d.bytes { -// return d.rb.readn1eof() -// } else { -// return d.ri.readn1eof() -// } -// } - -// var _ decReader = (*Decoder)(nil) // decReaderT{} // +// ... for other methods of decReader. +// Testing showed that performance improvement was negligible. diff --git a/Godeps/_workspace/src/github.com/ugorji/go/codec/encode.go b/Godeps/_workspace/src/github.com/ugorji/go/codec/encode.go index 38c55be4e..dbb988634 100644 --- a/Godeps/_workspace/src/github.com/ugorji/go/codec/encode.go +++ b/Godeps/_workspace/src/github.com/ugorji/go/codec/encode.go @@ -63,12 +63,8 @@ type encDriver interface { EncodeRawExt(re *RawExt, e *Encoder) EncodeExt(v interface{}, xtag uint64, ext Ext, e *Encoder) EncodeArrayStart(length int) - EncodeArrayEnd() - EncodeArrayEntrySeparator() EncodeMapStart(length int) - EncodeMapEnd() - EncodeMapEntrySeparator() - EncodeMapKVSeparator() + EncodeEnd() EncodeString(c charEncoding, v string) EncodeSymbol(v string) EncodeStringBytes(c charEncoding, v []byte) @@ -77,13 +73,13 @@ type encDriver interface { //encStringRunes(c charEncoding, v []rune) } +type encDriverAsis interface { + EncodeAsis(v []byte) +} + type encNoSeparator struct{} -func (_ encNoSeparator) EncodeMapEnd() {} -func (_ encNoSeparator) EncodeArrayEnd() {} -func (_ encNoSeparator) EncodeArrayEntrySeparator() {} -func (_ encNoSeparator) EncodeMapEntrySeparator() {} -func (_ encNoSeparator) EncodeMapKVSeparator() {} +func (_ encNoSeparator) EncodeEnd() {} type encStructFieldBytesV struct { b []byte @@ -113,8 +109,9 @@ type EncodeOptions struct { // Canonical representation means that encoding a value will always result in the same // sequence of bytes. // - // This mostly will apply to maps. In this case, codec will do more work to encode the - // map keys out of band, and then sort them, before writing out the map to the stream. + // This only affects maps, as the iteration order for maps is random. + // In this case, the map keys will first be encoded into []byte, and then sorted, + // before writing the sorted keys and the corresponding map values to the stream. Canonical bool // AsSymbols defines what should be encoded as symbols. @@ -302,8 +299,8 @@ func (f encFnInfo) rawExt(rv reflect.Value) { } func (f encFnInfo) ext(rv reflect.Value) { - // if this is a struct and it was addressable, then pass the address directly (not the value) - if rv.CanAddr() && rv.Kind() == reflect.Struct { + // if this is a struct|array and it was addressable, then pass the address directly (not the value) + if k := rv.Kind(); (k == reflect.Struct || k == reflect.Array) && rv.CanAddr() { rv = rv.Addr() } f.ee.EncodeExt(rv.Interface(), f.xfTag, f.xfFn, f.e) @@ -313,7 +310,16 @@ func (f encFnInfo) getValueForMarshalInterface(rv reflect.Value, indir int8) (v if indir == 0 { v = rv.Interface() } else if indir == -1 { - v = rv.Addr().Interface() + // If a non-pointer was passed to Encode(), then that value is not addressable. + // Take addr if addresable, else copy value to an addressable value. + if rv.CanAddr() { + v = rv.Addr().Interface() + } else { + rv2 := reflect.New(rv.Type()) + rv2.Elem().Set(rv) + v = rv2.Interface() + // fmt.Printf("rv.Type: %v, rv2.Type: %v, v: %v\n", rv.Type(), rv2.Type(), v) + } } else { for j := int8(0); j < indir; j++ { if rv.IsNil() { @@ -336,14 +342,7 @@ func (f encFnInfo) selferMarshal(rv reflect.Value) { func (f encFnInfo) binaryMarshal(rv reflect.Value) { if v, proceed := f.getValueForMarshalInterface(rv, f.ti.bmIndir); proceed { bs, fnerr := v.(encoding.BinaryMarshaler).MarshalBinary() - if fnerr != nil { - panic(fnerr) - } - if bs == nil { - f.ee.EncodeNil() - } else { - f.ee.EncodeStringBytes(c_RAW, bs) - } + f.e.marshal(bs, fnerr, false, c_RAW) } } @@ -351,14 +350,14 @@ func (f encFnInfo) textMarshal(rv reflect.Value) { if v, proceed := f.getValueForMarshalInterface(rv, f.ti.tmIndir); proceed { // debugf(">>>> encoding.TextMarshaler: %T", rv.Interface()) bs, fnerr := v.(encoding.TextMarshaler).MarshalText() - if fnerr != nil { - panic(fnerr) - } - if bs == nil { - f.ee.EncodeNil() - } else { - f.ee.EncodeStringBytes(c_UTF8, bs) - } + f.e.marshal(bs, fnerr, false, c_UTF8) + } +} + +func (f encFnInfo) jsonMarshal(rv reflect.Value) { + if v, proceed := f.getValueForMarshalInterface(rv, f.ti.jmIndir); proceed { + bs, fnerr := v.(jsonMarshaler).MarshalJSON() + f.e.marshal(bs, fnerr, true, c_UTF8) } } @@ -463,7 +462,6 @@ func (f encFnInfo) kSlice(rv reflect.Value) { } e := f.e - sep := !e.be if l > 0 { for rtelem.Kind() == reflect.Ptr { rtelem = rtelem.Elem() @@ -477,47 +475,19 @@ func (f encFnInfo) kSlice(rv reflect.Value) { fn = e.getEncFn(rtelemid, rtelem, true, true) } // TODO: Consider perf implication of encoding odd index values as symbols if type is string - if sep { - for j := 0; j < l; j++ { - if j > 0 { - if ti.mbs { - if j%2 == 0 { - f.ee.EncodeMapEntrySeparator() - } else { - f.ee.EncodeMapKVSeparator() - } - } else { - f.ee.EncodeArrayEntrySeparator() - } - } - if f.seq == seqTypeChan { - if rv2, ok2 := rv.Recv(); ok2 { - e.encodeValue(rv2, fn) - } - } else { - e.encodeValue(rv.Index(j), fn) - } - } - } else { - for j := 0; j < l; j++ { - if f.seq == seqTypeChan { - if rv2, ok2 := rv.Recv(); ok2 { - e.encodeValue(rv2, fn) - } - } else { - e.encodeValue(rv.Index(j), fn) + for j := 0; j < l; j++ { + if f.seq == seqTypeChan { + if rv2, ok2 := rv.Recv(); ok2 { + e.encodeValue(rv2, fn) } + } else { + e.encodeValue(rv.Index(j), fn) } } + } - if sep { - if ti.mbs { - f.ee.EncodeMapEnd() - } else { - f.ee.EncodeArrayEnd() - } - } + f.ee.EncodeEnd() } func (f encFnInfo) kStruct(rv reflect.Value) { @@ -587,60 +557,30 @@ func (f encFnInfo) kStruct(rv reflect.Value) { } // debugf(">>>> kStruct: newlen: %v", newlen) - sep := !e.be + // sep := !e.be ee := f.ee //don't dereference everytime - if sep { - if toMap { - ee.EncodeMapStart(newlen) - // asSymbols := e.h.AsSymbols&AsSymbolStructFieldNameFlag != 0 - asSymbols := e.h.AsSymbols == AsSymbolDefault || e.h.AsSymbols&AsSymbolStructFieldNameFlag != 0 - for j := 0; j < newlen; j++ { - kv = fkvs[j] - if j > 0 { - ee.EncodeMapEntrySeparator() - } - if asSymbols { - ee.EncodeSymbol(kv.k) - } else { - ee.EncodeString(c_UTF8, kv.k) - } - ee.EncodeMapKVSeparator() - e.encodeValue(kv.v, encFn{}) + + if toMap { + ee.EncodeMapStart(newlen) + // asSymbols := e.h.AsSymbols&AsSymbolStructFieldNameFlag != 0 + asSymbols := e.h.AsSymbols == AsSymbolDefault || e.h.AsSymbols&AsSymbolStructFieldNameFlag != 0 + for j := 0; j < newlen; j++ { + kv = fkvs[j] + if asSymbols { + ee.EncodeSymbol(kv.k) + } else { + ee.EncodeString(c_UTF8, kv.k) } - ee.EncodeMapEnd() - } else { - ee.EncodeArrayStart(newlen) - for j := 0; j < newlen; j++ { - kv = fkvs[j] - if j > 0 { - ee.EncodeArrayEntrySeparator() - } - e.encodeValue(kv.v, encFn{}) - } - ee.EncodeArrayEnd() + e.encodeValue(kv.v, encFn{}) } } else { - if toMap { - ee.EncodeMapStart(newlen) - // asSymbols := e.h.AsSymbols&AsSymbolStructFieldNameFlag != 0 - asSymbols := e.h.AsSymbols == AsSymbolDefault || e.h.AsSymbols&AsSymbolStructFieldNameFlag != 0 - for j := 0; j < newlen; j++ { - kv = fkvs[j] - if asSymbols { - ee.EncodeSymbol(kv.k) - } else { - ee.EncodeString(c_UTF8, kv.k) - } - e.encodeValue(kv.v, encFn{}) - } - } else { - ee.EncodeArrayStart(newlen) - for j := 0; j < newlen; j++ { - kv = fkvs[j] - e.encodeValue(kv.v, encFn{}) - } + ee.EncodeArrayStart(newlen) + for j := 0; j < newlen; j++ { + kv = fkvs[j] + e.encodeValue(kv.v, encFn{}) } } + ee.EncodeEnd() // do not use defer. Instead, use explicit pool return at end of function. // defer has a cost we are trying to avoid. @@ -676,11 +616,8 @@ func (f encFnInfo) kMap(rv reflect.Value) { l := rv.Len() f.ee.EncodeMapStart(l) e := f.e - sep := !e.be if l == 0 { - if sep { - f.ee.EncodeMapEnd() - } + f.ee.EncodeEnd() return } var asSymbols bool @@ -722,7 +659,7 @@ func (f encFnInfo) kMap(rv reflect.Value) { if e.h.Canonical { // first encode each key to a []byte first, then sort them, then record // println(">>>>>>>> CANONICAL <<<<<<<<") - var mksv []byte // temporary byte slice for the encoding + var mksv []byte = make([]byte, 0, len(mks)*16) // temporary byte slice for the encoding e2 := NewEncoderBytes(&mksv, e.hh) mksbv := make([]encStructFieldBytesV, len(mks)) for i, k := range mks { @@ -730,35 +667,13 @@ func (f encFnInfo) kMap(rv reflect.Value) { e2.MustEncode(k) mksbv[i].v = k mksbv[i].b = mksv[l:] + // fmt.Printf(">>>>> %s\n", mksv[l:]) } sort.Sort(encStructFieldBytesVslice(mksbv)) for j := range mksbv { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - e.w.writeb(mksbv[j].b) - ee.EncodeMapKVSeparator() + e.asis(mksbv[j].b) e.encodeValue(rv.MapIndex(mksbv[j].v), valFn) } - ee.EncodeMapEnd() - } else if sep { - for j := range mks { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - if keyTypeIsString { - if asSymbols { - ee.EncodeSymbol(mks[j].String()) - } else { - ee.EncodeString(c_UTF8, mks[j].String()) - } - } else { - e.encodeValue(mks[j], keyFn) - } - ee.EncodeMapKVSeparator() - e.encodeValue(rv.MapIndex(mks[j]), valFn) - } - ee.EncodeMapEnd() } else { for j := range mks { if keyTypeIsString { @@ -773,6 +688,7 @@ func (f encFnInfo) kMap(rv reflect.Value) { e.encodeValue(rv.MapIndex(mks[j]), valFn) } } + ee.EncodeEnd() } // -------------------------------------------------- @@ -796,15 +712,19 @@ type rtidEncFn struct { // An Encoder writes an object to an output stream in the codec format. type Encoder struct { // hopefully, reduce derefencing cost by laying the encWriter inside the Encoder - e encDriver + e encDriver + // NOTE: Encoder shouldn't call it's write methods, + // as the handler MAY need to do some coordination. w encWriter s []rtidEncFn be bool // is binary encoding + js bool // is json handle wi ioEncWriter wb bytesEncWriter h *BasicHandle + as encDriverAsis hh Handle f map[uintptr]encFn b [scratchByteArrayLen]byte @@ -826,7 +746,9 @@ func NewEncoder(w io.Writer, h Handle) *Encoder { } e.wi.w = ww e.w = &e.wi + _, e.js = h.(*JsonHandle) e.e = h.newEncDriver(e) + e.as, _ = e.e.(encDriverAsis) return e } @@ -843,7 +765,9 @@ func NewEncoderBytes(out *[]byte, h Handle) *Encoder { } e.wb.b, e.wb.out = in, out e.w = &e.wb + _, e.js = h.(*JsonHandle) e.e = h.newEncDriver(e) + e.as, _ = e.e.(encDriverAsis) return e } @@ -873,8 +797,9 @@ func NewEncoderBytes(out *[]byte, h Handle) *Encoder { // The empty values (for omitempty option) are false, 0, any nil pointer // or interface value, and any array, slice, map, or string of length zero. // -// Anonymous fields are encoded inline if no struct tag is present. -// Else they are encoded as regular fields. +// Anonymous fields are encoded inline except: +// - the struct tag specifies a replacement name (first value) +// - the field is of an interface type // // Examples: // @@ -885,6 +810,9 @@ func NewEncoderBytes(out *[]byte, h Handle) *Encoder { // Field2 int `codec:"myName"` //Use key "myName" in encode stream // Field3 int32 `codec:",omitempty"` //use key "Field3". Omit if empty. // Field4 bool `codec:"f4,omitempty"` //use key "f4". Omit if empty. +// io.Reader //use key "Reader". +// MyStruct `codec:"my1" //use key "my1". +// MyStruct //inline it // ... // } // @@ -894,8 +822,9 @@ func NewEncoderBytes(out *[]byte, h Handle) *Encoder { // } // // The mode of encoding is based on the type of the value. When a value is seen: +// - If a Selfer, call its CodecEncodeSelf method // - If an extension is registered for it, call that extension function -// - If it implements BinaryMarshaler, call its MarshalBinary() (data []byte, err error) +// - If it implements encoding.(Binary|Text|JSON)Marshaler, call its Marshal(Binary|Text|JSON) method // - Else encode it based on its reflect.Kind // // Note that struct field names and keys in map[string]XXX will be treated as symbols. @@ -1010,12 +939,15 @@ func (e *Encoder) encode(iv interface{}) { default: // canonical mode is not supported for fastpath of maps (but is fine for slices) + const checkCodecSelfer1 = true // in case T is passed, where *T is a Selfer, still checkCodecSelfer if e.h.Canonical { if !fastpathEncodeTypeSwitchSlice(iv, e) { - e.encodeI(iv, false, false) + e.encodeI(iv, false, checkCodecSelfer1) + } + } else { + if !fastpathEncodeTypeSwitch(iv, e) { + e.encodeI(iv, false, checkCodecSelfer1) } - } else if !fastpathEncodeTypeSwitch(iv, e) { - e.encodeI(iv, false, false) } } } @@ -1105,12 +1037,17 @@ func (e *Encoder) getEncFn(rtid uintptr, rt reflect.Type, checkFastpath, checkCo } else if supportMarshalInterfaces && e.be && ti.bm { fi.encFnInfoX = &encFnInfoX{e: e, ti: ti} fn.f = (encFnInfo).binaryMarshal + } else if supportMarshalInterfaces && !e.be && e.js && ti.jm { + //If JSON, we should check JSONMarshal before textMarshal + fi.encFnInfoX = &encFnInfoX{e: e, ti: ti} + fn.f = (encFnInfo).jsonMarshal } else if supportMarshalInterfaces && !e.be && ti.tm { fi.encFnInfoX = &encFnInfoX{e: e, ti: ti} fn.f = (encFnInfo).textMarshal } else { rk := rt.Kind() - if fastpathEnabled && checkFastpath && (rk == reflect.Map || rk == reflect.Slice) { + // if fastpathEnabled && checkFastpath && (rk == reflect.Map || rk == reflect.Slice) { + if fastpathEnabled && checkFastpath && (rk == reflect.Slice || (rk == reflect.Map && !e.h.Canonical)) { if rt.PkgPath() == "" { if idx := fastpathAV.index(rtid); idx != -1 { fi.encFnInfoX = &encFnInfoX{e: e, ti: ti} @@ -1148,7 +1085,7 @@ func (e *Encoder) getEncFn(rtid uintptr, rt reflect.Type, checkFastpath, checkCo fn.f = (encFnInfo).kFloat32 case reflect.Int, reflect.Int8, reflect.Int64, reflect.Int32, reflect.Int16: fn.f = (encFnInfo).kInt - case reflect.Uint8, reflect.Uint64, reflect.Uint, reflect.Uint32, reflect.Uint16: + case reflect.Uint8, reflect.Uint64, reflect.Uint, reflect.Uint32, reflect.Uint16, reflect.Uintptr: fn.f = (encFnInfo).kUint case reflect.Invalid: fn.f = (encFnInfo).kInvalid @@ -1193,6 +1130,27 @@ func (e *Encoder) getEncFn(rtid uintptr, rt reflect.Type, checkFastpath, checkCo return } +func (e *Encoder) marshal(bs []byte, fnerr error, asis bool, c charEncoding) { + if fnerr != nil { + panic(fnerr) + } + if bs == nil { + e.e.EncodeNil() + } else if asis { + e.asis(bs) + } else { + e.e.EncodeStringBytes(c, bs) + } +} + +func (e *Encoder) asis(v []byte) { + if e.as == nil { + e.w.writeb(v) + } else { + e.as.EncodeAsis(v) + } +} + func (e *Encoder) errorf(format string, params ...interface{}) { err := fmt.Errorf(format, params...) panic(err) diff --git a/Godeps/_workspace/src/github.com/ugorji/go/codec/fast-path.generated.go b/Godeps/_workspace/src/github.com/ugorji/go/codec/fast-path.generated.go index b0f7f8070..b395b0c59 100644 --- a/Godeps/_workspace/src/github.com/ugorji/go/codec/fast-path.generated.go +++ b/Godeps/_workspace/src/github.com/ugorji/go/codec/fast-path.generated.go @@ -2769,19 +2769,10 @@ func (_ fastpathT) EncSliceIntfV(v []interface{}, checkNil bool, e *Encoder) { return } ee.EncodeArrayStart(len(v)) - if e.be { - for _, v2 := range v { - e.encode(v2) - } - } else { - for j, v2 := range v { - if j > 0 { - ee.EncodeArrayEntrySeparator() - } - e.encode(v2) - } - ee.EncodeArrayEnd() + for _, v2 := range v { + e.encode(v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncSliceStringR(rv reflect.Value) { @@ -2794,19 +2785,10 @@ func (_ fastpathT) EncSliceStringV(v []string, checkNil bool, e *Encoder) { return } ee.EncodeArrayStart(len(v)) - if e.be { - for _, v2 := range v { - ee.EncodeString(c_UTF8, v2) - } - } else { - for j, v2 := range v { - if j > 0 { - ee.EncodeArrayEntrySeparator() - } - ee.EncodeString(c_UTF8, v2) - } - ee.EncodeArrayEnd() + for _, v2 := range v { + ee.EncodeString(c_UTF8, v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncSliceFloat32R(rv reflect.Value) { @@ -2819,19 +2801,10 @@ func (_ fastpathT) EncSliceFloat32V(v []float32, checkNil bool, e *Encoder) { return } ee.EncodeArrayStart(len(v)) - if e.be { - for _, v2 := range v { - ee.EncodeFloat32(v2) - } - } else { - for j, v2 := range v { - if j > 0 { - ee.EncodeArrayEntrySeparator() - } - ee.EncodeFloat32(v2) - } - ee.EncodeArrayEnd() + for _, v2 := range v { + ee.EncodeFloat32(v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncSliceFloat64R(rv reflect.Value) { @@ -2844,19 +2817,10 @@ func (_ fastpathT) EncSliceFloat64V(v []float64, checkNil bool, e *Encoder) { return } ee.EncodeArrayStart(len(v)) - if e.be { - for _, v2 := range v { - ee.EncodeFloat64(v2) - } - } else { - for j, v2 := range v { - if j > 0 { - ee.EncodeArrayEntrySeparator() - } - ee.EncodeFloat64(v2) - } - ee.EncodeArrayEnd() + for _, v2 := range v { + ee.EncodeFloat64(v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncSliceUintR(rv reflect.Value) { @@ -2869,19 +2833,10 @@ func (_ fastpathT) EncSliceUintV(v []uint, checkNil bool, e *Encoder) { return } ee.EncodeArrayStart(len(v)) - if e.be { - for _, v2 := range v { - ee.EncodeUint(uint64(v2)) - } - } else { - for j, v2 := range v { - if j > 0 { - ee.EncodeArrayEntrySeparator() - } - ee.EncodeUint(uint64(v2)) - } - ee.EncodeArrayEnd() + for _, v2 := range v { + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncSliceUint16R(rv reflect.Value) { @@ -2894,19 +2849,10 @@ func (_ fastpathT) EncSliceUint16V(v []uint16, checkNil bool, e *Encoder) { return } ee.EncodeArrayStart(len(v)) - if e.be { - for _, v2 := range v { - ee.EncodeUint(uint64(v2)) - } - } else { - for j, v2 := range v { - if j > 0 { - ee.EncodeArrayEntrySeparator() - } - ee.EncodeUint(uint64(v2)) - } - ee.EncodeArrayEnd() + for _, v2 := range v { + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncSliceUint32R(rv reflect.Value) { @@ -2919,19 +2865,10 @@ func (_ fastpathT) EncSliceUint32V(v []uint32, checkNil bool, e *Encoder) { return } ee.EncodeArrayStart(len(v)) - if e.be { - for _, v2 := range v { - ee.EncodeUint(uint64(v2)) - } - } else { - for j, v2 := range v { - if j > 0 { - ee.EncodeArrayEntrySeparator() - } - ee.EncodeUint(uint64(v2)) - } - ee.EncodeArrayEnd() + for _, v2 := range v { + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncSliceUint64R(rv reflect.Value) { @@ -2944,19 +2881,10 @@ func (_ fastpathT) EncSliceUint64V(v []uint64, checkNil bool, e *Encoder) { return } ee.EncodeArrayStart(len(v)) - if e.be { - for _, v2 := range v { - ee.EncodeUint(uint64(v2)) - } - } else { - for j, v2 := range v { - if j > 0 { - ee.EncodeArrayEntrySeparator() - } - ee.EncodeUint(uint64(v2)) - } - ee.EncodeArrayEnd() + for _, v2 := range v { + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncSliceIntR(rv reflect.Value) { @@ -2969,19 +2897,10 @@ func (_ fastpathT) EncSliceIntV(v []int, checkNil bool, e *Encoder) { return } ee.EncodeArrayStart(len(v)) - if e.be { - for _, v2 := range v { - ee.EncodeInt(int64(v2)) - } - } else { - for j, v2 := range v { - if j > 0 { - ee.EncodeArrayEntrySeparator() - } - ee.EncodeInt(int64(v2)) - } - ee.EncodeArrayEnd() + for _, v2 := range v { + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncSliceInt8R(rv reflect.Value) { @@ -2994,19 +2913,10 @@ func (_ fastpathT) EncSliceInt8V(v []int8, checkNil bool, e *Encoder) { return } ee.EncodeArrayStart(len(v)) - if e.be { - for _, v2 := range v { - ee.EncodeInt(int64(v2)) - } - } else { - for j, v2 := range v { - if j > 0 { - ee.EncodeArrayEntrySeparator() - } - ee.EncodeInt(int64(v2)) - } - ee.EncodeArrayEnd() + for _, v2 := range v { + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncSliceInt16R(rv reflect.Value) { @@ -3019,19 +2929,10 @@ func (_ fastpathT) EncSliceInt16V(v []int16, checkNil bool, e *Encoder) { return } ee.EncodeArrayStart(len(v)) - if e.be { - for _, v2 := range v { - ee.EncodeInt(int64(v2)) - } - } else { - for j, v2 := range v { - if j > 0 { - ee.EncodeArrayEntrySeparator() - } - ee.EncodeInt(int64(v2)) - } - ee.EncodeArrayEnd() + for _, v2 := range v { + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncSliceInt32R(rv reflect.Value) { @@ -3044,19 +2945,10 @@ func (_ fastpathT) EncSliceInt32V(v []int32, checkNil bool, e *Encoder) { return } ee.EncodeArrayStart(len(v)) - if e.be { - for _, v2 := range v { - ee.EncodeInt(int64(v2)) - } - } else { - for j, v2 := range v { - if j > 0 { - ee.EncodeArrayEntrySeparator() - } - ee.EncodeInt(int64(v2)) - } - ee.EncodeArrayEnd() + for _, v2 := range v { + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncSliceInt64R(rv reflect.Value) { @@ -3069,19 +2961,10 @@ func (_ fastpathT) EncSliceInt64V(v []int64, checkNil bool, e *Encoder) { return } ee.EncodeArrayStart(len(v)) - if e.be { - for _, v2 := range v { - ee.EncodeInt(int64(v2)) - } - } else { - for j, v2 := range v { - if j > 0 { - ee.EncodeArrayEntrySeparator() - } - ee.EncodeInt(int64(v2)) - } - ee.EncodeArrayEnd() + for _, v2 := range v { + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncSliceBoolR(rv reflect.Value) { @@ -3094,19 +2977,10 @@ func (_ fastpathT) EncSliceBoolV(v []bool, checkNil bool, e *Encoder) { return } ee.EncodeArrayStart(len(v)) - if e.be { - for _, v2 := range v { - ee.EncodeBool(v2) - } - } else { - for j, v2 := range v { - if j > 0 { - ee.EncodeArrayEntrySeparator() - } - ee.EncodeBool(v2) - } - ee.EncodeArrayEnd() + for _, v2 := range v { + ee.EncodeBool(v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapIntfIntfR(rv reflect.Value) { @@ -3120,24 +2994,11 @@ func (_ fastpathT) EncMapIntfIntfV(v map[interface{}]interface{}, checkNil bool, } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - e.encode(k2) - e.encode(v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - e.encode(k2) - ee.EncodeMapKVSeparator() - e.encode(v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + e.encode(k2) + e.encode(v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapIntfStringR(rv reflect.Value) { @@ -3151,24 +3012,11 @@ func (_ fastpathT) EncMapIntfStringV(v map[interface{}]string, checkNil bool, e } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - e.encode(k2) - ee.EncodeString(c_UTF8, v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - e.encode(k2) - ee.EncodeMapKVSeparator() - ee.EncodeString(c_UTF8, v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + e.encode(k2) + ee.EncodeString(c_UTF8, v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapIntfUintR(rv reflect.Value) { @@ -3182,24 +3030,11 @@ func (_ fastpathT) EncMapIntfUintV(v map[interface{}]uint, checkNil bool, e *Enc } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - e.encode(k2) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - e.encode(k2) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + e.encode(k2) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapIntfUint8R(rv reflect.Value) { @@ -3213,24 +3048,11 @@ func (_ fastpathT) EncMapIntfUint8V(v map[interface{}]uint8, checkNil bool, e *E } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - e.encode(k2) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - e.encode(k2) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + e.encode(k2) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapIntfUint16R(rv reflect.Value) { @@ -3244,24 +3066,11 @@ func (_ fastpathT) EncMapIntfUint16V(v map[interface{}]uint16, checkNil bool, e } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - e.encode(k2) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - e.encode(k2) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + e.encode(k2) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapIntfUint32R(rv reflect.Value) { @@ -3275,24 +3084,11 @@ func (_ fastpathT) EncMapIntfUint32V(v map[interface{}]uint32, checkNil bool, e } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - e.encode(k2) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - e.encode(k2) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + e.encode(k2) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapIntfUint64R(rv reflect.Value) { @@ -3306,24 +3102,11 @@ func (_ fastpathT) EncMapIntfUint64V(v map[interface{}]uint64, checkNil bool, e } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - e.encode(k2) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - e.encode(k2) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + e.encode(k2) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapIntfIntR(rv reflect.Value) { @@ -3337,24 +3120,11 @@ func (_ fastpathT) EncMapIntfIntV(v map[interface{}]int, checkNil bool, e *Encod } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - e.encode(k2) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - e.encode(k2) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + e.encode(k2) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapIntfInt8R(rv reflect.Value) { @@ -3368,24 +3138,11 @@ func (_ fastpathT) EncMapIntfInt8V(v map[interface{}]int8, checkNil bool, e *Enc } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - e.encode(k2) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - e.encode(k2) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + e.encode(k2) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapIntfInt16R(rv reflect.Value) { @@ -3399,24 +3156,11 @@ func (_ fastpathT) EncMapIntfInt16V(v map[interface{}]int16, checkNil bool, e *E } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - e.encode(k2) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - e.encode(k2) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + e.encode(k2) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapIntfInt32R(rv reflect.Value) { @@ -3430,24 +3174,11 @@ func (_ fastpathT) EncMapIntfInt32V(v map[interface{}]int32, checkNil bool, e *E } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - e.encode(k2) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - e.encode(k2) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + e.encode(k2) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapIntfInt64R(rv reflect.Value) { @@ -3461,24 +3192,11 @@ func (_ fastpathT) EncMapIntfInt64V(v map[interface{}]int64, checkNil bool, e *E } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - e.encode(k2) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - e.encode(k2) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + e.encode(k2) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapIntfFloat32R(rv reflect.Value) { @@ -3492,24 +3210,11 @@ func (_ fastpathT) EncMapIntfFloat32V(v map[interface{}]float32, checkNil bool, } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - e.encode(k2) - ee.EncodeFloat32(v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - e.encode(k2) - ee.EncodeMapKVSeparator() - ee.EncodeFloat32(v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + e.encode(k2) + ee.EncodeFloat32(v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapIntfFloat64R(rv reflect.Value) { @@ -3523,24 +3228,11 @@ func (_ fastpathT) EncMapIntfFloat64V(v map[interface{}]float64, checkNil bool, } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - e.encode(k2) - ee.EncodeFloat64(v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - e.encode(k2) - ee.EncodeMapKVSeparator() - ee.EncodeFloat64(v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + e.encode(k2) + ee.EncodeFloat64(v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapIntfBoolR(rv reflect.Value) { @@ -3554,24 +3246,11 @@ func (_ fastpathT) EncMapIntfBoolV(v map[interface{}]bool, checkNil bool, e *Enc } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - e.encode(k2) - ee.EncodeBool(v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - e.encode(k2) - ee.EncodeMapKVSeparator() - ee.EncodeBool(v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + e.encode(k2) + ee.EncodeBool(v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapStringIntfR(rv reflect.Value) { @@ -3585,32 +3264,15 @@ func (_ fastpathT) EncMapStringIntfV(v map[string]interface{}, checkNil bool, e } ee.EncodeMapStart(len(v)) asSymbols := e.h.AsSymbols&AsSymbolMapStringKeysFlag != 0 - if e.be { - for k2, v2 := range v { - if asSymbols { - ee.EncodeSymbol(k2) - } else { - ee.EncodeString(c_UTF8, k2) - } - e.encode(v2) + for k2, v2 := range v { + if asSymbols { + ee.EncodeSymbol(k2) + } else { + ee.EncodeString(c_UTF8, k2) } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - if asSymbols { - ee.EncodeSymbol(k2) - } else { - ee.EncodeString(c_UTF8, k2) - } - ee.EncodeMapKVSeparator() - e.encode(v2) - j++ - } - ee.EncodeMapEnd() + e.encode(v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapStringStringR(rv reflect.Value) { @@ -3624,32 +3286,15 @@ func (_ fastpathT) EncMapStringStringV(v map[string]string, checkNil bool, e *En } ee.EncodeMapStart(len(v)) asSymbols := e.h.AsSymbols&AsSymbolMapStringKeysFlag != 0 - if e.be { - for k2, v2 := range v { - if asSymbols { - ee.EncodeSymbol(k2) - } else { - ee.EncodeString(c_UTF8, k2) - } - ee.EncodeString(c_UTF8, v2) + for k2, v2 := range v { + if asSymbols { + ee.EncodeSymbol(k2) + } else { + ee.EncodeString(c_UTF8, k2) } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - if asSymbols { - ee.EncodeSymbol(k2) - } else { - ee.EncodeString(c_UTF8, k2) - } - ee.EncodeMapKVSeparator() - ee.EncodeString(c_UTF8, v2) - j++ - } - ee.EncodeMapEnd() + ee.EncodeString(c_UTF8, v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapStringUintR(rv reflect.Value) { @@ -3663,32 +3308,15 @@ func (_ fastpathT) EncMapStringUintV(v map[string]uint, checkNil bool, e *Encode } ee.EncodeMapStart(len(v)) asSymbols := e.h.AsSymbols&AsSymbolMapStringKeysFlag != 0 - if e.be { - for k2, v2 := range v { - if asSymbols { - ee.EncodeSymbol(k2) - } else { - ee.EncodeString(c_UTF8, k2) - } - ee.EncodeUint(uint64(v2)) + for k2, v2 := range v { + if asSymbols { + ee.EncodeSymbol(k2) + } else { + ee.EncodeString(c_UTF8, k2) } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - if asSymbols { - ee.EncodeSymbol(k2) - } else { - ee.EncodeString(c_UTF8, k2) - } - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapStringUint8R(rv reflect.Value) { @@ -3702,32 +3330,15 @@ func (_ fastpathT) EncMapStringUint8V(v map[string]uint8, checkNil bool, e *Enco } ee.EncodeMapStart(len(v)) asSymbols := e.h.AsSymbols&AsSymbolMapStringKeysFlag != 0 - if e.be { - for k2, v2 := range v { - if asSymbols { - ee.EncodeSymbol(k2) - } else { - ee.EncodeString(c_UTF8, k2) - } - ee.EncodeUint(uint64(v2)) + for k2, v2 := range v { + if asSymbols { + ee.EncodeSymbol(k2) + } else { + ee.EncodeString(c_UTF8, k2) } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - if asSymbols { - ee.EncodeSymbol(k2) - } else { - ee.EncodeString(c_UTF8, k2) - } - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapStringUint16R(rv reflect.Value) { @@ -3741,32 +3352,15 @@ func (_ fastpathT) EncMapStringUint16V(v map[string]uint16, checkNil bool, e *En } ee.EncodeMapStart(len(v)) asSymbols := e.h.AsSymbols&AsSymbolMapStringKeysFlag != 0 - if e.be { - for k2, v2 := range v { - if asSymbols { - ee.EncodeSymbol(k2) - } else { - ee.EncodeString(c_UTF8, k2) - } - ee.EncodeUint(uint64(v2)) + for k2, v2 := range v { + if asSymbols { + ee.EncodeSymbol(k2) + } else { + ee.EncodeString(c_UTF8, k2) } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - if asSymbols { - ee.EncodeSymbol(k2) - } else { - ee.EncodeString(c_UTF8, k2) - } - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapStringUint32R(rv reflect.Value) { @@ -3780,32 +3374,15 @@ func (_ fastpathT) EncMapStringUint32V(v map[string]uint32, checkNil bool, e *En } ee.EncodeMapStart(len(v)) asSymbols := e.h.AsSymbols&AsSymbolMapStringKeysFlag != 0 - if e.be { - for k2, v2 := range v { - if asSymbols { - ee.EncodeSymbol(k2) - } else { - ee.EncodeString(c_UTF8, k2) - } - ee.EncodeUint(uint64(v2)) + for k2, v2 := range v { + if asSymbols { + ee.EncodeSymbol(k2) + } else { + ee.EncodeString(c_UTF8, k2) } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - if asSymbols { - ee.EncodeSymbol(k2) - } else { - ee.EncodeString(c_UTF8, k2) - } - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapStringUint64R(rv reflect.Value) { @@ -3819,32 +3396,15 @@ func (_ fastpathT) EncMapStringUint64V(v map[string]uint64, checkNil bool, e *En } ee.EncodeMapStart(len(v)) asSymbols := e.h.AsSymbols&AsSymbolMapStringKeysFlag != 0 - if e.be { - for k2, v2 := range v { - if asSymbols { - ee.EncodeSymbol(k2) - } else { - ee.EncodeString(c_UTF8, k2) - } - ee.EncodeUint(uint64(v2)) + for k2, v2 := range v { + if asSymbols { + ee.EncodeSymbol(k2) + } else { + ee.EncodeString(c_UTF8, k2) } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - if asSymbols { - ee.EncodeSymbol(k2) - } else { - ee.EncodeString(c_UTF8, k2) - } - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapStringIntR(rv reflect.Value) { @@ -3858,32 +3418,15 @@ func (_ fastpathT) EncMapStringIntV(v map[string]int, checkNil bool, e *Encoder) } ee.EncodeMapStart(len(v)) asSymbols := e.h.AsSymbols&AsSymbolMapStringKeysFlag != 0 - if e.be { - for k2, v2 := range v { - if asSymbols { - ee.EncodeSymbol(k2) - } else { - ee.EncodeString(c_UTF8, k2) - } - ee.EncodeInt(int64(v2)) + for k2, v2 := range v { + if asSymbols { + ee.EncodeSymbol(k2) + } else { + ee.EncodeString(c_UTF8, k2) } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - if asSymbols { - ee.EncodeSymbol(k2) - } else { - ee.EncodeString(c_UTF8, k2) - } - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapStringInt8R(rv reflect.Value) { @@ -3897,32 +3440,15 @@ func (_ fastpathT) EncMapStringInt8V(v map[string]int8, checkNil bool, e *Encode } ee.EncodeMapStart(len(v)) asSymbols := e.h.AsSymbols&AsSymbolMapStringKeysFlag != 0 - if e.be { - for k2, v2 := range v { - if asSymbols { - ee.EncodeSymbol(k2) - } else { - ee.EncodeString(c_UTF8, k2) - } - ee.EncodeInt(int64(v2)) + for k2, v2 := range v { + if asSymbols { + ee.EncodeSymbol(k2) + } else { + ee.EncodeString(c_UTF8, k2) } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - if asSymbols { - ee.EncodeSymbol(k2) - } else { - ee.EncodeString(c_UTF8, k2) - } - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapStringInt16R(rv reflect.Value) { @@ -3936,32 +3462,15 @@ func (_ fastpathT) EncMapStringInt16V(v map[string]int16, checkNil bool, e *Enco } ee.EncodeMapStart(len(v)) asSymbols := e.h.AsSymbols&AsSymbolMapStringKeysFlag != 0 - if e.be { - for k2, v2 := range v { - if asSymbols { - ee.EncodeSymbol(k2) - } else { - ee.EncodeString(c_UTF8, k2) - } - ee.EncodeInt(int64(v2)) + for k2, v2 := range v { + if asSymbols { + ee.EncodeSymbol(k2) + } else { + ee.EncodeString(c_UTF8, k2) } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - if asSymbols { - ee.EncodeSymbol(k2) - } else { - ee.EncodeString(c_UTF8, k2) - } - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapStringInt32R(rv reflect.Value) { @@ -3975,32 +3484,15 @@ func (_ fastpathT) EncMapStringInt32V(v map[string]int32, checkNil bool, e *Enco } ee.EncodeMapStart(len(v)) asSymbols := e.h.AsSymbols&AsSymbolMapStringKeysFlag != 0 - if e.be { - for k2, v2 := range v { - if asSymbols { - ee.EncodeSymbol(k2) - } else { - ee.EncodeString(c_UTF8, k2) - } - ee.EncodeInt(int64(v2)) + for k2, v2 := range v { + if asSymbols { + ee.EncodeSymbol(k2) + } else { + ee.EncodeString(c_UTF8, k2) } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - if asSymbols { - ee.EncodeSymbol(k2) - } else { - ee.EncodeString(c_UTF8, k2) - } - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapStringInt64R(rv reflect.Value) { @@ -4014,32 +3506,15 @@ func (_ fastpathT) EncMapStringInt64V(v map[string]int64, checkNil bool, e *Enco } ee.EncodeMapStart(len(v)) asSymbols := e.h.AsSymbols&AsSymbolMapStringKeysFlag != 0 - if e.be { - for k2, v2 := range v { - if asSymbols { - ee.EncodeSymbol(k2) - } else { - ee.EncodeString(c_UTF8, k2) - } - ee.EncodeInt(int64(v2)) + for k2, v2 := range v { + if asSymbols { + ee.EncodeSymbol(k2) + } else { + ee.EncodeString(c_UTF8, k2) } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - if asSymbols { - ee.EncodeSymbol(k2) - } else { - ee.EncodeString(c_UTF8, k2) - } - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapStringFloat32R(rv reflect.Value) { @@ -4053,32 +3528,15 @@ func (_ fastpathT) EncMapStringFloat32V(v map[string]float32, checkNil bool, e * } ee.EncodeMapStart(len(v)) asSymbols := e.h.AsSymbols&AsSymbolMapStringKeysFlag != 0 - if e.be { - for k2, v2 := range v { - if asSymbols { - ee.EncodeSymbol(k2) - } else { - ee.EncodeString(c_UTF8, k2) - } - ee.EncodeFloat32(v2) + for k2, v2 := range v { + if asSymbols { + ee.EncodeSymbol(k2) + } else { + ee.EncodeString(c_UTF8, k2) } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - if asSymbols { - ee.EncodeSymbol(k2) - } else { - ee.EncodeString(c_UTF8, k2) - } - ee.EncodeMapKVSeparator() - ee.EncodeFloat32(v2) - j++ - } - ee.EncodeMapEnd() + ee.EncodeFloat32(v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapStringFloat64R(rv reflect.Value) { @@ -4092,32 +3550,15 @@ func (_ fastpathT) EncMapStringFloat64V(v map[string]float64, checkNil bool, e * } ee.EncodeMapStart(len(v)) asSymbols := e.h.AsSymbols&AsSymbolMapStringKeysFlag != 0 - if e.be { - for k2, v2 := range v { - if asSymbols { - ee.EncodeSymbol(k2) - } else { - ee.EncodeString(c_UTF8, k2) - } - ee.EncodeFloat64(v2) + for k2, v2 := range v { + if asSymbols { + ee.EncodeSymbol(k2) + } else { + ee.EncodeString(c_UTF8, k2) } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - if asSymbols { - ee.EncodeSymbol(k2) - } else { - ee.EncodeString(c_UTF8, k2) - } - ee.EncodeMapKVSeparator() - ee.EncodeFloat64(v2) - j++ - } - ee.EncodeMapEnd() + ee.EncodeFloat64(v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapStringBoolR(rv reflect.Value) { @@ -4131,32 +3572,15 @@ func (_ fastpathT) EncMapStringBoolV(v map[string]bool, checkNil bool, e *Encode } ee.EncodeMapStart(len(v)) asSymbols := e.h.AsSymbols&AsSymbolMapStringKeysFlag != 0 - if e.be { - for k2, v2 := range v { - if asSymbols { - ee.EncodeSymbol(k2) - } else { - ee.EncodeString(c_UTF8, k2) - } - ee.EncodeBool(v2) + for k2, v2 := range v { + if asSymbols { + ee.EncodeSymbol(k2) + } else { + ee.EncodeString(c_UTF8, k2) } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - if asSymbols { - ee.EncodeSymbol(k2) - } else { - ee.EncodeString(c_UTF8, k2) - } - ee.EncodeMapKVSeparator() - ee.EncodeBool(v2) - j++ - } - ee.EncodeMapEnd() + ee.EncodeBool(v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapFloat32IntfR(rv reflect.Value) { @@ -4170,24 +3594,11 @@ func (_ fastpathT) EncMapFloat32IntfV(v map[float32]interface{}, checkNil bool, } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeFloat32(k2) - e.encode(v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeFloat32(k2) - ee.EncodeMapKVSeparator() - e.encode(v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeFloat32(k2) + e.encode(v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapFloat32StringR(rv reflect.Value) { @@ -4201,24 +3612,11 @@ func (_ fastpathT) EncMapFloat32StringV(v map[float32]string, checkNil bool, e * } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeFloat32(k2) - ee.EncodeString(c_UTF8, v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeFloat32(k2) - ee.EncodeMapKVSeparator() - ee.EncodeString(c_UTF8, v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeFloat32(k2) + ee.EncodeString(c_UTF8, v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapFloat32UintR(rv reflect.Value) { @@ -4232,24 +3630,11 @@ func (_ fastpathT) EncMapFloat32UintV(v map[float32]uint, checkNil bool, e *Enco } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeFloat32(k2) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeFloat32(k2) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeFloat32(k2) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapFloat32Uint8R(rv reflect.Value) { @@ -4263,24 +3648,11 @@ func (_ fastpathT) EncMapFloat32Uint8V(v map[float32]uint8, checkNil bool, e *En } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeFloat32(k2) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeFloat32(k2) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeFloat32(k2) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapFloat32Uint16R(rv reflect.Value) { @@ -4294,24 +3666,11 @@ func (_ fastpathT) EncMapFloat32Uint16V(v map[float32]uint16, checkNil bool, e * } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeFloat32(k2) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeFloat32(k2) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeFloat32(k2) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapFloat32Uint32R(rv reflect.Value) { @@ -4325,24 +3684,11 @@ func (_ fastpathT) EncMapFloat32Uint32V(v map[float32]uint32, checkNil bool, e * } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeFloat32(k2) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeFloat32(k2) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeFloat32(k2) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapFloat32Uint64R(rv reflect.Value) { @@ -4356,24 +3702,11 @@ func (_ fastpathT) EncMapFloat32Uint64V(v map[float32]uint64, checkNil bool, e * } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeFloat32(k2) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeFloat32(k2) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeFloat32(k2) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapFloat32IntR(rv reflect.Value) { @@ -4387,24 +3720,11 @@ func (_ fastpathT) EncMapFloat32IntV(v map[float32]int, checkNil bool, e *Encode } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeFloat32(k2) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeFloat32(k2) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeFloat32(k2) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapFloat32Int8R(rv reflect.Value) { @@ -4418,24 +3738,11 @@ func (_ fastpathT) EncMapFloat32Int8V(v map[float32]int8, checkNil bool, e *Enco } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeFloat32(k2) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeFloat32(k2) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeFloat32(k2) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapFloat32Int16R(rv reflect.Value) { @@ -4449,24 +3756,11 @@ func (_ fastpathT) EncMapFloat32Int16V(v map[float32]int16, checkNil bool, e *En } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeFloat32(k2) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeFloat32(k2) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeFloat32(k2) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapFloat32Int32R(rv reflect.Value) { @@ -4480,24 +3774,11 @@ func (_ fastpathT) EncMapFloat32Int32V(v map[float32]int32, checkNil bool, e *En } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeFloat32(k2) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeFloat32(k2) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeFloat32(k2) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapFloat32Int64R(rv reflect.Value) { @@ -4511,24 +3792,11 @@ func (_ fastpathT) EncMapFloat32Int64V(v map[float32]int64, checkNil bool, e *En } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeFloat32(k2) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeFloat32(k2) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeFloat32(k2) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapFloat32Float32R(rv reflect.Value) { @@ -4542,24 +3810,11 @@ func (_ fastpathT) EncMapFloat32Float32V(v map[float32]float32, checkNil bool, e } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeFloat32(k2) - ee.EncodeFloat32(v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeFloat32(k2) - ee.EncodeMapKVSeparator() - ee.EncodeFloat32(v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeFloat32(k2) + ee.EncodeFloat32(v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapFloat32Float64R(rv reflect.Value) { @@ -4573,24 +3828,11 @@ func (_ fastpathT) EncMapFloat32Float64V(v map[float32]float64, checkNil bool, e } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeFloat32(k2) - ee.EncodeFloat64(v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeFloat32(k2) - ee.EncodeMapKVSeparator() - ee.EncodeFloat64(v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeFloat32(k2) + ee.EncodeFloat64(v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapFloat32BoolR(rv reflect.Value) { @@ -4604,24 +3846,11 @@ func (_ fastpathT) EncMapFloat32BoolV(v map[float32]bool, checkNil bool, e *Enco } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeFloat32(k2) - ee.EncodeBool(v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeFloat32(k2) - ee.EncodeMapKVSeparator() - ee.EncodeBool(v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeFloat32(k2) + ee.EncodeBool(v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapFloat64IntfR(rv reflect.Value) { @@ -4635,24 +3864,11 @@ func (_ fastpathT) EncMapFloat64IntfV(v map[float64]interface{}, checkNil bool, } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeFloat64(k2) - e.encode(v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeFloat64(k2) - ee.EncodeMapKVSeparator() - e.encode(v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeFloat64(k2) + e.encode(v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapFloat64StringR(rv reflect.Value) { @@ -4666,24 +3882,11 @@ func (_ fastpathT) EncMapFloat64StringV(v map[float64]string, checkNil bool, e * } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeFloat64(k2) - ee.EncodeString(c_UTF8, v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeFloat64(k2) - ee.EncodeMapKVSeparator() - ee.EncodeString(c_UTF8, v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeFloat64(k2) + ee.EncodeString(c_UTF8, v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapFloat64UintR(rv reflect.Value) { @@ -4697,24 +3900,11 @@ func (_ fastpathT) EncMapFloat64UintV(v map[float64]uint, checkNil bool, e *Enco } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeFloat64(k2) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeFloat64(k2) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeFloat64(k2) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapFloat64Uint8R(rv reflect.Value) { @@ -4728,24 +3918,11 @@ func (_ fastpathT) EncMapFloat64Uint8V(v map[float64]uint8, checkNil bool, e *En } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeFloat64(k2) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeFloat64(k2) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeFloat64(k2) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapFloat64Uint16R(rv reflect.Value) { @@ -4759,24 +3936,11 @@ func (_ fastpathT) EncMapFloat64Uint16V(v map[float64]uint16, checkNil bool, e * } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeFloat64(k2) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeFloat64(k2) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeFloat64(k2) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapFloat64Uint32R(rv reflect.Value) { @@ -4790,24 +3954,11 @@ func (_ fastpathT) EncMapFloat64Uint32V(v map[float64]uint32, checkNil bool, e * } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeFloat64(k2) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeFloat64(k2) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeFloat64(k2) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapFloat64Uint64R(rv reflect.Value) { @@ -4821,24 +3972,11 @@ func (_ fastpathT) EncMapFloat64Uint64V(v map[float64]uint64, checkNil bool, e * } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeFloat64(k2) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeFloat64(k2) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeFloat64(k2) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapFloat64IntR(rv reflect.Value) { @@ -4852,24 +3990,11 @@ func (_ fastpathT) EncMapFloat64IntV(v map[float64]int, checkNil bool, e *Encode } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeFloat64(k2) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeFloat64(k2) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeFloat64(k2) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapFloat64Int8R(rv reflect.Value) { @@ -4883,24 +4008,11 @@ func (_ fastpathT) EncMapFloat64Int8V(v map[float64]int8, checkNil bool, e *Enco } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeFloat64(k2) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeFloat64(k2) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeFloat64(k2) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapFloat64Int16R(rv reflect.Value) { @@ -4914,24 +4026,11 @@ func (_ fastpathT) EncMapFloat64Int16V(v map[float64]int16, checkNil bool, e *En } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeFloat64(k2) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeFloat64(k2) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeFloat64(k2) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapFloat64Int32R(rv reflect.Value) { @@ -4945,24 +4044,11 @@ func (_ fastpathT) EncMapFloat64Int32V(v map[float64]int32, checkNil bool, e *En } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeFloat64(k2) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeFloat64(k2) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeFloat64(k2) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapFloat64Int64R(rv reflect.Value) { @@ -4976,24 +4062,11 @@ func (_ fastpathT) EncMapFloat64Int64V(v map[float64]int64, checkNil bool, e *En } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeFloat64(k2) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeFloat64(k2) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeFloat64(k2) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapFloat64Float32R(rv reflect.Value) { @@ -5007,24 +4080,11 @@ func (_ fastpathT) EncMapFloat64Float32V(v map[float64]float32, checkNil bool, e } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeFloat64(k2) - ee.EncodeFloat32(v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeFloat64(k2) - ee.EncodeMapKVSeparator() - ee.EncodeFloat32(v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeFloat64(k2) + ee.EncodeFloat32(v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapFloat64Float64R(rv reflect.Value) { @@ -5038,24 +4098,11 @@ func (_ fastpathT) EncMapFloat64Float64V(v map[float64]float64, checkNil bool, e } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeFloat64(k2) - ee.EncodeFloat64(v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeFloat64(k2) - ee.EncodeMapKVSeparator() - ee.EncodeFloat64(v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeFloat64(k2) + ee.EncodeFloat64(v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapFloat64BoolR(rv reflect.Value) { @@ -5069,24 +4116,11 @@ func (_ fastpathT) EncMapFloat64BoolV(v map[float64]bool, checkNil bool, e *Enco } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeFloat64(k2) - ee.EncodeBool(v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeFloat64(k2) - ee.EncodeMapKVSeparator() - ee.EncodeBool(v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeFloat64(k2) + ee.EncodeBool(v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUintIntfR(rv reflect.Value) { @@ -5100,24 +4134,11 @@ func (_ fastpathT) EncMapUintIntfV(v map[uint]interface{}, checkNil bool, e *Enc } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - e.encode(v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - e.encode(v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + e.encode(v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUintStringR(rv reflect.Value) { @@ -5131,24 +4152,11 @@ func (_ fastpathT) EncMapUintStringV(v map[uint]string, checkNil bool, e *Encode } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeString(c_UTF8, v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeString(c_UTF8, v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeString(c_UTF8, v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUintUintR(rv reflect.Value) { @@ -5162,24 +4170,11 @@ func (_ fastpathT) EncMapUintUintV(v map[uint]uint, checkNil bool, e *Encoder) { } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUintUint8R(rv reflect.Value) { @@ -5193,24 +4188,11 @@ func (_ fastpathT) EncMapUintUint8V(v map[uint]uint8, checkNil bool, e *Encoder) } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUintUint16R(rv reflect.Value) { @@ -5224,24 +4206,11 @@ func (_ fastpathT) EncMapUintUint16V(v map[uint]uint16, checkNil bool, e *Encode } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUintUint32R(rv reflect.Value) { @@ -5255,24 +4224,11 @@ func (_ fastpathT) EncMapUintUint32V(v map[uint]uint32, checkNil bool, e *Encode } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUintUint64R(rv reflect.Value) { @@ -5286,24 +4242,11 @@ func (_ fastpathT) EncMapUintUint64V(v map[uint]uint64, checkNil bool, e *Encode } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUintIntR(rv reflect.Value) { @@ -5317,24 +4260,11 @@ func (_ fastpathT) EncMapUintIntV(v map[uint]int, checkNil bool, e *Encoder) { } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUintInt8R(rv reflect.Value) { @@ -5348,24 +4278,11 @@ func (_ fastpathT) EncMapUintInt8V(v map[uint]int8, checkNil bool, e *Encoder) { } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUintInt16R(rv reflect.Value) { @@ -5379,24 +4296,11 @@ func (_ fastpathT) EncMapUintInt16V(v map[uint]int16, checkNil bool, e *Encoder) } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUintInt32R(rv reflect.Value) { @@ -5410,24 +4314,11 @@ func (_ fastpathT) EncMapUintInt32V(v map[uint]int32, checkNil bool, e *Encoder) } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUintInt64R(rv reflect.Value) { @@ -5441,24 +4332,11 @@ func (_ fastpathT) EncMapUintInt64V(v map[uint]int64, checkNil bool, e *Encoder) } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUintFloat32R(rv reflect.Value) { @@ -5472,24 +4350,11 @@ func (_ fastpathT) EncMapUintFloat32V(v map[uint]float32, checkNil bool, e *Enco } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeFloat32(v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeFloat32(v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeFloat32(v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUintFloat64R(rv reflect.Value) { @@ -5503,24 +4368,11 @@ func (_ fastpathT) EncMapUintFloat64V(v map[uint]float64, checkNil bool, e *Enco } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeFloat64(v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeFloat64(v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeFloat64(v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUintBoolR(rv reflect.Value) { @@ -5534,24 +4386,11 @@ func (_ fastpathT) EncMapUintBoolV(v map[uint]bool, checkNil bool, e *Encoder) { } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeBool(v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeBool(v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeBool(v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUint8IntfR(rv reflect.Value) { @@ -5565,24 +4404,11 @@ func (_ fastpathT) EncMapUint8IntfV(v map[uint8]interface{}, checkNil bool, e *E } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - e.encode(v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - e.encode(v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + e.encode(v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUint8StringR(rv reflect.Value) { @@ -5596,24 +4422,11 @@ func (_ fastpathT) EncMapUint8StringV(v map[uint8]string, checkNil bool, e *Enco } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeString(c_UTF8, v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeString(c_UTF8, v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeString(c_UTF8, v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUint8UintR(rv reflect.Value) { @@ -5627,24 +4440,11 @@ func (_ fastpathT) EncMapUint8UintV(v map[uint8]uint, checkNil bool, e *Encoder) } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUint8Uint8R(rv reflect.Value) { @@ -5658,24 +4458,11 @@ func (_ fastpathT) EncMapUint8Uint8V(v map[uint8]uint8, checkNil bool, e *Encode } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUint8Uint16R(rv reflect.Value) { @@ -5689,24 +4476,11 @@ func (_ fastpathT) EncMapUint8Uint16V(v map[uint8]uint16, checkNil bool, e *Enco } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUint8Uint32R(rv reflect.Value) { @@ -5720,24 +4494,11 @@ func (_ fastpathT) EncMapUint8Uint32V(v map[uint8]uint32, checkNil bool, e *Enco } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUint8Uint64R(rv reflect.Value) { @@ -5751,24 +4512,11 @@ func (_ fastpathT) EncMapUint8Uint64V(v map[uint8]uint64, checkNil bool, e *Enco } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUint8IntR(rv reflect.Value) { @@ -5782,24 +4530,11 @@ func (_ fastpathT) EncMapUint8IntV(v map[uint8]int, checkNil bool, e *Encoder) { } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUint8Int8R(rv reflect.Value) { @@ -5813,24 +4548,11 @@ func (_ fastpathT) EncMapUint8Int8V(v map[uint8]int8, checkNil bool, e *Encoder) } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUint8Int16R(rv reflect.Value) { @@ -5844,24 +4566,11 @@ func (_ fastpathT) EncMapUint8Int16V(v map[uint8]int16, checkNil bool, e *Encode } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUint8Int32R(rv reflect.Value) { @@ -5875,24 +4584,11 @@ func (_ fastpathT) EncMapUint8Int32V(v map[uint8]int32, checkNil bool, e *Encode } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUint8Int64R(rv reflect.Value) { @@ -5906,24 +4602,11 @@ func (_ fastpathT) EncMapUint8Int64V(v map[uint8]int64, checkNil bool, e *Encode } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUint8Float32R(rv reflect.Value) { @@ -5937,24 +4620,11 @@ func (_ fastpathT) EncMapUint8Float32V(v map[uint8]float32, checkNil bool, e *En } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeFloat32(v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeFloat32(v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeFloat32(v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUint8Float64R(rv reflect.Value) { @@ -5968,24 +4638,11 @@ func (_ fastpathT) EncMapUint8Float64V(v map[uint8]float64, checkNil bool, e *En } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeFloat64(v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeFloat64(v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeFloat64(v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUint8BoolR(rv reflect.Value) { @@ -5999,24 +4656,11 @@ func (_ fastpathT) EncMapUint8BoolV(v map[uint8]bool, checkNil bool, e *Encoder) } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeBool(v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeBool(v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeBool(v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUint16IntfR(rv reflect.Value) { @@ -6030,24 +4674,11 @@ func (_ fastpathT) EncMapUint16IntfV(v map[uint16]interface{}, checkNil bool, e } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - e.encode(v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - e.encode(v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + e.encode(v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUint16StringR(rv reflect.Value) { @@ -6061,24 +4692,11 @@ func (_ fastpathT) EncMapUint16StringV(v map[uint16]string, checkNil bool, e *En } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeString(c_UTF8, v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeString(c_UTF8, v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeString(c_UTF8, v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUint16UintR(rv reflect.Value) { @@ -6092,24 +4710,11 @@ func (_ fastpathT) EncMapUint16UintV(v map[uint16]uint, checkNil bool, e *Encode } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUint16Uint8R(rv reflect.Value) { @@ -6123,24 +4728,11 @@ func (_ fastpathT) EncMapUint16Uint8V(v map[uint16]uint8, checkNil bool, e *Enco } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUint16Uint16R(rv reflect.Value) { @@ -6154,24 +4746,11 @@ func (_ fastpathT) EncMapUint16Uint16V(v map[uint16]uint16, checkNil bool, e *En } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUint16Uint32R(rv reflect.Value) { @@ -6185,24 +4764,11 @@ func (_ fastpathT) EncMapUint16Uint32V(v map[uint16]uint32, checkNil bool, e *En } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUint16Uint64R(rv reflect.Value) { @@ -6216,24 +4782,11 @@ func (_ fastpathT) EncMapUint16Uint64V(v map[uint16]uint64, checkNil bool, e *En } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUint16IntR(rv reflect.Value) { @@ -6247,24 +4800,11 @@ func (_ fastpathT) EncMapUint16IntV(v map[uint16]int, checkNil bool, e *Encoder) } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUint16Int8R(rv reflect.Value) { @@ -6278,24 +4818,11 @@ func (_ fastpathT) EncMapUint16Int8V(v map[uint16]int8, checkNil bool, e *Encode } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUint16Int16R(rv reflect.Value) { @@ -6309,24 +4836,11 @@ func (_ fastpathT) EncMapUint16Int16V(v map[uint16]int16, checkNil bool, e *Enco } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUint16Int32R(rv reflect.Value) { @@ -6340,24 +4854,11 @@ func (_ fastpathT) EncMapUint16Int32V(v map[uint16]int32, checkNil bool, e *Enco } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUint16Int64R(rv reflect.Value) { @@ -6371,24 +4872,11 @@ func (_ fastpathT) EncMapUint16Int64V(v map[uint16]int64, checkNil bool, e *Enco } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUint16Float32R(rv reflect.Value) { @@ -6402,24 +4890,11 @@ func (_ fastpathT) EncMapUint16Float32V(v map[uint16]float32, checkNil bool, e * } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeFloat32(v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeFloat32(v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeFloat32(v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUint16Float64R(rv reflect.Value) { @@ -6433,24 +4908,11 @@ func (_ fastpathT) EncMapUint16Float64V(v map[uint16]float64, checkNil bool, e * } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeFloat64(v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeFloat64(v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeFloat64(v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUint16BoolR(rv reflect.Value) { @@ -6464,24 +4926,11 @@ func (_ fastpathT) EncMapUint16BoolV(v map[uint16]bool, checkNil bool, e *Encode } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeBool(v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeBool(v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeBool(v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUint32IntfR(rv reflect.Value) { @@ -6495,24 +4944,11 @@ func (_ fastpathT) EncMapUint32IntfV(v map[uint32]interface{}, checkNil bool, e } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - e.encode(v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - e.encode(v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + e.encode(v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUint32StringR(rv reflect.Value) { @@ -6526,24 +4962,11 @@ func (_ fastpathT) EncMapUint32StringV(v map[uint32]string, checkNil bool, e *En } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeString(c_UTF8, v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeString(c_UTF8, v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeString(c_UTF8, v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUint32UintR(rv reflect.Value) { @@ -6557,24 +4980,11 @@ func (_ fastpathT) EncMapUint32UintV(v map[uint32]uint, checkNil bool, e *Encode } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUint32Uint8R(rv reflect.Value) { @@ -6588,24 +4998,11 @@ func (_ fastpathT) EncMapUint32Uint8V(v map[uint32]uint8, checkNil bool, e *Enco } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUint32Uint16R(rv reflect.Value) { @@ -6619,24 +5016,11 @@ func (_ fastpathT) EncMapUint32Uint16V(v map[uint32]uint16, checkNil bool, e *En } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUint32Uint32R(rv reflect.Value) { @@ -6650,24 +5034,11 @@ func (_ fastpathT) EncMapUint32Uint32V(v map[uint32]uint32, checkNil bool, e *En } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUint32Uint64R(rv reflect.Value) { @@ -6681,24 +5052,11 @@ func (_ fastpathT) EncMapUint32Uint64V(v map[uint32]uint64, checkNil bool, e *En } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUint32IntR(rv reflect.Value) { @@ -6712,24 +5070,11 @@ func (_ fastpathT) EncMapUint32IntV(v map[uint32]int, checkNil bool, e *Encoder) } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUint32Int8R(rv reflect.Value) { @@ -6743,24 +5088,11 @@ func (_ fastpathT) EncMapUint32Int8V(v map[uint32]int8, checkNil bool, e *Encode } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUint32Int16R(rv reflect.Value) { @@ -6774,24 +5106,11 @@ func (_ fastpathT) EncMapUint32Int16V(v map[uint32]int16, checkNil bool, e *Enco } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUint32Int32R(rv reflect.Value) { @@ -6805,24 +5124,11 @@ func (_ fastpathT) EncMapUint32Int32V(v map[uint32]int32, checkNil bool, e *Enco } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUint32Int64R(rv reflect.Value) { @@ -6836,24 +5142,11 @@ func (_ fastpathT) EncMapUint32Int64V(v map[uint32]int64, checkNil bool, e *Enco } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUint32Float32R(rv reflect.Value) { @@ -6867,24 +5160,11 @@ func (_ fastpathT) EncMapUint32Float32V(v map[uint32]float32, checkNil bool, e * } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeFloat32(v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeFloat32(v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeFloat32(v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUint32Float64R(rv reflect.Value) { @@ -6898,24 +5178,11 @@ func (_ fastpathT) EncMapUint32Float64V(v map[uint32]float64, checkNil bool, e * } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeFloat64(v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeFloat64(v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeFloat64(v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUint32BoolR(rv reflect.Value) { @@ -6929,24 +5196,11 @@ func (_ fastpathT) EncMapUint32BoolV(v map[uint32]bool, checkNil bool, e *Encode } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeBool(v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeBool(v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeBool(v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUint64IntfR(rv reflect.Value) { @@ -6960,24 +5214,11 @@ func (_ fastpathT) EncMapUint64IntfV(v map[uint64]interface{}, checkNil bool, e } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - e.encode(v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - e.encode(v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + e.encode(v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUint64StringR(rv reflect.Value) { @@ -6991,24 +5232,11 @@ func (_ fastpathT) EncMapUint64StringV(v map[uint64]string, checkNil bool, e *En } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeString(c_UTF8, v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeString(c_UTF8, v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeString(c_UTF8, v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUint64UintR(rv reflect.Value) { @@ -7022,24 +5250,11 @@ func (_ fastpathT) EncMapUint64UintV(v map[uint64]uint, checkNil bool, e *Encode } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUint64Uint8R(rv reflect.Value) { @@ -7053,24 +5268,11 @@ func (_ fastpathT) EncMapUint64Uint8V(v map[uint64]uint8, checkNil bool, e *Enco } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUint64Uint16R(rv reflect.Value) { @@ -7084,24 +5286,11 @@ func (_ fastpathT) EncMapUint64Uint16V(v map[uint64]uint16, checkNil bool, e *En } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUint64Uint32R(rv reflect.Value) { @@ -7115,24 +5304,11 @@ func (_ fastpathT) EncMapUint64Uint32V(v map[uint64]uint32, checkNil bool, e *En } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUint64Uint64R(rv reflect.Value) { @@ -7146,24 +5322,11 @@ func (_ fastpathT) EncMapUint64Uint64V(v map[uint64]uint64, checkNil bool, e *En } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUint64IntR(rv reflect.Value) { @@ -7177,24 +5340,11 @@ func (_ fastpathT) EncMapUint64IntV(v map[uint64]int, checkNil bool, e *Encoder) } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUint64Int8R(rv reflect.Value) { @@ -7208,24 +5358,11 @@ func (_ fastpathT) EncMapUint64Int8V(v map[uint64]int8, checkNil bool, e *Encode } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUint64Int16R(rv reflect.Value) { @@ -7239,24 +5376,11 @@ func (_ fastpathT) EncMapUint64Int16V(v map[uint64]int16, checkNil bool, e *Enco } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUint64Int32R(rv reflect.Value) { @@ -7270,24 +5394,11 @@ func (_ fastpathT) EncMapUint64Int32V(v map[uint64]int32, checkNil bool, e *Enco } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUint64Int64R(rv reflect.Value) { @@ -7301,24 +5412,11 @@ func (_ fastpathT) EncMapUint64Int64V(v map[uint64]int64, checkNil bool, e *Enco } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUint64Float32R(rv reflect.Value) { @@ -7332,24 +5430,11 @@ func (_ fastpathT) EncMapUint64Float32V(v map[uint64]float32, checkNil bool, e * } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeFloat32(v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeFloat32(v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeFloat32(v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUint64Float64R(rv reflect.Value) { @@ -7363,24 +5448,11 @@ func (_ fastpathT) EncMapUint64Float64V(v map[uint64]float64, checkNil bool, e * } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeFloat64(v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeFloat64(v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeFloat64(v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapUint64BoolR(rv reflect.Value) { @@ -7394,24 +5466,11 @@ func (_ fastpathT) EncMapUint64BoolV(v map[uint64]bool, checkNil bool, e *Encode } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeUint(uint64(k2)) - ee.EncodeBool(v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeUint(uint64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeBool(v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeUint(uint64(k2)) + ee.EncodeBool(v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapIntIntfR(rv reflect.Value) { @@ -7425,24 +5484,11 @@ func (_ fastpathT) EncMapIntIntfV(v map[int]interface{}, checkNil bool, e *Encod } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - e.encode(v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - e.encode(v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + e.encode(v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapIntStringR(rv reflect.Value) { @@ -7456,24 +5502,11 @@ func (_ fastpathT) EncMapIntStringV(v map[int]string, checkNil bool, e *Encoder) } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeString(c_UTF8, v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeString(c_UTF8, v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeString(c_UTF8, v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapIntUintR(rv reflect.Value) { @@ -7487,24 +5520,11 @@ func (_ fastpathT) EncMapIntUintV(v map[int]uint, checkNil bool, e *Encoder) { } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapIntUint8R(rv reflect.Value) { @@ -7518,24 +5538,11 @@ func (_ fastpathT) EncMapIntUint8V(v map[int]uint8, checkNil bool, e *Encoder) { } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapIntUint16R(rv reflect.Value) { @@ -7549,24 +5556,11 @@ func (_ fastpathT) EncMapIntUint16V(v map[int]uint16, checkNil bool, e *Encoder) } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapIntUint32R(rv reflect.Value) { @@ -7580,24 +5574,11 @@ func (_ fastpathT) EncMapIntUint32V(v map[int]uint32, checkNil bool, e *Encoder) } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapIntUint64R(rv reflect.Value) { @@ -7611,24 +5592,11 @@ func (_ fastpathT) EncMapIntUint64V(v map[int]uint64, checkNil bool, e *Encoder) } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapIntIntR(rv reflect.Value) { @@ -7642,24 +5610,11 @@ func (_ fastpathT) EncMapIntIntV(v map[int]int, checkNil bool, e *Encoder) { } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapIntInt8R(rv reflect.Value) { @@ -7673,24 +5628,11 @@ func (_ fastpathT) EncMapIntInt8V(v map[int]int8, checkNil bool, e *Encoder) { } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapIntInt16R(rv reflect.Value) { @@ -7704,24 +5646,11 @@ func (_ fastpathT) EncMapIntInt16V(v map[int]int16, checkNil bool, e *Encoder) { } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapIntInt32R(rv reflect.Value) { @@ -7735,24 +5664,11 @@ func (_ fastpathT) EncMapIntInt32V(v map[int]int32, checkNil bool, e *Encoder) { } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapIntInt64R(rv reflect.Value) { @@ -7766,24 +5682,11 @@ func (_ fastpathT) EncMapIntInt64V(v map[int]int64, checkNil bool, e *Encoder) { } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapIntFloat32R(rv reflect.Value) { @@ -7797,24 +5700,11 @@ func (_ fastpathT) EncMapIntFloat32V(v map[int]float32, checkNil bool, e *Encode } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeFloat32(v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeFloat32(v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeFloat32(v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapIntFloat64R(rv reflect.Value) { @@ -7828,24 +5718,11 @@ func (_ fastpathT) EncMapIntFloat64V(v map[int]float64, checkNil bool, e *Encode } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeFloat64(v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeFloat64(v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeFloat64(v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapIntBoolR(rv reflect.Value) { @@ -7859,24 +5736,11 @@ func (_ fastpathT) EncMapIntBoolV(v map[int]bool, checkNil bool, e *Encoder) { } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeBool(v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeBool(v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeBool(v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapInt8IntfR(rv reflect.Value) { @@ -7890,24 +5754,11 @@ func (_ fastpathT) EncMapInt8IntfV(v map[int8]interface{}, checkNil bool, e *Enc } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - e.encode(v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - e.encode(v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + e.encode(v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapInt8StringR(rv reflect.Value) { @@ -7921,24 +5772,11 @@ func (_ fastpathT) EncMapInt8StringV(v map[int8]string, checkNil bool, e *Encode } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeString(c_UTF8, v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeString(c_UTF8, v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeString(c_UTF8, v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapInt8UintR(rv reflect.Value) { @@ -7952,24 +5790,11 @@ func (_ fastpathT) EncMapInt8UintV(v map[int8]uint, checkNil bool, e *Encoder) { } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapInt8Uint8R(rv reflect.Value) { @@ -7983,24 +5808,11 @@ func (_ fastpathT) EncMapInt8Uint8V(v map[int8]uint8, checkNil bool, e *Encoder) } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapInt8Uint16R(rv reflect.Value) { @@ -8014,24 +5826,11 @@ func (_ fastpathT) EncMapInt8Uint16V(v map[int8]uint16, checkNil bool, e *Encode } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapInt8Uint32R(rv reflect.Value) { @@ -8045,24 +5844,11 @@ func (_ fastpathT) EncMapInt8Uint32V(v map[int8]uint32, checkNil bool, e *Encode } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapInt8Uint64R(rv reflect.Value) { @@ -8076,24 +5862,11 @@ func (_ fastpathT) EncMapInt8Uint64V(v map[int8]uint64, checkNil bool, e *Encode } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapInt8IntR(rv reflect.Value) { @@ -8107,24 +5880,11 @@ func (_ fastpathT) EncMapInt8IntV(v map[int8]int, checkNil bool, e *Encoder) { } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapInt8Int8R(rv reflect.Value) { @@ -8138,24 +5898,11 @@ func (_ fastpathT) EncMapInt8Int8V(v map[int8]int8, checkNil bool, e *Encoder) { } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapInt8Int16R(rv reflect.Value) { @@ -8169,24 +5916,11 @@ func (_ fastpathT) EncMapInt8Int16V(v map[int8]int16, checkNil bool, e *Encoder) } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapInt8Int32R(rv reflect.Value) { @@ -8200,24 +5934,11 @@ func (_ fastpathT) EncMapInt8Int32V(v map[int8]int32, checkNil bool, e *Encoder) } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapInt8Int64R(rv reflect.Value) { @@ -8231,24 +5952,11 @@ func (_ fastpathT) EncMapInt8Int64V(v map[int8]int64, checkNil bool, e *Encoder) } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapInt8Float32R(rv reflect.Value) { @@ -8262,24 +5970,11 @@ func (_ fastpathT) EncMapInt8Float32V(v map[int8]float32, checkNil bool, e *Enco } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeFloat32(v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeFloat32(v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeFloat32(v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapInt8Float64R(rv reflect.Value) { @@ -8293,24 +5988,11 @@ func (_ fastpathT) EncMapInt8Float64V(v map[int8]float64, checkNil bool, e *Enco } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeFloat64(v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeFloat64(v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeFloat64(v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapInt8BoolR(rv reflect.Value) { @@ -8324,24 +6006,11 @@ func (_ fastpathT) EncMapInt8BoolV(v map[int8]bool, checkNil bool, e *Encoder) { } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeBool(v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeBool(v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeBool(v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapInt16IntfR(rv reflect.Value) { @@ -8355,24 +6024,11 @@ func (_ fastpathT) EncMapInt16IntfV(v map[int16]interface{}, checkNil bool, e *E } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - e.encode(v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - e.encode(v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + e.encode(v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapInt16StringR(rv reflect.Value) { @@ -8386,24 +6042,11 @@ func (_ fastpathT) EncMapInt16StringV(v map[int16]string, checkNil bool, e *Enco } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeString(c_UTF8, v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeString(c_UTF8, v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeString(c_UTF8, v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapInt16UintR(rv reflect.Value) { @@ -8417,24 +6060,11 @@ func (_ fastpathT) EncMapInt16UintV(v map[int16]uint, checkNil bool, e *Encoder) } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapInt16Uint8R(rv reflect.Value) { @@ -8448,24 +6078,11 @@ func (_ fastpathT) EncMapInt16Uint8V(v map[int16]uint8, checkNil bool, e *Encode } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapInt16Uint16R(rv reflect.Value) { @@ -8479,24 +6096,11 @@ func (_ fastpathT) EncMapInt16Uint16V(v map[int16]uint16, checkNil bool, e *Enco } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapInt16Uint32R(rv reflect.Value) { @@ -8510,24 +6114,11 @@ func (_ fastpathT) EncMapInt16Uint32V(v map[int16]uint32, checkNil bool, e *Enco } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapInt16Uint64R(rv reflect.Value) { @@ -8541,24 +6132,11 @@ func (_ fastpathT) EncMapInt16Uint64V(v map[int16]uint64, checkNil bool, e *Enco } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapInt16IntR(rv reflect.Value) { @@ -8572,24 +6150,11 @@ func (_ fastpathT) EncMapInt16IntV(v map[int16]int, checkNil bool, e *Encoder) { } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapInt16Int8R(rv reflect.Value) { @@ -8603,24 +6168,11 @@ func (_ fastpathT) EncMapInt16Int8V(v map[int16]int8, checkNil bool, e *Encoder) } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapInt16Int16R(rv reflect.Value) { @@ -8634,24 +6186,11 @@ func (_ fastpathT) EncMapInt16Int16V(v map[int16]int16, checkNil bool, e *Encode } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapInt16Int32R(rv reflect.Value) { @@ -8665,24 +6204,11 @@ func (_ fastpathT) EncMapInt16Int32V(v map[int16]int32, checkNil bool, e *Encode } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapInt16Int64R(rv reflect.Value) { @@ -8696,24 +6222,11 @@ func (_ fastpathT) EncMapInt16Int64V(v map[int16]int64, checkNil bool, e *Encode } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapInt16Float32R(rv reflect.Value) { @@ -8727,24 +6240,11 @@ func (_ fastpathT) EncMapInt16Float32V(v map[int16]float32, checkNil bool, e *En } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeFloat32(v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeFloat32(v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeFloat32(v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapInt16Float64R(rv reflect.Value) { @@ -8758,24 +6258,11 @@ func (_ fastpathT) EncMapInt16Float64V(v map[int16]float64, checkNil bool, e *En } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeFloat64(v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeFloat64(v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeFloat64(v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapInt16BoolR(rv reflect.Value) { @@ -8789,24 +6276,11 @@ func (_ fastpathT) EncMapInt16BoolV(v map[int16]bool, checkNil bool, e *Encoder) } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeBool(v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeBool(v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeBool(v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapInt32IntfR(rv reflect.Value) { @@ -8820,24 +6294,11 @@ func (_ fastpathT) EncMapInt32IntfV(v map[int32]interface{}, checkNil bool, e *E } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - e.encode(v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - e.encode(v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + e.encode(v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapInt32StringR(rv reflect.Value) { @@ -8851,24 +6312,11 @@ func (_ fastpathT) EncMapInt32StringV(v map[int32]string, checkNil bool, e *Enco } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeString(c_UTF8, v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeString(c_UTF8, v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeString(c_UTF8, v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapInt32UintR(rv reflect.Value) { @@ -8882,24 +6330,11 @@ func (_ fastpathT) EncMapInt32UintV(v map[int32]uint, checkNil bool, e *Encoder) } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapInt32Uint8R(rv reflect.Value) { @@ -8913,24 +6348,11 @@ func (_ fastpathT) EncMapInt32Uint8V(v map[int32]uint8, checkNil bool, e *Encode } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapInt32Uint16R(rv reflect.Value) { @@ -8944,24 +6366,11 @@ func (_ fastpathT) EncMapInt32Uint16V(v map[int32]uint16, checkNil bool, e *Enco } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapInt32Uint32R(rv reflect.Value) { @@ -8975,24 +6384,11 @@ func (_ fastpathT) EncMapInt32Uint32V(v map[int32]uint32, checkNil bool, e *Enco } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapInt32Uint64R(rv reflect.Value) { @@ -9006,24 +6402,11 @@ func (_ fastpathT) EncMapInt32Uint64V(v map[int32]uint64, checkNil bool, e *Enco } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapInt32IntR(rv reflect.Value) { @@ -9037,24 +6420,11 @@ func (_ fastpathT) EncMapInt32IntV(v map[int32]int, checkNil bool, e *Encoder) { } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapInt32Int8R(rv reflect.Value) { @@ -9068,24 +6438,11 @@ func (_ fastpathT) EncMapInt32Int8V(v map[int32]int8, checkNil bool, e *Encoder) } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapInt32Int16R(rv reflect.Value) { @@ -9099,24 +6456,11 @@ func (_ fastpathT) EncMapInt32Int16V(v map[int32]int16, checkNil bool, e *Encode } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapInt32Int32R(rv reflect.Value) { @@ -9130,24 +6474,11 @@ func (_ fastpathT) EncMapInt32Int32V(v map[int32]int32, checkNil bool, e *Encode } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapInt32Int64R(rv reflect.Value) { @@ -9161,24 +6492,11 @@ func (_ fastpathT) EncMapInt32Int64V(v map[int32]int64, checkNil bool, e *Encode } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapInt32Float32R(rv reflect.Value) { @@ -9192,24 +6510,11 @@ func (_ fastpathT) EncMapInt32Float32V(v map[int32]float32, checkNil bool, e *En } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeFloat32(v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeFloat32(v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeFloat32(v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapInt32Float64R(rv reflect.Value) { @@ -9223,24 +6528,11 @@ func (_ fastpathT) EncMapInt32Float64V(v map[int32]float64, checkNil bool, e *En } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeFloat64(v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeFloat64(v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeFloat64(v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapInt32BoolR(rv reflect.Value) { @@ -9254,24 +6546,11 @@ func (_ fastpathT) EncMapInt32BoolV(v map[int32]bool, checkNil bool, e *Encoder) } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeBool(v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeBool(v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeBool(v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapInt64IntfR(rv reflect.Value) { @@ -9285,24 +6564,11 @@ func (_ fastpathT) EncMapInt64IntfV(v map[int64]interface{}, checkNil bool, e *E } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - e.encode(v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - e.encode(v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + e.encode(v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapInt64StringR(rv reflect.Value) { @@ -9316,24 +6582,11 @@ func (_ fastpathT) EncMapInt64StringV(v map[int64]string, checkNil bool, e *Enco } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeString(c_UTF8, v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeString(c_UTF8, v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeString(c_UTF8, v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapInt64UintR(rv reflect.Value) { @@ -9347,24 +6600,11 @@ func (_ fastpathT) EncMapInt64UintV(v map[int64]uint, checkNil bool, e *Encoder) } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapInt64Uint8R(rv reflect.Value) { @@ -9378,24 +6618,11 @@ func (_ fastpathT) EncMapInt64Uint8V(v map[int64]uint8, checkNil bool, e *Encode } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapInt64Uint16R(rv reflect.Value) { @@ -9409,24 +6636,11 @@ func (_ fastpathT) EncMapInt64Uint16V(v map[int64]uint16, checkNil bool, e *Enco } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapInt64Uint32R(rv reflect.Value) { @@ -9440,24 +6654,11 @@ func (_ fastpathT) EncMapInt64Uint32V(v map[int64]uint32, checkNil bool, e *Enco } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapInt64Uint64R(rv reflect.Value) { @@ -9471,24 +6672,11 @@ func (_ fastpathT) EncMapInt64Uint64V(v map[int64]uint64, checkNil bool, e *Enco } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapInt64IntR(rv reflect.Value) { @@ -9502,24 +6690,11 @@ func (_ fastpathT) EncMapInt64IntV(v map[int64]int, checkNil bool, e *Encoder) { } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapInt64Int8R(rv reflect.Value) { @@ -9533,24 +6708,11 @@ func (_ fastpathT) EncMapInt64Int8V(v map[int64]int8, checkNil bool, e *Encoder) } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapInt64Int16R(rv reflect.Value) { @@ -9564,24 +6726,11 @@ func (_ fastpathT) EncMapInt64Int16V(v map[int64]int16, checkNil bool, e *Encode } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapInt64Int32R(rv reflect.Value) { @@ -9595,24 +6744,11 @@ func (_ fastpathT) EncMapInt64Int32V(v map[int64]int32, checkNil bool, e *Encode } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapInt64Int64R(rv reflect.Value) { @@ -9626,24 +6762,11 @@ func (_ fastpathT) EncMapInt64Int64V(v map[int64]int64, checkNil bool, e *Encode } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapInt64Float32R(rv reflect.Value) { @@ -9657,24 +6780,11 @@ func (_ fastpathT) EncMapInt64Float32V(v map[int64]float32, checkNil bool, e *En } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeFloat32(v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeFloat32(v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeFloat32(v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapInt64Float64R(rv reflect.Value) { @@ -9688,24 +6798,11 @@ func (_ fastpathT) EncMapInt64Float64V(v map[int64]float64, checkNil bool, e *En } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeFloat64(v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeFloat64(v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeFloat64(v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapInt64BoolR(rv reflect.Value) { @@ -9719,24 +6816,11 @@ func (_ fastpathT) EncMapInt64BoolV(v map[int64]bool, checkNil bool, e *Encoder) } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeInt(int64(k2)) - ee.EncodeBool(v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeInt(int64(k2)) - ee.EncodeMapKVSeparator() - ee.EncodeBool(v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeInt(int64(k2)) + ee.EncodeBool(v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapBoolIntfR(rv reflect.Value) { @@ -9750,24 +6834,11 @@ func (_ fastpathT) EncMapBoolIntfV(v map[bool]interface{}, checkNil bool, e *Enc } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeBool(k2) - e.encode(v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeBool(k2) - ee.EncodeMapKVSeparator() - e.encode(v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeBool(k2) + e.encode(v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapBoolStringR(rv reflect.Value) { @@ -9781,24 +6852,11 @@ func (_ fastpathT) EncMapBoolStringV(v map[bool]string, checkNil bool, e *Encode } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeBool(k2) - ee.EncodeString(c_UTF8, v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeBool(k2) - ee.EncodeMapKVSeparator() - ee.EncodeString(c_UTF8, v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeBool(k2) + ee.EncodeString(c_UTF8, v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapBoolUintR(rv reflect.Value) { @@ -9812,24 +6870,11 @@ func (_ fastpathT) EncMapBoolUintV(v map[bool]uint, checkNil bool, e *Encoder) { } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeBool(k2) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeBool(k2) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeBool(k2) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapBoolUint8R(rv reflect.Value) { @@ -9843,24 +6888,11 @@ func (_ fastpathT) EncMapBoolUint8V(v map[bool]uint8, checkNil bool, e *Encoder) } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeBool(k2) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeBool(k2) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeBool(k2) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapBoolUint16R(rv reflect.Value) { @@ -9874,24 +6906,11 @@ func (_ fastpathT) EncMapBoolUint16V(v map[bool]uint16, checkNil bool, e *Encode } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeBool(k2) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeBool(k2) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeBool(k2) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapBoolUint32R(rv reflect.Value) { @@ -9905,24 +6924,11 @@ func (_ fastpathT) EncMapBoolUint32V(v map[bool]uint32, checkNil bool, e *Encode } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeBool(k2) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeBool(k2) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeBool(k2) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapBoolUint64R(rv reflect.Value) { @@ -9936,24 +6942,11 @@ func (_ fastpathT) EncMapBoolUint64V(v map[bool]uint64, checkNil bool, e *Encode } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeBool(k2) - ee.EncodeUint(uint64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeBool(k2) - ee.EncodeMapKVSeparator() - ee.EncodeUint(uint64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeBool(k2) + ee.EncodeUint(uint64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapBoolIntR(rv reflect.Value) { @@ -9967,24 +6960,11 @@ func (_ fastpathT) EncMapBoolIntV(v map[bool]int, checkNil bool, e *Encoder) { } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeBool(k2) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeBool(k2) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeBool(k2) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapBoolInt8R(rv reflect.Value) { @@ -9998,24 +6978,11 @@ func (_ fastpathT) EncMapBoolInt8V(v map[bool]int8, checkNil bool, e *Encoder) { } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeBool(k2) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeBool(k2) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeBool(k2) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapBoolInt16R(rv reflect.Value) { @@ -10029,24 +6996,11 @@ func (_ fastpathT) EncMapBoolInt16V(v map[bool]int16, checkNil bool, e *Encoder) } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeBool(k2) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeBool(k2) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeBool(k2) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapBoolInt32R(rv reflect.Value) { @@ -10060,24 +7014,11 @@ func (_ fastpathT) EncMapBoolInt32V(v map[bool]int32, checkNil bool, e *Encoder) } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeBool(k2) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeBool(k2) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeBool(k2) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapBoolInt64R(rv reflect.Value) { @@ -10091,24 +7032,11 @@ func (_ fastpathT) EncMapBoolInt64V(v map[bool]int64, checkNil bool, e *Encoder) } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeBool(k2) - ee.EncodeInt(int64(v2)) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeBool(k2) - ee.EncodeMapKVSeparator() - ee.EncodeInt(int64(v2)) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeBool(k2) + ee.EncodeInt(int64(v2)) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapBoolFloat32R(rv reflect.Value) { @@ -10122,24 +7050,11 @@ func (_ fastpathT) EncMapBoolFloat32V(v map[bool]float32, checkNil bool, e *Enco } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeBool(k2) - ee.EncodeFloat32(v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeBool(k2) - ee.EncodeMapKVSeparator() - ee.EncodeFloat32(v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeBool(k2) + ee.EncodeFloat32(v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapBoolFloat64R(rv reflect.Value) { @@ -10153,24 +7068,11 @@ func (_ fastpathT) EncMapBoolFloat64V(v map[bool]float64, checkNil bool, e *Enco } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeBool(k2) - ee.EncodeFloat64(v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeBool(k2) - ee.EncodeMapKVSeparator() - ee.EncodeFloat64(v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeBool(k2) + ee.EncodeFloat64(v2) } + ee.EncodeEnd() } func (f encFnInfo) fastpathEncMapBoolBoolR(rv reflect.Value) { @@ -10184,24 +7086,11 @@ func (_ fastpathT) EncMapBoolBoolV(v map[bool]bool, checkNil bool, e *Encoder) { } ee.EncodeMapStart(len(v)) - if e.be { - for k2, v2 := range v { - ee.EncodeBool(k2) - ee.EncodeBool(v2) - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - ee.EncodeBool(k2) - ee.EncodeMapKVSeparator() - ee.EncodeBool(v2) - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + ee.EncodeBool(k2) + ee.EncodeBool(v2) } + ee.EncodeEnd() } // -- decode @@ -12216,9 +9105,6 @@ func (_ fastpathT) DecSliceIntfV(v []interface{}, checkNil bool, canChange bool, d.arrayCannotExpand(len(v), j+1) } } - if j > 0 { - slh.Sep(j) - } if j < len(v) { // all checks done. cannot go past len. d.decode(&v[j]) @@ -12317,9 +9203,6 @@ func (_ fastpathT) DecSliceStringV(v []string, checkNil bool, canChange bool, d.arrayCannotExpand(len(v), j+1) } } - if j > 0 { - slh.Sep(j) - } if j < len(v) { // all checks done. cannot go past len. v[j] = dd.DecodeString() } else { @@ -12417,9 +9300,6 @@ func (_ fastpathT) DecSliceFloat32V(v []float32, checkNil bool, canChange bool, d.arrayCannotExpand(len(v), j+1) } } - if j > 0 { - slh.Sep(j) - } if j < len(v) { // all checks done. cannot go past len. v[j] = float32(dd.DecodeFloat(true)) } else { @@ -12517,9 +9397,6 @@ func (_ fastpathT) DecSliceFloat64V(v []float64, checkNil bool, canChange bool, d.arrayCannotExpand(len(v), j+1) } } - if j > 0 { - slh.Sep(j) - } if j < len(v) { // all checks done. cannot go past len. v[j] = dd.DecodeFloat(false) } else { @@ -12617,9 +9494,6 @@ func (_ fastpathT) DecSliceUintV(v []uint, checkNil bool, canChange bool, d.arrayCannotExpand(len(v), j+1) } } - if j > 0 { - slh.Sep(j) - } if j < len(v) { // all checks done. cannot go past len. v[j] = uint(dd.DecodeUint(uintBitsize)) } else { @@ -12717,9 +9591,6 @@ func (_ fastpathT) DecSliceUint16V(v []uint16, checkNil bool, canChange bool, d.arrayCannotExpand(len(v), j+1) } } - if j > 0 { - slh.Sep(j) - } if j < len(v) { // all checks done. cannot go past len. v[j] = uint16(dd.DecodeUint(16)) } else { @@ -12817,9 +9688,6 @@ func (_ fastpathT) DecSliceUint32V(v []uint32, checkNil bool, canChange bool, d.arrayCannotExpand(len(v), j+1) } } - if j > 0 { - slh.Sep(j) - } if j < len(v) { // all checks done. cannot go past len. v[j] = uint32(dd.DecodeUint(32)) } else { @@ -12917,9 +9785,6 @@ func (_ fastpathT) DecSliceUint64V(v []uint64, checkNil bool, canChange bool, d.arrayCannotExpand(len(v), j+1) } } - if j > 0 { - slh.Sep(j) - } if j < len(v) { // all checks done. cannot go past len. v[j] = dd.DecodeUint(64) } else { @@ -13017,9 +9882,6 @@ func (_ fastpathT) DecSliceIntV(v []int, checkNil bool, canChange bool, d.arrayCannotExpand(len(v), j+1) } } - if j > 0 { - slh.Sep(j) - } if j < len(v) { // all checks done. cannot go past len. v[j] = int(dd.DecodeInt(intBitsize)) } else { @@ -13117,9 +9979,6 @@ func (_ fastpathT) DecSliceInt8V(v []int8, checkNil bool, canChange bool, d.arrayCannotExpand(len(v), j+1) } } - if j > 0 { - slh.Sep(j) - } if j < len(v) { // all checks done. cannot go past len. v[j] = int8(dd.DecodeInt(8)) } else { @@ -13217,9 +10076,6 @@ func (_ fastpathT) DecSliceInt16V(v []int16, checkNil bool, canChange bool, d.arrayCannotExpand(len(v), j+1) } } - if j > 0 { - slh.Sep(j) - } if j < len(v) { // all checks done. cannot go past len. v[j] = int16(dd.DecodeInt(16)) } else { @@ -13317,9 +10173,6 @@ func (_ fastpathT) DecSliceInt32V(v []int32, checkNil bool, canChange bool, d.arrayCannotExpand(len(v), j+1) } } - if j > 0 { - slh.Sep(j) - } if j < len(v) { // all checks done. cannot go past len. v[j] = int32(dd.DecodeInt(32)) } else { @@ -13417,9 +10270,6 @@ func (_ fastpathT) DecSliceInt64V(v []int64, checkNil bool, canChange bool, d.arrayCannotExpand(len(v), j+1) } } - if j > 0 { - slh.Sep(j) - } if j < len(v) { // all checks done. cannot go past len. v[j] = dd.DecodeInt(64) } else { @@ -13517,9 +10367,6 @@ func (_ fastpathT) DecSliceBoolV(v []bool, checkNil bool, canChange bool, d.arrayCannotExpand(len(v), j+1) } } - if j > 0 { - slh.Sep(j) - } if j < len(v) { // all checks done. cannot go past len. v[j] = dd.DecodeBool() } else { @@ -13585,15 +10432,11 @@ func (_ fastpathT) DecMapIntfIntfV(v map[interface{}]interface{}, checkNil bool, } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } var mk interface{} d.decode(&mk) if bv, bok := mk.([]byte); bok { mk = string(bv) // maps cannot have []byte as key. switch to string. } - dd.ReadMapKVSeparator() mv := v[mk] d.decode(&mv) @@ -13601,7 +10444,7 @@ func (_ fastpathT) DecMapIntfIntfV(v map[interface{}]interface{}, checkNil bool, v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -13659,22 +10502,18 @@ func (_ fastpathT) DecMapIntfStringV(v map[interface{}]string, checkNil bool, ca } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } var mk interface{} d.decode(&mk) if bv, bok := mk.([]byte); bok { mk = string(bv) // maps cannot have []byte as key. switch to string. } - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeString() if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -13732,22 +10571,18 @@ func (_ fastpathT) DecMapIntfUintV(v map[interface{}]uint, checkNil bool, canCha } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } var mk interface{} d.decode(&mk) if bv, bok := mk.([]byte); bok { mk = string(bv) // maps cannot have []byte as key. switch to string. } - dd.ReadMapKVSeparator() mv := v[mk] mv = uint(dd.DecodeUint(uintBitsize)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -13805,22 +10640,18 @@ func (_ fastpathT) DecMapIntfUint8V(v map[interface{}]uint8, checkNil bool, canC } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } var mk interface{} d.decode(&mk) if bv, bok := mk.([]byte); bok { mk = string(bv) // maps cannot have []byte as key. switch to string. } - dd.ReadMapKVSeparator() mv := v[mk] mv = uint8(dd.DecodeUint(8)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -13878,22 +10709,18 @@ func (_ fastpathT) DecMapIntfUint16V(v map[interface{}]uint16, checkNil bool, ca } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } var mk interface{} d.decode(&mk) if bv, bok := mk.([]byte); bok { mk = string(bv) // maps cannot have []byte as key. switch to string. } - dd.ReadMapKVSeparator() mv := v[mk] mv = uint16(dd.DecodeUint(16)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -13951,22 +10778,18 @@ func (_ fastpathT) DecMapIntfUint32V(v map[interface{}]uint32, checkNil bool, ca } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } var mk interface{} d.decode(&mk) if bv, bok := mk.([]byte); bok { mk = string(bv) // maps cannot have []byte as key. switch to string. } - dd.ReadMapKVSeparator() mv := v[mk] mv = uint32(dd.DecodeUint(32)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -14024,22 +10847,18 @@ func (_ fastpathT) DecMapIntfUint64V(v map[interface{}]uint64, checkNil bool, ca } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } var mk interface{} d.decode(&mk) if bv, bok := mk.([]byte); bok { mk = string(bv) // maps cannot have []byte as key. switch to string. } - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeUint(64) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -14097,22 +10916,18 @@ func (_ fastpathT) DecMapIntfIntV(v map[interface{}]int, checkNil bool, canChang } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } var mk interface{} d.decode(&mk) if bv, bok := mk.([]byte); bok { mk = string(bv) // maps cannot have []byte as key. switch to string. } - dd.ReadMapKVSeparator() mv := v[mk] mv = int(dd.DecodeInt(intBitsize)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -14170,22 +10985,18 @@ func (_ fastpathT) DecMapIntfInt8V(v map[interface{}]int8, checkNil bool, canCha } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } var mk interface{} d.decode(&mk) if bv, bok := mk.([]byte); bok { mk = string(bv) // maps cannot have []byte as key. switch to string. } - dd.ReadMapKVSeparator() mv := v[mk] mv = int8(dd.DecodeInt(8)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -14243,22 +11054,18 @@ func (_ fastpathT) DecMapIntfInt16V(v map[interface{}]int16, checkNil bool, canC } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } var mk interface{} d.decode(&mk) if bv, bok := mk.([]byte); bok { mk = string(bv) // maps cannot have []byte as key. switch to string. } - dd.ReadMapKVSeparator() mv := v[mk] mv = int16(dd.DecodeInt(16)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -14316,22 +11123,18 @@ func (_ fastpathT) DecMapIntfInt32V(v map[interface{}]int32, checkNil bool, canC } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } var mk interface{} d.decode(&mk) if bv, bok := mk.([]byte); bok { mk = string(bv) // maps cannot have []byte as key. switch to string. } - dd.ReadMapKVSeparator() mv := v[mk] mv = int32(dd.DecodeInt(32)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -14389,22 +11192,18 @@ func (_ fastpathT) DecMapIntfInt64V(v map[interface{}]int64, checkNil bool, canC } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } var mk interface{} d.decode(&mk) if bv, bok := mk.([]byte); bok { mk = string(bv) // maps cannot have []byte as key. switch to string. } - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeInt(64) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -14462,22 +11261,18 @@ func (_ fastpathT) DecMapIntfFloat32V(v map[interface{}]float32, checkNil bool, } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } var mk interface{} d.decode(&mk) if bv, bok := mk.([]byte); bok { mk = string(bv) // maps cannot have []byte as key. switch to string. } - dd.ReadMapKVSeparator() mv := v[mk] mv = float32(dd.DecodeFloat(true)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -14535,22 +11330,18 @@ func (_ fastpathT) DecMapIntfFloat64V(v map[interface{}]float64, checkNil bool, } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } var mk interface{} d.decode(&mk) if bv, bok := mk.([]byte); bok { mk = string(bv) // maps cannot have []byte as key. switch to string. } - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeFloat(false) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -14608,22 +11399,18 @@ func (_ fastpathT) DecMapIntfBoolV(v map[interface{}]bool, checkNil bool, canCha } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } var mk interface{} d.decode(&mk) if bv, bok := mk.([]byte); bok { mk = string(bv) // maps cannot have []byte as key. switch to string. } - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeBool() if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -14678,11 +11465,7 @@ func (_ fastpathT) DecMapStringIntfV(v map[string]interface{}, checkNil bool, ca } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeString() - dd.ReadMapKVSeparator() mv := v[mk] d.decode(&mv) @@ -14690,7 +11473,7 @@ func (_ fastpathT) DecMapStringIntfV(v map[string]interface{}, checkNil bool, ca v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -14744,18 +11527,14 @@ func (_ fastpathT) DecMapStringStringV(v map[string]string, checkNil bool, canCh } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeString() - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeString() if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -14809,18 +11588,14 @@ func (_ fastpathT) DecMapStringUintV(v map[string]uint, checkNil bool, canChange } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeString() - dd.ReadMapKVSeparator() mv := v[mk] mv = uint(dd.DecodeUint(uintBitsize)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -14874,18 +11649,14 @@ func (_ fastpathT) DecMapStringUint8V(v map[string]uint8, checkNil bool, canChan } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeString() - dd.ReadMapKVSeparator() mv := v[mk] mv = uint8(dd.DecodeUint(8)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -14939,18 +11710,14 @@ func (_ fastpathT) DecMapStringUint16V(v map[string]uint16, checkNil bool, canCh } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeString() - dd.ReadMapKVSeparator() mv := v[mk] mv = uint16(dd.DecodeUint(16)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -15004,18 +11771,14 @@ func (_ fastpathT) DecMapStringUint32V(v map[string]uint32, checkNil bool, canCh } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeString() - dd.ReadMapKVSeparator() mv := v[mk] mv = uint32(dd.DecodeUint(32)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -15069,18 +11832,14 @@ func (_ fastpathT) DecMapStringUint64V(v map[string]uint64, checkNil bool, canCh } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeString() - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeUint(64) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -15134,18 +11893,14 @@ func (_ fastpathT) DecMapStringIntV(v map[string]int, checkNil bool, canChange b } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeString() - dd.ReadMapKVSeparator() mv := v[mk] mv = int(dd.DecodeInt(intBitsize)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -15199,18 +11954,14 @@ func (_ fastpathT) DecMapStringInt8V(v map[string]int8, checkNil bool, canChange } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeString() - dd.ReadMapKVSeparator() mv := v[mk] mv = int8(dd.DecodeInt(8)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -15264,18 +12015,14 @@ func (_ fastpathT) DecMapStringInt16V(v map[string]int16, checkNil bool, canChan } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeString() - dd.ReadMapKVSeparator() mv := v[mk] mv = int16(dd.DecodeInt(16)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -15329,18 +12076,14 @@ func (_ fastpathT) DecMapStringInt32V(v map[string]int32, checkNil bool, canChan } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeString() - dd.ReadMapKVSeparator() mv := v[mk] mv = int32(dd.DecodeInt(32)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -15394,18 +12137,14 @@ func (_ fastpathT) DecMapStringInt64V(v map[string]int64, checkNil bool, canChan } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeString() - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeInt(64) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -15459,18 +12198,14 @@ func (_ fastpathT) DecMapStringFloat32V(v map[string]float32, checkNil bool, can } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeString() - dd.ReadMapKVSeparator() mv := v[mk] mv = float32(dd.DecodeFloat(true)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -15524,18 +12259,14 @@ func (_ fastpathT) DecMapStringFloat64V(v map[string]float64, checkNil bool, can } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeString() - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeFloat(false) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -15589,18 +12320,14 @@ func (_ fastpathT) DecMapStringBoolV(v map[string]bool, checkNil bool, canChange } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeString() - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeBool() if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -15655,11 +12382,7 @@ func (_ fastpathT) DecMapFloat32IntfV(v map[float32]interface{}, checkNil bool, } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := float32(dd.DecodeFloat(true)) - dd.ReadMapKVSeparator() mv := v[mk] d.decode(&mv) @@ -15667,7 +12390,7 @@ func (_ fastpathT) DecMapFloat32IntfV(v map[float32]interface{}, checkNil bool, v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -15721,18 +12444,14 @@ func (_ fastpathT) DecMapFloat32StringV(v map[float32]string, checkNil bool, can } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := float32(dd.DecodeFloat(true)) - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeString() if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -15786,18 +12505,14 @@ func (_ fastpathT) DecMapFloat32UintV(v map[float32]uint, checkNil bool, canChan } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := float32(dd.DecodeFloat(true)) - dd.ReadMapKVSeparator() mv := v[mk] mv = uint(dd.DecodeUint(uintBitsize)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -15851,18 +12566,14 @@ func (_ fastpathT) DecMapFloat32Uint8V(v map[float32]uint8, checkNil bool, canCh } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := float32(dd.DecodeFloat(true)) - dd.ReadMapKVSeparator() mv := v[mk] mv = uint8(dd.DecodeUint(8)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -15916,18 +12627,14 @@ func (_ fastpathT) DecMapFloat32Uint16V(v map[float32]uint16, checkNil bool, can } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := float32(dd.DecodeFloat(true)) - dd.ReadMapKVSeparator() mv := v[mk] mv = uint16(dd.DecodeUint(16)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -15981,18 +12688,14 @@ func (_ fastpathT) DecMapFloat32Uint32V(v map[float32]uint32, checkNil bool, can } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := float32(dd.DecodeFloat(true)) - dd.ReadMapKVSeparator() mv := v[mk] mv = uint32(dd.DecodeUint(32)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -16046,18 +12749,14 @@ func (_ fastpathT) DecMapFloat32Uint64V(v map[float32]uint64, checkNil bool, can } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := float32(dd.DecodeFloat(true)) - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeUint(64) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -16111,18 +12810,14 @@ func (_ fastpathT) DecMapFloat32IntV(v map[float32]int, checkNil bool, canChange } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := float32(dd.DecodeFloat(true)) - dd.ReadMapKVSeparator() mv := v[mk] mv = int(dd.DecodeInt(intBitsize)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -16176,18 +12871,14 @@ func (_ fastpathT) DecMapFloat32Int8V(v map[float32]int8, checkNil bool, canChan } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := float32(dd.DecodeFloat(true)) - dd.ReadMapKVSeparator() mv := v[mk] mv = int8(dd.DecodeInt(8)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -16241,18 +12932,14 @@ func (_ fastpathT) DecMapFloat32Int16V(v map[float32]int16, checkNil bool, canCh } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := float32(dd.DecodeFloat(true)) - dd.ReadMapKVSeparator() mv := v[mk] mv = int16(dd.DecodeInt(16)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -16306,18 +12993,14 @@ func (_ fastpathT) DecMapFloat32Int32V(v map[float32]int32, checkNil bool, canCh } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := float32(dd.DecodeFloat(true)) - dd.ReadMapKVSeparator() mv := v[mk] mv = int32(dd.DecodeInt(32)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -16371,18 +13054,14 @@ func (_ fastpathT) DecMapFloat32Int64V(v map[float32]int64, checkNil bool, canCh } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := float32(dd.DecodeFloat(true)) - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeInt(64) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -16436,18 +13115,14 @@ func (_ fastpathT) DecMapFloat32Float32V(v map[float32]float32, checkNil bool, c } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := float32(dd.DecodeFloat(true)) - dd.ReadMapKVSeparator() mv := v[mk] mv = float32(dd.DecodeFloat(true)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -16501,18 +13176,14 @@ func (_ fastpathT) DecMapFloat32Float64V(v map[float32]float64, checkNil bool, c } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := float32(dd.DecodeFloat(true)) - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeFloat(false) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -16566,18 +13237,14 @@ func (_ fastpathT) DecMapFloat32BoolV(v map[float32]bool, checkNil bool, canChan } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := float32(dd.DecodeFloat(true)) - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeBool() if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -16632,11 +13299,7 @@ func (_ fastpathT) DecMapFloat64IntfV(v map[float64]interface{}, checkNil bool, } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeFloat(false) - dd.ReadMapKVSeparator() mv := v[mk] d.decode(&mv) @@ -16644,7 +13307,7 @@ func (_ fastpathT) DecMapFloat64IntfV(v map[float64]interface{}, checkNil bool, v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -16698,18 +13361,14 @@ func (_ fastpathT) DecMapFloat64StringV(v map[float64]string, checkNil bool, can } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeFloat(false) - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeString() if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -16763,18 +13422,14 @@ func (_ fastpathT) DecMapFloat64UintV(v map[float64]uint, checkNil bool, canChan } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeFloat(false) - dd.ReadMapKVSeparator() mv := v[mk] mv = uint(dd.DecodeUint(uintBitsize)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -16828,18 +13483,14 @@ func (_ fastpathT) DecMapFloat64Uint8V(v map[float64]uint8, checkNil bool, canCh } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeFloat(false) - dd.ReadMapKVSeparator() mv := v[mk] mv = uint8(dd.DecodeUint(8)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -16893,18 +13544,14 @@ func (_ fastpathT) DecMapFloat64Uint16V(v map[float64]uint16, checkNil bool, can } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeFloat(false) - dd.ReadMapKVSeparator() mv := v[mk] mv = uint16(dd.DecodeUint(16)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -16958,18 +13605,14 @@ func (_ fastpathT) DecMapFloat64Uint32V(v map[float64]uint32, checkNil bool, can } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeFloat(false) - dd.ReadMapKVSeparator() mv := v[mk] mv = uint32(dd.DecodeUint(32)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -17023,18 +13666,14 @@ func (_ fastpathT) DecMapFloat64Uint64V(v map[float64]uint64, checkNil bool, can } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeFloat(false) - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeUint(64) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -17088,18 +13727,14 @@ func (_ fastpathT) DecMapFloat64IntV(v map[float64]int, checkNil bool, canChange } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeFloat(false) - dd.ReadMapKVSeparator() mv := v[mk] mv = int(dd.DecodeInt(intBitsize)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -17153,18 +13788,14 @@ func (_ fastpathT) DecMapFloat64Int8V(v map[float64]int8, checkNil bool, canChan } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeFloat(false) - dd.ReadMapKVSeparator() mv := v[mk] mv = int8(dd.DecodeInt(8)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -17218,18 +13849,14 @@ func (_ fastpathT) DecMapFloat64Int16V(v map[float64]int16, checkNil bool, canCh } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeFloat(false) - dd.ReadMapKVSeparator() mv := v[mk] mv = int16(dd.DecodeInt(16)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -17283,18 +13910,14 @@ func (_ fastpathT) DecMapFloat64Int32V(v map[float64]int32, checkNil bool, canCh } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeFloat(false) - dd.ReadMapKVSeparator() mv := v[mk] mv = int32(dd.DecodeInt(32)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -17348,18 +13971,14 @@ func (_ fastpathT) DecMapFloat64Int64V(v map[float64]int64, checkNil bool, canCh } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeFloat(false) - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeInt(64) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -17413,18 +14032,14 @@ func (_ fastpathT) DecMapFloat64Float32V(v map[float64]float32, checkNil bool, c } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeFloat(false) - dd.ReadMapKVSeparator() mv := v[mk] mv = float32(dd.DecodeFloat(true)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -17478,18 +14093,14 @@ func (_ fastpathT) DecMapFloat64Float64V(v map[float64]float64, checkNil bool, c } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeFloat(false) - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeFloat(false) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -17543,18 +14154,14 @@ func (_ fastpathT) DecMapFloat64BoolV(v map[float64]bool, checkNil bool, canChan } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeFloat(false) - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeBool() if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -17609,11 +14216,7 @@ func (_ fastpathT) DecMapUintIntfV(v map[uint]interface{}, checkNil bool, canCha } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := uint(dd.DecodeUint(uintBitsize)) - dd.ReadMapKVSeparator() mv := v[mk] d.decode(&mv) @@ -17621,7 +14224,7 @@ func (_ fastpathT) DecMapUintIntfV(v map[uint]interface{}, checkNil bool, canCha v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -17675,18 +14278,14 @@ func (_ fastpathT) DecMapUintStringV(v map[uint]string, checkNil bool, canChange } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := uint(dd.DecodeUint(uintBitsize)) - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeString() if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -17740,18 +14339,14 @@ func (_ fastpathT) DecMapUintUintV(v map[uint]uint, checkNil bool, canChange boo } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := uint(dd.DecodeUint(uintBitsize)) - dd.ReadMapKVSeparator() mv := v[mk] mv = uint(dd.DecodeUint(uintBitsize)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -17805,18 +14400,14 @@ func (_ fastpathT) DecMapUintUint8V(v map[uint]uint8, checkNil bool, canChange b } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := uint(dd.DecodeUint(uintBitsize)) - dd.ReadMapKVSeparator() mv := v[mk] mv = uint8(dd.DecodeUint(8)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -17870,18 +14461,14 @@ func (_ fastpathT) DecMapUintUint16V(v map[uint]uint16, checkNil bool, canChange } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := uint(dd.DecodeUint(uintBitsize)) - dd.ReadMapKVSeparator() mv := v[mk] mv = uint16(dd.DecodeUint(16)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -17935,18 +14522,14 @@ func (_ fastpathT) DecMapUintUint32V(v map[uint]uint32, checkNil bool, canChange } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := uint(dd.DecodeUint(uintBitsize)) - dd.ReadMapKVSeparator() mv := v[mk] mv = uint32(dd.DecodeUint(32)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -18000,18 +14583,14 @@ func (_ fastpathT) DecMapUintUint64V(v map[uint]uint64, checkNil bool, canChange } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := uint(dd.DecodeUint(uintBitsize)) - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeUint(64) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -18065,18 +14644,14 @@ func (_ fastpathT) DecMapUintIntV(v map[uint]int, checkNil bool, canChange bool, } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := uint(dd.DecodeUint(uintBitsize)) - dd.ReadMapKVSeparator() mv := v[mk] mv = int(dd.DecodeInt(intBitsize)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -18130,18 +14705,14 @@ func (_ fastpathT) DecMapUintInt8V(v map[uint]int8, checkNil bool, canChange boo } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := uint(dd.DecodeUint(uintBitsize)) - dd.ReadMapKVSeparator() mv := v[mk] mv = int8(dd.DecodeInt(8)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -18195,18 +14766,14 @@ func (_ fastpathT) DecMapUintInt16V(v map[uint]int16, checkNil bool, canChange b } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := uint(dd.DecodeUint(uintBitsize)) - dd.ReadMapKVSeparator() mv := v[mk] mv = int16(dd.DecodeInt(16)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -18260,18 +14827,14 @@ func (_ fastpathT) DecMapUintInt32V(v map[uint]int32, checkNil bool, canChange b } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := uint(dd.DecodeUint(uintBitsize)) - dd.ReadMapKVSeparator() mv := v[mk] mv = int32(dd.DecodeInt(32)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -18325,18 +14888,14 @@ func (_ fastpathT) DecMapUintInt64V(v map[uint]int64, checkNil bool, canChange b } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := uint(dd.DecodeUint(uintBitsize)) - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeInt(64) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -18390,18 +14949,14 @@ func (_ fastpathT) DecMapUintFloat32V(v map[uint]float32, checkNil bool, canChan } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := uint(dd.DecodeUint(uintBitsize)) - dd.ReadMapKVSeparator() mv := v[mk] mv = float32(dd.DecodeFloat(true)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -18455,18 +15010,14 @@ func (_ fastpathT) DecMapUintFloat64V(v map[uint]float64, checkNil bool, canChan } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := uint(dd.DecodeUint(uintBitsize)) - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeFloat(false) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -18520,18 +15071,14 @@ func (_ fastpathT) DecMapUintBoolV(v map[uint]bool, checkNil bool, canChange boo } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := uint(dd.DecodeUint(uintBitsize)) - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeBool() if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -18586,11 +15133,7 @@ func (_ fastpathT) DecMapUint8IntfV(v map[uint8]interface{}, checkNil bool, canC } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := uint8(dd.DecodeUint(8)) - dd.ReadMapKVSeparator() mv := v[mk] d.decode(&mv) @@ -18598,7 +15141,7 @@ func (_ fastpathT) DecMapUint8IntfV(v map[uint8]interface{}, checkNil bool, canC v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -18652,18 +15195,14 @@ func (_ fastpathT) DecMapUint8StringV(v map[uint8]string, checkNil bool, canChan } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := uint8(dd.DecodeUint(8)) - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeString() if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -18717,18 +15256,14 @@ func (_ fastpathT) DecMapUint8UintV(v map[uint8]uint, checkNil bool, canChange b } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := uint8(dd.DecodeUint(8)) - dd.ReadMapKVSeparator() mv := v[mk] mv = uint(dd.DecodeUint(uintBitsize)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -18782,18 +15317,14 @@ func (_ fastpathT) DecMapUint8Uint8V(v map[uint8]uint8, checkNil bool, canChange } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := uint8(dd.DecodeUint(8)) - dd.ReadMapKVSeparator() mv := v[mk] mv = uint8(dd.DecodeUint(8)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -18847,18 +15378,14 @@ func (_ fastpathT) DecMapUint8Uint16V(v map[uint8]uint16, checkNil bool, canChan } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := uint8(dd.DecodeUint(8)) - dd.ReadMapKVSeparator() mv := v[mk] mv = uint16(dd.DecodeUint(16)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -18912,18 +15439,14 @@ func (_ fastpathT) DecMapUint8Uint32V(v map[uint8]uint32, checkNil bool, canChan } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := uint8(dd.DecodeUint(8)) - dd.ReadMapKVSeparator() mv := v[mk] mv = uint32(dd.DecodeUint(32)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -18977,18 +15500,14 @@ func (_ fastpathT) DecMapUint8Uint64V(v map[uint8]uint64, checkNil bool, canChan } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := uint8(dd.DecodeUint(8)) - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeUint(64) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -19042,18 +15561,14 @@ func (_ fastpathT) DecMapUint8IntV(v map[uint8]int, checkNil bool, canChange boo } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := uint8(dd.DecodeUint(8)) - dd.ReadMapKVSeparator() mv := v[mk] mv = int(dd.DecodeInt(intBitsize)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -19107,18 +15622,14 @@ func (_ fastpathT) DecMapUint8Int8V(v map[uint8]int8, checkNil bool, canChange b } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := uint8(dd.DecodeUint(8)) - dd.ReadMapKVSeparator() mv := v[mk] mv = int8(dd.DecodeInt(8)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -19172,18 +15683,14 @@ func (_ fastpathT) DecMapUint8Int16V(v map[uint8]int16, checkNil bool, canChange } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := uint8(dd.DecodeUint(8)) - dd.ReadMapKVSeparator() mv := v[mk] mv = int16(dd.DecodeInt(16)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -19237,18 +15744,14 @@ func (_ fastpathT) DecMapUint8Int32V(v map[uint8]int32, checkNil bool, canChange } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := uint8(dd.DecodeUint(8)) - dd.ReadMapKVSeparator() mv := v[mk] mv = int32(dd.DecodeInt(32)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -19302,18 +15805,14 @@ func (_ fastpathT) DecMapUint8Int64V(v map[uint8]int64, checkNil bool, canChange } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := uint8(dd.DecodeUint(8)) - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeInt(64) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -19367,18 +15866,14 @@ func (_ fastpathT) DecMapUint8Float32V(v map[uint8]float32, checkNil bool, canCh } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := uint8(dd.DecodeUint(8)) - dd.ReadMapKVSeparator() mv := v[mk] mv = float32(dd.DecodeFloat(true)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -19432,18 +15927,14 @@ func (_ fastpathT) DecMapUint8Float64V(v map[uint8]float64, checkNil bool, canCh } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := uint8(dd.DecodeUint(8)) - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeFloat(false) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -19497,18 +15988,14 @@ func (_ fastpathT) DecMapUint8BoolV(v map[uint8]bool, checkNil bool, canChange b } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := uint8(dd.DecodeUint(8)) - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeBool() if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -19563,11 +16050,7 @@ func (_ fastpathT) DecMapUint16IntfV(v map[uint16]interface{}, checkNil bool, ca } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := uint16(dd.DecodeUint(16)) - dd.ReadMapKVSeparator() mv := v[mk] d.decode(&mv) @@ -19575,7 +16058,7 @@ func (_ fastpathT) DecMapUint16IntfV(v map[uint16]interface{}, checkNil bool, ca v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -19629,18 +16112,14 @@ func (_ fastpathT) DecMapUint16StringV(v map[uint16]string, checkNil bool, canCh } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := uint16(dd.DecodeUint(16)) - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeString() if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -19694,18 +16173,14 @@ func (_ fastpathT) DecMapUint16UintV(v map[uint16]uint, checkNil bool, canChange } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := uint16(dd.DecodeUint(16)) - dd.ReadMapKVSeparator() mv := v[mk] mv = uint(dd.DecodeUint(uintBitsize)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -19759,18 +16234,14 @@ func (_ fastpathT) DecMapUint16Uint8V(v map[uint16]uint8, checkNil bool, canChan } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := uint16(dd.DecodeUint(16)) - dd.ReadMapKVSeparator() mv := v[mk] mv = uint8(dd.DecodeUint(8)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -19824,18 +16295,14 @@ func (_ fastpathT) DecMapUint16Uint16V(v map[uint16]uint16, checkNil bool, canCh } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := uint16(dd.DecodeUint(16)) - dd.ReadMapKVSeparator() mv := v[mk] mv = uint16(dd.DecodeUint(16)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -19889,18 +16356,14 @@ func (_ fastpathT) DecMapUint16Uint32V(v map[uint16]uint32, checkNil bool, canCh } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := uint16(dd.DecodeUint(16)) - dd.ReadMapKVSeparator() mv := v[mk] mv = uint32(dd.DecodeUint(32)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -19954,18 +16417,14 @@ func (_ fastpathT) DecMapUint16Uint64V(v map[uint16]uint64, checkNil bool, canCh } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := uint16(dd.DecodeUint(16)) - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeUint(64) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -20019,18 +16478,14 @@ func (_ fastpathT) DecMapUint16IntV(v map[uint16]int, checkNil bool, canChange b } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := uint16(dd.DecodeUint(16)) - dd.ReadMapKVSeparator() mv := v[mk] mv = int(dd.DecodeInt(intBitsize)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -20084,18 +16539,14 @@ func (_ fastpathT) DecMapUint16Int8V(v map[uint16]int8, checkNil bool, canChange } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := uint16(dd.DecodeUint(16)) - dd.ReadMapKVSeparator() mv := v[mk] mv = int8(dd.DecodeInt(8)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -20149,18 +16600,14 @@ func (_ fastpathT) DecMapUint16Int16V(v map[uint16]int16, checkNil bool, canChan } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := uint16(dd.DecodeUint(16)) - dd.ReadMapKVSeparator() mv := v[mk] mv = int16(dd.DecodeInt(16)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -20214,18 +16661,14 @@ func (_ fastpathT) DecMapUint16Int32V(v map[uint16]int32, checkNil bool, canChan } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := uint16(dd.DecodeUint(16)) - dd.ReadMapKVSeparator() mv := v[mk] mv = int32(dd.DecodeInt(32)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -20279,18 +16722,14 @@ func (_ fastpathT) DecMapUint16Int64V(v map[uint16]int64, checkNil bool, canChan } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := uint16(dd.DecodeUint(16)) - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeInt(64) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -20344,18 +16783,14 @@ func (_ fastpathT) DecMapUint16Float32V(v map[uint16]float32, checkNil bool, can } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := uint16(dd.DecodeUint(16)) - dd.ReadMapKVSeparator() mv := v[mk] mv = float32(dd.DecodeFloat(true)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -20409,18 +16844,14 @@ func (_ fastpathT) DecMapUint16Float64V(v map[uint16]float64, checkNil bool, can } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := uint16(dd.DecodeUint(16)) - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeFloat(false) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -20474,18 +16905,14 @@ func (_ fastpathT) DecMapUint16BoolV(v map[uint16]bool, checkNil bool, canChange } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := uint16(dd.DecodeUint(16)) - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeBool() if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -20540,11 +16967,7 @@ func (_ fastpathT) DecMapUint32IntfV(v map[uint32]interface{}, checkNil bool, ca } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := uint32(dd.DecodeUint(32)) - dd.ReadMapKVSeparator() mv := v[mk] d.decode(&mv) @@ -20552,7 +16975,7 @@ func (_ fastpathT) DecMapUint32IntfV(v map[uint32]interface{}, checkNil bool, ca v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -20606,18 +17029,14 @@ func (_ fastpathT) DecMapUint32StringV(v map[uint32]string, checkNil bool, canCh } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := uint32(dd.DecodeUint(32)) - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeString() if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -20671,18 +17090,14 @@ func (_ fastpathT) DecMapUint32UintV(v map[uint32]uint, checkNil bool, canChange } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := uint32(dd.DecodeUint(32)) - dd.ReadMapKVSeparator() mv := v[mk] mv = uint(dd.DecodeUint(uintBitsize)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -20736,18 +17151,14 @@ func (_ fastpathT) DecMapUint32Uint8V(v map[uint32]uint8, checkNil bool, canChan } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := uint32(dd.DecodeUint(32)) - dd.ReadMapKVSeparator() mv := v[mk] mv = uint8(dd.DecodeUint(8)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -20801,18 +17212,14 @@ func (_ fastpathT) DecMapUint32Uint16V(v map[uint32]uint16, checkNil bool, canCh } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := uint32(dd.DecodeUint(32)) - dd.ReadMapKVSeparator() mv := v[mk] mv = uint16(dd.DecodeUint(16)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -20866,18 +17273,14 @@ func (_ fastpathT) DecMapUint32Uint32V(v map[uint32]uint32, checkNil bool, canCh } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := uint32(dd.DecodeUint(32)) - dd.ReadMapKVSeparator() mv := v[mk] mv = uint32(dd.DecodeUint(32)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -20931,18 +17334,14 @@ func (_ fastpathT) DecMapUint32Uint64V(v map[uint32]uint64, checkNil bool, canCh } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := uint32(dd.DecodeUint(32)) - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeUint(64) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -20996,18 +17395,14 @@ func (_ fastpathT) DecMapUint32IntV(v map[uint32]int, checkNil bool, canChange b } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := uint32(dd.DecodeUint(32)) - dd.ReadMapKVSeparator() mv := v[mk] mv = int(dd.DecodeInt(intBitsize)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -21061,18 +17456,14 @@ func (_ fastpathT) DecMapUint32Int8V(v map[uint32]int8, checkNil bool, canChange } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := uint32(dd.DecodeUint(32)) - dd.ReadMapKVSeparator() mv := v[mk] mv = int8(dd.DecodeInt(8)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -21126,18 +17517,14 @@ func (_ fastpathT) DecMapUint32Int16V(v map[uint32]int16, checkNil bool, canChan } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := uint32(dd.DecodeUint(32)) - dd.ReadMapKVSeparator() mv := v[mk] mv = int16(dd.DecodeInt(16)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -21191,18 +17578,14 @@ func (_ fastpathT) DecMapUint32Int32V(v map[uint32]int32, checkNil bool, canChan } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := uint32(dd.DecodeUint(32)) - dd.ReadMapKVSeparator() mv := v[mk] mv = int32(dd.DecodeInt(32)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -21256,18 +17639,14 @@ func (_ fastpathT) DecMapUint32Int64V(v map[uint32]int64, checkNil bool, canChan } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := uint32(dd.DecodeUint(32)) - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeInt(64) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -21321,18 +17700,14 @@ func (_ fastpathT) DecMapUint32Float32V(v map[uint32]float32, checkNil bool, can } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := uint32(dd.DecodeUint(32)) - dd.ReadMapKVSeparator() mv := v[mk] mv = float32(dd.DecodeFloat(true)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -21386,18 +17761,14 @@ func (_ fastpathT) DecMapUint32Float64V(v map[uint32]float64, checkNil bool, can } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := uint32(dd.DecodeUint(32)) - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeFloat(false) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -21451,18 +17822,14 @@ func (_ fastpathT) DecMapUint32BoolV(v map[uint32]bool, checkNil bool, canChange } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := uint32(dd.DecodeUint(32)) - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeBool() if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -21517,11 +17884,7 @@ func (_ fastpathT) DecMapUint64IntfV(v map[uint64]interface{}, checkNil bool, ca } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeUint(64) - dd.ReadMapKVSeparator() mv := v[mk] d.decode(&mv) @@ -21529,7 +17892,7 @@ func (_ fastpathT) DecMapUint64IntfV(v map[uint64]interface{}, checkNil bool, ca v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -21583,18 +17946,14 @@ func (_ fastpathT) DecMapUint64StringV(v map[uint64]string, checkNil bool, canCh } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeUint(64) - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeString() if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -21648,18 +18007,14 @@ func (_ fastpathT) DecMapUint64UintV(v map[uint64]uint, checkNil bool, canChange } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeUint(64) - dd.ReadMapKVSeparator() mv := v[mk] mv = uint(dd.DecodeUint(uintBitsize)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -21713,18 +18068,14 @@ func (_ fastpathT) DecMapUint64Uint8V(v map[uint64]uint8, checkNil bool, canChan } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeUint(64) - dd.ReadMapKVSeparator() mv := v[mk] mv = uint8(dd.DecodeUint(8)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -21778,18 +18129,14 @@ func (_ fastpathT) DecMapUint64Uint16V(v map[uint64]uint16, checkNil bool, canCh } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeUint(64) - dd.ReadMapKVSeparator() mv := v[mk] mv = uint16(dd.DecodeUint(16)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -21843,18 +18190,14 @@ func (_ fastpathT) DecMapUint64Uint32V(v map[uint64]uint32, checkNil bool, canCh } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeUint(64) - dd.ReadMapKVSeparator() mv := v[mk] mv = uint32(dd.DecodeUint(32)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -21908,18 +18251,14 @@ func (_ fastpathT) DecMapUint64Uint64V(v map[uint64]uint64, checkNil bool, canCh } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeUint(64) - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeUint(64) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -21973,18 +18312,14 @@ func (_ fastpathT) DecMapUint64IntV(v map[uint64]int, checkNil bool, canChange b } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeUint(64) - dd.ReadMapKVSeparator() mv := v[mk] mv = int(dd.DecodeInt(intBitsize)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -22038,18 +18373,14 @@ func (_ fastpathT) DecMapUint64Int8V(v map[uint64]int8, checkNil bool, canChange } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeUint(64) - dd.ReadMapKVSeparator() mv := v[mk] mv = int8(dd.DecodeInt(8)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -22103,18 +18434,14 @@ func (_ fastpathT) DecMapUint64Int16V(v map[uint64]int16, checkNil bool, canChan } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeUint(64) - dd.ReadMapKVSeparator() mv := v[mk] mv = int16(dd.DecodeInt(16)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -22168,18 +18495,14 @@ func (_ fastpathT) DecMapUint64Int32V(v map[uint64]int32, checkNil bool, canChan } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeUint(64) - dd.ReadMapKVSeparator() mv := v[mk] mv = int32(dd.DecodeInt(32)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -22233,18 +18556,14 @@ func (_ fastpathT) DecMapUint64Int64V(v map[uint64]int64, checkNil bool, canChan } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeUint(64) - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeInt(64) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -22298,18 +18617,14 @@ func (_ fastpathT) DecMapUint64Float32V(v map[uint64]float32, checkNil bool, can } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeUint(64) - dd.ReadMapKVSeparator() mv := v[mk] mv = float32(dd.DecodeFloat(true)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -22363,18 +18678,14 @@ func (_ fastpathT) DecMapUint64Float64V(v map[uint64]float64, checkNil bool, can } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeUint(64) - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeFloat(false) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -22428,18 +18739,14 @@ func (_ fastpathT) DecMapUint64BoolV(v map[uint64]bool, checkNil bool, canChange } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeUint(64) - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeBool() if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -22494,11 +18801,7 @@ func (_ fastpathT) DecMapIntIntfV(v map[int]interface{}, checkNil bool, canChang } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := int(dd.DecodeInt(intBitsize)) - dd.ReadMapKVSeparator() mv := v[mk] d.decode(&mv) @@ -22506,7 +18809,7 @@ func (_ fastpathT) DecMapIntIntfV(v map[int]interface{}, checkNil bool, canChang v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -22560,18 +18863,14 @@ func (_ fastpathT) DecMapIntStringV(v map[int]string, checkNil bool, canChange b } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := int(dd.DecodeInt(intBitsize)) - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeString() if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -22625,18 +18924,14 @@ func (_ fastpathT) DecMapIntUintV(v map[int]uint, checkNil bool, canChange bool, } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := int(dd.DecodeInt(intBitsize)) - dd.ReadMapKVSeparator() mv := v[mk] mv = uint(dd.DecodeUint(uintBitsize)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -22690,18 +18985,14 @@ func (_ fastpathT) DecMapIntUint8V(v map[int]uint8, checkNil bool, canChange boo } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := int(dd.DecodeInt(intBitsize)) - dd.ReadMapKVSeparator() mv := v[mk] mv = uint8(dd.DecodeUint(8)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -22755,18 +19046,14 @@ func (_ fastpathT) DecMapIntUint16V(v map[int]uint16, checkNil bool, canChange b } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := int(dd.DecodeInt(intBitsize)) - dd.ReadMapKVSeparator() mv := v[mk] mv = uint16(dd.DecodeUint(16)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -22820,18 +19107,14 @@ func (_ fastpathT) DecMapIntUint32V(v map[int]uint32, checkNil bool, canChange b } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := int(dd.DecodeInt(intBitsize)) - dd.ReadMapKVSeparator() mv := v[mk] mv = uint32(dd.DecodeUint(32)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -22885,18 +19168,14 @@ func (_ fastpathT) DecMapIntUint64V(v map[int]uint64, checkNil bool, canChange b } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := int(dd.DecodeInt(intBitsize)) - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeUint(64) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -22950,18 +19229,14 @@ func (_ fastpathT) DecMapIntIntV(v map[int]int, checkNil bool, canChange bool, } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := int(dd.DecodeInt(intBitsize)) - dd.ReadMapKVSeparator() mv := v[mk] mv = int(dd.DecodeInt(intBitsize)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -23015,18 +19290,14 @@ func (_ fastpathT) DecMapIntInt8V(v map[int]int8, checkNil bool, canChange bool, } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := int(dd.DecodeInt(intBitsize)) - dd.ReadMapKVSeparator() mv := v[mk] mv = int8(dd.DecodeInt(8)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -23080,18 +19351,14 @@ func (_ fastpathT) DecMapIntInt16V(v map[int]int16, checkNil bool, canChange boo } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := int(dd.DecodeInt(intBitsize)) - dd.ReadMapKVSeparator() mv := v[mk] mv = int16(dd.DecodeInt(16)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -23145,18 +19412,14 @@ func (_ fastpathT) DecMapIntInt32V(v map[int]int32, checkNil bool, canChange boo } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := int(dd.DecodeInt(intBitsize)) - dd.ReadMapKVSeparator() mv := v[mk] mv = int32(dd.DecodeInt(32)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -23210,18 +19473,14 @@ func (_ fastpathT) DecMapIntInt64V(v map[int]int64, checkNil bool, canChange boo } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := int(dd.DecodeInt(intBitsize)) - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeInt(64) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -23275,18 +19534,14 @@ func (_ fastpathT) DecMapIntFloat32V(v map[int]float32, checkNil bool, canChange } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := int(dd.DecodeInt(intBitsize)) - dd.ReadMapKVSeparator() mv := v[mk] mv = float32(dd.DecodeFloat(true)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -23340,18 +19595,14 @@ func (_ fastpathT) DecMapIntFloat64V(v map[int]float64, checkNil bool, canChange } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := int(dd.DecodeInt(intBitsize)) - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeFloat(false) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -23405,18 +19656,14 @@ func (_ fastpathT) DecMapIntBoolV(v map[int]bool, checkNil bool, canChange bool, } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := int(dd.DecodeInt(intBitsize)) - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeBool() if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -23471,11 +19718,7 @@ func (_ fastpathT) DecMapInt8IntfV(v map[int8]interface{}, checkNil bool, canCha } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := int8(dd.DecodeInt(8)) - dd.ReadMapKVSeparator() mv := v[mk] d.decode(&mv) @@ -23483,7 +19726,7 @@ func (_ fastpathT) DecMapInt8IntfV(v map[int8]interface{}, checkNil bool, canCha v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -23537,18 +19780,14 @@ func (_ fastpathT) DecMapInt8StringV(v map[int8]string, checkNil bool, canChange } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := int8(dd.DecodeInt(8)) - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeString() if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -23602,18 +19841,14 @@ func (_ fastpathT) DecMapInt8UintV(v map[int8]uint, checkNil bool, canChange boo } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := int8(dd.DecodeInt(8)) - dd.ReadMapKVSeparator() mv := v[mk] mv = uint(dd.DecodeUint(uintBitsize)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -23667,18 +19902,14 @@ func (_ fastpathT) DecMapInt8Uint8V(v map[int8]uint8, checkNil bool, canChange b } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := int8(dd.DecodeInt(8)) - dd.ReadMapKVSeparator() mv := v[mk] mv = uint8(dd.DecodeUint(8)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -23732,18 +19963,14 @@ func (_ fastpathT) DecMapInt8Uint16V(v map[int8]uint16, checkNil bool, canChange } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := int8(dd.DecodeInt(8)) - dd.ReadMapKVSeparator() mv := v[mk] mv = uint16(dd.DecodeUint(16)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -23797,18 +20024,14 @@ func (_ fastpathT) DecMapInt8Uint32V(v map[int8]uint32, checkNil bool, canChange } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := int8(dd.DecodeInt(8)) - dd.ReadMapKVSeparator() mv := v[mk] mv = uint32(dd.DecodeUint(32)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -23862,18 +20085,14 @@ func (_ fastpathT) DecMapInt8Uint64V(v map[int8]uint64, checkNil bool, canChange } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := int8(dd.DecodeInt(8)) - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeUint(64) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -23927,18 +20146,14 @@ func (_ fastpathT) DecMapInt8IntV(v map[int8]int, checkNil bool, canChange bool, } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := int8(dd.DecodeInt(8)) - dd.ReadMapKVSeparator() mv := v[mk] mv = int(dd.DecodeInt(intBitsize)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -23992,18 +20207,14 @@ func (_ fastpathT) DecMapInt8Int8V(v map[int8]int8, checkNil bool, canChange boo } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := int8(dd.DecodeInt(8)) - dd.ReadMapKVSeparator() mv := v[mk] mv = int8(dd.DecodeInt(8)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -24057,18 +20268,14 @@ func (_ fastpathT) DecMapInt8Int16V(v map[int8]int16, checkNil bool, canChange b } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := int8(dd.DecodeInt(8)) - dd.ReadMapKVSeparator() mv := v[mk] mv = int16(dd.DecodeInt(16)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -24122,18 +20329,14 @@ func (_ fastpathT) DecMapInt8Int32V(v map[int8]int32, checkNil bool, canChange b } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := int8(dd.DecodeInt(8)) - dd.ReadMapKVSeparator() mv := v[mk] mv = int32(dd.DecodeInt(32)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -24187,18 +20390,14 @@ func (_ fastpathT) DecMapInt8Int64V(v map[int8]int64, checkNil bool, canChange b } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := int8(dd.DecodeInt(8)) - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeInt(64) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -24252,18 +20451,14 @@ func (_ fastpathT) DecMapInt8Float32V(v map[int8]float32, checkNil bool, canChan } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := int8(dd.DecodeInt(8)) - dd.ReadMapKVSeparator() mv := v[mk] mv = float32(dd.DecodeFloat(true)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -24317,18 +20512,14 @@ func (_ fastpathT) DecMapInt8Float64V(v map[int8]float64, checkNil bool, canChan } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := int8(dd.DecodeInt(8)) - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeFloat(false) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -24382,18 +20573,14 @@ func (_ fastpathT) DecMapInt8BoolV(v map[int8]bool, checkNil bool, canChange boo } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := int8(dd.DecodeInt(8)) - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeBool() if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -24448,11 +20635,7 @@ func (_ fastpathT) DecMapInt16IntfV(v map[int16]interface{}, checkNil bool, canC } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := int16(dd.DecodeInt(16)) - dd.ReadMapKVSeparator() mv := v[mk] d.decode(&mv) @@ -24460,7 +20643,7 @@ func (_ fastpathT) DecMapInt16IntfV(v map[int16]interface{}, checkNil bool, canC v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -24514,18 +20697,14 @@ func (_ fastpathT) DecMapInt16StringV(v map[int16]string, checkNil bool, canChan } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := int16(dd.DecodeInt(16)) - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeString() if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -24579,18 +20758,14 @@ func (_ fastpathT) DecMapInt16UintV(v map[int16]uint, checkNil bool, canChange b } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := int16(dd.DecodeInt(16)) - dd.ReadMapKVSeparator() mv := v[mk] mv = uint(dd.DecodeUint(uintBitsize)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -24644,18 +20819,14 @@ func (_ fastpathT) DecMapInt16Uint8V(v map[int16]uint8, checkNil bool, canChange } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := int16(dd.DecodeInt(16)) - dd.ReadMapKVSeparator() mv := v[mk] mv = uint8(dd.DecodeUint(8)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -24709,18 +20880,14 @@ func (_ fastpathT) DecMapInt16Uint16V(v map[int16]uint16, checkNil bool, canChan } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := int16(dd.DecodeInt(16)) - dd.ReadMapKVSeparator() mv := v[mk] mv = uint16(dd.DecodeUint(16)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -24774,18 +20941,14 @@ func (_ fastpathT) DecMapInt16Uint32V(v map[int16]uint32, checkNil bool, canChan } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := int16(dd.DecodeInt(16)) - dd.ReadMapKVSeparator() mv := v[mk] mv = uint32(dd.DecodeUint(32)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -24839,18 +21002,14 @@ func (_ fastpathT) DecMapInt16Uint64V(v map[int16]uint64, checkNil bool, canChan } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := int16(dd.DecodeInt(16)) - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeUint(64) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -24904,18 +21063,14 @@ func (_ fastpathT) DecMapInt16IntV(v map[int16]int, checkNil bool, canChange boo } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := int16(dd.DecodeInt(16)) - dd.ReadMapKVSeparator() mv := v[mk] mv = int(dd.DecodeInt(intBitsize)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -24969,18 +21124,14 @@ func (_ fastpathT) DecMapInt16Int8V(v map[int16]int8, checkNil bool, canChange b } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := int16(dd.DecodeInt(16)) - dd.ReadMapKVSeparator() mv := v[mk] mv = int8(dd.DecodeInt(8)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -25034,18 +21185,14 @@ func (_ fastpathT) DecMapInt16Int16V(v map[int16]int16, checkNil bool, canChange } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := int16(dd.DecodeInt(16)) - dd.ReadMapKVSeparator() mv := v[mk] mv = int16(dd.DecodeInt(16)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -25099,18 +21246,14 @@ func (_ fastpathT) DecMapInt16Int32V(v map[int16]int32, checkNil bool, canChange } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := int16(dd.DecodeInt(16)) - dd.ReadMapKVSeparator() mv := v[mk] mv = int32(dd.DecodeInt(32)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -25164,18 +21307,14 @@ func (_ fastpathT) DecMapInt16Int64V(v map[int16]int64, checkNil bool, canChange } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := int16(dd.DecodeInt(16)) - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeInt(64) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -25229,18 +21368,14 @@ func (_ fastpathT) DecMapInt16Float32V(v map[int16]float32, checkNil bool, canCh } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := int16(dd.DecodeInt(16)) - dd.ReadMapKVSeparator() mv := v[mk] mv = float32(dd.DecodeFloat(true)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -25294,18 +21429,14 @@ func (_ fastpathT) DecMapInt16Float64V(v map[int16]float64, checkNil bool, canCh } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := int16(dd.DecodeInt(16)) - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeFloat(false) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -25359,18 +21490,14 @@ func (_ fastpathT) DecMapInt16BoolV(v map[int16]bool, checkNil bool, canChange b } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := int16(dd.DecodeInt(16)) - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeBool() if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -25425,11 +21552,7 @@ func (_ fastpathT) DecMapInt32IntfV(v map[int32]interface{}, checkNil bool, canC } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := int32(dd.DecodeInt(32)) - dd.ReadMapKVSeparator() mv := v[mk] d.decode(&mv) @@ -25437,7 +21560,7 @@ func (_ fastpathT) DecMapInt32IntfV(v map[int32]interface{}, checkNil bool, canC v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -25491,18 +21614,14 @@ func (_ fastpathT) DecMapInt32StringV(v map[int32]string, checkNil bool, canChan } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := int32(dd.DecodeInt(32)) - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeString() if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -25556,18 +21675,14 @@ func (_ fastpathT) DecMapInt32UintV(v map[int32]uint, checkNil bool, canChange b } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := int32(dd.DecodeInt(32)) - dd.ReadMapKVSeparator() mv := v[mk] mv = uint(dd.DecodeUint(uintBitsize)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -25621,18 +21736,14 @@ func (_ fastpathT) DecMapInt32Uint8V(v map[int32]uint8, checkNil bool, canChange } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := int32(dd.DecodeInt(32)) - dd.ReadMapKVSeparator() mv := v[mk] mv = uint8(dd.DecodeUint(8)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -25686,18 +21797,14 @@ func (_ fastpathT) DecMapInt32Uint16V(v map[int32]uint16, checkNil bool, canChan } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := int32(dd.DecodeInt(32)) - dd.ReadMapKVSeparator() mv := v[mk] mv = uint16(dd.DecodeUint(16)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -25751,18 +21858,14 @@ func (_ fastpathT) DecMapInt32Uint32V(v map[int32]uint32, checkNil bool, canChan } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := int32(dd.DecodeInt(32)) - dd.ReadMapKVSeparator() mv := v[mk] mv = uint32(dd.DecodeUint(32)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -25816,18 +21919,14 @@ func (_ fastpathT) DecMapInt32Uint64V(v map[int32]uint64, checkNil bool, canChan } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := int32(dd.DecodeInt(32)) - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeUint(64) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -25881,18 +21980,14 @@ func (_ fastpathT) DecMapInt32IntV(v map[int32]int, checkNil bool, canChange boo } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := int32(dd.DecodeInt(32)) - dd.ReadMapKVSeparator() mv := v[mk] mv = int(dd.DecodeInt(intBitsize)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -25946,18 +22041,14 @@ func (_ fastpathT) DecMapInt32Int8V(v map[int32]int8, checkNil bool, canChange b } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := int32(dd.DecodeInt(32)) - dd.ReadMapKVSeparator() mv := v[mk] mv = int8(dd.DecodeInt(8)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -26011,18 +22102,14 @@ func (_ fastpathT) DecMapInt32Int16V(v map[int32]int16, checkNil bool, canChange } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := int32(dd.DecodeInt(32)) - dd.ReadMapKVSeparator() mv := v[mk] mv = int16(dd.DecodeInt(16)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -26076,18 +22163,14 @@ func (_ fastpathT) DecMapInt32Int32V(v map[int32]int32, checkNil bool, canChange } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := int32(dd.DecodeInt(32)) - dd.ReadMapKVSeparator() mv := v[mk] mv = int32(dd.DecodeInt(32)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -26141,18 +22224,14 @@ func (_ fastpathT) DecMapInt32Int64V(v map[int32]int64, checkNil bool, canChange } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := int32(dd.DecodeInt(32)) - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeInt(64) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -26206,18 +22285,14 @@ func (_ fastpathT) DecMapInt32Float32V(v map[int32]float32, checkNil bool, canCh } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := int32(dd.DecodeInt(32)) - dd.ReadMapKVSeparator() mv := v[mk] mv = float32(dd.DecodeFloat(true)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -26271,18 +22346,14 @@ func (_ fastpathT) DecMapInt32Float64V(v map[int32]float64, checkNil bool, canCh } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := int32(dd.DecodeInt(32)) - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeFloat(false) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -26336,18 +22407,14 @@ func (_ fastpathT) DecMapInt32BoolV(v map[int32]bool, checkNil bool, canChange b } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := int32(dd.DecodeInt(32)) - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeBool() if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -26402,11 +22469,7 @@ func (_ fastpathT) DecMapInt64IntfV(v map[int64]interface{}, checkNil bool, canC } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeInt(64) - dd.ReadMapKVSeparator() mv := v[mk] d.decode(&mv) @@ -26414,7 +22477,7 @@ func (_ fastpathT) DecMapInt64IntfV(v map[int64]interface{}, checkNil bool, canC v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -26468,18 +22531,14 @@ func (_ fastpathT) DecMapInt64StringV(v map[int64]string, checkNil bool, canChan } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeInt(64) - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeString() if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -26533,18 +22592,14 @@ func (_ fastpathT) DecMapInt64UintV(v map[int64]uint, checkNil bool, canChange b } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeInt(64) - dd.ReadMapKVSeparator() mv := v[mk] mv = uint(dd.DecodeUint(uintBitsize)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -26598,18 +22653,14 @@ func (_ fastpathT) DecMapInt64Uint8V(v map[int64]uint8, checkNil bool, canChange } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeInt(64) - dd.ReadMapKVSeparator() mv := v[mk] mv = uint8(dd.DecodeUint(8)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -26663,18 +22714,14 @@ func (_ fastpathT) DecMapInt64Uint16V(v map[int64]uint16, checkNil bool, canChan } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeInt(64) - dd.ReadMapKVSeparator() mv := v[mk] mv = uint16(dd.DecodeUint(16)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -26728,18 +22775,14 @@ func (_ fastpathT) DecMapInt64Uint32V(v map[int64]uint32, checkNil bool, canChan } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeInt(64) - dd.ReadMapKVSeparator() mv := v[mk] mv = uint32(dd.DecodeUint(32)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -26793,18 +22836,14 @@ func (_ fastpathT) DecMapInt64Uint64V(v map[int64]uint64, checkNil bool, canChan } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeInt(64) - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeUint(64) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -26858,18 +22897,14 @@ func (_ fastpathT) DecMapInt64IntV(v map[int64]int, checkNil bool, canChange boo } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeInt(64) - dd.ReadMapKVSeparator() mv := v[mk] mv = int(dd.DecodeInt(intBitsize)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -26923,18 +22958,14 @@ func (_ fastpathT) DecMapInt64Int8V(v map[int64]int8, checkNil bool, canChange b } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeInt(64) - dd.ReadMapKVSeparator() mv := v[mk] mv = int8(dd.DecodeInt(8)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -26988,18 +23019,14 @@ func (_ fastpathT) DecMapInt64Int16V(v map[int64]int16, checkNil bool, canChange } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeInt(64) - dd.ReadMapKVSeparator() mv := v[mk] mv = int16(dd.DecodeInt(16)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -27053,18 +23080,14 @@ func (_ fastpathT) DecMapInt64Int32V(v map[int64]int32, checkNil bool, canChange } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeInt(64) - dd.ReadMapKVSeparator() mv := v[mk] mv = int32(dd.DecodeInt(32)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -27118,18 +23141,14 @@ func (_ fastpathT) DecMapInt64Int64V(v map[int64]int64, checkNil bool, canChange } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeInt(64) - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeInt(64) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -27183,18 +23202,14 @@ func (_ fastpathT) DecMapInt64Float32V(v map[int64]float32, checkNil bool, canCh } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeInt(64) - dd.ReadMapKVSeparator() mv := v[mk] mv = float32(dd.DecodeFloat(true)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -27248,18 +23263,14 @@ func (_ fastpathT) DecMapInt64Float64V(v map[int64]float64, checkNil bool, canCh } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeInt(64) - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeFloat(false) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -27313,18 +23324,14 @@ func (_ fastpathT) DecMapInt64BoolV(v map[int64]bool, checkNil bool, canChange b } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeInt(64) - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeBool() if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -27379,11 +23386,7 @@ func (_ fastpathT) DecMapBoolIntfV(v map[bool]interface{}, checkNil bool, canCha } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeBool() - dd.ReadMapKVSeparator() mv := v[mk] d.decode(&mv) @@ -27391,7 +23394,7 @@ func (_ fastpathT) DecMapBoolIntfV(v map[bool]interface{}, checkNil bool, canCha v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -27445,18 +23448,14 @@ func (_ fastpathT) DecMapBoolStringV(v map[bool]string, checkNil bool, canChange } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeBool() - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeString() if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -27510,18 +23509,14 @@ func (_ fastpathT) DecMapBoolUintV(v map[bool]uint, checkNil bool, canChange boo } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeBool() - dd.ReadMapKVSeparator() mv := v[mk] mv = uint(dd.DecodeUint(uintBitsize)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -27575,18 +23570,14 @@ func (_ fastpathT) DecMapBoolUint8V(v map[bool]uint8, checkNil bool, canChange b } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeBool() - dd.ReadMapKVSeparator() mv := v[mk] mv = uint8(dd.DecodeUint(8)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -27640,18 +23631,14 @@ func (_ fastpathT) DecMapBoolUint16V(v map[bool]uint16, checkNil bool, canChange } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeBool() - dd.ReadMapKVSeparator() mv := v[mk] mv = uint16(dd.DecodeUint(16)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -27705,18 +23692,14 @@ func (_ fastpathT) DecMapBoolUint32V(v map[bool]uint32, checkNil bool, canChange } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeBool() - dd.ReadMapKVSeparator() mv := v[mk] mv = uint32(dd.DecodeUint(32)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -27770,18 +23753,14 @@ func (_ fastpathT) DecMapBoolUint64V(v map[bool]uint64, checkNil bool, canChange } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeBool() - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeUint(64) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -27835,18 +23814,14 @@ func (_ fastpathT) DecMapBoolIntV(v map[bool]int, checkNil bool, canChange bool, } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeBool() - dd.ReadMapKVSeparator() mv := v[mk] mv = int(dd.DecodeInt(intBitsize)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -27900,18 +23875,14 @@ func (_ fastpathT) DecMapBoolInt8V(v map[bool]int8, checkNil bool, canChange boo } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeBool() - dd.ReadMapKVSeparator() mv := v[mk] mv = int8(dd.DecodeInt(8)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -27965,18 +23936,14 @@ func (_ fastpathT) DecMapBoolInt16V(v map[bool]int16, checkNil bool, canChange b } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeBool() - dd.ReadMapKVSeparator() mv := v[mk] mv = int16(dd.DecodeInt(16)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -28030,18 +23997,14 @@ func (_ fastpathT) DecMapBoolInt32V(v map[bool]int32, checkNil bool, canChange b } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeBool() - dd.ReadMapKVSeparator() mv := v[mk] mv = int32(dd.DecodeInt(32)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -28095,18 +24058,14 @@ func (_ fastpathT) DecMapBoolInt64V(v map[bool]int64, checkNil bool, canChange b } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeBool() - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeInt(64) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -28160,18 +24119,14 @@ func (_ fastpathT) DecMapBoolFloat32V(v map[bool]float32, checkNil bool, canChan } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeBool() - dd.ReadMapKVSeparator() mv := v[mk] mv = float32(dd.DecodeFloat(true)) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -28225,18 +24180,14 @@ func (_ fastpathT) DecMapBoolFloat64V(v map[bool]float64, checkNil bool, canChan } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeBool() - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeFloat(false) if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } @@ -28290,18 +24241,14 @@ func (_ fastpathT) DecMapBoolBoolV(v map[bool]bool, checkNil bool, canChange boo } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } mk := dd.DecodeBool() - dd.ReadMapKVSeparator() mv := v[mk] mv = dd.DecodeBool() if v != nil { v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } diff --git a/Godeps/_workspace/src/github.com/ugorji/go/codec/fast-path.go.tmpl b/Godeps/_workspace/src/github.com/ugorji/go/codec/fast-path.go.tmpl index 9f0adccf8..d45e2b638 100644 --- a/Godeps/_workspace/src/github.com/ugorji/go/codec/fast-path.go.tmpl +++ b/Godeps/_workspace/src/github.com/ugorji/go/codec/fast-path.go.tmpl @@ -162,19 +162,10 @@ func (_ fastpathT) {{ .MethodNamePfx "Enc" false }}V(v []{{ .Elem }}, checkNil b return } ee.EncodeArrayStart(len(v)) - if e.be { - for _, v2 := range v { - {{ encmd .Elem "v2"}} - } - } else { - for j, v2 := range v { - if j > 0 { - ee.EncodeArrayEntrySeparator() - } - {{ encmd .Elem "v2"}} - } - ee.EncodeArrayEnd() + for _, v2 := range v { + {{ encmd .Elem "v2"}} } + ee.EncodeEnd() } {{end}}{{end}}{{end}} @@ -192,32 +183,15 @@ func (_ fastpathT) {{ .MethodNamePfx "Enc" false }}V(v map[{{ .MapKey }}]{{ .Ele } ee.EncodeMapStart(len(v)) {{if eq .MapKey "string"}}asSymbols := e.h.AsSymbols&AsSymbolMapStringKeysFlag != 0{{end}} - if e.be { - for k2, v2 := range v { - {{if eq .MapKey "string"}}if asSymbols { - ee.EncodeSymbol(k2) - } else { - ee.EncodeString(c_UTF8, k2) - }{{else}}{{ encmd .MapKey "k2"}}{{end}} - {{ encmd .Elem "v2"}} - } - } else { - j := 0 - for k2, v2 := range v { - if j > 0 { - ee.EncodeMapEntrySeparator() - } - {{if eq .MapKey "string"}}if asSymbols { - ee.EncodeSymbol(k2) - } else { - ee.EncodeString(c_UTF8, k2) - }{{else}}{{ encmd .MapKey "k2"}}{{end}} - ee.EncodeMapKVSeparator() - {{ encmd .Elem "v2"}} - j++ - } - ee.EncodeMapEnd() + for k2, v2 := range v { + {{if eq .MapKey "string"}}if asSymbols { + ee.EncodeSymbol(k2) + } else { + ee.EncodeString(c_UTF8, k2) + }{{else}}{{ encmd .MapKey "k2"}}{{end}} + {{ encmd .Elem "v2"}} } + ee.EncodeEnd() } {{end}}{{end}}{{end}} @@ -340,9 +314,6 @@ func (_ fastpathT) {{ .MethodNamePfx "Dec" false }}V(v []{{ .Elem }}, checkNil b d.arrayCannotExpand(len(v), j+1) } } - if j > 0 { - slh.Sep(j) - } if j < len(v) { // all checks done. cannot go past len. {{ if eq .Elem "interface{}" }}d.decode(&v[j]) {{ else }}v[j] = {{ decmd .Elem }}{{ end }} @@ -418,15 +389,11 @@ func (_ fastpathT) {{ .MethodNamePfx "Dec" false }}V(v map[{{ .MapKey }}]{{ .Ele } } else if containerLen < 0 { for j := 0; !dd.CheckBreak(); j++ { - if j > 0 { - dd.ReadMapEntrySeparator() - } {{ if eq .MapKey "interface{}" }}var mk interface{} d.decode(&mk) if bv, bok := mk.([]byte); bok { mk = string(bv) // maps cannot have []byte as key. switch to string. }{{ else }}mk := {{ decmd .MapKey }}{{ end }} - dd.ReadMapKVSeparator() mv := v[mk] {{ if eq .Elem "interface{}" }}d.decode(&mv) {{ else }}mv = {{ decmd .Elem }}{{ end }} @@ -434,7 +401,7 @@ func (_ fastpathT) {{ .MethodNamePfx "Dec" false }}V(v map[{{ .MapKey }}]{{ .Ele v[mk] = mv } } - dd.ReadMapEnd() + dd.ReadEnd() } return v, changed } diff --git a/Godeps/_workspace/src/github.com/ugorji/go/codec/gen-dec-array.go.tmpl b/Godeps/_workspace/src/github.com/ugorji/go/codec/gen-dec-array.go.tmpl index 0f4ea91d2..4c15e85ed 100644 --- a/Godeps/_workspace/src/github.com/ugorji/go/codec/gen-dec-array.go.tmpl +++ b/Godeps/_workspace/src/github.com/ugorji/go/codec/gen-dec-array.go.tmpl @@ -57,9 +57,6 @@ if {{var "l"}} == 0 { {{ if isSlice }} {{ else if isSlice}}{{var "v"}} = append({{var "v"}}, {{zero}})// var {{var "z"}} {{ .Typ }} {{var "c"}} = true {{ end }} } - if {{var "j"}} > 0 { - {{var "h"}}.Sep({{var "j"}}) - } {{ if isChan}} var {{var "t"}} {{ .Typ }} {{ $x := printf "%st%s" .TempVar .Rand }}{{ decLineVar $x }} diff --git a/Godeps/_workspace/src/github.com/ugorji/go/codec/gen-dec-map.go.tmpl b/Godeps/_workspace/src/github.com/ugorji/go/codec/gen-dec-map.go.tmpl index 9f8dafa54..07e570cbe 100644 --- a/Godeps/_workspace/src/github.com/ugorji/go/codec/gen-dec-map.go.tmpl +++ b/Godeps/_workspace/src/github.com/ugorji/go/codec/gen-dec-map.go.tmpl @@ -25,9 +25,6 @@ for {{var "j"}} := 0; {{var "j"}} < {{var "l"}}; {{var "j"}}++ { } } else if {{var "l"}} < 0 { for {{var "j"}} := 0; !r.CheckBreak(); {{var "j"}}++ { - if {{var "j"}} > 0 { - r.ReadMapEntrySeparator() - } var {{var "mk"}} {{ .KTyp }} {{ $x := printf "%vmk%v" .TempVar .Rand }}{{ decLineVarK $x }} {{ if eq .KTyp "interface{}" }}// special case if a byte array. @@ -35,12 +32,11 @@ for {{var "j"}} := 0; !r.CheckBreak(); {{var "j"}}++ { {{var "mk"}} = string({{var "bv"}}) } {{ end }} - r.ReadMapKVSeparator() {{var "mv"}} := {{var "v"}}[{{var "mk"}}] {{ $x := printf "%vmv%v" .TempVar .Rand }}{{ decLineVar $x }} if {{var "v"}} != nil { {{var "v"}}[{{var "mk"}}] = {{var "mv"}} } } -r.ReadMapEnd() +r.ReadEnd() } // else len==0: TODO: Should we clear map entries? diff --git a/Godeps/_workspace/src/github.com/ugorji/go/codec/gen-helper.generated.go b/Godeps/_workspace/src/github.com/ugorji/go/codec/gen-helper.generated.go index ecf3ee54c..32f494668 100644 --- a/Godeps/_workspace/src/github.com/ugorji/go/codec/gen-helper.generated.go +++ b/Godeps/_workspace/src/github.com/ugorji/go/codec/gen-helper.generated.go @@ -10,6 +10,11 @@ package codec +import ( + "encoding" + "reflect" +) + // This file is used to generate helper code for codecgen. // The values here i.e. genHelper(En|De)coder are not to be used directly by // library users. They WILL change continously and without notice. @@ -60,6 +65,56 @@ func (f genHelperEncoder) EncFallback(iv interface{}) { f.e.encodeI(iv, false, false) } +// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* +func (f genHelperEncoder) EncTextMarshal(iv encoding.TextMarshaler) { + bs, fnerr := iv.MarshalText() + f.e.marshal(bs, fnerr, false, c_UTF8) +} + +// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* +func (f genHelperEncoder) EncJSONMarshal(iv jsonMarshaler) { + bs, fnerr := iv.MarshalJSON() + f.e.marshal(bs, fnerr, true, c_UTF8) +} + +// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* +func (f genHelperEncoder) EncBinaryMarshal(iv encoding.BinaryMarshaler) { + bs, fnerr := iv.MarshalBinary() + f.e.marshal(bs, fnerr, false, c_RAW) +} + +// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* +func (f genHelperEncoder) TimeRtidIfBinc() uintptr { + if _, ok := f.e.hh.(*BincHandle); ok { + return timeTypId + } + return 0 +} + +// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* +func (f genHelperEncoder) IsJSONHandle() bool { + return f.e.js +} + +// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* +func (f genHelperEncoder) HasExtensions() bool { + return len(f.e.h.extHandle) != 0 +} + +// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* +func (f genHelperEncoder) EncExt(v interface{}) (r bool) { + rt := reflect.TypeOf(v) + if rt.Kind() == reflect.Ptr { + rt = rt.Elem() + } + rtid := reflect.ValueOf(rt).Pointer() + if xfFn := f.e.h.getExt(rtid); xfFn != nil { + f.e.e.EncodeExt(v, xfFn.tag, xfFn.ext, f.e) + return true + } + return false +} + // FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* func (f genHelperDecoder) DecBasicHandle() *BasicHandle { return f.d.h @@ -100,3 +155,61 @@ func (f genHelperDecoder) DecStructFieldNotFound(index int, name string) { func (f genHelperDecoder) DecArrayCannotExpand(sliceLen, streamLen int) { f.d.arrayCannotExpand(sliceLen, streamLen) } + +// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* +func (f genHelperDecoder) DecTextUnmarshal(tm encoding.TextUnmarshaler) { + fnerr := tm.UnmarshalText(f.d.d.DecodeBytes(f.d.b[:], true, true)) + if fnerr != nil { + panic(fnerr) + } +} + +// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* +func (f genHelperDecoder) DecJSONUnmarshal(tm jsonUnmarshaler) { + // bs := f.dd.DecodeBytes(f.d.b[:], true, true) + f.d.r.track() + f.d.swallow() + bs := f.d.r.stopTrack() + // fmt.Printf(">>>>>> CODECGEN JSON: %s\n", bs) + fnerr := tm.UnmarshalJSON(bs) + if fnerr != nil { + panic(fnerr) + } +} + +// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* +func (f genHelperDecoder) DecBinaryUnmarshal(bm encoding.BinaryUnmarshaler) { + fnerr := bm.UnmarshalBinary(f.d.d.DecodeBytes(nil, false, true)) + if fnerr != nil { + panic(fnerr) + } +} + +// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* +func (f genHelperDecoder) TimeRtidIfBinc() uintptr { + if _, ok := f.d.hh.(*BincHandle); ok { + return timeTypId + } + return 0 +} + +// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* +func (f genHelperDecoder) IsJSONHandle() bool { + return f.d.js +} + +// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* +func (f genHelperDecoder) HasExtensions() bool { + return len(f.d.h.extHandle) != 0 +} + +// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* +func (f genHelperDecoder) DecExt(v interface{}) (r bool) { + rt := reflect.TypeOf(v).Elem() + rtid := reflect.ValueOf(rt).Pointer() + if xfFn := f.d.h.getExt(rtid); xfFn != nil { + f.d.d.DecodeExt(v, xfFn.tag, xfFn.ext) + return true + } + return false +} diff --git a/Godeps/_workspace/src/github.com/ugorji/go/codec/gen-helper.go.tmpl b/Godeps/_workspace/src/github.com/ugorji/go/codec/gen-helper.go.tmpl index 89d75185a..0960b56d5 100644 --- a/Godeps/_workspace/src/github.com/ugorji/go/codec/gen-helper.go.tmpl +++ b/Godeps/_workspace/src/github.com/ugorji/go/codec/gen-helper.go.tmpl @@ -10,6 +10,11 @@ package codec +import ( + "encoding" + "reflect" +) + // This file is used to generate helper code for codecgen. // The values here i.e. genHelper(En|De)coder are not to be used directly by // library users. They WILL change continously and without notice. @@ -48,6 +53,7 @@ type genHelperDecoder struct { func (f genHelperEncoder) EncBasicHandle() *BasicHandle { return f.e.h } + // FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* func (f genHelperEncoder) EncBinary() bool { return f.e.be // f.e.hh.isBinaryEncoding() @@ -57,6 +63,49 @@ func (f genHelperEncoder) EncFallback(iv interface{}) { // println(">>>>>>>>> EncFallback") f.e.encodeI(iv, false, false) } +// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* +func (f genHelperEncoder) EncTextMarshal(iv encoding.TextMarshaler) { + bs, fnerr := iv.MarshalText() + f.e.marshal(bs, fnerr, false, c_UTF8) +} +// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* +func (f genHelperEncoder) EncJSONMarshal(iv jsonMarshaler) { + bs, fnerr := iv.MarshalJSON() + f.e.marshal(bs, fnerr, true, c_UTF8) +} +// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* +func (f genHelperEncoder) EncBinaryMarshal(iv encoding.BinaryMarshaler) { + bs, fnerr := iv.MarshalBinary() + f.e.marshal(bs, fnerr, false, c_RAW) +} +// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* +func (f genHelperEncoder) TimeRtidIfBinc() uintptr { + if _, ok := f.e.hh.(*BincHandle); ok { + return timeTypId + } + return 0 +} +// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* +func (f genHelperEncoder) IsJSONHandle() bool { + return f.e.js +} +// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* +func (f genHelperEncoder) HasExtensions() bool { + return len(f.e.h.extHandle) != 0 +} +// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* +func (f genHelperEncoder) EncExt(v interface{}) (r bool) { + rt := reflect.TypeOf(v) + if rt.Kind() == reflect.Ptr { + rt = rt.Elem() + } + rtid := reflect.ValueOf(rt).Pointer() + if xfFn := f.e.h.getExt(rtid); xfFn != nil { + f.e.e.EncodeExt(v, xfFn.tag, xfFn.ext, f.e) + return true + } + return false +} // FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* func (f genHelperDecoder) DecBasicHandle() *BasicHandle { @@ -91,7 +140,57 @@ func (f genHelperDecoder) DecStructFieldNotFound(index int, name string) { func (f genHelperDecoder) DecArrayCannotExpand(sliceLen, streamLen int) { f.d.arrayCannotExpand(sliceLen, streamLen) } - +// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* +func (f genHelperDecoder) DecTextUnmarshal(tm encoding.TextUnmarshaler) { + fnerr := tm.UnmarshalText(f.d.d.DecodeBytes(f.d.b[:], true, true)) + if fnerr != nil { + panic(fnerr) + } +} +// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* +func (f genHelperDecoder) DecJSONUnmarshal(tm jsonUnmarshaler) { + // bs := f.dd.DecodeBytes(f.d.b[:], true, true) + f.d.r.track() + f.d.swallow() + bs := f.d.r.stopTrack() + // fmt.Printf(">>>>>> CODECGEN JSON: %s\n", bs) + fnerr := tm.UnmarshalJSON(bs) + if fnerr != nil { + panic(fnerr) + } +} +// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* +func (f genHelperDecoder) DecBinaryUnmarshal(bm encoding.BinaryUnmarshaler) { + fnerr := bm.UnmarshalBinary(f.d.d.DecodeBytes(nil, false, true)) + if fnerr != nil { + panic(fnerr) + } +} +// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* +func (f genHelperDecoder) TimeRtidIfBinc() uintptr { + if _, ok := f.d.hh.(*BincHandle); ok { + return timeTypId + } + return 0 +} +// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* +func (f genHelperDecoder) IsJSONHandle() bool { + return f.d.js +} +// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* +func (f genHelperDecoder) HasExtensions() bool { + return len(f.d.h.extHandle) != 0 +} +// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE* +func (f genHelperDecoder) DecExt(v interface{}) (r bool) { + rt := reflect.TypeOf(v).Elem() + rtid := reflect.ValueOf(rt).Pointer() + if xfFn := f.d.h.getExt(rtid); xfFn != nil { + f.d.d.DecodeExt(v, xfFn.tag, xfFn.ext) + return true + } + return false +} {{/* diff --git a/Godeps/_workspace/src/github.com/ugorji/go/codec/gen.generated.go b/Godeps/_workspace/src/github.com/ugorji/go/codec/gen.generated.go index 8cc254ebf..adc164569 100644 --- a/Godeps/_workspace/src/github.com/ugorji/go/codec/gen.generated.go +++ b/Godeps/_workspace/src/github.com/ugorji/go/codec/gen.generated.go @@ -33,9 +33,6 @@ for {{var "j"}} := 0; {{var "j"}} < {{var "l"}}; {{var "j"}}++ { } } else if {{var "l"}} < 0 { for {{var "j"}} := 0; !r.CheckBreak(); {{var "j"}}++ { - if {{var "j"}} > 0 { - r.ReadMapEntrySeparator() - } var {{var "mk"}} {{ .KTyp }} {{ $x := printf "%vmk%v" .TempVar .Rand }}{{ decLineVarK $x }} {{ if eq .KTyp "interface{}" }}// special case if a byte array. @@ -43,14 +40,13 @@ for {{var "j"}} := 0; !r.CheckBreak(); {{var "j"}}++ { {{var "mk"}} = string({{var "bv"}}) } {{ end }} - r.ReadMapKVSeparator() {{var "mv"}} := {{var "v"}}[{{var "mk"}}] {{ $x := printf "%vmv%v" .TempVar .Rand }}{{ decLineVar $x }} if {{var "v"}} != nil { {{var "v"}}[{{var "mk"}}] = {{var "mv"}} } } -r.ReadMapEnd() +r.ReadEnd() } // else len==0: TODO: Should we clear map entries? ` @@ -114,9 +110,6 @@ if {{var "l"}} == 0 { {{ if isSlice }} {{ else if isSlice}}{{var "v"}} = append({{var "v"}}, {{zero}})// var {{var "z"}} {{ .Typ }} {{var "c"}} = true {{ end }} } - if {{var "j"}} > 0 { - {{var "h"}}.Sep({{var "j"}}) - } {{ if isChan}} var {{var "t"}} {{ .Typ }} {{ $x := printf "%st%s" .TempVar .Rand }}{{ decLineVar $x }} diff --git a/Godeps/_workspace/src/github.com/ugorji/go/codec/gen.go b/Godeps/_workspace/src/github.com/ugorji/go/codec/gen.go index b1eee33fe..64acfa3eb 100644 --- a/Godeps/_workspace/src/github.com/ugorji/go/codec/gen.go +++ b/Godeps/_workspace/src/github.com/ugorji/go/codec/gen.go @@ -22,14 +22,25 @@ import ( ) // --------------------------------------------------- -// codecgen only works in the following: -// - extensions are not supported. Do not make a type a Selfer and an extension. -// - Selfer takes precedence. -// Any type that implements it knows how to encode/decode itself statically. -// Extensions are only known at runtime. -// codecgen only looks at the Kind of the type. +// codecgen supports the full cycle of reflection-based codec: +// - RawExt +// - Builtins +// - Extensions +// - (Binary|Text|JSON)(Unm|M)arshal +// - generic by-kind // -// - the following types are supported: +// This means that, for dynamic things, we MUST use reflection to at least get the reflect.Type. +// In those areas, we try to only do reflection or interface-conversion when NECESSARY: +// - Extensions, only if Extensions are configured. +// +// However, codecgen doesn't support the following: +// - Canonical option. (codecgen IGNORES it currently) +// This is just because it has not been implemented. +// +// During encode/decode, Selfer takes precedence. +// A type implementing Selfer will know how to encode/decode itself statically. +// +// The following field types are supported: // array: [n]T // slice: []T // map: map[K]V @@ -66,11 +77,24 @@ import ( // It was a concious decision to have gen.go always explicitly call EncodeNil or TryDecodeAsNil. // This way, there isn't a function call overhead just to see that we should not enter a block of code. -const GenVersion = 2 // increment this value each time codecgen changes fundamentally. +// GenVersion is the current version of codecgen. +// +// NOTE: Increment this value each time codecgen changes fundamentally. +// Fundamental changes are: +// - helper methods change (signature change, new ones added, some removed, etc) +// - codecgen command line changes +// +// v1: Initial Version +// v2: +// v3: Changes for Kubernetes: +// changes in signature of some unpublished helper methods and codecgen cmdline arguments. +// v4: Removed separator support from (en|de)cDriver, and refactored codec(gen) +const GenVersion = 4 const ( - genCodecPkg = "codec1978" - genTempVarPfx = "yy" + genCodecPkg = "codec1978" + genTempVarPfx = "yy" + genTopLevelVarName = "x" // ignore canBeNil parameter, and always set to true. // This is because nil can appear anywhere, so we should always check. @@ -94,30 +118,38 @@ var ( // genRunner holds some state used during a Gen run. type genRunner struct { w io.Writer // output - c uint64 // ctr used for generating varsfx + c uint64 // counter used for generating varsfx t []reflect.Type // list of types to run selfer on - tc reflect.Type // currently running selfer on this type - te map[uintptr]bool // types for which the encoder has been created - td map[uintptr]bool // types for which the decoder has been created - cp string // codec import path - im map[string]reflect.Type // imports to add + tc reflect.Type // currently running selfer on this type + te map[uintptr]bool // types for which the encoder has been created + td map[uintptr]bool // types for which the decoder has been created + cp string // codec import path + + im map[string]reflect.Type // imports to add + imn map[string]string // package names of imports to add + imc uint64 // counter for import numbers + is map[reflect.Type]struct{} // types seen during import search bp string // base PkgPath, for which we are generating for cpfx string // codec package prefix unsafe bool // is unsafe to be used in generated code? - ts map[reflect.Type]struct{} // types for which enc/dec must be generated - xs string // top level variable/constant suffix - hn string // fn helper type name + tm map[reflect.Type]struct{} // types for which enc/dec must be generated + ts []reflect.Type // types for which enc/dec must be generated - rr *rand.Rand // random generator for file-specific types + xs string // top level variable/constant suffix + hn string // fn helper type name + + // rr *rand.Rand // random generator for file-specific types } // Gen will write a complete go file containing Selfer implementations for each // type passed. All the types must be in the same package. -func Gen(w io.Writer, buildTags, pkgName string, useUnsafe bool, typ ...reflect.Type) { +// +// Library users: *DO NOT USE IT DIRECTLY. IT WILL CHANGE CONTINOUSLY WITHOUT NOTICE.* +func Gen(w io.Writer, buildTags, pkgName, uid string, useUnsafe bool, typ ...reflect.Type) { if len(typ) == 0 { return } @@ -128,14 +160,21 @@ func Gen(w io.Writer, buildTags, pkgName string, useUnsafe bool, typ ...reflect. te: make(map[uintptr]bool), td: make(map[uintptr]bool), im: make(map[string]reflect.Type), + imn: make(map[string]string), is: make(map[reflect.Type]struct{}), - ts: make(map[reflect.Type]struct{}), + tm: make(map[reflect.Type]struct{}), + ts: []reflect.Type{}, bp: typ[0].PkgPath(), - rr: rand.New(rand.NewSource(time.Now().UnixNano())), + xs: uid, + } + if x.xs == "" { + rr := rand.New(rand.NewSource(time.Now().UnixNano())) + x.xs = strconv.FormatInt(rr.Int63n(9999), 10) } // gather imports first: x.cp = reflect.TypeOf(x).PkgPath() + x.imn[x.cp] = genCodecPkg for _, t := range typ { // fmt.Printf("###########: PkgPath: '%v', Name: '%s'\n", t.PkgPath(), t.Name()) if t.PkgPath() != x.bp { @@ -163,7 +202,7 @@ func Gen(w io.Writer, buildTags, pkgName string, useUnsafe bool, typ ...reflect. x.linef("%s \"%s\"", genCodecPkg, x.cp) } for k, _ := range x.im { - x.line("\"" + k + "\"") + x.linef("%s \"%s\"", x.imn[k], k) } // add required packages for _, k := range [...]string{"reflect", "unsafe", "runtime", "fmt", "errors"} { @@ -177,8 +216,6 @@ func Gen(w io.Writer, buildTags, pkgName string, useUnsafe bool, typ ...reflect. x.line(")") x.line("") - x.xs = strconv.FormatInt(x.rr.Int63n(9999), 10) - x.line("const (") x.linef("codecSelferC_UTF8%s = %v", x.xs, int64(c_UTF8)) x.linef("codecSelferC_RAW%s = %v", x.xs, int64(c_RAW)) @@ -210,8 +247,8 @@ func Gen(w io.Writer, buildTags, pkgName string, useUnsafe bool, typ ...reflect. x.linef("}") x.line("if false { // reference the types, but skip this branch at build/run time") var n int - for _, t := range x.im { - x.linef("var v%v %s", n, t.String()) + for k, t := range x.im { + x.linef("var v%v %s.%s", n, x.imn[k], t.Name()) n++ } if x.unsafe { @@ -239,7 +276,7 @@ func Gen(w io.Writer, buildTags, pkgName string, useUnsafe bool, typ ...reflect. x.selfer(false) } - for t, _ := range x.ts { + for _, t := range x.ts { rtid := reflect.ValueOf(t).Pointer() // generate enc functions for all these slice/map types. x.linef("func (x %s) enc%s(v %s%s, e *%sEncoder) {", x.hn, x.genMethodNameT(t), x.arr2str(t, "*"), x.genTypeName(t), x.cpfx) @@ -273,6 +310,12 @@ func Gen(w io.Writer, buildTags, pkgName string, useUnsafe bool, typ ...reflect. x.line("") } +func (x *genRunner) checkForSelfer(t reflect.Type, varname string) bool { + // return varname != genTopLevelVarName && t != x.tc + // the only time we checkForSelfer is if we are not at the TOP of the generated code. + return varname != genTopLevelVarName +} + func (x *genRunner) arr2str(t reflect.Type, s string) string { if t.Kind() == reflect.Array { return s @@ -298,7 +341,15 @@ func (x *genRunner) genRefPkgs(t reflect.Type) { x.is[t] = struct{}{} tpkg, tname := t.PkgPath(), t.Name() if tpkg != "" && tpkg != x.bp && tpkg != x.cp && tname != "" && tname[0] >= 'A' && tname[0] <= 'Z' { - x.im[tpkg] = t + if _, ok := x.im[tpkg]; !ok { + x.im[tpkg] = t + if idx := strings.LastIndex(tpkg, "/"); idx < 0 { + x.imn[tpkg] = tpkg + } else { + x.imc++ + x.imn[tpkg] = "pkg" + strconv.FormatUint(x.imc, 10) + "_" + tpkg[idx+1:] + } + } } switch t.Kind() { case reflect.Array, reflect.Slice, reflect.Ptr, reflect.Chan: @@ -342,7 +393,65 @@ func (x *genRunner) outf(s string, params ...interface{}) { } func (x *genRunner) genTypeName(t reflect.Type) (n string) { - return genTypeName(t, x.tc) + // defer func() { fmt.Printf(">>>> ####: genTypeName: t: %v, name: '%s'\n", t, n) }() + + // if the type has a PkgPath, which doesn't match the current package, + // then include it. + // We cannot depend on t.String() because it includes current package, + // or t.PkgPath because it includes full import path, + // + var ptrPfx string + for t.Kind() == reflect.Ptr { + ptrPfx += "*" + t = t.Elem() + } + if tn := t.Name(); tn != "" { + return ptrPfx + x.genTypeNamePrim(t) + } + switch t.Kind() { + case reflect.Map: + return ptrPfx + "map[" + x.genTypeName(t.Key()) + "]" + x.genTypeName(t.Elem()) + case reflect.Slice: + return ptrPfx + "[]" + x.genTypeName(t.Elem()) + case reflect.Array: + return ptrPfx + "[" + strconv.FormatInt(int64(t.Len()), 10) + "]" + x.genTypeName(t.Elem()) + case reflect.Chan: + return ptrPfx + t.ChanDir().String() + " " + x.genTypeName(t.Elem()) + default: + if t == intfTyp { + return ptrPfx + "interface{}" + } else { + return ptrPfx + x.genTypeNamePrim(t) + } + } +} + +func (x *genRunner) genTypeNamePrim(t reflect.Type) (n string) { + if t.Name() == "" { + return t.String() + } else if t.PkgPath() == "" || t.PkgPath() == x.tc.PkgPath() { + return t.Name() + } else { + return x.imn[t.PkgPath()] + "." + t.Name() + // return t.String() // best way to get the package name inclusive + } +} + +func (x *genRunner) genZeroValueR(t reflect.Type) string { + // if t is a named type, w + switch t.Kind() { + case reflect.Ptr, reflect.Interface, reflect.Chan, reflect.Func, + reflect.Slice, reflect.Map, reflect.Invalid: + return "nil" + case reflect.Bool: + return "false" + case reflect.String: + return `""` + case reflect.Struct, reflect.Array: + return x.genTypeName(t) + "{}" + default: // all numbers + return "0" + } } func (x *genRunner) genMethodNameT(t reflect.Type) (s string) { @@ -368,16 +477,16 @@ func (x *genRunner) selfer(encode bool) { if encode { x.line(") CodecEncodeSelf(e *" + x.cpfx + "Encoder) {") x.genRequiredMethodVars(true) - // x.enc("x", t) - x.encVar("x", t) + // x.enc(genTopLevelVarName, t) + x.encVar(genTopLevelVarName, t) } else { x.line(") CodecDecodeSelf(d *" + x.cpfx + "Decoder) {") x.genRequiredMethodVars(false) // do not use decVar, as there is no need to check TryDecodeAsNil // or way to elegantly handle that, and also setting it to a // non-nil value doesn't affect the pointer passed. - // x.decVar("x", t, false) - x.dec("x", t0) + // x.decVar(genTopLevelVarName, t, false) + x.dec(genTopLevelVarName, t0) } x.line("}") x.line("") @@ -391,21 +500,21 @@ func (x *genRunner) selfer(encode bool) { x.out(fnSigPfx) x.line(") codecDecodeSelfFromMap(l int, d *" + x.cpfx + "Decoder) {") x.genRequiredMethodVars(false) - x.decStructMap("x", "l", reflect.ValueOf(t0).Pointer(), t0, 0) + x.decStructMap(genTopLevelVarName, "l", reflect.ValueOf(t0).Pointer(), t0, 0) x.line("}") x.line("") } else { x.out(fnSigPfx) x.line(") codecDecodeSelfFromMapLenPrefix(l int, d *" + x.cpfx + "Decoder) {") x.genRequiredMethodVars(false) - x.decStructMap("x", "l", reflect.ValueOf(t0).Pointer(), t0, 1) + x.decStructMap(genTopLevelVarName, "l", reflect.ValueOf(t0).Pointer(), t0, 1) x.line("}") x.line("") x.out(fnSigPfx) x.line(") codecDecodeSelfFromMapCheckBreak(l int, d *" + x.cpfx + "Decoder) {") x.genRequiredMethodVars(false) - x.decStructMap("x", "l", reflect.ValueOf(t0).Pointer(), t0, 2) + x.decStructMap(genTopLevelVarName, "l", reflect.ValueOf(t0).Pointer(), t0, 2) x.line("}") x.line("") } @@ -414,7 +523,7 @@ func (x *genRunner) selfer(encode bool) { x.out(fnSigPfx) x.line(") codecDecodeSelfFromArray(l int, d *" + x.cpfx + "Decoder) {") x.genRequiredMethodVars(false) - x.decStructArray("x", "l", "return", reflect.ValueOf(t0).Pointer(), t0) + x.decStructArray(genTopLevelVarName, "l", "return", reflect.ValueOf(t0).Pointer(), t0) x.line("}") x.line("") @@ -429,12 +538,16 @@ func (x *genRunner) xtraSM(varname string, encode bool, t reflect.Type) { x.linef("h.dec%s((*%s)(%s), d)", x.genMethodNameT(t), x.genTypeName(t), varname) // x.line("h.dec" + x.genMethodNameT(t) + "((*" + x.genTypeName(t) + ")(" + varname + "), d)") } - x.ts[t] = struct{}{} + if _, ok := x.tm[t]; !ok { + x.tm[t] = struct{}{} + x.ts = append(x.ts, t) + } } // encVar will encode a variable. // The parameter, t, is the reflect.Type of the variable itself func (x *genRunner) encVar(varname string, t reflect.Type) { + // fmt.Printf(">>>>>> varname: %s, t: %v\n", varname, t) var checkNil bool switch t.Kind() { case reflect.Ptr, reflect.Interface, reflect.Slice, reflect.Map, reflect.Chan: @@ -470,46 +583,86 @@ func (x *genRunner) encVar(varname string, t reflect.Type) { // enc will encode a variable (varname) of type T, // except t is of kind reflect.Struct or reflect.Array, wherein varname is of type *T (to prevent copying) func (x *genRunner) enc(varname string, t reflect.Type) { - // varName here must be to a pointer to a struct, or to a value directly. + // varName here must be to a pointer to a struct/array, or to a value directly. rtid := reflect.ValueOf(t).Pointer() // We call CodecEncodeSelf if one of the following are honored: // - the type already implements Selfer, call that // - the type has a Selfer implementation just created, use that // - the type is in the list of the ones we will generate for, but it is not currently being generated - if t.Implements(selferTyp) { - x.line(varname + ".CodecEncodeSelf(e)") - return - } - if t.Kind() == reflect.Struct && reflect.PtrTo(t).Implements(selferTyp) { - x.line(varname + ".CodecEncodeSelf(e)") - return - } - if _, ok := x.te[rtid]; ok { - x.line(varname + ".CodecEncodeSelf(e)") - return + + tptr := reflect.PtrTo(t) + tk := t.Kind() + if x.checkForSelfer(t, varname) { + if t.Implements(selferTyp) || (tptr.Implements(selferTyp) && (tk == reflect.Array || tk == reflect.Struct)) { + x.line(varname + ".CodecEncodeSelf(e)") + return + } + + if _, ok := x.te[rtid]; ok { + x.line(varname + ".CodecEncodeSelf(e)") + return + } } inlist := false for _, t0 := range x.t { if t == t0 { inlist = true - if t != x.tc { + if x.checkForSelfer(t, varname) { x.line(varname + ".CodecEncodeSelf(e)") return } break } } + var rtidAdded bool if t == x.tc { x.te[rtid] = true rtidAdded = true } + // check if + // - type is RawExt + // - the type implements (Text|JSON|Binary)(Unm|M)arshal + mi := x.varsfx() + x.linef("%sm%s := z.EncBinary()", genTempVarPfx, mi) + x.linef("_ = %sm%s", genTempVarPfx, mi) + x.line("if false {") //start if block + defer func() { x.line("}") }() //end if block + + if t == rawExtTyp { + x.linef("} else { r.EncodeRawExt(%v, e)", varname) + return + } + // HACK: Support for Builtins. + // Currently, only Binc supports builtins, and the only builtin type is time.Time. + // Have a method that returns the rtid for time.Time if Handle is Binc. + if t == timeTyp { + vrtid := genTempVarPfx + "m" + x.varsfx() + x.linef("} else if %s := z.TimeRtidIfBinc(); %s != 0 { ", vrtid, vrtid) + x.linef("r.EncodeBuiltin(%s, %s)", vrtid, varname) + } + // only check for extensions if the type is named, and has a packagePath. + if t.PkgPath() != "" && t.Name() != "" { + // first check if extensions are configued, before doing the interface conversion + x.linef("} else if z.HasExtensions() && z.EncExt(%s) {", varname) + } + if t.Implements(binaryMarshalerTyp) || tptr.Implements(binaryMarshalerTyp) { + x.linef("} else if %sm%s { z.EncBinaryMarshal(%v) ", genTempVarPfx, mi, varname) + } + if t.Implements(jsonMarshalerTyp) || tptr.Implements(jsonMarshalerTyp) { + x.linef("} else if !%sm%s && z.IsJSONHandle() { z.EncJSONMarshal(%v) ", genTempVarPfx, mi, varname) + } else if t.Implements(textMarshalerTyp) || tptr.Implements(textMarshalerTyp) { + x.linef("} else if !%sm%s { z.EncTextMarshal(%v) ", genTempVarPfx, mi, varname) + } + + x.line("} else {") + switch t.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: x.line("r.EncodeInt(int64(" + varname + "))") - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: x.line("r.EncodeUint(uint64(" + varname + "))") case reflect.Float32: x.line("r.EncodeFloat32(float32(" + varname + "))") @@ -575,7 +728,7 @@ func (x *genRunner) encZero(t reflect.Type) { switch t.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: x.line("r.EncodeInt(0)") - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: x.line("r.EncodeUint(0)") case reflect.Float32: x.line("r.EncodeFloat32(0)") @@ -598,21 +751,19 @@ func (x *genRunner) encStruct(varname string, rtid uintptr, t reflect.Type) { ti := getTypeInfo(rtid, t) i := x.varsfx() sepVarname := genTempVarPfx + "sep" + i - firstVarname := genTempVarPfx + "first" + i numfieldsvar := genTempVarPfx + "q" + i ti2arrayvar := genTempVarPfx + "r" + i struct2arrvar := genTempVarPfx + "2arr" + i x.line(sepVarname + " := !z.EncBinary()") x.linef("%s := z.EncBasicHandle().StructToArray", struct2arrvar) - x.line("var " + firstVarname + " bool") tisfi := ti.sfip // always use sequence from file. decStruct expects same thing. // due to omitEmpty, we need to calculate the // number of non-empty things we write out first. // This is required as we need to pre-determine the size of the container, // to support length-prefixing. x.linef("var %s [%v]bool", numfieldsvar, len(tisfi)) - x.linef("_, _, _, _ = %s, %s, %s, %s", sepVarname, firstVarname, numfieldsvar, struct2arrvar) + x.linef("_, _, _ = %s, %s, %s", sepVarname, numfieldsvar, struct2arrvar) x.linef("const %s bool = %v", ti2arrayvar, ti.toArray) nn := 0 for j, si := range tisfi { @@ -647,7 +798,7 @@ func (x *genRunner) encStruct(varname string, rtid uintptr, t reflect.Type) { case reflect.Map, reflect.Slice, reflect.Array, reflect.Chan: omitline += "len(" + varname + "." + t2.Name + ") != 0" default: - omitline += varname + "." + t2.Name + " != " + genZeroValueR(t2.Type, x.tc) + omitline += varname + "." + t2.Name + " != " + x.genZeroValueR(t2.Type) } x.linef("%s[%v] = %s", numfieldsvar, j, omitline) } @@ -697,11 +848,6 @@ func (x *genRunner) encStruct(varname string, rtid uintptr, t reflect.Type) { // if the type of the field is a Selfer, or one of the ones x.linef("if %s || %s {", ti2arrayvar, struct2arrvar) // if ti.toArray - if j > 0 { - x.line("if " + sepVarname + " {") - x.line("r.EncodeArrayEntrySeparator()") - x.line("}") - } if labelUsed { x.line("if " + isNilVarName + " { r.EncodeNil() } else { ") } @@ -733,17 +879,8 @@ func (x *genRunner) encStruct(varname string, rtid uintptr, t reflect.Type) { // } // x.line(varname + "." + t2.Name + " != " + genZeroValueR(t2.Type, x.tc) + " {") } - if j == 0 { - x.linef("%s = true", firstVarname) - } else { - x.linef("if %s { r.EncodeMapEntrySeparator() } else { %s = true }", firstVarname, firstVarname) - } - // x.line("r.EncodeString(codecSelferC_UTF8" + x.xs + ", string(\"" + t2.Name + "\"))") x.line("r.EncodeString(codecSelferC_UTF8" + x.xs + ", string(\"" + si.encName + "\"))") - x.line("if " + sepVarname + " {") - x.line("r.EncodeMapKVSeparator()") - x.line("}") if labelUsed { x.line("if " + isNilVarName + " { r.EncodeNil() } else { ") x.encVar(varname+"."+t2.Name, t2.Type) @@ -757,11 +894,7 @@ func (x *genRunner) encStruct(varname string, rtid uintptr, t reflect.Type) { x.linef("} ") // end if/else ti.toArray } x.line("if " + sepVarname + " {") - x.linef("if %s || %s {", ti2arrayvar, struct2arrvar) // if ti.toArray { - x.line("r.EncodeArrayEnd()") - x.linef("} else {") // if not ti.toArray - x.line("r.EncodeMapEnd()") - x.linef("} ") // end if/else ti.toArray + x.line("r.EncodeEnd()") x.line("}") } @@ -769,56 +902,27 @@ func (x *genRunner) encListFallback(varname string, t reflect.Type) { i := x.varsfx() g := genTempVarPfx x.line("r.EncodeArrayStart(len(" + varname + "))") - x.line(genTempVarPfx + "s" + i + " := !z.EncBinary()") - x.line("if " + genTempVarPfx + "s" + i + " {") if t.Kind() == reflect.Chan { x.linef("for %si%s, %si2%s := 0, len(%s); %si%s < %si2%s; %si%s++ {", g, i, g, i, varname, g, i, g, i, g, i) x.linef("%sv%s := <-%s", g, i, varname) } else { - x.linef("for %si%s, %sv%s := range %s {", genTempVarPfx, i, genTempVarPfx, i, varname) - } - x.linef("if %si%s > 0 { r.EncodeArrayEntrySeparator() }", genTempVarPfx, i) - x.encVar(genTempVarPfx+"v"+i, t.Elem()) - x.line("}") - x.line("r.EncodeArrayEnd()") - x.line("} else {") - if t.Kind() == reflect.Chan { - x.linef("for %si%s, %si2%s := 0, len(%s); %si%s < %si2%s; %si%s++ {", g, i, g, i, varname, g, i, g, i, g, i) - x.linef("%sv%s := <-%s", g, i, varname) - } else { - x.line("for _, " + genTempVarPfx + "v" + i + " := range " + varname + " {") + // x.linef("for %si%s, %sv%s := range %s {", genTempVarPfx, i, genTempVarPfx, i, varname) + x.linef("for _, %sv%s := range %s {", genTempVarPfx, i, varname) } x.encVar(genTempVarPfx+"v"+i, t.Elem()) x.line("}") - x.line("}") + x.line("r.EncodeEnd()") } func (x *genRunner) encMapFallback(varname string, t reflect.Type) { i := x.varsfx() x.line("r.EncodeMapStart(len(" + varname + "))") - x.line(genTempVarPfx + "s" + i + " := !z.EncBinary()") - - x.line(genTempVarPfx + "j" + i + " := 0") - - x.line("if " + genTempVarPfx + "s" + i + " {") - - x.line("for " + genTempVarPfx + "k" + i + ", " + - genTempVarPfx + "v" + i + " := range " + varname + " {") - x.line("if " + genTempVarPfx + "j" + i + " > 0 { r.EncodeMapEntrySeparator() }") - x.encVar(genTempVarPfx+"k"+i, t.Key()) - x.line("r.EncodeMapKVSeparator()") - x.encVar(genTempVarPfx+"v"+i, t.Elem()) - x.line(genTempVarPfx + "j" + i + "++") - x.line("}") - x.line("r.EncodeMapEnd()") - - x.line("} else {") x.linef("for %sk%s, %sv%s := range %s {", genTempVarPfx, i, genTempVarPfx, i, varname) + // x.line("for " + genTempVarPfx + "k" + i + ", " + genTempVarPfx + "v" + i + " := range " + varname + " {") x.encVar(genTempVarPfx+"k"+i, t.Key()) x.encVar(genTempVarPfx+"v"+i, t.Elem()) x.line("}") - - x.line("}") + x.line("r.EncodeEnd()") } func (x *genRunner) decVar(varname string, t reflect.Type, canBeNil bool) { @@ -844,7 +948,7 @@ func (x *genRunner) decVar(varname string, t reflect.Type, canBeNil bool) { if strings.IndexByte(varname, '.') != -1 { x.line(varname + " = nil") } else { - x.line("*" + varname + " = " + genZeroValueR(t.Elem(), x.tc)) + x.line("*" + varname + " = " + x.genZeroValueR(t.Elem())) } // x.line("*" + varname + " = nil") x.line("}") @@ -852,7 +956,7 @@ func (x *genRunner) decVar(varname string, t reflect.Type, canBeNil bool) { } else { // x.line("var " + genTempVarPfx + i + " " + x.genTypeName(t)) // x.line(varname + " = " + genTempVarPfx + i) - x.line(varname + " = " + genZeroValueR(t, x.tc)) + x.line(varname + " = " + x.genZeroValueR(t)) } x.line("} else {") } else { @@ -897,35 +1001,77 @@ func (x *genRunner) decVar(varname string, t reflect.Type, canBeNil bool) { func (x *genRunner) dec(varname string, t reflect.Type) { // assumptions: // - the varname is to a pointer already. No need to take address of it - + // - t is always a baseType T (not a *T, etc). rtid := reflect.ValueOf(t).Pointer() - if t.Implements(selferTyp) || (t.Kind() == reflect.Struct && - reflect.PtrTo(t).Implements(selferTyp)) { - x.line(varname + ".CodecDecodeSelf(d)") - return - } - if _, ok := x.td[rtid]; ok { - x.line(varname + ".CodecDecodeSelf(d)") - return + tptr := reflect.PtrTo(t) + if x.checkForSelfer(t, varname) { + if t.Implements(selferTyp) || tptr.Implements(selferTyp) { + x.line(varname + ".CodecDecodeSelf(d)") + return + } + if _, ok := x.td[rtid]; ok { + x.line(varname + ".CodecDecodeSelf(d)") + return + } } inlist := false for _, t0 := range x.t { if t == t0 { inlist = true - if t != x.tc { + if x.checkForSelfer(t, varname) { x.line(varname + ".CodecDecodeSelf(d)") return } break } } + var rtidAdded bool if t == x.tc { x.td[rtid] = true rtidAdded = true } + // check if + // - type is RawExt + // - the type implements (Text|JSON|Binary)(Unm|M)arshal + mi := x.varsfx() + x.linef("%sm%s := z.DecBinary()", genTempVarPfx, mi) + x.linef("_ = %sm%s", genTempVarPfx, mi) + x.line("if false {") //start if block + defer func() { x.line("}") }() //end if block + + if t == rawExtTyp { + x.linef("} else { r.DecodeExt(%v, 0, nil)", varname) + return + } + + // HACK: Support for Builtins. + // Currently, only Binc supports builtins, and the only builtin type is time.Time. + // Have a method that returns the rtid for time.Time if Handle is Binc. + if t == timeTyp { + vrtid := genTempVarPfx + "m" + x.varsfx() + x.linef("} else if %s := z.TimeRtidIfBinc(); %s != 0 { ", vrtid, vrtid) + x.linef("r.DecodeBuiltin(%s, %s)", vrtid, varname) + } + // only check for extensions if the type is named, and has a packagePath. + if t.PkgPath() != "" && t.Name() != "" { + // first check if extensions are configued, before doing the interface conversion + x.linef("} else if z.HasExtensions() && z.DecExt(%s) {", varname) + } + + if t.Implements(binaryUnmarshalerTyp) || tptr.Implements(binaryUnmarshalerTyp) { + x.linef("} else if %sm%s { z.DecBinaryUnmarshal(%v) ", genTempVarPfx, mi, varname) + } + if t.Implements(jsonUnmarshalerTyp) || tptr.Implements(jsonUnmarshalerTyp) { + x.linef("} else if !%sm%s && z.IsJSONHandle() { z.DecJSONUnmarshal(%v)", genTempVarPfx, mi, varname) + } else if t.Implements(textUnmarshalerTyp) || tptr.Implements(textUnmarshalerTyp) { + x.linef("} else if !%sm%s { z.DecTextUnmarshal(%v)", genTempVarPfx, mi, varname) + } + + x.line("} else {") + // Since these are pointers, we cannot share, and have to use them one by one switch t.Kind() { case reflect.Int: @@ -959,6 +1105,8 @@ func (x *genRunner) dec(varname string, t reflect.Type) { case reflect.Uint64: x.line("*((*uint64)(" + varname + ")) = uint64(r.DecodeUint(64))") //x.line("z.DecUint64((*uint64)(" + varname + "))") + case reflect.Uintptr: + x.line("*((*uintptr)(" + varname + ")) = uintptr(r.DecodeUint(codecSelferBitsize" + x.xs + "))") case reflect.Float32: x.line("*((*float32)(" + varname + ")) = float32(r.DecodeFloat(true))") @@ -1037,10 +1185,10 @@ func (x *genRunner) decTryAssignPrimitive(varname string, t reflect.Type) (tryAs // Consequently, we replace: // case reflect.Uint32: x.line(varname + " = uint32(r.DecodeUint(32))") // with: - // case reflect.Uint32: x.line(varname + " = " + genTypeNamePrimitiveKind(t, x.tc) + "(r.DecodeUint(32))") + // case reflect.Uint32: x.line(varname + " = " + genTypeNamePrim(t, x.tc) + "(r.DecodeUint(32))") xfn := func(t reflect.Type) string { - return genTypeNamePrimitiveKind(t, x.tc) + return x.genTypeNamePrim(t) } switch t.Kind() { case reflect.Int: @@ -1064,6 +1212,8 @@ func (x *genRunner) decTryAssignPrimitive(varname string, t reflect.Type) (tryAs x.linef("%s = %s(r.DecodeUint(32))", varname, xfn(t)) case reflect.Uint64: x.linef("%s = %s(r.DecodeUint(64))", varname, xfn(t)) + case reflect.Uintptr: + x.linef("%s = %s(r.DecodeUint(codecSelferBitsize%s))", varname, xfn(t), x.xs) case reflect.Float32: x.linef("%s = %s(r.DecodeFloat(true))", varname, xfn(t)) @@ -1105,7 +1255,7 @@ func (x *genRunner) decListFallback(varname string, rtid uintptr, t reflect.Type return ts.TempVar + s + ts.Rand } funcs["zero"] = func() string { - return genZeroValueR(telem, x.tc) + return x.genZeroValueR(telem) } funcs["isArray"] = func() bool { return t.Kind() == reflect.Array @@ -1232,13 +1382,11 @@ func (x *genRunner) decStructMap(varname, lenvarname string, rtid uintptr, t ref x.linef("for %sj%s := 0; %sj%s < %s; %sj%s++ {", tpfx, i, tpfx, i, lenvarname, tpfx, i) case 2: x.linef("for %sj%s := 0; !r.CheckBreak(); %sj%s++ {", tpfx, i, tpfx, i) - x.linef("if %sj%s > 0 { r.ReadMapEntrySeparator() }", tpfx, i) default: // 0, otherwise. x.linef("var %shl%s bool = %s >= 0", tpfx, i, lenvarname) // has length x.linef("for %sj%s := 0; ; %sj%s++ {", tpfx, i, tpfx, i) x.linef("if %shl%s { if %sj%s >= %s { break }", tpfx, i, tpfx, i, lenvarname) - x.linef("} else { if r.CheckBreak() { break }; if %sj%s > 0 { r.ReadMapEntrySeparator() } }", - tpfx, i) + x.line("} else { if r.CheckBreak() { break }; }") } // x.line(kName + " = z.ReadStringAsBytes(" + kName + ")") // x.line(kName + " = z.ReadString()") @@ -1252,22 +1400,15 @@ func (x *genRunner) decStructMap(varname, lenvarname string, rtid uintptr, t ref } else { x.line(kName + " := string(" + kName + "Slc)") } - switch style { - case 1: - case 2: - x.line("r.ReadMapKVSeparator()") - default: - x.linef("if !%shl%s { r.ReadMapKVSeparator() }", tpfx, i) - } x.decStructMapSwitch(kName, varname, rtid, t) x.line("} // end for " + tpfx + "j" + i) switch style { case 1: case 2: - x.line("r.ReadMapEnd()") + x.line("r.ReadEnd()") default: - x.linef("if !%shl%s { r.ReadMapEnd() }", tpfx, i) + x.linef("if !%shl%s { r.ReadEnd() }", tpfx, i) } } @@ -1280,7 +1421,7 @@ func (x *genRunner) decStructArray(varname, lenvarname, breakString string, rtid x.linef("var %sb%s bool", tpfx, i) // break // x.linef("var %sl%s := r.ReadArrayStart()", tpfx, i) x.linef("var %shl%s bool = %s >= 0", tpfx, i, lenvarname) // has length - for j, si := range tisfi { + for _, si := range tisfi { var t2 reflect.StructField if si.i != -1 { t2 = t.Field(int(si.i)) @@ -1293,10 +1434,7 @@ func (x *genRunner) decStructArray(varname, lenvarname, breakString string, rtid tpfx, i, lenvarname, tpfx, i) // x.line("if " + tpfx + "j" + i + "++; " + tpfx + "j" + // i + " <= " + tpfx + "l" + i + " {") - x.linef("if %sb%s { r.ReadArrayEnd(); %s }", tpfx, i, breakString) - if j > 0 { - x.line("r.ReadArrayEntrySeparator()") - } + x.linef("if %sb%s { r.ReadEnd(); %s }", tpfx, i, breakString) x.decVar(varname+"."+t2.Name, t2.Type, true) // x.line("} // end if " + tpfx + "j" + i + " <= " + tpfx + "l" + i) } @@ -1306,10 +1444,9 @@ func (x *genRunner) decStructArray(varname, lenvarname, breakString string, rtid tpfx, i, tpfx, i, tpfx, i, tpfx, i, lenvarname, tpfx, i) x.linef("if %sb%s { break }", tpfx, i) - x.linef("if %sj%s > 1 { r.ReadArrayEntrySeparator() }", tpfx, i) x.linef(`z.DecStructFieldNotFound(%sj%s - 1, "")`, tpfx, i) x.line("}") - x.line("r.ReadArrayEnd()") + x.line("r.ReadEnd()") } func (x *genRunner) decStruct(varname string, rtid uintptr, t reflect.Type) { @@ -1319,7 +1456,7 @@ func (x *genRunner) decStruct(varname string, rtid uintptr, t reflect.Type) { x.line("if r.IsContainerType(codecSelverValueTypeMap" + x.xs + ") {") x.line(genTempVarPfx + "l" + i + " := r.ReadMapStart()") x.linef("if %sl%s == 0 {", genTempVarPfx, i) - x.line("r.ReadMapEnd()") + x.line("r.ReadEnd()") if genUseOneFunctionForDecStructMap { x.line("} else { ") x.linef("x.codecDecodeSelfFromMap(%sl%s, d)", genTempVarPfx, i) @@ -1336,7 +1473,7 @@ func (x *genRunner) decStruct(varname string, rtid uintptr, t reflect.Type) { x.line("} else if r.IsContainerType(codecSelverValueTypeArray" + x.xs + ") {") x.line(genTempVarPfx + "l" + i + " := r.ReadArrayStart()") x.linef("if %sl%s == 0 {", genTempVarPfx, i) - x.line("r.ReadArrayEnd()") + x.line("r.ReadEnd()") x.line("} else { ") x.linef("x.codecDecodeSelfFromArray(%sl%s, d)", genTempVarPfx, i) x.line("}") @@ -1393,59 +1530,17 @@ func genTitleCaseName(s string) string { } } -func genTypeNamePrimitiveKind(t reflect.Type, tRef reflect.Type) (n string) { - if tRef != nil && t.PkgPath() == tRef.PkgPath() && t.Name() != "" { - return t.Name() - } else { - return t.String() // best way to get the package name inclusive - } -} - -func genTypeName(t reflect.Type, tRef reflect.Type) (n string) { - // defer func() { fmt.Printf(">>>> ####: genTypeName: t: %v, name: '%s'\n", t, n) }() - - // if the type has a PkgPath, which doesn't match the current package, - // then include it. - // We cannot depend on t.String() because it includes current package, - // or t.PkgPath because it includes full import path, - // - var ptrPfx string - for t.Kind() == reflect.Ptr { - ptrPfx += "*" - t = t.Elem() - } - if tn := t.Name(); tn != "" { - return ptrPfx + genTypeNamePrimitiveKind(t, tRef) - } - switch t.Kind() { - case reflect.Map: - return ptrPfx + "map[" + genTypeName(t.Key(), tRef) + "]" + genTypeName(t.Elem(), tRef) - case reflect.Slice: - return ptrPfx + "[]" + genTypeName(t.Elem(), tRef) - case reflect.Array: - return ptrPfx + "[" + strconv.FormatInt(int64(t.Len()), 10) + "]" + genTypeName(t.Elem(), tRef) - case reflect.Chan: - return ptrPfx + t.ChanDir().String() + " " + genTypeName(t.Elem(), tRef) - default: - if t == intfTyp { - return ptrPfx + "interface{}" - } else { - return ptrPfx + genTypeNamePrimitiveKind(t, tRef) - } - } -} - func genMethodNameT(t reflect.Type, tRef reflect.Type) (n string) { var ptrPfx string for t.Kind() == reflect.Ptr { ptrPfx += "Ptrto" t = t.Elem() } + tstr := t.String() if tn := t.Name(); tn != "" { if tRef != nil && t.PkgPath() == tRef.PkgPath() { return ptrPfx + tn } else { - tstr := t.String() if genQNameRegex.MatchString(tstr) { return ptrPfx + strings.Replace(tstr, ".", "_", 1000) } else { @@ -1479,13 +1574,12 @@ func genMethodNameT(t reflect.Type, tRef reflect.Type) (n string) { if t.Name() != "" { return ptrPfx + t.Name() } else { - return ptrPfx + genCustomTypeName(t.String()) + return ptrPfx + genCustomTypeName(tstr) } } else { // best way to get the package name inclusive - // return ptrPfx + strings.Replace(t.String(), ".", "_", 1000) - // return ptrPfx + genBase64enc.EncodeToString([]byte(t.String())) - tstr := t.String() + // return ptrPfx + strings.Replace(tstr, ".", "_", 1000) + // return ptrPfx + genBase64enc.EncodeToString([]byte(tstr)) if t.Name() != "" && genQNameRegex.MatchString(tstr) { return ptrPfx + strings.Replace(tstr, ".", "_", 1000) } else { @@ -1516,23 +1610,6 @@ func genIsImmutable(t reflect.Type) (v bool) { return isMutableKind(t.Kind()) } -func genZeroValueR(t reflect.Type, tRef reflect.Type) string { - // if t is a named type, w - switch t.Kind() { - case reflect.Ptr, reflect.Interface, reflect.Chan, reflect.Func, - reflect.Slice, reflect.Map, reflect.Invalid: - return "nil" - case reflect.Bool: - return "false" - case reflect.String: - return `""` - case reflect.Struct, reflect.Array: - return genTypeName(t, tRef) + "{}" - default: // all numbers - return "0" - } -} - type genInternal struct { Values []genV Unsafe bool diff --git a/Godeps/_workspace/src/github.com/ugorji/go/codec/helper.go b/Godeps/_workspace/src/github.com/ugorji/go/codec/helper.go index 7848ea135..8b76e8e48 100644 --- a/Godeps/_workspace/src/github.com/ugorji/go/codec/helper.go +++ b/Godeps/_workspace/src/github.com/ugorji/go/codec/helper.go @@ -186,6 +186,14 @@ const ( type seqType uint8 +// mirror json.Marshaler and json.Unmarshaler here, so we don't import the encoding/json package +type jsonMarshaler interface { + MarshalJSON() ([]byte, error) +} +type jsonUnmarshaler interface { + UnmarshalJSON([]byte) error +} + const ( _ seqType = iota seqTypeArray @@ -217,6 +225,9 @@ var ( textMarshalerTyp = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem() textUnmarshalerTyp = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem() + jsonMarshalerTyp = reflect.TypeOf((*jsonMarshaler)(nil)).Elem() + jsonUnmarshalerTyp = reflect.TypeOf((*jsonUnmarshaler)(nil)).Elem() + selferTyp = reflect.TypeOf((*Selfer)(nil)).Elem() uint8SliceTypId = reflect.ValueOf(uint8SliceTyp).Pointer() @@ -471,6 +482,10 @@ type structFieldInfo struct { toArray bool // if field is _struct, is the toArray set? } +// func (si *structFieldInfo) isZero() bool { +// return si.encName == "" && len(si.is) == 0 && si.i == 0 && !si.omitEmpty && !si.toArray +// } + // rv returns the field of the struct. // If anonymous, it returns an Invalid func (si *structFieldInfo) field(v reflect.Value, update bool) (rv2 reflect.Value) { @@ -516,9 +531,9 @@ func (si *structFieldInfo) setToZeroValue(v reflect.Value) { } func parseStructFieldInfo(fname string, stag string) *structFieldInfo { - if fname == "" { - panic(noFieldNameToStructFieldInfoErr) - } + // if fname == "" { + // panic(noFieldNameToStructFieldInfoErr) + // } si := structFieldInfo{ encName: fname, } @@ -589,6 +604,11 @@ type typeInfo struct { tmIndir int8 // number of indirections to get to textMarshaler type tunmIndir int8 // number of indirections to get to textUnmarshaler type + jm bool // base type (T or *T) is a jsonMarshaler + junm bool // base type (T or *T) is a jsonUnmarshaler + jmIndir int8 // number of indirections to get to jsonMarshaler type + junmIndir int8 // number of indirections to get to jsonUnmarshaler type + cs bool // base type (T or *T) is a Selfer csIndir int8 // number of indirections to get to Selfer type @@ -664,6 +684,12 @@ func getTypeInfo(rtid uintptr, rt reflect.Type) (pti *typeInfo) { if ok, indir = implementsIntf(rt, textUnmarshalerTyp); ok { ti.tunm, ti.tunmIndir = true, indir } + if ok, indir = implementsIntf(rt, jsonMarshalerTyp); ok { + ti.jm, ti.jmIndir = true, indir + } + if ok, indir = implementsIntf(rt, jsonUnmarshalerTyp); ok { + ti.junm, ti.junmIndir = true, indir + } if ok, indir = implementsIntf(rt, selferTyp); ok { ti.cs, ti.csIndir = true, indir } @@ -723,8 +749,21 @@ func rgetTypeInfo(rt reflect.Type, indexstack []int, fnameToHastag map[string]bo if r1, _ := utf8.DecodeRuneInString(f.Name); r1 == utf8.RuneError || !unicode.IsUpper(r1) { continue } - // if anonymous and there is no struct tag and its a struct (or pointer to struct), inline it. - if f.Anonymous && stag == "" { + var si *structFieldInfo + // if anonymous and there is no struct tag (or it's blank) + // and its a struct (or pointer to struct), inline it. + var doInline bool + if f.Anonymous && f.Type.Kind() != reflect.Interface { + doInline = stag == "" + if !doInline { + si = parseStructFieldInfo("", stag) + doInline = si.encName == "" + // doInline = si.isZero() + // fmt.Printf(">>>> doInline for si.isZero: %s: %v\n", f.Name, doInline) + } + } + + if doInline { ft := f.Type for ft.Kind() == reflect.Ptr { ft = ft.Elem() @@ -744,7 +783,14 @@ func rgetTypeInfo(rt reflect.Type, indexstack []int, fnameToHastag map[string]bo if _, ok := fnameToHastag[f.Name]; ok { continue } - si := parseStructFieldInfo(f.Name, stag) + if f.Name == "" { + panic(noFieldNameToStructFieldInfoErr) + } + if si == nil { + si = parseStructFieldInfo(f.Name, stag) + } else if si.encName == "" { + si.encName = f.Name + } // si.ikind = int(f.Type.Kind()) if len(indexstack) == 0 { si.i = int16(j) @@ -780,7 +826,8 @@ func panicToErr(err *error) { // } func isMutableKind(k reflect.Kind) (v bool) { - return k == reflect.Int || + return false || + k == reflect.Int || k == reflect.Int8 || k == reflect.Int16 || k == reflect.Int32 || @@ -790,6 +837,7 @@ func isMutableKind(k reflect.Kind) (v bool) { k == reflect.Uint16 || k == reflect.Uint32 || k == reflect.Uint64 || + k == reflect.Uintptr || k == reflect.Float32 || k == reflect.Float64 || k == reflect.Bool || diff --git a/Godeps/_workspace/src/github.com/ugorji/go/codec/helper_test.go b/Godeps/_workspace/src/github.com/ugorji/go/codec/helper_test.go deleted file mode 100644 index 685c576c4..000000000 --- a/Godeps/_workspace/src/github.com/ugorji/go/codec/helper_test.go +++ /dev/null @@ -1,155 +0,0 @@ -// Copyright (c) 2012-2015 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -package codec - -// All non-std package dependencies related to testing live in this file, -// so porting to different environment is easy (just update functions). -// -// This file sets up the variables used, including testInitFns. -// Each file should add initialization that should be performed -// after flags are parsed. -// -// init is a multi-step process: -// - setup vars (handled by init functions in each file) -// - parse flags -// - setup derived vars (handled by pre-init registered functions - registered in init function) -// - post init (handled by post-init registered functions - registered in init function) -// This way, no one has to manage carefully control the initialization -// using file names, etc. -// -// Tests which require external dependencies need the -tag=x parameter. -// They should be run as: -// go test -tags=x -run=. -// Benchmarks should also take this parameter, to include the sereal, xdr, etc. -// To run against codecgen, etc, make sure you pass extra parameters. -// Example usage: -// go test "-tags=x codecgen unsafe" -bench=. -// -// To fully test everything: -// go test -tags=x -benchtime=100ms -tv -bg -bi -brw -bu -v -run=. -bench=. - -import ( - "errors" - "flag" - "fmt" - "reflect" - "sync" - "testing" -) - -const ( - testLogToT = true - failNowOnFail = true -) - -var ( - testNoopH = NoopHandle(8) - testMsgpackH = &MsgpackHandle{} - testBincH = &BincHandle{} - testBincHNoSym = &BincHandle{} - testBincHSym = &BincHandle{} - testSimpleH = &SimpleHandle{} - testCborH = &CborHandle{} - testJsonH = &JsonHandle{} - - testPreInitFns []func() - testPostInitFns []func() - - testOnce sync.Once -) - -func init() { - testBincHSym.AsSymbols = AsSymbolAll - testBincHNoSym.AsSymbols = AsSymbolNone -} - -func testInitAll() { - flag.Parse() - for _, f := range testPreInitFns { - f() - } - for _, f := range testPostInitFns { - f() - } -} - -func logT(x interface{}, format string, args ...interface{}) { - if t, ok := x.(*testing.T); ok && t != nil && testLogToT { - if testVerbose { - t.Logf(format, args...) - } - } else if b, ok := x.(*testing.B); ok && b != nil && testLogToT { - b.Logf(format, args...) - } else { - if len(format) == 0 || format[len(format)-1] != '\n' { - format = format + "\n" - } - fmt.Printf(format, args...) - } -} - -func approxDataSize(rv reflect.Value) (sum int) { - switch rk := rv.Kind(); rk { - case reflect.Invalid: - case reflect.Ptr, reflect.Interface: - sum += int(rv.Type().Size()) - sum += approxDataSize(rv.Elem()) - case reflect.Slice: - sum += int(rv.Type().Size()) - for j := 0; j < rv.Len(); j++ { - sum += approxDataSize(rv.Index(j)) - } - case reflect.String: - sum += int(rv.Type().Size()) - sum += rv.Len() - case reflect.Map: - sum += int(rv.Type().Size()) - for _, mk := range rv.MapKeys() { - sum += approxDataSize(mk) - sum += approxDataSize(rv.MapIndex(mk)) - } - case reflect.Struct: - //struct size already includes the full data size. - //sum += int(rv.Type().Size()) - for j := 0; j < rv.NumField(); j++ { - sum += approxDataSize(rv.Field(j)) - } - default: - //pure value types - sum += int(rv.Type().Size()) - } - return -} - -// ----- functions below are used only by tests (not benchmarks) - -func checkErrT(t *testing.T, err error) { - if err != nil { - logT(t, err.Error()) - failT(t) - } -} - -func checkEqualT(t *testing.T, v1 interface{}, v2 interface{}, desc string) (err error) { - if err = deepEqual(v1, v2); err != nil { - logT(t, "Not Equal: %s: %v. v1: %v, v2: %v", desc, err, v1, v2) - failT(t) - } - return -} - -func failT(t *testing.T) { - if failNowOnFail { - t.FailNow() - } else { - t.Fail() - } -} - -func deepEqual(v1, v2 interface{}) (err error) { - if !reflect.DeepEqual(v1, v2) { - err = errors.New("Not Match") - } - return -} diff --git a/Godeps/_workspace/src/github.com/ugorji/go/codec/json.go b/Godeps/_workspace/src/github.com/ugorji/go/codec/json.go index cb370d48e..f2f7bceb8 100644 --- a/Godeps/_workspace/src/github.com/ugorji/go/codec/json.go +++ b/Godeps/_workspace/src/github.com/ugorji/go/codec/json.go @@ -27,6 +27,11 @@ package codec // - encode does not beautify. There is no whitespace when encoding. // - rpc calls which take single integer arguments or write single numeric arguments will need care. +// Top-level methods of json(End|Dec)Driver (which are implementations of (en|de)cDriver +// MUST not call one-another. +// They all must call sep(), and sep() MUST NOT be called more than once for each read. +// If sep() is called and read is not done, you MUST call retryRead so separator wouldn't be read/written twice. + import ( "bytes" "encoding/base64" @@ -81,20 +86,102 @@ const ( // jsonNumDigitsUint64Largest = 19 ) +// A stack is used to keep track of where we are in the tree. +// This is necessary, as the Handle must know whether to consume or emit a separator. + +type jsonStackElem struct { + st byte // top of stack (either '}' or ']' or 0 for map, array or neither). + sf bool // NOT first time in that container at top of stack + so bool // stack ctr odd + sr bool // value has NOT been read, so do not re-send separator +} + +func (x *jsonStackElem) retryRead() { + if x != nil && !x.sr { + x.sr = true + } +} + +func (x *jsonStackElem) sep() (c byte) { + // do not use switch, so it's a candidate for inlining. + // to inline effectively, this must not be called from within another method. + // v := j.st + if x == nil || x.st == 0 { + return + } + if x.sr { + x.sr = false + return + } + // v == '}' OR ']' + if x.st == '}' { + // put , or : depending on if even or odd respectively + if x.so { + c = ':' + if !x.sf { + x.sf = true + } + } else if x.sf { + c = ',' + } + } else { + if x.sf { + c = ',' + } else { + x.sf = true + } + } + x.so = !x.so + if x.sr { + x.sr = false + } + return +} + +// jsonStack contains the stack for tracking the state of the container (branch). +// The same data structure is used during encode and decode, as it is similar functionality. +type jsonStack struct { + s []jsonStackElem // stack for map or array end tag. map=}, array=] + sc *jsonStackElem // pointer to current (top) element on the stack. +} + +func (j *jsonStack) start(c byte) { + j.s = append(j.s, jsonStackElem{st: c}) + j.sc = &(j.s[len(j.s)-1]) +} + +func (j *jsonStack) end() { + l := len(j.s) - 1 // length of new stack after pop'ing + j.s = j.s[:l] + if l == 0 { + j.sc = nil + } else { + j.sc = &(j.s[l-1]) + } + //j.sc = &(j.s[len(j.s)-1]) +} + type jsonEncDriver struct { e *Encoder w encWriter h *JsonHandle b [64]byte // scratch bs []byte // scratch + s jsonStack noBuiltInTypes } func (e *jsonEncDriver) EncodeNil() { + if c := e.s.sc.sep(); c != 0 { + e.w.writen1(c) + } e.w.writeb(jsonLiterals[9:13]) // null } func (e *jsonEncDriver) EncodeBool(b bool) { + if c := e.s.sc.sep(); c != 0 { + e.w.writen1(c) + } if b { e.w.writeb(jsonLiterals[0:4]) // true } else { @@ -103,78 +190,101 @@ func (e *jsonEncDriver) EncodeBool(b bool) { } func (e *jsonEncDriver) EncodeFloat32(f float32) { + if c := e.s.sc.sep(); c != 0 { + e.w.writen1(c) + } e.w.writeb(strconv.AppendFloat(e.b[:0], float64(f), 'E', -1, 32)) } func (e *jsonEncDriver) EncodeFloat64(f float64) { + if c := e.s.sc.sep(); c != 0 { + e.w.writen1(c) + } // e.w.writestr(strconv.FormatFloat(f, 'E', -1, 64)) e.w.writeb(strconv.AppendFloat(e.b[:0], f, 'E', -1, 64)) } func (e *jsonEncDriver) EncodeInt(v int64) { + if c := e.s.sc.sep(); c != 0 { + e.w.writen1(c) + } e.w.writeb(strconv.AppendInt(e.b[:0], v, 10)) } func (e *jsonEncDriver) EncodeUint(v uint64) { + if c := e.s.sc.sep(); c != 0 { + e.w.writen1(c) + } e.w.writeb(strconv.AppendUint(e.b[:0], v, 10)) } func (e *jsonEncDriver) EncodeExt(rv interface{}, xtag uint64, ext Ext, en *Encoder) { + if c := e.s.sc.sep(); c != 0 { + e.w.writen1(c) + } if v := ext.ConvertExt(rv); v == nil { - e.EncodeNil() + e.w.writeb(jsonLiterals[9:13]) // null // e.EncodeNil() } else { + e.s.sc.retryRead() en.encode(v) } } func (e *jsonEncDriver) EncodeRawExt(re *RawExt, en *Encoder) { + if c := e.s.sc.sep(); c != 0 { + e.w.writen1(c) + } // only encodes re.Value (never re.Data) if re.Value == nil { - e.EncodeNil() + e.w.writeb(jsonLiterals[9:13]) // null // e.EncodeNil() } else { + e.s.sc.retryRead() en.encode(re.Value) } } func (e *jsonEncDriver) EncodeArrayStart(length int) { + if c := e.s.sc.sep(); c != 0 { + e.w.writen1(c) + } + e.s.start(']') e.w.writen1('[') } -func (e *jsonEncDriver) EncodeArrayEntrySeparator() { - e.w.writen1(',') -} - -func (e *jsonEncDriver) EncodeArrayEnd() { - e.w.writen1(']') -} - func (e *jsonEncDriver) EncodeMapStart(length int) { + if c := e.s.sc.sep(); c != 0 { + e.w.writen1(c) + } + e.s.start('}') e.w.writen1('{') } -func (e *jsonEncDriver) EncodeMapEntrySeparator() { - e.w.writen1(',') -} - -func (e *jsonEncDriver) EncodeMapKVSeparator() { - e.w.writen1(':') -} - -func (e *jsonEncDriver) EncodeMapEnd() { - e.w.writen1('}') +func (e *jsonEncDriver) EncodeEnd() { + b := e.s.sc.st + e.s.end() + e.w.writen1(b) } func (e *jsonEncDriver) EncodeString(c charEncoding, v string) { // e.w.writestr(strconv.Quote(v)) + if c := e.s.sc.sep(); c != 0 { + e.w.writen1(c) + } e.quoteStr(v) } func (e *jsonEncDriver) EncodeSymbol(v string) { // e.EncodeString(c_UTF8, v) + if c := e.s.sc.sep(); c != 0 { + e.w.writen1(c) + } e.quoteStr(v) } func (e *jsonEncDriver) EncodeStringBytes(c charEncoding, v []byte) { + if c := e.s.sc.sep(); c != 0 { + e.w.writen1(c) + } if c == c_RAW { slen := base64.StdEncoding.EncodedLen(len(v)) if e.bs == nil { @@ -195,6 +305,13 @@ func (e *jsonEncDriver) EncodeStringBytes(c charEncoding, v []byte) { } } +func (e *jsonEncDriver) EncodeAsis(v []byte) { + if c := e.s.sc.sep(); c != 0 { + e.w.writen1(c) + } + e.w.writeb(v) +} + func (e *jsonEncDriver) quoteStr(s string) { // adapted from std pkg encoding/json const hex = "0123456789abcdef" @@ -359,6 +476,8 @@ type jsonDecDriver struct { wsSkipped bool // whitespace skipped + s jsonStack + n jsonNum noBuiltInTypes } @@ -402,16 +521,27 @@ func (d *jsonDecDriver) readStrIdx(fromIdx, toIdx uint8) { } func (d *jsonDecDriver) TryDecodeAsNil() bool { - b := d.skipWhitespace(true) + // we mustn't consume the state here, and end up trying to read separator twice. + // Instead, we keep track of the state and restore it if we couldn't decode as nil. + + if c := d.s.sc.sep(); c != 0 { + d.expectChar(c) + } + b := d.skipWhitespace(false) if b == 'n' { - d.readStrIdx(9, 13) // null + d.readStrIdx(10, 13) // ull d.ct = valueTypeNil return true } + d.r.unreadn1() + d.s.sc.retryRead() return false } func (d *jsonDecDriver) DecodeBool() bool { + if c := d.s.sc.sep(); c != 0 { + d.expectChar(c) + } b := d.skipWhitespace(false) if b == 'f' { d.readStrIdx(5, 9) // alse @@ -426,35 +556,35 @@ func (d *jsonDecDriver) DecodeBool() bool { } func (d *jsonDecDriver) ReadMapStart() int { + if c := d.s.sc.sep(); c != 0 { + d.expectChar(c) + } + d.s.start('}') d.expectChar('{') d.ct = valueTypeMap return -1 } func (d *jsonDecDriver) ReadArrayStart() int { + if c := d.s.sc.sep(); c != 0 { + d.expectChar(c) + } + d.s.start(']') d.expectChar('[') d.ct = valueTypeArray return -1 } -func (d *jsonDecDriver) ReadMapEnd() { - d.expectChar('}') -} -func (d *jsonDecDriver) ReadArrayEnd() { - d.expectChar(']') -} -func (d *jsonDecDriver) ReadArrayEntrySeparator() { - d.expectChar(',') -} -func (d *jsonDecDriver) ReadMapEntrySeparator() { - d.expectChar(',') -} -func (d *jsonDecDriver) ReadMapKVSeparator() { - d.expectChar(':') + +func (d *jsonDecDriver) ReadEnd() { + b := d.s.sc.st + d.s.end() + d.expectChar(b) } + func (d *jsonDecDriver) expectChar(c uint8) { b := d.skipWhitespace(false) if b != c { - d.d.errorf("json: expect char %c but got char %c", c, b) + d.d.errorf("json: expect char '%c' but got char '%c'", c, b) return } if jsonTrackSkipWhitespace { @@ -462,6 +592,17 @@ func (d *jsonDecDriver) expectChar(c uint8) { } } +// func (d *jsonDecDriver) maybeChar(c uint8) { +// b := d.skipWhitespace(false) +// if b != c { +// d.r.unreadn1() +// return +// } +// if jsonTrackSkipWhitespace { +// d.wsSkipped = false +// } +// } + func (d *jsonDecDriver) IsContainerType(vt valueType) bool { // check container type by checking the first char if d.ct == valueTypeUnset { @@ -635,6 +776,9 @@ LOOP: } func (d *jsonDecDriver) DecodeInt(bitsize uint8) (i int64) { + if c := d.s.sc.sep(); c != 0 { + d.expectChar(c) + } d.decNum(false) n := &d.n if n.manOverflow { @@ -667,6 +811,9 @@ func (d *jsonDecDriver) DecodeInt(bitsize uint8) (i int64) { } func (d *jsonDecDriver) DecodeUint(bitsize uint8) (u uint64) { + if c := d.s.sc.sep(); c != 0 { + d.expectChar(c) + } d.decNum(false) n := &d.n if n.neg { @@ -698,6 +845,9 @@ func (d *jsonDecDriver) DecodeUint(bitsize uint8) (u uint64) { } func (d *jsonDecDriver) DecodeFloat(chkOverflow32 bool) (f float64) { + if c := d.s.sc.sep(); c != 0 { + d.expectChar(c) + } d.decNum(true) n := &d.n f = n.floatVal() @@ -709,6 +859,10 @@ func (d *jsonDecDriver) DecodeFloat(chkOverflow32 bool) (f float64) { } func (d *jsonDecDriver) DecodeExt(rv interface{}, xtag uint64, ext Ext) (realxtag uint64) { + // No need to call sep here, as d.d.decode() handles it + // if c := d.s.sc.sep(); c != 0 { + // d.expectChar(c) + // } if ext == nil { re := rv.(*RawExt) re.Tag = xtag @@ -722,6 +876,9 @@ func (d *jsonDecDriver) DecodeExt(rv interface{}, xtag uint64, ext Ext) (realxta } func (d *jsonDecDriver) DecodeBytes(bs []byte, isstring, zerocopy bool) (bsOut []byte) { + if c := d.s.sc.sep(); c != 0 { + d.expectChar(c) + } // zerocopy doesn't matter for json, as the bytes must be parsed. bs0 := d.appendStringAsBytes(d.b[:0]) if isstring { @@ -745,6 +902,9 @@ func (d *jsonDecDriver) DecodeBytes(bs []byte, isstring, zerocopy bool) (bsOut [ } func (d *jsonDecDriver) DecodeString() (s string) { + if c := d.s.sc.sep(); c != 0 { + d.expectChar(c) + } return string(d.appendStringAsBytes(d.b[:0])) } @@ -816,6 +976,9 @@ func (d *jsonDecDriver) jsonU4(checkSlashU bool) rune { } func (d *jsonDecDriver) DecodeNaked() (v interface{}, vt valueType, decodeFurther bool) { + if c := d.s.sc.sep(); c != 0 { + d.expectChar(c) + } n := d.skipWhitespace(true) switch n { case 'n': @@ -837,7 +1000,7 @@ func (d *jsonDecDriver) DecodeNaked() (v interface{}, vt valueType, decodeFurthe decodeFurther = true case '"': vt = valueTypeString - v = d.DecodeString() + v = string(d.appendStringAsBytes(d.b[:0])) // same as d.DecodeString(), but skipping sep() call. default: // number d.decNum(true) n := &d.n @@ -878,6 +1041,9 @@ func (d *jsonDecDriver) DecodeNaked() (v interface{}, vt valueType, decodeFurthe } // fmt.Printf("DecodeNaked: Number: %T, %v\n", v, v) } + if decodeFurther { + d.s.sc.retryRead() + } return } diff --git a/Godeps/_workspace/src/github.com/ugorji/go/codec/msgpack.go b/Godeps/_workspace/src/github.com/ugorji/go/codec/msgpack.go index 5cfc2a259..7c9f8e678 100644 --- a/Godeps/_workspace/src/github.com/ugorji/go/codec/msgpack.go +++ b/Godeps/_workspace/src/github.com/ugorji/go/codec/msgpack.go @@ -536,15 +536,11 @@ func (d *msgpackDecDriver) DecodeBytes(bs []byte, isstring, zerocopy bool) (bsOu d.readNextBd() } var clen int - if isstring { - clen = d.readContainerLen(msgpackContainerStr) + // ignore isstring. Expect that the bytes may be found from msgpackContainerStr or msgpackContainerBin + if bd := d.bd; bd == mpBin8 || bd == mpBin16 || bd == mpBin32 { + clen = d.readContainerLen(msgpackContainerBin) } else { - // bytes can be decoded from msgpackContainerStr or msgpackContainerBin - if bd := d.bd; bd == mpBin8 || bd == mpBin16 || bd == mpBin32 { - clen = d.readContainerLen(msgpackContainerBin) - } else { - clen = d.readContainerLen(msgpackContainerStr) - } + clen = d.readContainerLen(msgpackContainerStr) } // println("DecodeBytes: clen: ", clen) d.bdRead = false @@ -617,7 +613,7 @@ func (d *msgpackDecDriver) readContainerLen(ct msgpackContainerType) (clen int) } else if (ct.bFixMin & bd) == ct.bFixMin { clen = int(ct.bFixMin ^ bd) } else { - d.d.errorf("readContainerLen: %s: hex: %x, dec: %d", msgBadDesc, bd, bd) + d.d.errorf("readContainerLen: %s: hex: %x, decimal: %d", msgBadDesc, bd, bd) return } d.bdRead = false diff --git a/Godeps/_workspace/src/github.com/ugorji/go/codec/noop.go b/Godeps/_workspace/src/github.com/ugorji/go/codec/noop.go index 25bef4fc3..bcfe60e45 100644 --- a/Godeps/_workspace/src/github.com/ugorji/go/codec/noop.go +++ b/Godeps/_workspace/src/github.com/ugorji/go/codec/noop.go @@ -11,6 +11,7 @@ import ( // NoopHandle returns a no-op handle. It basically does nothing. // It is only useful for benchmarking, as it gives an idea of the // overhead from the codec framework. +// // LIBRARY USERS: *** DO NOT USE *** func NoopHandle(slen int) *noopHandle { h := noopHandle{} @@ -40,7 +41,8 @@ type noopDrv struct { i int S []string B [][]byte - mk bool // are we about to read a map key? + mks []bool // stack. if map (true), else if array (false) + mk bool // top of stack. what container are we on? map or array? ct valueType // last request for IsContainerType. cb bool // last response for IsContainerType. rand *rand.Rand @@ -54,21 +56,22 @@ func (h *noopDrv) newDecDriver(_ *Decoder) decDriver { return h } // --- encDriver -func (h *noopDrv) EncodeBuiltin(rt uintptr, v interface{}) {} -func (h *noopDrv) EncodeNil() {} -func (h *noopDrv) EncodeInt(i int64) {} -func (h *noopDrv) EncodeUint(i uint64) {} -func (h *noopDrv) EncodeBool(b bool) {} -func (h *noopDrv) EncodeFloat32(f float32) {} -func (h *noopDrv) EncodeFloat64(f float64) {} -func (h *noopDrv) EncodeRawExt(re *RawExt, e *Encoder) {} -func (h *noopDrv) EncodeArrayStart(length int) {} -func (h *noopDrv) EncodeArrayEnd() {} -func (h *noopDrv) EncodeArrayEntrySeparator() {} -func (h *noopDrv) EncodeMapStart(length int) {} -func (h *noopDrv) EncodeMapEnd() {} -func (h *noopDrv) EncodeMapEntrySeparator() {} -func (h *noopDrv) EncodeMapKVSeparator() {} +// stack functions (for map and array) +func (h *noopDrv) start(b bool) { h.mks = append(h.mks, b); h.mk = b } +func (h *noopDrv) end() { h.mks = h.mks[:len(h.mks)-1]; h.mk = h.mks[len(h.mks)-1] } + +func (h *noopDrv) EncodeBuiltin(rt uintptr, v interface{}) {} +func (h *noopDrv) EncodeNil() {} +func (h *noopDrv) EncodeInt(i int64) {} +func (h *noopDrv) EncodeUint(i uint64) {} +func (h *noopDrv) EncodeBool(b bool) {} +func (h *noopDrv) EncodeFloat32(f float32) {} +func (h *noopDrv) EncodeFloat64(f float64) {} +func (h *noopDrv) EncodeRawExt(re *RawExt, e *Encoder) {} +func (h *noopDrv) EncodeArrayStart(length int) { h.start(true) } +func (h *noopDrv) EncodeMapStart(length int) { h.start(false) } +func (h *noopDrv) EncodeEnd() { h.end() } + func (h *noopDrv) EncodeString(c charEncoding, v string) {} func (h *noopDrv) EncodeSymbol(v string) {} func (h *noopDrv) EncodeStringBytes(c charEncoding, v []byte) {} @@ -90,15 +93,11 @@ func (h *noopDrv) DecodeString() (s string) { return h.S[h.m(8 func (h *noopDrv) DecodeBytes(bs []byte, isstring, zerocopy bool) []byte { return h.B[h.m(len(h.B))] } -func (h *noopDrv) ReadMapEnd() { h.mk = false } -func (h *noopDrv) ReadArrayEnd() {} -func (h *noopDrv) ReadArrayEntrySeparator() {} -func (h *noopDrv) ReadMapEntrySeparator() { h.mk = true } -func (h *noopDrv) ReadMapKVSeparator() { h.mk = false } +func (h *noopDrv) ReadEnd() { h.start(true) } // toggle map/slice -func (h *noopDrv) ReadMapStart() int { h.mk = true; return h.m(10) } -func (h *noopDrv) ReadArrayStart() int { return h.m(10) } +func (h *noopDrv) ReadMapStart() int { h.start(true); return h.m(10) } +func (h *noopDrv) ReadArrayStart() int { h.start(false); return h.m(10) } func (h *noopDrv) IsContainerType(vt valueType) bool { // return h.m(2) == 0 diff --git a/Godeps/_workspace/src/github.com/ugorji/go/codec/prebuild.sh b/Godeps/_workspace/src/github.com/ugorji/go/codec/prebuild.sh index c1916f303..c58f17806 100644 --- a/Godeps/_workspace/src/github.com/ugorji/go/codec/prebuild.sh +++ b/Godeps/_workspace/src/github.com/ugorji/go/codec/prebuild.sh @@ -142,9 +142,9 @@ _codegenerators() { then true && \ echo "codecgen - !unsafe ... " && \ - codecgen -rt codecgen -t 'x,codecgen,!unsafe' -o values_codecgen${zsfx} $zfin && \ + codecgen -rt codecgen -t 'x,codecgen,!unsafe' -o values_codecgen${zsfx} -d 1978 $zfin && \ echo "codecgen - unsafe ... " && \ - codecgen -u -rt codecgen -t 'x,codecgen,unsafe' -o values_codecgen_unsafe${zsfx} $zfin && \ + codecgen -u -rt codecgen -t 'x,codecgen,unsafe' -o values_codecgen_unsafe${zsfx} -d 1978 $zfin && \ echo "msgp ... " && \ msgp -tests=false -pkg=codec -o=values_msgp${zsfx} -file=$zfin && \ echo "ffjson ... " && \ diff --git a/Godeps/_workspace/src/github.com/ugorji/go/codec/py_test.go b/Godeps/_workspace/src/github.com/ugorji/go/codec/py_test.go deleted file mode 100644 index be0374c99..000000000 --- a/Godeps/_workspace/src/github.com/ugorji/go/codec/py_test.go +++ /dev/null @@ -1,29 +0,0 @@ -//+build x - -// Copyright (c) 2012-2015 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -package codec - -// These tests are used to verify msgpack and cbor implementations against their python libraries. -// If you have the library installed, you can enable the tests back by removing the //+build ignore. - -import ( - "testing" -) - -func TestMsgpackPythonGenStreams(t *testing.T) { - doTestPythonGenStreams(t, "msgpack", testMsgpackH) -} - -func TestCborPythonGenStreams(t *testing.T) { - doTestPythonGenStreams(t, "cbor", testCborH) -} - -func TestMsgpackRpcSpecGoClientToPythonSvc(t *testing.T) { - doTestMsgpackRpcSpecGoClientToPythonSvc(t) -} - -func TestMsgpackRpcSpecPythonClientToGoSvc(t *testing.T) { - doTestMsgpackRpcSpecPythonClientToGoSvc(t) -} diff --git a/Godeps/_workspace/src/github.com/ugorji/go/codec/test.py b/Godeps/_workspace/src/github.com/ugorji/go/codec/test.py index 7b75e8cc0..dfe3b0c9a 100644 --- a/Godeps/_workspace/src/github.com/ugorji/go/codec/test.py +++ b/Godeps/_workspace/src/github.com/ugorji/go/codec/test.py @@ -5,8 +5,9 @@ # So it can process them (so we don't have to checkin the files). # Ensure msgpack-python and cbor are installed first, using: -# pip install --user msgpack-python -# pip install --user cbor +# sudo apt-get install python-dev +# sudo apt-get install python-pip +# pip install --user msgpack-python msgpack-rpc-python cbor import cbor, msgpack, msgpackrpc, sys, os, threading diff --git a/Godeps/_workspace/src/github.com/ugorji/go/codec/tests.sh b/Godeps/_workspace/src/github.com/ugorji/go/codec/tests.sh new file mode 100644 index 000000000..f14a4be96 --- /dev/null +++ b/Godeps/_workspace/src/github.com/ugorji/go/codec/tests.sh @@ -0,0 +1,55 @@ +#!/bin/bash + +# Run all the different permutations of all the tests. +# This helps ensure that nothing gets broken. + +_run() { + # 1. VARIATIONS: regular (t), canonical (c), IO R/W (i), binc-nosymbols (n), struct2array (s) + # 2. MODE: reflection (r), codecgen (x), codecgen+unsafe (u) + # + # Typically, you would run a combination of one value from a and b. + + ztags="" + local OPTIND + OPTIND=1 + while getopts "xurtcinsvg" flag + do + case "x$flag" in + 'xr') ;; + 'xg') ztags="$ztags codecgen" ;; + 'xx') ztags="$ztags x" ;; + 'xu') ztags="$ztags unsafe" ;; + 'xv') zverbose="-tv" ;; + *) ;; + esac + done + # shift $((OPTIND-1)) + echo ">>>>>>> tags: $ztags" + + OPTIND=1 + while getopts "xurtcinsvg" flag + do + case "x$flag" in + 'xt') echo ">>>>>>> REGULAR "; go test "-tags=$ztags" "$zverbose" ; sleep 2 ;; + 'xc') echo ">>>>>>> CANONICAL "; go test "-tags=$ztags" "$zverbose" -tc; sleep 2 ;; + 'xi') echo ">>>>>>> I/O "; go test "-tags=$ztags" "$zverbose" -ti; sleep 2 ;; + 'xn') echo ">>>>>>> NO_SYMBOLS "; go test "-tags=$ztags" "$zverbose" -tn; sleep 2 ;; + 'xs') echo ">>>>>>> TO_ARRAY "; go test "-tags=$ztags" "$zverbose" -ts; sleep 2 ;; + *) ;; + esac + done + shift $((OPTIND-1)) + + OPTIND=1 +} + +echo ">>>>>>> RUNNING VARIATIONS OF TESTS" +if [[ "x$@" = x ]]; then + # r, x, g, gu + _run "-rtcins" + _run "-xtcins" + _run "-gtcins" + _run "-gutcins" +else + _run "$@" +fi diff --git a/Godeps/_workspace/src/github.com/ugorji/go/codec/values_test.go b/Godeps/_workspace/src/github.com/ugorji/go/codec/values_test.go deleted file mode 100644 index 4ec28e131..000000000 --- a/Godeps/_workspace/src/github.com/ugorji/go/codec/values_test.go +++ /dev/null @@ -1,203 +0,0 @@ -// // +build testing - -// Copyright (c) 2012-2015 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -package codec - -// This file contains values used by tests and benchmarks. -// JSON/BSON do not like maps with keys that are not strings, -// so we only use maps with string keys here. - -import ( - "math" - "time" -) - -var testStrucTime = time.Date(2012, 2, 2, 2, 2, 2, 2000, time.UTC).UTC() - -type AnonInTestStruc struct { - AS string - AI64 int64 - AI16 int16 - AUi64 uint64 - ASslice []string - AI64slice []int64 - AF64slice []float64 - // AMI32U32 map[int32]uint32 - // AMU32F64 map[uint32]float64 // json/bson do not like it - AMSU16 map[string]uint16 -} - -type AnonInTestStrucIntf struct { - Islice []interface{} - Ms map[string]interface{} - Nintf interface{} //don't set this, so we can test for nil - T time.Time -} - -type TestStruc struct { - _struct struct{} `codec:",omitempty"` //set omitempty for every field - - S string - I64 int64 - I16 int16 - Ui64 uint64 - Ui8 uint8 - B bool - By uint8 // byte: msgp doesn't like byte - - Sslice []string - I64slice []int64 - I16slice []int16 - Ui64slice []uint64 - Ui8slice []uint8 - Bslice []bool - Byslice []byte - - Iptrslice []*int64 - - // TODO: test these separately, specifically for reflection and codecgen. - // Unfortunately, ffjson doesn't support these. Its compilation even fails. - // Ui64array [4]uint64 - // Ui64slicearray [][4]uint64 - - AnonInTestStruc - - //M map[interface{}]interface{} `json:"-",bson:"-"` - Msi64 map[string]int64 - - // make this a ptr, so that it could be set or not. - // for comparison (e.g. with msgp), give it a struct tag (so it is not inlined), - // make this one omitempty (so it is included if nil). - *AnonInTestStrucIntf `codec:",omitempty"` - - Nmap map[string]bool //don't set this, so we can test for nil - Nslice []byte //don't set this, so we can test for nil - Nint64 *int64 //don't set this, so we can test for nil - Mtsptr map[string]*TestStruc - Mts map[string]TestStruc - Its []*TestStruc - Nteststruc *TestStruc -} - -// small struct for testing that codecgen works for unexported types -type tLowerFirstLetter struct { - I int - u uint64 - S string - b []byte -} - -func newTestStruc(depth int, bench bool, useInterface, useStringKeyOnly bool) (ts *TestStruc) { - var i64a, i64b, i64c, i64d int64 = 64, 6464, 646464, 64646464 - - ts = &TestStruc{ - S: "some string", - I64: math.MaxInt64 * 2 / 3, // 64, - I16: 1616, - Ui64: uint64(int64(math.MaxInt64 * 2 / 3)), // 64, //don't use MaxUint64, as bson can't write it - Ui8: 160, - B: true, - By: 5, - - Sslice: []string{"one", "two", "three"}, - I64slice: []int64{1111, 2222, 3333}, - I16slice: []int16{44, 55, 66}, - Ui64slice: []uint64{12121212, 34343434, 56565656}, - Ui8slice: []uint8{210, 211, 212}, - Bslice: []bool{true, false, true, false}, - Byslice: []byte{13, 14, 15}, - - Msi64: map[string]int64{ - "one": 1, - "two": 2, - }, - AnonInTestStruc: AnonInTestStruc{ - // There's more leeway in altering this. - AS: "A-String", - AI64: -64646464, - AI16: 1616, - AUi64: 64646464, - // (U+1D11E)G-clef character may be represented in json as "\uD834\uDD1E". - // single reverse solidus character may be represented in json as "\u005C". - // include these in ASslice below. - ASslice: []string{"Aone", "Atwo", "Athree", - "Afour.reverse_solidus.\u005c", "Afive.Gclef.\U0001d11E"}, - AI64slice: []int64{1, -22, 333, -4444, 55555, -666666}, - AMSU16: map[string]uint16{"1": 1, "22": 2, "333": 3, "4444": 4}, - AF64slice: []float64{11.11e-11, 22.22E+22, 33.33E-33, 44.44e+44, 555.55E-6, 666.66E6}, - }, - } - if useInterface { - ts.AnonInTestStrucIntf = &AnonInTestStrucIntf{ - Islice: []interface{}{"true", true, "no", false, uint64(288), float64(0.4)}, - Ms: map[string]interface{}{ - "true": "true", - "int64(9)": false, - }, - T: testStrucTime, - } - } - - //For benchmarks, some things will not work. - if !bench { - //json and bson require string keys in maps - //ts.M = map[interface{}]interface{}{ - // true: "true", - // int8(9): false, - //} - //gob cannot encode nil in element in array (encodeArray: nil element) - ts.Iptrslice = []*int64{nil, &i64a, nil, &i64b, nil, &i64c, nil, &i64d, nil} - // ts.Iptrslice = nil - } - if !useStringKeyOnly { - // ts.AnonInTestStruc.AMU32F64 = map[uint32]float64{1: 1, 2: 2, 3: 3} // Json/Bson barf - } - if depth > 0 { - depth-- - if ts.Mtsptr == nil { - ts.Mtsptr = make(map[string]*TestStruc) - } - if ts.Mts == nil { - ts.Mts = make(map[string]TestStruc) - } - ts.Mtsptr["0"] = newTestStruc(depth, bench, useInterface, useStringKeyOnly) - ts.Mts["0"] = *(ts.Mtsptr["0"]) - ts.Its = append(ts.Its, ts.Mtsptr["0"]) - } - return -} - -// Some other types - -type Sstring string -type Bbool bool -type Sstructsmall struct { - A int -} - -type Sstructbig struct { - A int - B bool - c string - // Sval Sstruct - Ssmallptr *Sstructsmall - Ssmall *Sstructsmall - Sptr *Sstructbig -} - -type SstructbigMapBySlice struct { - _struct struct{} `codec:",toarray"` - A int - B bool - c string - // Sval Sstruct - Ssmallptr *Sstructsmall - Ssmall *Sstructsmall - Sptr *Sstructbig -} - -type Sinterface interface { - Noop() -} diff --git a/Godeps/_workspace/src/github.com/vaughan0/go-ini/ini_linux_test.go b/Godeps/_workspace/src/github.com/vaughan0/go-ini/ini_linux_test.go deleted file mode 100644 index 38a6f0004..000000000 --- a/Godeps/_workspace/src/github.com/vaughan0/go-ini/ini_linux_test.go +++ /dev/null @@ -1,43 +0,0 @@ -package ini - -import ( - "reflect" - "syscall" - "testing" -) - -func TestLoadFile(t *testing.T) { - originalOpenFiles := numFilesOpen(t) - - file, err := LoadFile("test.ini") - if err != nil { - t.Fatal(err) - } - - if originalOpenFiles != numFilesOpen(t) { - t.Error("test.ini not closed") - } - - if !reflect.DeepEqual(file, File{"default": {"stuff": "things"}}) { - t.Error("file not read correctly") - } -} - -func numFilesOpen(t *testing.T) (num uint64) { - var rlimit syscall.Rlimit - err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rlimit) - if err != nil { - t.Fatal(err) - } - maxFds := int(rlimit.Cur) - - var stat syscall.Stat_t - for i := 0; i < maxFds; i++ { - if syscall.Fstat(i, &stat) == nil { - num++ - } else { - return - } - } - return -} diff --git a/Godeps/_workspace/src/github.com/vaughan0/go-ini/ini_test.go b/Godeps/_workspace/src/github.com/vaughan0/go-ini/ini_test.go deleted file mode 100644 index 06a4d05ea..000000000 --- a/Godeps/_workspace/src/github.com/vaughan0/go-ini/ini_test.go +++ /dev/null @@ -1,89 +0,0 @@ -package ini - -import ( - "reflect" - "strings" - "testing" -) - -func TestLoad(t *testing.T) { - src := ` - # Comments are ignored - - herp = derp - - [foo] - hello=world - whitespace should = not matter - ; sneaky semicolon-style comment - multiple = equals = signs - - [bar] - this = that` - - file, err := Load(strings.NewReader(src)) - if err != nil { - t.Fatal(err) - } - check := func(section, key, expect string) { - if value, _ := file.Get(section, key); value != expect { - t.Errorf("Get(%q, %q): expected %q, got %q", section, key, expect, value) - } - } - - check("", "herp", "derp") - check("foo", "hello", "world") - check("foo", "whitespace should", "not matter") - check("foo", "multiple", "equals = signs") - check("bar", "this", "that") -} - -func TestSyntaxError(t *testing.T) { - src := ` - # Line 2 - [foo] - bar = baz - # Here's an error on line 6: - wut? - herp = derp` - _, err := Load(strings.NewReader(src)) - t.Logf("%T: %v", err, err) - if err == nil { - t.Fatal("expected an error, got nil") - } - syntaxErr, ok := err.(ErrSyntax) - if !ok { - t.Fatal("expected an error of type ErrSyntax") - } - if syntaxErr.Line != 6 { - t.Fatal("incorrect line number") - } - if syntaxErr.Source != "wut?" { - t.Fatal("incorrect source") - } -} - -func TestDefinedSectionBehaviour(t *testing.T) { - check := func(src string, expect File) { - file, err := Load(strings.NewReader(src)) - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(file, expect) { - t.Errorf("expected %v, got %v", expect, file) - } - } - // No sections for an empty file - check("", File{}) - // Default section only if there are actually values for it - check("foo=bar", File{"": {"foo": "bar"}}) - // User-defined sections should always be present, even if empty - check("[a]\n[b]\nfoo=bar", File{ - "a": {}, - "b": {"foo": "bar"}, - }) - check("foo=bar\n[a]\nthis=that", File{ - "": {"foo": "bar"}, - "a": {"this": "that"}, - }) -} diff --git a/Godeps/_workspace/src/golang.org/x/crypto/bcrypt/bcrypt_test.go b/Godeps/_workspace/src/golang.org/x/crypto/bcrypt/bcrypt_test.go deleted file mode 100644 index f08a6f5b2..000000000 --- a/Godeps/_workspace/src/golang.org/x/crypto/bcrypt/bcrypt_test.go +++ /dev/null @@ -1,226 +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 bcrypt - -import ( - "bytes" - "fmt" - "testing" -) - -func TestBcryptingIsEasy(t *testing.T) { - pass := []byte("mypassword") - hp, err := GenerateFromPassword(pass, 0) - if err != nil { - t.Fatalf("GenerateFromPassword error: %s", err) - } - - if CompareHashAndPassword(hp, pass) != nil { - t.Errorf("%v should hash %s correctly", hp, pass) - } - - notPass := "notthepass" - err = CompareHashAndPassword(hp, []byte(notPass)) - if err != ErrMismatchedHashAndPassword { - t.Errorf("%v and %s should be mismatched", hp, notPass) - } -} - -func TestBcryptingIsCorrect(t *testing.T) { - pass := []byte("allmine") - salt := []byte("XajjQvNhvvRt5GSeFk1xFe") - expectedHash := []byte("$2a$10$XajjQvNhvvRt5GSeFk1xFeyqRrsxkhBkUiQeg0dt.wU1qD4aFDcga") - - hash, err := bcrypt(pass, 10, salt) - if err != nil { - t.Fatalf("bcrypt blew up: %v", err) - } - if !bytes.HasSuffix(expectedHash, hash) { - t.Errorf("%v should be the suffix of %v", hash, expectedHash) - } - - h, err := newFromHash(expectedHash) - if err != nil { - t.Errorf("Unable to parse %s: %v", string(expectedHash), err) - } - - // This is not the safe way to compare these hashes. We do this only for - // testing clarity. Use bcrypt.CompareHashAndPassword() - if err == nil && !bytes.Equal(expectedHash, h.Hash()) { - t.Errorf("Parsed hash %v should equal %v", h.Hash(), expectedHash) - } -} - -func TestVeryShortPasswords(t *testing.T) { - key := []byte("k") - salt := []byte("XajjQvNhvvRt5GSeFk1xFe") - _, err := bcrypt(key, 10, salt) - if err != nil { - t.Errorf("One byte key resulted in error: %s", err) - } -} - -func TestTooLongPasswordsWork(t *testing.T) { - salt := []byte("XajjQvNhvvRt5GSeFk1xFe") - // One byte over the usual 56 byte limit that blowfish has - tooLongPass := []byte("012345678901234567890123456789012345678901234567890123456") - tooLongExpected := []byte("$2a$10$XajjQvNhvvRt5GSeFk1xFe5l47dONXg781AmZtd869sO8zfsHuw7C") - hash, err := bcrypt(tooLongPass, 10, salt) - if err != nil { - t.Fatalf("bcrypt blew up on long password: %v", err) - } - if !bytes.HasSuffix(tooLongExpected, hash) { - t.Errorf("%v should be the suffix of %v", hash, tooLongExpected) - } -} - -type InvalidHashTest struct { - err error - hash []byte -} - -var invalidTests = []InvalidHashTest{ - {ErrHashTooShort, []byte("$2a$10$fooo")}, - {ErrHashTooShort, []byte("$2a")}, - {HashVersionTooNewError('3'), []byte("$3a$10$sssssssssssssssssssssshhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh")}, - {InvalidHashPrefixError('%'), []byte("%2a$10$sssssssssssssssssssssshhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh")}, - {InvalidCostError(32), []byte("$2a$32$sssssssssssssssssssssshhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh")}, -} - -func TestInvalidHashErrors(t *testing.T) { - check := func(name string, expected, err error) { - if err == nil { - t.Errorf("%s: Should have returned an error", name) - } - if err != nil && err != expected { - t.Errorf("%s gave err %v but should have given %v", name, err, expected) - } - } - for _, iht := range invalidTests { - _, err := newFromHash(iht.hash) - check("newFromHash", iht.err, err) - err = CompareHashAndPassword(iht.hash, []byte("anything")) - check("CompareHashAndPassword", iht.err, err) - } -} - -func TestUnpaddedBase64Encoding(t *testing.T) { - original := []byte{101, 201, 101, 75, 19, 227, 199, 20, 239, 236, 133, 32, 30, 109, 243, 30} - encodedOriginal := []byte("XajjQvNhvvRt5GSeFk1xFe") - - encoded := base64Encode(original) - - if !bytes.Equal(encodedOriginal, encoded) { - t.Errorf("Encoded %v should have equaled %v", encoded, encodedOriginal) - } - - decoded, err := base64Decode(encodedOriginal) - if err != nil { - t.Fatalf("base64Decode blew up: %s", err) - } - - if !bytes.Equal(decoded, original) { - t.Errorf("Decoded %v should have equaled %v", decoded, original) - } -} - -func TestCost(t *testing.T) { - suffix := "XajjQvNhvvRt5GSeFk1xFe5l47dONXg781AmZtd869sO8zfsHuw7C" - for _, vers := range []string{"2a", "2"} { - for _, cost := range []int{4, 10} { - s := fmt.Sprintf("$%s$%02d$%s", vers, cost, suffix) - h := []byte(s) - actual, err := Cost(h) - if err != nil { - t.Errorf("Cost, error: %s", err) - continue - } - if actual != cost { - t.Errorf("Cost, expected: %d, actual: %d", cost, actual) - } - } - } - _, err := Cost([]byte("$a$a$" + suffix)) - if err == nil { - t.Errorf("Cost, malformed but no error returned") - } -} - -func TestCostValidationInHash(t *testing.T) { - if testing.Short() { - return - } - - pass := []byte("mypassword") - - for c := 0; c < MinCost; c++ { - p, _ := newFromPassword(pass, c) - if p.cost != DefaultCost { - t.Errorf("newFromPassword should default costs below %d to %d, but was %d", MinCost, DefaultCost, p.cost) - } - } - - p, _ := newFromPassword(pass, 14) - if p.cost != 14 { - t.Errorf("newFromPassword should default cost to 14, but was %d", p.cost) - } - - hp, _ := newFromHash(p.Hash()) - if p.cost != hp.cost { - t.Errorf("newFromHash should maintain the cost at %d, but was %d", p.cost, hp.cost) - } - - _, err := newFromPassword(pass, 32) - if err == nil { - t.Fatalf("newFromPassword: should return a cost error") - } - if err != InvalidCostError(32) { - t.Errorf("newFromPassword: should return cost error, got %#v", err) - } -} - -func TestCostReturnsWithLeadingZeroes(t *testing.T) { - hp, _ := newFromPassword([]byte("abcdefgh"), 7) - cost := hp.Hash()[4:7] - expected := []byte("07$") - - if !bytes.Equal(expected, cost) { - t.Errorf("single digit costs in hash should have leading zeros: was %v instead of %v", cost, expected) - } -} - -func TestMinorNotRequired(t *testing.T) { - noMinorHash := []byte("$2$10$XajjQvNhvvRt5GSeFk1xFeyqRrsxkhBkUiQeg0dt.wU1qD4aFDcga") - h, err := newFromHash(noMinorHash) - if err != nil { - t.Fatalf("No minor hash blew up: %s", err) - } - if h.minor != 0 { - t.Errorf("Should leave minor version at 0, but was %d", h.minor) - } - - if !bytes.Equal(noMinorHash, h.Hash()) { - t.Errorf("Should generate hash %v, but created %v", noMinorHash, h.Hash()) - } -} - -func BenchmarkEqual(b *testing.B) { - b.StopTimer() - passwd := []byte("somepasswordyoulike") - hash, _ := GenerateFromPassword(passwd, 10) - b.StartTimer() - for i := 0; i < b.N; i++ { - CompareHashAndPassword(hash, passwd) - } -} - -func BenchmarkGeneration(b *testing.B) { - b.StopTimer() - passwd := []byte("mylongpassword1234") - b.StartTimer() - for i := 0; i < b.N; i++ { - GenerateFromPassword(passwd, 10) - } -} diff --git a/Godeps/_workspace/src/golang.org/x/crypto/blowfish/blowfish_test.go b/Godeps/_workspace/src/golang.org/x/crypto/blowfish/blowfish_test.go deleted file mode 100644 index 7afa1fdf3..000000000 --- a/Godeps/_workspace/src/golang.org/x/crypto/blowfish/blowfish_test.go +++ /dev/null @@ -1,274 +0,0 @@ -// Copyright 2010 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 blowfish - -import "testing" - -type CryptTest struct { - key []byte - in []byte - out []byte -} - -// Test vector values are from http://www.schneier.com/code/vectors.txt. -var encryptTests = []CryptTest{ - { - []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - []byte{0x4E, 0xF9, 0x97, 0x45, 0x61, 0x98, 0xDD, 0x78}}, - { - []byte{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}, - []byte{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}, - []byte{0x51, 0x86, 0x6F, 0xD5, 0xB8, 0x5E, 0xCB, 0x8A}}, - { - []byte{0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - []byte{0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}, - []byte{0x7D, 0x85, 0x6F, 0x9A, 0x61, 0x30, 0x63, 0xF2}}, - { - []byte{0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11}, - []byte{0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11}, - []byte{0x24, 0x66, 0xDD, 0x87, 0x8B, 0x96, 0x3C, 0x9D}}, - - { - []byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF}, - []byte{0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11}, - []byte{0x61, 0xF9, 0xC3, 0x80, 0x22, 0x81, 0xB0, 0x96}}, - { - []byte{0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11}, - []byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF}, - []byte{0x7D, 0x0C, 0xC6, 0x30, 0xAF, 0xDA, 0x1E, 0xC7}}, - { - []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - []byte{0x4E, 0xF9, 0x97, 0x45, 0x61, 0x98, 0xDD, 0x78}}, - { - []byte{0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}, - []byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF}, - []byte{0x0A, 0xCE, 0xAB, 0x0F, 0xC6, 0xA0, 0xA2, 0x8D}}, - { - []byte{0x7C, 0xA1, 0x10, 0x45, 0x4A, 0x1A, 0x6E, 0x57}, - []byte{0x01, 0xA1, 0xD6, 0xD0, 0x39, 0x77, 0x67, 0x42}, - []byte{0x59, 0xC6, 0x82, 0x45, 0xEB, 0x05, 0x28, 0x2B}}, - { - []byte{0x01, 0x31, 0xD9, 0x61, 0x9D, 0xC1, 0x37, 0x6E}, - []byte{0x5C, 0xD5, 0x4C, 0xA8, 0x3D, 0xEF, 0x57, 0xDA}, - []byte{0xB1, 0xB8, 0xCC, 0x0B, 0x25, 0x0F, 0x09, 0xA0}}, - { - []byte{0x07, 0xA1, 0x13, 0x3E, 0x4A, 0x0B, 0x26, 0x86}, - []byte{0x02, 0x48, 0xD4, 0x38, 0x06, 0xF6, 0x71, 0x72}, - []byte{0x17, 0x30, 0xE5, 0x77, 0x8B, 0xEA, 0x1D, 0xA4}}, - { - []byte{0x38, 0x49, 0x67, 0x4C, 0x26, 0x02, 0x31, 0x9E}, - []byte{0x51, 0x45, 0x4B, 0x58, 0x2D, 0xDF, 0x44, 0x0A}, - []byte{0xA2, 0x5E, 0x78, 0x56, 0xCF, 0x26, 0x51, 0xEB}}, - { - []byte{0x04, 0xB9, 0x15, 0xBA, 0x43, 0xFE, 0xB5, 0xB6}, - []byte{0x42, 0xFD, 0x44, 0x30, 0x59, 0x57, 0x7F, 0xA2}, - []byte{0x35, 0x38, 0x82, 0xB1, 0x09, 0xCE, 0x8F, 0x1A}}, - { - []byte{0x01, 0x13, 0xB9, 0x70, 0xFD, 0x34, 0xF2, 0xCE}, - []byte{0x05, 0x9B, 0x5E, 0x08, 0x51, 0xCF, 0x14, 0x3A}, - []byte{0x48, 0xF4, 0xD0, 0x88, 0x4C, 0x37, 0x99, 0x18}}, - { - []byte{0x01, 0x70, 0xF1, 0x75, 0x46, 0x8F, 0xB5, 0xE6}, - []byte{0x07, 0x56, 0xD8, 0xE0, 0x77, 0x47, 0x61, 0xD2}, - []byte{0x43, 0x21, 0x93, 0xB7, 0x89, 0x51, 0xFC, 0x98}}, - { - []byte{0x43, 0x29, 0x7F, 0xAD, 0x38, 0xE3, 0x73, 0xFE}, - []byte{0x76, 0x25, 0x14, 0xB8, 0x29, 0xBF, 0x48, 0x6A}, - []byte{0x13, 0xF0, 0x41, 0x54, 0xD6, 0x9D, 0x1A, 0xE5}}, - { - []byte{0x07, 0xA7, 0x13, 0x70, 0x45, 0xDA, 0x2A, 0x16}, - []byte{0x3B, 0xDD, 0x11, 0x90, 0x49, 0x37, 0x28, 0x02}, - []byte{0x2E, 0xED, 0xDA, 0x93, 0xFF, 0xD3, 0x9C, 0x79}}, - { - []byte{0x04, 0x68, 0x91, 0x04, 0xC2, 0xFD, 0x3B, 0x2F}, - []byte{0x26, 0x95, 0x5F, 0x68, 0x35, 0xAF, 0x60, 0x9A}, - []byte{0xD8, 0x87, 0xE0, 0x39, 0x3C, 0x2D, 0xA6, 0xE3}}, - { - []byte{0x37, 0xD0, 0x6B, 0xB5, 0x16, 0xCB, 0x75, 0x46}, - []byte{0x16, 0x4D, 0x5E, 0x40, 0x4F, 0x27, 0x52, 0x32}, - []byte{0x5F, 0x99, 0xD0, 0x4F, 0x5B, 0x16, 0x39, 0x69}}, - { - []byte{0x1F, 0x08, 0x26, 0x0D, 0x1A, 0xC2, 0x46, 0x5E}, - []byte{0x6B, 0x05, 0x6E, 0x18, 0x75, 0x9F, 0x5C, 0xCA}, - []byte{0x4A, 0x05, 0x7A, 0x3B, 0x24, 0xD3, 0x97, 0x7B}}, - { - []byte{0x58, 0x40, 0x23, 0x64, 0x1A, 0xBA, 0x61, 0x76}, - []byte{0x00, 0x4B, 0xD6, 0xEF, 0x09, 0x17, 0x60, 0x62}, - []byte{0x45, 0x20, 0x31, 0xC1, 0xE4, 0xFA, 0xDA, 0x8E}}, - { - []byte{0x02, 0x58, 0x16, 0x16, 0x46, 0x29, 0xB0, 0x07}, - []byte{0x48, 0x0D, 0x39, 0x00, 0x6E, 0xE7, 0x62, 0xF2}, - []byte{0x75, 0x55, 0xAE, 0x39, 0xF5, 0x9B, 0x87, 0xBD}}, - { - []byte{0x49, 0x79, 0x3E, 0xBC, 0x79, 0xB3, 0x25, 0x8F}, - []byte{0x43, 0x75, 0x40, 0xC8, 0x69, 0x8F, 0x3C, 0xFA}, - []byte{0x53, 0xC5, 0x5F, 0x9C, 0xB4, 0x9F, 0xC0, 0x19}}, - { - []byte{0x4F, 0xB0, 0x5E, 0x15, 0x15, 0xAB, 0x73, 0xA7}, - []byte{0x07, 0x2D, 0x43, 0xA0, 0x77, 0x07, 0x52, 0x92}, - []byte{0x7A, 0x8E, 0x7B, 0xFA, 0x93, 0x7E, 0x89, 0xA3}}, - { - []byte{0x49, 0xE9, 0x5D, 0x6D, 0x4C, 0xA2, 0x29, 0xBF}, - []byte{0x02, 0xFE, 0x55, 0x77, 0x81, 0x17, 0xF1, 0x2A}, - []byte{0xCF, 0x9C, 0x5D, 0x7A, 0x49, 0x86, 0xAD, 0xB5}}, - { - []byte{0x01, 0x83, 0x10, 0xDC, 0x40, 0x9B, 0x26, 0xD6}, - []byte{0x1D, 0x9D, 0x5C, 0x50, 0x18, 0xF7, 0x28, 0xC2}, - []byte{0xD1, 0xAB, 0xB2, 0x90, 0x65, 0x8B, 0xC7, 0x78}}, - { - []byte{0x1C, 0x58, 0x7F, 0x1C, 0x13, 0x92, 0x4F, 0xEF}, - []byte{0x30, 0x55, 0x32, 0x28, 0x6D, 0x6F, 0x29, 0x5A}, - []byte{0x55, 0xCB, 0x37, 0x74, 0xD1, 0x3E, 0xF2, 0x01}}, - { - []byte{0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01}, - []byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF}, - []byte{0xFA, 0x34, 0xEC, 0x48, 0x47, 0xB2, 0x68, 0xB2}}, - { - []byte{0x1F, 0x1F, 0x1F, 0x1F, 0x0E, 0x0E, 0x0E, 0x0E}, - []byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF}, - []byte{0xA7, 0x90, 0x79, 0x51, 0x08, 0xEA, 0x3C, 0xAE}}, - { - []byte{0xE0, 0xFE, 0xE0, 0xFE, 0xF1, 0xFE, 0xF1, 0xFE}, - []byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF}, - []byte{0xC3, 0x9E, 0x07, 0x2D, 0x9F, 0xAC, 0x63, 0x1D}}, - { - []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - []byte{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}, - []byte{0x01, 0x49, 0x33, 0xE0, 0xCD, 0xAF, 0xF6, 0xE4}}, - { - []byte{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}, - []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - []byte{0xF2, 0x1E, 0x9A, 0x77, 0xB7, 0x1C, 0x49, 0xBC}}, - { - []byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF}, - []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - []byte{0x24, 0x59, 0x46, 0x88, 0x57, 0x54, 0x36, 0x9A}}, - { - []byte{0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}, - []byte{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}, - []byte{0x6B, 0x5C, 0x5A, 0x9C, 0x5D, 0x9E, 0x0A, 0x5A}}, -} - -func TestCipherEncrypt(t *testing.T) { - for i, tt := range encryptTests { - c, err := NewCipher(tt.key) - if err != nil { - t.Errorf("NewCipher(%d bytes) = %s", len(tt.key), err) - continue - } - ct := make([]byte, len(tt.out)) - c.Encrypt(ct, tt.in) - for j, v := range ct { - if v != tt.out[j] { - t.Errorf("Cipher.Encrypt, test vector #%d: cipher-text[%d] = %#x, expected %#x", i, j, v, tt.out[j]) - break - } - } - } -} - -func TestCipherDecrypt(t *testing.T) { - for i, tt := range encryptTests { - c, err := NewCipher(tt.key) - if err != nil { - t.Errorf("NewCipher(%d bytes) = %s", len(tt.key), err) - continue - } - pt := make([]byte, len(tt.in)) - c.Decrypt(pt, tt.out) - for j, v := range pt { - if v != tt.in[j] { - t.Errorf("Cipher.Decrypt, test vector #%d: plain-text[%d] = %#x, expected %#x", i, j, v, tt.in[j]) - break - } - } - } -} - -func TestSaltedCipherKeyLength(t *testing.T) { - if _, err := NewSaltedCipher(nil, []byte{'a'}); err != KeySizeError(0) { - t.Errorf("NewSaltedCipher with short key, gave error %#v, expected %#v", err, KeySizeError(0)) - } - - // A 57-byte key. One over the typical blowfish restriction. - key := []byte("012345678901234567890123456789012345678901234567890123456") - if _, err := NewSaltedCipher(key, []byte{'a'}); err != nil { - t.Errorf("NewSaltedCipher with long key, gave error %#v", err) - } -} - -// Test vectors generated with Blowfish from OpenSSH. -var saltedVectors = [][8]byte{ - {0x0c, 0x82, 0x3b, 0x7b, 0x8d, 0x01, 0x4b, 0x7e}, - {0xd1, 0xe1, 0x93, 0xf0, 0x70, 0xa6, 0xdb, 0x12}, - {0xfc, 0x5e, 0xba, 0xde, 0xcb, 0xf8, 0x59, 0xad}, - {0x8a, 0x0c, 0x76, 0xe7, 0xdd, 0x2c, 0xd3, 0xa8}, - {0x2c, 0xcb, 0x7b, 0xee, 0xac, 0x7b, 0x7f, 0xf8}, - {0xbb, 0xf6, 0x30, 0x6f, 0xe1, 0x5d, 0x62, 0xbf}, - {0x97, 0x1e, 0xc1, 0x3d, 0x3d, 0xe0, 0x11, 0xe9}, - {0x06, 0xd7, 0x4d, 0xb1, 0x80, 0xa3, 0xb1, 0x38}, - {0x67, 0xa1, 0xa9, 0x75, 0x0e, 0x5b, 0xc6, 0xb4}, - {0x51, 0x0f, 0x33, 0x0e, 0x4f, 0x67, 0xd2, 0x0c}, - {0xf1, 0x73, 0x7e, 0xd8, 0x44, 0xea, 0xdb, 0xe5}, - {0x14, 0x0e, 0x16, 0xce, 0x7f, 0x4a, 0x9c, 0x7b}, - {0x4b, 0xfe, 0x43, 0xfd, 0xbf, 0x36, 0x04, 0x47}, - {0xb1, 0xeb, 0x3e, 0x15, 0x36, 0xa7, 0xbb, 0xe2}, - {0x6d, 0x0b, 0x41, 0xdd, 0x00, 0x98, 0x0b, 0x19}, - {0xd3, 0xce, 0x45, 0xce, 0x1d, 0x56, 0xb7, 0xfc}, - {0xd9, 0xf0, 0xfd, 0xda, 0xc0, 0x23, 0xb7, 0x93}, - {0x4c, 0x6f, 0xa1, 0xe4, 0x0c, 0xa8, 0xca, 0x57}, - {0xe6, 0x2f, 0x28, 0xa7, 0x0c, 0x94, 0x0d, 0x08}, - {0x8f, 0xe3, 0xf0, 0xb6, 0x29, 0xe3, 0x44, 0x03}, - {0xff, 0x98, 0xdd, 0x04, 0x45, 0xb4, 0x6d, 0x1f}, - {0x9e, 0x45, 0x4d, 0x18, 0x40, 0x53, 0xdb, 0xef}, - {0xb7, 0x3b, 0xef, 0x29, 0xbe, 0xa8, 0x13, 0x71}, - {0x02, 0x54, 0x55, 0x41, 0x8e, 0x04, 0xfc, 0xad}, - {0x6a, 0x0a, 0xee, 0x7c, 0x10, 0xd9, 0x19, 0xfe}, - {0x0a, 0x22, 0xd9, 0x41, 0xcc, 0x23, 0x87, 0x13}, - {0x6e, 0xff, 0x1f, 0xff, 0x36, 0x17, 0x9c, 0xbe}, - {0x79, 0xad, 0xb7, 0x40, 0xf4, 0x9f, 0x51, 0xa6}, - {0x97, 0x81, 0x99, 0xa4, 0xde, 0x9e, 0x9f, 0xb6}, - {0x12, 0x19, 0x7a, 0x28, 0xd0, 0xdc, 0xcc, 0x92}, - {0x81, 0xda, 0x60, 0x1e, 0x0e, 0xdd, 0x65, 0x56}, - {0x7d, 0x76, 0x20, 0xb2, 0x73, 0xc9, 0x9e, 0xee}, -} - -func TestSaltedCipher(t *testing.T) { - var key, salt [32]byte - for i := range key { - key[i] = byte(i) - salt[i] = byte(i + 32) - } - for i, v := range saltedVectors { - c, err := NewSaltedCipher(key[:], salt[:i]) - if err != nil { - t.Fatal(err) - } - var buf [8]byte - c.Encrypt(buf[:], buf[:]) - if v != buf { - t.Errorf("%d: expected %x, got %x", i, v, buf) - } - } -} - -func BenchmarkExpandKeyWithSalt(b *testing.B) { - key := make([]byte, 32) - salt := make([]byte, 16) - c, _ := NewCipher(key) - for i := 0; i < b.N; i++ { - expandKeyWithSalt(key, salt, c) - } -} - -func BenchmarkExpandKey(b *testing.B) { - key := make([]byte, 32) - c, _ := NewCipher(key) - for i := 0; i < b.N; i++ { - ExpandKey(key, c) - } -} diff --git a/Godeps/_workspace/src/golang.org/x/crypto/cast5/cast5_test.go b/Godeps/_workspace/src/golang.org/x/crypto/cast5/cast5_test.go deleted file mode 100644 index 778b272a6..000000000 --- a/Godeps/_workspace/src/golang.org/x/crypto/cast5/cast5_test.go +++ /dev/null @@ -1,106 +0,0 @@ -// Copyright 2010 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 cast5 - -import ( - "bytes" - "encoding/hex" - "testing" -) - -// This test vector is taken from RFC 2144, App B.1. -// Since the other two test vectors are for reduced-round variants, we can't -// use them. -var basicTests = []struct { - key, plainText, cipherText string -}{ - { - "0123456712345678234567893456789a", - "0123456789abcdef", - "238b4fe5847e44b2", - }, -} - -func TestBasic(t *testing.T) { - for i, test := range basicTests { - key, _ := hex.DecodeString(test.key) - plainText, _ := hex.DecodeString(test.plainText) - expected, _ := hex.DecodeString(test.cipherText) - - c, err := NewCipher(key) - if err != nil { - t.Errorf("#%d: failed to create Cipher: %s", i, err) - continue - } - var cipherText [BlockSize]byte - c.Encrypt(cipherText[:], plainText) - if !bytes.Equal(cipherText[:], expected) { - t.Errorf("#%d: got:%x want:%x", i, cipherText, expected) - } - - var plainTextAgain [BlockSize]byte - c.Decrypt(plainTextAgain[:], cipherText[:]) - if !bytes.Equal(plainTextAgain[:], plainText) { - t.Errorf("#%d: got:%x want:%x", i, plainTextAgain, plainText) - } - } -} - -// TestFull performs the test specified in RFC 2144, App B.2. -// However, due to the length of time taken, it's disabled here and a more -// limited version is included, below. -func TestFull(t *testing.T) { - if testing.Short() { - // This is too slow for normal testing - return - } - - a, b := iterate(1000000) - - const expectedA = "eea9d0a249fd3ba6b3436fb89d6dca92" - const expectedB = "b2c95eb00c31ad7180ac05b8e83d696e" - - if hex.EncodeToString(a) != expectedA { - t.Errorf("a: got:%x want:%s", a, expectedA) - } - if hex.EncodeToString(b) != expectedB { - t.Errorf("b: got:%x want:%s", b, expectedB) - } -} - -func iterate(iterations int) ([]byte, []byte) { - const initValueHex = "0123456712345678234567893456789a" - - initValue, _ := hex.DecodeString(initValueHex) - - var a, b [16]byte - copy(a[:], initValue) - copy(b[:], initValue) - - for i := 0; i < iterations; i++ { - c, _ := NewCipher(b[:]) - c.Encrypt(a[:8], a[:8]) - c.Encrypt(a[8:], a[8:]) - c, _ = NewCipher(a[:]) - c.Encrypt(b[:8], b[:8]) - c.Encrypt(b[8:], b[8:]) - } - - return a[:], b[:] -} - -func TestLimited(t *testing.T) { - a, b := iterate(1000) - - const expectedA = "23f73b14b02a2ad7dfb9f2c35644798d" - const expectedB = "e5bf37eff14c456a40b21ce369370a9f" - - if hex.EncodeToString(a) != expectedA { - t.Errorf("a: got:%x want:%s", a, expectedA) - } - if hex.EncodeToString(b) != expectedB { - t.Errorf("b: got:%x want:%s", b, expectedB) - } -} diff --git a/Godeps/_workspace/src/golang.org/x/crypto/curve25519/curve25519_test.go b/Godeps/_workspace/src/golang.org/x/crypto/curve25519/curve25519_test.go deleted file mode 100644 index 14b0ee87c..000000000 --- a/Godeps/_workspace/src/golang.org/x/crypto/curve25519/curve25519_test.go +++ /dev/null @@ -1,29 +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 curve25519 - -import ( - "fmt" - "testing" -) - -const expectedHex = "89161fde887b2b53de549af483940106ecc114d6982daa98256de23bdf77661a" - -func TestBaseScalarMult(t *testing.T) { - var a, b [32]byte - in := &a - out := &b - a[0] = 1 - - for i := 0; i < 200; i++ { - ScalarBaseMult(out, in) - in, out = out, in - } - - result := fmt.Sprintf("%x", in[:]) - if result != expectedHex { - t.Errorf("incorrect result: got %s, want %s", result, expectedHex) - } -} diff --git a/Godeps/_workspace/src/golang.org/x/crypto/openpgp/armor/armor_test.go b/Godeps/_workspace/src/golang.org/x/crypto/openpgp/armor/armor_test.go deleted file mode 100644 index 9334e94e9..000000000 --- a/Godeps/_workspace/src/golang.org/x/crypto/openpgp/armor/armor_test.go +++ /dev/null @@ -1,95 +0,0 @@ -// Copyright 2010 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 armor - -import ( - "bytes" - "hash/adler32" - "io/ioutil" - "testing" -) - -func TestDecodeEncode(t *testing.T) { - buf := bytes.NewBuffer([]byte(armorExample1)) - result, err := Decode(buf) - if err != nil { - t.Error(err) - } - expectedType := "PGP SIGNATURE" - if result.Type != expectedType { - t.Errorf("result.Type: got:%s want:%s", result.Type, expectedType) - } - if len(result.Header) != 1 { - t.Errorf("len(result.Header): got:%d want:1", len(result.Header)) - } - v, ok := result.Header["Version"] - if !ok || v != "GnuPG v1.4.10 (GNU/Linux)" { - t.Errorf("result.Header: got:%#v", result.Header) - } - - contents, err := ioutil.ReadAll(result.Body) - if err != nil { - t.Error(err) - } - - if adler32.Checksum(contents) != 0x27b144be { - t.Errorf("contents: got: %x", contents) - } - - buf = bytes.NewBuffer(nil) - w, err := Encode(buf, result.Type, result.Header) - if err != nil { - t.Error(err) - } - _, err = w.Write(contents) - if err != nil { - t.Error(err) - } - w.Close() - - if !bytes.Equal(buf.Bytes(), []byte(armorExample1)) { - t.Errorf("got: %s\nwant: %s", string(buf.Bytes()), armorExample1) - } -} - -func TestLongHeader(t *testing.T) { - buf := bytes.NewBuffer([]byte(armorLongLine)) - result, err := Decode(buf) - if err != nil { - t.Error(err) - return - } - value, ok := result.Header["Version"] - if !ok { - t.Errorf("missing Version header") - } - if value != longValueExpected { - t.Errorf("got: %s want: %s", value, longValueExpected) - } -} - -const armorExample1 = `-----BEGIN PGP SIGNATURE----- -Version: GnuPG v1.4.10 (GNU/Linux) - -iJwEAAECAAYFAk1Fv/0ACgkQo01+GMIMMbsYTwQAiAw+QAaNfY6WBdplZ/uMAccm -4g+81QPmTSGHnetSb6WBiY13kVzK4HQiZH8JSkmmroMLuGeJwsRTEL4wbjRyUKEt -p1xwUZDECs234F1xiG5enc5SGlRtP7foLBz9lOsjx+LEcA4sTl5/2eZR9zyFZqWW -TxRjs+fJCIFuo71xb1g= -=/teI ------END PGP SIGNATURE-----` - -const armorLongLine = `-----BEGIN PGP SIGNATURE----- -Version: 0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz - -iQEcBAABAgAGBQJMtFESAAoJEKsQXJGvOPsVj40H/1WW6jaMXv4BW+1ueDSMDwM8 -kx1fLOXbVM5/Kn5LStZNt1jWWnpxdz7eq3uiqeCQjmqUoRde3YbB2EMnnwRbAhpp -cacnAvy9ZQ78OTxUdNW1mhX5bS6q1MTEJnl+DcyigD70HG/yNNQD7sOPMdYQw0TA -byQBwmLwmTsuZsrYqB68QyLHI+DUugn+kX6Hd2WDB62DKa2suoIUIHQQCd/ofwB3 -WfCYInXQKKOSxu2YOg2Eb4kLNhSMc1i9uKUWAH+sdgJh7NBgdoE4MaNtBFkHXRvv -okWuf3+xA9ksp1npSY/mDvgHijmjvtpRDe6iUeqfCn8N9u9CBg8geANgaG8+QA4= -=wfQG ------END PGP SIGNATURE-----` - -const longValueExpected = "0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz" diff --git a/Godeps/_workspace/src/golang.org/x/crypto/openpgp/canonical_text_test.go b/Godeps/_workspace/src/golang.org/x/crypto/openpgp/canonical_text_test.go deleted file mode 100644 index 8f3ba2a88..000000000 --- a/Godeps/_workspace/src/golang.org/x/crypto/openpgp/canonical_text_test.go +++ /dev/null @@ -1,52 +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 openpgp - -import ( - "bytes" - "testing" -) - -type recordingHash struct { - buf *bytes.Buffer -} - -func (r recordingHash) Write(b []byte) (n int, err error) { - return r.buf.Write(b) -} - -func (r recordingHash) Sum(in []byte) []byte { - return append(in, r.buf.Bytes()...) -} - -func (r recordingHash) Reset() { - panic("shouldn't be called") -} - -func (r recordingHash) Size() int { - panic("shouldn't be called") -} - -func (r recordingHash) BlockSize() int { - panic("shouldn't be called") -} - -func testCanonicalText(t *testing.T, input, expected string) { - r := recordingHash{bytes.NewBuffer(nil)} - c := NewCanonicalTextHash(r) - c.Write([]byte(input)) - result := c.Sum(nil) - if expected != string(result) { - t.Errorf("input: %x got: %x want: %x", input, result, expected) - } -} - -func TestCanonicalText(t *testing.T) { - testCanonicalText(t, "foo\n", "foo\r\n") - testCanonicalText(t, "foo", "foo") - testCanonicalText(t, "foo\r\n", "foo\r\n") - testCanonicalText(t, "foo\r\nbar", "foo\r\nbar") - testCanonicalText(t, "foo\r\nbar\n\n", "foo\r\nbar\r\n\r\n") -} diff --git a/Godeps/_workspace/src/golang.org/x/crypto/openpgp/clearsign/clearsign.go b/Godeps/_workspace/src/golang.org/x/crypto/openpgp/clearsign/clearsign.go index 41a4e4341..256cefa12 100644 --- a/Godeps/_workspace/src/golang.org/x/crypto/openpgp/clearsign/clearsign.go +++ b/Godeps/_workspace/src/golang.org/x/crypto/openpgp/clearsign/clearsign.go @@ -35,7 +35,7 @@ type Block struct { // start is the marker which denotes the beginning of a clearsigned message. var start = []byte("\n-----BEGIN PGP SIGNED MESSAGE-----") -// dashEscape is prefixed to any lines that begin with a hypen so that they +// dashEscape is prefixed to any lines that begin with a hyphen so that they // can't be confused with endText. var dashEscape = []byte("- ") @@ -197,7 +197,17 @@ func (d *dashEscaper) Write(data []byte) (n int, err error) { d.h.Write(crlf) } d.isFirstLine = false + } + // Any whitespace at the end of the line has to be removed so we + // buffer it until we find out whether there's more on this line. + if b == ' ' || b == '\t' || b == '\r' { + d.whitespace = append(d.whitespace, b) + d.atBeginningOfLine = false + continue + } + + if d.atBeginningOfLine { // At the beginning of a line, hyphens have to be escaped. if b == '-' { // The signature isn't calculated over the dash-escaped text so @@ -208,7 +218,7 @@ func (d *dashEscaper) Write(data []byte) (n int, err error) { d.h.Write(d.byteBuf) d.atBeginningOfLine = false } else if b == '\n' { - // Nothing to do because we dely writing CRLF to the hash. + // Nothing to do because we delay writing CRLF to the hash. } else { d.h.Write(d.byteBuf) d.atBeginningOfLine = false @@ -217,15 +227,11 @@ func (d *dashEscaper) Write(data []byte) (n int, err error) { return } } else { - // Any whitespace at the end of the line has to be removed so we - // buffer it until we find out whether there's more on this line. - if b == ' ' || b == '\t' || b == '\r' { - d.whitespace = append(d.whitespace, b) - } else if b == '\n' { + if b == '\n' { // We got a raw \n. Drop any trailing whitespace and write a // CRLF. d.whitespace = d.whitespace[:0] - // We dely writing CRLF to the hash until the start of the + // We delay writing CRLF to the hash until the start of the // next line. if err = d.buffered.WriteByte(b); err != nil { return diff --git a/Godeps/_workspace/src/golang.org/x/crypto/openpgp/clearsign/clearsign_test.go b/Godeps/_workspace/src/golang.org/x/crypto/openpgp/clearsign/clearsign_test.go deleted file mode 100644 index 51538b976..000000000 --- a/Godeps/_workspace/src/golang.org/x/crypto/openpgp/clearsign/clearsign_test.go +++ /dev/null @@ -1,187 +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 clearsign - -import ( - "bytes" - "golang.org/x/crypto/openpgp" - "testing" -) - -func testParse(t *testing.T, input []byte, expected, expectedPlaintext string) { - b, rest := Decode(input) - if b == nil { - t.Fatal("failed to decode clearsign message") - } - if !bytes.Equal(rest, []byte("trailing")) { - t.Errorf("unexpected remaining bytes returned: %s", string(rest)) - } - if b.ArmoredSignature.Type != "PGP SIGNATURE" { - t.Errorf("bad armor type, got:%s, want:PGP SIGNATURE", b.ArmoredSignature.Type) - } - if !bytes.Equal(b.Bytes, []byte(expected)) { - t.Errorf("bad body, got:%x want:%x", b.Bytes, expected) - } - - if !bytes.Equal(b.Plaintext, []byte(expectedPlaintext)) { - t.Errorf("bad plaintext, got:%x want:%x", b.Plaintext, expectedPlaintext) - } - - keyring, err := openpgp.ReadArmoredKeyRing(bytes.NewBufferString(signingKey)) - if err != nil { - t.Errorf("failed to parse public key: %s", err) - } - - if _, err := openpgp.CheckDetachedSignature(keyring, bytes.NewBuffer(b.Bytes), b.ArmoredSignature.Body); err != nil { - t.Errorf("failed to check signature: %s", err) - } -} - -func TestParse(t *testing.T) { - testParse(t, clearsignInput, "Hello world\r\nline 2", "Hello world\nline 2\n") - testParse(t, clearsignInput2, "\r\n\r\n(This message has a couple of blank lines at the start and end.)\r\n\r\n", "\n\n(This message has a couple of blank lines at the start and end.)\n\n\n") -} - -func TestParseWithNoNewlineAtEnd(t *testing.T) { - input := clearsignInput - input = input[:len(input)-len("trailing")-1] - b, rest := Decode(input) - if b == nil { - t.Fatal("failed to decode clearsign message") - } - if len(rest) > 0 { - t.Errorf("unexpected remaining bytes returned: %s", string(rest)) - } -} - -var signingTests = []struct { - in, signed, plaintext string -}{ - {"", "", ""}, - {"a", "a", "a\n"}, - {"a\n", "a", "a\n"}, - {"-a\n", "-a", "-a\n"}, - {"--a\nb", "--a\r\nb", "--a\nb\n"}, -} - -func TestSigning(t *testing.T) { - keyring, err := openpgp.ReadArmoredKeyRing(bytes.NewBufferString(signingKey)) - if err != nil { - t.Errorf("failed to parse public key: %s", err) - } - - for i, test := range signingTests { - var buf bytes.Buffer - - plaintext, err := Encode(&buf, keyring[0].PrivateKey, nil) - if err != nil { - t.Errorf("#%d: error from Encode: %s", i, err) - continue - } - if _, err := plaintext.Write([]byte(test.in)); err != nil { - t.Errorf("#%d: error from Write: %s", i, err) - continue - } - if err := plaintext.Close(); err != nil { - t.Fatalf("#%d: error from Close: %s", i, err) - continue - } - - b, _ := Decode(buf.Bytes()) - if b == nil { - t.Errorf("#%d: failed to decode clearsign message", i) - continue - } - if !bytes.Equal(b.Bytes, []byte(test.signed)) { - t.Errorf("#%d: bad result, got:%x, want:%x", i, b.Bytes, test.signed) - continue - } - if !bytes.Equal(b.Plaintext, []byte(test.plaintext)) { - t.Errorf("#%d: bad result, got:%x, want:%x", i, b.Plaintext, test.plaintext) - continue - } - - if _, err := openpgp.CheckDetachedSignature(keyring, bytes.NewBuffer(b.Bytes), b.ArmoredSignature.Body); err != nil { - t.Errorf("#%d: failed to check signature: %s", i, err) - } - } -} - -var clearsignInput = []byte(` -;lasjlkfdsa - ------BEGIN PGP SIGNED MESSAGE----- -Hash: SHA1 - -Hello world -line 2 ------BEGIN PGP SIGNATURE----- -Version: GnuPG v1.4.10 (GNU/Linux) - -iJwEAQECAAYFAk8kMuEACgkQO9o98PRieSpMsAQAhmY/vwmNpflrPgmfWsYhk5O8 -pjnBUzZwqTDoDeINjZEoPDSpQAHGhjFjgaDx/Gj4fAl0dM4D0wuUEBb6QOrwflog -2A2k9kfSOMOtk0IH/H5VuFN1Mie9L/erYXjTQIptv9t9J7NoRBMU0QOOaFU0JaO9 -MyTpno24AjIAGb+mH1U= -=hIJ6 ------END PGP SIGNATURE----- -trailing`) - -var clearsignInput2 = []byte(` -asdlfkjasdlkfjsadf - ------BEGIN PGP SIGNED MESSAGE----- -Hash: SHA256 - - - -(This message has a couple of blank lines at the start and end.) - - ------BEGIN PGP SIGNATURE----- -Version: GnuPG v1.4.11 (GNU/Linux) - -iJwEAQEIAAYFAlPpSREACgkQO9o98PRieSpZTAP+M8QUoCt/7Rf3YbXPcdzIL32v -pt1I+cMNeopzfLy0u4ioEFi8s5VkwpL1AFmirvgViCwlf82inoRxzZRiW05JQ5LI -ESEzeCoy2LIdRCQ2hcrG8pIUPzUO4TqO5D/dMbdHwNH4h5nNmGJUAEG6FpURlPm+ -qZg6BaTvOxepqOxnhVU= -=e+C6 ------END PGP SIGNATURE----- - -trailing`) - -var signingKey = `-----BEGIN PGP PRIVATE KEY BLOCK----- -Version: GnuPG v1.4.10 (GNU/Linux) - -lQHYBE2rFNoBBADFwqWQIW/DSqcB4yCQqnAFTJ27qS5AnB46ccAdw3u4Greeu3Bp -idpoHdjULy7zSKlwR1EA873dO/k/e11Ml3dlAFUinWeejWaK2ugFP6JjiieSsrKn -vWNicdCS4HTWn0X4sjl0ZiAygw6GNhqEQ3cpLeL0g8E9hnYzJKQ0LWJa0QARAQAB -AAP/TB81EIo2VYNmTq0pK1ZXwUpxCrvAAIG3hwKjEzHcbQznsjNvPUihZ+NZQ6+X -0HCfPAdPkGDCLCb6NavcSW+iNnLTrdDnSI6+3BbIONqWWdRDYJhqZCkqmG6zqSfL -IdkJgCw94taUg5BWP/AAeQrhzjChvpMQTVKQL5mnuZbUCeMCAN5qrYMP2S9iKdnk -VANIFj7656ARKt/nf4CBzxcpHTyB8+d2CtPDKCmlJP6vL8t58Jmih+kHJMvC0dzn -gr5f5+sCAOOe5gt9e0am7AvQWhdbHVfJU0TQJx+m2OiCJAqGTB1nvtBLHdJnfdC9 -TnXXQ6ZXibqLyBies/xeY2sCKL5qtTMCAKnX9+9d/5yQxRyrQUHt1NYhaXZnJbHx -q4ytu0eWz+5i68IYUSK69jJ1NWPM0T6SkqpB3KCAIv68VFm9PxqG1KmhSrQIVGVz -dCBLZXmIuAQTAQIAIgUCTasU2gIbAwYLCQgHAwIGFQgCCQoLBBYCAwECHgECF4AA -CgkQO9o98PRieSoLhgQAkLEZex02Qt7vGhZzMwuN0R22w3VwyYyjBx+fM3JFETy1 -ut4xcLJoJfIaF5ZS38UplgakHG0FQ+b49i8dMij0aZmDqGxrew1m4kBfjXw9B/v+ -eIqpODryb6cOSwyQFH0lQkXC040pjq9YqDsO5w0WYNXYKDnzRV0p4H1pweo2VDid -AdgETasU2gEEAN46UPeWRqKHvA99arOxee38fBt2CI08iiWyI8T3J6ivtFGixSqV -bRcPxYO/qLpVe5l84Nb3X71GfVXlc9hyv7CD6tcowL59hg1E/DC5ydI8K8iEpUmK -/UnHdIY5h8/kqgGxkY/T/hgp5fRQgW1ZoZxLajVlMRZ8W4tFtT0DeA+JABEBAAEA -A/0bE1jaaZKj6ndqcw86jd+QtD1SF+Cf21CWRNeLKnUds4FRRvclzTyUMuWPkUeX -TaNNsUOFqBsf6QQ2oHUBBK4VCHffHCW4ZEX2cd6umz7mpHW6XzN4DECEzOVksXtc -lUC1j4UB91DC/RNQqwX1IV2QLSwssVotPMPqhOi0ZLNY7wIA3n7DWKInxYZZ4K+6 -rQ+POsz6brEoRHwr8x6XlHenq1Oki855pSa1yXIARoTrSJkBtn5oI+f8AzrnN0BN -oyeQAwIA/7E++3HDi5aweWrViiul9cd3rcsS0dEnksPhvS0ozCJiHsq/6GFmy7J8 -QSHZPteedBnZyNp5jR+H7cIfVN3KgwH/Skq4PsuPhDq5TKK6i8Pc1WW8MA6DXTdU -nLkX7RGmMwjC0DBf7KWAlPjFaONAX3a8ndnz//fy1q7u2l9AZwrj1qa1iJ8EGAEC -AAkFAk2rFNoCGwwACgkQO9o98PRieSo2/QP/WTzr4ioINVsvN1akKuekmEMI3LAp -BfHwatufxxP1U+3Si/6YIk7kuPB9Hs+pRqCXzbvPRrI8NHZBmc8qIGthishdCYad -AHcVnXjtxrULkQFGbGvhKURLvS9WnzD/m1K2zzwxzkPTzT9/Yf06O6Mal5AdugPL -VrM0m72/jnpKo04= -=zNCn ------END PGP PRIVATE KEY BLOCK----- -` diff --git a/Godeps/_workspace/src/golang.org/x/crypto/openpgp/elgamal/elgamal_test.go b/Godeps/_workspace/src/golang.org/x/crypto/openpgp/elgamal/elgamal_test.go deleted file mode 100644 index c4f99f5c4..000000000 --- a/Godeps/_workspace/src/golang.org/x/crypto/openpgp/elgamal/elgamal_test.go +++ /dev/null @@ -1,49 +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 elgamal - -import ( - "bytes" - "crypto/rand" - "math/big" - "testing" -) - -// This is the 1024-bit MODP group from RFC 5114, section 2.1: -const primeHex = "B10B8F96A080E01DDE92DE5EAE5D54EC52C99FBCFB06A3C69A6A9DCA52D23B616073E28675A23D189838EF1E2EE652C013ECB4AEA906112324975C3CD49B83BFACCBDD7D90C4BD7098488E9C219A73724EFFD6FAE5644738FAA31A4FF55BCCC0A151AF5F0DC8B4BD45BF37DF365C1A65E68CFDA76D4DA708DF1FB2BC2E4A4371" - -const generatorHex = "A4D1CBD5C3FD34126765A442EFB99905F8104DD258AC507FD6406CFF14266D31266FEA1E5C41564B777E690F5504F213160217B4B01B886A5E91547F9E2749F4D7FBD7D3B9A92EE1909D0D2263F80A76A6A24C087A091F531DBF0A0169B6A28AD662A4D18E73AFA32D779D5918D08BC8858F4DCEF97C2A24855E6EEB22B3B2E5" - -func fromHex(hex string) *big.Int { - n, ok := new(big.Int).SetString(hex, 16) - if !ok { - panic("failed to parse hex number") - } - return n -} - -func TestEncryptDecrypt(t *testing.T) { - priv := &PrivateKey{ - PublicKey: PublicKey{ - G: fromHex(generatorHex), - P: fromHex(primeHex), - }, - X: fromHex("42"), - } - priv.Y = new(big.Int).Exp(priv.G, priv.X, priv.P) - - message := []byte("hello world") - c1, c2, err := Encrypt(rand.Reader, &priv.PublicKey, message) - if err != nil { - t.Errorf("error encrypting: %s", err) - } - message2, err := Decrypt(priv, c1, c2) - if err != nil { - t.Errorf("error decrypting: %s", err) - } - if !bytes.Equal(message2, message) { - t.Errorf("decryption failed, got: %x, want: %x", message2, message) - } -} diff --git a/Godeps/_workspace/src/golang.org/x/crypto/openpgp/keys_test.go b/Godeps/_workspace/src/golang.org/x/crypto/openpgp/keys_test.go deleted file mode 100644 index d5e2056bb..000000000 --- a/Godeps/_workspace/src/golang.org/x/crypto/openpgp/keys_test.go +++ /dev/null @@ -1,370 +0,0 @@ -package openpgp - -import ( - "bytes" - "strings" - "testing" - "time" - - "golang.org/x/crypto/openpgp/errors" - "golang.org/x/crypto/openpgp/packet" -) - -func TestKeyExpiry(t *testing.T) { - kring, _ := ReadKeyRing(readerFromHex(expiringKeyHex)) - entity := kring[0] - - const timeFormat = "2006-01-02" - time1, _ := time.Parse(timeFormat, "2013-07-01") - - // The expiringKeyHex key is structured as: - // - // pub 1024R/5E237D8C created: 2013-07-01 expires: 2013-07-31 usage: SC - // sub 1024R/1ABB25A0 created: 2013-07-01 23:11:07 +0200 CEST expires: 2013-07-08 usage: E - // sub 1024R/96A672F5 created: 2013-07-01 23:11:23 +0200 CEST expires: 2013-07-31 usage: E - // - // So this should select the newest, non-expired encryption key. - key, _ := entity.encryptionKey(time1) - if id := key.PublicKey.KeyIdShortString(); id != "96A672F5" { - t.Errorf("Expected key 1ABB25A0 at time %s, but got key %s", time1.Format(timeFormat), id) - } - - // Once the first encryption subkey has expired, the second should be - // selected. - time2, _ := time.Parse(timeFormat, "2013-07-09") - key, _ = entity.encryptionKey(time2) - if id := key.PublicKey.KeyIdShortString(); id != "96A672F5" { - t.Errorf("Expected key 96A672F5 at time %s, but got key %s", time2.Format(timeFormat), id) - } - - // Once all the keys have expired, nothing should be returned. - time3, _ := time.Parse(timeFormat, "2013-08-01") - if key, ok := entity.encryptionKey(time3); ok { - t.Errorf("Expected no key at time %s, but got key %s", time3.Format(timeFormat), key.PublicKey.KeyIdShortString()) - } -} - -func TestMissingCrossSignature(t *testing.T) { - // This public key has a signing subkey, but the subkey does not - // contain a cross-signature. - keys, err := ReadArmoredKeyRing(bytes.NewBufferString(missingCrossSignatureKey)) - if len(keys) != 0 { - t.Errorf("Accepted key with missing cross signature") - } - if err == nil { - t.Fatal("Failed to detect error in keyring with missing cross signature") - } - structural, ok := err.(errors.StructuralError) - if !ok { - t.Fatalf("Unexpected class of error: %T. Wanted StructuralError", err) - } - const expectedMsg = "signing subkey is missing cross-signature" - if !strings.Contains(string(structural), expectedMsg) { - t.Fatalf("Unexpected error: %q. Expected it to contain %q", err, expectedMsg) - } -} - -func TestInvalidCrossSignature(t *testing.T) { - // This public key has a signing subkey, and the subkey has an - // embedded cross-signature. However, the cross-signature does - // not correctly validate over the primary and subkey. - keys, err := ReadArmoredKeyRing(bytes.NewBufferString(invalidCrossSignatureKey)) - if len(keys) != 0 { - t.Errorf("Accepted key with invalid cross signature") - } - if err == nil { - t.Fatal("Failed to detect error in keyring with an invalid cross signature") - } - structural, ok := err.(errors.StructuralError) - if !ok { - t.Fatalf("Unexpected class of error: %T. Wanted StructuralError", err) - } - const expectedMsg = "subkey signature invalid" - if !strings.Contains(string(structural), expectedMsg) { - t.Fatalf("Unexpected error: %q. Expected it to contain %q", err, expectedMsg) - } -} - -func TestGoodCrossSignature(t *testing.T) { - // This public key has a signing subkey, and the subkey has an - // embedded cross-signature which correctly validates over the - // primary and subkey. - keys, err := ReadArmoredKeyRing(bytes.NewBufferString(goodCrossSignatureKey)) - if err != nil { - t.Fatal(err) - } - if len(keys) != 1 { - t.Errorf("Failed to accept key with good cross signature, %d", len(keys)) - } - if len(keys[0].Subkeys) != 1 { - t.Errorf("Failed to accept good subkey, %d", len(keys[0].Subkeys)) - } -} - -// TestExternallyRevokableKey attempts to load and parse a key with a third party revocation permission. -func TestExternallyRevocableKey(t *testing.T) { - kring, _ := ReadKeyRing(readerFromHex(subkeyUsageHex)) - - // The 0xA42704B92866382A key can be revoked by 0xBE3893CB843D0FE70C - // according to this signature that appears within the key: - // :signature packet: algo 1, keyid A42704B92866382A - // version 4, created 1396409682, md5len 0, sigclass 0x1f - // digest algo 2, begin of digest a9 84 - // hashed subpkt 2 len 4 (sig created 2014-04-02) - // hashed subpkt 12 len 22 (revocation key: c=80 a=1 f=CE094AA433F7040BB2DDF0BE3893CB843D0FE70C) - // hashed subpkt 7 len 1 (not revocable) - // subpkt 16 len 8 (issuer key ID A42704B92866382A) - // data: [1024 bits] - - id := uint64(0xA42704B92866382A) - keys := kring.KeysById(id) - if len(keys) != 1 { - t.Errorf("Expected to find key id %X, but got %d matches", id, len(keys)) - } -} - -func TestKeyRevocation(t *testing.T) { - kring, _ := ReadKeyRing(readerFromHex(revokedKeyHex)) - - // revokedKeyHex contains these keys: - // pub 1024R/9A34F7C0 2014-03-25 [revoked: 2014-03-25] - // sub 1024R/1BA3CD60 2014-03-25 [revoked: 2014-03-25] - ids := []uint64{0xA401D9F09A34F7C0, 0x5CD3BE0A1BA3CD60} - - for _, id := range ids { - keys := kring.KeysById(id) - if len(keys) != 1 { - t.Errorf("Expected KeysById to find revoked key %X, but got %d matches", id, len(keys)) - } - keys = kring.KeysByIdUsage(id, 0) - if len(keys) != 0 { - t.Errorf("Expected KeysByIdUsage to filter out revoked key %X, but got %d matches", id, len(keys)) - } - } -} - -func TestSubkeyRevocation(t *testing.T) { - kring, _ := ReadKeyRing(readerFromHex(revokedSubkeyHex)) - - // revokedSubkeyHex contains these keys: - // pub 1024R/4EF7E4BECCDE97F0 2014-03-25 - // sub 1024R/D63636E2B96AE423 2014-03-25 - // sub 1024D/DBCE4EE19529437F 2014-03-25 - // sub 1024R/677815E371C2FD23 2014-03-25 [revoked: 2014-03-25] - validKeys := []uint64{0x4EF7E4BECCDE97F0, 0xD63636E2B96AE423, 0xDBCE4EE19529437F} - revokedKey := uint64(0x677815E371C2FD23) - - for _, id := range validKeys { - keys := kring.KeysById(id) - if len(keys) != 1 { - t.Errorf("Expected KeysById to find key %X, but got %d matches", id, len(keys)) - } - keys = kring.KeysByIdUsage(id, 0) - if len(keys) != 1 { - t.Errorf("Expected KeysByIdUsage to find key %X, but got %d matches", id, len(keys)) - } - } - - keys := kring.KeysById(revokedKey) - if len(keys) != 1 { - t.Errorf("Expected KeysById to find key %X, but got %d matches", revokedKey, len(keys)) - } - - keys = kring.KeysByIdUsage(revokedKey, 0) - if len(keys) != 0 { - t.Errorf("Expected KeysByIdUsage to filter out revoked key %X, but got %d matches", revokedKey, len(keys)) - } -} - -func TestKeyUsage(t *testing.T) { - kring, _ := ReadKeyRing(readerFromHex(subkeyUsageHex)) - - // subkeyUsageHex contains these keys: - // pub 1024R/2866382A created: 2014-04-01 expires: never usage: SC - // sub 1024R/936C9153 created: 2014-04-01 expires: never usage: E - // sub 1024R/64D5F5BB created: 2014-04-02 expires: never usage: E - // sub 1024D/BC0BA992 created: 2014-04-02 expires: never usage: S - certifiers := []uint64{0xA42704B92866382A} - signers := []uint64{0xA42704B92866382A, 0x42CE2C64BC0BA992} - encrypters := []uint64{0x09C0C7D9936C9153, 0xC104E98664D5F5BB} - - for _, id := range certifiers { - keys := kring.KeysByIdUsage(id, packet.KeyFlagCertify) - if len(keys) == 1 { - if keys[0].PublicKey.KeyId != id { - t.Errorf("Expected to find certifier key id %X, but got %X", id, keys[0].PublicKey.KeyId) - } - } else { - t.Errorf("Expected one match for certifier key id %X, but got %d matches", id, len(keys)) - } - } - - for _, id := range signers { - keys := kring.KeysByIdUsage(id, packet.KeyFlagSign) - if len(keys) == 1 { - if keys[0].PublicKey.KeyId != id { - t.Errorf("Expected to find signing key id %X, but got %X", id, keys[0].PublicKey.KeyId) - } - } else { - t.Errorf("Expected one match for signing key id %X, but got %d matches", id, len(keys)) - } - - // This keyring contains no encryption keys that are also good for signing. - keys = kring.KeysByIdUsage(id, packet.KeyFlagEncryptStorage|packet.KeyFlagEncryptCommunications) - if len(keys) != 0 { - t.Errorf("Unexpected match for encryption key id %X", id) - } - } - - for _, id := range encrypters { - keys := kring.KeysByIdUsage(id, packet.KeyFlagEncryptStorage|packet.KeyFlagEncryptCommunications) - if len(keys) == 1 { - if keys[0].PublicKey.KeyId != id { - t.Errorf("Expected to find encryption key id %X, but got %X", id, keys[0].PublicKey.KeyId) - } - } else { - t.Errorf("Expected one match for encryption key id %X, but got %d matches", id, len(keys)) - } - - // This keyring contains no encryption keys that are also good for signing. - keys = kring.KeysByIdUsage(id, packet.KeyFlagSign) - if len(keys) != 0 { - t.Errorf("Unexpected match for signing key id %X", id) - } - } -} - -func TestIdVerification(t *testing.T) { - kring, err := ReadKeyRing(readerFromHex(testKeys1And2PrivateHex)) - if err != nil { - t.Fatal(err) - } - if err := kring[1].PrivateKey.Decrypt([]byte("passphrase")); err != nil { - t.Fatal(err) - } - - const identity = "Test Key 1 (RSA)" - if err := kring[0].SignIdentity(identity, kring[1], nil); err != nil { - t.Fatal(err) - } - - ident, ok := kring[0].Identities[identity] - if !ok { - t.Fatal("identity missing from key after signing") - } - - checked := false - for _, sig := range ident.Signatures { - if sig.IssuerKeyId == nil || *sig.IssuerKeyId != kring[1].PrimaryKey.KeyId { - continue - } - - if err := kring[1].PrimaryKey.VerifyUserIdSignature(identity, kring[0].PrimaryKey, sig); err != nil { - t.Fatalf("error verifying new identity signature: %s", err) - } - checked = true - break - } - - if !checked { - t.Fatal("didn't find identity signature in Entity") - } -} - -const expiringKeyHex = "988d0451d1ec5d010400ba3385721f2dc3f4ab096b2ee867ab77213f0a27a8538441c35d2fa225b08798a1439a66a5150e6bdc3f40f5d28d588c712394c632b6299f77db8c0d48d37903fb72ebd794d61be6aa774688839e5fdecfe06b2684cc115d240c98c66cb1ef22ae84e3aa0c2b0c28665c1e7d4d044e7f270706193f5223c8d44e0d70b7b8da830011010001b40f4578706972792074657374206b657988be041301020028050251d1ec5d021b03050900278d00060b090807030206150802090a0b0416020301021e01021780000a091072589ad75e237d8c033503fd10506d72837834eb7f994117740723adc39227104b0d326a1161871c0b415d25b4aedef946ca77ea4c05af9c22b32cf98be86ab890111fced1ee3f75e87b7cc3c00dc63bbc85dfab91c0dc2ad9de2c4d13a34659333a85c6acc1a669c5e1d6cecb0cf1e56c10e72d855ae177ddc9e766f9b2dda57ccbb75f57156438bbdb4e42b88d0451d1ec5d0104009c64906559866c5cb61578f5846a94fcee142a489c9b41e67b12bb54cfe86eb9bc8566460f9a720cb00d6526fbccfd4f552071a8e3f7744b1882d01036d811ee5a3fb91a1c568055758f43ba5d2c6a9676b012f3a1a89e47bbf624f1ad571b208f3cc6224eb378f1645dd3d47584463f9eadeacfd1ce6f813064fbfdcc4b5a53001101000188a504180102000f021b0c050251d1f06b050900093e89000a091072589ad75e237d8c20e00400ab8310a41461425b37889c4da28129b5fae6084fafbc0a47dd1adc74a264c6e9c9cc125f40462ee1433072a58384daef88c961c390ed06426a81b464a53194c4e291ddd7e2e2ba3efced01537d713bd111f48437bde2363446200995e8e0d4e528dda377fd1e8f8ede9c8e2198b393bd86852ce7457a7e3daf74d510461a5b77b88d0451d1ece8010400b3a519f83ab0010307e83bca895170acce8964a044190a2b368892f7a244758d9fc193482648acb1fb9780d28cc22d171931f38bb40279389fc9bf2110876d4f3db4fcfb13f22f7083877fe56592b3b65251312c36f83ffcb6d313c6a17f197dd471f0712aad15a8537b435a92471ba2e5b0c72a6c72536c3b567c558d7b6051001101000188a504180102000f021b0c050251d1f07b050900279091000a091072589ad75e237d8ce69e03fe286026afacf7c97ee20673864d4459a2240b5655219950643c7dba0ac384b1d4359c67805b21d98211f7b09c2a0ccf6410c8c04d4ff4a51293725d8d6570d9d8bb0e10c07d22357caeb49626df99c180be02d77d1fe8ed25e7a54481237646083a9f89a11566cd20b9e995b1487c5f9e02aeb434f3a1897cd416dd0a87861838da3e9e" -const subkeyUsageHex = "988d04533a52bc010400d26af43085558f65b9e7dbc90cb9238015259aed5e954637adcfa2181548b2d0b60c65f1f42ec5081cbf1bc0a8aa4900acfb77070837c58f26012fbce297d70afe96e759ad63531f0037538e70dbf8e384569b9720d99d8eb39d8d0a2947233ed242436cb6ac7dfe74123354b3d0119b5c235d3dd9c9d6c004f8ffaf67ad8583001101000188b7041f010200210502533b8552170c8001ce094aa433f7040bb2ddf0be3893cb843d0fe70c020700000a0910a42704b92866382aa98404009d63d916a27543da4221c60087c33f1c44bec9998c5438018ed370cca4962876c748e94b73eb39c58eb698063f3fd6346d58dd2a11c0247934c4a9d71f24754f7468f96fb24c3e791dd2392b62f626148ad724189498cbf993db2df7c0cdc2d677c35da0f16cb16c9ce7c33b4de65a4a91b1d21a130ae9cc26067718910ef8e2b417556d627261203c756d627261407379642e65642e61753e88b80413010200220502533a52bc021b03060b090807030206150802090a0b0416020301021e01021780000a0910a42704b92866382a47840400c0c2bd04f5fca586de408b395b3c280a278259c93eaaa8b79a53b97003f8ed502a8a00446dd9947fb462677e4fcac0dac2f0701847d15130aadb6cd9e0705ea0cf5f92f129136c7be21a718d46c8e641eb7f044f2adae573e11ae423a0a9ca51324f03a8a2f34b91fa40c3cc764bee4dccadedb54c768ba0469b683ea53f1c29b88d04533a52bc01040099c92a5d6f8b744224da27bc2369127c35269b58bec179de6bbc038f749344222f85a31933224f26b70243c4e4b2d242f0c4777eaef7b5502f9dad6d8bf3aaeb471210674b74de2d7078af497d55f5cdad97c7bedfbc1b41e8065a97c9c3d344b21fc81d27723af8e374bc595da26ea242dccb6ae497be26eea57e563ed517e90011010001889f0418010200090502533a52bc021b0c000a0910a42704b92866382afa1403ff70284c2de8a043ff51d8d29772602fa98009b7861c540535f874f2c230af8caf5638151a636b21f8255003997ccd29747fdd06777bb24f9593bd7d98a3e887689bf902f999915fcc94625ae487e5d13e6616f89090ebc4fdc7eb5cad8943e4056995bb61c6af37f8043016876a958ec7ebf39c43d20d53b7f546cfa83e8d2604b88d04533b8283010400c0b529316dbdf58b4c54461e7e669dc11c09eb7f73819f178ccd4177b9182b91d138605fcf1e463262fabefa73f94a52b5e15d1904635541c7ea540f07050ce0fb51b73e6f88644cec86e91107c957a114f69554548a85295d2b70bd0b203992f76eb5d493d86d9eabcaa7ef3fc7db7e458438db3fcdb0ca1cc97c638439a9170011010001889f0418010200090502533b8283021b0c000a0910a42704b92866382adc6d0400cfff6258485a21675adb7a811c3e19ebca18851533f75a7ba317950b9997fda8d1a4c8c76505c08c04b6c2cc31dc704d33da36a21273f2b388a1a706f7c3378b66d887197a525936ed9a69acb57fe7f718133da85ec742001c5d1864e9c6c8ea1b94f1c3759cebfd93b18606066c063a63be86085b7e37bdbc65f9a915bf084bb901a204533b85cd110400aed3d2c52af2b38b5b67904b0ef73d6dd7aef86adb770e2b153cd22489654dcc91730892087bb9856ae2d9f7ed1eb48f214243fe86bfe87b349ebd7c30e630e49c07b21fdabf78b7a95c8b7f969e97e3d33f2e074c63552ba64a2ded7badc05ce0ea2be6d53485f6900c7860c7aa76560376ce963d7271b9b54638a4028b573f00a0d8854bfcdb04986141568046202192263b9b67350400aaa1049dbc7943141ef590a70dcb028d730371d92ea4863de715f7f0f16d168bd3dc266c2450457d46dcbbf0b071547e5fbee7700a820c3750b236335d8d5848adb3c0da010e998908dfd93d961480084f3aea20b247034f8988eccb5546efaa35a92d0451df3aaf1aee5aa36a4c4d462c760ecd9cebcabfbe1412b1f21450f203fd126687cd486496e971a87fd9e1a8a765fe654baa219a6871ab97768596ab05c26c1aeea8f1a2c72395a58dbc12ef9640d2b95784e974a4d2d5a9b17c25fedacfe551bda52602de8f6d2e48443f5dd1a2a2a8e6a5e70ecdb88cd6e766ad9745c7ee91d78cc55c3d06536b49c3fee6c3d0b6ff0fb2bf13a314f57c953b8f4d93bf88e70418010200090502533b85cd021b0200520910a42704b92866382a47200419110200060502533b85cd000a091042ce2c64bc0ba99214b2009e26b26852c8b13b10c35768e40e78fbbb48bd084100a0c79d9ea0844fa5853dd3c85ff3ecae6f2c9dd6c557aa04008bbbc964cd65b9b8299d4ebf31f41cc7264b8cf33a00e82c5af022331fac79efc9563a822497ba012953cefe2629f1242fcdcb911dbb2315985bab060bfd58261ace3c654bdbbe2e8ed27a46e836490145c86dc7bae15c011f7e1ffc33730109b9338cd9f483e7cef3d2f396aab5bd80efb6646d7e778270ee99d934d187dd98" -const revokedKeyHex = "988d045331ce82010400c4fdf7b40a5477f206e6ee278eaef888ca73bf9128a9eef9f2f1ddb8b7b71a4c07cfa241f028a04edb405e4d916c61d6beabc333813dc7b484d2b3c52ee233c6a79b1eea4e9cc51596ba9cd5ac5aeb9df62d86ea051055b79d03f8a4fa9f38386f5bd17529138f3325d46801514ea9047977e0829ed728e68636802796801be10011010001889f04200102000905025331d0e3021d03000a0910a401d9f09a34f7c042aa040086631196405b7e6af71026b88e98012eab44aa9849f6ef3fa930c7c9f23deaedba9db1538830f8652fb7648ec3fcade8dbcbf9eaf428e83c6cbcc272201bfe2fbb90d41963397a7c0637a1a9d9448ce695d9790db2dc95433ad7be19eb3de72dacf1d6db82c3644c13eae2a3d072b99bb341debba012c5ce4006a7d34a1f4b94b444526567205265766f6b657220283c52656727732022424d204261726973746122204b657920262530305c303e5c29203c72656740626d626172697374612e636f2e61753e88b704130102002205025331ce82021b03060b090807030206150802090a0b0416020301021e01021780000a0910a401d9f09a34f7c0019c03f75edfbeb6a73e7225ad3cc52724e2872e04260d7daf0d693c170d8c4b243b8767bc7785763533febc62ec2600c30603c433c095453ede59ff2fcabeb84ce32e0ed9d5cf15ffcbc816202b64370d4d77c1e9077d74e94a16fb4fa2e5bec23a56d7a73cf275f91691ae1801a976fcde09e981a2f6327ac27ea1fecf3185df0d56889c04100102000605025331cfb5000a0910fe9645554e8266b64b4303fc084075396674fb6f778d302ac07cef6bc0b5d07b66b2004c44aef711cbac79617ef06d836b4957522d8772dd94bf41a2f4ac8b1ee6d70c57503f837445a74765a076d07b829b8111fc2a918423ddb817ead7ca2a613ef0bfb9c6b3562aec6c3cf3c75ef3031d81d95f6563e4cdcc9960bcb386c5d757b104fcca5fe11fc709df884604101102000605025331cfe7000a09107b15a67f0b3ddc0317f6009e360beea58f29c1d963a22b962b80788c3fa6c84e009d148cfde6b351469b8eae91187eff07ad9d08fcaab88d045331ce820104009f25e20a42b904f3fa555530fe5c46737cf7bd076c35a2a0d22b11f7e0b61a69320b768f4a80fe13980ce380d1cfc4a0cd8fbe2d2e2ef85416668b77208baa65bf973fe8e500e78cc310d7c8705cdb34328bf80e24f0385fce5845c33bc7943cf6b11b02348a23da0bf6428e57c05135f2dc6bd7c1ce325d666d5a5fd2fd5e410011010001889f04180102000905025331ce82021b0c000a0910a401d9f09a34f7c0418003fe34feafcbeaef348a800a0d908a7a6809cc7304017d820f70f0474d5e23cb17e38b67dc6dca282c6ca00961f4ec9edf2738d0f087b1d81e4871ef08e1798010863afb4eac4c44a376cb343be929c5be66a78cfd4456ae9ec6a99d97f4e1c3ff3583351db2147a65c0acef5c003fb544ab3a2e2dc4d43646f58b811a6c3a369d1f" -const revokedSubkeyHex = "988d04533121f6010400aefc803a3e4bb1a61c86e8a86d2726c6a43e0079e9f2713f1fa017e9854c83877f4aced8e331d675c67ea83ddab80aacbfa0b9040bb12d96f5a3d6be09455e2a76546cbd21677537db941cab710216b6d24ec277ee0bd65b910f416737ed120f6b93a9d3b306245c8cfd8394606fdb462e5cf43c551438d2864506c63367fc890011010001b41d416c696365203c616c69636540626d626172697374612e636f2e61753e88bb041301020025021b03060b090807030206150802090a0b0416020301021e01021780050253312798021901000a09104ef7e4beccde97f015a803ff5448437780f63263b0df8442a995e7f76c221351a51edd06f2063d8166cf3157aada4923dfc44aa0f2a6a4da5cf83b7fe722ba8ab416c976e77c6b5682e7f1069026673bd0de56ba06fd5d7a9f177607f277d9b55ff940a638c3e68525c67517e2b3d976899b93ca267f705b3e5efad7d61220e96b618a4497eab8d04403d23f8846041011020006050253312910000a09107b15a67f0b3ddc03d96e009f50b6365d86c4be5d5e9d0ea42d5e56f5794c617700a0ab274e19c2827780016d23417ce89e0a2c0d987d889c04100102000605025331cf7a000a0910a401d9f09a34f7c0ee970400aca292f213041c9f3b3fc49148cbda9d84afee6183c8dd6c5ff2600b29482db5fecd4303797be1ee6d544a20a858080fec43412061c9a71fae4039fd58013b4ae341273e6c66ad4c7cdd9e68245bedb260562e7b166f2461a1032f2b38c0e0e5715fb3d1656979e052b55ca827a76f872b78a9fdae64bc298170bfcebedc1271b41a416c696365203c616c696365407379646973702e6f722e61753e88b804130102002205025331278b021b03060b090807030206150802090a0b0416020301021e01021780000a09104ef7e4beccde97f06a7003fa03c3af68d272ebc1fa08aa72a03b02189c26496a2833d90450801c4e42c5b5f51ad96ce2d2c9cef4b7c02a6a2fcf1412d6a2d486098eb762f5010a201819c17fd2888aec8eda20c65a3b75744de7ee5cc8ac7bfc470cbe3cb982720405a27a3c6a8c229cfe36905f881b02ed5680f6a8f05866efb9d6c5844897e631deb949ca8846041011020006050253312910000a09107b15a67f0b3ddc0347bc009f7fa35db59147469eb6f2c5aaf6428accb138b22800a0caa2f5f0874bacc5909c652a57a31beda65eddd5889c04100102000605025331cf7a000a0910a401d9f09a34f7c0316403ff46f2a5c101256627f16384d34a38fb47a6c88ba60506843e532d91614339fccae5f884a5741e7582ffaf292ba38ee10a270a05f139bde3814b6a077e8cd2db0f105ebea2a83af70d385f13b507fac2ad93ff79d84950328bb86f3074745a8b7f9b64990fb142e2a12976e27e8d09a28dc5621f957ac49091116da410ac3cbde1b88d04533121f6010400cbd785b56905e4192e2fb62a720727d43c4fa487821203cf72138b884b78b701093243e1d8c92a0248a6c0203a5a88693da34af357499abacaf4b3309c640797d03093870a323b4b6f37865f6eaa2838148a67df4735d43a90ca87942554cdf1c4a751b1e75f9fd4ce4e97e278d6c1c7ed59d33441df7d084f3f02beb68896c70011010001889f0418010200090502533121f6021b0c000a09104ef7e4beccde97f0b98b03fc0a5ccf6a372995835a2f5da33b282a7d612c0ab2a97f59cf9fff73e9110981aac2858c41399afa29624a7fd8a0add11654e3d882c0fd199e161bdad65e5e2548f7b68a437ea64293db1246e3011cbb94dc1bcdeaf0f2539bd88ff16d95547144d97cead6a8c5927660a91e6db0d16eb36b7b49a3525b54d1644e65599b032b7eb901a204533127a0110400bd3edaa09eff9809c4edc2c2a0ebe52e53c50a19c1e49ab78e6167bf61473bb08f2050d78a5cbbc6ed66aff7b42cd503f16b4a0b99fa1609681fca9b7ce2bbb1a5b3864d6cdda4d7ef7849d156d534dea30fb0efb9e4cf8959a2b2ce623905882d5430b995a15c3b9fe92906086788b891002924f94abe139b42cbbfaaabe42f00a0b65dc1a1ad27d798adbcb5b5ad02d2688c89477b03ff4eebb6f7b15a73b96a96bed201c0e5e4ea27e4c6e2dd1005b94d4b90137a5b1cf5e01c6226c070c4cc999938101578877ee76d296b9aab8246d57049caacf489e80a3f40589cade790a020b1ac146d6f7a6241184b8c7fcde680eae3188f5dcbe846d7f7bdad34f6fcfca08413e19c1d5df83fc7c7c627d493492e009c2f52a80400a2fe82de87136fd2e8845888c4431b032ba29d9a29a804277e31002a8201fb8591a3e55c7a0d0881496caf8b9fb07544a5a4879291d0dc026a0ea9e5bd88eb4aa4947bbd694b25012e208a250d65ddc6f1eea59d3aed3b4ec15fcab85e2afaa23a40ab1ef9ce3e11e1bc1c34a0e758e7aa64deb8739276df0af7d4121f834a9b88e70418010200090502533127a0021b02005209104ef7e4beccde97f047200419110200060502533127a0000a0910dbce4ee19529437fe045009c0b32f5ead48ee8a7e98fac0dea3d3e6c0e2c552500a0ad71fadc5007cfaf842d9b7db3335a8cdad15d3d1a6404009b08e2c68fe8f3b45c1bb72a4b3278cdf3012aa0f229883ad74aa1f6000bb90b18301b2f85372ca5d6b9bf478d235b733b1b197d19ccca48e9daf8e890cb64546b4ce1b178faccfff07003c172a2d4f5ebaba9f57153955f3f61a9b80a4f5cb959908f8b211b03b7026a8a82fc612bfedd3794969bcf458c4ce92be215a1176ab88d045331d144010400a5063000c5aaf34953c1aa3bfc95045b3aab9882b9a8027fecfe2142dc6b47ba8aca667399990244d513dd0504716908c17d92c65e74219e004f7b83fc125e575dd58efec3ab6dd22e3580106998523dea42ec75bf9aa111734c82df54630bebdff20fe981cfc36c76f865eb1c2fb62c9e85bc3a6e5015a361a2eb1c8431578d0011010001889f04280102000905025331d433021d03000a09104ef7e4beccde97f02e5503ff5e0630d1b65291f4882b6d40a29da4616bb5088717d469fbcc3648b8276de04a04988b1f1b9f3e18f52265c1f8b6c85861691c1a6b8a3a25a1809a0b32ad330aec5667cb4262f4450649184e8113849b05e5ad06a316ea80c001e8e71838190339a6e48bbde30647bcf245134b9a97fa875c1d83a9862cae87ffd7e2c4ce3a1b89013d04180102000905025331d144021b0200a809104ef7e4beccde97f09d2004190102000605025331d144000a0910677815e371c2fd23522203fe22ab62b8e7a151383cea3edd3a12995693911426f8ccf125e1f6426388c0010f88d9ca7da2224aee8d1c12135998640c5e1813d55a93df472faae75bef858457248db41b4505827590aeccf6f9eb646da7f980655dd3050c6897feddddaca90676dee856d66db8923477d251712bb9b3186b4d0114daf7d6b59272b53218dd1da94a03ff64006fcbe71211e5daecd9961fba66cdb6de3f914882c58ba5beddeba7dcb950c1156d7fba18c19ea880dccc800eae335deec34e3b84ac75ffa24864f782f87815cda1c0f634b3dd2fa67cea30811d21723d21d9551fa12ccbcfa62b6d3a15d01307b99925707992556d50065505b090aadb8579083a20fe65bd2a270da9b011" -const missingCrossSignatureKey = `-----BEGIN PGP PUBLIC KEY BLOCK----- -Charset: UTF-8 - -mQENBFMYynYBCACVOZ3/e8Bm2b9KH9QyIlHGo/i1bnkpqsgXj8tpJ2MIUOnXMMAY -ztW7kKFLCmgVdLIC0vSoLA4yhaLcMojznh/2CcUglZeb6Ao8Gtelr//Rd5DRfPpG -zqcfUo+m+eO1co2Orabw0tZDfGpg5p3AYl0hmxhUyYSc/xUq93xL1UJzBFgYXY54 -QsM8dgeQgFseSk/YvdP5SMx1ev+eraUyiiUtWzWrWC1TdyRa5p4UZg6Rkoppf+WJ -QrW6BWrhAtqATHc8ozV7uJjeONjUEq24roRc/OFZdmQQGK6yrzKnnbA6MdHhqpdo -9kWDcXYb7pSE63Lc+OBa5X2GUVvXJLS/3nrtABEBAAG0F2ludmFsaWQtc2lnbmlu -Zy1zdWJrZXlziQEoBBMBAgASBQJTnKB5AhsBAgsHAhUIAh4BAAoJEO3UDQUIHpI/ -dN4H/idX4FQ1LIZCnpHS/oxoWQWfpRgdKAEM0qCqjMgiipJeEwSQbqjTCynuh5/R -JlODDz85ABR06aoF4l5ebGLQWFCYifPnJZ/Yf5OYcMGtb7dIbqxWVFL9iLMO/oDL -ioI3dotjPui5e+2hI9pVH1UHB/bZ/GvMGo6Zg0XxLPolKQODMVjpjLAQ0YJ3spew -RAmOGre6tIvbDsMBnm8qREt7a07cBJ6XK7xjxYaZHQBiHVxyEWDa6gyANONx8duW -/fhQ/zDTnyVM/ik6VO0Ty9BhPpcEYLFwh5c1ilFari1ta3e6qKo6ZGa9YMk/REhu -yBHd9nTkI+0CiQUmbckUiVjDKKe5AQ0EUxjKdgEIAJcXQeP+NmuciE99YcJoffxv -2gVLU4ZXBNHEaP0mgaJ1+tmMD089vUQAcyGRvw8jfsNsVZQIOAuRxY94aHQhIRHR -bUzBN28ofo/AJJtfx62C15xt6fDKRV6HXYqAiygrHIpEoRLyiN69iScUsjIJeyFL -C8wa72e8pSL6dkHoaV1N9ZH/xmrJ+k0vsgkQaAh9CzYufncDxcwkoP+aOlGtX1gP -WwWoIbz0JwLEMPHBWvDDXQcQPQTYQyj+LGC9U6f9VZHN25E94subM1MjuT9OhN9Y -MLfWaaIc5WyhLFyQKW2Upofn9wSFi8ubyBnv640Dfd0rVmaWv7LNTZpoZ/GbJAMA -EQEAAYkBHwQYAQIACQUCU5ygeQIbAgAKCRDt1A0FCB6SP0zCB/sEzaVR38vpx+OQ -MMynCBJrakiqDmUZv9xtplY7zsHSQjpd6xGflbU2n+iX99Q+nav0ETQZifNUEd4N -1ljDGQejcTyKD6Pkg6wBL3x9/RJye7Zszazm4+toJXZ8xJ3800+BtaPoI39akYJm -+ijzbskvN0v/j5GOFJwQO0pPRAFtdHqRs9Kf4YanxhedB4dIUblzlIJuKsxFit6N -lgGRblagG3Vv2eBszbxzPbJjHCgVLR3RmrVezKOsZjr/2i7X+xLWIR0uD3IN1qOW -CXQxLBizEEmSNVNxsp7KPGTLnqO3bPtqFirxS9PJLIMPTPLNBY7ZYuPNTMqVIUWF -4artDmrG -=7FfJ ------END PGP PUBLIC KEY BLOCK-----` - -const invalidCrossSignatureKey = `-----BEGIN PGP PUBLIC KEY BLOCK----- - -mQENBFMYynYBCACVOZ3/e8Bm2b9KH9QyIlHGo/i1bnkpqsgXj8tpJ2MIUOnXMMAY -ztW7kKFLCmgVdLIC0vSoLA4yhaLcMojznh/2CcUglZeb6Ao8Gtelr//Rd5DRfPpG -zqcfUo+m+eO1co2Orabw0tZDfGpg5p3AYl0hmxhUyYSc/xUq93xL1UJzBFgYXY54 -QsM8dgeQgFseSk/YvdP5SMx1ev+eraUyiiUtWzWrWC1TdyRa5p4UZg6Rkoppf+WJ -QrW6BWrhAtqATHc8ozV7uJjeONjUEq24roRc/OFZdmQQGK6yrzKnnbA6MdHhqpdo -9kWDcXYb7pSE63Lc+OBa5X2GUVvXJLS/3nrtABEBAAG0F2ludmFsaWQtc2lnbmlu -Zy1zdWJrZXlziQEoBBMBAgASBQJTnKB5AhsBAgsHAhUIAh4BAAoJEO3UDQUIHpI/ -dN4H/idX4FQ1LIZCnpHS/oxoWQWfpRgdKAEM0qCqjMgiipJeEwSQbqjTCynuh5/R -JlODDz85ABR06aoF4l5ebGLQWFCYifPnJZ/Yf5OYcMGtb7dIbqxWVFL9iLMO/oDL -ioI3dotjPui5e+2hI9pVH1UHB/bZ/GvMGo6Zg0XxLPolKQODMVjpjLAQ0YJ3spew -RAmOGre6tIvbDsMBnm8qREt7a07cBJ6XK7xjxYaZHQBiHVxyEWDa6gyANONx8duW -/fhQ/zDTnyVM/ik6VO0Ty9BhPpcEYLFwh5c1ilFari1ta3e6qKo6ZGa9YMk/REhu -yBHd9nTkI+0CiQUmbckUiVjDKKe5AQ0EUxjKdgEIAIINDqlj7X6jYKc6DjwrOkjQ -UIRWbQQar0LwmNilehmt70g5DCL1SYm9q4LcgJJ2Nhxj0/5qqsYib50OSWMcKeEe -iRXpXzv1ObpcQtI5ithp0gR53YPXBib80t3bUzomQ5UyZqAAHzMp3BKC54/vUrSK -FeRaxDzNLrCeyI00+LHNUtwghAqHvdNcsIf8VRumK8oTm3RmDh0TyjASWYbrt9c8 -R1Um3zuoACOVy+mEIgIzsfHq0u7dwYwJB5+KeM7ZLx+HGIYdUYzHuUE1sLwVoELh -+SHIGHI1HDicOjzqgajShuIjj5hZTyQySVprrsLKiXS6NEwHAP20+XjayJ/R3tEA -EQEAAYkCPgQYAQIBKAUCU5ygeQIbAsBdIAQZAQIABgUCU5ygeQAKCRCpVlnFZmhO -52RJB/9uD1MSa0wjY6tHOIgquZcP3bHBvHmrHNMw9HR2wRCMO91ZkhrpdS3ZHtgb -u3/55etj0FdvDo1tb8P8FGSVtO5Vcwf5APM8sbbqoi8L951Q3i7qt847lfhu6sMl -w0LWFvPTOLHrliZHItPRjOltS1WAWfr2jUYhsU9ytaDAJmvf9DujxEOsN5G1YJep -54JCKVCkM/y585Zcnn+yxk/XwqoNQ0/iJUT9qRrZWvoeasxhl1PQcwihCwss44A+ -YXaAt3hbk+6LEQuZoYS73yR3WHj+42tfm7YxRGeubXfgCEz/brETEWXMh4pe0vCL -bfWrmfSPq2rDegYcAybxRQz0lF8PAAoJEO3UDQUIHpI/exkH/0vQfdHA8g/N4T6E -i6b1CUVBAkvtdJpCATZjWPhXmShOw62gkDw306vHPilL4SCvEEi4KzG72zkp6VsB -DSRcpxCwT4mHue+duiy53/aRMtSJ+vDfiV1Vhq+3sWAck/yUtfDU9/u4eFaiNok1 -8/Gd7reyuZt5CiJnpdPpjCwelK21l2w7sHAnJF55ITXdOxI8oG3BRKufz0z5lyDY -s2tXYmhhQIggdgelN8LbcMhWs/PBbtUr6uZlNJG2lW1yscD4aI529VjwJlCeo745 -U7pO4eF05VViUJ2mmfoivL3tkhoTUWhx8xs8xCUcCg8DoEoSIhxtOmoTPR22Z9BL -6LCg2mg= -=Dhm4 ------END PGP PUBLIC KEY BLOCK-----` - -const goodCrossSignatureKey = `-----BEGIN PGP PUBLIC KEY BLOCK----- -Version: GnuPG v1 - -mI0EVUqeVwEEAMufHRrMPWK3gyvi0O0tABCs/oON9zV9KDZlr1a1M91ShCSFwCPo -7r80PxdWVWcj0V5h50/CJYtpN3eE/mUIgW2z1uDYQF1OzrQ8ubrksfsJvpAhENom -lTQEppv9mV8qhcM278teb7TX0pgrUHLYF5CfPdp1L957JLLXoQR/lwLVABEBAAG0 -E2dvb2Qtc2lnbmluZy1zdWJrZXmIuAQTAQIAIgUCVUqeVwIbAwYLCQgHAwIGFQgC -CQoLBBYCAwECHgECF4AACgkQNRjL95IRWP69XQQAlH6+eyXJN4DZTLX78KGjHrsw -6FCvxxClEPtPUjcJy/1KCRQmtLAt9PbbA78dvgzjDeZMZqRAwdjyJhjyg/fkU2OH -7wq4ktjUu+dLcOBb+BFMEY+YjKZhf6EJuVfxoTVr5f82XNPbYHfTho9/OABKH6kv -X70PaKZhbwnwij8Nts65AaIEVUqftREEAJ3WxZfqAX0bTDbQPf2CMT2IVMGDfhK7 -GyubOZgDFFjwUJQvHNvsrbeGLZ0xOBumLINyPO1amIfTgJNm1iiWFWfmnHReGcDl -y5mpYG60Mb79Whdcer7CMm3AqYh/dW4g6IB02NwZMKoUHo3PXmFLxMKXnWyJ0clw -R0LI/Qn509yXAKDh1SO20rqrBM+EAP2c5bfI98kyNwQAi3buu94qo3RR1ZbvfxgW -CKXDVm6N99jdZGNK7FbRifXqzJJDLcXZKLnstnC4Sd3uyfyf1uFhmDLIQRryn5m+ -LBYHfDBPN3kdm7bsZDDq9GbTHiFZUfm/tChVKXWxkhpAmHhU/tH6GGzNSMXuIWSO -aOz3Rqq0ED4NXyNKjdF9MiwD/i83S0ZBc0LmJYt4Z10jtH2B6tYdqnAK29uQaadx -yZCX2scE09UIm32/w7pV77CKr1Cp/4OzAXS1tmFzQ+bX7DR+Gl8t4wxr57VeEMvl -BGw4Vjh3X8//m3xynxycQU18Q1zJ6PkiMyPw2owZ/nss3hpSRKFJsxMLhW3fKmKr -Ey2KiOcEGAECAAkFAlVKn7UCGwIAUgkQNRjL95IRWP5HIAQZEQIABgUCVUqftQAK -CRD98VjDN10SqkWrAKDTpEY8D8HC02E/KVC5YUI01B30wgCgurpILm20kXEDCeHp -C5pygfXw1DJrhAP+NyPJ4um/bU1I+rXaHHJYroYJs8YSweiNcwiHDQn0Engh/mVZ -SqLHvbKh2dL/RXymC3+rjPvQf5cup9bPxNMa6WagdYBNAfzWGtkVISeaQW+cTEp/ -MtgVijRGXR/lGLGETPg2X3Afwn9N9bLMBkBprKgbBqU7lpaoPupxT61bL70= -=vtbN ------END PGP PUBLIC KEY BLOCK-----` diff --git a/Godeps/_workspace/src/golang.org/x/crypto/openpgp/packet/compressed_test.go b/Godeps/_workspace/src/golang.org/x/crypto/openpgp/packet/compressed_test.go deleted file mode 100644 index cb2d70bd4..000000000 --- a/Godeps/_workspace/src/golang.org/x/crypto/openpgp/packet/compressed_test.go +++ /dev/null @@ -1,41 +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 packet - -import ( - "bytes" - "encoding/hex" - "io" - "io/ioutil" - "testing" -) - -func TestCompressed(t *testing.T) { - packet, err := Read(readerFromHex(compressedHex)) - if err != nil { - t.Errorf("failed to read Compressed: %s", err) - return - } - - c, ok := packet.(*Compressed) - if !ok { - t.Error("didn't find Compressed packet") - return - } - - contents, err := ioutil.ReadAll(c.Body) - if err != nil && err != io.EOF { - t.Error(err) - return - } - - expected, _ := hex.DecodeString(compressedExpectedHex) - if !bytes.Equal(expected, contents) { - t.Errorf("got:%x want:%x", contents, expected) - } -} - -const compressedHex = "a3013b2d90c4e02b72e25f727e5e496a5e49b11e1700" -const compressedExpectedHex = "cb1062004d14c8fe636f6e74656e74732e0a" diff --git a/Godeps/_workspace/src/golang.org/x/crypto/openpgp/packet/encrypted_key_test.go b/Godeps/_workspace/src/golang.org/x/crypto/openpgp/packet/encrypted_key_test.go deleted file mode 100644 index fee14cf3c..000000000 --- a/Godeps/_workspace/src/golang.org/x/crypto/openpgp/packet/encrypted_key_test.go +++ /dev/null @@ -1,146 +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 packet - -import ( - "bytes" - "crypto/rsa" - "encoding/hex" - "fmt" - "math/big" - "testing" -) - -func bigFromBase10(s string) *big.Int { - b, ok := new(big.Int).SetString(s, 10) - if !ok { - panic("bigFromBase10 failed") - } - return b -} - -var encryptedKeyPub = rsa.PublicKey{ - E: 65537, - N: bigFromBase10("115804063926007623305902631768113868327816898845124614648849934718568541074358183759250136204762053879858102352159854352727097033322663029387610959884180306668628526686121021235757016368038585212410610742029286439607686208110250133174279811431933746643015923132833417396844716207301518956640020862630546868823"), -} - -var encryptedKeyRSAPriv = &rsa.PrivateKey{ - PublicKey: encryptedKeyPub, - D: bigFromBase10("32355588668219869544751561565313228297765464314098552250409557267371233892496951383426602439009993875125222579159850054973310859166139474359774543943714622292329487391199285040721944491839695981199720170366763547754915493640685849961780092241140181198779299712578774460837139360803883139311171713302987058393"), -} - -var encryptedKeyPriv = &PrivateKey{ - PublicKey: PublicKey{ - PubKeyAlgo: PubKeyAlgoRSA, - }, - PrivateKey: encryptedKeyRSAPriv, -} - -func TestDecryptingEncryptedKey(t *testing.T) { - const encryptedKeyHex = "c18c032a67d68660df41c70104005789d0de26b6a50c985a02a13131ca829c413a35d0e6fa8d6842599252162808ac7439c72151c8c6183e76923fe3299301414d0c25a2f06a2257db3839e7df0ec964773f6e4c4ac7ff3b48c444237166dd46ba8ff443a5410dc670cb486672fdbe7c9dfafb75b4fea83af3a204fe2a7dfa86bd20122b4f3d2646cbeecb8f7be8" - const expectedKeyHex = "d930363f7e0308c333b9618617ea728963d8df993665ae7be1092d4926fd864b" - - p, err := Read(readerFromHex(encryptedKeyHex)) - if err != nil { - t.Errorf("error from Read: %s", err) - return - } - ek, ok := p.(*EncryptedKey) - if !ok { - t.Errorf("didn't parse an EncryptedKey, got %#v", p) - return - } - - if ek.KeyId != 0x2a67d68660df41c7 || ek.Algo != PubKeyAlgoRSA { - t.Errorf("unexpected EncryptedKey contents: %#v", ek) - return - } - - err = ek.Decrypt(encryptedKeyPriv, nil) - if err != nil { - t.Errorf("error from Decrypt: %s", err) - return - } - - if ek.CipherFunc != CipherAES256 { - t.Errorf("unexpected EncryptedKey contents: %#v", ek) - return - } - - keyHex := fmt.Sprintf("%x", ek.Key) - if keyHex != expectedKeyHex { - t.Errorf("bad key, got %s want %x", keyHex, expectedKeyHex) - } -} - -func TestEncryptingEncryptedKey(t *testing.T) { - key := []byte{1, 2, 3, 4} - const expectedKeyHex = "01020304" - const keyId = 42 - - pub := &PublicKey{ - PublicKey: &encryptedKeyPub, - KeyId: keyId, - PubKeyAlgo: PubKeyAlgoRSAEncryptOnly, - } - - buf := new(bytes.Buffer) - err := SerializeEncryptedKey(buf, pub, CipherAES128, key, nil) - if err != nil { - t.Errorf("error writing encrypted key packet: %s", err) - } - - p, err := Read(buf) - if err != nil { - t.Errorf("error from Read: %s", err) - return - } - ek, ok := p.(*EncryptedKey) - if !ok { - t.Errorf("didn't parse an EncryptedKey, got %#v", p) - return - } - - if ek.KeyId != keyId || ek.Algo != PubKeyAlgoRSAEncryptOnly { - t.Errorf("unexpected EncryptedKey contents: %#v", ek) - return - } - - err = ek.Decrypt(encryptedKeyPriv, nil) - if err != nil { - t.Errorf("error from Decrypt: %s", err) - return - } - - if ek.CipherFunc != CipherAES128 { - t.Errorf("unexpected EncryptedKey contents: %#v", ek) - return - } - - keyHex := fmt.Sprintf("%x", ek.Key) - if keyHex != expectedKeyHex { - t.Errorf("bad key, got %s want %x", keyHex, expectedKeyHex) - } -} - -func TestSerializingEncryptedKey(t *testing.T) { - const encryptedKeyHex = "c18c032a67d68660df41c70104005789d0de26b6a50c985a02a13131ca829c413a35d0e6fa8d6842599252162808ac7439c72151c8c6183e76923fe3299301414d0c25a2f06a2257db3839e7df0ec964773f6e4c4ac7ff3b48c444237166dd46ba8ff443a5410dc670cb486672fdbe7c9dfafb75b4fea83af3a204fe2a7dfa86bd20122b4f3d2646cbeecb8f7be8" - - p, err := Read(readerFromHex(encryptedKeyHex)) - if err != nil { - t.Fatalf("error from Read: %s", err) - } - ek, ok := p.(*EncryptedKey) - if !ok { - t.Fatalf("didn't parse an EncryptedKey, got %#v", p) - } - - var buf bytes.Buffer - ek.Serialize(&buf) - - if bufHex := hex.EncodeToString(buf.Bytes()); bufHex != encryptedKeyHex { - t.Fatalf("serialization of encrypted key differed from original. Original was %s, but reserialized as %s", encryptedKeyHex, bufHex) - } -} diff --git a/Godeps/_workspace/src/golang.org/x/crypto/openpgp/packet/ocfb_test.go b/Godeps/_workspace/src/golang.org/x/crypto/openpgp/packet/ocfb_test.go deleted file mode 100644 index 91022c042..000000000 --- a/Godeps/_workspace/src/golang.org/x/crypto/openpgp/packet/ocfb_test.go +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright 2010 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 packet - -import ( - "bytes" - "crypto/aes" - "crypto/rand" - "testing" -) - -var commonKey128 = []byte{0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c} - -func testOCFB(t *testing.T, resync OCFBResyncOption) { - block, err := aes.NewCipher(commonKey128) - if err != nil { - t.Error(err) - return - } - - plaintext := []byte("this is the plaintext, which is long enough to span several blocks.") - randData := make([]byte, block.BlockSize()) - rand.Reader.Read(randData) - ocfb, prefix := NewOCFBEncrypter(block, randData, resync) - ciphertext := make([]byte, len(plaintext)) - ocfb.XORKeyStream(ciphertext, plaintext) - - ocfbdec := NewOCFBDecrypter(block, prefix, resync) - if ocfbdec == nil { - t.Errorf("NewOCFBDecrypter failed (resync: %t)", resync) - return - } - plaintextCopy := make([]byte, len(plaintext)) - ocfbdec.XORKeyStream(plaintextCopy, ciphertext) - - if !bytes.Equal(plaintextCopy, plaintext) { - t.Errorf("got: %x, want: %x (resync: %t)", plaintextCopy, plaintext, resync) - } -} - -func TestOCFB(t *testing.T) { - testOCFB(t, OCFBNoResync) - testOCFB(t, OCFBResync) -} diff --git a/Godeps/_workspace/src/golang.org/x/crypto/openpgp/packet/opaque_test.go b/Godeps/_workspace/src/golang.org/x/crypto/openpgp/packet/opaque_test.go deleted file mode 100644 index f27bbfe09..000000000 --- a/Godeps/_workspace/src/golang.org/x/crypto/openpgp/packet/opaque_test.go +++ /dev/null @@ -1,67 +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 packet - -import ( - "bytes" - "encoding/hex" - "io" - "testing" -) - -// Test packet.Read error handling in OpaquePacket.Parse, -// which attempts to re-read an OpaquePacket as a supported -// Packet type. -func TestOpaqueParseReason(t *testing.T) { - buf, err := hex.DecodeString(UnsupportedKeyHex) - if err != nil { - t.Fatal(err) - } - or := NewOpaqueReader(bytes.NewBuffer(buf)) - count := 0 - badPackets := 0 - var uid *UserId - for { - op, err := or.Next() - if err == io.EOF { - break - } else if err != nil { - t.Errorf("#%d: opaque read error: %v", count, err) - break - } - // try to parse opaque packet - p, err := op.Parse() - switch pkt := p.(type) { - case *UserId: - uid = pkt - case *OpaquePacket: - // If an OpaquePacket can't re-parse, packet.Read - // certainly had its reasons. - if pkt.Reason == nil { - t.Errorf("#%d: opaque packet, no reason", count) - } else { - badPackets++ - } - } - count++ - } - - const expectedBad = 3 - // Test post-conditions, make sure we actually parsed packets as expected. - if badPackets != expectedBad { - t.Errorf("unexpected # unparseable packets: %d (want %d)", badPackets, expectedBad) - } - if uid == nil { - t.Errorf("failed to find expected UID in unsupported keyring") - } else if uid.Id != "Armin M. Warda " { - t.Errorf("unexpected UID: %v", uid.Id) - } -} - -// This key material has public key and signature packet versions modified to -// an unsupported value (1), so that trying to parse the OpaquePacket to -// a typed packet will get an error. It also contains a GnuPG trust packet. -// (Created with: od -An -t x1 pubring.gpg | xargs | sed 's/ //g') -const UnsupportedKeyHex = `988d012e7a18a20000010400d6ac00d92b89c1f4396c243abb9b76d2e9673ad63483291fed88e22b82e255e441c078c6abbbf7d2d195e50b62eeaa915b85b0ec20c225ce2c64c167cacb6e711daf2e45da4a8356a059b8160e3b3628ac0dd8437b31f06d53d6e8ea4214d4a26406a6b63e1001406ef23e0bb3069fac9a99a91f77dfafd5de0f188a5da5e3c9000511b42741726d696e204d2e205761726461203c7761726461406e657068696c696d2e727568722e64653e8900950105102e8936c705d1eb399e58489901013f0e03ff5a0c4f421e34fcfa388129166420c08cd76987bcdec6f01bd0271459a85cc22048820dd4e44ac2c7d23908d540f54facf1b36b0d9c20488781ce9dca856531e76e2e846826e9951338020a03a09b57aa5faa82e9267458bd76105399885ac35af7dc1cbb6aaed7c39e1039f3b5beda2c0e916bd38560509bab81235d1a0ead83b0020000` diff --git a/Godeps/_workspace/src/golang.org/x/crypto/openpgp/packet/packet_test.go b/Godeps/_workspace/src/golang.org/x/crypto/openpgp/packet/packet_test.go deleted file mode 100644 index 1dab5c3d5..000000000 --- a/Godeps/_workspace/src/golang.org/x/crypto/openpgp/packet/packet_test.go +++ /dev/null @@ -1,255 +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 packet - -import ( - "bytes" - "encoding/hex" - "fmt" - "golang.org/x/crypto/openpgp/errors" - "io" - "io/ioutil" - "testing" -) - -func TestReadFull(t *testing.T) { - var out [4]byte - - b := bytes.NewBufferString("foo") - n, err := readFull(b, out[:3]) - if n != 3 || err != nil { - t.Errorf("full read failed n:%d err:%s", n, err) - } - - b = bytes.NewBufferString("foo") - n, err = readFull(b, out[:4]) - if n != 3 || err != io.ErrUnexpectedEOF { - t.Errorf("partial read failed n:%d err:%s", n, err) - } - - b = bytes.NewBuffer(nil) - n, err = readFull(b, out[:3]) - if n != 0 || err != io.ErrUnexpectedEOF { - t.Errorf("empty read failed n:%d err:%s", n, err) - } -} - -func readerFromHex(s string) io.Reader { - data, err := hex.DecodeString(s) - if err != nil { - panic("readerFromHex: bad input") - } - return bytes.NewBuffer(data) -} - -var readLengthTests = []struct { - hexInput string - length int64 - isPartial bool - err error -}{ - {"", 0, false, io.ErrUnexpectedEOF}, - {"1f", 31, false, nil}, - {"c0", 0, false, io.ErrUnexpectedEOF}, - {"c101", 256 + 1 + 192, false, nil}, - {"e0", 1, true, nil}, - {"e1", 2, true, nil}, - {"e2", 4, true, nil}, - {"ff", 0, false, io.ErrUnexpectedEOF}, - {"ff00", 0, false, io.ErrUnexpectedEOF}, - {"ff0000", 0, false, io.ErrUnexpectedEOF}, - {"ff000000", 0, false, io.ErrUnexpectedEOF}, - {"ff00000000", 0, false, nil}, - {"ff01020304", 16909060, false, nil}, -} - -func TestReadLength(t *testing.T) { - for i, test := range readLengthTests { - length, isPartial, err := readLength(readerFromHex(test.hexInput)) - if test.err != nil { - if err != test.err { - t.Errorf("%d: expected different error got:%s want:%s", i, err, test.err) - } - continue - } - if err != nil { - t.Errorf("%d: unexpected error: %s", i, err) - continue - } - if length != test.length || isPartial != test.isPartial { - t.Errorf("%d: bad result got:(%d,%t) want:(%d,%t)", i, length, isPartial, test.length, test.isPartial) - } - } -} - -var partialLengthReaderTests = []struct { - hexInput string - err error - hexOutput string -}{ - {"e0", io.ErrUnexpectedEOF, ""}, - {"e001", io.ErrUnexpectedEOF, ""}, - {"e0010102", nil, "0102"}, - {"ff00000000", nil, ""}, - {"e10102e1030400", nil, "01020304"}, - {"e101", io.ErrUnexpectedEOF, ""}, -} - -func TestPartialLengthReader(t *testing.T) { - for i, test := range partialLengthReaderTests { - r := &partialLengthReader{readerFromHex(test.hexInput), 0, true} - out, err := ioutil.ReadAll(r) - if test.err != nil { - if err != test.err { - t.Errorf("%d: expected different error got:%s want:%s", i, err, test.err) - } - continue - } - if err != nil { - t.Errorf("%d: unexpected error: %s", i, err) - continue - } - - got := fmt.Sprintf("%x", out) - if got != test.hexOutput { - t.Errorf("%d: got:%s want:%s", i, test.hexOutput, got) - } - } -} - -var readHeaderTests = []struct { - hexInput string - structuralError bool - unexpectedEOF bool - tag int - length int64 - hexOutput string -}{ - {"", false, false, 0, 0, ""}, - {"7f", true, false, 0, 0, ""}, - - // Old format headers - {"80", false, true, 0, 0, ""}, - {"8001", false, true, 0, 1, ""}, - {"800102", false, false, 0, 1, "02"}, - {"81000102", false, false, 0, 1, "02"}, - {"820000000102", false, false, 0, 1, "02"}, - {"860000000102", false, false, 1, 1, "02"}, - {"83010203", false, false, 0, -1, "010203"}, - - // New format headers - {"c0", false, true, 0, 0, ""}, - {"c000", false, false, 0, 0, ""}, - {"c00102", false, false, 0, 1, "02"}, - {"c0020203", false, false, 0, 2, "0203"}, - {"c00202", false, true, 0, 2, ""}, - {"c3020203", false, false, 3, 2, "0203"}, -} - -func TestReadHeader(t *testing.T) { - for i, test := range readHeaderTests { - tag, length, contents, err := readHeader(readerFromHex(test.hexInput)) - if test.structuralError { - if _, ok := err.(errors.StructuralError); ok { - continue - } - t.Errorf("%d: expected StructuralError, got:%s", i, err) - continue - } - if err != nil { - if len(test.hexInput) == 0 && err == io.EOF { - continue - } - if !test.unexpectedEOF || err != io.ErrUnexpectedEOF { - t.Errorf("%d: unexpected error from readHeader: %s", i, err) - } - continue - } - if int(tag) != test.tag || length != test.length { - t.Errorf("%d: got:(%d,%d) want:(%d,%d)", i, int(tag), length, test.tag, test.length) - continue - } - - body, err := ioutil.ReadAll(contents) - if err != nil { - if !test.unexpectedEOF || err != io.ErrUnexpectedEOF { - t.Errorf("%d: unexpected error from contents: %s", i, err) - } - continue - } - if test.unexpectedEOF { - t.Errorf("%d: expected ErrUnexpectedEOF from contents but got no error", i) - continue - } - got := fmt.Sprintf("%x", body) - if got != test.hexOutput { - t.Errorf("%d: got:%s want:%s", i, got, test.hexOutput) - } - } -} - -func TestSerializeHeader(t *testing.T) { - tag := packetTypePublicKey - lengths := []int{0, 1, 2, 64, 192, 193, 8000, 8384, 8385, 10000} - - for _, length := range lengths { - buf := bytes.NewBuffer(nil) - serializeHeader(buf, tag, length) - tag2, length2, _, err := readHeader(buf) - if err != nil { - t.Errorf("length %d, err: %s", length, err) - } - if tag2 != tag { - t.Errorf("length %d, tag incorrect (got %d, want %d)", length, tag2, tag) - } - if int(length2) != length { - t.Errorf("length %d, length incorrect (got %d)", length, length2) - } - } -} - -func TestPartialLengths(t *testing.T) { - buf := bytes.NewBuffer(nil) - w := new(partialLengthWriter) - w.w = noOpCloser{buf} - - const maxChunkSize = 64 - - var b [maxChunkSize]byte - var n uint8 - for l := 1; l <= maxChunkSize; l++ { - for i := 0; i < l; i++ { - b[i] = n - n++ - } - m, err := w.Write(b[:l]) - if m != l { - t.Errorf("short write got: %d want: %d", m, l) - } - if err != nil { - t.Errorf("error from write: %s", err) - } - } - w.Close() - - want := (maxChunkSize * (maxChunkSize + 1)) / 2 - copyBuf := bytes.NewBuffer(nil) - r := &partialLengthReader{buf, 0, true} - m, err := io.Copy(copyBuf, r) - if m != int64(want) { - t.Errorf("short copy got: %d want: %d", m, want) - } - if err != nil { - t.Errorf("error from copy: %s", err) - } - - copyBytes := copyBuf.Bytes() - for i := 0; i < want; i++ { - if copyBytes[i] != uint8(i) { - t.Errorf("bad pattern in copy at %d", i) - break - } - } -} diff --git a/Godeps/_workspace/src/golang.org/x/crypto/openpgp/packet/private_key_test.go b/Godeps/_workspace/src/golang.org/x/crypto/openpgp/packet/private_key_test.go deleted file mode 100644 index 25c8931f2..000000000 --- a/Godeps/_workspace/src/golang.org/x/crypto/openpgp/packet/private_key_test.go +++ /dev/null @@ -1,69 +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 packet - -import ( - "testing" - "time" -) - -var privateKeyTests = []struct { - privateKeyHex string - creationTime time.Time -}{ - { - privKeyRSAHex, - time.Unix(0x4cc349a8, 0), - }, - { - privKeyElGamalHex, - time.Unix(0x4df9ee1a, 0), - }, -} - -func TestPrivateKeyRead(t *testing.T) { - for i, test := range privateKeyTests { - packet, err := Read(readerFromHex(test.privateKeyHex)) - if err != nil { - t.Errorf("#%d: failed to parse: %s", i, err) - continue - } - - privKey := packet.(*PrivateKey) - - if !privKey.Encrypted { - t.Errorf("#%d: private key isn't encrypted", i) - continue - } - - err = privKey.Decrypt([]byte("wrong password")) - if err == nil { - t.Errorf("#%d: decrypted with incorrect key", i) - continue - } - - err = privKey.Decrypt([]byte("testing")) - if err != nil { - t.Errorf("#%d: failed to decrypt: %s", i, err) - continue - } - - if !privKey.CreationTime.Equal(test.creationTime) || privKey.Encrypted { - t.Errorf("#%d: bad result, got: %#v", i, privKey) - } - } -} - -func TestIssue11505(t *testing.T) { - // parsing a rsa private key with p or q == 1 used to panic due to a divide by zero - _, _ = Read(readerFromHex("9c3004303030300100000011303030000000000000010130303030303030303030303030303030303030303030303030303030303030303030303030303030303030")) -} - -// Generated with `gpg --export-secret-keys "Test Key 2"` -const privKeyRSAHex = "9501fe044cc349a8010400b70ca0010e98c090008d45d1ee8f9113bd5861fd57b88bacb7c68658747663f1e1a3b5a98f32fda6472373c024b97359cd2efc88ff60f77751adfbf6af5e615e6a1408cfad8bf0cea30b0d5f53aa27ad59089ba9b15b7ebc2777a25d7b436144027e3bcd203909f147d0e332b240cf63d3395f5dfe0df0a6c04e8655af7eacdf0011010001fe0303024a252e7d475fd445607de39a265472aa74a9320ba2dac395faa687e9e0336aeb7e9a7397e511b5afd9dc84557c80ac0f3d4d7bfec5ae16f20d41c8c84a04552a33870b930420e230e179564f6d19bb153145e76c33ae993886c388832b0fa042ddda7f133924f3854481533e0ede31d51278c0519b29abc3bf53da673e13e3e1214b52413d179d7f66deee35cac8eacb060f78379d70ef4af8607e68131ff529439668fc39c9ce6dfef8a5ac234d234802cbfb749a26107db26406213ae5c06d4673253a3cbee1fcbae58d6ab77e38d6e2c0e7c6317c48e054edadb5a40d0d48acb44643d998139a8a66bb820be1f3f80185bc777d14b5954b60effe2448a036d565c6bc0b915fcea518acdd20ab07bc1529f561c58cd044f723109b93f6fd99f876ff891d64306b5d08f48bab59f38695e9109c4dec34013ba3153488ce070268381ba923ee1eb77125b36afcb4347ec3478c8f2735b06ef17351d872e577fa95d0c397c88c71b59629a36aec" - -// Generated by `gpg --export-secret-keys` followed by a manual extraction of -// the ElGamal subkey from the packets. -const privKeyElGamalHex = "9d0157044df9ee1a100400eb8e136a58ec39b582629cdadf830bc64e0a94ed8103ca8bb247b27b11b46d1d25297ef4bcc3071785ba0c0bedfe89eabc5287fcc0edf81ab5896c1c8e4b20d27d79813c7aede75320b33eaeeaa586edc00fd1036c10133e6ba0ff277245d0d59d04b2b3421b7244aca5f4a8d870c6f1c1fbff9e1c26699a860b9504f35ca1d700030503fd1ededd3b840795be6d9ccbe3c51ee42e2f39233c432b831ddd9c4e72b7025a819317e47bf94f9ee316d7273b05d5fcf2999c3a681f519b1234bbfa6d359b4752bd9c3f77d6b6456cde152464763414ca130f4e91d91041432f90620fec0e6d6b5116076c2985d5aeaae13be492b9b329efcaf7ee25120159a0a30cd976b42d7afe030302dae7eb80db744d4960c4df930d57e87fe81412eaace9f900e6c839817a614ddb75ba6603b9417c33ea7b6c93967dfa2bcff3fa3c74a5ce2c962db65b03aece14c96cbd0038fc" diff --git a/Godeps/_workspace/src/golang.org/x/crypto/openpgp/packet/public_key_test.go b/Godeps/_workspace/src/golang.org/x/crypto/openpgp/packet/public_key_test.go deleted file mode 100644 index 7ad7d9185..000000000 --- a/Godeps/_workspace/src/golang.org/x/crypto/openpgp/packet/public_key_test.go +++ /dev/null @@ -1,202 +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 packet - -import ( - "bytes" - "encoding/hex" - "testing" - "time" -) - -var pubKeyTests = []struct { - hexData string - hexFingerprint string - creationTime time.Time - pubKeyAlgo PublicKeyAlgorithm - keyId uint64 - keyIdString string - keyIdShort string -}{ - {rsaPkDataHex, rsaFingerprintHex, time.Unix(0x4d3c5c10, 0), PubKeyAlgoRSA, 0xa34d7e18c20c31bb, "A34D7E18C20C31BB", "C20C31BB"}, - {dsaPkDataHex, dsaFingerprintHex, time.Unix(0x4d432f89, 0), PubKeyAlgoDSA, 0x8e8fbe54062f19ed, "8E8FBE54062F19ED", "062F19ED"}, - {ecdsaPkDataHex, ecdsaFingerprintHex, time.Unix(0x5071c294, 0), PubKeyAlgoECDSA, 0x43fe956c542ca00b, "43FE956C542CA00B", "542CA00B"}, -} - -func TestPublicKeyRead(t *testing.T) { - for i, test := range pubKeyTests { - packet, err := Read(readerFromHex(test.hexData)) - if err != nil { - t.Errorf("#%d: Read error: %s", i, err) - continue - } - pk, ok := packet.(*PublicKey) - if !ok { - t.Errorf("#%d: failed to parse, got: %#v", i, packet) - continue - } - if pk.PubKeyAlgo != test.pubKeyAlgo { - t.Errorf("#%d: bad public key algorithm got:%x want:%x", i, pk.PubKeyAlgo, test.pubKeyAlgo) - } - if !pk.CreationTime.Equal(test.creationTime) { - t.Errorf("#%d: bad creation time got:%v want:%v", i, pk.CreationTime, test.creationTime) - } - expectedFingerprint, _ := hex.DecodeString(test.hexFingerprint) - if !bytes.Equal(expectedFingerprint, pk.Fingerprint[:]) { - t.Errorf("#%d: bad fingerprint got:%x want:%x", i, pk.Fingerprint[:], expectedFingerprint) - } - if pk.KeyId != test.keyId { - t.Errorf("#%d: bad keyid got:%x want:%x", i, pk.KeyId, test.keyId) - } - if g, e := pk.KeyIdString(), test.keyIdString; g != e { - t.Errorf("#%d: bad KeyIdString got:%q want:%q", i, g, e) - } - if g, e := pk.KeyIdShortString(), test.keyIdShort; g != e { - t.Errorf("#%d: bad KeyIdShortString got:%q want:%q", i, g, e) - } - } -} - -func TestPublicKeySerialize(t *testing.T) { - for i, test := range pubKeyTests { - packet, err := Read(readerFromHex(test.hexData)) - if err != nil { - t.Errorf("#%d: Read error: %s", i, err) - continue - } - pk, ok := packet.(*PublicKey) - if !ok { - t.Errorf("#%d: failed to parse, got: %#v", i, packet) - continue - } - serializeBuf := bytes.NewBuffer(nil) - err = pk.Serialize(serializeBuf) - if err != nil { - t.Errorf("#%d: failed to serialize: %s", i, err) - continue - } - - packet, err = Read(serializeBuf) - if err != nil { - t.Errorf("#%d: Read error (from serialized data): %s", i, err) - continue - } - pk, ok = packet.(*PublicKey) - if !ok { - t.Errorf("#%d: failed to parse serialized data, got: %#v", i, packet) - continue - } - } -} - -func TestEcc384Serialize(t *testing.T) { - r := readerFromHex(ecc384PubHex) - var w bytes.Buffer - for i := 0; i < 2; i++ { - // Public key - p, err := Read(r) - if err != nil { - t.Error(err) - } - pubkey := p.(*PublicKey) - if !bytes.Equal(pubkey.ec.oid, []byte{0x2b, 0x81, 0x04, 0x00, 0x22}) { - t.Errorf("Unexpected pubkey OID: %x", pubkey.ec.oid) - } - if !bytes.Equal(pubkey.ec.p.bytes[:5], []byte{0x04, 0xf6, 0xb8, 0xc5, 0xac}) { - t.Errorf("Unexpected pubkey P[:5]: %x", pubkey.ec.p.bytes) - } - if pubkey.KeyId != 0x098033880F54719F { - t.Errorf("Unexpected pubkey ID: %x", pubkey.KeyId) - } - err = pubkey.Serialize(&w) - if err != nil { - t.Error(err) - } - // User ID - p, err = Read(r) - if err != nil { - t.Error(err) - } - uid := p.(*UserId) - if uid.Id != "ec_dsa_dh_384 " { - t.Error("Unexpected UID:", uid.Id) - } - err = uid.Serialize(&w) - if err != nil { - t.Error(err) - } - // User ID Sig - p, err = Read(r) - if err != nil { - t.Error(err) - } - uidSig := p.(*Signature) - err = pubkey.VerifyUserIdSignature(uid.Id, pubkey, uidSig) - if err != nil { - t.Error(err, ": UID") - } - err = uidSig.Serialize(&w) - if err != nil { - t.Error(err) - } - // Subkey - p, err = Read(r) - if err != nil { - t.Error(err) - } - subkey := p.(*PublicKey) - if !bytes.Equal(subkey.ec.oid, []byte{0x2b, 0x81, 0x04, 0x00, 0x22}) { - t.Errorf("Unexpected subkey OID: %x", subkey.ec.oid) - } - if !bytes.Equal(subkey.ec.p.bytes[:5], []byte{0x04, 0x2f, 0xaa, 0x84, 0x02}) { - t.Errorf("Unexpected subkey P[:5]: %x", subkey.ec.p.bytes) - } - if subkey.ecdh.KdfHash != 0x09 { - t.Error("Expected KDF hash function SHA384 (0x09), got", subkey.ecdh.KdfHash) - } - if subkey.ecdh.KdfAlgo != 0x09 { - t.Error("Expected KDF symmetric alg AES256 (0x09), got", subkey.ecdh.KdfAlgo) - } - if subkey.KeyId != 0xAA8B938F9A201946 { - t.Errorf("Unexpected subkey ID: %x", subkey.KeyId) - } - err = subkey.Serialize(&w) - if err != nil { - t.Error(err) - } - // Subkey Sig - p, err = Read(r) - if err != nil { - t.Error(err) - } - subkeySig := p.(*Signature) - err = pubkey.VerifyKeySignature(subkey, subkeySig) - if err != nil { - t.Error(err) - } - err = subkeySig.Serialize(&w) - if err != nil { - t.Error(err) - } - // Now read back what we've written again - r = bytes.NewBuffer(w.Bytes()) - w.Reset() - } -} - -const rsaFingerprintHex = "5fb74b1d03b1e3cb31bc2f8aa34d7e18c20c31bb" - -const rsaPkDataHex = "988d044d3c5c10010400b1d13382944bd5aba23a4312968b5095d14f947f600eb478e14a6fcb16b0e0cac764884909c020bc495cfcc39a935387c661507bdb236a0612fb582cac3af9b29cc2c8c70090616c41b662f4da4c1201e195472eb7f4ae1ccbcbf9940fe21d985e379a5563dde5b9a23d35f1cfaa5790da3b79db26f23695107bfaca8e7b5bcd0011010001" - -const dsaFingerprintHex = "eece4c094db002103714c63c8e8fbe54062f19ed" - -const dsaPkDataHex = "9901a2044d432f89110400cd581334f0d7a1e1bdc8b9d6d8c0baf68793632735d2bb0903224cbaa1dfbf35a60ee7a13b92643421e1eb41aa8d79bea19a115a677f6b8ba3c7818ce53a6c2a24a1608bd8b8d6e55c5090cbde09dd26e356267465ae25e69ec8bdd57c7bbb2623e4d73336f73a0a9098f7f16da2e25252130fd694c0e8070c55a812a423ae7f00a0ebf50e70c2f19c3520a551bd4b08d30f23530d3d03ff7d0bf4a53a64a09dc5e6e6e35854b7d70c882b0c60293401958b1bd9e40abec3ea05ba87cf64899299d4bd6aa7f459c201d3fbbd6c82004bdc5e8a9eb8082d12054cc90fa9d4ec251a843236a588bf49552441817436c4f43326966fe85447d4e6d0acf8fa1ef0f014730770603ad7634c3088dc52501c237328417c31c89ed70400b2f1a98b0bf42f11fefc430704bebbaa41d9f355600c3facee1e490f64208e0e094ea55e3a598a219a58500bf78ac677b670a14f4e47e9cf8eab4f368cc1ddcaa18cc59309d4cc62dd4f680e73e6cc3e1ce87a84d0925efbcb26c575c093fc42eecf45135fabf6403a25c2016e1774c0484e440a18319072c617cc97ac0a3bb0" - -const ecdsaFingerprintHex = "9892270b38b8980b05c8d56d43fe956c542ca00b" - -const ecdsaPkDataHex = "9893045071c29413052b8104002304230401f4867769cedfa52c325018896245443968e52e51d0c2df8d939949cb5b330f2921711fbee1c9b9dddb95d15cb0255e99badeddda7cc23d9ddcaacbc290969b9f24019375d61c2e4e3b36953a28d8b2bc95f78c3f1d592fb24499be348656a7b17e3963187b4361afe497bc5f9f81213f04069f8e1fb9e6a6290ae295ca1a92b894396cb4" - -// Source: https://sites.google.com/site/brainhub/pgpecckeys#TOC-ECC-NIST-P-384-key -const ecc384PubHex = `99006f044d53059213052b81040022030304f6b8c5aced5b84ef9f4a209db2e4a9dfb70d28cb8c10ecd57674a9fa5a67389942b62d5e51367df4c7bfd3f8e500feecf07ed265a621a8ebbbe53e947ec78c677eba143bd1533c2b350e1c29f82313e1e1108eba063be1e64b10e6950e799c2db42465635f6473615f64685f333834203c6f70656e70677040627261696e6875622e6f72673e8900cb04101309005305024d530592301480000000002000077072656665727265642d656d61696c2d656e636f64696e67407067702e636f6d7067706d696d65040b090807021901051b03000000021602051e010000000415090a08000a0910098033880f54719fca2b0180aa37350968bd5f115afd8ce7bc7b103822152dbff06d0afcda835329510905b98cb469ba208faab87c7412b799e7b633017f58364ea480e8a1a3f253a0c5f22c446e8be9a9fce6210136ee30811abbd49139de28b5bdf8dc36d06ae748579e9ff503b90073044d53059212052b810400220303042faa84024a20b6735c4897efa5bfb41bf85b7eefeab5ca0cb9ffc8ea04a46acb25534a577694f9e25340a4ab5223a9dd1eda530c8aa2e6718db10d7e672558c7736fe09369ea5739a2a3554bf16d41faa50562f11c6d39bbd5dffb6b9a9ec9180301090989008404181309000c05024d530592051b0c000000000a0910098033880f54719f80970180eee7a6d8fcee41ee4f9289df17f9bcf9d955dca25c583b94336f3a2b2d4986dc5cf417b8d2dc86f741a9e1a6d236c0e3017d1c76575458a0cfb93ae8a2b274fcc65ceecd7a91eec83656ba13219969f06945b48c56bd04152c3a0553c5f2f4bd1267` diff --git a/Godeps/_workspace/src/golang.org/x/crypto/openpgp/packet/public_key_v3_test.go b/Godeps/_workspace/src/golang.org/x/crypto/openpgp/packet/public_key_v3_test.go deleted file mode 100644 index e06405904..000000000 --- a/Godeps/_workspace/src/golang.org/x/crypto/openpgp/packet/public_key_v3_test.go +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package packet - -import ( - "bytes" - "encoding/hex" - "testing" - "time" -) - -var pubKeyV3Test = struct { - hexFingerprint string - creationTime time.Time - pubKeyAlgo PublicKeyAlgorithm - keyId uint64 - keyIdString string - keyIdShort string -}{ - "103BECF5BD1E837C89D19E98487767F7", - time.Unix(779753634, 0), - PubKeyAlgoRSA, - 0xDE0F188A5DA5E3C9, - "DE0F188A5DA5E3C9", - "5DA5E3C9"} - -func TestPublicKeyV3Read(t *testing.T) { - i, test := 0, pubKeyV3Test - packet, err := Read(v3KeyReader(t)) - if err != nil { - t.Fatalf("#%d: Read error: %s", i, err) - } - pk, ok := packet.(*PublicKeyV3) - if !ok { - t.Fatalf("#%d: failed to parse, got: %#v", i, packet) - } - if pk.PubKeyAlgo != test.pubKeyAlgo { - t.Errorf("#%d: bad public key algorithm got:%x want:%x", i, pk.PubKeyAlgo, test.pubKeyAlgo) - } - if !pk.CreationTime.Equal(test.creationTime) { - t.Errorf("#%d: bad creation time got:%v want:%v", i, pk.CreationTime, test.creationTime) - } - expectedFingerprint, _ := hex.DecodeString(test.hexFingerprint) - if !bytes.Equal(expectedFingerprint, pk.Fingerprint[:]) { - t.Errorf("#%d: bad fingerprint got:%x want:%x", i, pk.Fingerprint[:], expectedFingerprint) - } - if pk.KeyId != test.keyId { - t.Errorf("#%d: bad keyid got:%x want:%x", i, pk.KeyId, test.keyId) - } - if g, e := pk.KeyIdString(), test.keyIdString; g != e { - t.Errorf("#%d: bad KeyIdString got:%q want:%q", i, g, e) - } - if g, e := pk.KeyIdShortString(), test.keyIdShort; g != e { - t.Errorf("#%d: bad KeyIdShortString got:%q want:%q", i, g, e) - } -} - -func TestPublicKeyV3Serialize(t *testing.T) { - //for i, test := range pubKeyV3Tests { - i := 0 - packet, err := Read(v3KeyReader(t)) - if err != nil { - t.Fatalf("#%d: Read error: %s", i, err) - } - pk, ok := packet.(*PublicKeyV3) - if !ok { - t.Fatalf("#%d: failed to parse, got: %#v", i, packet) - } - var serializeBuf bytes.Buffer - if err = pk.Serialize(&serializeBuf); err != nil { - t.Fatalf("#%d: failed to serialize: %s", i, err) - } - - if packet, err = Read(bytes.NewBuffer(serializeBuf.Bytes())); err != nil { - t.Fatalf("#%d: Read error (from serialized data): %s", i, err) - } - if pk, ok = packet.(*PublicKeyV3); !ok { - t.Fatalf("#%d: failed to parse serialized data, got: %#v", i, packet) - } -} diff --git a/Godeps/_workspace/src/golang.org/x/crypto/openpgp/packet/signature_test.go b/Godeps/_workspace/src/golang.org/x/crypto/openpgp/packet/signature_test.go deleted file mode 100644 index c1bbde8b0..000000000 --- a/Godeps/_workspace/src/golang.org/x/crypto/openpgp/packet/signature_test.go +++ /dev/null @@ -1,42 +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 packet - -import ( - "bytes" - "crypto" - "encoding/hex" - "testing" -) - -func TestSignatureRead(t *testing.T) { - packet, err := Read(readerFromHex(signatureDataHex)) - if err != nil { - t.Error(err) - return - } - sig, ok := packet.(*Signature) - if !ok || sig.SigType != SigTypeBinary || sig.PubKeyAlgo != PubKeyAlgoRSA || sig.Hash != crypto.SHA1 { - t.Errorf("failed to parse, got: %#v", packet) - } -} - -func TestSignatureReserialize(t *testing.T) { - packet, _ := Read(readerFromHex(signatureDataHex)) - sig := packet.(*Signature) - out := new(bytes.Buffer) - err := sig.Serialize(out) - if err != nil { - t.Errorf("error reserializing: %s", err) - return - } - - expected, _ := hex.DecodeString(signatureDataHex) - if !bytes.Equal(expected, out.Bytes()) { - t.Errorf("output doesn't match input (got vs expected):\n%s\n%s", hex.Dump(out.Bytes()), hex.Dump(expected)) - } -} - -const signatureDataHex = "c2c05c04000102000605024cb45112000a0910ab105c91af38fb158f8d07ff5596ea368c5efe015bed6e78348c0f033c931d5f2ce5db54ce7f2a7e4b4ad64db758d65a7a71773edeab7ba2a9e0908e6a94a1175edd86c1d843279f045b021a6971a72702fcbd650efc393c5474d5b59a15f96d2eaad4c4c426797e0dcca2803ef41c6ff234d403eec38f31d610c344c06f2401c262f0993b2e66cad8a81ebc4322c723e0d4ba09fe917e8777658307ad8329adacba821420741009dfe87f007759f0982275d028a392c6ed983a0d846f890b36148c7358bdb8a516007fac760261ecd06076813831a36d0459075d1befa245ae7f7fb103d92ca759e9498fe60ef8078a39a3beda510deea251ea9f0a7f0df6ef42060f20780360686f3e400e" diff --git a/Godeps/_workspace/src/golang.org/x/crypto/openpgp/packet/signature_v3_test.go b/Godeps/_workspace/src/golang.org/x/crypto/openpgp/packet/signature_v3_test.go deleted file mode 100644 index ad7b62ac1..000000000 --- a/Godeps/_workspace/src/golang.org/x/crypto/openpgp/packet/signature_v3_test.go +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package packet - -import ( - "bytes" - "crypto" - "encoding/hex" - "io" - "io/ioutil" - "testing" - - "golang.org/x/crypto/openpgp/armor" -) - -func TestSignatureV3Read(t *testing.T) { - r := v3KeyReader(t) - Read(r) // Skip public key - Read(r) // Skip uid - packet, err := Read(r) // Signature - if err != nil { - t.Error(err) - return - } - sig, ok := packet.(*SignatureV3) - if !ok || sig.SigType != SigTypeGenericCert || sig.PubKeyAlgo != PubKeyAlgoRSA || sig.Hash != crypto.MD5 { - t.Errorf("failed to parse, got: %#v", packet) - } -} - -func TestSignatureV3Reserialize(t *testing.T) { - r := v3KeyReader(t) - Read(r) // Skip public key - Read(r) // Skip uid - packet, err := Read(r) - if err != nil { - t.Error(err) - return - } - sig := packet.(*SignatureV3) - out := new(bytes.Buffer) - if err = sig.Serialize(out); err != nil { - t.Errorf("error reserializing: %s", err) - return - } - expected, err := ioutil.ReadAll(v3KeyReader(t)) - if err != nil { - t.Error(err) - return - } - expected = expected[4+141+4+39:] // See pgpdump offsets below, this is where the sig starts - if !bytes.Equal(expected, out.Bytes()) { - t.Errorf("output doesn't match input (got vs expected):\n%s\n%s", hex.Dump(out.Bytes()), hex.Dump(expected)) - } -} - -func v3KeyReader(t *testing.T) io.Reader { - armorBlock, err := armor.Decode(bytes.NewBufferString(keySigV3Armor)) - if err != nil { - t.Fatalf("armor Decode failed: %v", err) - } - return armorBlock.Body -} - -// keySigV3Armor is some V3 public key I found in an SKS dump. -// Old: Public Key Packet(tag 6)(141 bytes) -// Ver 4 - new -// Public key creation time - Fri Sep 16 17:13:54 CDT 1994 -// Pub alg - unknown(pub 0) -// Unknown public key(pub 0) -// Old: User ID Packet(tag 13)(39 bytes) -// User ID - Armin M. Warda -// Old: Signature Packet(tag 2)(149 bytes) -// Ver 4 - new -// Sig type - unknown(05) -// Pub alg - ElGamal Encrypt-Only(pub 16) -// Hash alg - unknown(hash 46) -// Hashed Sub: unknown(sub 81, critical)(1988 bytes) -const keySigV3Armor = `-----BEGIN PGP PUBLIC KEY BLOCK----- -Version: SKS 1.0.10 - -mI0CLnoYogAAAQQA1qwA2SuJwfQ5bCQ6u5t20ulnOtY0gykf7YjiK4LiVeRBwHjGq7v30tGV -5Qti7qqRW4Ww7CDCJc4sZMFnystucR2vLkXaSoNWoFm4Fg47NiisDdhDezHwbVPW6OpCFNSi -ZAamtj4QAUBu8j4LswafrJqZqR9336/V3g8Yil2l48kABRG0J0FybWluIE0uIFdhcmRhIDx3 -YXJkYUBuZXBoaWxpbS5ydWhyLmRlPoiVAgUQLok2xwXR6zmeWEiZAQE/DgP/WgxPQh40/Po4 -gSkWZCDAjNdph7zexvAb0CcUWahcwiBIgg3U5ErCx9I5CNVA9U+s8bNrDZwgSIeBzp3KhWUx -524uhGgm6ZUTOAIKA6CbV6pfqoLpJnRYvXYQU5mIWsNa99wcu2qu18OeEDnztb7aLA6Ra9OF -YFCbq4EjXRoOrYM= -=LPjs ------END PGP PUBLIC KEY BLOCK-----` diff --git a/Godeps/_workspace/src/golang.org/x/crypto/openpgp/packet/symmetric_key_encrypted_test.go b/Godeps/_workspace/src/golang.org/x/crypto/openpgp/packet/symmetric_key_encrypted_test.go deleted file mode 100644 index dd983cb38..000000000 --- a/Godeps/_workspace/src/golang.org/x/crypto/openpgp/packet/symmetric_key_encrypted_test.go +++ /dev/null @@ -1,102 +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 packet - -import ( - "bytes" - "encoding/hex" - "io" - "io/ioutil" - "testing" -) - -func TestSymmetricKeyEncrypted(t *testing.T) { - buf := readerFromHex(symmetricallyEncryptedHex) - packet, err := Read(buf) - if err != nil { - t.Errorf("failed to read SymmetricKeyEncrypted: %s", err) - return - } - ske, ok := packet.(*SymmetricKeyEncrypted) - if !ok { - t.Error("didn't find SymmetricKeyEncrypted packet") - return - } - err = ske.Decrypt([]byte("password")) - if err != nil { - t.Error(err) - return - } - - packet, err = Read(buf) - if err != nil { - t.Errorf("failed to read SymmetricallyEncrypted: %s", err) - return - } - se, ok := packet.(*SymmetricallyEncrypted) - if !ok { - t.Error("didn't find SymmetricallyEncrypted packet") - return - } - r, err := se.Decrypt(ske.CipherFunc, ske.Key) - if err != nil { - t.Error(err) - return - } - - contents, err := ioutil.ReadAll(r) - if err != nil && err != io.EOF { - t.Error(err) - return - } - - expectedContents, _ := hex.DecodeString(symmetricallyEncryptedContentsHex) - if !bytes.Equal(expectedContents, contents) { - t.Errorf("bad contents got:%x want:%x", contents, expectedContents) - } -} - -const symmetricallyEncryptedHex = "8c0d04030302371a0b38d884f02060c91cf97c9973b8e58e028e9501708ccfe618fb92afef7fa2d80ddadd93cf" -const symmetricallyEncryptedContentsHex = "cb1062004d14c4df636f6e74656e74732e0a" - -func TestSerializeSymmetricKeyEncrypted(t *testing.T) { - buf := bytes.NewBuffer(nil) - passphrase := []byte("testing") - config := &Config{ - DefaultCipher: CipherAES128, - } - - key, err := SerializeSymmetricKeyEncrypted(buf, passphrase, config) - if err != nil { - t.Errorf("failed to serialize: %s", err) - return - } - - p, err := Read(buf) - if err != nil { - t.Errorf("failed to reparse: %s", err) - return - } - ske, ok := p.(*SymmetricKeyEncrypted) - if !ok { - t.Errorf("parsed a different packet type: %#v", p) - return - } - - if !ske.Encrypted { - t.Errorf("SKE not encrypted but should be") - } - if ske.CipherFunc != config.DefaultCipher { - t.Errorf("SKE cipher function is %d (expected %d)", ske.CipherFunc, config.DefaultCipher) - } - err = ske.Decrypt(passphrase) - if err != nil { - t.Errorf("failed to decrypt reparsed SKE: %s", err) - return - } - if !bytes.Equal(key, ske.Key) { - t.Errorf("keys don't match after Decrpyt: %x (original) vs %x (parsed)", key, ske.Key) - } -} diff --git a/Godeps/_workspace/src/golang.org/x/crypto/openpgp/packet/symmetrically_encrypted_test.go b/Godeps/_workspace/src/golang.org/x/crypto/openpgp/packet/symmetrically_encrypted_test.go deleted file mode 100644 index c5c00f7b9..000000000 --- a/Godeps/_workspace/src/golang.org/x/crypto/openpgp/packet/symmetrically_encrypted_test.go +++ /dev/null @@ -1,123 +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 packet - -import ( - "bytes" - "crypto/sha1" - "encoding/hex" - "golang.org/x/crypto/openpgp/errors" - "io" - "io/ioutil" - "testing" -) - -// TestReader wraps a []byte and returns reads of a specific length. -type testReader struct { - data []byte - stride int -} - -func (t *testReader) Read(buf []byte) (n int, err error) { - n = t.stride - if n > len(t.data) { - n = len(t.data) - } - if n > len(buf) { - n = len(buf) - } - copy(buf, t.data) - t.data = t.data[n:] - if len(t.data) == 0 { - err = io.EOF - } - return -} - -func testMDCReader(t *testing.T) { - mdcPlaintext, _ := hex.DecodeString(mdcPlaintextHex) - - for stride := 1; stride < len(mdcPlaintext)/2; stride++ { - r := &testReader{data: mdcPlaintext, stride: stride} - mdcReader := &seMDCReader{in: r, h: sha1.New()} - body, err := ioutil.ReadAll(mdcReader) - if err != nil { - t.Errorf("stride: %d, error: %s", stride, err) - continue - } - if !bytes.Equal(body, mdcPlaintext[:len(mdcPlaintext)-22]) { - t.Errorf("stride: %d: bad contents %x", stride, body) - continue - } - - err = mdcReader.Close() - if err != nil { - t.Errorf("stride: %d, error on Close: %s", stride, err) - } - } - - mdcPlaintext[15] ^= 80 - - r := &testReader{data: mdcPlaintext, stride: 2} - mdcReader := &seMDCReader{in: r, h: sha1.New()} - _, err := ioutil.ReadAll(mdcReader) - if err != nil { - t.Errorf("corruption test, error: %s", err) - return - } - err = mdcReader.Close() - if err == nil { - t.Error("corruption: no error") - } else if _, ok := err.(*errors.SignatureError); !ok { - t.Errorf("corruption: expected SignatureError, got: %s", err) - } -} - -const mdcPlaintextHex = "a302789c3b2d93c4e0eb9aba22283539b3203335af44a134afb800c849cb4c4de10200aff40b45d31432c80cb384299a0655966d6939dfdeed1dddf980" - -func TestSerialize(t *testing.T) { - buf := bytes.NewBuffer(nil) - c := CipherAES128 - key := make([]byte, c.KeySize()) - - w, err := SerializeSymmetricallyEncrypted(buf, c, key, nil) - if err != nil { - t.Errorf("error from SerializeSymmetricallyEncrypted: %s", err) - return - } - - contents := []byte("hello world\n") - - w.Write(contents) - w.Close() - - p, err := Read(buf) - if err != nil { - t.Errorf("error from Read: %s", err) - return - } - - se, ok := p.(*SymmetricallyEncrypted) - if !ok { - t.Errorf("didn't read a *SymmetricallyEncrypted") - return - } - - r, err := se.Decrypt(c, key) - if err != nil { - t.Errorf("error from Decrypt: %s", err) - return - } - - contentsCopy := bytes.NewBuffer(nil) - _, err = io.Copy(contentsCopy, r) - if err != nil { - t.Errorf("error from io.Copy: %s", err) - return - } - if !bytes.Equal(contentsCopy.Bytes(), contents) { - t.Errorf("contents not equal got: %x want: %x", contentsCopy.Bytes(), contents) - } -} diff --git a/Godeps/_workspace/src/golang.org/x/crypto/openpgp/packet/userattribute_test.go b/Godeps/_workspace/src/golang.org/x/crypto/openpgp/packet/userattribute_test.go deleted file mode 100644 index 13ca5143c..000000000 --- a/Godeps/_workspace/src/golang.org/x/crypto/openpgp/packet/userattribute_test.go +++ /dev/null @@ -1,109 +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 packet - -import ( - "bytes" - "encoding/base64" - "image/color" - "image/jpeg" - "testing" -) - -func TestParseUserAttribute(t *testing.T) { - r := base64.NewDecoder(base64.StdEncoding, bytes.NewBufferString(userAttributePacket)) - for i := 0; i < 2; i++ { - p, err := Read(r) - if err != nil { - t.Fatal(err) - } - uat := p.(*UserAttribute) - imgs := uat.ImageData() - if len(imgs) != 1 { - t.Errorf("Unexpected number of images in user attribute packet: %d", len(imgs)) - } - if len(imgs[0]) != 3395 { - t.Errorf("Unexpected JPEG image size: %d", len(imgs[0])) - } - img, err := jpeg.Decode(bytes.NewBuffer(imgs[0])) - if err != nil { - t.Errorf("Error decoding JPEG image: %v", err) - } - // A pixel in my right eye. - pixel := color.NRGBAModel.Convert(img.At(56, 36)) - ref := color.NRGBA{R: 157, G: 128, B: 124, A: 255} - if pixel != ref { - t.Errorf("Unexpected pixel color: %v", pixel) - } - w := bytes.NewBuffer(nil) - err = uat.Serialize(w) - if err != nil { - t.Errorf("Error writing user attribute: %v", err) - } - r = bytes.NewBuffer(w.Bytes()) - } -} - -const userAttributePacket = ` -0cyWzJQBEAABAQAAAAAAAAAAAAAAAP/Y/+AAEEpGSUYAAQIAAAEAAQAA/9sAQwAFAwQEBAMFBAQE -BQUFBgcMCAcHBwcPCgsJDBEPEhIRDxEQExYcFxMUGhUQERghGBocHR8fHxMXIiQiHiQcHh8e/9sA -QwEFBQUHBgcOCAgOHhQRFB4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4e -Hh4eHh4eHh4e/8AAEQgAZABkAwEiAAIRAQMRAf/EAB8AAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYH -CAkKC//EALUQAAIBAwMCBAMFBQQEAAABfQECAwAEEQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHw -JDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6 -g4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2drh4uPk -5ebn6Onq8fLz9PX29/j5+v/EAB8BAAMBAQEBAQEBAQEAAAAAAAABAgMEBQYHCAkKC//EALURAAIB -AgQEAwQHBQQEAAECdwABAgMRBAUhMQYSQVEHYXETIjKBCBRCkaGxwQkjM1LwFWJy0QoWJDThJfEX -GBkaJicoKSo1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoKDhIWGh4iJipKT -lJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uLj5OXm5+jp6vLz9PX2 -9/j5+v/aAAwDAQACEQMRAD8A5uGP06VehQ4pIox04q5EnHSvAep+hIIl4zVuMHGPWmRrUWtalaaN -pU2oXsgSGJSxPr6ClvoitErs0Itqjc7BQOpPAFYmrfEnwjojtHNqaXEynBjtx5hH4jj9a8B8d+Od -W8UXZjWR4LJT+7t0Jwfc+prnIdO1CWZEW2mZ3HyDactXXDB3V5s8evm1namj6r0H4weCLtxG+ova -ueP30RA/MV6not1bX0Ed1ZzxzwyDKvGwZSPqK+Ff+ES8R8t/ZV2oHUmM10Hgbxp4m8BatEfNnWBH -/eWshOxx9Kmpg4te49RUM1kn+8Wh9zQ4P1FaMC7l465rjPh14y0fxnoseoaXOpfaPOgJ+eI98j09 -67W19M15bi4uzPSqTU480WXkjZkAyAR61DPE6OCSOalWRRgZxjvTb598sfU4FBwx5uY4T4feIm8P -TeJbAgc65NIM+8cX+FFeLfF3Vr3SfiNrMFrMypJMJcDPUqP8KK+kpVFyLU+ar037SXqX4hxVpMY7 -1UhPpVlT2rybKx9smWYz3NeH/EDVLzxt40j8O6bITaQybPlbKkjq39K9O8fasdH8IahfKxWQRFIy -Ou9uB/OuE/Z/0y3j1d9TuyoZCMs5xjuea1pLli5nn46q240l13PcfhN8EvDNtpcEl/CklyVBLuMk -mvU/Dfwo0BL/AO13FjEDD/qyV7Vn+CvGPg8zRpJrVm8ikLtEg6+1ew2dxZ3EQaJgysuQPasH7eXW -1zzsbVhT92kk/PsYieEND+zlPs6c/wCyAPyryH4wfCPRtW0u6j+xRLOxLxSoADkDpXY+MPjJ4c0S -9k082d3O8ZKkxw5XI96ytK+IGk+IpFjRpod+Qq3C7QT6A1E6NenaXbqRg6rlLlqS0fRnxjpd1r/w -w8afa7GWRPKbZLGeBKmeVNfZngLxNaeKfDdprVjxHcLlkJ5Vh1H5185/tDad9h8XOsqAw3Cb0cjq -CfX61P8AsveKf7L8T3fhe5nxa3g324YniQdh9R/KuivTdSmp9TXB1/Z1nRlsfU249QBx1pWfcwI7 -Cq6u2Ovamb9rYz16V5x7Psz5q/aJhZfibcupIElvE3H+7j+lFbXx9szP45jlUfeso8/99OKK9elL -3EeNVopzZVharCtxVRGGMk02S5JyFOB69zWTieypnL/GksfB+0cr9oQt69awPhPpD69Y3Ky3DWth -CWluGU4LAdq3vibGs/g68BJygVxjrwRW5+ztoRv/AAs8EeCZnO/J/hzz/Kumi4wp3kePjlOdZKPY -ml8Mvo6WM9ppi7J0EkQYMzkb1X0wW+bJHGACa+ivg14huZPCkjXUO6SImIYOQAP6UQ2sGneHmiWF -CYoSAAuM8etXfhBpMr+EZ3SSNRcMx6ZxWdes6ytBGSwkMNFuo7pnP614Ut9Zn1C4uLySKcwObGFA -Qnm4+XcR71h+CfDHiKCQWuv2YWFtw+bBZQD8rcE8n2Ney+GbGGQSM6I7xvtI681rXdp8hKRRp6t3 -FYPE1VDlsY1nQjWdl+J8w/tOeDZZ/AMd/EGefTHyxxyYjwfyODXg3waRh8UtEcFh+8Jb8FNfZPxh -Ak8J6nbPIsiyW7LnseK+Ofh99ptPHFnf2lu0y2twGcKuSEPB/Q1WHk50miq1o14TXU+xop+On61H -NMC6Nis1LgsAcUTSt1APFcXJZn0EqmhyvxA037friTYziBV6f7Tf40Vr3k4aXLx5OMZIzRXZB2ik -efJXbPHJJcnaD9aN2R1qoGO8/WkuLlIV+YjdjpXSonQ5lTxfiTwzqCnkeQxx9BWx+zPrQsrBFYja -zEfrXL6lfie3khcjY6lSPUGud+G3iA6FrY0uQ/KJsA9gCa0jSvFpnBi6tpKSPu++nsIfDFxeXciR -qIicscY4rxTwB8RUkn1axsPEf2LTYx85kTGzqCUP8VcJ47+JOs+I0Hhq1njjt/ufIeSvq1VtE+Gs -eoaUbSHUrkHdu3WtuX5Ix81XRh7OL5jirVpV5Whdn0F8C/iX4auVn0i612T7bASoe8wjTAd89K9g -vtSt5NMa4t5lkRhgOh3Dn6V8aaz8KZrIR3OlQ6r56LySmSxxz06Vo/CHx34h0rxBP4XvJ5AjK2RP -nEbAEj6ZxjPrWM6fMmoswqJxqJ1VZnqHxn1NLPwveqWHmNC2BnnNcD8DfDkGi+CH1m+ijN1qMzNA -4GSIiAMf+hVxPxU8Tapc3c0F9MGCn5GU5BX0Pau3+HmrT3XgXSIJCBHDGdgAx1NYSpezha52Yauq -1dya2Wh2onAIwTj1p0lxxWWLkhRyCKWa5O3ORXOos9KVQluZm83j0oqi84JyWH50Vdmc7ep43d3I -t1Z2Iz2FYdxeSTsxyRnvTdVuDNcNluM9KrKcg817NOnZGNbEXdkNckjrXGeIIprPxFFdRHAlIwem -COtdmxrG8Q2cd/ZNExw45RvQ1bVjim+dWNzw7eaTD4mN3dndCQCo6hmI5zXpj/Ea/wBHjkh0kwRW -xXEfl4yTxXzXZalJDL9nuWKMmRnHcV2Hh3WreCyYXW2SWQhd5P3F6n+lS43d2cTm6d7Ox9EWPxH1 -ODQxPqWpCaSU/ukUc4z3/WvKW8UhviAdaMewYZG98gj9c1ymoa8LyWOJHwkTDaVPb0qpr+q2m6Nb -cfvNo349az9mou9iZVXNWbub3jm98/Vza2ReV7lsJg/e3dsV654UR9N0K0sZP9ZDGFbHr3rzL4P+ -H7rXfEEWr3I3W1qf3IYdW9fwqDxf4k8UeH/G95p08kscHmk25dPlZT0we9YTj7SXKjpw1aNG8mj3 -FLv5ccU959ycnmvKPDnxB82YQarGsZPAlTp+IrvIr1ZIgySKwIyCOhFYTpyg9T0qWIhVV4svzPvf -IdhgY4orPachj81FRdmtzxqdiZmJ9aQEgdqZcPtmbJ71DJcAZ5r20kkeXJtsfPIQDwPzrG1a+S3i -LyHAHvmp7y7HOD1rlNdm+1T7Acovf3o+J2RMpezjzMvrob67pX9o2ShZlYgg/wAWKxZLLWLZ/Ke3 -mVh14yK9M+BMC3dre2ko3LHKCB7EV7EngeGQJdQ7HyBkMKS0djgq1W3c+XtK03U522RwzsTwNiEk -ntXoHgf4calql9El/G8UZbLfLyfr7V9FeGvh+s+0Lbxxcglu2K1NW1nwN4Gk/wBLuI57tV5jjwzE -/QVNS+0dWYRqNvXRFv4eeCodKsY1ggVIY1G3K4z714h+1Jqul3GpwaXYeXJLbzgyyrg4b+6D+HNb -vjz436zq9m+naHF/ZdkeGfOZXH17V4Vqt2b29K+ZuOc5bnce5zWdPBShL2lTfojSeJhy+zp/NjVz -1Bwa6DSfFGq6fbJFDKrov8DjPFcu97ZxsUe4jVhwVJ5Bpp1mwQiLewJPXacVq6fNpYyjOUXdHoKf -EG8VQHsInbuVcgflRXnt5fIs2FYHgcgUVi8LG+xusdW/mN7U2KgEVkTzPt60UVfQ9eHxGHrV1MGi -iD4V25x1qvdgLAMd6KK0pbHm4x++dp8FtUubLxJ5EIjMc+A4Za+qfD8pe1JZVOBmiinW3RyRPMfi -R8QPE638+k2l6LK0Hylbddhb6nOa80mlkcmWR2kcnlnOSaKK7qCXKcNdu5narcSrAoBxvODWJIga -VckjDdqKKwq/EaQ0gUdbjQ6mr7QGBUcd6tPBC6gtGpOOuKKKie5qn7qIpEXd0HSiiimSf//Z` diff --git a/Godeps/_workspace/src/golang.org/x/crypto/openpgp/packet/userid_test.go b/Godeps/_workspace/src/golang.org/x/crypto/openpgp/packet/userid_test.go deleted file mode 100644 index 296819389..000000000 --- a/Godeps/_workspace/src/golang.org/x/crypto/openpgp/packet/userid_test.go +++ /dev/null @@ -1,87 +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 packet - -import ( - "testing" -) - -var userIdTests = []struct { - id string - name, comment, email string -}{ - {"", "", "", ""}, - {"John Smith", "John Smith", "", ""}, - {"John Smith ()", "John Smith", "", ""}, - {"John Smith () <>", "John Smith", "", ""}, - {"(comment", "", "comment", ""}, - {"(comment)", "", "comment", ""}, - {" sdfk", "", "", "email"}, - {" John Smith ( Comment ) asdkflj < email > lksdfj", "John Smith", "Comment", "email"}, - {" John Smith < email > lksdfj", "John Smith", "", "email"}, - {"("}, - {"foo", "bar", "", "foo (bar)"}, - {"foo", "", "baz", "foo "}, - {"", "bar", "baz", "(bar) "}, - {"foo", "bar", "baz", "foo (bar) "}, -} - -func TestNewUserId(t *testing.T) { - for i, test := range newUserIdTests { - uid := NewUserId(test.name, test.comment, test.email) - if uid == nil { - t.Errorf("#%d: returned nil", i) - continue - } - if uid.Id != test.id { - t.Errorf("#%d: got '%s', want '%s'", i, uid.Id, test.id) - } - } -} - -var invalidNewUserIdTests = []struct { - name, comment, email string -}{ - {"foo(", "", ""}, - {"foo<", "", ""}, - {"", "bar)", ""}, - {"", "bar<", ""}, - {"", "", "baz>"}, - {"", "", "baz)"}, - {"", "", "baz\x00"}, -} - -func TestNewUserIdWithInvalidInput(t *testing.T) { - for i, test := range invalidNewUserIdTests { - if uid := NewUserId(test.name, test.comment, test.email); uid != nil { - t.Errorf("#%d: returned non-nil value: %#v", i, uid) - } - } -} diff --git a/Godeps/_workspace/src/golang.org/x/crypto/openpgp/read.go b/Godeps/_workspace/src/golang.org/x/crypto/openpgp/read.go index 7469792a5..33d468d47 100644 --- a/Godeps/_workspace/src/golang.org/x/crypto/openpgp/read.go +++ b/Godeps/_workspace/src/golang.org/x/crypto/openpgp/read.go @@ -8,12 +8,13 @@ package openpgp import ( "crypto" _ "crypto/sha256" - "golang.org/x/crypto/openpgp/armor" - "golang.org/x/crypto/openpgp/errors" - "golang.org/x/crypto/openpgp/packet" "hash" "io" "strconv" + + "golang.org/x/crypto/openpgp/armor" + "golang.org/x/crypto/openpgp/errors" + "golang.org/x/crypto/openpgp/packet" ) // SignatureType is the armor type for a PGP signature. @@ -357,44 +358,55 @@ func (scr *signatureCheckReader) Read(buf []byte) (n int, err error) { // returns the signer if the signature is valid. If the signer isn't known, // ErrUnknownIssuer is returned. func CheckDetachedSignature(keyring KeyRing, signed, signature io.Reader) (signer *Entity, err error) { - p, err := packet.Read(signature) - if err != nil { - return - } - var issuerKeyId uint64 var hashFunc crypto.Hash var sigType packet.SignatureType + var keys []Key + var p packet.Packet - switch sig := p.(type) { - case *packet.Signature: - if sig.IssuerKeyId == nil { - return nil, errors.StructuralError("signature doesn't have an issuer") + packets := packet.NewReader(signature) + for { + p, err = packets.Next() + if err == io.EOF { + return nil, errors.ErrUnknownIssuer } - issuerKeyId = *sig.IssuerKeyId - hashFunc = sig.Hash - sigType = sig.SigType - case *packet.SignatureV3: - issuerKeyId = sig.IssuerKeyId - hashFunc = sig.Hash - sigType = sig.SigType - default: - return nil, errors.StructuralError("non signature packet found") + if err != nil { + return nil, err + } + + switch sig := p.(type) { + case *packet.Signature: + if sig.IssuerKeyId == nil { + return nil, errors.StructuralError("signature doesn't have an issuer") + } + issuerKeyId = *sig.IssuerKeyId + hashFunc = sig.Hash + sigType = sig.SigType + case *packet.SignatureV3: + issuerKeyId = sig.IssuerKeyId + hashFunc = sig.Hash + sigType = sig.SigType + default: + return nil, errors.StructuralError("non signature packet found") + } + + keys = keyring.KeysByIdUsage(issuerKeyId, packet.KeyFlagSign) + if len(keys) > 0 { + break + } + } + + if len(keys) == 0 { + panic("unreachable") } h, wrappedHash, err := hashForSignature(hashFunc, sigType) if err != nil { - return + return nil, err } - _, err = io.Copy(wrappedHash, signed) - if err != nil && err != io.EOF { - return - } - - keys := keyring.KeysByIdUsage(issuerKeyId, packet.KeyFlagSign) - if len(keys) == 0 { - return nil, errors.ErrUnknownIssuer + if _, err := io.Copy(wrappedHash, signed); err != nil && err != io.EOF { + return nil, err } for _, key := range keys { @@ -403,15 +415,15 @@ func CheckDetachedSignature(keyring KeyRing, signed, signature io.Reader) (signe err = key.PublicKey.VerifySignature(h, sig) case *packet.SignatureV3: err = key.PublicKey.VerifySignatureV3(h, sig) + default: + panic("unreachable") } + if err == nil { return key.Entity, nil } } - if err == nil { - err = errors.ErrUnknownIssuer - } return nil, err } diff --git a/Godeps/_workspace/src/golang.org/x/crypto/openpgp/read_test.go b/Godeps/_workspace/src/golang.org/x/crypto/openpgp/read_test.go deleted file mode 100644 index 3d74ea368..000000000 --- a/Godeps/_workspace/src/golang.org/x/crypto/openpgp/read_test.go +++ /dev/null @@ -1,493 +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 openpgp - -import ( - "bytes" - _ "crypto/sha512" - "encoding/hex" - "io" - "io/ioutil" - "strings" - "testing" - - "golang.org/x/crypto/openpgp/errors" -) - -func readerFromHex(s string) io.Reader { - data, err := hex.DecodeString(s) - if err != nil { - panic("readerFromHex: bad input") - } - return bytes.NewBuffer(data) -} - -func TestReadKeyRing(t *testing.T) { - kring, err := ReadKeyRing(readerFromHex(testKeys1And2Hex)) - if err != nil { - t.Error(err) - return - } - if len(kring) != 2 || uint32(kring[0].PrimaryKey.KeyId) != 0xC20C31BB || uint32(kring[1].PrimaryKey.KeyId) != 0x1E35246B { - t.Errorf("bad keyring: %#v", kring) - } -} - -func TestRereadKeyRing(t *testing.T) { - kring, err := ReadKeyRing(readerFromHex(testKeys1And2Hex)) - if err != nil { - t.Errorf("error in initial parse: %s", err) - return - } - out := new(bytes.Buffer) - err = kring[0].Serialize(out) - if err != nil { - t.Errorf("error in serialization: %s", err) - return - } - kring, err = ReadKeyRing(out) - if err != nil { - t.Errorf("error in second parse: %s", err) - return - } - - if len(kring) != 1 || uint32(kring[0].PrimaryKey.KeyId) != 0xC20C31BB { - t.Errorf("bad keyring: %#v", kring) - } -} - -func TestReadPrivateKeyRing(t *testing.T) { - kring, err := ReadKeyRing(readerFromHex(testKeys1And2PrivateHex)) - if err != nil { - t.Error(err) - return - } - if len(kring) != 2 || uint32(kring[0].PrimaryKey.KeyId) != 0xC20C31BB || uint32(kring[1].PrimaryKey.KeyId) != 0x1E35246B || kring[0].PrimaryKey == nil { - t.Errorf("bad keyring: %#v", kring) - } -} - -func TestReadDSAKey(t *testing.T) { - kring, err := ReadKeyRing(readerFromHex(dsaTestKeyHex)) - if err != nil { - t.Error(err) - return - } - if len(kring) != 1 || uint32(kring[0].PrimaryKey.KeyId) != 0x0CCC0360 { - t.Errorf("bad parse: %#v", kring) - } -} - -func TestDSAHashTruncatation(t *testing.T) { - // dsaKeyWithSHA512 was generated with GnuPG and --cert-digest-algo - // SHA512 in order to require DSA hash truncation to verify correctly. - _, err := ReadKeyRing(readerFromHex(dsaKeyWithSHA512)) - if err != nil { - t.Error(err) - } -} - -func TestGetKeyById(t *testing.T) { - kring, _ := ReadKeyRing(readerFromHex(testKeys1And2Hex)) - - keys := kring.KeysById(0xa34d7e18c20c31bb) - if len(keys) != 1 || keys[0].Entity != kring[0] { - t.Errorf("bad result for 0xa34d7e18c20c31bb: %#v", keys) - } - - keys = kring.KeysById(0xfd94408d4543314f) - if len(keys) != 1 || keys[0].Entity != kring[0] { - t.Errorf("bad result for 0xa34d7e18c20c31bb: %#v", keys) - } -} - -func checkSignedMessage(t *testing.T, signedHex, expected string) { - kring, _ := ReadKeyRing(readerFromHex(testKeys1And2Hex)) - - md, err := ReadMessage(readerFromHex(signedHex), kring, nil, nil) - if err != nil { - t.Error(err) - return - } - - if !md.IsSigned || md.SignedByKeyId != 0xa34d7e18c20c31bb || md.SignedBy == nil || md.IsEncrypted || md.IsSymmetricallyEncrypted || len(md.EncryptedToKeyIds) != 0 || md.IsSymmetricallyEncrypted { - t.Errorf("bad MessageDetails: %#v", md) - } - - contents, err := ioutil.ReadAll(md.UnverifiedBody) - if err != nil { - t.Errorf("error reading UnverifiedBody: %s", err) - } - if string(contents) != expected { - t.Errorf("bad UnverifiedBody got:%s want:%s", string(contents), expected) - } - if md.SignatureError != nil || md.Signature == nil { - t.Errorf("failed to validate: %s", md.SignatureError) - } -} - -func TestSignedMessage(t *testing.T) { - checkSignedMessage(t, signedMessageHex, signedInput) -} - -func TestTextSignedMessage(t *testing.T) { - checkSignedMessage(t, signedTextMessageHex, signedTextInput) -} - -// The reader should detect "compressed quines", which are compressed -// packets that expand into themselves and cause an infinite recursive -// parsing loop. -// The packet in this test case comes from Taylor R. Campbell at -// http://mumble.net/~campbell/misc/pgp-quine/ -func TestCampbellQuine(t *testing.T) { - md, err := ReadMessage(readerFromHex(campbellQuine), nil, nil, nil) - if md != nil { - t.Errorf("Reading a compressed quine should not return any data: %#v", md) - } - structural, ok := err.(errors.StructuralError) - if !ok { - t.Fatalf("Unexpected class of error: %T", err) - } - if !strings.Contains(string(structural), "too many layers of packets") { - t.Fatalf("Unexpected error: %s", err) - } -} - -var signedEncryptedMessageTests = []struct { - keyRingHex string - messageHex string - signedByKeyId uint64 - encryptedToKeyId uint64 -}{ - { - testKeys1And2PrivateHex, - signedEncryptedMessageHex, - 0xa34d7e18c20c31bb, - 0x2a67d68660df41c7, - }, - { - dsaElGamalTestKeysHex, - signedEncryptedMessage2Hex, - 0x33af447ccd759b09, - 0xcf6a7abcd43e3673, - }, -} - -func TestSignedEncryptedMessage(t *testing.T) { - for i, test := range signedEncryptedMessageTests { - expected := "Signed and encrypted message\n" - kring, _ := ReadKeyRing(readerFromHex(test.keyRingHex)) - prompt := func(keys []Key, symmetric bool) ([]byte, error) { - if symmetric { - t.Errorf("prompt: message was marked as symmetrically encrypted") - return nil, errors.ErrKeyIncorrect - } - - if len(keys) == 0 { - t.Error("prompt: no keys requested") - return nil, errors.ErrKeyIncorrect - } - - err := keys[0].PrivateKey.Decrypt([]byte("passphrase")) - if err != nil { - t.Errorf("prompt: error decrypting key: %s", err) - return nil, errors.ErrKeyIncorrect - } - - return nil, nil - } - - md, err := ReadMessage(readerFromHex(test.messageHex), kring, prompt, nil) - if err != nil { - t.Errorf("#%d: error reading message: %s", i, err) - return - } - - if !md.IsSigned || md.SignedByKeyId != test.signedByKeyId || md.SignedBy == nil || !md.IsEncrypted || md.IsSymmetricallyEncrypted || len(md.EncryptedToKeyIds) == 0 || md.EncryptedToKeyIds[0] != test.encryptedToKeyId { - t.Errorf("#%d: bad MessageDetails: %#v", i, md) - } - - contents, err := ioutil.ReadAll(md.UnverifiedBody) - if err != nil { - t.Errorf("#%d: error reading UnverifiedBody: %s", i, err) - } - if string(contents) != expected { - t.Errorf("#%d: bad UnverifiedBody got:%s want:%s", i, string(contents), expected) - } - - if md.SignatureError != nil || md.Signature == nil { - t.Errorf("#%d: failed to validate: %s", i, md.SignatureError) - } - } -} - -func TestUnspecifiedRecipient(t *testing.T) { - expected := "Recipient unspecified\n" - kring, _ := ReadKeyRing(readerFromHex(testKeys1And2PrivateHex)) - - md, err := ReadMessage(readerFromHex(recipientUnspecifiedHex), kring, nil, nil) - if err != nil { - t.Errorf("error reading message: %s", err) - return - } - - contents, err := ioutil.ReadAll(md.UnverifiedBody) - if err != nil { - t.Errorf("error reading UnverifiedBody: %s", err) - } - if string(contents) != expected { - t.Errorf("bad UnverifiedBody got:%s want:%s", string(contents), expected) - } -} - -func TestSymmetricallyEncrypted(t *testing.T) { - expected := "Symmetrically encrypted.\n" - - prompt := func(keys []Key, symmetric bool) ([]byte, error) { - if len(keys) != 0 { - t.Errorf("prompt: len(keys) = %d (want 0)", len(keys)) - } - - if !symmetric { - t.Errorf("symmetric is not set") - } - - return []byte("password"), nil - } - - md, err := ReadMessage(readerFromHex(symmetricallyEncryptedCompressedHex), nil, prompt, nil) - if err != nil { - t.Errorf("ReadMessage: %s", err) - return - } - - contents, err := ioutil.ReadAll(md.UnverifiedBody) - if err != nil { - t.Errorf("ReadAll: %s", err) - } - - expectedCreationTime := uint32(1295992998) - if md.LiteralData.Time != expectedCreationTime { - t.Errorf("LiteralData.Time is %d, want %d", md.LiteralData.Time, expectedCreationTime) - } - - if string(contents) != expected { - t.Errorf("contents got: %s want: %s", string(contents), expected) - } -} - -func testDetachedSignature(t *testing.T, kring KeyRing, signature io.Reader, sigInput, tag string, expectedSignerKeyId uint64) { - signed := bytes.NewBufferString(sigInput) - signer, err := CheckDetachedSignature(kring, signed, signature) - if err != nil { - t.Errorf("%s: signature error: %s", tag, err) - return - } - if signer == nil { - t.Errorf("%s: signer is nil", tag) - return - } - if signer.PrimaryKey.KeyId != expectedSignerKeyId { - t.Errorf("%s: wrong signer got:%x want:%x", tag, signer.PrimaryKey.KeyId, expectedSignerKeyId) - } -} - -func TestDetachedSignature(t *testing.T) { - kring, _ := ReadKeyRing(readerFromHex(testKeys1And2Hex)) - testDetachedSignature(t, kring, readerFromHex(detachedSignatureHex), signedInput, "binary", testKey1KeyId) - testDetachedSignature(t, kring, readerFromHex(detachedSignatureTextHex), signedInput, "text", testKey1KeyId) - testDetachedSignature(t, kring, readerFromHex(detachedSignatureV3TextHex), signedInput, "v3", testKey1KeyId) - - incorrectSignedInput := signedInput + "X" - _, err := CheckDetachedSignature(kring, bytes.NewBufferString(incorrectSignedInput), readerFromHex(detachedSignatureHex)) - if err == nil { - t.Fatal("CheckDetachedSignature returned without error for bad signature") - } - if err == errors.ErrUnknownIssuer { - t.Fatal("CheckDetachedSignature returned ErrUnknownIssuer when the signer was known, but the signature invalid") - } -} - -func TestDetachedSignatureDSA(t *testing.T) { - kring, _ := ReadKeyRing(readerFromHex(dsaTestKeyHex)) - testDetachedSignature(t, kring, readerFromHex(detachedSignatureDSAHex), signedInput, "binary", testKey3KeyId) -} - -func testHashFunctionError(t *testing.T, signatureHex string) { - kring, _ := ReadKeyRing(readerFromHex(testKeys1And2Hex)) - _, err := CheckDetachedSignature(kring, nil, readerFromHex(signatureHex)) - if err == nil { - t.Fatal("Packet with bad hash type was correctly parsed") - } - unsupported, ok := err.(errors.UnsupportedError) - if !ok { - t.Fatalf("Unexpected class of error: %s", err) - } - if !strings.Contains(string(unsupported), "hash ") { - t.Fatalf("Unexpected error: %s", err) - } -} - -func TestUnknownHashFunction(t *testing.T) { - // unknownHashFunctionHex contains a signature packet with hash - // function type 153 (which isn't a real hash function id). - testHashFunctionError(t, unknownHashFunctionHex) -} - -func TestMissingHashFunction(t *testing.T) { - // missingHashFunctionHex contains a signature packet that uses - // RIPEMD160, which isn't compiled in. - testHashFunctionError(t, missingHashFunctionHex) -} - -func TestReadingArmoredPrivateKey(t *testing.T) { - el, err := ReadArmoredKeyRing(bytes.NewBufferString(armoredPrivateKeyBlock)) - if err != nil { - t.Error(err) - } - if len(el) != 1 { - t.Errorf("got %d entities, wanted 1\n", len(el)) - } -} - -func TestReadingArmoredPublicKey(t *testing.T) { - el, err := ReadArmoredKeyRing(bytes.NewBufferString(e2ePublicKey)) - if err != nil { - t.Error(err) - } - if len(el) != 1 { - t.Errorf("didn't get a valid entity") - } -} - -func TestNoArmoredData(t *testing.T) { - _, err := ReadArmoredKeyRing(bytes.NewBufferString("foo")) - if _, ok := err.(errors.InvalidArgumentError); !ok { - t.Errorf("error was not an InvalidArgumentError: %s", err) - } -} - -func testReadMessageError(t *testing.T, messageHex string) { - buf, err := hex.DecodeString(messageHex) - if err != nil { - t.Errorf("hex.DecodeString(): %v", err) - } - - kr, err := ReadKeyRing(new(bytes.Buffer)) - if err != nil { - t.Errorf("ReadKeyring(): %v", err) - } - - _, err = ReadMessage(bytes.NewBuffer(buf), kr, - func([]Key, bool) ([]byte, error) { - return []byte("insecure"), nil - }, nil) - - if err == nil { - t.Errorf("ReadMessage(): Unexpected nil error") - } -} - -func TestIssue11503(t *testing.T) { - testReadMessageError(t, "8c040402000aa430aa8228b9248b01fc899a91197130303030") -} - -func TestIssue11504(t *testing.T) { - testReadMessageError(t, "9303000130303030303030303030983002303030303030030000000130") -} - -const testKey1KeyId = 0xA34D7E18C20C31BB -const testKey3KeyId = 0x338934250CCC0360 - -const signedInput = "Signed message\nline 2\nline 3\n" -const signedTextInput = "Signed message\r\nline 2\r\nline 3\r\n" - -const recipientUnspecifiedHex = "848c0300000000000000000103ff62d4d578d03cf40c3da998dfe216c074fa6ddec5e31c197c9666ba292830d91d18716a80f699f9d897389a90e6d62d0238f5f07a5248073c0f24920e4bc4a30c2d17ee4e0cae7c3d4aaa4e8dced50e3010a80ee692175fa0385f62ecca4b56ee6e9980aa3ec51b61b077096ac9e800edaf161268593eedb6cc7027ff5cb32745d250010d407a6221ae22ef18469b444f2822478c4d190b24d36371a95cb40087cdd42d9399c3d06a53c0673349bfb607927f20d1e122bde1e2bf3aa6cae6edf489629bcaa0689539ae3b718914d88ededc3b" - -const detachedSignatureHex = "889c04000102000605024d449cd1000a0910a34d7e18c20c31bb167603ff57718d09f28a519fdc7b5a68b6a3336da04df85e38c5cd5d5bd2092fa4629848a33d85b1729402a2aab39c3ac19f9d573f773cc62c264dc924c067a79dfd8a863ae06c7c8686120760749f5fd9b1e03a64d20a7df3446ddc8f0aeadeaeba7cbaee5c1e366d65b6a0c6cc749bcb912d2f15013f812795c2e29eb7f7b77f39ce77" - -const detachedSignatureTextHex = "889c04010102000605024d449d21000a0910a34d7e18c20c31bbc8c60400a24fbef7342603a41cb1165767bd18985d015fb72fe05db42db36cfb2f1d455967f1e491194fbf6cf88146222b23bf6ffbd50d17598d976a0417d3192ff9cc0034fd00f287b02e90418bbefe609484b09231e4e7a5f3562e199bf39909ab5276c4d37382fe088f6b5c3426fc1052865da8b3ab158672d58b6264b10823dc4b39" - -const detachedSignatureV3TextHex = "8900950305005255c25ca34d7e18c20c31bb0102bb3f04009f6589ef8a028d6e54f6eaf25432e590d31c3a41f4710897585e10c31e5e332c7f9f409af8512adceaff24d0da1474ab07aa7bce4f674610b010fccc5b579ae5eb00a127f272fb799f988ab8e4574c141da6dbfecfef7e6b2c478d9a3d2551ba741f260ee22bec762812f0053e05380bfdd55ad0f22d8cdf71b233fe51ae8a24" - -const detachedSignatureDSAHex = "884604001102000605024d6c4eac000a0910338934250ccc0360f18d00a087d743d6405ed7b87755476629600b8b694a39e900a0abff8126f46faf1547c1743c37b21b4ea15b8f83" - -const testKeys1And2Hex = "988d044d3c5c10010400b1d13382944bd5aba23a4312968b5095d14f947f600eb478e14a6fcb16b0e0cac764884909c020bc495cfcc39a935387c661507bdb236a0612fb582cac3af9b29cc2c8c70090616c41b662f4da4c1201e195472eb7f4ae1ccbcbf9940fe21d985e379a5563dde5b9a23d35f1cfaa5790da3b79db26f23695107bfaca8e7b5bcd0011010001b41054657374204b6579203120285253412988b804130102002205024d3c5c10021b03060b090807030206150802090a0b0416020301021e01021780000a0910a34d7e18c20c31bbb5b304009cc45fe610b641a2c146331be94dade0a396e73ca725e1b25c21708d9cab46ecca5ccebc23055879df8f99eea39b377962a400f2ebdc36a7c99c333d74aeba346315137c3ff9d0a09b0273299090343048afb8107cf94cbd1400e3026f0ccac7ecebbc4d78588eb3e478fe2754d3ca664bcf3eac96ca4a6b0c8d7df5102f60f6b0020003b88d044d3c5c10010400b201df61d67487301f11879d514f4248ade90c8f68c7af1284c161098de4c28c2850f1ec7b8e30f959793e571542ffc6532189409cb51c3d30dad78c4ad5165eda18b20d9826d8707d0f742e2ab492103a85bbd9ddf4f5720f6de7064feb0d39ee002219765bb07bcfb8b877f47abe270ddeda4f676108cecb6b9bb2ad484a4f0011010001889f04180102000905024d3c5c10021b0c000a0910a34d7e18c20c31bb1a03040085c8d62e16d05dc4e9dad64953c8a2eed8b6c12f92b1575eeaa6dcf7be9473dd5b24b37b6dffbb4e7c99ed1bd3cb11634be19b3e6e207bed7505c7ca111ccf47cb323bf1f8851eb6360e8034cbff8dd149993c959de89f8f77f38e7e98b8e3076323aa719328e2b408db5ec0d03936efd57422ba04f925cdc7b4c1af7590e40ab0020003988d044d3c5c33010400b488c3e5f83f4d561f317817538d9d0397981e9aef1321ca68ebfae1cf8b7d388e19f4b5a24a82e2fbbf1c6c26557a6c5845307a03d815756f564ac7325b02bc83e87d5480a8fae848f07cb891f2d51ce7df83dcafdc12324517c86d472cc0ee10d47a68fd1d9ae49a6c19bbd36d82af597a0d88cc9c49de9df4e696fc1f0b5d0011010001b42754657374204b6579203220285253412c20656e637279707465642070726976617465206b65792988b804130102002205024d3c5c33021b03060b090807030206150802090a0b0416020301021e01021780000a0910d4984f961e35246b98940400908a73b6a6169f700434f076c6c79015a49bee37130eaf23aaa3cfa9ce60bfe4acaa7bc95f1146ada5867e0079babb38804891f4f0b8ebca57a86b249dee786161a755b7a342e68ccf3f78ed6440a93a6626beb9a37aa66afcd4f888790cb4bb46d94a4ae3eb3d7d3e6b00f6bfec940303e89ec5b32a1eaaacce66497d539328b0020003b88d044d3c5c33010400a4e913f9442abcc7f1804ccab27d2f787ffa592077ca935a8bb23165bd8d57576acac647cc596b2c3f814518cc8c82953c7a4478f32e0cf645630a5ba38d9618ef2bc3add69d459ae3dece5cab778938d988239f8c5ae437807075e06c828019959c644ff05ef6a5a1dab72227c98e3a040b0cf219026640698d7a13d8538a570011010001889f04180102000905024d3c5c33021b0c000a0910d4984f961e35246b26c703ff7ee29ef53bc1ae1ead533c408fa136db508434e233d6e62be621e031e5940bbd4c08142aed0f82217e7c3e1ec8de574bc06ccf3c36633be41ad78a9eacd209f861cae7b064100758545cc9dd83db71806dc1cfd5fb9ae5c7474bba0c19c44034ae61bae5eca379383339dece94ff56ff7aa44a582f3e5c38f45763af577c0934b0020003" - -const testKeys1And2PrivateHex = "9501d8044d3c5c10010400b1d13382944bd5aba23a4312968b5095d14f947f600eb478e14a6fcb16b0e0cac764884909c020bc495cfcc39a935387c661507bdb236a0612fb582cac3af9b29cc2c8c70090616c41b662f4da4c1201e195472eb7f4ae1ccbcbf9940fe21d985e379a5563dde5b9a23d35f1cfaa5790da3b79db26f23695107bfaca8e7b5bcd00110100010003ff4d91393b9a8e3430b14d6209df42f98dc927425b881f1209f319220841273a802a97c7bdb8b3a7740b3ab5866c4d1d308ad0d3a79bd1e883aacf1ac92dfe720285d10d08752a7efe3c609b1d00f17f2805b217be53999a7da7e493bfc3e9618fd17018991b8128aea70a05dbce30e4fbe626aa45775fa255dd9177aabf4df7cf0200c1ded12566e4bc2bb590455e5becfb2e2c9796482270a943343a7835de41080582c2be3caf5981aa838140e97afa40ad652a0b544f83eb1833b0957dce26e47b0200eacd6046741e9ce2ec5beb6fb5e6335457844fb09477f83b050a96be7da043e17f3a9523567ed40e7a521f818813a8b8a72209f1442844843ccc7eb9805442570200bdafe0438d97ac36e773c7162028d65844c4d463e2420aa2228c6e50dc2743c3d6c72d0d782a5173fe7be2169c8a9f4ef8a7cf3e37165e8c61b89c346cdc6c1799d2b41054657374204b6579203120285253412988b804130102002205024d3c5c10021b03060b090807030206150802090a0b0416020301021e01021780000a0910a34d7e18c20c31bbb5b304009cc45fe610b641a2c146331be94dade0a396e73ca725e1b25c21708d9cab46ecca5ccebc23055879df8f99eea39b377962a400f2ebdc36a7c99c333d74aeba346315137c3ff9d0a09b0273299090343048afb8107cf94cbd1400e3026f0ccac7ecebbc4d78588eb3e478fe2754d3ca664bcf3eac96ca4a6b0c8d7df5102f60f6b00200009d01d8044d3c5c10010400b201df61d67487301f11879d514f4248ade90c8f68c7af1284c161098de4c28c2850f1ec7b8e30f959793e571542ffc6532189409cb51c3d30dad78c4ad5165eda18b20d9826d8707d0f742e2ab492103a85bbd9ddf4f5720f6de7064feb0d39ee002219765bb07bcfb8b877f47abe270ddeda4f676108cecb6b9bb2ad484a4f00110100010003fd17a7490c22a79c59281fb7b20f5e6553ec0c1637ae382e8adaea295f50241037f8997cf42c1ce26417e015091451b15424b2c59eb8d4161b0975630408e394d3b00f88d4b4e18e2cc85e8251d4753a27c639c83f5ad4a571c4f19d7cd460b9b73c25ade730c99df09637bd173d8e3e981ac64432078263bb6dc30d3e974150dd0200d0ee05be3d4604d2146fb0457f31ba17c057560785aa804e8ca5530a7cd81d3440d0f4ba6851efcfd3954b7e68908fc0ba47f7ac37bf559c6c168b70d3a7c8cd0200da1c677c4bce06a068070f2b3733b0a714e88d62aa3f9a26c6f5216d48d5c2b5624144f3807c0df30be66b3268eeeca4df1fbded58faf49fc95dc3c35f134f8b01fd1396b6c0fc1b6c4f0eb8f5e44b8eace1e6073e20d0b8bc5385f86f1cf3f050f66af789f3ef1fc107b7f4421e19e0349c730c68f0a226981f4e889054fdb4dc149e8e889f04180102000905024d3c5c10021b0c000a0910a34d7e18c20c31bb1a03040085c8d62e16d05dc4e9dad64953c8a2eed8b6c12f92b1575eeaa6dcf7be9473dd5b24b37b6dffbb4e7c99ed1bd3cb11634be19b3e6e207bed7505c7ca111ccf47cb323bf1f8851eb6360e8034cbff8dd149993c959de89f8f77f38e7e98b8e3076323aa719328e2b408db5ec0d03936efd57422ba04f925cdc7b4c1af7590e40ab00200009501fe044d3c5c33010400b488c3e5f83f4d561f317817538d9d0397981e9aef1321ca68ebfae1cf8b7d388e19f4b5a24a82e2fbbf1c6c26557a6c5845307a03d815756f564ac7325b02bc83e87d5480a8fae848f07cb891f2d51ce7df83dcafdc12324517c86d472cc0ee10d47a68fd1d9ae49a6c19bbd36d82af597a0d88cc9c49de9df4e696fc1f0b5d0011010001fe030302e9030f3c783e14856063f16938530e148bc57a7aa3f3e4f90df9dceccdc779bc0835e1ad3d006e4a8d7b36d08b8e0de5a0d947254ecfbd22037e6572b426bcfdc517796b224b0036ff90bc574b5509bede85512f2eefb520fb4b02aa523ba739bff424a6fe81c5041f253f8d757e69a503d3563a104d0d49e9e890b9d0c26f96b55b743883b472caa7050c4acfd4a21f875bdf1258d88bd61224d303dc9df77f743137d51e6d5246b88c406780528fd9a3e15bab5452e5b93970d9dcc79f48b38651b9f15bfbcf6da452837e9cc70683d1bdca94507870f743e4ad902005812488dd342f836e72869afd00ce1850eea4cfa53ce10e3608e13d3c149394ee3cbd0e23d018fcbcb6e2ec5a1a22972d1d462ca05355d0d290dd2751e550d5efb38c6c89686344df64852bf4ff86638708f644e8ec6bd4af9b50d8541cb91891a431326ab2e332faa7ae86cfb6e0540aa63160c1e5cdd5a4add518b303fff0a20117c6bc77f7cfbaf36b04c865c6c2b42754657374204b6579203220285253412c20656e637279707465642070726976617465206b65792988b804130102002205024d3c5c33021b03060b090807030206150802090a0b0416020301021e01021780000a0910d4984f961e35246b98940400908a73b6a6169f700434f076c6c79015a49bee37130eaf23aaa3cfa9ce60bfe4acaa7bc95f1146ada5867e0079babb38804891f4f0b8ebca57a86b249dee786161a755b7a342e68ccf3f78ed6440a93a6626beb9a37aa66afcd4f888790cb4bb46d94a4ae3eb3d7d3e6b00f6bfec940303e89ec5b32a1eaaacce66497d539328b00200009d01fe044d3c5c33010400a4e913f9442abcc7f1804ccab27d2f787ffa592077ca935a8bb23165bd8d57576acac647cc596b2c3f814518cc8c82953c7a4478f32e0cf645630a5ba38d9618ef2bc3add69d459ae3dece5cab778938d988239f8c5ae437807075e06c828019959c644ff05ef6a5a1dab72227c98e3a040b0cf219026640698d7a13d8538a570011010001fe030302e9030f3c783e148560f936097339ae381d63116efcf802ff8b1c9360767db5219cc987375702a4123fd8657d3e22700f23f95020d1b261eda5257e9a72f9a918e8ef22dd5b3323ae03bbc1923dd224db988cadc16acc04b120a9f8b7e84da9716c53e0334d7b66586ddb9014df604b41be1e960dcfcbc96f4ed150a1a0dd070b9eb14276b9b6be413a769a75b519a53d3ecc0c220e85cd91ca354d57e7344517e64b43b6e29823cbd87eae26e2b2e78e6dedfbb76e3e9f77bcb844f9a8932eb3db2c3f9e44316e6f5d60e9e2a56e46b72abe6b06dc9a31cc63f10023d1f5e12d2a3ee93b675c96f504af0001220991c88db759e231b3320dcedf814dcf723fd9857e3d72d66a0f2af26950b915abdf56c1596f46a325bf17ad4810d3535fb02a259b247ac3dbd4cc3ecf9c51b6c07cebb009c1506fba0a89321ec8683e3fd009a6e551d50243e2d5092fefb3321083a4bad91320dc624bd6b5dddf93553e3d53924c05bfebec1fb4bd47e89a1a889f04180102000905024d3c5c33021b0c000a0910d4984f961e35246b26c703ff7ee29ef53bc1ae1ead533c408fa136db508434e233d6e62be621e031e5940bbd4c08142aed0f82217e7c3e1ec8de574bc06ccf3c36633be41ad78a9eacd209f861cae7b064100758545cc9dd83db71806dc1cfd5fb9ae5c7474bba0c19c44034ae61bae5eca379383339dece94ff56ff7aa44a582f3e5c38f45763af577c0934b0020000" - -const dsaElGamalTestKeysHex = "9501e1044dfcb16a110400aa3e5c1a1f43dd28c2ffae8abf5cfce555ee874134d8ba0a0f7b868ce2214beddc74e5e1e21ded354a95d18acdaf69e5e342371a71fbb9093162e0c5f3427de413a7f2c157d83f5cd2f9d791256dc4f6f0e13f13c3302af27f2384075ab3021dff7a050e14854bbde0a1094174855fc02f0bae8e00a340d94a1f22b32e48485700a0cec672ac21258fb95f61de2ce1af74b2c4fa3e6703ff698edc9be22c02ae4d916e4fa223f819d46582c0516235848a77b577ea49018dcd5e9e15cff9dbb4663a1ae6dd7580fa40946d40c05f72814b0f88481207e6c0832c3bded4853ebba0a7e3bd8e8c66df33d5a537cd4acf946d1080e7a3dcea679cb2b11a72a33a2b6a9dc85f466ad2ddf4c3db6283fa645343286971e3dd700703fc0c4e290d45767f370831a90187e74e9972aae5bff488eeff7d620af0362bfb95c1a6c3413ab5d15a2e4139e5d07a54d72583914661ed6a87cce810be28a0aa8879a2dd39e52fb6fe800f4f181ac7e328f740cde3d09a05cecf9483e4cca4253e60d4429ffd679d9996a520012aad119878c941e3cf151459873bdfc2a9563472fe0303027a728f9feb3b864260a1babe83925ce794710cfd642ee4ae0e5b9d74cee49e9c67b6cd0ea5dfbb582132195a121356a1513e1bca73e5b80c58c7ccb4164453412f456c47616d616c2054657374204b65792031886204131102002205024dfcb16a021b03060b090807030206150802090a0b0416020301021e01021780000a091033af447ccd759b09fadd00a0b8fd6f5a790bad7e9f2dbb7632046dc4493588db009c087c6a9ba9f7f49fab221587a74788c00db4889ab00200009d0157044dfcb16a1004008dec3f9291205255ccff8c532318133a6840739dd68b03ba942676f9038612071447bf07d00d559c5c0875724ea16a4c774f80d8338b55fca691a0522e530e604215b467bbc9ccfd483a1da99d7bc2648b4318fdbd27766fc8bfad3fddb37c62b8ae7ccfe9577e9b8d1e77c1d417ed2c2ef02d52f4da11600d85d3229607943700030503ff506c94c87c8cab778e963b76cf63770f0a79bf48fb49d3b4e52234620fc9f7657f9f8d56c96a2b7c7826ae6b57ebb2221a3fe154b03b6637cea7e6d98e3e45d87cf8dc432f723d3d71f89c5192ac8d7290684d2c25ce55846a80c9a7823f6acd9bb29fa6cd71f20bc90eccfca20451d0c976e460e672b000df49466408d527affe0303027a728f9feb3b864260abd761730327bca2aaa4ea0525c175e92bf240682a0e83b226f97ecb2e935b62c9a133858ce31b271fa8eb41f6a1b3cd72a63025ce1a75ee4180dcc284884904181102000905024dfcb16a021b0c000a091033af447ccd759b09dd0b009e3c3e7296092c81bee5a19929462caaf2fff3ae26009e218c437a2340e7ea628149af1ec98ec091a43992b00200009501e1044dfcb1be1104009f61faa61aa43df75d128cbe53de528c4aec49ce9360c992e70c77072ad5623de0a3a6212771b66b39a30dad6781799e92608316900518ec01184a85d872365b7d2ba4bacfb5882ea3c2473d3750dc6178cc1cf82147fb58caa28b28e9f12f6d1efcb0534abed644156c91cca4ab78834268495160b2400bc422beb37d237c2300a0cac94911b6d493bda1e1fbc6feeca7cb7421d34b03fe22cec6ccb39675bb7b94a335c2b7be888fd3906a1125f33301d8aa6ec6ee6878f46f73961c8d57a3e9544d8ef2a2cbfd4d52da665b1266928cfe4cb347a58c412815f3b2d2369dec04b41ac9a71cc9547426d5ab941cccf3b18575637ccfb42df1a802df3cfe0a999f9e7109331170e3a221991bf868543960f8c816c28097e503fe319db10fb98049f3a57d7c80c420da66d56f3644371631fad3f0ff4040a19a4fedc2d07727a1b27576f75a4d28c47d8246f27071e12d7a8de62aad216ddbae6aa02efd6b8a3e2818cda48526549791ab277e447b3a36c57cefe9b592f5eab73959743fcc8e83cbefec03a329b55018b53eec196765ae40ef9e20521a603c551efe0303020950d53a146bf9c66034d00c23130cce95576a2ff78016ca471276e8227fb30b1ffbd92e61804fb0c3eff9e30b1a826ee8f3e4730b4d86273ca977b4164453412f456c47616d616c2054657374204b65792032886204131102002205024dfcb1be021b03060b090807030206150802090a0b0416020301021e01021780000a0910a86bf526325b21b22bd9009e34511620415c974750a20df5cb56b182f3b48e6600a0a9466cb1a1305a84953445f77d461593f1d42bc1b00200009d0157044dfcb1be1004009565a951da1ee87119d600c077198f1c1bceb0f7aa54552489298e41ff788fa8f0d43a69871f0f6f77ebdfb14a4260cf9fbeb65d5844b4272a1904dd95136d06c3da745dc46327dd44a0f16f60135914368c8039a34033862261806bb2c5ce1152e2840254697872c85441ccb7321431d75a747a4bfb1d2c66362b51ce76311700030503fc0ea76601c196768070b7365a200e6ddb09307f262d5f39eec467b5f5784e22abdf1aa49226f59ab37cb49969d8f5230ea65caf56015abda62604544ed526c5c522bf92bed178a078789f6c807b6d34885688024a5bed9e9f8c58d11d4b82487b44c5f470c5606806a0443b79cadb45e0f897a561a53f724e5349b9267c75ca17fe0303020950d53a146bf9c660bc5f4ce8f072465e2d2466434320c1e712272fafc20e342fe7608101580fa1a1a367e60486a7cd1246b7ef5586cf5e10b32762b710a30144f12dd17dd4884904181102000905024dfcb1be021b0c000a0910a86bf526325b21b2904c00a0b2b66b4b39ccffda1d10f3ea8d58f827e30a8b8e009f4255b2d8112a184e40cde43a34e8655ca7809370b0020000" - -const signedMessageHex = "a3019bc0cbccc0c4b8d8b74ee2108fe16ec6d3ca490cbe362d3f8333d3f352531472538b8b13d353b97232f352158c20943157c71c16064626063656269052062e4e01987e9b6fccff4b7df3a34c534b23e679cbec3bc0f8f6e64dfb4b55fe3f8efa9ce110ddb5cd79faf1d753c51aecfa669f7e7aa043436596cccc3359cb7dd6bbe9ecaa69e5989d9e57209571edc0b2fa7f57b9b79a64ee6e99ce1371395fee92fec2796f7b15a77c386ff668ee27f6d38f0baa6c438b561657377bf6acff3c5947befd7bf4c196252f1d6e5c524d0300" - -const signedTextMessageHex = "a3019bc0cbccc8c4b8d8b74ee2108fe16ec6d36a250cbece0c178233d3f352531472538b8b13d35379b97232f352158ca0b4312f57c71c1646462606365626906a062e4e019811591798ff99bf8afee860b0d8a8c2a85c3387e3bcf0bb3b17987f2bbcfab2aa526d930cbfd3d98757184df3995c9f3e7790e36e3e9779f06089d4c64e9e47dd6202cb6e9bc73c5d11bb59fbaf89d22d8dc7cf199ddf17af96e77c5f65f9bbed56f427bd8db7af37f6c9984bf9385efaf5f184f986fb3e6adb0ecfe35bbf92d16a7aa2a344fb0bc52fb7624f0200" - -const signedEncryptedMessageHex = "848c032a67d68660df41c70103ff5789d0de26b6a50c985a02a13131ca829c413a35d0e6fa8d6842599252162808ac7439c72151c8c6183e76923fe3299301414d0c25a2f06a2257db3839e7df0ec964773f6e4c4ac7ff3b48c444237166dd46ba8ff443a5410dc670cb486672fdbe7c9dfafb75b4fea83af3a204fe2a7dfa86bd20122b4f3d2646cbeecb8f7be8d2c03b018bd210b1d3791e1aba74b0f1034e122ab72e760492c192383cf5e20b5628bd043272d63df9b923f147eb6091cd897553204832aba48fec54aa447547bb16305a1024713b90e77fd0065f1918271947549205af3c74891af22ee0b56cd29bfec6d6e351901cd4ab3ece7c486f1e32a792d4e474aed98ee84b3f591c7dff37b64e0ecd68fd036d517e412dcadf85840ce184ad7921ad446c4ee28db80447aea1ca8d4f574db4d4e37688158ddd19e14ee2eab4873d46947d65d14a23e788d912cf9a19624ca7352469b72a83866b7c23cb5ace3deab3c7018061b0ba0f39ed2befe27163e5083cf9b8271e3e3d52cc7ad6e2a3bd81d4c3d7022f8d" - -const signedEncryptedMessage2Hex = "85010e03cf6a7abcd43e36731003fb057f5495b79db367e277cdbe4ab90d924ddee0c0381494112ff8c1238fb0184af35d1731573b01bc4c55ecacd2aafbe2003d36310487d1ecc9ac994f3fada7f9f7f5c3a64248ab7782906c82c6ff1303b69a84d9a9529c31ecafbcdb9ba87e05439897d87e8a2a3dec55e14df19bba7f7bd316291c002ae2efd24f83f9e3441203fc081c0c23dc3092a454ca8a082b27f631abf73aca341686982e8fbda7e0e7d863941d68f3de4a755c2964407f4b5e0477b3196b8c93d551dd23c8beef7d0f03fbb1b6066f78907faf4bf1677d8fcec72651124080e0b7feae6b476e72ab207d38d90b958759fdedfc3c6c35717c9dbfc979b3cfbbff0a76d24a5e57056bb88acbd2a901ef64bc6e4db02adc05b6250ff378de81dca18c1910ab257dff1b9771b85bb9bbe0a69f5989e6d1710a35e6dfcceb7d8fb5ccea8db3932b3d9ff3fe0d327597c68b3622aec8e3716c83a6c93f497543b459b58ba504ed6bcaa747d37d2ca746fe49ae0a6ce4a8b694234e941b5159ff8bd34b9023da2814076163b86f40eed7c9472f81b551452d5ab87004a373c0172ec87ea6ce42ccfa7dbdad66b745496c4873d8019e8c28d6b3" - -const symmetricallyEncryptedCompressedHex = "8c0d04030302eb4a03808145d0d260c92f714339e13de5a79881216431925bf67ee2898ea61815f07894cd0703c50d0a76ef64d482196f47a8bc729af9b80bb6" - -const dsaTestKeyHex = "9901a2044d6c49de110400cb5ce438cf9250907ac2ba5bf6547931270b89f7c4b53d9d09f4d0213a5ef2ec1f26806d3d259960f872a4a102ef1581ea3f6d6882d15134f21ef6a84de933cc34c47cc9106efe3bd84c6aec12e78523661e29bc1a61f0aab17fa58a627fd5fd33f5149153fbe8cd70edf3d963bc287ef875270ff14b5bfdd1bca4483793923b00a0fe46d76cb6e4cbdc568435cd5480af3266d610d303fe33ae8273f30a96d4d34f42fa28ce1112d425b2e3bf7ea553d526e2db6b9255e9dc7419045ce817214d1a0056dbc8d5289956a4b1b69f20f1105124096e6a438f41f2e2495923b0f34b70642607d45559595c7fe94d7fa85fc41bf7d68c1fd509ebeaa5f315f6059a446b9369c277597e4f474a9591535354c7e7f4fd98a08aa60400b130c24ff20bdfbf683313f5daebf1c9b34b3bdadfc77f2ddd72ee1fb17e56c473664bc21d66467655dd74b9005e3a2bacce446f1920cd7017231ae447b67036c9b431b8179deacd5120262d894c26bc015bffe3d827ba7087ad9b700d2ca1f6d16cc1786581e5dd065f293c31209300f9b0afcc3f7c08dd26d0a22d87580b4db41054657374204b65792033202844534129886204131102002205024d6c49de021b03060b090807030206150802090a0b0416020301021e01021780000a0910338934250ccc03607e0400a0bdb9193e8a6b96fc2dfc108ae848914b504481f100a09c4dc148cb693293a67af24dd40d2b13a9e36794" - -const dsaTestKeyPrivateHex = "9501bb044d6c49de110400cb5ce438cf9250907ac2ba5bf6547931270b89f7c4b53d9d09f4d0213a5ef2ec1f26806d3d259960f872a4a102ef1581ea3f6d6882d15134f21ef6a84de933cc34c47cc9106efe3bd84c6aec12e78523661e29bc1a61f0aab17fa58a627fd5fd33f5149153fbe8cd70edf3d963bc287ef875270ff14b5bfdd1bca4483793923b00a0fe46d76cb6e4cbdc568435cd5480af3266d610d303fe33ae8273f30a96d4d34f42fa28ce1112d425b2e3bf7ea553d526e2db6b9255e9dc7419045ce817214d1a0056dbc8d5289956a4b1b69f20f1105124096e6a438f41f2e2495923b0f34b70642607d45559595c7fe94d7fa85fc41bf7d68c1fd509ebeaa5f315f6059a446b9369c277597e4f474a9591535354c7e7f4fd98a08aa60400b130c24ff20bdfbf683313f5daebf1c9b34b3bdadfc77f2ddd72ee1fb17e56c473664bc21d66467655dd74b9005e3a2bacce446f1920cd7017231ae447b67036c9b431b8179deacd5120262d894c26bc015bffe3d827ba7087ad9b700d2ca1f6d16cc1786581e5dd065f293c31209300f9b0afcc3f7c08dd26d0a22d87580b4d00009f592e0619d823953577d4503061706843317e4fee083db41054657374204b65792033202844534129886204131102002205024d6c49de021b03060b090807030206150802090a0b0416020301021e01021780000a0910338934250ccc03607e0400a0bdb9193e8a6b96fc2dfc108ae848914b504481f100a09c4dc148cb693293a67af24dd40d2b13a9e36794" - -const armoredPrivateKeyBlock = `-----BEGIN PGP PRIVATE KEY BLOCK----- -Version: GnuPG v1.4.10 (GNU/Linux) - -lQHYBE2rFNoBBADFwqWQIW/DSqcB4yCQqnAFTJ27qS5AnB46ccAdw3u4Greeu3Bp -idpoHdjULy7zSKlwR1EA873dO/k/e11Ml3dlAFUinWeejWaK2ugFP6JjiieSsrKn -vWNicdCS4HTWn0X4sjl0ZiAygw6GNhqEQ3cpLeL0g8E9hnYzJKQ0LWJa0QARAQAB -AAP/TB81EIo2VYNmTq0pK1ZXwUpxCrvAAIG3hwKjEzHcbQznsjNvPUihZ+NZQ6+X -0HCfPAdPkGDCLCb6NavcSW+iNnLTrdDnSI6+3BbIONqWWdRDYJhqZCkqmG6zqSfL -IdkJgCw94taUg5BWP/AAeQrhzjChvpMQTVKQL5mnuZbUCeMCAN5qrYMP2S9iKdnk -VANIFj7656ARKt/nf4CBzxcpHTyB8+d2CtPDKCmlJP6vL8t58Jmih+kHJMvC0dzn -gr5f5+sCAOOe5gt9e0am7AvQWhdbHVfJU0TQJx+m2OiCJAqGTB1nvtBLHdJnfdC9 -TnXXQ6ZXibqLyBies/xeY2sCKL5qtTMCAKnX9+9d/5yQxRyrQUHt1NYhaXZnJbHx -q4ytu0eWz+5i68IYUSK69jJ1NWPM0T6SkqpB3KCAIv68VFm9PxqG1KmhSrQIVGVz -dCBLZXmIuAQTAQIAIgUCTasU2gIbAwYLCQgHAwIGFQgCCQoLBBYCAwECHgECF4AA -CgkQO9o98PRieSoLhgQAkLEZex02Qt7vGhZzMwuN0R22w3VwyYyjBx+fM3JFETy1 -ut4xcLJoJfIaF5ZS38UplgakHG0FQ+b49i8dMij0aZmDqGxrew1m4kBfjXw9B/v+ -eIqpODryb6cOSwyQFH0lQkXC040pjq9YqDsO5w0WYNXYKDnzRV0p4H1pweo2VDid -AdgETasU2gEEAN46UPeWRqKHvA99arOxee38fBt2CI08iiWyI8T3J6ivtFGixSqV -bRcPxYO/qLpVe5l84Nb3X71GfVXlc9hyv7CD6tcowL59hg1E/DC5ydI8K8iEpUmK -/UnHdIY5h8/kqgGxkY/T/hgp5fRQgW1ZoZxLajVlMRZ8W4tFtT0DeA+JABEBAAEA -A/0bE1jaaZKj6ndqcw86jd+QtD1SF+Cf21CWRNeLKnUds4FRRvclzTyUMuWPkUeX -TaNNsUOFqBsf6QQ2oHUBBK4VCHffHCW4ZEX2cd6umz7mpHW6XzN4DECEzOVksXtc -lUC1j4UB91DC/RNQqwX1IV2QLSwssVotPMPqhOi0ZLNY7wIA3n7DWKInxYZZ4K+6 -rQ+POsz6brEoRHwr8x6XlHenq1Oki855pSa1yXIARoTrSJkBtn5oI+f8AzrnN0BN -oyeQAwIA/7E++3HDi5aweWrViiul9cd3rcsS0dEnksPhvS0ozCJiHsq/6GFmy7J8 -QSHZPteedBnZyNp5jR+H7cIfVN3KgwH/Skq4PsuPhDq5TKK6i8Pc1WW8MA6DXTdU -nLkX7RGmMwjC0DBf7KWAlPjFaONAX3a8ndnz//fy1q7u2l9AZwrj1qa1iJ8EGAEC -AAkFAk2rFNoCGwwACgkQO9o98PRieSo2/QP/WTzr4ioINVsvN1akKuekmEMI3LAp -BfHwatufxxP1U+3Si/6YIk7kuPB9Hs+pRqCXzbvPRrI8NHZBmc8qIGthishdCYad -AHcVnXjtxrULkQFGbGvhKURLvS9WnzD/m1K2zzwxzkPTzT9/Yf06O6Mal5AdugPL -VrM0m72/jnpKo04= -=zNCn ------END PGP PRIVATE KEY BLOCK-----` - -const e2ePublicKey = `-----BEGIN PGP PUBLIC KEY BLOCK----- -Charset: UTF-8 - -xv8AAABSBAAAAAATCCqGSM49AwEHAgME1LRoXSpOxtHXDUdmuvzchyg6005qIBJ4 -sfaSxX7QgH9RV2ONUhC+WiayCNADq+UMzuR/vunSr4aQffXvuGnR383/AAAAFDxk -Z2lsQHlhaG9vLWluYy5jb20+wv8AAACGBBATCAA4/wAAAAWCVGvAG/8AAAACiwn/ -AAAACZC2VkQCOjdvYf8AAAAFlQgJCgv/AAAAA5YBAv8AAAACngEAAE1BAP0X8veD -24IjmI5/C6ZAfVNXxgZZFhTAACFX75jUA3oD6AEAzoSwKf1aqH6oq62qhCN/pekX -+WAsVMBhNwzLpqtCRjLO/wAAAFYEAAAAABIIKoZIzj0DAQcCAwT50ain7vXiIRv8 -B1DO3x3cE/aattZ5sHNixJzRCXi2vQIA5QmOxZ6b5jjUekNbdHG3SZi1a2Ak5mfX -fRxC/5VGAwEIB8L/AAAAZQQYEwgAGP8AAAAFglRrwBz/AAAACZC2VkQCOjdvYQAA -FJAA9isX3xtGyMLYwp2F3nXm7QEdY5bq5VUcD/RJlj792VwA/1wH0pCzVLl4Q9F9 -ex7En5r7rHR5xwX82Msc+Rq9dSyO -=7MrZ ------END PGP PUBLIC KEY BLOCK-----` - -const dsaKeyWithSHA512 = `9901a2044f04b07f110400db244efecc7316553ee08d179972aab87bb1214de7692593fcf5b6feb1c80fba268722dd464748539b85b81d574cd2d7ad0ca2444de4d849b8756bad7768c486c83a824f9bba4af773d11742bdfb4ac3b89ef8cc9452d4aad31a37e4b630d33927bff68e879284a1672659b8b298222fc68f370f3e24dccacc4a862442b9438b00a0ea444a24088dc23e26df7daf8f43cba3bffc4fe703fe3d6cd7fdca199d54ed8ae501c30e3ec7871ea9cdd4cf63cfe6fc82281d70a5b8bb493f922cd99fba5f088935596af087c8d818d5ec4d0b9afa7f070b3d7c1dd32a84fca08d8280b4890c8da1dde334de8e3cad8450eed2a4a4fcc2db7b8e5528b869a74a7f0189e11ef097ef1253582348de072bb07a9fa8ab838e993cef0ee203ff49298723e2d1f549b00559f886cd417a41692ce58d0ac1307dc71d85a8af21b0cf6eaa14baf2922d3a70389bedf17cc514ba0febbd107675a372fe84b90162a9e88b14d4b1c6be855b96b33fb198c46f058568817780435b6936167ebb3724b680f32bf27382ada2e37a879b3d9de2abe0c3f399350afd1ad438883f4791e2e3b4184453412068617368207472756e636174696f6e207465737488620413110a002205024f04b07f021b03060b090807030206150802090a0b0416020301021e01021780000a0910ef20e0cefca131581318009e2bf3bf047a44d75a9bacd00161ee04d435522397009a03a60d51bd8a568c6c021c8d7cf1be8d990d6417b0020003` - -const unknownHashFunctionHex = `8a00000040040001990006050253863c24000a09103b4fe6acc0b21f32ffff01010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101` - -const missingHashFunctionHex = `8a00000040040001030006050253863c24000a09103b4fe6acc0b21f32ffff01010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101` - -const campbellQuine = `a0b001000300fcffa0b001000d00f2ff000300fcffa0b001000d00f2ff8270a01c00000500faff8270a01c00000500faff000500faff001400ebff8270a01c00000500faff000500faff001400ebff428821c400001400ebff428821c400001400ebff428821c400001400ebff428821c400001400ebff428821c400000000ffff000000ffff000b00f4ff428821c400000000ffff000000ffff000b00f4ff0233214c40000100feff000233214c40000100feff0000` diff --git a/Godeps/_workspace/src/golang.org/x/crypto/openpgp/s2k/s2k_test.go b/Godeps/_workspace/src/golang.org/x/crypto/openpgp/s2k/s2k_test.go deleted file mode 100644 index 183d26056..000000000 --- a/Godeps/_workspace/src/golang.org/x/crypto/openpgp/s2k/s2k_test.go +++ /dev/null @@ -1,137 +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 s2k - -import ( - "bytes" - "crypto" - _ "crypto/md5" - "crypto/rand" - "crypto/sha1" - _ "crypto/sha256" - _ "crypto/sha512" - "encoding/hex" - "testing" - - _ "golang.org/x/crypto/ripemd160" -) - -var saltedTests = []struct { - in, out string -}{ - {"hello", "10295ac1"}, - {"world", "ac587a5e"}, - {"foo", "4dda8077"}, - {"bar", "bd8aac6b9ea9cae04eae6a91c6133b58b5d9a61c14f355516ed9370456"}, - {"x", "f1d3f289"}, - {"xxxxxxxxxxxxxxxxxxxxxxx", "e00d7b45"}, -} - -func TestSalted(t *testing.T) { - h := sha1.New() - salt := [4]byte{1, 2, 3, 4} - - for i, test := range saltedTests { - expected, _ := hex.DecodeString(test.out) - out := make([]byte, len(expected)) - Salted(out, h, []byte(test.in), salt[:]) - if !bytes.Equal(expected, out) { - t.Errorf("#%d, got: %x want: %x", i, out, expected) - } - } -} - -var iteratedTests = []struct { - in, out string -}{ - {"hello", "83126105"}, - {"world", "6fa317f9"}, - {"foo", "8fbc35b9"}, - {"bar", "2af5a99b54f093789fd657f19bd245af7604d0f6ae06f66602a46a08ae"}, - {"x", "5a684dfe"}, - {"xxxxxxxxxxxxxxxxxxxxxxx", "18955174"}, -} - -func TestIterated(t *testing.T) { - h := sha1.New() - salt := [4]byte{4, 3, 2, 1} - - for i, test := range iteratedTests { - expected, _ := hex.DecodeString(test.out) - out := make([]byte, len(expected)) - Iterated(out, h, []byte(test.in), salt[:], 31) - if !bytes.Equal(expected, out) { - t.Errorf("#%d, got: %x want: %x", i, out, expected) - } - } -} - -var parseTests = []struct { - spec, in, out string -}{ - /* Simple with SHA1 */ - {"0002", "hello", "aaf4c61d"}, - /* Salted with SHA1 */ - {"01020102030405060708", "hello", "f4f7d67e"}, - /* Iterated with SHA1 */ - {"03020102030405060708f1", "hello", "f2a57b7c"}, -} - -func TestParse(t *testing.T) { - for i, test := range parseTests { - spec, _ := hex.DecodeString(test.spec) - buf := bytes.NewBuffer(spec) - f, err := Parse(buf) - if err != nil { - t.Errorf("%d: Parse returned error: %s", i, err) - continue - } - - expected, _ := hex.DecodeString(test.out) - out := make([]byte, len(expected)) - f(out, []byte(test.in)) - if !bytes.Equal(out, expected) { - t.Errorf("%d: output got: %x want: %x", i, out, expected) - } - if testing.Short() { - break - } - } -} - -func TestSerialize(t *testing.T) { - hashes := []crypto.Hash{crypto.MD5, crypto.SHA1, crypto.RIPEMD160, - crypto.SHA256, crypto.SHA384, crypto.SHA512, crypto.SHA224} - testCounts := []int{-1, 0, 1024, 65536, 4063232, 65011712} - for _, h := range hashes { - for _, c := range testCounts { - testSerializeConfig(t, &Config{Hash: h, S2KCount: c}) - } - } -} - -func testSerializeConfig(t *testing.T, c *Config) { - t.Logf("Running testSerializeConfig() with config: %+v", c) - - buf := bytes.NewBuffer(nil) - key := make([]byte, 16) - passphrase := []byte("testing") - err := Serialize(buf, key, rand.Reader, passphrase, c) - if err != nil { - t.Errorf("failed to serialize: %s", err) - return - } - - f, err := Parse(buf) - if err != nil { - t.Errorf("failed to reparse: %s", err) - return - } - key2 := make([]byte, len(key)) - f(key2, passphrase) - if !bytes.Equal(key2, key) { - t.Errorf("keys don't match: %x (serialied) vs %x (parsed)", key, key2) - } -} diff --git a/Godeps/_workspace/src/golang.org/x/crypto/openpgp/write_test.go b/Godeps/_workspace/src/golang.org/x/crypto/openpgp/write_test.go deleted file mode 100644 index 8e9a33583..000000000 --- a/Godeps/_workspace/src/golang.org/x/crypto/openpgp/write_test.go +++ /dev/null @@ -1,259 +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 openpgp - -import ( - "bytes" - "io" - "io/ioutil" - "testing" - "time" - - "golang.org/x/crypto/openpgp/packet" -) - -func TestSignDetached(t *testing.T) { - kring, _ := ReadKeyRing(readerFromHex(testKeys1And2PrivateHex)) - out := bytes.NewBuffer(nil) - message := bytes.NewBufferString(signedInput) - err := DetachSign(out, kring[0], message, nil) - if err != nil { - t.Error(err) - } - - testDetachedSignature(t, kring, out, signedInput, "check", testKey1KeyId) -} - -func TestSignTextDetached(t *testing.T) { - kring, _ := ReadKeyRing(readerFromHex(testKeys1And2PrivateHex)) - out := bytes.NewBuffer(nil) - message := bytes.NewBufferString(signedInput) - err := DetachSignText(out, kring[0], message, nil) - if err != nil { - t.Error(err) - } - - testDetachedSignature(t, kring, out, signedInput, "check", testKey1KeyId) -} - -func TestSignDetachedDSA(t *testing.T) { - kring, _ := ReadKeyRing(readerFromHex(dsaTestKeyPrivateHex)) - out := bytes.NewBuffer(nil) - message := bytes.NewBufferString(signedInput) - err := DetachSign(out, kring[0], message, nil) - if err != nil { - t.Error(err) - } - - testDetachedSignature(t, kring, out, signedInput, "check", testKey3KeyId) -} - -func TestNewEntity(t *testing.T) { - if testing.Short() { - return - } - - // Check bit-length with no config. - e, err := NewEntity("Test User", "test", "test@example.com", nil) - if err != nil { - t.Errorf("failed to create entity: %s", err) - return - } - bl, err := e.PrimaryKey.BitLength() - if err != nil { - t.Errorf("failed to find bit length: %s", err) - } - if int(bl) != defaultRSAKeyBits { - t.Errorf("BitLength %v, expected %v", defaultRSAKeyBits) - } - - // Check bit-length with a config. - cfg := &packet.Config{RSABits: 1024} - e, err = NewEntity("Test User", "test", "test@example.com", cfg) - if err != nil { - t.Errorf("failed to create entity: %s", err) - return - } - bl, err = e.PrimaryKey.BitLength() - if err != nil { - t.Errorf("failed to find bit length: %s", err) - } - if int(bl) != cfg.RSABits { - t.Errorf("BitLength %v, expected %v", bl, cfg.RSABits) - } - - w := bytes.NewBuffer(nil) - if err := e.SerializePrivate(w, nil); err != nil { - t.Errorf("failed to serialize entity: %s", err) - return - } - serialized := w.Bytes() - - el, err := ReadKeyRing(w) - if err != nil { - t.Errorf("failed to reparse entity: %s", err) - return - } - - if len(el) != 1 { - t.Errorf("wrong number of entities found, got %d, want 1", len(el)) - } - - w = bytes.NewBuffer(nil) - if err := e.SerializePrivate(w, nil); err != nil { - t.Errorf("failed to serialize entity second time: %s", err) - return - } - - if !bytes.Equal(w.Bytes(), serialized) { - t.Errorf("results differed") - } -} - -func TestSymmetricEncryption(t *testing.T) { - buf := new(bytes.Buffer) - plaintext, err := SymmetricallyEncrypt(buf, []byte("testing"), nil, nil) - if err != nil { - t.Errorf("error writing headers: %s", err) - return - } - message := []byte("hello world\n") - _, err = plaintext.Write(message) - if err != nil { - t.Errorf("error writing to plaintext writer: %s", err) - } - err = plaintext.Close() - if err != nil { - t.Errorf("error closing plaintext writer: %s", err) - } - - md, err := ReadMessage(buf, nil, func(keys []Key, symmetric bool) ([]byte, error) { - return []byte("testing"), nil - }, nil) - if err != nil { - t.Errorf("error rereading message: %s", err) - } - messageBuf := bytes.NewBuffer(nil) - _, err = io.Copy(messageBuf, md.UnverifiedBody) - if err != nil { - t.Errorf("error rereading message: %s", err) - } - if !bytes.Equal(message, messageBuf.Bytes()) { - t.Errorf("recovered message incorrect got '%s', want '%s'", messageBuf.Bytes(), message) - } -} - -var testEncryptionTests = []struct { - keyRingHex string - isSigned bool -}{ - { - testKeys1And2PrivateHex, - false, - }, - { - testKeys1And2PrivateHex, - true, - }, - { - dsaElGamalTestKeysHex, - false, - }, - { - dsaElGamalTestKeysHex, - true, - }, -} - -func TestEncryption(t *testing.T) { - for i, test := range testEncryptionTests { - kring, _ := ReadKeyRing(readerFromHex(test.keyRingHex)) - - passphrase := []byte("passphrase") - for _, entity := range kring { - if entity.PrivateKey != nil && entity.PrivateKey.Encrypted { - err := entity.PrivateKey.Decrypt(passphrase) - if err != nil { - t.Errorf("#%d: failed to decrypt key", i) - } - } - for _, subkey := range entity.Subkeys { - if subkey.PrivateKey != nil && subkey.PrivateKey.Encrypted { - err := subkey.PrivateKey.Decrypt(passphrase) - if err != nil { - t.Errorf("#%d: failed to decrypt subkey", i) - } - } - } - } - - var signed *Entity - if test.isSigned { - signed = kring[0] - } - - buf := new(bytes.Buffer) - w, err := Encrypt(buf, kring[:1], signed, nil /* no hints */, nil) - if err != nil { - t.Errorf("#%d: error in Encrypt: %s", i, err) - continue - } - - const message = "testing" - _, err = w.Write([]byte(message)) - if err != nil { - t.Errorf("#%d: error writing plaintext: %s", i, err) - continue - } - err = w.Close() - if err != nil { - t.Errorf("#%d: error closing WriteCloser: %s", i, err) - continue - } - - md, err := ReadMessage(buf, kring, nil /* no prompt */, nil) - if err != nil { - t.Errorf("#%d: error reading message: %s", i, err) - continue - } - - testTime, _ := time.Parse("2006-01-02", "2013-07-01") - if test.isSigned { - signKey, _ := kring[0].signingKey(testTime) - expectedKeyId := signKey.PublicKey.KeyId - if md.SignedByKeyId != expectedKeyId { - t.Errorf("#%d: message signed by wrong key id, got: %d, want: %d", i, *md.SignedBy, expectedKeyId) - } - if md.SignedBy == nil { - t.Errorf("#%d: failed to find the signing Entity", i) - } - } - - plaintext, err := ioutil.ReadAll(md.UnverifiedBody) - if err != nil { - t.Errorf("#%d: error reading encrypted contents: %s", i, err) - continue - } - - encryptKey, _ := kring[0].encryptionKey(testTime) - expectedKeyId := encryptKey.PublicKey.KeyId - if len(md.EncryptedToKeyIds) != 1 || md.EncryptedToKeyIds[0] != expectedKeyId { - t.Errorf("#%d: expected message to be encrypted to %v, but got %#v", i, expectedKeyId, md.EncryptedToKeyIds) - } - - if string(plaintext) != message { - t.Errorf("#%d: got: %s, want: %s", i, string(plaintext), message) - } - - if test.isSigned { - if md.SignatureError != nil { - t.Errorf("#%d: signature error: %s", i, md.SignatureError) - } - if md.Signature == nil { - t.Error("signature missing") - } - } - } -} diff --git a/Godeps/_workspace/src/golang.org/x/crypto/ssh/agent/client_test.go b/Godeps/_workspace/src/golang.org/x/crypto/ssh/agent/client_test.go deleted file mode 100644 index ec7198d54..000000000 --- a/Godeps/_workspace/src/golang.org/x/crypto/ssh/agent/client_test.go +++ /dev/null @@ -1,287 +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 agent - -import ( - "bytes" - "crypto/rand" - "errors" - "net" - "os" - "os/exec" - "path/filepath" - "strconv" - "testing" - - "golang.org/x/crypto/ssh" -) - -// startAgent executes ssh-agent, and returns a Agent interface to it. -func startAgent(t *testing.T) (client Agent, socket string, cleanup func()) { - if testing.Short() { - // ssh-agent is not always available, and the key - // types supported vary by platform. - t.Skip("skipping test due to -short") - } - - bin, err := exec.LookPath("ssh-agent") - if err != nil { - t.Skip("could not find ssh-agent") - } - - cmd := exec.Command(bin, "-s") - out, err := cmd.Output() - if err != nil { - t.Fatalf("cmd.Output: %v", err) - } - - /* Output looks like: - - SSH_AUTH_SOCK=/tmp/ssh-P65gpcqArqvH/agent.15541; export SSH_AUTH_SOCK; - SSH_AGENT_PID=15542; export SSH_AGENT_PID; - echo Agent pid 15542; - */ - fields := bytes.Split(out, []byte(";")) - line := bytes.SplitN(fields[0], []byte("="), 2) - line[0] = bytes.TrimLeft(line[0], "\n") - if string(line[0]) != "SSH_AUTH_SOCK" { - t.Fatalf("could not find key SSH_AUTH_SOCK in %q", fields[0]) - } - socket = string(line[1]) - - line = bytes.SplitN(fields[2], []byte("="), 2) - line[0] = bytes.TrimLeft(line[0], "\n") - if string(line[0]) != "SSH_AGENT_PID" { - t.Fatalf("could not find key SSH_AGENT_PID in %q", fields[2]) - } - pidStr := line[1] - pid, err := strconv.Atoi(string(pidStr)) - if err != nil { - t.Fatalf("Atoi(%q): %v", pidStr, err) - } - - conn, err := net.Dial("unix", string(socket)) - if err != nil { - t.Fatalf("net.Dial: %v", err) - } - - ac := NewClient(conn) - return ac, socket, func() { - proc, _ := os.FindProcess(pid) - if proc != nil { - proc.Kill() - } - conn.Close() - os.RemoveAll(filepath.Dir(socket)) - } -} - -func testAgent(t *testing.T, key interface{}, cert *ssh.Certificate, lifetimeSecs uint32) { - agent, _, cleanup := startAgent(t) - defer cleanup() - - testAgentInterface(t, agent, key, cert, lifetimeSecs) -} - -func testAgentInterface(t *testing.T, agent Agent, key interface{}, cert *ssh.Certificate, lifetimeSecs uint32) { - signer, err := ssh.NewSignerFromKey(key) - if err != nil { - t.Fatalf("NewSignerFromKey(%T): %v", key, err) - } - // The agent should start up empty. - if keys, err := agent.List(); err != nil { - t.Fatalf("RequestIdentities: %v", err) - } else if len(keys) > 0 { - t.Fatalf("got %d keys, want 0: %v", len(keys), keys) - } - - // Attempt to insert the key, with certificate if specified. - var pubKey ssh.PublicKey - if cert != nil { - err = agent.Add(AddedKey{ - PrivateKey: key, - Certificate: cert, - Comment: "comment", - LifetimeSecs: lifetimeSecs, - }) - pubKey = cert - } else { - err = agent.Add(AddedKey{PrivateKey: key, Comment: "comment", LifetimeSecs: lifetimeSecs}) - pubKey = signer.PublicKey() - } - if err != nil { - t.Fatalf("insert(%T): %v", key, err) - } - - // Did the key get inserted successfully? - if keys, err := agent.List(); err != nil { - t.Fatalf("List: %v", err) - } else if len(keys) != 1 { - t.Fatalf("got %v, want 1 key", keys) - } else if keys[0].Comment != "comment" { - t.Fatalf("key comment: got %v, want %v", keys[0].Comment, "comment") - } else if !bytes.Equal(keys[0].Blob, pubKey.Marshal()) { - t.Fatalf("key mismatch") - } - - // Can the agent make a valid signature? - data := []byte("hello") - sig, err := agent.Sign(pubKey, data) - if err != nil { - t.Fatalf("Sign(%s): %v", pubKey.Type(), err) - } - - if err := pubKey.Verify(data, sig); err != nil { - t.Fatalf("Verify(%s): %v", pubKey.Type(), err) - } -} - -func TestAgent(t *testing.T) { - for _, keyType := range []string{"rsa", "dsa", "ecdsa"} { - testAgent(t, testPrivateKeys[keyType], nil, 0) - } -} - -func TestCert(t *testing.T) { - cert := &ssh.Certificate{ - Key: testPublicKeys["rsa"], - ValidBefore: ssh.CertTimeInfinity, - CertType: ssh.UserCert, - } - cert.SignCert(rand.Reader, testSigners["ecdsa"]) - - testAgent(t, testPrivateKeys["rsa"], cert, 0) -} - -func TestConstraints(t *testing.T) { - testAgent(t, testPrivateKeys["rsa"], nil, 3600 /* lifetime in seconds */) -} - -// netPipe is analogous to net.Pipe, but it uses a real net.Conn, and -// therefore is buffered (net.Pipe deadlocks if both sides start with -// a write.) -func netPipe() (net.Conn, net.Conn, error) { - listener, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - return nil, nil, err - } - defer listener.Close() - c1, err := net.Dial("tcp", listener.Addr().String()) - if err != nil { - return nil, nil, err - } - - c2, err := listener.Accept() - if err != nil { - c1.Close() - return nil, nil, err - } - - return c1, c2, nil -} - -func TestAuth(t *testing.T) { - a, b, err := netPipe() - if err != nil { - t.Fatalf("netPipe: %v", err) - } - - defer a.Close() - defer b.Close() - - agent, _, cleanup := startAgent(t) - defer cleanup() - - if err := agent.Add(AddedKey{PrivateKey: testPrivateKeys["rsa"], Comment: "comment"}); err != nil { - t.Errorf("Add: %v", err) - } - - serverConf := ssh.ServerConfig{} - serverConf.AddHostKey(testSigners["rsa"]) - serverConf.PublicKeyCallback = func(c ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) { - if bytes.Equal(key.Marshal(), testPublicKeys["rsa"].Marshal()) { - return nil, nil - } - - return nil, errors.New("pubkey rejected") - } - - go func() { - conn, _, _, err := ssh.NewServerConn(a, &serverConf) - if err != nil { - t.Fatalf("Server: %v", err) - } - conn.Close() - }() - - conf := ssh.ClientConfig{} - conf.Auth = append(conf.Auth, ssh.PublicKeysCallback(agent.Signers)) - conn, _, _, err := ssh.NewClientConn(b, "", &conf) - if err != nil { - t.Fatalf("NewClientConn: %v", err) - } - conn.Close() -} - -func TestLockClient(t *testing.T) { - agent, _, cleanup := startAgent(t) - defer cleanup() - testLockAgent(agent, t) -} - -func testLockAgent(agent Agent, t *testing.T) { - if err := agent.Add(AddedKey{PrivateKey: testPrivateKeys["rsa"], Comment: "comment 1"}); err != nil { - t.Errorf("Add: %v", err) - } - if err := agent.Add(AddedKey{PrivateKey: testPrivateKeys["dsa"], Comment: "comment dsa"}); err != nil { - t.Errorf("Add: %v", err) - } - if keys, err := agent.List(); err != nil { - t.Errorf("List: %v", err) - } else if len(keys) != 2 { - t.Errorf("Want 2 keys, got %v", keys) - } - - passphrase := []byte("secret") - if err := agent.Lock(passphrase); err != nil { - t.Errorf("Lock: %v", err) - } - - if keys, err := agent.List(); err != nil { - t.Errorf("List: %v", err) - } else if len(keys) != 0 { - t.Errorf("Want 0 keys, got %v", keys) - } - - signer, _ := ssh.NewSignerFromKey(testPrivateKeys["rsa"]) - if _, err := agent.Sign(signer.PublicKey(), []byte("hello")); err == nil { - t.Fatalf("Sign did not fail") - } - - if err := agent.Remove(signer.PublicKey()); err == nil { - t.Fatalf("Remove did not fail") - } - - if err := agent.RemoveAll(); err == nil { - t.Fatalf("RemoveAll did not fail") - } - - if err := agent.Unlock(nil); err == nil { - t.Errorf("Unlock with wrong passphrase succeeded") - } - if err := agent.Unlock(passphrase); err != nil { - t.Errorf("Unlock: %v", err) - } - - if err := agent.Remove(signer.PublicKey()); err != nil { - t.Fatalf("Remove: %v", err) - } - - if keys, err := agent.List(); err != nil { - t.Errorf("List: %v", err) - } else if len(keys) != 1 { - t.Errorf("Want 1 keys, got %v", keys) - } -} diff --git a/Godeps/_workspace/src/golang.org/x/crypto/ssh/agent/server_test.go b/Godeps/_workspace/src/golang.org/x/crypto/ssh/agent/server_test.go deleted file mode 100644 index ef0ab2934..000000000 --- a/Godeps/_workspace/src/golang.org/x/crypto/ssh/agent/server_test.go +++ /dev/null @@ -1,77 +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 agent - -import ( - "testing" - - "golang.org/x/crypto/ssh" -) - -func TestServer(t *testing.T) { - c1, c2, err := netPipe() - if err != nil { - t.Fatalf("netPipe: %v", err) - } - defer c1.Close() - defer c2.Close() - client := NewClient(c1) - - go ServeAgent(NewKeyring(), c2) - - testAgentInterface(t, client, testPrivateKeys["rsa"], nil, 0) -} - -func TestLockServer(t *testing.T) { - testLockAgent(NewKeyring(), t) -} - -func TestSetupForwardAgent(t *testing.T) { - a, b, err := netPipe() - if err != nil { - t.Fatalf("netPipe: %v", err) - } - - defer a.Close() - defer b.Close() - - _, socket, cleanup := startAgent(t) - defer cleanup() - - serverConf := ssh.ServerConfig{ - NoClientAuth: true, - } - serverConf.AddHostKey(testSigners["rsa"]) - incoming := make(chan *ssh.ServerConn, 1) - go func() { - conn, _, _, err := ssh.NewServerConn(a, &serverConf) - if err != nil { - t.Fatalf("Server: %v", err) - } - incoming <- conn - }() - - conf := ssh.ClientConfig{} - conn, chans, reqs, err := ssh.NewClientConn(b, "", &conf) - if err != nil { - t.Fatalf("NewClientConn: %v", err) - } - client := ssh.NewClient(conn, chans, reqs) - - if err := ForwardToRemote(client, socket); err != nil { - t.Fatalf("SetupForwardAgent: %v", err) - } - - server := <-incoming - ch, reqs, err := server.OpenChannel(channelType, nil) - if err != nil { - t.Fatalf("OpenChannel(%q): %v", channelType, err) - } - go ssh.DiscardRequests(reqs) - - agentClient := NewClient(ch) - testAgentInterface(t, agentClient, testPrivateKeys["rsa"], nil, 0) - conn.Close() -} diff --git a/Godeps/_workspace/src/golang.org/x/crypto/ssh/agent/testdata_test.go b/Godeps/_workspace/src/golang.org/x/crypto/ssh/agent/testdata_test.go deleted file mode 100644 index b7a8781e1..000000000 --- a/Godeps/_workspace/src/golang.org/x/crypto/ssh/agent/testdata_test.go +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright 2014 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. - -// IMPLEMENTOR NOTE: To avoid a package loop, this file is in three places: -// ssh/, ssh/agent, and ssh/test/. It should be kept in sync across all three -// instances. - -package agent - -import ( - "crypto/rand" - "fmt" - - "golang.org/x/crypto/ssh" - "golang.org/x/crypto/ssh/testdata" -) - -var ( - testPrivateKeys map[string]interface{} - testSigners map[string]ssh.Signer - testPublicKeys map[string]ssh.PublicKey -) - -func init() { - var err error - - n := len(testdata.PEMBytes) - testPrivateKeys = make(map[string]interface{}, n) - testSigners = make(map[string]ssh.Signer, n) - testPublicKeys = make(map[string]ssh.PublicKey, n) - for t, k := range testdata.PEMBytes { - testPrivateKeys[t], err = ssh.ParseRawPrivateKey(k) - if err != nil { - panic(fmt.Sprintf("Unable to parse test key %s: %v", t, err)) - } - testSigners[t], err = ssh.NewSignerFromKey(testPrivateKeys[t]) - if err != nil { - panic(fmt.Sprintf("Unable to create signer for test key %s: %v", t, err)) - } - testPublicKeys[t] = testSigners[t].PublicKey() - } - - // Create a cert and sign it for use in tests. - testCert := &ssh.Certificate{ - Nonce: []byte{}, // To pass reflect.DeepEqual after marshal & parse, this must be non-nil - ValidPrincipals: []string{"gopher1", "gopher2"}, // increases test coverage - ValidAfter: 0, // unix epoch - ValidBefore: ssh.CertTimeInfinity, // The end of currently representable time. - Reserved: []byte{}, // To pass reflect.DeepEqual after marshal & parse, this must be non-nil - Key: testPublicKeys["ecdsa"], - SignatureKey: testPublicKeys["rsa"], - Permissions: ssh.Permissions{ - CriticalOptions: map[string]string{}, - Extensions: map[string]string{}, - }, - } - testCert.SignCert(rand.Reader, testSigners["rsa"]) - testPrivateKeys["cert"] = testPrivateKeys["ecdsa"] - testSigners["cert"], err = ssh.NewCertSigner(testCert, testSigners["ecdsa"]) - if err != nil { - panic(fmt.Sprintf("Unable to create certificate signer: %v", err)) - } -} diff --git a/Godeps/_workspace/src/golang.org/x/crypto/ssh/benchmark_test.go b/Godeps/_workspace/src/golang.org/x/crypto/ssh/benchmark_test.go deleted file mode 100644 index d9f7eb9b6..000000000 --- a/Godeps/_workspace/src/golang.org/x/crypto/ssh/benchmark_test.go +++ /dev/null @@ -1,122 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package ssh - -import ( - "errors" - "io" - "net" - "testing" -) - -type server struct { - *ServerConn - chans <-chan NewChannel -} - -func newServer(c net.Conn, conf *ServerConfig) (*server, error) { - sconn, chans, reqs, err := NewServerConn(c, conf) - if err != nil { - return nil, err - } - go DiscardRequests(reqs) - return &server{sconn, chans}, nil -} - -func (s *server) Accept() (NewChannel, error) { - n, ok := <-s.chans - if !ok { - return nil, io.EOF - } - return n, nil -} - -func sshPipe() (Conn, *server, error) { - c1, c2, err := netPipe() - if err != nil { - return nil, nil, err - } - - clientConf := ClientConfig{ - User: "user", - } - serverConf := ServerConfig{ - NoClientAuth: true, - } - serverConf.AddHostKey(testSigners["ecdsa"]) - done := make(chan *server, 1) - go func() { - server, err := newServer(c2, &serverConf) - if err != nil { - done <- nil - } - done <- server - }() - - client, _, reqs, err := NewClientConn(c1, "", &clientConf) - if err != nil { - return nil, nil, err - } - - server := <-done - if server == nil { - return nil, nil, errors.New("server handshake failed.") - } - go DiscardRequests(reqs) - - return client, server, nil -} - -func BenchmarkEndToEnd(b *testing.B) { - b.StopTimer() - - client, server, err := sshPipe() - if err != nil { - b.Fatalf("sshPipe: %v", err) - } - - defer client.Close() - defer server.Close() - - size := (1 << 20) - input := make([]byte, size) - output := make([]byte, size) - b.SetBytes(int64(size)) - done := make(chan int, 1) - - go func() { - newCh, err := server.Accept() - if err != nil { - b.Fatalf("Client: %v", err) - } - ch, incoming, err := newCh.Accept() - go DiscardRequests(incoming) - for i := 0; i < b.N; i++ { - if _, err := io.ReadFull(ch, output); err != nil { - b.Fatalf("ReadFull: %v", err) - } - } - ch.Close() - done <- 1 - }() - - ch, in, err := client.OpenChannel("speed", nil) - if err != nil { - b.Fatalf("OpenChannel: %v", err) - } - go DiscardRequests(in) - - b.ResetTimer() - b.StartTimer() - for i := 0; i < b.N; i++ { - if _, err := ch.Write(input); err != nil { - b.Fatalf("WriteFull: %v", err) - } - } - ch.Close() - b.StopTimer() - - <-done -} diff --git a/Godeps/_workspace/src/golang.org/x/crypto/ssh/buffer_test.go b/Godeps/_workspace/src/golang.org/x/crypto/ssh/buffer_test.go deleted file mode 100644 index d5781cb3d..000000000 --- a/Godeps/_workspace/src/golang.org/x/crypto/ssh/buffer_test.go +++ /dev/null @@ -1,87 +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 ssh - -import ( - "io" - "testing" -) - -var alphabet = []byte("abcdefghijklmnopqrstuvwxyz") - -func TestBufferReadwrite(t *testing.T) { - b := newBuffer() - b.write(alphabet[:10]) - r, _ := b.Read(make([]byte, 10)) - if r != 10 { - t.Fatalf("Expected written == read == 10, written: 10, read %d", r) - } - - b = newBuffer() - b.write(alphabet[:5]) - r, _ = b.Read(make([]byte, 10)) - if r != 5 { - t.Fatalf("Expected written == read == 5, written: 5, read %d", r) - } - - b = newBuffer() - b.write(alphabet[:10]) - r, _ = b.Read(make([]byte, 5)) - if r != 5 { - t.Fatalf("Expected written == 10, read == 5, written: 10, read %d", r) - } - - b = newBuffer() - b.write(alphabet[:5]) - b.write(alphabet[5:15]) - r, _ = b.Read(make([]byte, 10)) - r2, _ := b.Read(make([]byte, 10)) - if r != 10 || r2 != 5 || 15 != r+r2 { - t.Fatal("Expected written == read == 15") - } -} - -func TestBufferClose(t *testing.T) { - b := newBuffer() - b.write(alphabet[:10]) - b.eof() - _, err := b.Read(make([]byte, 5)) - if err != nil { - t.Fatal("expected read of 5 to not return EOF") - } - b = newBuffer() - b.write(alphabet[:10]) - b.eof() - r, err := b.Read(make([]byte, 5)) - r2, err2 := b.Read(make([]byte, 10)) - if r != 5 || r2 != 5 || err != nil || err2 != nil { - t.Fatal("expected reads of 5 and 5") - } - - b = newBuffer() - b.write(alphabet[:10]) - b.eof() - r, err = b.Read(make([]byte, 5)) - r2, err2 = b.Read(make([]byte, 10)) - r3, err3 := b.Read(make([]byte, 10)) - if r != 5 || r2 != 5 || r3 != 0 || err != nil || err2 != nil || err3 != io.EOF { - t.Fatal("expected reads of 5 and 5 and 0, with EOF") - } - - b = newBuffer() - b.write(make([]byte, 5)) - b.write(make([]byte, 10)) - b.eof() - r, err = b.Read(make([]byte, 9)) - r2, err2 = b.Read(make([]byte, 3)) - r3, err3 = b.Read(make([]byte, 3)) - r4, err4 := b.Read(make([]byte, 10)) - if err != nil || err2 != nil || err3 != nil || err4 != io.EOF { - t.Fatalf("Expected EOF on forth read only, err=%v, err2=%v, err3=%v, err4=%v", err, err2, err3, err4) - } - if r != 9 || r2 != 3 || r3 != 3 || r4 != 0 { - t.Fatal("Expected written == read == 15", r, r2, r3, r4) - } -} diff --git a/Godeps/_workspace/src/golang.org/x/crypto/ssh/certs_test.go b/Godeps/_workspace/src/golang.org/x/crypto/ssh/certs_test.go deleted file mode 100644 index c5f2e5330..000000000 --- a/Godeps/_workspace/src/golang.org/x/crypto/ssh/certs_test.go +++ /dev/null @@ -1,216 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package ssh - -import ( - "bytes" - "crypto/rand" - "reflect" - "testing" - "time" -) - -// Cert generated by ssh-keygen 6.0p1 Debian-4. -// % ssh-keygen -s ca-key -I test user-key -const exampleSSHCert = `ssh-rsa-cert-v01@openssh.com AAAAHHNzaC1yc2EtY2VydC12MDFAb3BlbnNzaC5jb20AAAAgb1srW/W3ZDjYAO45xLYAwzHBDLsJ4Ux6ICFIkTjb1LEAAAADAQABAAAAYQCkoR51poH0wE8w72cqSB8Sszx+vAhzcMdCO0wqHTj7UNENHWEXGrU0E0UQekD7U+yhkhtoyjbPOVIP7hNa6aRk/ezdh/iUnCIt4Jt1v3Z1h1P+hA4QuYFMHNB+rmjPwAcAAAAAAAAAAAAAAAEAAAAEdGVzdAAAAAAAAAAAAAAAAP//////////AAAAAAAAAIIAAAAVcGVybWl0LVgxMS1mb3J3YXJkaW5nAAAAAAAAABdwZXJtaXQtYWdlbnQtZm9yd2FyZGluZwAAAAAAAAAWcGVybWl0LXBvcnQtZm9yd2FyZGluZwAAAAAAAAAKcGVybWl0LXB0eQAAAAAAAAAOcGVybWl0LXVzZXItcmMAAAAAAAAAAAAAAHcAAAAHc3NoLXJzYQAAAAMBAAEAAABhANFS2kaktpSGc+CcmEKPyw9mJC4nZKxHKTgLVZeaGbFZOvJTNzBspQHdy7Q1uKSfktxpgjZnksiu/tFF9ngyY2KFoc+U88ya95IZUycBGCUbBQ8+bhDtw/icdDGQD5WnUwAAAG8AAAAHc3NoLXJzYQAAAGC8Y9Z2LQKhIhxf52773XaWrXdxP0t3GBVo4A10vUWiYoAGepr6rQIoGGXFxT4B9Gp+nEBJjOwKDXPrAevow0T9ca8gZN+0ykbhSrXLE5Ao48rqr3zP4O1/9P7e6gp0gw8=` - -func TestParseCert(t *testing.T) { - authKeyBytes := []byte(exampleSSHCert) - - key, _, _, rest, err := ParseAuthorizedKey(authKeyBytes) - if err != nil { - t.Fatalf("ParseAuthorizedKey: %v", err) - } - if len(rest) > 0 { - t.Errorf("rest: got %q, want empty", rest) - } - - if _, ok := key.(*Certificate); !ok { - t.Fatalf("got %v (%T), want *Certificate", key, key) - } - - marshaled := MarshalAuthorizedKey(key) - // Before comparison, remove the trailing newline that - // MarshalAuthorizedKey adds. - marshaled = marshaled[:len(marshaled)-1] - if !bytes.Equal(authKeyBytes, marshaled) { - t.Errorf("marshaled certificate does not match original: got %q, want %q", marshaled, authKeyBytes) - } -} - -// Cert generated by ssh-keygen OpenSSH_6.8p1 OS X 10.10.3 -// % ssh-keygen -s ca -I testcert -O source-address=192.168.1.0/24 -O force-command=/bin/sleep user.pub -// user.pub key: ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDACh1rt2DXfV3hk6fszSQcQ/rueMId0kVD9U7nl8cfEnFxqOCrNT92g4laQIGl2mn8lsGZfTLg8ksHq3gkvgO3oo/0wHy4v32JeBOHTsN5AL4gfHNEhWeWb50ev47hnTsRIt9P4dxogeUo/hTu7j9+s9lLpEQXCvq6xocXQt0j8MV9qZBBXFLXVT3cWIkSqOdwt/5ZBg+1GSrc7WfCXVWgTk4a20uPMuJPxU4RQwZW6X3+O8Pqo8C3cW0OzZRFP6gUYUKUsTI5WntlS+LAxgw1mZNsozFGdbiOPRnEryE3SRldh9vjDR3tin1fGpA5P7+CEB/bqaXtG3V+F2OkqaMN -// Critical Options: -// force-command /bin/sleep -// source-address 192.168.1.0/24 -// Extensions: -// permit-X11-forwarding -// permit-agent-forwarding -// permit-port-forwarding -// permit-pty -// permit-user-rc -const exampleSSHCertWithOptions = `ssh-rsa-cert-v01@openssh.com AAAAHHNzaC1yc2EtY2VydC12MDFAb3BlbnNzaC5jb20AAAAgDyysCJY0XrO1n03EeRRoITnTPdjENFmWDs9X58PP3VUAAAADAQABAAABAQDACh1rt2DXfV3hk6fszSQcQ/rueMId0kVD9U7nl8cfEnFxqOCrNT92g4laQIGl2mn8lsGZfTLg8ksHq3gkvgO3oo/0wHy4v32JeBOHTsN5AL4gfHNEhWeWb50ev47hnTsRIt9P4dxogeUo/hTu7j9+s9lLpEQXCvq6xocXQt0j8MV9qZBBXFLXVT3cWIkSqOdwt/5ZBg+1GSrc7WfCXVWgTk4a20uPMuJPxU4RQwZW6X3+O8Pqo8C3cW0OzZRFP6gUYUKUsTI5WntlS+LAxgw1mZNsozFGdbiOPRnEryE3SRldh9vjDR3tin1fGpA5P7+CEB/bqaXtG3V+F2OkqaMNAAAAAAAAAAAAAAABAAAACHRlc3RjZXJ0AAAAAAAAAAAAAAAA//////////8AAABLAAAADWZvcmNlLWNvbW1hbmQAAAAOAAAACi9iaW4vc2xlZXAAAAAOc291cmNlLWFkZHJlc3MAAAASAAAADjE5Mi4xNjguMS4wLzI0AAAAggAAABVwZXJtaXQtWDExLWZvcndhcmRpbmcAAAAAAAAAF3Blcm1pdC1hZ2VudC1mb3J3YXJkaW5nAAAAAAAAABZwZXJtaXQtcG9ydC1mb3J3YXJkaW5nAAAAAAAAAApwZXJtaXQtcHR5AAAAAAAAAA5wZXJtaXQtdXNlci1yYwAAAAAAAAAAAAABFwAAAAdzc2gtcnNhAAAAAwEAAQAAAQEAwU+c5ui5A8+J/CFpjW8wCa52bEODA808WWQDCSuTG/eMXNf59v9Y8Pk0F1E9dGCosSNyVcB/hacUrc6He+i97+HJCyKavBsE6GDxrjRyxYqAlfcOXi/IVmaUGiO8OQ39d4GHrjToInKvExSUeleQyH4Y4/e27T/pILAqPFL3fyrvMLT5qU9QyIt6zIpa7GBP5+urouNavMprV3zsfIqNBbWypinOQAw823a5wN+zwXnhZrgQiHZ/USG09Y6k98y1dTVz8YHlQVR4D3lpTAsKDKJ5hCH9WU4fdf+lU8OyNGaJ/vz0XNqxcToe1l4numLTnaoSuH89pHryjqurB7lJKwAAAQ8AAAAHc3NoLXJzYQAAAQCaHvUIoPL1zWUHIXLvu96/HU1s/i4CAW2IIEuGgxCUCiFj6vyTyYtgxQxcmbfZf6eaITlS6XJZa7Qq4iaFZh75C1DXTX8labXhRSD4E2t//AIP9MC1rtQC5xo6FmbQ+BoKcDskr+mNACcbRSxs3IL3bwCfWDnIw2WbVox9ZdcthJKk4UoCW4ix4QwdHw7zlddlz++fGEEVhmTbll1SUkycGApPFBsAYRTMupUJcYPIeReBI/m8XfkoMk99bV8ZJQTAd7OekHY2/48Ff53jLmyDjP7kNw1F8OaPtkFs6dGJXta4krmaekPy87j+35In5hFj7yoOqvSbmYUkeX70/GGQ` - -func TestParseCertWithOptions(t *testing.T) { - opts := map[string]string{ - "source-address": "192.168.1.0/24", - "force-command": "/bin/sleep", - } - exts := map[string]string{ - "permit-X11-forwarding": "", - "permit-agent-forwarding": "", - "permit-port-forwarding": "", - "permit-pty": "", - "permit-user-rc": "", - } - authKeyBytes := []byte(exampleSSHCertWithOptions) - - key, _, _, rest, err := ParseAuthorizedKey(authKeyBytes) - if err != nil { - t.Fatalf("ParseAuthorizedKey: %v", err) - } - if len(rest) > 0 { - t.Errorf("rest: got %q, want empty", rest) - } - cert, ok := key.(*Certificate) - if !ok { - t.Fatalf("got %v (%T), want *Certificate", key, key) - } - if !reflect.DeepEqual(cert.CriticalOptions, opts) { - t.Errorf("unexpected critical options - got %v, want %v", cert.CriticalOptions, opts) - } - if !reflect.DeepEqual(cert.Extensions, exts) { - t.Errorf("unexpected Extensions - got %v, want %v", cert.Extensions, exts) - } - marshaled := MarshalAuthorizedKey(key) - // Before comparison, remove the trailing newline that - // MarshalAuthorizedKey adds. - marshaled = marshaled[:len(marshaled)-1] - if !bytes.Equal(authKeyBytes, marshaled) { - t.Errorf("marshaled certificate does not match original: got %q, want %q", marshaled, authKeyBytes) - } -} - -func TestValidateCert(t *testing.T) { - key, _, _, _, err := ParseAuthorizedKey([]byte(exampleSSHCert)) - if err != nil { - t.Fatalf("ParseAuthorizedKey: %v", err) - } - validCert, ok := key.(*Certificate) - if !ok { - t.Fatalf("got %v (%T), want *Certificate", key, key) - } - checker := CertChecker{} - checker.IsAuthority = func(k PublicKey) bool { - return bytes.Equal(k.Marshal(), validCert.SignatureKey.Marshal()) - } - - if err := checker.CheckCert("user", validCert); err != nil { - t.Errorf("Unable to validate certificate: %v", err) - } - invalidCert := &Certificate{ - Key: testPublicKeys["rsa"], - SignatureKey: testPublicKeys["ecdsa"], - ValidBefore: CertTimeInfinity, - Signature: &Signature{}, - } - if err := checker.CheckCert("user", invalidCert); err == nil { - t.Error("Invalid cert signature passed validation") - } -} - -func TestValidateCertTime(t *testing.T) { - cert := Certificate{ - ValidPrincipals: []string{"user"}, - Key: testPublicKeys["rsa"], - ValidAfter: 50, - ValidBefore: 100, - } - - cert.SignCert(rand.Reader, testSigners["ecdsa"]) - - for ts, ok := range map[int64]bool{ - 25: false, - 50: true, - 99: true, - 100: false, - 125: false, - } { - checker := CertChecker{ - Clock: func() time.Time { return time.Unix(ts, 0) }, - } - checker.IsAuthority = func(k PublicKey) bool { - return bytes.Equal(k.Marshal(), - testPublicKeys["ecdsa"].Marshal()) - } - - if v := checker.CheckCert("user", &cert); (v == nil) != ok { - t.Errorf("Authenticate(%d): %v", ts, v) - } - } -} - -// TODO(hanwen): tests for -// -// host keys: -// * fallbacks - -func TestHostKeyCert(t *testing.T) { - cert := &Certificate{ - ValidPrincipals: []string{"hostname", "hostname.domain"}, - Key: testPublicKeys["rsa"], - ValidBefore: CertTimeInfinity, - CertType: HostCert, - } - cert.SignCert(rand.Reader, testSigners["ecdsa"]) - - checker := &CertChecker{ - IsAuthority: func(p PublicKey) bool { - return bytes.Equal(testPublicKeys["ecdsa"].Marshal(), p.Marshal()) - }, - } - - certSigner, err := NewCertSigner(cert, testSigners["rsa"]) - if err != nil { - t.Errorf("NewCertSigner: %v", err) - } - - for _, name := range []string{"hostname", "otherhost"} { - c1, c2, err := netPipe() - if err != nil { - t.Fatalf("netPipe: %v", err) - } - defer c1.Close() - defer c2.Close() - - errc := make(chan error) - - go func() { - conf := ServerConfig{ - NoClientAuth: true, - } - conf.AddHostKey(certSigner) - _, _, _, err := NewServerConn(c1, &conf) - errc <- err - }() - - config := &ClientConfig{ - User: "user", - HostKeyCallback: checker.CheckHostKey, - } - _, _, _, err = NewClientConn(c2, name, config) - - succeed := name == "hostname" - if (err == nil) != succeed { - t.Fatalf("NewClientConn(%q): %v", name, err) - } - - err = <-errc - if (err == nil) != succeed { - t.Fatalf("NewServerConn(%q): %v", name, err) - } - } -} diff --git a/Godeps/_workspace/src/golang.org/x/crypto/ssh/cipher_test.go b/Godeps/_workspace/src/golang.org/x/crypto/ssh/cipher_test.go deleted file mode 100644 index 54b92b6ed..000000000 --- a/Godeps/_workspace/src/golang.org/x/crypto/ssh/cipher_test.go +++ /dev/null @@ -1,127 +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 ssh - -import ( - "bytes" - "crypto" - "crypto/aes" - "crypto/rand" - "testing" -) - -func TestDefaultCiphersExist(t *testing.T) { - for _, cipherAlgo := range supportedCiphers { - if _, ok := cipherModes[cipherAlgo]; !ok { - t.Errorf("default cipher %q is unknown", cipherAlgo) - } - } -} - -func TestPacketCiphers(t *testing.T) { - // Still test aes128cbc cipher althought it's commented out. - cipherModes[aes128cbcID] = &streamCipherMode{16, aes.BlockSize, 0, nil} - defer delete(cipherModes, aes128cbcID) - - for cipher := range cipherModes { - kr := &kexResult{Hash: crypto.SHA1} - algs := directionAlgorithms{ - Cipher: cipher, - MAC: "hmac-sha1", - Compression: "none", - } - client, err := newPacketCipher(clientKeys, algs, kr) - if err != nil { - t.Errorf("newPacketCipher(client, %q): %v", cipher, err) - continue - } - server, err := newPacketCipher(clientKeys, algs, kr) - if err != nil { - t.Errorf("newPacketCipher(client, %q): %v", cipher, err) - continue - } - - want := "bla bla" - input := []byte(want) - buf := &bytes.Buffer{} - if err := client.writePacket(0, buf, rand.Reader, input); err != nil { - t.Errorf("writePacket(%q): %v", cipher, err) - continue - } - - packet, err := server.readPacket(0, buf) - if err != nil { - t.Errorf("readPacket(%q): %v", cipher, err) - continue - } - - if string(packet) != want { - t.Errorf("roundtrip(%q): got %q, want %q", cipher, packet, want) - } - } -} - -func TestCBCOracleCounterMeasure(t *testing.T) { - cipherModes[aes128cbcID] = &streamCipherMode{16, aes.BlockSize, 0, nil} - defer delete(cipherModes, aes128cbcID) - - kr := &kexResult{Hash: crypto.SHA1} - algs := directionAlgorithms{ - Cipher: aes128cbcID, - MAC: "hmac-sha1", - Compression: "none", - } - client, err := newPacketCipher(clientKeys, algs, kr) - if err != nil { - t.Fatalf("newPacketCipher(client): %v", err) - } - - want := "bla bla" - input := []byte(want) - buf := &bytes.Buffer{} - if err := client.writePacket(0, buf, rand.Reader, input); err != nil { - t.Errorf("writePacket: %v", err) - } - - packetSize := buf.Len() - buf.Write(make([]byte, 2*maxPacket)) - - // We corrupt each byte, but this usually will only test the - // 'packet too large' or 'MAC failure' cases. - lastRead := -1 - for i := 0; i < packetSize; i++ { - server, err := newPacketCipher(clientKeys, algs, kr) - if err != nil { - t.Fatalf("newPacketCipher(client): %v", err) - } - - fresh := &bytes.Buffer{} - fresh.Write(buf.Bytes()) - fresh.Bytes()[i] ^= 0x01 - - before := fresh.Len() - _, err = server.readPacket(0, fresh) - if err == nil { - t.Errorf("corrupt byte %d: readPacket succeeded ", i) - continue - } - if _, ok := err.(cbcError); !ok { - t.Errorf("corrupt byte %d: got %v (%T), want cbcError", i, err, err) - continue - } - - after := fresh.Len() - bytesRead := before - after - if bytesRead < maxPacket { - t.Errorf("corrupt byte %d: read %d bytes, want more than %d", i, bytesRead, maxPacket) - continue - } - - if i > 0 && bytesRead != lastRead { - t.Errorf("corrupt byte %d: read %d bytes, want %d bytes read", i, bytesRead, lastRead) - } - lastRead = bytesRead - } -} diff --git a/Godeps/_workspace/src/golang.org/x/crypto/ssh/client_auth_test.go b/Godeps/_workspace/src/golang.org/x/crypto/ssh/client_auth_test.go deleted file mode 100644 index c92b58786..000000000 --- a/Godeps/_workspace/src/golang.org/x/crypto/ssh/client_auth_test.go +++ /dev/null @@ -1,393 +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 ssh - -import ( - "bytes" - "crypto/rand" - "errors" - "fmt" - "strings" - "testing" -) - -type keyboardInteractive map[string]string - -func (cr keyboardInteractive) Challenge(user string, instruction string, questions []string, echos []bool) ([]string, error) { - var answers []string - for _, q := range questions { - answers = append(answers, cr[q]) - } - return answers, nil -} - -// reused internally by tests -var clientPassword = "tiger" - -// tryAuth runs a handshake with a given config against an SSH server -// with config serverConfig -func tryAuth(t *testing.T, config *ClientConfig) error { - c1, c2, err := netPipe() - if err != nil { - t.Fatalf("netPipe: %v", err) - } - defer c1.Close() - defer c2.Close() - - certChecker := CertChecker{ - IsAuthority: func(k PublicKey) bool { - return bytes.Equal(k.Marshal(), testPublicKeys["ecdsa"].Marshal()) - }, - UserKeyFallback: func(conn ConnMetadata, key PublicKey) (*Permissions, error) { - if conn.User() == "testuser" && bytes.Equal(key.Marshal(), testPublicKeys["rsa"].Marshal()) { - return nil, nil - } - - return nil, fmt.Errorf("pubkey for %q not acceptable", conn.User()) - }, - IsRevoked: func(c *Certificate) bool { - return c.Serial == 666 - }, - } - - serverConfig := &ServerConfig{ - PasswordCallback: func(conn ConnMetadata, pass []byte) (*Permissions, error) { - if conn.User() == "testuser" && string(pass) == clientPassword { - return nil, nil - } - return nil, errors.New("password auth failed") - }, - PublicKeyCallback: certChecker.Authenticate, - KeyboardInteractiveCallback: func(conn ConnMetadata, challenge KeyboardInteractiveChallenge) (*Permissions, error) { - ans, err := challenge("user", - "instruction", - []string{"question1", "question2"}, - []bool{true, true}) - if err != nil { - return nil, err - } - ok := conn.User() == "testuser" && ans[0] == "answer1" && ans[1] == "answer2" - if ok { - challenge("user", "motd", nil, nil) - return nil, nil - } - return nil, errors.New("keyboard-interactive failed") - }, - AuthLogCallback: func(conn ConnMetadata, method string, err error) { - t.Logf("user %q, method %q: %v", conn.User(), method, err) - }, - } - serverConfig.AddHostKey(testSigners["rsa"]) - - go newServer(c1, serverConfig) - _, _, _, err = NewClientConn(c2, "", config) - return err -} - -func TestClientAuthPublicKey(t *testing.T) { - config := &ClientConfig{ - User: "testuser", - Auth: []AuthMethod{ - PublicKeys(testSigners["rsa"]), - }, - } - if err := tryAuth(t, config); err != nil { - t.Fatalf("unable to dial remote side: %s", err) - } -} - -func TestAuthMethodPassword(t *testing.T) { - config := &ClientConfig{ - User: "testuser", - Auth: []AuthMethod{ - Password(clientPassword), - }, - } - - if err := tryAuth(t, config); err != nil { - t.Fatalf("unable to dial remote side: %s", err) - } -} - -func TestAuthMethodFallback(t *testing.T) { - var passwordCalled bool - config := &ClientConfig{ - User: "testuser", - Auth: []AuthMethod{ - PublicKeys(testSigners["rsa"]), - PasswordCallback( - func() (string, error) { - passwordCalled = true - return "WRONG", nil - }), - }, - } - - if err := tryAuth(t, config); err != nil { - t.Fatalf("unable to dial remote side: %s", err) - } - - if passwordCalled { - t.Errorf("password auth tried before public-key auth.") - } -} - -func TestAuthMethodWrongPassword(t *testing.T) { - config := &ClientConfig{ - User: "testuser", - Auth: []AuthMethod{ - Password("wrong"), - PublicKeys(testSigners["rsa"]), - }, - } - - if err := tryAuth(t, config); err != nil { - t.Fatalf("unable to dial remote side: %s", err) - } -} - -func TestAuthMethodKeyboardInteractive(t *testing.T) { - answers := keyboardInteractive(map[string]string{ - "question1": "answer1", - "question2": "answer2", - }) - config := &ClientConfig{ - User: "testuser", - Auth: []AuthMethod{ - KeyboardInteractive(answers.Challenge), - }, - } - - if err := tryAuth(t, config); err != nil { - t.Fatalf("unable to dial remote side: %s", err) - } -} - -func TestAuthMethodWrongKeyboardInteractive(t *testing.T) { - answers := keyboardInteractive(map[string]string{ - "question1": "answer1", - "question2": "WRONG", - }) - config := &ClientConfig{ - User: "testuser", - Auth: []AuthMethod{ - KeyboardInteractive(answers.Challenge), - }, - } - - if err := tryAuth(t, config); err == nil { - t.Fatalf("wrong answers should not have authenticated with KeyboardInteractive") - } -} - -// the mock server will only authenticate ssh-rsa keys -func TestAuthMethodInvalidPublicKey(t *testing.T) { - config := &ClientConfig{ - User: "testuser", - Auth: []AuthMethod{ - PublicKeys(testSigners["dsa"]), - }, - } - - if err := tryAuth(t, config); err == nil { - t.Fatalf("dsa private key should not have authenticated with rsa public key") - } -} - -// the client should authenticate with the second key -func TestAuthMethodRSAandDSA(t *testing.T) { - config := &ClientConfig{ - User: "testuser", - Auth: []AuthMethod{ - PublicKeys(testSigners["dsa"], testSigners["rsa"]), - }, - } - if err := tryAuth(t, config); err != nil { - t.Fatalf("client could not authenticate with rsa key: %v", err) - } -} - -func TestClientHMAC(t *testing.T) { - for _, mac := range supportedMACs { - config := &ClientConfig{ - User: "testuser", - Auth: []AuthMethod{ - PublicKeys(testSigners["rsa"]), - }, - Config: Config{ - MACs: []string{mac}, - }, - } - if err := tryAuth(t, config); err != nil { - t.Fatalf("client could not authenticate with mac algo %s: %v", mac, err) - } - } -} - -// issue 4285. -func TestClientUnsupportedCipher(t *testing.T) { - config := &ClientConfig{ - User: "testuser", - Auth: []AuthMethod{ - PublicKeys(), - }, - Config: Config{ - Ciphers: []string{"aes128-cbc"}, // not currently supported - }, - } - if err := tryAuth(t, config); err == nil { - t.Errorf("expected no ciphers in common") - } -} - -func TestClientUnsupportedKex(t *testing.T) { - config := &ClientConfig{ - User: "testuser", - Auth: []AuthMethod{ - PublicKeys(), - }, - Config: Config{ - KeyExchanges: []string{"diffie-hellman-group-exchange-sha256"}, // not currently supported - }, - } - if err := tryAuth(t, config); err == nil || !strings.Contains(err.Error(), "no common algorithms") { - t.Errorf("got %v, expected 'no common algorithms'", err) - } -} - -func TestClientLoginCert(t *testing.T) { - cert := &Certificate{ - Key: testPublicKeys["rsa"], - ValidBefore: CertTimeInfinity, - CertType: UserCert, - } - cert.SignCert(rand.Reader, testSigners["ecdsa"]) - certSigner, err := NewCertSigner(cert, testSigners["rsa"]) - if err != nil { - t.Fatalf("NewCertSigner: %v", err) - } - - clientConfig := &ClientConfig{ - User: "user", - } - clientConfig.Auth = append(clientConfig.Auth, PublicKeys(certSigner)) - - t.Log("should succeed") - if err := tryAuth(t, clientConfig); err != nil { - t.Errorf("cert login failed: %v", err) - } - - t.Log("corrupted signature") - cert.Signature.Blob[0]++ - if err := tryAuth(t, clientConfig); err == nil { - t.Errorf("cert login passed with corrupted sig") - } - - t.Log("revoked") - cert.Serial = 666 - cert.SignCert(rand.Reader, testSigners["ecdsa"]) - if err := tryAuth(t, clientConfig); err == nil { - t.Errorf("revoked cert login succeeded") - } - cert.Serial = 1 - - t.Log("sign with wrong key") - cert.SignCert(rand.Reader, testSigners["dsa"]) - if err := tryAuth(t, clientConfig); err == nil { - t.Errorf("cert login passed with non-authoritive key") - } - - t.Log("host cert") - cert.CertType = HostCert - cert.SignCert(rand.Reader, testSigners["ecdsa"]) - if err := tryAuth(t, clientConfig); err == nil { - t.Errorf("cert login passed with wrong type") - } - cert.CertType = UserCert - - t.Log("principal specified") - cert.ValidPrincipals = []string{"user"} - cert.SignCert(rand.Reader, testSigners["ecdsa"]) - if err := tryAuth(t, clientConfig); err != nil { - t.Errorf("cert login failed: %v", err) - } - - t.Log("wrong principal specified") - cert.ValidPrincipals = []string{"fred"} - cert.SignCert(rand.Reader, testSigners["ecdsa"]) - if err := tryAuth(t, clientConfig); err == nil { - t.Errorf("cert login passed with wrong principal") - } - cert.ValidPrincipals = nil - - t.Log("added critical option") - cert.CriticalOptions = map[string]string{"root-access": "yes"} - cert.SignCert(rand.Reader, testSigners["ecdsa"]) - if err := tryAuth(t, clientConfig); err == nil { - t.Errorf("cert login passed with unrecognized critical option") - } - - t.Log("allowed source address") - cert.CriticalOptions = map[string]string{"source-address": "127.0.0.42/24"} - cert.SignCert(rand.Reader, testSigners["ecdsa"]) - if err := tryAuth(t, clientConfig); err != nil { - t.Errorf("cert login with source-address failed: %v", err) - } - - t.Log("disallowed source address") - cert.CriticalOptions = map[string]string{"source-address": "127.0.0.42"} - cert.SignCert(rand.Reader, testSigners["ecdsa"]) - if err := tryAuth(t, clientConfig); err == nil { - t.Errorf("cert login with source-address succeeded") - } -} - -func testPermissionsPassing(withPermissions bool, t *testing.T) { - serverConfig := &ServerConfig{ - PublicKeyCallback: func(conn ConnMetadata, key PublicKey) (*Permissions, error) { - if conn.User() == "nopermissions" { - return nil, nil - } else { - return &Permissions{}, nil - } - }, - } - serverConfig.AddHostKey(testSigners["rsa"]) - - clientConfig := &ClientConfig{ - Auth: []AuthMethod{ - PublicKeys(testSigners["rsa"]), - }, - } - if withPermissions { - clientConfig.User = "permissions" - } else { - clientConfig.User = "nopermissions" - } - - c1, c2, err := netPipe() - if err != nil { - t.Fatalf("netPipe: %v", err) - } - defer c1.Close() - defer c2.Close() - - go NewClientConn(c2, "", clientConfig) - serverConn, err := newServer(c1, serverConfig) - if err != nil { - t.Fatal(err) - } - if p := serverConn.Permissions; (p != nil) != withPermissions { - t.Fatalf("withPermissions is %t, but Permissions object is %#v", withPermissions, p) - } -} - -func TestPermissionsPassing(t *testing.T) { - testPermissionsPassing(true, t) -} - -func TestNoPermissionsPassing(t *testing.T) { - testPermissionsPassing(false, t) -} diff --git a/Godeps/_workspace/src/golang.org/x/crypto/ssh/client_test.go b/Godeps/_workspace/src/golang.org/x/crypto/ssh/client_test.go deleted file mode 100644 index 1fe790cb4..000000000 --- a/Godeps/_workspace/src/golang.org/x/crypto/ssh/client_test.go +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright 2014 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 ssh - -import ( - "net" - "testing" -) - -func testClientVersion(t *testing.T, config *ClientConfig, expected string) { - clientConn, serverConn := net.Pipe() - defer clientConn.Close() - receivedVersion := make(chan string, 1) - go func() { - version, err := readVersion(serverConn) - if err != nil { - receivedVersion <- "" - } else { - receivedVersion <- string(version) - } - serverConn.Close() - }() - NewClientConn(clientConn, "", config) - actual := <-receivedVersion - if actual != expected { - t.Fatalf("got %s; want %s", actual, expected) - } -} - -func TestCustomClientVersion(t *testing.T) { - version := "Test-Client-Version-0.0" - testClientVersion(t, &ClientConfig{ClientVersion: version}, version) -} - -func TestDefaultClientVersion(t *testing.T) { - testClientVersion(t, &ClientConfig{}, packageVersion) -} diff --git a/Godeps/_workspace/src/golang.org/x/crypto/ssh/common.go b/Godeps/_workspace/src/golang.org/x/crypto/ssh/common.go index 1aef9c050..9fc739e1d 100644 --- a/Godeps/_workspace/src/golang.org/x/crypto/ssh/common.go +++ b/Godeps/_workspace/src/golang.org/x/crypto/ssh/common.go @@ -85,27 +85,15 @@ func parseError(tag uint8) error { return fmt.Errorf("ssh: parse error in message type %d", tag) } -func findCommonAlgorithm(clientAlgos []string, serverAlgos []string) (commonAlgo string, ok bool) { - for _, clientAlgo := range clientAlgos { - for _, serverAlgo := range serverAlgos { - if clientAlgo == serverAlgo { - return clientAlgo, true +func findCommon(what string, client []string, server []string) (common string, err error) { + for _, c := range client { + for _, s := range server { + if c == s { + return c, nil } } } - return -} - -func findCommonCipher(clientCiphers []string, serverCiphers []string) (commonCipher string, ok bool) { - for _, clientCipher := range clientCiphers { - for _, serverCipher := range serverCiphers { - // reject the cipher if we have no cipherModes definition - if clientCipher == serverCipher && cipherModes[clientCipher] != nil { - return clientCipher, true - } - } - } - return + return "", fmt.Errorf("ssh: no common algorithm for %s; client offered: %v, server offered: %v", what, client, server) } type directionAlgorithms struct { @@ -121,50 +109,50 @@ type algorithms struct { r directionAlgorithms } -func findAgreedAlgorithms(clientKexInit, serverKexInit *kexInitMsg) (algs *algorithms) { - var ok bool +func findAgreedAlgorithms(clientKexInit, serverKexInit *kexInitMsg) (algs *algorithms, err error) { result := &algorithms{} - result.kex, ok = findCommonAlgorithm(clientKexInit.KexAlgos, serverKexInit.KexAlgos) - if !ok { + + result.kex, err = findCommon("key exchange", clientKexInit.KexAlgos, serverKexInit.KexAlgos) + if err != nil { return } - result.hostKey, ok = findCommonAlgorithm(clientKexInit.ServerHostKeyAlgos, serverKexInit.ServerHostKeyAlgos) - if !ok { + result.hostKey, err = findCommon("host key", clientKexInit.ServerHostKeyAlgos, serverKexInit.ServerHostKeyAlgos) + if err != nil { return } - result.w.Cipher, ok = findCommonCipher(clientKexInit.CiphersClientServer, serverKexInit.CiphersClientServer) - if !ok { + result.w.Cipher, err = findCommon("client to server cipher", clientKexInit.CiphersClientServer, serverKexInit.CiphersClientServer) + if err != nil { return } - result.r.Cipher, ok = findCommonCipher(clientKexInit.CiphersServerClient, serverKexInit.CiphersServerClient) - if !ok { + result.r.Cipher, err = findCommon("server to client cipher", clientKexInit.CiphersServerClient, serverKexInit.CiphersServerClient) + if err != nil { return } - result.w.MAC, ok = findCommonAlgorithm(clientKexInit.MACsClientServer, serverKexInit.MACsClientServer) - if !ok { + result.w.MAC, err = findCommon("client to server MAC", clientKexInit.MACsClientServer, serverKexInit.MACsClientServer) + if err != nil { return } - result.r.MAC, ok = findCommonAlgorithm(clientKexInit.MACsServerClient, serverKexInit.MACsServerClient) - if !ok { + result.r.MAC, err = findCommon("server to client MAC", clientKexInit.MACsServerClient, serverKexInit.MACsServerClient) + if err != nil { return } - result.w.Compression, ok = findCommonAlgorithm(clientKexInit.CompressionClientServer, serverKexInit.CompressionClientServer) - if !ok { + result.w.Compression, err = findCommon("client to server compression", clientKexInit.CompressionClientServer, serverKexInit.CompressionClientServer) + if err != nil { return } - result.r.Compression, ok = findCommonAlgorithm(clientKexInit.CompressionServerClient, serverKexInit.CompressionServerClient) - if !ok { + result.r.Compression, err = findCommon("server to client compression", clientKexInit.CompressionServerClient, serverKexInit.CompressionServerClient) + if err != nil { return } - return result + return result, nil } // If rekeythreshold is too small, we can't make any progress sending diff --git a/Godeps/_workspace/src/golang.org/x/crypto/ssh/example_test.go b/Godeps/_workspace/src/golang.org/x/crypto/ssh/example_test.go deleted file mode 100644 index dfd9dcab6..000000000 --- a/Godeps/_workspace/src/golang.org/x/crypto/ssh/example_test.go +++ /dev/null @@ -1,211 +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 ssh_test - -import ( - "bytes" - "fmt" - "io/ioutil" - "log" - "net" - "net/http" - - "golang.org/x/crypto/ssh" - "golang.org/x/crypto/ssh/terminal" -) - -func ExampleNewServerConn() { - // An SSH server is represented by a ServerConfig, which holds - // certificate details and handles authentication of ServerConns. - config := &ssh.ServerConfig{ - PasswordCallback: func(c ssh.ConnMetadata, pass []byte) (*ssh.Permissions, error) { - // Should use constant-time compare (or better, salt+hash) in - // a production setting. - if c.User() == "testuser" && string(pass) == "tiger" { - return nil, nil - } - return nil, fmt.Errorf("password rejected for %q", c.User()) - }, - } - - privateBytes, err := ioutil.ReadFile("id_rsa") - if err != nil { - panic("Failed to load private key") - } - - private, err := ssh.ParsePrivateKey(privateBytes) - if err != nil { - panic("Failed to parse private key") - } - - config.AddHostKey(private) - - // Once a ServerConfig has been configured, connections can be - // accepted. - listener, err := net.Listen("tcp", "0.0.0.0:2022") - if err != nil { - panic("failed to listen for connection") - } - nConn, err := listener.Accept() - if err != nil { - panic("failed to accept incoming connection") - } - - // Before use, a handshake must be performed on the incoming - // net.Conn. - _, chans, reqs, err := ssh.NewServerConn(nConn, config) - if err != nil { - panic("failed to handshake") - } - // The incoming Request channel must be serviced. - go ssh.DiscardRequests(reqs) - - // Service the incoming Channel channel. - for newChannel := range chans { - // Channels have a type, depending on the application level - // protocol intended. In the case of a shell, the type is - // "session" and ServerShell may be used to present a simple - // terminal interface. - if newChannel.ChannelType() != "session" { - newChannel.Reject(ssh.UnknownChannelType, "unknown channel type") - continue - } - channel, requests, err := newChannel.Accept() - if err != nil { - panic("could not accept channel.") - } - - // Sessions have out-of-band requests such as "shell", - // "pty-req" and "env". Here we handle only the - // "shell" request. - go func(in <-chan *ssh.Request) { - for req := range in { - ok := false - switch req.Type { - case "shell": - ok = true - if len(req.Payload) > 0 { - // We don't accept any - // commands, only the - // default shell. - ok = false - } - } - req.Reply(ok, nil) - } - }(requests) - - term := terminal.NewTerminal(channel, "> ") - - go func() { - defer channel.Close() - for { - line, err := term.ReadLine() - if err != nil { - break - } - fmt.Println(line) - } - }() - } -} - -func ExampleDial() { - // An SSH client is represented with a ClientConn. Currently only - // the "password" authentication method is supported. - // - // To authenticate with the remote server you must pass at least one - // implementation of AuthMethod via the Auth field in ClientConfig. - config := &ssh.ClientConfig{ - User: "username", - Auth: []ssh.AuthMethod{ - ssh.Password("yourpassword"), - }, - } - client, err := ssh.Dial("tcp", "yourserver.com:22", config) - if err != nil { - panic("Failed to dial: " + err.Error()) - } - - // Each ClientConn can support multiple interactive sessions, - // represented by a Session. - session, err := client.NewSession() - if err != nil { - panic("Failed to create session: " + err.Error()) - } - defer session.Close() - - // Once a Session is created, you can execute a single command on - // the remote side using the Run method. - var b bytes.Buffer - session.Stdout = &b - if err := session.Run("/usr/bin/whoami"); err != nil { - panic("Failed to run: " + err.Error()) - } - fmt.Println(b.String()) -} - -func ExampleClient_Listen() { - config := &ssh.ClientConfig{ - User: "username", - Auth: []ssh.AuthMethod{ - ssh.Password("password"), - }, - } - // Dial your ssh server. - conn, err := ssh.Dial("tcp", "localhost:22", config) - if err != nil { - log.Fatalf("unable to connect: %s", err) - } - defer conn.Close() - - // Request the remote side to open port 8080 on all interfaces. - l, err := conn.Listen("tcp", "0.0.0.0:8080") - if err != nil { - log.Fatalf("unable to register tcp forward: %v", err) - } - defer l.Close() - - // Serve HTTP with your SSH server acting as a reverse proxy. - http.Serve(l, http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) { - fmt.Fprintf(resp, "Hello world!\n") - })) -} - -func ExampleSession_RequestPty() { - // Create client config - config := &ssh.ClientConfig{ - User: "username", - Auth: []ssh.AuthMethod{ - ssh.Password("password"), - }, - } - // Connect to ssh server - conn, err := ssh.Dial("tcp", "localhost:22", config) - if err != nil { - log.Fatalf("unable to connect: %s", err) - } - defer conn.Close() - // Create a session - session, err := conn.NewSession() - if err != nil { - log.Fatalf("unable to create session: %s", err) - } - defer session.Close() - // Set up terminal modes - modes := ssh.TerminalModes{ - ssh.ECHO: 0, // disable echoing - ssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud - ssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud - } - // Request pseudo terminal - if err := session.RequestPty("xterm", 80, 40, modes); err != nil { - log.Fatalf("request for pseudo terminal failed: %s", err) - } - // Start remote shell - if err := session.Shell(); err != nil { - log.Fatalf("failed to start shell: %s", err) - } -} diff --git a/Godeps/_workspace/src/golang.org/x/crypto/ssh/handshake.go b/Godeps/_workspace/src/golang.org/x/crypto/ssh/handshake.go index 12633c811..1c54f7587 100644 --- a/Godeps/_workspace/src/golang.org/x/crypto/ssh/handshake.go +++ b/Godeps/_workspace/src/golang.org/x/crypto/ssh/handshake.go @@ -332,9 +332,9 @@ func (t *handshakeTransport) enterKeyExchange(otherInitPacket []byte) error { magics.serverKexInit = otherInitPacket } - algs := findAgreedAlgorithms(clientInit, serverInit) - if algs == nil { - return errors.New("ssh: no common algorithms") + algs, err := findAgreedAlgorithms(clientInit, serverInit) + if err != nil { + return err } // We don't send FirstKexFollows, but we handle receiving it. diff --git a/Godeps/_workspace/src/golang.org/x/crypto/ssh/handshake_test.go b/Godeps/_workspace/src/golang.org/x/crypto/ssh/handshake_test.go deleted file mode 100644 index b86d369cc..000000000 --- a/Godeps/_workspace/src/golang.org/x/crypto/ssh/handshake_test.go +++ /dev/null @@ -1,415 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package ssh - -import ( - "bytes" - "crypto/rand" - "errors" - "fmt" - "net" - "runtime" - "strings" - "sync" - "testing" -) - -type testChecker struct { - calls []string -} - -func (t *testChecker) Check(dialAddr string, addr net.Addr, key PublicKey) error { - if dialAddr == "bad" { - return fmt.Errorf("dialAddr is bad") - } - - if tcpAddr, ok := addr.(*net.TCPAddr); !ok || tcpAddr == nil { - return fmt.Errorf("testChecker: got %T want *net.TCPAddr", addr) - } - - t.calls = append(t.calls, fmt.Sprintf("%s %v %s %x", dialAddr, addr, key.Type(), key.Marshal())) - - return nil -} - -// netPipe is analogous to net.Pipe, but it uses a real net.Conn, and -// therefore is buffered (net.Pipe deadlocks if both sides start with -// a write.) -func netPipe() (net.Conn, net.Conn, error) { - listener, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - return nil, nil, err - } - defer listener.Close() - c1, err := net.Dial("tcp", listener.Addr().String()) - if err != nil { - return nil, nil, err - } - - c2, err := listener.Accept() - if err != nil { - c1.Close() - return nil, nil, err - } - - return c1, c2, nil -} - -func handshakePair(clientConf *ClientConfig, addr string) (client *handshakeTransport, server *handshakeTransport, err error) { - a, b, err := netPipe() - if err != nil { - return nil, nil, err - } - - trC := newTransport(a, rand.Reader, true) - trS := newTransport(b, rand.Reader, false) - clientConf.SetDefaults() - - v := []byte("version") - client = newClientTransport(trC, v, v, clientConf, addr, a.RemoteAddr()) - - serverConf := &ServerConfig{} - serverConf.AddHostKey(testSigners["ecdsa"]) - serverConf.AddHostKey(testSigners["rsa"]) - serverConf.SetDefaults() - server = newServerTransport(trS, v, v, serverConf) - - return client, server, nil -} - -func TestHandshakeBasic(t *testing.T) { - if runtime.GOOS == "plan9" { - t.Skip("see golang.org/issue/7237") - } - checker := &testChecker{} - trC, trS, err := handshakePair(&ClientConfig{HostKeyCallback: checker.Check}, "addr") - if err != nil { - t.Fatalf("handshakePair: %v", err) - } - - defer trC.Close() - defer trS.Close() - - go func() { - // Client writes a bunch of stuff, and does a key - // change in the middle. This should not confuse the - // handshake in progress - for i := 0; i < 10; i++ { - p := []byte{msgRequestSuccess, byte(i)} - if err := trC.writePacket(p); err != nil { - t.Fatalf("sendPacket: %v", err) - } - if i == 5 { - // halfway through, we request a key change. - _, _, err := trC.sendKexInit() - if err != nil { - t.Fatalf("sendKexInit: %v", err) - } - } - } - trC.Close() - }() - - // Server checks that client messages come in cleanly - i := 0 - for { - p, err := trS.readPacket() - if err != nil { - break - } - if p[0] == msgNewKeys { - continue - } - want := []byte{msgRequestSuccess, byte(i)} - if bytes.Compare(p, want) != 0 { - t.Errorf("message %d: got %q, want %q", i, p, want) - } - i++ - } - if i != 10 { - t.Errorf("received %d messages, want 10.", i) - } - - // If all went well, we registered exactly 1 key change. - if len(checker.calls) != 1 { - t.Fatalf("got %d host key checks, want 1", len(checker.calls)) - } - - pub := testSigners["ecdsa"].PublicKey() - want := fmt.Sprintf("%s %v %s %x", "addr", trC.remoteAddr, pub.Type(), pub.Marshal()) - if want != checker.calls[0] { - t.Errorf("got %q want %q for host key check", checker.calls[0], want) - } -} - -func TestHandshakeError(t *testing.T) { - checker := &testChecker{} - trC, trS, err := handshakePair(&ClientConfig{HostKeyCallback: checker.Check}, "bad") - if err != nil { - t.Fatalf("handshakePair: %v", err) - } - defer trC.Close() - defer trS.Close() - - // send a packet - packet := []byte{msgRequestSuccess, 42} - if err := trC.writePacket(packet); err != nil { - t.Errorf("writePacket: %v", err) - } - - // Now request a key change. - _, _, err = trC.sendKexInit() - if err != nil { - t.Errorf("sendKexInit: %v", err) - } - - // the key change will fail, and afterwards we can't write. - if err := trC.writePacket([]byte{msgRequestSuccess, 43}); err == nil { - t.Errorf("writePacket after botched rekey succeeded.") - } - - readback, err := trS.readPacket() - if err != nil { - t.Fatalf("server closed too soon: %v", err) - } - if bytes.Compare(readback, packet) != 0 { - t.Errorf("got %q want %q", readback, packet) - } - readback, err = trS.readPacket() - if err == nil { - t.Errorf("got a message %q after failed key change", readback) - } -} - -func TestHandshakeTwice(t *testing.T) { - checker := &testChecker{} - trC, trS, err := handshakePair(&ClientConfig{HostKeyCallback: checker.Check}, "addr") - if err != nil { - t.Fatalf("handshakePair: %v", err) - } - - defer trC.Close() - defer trS.Close() - - // send a packet - packet := make([]byte, 5) - packet[0] = msgRequestSuccess - if err := trC.writePacket(packet); err != nil { - t.Errorf("writePacket: %v", err) - } - - // Now request a key change. - _, _, err = trC.sendKexInit() - if err != nil { - t.Errorf("sendKexInit: %v", err) - } - - // Send another packet. Use a fresh one, since writePacket destroys. - packet = make([]byte, 5) - packet[0] = msgRequestSuccess - if err := trC.writePacket(packet); err != nil { - t.Errorf("writePacket: %v", err) - } - - // 2nd key change. - _, _, err = trC.sendKexInit() - if err != nil { - t.Errorf("sendKexInit: %v", err) - } - - packet = make([]byte, 5) - packet[0] = msgRequestSuccess - if err := trC.writePacket(packet); err != nil { - t.Errorf("writePacket: %v", err) - } - - packet = make([]byte, 5) - packet[0] = msgRequestSuccess - for i := 0; i < 5; i++ { - msg, err := trS.readPacket() - if err != nil { - t.Fatalf("server closed too soon: %v", err) - } - if msg[0] == msgNewKeys { - continue - } - - if bytes.Compare(msg, packet) != 0 { - t.Errorf("packet %d: got %q want %q", i, msg, packet) - } - } - if len(checker.calls) != 2 { - t.Errorf("got %d key changes, want 2", len(checker.calls)) - } -} - -func TestHandshakeAutoRekeyWrite(t *testing.T) { - checker := &testChecker{} - clientConf := &ClientConfig{HostKeyCallback: checker.Check} - clientConf.RekeyThreshold = 500 - trC, trS, err := handshakePair(clientConf, "addr") - if err != nil { - t.Fatalf("handshakePair: %v", err) - } - defer trC.Close() - defer trS.Close() - - for i := 0; i < 5; i++ { - packet := make([]byte, 251) - packet[0] = msgRequestSuccess - if err := trC.writePacket(packet); err != nil { - t.Errorf("writePacket: %v", err) - } - } - - j := 0 - for ; j < 5; j++ { - _, err := trS.readPacket() - if err != nil { - break - } - } - - if j != 5 { - t.Errorf("got %d, want 5 messages", j) - } - - if len(checker.calls) != 2 { - t.Errorf("got %d key changes, wanted 2", len(checker.calls)) - } -} - -type syncChecker struct { - called chan int -} - -func (t *syncChecker) Check(dialAddr string, addr net.Addr, key PublicKey) error { - t.called <- 1 - return nil -} - -func TestHandshakeAutoRekeyRead(t *testing.T) { - sync := &syncChecker{make(chan int, 2)} - clientConf := &ClientConfig{ - HostKeyCallback: sync.Check, - } - clientConf.RekeyThreshold = 500 - - trC, trS, err := handshakePair(clientConf, "addr") - if err != nil { - t.Fatalf("handshakePair: %v", err) - } - defer trC.Close() - defer trS.Close() - - packet := make([]byte, 501) - packet[0] = msgRequestSuccess - if err := trS.writePacket(packet); err != nil { - t.Fatalf("writePacket: %v", err) - } - // While we read out the packet, a key change will be - // initiated. - if _, err := trC.readPacket(); err != nil { - t.Fatalf("readPacket(client): %v", err) - } - - <-sync.called -} - -// errorKeyingTransport generates errors after a given number of -// read/write operations. -type errorKeyingTransport struct { - packetConn - readLeft, writeLeft int -} - -func (n *errorKeyingTransport) prepareKeyChange(*algorithms, *kexResult) error { - return nil -} -func (n *errorKeyingTransport) getSessionID() []byte { - return nil -} - -func (n *errorKeyingTransport) writePacket(packet []byte) error { - if n.writeLeft == 0 { - n.Close() - return errors.New("barf") - } - - n.writeLeft-- - return n.packetConn.writePacket(packet) -} - -func (n *errorKeyingTransport) readPacket() ([]byte, error) { - if n.readLeft == 0 { - n.Close() - return nil, errors.New("barf") - } - - n.readLeft-- - return n.packetConn.readPacket() -} - -func TestHandshakeErrorHandlingRead(t *testing.T) { - for i := 0; i < 20; i++ { - testHandshakeErrorHandlingN(t, i, -1) - } -} - -func TestHandshakeErrorHandlingWrite(t *testing.T) { - for i := 0; i < 20; i++ { - testHandshakeErrorHandlingN(t, -1, i) - } -} - -// testHandshakeErrorHandlingN runs handshakes, injecting errors. If -// handshakeTransport deadlocks, the go runtime will detect it and -// panic. -func testHandshakeErrorHandlingN(t *testing.T, readLimit, writeLimit int) { - msg := Marshal(&serviceRequestMsg{strings.Repeat("x", int(minRekeyThreshold)/4)}) - - a, b := memPipe() - defer a.Close() - defer b.Close() - - key := testSigners["ecdsa"] - serverConf := Config{RekeyThreshold: minRekeyThreshold} - serverConf.SetDefaults() - serverConn := newHandshakeTransport(&errorKeyingTransport{a, readLimit, writeLimit}, &serverConf, []byte{'a'}, []byte{'b'}) - serverConn.hostKeys = []Signer{key} - go serverConn.readLoop() - - clientConf := Config{RekeyThreshold: 10 * minRekeyThreshold} - clientConf.SetDefaults() - clientConn := newHandshakeTransport(&errorKeyingTransport{b, -1, -1}, &clientConf, []byte{'a'}, []byte{'b'}) - clientConn.hostKeyAlgorithms = []string{key.PublicKey().Type()} - go clientConn.readLoop() - - var wg sync.WaitGroup - wg.Add(4) - - for _, hs := range []packetConn{serverConn, clientConn} { - go func(c packetConn) { - for { - err := c.writePacket(msg) - if err != nil { - break - } - } - wg.Done() - }(hs) - go func(c packetConn) { - for { - _, err := c.readPacket() - if err != nil { - break - } - } - wg.Done() - }(hs) - } - - wg.Wait() -} diff --git a/Godeps/_workspace/src/golang.org/x/crypto/ssh/kex_test.go b/Godeps/_workspace/src/golang.org/x/crypto/ssh/kex_test.go deleted file mode 100644 index 12ca0acd3..000000000 --- a/Godeps/_workspace/src/golang.org/x/crypto/ssh/kex_test.go +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package ssh - -// Key exchange tests. - -import ( - "crypto/rand" - "reflect" - "testing" -) - -func TestKexes(t *testing.T) { - type kexResultErr struct { - result *kexResult - err error - } - - for name, kex := range kexAlgoMap { - a, b := memPipe() - - s := make(chan kexResultErr, 1) - c := make(chan kexResultErr, 1) - var magics handshakeMagics - go func() { - r, e := kex.Client(a, rand.Reader, &magics) - a.Close() - c <- kexResultErr{r, e} - }() - go func() { - r, e := kex.Server(b, rand.Reader, &magics, testSigners["ecdsa"]) - b.Close() - s <- kexResultErr{r, e} - }() - - clientRes := <-c - serverRes := <-s - if clientRes.err != nil { - t.Errorf("client: %v", clientRes.err) - } - if serverRes.err != nil { - t.Errorf("server: %v", serverRes.err) - } - if !reflect.DeepEqual(clientRes.result, serverRes.result) { - t.Errorf("kex %q: mismatch %#v, %#v", name, clientRes.result, serverRes.result) - } - } -} diff --git a/Godeps/_workspace/src/golang.org/x/crypto/ssh/keys.go b/Godeps/_workspace/src/golang.org/x/crypto/ssh/keys.go index e8af511ee..3272d7c93 100644 --- a/Godeps/_workspace/src/golang.org/x/crypto/ssh/keys.go +++ b/Godeps/_workspace/src/golang.org/x/crypto/ssh/keys.go @@ -422,14 +422,19 @@ func ecHash(curve elliptic.Curve) crypto.Hash { // parseECDSA parses an ECDSA key according to RFC 5656, section 3.1. func parseECDSA(in []byte) (out PublicKey, rest []byte, err error) { - identifier, in, ok := parseString(in) - if !ok { - return nil, nil, errShortRead + var w struct { + Curve string + KeyBytes []byte + Rest []byte `ssh:"rest"` + } + + if err := Unmarshal(in, &w); err != nil { + return nil, nil, err } key := new(ecdsa.PublicKey) - switch string(identifier) { + switch w.Curve { case "nistp256": key.Curve = elliptic.P256() case "nistp384": @@ -440,16 +445,11 @@ func parseECDSA(in []byte) (out PublicKey, rest []byte, err error) { return nil, nil, errors.New("ssh: unsupported curve") } - var keyBytes []byte - if keyBytes, in, ok = parseString(in); !ok { - return nil, nil, errShortRead - } - - key.X, key.Y = elliptic.Unmarshal(key.Curve, keyBytes) + key.X, key.Y = elliptic.Unmarshal(key.Curve, w.KeyBytes) if key.X == nil || key.Y == nil { return nil, nil, errors.New("ssh: invalid curve point") } - return (*ecdsaPublicKey)(key), in, nil + return (*ecdsaPublicKey)(key), w.Rest, nil } func (key *ecdsaPublicKey) Marshal() []byte { diff --git a/Godeps/_workspace/src/golang.org/x/crypto/ssh/keys_test.go b/Godeps/_workspace/src/golang.org/x/crypto/ssh/keys_test.go deleted file mode 100644 index 36b97ad22..000000000 --- a/Godeps/_workspace/src/golang.org/x/crypto/ssh/keys_test.go +++ /dev/null @@ -1,306 +0,0 @@ -// Copyright 2014 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 ssh - -import ( - "bytes" - "crypto/dsa" - "crypto/ecdsa" - "crypto/elliptic" - "crypto/rand" - "crypto/rsa" - "encoding/base64" - "fmt" - "reflect" - "strings" - "testing" - - "golang.org/x/crypto/ssh/testdata" -) - -func rawKey(pub PublicKey) interface{} { - switch k := pub.(type) { - case *rsaPublicKey: - return (*rsa.PublicKey)(k) - case *dsaPublicKey: - return (*dsa.PublicKey)(k) - case *ecdsaPublicKey: - return (*ecdsa.PublicKey)(k) - case *Certificate: - return k - } - panic("unknown key type") -} - -func TestKeyMarshalParse(t *testing.T) { - for _, priv := range testSigners { - pub := priv.PublicKey() - roundtrip, err := ParsePublicKey(pub.Marshal()) - if err != nil { - t.Errorf("ParsePublicKey(%T): %v", pub, err) - } - - k1 := rawKey(pub) - k2 := rawKey(roundtrip) - - if !reflect.DeepEqual(k1, k2) { - t.Errorf("got %#v in roundtrip, want %#v", k2, k1) - } - } -} - -func TestUnsupportedCurves(t *testing.T) { - raw, err := ecdsa.GenerateKey(elliptic.P224(), rand.Reader) - if err != nil { - t.Fatalf("GenerateKey: %v", err) - } - - if _, err = NewSignerFromKey(raw); err == nil || !strings.Contains(err.Error(), "only P256") { - t.Fatalf("NewPrivateKey should not succeed with P224, got: %v", err) - } - - if _, err = NewPublicKey(&raw.PublicKey); err == nil || !strings.Contains(err.Error(), "only P256") { - t.Fatalf("NewPublicKey should not succeed with P224, got: %v", err) - } -} - -func TestNewPublicKey(t *testing.T) { - for _, k := range testSigners { - raw := rawKey(k.PublicKey()) - // Skip certificates, as NewPublicKey does not support them. - if _, ok := raw.(*Certificate); ok { - continue - } - pub, err := NewPublicKey(raw) - if err != nil { - t.Errorf("NewPublicKey(%#v): %v", raw, err) - } - if !reflect.DeepEqual(k.PublicKey(), pub) { - t.Errorf("NewPublicKey(%#v) = %#v, want %#v", raw, pub, k.PublicKey()) - } - } -} - -func TestKeySignVerify(t *testing.T) { - for _, priv := range testSigners { - pub := priv.PublicKey() - - data := []byte("sign me") - sig, err := priv.Sign(rand.Reader, data) - if err != nil { - t.Fatalf("Sign(%T): %v", priv, err) - } - - if err := pub.Verify(data, sig); err != nil { - t.Errorf("publicKey.Verify(%T): %v", priv, err) - } - sig.Blob[5]++ - if err := pub.Verify(data, sig); err == nil { - t.Errorf("publicKey.Verify on broken sig did not fail") - } - } -} - -func TestParseRSAPrivateKey(t *testing.T) { - key := testPrivateKeys["rsa"] - - rsa, ok := key.(*rsa.PrivateKey) - if !ok { - t.Fatalf("got %T, want *rsa.PrivateKey", rsa) - } - - if err := rsa.Validate(); err != nil { - t.Errorf("Validate: %v", err) - } -} - -func TestParseECPrivateKey(t *testing.T) { - key := testPrivateKeys["ecdsa"] - - ecKey, ok := key.(*ecdsa.PrivateKey) - if !ok { - t.Fatalf("got %T, want *ecdsa.PrivateKey", ecKey) - } - - if !validateECPublicKey(ecKey.Curve, ecKey.X, ecKey.Y) { - t.Fatalf("public key does not validate.") - } -} - -func TestParseDSA(t *testing.T) { - // We actually exercise the ParsePrivateKey codepath here, as opposed to - // using the ParseRawPrivateKey+NewSignerFromKey path that testdata_test.go - // uses. - s, err := ParsePrivateKey(testdata.PEMBytes["dsa"]) - if err != nil { - t.Fatalf("ParsePrivateKey returned error: %s", err) - } - - data := []byte("sign me") - sig, err := s.Sign(rand.Reader, data) - if err != nil { - t.Fatalf("dsa.Sign: %v", err) - } - - if err := s.PublicKey().Verify(data, sig); err != nil { - t.Errorf("Verify failed: %v", err) - } -} - -// Tests for authorized_keys parsing. - -// getTestKey returns a public key, and its base64 encoding. -func getTestKey() (PublicKey, string) { - k := testPublicKeys["rsa"] - - b := &bytes.Buffer{} - e := base64.NewEncoder(base64.StdEncoding, b) - e.Write(k.Marshal()) - e.Close() - - return k, b.String() -} - -func TestMarshalParsePublicKey(t *testing.T) { - pub, pubSerialized := getTestKey() - line := fmt.Sprintf("%s %s user@host", pub.Type(), pubSerialized) - - authKeys := MarshalAuthorizedKey(pub) - actualFields := strings.Fields(string(authKeys)) - if len(actualFields) == 0 { - t.Fatalf("failed authKeys: %v", authKeys) - } - - // drop the comment - expectedFields := strings.Fields(line)[0:2] - - if !reflect.DeepEqual(actualFields, expectedFields) { - t.Errorf("got %v, expected %v", actualFields, expectedFields) - } - - actPub, _, _, _, err := ParseAuthorizedKey([]byte(line)) - if err != nil { - t.Fatalf("cannot parse %v: %v", line, err) - } - if !reflect.DeepEqual(actPub, pub) { - t.Errorf("got %v, expected %v", actPub, pub) - } -} - -type authResult struct { - pubKey PublicKey - options []string - comments string - rest string - ok bool -} - -func testAuthorizedKeys(t *testing.T, authKeys []byte, expected []authResult) { - rest := authKeys - var values []authResult - for len(rest) > 0 { - var r authResult - var err error - r.pubKey, r.comments, r.options, rest, err = ParseAuthorizedKey(rest) - r.ok = (err == nil) - t.Log(err) - r.rest = string(rest) - values = append(values, r) - } - - if !reflect.DeepEqual(values, expected) { - t.Errorf("got %#v, expected %#v", values, expected) - } -} - -func TestAuthorizedKeyBasic(t *testing.T) { - pub, pubSerialized := getTestKey() - line := "ssh-rsa " + pubSerialized + " user@host" - testAuthorizedKeys(t, []byte(line), - []authResult{ - {pub, nil, "user@host", "", true}, - }) -} - -func TestAuth(t *testing.T) { - pub, pubSerialized := getTestKey() - authWithOptions := []string{ - `# comments to ignore before any keys...`, - ``, - `env="HOME=/home/root",no-port-forwarding ssh-rsa ` + pubSerialized + ` user@host`, - `# comments to ignore, along with a blank line`, - ``, - `env="HOME=/home/root2" ssh-rsa ` + pubSerialized + ` user2@host2`, - ``, - `# more comments, plus a invalid entry`, - `ssh-rsa data-that-will-not-parse user@host3`, - } - for _, eol := range []string{"\n", "\r\n"} { - authOptions := strings.Join(authWithOptions, eol) - rest2 := strings.Join(authWithOptions[3:], eol) - rest3 := strings.Join(authWithOptions[6:], eol) - testAuthorizedKeys(t, []byte(authOptions), []authResult{ - {pub, []string{`env="HOME=/home/root"`, "no-port-forwarding"}, "user@host", rest2, true}, - {pub, []string{`env="HOME=/home/root2"`}, "user2@host2", rest3, true}, - {nil, nil, "", "", false}, - }) - } -} - -func TestAuthWithQuotedSpaceInEnv(t *testing.T) { - pub, pubSerialized := getTestKey() - authWithQuotedSpaceInEnv := []byte(`env="HOME=/home/root dir",no-port-forwarding ssh-rsa ` + pubSerialized + ` user@host`) - testAuthorizedKeys(t, []byte(authWithQuotedSpaceInEnv), []authResult{ - {pub, []string{`env="HOME=/home/root dir"`, "no-port-forwarding"}, "user@host", "", true}, - }) -} - -func TestAuthWithQuotedCommaInEnv(t *testing.T) { - pub, pubSerialized := getTestKey() - authWithQuotedCommaInEnv := []byte(`env="HOME=/home/root,dir",no-port-forwarding ssh-rsa ` + pubSerialized + ` user@host`) - testAuthorizedKeys(t, []byte(authWithQuotedCommaInEnv), []authResult{ - {pub, []string{`env="HOME=/home/root,dir"`, "no-port-forwarding"}, "user@host", "", true}, - }) -} - -func TestAuthWithQuotedQuoteInEnv(t *testing.T) { - pub, pubSerialized := getTestKey() - authWithQuotedQuoteInEnv := []byte(`env="HOME=/home/\"root dir",no-port-forwarding` + "\t" + `ssh-rsa` + "\t" + pubSerialized + ` user@host`) - authWithDoubleQuotedQuote := []byte(`no-port-forwarding,env="HOME=/home/ \"root dir\"" ssh-rsa ` + pubSerialized + "\t" + `user@host`) - testAuthorizedKeys(t, []byte(authWithQuotedQuoteInEnv), []authResult{ - {pub, []string{`env="HOME=/home/\"root dir"`, "no-port-forwarding"}, "user@host", "", true}, - }) - - testAuthorizedKeys(t, []byte(authWithDoubleQuotedQuote), []authResult{ - {pub, []string{"no-port-forwarding", `env="HOME=/home/ \"root dir\""`}, "user@host", "", true}, - }) -} - -func TestAuthWithInvalidSpace(t *testing.T) { - _, pubSerialized := getTestKey() - authWithInvalidSpace := []byte(`env="HOME=/home/root dir", no-port-forwarding ssh-rsa ` + pubSerialized + ` user@host -#more to follow but still no valid keys`) - testAuthorizedKeys(t, []byte(authWithInvalidSpace), []authResult{ - {nil, nil, "", "", false}, - }) -} - -func TestAuthWithMissingQuote(t *testing.T) { - pub, pubSerialized := getTestKey() - authWithMissingQuote := []byte(`env="HOME=/home/root,no-port-forwarding ssh-rsa ` + pubSerialized + ` user@host -env="HOME=/home/root",shared-control ssh-rsa ` + pubSerialized + ` user@host`) - - testAuthorizedKeys(t, []byte(authWithMissingQuote), []authResult{ - {pub, []string{`env="HOME=/home/root"`, `shared-control`}, "user@host", "", true}, - }) -} - -func TestInvalidEntry(t *testing.T) { - authInvalid := []byte(`ssh-rsa`) - _, _, _, _, err := ParseAuthorizedKey(authInvalid) - if err == nil { - t.Errorf("got valid entry for %q", authInvalid) - } -} diff --git a/Godeps/_workspace/src/golang.org/x/crypto/ssh/mempipe_test.go b/Godeps/_workspace/src/golang.org/x/crypto/ssh/mempipe_test.go deleted file mode 100644 index 8697cd614..000000000 --- a/Godeps/_workspace/src/golang.org/x/crypto/ssh/mempipe_test.go +++ /dev/null @@ -1,110 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package ssh - -import ( - "io" - "sync" - "testing" -) - -// An in-memory packetConn. It is safe to call Close and writePacket -// from different goroutines. -type memTransport struct { - eof bool - pending [][]byte - write *memTransport - sync.Mutex - *sync.Cond -} - -func (t *memTransport) readPacket() ([]byte, error) { - t.Lock() - defer t.Unlock() - for { - if len(t.pending) > 0 { - r := t.pending[0] - t.pending = t.pending[1:] - return r, nil - } - if t.eof { - return nil, io.EOF - } - t.Cond.Wait() - } -} - -func (t *memTransport) closeSelf() error { - t.Lock() - defer t.Unlock() - if t.eof { - return io.EOF - } - t.eof = true - t.Cond.Broadcast() - return nil -} - -func (t *memTransport) Close() error { - err := t.write.closeSelf() - t.closeSelf() - return err -} - -func (t *memTransport) writePacket(p []byte) error { - t.write.Lock() - defer t.write.Unlock() - if t.write.eof { - return io.EOF - } - c := make([]byte, len(p)) - copy(c, p) - t.write.pending = append(t.write.pending, c) - t.write.Cond.Signal() - return nil -} - -func memPipe() (a, b packetConn) { - t1 := memTransport{} - t2 := memTransport{} - t1.write = &t2 - t2.write = &t1 - t1.Cond = sync.NewCond(&t1.Mutex) - t2.Cond = sync.NewCond(&t2.Mutex) - return &t1, &t2 -} - -func TestMemPipe(t *testing.T) { - a, b := memPipe() - if err := a.writePacket([]byte{42}); err != nil { - t.Fatalf("writePacket: %v", err) - } - if err := a.Close(); err != nil { - t.Fatal("Close: ", err) - } - p, err := b.readPacket() - if err != nil { - t.Fatal("readPacket: ", err) - } - if len(p) != 1 || p[0] != 42 { - t.Fatalf("got %v, want {42}", p) - } - p, err = b.readPacket() - if err != io.EOF { - t.Fatalf("got %v, %v, want EOF", p, err) - } -} - -func TestDoubleClose(t *testing.T) { - a, _ := memPipe() - err := a.Close() - if err != nil { - t.Errorf("Close: %v", err) - } - err = a.Close() - if err != io.EOF { - t.Errorf("expect EOF on double close.") - } -} diff --git a/Godeps/_workspace/src/golang.org/x/crypto/ssh/messages_test.go b/Godeps/_workspace/src/golang.org/x/crypto/ssh/messages_test.go deleted file mode 100644 index 955b5127f..000000000 --- a/Godeps/_workspace/src/golang.org/x/crypto/ssh/messages_test.go +++ /dev/null @@ -1,254 +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 ssh - -import ( - "bytes" - "math/big" - "math/rand" - "reflect" - "testing" - "testing/quick" -) - -var intLengthTests = []struct { - val, length int -}{ - {0, 4 + 0}, - {1, 4 + 1}, - {127, 4 + 1}, - {128, 4 + 2}, - {-1, 4 + 1}, -} - -func TestIntLength(t *testing.T) { - for _, test := range intLengthTests { - v := new(big.Int).SetInt64(int64(test.val)) - length := intLength(v) - if length != test.length { - t.Errorf("For %d, got length %d but expected %d", test.val, length, test.length) - } - } -} - -type msgAllTypes struct { - Bool bool `sshtype:"21"` - Array [16]byte - Uint64 uint64 - Uint32 uint32 - Uint8 uint8 - String string - Strings []string - Bytes []byte - Int *big.Int - Rest []byte `ssh:"rest"` -} - -func (t *msgAllTypes) Generate(rand *rand.Rand, size int) reflect.Value { - m := &msgAllTypes{} - m.Bool = rand.Intn(2) == 1 - randomBytes(m.Array[:], rand) - m.Uint64 = uint64(rand.Int63n(1<<63 - 1)) - m.Uint32 = uint32(rand.Intn((1 << 31) - 1)) - m.Uint8 = uint8(rand.Intn(1 << 8)) - m.String = string(m.Array[:]) - m.Strings = randomNameList(rand) - m.Bytes = m.Array[:] - m.Int = randomInt(rand) - m.Rest = m.Array[:] - return reflect.ValueOf(m) -} - -func TestMarshalUnmarshal(t *testing.T) { - rand := rand.New(rand.NewSource(0)) - iface := &msgAllTypes{} - ty := reflect.ValueOf(iface).Type() - - n := 100 - if testing.Short() { - n = 5 - } - for j := 0; j < n; j++ { - v, ok := quick.Value(ty, rand) - if !ok { - t.Errorf("failed to create value") - break - } - - m1 := v.Elem().Interface() - m2 := iface - - marshaled := Marshal(m1) - if err := Unmarshal(marshaled, m2); err != nil { - t.Errorf("Unmarshal %#v: %s", m1, err) - break - } - - if !reflect.DeepEqual(v.Interface(), m2) { - t.Errorf("got: %#v\nwant:%#v\n%x", m2, m1, marshaled) - break - } - } -} - -func TestUnmarshalEmptyPacket(t *testing.T) { - var b []byte - var m channelRequestSuccessMsg - if err := Unmarshal(b, &m); err == nil { - t.Fatalf("unmarshal of empty slice succeeded") - } -} - -func TestUnmarshalUnexpectedPacket(t *testing.T) { - type S struct { - I uint32 `sshtype:"43"` - S string - B bool - } - - s := S{11, "hello", true} - packet := Marshal(s) - packet[0] = 42 - roundtrip := S{} - err := Unmarshal(packet, &roundtrip) - if err == nil { - t.Fatal("expected error, not nil") - } -} - -func TestMarshalPtr(t *testing.T) { - s := struct { - S string - }{"hello"} - - m1 := Marshal(s) - m2 := Marshal(&s) - if !bytes.Equal(m1, m2) { - t.Errorf("got %q, want %q for marshaled pointer", m2, m1) - } -} - -func TestBareMarshalUnmarshal(t *testing.T) { - type S struct { - I uint32 - S string - B bool - } - - s := S{42, "hello", true} - packet := Marshal(s) - roundtrip := S{} - Unmarshal(packet, &roundtrip) - - if !reflect.DeepEqual(s, roundtrip) { - t.Errorf("got %#v, want %#v", roundtrip, s) - } -} - -func TestBareMarshal(t *testing.T) { - type S2 struct { - I uint32 - } - s := S2{42} - packet := Marshal(s) - i, rest, ok := parseUint32(packet) - if len(rest) > 0 || !ok { - t.Errorf("parseInt(%q): parse error", packet) - } - if i != s.I { - t.Errorf("got %d, want %d", i, s.I) - } -} - -func TestUnmarshalShortKexInitPacket(t *testing.T) { - // This used to panic. - // Issue 11348 - packet := []byte{0x14, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0xff, 0xff, 0xff, 0xff} - kim := &kexInitMsg{} - if err := Unmarshal(packet, kim); err == nil { - t.Error("truncated packet unmarshaled without error") - } -} - -func randomBytes(out []byte, rand *rand.Rand) { - for i := 0; i < len(out); i++ { - out[i] = byte(rand.Int31()) - } -} - -func randomNameList(rand *rand.Rand) []string { - ret := make([]string, rand.Int31()&15) - for i := range ret { - s := make([]byte, 1+(rand.Int31()&15)) - for j := range s { - s[j] = 'a' + uint8(rand.Int31()&15) - } - ret[i] = string(s) - } - return ret -} - -func randomInt(rand *rand.Rand) *big.Int { - return new(big.Int).SetInt64(int64(int32(rand.Uint32()))) -} - -func (*kexInitMsg) Generate(rand *rand.Rand, size int) reflect.Value { - ki := &kexInitMsg{} - randomBytes(ki.Cookie[:], rand) - ki.KexAlgos = randomNameList(rand) - ki.ServerHostKeyAlgos = randomNameList(rand) - ki.CiphersClientServer = randomNameList(rand) - ki.CiphersServerClient = randomNameList(rand) - ki.MACsClientServer = randomNameList(rand) - ki.MACsServerClient = randomNameList(rand) - ki.CompressionClientServer = randomNameList(rand) - ki.CompressionServerClient = randomNameList(rand) - ki.LanguagesClientServer = randomNameList(rand) - ki.LanguagesServerClient = randomNameList(rand) - if rand.Int31()&1 == 1 { - ki.FirstKexFollows = true - } - return reflect.ValueOf(ki) -} - -func (*kexDHInitMsg) Generate(rand *rand.Rand, size int) reflect.Value { - dhi := &kexDHInitMsg{} - dhi.X = randomInt(rand) - return reflect.ValueOf(dhi) -} - -var ( - _kexInitMsg = new(kexInitMsg).Generate(rand.New(rand.NewSource(0)), 10).Elem().Interface() - _kexDHInitMsg = new(kexDHInitMsg).Generate(rand.New(rand.NewSource(0)), 10).Elem().Interface() - - _kexInit = Marshal(_kexInitMsg) - _kexDHInit = Marshal(_kexDHInitMsg) -) - -func BenchmarkMarshalKexInitMsg(b *testing.B) { - for i := 0; i < b.N; i++ { - Marshal(_kexInitMsg) - } -} - -func BenchmarkUnmarshalKexInitMsg(b *testing.B) { - m := new(kexInitMsg) - for i := 0; i < b.N; i++ { - Unmarshal(_kexInit, m) - } -} - -func BenchmarkMarshalKexDHInitMsg(b *testing.B) { - for i := 0; i < b.N; i++ { - Marshal(_kexDHInitMsg) - } -} - -func BenchmarkUnmarshalKexDHInitMsg(b *testing.B) { - m := new(kexDHInitMsg) - for i := 0; i < b.N; i++ { - Unmarshal(_kexDHInit, m) - } -} diff --git a/Godeps/_workspace/src/golang.org/x/crypto/ssh/mux_test.go b/Godeps/_workspace/src/golang.org/x/crypto/ssh/mux_test.go deleted file mode 100644 index 523038960..000000000 --- a/Godeps/_workspace/src/golang.org/x/crypto/ssh/mux_test.go +++ /dev/null @@ -1,525 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package ssh - -import ( - "io" - "io/ioutil" - "sync" - "testing" -) - -func muxPair() (*mux, *mux) { - a, b := memPipe() - - s := newMux(a) - c := newMux(b) - - return s, c -} - -// Returns both ends of a channel, and the mux for the the 2nd -// channel. -func channelPair(t *testing.T) (*channel, *channel, *mux) { - c, s := muxPair() - - res := make(chan *channel, 1) - go func() { - newCh, ok := <-s.incomingChannels - if !ok { - t.Fatalf("No incoming channel") - } - if newCh.ChannelType() != "chan" { - t.Fatalf("got type %q want chan", newCh.ChannelType()) - } - ch, _, err := newCh.Accept() - if err != nil { - t.Fatalf("Accept %v", err) - } - res <- ch.(*channel) - }() - - ch, err := c.openChannel("chan", nil) - if err != nil { - t.Fatalf("OpenChannel: %v", err) - } - - return <-res, ch, c -} - -// Test that stderr and stdout can be addressed from different -// goroutines. This is intended for use with the race detector. -func TestMuxChannelExtendedThreadSafety(t *testing.T) { - writer, reader, mux := channelPair(t) - defer writer.Close() - defer reader.Close() - defer mux.Close() - - var wr, rd sync.WaitGroup - magic := "hello world" - - wr.Add(2) - go func() { - io.WriteString(writer, magic) - wr.Done() - }() - go func() { - io.WriteString(writer.Stderr(), magic) - wr.Done() - }() - - rd.Add(2) - go func() { - c, err := ioutil.ReadAll(reader) - if string(c) != magic { - t.Fatalf("stdout read got %q, want %q (error %s)", c, magic, err) - } - rd.Done() - }() - go func() { - c, err := ioutil.ReadAll(reader.Stderr()) - if string(c) != magic { - t.Fatalf("stderr read got %q, want %q (error %s)", c, magic, err) - } - rd.Done() - }() - - wr.Wait() - writer.CloseWrite() - rd.Wait() -} - -func TestMuxReadWrite(t *testing.T) { - s, c, mux := channelPair(t) - defer s.Close() - defer c.Close() - defer mux.Close() - - magic := "hello world" - magicExt := "hello stderr" - go func() { - _, err := s.Write([]byte(magic)) - if err != nil { - t.Fatalf("Write: %v", err) - } - _, err = s.Extended(1).Write([]byte(magicExt)) - if err != nil { - t.Fatalf("Write: %v", err) - } - err = s.Close() - if err != nil { - t.Fatalf("Close: %v", err) - } - }() - - var buf [1024]byte - n, err := c.Read(buf[:]) - if err != nil { - t.Fatalf("server Read: %v", err) - } - got := string(buf[:n]) - if got != magic { - t.Fatalf("server: got %q want %q", got, magic) - } - - n, err = c.Extended(1).Read(buf[:]) - if err != nil { - t.Fatalf("server Read: %v", err) - } - - got = string(buf[:n]) - if got != magicExt { - t.Fatalf("server: got %q want %q", got, magic) - } -} - -func TestMuxChannelOverflow(t *testing.T) { - reader, writer, mux := channelPair(t) - defer reader.Close() - defer writer.Close() - defer mux.Close() - - wDone := make(chan int, 1) - go func() { - if _, err := writer.Write(make([]byte, channelWindowSize)); err != nil { - t.Errorf("could not fill window: %v", err) - } - writer.Write(make([]byte, 1)) - wDone <- 1 - }() - writer.remoteWin.waitWriterBlocked() - - // Send 1 byte. - packet := make([]byte, 1+4+4+1) - packet[0] = msgChannelData - marshalUint32(packet[1:], writer.remoteId) - marshalUint32(packet[5:], uint32(1)) - packet[9] = 42 - - if err := writer.mux.conn.writePacket(packet); err != nil { - t.Errorf("could not send packet") - } - if _, err := reader.SendRequest("hello", true, nil); err == nil { - t.Errorf("SendRequest succeeded.") - } - <-wDone -} - -func TestMuxChannelCloseWriteUnblock(t *testing.T) { - reader, writer, mux := channelPair(t) - defer reader.Close() - defer writer.Close() - defer mux.Close() - - wDone := make(chan int, 1) - go func() { - if _, err := writer.Write(make([]byte, channelWindowSize)); err != nil { - t.Errorf("could not fill window: %v", err) - } - if _, err := writer.Write(make([]byte, 1)); err != io.EOF { - t.Errorf("got %v, want EOF for unblock write", err) - } - wDone <- 1 - }() - - writer.remoteWin.waitWriterBlocked() - reader.Close() - <-wDone -} - -func TestMuxConnectionCloseWriteUnblock(t *testing.T) { - reader, writer, mux := channelPair(t) - defer reader.Close() - defer writer.Close() - defer mux.Close() - - wDone := make(chan int, 1) - go func() { - if _, err := writer.Write(make([]byte, channelWindowSize)); err != nil { - t.Errorf("could not fill window: %v", err) - } - if _, err := writer.Write(make([]byte, 1)); err != io.EOF { - t.Errorf("got %v, want EOF for unblock write", err) - } - wDone <- 1 - }() - - writer.remoteWin.waitWriterBlocked() - mux.Close() - <-wDone -} - -func TestMuxReject(t *testing.T) { - client, server := muxPair() - defer server.Close() - defer client.Close() - - go func() { - ch, ok := <-server.incomingChannels - if !ok { - t.Fatalf("Accept") - } - if ch.ChannelType() != "ch" || string(ch.ExtraData()) != "extra" { - t.Fatalf("unexpected channel: %q, %q", ch.ChannelType(), ch.ExtraData()) - } - ch.Reject(RejectionReason(42), "message") - }() - - ch, err := client.openChannel("ch", []byte("extra")) - if ch != nil { - t.Fatal("openChannel not rejected") - } - - ocf, ok := err.(*OpenChannelError) - if !ok { - t.Errorf("got %#v want *OpenChannelError", err) - } else if ocf.Reason != 42 || ocf.Message != "message" { - t.Errorf("got %#v, want {Reason: 42, Message: %q}", ocf, "message") - } - - want := "ssh: rejected: unknown reason 42 (message)" - if err.Error() != want { - t.Errorf("got %q, want %q", err.Error(), want) - } -} - -func TestMuxChannelRequest(t *testing.T) { - client, server, mux := channelPair(t) - defer server.Close() - defer client.Close() - defer mux.Close() - - var received int - var wg sync.WaitGroup - wg.Add(1) - go func() { - for r := range server.incomingRequests { - received++ - r.Reply(r.Type == "yes", nil) - } - wg.Done() - }() - _, err := client.SendRequest("yes", false, nil) - if err != nil { - t.Fatalf("SendRequest: %v", err) - } - ok, err := client.SendRequest("yes", true, nil) - if err != nil { - t.Fatalf("SendRequest: %v", err) - } - - if !ok { - t.Errorf("SendRequest(yes): %v", ok) - - } - - ok, err = client.SendRequest("no", true, nil) - if err != nil { - t.Fatalf("SendRequest: %v", err) - } - if ok { - t.Errorf("SendRequest(no): %v", ok) - - } - - client.Close() - wg.Wait() - - if received != 3 { - t.Errorf("got %d requests, want %d", received, 3) - } -} - -func TestMuxGlobalRequest(t *testing.T) { - clientMux, serverMux := muxPair() - defer serverMux.Close() - defer clientMux.Close() - - var seen bool - go func() { - for r := range serverMux.incomingRequests { - seen = seen || r.Type == "peek" - if r.WantReply { - err := r.Reply(r.Type == "yes", - append([]byte(r.Type), r.Payload...)) - if err != nil { - t.Errorf("AckRequest: %v", err) - } - } - } - }() - - _, _, err := clientMux.SendRequest("peek", false, nil) - if err != nil { - t.Errorf("SendRequest: %v", err) - } - - ok, data, err := clientMux.SendRequest("yes", true, []byte("a")) - if !ok || string(data) != "yesa" || err != nil { - t.Errorf("SendRequest(\"yes\", true, \"a\"): %v %v %v", - ok, data, err) - } - if ok, data, err := clientMux.SendRequest("yes", true, []byte("a")); !ok || string(data) != "yesa" || err != nil { - t.Errorf("SendRequest(\"yes\", true, \"a\"): %v %v %v", - ok, data, err) - } - - if ok, data, err := clientMux.SendRequest("no", true, []byte("a")); ok || string(data) != "noa" || err != nil { - t.Errorf("SendRequest(\"no\", true, \"a\"): %v %v %v", - ok, data, err) - } - - clientMux.Disconnect(0, "") - if !seen { - t.Errorf("never saw 'peek' request") - } -} - -func TestMuxGlobalRequestUnblock(t *testing.T) { - clientMux, serverMux := muxPair() - defer serverMux.Close() - defer clientMux.Close() - - result := make(chan error, 1) - go func() { - _, _, err := clientMux.SendRequest("hello", true, nil) - result <- err - }() - - <-serverMux.incomingRequests - serverMux.conn.Close() - err := <-result - - if err != io.EOF { - t.Errorf("want EOF, got %v", io.EOF) - } -} - -func TestMuxChannelRequestUnblock(t *testing.T) { - a, b, connB := channelPair(t) - defer a.Close() - defer b.Close() - defer connB.Close() - - result := make(chan error, 1) - go func() { - _, err := a.SendRequest("hello", true, nil) - result <- err - }() - - <-b.incomingRequests - connB.conn.Close() - err := <-result - - if err != io.EOF { - t.Errorf("want EOF, got %v", err) - } -} - -func TestMuxDisconnect(t *testing.T) { - a, b := muxPair() - defer a.Close() - defer b.Close() - - go func() { - for r := range b.incomingRequests { - r.Reply(true, nil) - } - }() - - a.Disconnect(42, "whatever") - ok, _, err := a.SendRequest("hello", true, nil) - if ok || err == nil { - t.Errorf("got reply after disconnecting") - } - err = b.Wait() - if d, ok := err.(*disconnectMsg); !ok || d.Reason != 42 { - t.Errorf("got %#v, want disconnectMsg{Reason:42}", err) - } -} - -func TestMuxCloseChannel(t *testing.T) { - r, w, mux := channelPair(t) - defer mux.Close() - defer r.Close() - defer w.Close() - - result := make(chan error, 1) - go func() { - var b [1024]byte - _, err := r.Read(b[:]) - result <- err - }() - if err := w.Close(); err != nil { - t.Errorf("w.Close: %v", err) - } - - if _, err := w.Write([]byte("hello")); err != io.EOF { - t.Errorf("got err %v, want io.EOF after Close", err) - } - - if err := <-result; err != io.EOF { - t.Errorf("got %v (%T), want io.EOF", err, err) - } -} - -func TestMuxCloseWriteChannel(t *testing.T) { - r, w, mux := channelPair(t) - defer mux.Close() - - result := make(chan error, 1) - go func() { - var b [1024]byte - _, err := r.Read(b[:]) - result <- err - }() - if err := w.CloseWrite(); err != nil { - t.Errorf("w.CloseWrite: %v", err) - } - - if _, err := w.Write([]byte("hello")); err != io.EOF { - t.Errorf("got err %v, want io.EOF after CloseWrite", err) - } - - if err := <-result; err != io.EOF { - t.Errorf("got %v (%T), want io.EOF", err, err) - } -} - -func TestMuxInvalidRecord(t *testing.T) { - a, b := muxPair() - defer a.Close() - defer b.Close() - - packet := make([]byte, 1+4+4+1) - packet[0] = msgChannelData - marshalUint32(packet[1:], 29348723 /* invalid channel id */) - marshalUint32(packet[5:], 1) - packet[9] = 42 - - a.conn.writePacket(packet) - go a.SendRequest("hello", false, nil) - // 'a' wrote an invalid packet, so 'b' has exited. - req, ok := <-b.incomingRequests - if ok { - t.Errorf("got request %#v after receiving invalid packet", req) - } -} - -func TestZeroWindowAdjust(t *testing.T) { - a, b, mux := channelPair(t) - defer a.Close() - defer b.Close() - defer mux.Close() - - go func() { - io.WriteString(a, "hello") - // bogus adjust. - a.sendMessage(windowAdjustMsg{}) - io.WriteString(a, "world") - a.Close() - }() - - want := "helloworld" - c, _ := ioutil.ReadAll(b) - if string(c) != want { - t.Errorf("got %q want %q", c, want) - } -} - -func TestMuxMaxPacketSize(t *testing.T) { - a, b, mux := channelPair(t) - defer a.Close() - defer b.Close() - defer mux.Close() - - large := make([]byte, a.maxRemotePayload+1) - packet := make([]byte, 1+4+4+1+len(large)) - packet[0] = msgChannelData - marshalUint32(packet[1:], a.remoteId) - marshalUint32(packet[5:], uint32(len(large))) - packet[9] = 42 - - if err := a.mux.conn.writePacket(packet); err != nil { - t.Errorf("could not send packet") - } - - go a.SendRequest("hello", false, nil) - - _, ok := <-b.incomingRequests - if ok { - t.Errorf("connection still alive after receiving large packet.") - } -} - -// Don't ship code with debug=true. -func TestDebug(t *testing.T) { - if debugMux { - t.Error("mux debug switched on") - } - if debugHandshake { - t.Error("handshake debug switched on") - } -} diff --git a/Godeps/_workspace/src/golang.org/x/crypto/ssh/session_test.go b/Godeps/_workspace/src/golang.org/x/crypto/ssh/session_test.go deleted file mode 100644 index f7f0f7642..000000000 --- a/Godeps/_workspace/src/golang.org/x/crypto/ssh/session_test.go +++ /dev/null @@ -1,774 +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 ssh - -// Session tests. - -import ( - "bytes" - crypto_rand "crypto/rand" - "errors" - "io" - "io/ioutil" - "math/rand" - "net" - "testing" - - "golang.org/x/crypto/ssh/terminal" -) - -type serverType func(Channel, <-chan *Request, *testing.T) - -// dial constructs a new test server and returns a *ClientConn. -func dial(handler serverType, t *testing.T) *Client { - c1, c2, err := netPipe() - if err != nil { - t.Fatalf("netPipe: %v", err) - } - - go func() { - defer c1.Close() - conf := ServerConfig{ - NoClientAuth: true, - } - conf.AddHostKey(testSigners["rsa"]) - - _, chans, reqs, err := NewServerConn(c1, &conf) - if err != nil { - t.Fatalf("Unable to handshake: %v", err) - } - go DiscardRequests(reqs) - - for newCh := range chans { - if newCh.ChannelType() != "session" { - newCh.Reject(UnknownChannelType, "unknown channel type") - continue - } - - ch, inReqs, err := newCh.Accept() - if err != nil { - t.Errorf("Accept: %v", err) - continue - } - go func() { - handler(ch, inReqs, t) - }() - } - }() - - config := &ClientConfig{ - User: "testuser", - } - - conn, chans, reqs, err := NewClientConn(c2, "", config) - if err != nil { - t.Fatalf("unable to dial remote side: %v", err) - } - - return NewClient(conn, chans, reqs) -} - -// Test a simple string is returned to session.Stdout. -func TestSessionShell(t *testing.T) { - conn := dial(shellHandler, t) - defer conn.Close() - session, err := conn.NewSession() - if err != nil { - t.Fatalf("Unable to request new session: %v", err) - } - defer session.Close() - stdout := new(bytes.Buffer) - session.Stdout = stdout - if err := session.Shell(); err != nil { - t.Fatalf("Unable to execute command: %s", err) - } - if err := session.Wait(); err != nil { - t.Fatalf("Remote command did not exit cleanly: %v", err) - } - actual := stdout.String() - if actual != "golang" { - t.Fatalf("Remote shell did not return expected string: expected=golang, actual=%s", actual) - } -} - -// TODO(dfc) add support for Std{in,err}Pipe when the Server supports it. - -// Test a simple string is returned via StdoutPipe. -func TestSessionStdoutPipe(t *testing.T) { - conn := dial(shellHandler, t) - defer conn.Close() - session, err := conn.NewSession() - if err != nil { - t.Fatalf("Unable to request new session: %v", err) - } - defer session.Close() - stdout, err := session.StdoutPipe() - if err != nil { - t.Fatalf("Unable to request StdoutPipe(): %v", err) - } - var buf bytes.Buffer - if err := session.Shell(); err != nil { - t.Fatalf("Unable to execute command: %v", err) - } - done := make(chan bool, 1) - go func() { - if _, err := io.Copy(&buf, stdout); err != nil { - t.Errorf("Copy of stdout failed: %v", err) - } - done <- true - }() - if err := session.Wait(); err != nil { - t.Fatalf("Remote command did not exit cleanly: %v", err) - } - <-done - actual := buf.String() - if actual != "golang" { - t.Fatalf("Remote shell did not return expected string: expected=golang, actual=%s", actual) - } -} - -// Test that a simple string is returned via the Output helper, -// and that stderr is discarded. -func TestSessionOutput(t *testing.T) { - conn := dial(fixedOutputHandler, t) - defer conn.Close() - session, err := conn.NewSession() - if err != nil { - t.Fatalf("Unable to request new session: %v", err) - } - defer session.Close() - - buf, err := session.Output("") // cmd is ignored by fixedOutputHandler - if err != nil { - t.Error("Remote command did not exit cleanly:", err) - } - w := "this-is-stdout." - g := string(buf) - if g != w { - t.Error("Remote command did not return expected string:") - t.Logf("want %q", w) - t.Logf("got %q", g) - } -} - -// Test that both stdout and stderr are returned -// via the CombinedOutput helper. -func TestSessionCombinedOutput(t *testing.T) { - conn := dial(fixedOutputHandler, t) - defer conn.Close() - session, err := conn.NewSession() - if err != nil { - t.Fatalf("Unable to request new session: %v", err) - } - defer session.Close() - - buf, err := session.CombinedOutput("") // cmd is ignored by fixedOutputHandler - if err != nil { - t.Error("Remote command did not exit cleanly:", err) - } - const stdout = "this-is-stdout." - const stderr = "this-is-stderr." - g := string(buf) - if g != stdout+stderr && g != stderr+stdout { - t.Error("Remote command did not return expected string:") - t.Logf("want %q, or %q", stdout+stderr, stderr+stdout) - t.Logf("got %q", g) - } -} - -// Test non-0 exit status is returned correctly. -func TestExitStatusNonZero(t *testing.T) { - conn := dial(exitStatusNonZeroHandler, t) - defer conn.Close() - session, err := conn.NewSession() - if err != nil { - t.Fatalf("Unable to request new session: %v", err) - } - defer session.Close() - if err := session.Shell(); err != nil { - t.Fatalf("Unable to execute command: %v", err) - } - err = session.Wait() - if err == nil { - t.Fatalf("expected command to fail but it didn't") - } - e, ok := err.(*ExitError) - if !ok { - t.Fatalf("expected *ExitError but got %T", err) - } - if e.ExitStatus() != 15 { - t.Fatalf("expected command to exit with 15 but got %v", e.ExitStatus()) - } -} - -// Test 0 exit status is returned correctly. -func TestExitStatusZero(t *testing.T) { - conn := dial(exitStatusZeroHandler, t) - defer conn.Close() - session, err := conn.NewSession() - if err != nil { - t.Fatalf("Unable to request new session: %v", err) - } - defer session.Close() - - if err := session.Shell(); err != nil { - t.Fatalf("Unable to execute command: %v", err) - } - err = session.Wait() - if err != nil { - t.Fatalf("expected nil but got %v", err) - } -} - -// Test exit signal and status are both returned correctly. -func TestExitSignalAndStatus(t *testing.T) { - conn := dial(exitSignalAndStatusHandler, t) - defer conn.Close() - session, err := conn.NewSession() - if err != nil { - t.Fatalf("Unable to request new session: %v", err) - } - defer session.Close() - if err := session.Shell(); err != nil { - t.Fatalf("Unable to execute command: %v", err) - } - err = session.Wait() - if err == nil { - t.Fatalf("expected command to fail but it didn't") - } - e, ok := err.(*ExitError) - if !ok { - t.Fatalf("expected *ExitError but got %T", err) - } - if e.Signal() != "TERM" || e.ExitStatus() != 15 { - t.Fatalf("expected command to exit with signal TERM and status 15 but got signal %s and status %v", e.Signal(), e.ExitStatus()) - } -} - -// Test exit signal and status are both returned correctly. -func TestKnownExitSignalOnly(t *testing.T) { - conn := dial(exitSignalHandler, t) - defer conn.Close() - session, err := conn.NewSession() - if err != nil { - t.Fatalf("Unable to request new session: %v", err) - } - defer session.Close() - if err := session.Shell(); err != nil { - t.Fatalf("Unable to execute command: %v", err) - } - err = session.Wait() - if err == nil { - t.Fatalf("expected command to fail but it didn't") - } - e, ok := err.(*ExitError) - if !ok { - t.Fatalf("expected *ExitError but got %T", err) - } - if e.Signal() != "TERM" || e.ExitStatus() != 143 { - t.Fatalf("expected command to exit with signal TERM and status 143 but got signal %s and status %v", e.Signal(), e.ExitStatus()) - } -} - -// Test exit signal and status are both returned correctly. -func TestUnknownExitSignal(t *testing.T) { - conn := dial(exitSignalUnknownHandler, t) - defer conn.Close() - session, err := conn.NewSession() - if err != nil { - t.Fatalf("Unable to request new session: %v", err) - } - defer session.Close() - if err := session.Shell(); err != nil { - t.Fatalf("Unable to execute command: %v", err) - } - err = session.Wait() - if err == nil { - t.Fatalf("expected command to fail but it didn't") - } - e, ok := err.(*ExitError) - if !ok { - t.Fatalf("expected *ExitError but got %T", err) - } - if e.Signal() != "SYS" || e.ExitStatus() != 128 { - t.Fatalf("expected command to exit with signal SYS and status 128 but got signal %s and status %v", e.Signal(), e.ExitStatus()) - } -} - -// Test WaitMsg is not returned if the channel closes abruptly. -func TestExitWithoutStatusOrSignal(t *testing.T) { - conn := dial(exitWithoutSignalOrStatus, t) - defer conn.Close() - session, err := conn.NewSession() - if err != nil { - t.Fatalf("Unable to request new session: %v", err) - } - defer session.Close() - if err := session.Shell(); err != nil { - t.Fatalf("Unable to execute command: %v", err) - } - err = session.Wait() - if err == nil { - t.Fatalf("expected command to fail but it didn't") - } - _, ok := err.(*ExitError) - if ok { - // you can't actually test for errors.errorString - // because it's not exported. - t.Fatalf("expected *errorString but got %T", err) - } -} - -// windowTestBytes is the number of bytes that we'll send to the SSH server. -const windowTestBytes = 16000 * 200 - -// TestServerWindow writes random data to the server. The server is expected to echo -// the same data back, which is compared against the original. -func TestServerWindow(t *testing.T) { - origBuf := bytes.NewBuffer(make([]byte, 0, windowTestBytes)) - io.CopyN(origBuf, crypto_rand.Reader, windowTestBytes) - origBytes := origBuf.Bytes() - - conn := dial(echoHandler, t) - defer conn.Close() - session, err := conn.NewSession() - if err != nil { - t.Fatal(err) - } - defer session.Close() - result := make(chan []byte) - - go func() { - defer close(result) - echoedBuf := bytes.NewBuffer(make([]byte, 0, windowTestBytes)) - serverStdout, err := session.StdoutPipe() - if err != nil { - t.Errorf("StdoutPipe failed: %v", err) - return - } - n, err := copyNRandomly("stdout", echoedBuf, serverStdout, windowTestBytes) - if err != nil && err != io.EOF { - t.Errorf("Read only %d bytes from server, expected %d: %v", n, windowTestBytes, err) - } - result <- echoedBuf.Bytes() - }() - - serverStdin, err := session.StdinPipe() - if err != nil { - t.Fatalf("StdinPipe failed: %v", err) - } - written, err := copyNRandomly("stdin", serverStdin, origBuf, windowTestBytes) - if err != nil { - t.Fatalf("failed to copy origBuf to serverStdin: %v", err) - } - if written != windowTestBytes { - t.Fatalf("Wrote only %d of %d bytes to server", written, windowTestBytes) - } - - echoedBytes := <-result - - if !bytes.Equal(origBytes, echoedBytes) { - t.Fatalf("Echoed buffer differed from original, orig %d, echoed %d", len(origBytes), len(echoedBytes)) - } -} - -// Verify the client can handle a keepalive packet from the server. -func TestClientHandlesKeepalives(t *testing.T) { - conn := dial(channelKeepaliveSender, t) - defer conn.Close() - session, err := conn.NewSession() - if err != nil { - t.Fatal(err) - } - defer session.Close() - if err := session.Shell(); err != nil { - t.Fatalf("Unable to execute command: %v", err) - } - err = session.Wait() - if err != nil { - t.Fatalf("expected nil but got: %v", err) - } -} - -type exitStatusMsg struct { - Status uint32 -} - -type exitSignalMsg struct { - Signal string - CoreDumped bool - Errmsg string - Lang string -} - -func handleTerminalRequests(in <-chan *Request) { - for req := range in { - ok := false - switch req.Type { - case "shell": - ok = true - if len(req.Payload) > 0 { - // We don't accept any commands, only the default shell. - ok = false - } - case "env": - ok = true - } - req.Reply(ok, nil) - } -} - -func newServerShell(ch Channel, in <-chan *Request, prompt string) *terminal.Terminal { - term := terminal.NewTerminal(ch, prompt) - go handleTerminalRequests(in) - return term -} - -func exitStatusZeroHandler(ch Channel, in <-chan *Request, t *testing.T) { - defer ch.Close() - // this string is returned to stdout - shell := newServerShell(ch, in, "> ") - readLine(shell, t) - sendStatus(0, ch, t) -} - -func exitStatusNonZeroHandler(ch Channel, in <-chan *Request, t *testing.T) { - defer ch.Close() - shell := newServerShell(ch, in, "> ") - readLine(shell, t) - sendStatus(15, ch, t) -} - -func exitSignalAndStatusHandler(ch Channel, in <-chan *Request, t *testing.T) { - defer ch.Close() - shell := newServerShell(ch, in, "> ") - readLine(shell, t) - sendStatus(15, ch, t) - sendSignal("TERM", ch, t) -} - -func exitSignalHandler(ch Channel, in <-chan *Request, t *testing.T) { - defer ch.Close() - shell := newServerShell(ch, in, "> ") - readLine(shell, t) - sendSignal("TERM", ch, t) -} - -func exitSignalUnknownHandler(ch Channel, in <-chan *Request, t *testing.T) { - defer ch.Close() - shell := newServerShell(ch, in, "> ") - readLine(shell, t) - sendSignal("SYS", ch, t) -} - -func exitWithoutSignalOrStatus(ch Channel, in <-chan *Request, t *testing.T) { - defer ch.Close() - shell := newServerShell(ch, in, "> ") - readLine(shell, t) -} - -func shellHandler(ch Channel, in <-chan *Request, t *testing.T) { - defer ch.Close() - // this string is returned to stdout - shell := newServerShell(ch, in, "golang") - readLine(shell, t) - sendStatus(0, ch, t) -} - -// Ignores the command, writes fixed strings to stderr and stdout. -// Strings are "this-is-stdout." and "this-is-stderr.". -func fixedOutputHandler(ch Channel, in <-chan *Request, t *testing.T) { - defer ch.Close() - _, err := ch.Read(nil) - - req, ok := <-in - if !ok { - t.Fatalf("error: expected channel request, got: %#v", err) - return - } - - // ignore request, always send some text - req.Reply(true, nil) - - _, err = io.WriteString(ch, "this-is-stdout.") - if err != nil { - t.Fatalf("error writing on server: %v", err) - } - _, err = io.WriteString(ch.Stderr(), "this-is-stderr.") - if err != nil { - t.Fatalf("error writing on server: %v", err) - } - sendStatus(0, ch, t) -} - -func readLine(shell *terminal.Terminal, t *testing.T) { - if _, err := shell.ReadLine(); err != nil && err != io.EOF { - t.Errorf("unable to read line: %v", err) - } -} - -func sendStatus(status uint32, ch Channel, t *testing.T) { - msg := exitStatusMsg{ - Status: status, - } - if _, err := ch.SendRequest("exit-status", false, Marshal(&msg)); err != nil { - t.Errorf("unable to send status: %v", err) - } -} - -func sendSignal(signal string, ch Channel, t *testing.T) { - sig := exitSignalMsg{ - Signal: signal, - CoreDumped: false, - Errmsg: "Process terminated", - Lang: "en-GB-oed", - } - if _, err := ch.SendRequest("exit-signal", false, Marshal(&sig)); err != nil { - t.Errorf("unable to send signal: %v", err) - } -} - -func discardHandler(ch Channel, t *testing.T) { - defer ch.Close() - io.Copy(ioutil.Discard, ch) -} - -func echoHandler(ch Channel, in <-chan *Request, t *testing.T) { - defer ch.Close() - if n, err := copyNRandomly("echohandler", ch, ch, windowTestBytes); err != nil { - t.Errorf("short write, wrote %d, expected %d: %v ", n, windowTestBytes, err) - } -} - -// copyNRandomly copies n bytes from src to dst. It uses a variable, and random, -// buffer size to exercise more code paths. -func copyNRandomly(title string, dst io.Writer, src io.Reader, n int) (int, error) { - var ( - buf = make([]byte, 32*1024) - written int - remaining = n - ) - for remaining > 0 { - l := rand.Intn(1 << 15) - if remaining < l { - l = remaining - } - nr, er := src.Read(buf[:l]) - nw, ew := dst.Write(buf[:nr]) - remaining -= nw - written += nw - if ew != nil { - return written, ew - } - if nr != nw { - return written, io.ErrShortWrite - } - if er != nil && er != io.EOF { - return written, er - } - } - return written, nil -} - -func channelKeepaliveSender(ch Channel, in <-chan *Request, t *testing.T) { - defer ch.Close() - shell := newServerShell(ch, in, "> ") - readLine(shell, t) - if _, err := ch.SendRequest("keepalive@openssh.com", true, nil); err != nil { - t.Errorf("unable to send channel keepalive request: %v", err) - } - sendStatus(0, ch, t) -} - -func TestClientWriteEOF(t *testing.T) { - conn := dial(simpleEchoHandler, t) - defer conn.Close() - - session, err := conn.NewSession() - if err != nil { - t.Fatal(err) - } - defer session.Close() - stdin, err := session.StdinPipe() - if err != nil { - t.Fatalf("StdinPipe failed: %v", err) - } - stdout, err := session.StdoutPipe() - if err != nil { - t.Fatalf("StdoutPipe failed: %v", err) - } - - data := []byte(`0000`) - _, err = stdin.Write(data) - if err != nil { - t.Fatalf("Write failed: %v", err) - } - stdin.Close() - - res, err := ioutil.ReadAll(stdout) - if err != nil { - t.Fatalf("Read failed: %v", err) - } - - if !bytes.Equal(data, res) { - t.Fatalf("Read differed from write, wrote: %v, read: %v", data, res) - } -} - -func simpleEchoHandler(ch Channel, in <-chan *Request, t *testing.T) { - defer ch.Close() - data, err := ioutil.ReadAll(ch) - if err != nil { - t.Errorf("handler read error: %v", err) - } - _, err = ch.Write(data) - if err != nil { - t.Errorf("handler write error: %v", err) - } -} - -func TestSessionID(t *testing.T) { - c1, c2, err := netPipe() - if err != nil { - t.Fatalf("netPipe: %v", err) - } - defer c1.Close() - defer c2.Close() - - serverID := make(chan []byte, 1) - clientID := make(chan []byte, 1) - - serverConf := &ServerConfig{ - NoClientAuth: true, - } - serverConf.AddHostKey(testSigners["ecdsa"]) - clientConf := &ClientConfig{ - User: "user", - } - - go func() { - conn, chans, reqs, err := NewServerConn(c1, serverConf) - if err != nil { - t.Fatalf("server handshake: %v", err) - } - serverID <- conn.SessionID() - go DiscardRequests(reqs) - for ch := range chans { - ch.Reject(Prohibited, "") - } - }() - - go func() { - conn, chans, reqs, err := NewClientConn(c2, "", clientConf) - if err != nil { - t.Fatalf("client handshake: %v", err) - } - clientID <- conn.SessionID() - go DiscardRequests(reqs) - for ch := range chans { - ch.Reject(Prohibited, "") - } - }() - - s := <-serverID - c := <-clientID - if bytes.Compare(s, c) != 0 { - t.Errorf("server session ID (%x) != client session ID (%x)", s, c) - } else if len(s) == 0 { - t.Errorf("client and server SessionID were empty.") - } -} - -type noReadConn struct { - readSeen bool - net.Conn -} - -func (c *noReadConn) Close() error { - return nil -} - -func (c *noReadConn) Read(b []byte) (int, error) { - c.readSeen = true - return 0, errors.New("noReadConn error") -} - -func TestInvalidServerConfiguration(t *testing.T) { - c1, c2, err := netPipe() - if err != nil { - t.Fatalf("netPipe: %v", err) - } - defer c1.Close() - defer c2.Close() - - serveConn := noReadConn{Conn: c1} - serverConf := &ServerConfig{} - - NewServerConn(&serveConn, serverConf) - if serveConn.readSeen { - t.Fatalf("NewServerConn attempted to Read() from Conn while configuration is missing host key") - } - - serverConf.AddHostKey(testSigners["ecdsa"]) - - NewServerConn(&serveConn, serverConf) - if serveConn.readSeen { - t.Fatalf("NewServerConn attempted to Read() from Conn while configuration is missing authentication method") - } -} - -func TestHostKeyAlgorithms(t *testing.T) { - serverConf := &ServerConfig{ - NoClientAuth: true, - } - serverConf.AddHostKey(testSigners["rsa"]) - serverConf.AddHostKey(testSigners["ecdsa"]) - - connect := func(clientConf *ClientConfig, want string) { - var alg string - clientConf.HostKeyCallback = func(h string, a net.Addr, key PublicKey) error { - alg = key.Type() - return nil - } - c1, c2, err := netPipe() - if err != nil { - t.Fatalf("netPipe: %v", err) - } - defer c1.Close() - defer c2.Close() - - go NewServerConn(c1, serverConf) - _, _, _, err = NewClientConn(c2, "", clientConf) - if err != nil { - t.Fatalf("NewClientConn: %v", err) - } - if alg != want { - t.Errorf("selected key algorithm %s, want %s", alg, want) - } - } - - // By default, we get the preferred algorithm, which is ECDSA 256. - - clientConf := &ClientConfig{} - connect(clientConf, KeyAlgoECDSA256) - - // Client asks for RSA explicitly. - clientConf.HostKeyAlgorithms = []string{KeyAlgoRSA} - connect(clientConf, KeyAlgoRSA) - - c1, c2, err := netPipe() - if err != nil { - t.Fatalf("netPipe: %v", err) - } - defer c1.Close() - defer c2.Close() - - go NewServerConn(c1, serverConf) - clientConf.HostKeyAlgorithms = []string{"nonexistent-hostkey-algo"} - _, _, _, err = NewClientConn(c2, "", clientConf) - if err == nil { - t.Fatal("succeeded connecting with unknown hostkey algorithm") - } -} diff --git a/Godeps/_workspace/src/golang.org/x/crypto/ssh/tcpip_test.go b/Godeps/_workspace/src/golang.org/x/crypto/ssh/tcpip_test.go deleted file mode 100644 index f1265cb49..000000000 --- a/Godeps/_workspace/src/golang.org/x/crypto/ssh/tcpip_test.go +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright 2014 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 ssh - -import ( - "testing" -) - -func TestAutoPortListenBroken(t *testing.T) { - broken := "SSH-2.0-OpenSSH_5.9hh11" - works := "SSH-2.0-OpenSSH_6.1" - if !isBrokenOpenSSHVersion(broken) { - t.Errorf("version %q not marked as broken", broken) - } - if isBrokenOpenSSHVersion(works) { - t.Errorf("version %q marked as broken", works) - } -} diff --git a/Godeps/_workspace/src/golang.org/x/crypto/ssh/terminal/terminal_test.go b/Godeps/_workspace/src/golang.org/x/crypto/ssh/terminal/terminal_test.go deleted file mode 100644 index a663fe41b..000000000 --- a/Godeps/_workspace/src/golang.org/x/crypto/ssh/terminal/terminal_test.go +++ /dev/null @@ -1,269 +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 terminal - -import ( - "io" - "testing" -) - -type MockTerminal struct { - toSend []byte - bytesPerRead int - received []byte -} - -func (c *MockTerminal) Read(data []byte) (n int, err error) { - n = len(data) - if n == 0 { - return - } - if n > len(c.toSend) { - n = len(c.toSend) - } - if n == 0 { - return 0, io.EOF - } - if c.bytesPerRead > 0 && n > c.bytesPerRead { - n = c.bytesPerRead - } - copy(data, c.toSend[:n]) - c.toSend = c.toSend[n:] - return -} - -func (c *MockTerminal) Write(data []byte) (n int, err error) { - c.received = append(c.received, data...) - return len(data), nil -} - -func TestClose(t *testing.T) { - c := &MockTerminal{} - ss := NewTerminal(c, "> ") - line, err := ss.ReadLine() - if line != "" { - t.Errorf("Expected empty line but got: %s", line) - } - if err != io.EOF { - t.Errorf("Error should have been EOF but got: %s", err) - } -} - -var keyPressTests = []struct { - in string - line string - err error - throwAwayLines int -}{ - { - err: io.EOF, - }, - { - in: "\r", - line: "", - }, - { - in: "foo\r", - line: "foo", - }, - { - in: "a\x1b[Cb\r", // right - line: "ab", - }, - { - in: "a\x1b[Db\r", // left - line: "ba", - }, - { - in: "a\177b\r", // backspace - line: "b", - }, - { - in: "\x1b[A\r", // up - }, - { - in: "\x1b[B\r", // down - }, - { - in: "line\x1b[A\x1b[B\r", // up then down - line: "line", - }, - { - in: "line1\rline2\x1b[A\r", // recall previous line. - line: "line1", - throwAwayLines: 1, - }, - { - // recall two previous lines and append. - in: "line1\rline2\rline3\x1b[A\x1b[Axxx\r", - line: "line1xxx", - throwAwayLines: 2, - }, - { - // Ctrl-A to move to beginning of line followed by ^K to kill - // line. - in: "a b \001\013\r", - line: "", - }, - { - // Ctrl-A to move to beginning of line, Ctrl-E to move to end, - // finally ^K to kill nothing. - in: "a b \001\005\013\r", - line: "a b ", - }, - { - in: "\027\r", - line: "", - }, - { - in: "a\027\r", - line: "", - }, - { - in: "a \027\r", - line: "", - }, - { - in: "a b\027\r", - line: "a ", - }, - { - in: "a b \027\r", - line: "a ", - }, - { - in: "one two thr\x1b[D\027\r", - line: "one two r", - }, - { - in: "\013\r", - line: "", - }, - { - in: "a\013\r", - line: "a", - }, - { - in: "ab\x1b[D\013\r", - line: "a", - }, - { - in: "Ξεσκεπάζω\r", - line: "Ξεσκεπάζω", - }, - { - in: "£\r\x1b[A\177\r", // non-ASCII char, enter, up, backspace. - line: "", - throwAwayLines: 1, - }, - { - in: "£\r££\x1b[A\x1b[B\177\r", // non-ASCII char, enter, 2x non-ASCII, up, down, backspace, enter. - line: "£", - throwAwayLines: 1, - }, - { - // Ctrl-D at the end of the line should be ignored. - in: "a\004\r", - line: "a", - }, - { - // a, b, left, Ctrl-D should erase the b. - in: "ab\x1b[D\004\r", - line: "a", - }, - { - // a, b, c, d, left, left, ^U should erase to the beginning of - // the line. - in: "abcd\x1b[D\x1b[D\025\r", - line: "cd", - }, - { - // Bracketed paste mode: control sequences should be returned - // verbatim in paste mode. - in: "abc\x1b[200~de\177f\x1b[201~\177\r", - line: "abcde\177", - }, - { - // Enter in bracketed paste mode should still work. - in: "abc\x1b[200~d\refg\x1b[201~h\r", - line: "efgh", - throwAwayLines: 1, - }, - { - // Lines consisting entirely of pasted data should be indicated as such. - in: "\x1b[200~a\r", - line: "a", - err: ErrPasteIndicator, - }, -} - -func TestKeyPresses(t *testing.T) { - for i, test := range keyPressTests { - for j := 1; j < len(test.in); j++ { - c := &MockTerminal{ - toSend: []byte(test.in), - bytesPerRead: j, - } - ss := NewTerminal(c, "> ") - for k := 0; k < test.throwAwayLines; k++ { - _, err := ss.ReadLine() - if err != nil { - t.Errorf("Throwaway line %d from test %d resulted in error: %s", k, i, err) - } - } - line, err := ss.ReadLine() - if line != test.line { - t.Errorf("Line resulting from test %d (%d bytes per read) was '%s', expected '%s'", i, j, line, test.line) - break - } - if err != test.err { - t.Errorf("Error resulting from test %d (%d bytes per read) was '%v', expected '%v'", i, j, err, test.err) - break - } - } - } -} - -func TestPasswordNotSaved(t *testing.T) { - c := &MockTerminal{ - toSend: []byte("password\r\x1b[A\r"), - bytesPerRead: 1, - } - ss := NewTerminal(c, "> ") - pw, _ := ss.ReadPassword("> ") - if pw != "password" { - t.Fatalf("failed to read password, got %s", pw) - } - line, _ := ss.ReadLine() - if len(line) > 0 { - t.Fatalf("password was saved in history") - } -} - -var setSizeTests = []struct { - width, height int -}{ - {40, 13}, - {80, 24}, - {132, 43}, -} - -func TestTerminalSetSize(t *testing.T) { - for _, setSize := range setSizeTests { - c := &MockTerminal{ - toSend: []byte("password\r\x1b[A\r"), - bytesPerRead: 1, - } - ss := NewTerminal(c, "> ") - ss.SetSize(setSize.width, setSize.height) - pw, _ := ss.ReadPassword("Password: ") - if pw != "password" { - t.Fatalf("failed to read password, got %s", pw) - } - if string(c.received) != "Password: \r\n" { - t.Errorf("failed to set the temporary prompt expected %q, got %q", "Password: ", c.received) - } - } -} diff --git a/Godeps/_workspace/src/golang.org/x/crypto/ssh/test/agent_unix_test.go b/Godeps/_workspace/src/golang.org/x/crypto/ssh/test/agent_unix_test.go deleted file mode 100644 index f481253c9..000000000 --- a/Godeps/_workspace/src/golang.org/x/crypto/ssh/test/agent_unix_test.go +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2014 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. - -// +build darwin dragonfly freebsd linux netbsd openbsd - -package test - -import ( - "bytes" - "testing" - - "golang.org/x/crypto/ssh" - "golang.org/x/crypto/ssh/agent" -) - -func TestAgentForward(t *testing.T) { - server := newServer(t) - defer server.Shutdown() - conn := server.Dial(clientConfig()) - defer conn.Close() - - keyring := agent.NewKeyring() - if err := keyring.Add(agent.AddedKey{PrivateKey: testPrivateKeys["dsa"]}); err != nil { - t.Fatalf("Error adding key: %s", err) - } - if err := keyring.Add(agent.AddedKey{ - PrivateKey: testPrivateKeys["dsa"], - ConfirmBeforeUse: true, - LifetimeSecs: 3600, - }); err != nil { - t.Fatalf("Error adding key with constraints: %s", err) - } - pub := testPublicKeys["dsa"] - - sess, err := conn.NewSession() - if err != nil { - t.Fatalf("NewSession: %v", err) - } - if err := agent.RequestAgentForwarding(sess); err != nil { - t.Fatalf("RequestAgentForwarding: %v", err) - } - - if err := agent.ForwardToAgent(conn, keyring); err != nil { - t.Fatalf("SetupForwardKeyring: %v", err) - } - out, err := sess.CombinedOutput("ssh-add -L") - if err != nil { - t.Fatalf("running ssh-add: %v, out %s", err, out) - } - key, _, _, _, err := ssh.ParseAuthorizedKey(out) - if err != nil { - t.Fatalf("ParseAuthorizedKey(%q): %v", out, err) - } - - if !bytes.Equal(key.Marshal(), pub.Marshal()) { - t.Fatalf("got key %s, want %s", ssh.MarshalAuthorizedKey(key), ssh.MarshalAuthorizedKey(pub)) - } -} diff --git a/Godeps/_workspace/src/golang.org/x/crypto/ssh/test/cert_test.go b/Godeps/_workspace/src/golang.org/x/crypto/ssh/test/cert_test.go deleted file mode 100644 index 364790f17..000000000 --- a/Godeps/_workspace/src/golang.org/x/crypto/ssh/test/cert_test.go +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright 2014 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. - -// +build darwin dragonfly freebsd linux netbsd openbsd - -package test - -import ( - "crypto/rand" - "testing" - - "golang.org/x/crypto/ssh" -) - -func TestCertLogin(t *testing.T) { - s := newServer(t) - defer s.Shutdown() - - // Use a key different from the default. - clientKey := testSigners["dsa"] - caAuthKey := testSigners["ecdsa"] - cert := &ssh.Certificate{ - Key: clientKey.PublicKey(), - ValidPrincipals: []string{username()}, - CertType: ssh.UserCert, - ValidBefore: ssh.CertTimeInfinity, - } - if err := cert.SignCert(rand.Reader, caAuthKey); err != nil { - t.Fatalf("SetSignature: %v", err) - } - - certSigner, err := ssh.NewCertSigner(cert, clientKey) - if err != nil { - t.Fatalf("NewCertSigner: %v", err) - } - - conf := &ssh.ClientConfig{ - User: username(), - } - conf.Auth = append(conf.Auth, ssh.PublicKeys(certSigner)) - client, err := s.TryDial(conf) - if err != nil { - t.Fatalf("TryDial: %v", err) - } - client.Close() -} diff --git a/Godeps/_workspace/src/golang.org/x/crypto/ssh/test/forward_unix_test.go b/Godeps/_workspace/src/golang.org/x/crypto/ssh/test/forward_unix_test.go deleted file mode 100644 index 877a88cde..000000000 --- a/Godeps/_workspace/src/golang.org/x/crypto/ssh/test/forward_unix_test.go +++ /dev/null @@ -1,160 +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. - -// +build darwin dragonfly freebsd linux netbsd openbsd - -package test - -import ( - "bytes" - "io" - "io/ioutil" - "math/rand" - "net" - "testing" - "time" -) - -func TestPortForward(t *testing.T) { - server := newServer(t) - defer server.Shutdown() - conn := server.Dial(clientConfig()) - defer conn.Close() - - sshListener, err := conn.Listen("tcp", "localhost:0") - if err != nil { - t.Fatal(err) - } - - go func() { - sshConn, err := sshListener.Accept() - if err != nil { - t.Fatalf("listen.Accept failed: %v", err) - } - - _, err = io.Copy(sshConn, sshConn) - if err != nil && err != io.EOF { - t.Fatalf("ssh client copy: %v", err) - } - sshConn.Close() - }() - - forwardedAddr := sshListener.Addr().String() - tcpConn, err := net.Dial("tcp", forwardedAddr) - if err != nil { - t.Fatalf("TCP dial failed: %v", err) - } - - readChan := make(chan []byte) - go func() { - data, _ := ioutil.ReadAll(tcpConn) - readChan <- data - }() - - // Invent some data. - data := make([]byte, 100*1000) - for i := range data { - data[i] = byte(i % 255) - } - - var sent []byte - for len(sent) < 1000*1000 { - // Send random sized chunks - m := rand.Intn(len(data)) - n, err := tcpConn.Write(data[:m]) - if err != nil { - break - } - sent = append(sent, data[:n]...) - } - if err := tcpConn.(*net.TCPConn).CloseWrite(); err != nil { - t.Errorf("tcpConn.CloseWrite: %v", err) - } - - read := <-readChan - - if len(sent) != len(read) { - t.Fatalf("got %d bytes, want %d", len(read), len(sent)) - } - if bytes.Compare(sent, read) != 0 { - t.Fatalf("read back data does not match") - } - - if err := sshListener.Close(); err != nil { - t.Fatalf("sshListener.Close: %v", err) - } - - // Check that the forward disappeared. - tcpConn, err = net.Dial("tcp", forwardedAddr) - if err == nil { - tcpConn.Close() - t.Errorf("still listening to %s after closing", forwardedAddr) - } -} - -func TestAcceptClose(t *testing.T) { - server := newServer(t) - defer server.Shutdown() - conn := server.Dial(clientConfig()) - - sshListener, err := conn.Listen("tcp", "localhost:0") - if err != nil { - t.Fatal(err) - } - - quit := make(chan error, 1) - go func() { - for { - c, err := sshListener.Accept() - if err != nil { - quit <- err - break - } - c.Close() - } - }() - sshListener.Close() - - select { - case <-time.After(1 * time.Second): - t.Errorf("timeout: listener did not close.") - case err := <-quit: - t.Logf("quit as expected (error %v)", err) - } -} - -// Check that listeners exit if the underlying client transport dies. -func TestPortForwardConnectionClose(t *testing.T) { - server := newServer(t) - defer server.Shutdown() - conn := server.Dial(clientConfig()) - - sshListener, err := conn.Listen("tcp", "localhost:0") - if err != nil { - t.Fatal(err) - } - - quit := make(chan error, 1) - go func() { - for { - c, err := sshListener.Accept() - if err != nil { - quit <- err - break - } - c.Close() - } - }() - - // It would be even nicer if we closed the server side, but it - // is more involved as the fd for that side is dup()ed. - server.clientConn.Close() - - select { - case <-time.After(1 * time.Second): - t.Errorf("timeout: listener did not close.") - case err := <-quit: - t.Logf("quit as expected (error %v)", err) - } -} diff --git a/Godeps/_workspace/src/golang.org/x/crypto/ssh/test/session_test.go b/Godeps/_workspace/src/golang.org/x/crypto/ssh/test/session_test.go deleted file mode 100644 index c0e714ba9..000000000 --- a/Godeps/_workspace/src/golang.org/x/crypto/ssh/test/session_test.go +++ /dev/null @@ -1,340 +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. - -// +build !windows - -package test - -// Session functional tests. - -import ( - "bytes" - "errors" - "io" - "strings" - "testing" - - "golang.org/x/crypto/ssh" -) - -func TestRunCommandSuccess(t *testing.T) { - server := newServer(t) - defer server.Shutdown() - conn := server.Dial(clientConfig()) - defer conn.Close() - - session, err := conn.NewSession() - if err != nil { - t.Fatalf("session failed: %v", err) - } - defer session.Close() - err = session.Run("true") - if err != nil { - t.Fatalf("session failed: %v", err) - } -} - -func TestHostKeyCheck(t *testing.T) { - server := newServer(t) - defer server.Shutdown() - - conf := clientConfig() - hostDB := hostKeyDB() - conf.HostKeyCallback = hostDB.Check - - // change the keys. - hostDB.keys[ssh.KeyAlgoRSA][25]++ - hostDB.keys[ssh.KeyAlgoDSA][25]++ - hostDB.keys[ssh.KeyAlgoECDSA256][25]++ - - conn, err := server.TryDial(conf) - if err == nil { - conn.Close() - t.Fatalf("dial should have failed.") - } else if !strings.Contains(err.Error(), "host key mismatch") { - t.Fatalf("'host key mismatch' not found in %v", err) - } -} - -func TestRunCommandStdin(t *testing.T) { - server := newServer(t) - defer server.Shutdown() - conn := server.Dial(clientConfig()) - defer conn.Close() - - session, err := conn.NewSession() - if err != nil { - t.Fatalf("session failed: %v", err) - } - defer session.Close() - - r, w := io.Pipe() - defer r.Close() - defer w.Close() - session.Stdin = r - - err = session.Run("true") - if err != nil { - t.Fatalf("session failed: %v", err) - } -} - -func TestRunCommandStdinError(t *testing.T) { - server := newServer(t) - defer server.Shutdown() - conn := server.Dial(clientConfig()) - defer conn.Close() - - session, err := conn.NewSession() - if err != nil { - t.Fatalf("session failed: %v", err) - } - defer session.Close() - - r, w := io.Pipe() - defer r.Close() - session.Stdin = r - pipeErr := errors.New("closing write end of pipe") - w.CloseWithError(pipeErr) - - err = session.Run("true") - if err != pipeErr { - t.Fatalf("expected %v, found %v", pipeErr, err) - } -} - -func TestRunCommandFailed(t *testing.T) { - server := newServer(t) - defer server.Shutdown() - conn := server.Dial(clientConfig()) - defer conn.Close() - - session, err := conn.NewSession() - if err != nil { - t.Fatalf("session failed: %v", err) - } - defer session.Close() - err = session.Run(`bash -c "kill -9 $$"`) - if err == nil { - t.Fatalf("session succeeded: %v", err) - } -} - -func TestRunCommandWeClosed(t *testing.T) { - server := newServer(t) - defer server.Shutdown() - conn := server.Dial(clientConfig()) - defer conn.Close() - - session, err := conn.NewSession() - if err != nil { - t.Fatalf("session failed: %v", err) - } - err = session.Shell() - if err != nil { - t.Fatalf("shell failed: %v", err) - } - err = session.Close() - if err != nil { - t.Fatalf("shell failed: %v", err) - } -} - -func TestFuncLargeRead(t *testing.T) { - server := newServer(t) - defer server.Shutdown() - conn := server.Dial(clientConfig()) - defer conn.Close() - - session, err := conn.NewSession() - if err != nil { - t.Fatalf("unable to create new session: %s", err) - } - - stdout, err := session.StdoutPipe() - if err != nil { - t.Fatalf("unable to acquire stdout pipe: %s", err) - } - - err = session.Start("dd if=/dev/urandom bs=2048 count=1024") - if err != nil { - t.Fatalf("unable to execute remote command: %s", err) - } - - buf := new(bytes.Buffer) - n, err := io.Copy(buf, stdout) - if err != nil { - t.Fatalf("error reading from remote stdout: %s", err) - } - - if n != 2048*1024 { - t.Fatalf("Expected %d bytes but read only %d from remote command", 2048, n) - } -} - -func TestKeyChange(t *testing.T) { - server := newServer(t) - defer server.Shutdown() - conf := clientConfig() - hostDB := hostKeyDB() - conf.HostKeyCallback = hostDB.Check - conf.RekeyThreshold = 1024 - conn := server.Dial(conf) - defer conn.Close() - - for i := 0; i < 4; i++ { - session, err := conn.NewSession() - if err != nil { - t.Fatalf("unable to create new session: %s", err) - } - - stdout, err := session.StdoutPipe() - if err != nil { - t.Fatalf("unable to acquire stdout pipe: %s", err) - } - - err = session.Start("dd if=/dev/urandom bs=1024 count=1") - if err != nil { - t.Fatalf("unable to execute remote command: %s", err) - } - buf := new(bytes.Buffer) - n, err := io.Copy(buf, stdout) - if err != nil { - t.Fatalf("error reading from remote stdout: %s", err) - } - - want := int64(1024) - if n != want { - t.Fatalf("Expected %d bytes but read only %d from remote command", want, n) - } - } - - if changes := hostDB.checkCount; changes < 4 { - t.Errorf("got %d key changes, want 4", changes) - } -} - -func TestInvalidTerminalMode(t *testing.T) { - server := newServer(t) - defer server.Shutdown() - conn := server.Dial(clientConfig()) - defer conn.Close() - - session, err := conn.NewSession() - if err != nil { - t.Fatalf("session failed: %v", err) - } - defer session.Close() - - if err = session.RequestPty("vt100", 80, 40, ssh.TerminalModes{255: 1984}); err == nil { - t.Fatalf("req-pty failed: successful request with invalid mode") - } -} - -func TestValidTerminalMode(t *testing.T) { - server := newServer(t) - defer server.Shutdown() - conn := server.Dial(clientConfig()) - defer conn.Close() - - session, err := conn.NewSession() - if err != nil { - t.Fatalf("session failed: %v", err) - } - defer session.Close() - - stdout, err := session.StdoutPipe() - if err != nil { - t.Fatalf("unable to acquire stdout pipe: %s", err) - } - - stdin, err := session.StdinPipe() - if err != nil { - t.Fatalf("unable to acquire stdin pipe: %s", err) - } - - tm := ssh.TerminalModes{ssh.ECHO: 0} - if err = session.RequestPty("xterm", 80, 40, tm); err != nil { - t.Fatalf("req-pty failed: %s", err) - } - - err = session.Shell() - if err != nil { - t.Fatalf("session failed: %s", err) - } - - stdin.Write([]byte("stty -a && exit\n")) - - var buf bytes.Buffer - if _, err := io.Copy(&buf, stdout); err != nil { - t.Fatalf("reading failed: %s", err) - } - - if sttyOutput := buf.String(); !strings.Contains(sttyOutput, "-echo ") { - t.Fatalf("terminal mode failure: expected -echo in stty output, got %s", sttyOutput) - } -} - -func TestCiphers(t *testing.T) { - var config ssh.Config - config.SetDefaults() - cipherOrder := config.Ciphers - // This cipher will not be tested when commented out in cipher.go it will - // fallback to the next available as per line 292. - cipherOrder = append(cipherOrder, "aes128-cbc") - - for _, ciph := range cipherOrder { - server := newServer(t) - defer server.Shutdown() - conf := clientConfig() - conf.Ciphers = []string{ciph} - // Don't fail if sshd doesnt have the cipher. - conf.Ciphers = append(conf.Ciphers, cipherOrder...) - conn, err := server.TryDial(conf) - if err == nil { - conn.Close() - } else { - t.Fatalf("failed for cipher %q", ciph) - } - } -} - -func TestMACs(t *testing.T) { - var config ssh.Config - config.SetDefaults() - macOrder := config.MACs - - for _, mac := range macOrder { - server := newServer(t) - defer server.Shutdown() - conf := clientConfig() - conf.MACs = []string{mac} - // Don't fail if sshd doesnt have the MAC. - conf.MACs = append(conf.MACs, macOrder...) - if conn, err := server.TryDial(conf); err == nil { - conn.Close() - } else { - t.Fatalf("failed for MAC %q", mac) - } - } -} - -func TestKeyExchanges(t *testing.T) { - var config ssh.Config - config.SetDefaults() - kexOrder := config.KeyExchanges - for _, kex := range kexOrder { - server := newServer(t) - defer server.Shutdown() - conf := clientConfig() - // Don't fail if sshd doesnt have the kex. - conf.KeyExchanges = append([]string{kex}, kexOrder...) - conn, err := server.TryDial(conf) - if err == nil { - conn.Close() - } else { - t.Errorf("failed for kex %q", kex) - } - } -} diff --git a/Godeps/_workspace/src/golang.org/x/crypto/ssh/test/tcpip_test.go b/Godeps/_workspace/src/golang.org/x/crypto/ssh/test/tcpip_test.go deleted file mode 100644 index a2eb9358d..000000000 --- a/Godeps/_workspace/src/golang.org/x/crypto/ssh/test/tcpip_test.go +++ /dev/null @@ -1,46 +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. - -// +build !windows - -package test - -// direct-tcpip functional tests - -import ( - "io" - "net" - "testing" -) - -func TestDial(t *testing.T) { - server := newServer(t) - defer server.Shutdown() - sshConn := server.Dial(clientConfig()) - defer sshConn.Close() - - l, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - t.Fatalf("Listen: %v", err) - } - defer l.Close() - - go func() { - for { - c, err := l.Accept() - if err != nil { - break - } - - io.WriteString(c, c.RemoteAddr().String()) - c.Close() - } - }() - - conn, err := sshConn.Dial("tcp", l.Addr().String()) - if err != nil { - t.Fatalf("Dial: %v", err) - } - defer conn.Close() -} diff --git a/Godeps/_workspace/src/golang.org/x/crypto/ssh/test/test_unix_test.go b/Godeps/_workspace/src/golang.org/x/crypto/ssh/test/test_unix_test.go deleted file mode 100644 index f1fc50b2e..000000000 --- a/Godeps/_workspace/src/golang.org/x/crypto/ssh/test/test_unix_test.go +++ /dev/null @@ -1,261 +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. - -// +build darwin dragonfly freebsd linux netbsd openbsd plan9 - -package test - -// functional test harness for unix. - -import ( - "bytes" - "fmt" - "io/ioutil" - "log" - "net" - "os" - "os/exec" - "os/user" - "path/filepath" - "testing" - "text/template" - - "golang.org/x/crypto/ssh" - "golang.org/x/crypto/ssh/testdata" -) - -const sshd_config = ` -Protocol 2 -HostKey {{.Dir}}/id_rsa -HostKey {{.Dir}}/id_dsa -HostKey {{.Dir}}/id_ecdsa -Pidfile {{.Dir}}/sshd.pid -#UsePrivilegeSeparation no -KeyRegenerationInterval 3600 -ServerKeyBits 768 -SyslogFacility AUTH -LogLevel DEBUG2 -LoginGraceTime 120 -PermitRootLogin no -StrictModes no -RSAAuthentication yes -PubkeyAuthentication yes -AuthorizedKeysFile {{.Dir}}/id_user.pub -TrustedUserCAKeys {{.Dir}}/id_ecdsa.pub -IgnoreRhosts yes -RhostsRSAAuthentication no -HostbasedAuthentication no -` - -var configTmpl = template.Must(template.New("").Parse(sshd_config)) - -type server struct { - t *testing.T - cleanup func() // executed during Shutdown - configfile string - cmd *exec.Cmd - output bytes.Buffer // holds stderr from sshd process - - // Client half of the network connection. - clientConn net.Conn -} - -func username() string { - var username string - if user, err := user.Current(); err == nil { - username = user.Username - } else { - // user.Current() currently requires cgo. If an error is - // returned attempt to get the username from the environment. - log.Printf("user.Current: %v; falling back on $USER", err) - username = os.Getenv("USER") - } - if username == "" { - panic("Unable to get username") - } - return username -} - -type storedHostKey struct { - // keys map from an algorithm string to binary key data. - keys map[string][]byte - - // checkCount counts the Check calls. Used for testing - // rekeying. - checkCount int -} - -func (k *storedHostKey) Add(key ssh.PublicKey) { - if k.keys == nil { - k.keys = map[string][]byte{} - } - k.keys[key.Type()] = key.Marshal() -} - -func (k *storedHostKey) Check(addr string, remote net.Addr, key ssh.PublicKey) error { - k.checkCount++ - algo := key.Type() - - if k.keys == nil || bytes.Compare(key.Marshal(), k.keys[algo]) != 0 { - return fmt.Errorf("host key mismatch. Got %q, want %q", key, k.keys[algo]) - } - return nil -} - -func hostKeyDB() *storedHostKey { - keyChecker := &storedHostKey{} - keyChecker.Add(testPublicKeys["ecdsa"]) - keyChecker.Add(testPublicKeys["rsa"]) - keyChecker.Add(testPublicKeys["dsa"]) - return keyChecker -} - -func clientConfig() *ssh.ClientConfig { - config := &ssh.ClientConfig{ - User: username(), - Auth: []ssh.AuthMethod{ - ssh.PublicKeys(testSigners["user"]), - }, - HostKeyCallback: hostKeyDB().Check, - } - return config -} - -// unixConnection creates two halves of a connected net.UnixConn. It -// is used for connecting the Go SSH client with sshd without opening -// ports. -func unixConnection() (*net.UnixConn, *net.UnixConn, error) { - dir, err := ioutil.TempDir("", "unixConnection") - if err != nil { - return nil, nil, err - } - defer os.Remove(dir) - - addr := filepath.Join(dir, "ssh") - listener, err := net.Listen("unix", addr) - if err != nil { - return nil, nil, err - } - defer listener.Close() - c1, err := net.Dial("unix", addr) - if err != nil { - return nil, nil, err - } - - c2, err := listener.Accept() - if err != nil { - c1.Close() - return nil, nil, err - } - - return c1.(*net.UnixConn), c2.(*net.UnixConn), nil -} - -func (s *server) TryDial(config *ssh.ClientConfig) (*ssh.Client, error) { - sshd, err := exec.LookPath("sshd") - if err != nil { - s.t.Skipf("skipping test: %v", err) - } - - c1, c2, err := unixConnection() - if err != nil { - s.t.Fatalf("unixConnection: %v", err) - } - - s.cmd = exec.Command(sshd, "-f", s.configfile, "-i", "-e") - f, err := c2.File() - if err != nil { - s.t.Fatalf("UnixConn.File: %v", err) - } - defer f.Close() - s.cmd.Stdin = f - s.cmd.Stdout = f - s.cmd.Stderr = &s.output - if err := s.cmd.Start(); err != nil { - s.t.Fail() - s.Shutdown() - s.t.Fatalf("s.cmd.Start: %v", err) - } - s.clientConn = c1 - conn, chans, reqs, err := ssh.NewClientConn(c1, "", config) - if err != nil { - return nil, err - } - return ssh.NewClient(conn, chans, reqs), nil -} - -func (s *server) Dial(config *ssh.ClientConfig) *ssh.Client { - conn, err := s.TryDial(config) - if err != nil { - s.t.Fail() - s.Shutdown() - s.t.Fatalf("ssh.Client: %v", err) - } - return conn -} - -func (s *server) Shutdown() { - if s.cmd != nil && s.cmd.Process != nil { - // Don't check for errors; if it fails it's most - // likely "os: process already finished", and we don't - // care about that. Use os.Interrupt, so child - // processes are killed too. - s.cmd.Process.Signal(os.Interrupt) - s.cmd.Wait() - } - if s.t.Failed() { - // log any output from sshd process - s.t.Logf("sshd: %s", s.output.String()) - } - s.cleanup() -} - -func writeFile(path string, contents []byte) { - f, err := os.OpenFile(path, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0600) - if err != nil { - panic(err) - } - defer f.Close() - if _, err := f.Write(contents); err != nil { - panic(err) - } -} - -// newServer returns a new mock ssh server. -func newServer(t *testing.T) *server { - if testing.Short() { - t.Skip("skipping test due to -short") - } - dir, err := ioutil.TempDir("", "sshtest") - if err != nil { - t.Fatal(err) - } - f, err := os.Create(filepath.Join(dir, "sshd_config")) - if err != nil { - t.Fatal(err) - } - err = configTmpl.Execute(f, map[string]string{ - "Dir": dir, - }) - if err != nil { - t.Fatal(err) - } - f.Close() - - for k, v := range testdata.PEMBytes { - filename := "id_" + k - writeFile(filepath.Join(dir, filename), v) - writeFile(filepath.Join(dir, filename+".pub"), ssh.MarshalAuthorizedKey(testPublicKeys[k])) - } - - return &server{ - t: t, - configfile: f.Name(), - cleanup: func() { - if err := os.RemoveAll(dir); err != nil { - t.Error(err) - } - }, - } -} diff --git a/Godeps/_workspace/src/golang.org/x/crypto/ssh/test/testdata_test.go b/Godeps/_workspace/src/golang.org/x/crypto/ssh/test/testdata_test.go deleted file mode 100644 index ae48c7516..000000000 --- a/Godeps/_workspace/src/golang.org/x/crypto/ssh/test/testdata_test.go +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright 2014 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. - -// IMPLEMENTOR NOTE: To avoid a package loop, this file is in three places: -// ssh/, ssh/agent, and ssh/test/. It should be kept in sync across all three -// instances. - -package test - -import ( - "crypto/rand" - "fmt" - - "golang.org/x/crypto/ssh" - "golang.org/x/crypto/ssh/testdata" -) - -var ( - testPrivateKeys map[string]interface{} - testSigners map[string]ssh.Signer - testPublicKeys map[string]ssh.PublicKey -) - -func init() { - var err error - - n := len(testdata.PEMBytes) - testPrivateKeys = make(map[string]interface{}, n) - testSigners = make(map[string]ssh.Signer, n) - testPublicKeys = make(map[string]ssh.PublicKey, n) - for t, k := range testdata.PEMBytes { - testPrivateKeys[t], err = ssh.ParseRawPrivateKey(k) - if err != nil { - panic(fmt.Sprintf("Unable to parse test key %s: %v", t, err)) - } - testSigners[t], err = ssh.NewSignerFromKey(testPrivateKeys[t]) - if err != nil { - panic(fmt.Sprintf("Unable to create signer for test key %s: %v", t, err)) - } - testPublicKeys[t] = testSigners[t].PublicKey() - } - - // Create a cert and sign it for use in tests. - testCert := &ssh.Certificate{ - Nonce: []byte{}, // To pass reflect.DeepEqual after marshal & parse, this must be non-nil - ValidPrincipals: []string{"gopher1", "gopher2"}, // increases test coverage - ValidAfter: 0, // unix epoch - ValidBefore: ssh.CertTimeInfinity, // The end of currently representable time. - Reserved: []byte{}, // To pass reflect.DeepEqual after marshal & parse, this must be non-nil - Key: testPublicKeys["ecdsa"], - SignatureKey: testPublicKeys["rsa"], - Permissions: ssh.Permissions{ - CriticalOptions: map[string]string{}, - Extensions: map[string]string{}, - }, - } - testCert.SignCert(rand.Reader, testSigners["rsa"]) - testPrivateKeys["cert"] = testPrivateKeys["ecdsa"] - testSigners["cert"], err = ssh.NewCertSigner(testCert, testSigners["ecdsa"]) - if err != nil { - panic(fmt.Sprintf("Unable to create certificate signer: %v", err)) - } -} diff --git a/Godeps/_workspace/src/golang.org/x/crypto/ssh/testdata/doc.go b/Godeps/_workspace/src/golang.org/x/crypto/ssh/testdata/doc.go deleted file mode 100644 index ae7bd8b89..000000000 --- a/Godeps/_workspace/src/golang.org/x/crypto/ssh/testdata/doc.go +++ /dev/null @@ -1,8 +0,0 @@ -// Copyright 2014 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. - -// This package contains test data shared between the various subpackages of -// the golang.org/x/crypto/ssh package. Under no circumstance should -// this data be used for production code. -package testdata diff --git a/Godeps/_workspace/src/golang.org/x/crypto/ssh/testdata/keys.go b/Godeps/_workspace/src/golang.org/x/crypto/ssh/testdata/keys.go deleted file mode 100644 index 5ff1c0e03..000000000 --- a/Godeps/_workspace/src/golang.org/x/crypto/ssh/testdata/keys.go +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright 2014 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 testdata - -var PEMBytes = map[string][]byte{ - "dsa": []byte(`-----BEGIN DSA PRIVATE KEY----- -MIIBuwIBAAKBgQD6PDSEyXiI9jfNs97WuM46MSDCYlOqWw80ajN16AohtBncs1YB -lHk//dQOvCYOsYaE+gNix2jtoRjwXhDsc25/IqQbU1ahb7mB8/rsaILRGIbA5WH3 -EgFtJmXFovDz3if6F6TzvhFpHgJRmLYVR8cqsezL3hEZOvvs2iH7MorkxwIVAJHD -nD82+lxh2fb4PMsIiaXudAsBAoGAQRf7Q/iaPRn43ZquUhd6WwvirqUj+tkIu6eV -2nZWYmXLlqFQKEy4Tejl7Wkyzr2OSYvbXLzo7TNxLKoWor6ips0phYPPMyXld14r -juhT24CrhOzuLMhDduMDi032wDIZG4Y+K7ElU8Oufn8Sj5Wge8r6ANmmVgmFfynr -FhdYCngCgYEA3ucGJ93/Mx4q4eKRDxcWD3QzWyqpbRVRRV1Vmih9Ha/qC994nJFz -DQIdjxDIT2Rk2AGzMqFEB68Zc3O+Wcsmz5eWWzEwFxaTwOGWTyDqsDRLm3fD+QYj -nOwuxb0Kce+gWI8voWcqC9cyRm09jGzu2Ab3Bhtpg8JJ8L7gS3MRZK4CFEx4UAfY -Fmsr0W6fHB9nhS4/UXM8 ------END DSA PRIVATE KEY----- -`), - "ecdsa": []byte(`-----BEGIN EC PRIVATE KEY----- -MHcCAQEEINGWx0zo6fhJ/0EAfrPzVFyFC9s18lBt3cRoEDhS3ARooAoGCCqGSM49 -AwEHoUQDQgAEi9Hdw6KvZcWxfg2IDhA7UkpDtzzt6ZqJXSsFdLd+Kx4S3Sx4cVO+ -6/ZOXRnPmNAlLUqjShUsUBBngG0u2fqEqA== ------END EC PRIVATE KEY----- -`), - "rsa": []byte(`-----BEGIN RSA PRIVATE KEY----- -MIIBOwIBAAJBALdGZxkXDAjsYk10ihwU6Id2KeILz1TAJuoq4tOgDWxEEGeTrcld -r/ZwVaFzjWzxaf6zQIJbfaSEAhqD5yo72+sCAwEAAQJBAK8PEVU23Wj8mV0QjwcJ -tZ4GcTUYQL7cF4+ezTCE9a1NrGnCP2RuQkHEKxuTVrxXt+6OF15/1/fuXnxKjmJC -nxkCIQDaXvPPBi0c7vAxGwNY9726x01/dNbHCE0CBtcotobxpwIhANbbQbh3JHVW -2haQh4fAG5mhesZKAGcxTyv4mQ7uMSQdAiAj+4dzMpJWdSzQ+qGHlHMIBvVHLkqB -y2VdEyF7DPCZewIhAI7GOI/6LDIFOvtPo6Bj2nNmyQ1HU6k/LRtNIXi4c9NJAiAr -rrxx26itVhJmcvoUhOjwuzSlP2bE5VHAvkGB352YBg== ------END RSA PRIVATE KEY----- -`), - "user": []byte(`-----BEGIN EC PRIVATE KEY----- -MHcCAQEEILYCAeq8f7V4vSSypRw7pxy8yz3V5W4qg8kSC3zJhqpQoAoGCCqGSM49 -AwEHoUQDQgAEYcO2xNKiRUYOLEHM7VYAp57HNyKbOdYtHD83Z4hzNPVC4tM5mdGD -PLL8IEwvYu2wq+lpXfGQnNMbzYf9gspG0w== ------END EC PRIVATE KEY----- -`), -} diff --git a/Godeps/_workspace/src/golang.org/x/crypto/ssh/testdata_test.go b/Godeps/_workspace/src/golang.org/x/crypto/ssh/testdata_test.go deleted file mode 100644 index f2828c1b5..000000000 --- a/Godeps/_workspace/src/golang.org/x/crypto/ssh/testdata_test.go +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright 2014 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. - -// IMPLEMENTOR NOTE: To avoid a package loop, this file is in three places: -// ssh/, ssh/agent, and ssh/test/. It should be kept in sync across all three -// instances. - -package ssh - -import ( - "crypto/rand" - "fmt" - - "golang.org/x/crypto/ssh/testdata" -) - -var ( - testPrivateKeys map[string]interface{} - testSigners map[string]Signer - testPublicKeys map[string]PublicKey -) - -func init() { - var err error - - n := len(testdata.PEMBytes) - testPrivateKeys = make(map[string]interface{}, n) - testSigners = make(map[string]Signer, n) - testPublicKeys = make(map[string]PublicKey, n) - for t, k := range testdata.PEMBytes { - testPrivateKeys[t], err = ParseRawPrivateKey(k) - if err != nil { - panic(fmt.Sprintf("Unable to parse test key %s: %v", t, err)) - } - testSigners[t], err = NewSignerFromKey(testPrivateKeys[t]) - if err != nil { - panic(fmt.Sprintf("Unable to create signer for test key %s: %v", t, err)) - } - testPublicKeys[t] = testSigners[t].PublicKey() - } - - // Create a cert and sign it for use in tests. - testCert := &Certificate{ - Nonce: []byte{}, // To pass reflect.DeepEqual after marshal & parse, this must be non-nil - ValidPrincipals: []string{"gopher1", "gopher2"}, // increases test coverage - ValidAfter: 0, // unix epoch - ValidBefore: CertTimeInfinity, // The end of currently representable time. - Reserved: []byte{}, // To pass reflect.DeepEqual after marshal & parse, this must be non-nil - Key: testPublicKeys["ecdsa"], - SignatureKey: testPublicKeys["rsa"], - Permissions: Permissions{ - CriticalOptions: map[string]string{}, - Extensions: map[string]string{}, - }, - } - testCert.SignCert(rand.Reader, testSigners["rsa"]) - testPrivateKeys["cert"] = testPrivateKeys["ecdsa"] - testSigners["cert"], err = NewCertSigner(testCert, testSigners["ecdsa"]) - if err != nil { - panic(fmt.Sprintf("Unable to create certificate signer: %v", err)) - } -} diff --git a/Godeps/_workspace/src/golang.org/x/crypto/ssh/transport_test.go b/Godeps/_workspace/src/golang.org/x/crypto/ssh/transport_test.go deleted file mode 100644 index 92d83abf9..000000000 --- a/Godeps/_workspace/src/golang.org/x/crypto/ssh/transport_test.go +++ /dev/null @@ -1,109 +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 ssh - -import ( - "bytes" - "crypto/rand" - "encoding/binary" - "strings" - "testing" -) - -func TestReadVersion(t *testing.T) { - longversion := strings.Repeat("SSH-2.0-bla", 50)[:253] - cases := map[string]string{ - "SSH-2.0-bla\r\n": "SSH-2.0-bla", - "SSH-2.0-bla\n": "SSH-2.0-bla", - longversion + "\r\n": longversion, - } - - for in, want := range cases { - result, err := readVersion(bytes.NewBufferString(in)) - if err != nil { - t.Errorf("readVersion(%q): %s", in, err) - } - got := string(result) - if got != want { - t.Errorf("got %q, want %q", got, want) - } - } -} - -func TestReadVersionError(t *testing.T) { - longversion := strings.Repeat("SSH-2.0-bla", 50)[:253] - cases := []string{ - longversion + "too-long\r\n", - } - for _, in := range cases { - if _, err := readVersion(bytes.NewBufferString(in)); err == nil { - t.Errorf("readVersion(%q) should have failed", in) - } - } -} - -func TestExchangeVersionsBasic(t *testing.T) { - v := "SSH-2.0-bla" - buf := bytes.NewBufferString(v + "\r\n") - them, err := exchangeVersions(buf, []byte("xyz")) - if err != nil { - t.Errorf("exchangeVersions: %v", err) - } - - if want := "SSH-2.0-bla"; string(them) != want { - t.Errorf("got %q want %q for our version", them, want) - } -} - -func TestExchangeVersions(t *testing.T) { - cases := []string{ - "not\x000allowed", - "not allowed\n", - } - for _, c := range cases { - buf := bytes.NewBufferString("SSH-2.0-bla\r\n") - if _, err := exchangeVersions(buf, []byte(c)); err == nil { - t.Errorf("exchangeVersions(%q): should have failed", c) - } - } -} - -type closerBuffer struct { - bytes.Buffer -} - -func (b *closerBuffer) Close() error { - return nil -} - -func TestTransportMaxPacketWrite(t *testing.T) { - buf := &closerBuffer{} - tr := newTransport(buf, rand.Reader, true) - huge := make([]byte, maxPacket+1) - err := tr.writePacket(huge) - if err == nil { - t.Errorf("transport accepted write for a huge packet.") - } -} - -func TestTransportMaxPacketReader(t *testing.T) { - var header [5]byte - huge := make([]byte, maxPacket+128) - binary.BigEndian.PutUint32(header[0:], uint32(len(huge))) - // padding. - header[4] = 0 - - buf := &closerBuffer{} - buf.Write(header[:]) - buf.Write(huge) - - tr := newTransport(buf, rand.Reader, true) - _, err := tr.readPacket() - if err == nil { - t.Errorf("transport succeeded reading huge packet.") - } else if !strings.Contains(err.Error(), "large") { - t.Errorf("got %q, should mention %q", err.Error(), "large") - } -} diff --git a/Godeps/_workspace/src/golang.org/x/net/context/context_test.go b/Godeps/_workspace/src/golang.org/x/net/context/context_test.go deleted file mode 100644 index e64afa64c..000000000 --- a/Godeps/_workspace/src/golang.org/x/net/context/context_test.go +++ /dev/null @@ -1,575 +0,0 @@ -// Copyright 2014 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 context - -import ( - "fmt" - "math/rand" - "runtime" - "strings" - "sync" - "testing" - "time" -) - -// otherContext is a Context that's not one of the types defined in context.go. -// This lets us test code paths that differ based on the underlying type of the -// Context. -type otherContext struct { - Context -} - -func TestBackground(t *testing.T) { - c := Background() - if c == nil { - t.Fatalf("Background returned nil") - } - select { - case x := <-c.Done(): - t.Errorf("<-c.Done() == %v want nothing (it should block)", x) - default: - } - if got, want := fmt.Sprint(c), "context.Background"; got != want { - t.Errorf("Background().String() = %q want %q", got, want) - } -} - -func TestTODO(t *testing.T) { - c := TODO() - if c == nil { - t.Fatalf("TODO returned nil") - } - select { - case x := <-c.Done(): - t.Errorf("<-c.Done() == %v want nothing (it should block)", x) - default: - } - if got, want := fmt.Sprint(c), "context.TODO"; got != want { - t.Errorf("TODO().String() = %q want %q", got, want) - } -} - -func TestWithCancel(t *testing.T) { - c1, cancel := WithCancel(Background()) - - if got, want := fmt.Sprint(c1), "context.Background.WithCancel"; got != want { - t.Errorf("c1.String() = %q want %q", got, want) - } - - o := otherContext{c1} - c2, _ := WithCancel(o) - contexts := []Context{c1, o, c2} - - for i, c := range contexts { - if d := c.Done(); d == nil { - t.Errorf("c[%d].Done() == %v want non-nil", i, d) - } - if e := c.Err(); e != nil { - t.Errorf("c[%d].Err() == %v want nil", i, e) - } - - select { - case x := <-c.Done(): - t.Errorf("<-c.Done() == %v want nothing (it should block)", x) - default: - } - } - - cancel() - time.Sleep(100 * time.Millisecond) // let cancelation propagate - - for i, c := range contexts { - select { - case <-c.Done(): - default: - t.Errorf("<-c[%d].Done() blocked, but shouldn't have", i) - } - if e := c.Err(); e != Canceled { - t.Errorf("c[%d].Err() == %v want %v", i, e, Canceled) - } - } -} - -func TestParentFinishesChild(t *testing.T) { - // Context tree: - // parent -> cancelChild - // parent -> valueChild -> timerChild - parent, cancel := WithCancel(Background()) - cancelChild, stop := WithCancel(parent) - defer stop() - valueChild := WithValue(parent, "key", "value") - timerChild, stop := WithTimeout(valueChild, 10000*time.Hour) - defer stop() - - select { - case x := <-parent.Done(): - t.Errorf("<-parent.Done() == %v want nothing (it should block)", x) - case x := <-cancelChild.Done(): - t.Errorf("<-cancelChild.Done() == %v want nothing (it should block)", x) - case x := <-timerChild.Done(): - t.Errorf("<-timerChild.Done() == %v want nothing (it should block)", x) - case x := <-valueChild.Done(): - t.Errorf("<-valueChild.Done() == %v want nothing (it should block)", x) - default: - } - - // The parent's children should contain the two cancelable children. - pc := parent.(*cancelCtx) - cc := cancelChild.(*cancelCtx) - tc := timerChild.(*timerCtx) - pc.mu.Lock() - if len(pc.children) != 2 || !pc.children[cc] || !pc.children[tc] { - t.Errorf("bad linkage: pc.children = %v, want %v and %v", - pc.children, cc, tc) - } - pc.mu.Unlock() - - if p, ok := parentCancelCtx(cc.Context); !ok || p != pc { - t.Errorf("bad linkage: parentCancelCtx(cancelChild.Context) = %v, %v want %v, true", p, ok, pc) - } - if p, ok := parentCancelCtx(tc.Context); !ok || p != pc { - t.Errorf("bad linkage: parentCancelCtx(timerChild.Context) = %v, %v want %v, true", p, ok, pc) - } - - cancel() - - pc.mu.Lock() - if len(pc.children) != 0 { - t.Errorf("pc.cancel didn't clear pc.children = %v", pc.children) - } - pc.mu.Unlock() - - // parent and children should all be finished. - check := func(ctx Context, name string) { - select { - case <-ctx.Done(): - default: - t.Errorf("<-%s.Done() blocked, but shouldn't have", name) - } - if e := ctx.Err(); e != Canceled { - t.Errorf("%s.Err() == %v want %v", name, e, Canceled) - } - } - check(parent, "parent") - check(cancelChild, "cancelChild") - check(valueChild, "valueChild") - check(timerChild, "timerChild") - - // WithCancel should return a canceled context on a canceled parent. - precanceledChild := WithValue(parent, "key", "value") - select { - case <-precanceledChild.Done(): - default: - t.Errorf("<-precanceledChild.Done() blocked, but shouldn't have") - } - if e := precanceledChild.Err(); e != Canceled { - t.Errorf("precanceledChild.Err() == %v want %v", e, Canceled) - } -} - -func TestChildFinishesFirst(t *testing.T) { - cancelable, stop := WithCancel(Background()) - defer stop() - for _, parent := range []Context{Background(), cancelable} { - child, cancel := WithCancel(parent) - - select { - case x := <-parent.Done(): - t.Errorf("<-parent.Done() == %v want nothing (it should block)", x) - case x := <-child.Done(): - t.Errorf("<-child.Done() == %v want nothing (it should block)", x) - default: - } - - cc := child.(*cancelCtx) - pc, pcok := parent.(*cancelCtx) // pcok == false when parent == Background() - if p, ok := parentCancelCtx(cc.Context); ok != pcok || (ok && pc != p) { - t.Errorf("bad linkage: parentCancelCtx(cc.Context) = %v, %v want %v, %v", p, ok, pc, pcok) - } - - if pcok { - pc.mu.Lock() - if len(pc.children) != 1 || !pc.children[cc] { - t.Errorf("bad linkage: pc.children = %v, cc = %v", pc.children, cc) - } - pc.mu.Unlock() - } - - cancel() - - if pcok { - pc.mu.Lock() - if len(pc.children) != 0 { - t.Errorf("child's cancel didn't remove self from pc.children = %v", pc.children) - } - pc.mu.Unlock() - } - - // child should be finished. - select { - case <-child.Done(): - default: - t.Errorf("<-child.Done() blocked, but shouldn't have") - } - if e := child.Err(); e != Canceled { - t.Errorf("child.Err() == %v want %v", e, Canceled) - } - - // parent should not be finished. - select { - case x := <-parent.Done(): - t.Errorf("<-parent.Done() == %v want nothing (it should block)", x) - default: - } - if e := parent.Err(); e != nil { - t.Errorf("parent.Err() == %v want nil", e) - } - } -} - -func testDeadline(c Context, wait time.Duration, t *testing.T) { - select { - case <-time.After(wait): - t.Fatalf("context should have timed out") - case <-c.Done(): - } - if e := c.Err(); e != DeadlineExceeded { - t.Errorf("c.Err() == %v want %v", e, DeadlineExceeded) - } -} - -func TestDeadline(t *testing.T) { - c, _ := WithDeadline(Background(), time.Now().Add(100*time.Millisecond)) - if got, prefix := fmt.Sprint(c), "context.Background.WithDeadline("; !strings.HasPrefix(got, prefix) { - t.Errorf("c.String() = %q want prefix %q", got, prefix) - } - testDeadline(c, 200*time.Millisecond, t) - - c, _ = WithDeadline(Background(), time.Now().Add(100*time.Millisecond)) - o := otherContext{c} - testDeadline(o, 200*time.Millisecond, t) - - c, _ = WithDeadline(Background(), time.Now().Add(100*time.Millisecond)) - o = otherContext{c} - c, _ = WithDeadline(o, time.Now().Add(300*time.Millisecond)) - testDeadline(c, 200*time.Millisecond, t) -} - -func TestTimeout(t *testing.T) { - c, _ := WithTimeout(Background(), 100*time.Millisecond) - if got, prefix := fmt.Sprint(c), "context.Background.WithDeadline("; !strings.HasPrefix(got, prefix) { - t.Errorf("c.String() = %q want prefix %q", got, prefix) - } - testDeadline(c, 200*time.Millisecond, t) - - c, _ = WithTimeout(Background(), 100*time.Millisecond) - o := otherContext{c} - testDeadline(o, 200*time.Millisecond, t) - - c, _ = WithTimeout(Background(), 100*time.Millisecond) - o = otherContext{c} - c, _ = WithTimeout(o, 300*time.Millisecond) - testDeadline(c, 200*time.Millisecond, t) -} - -func TestCanceledTimeout(t *testing.T) { - c, _ := WithTimeout(Background(), 200*time.Millisecond) - o := otherContext{c} - c, cancel := WithTimeout(o, 400*time.Millisecond) - cancel() - time.Sleep(100 * time.Millisecond) // let cancelation propagate - select { - case <-c.Done(): - default: - t.Errorf("<-c.Done() blocked, but shouldn't have") - } - if e := c.Err(); e != Canceled { - t.Errorf("c.Err() == %v want %v", e, Canceled) - } -} - -type key1 int -type key2 int - -var k1 = key1(1) -var k2 = key2(1) // same int as k1, different type -var k3 = key2(3) // same type as k2, different int - -func TestValues(t *testing.T) { - check := func(c Context, nm, v1, v2, v3 string) { - if v, ok := c.Value(k1).(string); ok == (len(v1) == 0) || v != v1 { - t.Errorf(`%s.Value(k1).(string) = %q, %t want %q, %t`, nm, v, ok, v1, len(v1) != 0) - } - if v, ok := c.Value(k2).(string); ok == (len(v2) == 0) || v != v2 { - t.Errorf(`%s.Value(k2).(string) = %q, %t want %q, %t`, nm, v, ok, v2, len(v2) != 0) - } - if v, ok := c.Value(k3).(string); ok == (len(v3) == 0) || v != v3 { - t.Errorf(`%s.Value(k3).(string) = %q, %t want %q, %t`, nm, v, ok, v3, len(v3) != 0) - } - } - - c0 := Background() - check(c0, "c0", "", "", "") - - c1 := WithValue(Background(), k1, "c1k1") - check(c1, "c1", "c1k1", "", "") - - if got, want := fmt.Sprint(c1), `context.Background.WithValue(1, "c1k1")`; got != want { - t.Errorf("c.String() = %q want %q", got, want) - } - - c2 := WithValue(c1, k2, "c2k2") - check(c2, "c2", "c1k1", "c2k2", "") - - c3 := WithValue(c2, k3, "c3k3") - check(c3, "c2", "c1k1", "c2k2", "c3k3") - - c4 := WithValue(c3, k1, nil) - check(c4, "c4", "", "c2k2", "c3k3") - - o0 := otherContext{Background()} - check(o0, "o0", "", "", "") - - o1 := otherContext{WithValue(Background(), k1, "c1k1")} - check(o1, "o1", "c1k1", "", "") - - o2 := WithValue(o1, k2, "o2k2") - check(o2, "o2", "c1k1", "o2k2", "") - - o3 := otherContext{c4} - check(o3, "o3", "", "c2k2", "c3k3") - - o4 := WithValue(o3, k3, nil) - check(o4, "o4", "", "c2k2", "") -} - -func TestAllocs(t *testing.T) { - bg := Background() - for _, test := range []struct { - desc string - f func() - limit float64 - gccgoLimit float64 - }{ - { - desc: "Background()", - f: func() { Background() }, - limit: 0, - gccgoLimit: 0, - }, - { - desc: fmt.Sprintf("WithValue(bg, %v, nil)", k1), - f: func() { - c := WithValue(bg, k1, nil) - c.Value(k1) - }, - limit: 3, - gccgoLimit: 3, - }, - { - desc: "WithTimeout(bg, 15*time.Millisecond)", - f: func() { - c, _ := WithTimeout(bg, 15*time.Millisecond) - <-c.Done() - }, - limit: 8, - gccgoLimit: 15, - }, - { - desc: "WithCancel(bg)", - f: func() { - c, cancel := WithCancel(bg) - cancel() - <-c.Done() - }, - limit: 5, - gccgoLimit: 8, - }, - { - desc: "WithTimeout(bg, 100*time.Millisecond)", - f: func() { - c, cancel := WithTimeout(bg, 100*time.Millisecond) - cancel() - <-c.Done() - }, - limit: 8, - gccgoLimit: 25, - }, - } { - limit := test.limit - if runtime.Compiler == "gccgo" { - // gccgo does not yet do escape analysis. - // TOOD(iant): Remove this when gccgo does do escape analysis. - limit = test.gccgoLimit - } - if n := testing.AllocsPerRun(100, test.f); n > limit { - t.Errorf("%s allocs = %f want %d", test.desc, n, int(limit)) - } - } -} - -func TestSimultaneousCancels(t *testing.T) { - root, cancel := WithCancel(Background()) - m := map[Context]CancelFunc{root: cancel} - q := []Context{root} - // Create a tree of contexts. - for len(q) != 0 && len(m) < 100 { - parent := q[0] - q = q[1:] - for i := 0; i < 4; i++ { - ctx, cancel := WithCancel(parent) - m[ctx] = cancel - q = append(q, ctx) - } - } - // Start all the cancels in a random order. - var wg sync.WaitGroup - wg.Add(len(m)) - for _, cancel := range m { - go func(cancel CancelFunc) { - cancel() - wg.Done() - }(cancel) - } - // Wait on all the contexts in a random order. - for ctx := range m { - select { - case <-ctx.Done(): - case <-time.After(1 * time.Second): - buf := make([]byte, 10<<10) - n := runtime.Stack(buf, true) - t.Fatalf("timed out waiting for <-ctx.Done(); stacks:\n%s", buf[:n]) - } - } - // Wait for all the cancel functions to return. - done := make(chan struct{}) - go func() { - wg.Wait() - close(done) - }() - select { - case <-done: - case <-time.After(1 * time.Second): - buf := make([]byte, 10<<10) - n := runtime.Stack(buf, true) - t.Fatalf("timed out waiting for cancel functions; stacks:\n%s", buf[:n]) - } -} - -func TestInterlockedCancels(t *testing.T) { - parent, cancelParent := WithCancel(Background()) - child, cancelChild := WithCancel(parent) - go func() { - parent.Done() - cancelChild() - }() - cancelParent() - select { - case <-child.Done(): - case <-time.After(1 * time.Second): - buf := make([]byte, 10<<10) - n := runtime.Stack(buf, true) - t.Fatalf("timed out waiting for child.Done(); stacks:\n%s", buf[:n]) - } -} - -func TestLayersCancel(t *testing.T) { - testLayers(t, time.Now().UnixNano(), false) -} - -func TestLayersTimeout(t *testing.T) { - testLayers(t, time.Now().UnixNano(), true) -} - -func testLayers(t *testing.T, seed int64, testTimeout bool) { - rand.Seed(seed) - errorf := func(format string, a ...interface{}) { - t.Errorf(fmt.Sprintf("seed=%d: %s", seed, format), a...) - } - const ( - timeout = 200 * time.Millisecond - minLayers = 30 - ) - type value int - var ( - vals []*value - cancels []CancelFunc - numTimers int - ctx = Background() - ) - for i := 0; i < minLayers || numTimers == 0 || len(cancels) == 0 || len(vals) == 0; i++ { - switch rand.Intn(3) { - case 0: - v := new(value) - ctx = WithValue(ctx, v, v) - vals = append(vals, v) - case 1: - var cancel CancelFunc - ctx, cancel = WithCancel(ctx) - cancels = append(cancels, cancel) - case 2: - var cancel CancelFunc - ctx, cancel = WithTimeout(ctx, timeout) - cancels = append(cancels, cancel) - numTimers++ - } - } - checkValues := func(when string) { - for _, key := range vals { - if val := ctx.Value(key).(*value); key != val { - errorf("%s: ctx.Value(%p) = %p want %p", when, key, val, key) - } - } - } - select { - case <-ctx.Done(): - errorf("ctx should not be canceled yet") - default: - } - if s, prefix := fmt.Sprint(ctx), "context.Background."; !strings.HasPrefix(s, prefix) { - t.Errorf("ctx.String() = %q want prefix %q", s, prefix) - } - t.Log(ctx) - checkValues("before cancel") - if testTimeout { - select { - case <-ctx.Done(): - case <-time.After(timeout + timeout/10): - errorf("ctx should have timed out") - } - checkValues("after timeout") - } else { - cancel := cancels[rand.Intn(len(cancels))] - cancel() - select { - case <-ctx.Done(): - default: - errorf("ctx should be canceled") - } - checkValues("after cancel") - } -} - -func TestCancelRemoves(t *testing.T) { - checkChildren := func(when string, ctx Context, want int) { - if got := len(ctx.(*cancelCtx).children); got != want { - t.Errorf("%s: context has %d children, want %d", when, got, want) - } - } - - ctx, _ := WithCancel(Background()) - checkChildren("after creation", ctx, 0) - _, cancel := WithCancel(ctx) - checkChildren("with WithCancel child ", ctx, 1) - cancel() - checkChildren("after cancelling WithCancel child", ctx, 0) - - ctx, _ = WithCancel(Background()) - checkChildren("after creation", ctx, 0) - _, cancel = WithTimeout(ctx, 60*time.Minute) - checkChildren("with WithTimeout child ", ctx, 1) - cancel() - checkChildren("after cancelling WithTimeout child", ctx, 0) -} diff --git a/Godeps/_workspace/src/golang.org/x/net/context/ctxhttp/ctxhttp_test.go b/Godeps/_workspace/src/golang.org/x/net/context/ctxhttp/ctxhttp_test.go deleted file mode 100644 index 47b53d7f1..000000000 --- a/Godeps/_workspace/src/golang.org/x/net/context/ctxhttp/ctxhttp_test.go +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright 2015 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 ctxhttp - -import ( - "io/ioutil" - "net/http" - "net/http/httptest" - "testing" - "time" - - "golang.org/x/net/context" -) - -const ( - requestDuration = 100 * time.Millisecond - requestBody = "ok" -) - -func TestNoTimeout(t *testing.T) { - ctx := context.Background() - resp, err := doRequest(ctx) - - if resp == nil || err != nil { - t.Fatalf("error received from client: %v %v", err, resp) - } -} -func TestCancel(t *testing.T) { - ctx, cancel := context.WithCancel(context.Background()) - go func() { - time.Sleep(requestDuration / 2) - cancel() - }() - - resp, err := doRequest(ctx) - - if resp != nil || err == nil { - t.Fatalf("expected error, didn't get one. resp: %v", resp) - } - if err != ctx.Err() { - t.Fatalf("expected error from context but got: %v", err) - } -} - -func TestCancelAfterRequest(t *testing.T) { - ctx, cancel := context.WithCancel(context.Background()) - - resp, err := doRequest(ctx) - - // Cancel before reading the body. - // Request.Body should still be readable after the context is canceled. - cancel() - - b, err := ioutil.ReadAll(resp.Body) - if err != nil || string(b) != requestBody { - t.Fatalf("could not read body: %q %v", b, err) - } -} - -func doRequest(ctx context.Context) (*http.Response, error) { - var okHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - time.Sleep(requestDuration) - w.Write([]byte(requestBody)) - }) - - serv := httptest.NewServer(okHandler) - defer serv.Close() - - return Get(ctx, nil, serv.URL) -} diff --git a/Godeps/_workspace/src/golang.org/x/net/context/withtimeout_test.go b/Godeps/_workspace/src/golang.org/x/net/context/withtimeout_test.go deleted file mode 100644 index a6754dc36..000000000 --- a/Godeps/_workspace/src/golang.org/x/net/context/withtimeout_test.go +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright 2014 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 context_test - -import ( - "fmt" - "time" - - "golang.org/x/net/context" -) - -func ExampleWithTimeout() { - // Pass a context with a timeout to tell a blocking function that it - // should abandon its work after the timeout elapses. - ctx, _ := context.WithTimeout(context.Background(), 100*time.Millisecond) - select { - case <-time.After(200 * time.Millisecond): - fmt.Println("overslept") - case <-ctx.Done(): - fmt.Println(ctx.Err()) // prints "context deadline exceeded" - } - // Output: - // context deadline exceeded -} diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/bitbucket/bitbucket.go b/Godeps/_workspace/src/golang.org/x/oauth2/bitbucket/bitbucket.go new file mode 100644 index 000000000..44af1f1a9 --- /dev/null +++ b/Godeps/_workspace/src/golang.org/x/oauth2/bitbucket/bitbucket.go @@ -0,0 +1,16 @@ +// Copyright 2015 The oauth2 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 bitbucket provides constants for using OAuth2 to access Bitbucket. +package bitbucket + +import ( + "golang.org/x/oauth2" +) + +// Endpoint is Bitbucket's OAuth 2.0 endpoint. +var Endpoint = oauth2.Endpoint{ + AuthURL: "https://bitbucket.org/site/oauth2/authorize", + TokenURL: "https://bitbucket.org/site/oauth2/access_token", +} diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/client_appengine.go b/Godeps/_workspace/src/golang.org/x/oauth2/client_appengine.go index 4a554cb9b..52f8d1dd6 100644 --- a/Godeps/_workspace/src/golang.org/x/oauth2/client_appengine.go +++ b/Godeps/_workspace/src/golang.org/x/oauth2/client_appengine.go @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -// +build appengine appenginevm +// +build appengine // App Engine hooks. diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/clientcredentials/clientcredentials_test.go b/Godeps/_workspace/src/golang.org/x/oauth2/clientcredentials/clientcredentials_test.go deleted file mode 100644 index ab319e082..000000000 --- a/Godeps/_workspace/src/golang.org/x/oauth2/clientcredentials/clientcredentials_test.go +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright 2014 The oauth2 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 clientcredentials - -import ( - "io/ioutil" - "net/http" - "net/http/httptest" - "testing" - - "golang.org/x/oauth2" -) - -func newConf(url string) *Config { - return &Config{ - ClientID: "CLIENT_ID", - ClientSecret: "CLIENT_SECRET", - Scopes: []string{"scope1", "scope2"}, - TokenURL: url + "/token", - } -} - -type mockTransport struct { - rt func(req *http.Request) (resp *http.Response, err error) -} - -func (t *mockTransport) RoundTrip(req *http.Request) (resp *http.Response, err error) { - return t.rt(req) -} - -func TestTokenRequest(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.URL.String() != "/token" { - t.Errorf("authenticate client request URL = %q; want %q", r.URL, "/token") - } - headerAuth := r.Header.Get("Authorization") - if headerAuth != "Basic Q0xJRU5UX0lEOkNMSUVOVF9TRUNSRVQ=" { - t.Errorf("Unexpected authorization header, %v is found.", headerAuth) - } - if got, want := r.Header.Get("Content-Type"), "application/x-www-form-urlencoded"; got != want { - t.Errorf("Content-Type header = %q; want %q", got, want) - } - body, err := ioutil.ReadAll(r.Body) - if err != nil { - r.Body.Close() - } - if err != nil { - t.Errorf("failed reading request body: %s.", err) - } - if string(body) != "client_id=CLIENT_ID&grant_type=client_credentials&scope=scope1+scope2" { - t.Errorf("payload = %q; want %q", string(body), "client_id=CLIENT_ID&grant_type=client_credentials&scope=scope1+scope2") - } - w.Header().Set("Content-Type", "application/x-www-form-urlencoded") - w.Write([]byte("access_token=90d64460d14870c08c81352a05dedd3465940a7c&token_type=bearer")) - })) - defer ts.Close() - conf := newConf(ts.URL) - tok, err := conf.Token(oauth2.NoContext) - if err != nil { - t.Error(err) - } - if !tok.Valid() { - t.Fatalf("token invalid. got: %#v", tok) - } - if tok.AccessToken != "90d64460d14870c08c81352a05dedd3465940a7c" { - t.Errorf("Access token = %q; want %q", tok.AccessToken, "90d64460d14870c08c81352a05dedd3465940a7c") - } - if tok.TokenType != "bearer" { - t.Errorf("token type = %q; want %q", tok.TokenType, "bearer") - } -} - -func TestTokenRefreshRequest(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.URL.String() == "/somethingelse" { - return - } - if r.URL.String() != "/token" { - t.Errorf("Unexpected token refresh request URL, %v is found.", r.URL) - } - headerContentType := r.Header.Get("Content-Type") - if headerContentType != "application/x-www-form-urlencoded" { - t.Errorf("Unexpected Content-Type header, %v is found.", headerContentType) - } - body, _ := ioutil.ReadAll(r.Body) - if string(body) != "client_id=CLIENT_ID&grant_type=client_credentials&scope=scope1+scope2" { - t.Errorf("Unexpected refresh token payload, %v is found.", string(body)) - } - })) - defer ts.Close() - conf := newConf(ts.URL) - c := conf.Client(oauth2.NoContext) - c.Get(ts.URL + "/somethingelse") -} diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/example_test.go b/Godeps/_workspace/src/golang.org/x/oauth2/example_test.go deleted file mode 100644 index 8be278855..000000000 --- a/Godeps/_workspace/src/golang.org/x/oauth2/example_test.go +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright 2014 The oauth2 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 oauth2_test - -import ( - "fmt" - "log" - - "golang.org/x/oauth2" -) - -func ExampleConfig() { - conf := &oauth2.Config{ - ClientID: "YOUR_CLIENT_ID", - ClientSecret: "YOUR_CLIENT_SECRET", - Scopes: []string{"SCOPE1", "SCOPE2"}, - Endpoint: oauth2.Endpoint{ - AuthURL: "https://provider.com/o/oauth2/auth", - TokenURL: "https://provider.com/o/oauth2/token", - }, - } - - // Redirect user to consent page to ask for permission - // for the scopes specified above. - url := conf.AuthCodeURL("state", oauth2.AccessTypeOffline) - fmt.Printf("Visit the URL for the auth dialog: %v", url) - - // Use the authorization code that is pushed to the redirect URL. - // NewTransportWithCode will do the handshake to retrieve - // an access token and initiate a Transport that is - // authorized and authenticated by the retrieved token. - var code string - if _, err := fmt.Scan(&code); err != nil { - log.Fatal(err) - } - tok, err := conf.Exchange(oauth2.NoContext, code) - if err != nil { - log.Fatal(err) - } - - client := conf.Client(oauth2.NoContext, tok) - client.Get("...") -} diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/google/appengine.go b/Godeps/_workspace/src/golang.org/x/oauth2/google/appengine.go index 65dc34731..855422154 100644 --- a/Godeps/_workspace/src/golang.org/x/oauth2/google/appengine.go +++ b/Godeps/_workspace/src/golang.org/x/oauth2/google/appengine.go @@ -14,6 +14,9 @@ import ( "golang.org/x/oauth2" ) +// Set at init time by appenginevm_hook.go. If true, we are on App Engine Managed VMs. +var appengineVM bool + // Set at init time by appengine_hook.go. If nil, we're not on App Engine. var appengineTokenFunc func(c context.Context, scopes ...string) (token string, expiry time.Time, err error) diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/google/appengine_hook.go b/Godeps/_workspace/src/golang.org/x/oauth2/google/appengine_hook.go index 2f9b15432..362766fdd 100644 --- a/Godeps/_workspace/src/golang.org/x/oauth2/google/appengine_hook.go +++ b/Godeps/_workspace/src/golang.org/x/oauth2/google/appengine_hook.go @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -// +build appengine appenginevm +// +build appengine package google diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/google/appenginevm_hook.go b/Godeps/_workspace/src/golang.org/x/oauth2/google/appenginevm_hook.go new file mode 100644 index 000000000..633611cc3 --- /dev/null +++ b/Godeps/_workspace/src/golang.org/x/oauth2/google/appenginevm_hook.go @@ -0,0 +1,14 @@ +// Copyright 2015 The oauth2 Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build appenginevm + +package google + +import "google.golang.org/appengine" + +func init() { + appengineVM = true + appengineTokenFunc = appengine.AccessToken +} diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/google/default.go b/Godeps/_workspace/src/golang.org/x/oauth2/google/default.go index 78f808985..66daeefd5 100644 --- a/Godeps/_workspace/src/golang.org/x/oauth2/google/default.go +++ b/Godeps/_workspace/src/golang.org/x/oauth2/google/default.go @@ -50,7 +50,8 @@ func DefaultClient(ctx context.Context, scope ...string) (*http.Client, error) { // On Windows, this is %APPDATA%/gcloud/application_default_credentials.json. // On other systems, $HOME/.config/gcloud/application_default_credentials.json. // 3. On Google App Engine it uses the appengine.AccessToken function. -// 4. On Google Compute Engine, it fetches credentials from the metadata server. +// 4. On Google Compute Engine and Google App Engine Managed VMs, it fetches +// credentials from the metadata server. // (In this final case any provided scopes are ignored.) // // For more details, see: @@ -84,7 +85,7 @@ func DefaultTokenSource(ctx context.Context, scope ...string) (oauth2.TokenSourc } // Third, if we're on Google App Engine use those credentials. - if appengineTokenFunc != nil { + if appengineTokenFunc != nil && !appengineVM { return AppEngineTokenSource(ctx, scope...), nil } diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/google/example_test.go b/Godeps/_workspace/src/golang.org/x/oauth2/google/example_test.go deleted file mode 100644 index 17262802a..000000000 --- a/Godeps/_workspace/src/golang.org/x/oauth2/google/example_test.go +++ /dev/null @@ -1,150 +0,0 @@ -// Copyright 2014 The oauth2 Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build appenginevm !appengine - -package google_test - -import ( - "fmt" - "io/ioutil" - "log" - "net/http" - - "golang.org/x/oauth2" - "golang.org/x/oauth2/google" - "golang.org/x/oauth2/jwt" - "google.golang.org/appengine" - "google.golang.org/appengine/urlfetch" -) - -func ExampleDefaultClient() { - client, err := google.DefaultClient(oauth2.NoContext, - "https://www.googleapis.com/auth/devstorage.full_control") - if err != nil { - log.Fatal(err) - } - client.Get("...") -} - -func Example_webServer() { - // Your credentials should be obtained from the Google - // Developer Console (https://console.developers.google.com). - conf := &oauth2.Config{ - ClientID: "YOUR_CLIENT_ID", - ClientSecret: "YOUR_CLIENT_SECRET", - RedirectURL: "YOUR_REDIRECT_URL", - Scopes: []string{ - "https://www.googleapis.com/auth/bigquery", - "https://www.googleapis.com/auth/blogger", - }, - Endpoint: google.Endpoint, - } - // Redirect user to Google's consent page to ask for permission - // for the scopes specified above. - url := conf.AuthCodeURL("state") - fmt.Printf("Visit the URL for the auth dialog: %v", url) - - // Handle the exchange code to initiate a transport. - tok, err := conf.Exchange(oauth2.NoContext, "authorization-code") - if err != nil { - log.Fatal(err) - } - client := conf.Client(oauth2.NoContext, tok) - client.Get("...") -} - -func ExampleJWTConfigFromJSON() { - // Your credentials should be obtained from the Google - // Developer Console (https://console.developers.google.com). - // Navigate to your project, then see the "Credentials" page - // under "APIs & Auth". - // To create a service account client, click "Create new Client ID", - // select "Service Account", and click "Create Client ID". A JSON - // key file will then be downloaded to your computer. - data, err := ioutil.ReadFile("/path/to/your-project-key.json") - if err != nil { - log.Fatal(err) - } - conf, err := google.JWTConfigFromJSON(data, "https://www.googleapis.com/auth/bigquery") - if err != nil { - log.Fatal(err) - } - // Initiate an http.Client. The following GET request will be - // authorized and authenticated on the behalf of - // your service account. - client := conf.Client(oauth2.NoContext) - client.Get("...") -} - -func ExampleSDKConfig() { - // The credentials will be obtained from the first account that - // has been authorized with `gcloud auth login`. - conf, err := google.NewSDKConfig("") - if err != nil { - log.Fatal(err) - } - // Initiate an http.Client. The following GET request will be - // authorized and authenticated on the behalf of the SDK user. - client := conf.Client(oauth2.NoContext) - client.Get("...") -} - -func Example_serviceAccount() { - // Your credentials should be obtained from the Google - // Developer Console (https://console.developers.google.com). - conf := &jwt.Config{ - Email: "xxx@developer.gserviceaccount.com", - // The contents of your RSA private key or your PEM file - // that contains a private key. - // If you have a p12 file instead, you - // can use `openssl` to export the private key into a pem file. - // - // $ openssl pkcs12 -in key.p12 -passin pass:notasecret -out key.pem -nodes - // - // The field only supports PEM containers with no passphrase. - // The openssl command will convert p12 keys to passphrase-less PEM containers. - PrivateKey: []byte("-----BEGIN RSA PRIVATE KEY-----..."), - Scopes: []string{ - "https://www.googleapis.com/auth/bigquery", - "https://www.googleapis.com/auth/blogger", - }, - TokenURL: google.JWTTokenURL, - // If you would like to impersonate a user, you can - // create a transport with a subject. The following GET - // request will be made on the behalf of user@example.com. - // Optional. - Subject: "user@example.com", - } - // Initiate an http.Client, the following GET request will be - // authorized and authenticated on the behalf of user@example.com. - client := conf.Client(oauth2.NoContext) - client.Get("...") -} - -func ExampleAppEngineTokenSource() { - var req *http.Request // from the ServeHTTP handler - ctx := appengine.NewContext(req) - client := &http.Client{ - Transport: &oauth2.Transport{ - Source: google.AppEngineTokenSource(ctx, "https://www.googleapis.com/auth/bigquery"), - Base: &urlfetch.Transport{ - Context: ctx, - }, - }, - } - client.Get("...") -} - -func ExampleComputeTokenSource() { - client := &http.Client{ - Transport: &oauth2.Transport{ - // Fetch from Google Compute Engine's metadata server to retrieve - // an access token for the provided account. - // If no account is specified, "default" is used. - Source: google.ComputeTokenSource(""), - }, - } - client.Get("...") -} diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/google/google_test.go b/Godeps/_workspace/src/golang.org/x/oauth2/google/google_test.go deleted file mode 100644 index 4cc01884b..000000000 --- a/Godeps/_workspace/src/golang.org/x/oauth2/google/google_test.go +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright 2015 The oauth2 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 google - -import ( - "strings" - "testing" -) - -var webJSONKey = []byte(` -{ - "web": { - "auth_uri": "https://google.com/o/oauth2/auth", - "client_secret": "3Oknc4jS_wA2r9i", - "token_uri": "https://google.com/o/oauth2/token", - "client_email": "222-nprqovg5k43uum874cs9osjt2koe97g8@developer.gserviceaccount.com", - "redirect_uris": ["https://www.example.com/oauth2callback"], - "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/222-nprqovg5k43uum874cs9osjt2koe97g8@developer.gserviceaccount.com", - "client_id": "222-nprqovg5k43uum874cs9osjt2koe97g8.apps.googleusercontent.com", - "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", - "javascript_origins": ["https://www.example.com"] - } -}`) - -var installedJSONKey = []byte(`{ - "installed": { - "client_id": "222-installed.apps.googleusercontent.com", - "redirect_uris": ["https://www.example.com/oauth2callback"] - } -}`) - -func TestConfigFromJSON(t *testing.T) { - conf, err := ConfigFromJSON(webJSONKey, "scope1", "scope2") - if err != nil { - t.Error(err) - } - if got, want := conf.ClientID, "222-nprqovg5k43uum874cs9osjt2koe97g8.apps.googleusercontent.com"; got != want { - t.Errorf("ClientID = %q; want %q", got, want) - } - if got, want := conf.ClientSecret, "3Oknc4jS_wA2r9i"; got != want { - t.Errorf("ClientSecret = %q; want %q", got, want) - } - if got, want := conf.RedirectURL, "https://www.example.com/oauth2callback"; got != want { - t.Errorf("RedictURL = %q; want %q", got, want) - } - if got, want := strings.Join(conf.Scopes, ","), "scope1,scope2"; got != want { - t.Errorf("Scopes = %q; want %q", got, want) - } - if got, want := conf.Endpoint.AuthURL, "https://google.com/o/oauth2/auth"; got != want { - t.Errorf("AuthURL = %q; want %q", got, want) - } - if got, want := conf.Endpoint.TokenURL, "https://google.com/o/oauth2/token"; got != want { - t.Errorf("TokenURL = %q; want %q", got, want) - } -} - -func TestConfigFromJSON_Installed(t *testing.T) { - conf, err := ConfigFromJSON(installedJSONKey) - if err != nil { - t.Error(err) - } - if got, want := conf.ClientID, "222-installed.apps.googleusercontent.com"; got != want { - t.Errorf("ClientID = %q; want %q", got, want) - } -} diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/google/jwt.go b/Godeps/_workspace/src/golang.org/x/oauth2/google/jwt.go index 25d129288..804d9d077 100644 --- a/Godeps/_workspace/src/golang.org/x/oauth2/google/jwt.go +++ b/Godeps/_workspace/src/golang.org/x/oauth2/google/jwt.go @@ -19,6 +19,10 @@ import ( // requests, and returns a TokenSource that does not use any OAuth2 flow but // instead creates a JWT and sends that as the access token. // The audience is typically a URL that specifies the scope of the credentials. +// +// Note that this is not a standard OAuth flow, but rather an +// optimization supported by a few Google services. +// Unless you know otherwise, you should use JWTConfigFromJSON instead. func JWTAccessTokenSourceFromJSON(jsonKey []byte, audience string) (oauth2.TokenSource, error) { cfg, err := JWTConfigFromJSON(jsonKey) if err != nil { @@ -63,5 +67,5 @@ func (ts *jwtAccessTokenSource) Token() (*oauth2.Token, error) { if err != nil { return nil, fmt.Errorf("google: could not encode JWT: %v", err) } - return &oauth2.Token{AccessToken: msg}, nil + return &oauth2.Token{AccessToken: msg, TokenType: "Bearer"}, nil } diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/google/sdk_test.go b/Godeps/_workspace/src/golang.org/x/oauth2/google/sdk_test.go deleted file mode 100644 index 79df88964..000000000 --- a/Godeps/_workspace/src/golang.org/x/oauth2/google/sdk_test.go +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright 2015 The oauth2 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 google - -import "testing" - -func TestSDKConfig(t *testing.T) { - sdkConfigPath = func() (string, error) { - return "testdata/gcloud", nil - } - - tests := []struct { - account string - accessToken string - err bool - }{ - {"", "bar_access_token", false}, - {"foo@example.com", "foo_access_token", false}, - {"bar@example.com", "bar_access_token", false}, - {"baz@serviceaccount.example.com", "", true}, - } - for _, tt := range tests { - c, err := NewSDKConfig(tt.account) - if got, want := err != nil, tt.err; got != want { - if !tt.err { - t.Errorf("expected no error, got error: %v", tt.err, err) - } else { - t.Errorf("expected error, got none") - } - continue - } - if err != nil { - continue - } - tok := c.initialToken - if tok == nil { - t.Errorf("expected token %q, got: nil", tt.accessToken) - continue - } - if tok.AccessToken != tt.accessToken { - t.Errorf("expected token %q, got: %q", tt.accessToken, tok.AccessToken) - } - } -} diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/google/testdata/gcloud/credentials b/Godeps/_workspace/src/golang.org/x/oauth2/google/testdata/gcloud/credentials deleted file mode 100644 index ff5eefbd0..000000000 --- a/Godeps/_workspace/src/golang.org/x/oauth2/google/testdata/gcloud/credentials +++ /dev/null @@ -1,122 +0,0 @@ -{ - "data": [ - { - "credential": { - "_class": "OAuth2Credentials", - "_module": "oauth2client.client", - "access_token": "foo_access_token", - "client_id": "foo_client_id", - "client_secret": "foo_client_secret", - "id_token": { - "at_hash": "foo_at_hash", - "aud": "foo_aud", - "azp": "foo_azp", - "cid": "foo_cid", - "email": "foo@example.com", - "email_verified": true, - "exp": 1420573614, - "iat": 1420569714, - "id": "1337", - "iss": "accounts.google.com", - "sub": "1337", - "token_hash": "foo_token_hash", - "verified_email": true - }, - "invalid": false, - "refresh_token": "foo_refresh_token", - "revoke_uri": "https://accounts.google.com/o/oauth2/revoke", - "token_expiry": "2015-01-09T00:51:51Z", - "token_response": { - "access_token": "foo_access_token", - "expires_in": 3600, - "id_token": "foo_id_token", - "token_type": "Bearer" - }, - "token_uri": "https://accounts.google.com/o/oauth2/token", - "user_agent": "Cloud SDK Command Line Tool" - }, - "key": { - "account": "foo@example.com", - "clientId": "foo_client_id", - "scope": "https://www.googleapis.com/auth/appengine.admin https://www.googleapis.com/auth/bigquery https://www.googleapis.com/auth/compute https://www.googleapis.com/auth/devstorage.full_control https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/ndev.cloudman https://www.googleapis.com/auth/cloud-platform https://www.googleapis.com/auth/sqlservice.admin https://www.googleapis.com/auth/prediction https://www.googleapis.com/auth/projecthosting", - "type": "google-cloud-sdk" - } - }, - { - "credential": { - "_class": "OAuth2Credentials", - "_module": "oauth2client.client", - "access_token": "bar_access_token", - "client_id": "bar_client_id", - "client_secret": "bar_client_secret", - "id_token": { - "at_hash": "bar_at_hash", - "aud": "bar_aud", - "azp": "bar_azp", - "cid": "bar_cid", - "email": "bar@example.com", - "email_verified": true, - "exp": 1420573614, - "iat": 1420569714, - "id": "1337", - "iss": "accounts.google.com", - "sub": "1337", - "token_hash": "bar_token_hash", - "verified_email": true - }, - "invalid": false, - "refresh_token": "bar_refresh_token", - "revoke_uri": "https://accounts.google.com/o/oauth2/revoke", - "token_expiry": "2015-01-09T00:51:51Z", - "token_response": { - "access_token": "bar_access_token", - "expires_in": 3600, - "id_token": "bar_id_token", - "token_type": "Bearer" - }, - "token_uri": "https://accounts.google.com/o/oauth2/token", - "user_agent": "Cloud SDK Command Line Tool" - }, - "key": { - "account": "bar@example.com", - "clientId": "bar_client_id", - "scope": "https://www.googleapis.com/auth/appengine.admin https://www.googleapis.com/auth/bigquery https://www.googleapis.com/auth/compute https://www.googleapis.com/auth/devstorage.full_control https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/ndev.cloudman https://www.googleapis.com/auth/cloud-platform https://www.googleapis.com/auth/sqlservice.admin https://www.googleapis.com/auth/prediction https://www.googleapis.com/auth/projecthosting", - "type": "google-cloud-sdk" - } - }, - { - "credential": { - "_class": "ServiceAccountCredentials", - "_kwargs": {}, - "_module": "oauth2client.client", - "_private_key_id": "00000000000000000000000000000000", - "_private_key_pkcs8_text": "-----BEGIN RSA PRIVATE KEY-----\nMIICWwIBAAKBgQCt3fpiynPSaUhWSIKMGV331zudwJ6GkGmvQtwsoK2S2LbvnSwU\nNxgj4fp08kIDR5p26wF4+t/HrKydMwzftXBfZ9UmLVJgRdSswmS5SmChCrfDS5OE\nvFFcN5+6w1w8/Nu657PF/dse8T0bV95YrqyoR0Osy8WHrUOMSIIbC3hRuwIDAQAB\nAoGAJrGE/KFjn0sQ7yrZ6sXmdLawrM3mObo/2uI9T60+k7SpGbBX0/Pi6nFrJMWZ\nTVONG7P3Mu5aCPzzuVRYJB0j8aldSfzABTY3HKoWCczqw1OztJiEseXGiYz4QOyr\nYU3qDyEpdhS6q6wcoLKGH+hqRmz6pcSEsc8XzOOu7s4xW8kCQQDkc75HjhbarCnd\nJJGMe3U76+6UGmdK67ltZj6k6xoB5WbTNChY9TAyI2JC+ppYV89zv3ssj4L+02u3\nHIHFGxsHAkEAwtU1qYb1tScpchPobnYUFiVKJ7KA8EZaHVaJJODW/cghTCV7BxcJ\nbgVvlmk4lFKn3lPKAgWw7PdQsBTVBUcCrQJATPwoIirizrv3u5soJUQxZIkENAqV\nxmybZx9uetrzP7JTrVbFRf0SScMcyN90hdLJiQL8+i4+gaszgFht7sNMnwJAAbfj\nq0UXcauQwALQ7/h2oONfTg5S+MuGC/AxcXPSMZbMRGGoPh3D5YaCv27aIuS/ukQ+\n6dmm/9AGlCb64fsIWQJAPaokbjIifo+LwC5gyK73Mc4t8nAOSZDenzd/2f6TCq76\nS1dcnKiPxaED7W/y6LJiuBT2rbZiQ2L93NJpFZD/UA==\n-----END RSA PRIVATE KEY-----\n", - "_revoke_uri": "https://accounts.google.com/o/oauth2/revoke", - "_scopes": "https://www.googleapis.com/auth/appengine.admin https://www.googleapis.com/auth/bigquery https://www.googleapis.com/auth/compute https://www.googleapis.com/auth/devstorage.full_control https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/ndev.cloudman https://www.googleapis.com/auth/cloud-platform https://www.googleapis.com/auth/sqlservice.admin https://www.googleapis.com/auth/prediction https://www.googleapis.com/auth/projecthosting", - "_service_account_email": "baz@serviceaccount.example.com", - "_service_account_id": "baz.serviceaccount.example.com", - "_token_uri": "https://accounts.google.com/o/oauth2/token", - "_user_agent": "Cloud SDK Command Line Tool", - "access_token": null, - "assertion_type": null, - "client_id": null, - "client_secret": null, - "id_token": null, - "invalid": false, - "refresh_token": null, - "revoke_uri": "https://accounts.google.com/o/oauth2/revoke", - "service_account_name": "baz@serviceaccount.example.com", - "token_expiry": null, - "token_response": null, - "user_agent": "Cloud SDK Command Line Tool" - }, - "key": { - "account": "baz@serviceaccount.example.com", - "clientId": "baz_client_id", - "scope": "https://www.googleapis.com/auth/appengine.admin https://www.googleapis.com/auth/bigquery https://www.googleapis.com/auth/compute https://www.googleapis.com/auth/devstorage.full_control https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/ndev.cloudman https://www.googleapis.com/auth/cloud-platform https://www.googleapis.com/auth/sqlservice.admin https://www.googleapis.com/auth/prediction https://www.googleapis.com/auth/projecthosting", - "type": "google-cloud-sdk" - } - } - ], - "file_version": 1 -} diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/google/testdata/gcloud/properties b/Godeps/_workspace/src/golang.org/x/oauth2/google/testdata/gcloud/properties deleted file mode 100644 index 025de886c..000000000 --- a/Godeps/_workspace/src/golang.org/x/oauth2/google/testdata/gcloud/properties +++ /dev/null @@ -1,2 +0,0 @@ -[core] -account = bar@example.com \ No newline at end of file diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/internal/oauth2_test.go b/Godeps/_workspace/src/golang.org/x/oauth2/internal/oauth2_test.go deleted file mode 100644 index 014a351e0..000000000 --- a/Godeps/_workspace/src/golang.org/x/oauth2/internal/oauth2_test.go +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright 2014 The oauth2 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 internal contains support packages for oauth2 package. -package internal - -import ( - "reflect" - "strings" - "testing" -) - -func TestParseINI(t *testing.T) { - tests := []struct { - ini string - want map[string]map[string]string - }{ - { - `root = toor -[foo] -bar = hop -ini = nin -`, - map[string]map[string]string{ - "": map[string]string{"root": "toor"}, - "foo": map[string]string{"bar": "hop", "ini": "nin"}, - }, - }, - { - `[empty] -[section] -empty= -`, - map[string]map[string]string{ - "": map[string]string{}, - "empty": map[string]string{}, - "section": map[string]string{"empty": ""}, - }, - }, - { - `ignore -[invalid -=stuff -;comment=true -`, - map[string]map[string]string{ - "": map[string]string{}, - }, - }, - } - for _, tt := range tests { - result, err := ParseINI(strings.NewReader(tt.ini)) - if err != nil { - t.Errorf("ParseINI(%q) error %v, want: no error", tt.ini, err) - continue - } - if !reflect.DeepEqual(result, tt.want) { - t.Errorf("ParseINI(%q) = %#v, want: %#v", tt.ini, result, tt.want) - } - } -} diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/internal/token_test.go b/Godeps/_workspace/src/golang.org/x/oauth2/internal/token_test.go deleted file mode 100644 index 864f6fa07..000000000 --- a/Godeps/_workspace/src/golang.org/x/oauth2/internal/token_test.go +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright 2014 The oauth2 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 internal contains support packages for oauth2 package. -package internal - -import ( - "fmt" - "testing" -) - -func Test_providerAuthHeaderWorks(t *testing.T) { - for _, p := range brokenAuthHeaderProviders { - if providerAuthHeaderWorks(p) { - t.Errorf("URL: %s not found in list", p) - } - p := fmt.Sprintf("%ssomesuffix", p) - if providerAuthHeaderWorks(p) { - t.Errorf("URL: %s not found in list", p) - } - } - p := "https://api.not-in-the-list-example.com/" - if !providerAuthHeaderWorks(p) { - t.Errorf("URL: %s found in list", p) - } - -} diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/jws/jws.go b/Godeps/_workspace/src/golang.org/x/oauth2/jws/jws.go index 994ae1e88..a4595eb5e 100644 --- a/Godeps/_workspace/src/golang.org/x/oauth2/jws/jws.go +++ b/Godeps/_workspace/src/golang.org/x/oauth2/jws/jws.go @@ -41,23 +41,22 @@ type ClaimSet struct { // See http://tools.ietf.org/html/draft-jones-json-web-token-10#section-4.3 // This array is marshalled using custom code (see (c *ClaimSet) encode()). PrivateClaims map[string]interface{} `json:"-"` - - exp time.Time - iat time.Time } func (c *ClaimSet) encode() (string, error) { - if c.exp.IsZero() || c.iat.IsZero() { - // Reverting time back for machines whose time is not perfectly in sync. - // If client machine's time is in the future according - // to Google servers, an access token will not be issued. - now := time.Now().Add(-10 * time.Second) - c.iat = now - c.exp = now.Add(time.Hour) + // Reverting time back for machines whose time is not perfectly in sync. + // If client machine's time is in the future according + // to Google servers, an access token will not be issued. + now := time.Now().Add(-10 * time.Second) + if c.Iat == 0 { + c.Iat = now.Unix() + } + if c.Exp == 0 { + c.Exp = now.Add(time.Hour).Unix() + } + if c.Exp < c.Iat { + return "", fmt.Errorf("jws: invalid Exp = %v; must be later than Iat = %v", c.Exp, c.Iat) } - - c.Exp = c.exp.Unix() - c.Iat = c.iat.Unix() b, err := json.Marshal(c) if err != nil { diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/jwt/example_test.go b/Godeps/_workspace/src/golang.org/x/oauth2/jwt/example_test.go deleted file mode 100644 index 6d618836e..000000000 --- a/Godeps/_workspace/src/golang.org/x/oauth2/jwt/example_test.go +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2014 The oauth2 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 jwt_test - -import ( - "golang.org/x/oauth2" - "golang.org/x/oauth2/jwt" -) - -func ExampleJWTConfig() { - conf := &jwt.Config{ - Email: "xxx@developer.com", - // The contents of your RSA private key or your PEM file - // that contains a private key. - // If you have a p12 file instead, you - // can use `openssl` to export the private key into a pem file. - // - // $ openssl pkcs12 -in key.p12 -out key.pem -nodes - // - // It only supports PEM containers with no passphrase. - PrivateKey: []byte("-----BEGIN RSA PRIVATE KEY-----..."), - Subject: "user@example.com", - TokenURL: "https://provider.com/o/oauth2/token", - } - // Initiate an http.Client, the following GET request will be - // authorized and authenticated on the behalf of user@example.com. - client := conf.Client(oauth2.NoContext) - client.Get("...") -} diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/jwt/jwt.go b/Godeps/_workspace/src/golang.org/x/oauth2/jwt/jwt.go index 205d23ed4..11a2687ef 100644 --- a/Godeps/_workspace/src/golang.org/x/oauth2/jwt/jwt.go +++ b/Godeps/_workspace/src/golang.org/x/oauth2/jwt/jwt.go @@ -54,6 +54,9 @@ type Config struct { // TokenURL is the endpoint required to complete the 2-legged JWT flow. TokenURL string + + // Expires optionally specifies how long the token is valid for. + Expires time.Duration } // TokenSource returns a JWT TokenSource using the configuration @@ -95,6 +98,9 @@ func (js jwtSource) Token() (*oauth2.Token, error) { // to be compatible with legacy OAuth 2.0 providers. claimSet.Prn = subject } + if t := js.conf.Expires; t > 0 { + claimSet.Exp = time.Now().Add(t).Unix() + } payload, err := jws.Encode(defaultHeader, claimSet, pk) if err != nil { return nil, err diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/jwt/jwt_test.go b/Godeps/_workspace/src/golang.org/x/oauth2/jwt/jwt_test.go deleted file mode 100644 index da922c3d0..000000000 --- a/Godeps/_workspace/src/golang.org/x/oauth2/jwt/jwt_test.go +++ /dev/null @@ -1,134 +0,0 @@ -// Copyright 2014 The oauth2 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 jwt - -import ( - "net/http" - "net/http/httptest" - "testing" - - "golang.org/x/oauth2" -) - -var dummyPrivateKey = []byte(`-----BEGIN RSA PRIVATE KEY----- -MIIEpAIBAAKCAQEAx4fm7dngEmOULNmAs1IGZ9Apfzh+BkaQ1dzkmbUgpcoghucE -DZRnAGd2aPyB6skGMXUytWQvNYav0WTR00wFtX1ohWTfv68HGXJ8QXCpyoSKSSFY -fuP9X36wBSkSX9J5DVgiuzD5VBdzUISSmapjKm+DcbRALjz6OUIPEWi1Tjl6p5RK -1w41qdbmt7E5/kGhKLDuT7+M83g4VWhgIvaAXtnhklDAggilPPa8ZJ1IFe31lNlr -k4DRk38nc6sEutdf3RL7QoH7FBusI7uXV03DC6dwN1kP4GE7bjJhcRb/7jYt7CQ9 -/E9Exz3c0yAp0yrTg0Fwh+qxfH9dKwN52S7SBwIDAQABAoIBAQCaCs26K07WY5Jt -3a2Cw3y2gPrIgTCqX6hJs7O5ByEhXZ8nBwsWANBUe4vrGaajQHdLj5OKfsIDrOvn -2NI1MqflqeAbu/kR32q3tq8/Rl+PPiwUsW3E6Pcf1orGMSNCXxeducF2iySySzh3 -nSIhCG5uwJDWI7a4+9KiieFgK1pt/Iv30q1SQS8IEntTfXYwANQrfKUVMmVF9aIK -6/WZE2yd5+q3wVVIJ6jsmTzoDCX6QQkkJICIYwCkglmVy5AeTckOVwcXL0jqw5Kf -5/soZJQwLEyBoQq7Kbpa26QHq+CJONetPP8Ssy8MJJXBT+u/bSseMb3Zsr5cr43e -DJOhwsThAoGBAPY6rPKl2NT/K7XfRCGm1sbWjUQyDShscwuWJ5+kD0yudnT/ZEJ1 -M3+KS/iOOAoHDdEDi9crRvMl0UfNa8MAcDKHflzxg2jg/QI+fTBjPP5GOX0lkZ9g -z6VePoVoQw2gpPFVNPPTxKfk27tEzbaffvOLGBEih0Kb7HTINkW8rIlzAoGBAM9y -1yr+jvfS1cGFtNU+Gotoihw2eMKtIqR03Yn3n0PK1nVCDKqwdUqCypz4+ml6cxRK -J8+Pfdh7D+ZJd4LEG6Y4QRDLuv5OA700tUoSHxMSNn3q9As4+T3MUyYxWKvTeu3U -f2NWP9ePU0lV8ttk7YlpVRaPQmc1qwooBA/z/8AdAoGAW9x0HWqmRICWTBnpjyxx -QGlW9rQ9mHEtUotIaRSJ6K/F3cxSGUEkX1a3FRnp6kPLcckC6NlqdNgNBd6rb2rA -cPl/uSkZP42Als+9YMoFPU/xrrDPbUhu72EDrj3Bllnyb168jKLa4VBOccUvggxr -Dm08I1hgYgdN5huzs7y6GeUCgYEAj+AZJSOJ6o1aXS6rfV3mMRve9bQ9yt8jcKXw -5HhOCEmMtaSKfnOF1Ziih34Sxsb7O2428DiX0mV/YHtBnPsAJidL0SdLWIapBzeg -KHArByIRkwE6IvJvwpGMdaex1PIGhx5i/3VZL9qiq/ElT05PhIb+UXgoWMabCp84 -OgxDK20CgYAeaFo8BdQ7FmVX2+EEejF+8xSge6WVLtkaon8bqcn6P0O8lLypoOhd -mJAYH8WU+UAy9pecUnDZj14LAGNVmYcse8HFX71MoshnvCTFEPVo4rZxIAGwMpeJ -5jgQ3slYLpqrGlcbLgUXBUgzEO684Wk/UV9DFPlHALVqCfXQ9dpJPg== ------END RSA PRIVATE KEY-----`) - -func TestJWTFetch_JSONResponse(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - w.Write([]byte(`{ - "access_token": "90d64460d14870c08c81352a05dedd3465940a7c", - "scope": "user", - "token_type": "bearer", - "expires_in": 3600 - }`)) - })) - defer ts.Close() - - conf := &Config{ - Email: "aaa@xxx.com", - PrivateKey: dummyPrivateKey, - TokenURL: ts.URL, - } - tok, err := conf.TokenSource(oauth2.NoContext).Token() - if err != nil { - t.Fatal(err) - } - if !tok.Valid() { - t.Errorf("Token invalid") - } - if tok.AccessToken != "90d64460d14870c08c81352a05dedd3465940a7c" { - t.Errorf("Unexpected access token, %#v", tok.AccessToken) - } - if tok.TokenType != "bearer" { - t.Errorf("Unexpected token type, %#v", tok.TokenType) - } - if tok.Expiry.IsZero() { - t.Errorf("Unexpected token expiry, %#v", tok.Expiry) - } - scope := tok.Extra("scope") - if scope != "user" { - t.Errorf("Unexpected value for scope: %v", scope) - } -} - -func TestJWTFetch_BadResponse(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - w.Write([]byte(`{"scope": "user", "token_type": "bearer"}`)) - })) - defer ts.Close() - - conf := &Config{ - Email: "aaa@xxx.com", - PrivateKey: dummyPrivateKey, - TokenURL: ts.URL, - } - tok, err := conf.TokenSource(oauth2.NoContext).Token() - if err != nil { - t.Fatal(err) - } - if tok == nil { - t.Fatalf("token is nil") - } - if tok.Valid() { - t.Errorf("token is valid. want invalid.") - } - if tok.AccessToken != "" { - t.Errorf("Unexpected non-empty access token %q.", tok.AccessToken) - } - if want := "bearer"; tok.TokenType != want { - t.Errorf("TokenType = %q; want %q", tok.TokenType, want) - } - scope := tok.Extra("scope") - if want := "user"; scope != want { - t.Errorf("token scope = %q; want %q", scope, want) - } -} - -func TestJWTFetch_BadResponseType(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - w.Write([]byte(`{"access_token":123, "scope": "user", "token_type": "bearer"}`)) - })) - defer ts.Close() - conf := &Config{ - Email: "aaa@xxx.com", - PrivateKey: dummyPrivateKey, - TokenURL: ts.URL, - } - tok, err := conf.TokenSource(oauth2.NoContext).Token() - if err == nil { - t.Error("got a token; expected error") - if tok.AccessToken != "" { - t.Errorf("Unexpected access token, %#v.", tok.AccessToken) - } - } -} diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/oauth2_test.go b/Godeps/_workspace/src/golang.org/x/oauth2/oauth2_test.go deleted file mode 100644 index 2f7d731c1..000000000 --- a/Godeps/_workspace/src/golang.org/x/oauth2/oauth2_test.go +++ /dev/null @@ -1,422 +0,0 @@ -// Copyright 2014 The oauth2 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 oauth2 - -import ( - "encoding/json" - "errors" - "fmt" - "io/ioutil" - "net/http" - "net/http/httptest" - "reflect" - "strconv" - "testing" - "time" - - "golang.org/x/net/context" -) - -type mockTransport struct { - rt func(req *http.Request) (resp *http.Response, err error) -} - -func (t *mockTransport) RoundTrip(req *http.Request) (resp *http.Response, err error) { - return t.rt(req) -} - -type mockCache struct { - token *Token - readErr error -} - -func (c *mockCache) ReadToken() (*Token, error) { - return c.token, c.readErr -} - -func (c *mockCache) WriteToken(*Token) { - // do nothing -} - -func newConf(url string) *Config { - return &Config{ - ClientID: "CLIENT_ID", - ClientSecret: "CLIENT_SECRET", - RedirectURL: "REDIRECT_URL", - Scopes: []string{"scope1", "scope2"}, - Endpoint: Endpoint{ - AuthURL: url + "/auth", - TokenURL: url + "/token", - }, - } -} - -func TestAuthCodeURL(t *testing.T) { - conf := newConf("server") - url := conf.AuthCodeURL("foo", AccessTypeOffline, ApprovalForce) - if url != "server/auth?access_type=offline&approval_prompt=force&client_id=CLIENT_ID&redirect_uri=REDIRECT_URL&response_type=code&scope=scope1+scope2&state=foo" { - t.Errorf("Auth code URL doesn't match the expected, found: %v", url) - } -} - -func TestAuthCodeURL_CustomParam(t *testing.T) { - conf := newConf("server") - param := SetAuthURLParam("foo", "bar") - url := conf.AuthCodeURL("baz", param) - if url != "server/auth?client_id=CLIENT_ID&foo=bar&redirect_uri=REDIRECT_URL&response_type=code&scope=scope1+scope2&state=baz" { - t.Errorf("Auth code URL doesn't match the expected, found: %v", url) - } -} - -func TestAuthCodeURL_Optional(t *testing.T) { - conf := &Config{ - ClientID: "CLIENT_ID", - Endpoint: Endpoint{ - AuthURL: "/auth-url", - TokenURL: "/token-url", - }, - } - url := conf.AuthCodeURL("") - if url != "/auth-url?client_id=CLIENT_ID&response_type=code" { - t.Fatalf("Auth code URL doesn't match the expected, found: %v", url) - } -} - -func TestExchangeRequest(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.URL.String() != "/token" { - t.Errorf("Unexpected exchange request URL, %v is found.", r.URL) - } - headerAuth := r.Header.Get("Authorization") - if headerAuth != "Basic Q0xJRU5UX0lEOkNMSUVOVF9TRUNSRVQ=" { - t.Errorf("Unexpected authorization header, %v is found.", headerAuth) - } - headerContentType := r.Header.Get("Content-Type") - if headerContentType != "application/x-www-form-urlencoded" { - t.Errorf("Unexpected Content-Type header, %v is found.", headerContentType) - } - body, err := ioutil.ReadAll(r.Body) - if err != nil { - t.Errorf("Failed reading request body: %s.", err) - } - if string(body) != "client_id=CLIENT_ID&code=exchange-code&grant_type=authorization_code&redirect_uri=REDIRECT_URL&scope=scope1+scope2" { - t.Errorf("Unexpected exchange payload, %v is found.", string(body)) - } - w.Header().Set("Content-Type", "application/x-www-form-urlencoded") - w.Write([]byte("access_token=90d64460d14870c08c81352a05dedd3465940a7c&scope=user&token_type=bearer")) - })) - defer ts.Close() - conf := newConf(ts.URL) - tok, err := conf.Exchange(NoContext, "exchange-code") - if err != nil { - t.Error(err) - } - if !tok.Valid() { - t.Fatalf("Token invalid. Got: %#v", tok) - } - if tok.AccessToken != "90d64460d14870c08c81352a05dedd3465940a7c" { - t.Errorf("Unexpected access token, %#v.", tok.AccessToken) - } - if tok.TokenType != "bearer" { - t.Errorf("Unexpected token type, %#v.", tok.TokenType) - } - scope := tok.Extra("scope") - if scope != "user" { - t.Errorf("Unexpected value for scope: %v", scope) - } -} - -func TestExchangeRequest_JSONResponse(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.URL.String() != "/token" { - t.Errorf("Unexpected exchange request URL, %v is found.", r.URL) - } - headerAuth := r.Header.Get("Authorization") - if headerAuth != "Basic Q0xJRU5UX0lEOkNMSUVOVF9TRUNSRVQ=" { - t.Errorf("Unexpected authorization header, %v is found.", headerAuth) - } - headerContentType := r.Header.Get("Content-Type") - if headerContentType != "application/x-www-form-urlencoded" { - t.Errorf("Unexpected Content-Type header, %v is found.", headerContentType) - } - body, err := ioutil.ReadAll(r.Body) - if err != nil { - t.Errorf("Failed reading request body: %s.", err) - } - if string(body) != "client_id=CLIENT_ID&code=exchange-code&grant_type=authorization_code&redirect_uri=REDIRECT_URL&scope=scope1+scope2" { - t.Errorf("Unexpected exchange payload, %v is found.", string(body)) - } - w.Header().Set("Content-Type", "application/json") - w.Write([]byte(`{"access_token": "90d64460d14870c08c81352a05dedd3465940a7c", "scope": "user", "token_type": "bearer", "expires_in": 86400}`)) - })) - defer ts.Close() - conf := newConf(ts.URL) - tok, err := conf.Exchange(NoContext, "exchange-code") - if err != nil { - t.Error(err) - } - if !tok.Valid() { - t.Fatalf("Token invalid. Got: %#v", tok) - } - if tok.AccessToken != "90d64460d14870c08c81352a05dedd3465940a7c" { - t.Errorf("Unexpected access token, %#v.", tok.AccessToken) - } - if tok.TokenType != "bearer" { - t.Errorf("Unexpected token type, %#v.", tok.TokenType) - } - scope := tok.Extra("scope") - if scope != "user" { - t.Errorf("Unexpected value for scope: %v", scope) - } -} - -const day = 24 * time.Hour - -func TestExchangeRequest_JSONResponse_Expiry(t *testing.T) { - seconds := int32(day.Seconds()) - jsonNumberType := reflect.TypeOf(json.Number("0")) - for _, c := range []struct { - expires string - expect error - }{ - {fmt.Sprintf(`"expires_in": %d`, seconds), nil}, - {fmt.Sprintf(`"expires_in": "%d"`, seconds), nil}, // PayPal case - {fmt.Sprintf(`"expires": %d`, seconds), nil}, // Facebook case - {`"expires": false`, &json.UnmarshalTypeError{Value: "bool", Type: jsonNumberType}}, // wrong type - {`"expires": {}`, &json.UnmarshalTypeError{Value: "object", Type: jsonNumberType}}, // wrong type - {`"expires": "zzz"`, &strconv.NumError{Func: "ParseInt", Num: "zzz", Err: strconv.ErrSyntax}}, // wrong value - } { - testExchangeRequest_JSONResponse_expiry(t, c.expires, c.expect) - } -} - -func testExchangeRequest_JSONResponse_expiry(t *testing.T, exp string, expect error) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - w.Write([]byte(fmt.Sprintf(`{"access_token": "90d", "scope": "user", "token_type": "bearer", %s}`, exp))) - })) - defer ts.Close() - conf := newConf(ts.URL) - t1 := time.Now().Add(day) - tok, err := conf.Exchange(NoContext, "exchange-code") - t2 := time.Now().Add(day) - // Do a fmt.Sprint comparison so either side can be - // nil. fmt.Sprint just stringifies them to "", and no - // non-nil expected error ever stringifies as "", so this - // isn't terribly disgusting. We do this because Go 1.4 and - // Go 1.5 return a different deep value for - // json.UnmarshalTypeError. In Go 1.5, the - // json.UnmarshalTypeError contains a new field with a new - // non-zero value. Rather than ignore it here with reflect or - // add new files and +build tags, just look at the strings. - if fmt.Sprint(err) != fmt.Sprint(expect) { - t.Errorf("Error = %v; want %v", err, expect) - } - if err != nil { - return - } - if !tok.Valid() { - t.Fatalf("Token invalid. Got: %#v", tok) - } - expiry := tok.Expiry - if expiry.Before(t1) || expiry.After(t2) { - t.Errorf("Unexpected value for Expiry: %v (shold be between %v and %v)", expiry, t1, t2) - } -} - -func TestExchangeRequest_BadResponse(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - w.Write([]byte(`{"scope": "user", "token_type": "bearer"}`)) - })) - defer ts.Close() - conf := newConf(ts.URL) - tok, err := conf.Exchange(NoContext, "code") - if err != nil { - t.Fatal(err) - } - if tok.AccessToken != "" { - t.Errorf("Unexpected access token, %#v.", tok.AccessToken) - } -} - -func TestExchangeRequest_BadResponseType(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - w.Write([]byte(`{"access_token":123, "scope": "user", "token_type": "bearer"}`)) - })) - defer ts.Close() - conf := newConf(ts.URL) - _, err := conf.Exchange(NoContext, "exchange-code") - if err == nil { - t.Error("expected error from invalid access_token type") - } -} - -func TestExchangeRequest_NonBasicAuth(t *testing.T) { - tr := &mockTransport{ - rt: func(r *http.Request) (w *http.Response, err error) { - headerAuth := r.Header.Get("Authorization") - if headerAuth != "" { - t.Errorf("Unexpected authorization header, %v is found.", headerAuth) - } - return nil, errors.New("no response") - }, - } - c := &http.Client{Transport: tr} - conf := &Config{ - ClientID: "CLIENT_ID", - Endpoint: Endpoint{ - AuthURL: "https://accounts.google.com/auth", - TokenURL: "https://accounts.google.com/token", - }, - } - - ctx := context.WithValue(context.Background(), HTTPClient, c) - conf.Exchange(ctx, "code") -} - -func TestPasswordCredentialsTokenRequest(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - defer r.Body.Close() - expected := "/token" - if r.URL.String() != expected { - t.Errorf("URL = %q; want %q", r.URL, expected) - } - headerAuth := r.Header.Get("Authorization") - expected = "Basic Q0xJRU5UX0lEOkNMSUVOVF9TRUNSRVQ=" - if headerAuth != expected { - t.Errorf("Authorization header = %q; want %q", headerAuth, expected) - } - headerContentType := r.Header.Get("Content-Type") - expected = "application/x-www-form-urlencoded" - if headerContentType != expected { - t.Errorf("Content-Type header = %q; want %q", headerContentType, expected) - } - body, err := ioutil.ReadAll(r.Body) - if err != nil { - t.Errorf("Failed reading request body: %s.", err) - } - expected = "client_id=CLIENT_ID&grant_type=password&password=password1&scope=scope1+scope2&username=user1" - if string(body) != expected { - t.Errorf("res.Body = %q; want %q", string(body), expected) - } - w.Header().Set("Content-Type", "application/x-www-form-urlencoded") - w.Write([]byte("access_token=90d64460d14870c08c81352a05dedd3465940a7c&scope=user&token_type=bearer")) - })) - defer ts.Close() - conf := newConf(ts.URL) - tok, err := conf.PasswordCredentialsToken(NoContext, "user1", "password1") - if err != nil { - t.Error(err) - } - if !tok.Valid() { - t.Fatalf("Token invalid. Got: %#v", tok) - } - expected := "90d64460d14870c08c81352a05dedd3465940a7c" - if tok.AccessToken != expected { - t.Errorf("AccessToken = %q; want %q", tok.AccessToken, expected) - } - expected = "bearer" - if tok.TokenType != expected { - t.Errorf("TokenType = %q; want %q", tok.TokenType, expected) - } -} - -func TestTokenRefreshRequest(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.URL.String() == "/somethingelse" { - return - } - if r.URL.String() != "/token" { - t.Errorf("Unexpected token refresh request URL, %v is found.", r.URL) - } - headerContentType := r.Header.Get("Content-Type") - if headerContentType != "application/x-www-form-urlencoded" { - t.Errorf("Unexpected Content-Type header, %v is found.", headerContentType) - } - body, _ := ioutil.ReadAll(r.Body) - if string(body) != "client_id=CLIENT_ID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN" { - t.Errorf("Unexpected refresh token payload, %v is found.", string(body)) - } - })) - defer ts.Close() - conf := newConf(ts.URL) - c := conf.Client(NoContext, &Token{RefreshToken: "REFRESH_TOKEN"}) - c.Get(ts.URL + "/somethingelse") -} - -func TestFetchWithNoRefreshToken(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.URL.String() == "/somethingelse" { - return - } - if r.URL.String() != "/token" { - t.Errorf("Unexpected token refresh request URL, %v is found.", r.URL) - } - headerContentType := r.Header.Get("Content-Type") - if headerContentType != "application/x-www-form-urlencoded" { - t.Errorf("Unexpected Content-Type header, %v is found.", headerContentType) - } - body, _ := ioutil.ReadAll(r.Body) - if string(body) != "client_id=CLIENT_ID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN" { - t.Errorf("Unexpected refresh token payload, %v is found.", string(body)) - } - })) - defer ts.Close() - conf := newConf(ts.URL) - c := conf.Client(NoContext, nil) - _, err := c.Get(ts.URL + "/somethingelse") - if err == nil { - t.Errorf("Fetch should return an error if no refresh token is set") - } -} - -func TestRefreshToken_RefreshTokenReplacement(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - w.Write([]byte(`{"access_token":"ACCESS TOKEN", "scope": "user", "token_type": "bearer", "refresh_token": "NEW REFRESH TOKEN"}`)) - return - })) - defer ts.Close() - conf := newConf(ts.URL) - tkr := tokenRefresher{ - conf: conf, - ctx: NoContext, - refreshToken: "OLD REFRESH TOKEN", - } - tk, err := tkr.Token() - if err != nil { - t.Errorf("Unexpected refreshToken error returned: %v", err) - return - } - if tk.RefreshToken != tkr.refreshToken { - t.Errorf("tokenRefresher.refresh_token = %s; want %s", tkr.refreshToken, tk.RefreshToken) - } -} - -func TestConfigClientWithToken(t *testing.T) { - tok := &Token{ - AccessToken: "abc123", - } - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if got, want := r.Header.Get("Authorization"), fmt.Sprintf("Bearer %s", tok.AccessToken); got != want { - t.Errorf("Authorization header = %q; want %q", got, want) - } - return - })) - defer ts.Close() - conf := newConf(ts.URL) - - c := conf.Client(NoContext, tok) - req, err := http.NewRequest("GET", ts.URL, nil) - if err != nil { - t.Error(err) - } - _, err = c.Do(req) - if err != nil { - t.Error(err) - } -} diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/token_test.go b/Godeps/_workspace/src/golang.org/x/oauth2/token_test.go deleted file mode 100644 index 739eeb2a2..000000000 --- a/Godeps/_workspace/src/golang.org/x/oauth2/token_test.go +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright 2014 The oauth2 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 oauth2 - -import ( - "testing" - "time" -) - -func TestTokenExtra(t *testing.T) { - type testCase struct { - key string - val interface{} - want interface{} - } - const key = "extra-key" - cases := []testCase{ - {key: key, val: "abc", want: "abc"}, - {key: key, val: 123, want: 123}, - {key: key, val: "", want: ""}, - {key: "other-key", val: "def", want: nil}, - } - for _, tc := range cases { - extra := make(map[string]interface{}) - extra[tc.key] = tc.val - tok := &Token{raw: extra} - if got, want := tok.Extra(key), tc.want; got != want { - t.Errorf("Extra(%q) = %q; want %q", key, got, want) - } - } -} - -func TestTokenExpiry(t *testing.T) { - now := time.Now() - cases := []struct { - name string - tok *Token - want bool - }{ - {name: "12 seconds", tok: &Token{Expiry: now.Add(12 * time.Second)}, want: false}, - {name: "10 seconds", tok: &Token{Expiry: now.Add(expiryDelta)}, want: true}, - } - for _, tc := range cases { - if got, want := tc.tok.expired(), tc.want; got != want { - t.Errorf("expired (%q) = %v; want %v", tc.name, got, want) - } - } -} diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/transport_test.go b/Godeps/_workspace/src/golang.org/x/oauth2/transport_test.go deleted file mode 100644 index 35cb25ed5..000000000 --- a/Godeps/_workspace/src/golang.org/x/oauth2/transport_test.go +++ /dev/null @@ -1,86 +0,0 @@ -package oauth2 - -import ( - "net/http" - "net/http/httptest" - "testing" - "time" -) - -type tokenSource struct{ token *Token } - -func (t *tokenSource) Token() (*Token, error) { - return t.token, nil -} - -func TestTransportTokenSource(t *testing.T) { - ts := &tokenSource{ - token: &Token{ - AccessToken: "abc", - }, - } - tr := &Transport{ - Source: ts, - } - server := newMockServer(func(w http.ResponseWriter, r *http.Request) { - if r.Header.Get("Authorization") != "Bearer abc" { - t.Errorf("Transport doesn't set the Authorization header from the fetched token") - } - }) - defer server.Close() - client := http.Client{Transport: tr} - client.Get(server.URL) -} - -// Test for case-sensitive token types, per https://github.com/golang/oauth2/issues/113 -func TestTransportTokenSourceTypes(t *testing.T) { - const val = "abc" - tests := []struct { - key string - val string - want string - }{ - {key: "bearer", val: val, want: "Bearer abc"}, - {key: "mac", val: val, want: "MAC abc"}, - {key: "basic", val: val, want: "Basic abc"}, - } - for _, tc := range tests { - ts := &tokenSource{ - token: &Token{ - AccessToken: tc.val, - TokenType: tc.key, - }, - } - tr := &Transport{ - Source: ts, - } - server := newMockServer(func(w http.ResponseWriter, r *http.Request) { - if got, want := r.Header.Get("Authorization"), tc.want; got != want { - t.Errorf("Authorization header (%q) = %q; want %q", val, got, want) - } - }) - defer server.Close() - client := http.Client{Transport: tr} - client.Get(server.URL) - } -} - -func TestTokenValidNoAccessToken(t *testing.T) { - token := &Token{} - if token.Valid() { - t.Errorf("Token should not be valid with no access token") - } -} - -func TestExpiredWithExpiry(t *testing.T) { - token := &Token{ - Expiry: time.Now().Add(-5 * time.Hour), - } - if token.Valid() { - t.Errorf("Token should not be valid if it expired in the past") - } -} - -func newMockServer(handler func(w http.ResponseWriter, r *http.Request)) *httptest.Server { - return httptest.NewServer(http.HandlerFunc(handler)) -} diff --git a/Godeps/_workspace/src/gopkg.in/asn1-ber.v1/ber_test.go b/Godeps/_workspace/src/gopkg.in/asn1-ber.v1/ber_test.go deleted file mode 100644 index ccf490688..000000000 --- a/Godeps/_workspace/src/gopkg.in/asn1-ber.v1/ber_test.go +++ /dev/null @@ -1,158 +0,0 @@ -package ber - -import ( - "bytes" - - "io" - "testing" -) - -func TestEncodeDecodeInteger(t *testing.T) { - for _, v := range []int64{0, 10, 128, 1024, -1, -100, -128, -1024} { - enc := encodeInteger(v) - dec, err := parseInt64(enc) - if err != nil { - t.Fatalf("Error decoding %d : %s", v, err) - } - if v != dec { - t.Error("TestEncodeDecodeInteger failed for %d (got %d)", v, dec) - } - - } -} - -func TestBoolean(t *testing.T) { - var value bool = true - - packet := NewBoolean(ClassUniversal, TypePrimitive, TagBoolean, value, "first Packet, True") - - newBoolean, ok := packet.Value.(bool) - if !ok || newBoolean != value { - t.Error("error during creating packet") - } - - encodedPacket := packet.Bytes() - - newPacket := DecodePacket(encodedPacket) - - newBoolean, ok = newPacket.Value.(bool) - if !ok || newBoolean != value { - t.Error("error during decoding packet") - } - -} - -func TestInteger(t *testing.T) { - var value int64 = 10 - - packet := NewInteger(ClassUniversal, TypePrimitive, TagInteger, value, "Integer, 10") - - { - newInteger, ok := packet.Value.(int64) - if !ok || newInteger != value { - t.Error("error creating packet") - } - } - - encodedPacket := packet.Bytes() - - newPacket := DecodePacket(encodedPacket) - - { - newInteger, ok := newPacket.Value.(int64) - if !ok || int64(newInteger) != value { - t.Error("error decoding packet") - } - } -} - -func TestString(t *testing.T) { - var value string = "Hic sunt dracones" - - packet := NewString(ClassUniversal, TypePrimitive, TagOctetString, value, "String") - - newValue, ok := packet.Value.(string) - if !ok || newValue != value { - t.Error("error during creating packet") - } - - encodedPacket := packet.Bytes() - - newPacket := DecodePacket(encodedPacket) - - newValue, ok = newPacket.Value.(string) - if !ok || newValue != value { - t.Error("error during decoding packet") - } - -} - -func TestSequenceAndAppendChild(t *testing.T) { - - p1 := NewString(ClassUniversal, TypePrimitive, TagOctetString, "HIC SVNT LEONES", "String") - p2 := NewString(ClassUniversal, TypePrimitive, TagOctetString, "HIC SVNT DRACONES", "String") - p3 := NewString(ClassUniversal, TypePrimitive, TagOctetString, "Terra Incognita", "String") - - sequence := NewSequence("a sequence") - sequence.AppendChild(p1) - sequence.AppendChild(p2) - sequence.AppendChild(p3) - - if len(sequence.Children) != 3 { - t.Error("wrong length for children array should be three =>", len(sequence.Children)) - } - - encodedSequence := sequence.Bytes() - - decodedSequence := DecodePacket(encodedSequence) - if len(decodedSequence.Children) != 3 { - t.Error("wrong length for children array should be three =>", len(decodedSequence.Children)) - } - -} - -func TestReadPacket(t *testing.T) { - packet := NewString(ClassUniversal, TypePrimitive, TagOctetString, "Ad impossibilia nemo tenetur", "string") - var buffer io.ReadWriter - buffer = new(bytes.Buffer) - - buffer.Write(packet.Bytes()) - - newPacket, err := ReadPacket(buffer) - if err != nil { - t.Error("error during ReadPacket", err) - } - newPacket.ByteValue = nil - if !bytes.Equal(newPacket.ByteValue, packet.ByteValue) { - t.Error("packets should be the same") - } -} - -func TestBinaryInteger(t *testing.T) { - // data src : http://luca.ntop.org/Teaching/Appunti/asn1.html 5.7 - var data = []struct { - v int64 - e []byte - }{ - {v: 0, e: []byte{0x02, 0x01, 0x00}}, - {v: 127, e: []byte{0x02, 0x01, 0x7F}}, - {v: 128, e: []byte{0x02, 0x02, 0x00, 0x80}}, - {v: 256, e: []byte{0x02, 0x02, 0x01, 0x00}}, - {v: -128, e: []byte{0x02, 0x01, 0x80}}, - {v: -129, e: []byte{0x02, 0x02, 0xFF, 0x7F}}, - } - - for _, d := range data { - if b := NewInteger(ClassUniversal, TypePrimitive, TagInteger, int64(d.v), "").Bytes(); !bytes.Equal(d.e, b) { - t.Errorf("Wrong binary generated for %d : got % X, expected % X", d.v, b, d.e) - } - } -} - -func TestBinaryOctetString(t *testing.T) { - // data src : http://luca.ntop.org/Teaching/Appunti/asn1.html 5.10 - - if !bytes.Equal([]byte{0x04, 0x08, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef}, NewString(ClassUniversal, TypePrimitive, TagOctetString, "\x01\x23\x45\x67\x89\xab\xcd\xef", "").Bytes()) { - t.Error("wrong binary generated") - } -} diff --git a/Godeps/_workspace/src/gopkg.in/inf.v0/LICENSE b/Godeps/_workspace/src/gopkg.in/inf.v0/LICENSE index efa1aa189..87a5cede3 100644 --- a/Godeps/_workspace/src/gopkg.in/inf.v0/LICENSE +++ b/Godeps/_workspace/src/gopkg.in/inf.v0/LICENSE @@ -1,34 +1,5 @@ -Copyright (c) 2012 Péter Surányi. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - -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. - ----------------------------------------------------------------------- -Portions of inf.Dec's source code have been derived from Go and are -covered by the following license: ----------------------------------------------------------------------- - -Copyright (c) 2009 The Go Authors. All rights reserved. +Copyright (c) 2012 Péter Surányi. Portions Copyright (c) 2009 The Go +Authors. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are diff --git a/Godeps/_workspace/src/gopkg.in/inf.v0/benchmark_test.go b/Godeps/_workspace/src/gopkg.in/inf.v0/benchmark_test.go deleted file mode 100644 index 27071da0e..000000000 --- a/Godeps/_workspace/src/gopkg.in/inf.v0/benchmark_test.go +++ /dev/null @@ -1,210 +0,0 @@ -package inf - -import ( - "fmt" - "math/big" - "math/rand" - "sync" - "testing" -) - -const maxcap = 1024 * 1024 -const bits = 256 -const maxscale = 32 - -var once sync.Once - -var decInput [][2]Dec -var intInput [][2]big.Int - -var initBench = func() { - decInput = make([][2]Dec, maxcap) - intInput = make([][2]big.Int, maxcap) - max := new(big.Int).Lsh(big.NewInt(1), bits) - r := rand.New(rand.NewSource(0)) - for i := 0; i < cap(decInput); i++ { - decInput[i][0].SetUnscaledBig(new(big.Int).Rand(r, max)). - SetScale(Scale(r.Int31n(int32(2*maxscale-1)) - int32(maxscale))) - decInput[i][1].SetUnscaledBig(new(big.Int).Rand(r, max)). - SetScale(Scale(r.Int31n(int32(2*maxscale-1)) - int32(maxscale))) - } - for i := 0; i < cap(intInput); i++ { - intInput[i][0].Rand(r, max) - intInput[i][1].Rand(r, max) - } -} - -func doBenchmarkDec1(b *testing.B, f func(z *Dec)) { - once.Do(initBench) - b.ResetTimer() - b.StartTimer() - for i := 0; i < b.N; i++ { - f(&decInput[i%maxcap][0]) - } -} - -func doBenchmarkDec2(b *testing.B, f func(x, y *Dec)) { - once.Do(initBench) - b.ResetTimer() - b.StartTimer() - for i := 0; i < b.N; i++ { - f(&decInput[i%maxcap][0], &decInput[i%maxcap][1]) - } -} - -func doBenchmarkInt1(b *testing.B, f func(z *big.Int)) { - once.Do(initBench) - b.ResetTimer() - b.StartTimer() - for i := 0; i < b.N; i++ { - f(&intInput[i%maxcap][0]) - } -} - -func doBenchmarkInt2(b *testing.B, f func(x, y *big.Int)) { - once.Do(initBench) - b.ResetTimer() - b.StartTimer() - for i := 0; i < b.N; i++ { - f(&intInput[i%maxcap][0], &intInput[i%maxcap][1]) - } -} - -func Benchmark_Dec_String(b *testing.B) { - doBenchmarkDec1(b, func(x *Dec) { - x.String() - }) -} - -func Benchmark_Dec_StringScan(b *testing.B) { - doBenchmarkDec1(b, func(x *Dec) { - s := x.String() - d := new(Dec) - fmt.Sscan(s, d) - }) -} - -func Benchmark_Dec_GobEncode(b *testing.B) { - doBenchmarkDec1(b, func(x *Dec) { - x.GobEncode() - }) -} - -func Benchmark_Dec_GobEnDecode(b *testing.B) { - doBenchmarkDec1(b, func(x *Dec) { - g, _ := x.GobEncode() - new(Dec).GobDecode(g) - }) -} - -func Benchmark_Dec_Add(b *testing.B) { - doBenchmarkDec2(b, func(x, y *Dec) { - ys := y.Scale() - y.SetScale(x.Scale()) - _ = new(Dec).Add(x, y) - y.SetScale(ys) - }) -} - -func Benchmark_Dec_AddMixed(b *testing.B) { - doBenchmarkDec2(b, func(x, y *Dec) { - _ = new(Dec).Add(x, y) - }) -} - -func Benchmark_Dec_Sub(b *testing.B) { - doBenchmarkDec2(b, func(x, y *Dec) { - ys := y.Scale() - y.SetScale(x.Scale()) - _ = new(Dec).Sub(x, y) - y.SetScale(ys) - }) -} - -func Benchmark_Dec_SubMixed(b *testing.B) { - doBenchmarkDec2(b, func(x, y *Dec) { - _ = new(Dec).Sub(x, y) - }) -} - -func Benchmark_Dec_Mul(b *testing.B) { - doBenchmarkDec2(b, func(x, y *Dec) { - _ = new(Dec).Mul(x, y) - }) -} - -func Benchmark_Dec_Mul_QuoExact(b *testing.B) { - doBenchmarkDec2(b, func(x, y *Dec) { - v := new(Dec).Mul(x, y) - _ = new(Dec).QuoExact(v, y) - }) -} - -func Benchmark_Dec_QuoRound_Fixed_Down(b *testing.B) { - doBenchmarkDec2(b, func(x, y *Dec) { - _ = new(Dec).QuoRound(x, y, 0, RoundDown) - }) -} - -func Benchmark_Dec_QuoRound_Fixed_HalfUp(b *testing.B) { - doBenchmarkDec2(b, func(x, y *Dec) { - _ = new(Dec).QuoRound(x, y, 0, RoundHalfUp) - }) -} - -func Benchmark_Int_String(b *testing.B) { - doBenchmarkInt1(b, func(x *big.Int) { - x.String() - }) -} - -func Benchmark_Int_StringScan(b *testing.B) { - doBenchmarkInt1(b, func(x *big.Int) { - s := x.String() - d := new(big.Int) - fmt.Sscan(s, d) - }) -} - -func Benchmark_Int_GobEncode(b *testing.B) { - doBenchmarkInt1(b, func(x *big.Int) { - x.GobEncode() - }) -} - -func Benchmark_Int_GobEnDecode(b *testing.B) { - doBenchmarkInt1(b, func(x *big.Int) { - g, _ := x.GobEncode() - new(big.Int).GobDecode(g) - }) -} - -func Benchmark_Int_Add(b *testing.B) { - doBenchmarkInt2(b, func(x, y *big.Int) { - _ = new(big.Int).Add(x, y) - }) -} - -func Benchmark_Int_Sub(b *testing.B) { - doBenchmarkInt2(b, func(x, y *big.Int) { - _ = new(big.Int).Sub(x, y) - }) -} - -func Benchmark_Int_Mul(b *testing.B) { - doBenchmarkInt2(b, func(x, y *big.Int) { - _ = new(big.Int).Mul(x, y) - }) -} - -func Benchmark_Int_Quo(b *testing.B) { - doBenchmarkInt2(b, func(x, y *big.Int) { - _ = new(big.Int).Quo(x, y) - }) -} - -func Benchmark_Int_QuoRem(b *testing.B) { - doBenchmarkInt2(b, func(x, y *big.Int) { - _, _ = new(big.Int).QuoRem(x, y, new(big.Int)) - }) -} diff --git a/Godeps/_workspace/src/gopkg.in/inf.v0/dec_go1_2_test.go b/Godeps/_workspace/src/gopkg.in/inf.v0/dec_go1_2_test.go deleted file mode 100644 index 5df0f7b55..000000000 --- a/Godeps/_workspace/src/gopkg.in/inf.v0/dec_go1_2_test.go +++ /dev/null @@ -1,33 +0,0 @@ -// +build go1.2 - -package inf - -import ( - "encoding" - "encoding/json" - "testing" -) - -var _ encoding.TextMarshaler = new(Dec) -var _ encoding.TextUnmarshaler = new(Dec) - -type Obj struct { - Val *Dec -} - -func TestDecJsonMarshalUnmarshal(t *testing.T) { - o := Obj{Val: NewDec(123, 2)} - js, err := json.Marshal(o) - if err != nil { - t.Fatalf("json.Marshal(%v): got %v, want ok", o, err) - } - o2 := &Obj{} - err = json.Unmarshal(js, o2) - if err != nil { - t.Fatalf("json.Unmarshal(%#q): got %v, want ok", js, err) - } - if o.Val.Scale() != o2.Val.Scale() || - o.Val.UnscaledBig().Cmp(o2.Val.UnscaledBig()) != 0 { - t.Fatalf("json.Unmarshal(json.Marshal(%v)): want %v, got %v", o, o, o2) - } -} diff --git a/Godeps/_workspace/src/gopkg.in/inf.v0/dec_internal_test.go b/Godeps/_workspace/src/gopkg.in/inf.v0/dec_internal_test.go deleted file mode 100644 index d4fbe3e5b..000000000 --- a/Godeps/_workspace/src/gopkg.in/inf.v0/dec_internal_test.go +++ /dev/null @@ -1,40 +0,0 @@ -package inf - -import ( - "math/big" - "testing" -) - -var decQuoRemZZZ = []struct { - z, x, y *Dec - r *big.Rat - srA, srB int -}{ - // basic examples - {NewDec(1, 0), NewDec(2, 0), NewDec(2, 0), big.NewRat(0, 1), 0, 1}, - {NewDec(15, 1), NewDec(3, 0), NewDec(2, 0), big.NewRat(0, 1), 0, 1}, - {NewDec(1, 1), NewDec(1, 0), NewDec(10, 0), big.NewRat(0, 1), 0, 1}, - {NewDec(0, 0), NewDec(2, 0), NewDec(3, 0), big.NewRat(2, 3), 1, 1}, - {NewDec(0, 0), NewDec(2, 0), NewDec(6, 0), big.NewRat(1, 3), 1, 1}, - {NewDec(1, 1), NewDec(2, 0), NewDec(12, 0), big.NewRat(2, 3), 1, 1}, - - // examples from the Go Language Specification - {NewDec(1, 0), NewDec(5, 0), NewDec(3, 0), big.NewRat(2, 3), 1, 1}, - {NewDec(-1, 0), NewDec(-5, 0), NewDec(3, 0), big.NewRat(-2, 3), -1, 1}, - {NewDec(-1, 0), NewDec(5, 0), NewDec(-3, 0), big.NewRat(-2, 3), 1, -1}, - {NewDec(1, 0), NewDec(-5, 0), NewDec(-3, 0), big.NewRat(2, 3), -1, -1}, -} - -func TestDecQuoRem(t *testing.T) { - for i, a := range decQuoRemZZZ { - z, rA, rB := new(Dec), new(big.Int), new(big.Int) - s := scaleQuoExact{}.Scale(a.x, a.y) - z.quoRem(a.x, a.y, s, true, rA, rB) - if a.z.Cmp(z) != 0 || a.r.Cmp(new(big.Rat).SetFrac(rA, rB)) != 0 { - t.Errorf("#%d QuoRemZZZ got %v, %v, %v; expected %v, %v", i, z, rA, rB, a.z, a.r) - } - if a.srA != rA.Sign() || a.srB != rB.Sign() { - t.Errorf("#%d QuoRemZZZ wrong signs, got %v, %v; expected %v, %v", i, rA.Sign(), rB.Sign(), a.srA, a.srB) - } - } -} diff --git a/Godeps/_workspace/src/gopkg.in/inf.v0/dec_test.go b/Godeps/_workspace/src/gopkg.in/inf.v0/dec_test.go deleted file mode 100644 index e4b09b3fd..000000000 --- a/Godeps/_workspace/src/gopkg.in/inf.v0/dec_test.go +++ /dev/null @@ -1,379 +0,0 @@ -package inf_test - -import ( - "bytes" - "encoding/gob" - "fmt" - "math/big" - "strings" - "testing" - - "gopkg.in/inf.v0" -) - -type decFunZZ func(z, x, y *inf.Dec) *inf.Dec -type decArgZZ struct { - z, x, y *inf.Dec -} - -var decSumZZ = []decArgZZ{ - {inf.NewDec(0, 0), inf.NewDec(0, 0), inf.NewDec(0, 0)}, - {inf.NewDec(1, 0), inf.NewDec(1, 0), inf.NewDec(0, 0)}, - {inf.NewDec(1111111110, 0), inf.NewDec(123456789, 0), inf.NewDec(987654321, 0)}, - {inf.NewDec(-1, 0), inf.NewDec(-1, 0), inf.NewDec(0, 0)}, - {inf.NewDec(864197532, 0), inf.NewDec(-123456789, 0), inf.NewDec(987654321, 0)}, - {inf.NewDec(-1111111110, 0), inf.NewDec(-123456789, 0), inf.NewDec(-987654321, 0)}, - {inf.NewDec(12, 2), inf.NewDec(1, 1), inf.NewDec(2, 2)}, -} - -var decProdZZ = []decArgZZ{ - {inf.NewDec(0, 0), inf.NewDec(0, 0), inf.NewDec(0, 0)}, - {inf.NewDec(0, 0), inf.NewDec(1, 0), inf.NewDec(0, 0)}, - {inf.NewDec(1, 0), inf.NewDec(1, 0), inf.NewDec(1, 0)}, - {inf.NewDec(-991*991, 0), inf.NewDec(991, 0), inf.NewDec(-991, 0)}, - {inf.NewDec(2, 3), inf.NewDec(1, 1), inf.NewDec(2, 2)}, - {inf.NewDec(2, -3), inf.NewDec(1, -1), inf.NewDec(2, -2)}, - {inf.NewDec(2, 3), inf.NewDec(1, 1), inf.NewDec(2, 2)}, -} - -func TestDecSignZ(t *testing.T) { - var zero inf.Dec - for _, a := range decSumZZ { - s := a.z.Sign() - e := a.z.Cmp(&zero) - if s != e { - t.Errorf("got %d; want %d for z = %v", s, e, a.z) - } - } -} - -func TestDecAbsZ(t *testing.T) { - var zero inf.Dec - for _, a := range decSumZZ { - var z inf.Dec - z.Abs(a.z) - var e inf.Dec - e.Set(a.z) - if e.Cmp(&zero) < 0 { - e.Sub(&zero, &e) - } - if z.Cmp(&e) != 0 { - t.Errorf("got z = %v; want %v", z, e) - } - } -} - -func testDecFunZZ(t *testing.T, msg string, f decFunZZ, a decArgZZ) { - var z inf.Dec - f(&z, a.x, a.y) - if (&z).Cmp(a.z) != 0 { - t.Errorf("%s%+v\n\tgot z = %v; want %v", msg, a, &z, a.z) - } -} - -func TestDecSumZZ(t *testing.T) { - AddZZ := func(z, x, y *inf.Dec) *inf.Dec { return z.Add(x, y) } - SubZZ := func(z, x, y *inf.Dec) *inf.Dec { return z.Sub(x, y) } - for _, a := range decSumZZ { - arg := a - testDecFunZZ(t, "AddZZ", AddZZ, arg) - - arg = decArgZZ{a.z, a.y, a.x} - testDecFunZZ(t, "AddZZ symmetric", AddZZ, arg) - - arg = decArgZZ{a.x, a.z, a.y} - testDecFunZZ(t, "SubZZ", SubZZ, arg) - - arg = decArgZZ{a.y, a.z, a.x} - testDecFunZZ(t, "SubZZ symmetric", SubZZ, arg) - } -} - -func TestDecProdZZ(t *testing.T) { - MulZZ := func(z, x, y *inf.Dec) *inf.Dec { return z.Mul(x, y) } - for _, a := range decProdZZ { - arg := a - testDecFunZZ(t, "MulZZ", MulZZ, arg) - - arg = decArgZZ{a.z, a.y, a.x} - testDecFunZZ(t, "MulZZ symmetric", MulZZ, arg) - } -} - -var decUnscaledTests = []struct { - d *inf.Dec - u int64 // ignored when ok == false - ok bool -}{ - {new(inf.Dec), 0, true}, - {inf.NewDec(-1<<63, 0), -1 << 63, true}, - {inf.NewDec(-(-1<<63 + 1), 0), -(-1<<63 + 1), true}, - {new(inf.Dec).Neg(inf.NewDec(-1<<63, 0)), 0, false}, - {new(inf.Dec).Sub(inf.NewDec(-1<<63, 0), inf.NewDec(1, 0)), 0, false}, - {inf.NewDecBig(new(big.Int).Lsh(big.NewInt(1), 64), 0), 0, false}, -} - -func TestDecUnscaled(t *testing.T) { - for i, tt := range decUnscaledTests { - u, ok := tt.d.Unscaled() - if ok != tt.ok { - t.Errorf("#%d Unscaled: got %v, expected %v", i, ok, tt.ok) - } else if ok && u != tt.u { - t.Errorf("#%d Unscaled: got %v, expected %v", i, u, tt.u) - } - } -} - -var decRoundTests = [...]struct { - in *inf.Dec - s inf.Scale - r inf.Rounder - exp *inf.Dec -}{ - {inf.NewDec(123424999999999993, 15), 2, inf.RoundHalfUp, inf.NewDec(12342, 2)}, - {inf.NewDec(123425000000000001, 15), 2, inf.RoundHalfUp, inf.NewDec(12343, 2)}, - {inf.NewDec(123424999999999993, 15), 15, inf.RoundHalfUp, inf.NewDec(123424999999999993, 15)}, - {inf.NewDec(123424999999999993, 15), 16, inf.RoundHalfUp, inf.NewDec(1234249999999999930, 16)}, - {inf.NewDecBig(new(big.Int).Lsh(big.NewInt(1), 64), 0), -1, inf.RoundHalfUp, inf.NewDec(1844674407370955162, -1)}, - {inf.NewDecBig(new(big.Int).Lsh(big.NewInt(1), 64), 0), -2, inf.RoundHalfUp, inf.NewDec(184467440737095516, -2)}, - {inf.NewDecBig(new(big.Int).Lsh(big.NewInt(1), 64), 0), -3, inf.RoundHalfUp, inf.NewDec(18446744073709552, -3)}, - {inf.NewDecBig(new(big.Int).Lsh(big.NewInt(1), 64), 0), -4, inf.RoundHalfUp, inf.NewDec(1844674407370955, -4)}, - {inf.NewDecBig(new(big.Int).Lsh(big.NewInt(1), 64), 0), -5, inf.RoundHalfUp, inf.NewDec(184467440737096, -5)}, - {inf.NewDecBig(new(big.Int).Lsh(big.NewInt(1), 64), 0), -6, inf.RoundHalfUp, inf.NewDec(18446744073710, -6)}, -} - -func TestDecRound(t *testing.T) { - for i, tt := range decRoundTests { - z := new(inf.Dec).Round(tt.in, tt.s, tt.r) - if tt.exp.Cmp(z) != 0 { - t.Errorf("#%d Round got %v; expected %v", i, z, tt.exp) - } - } -} - -var decStringTests = []struct { - in string - out string - val int64 - scale inf.Scale // skip SetString if negative - ok bool - scanOk bool -}{ - {in: "", ok: false, scanOk: false}, - {in: "a", ok: false, scanOk: false}, - {in: "z", ok: false, scanOk: false}, - {in: "+", ok: false, scanOk: false}, - {in: "-", ok: false, scanOk: false}, - {in: "g", ok: false, scanOk: false}, - {in: ".", ok: false, scanOk: false}, - {in: ".-0", ok: false, scanOk: false}, - {in: ".+0", ok: false, scanOk: false}, - // Scannable but not SetStringable - {"0b", "ignored", 0, 0, false, true}, - {"0x", "ignored", 0, 0, false, true}, - {"0xg", "ignored", 0, 0, false, true}, - {"0.0g", "ignored", 0, 1, false, true}, - // examples from godoc for Dec - {"0", "0", 0, 0, true, true}, - {"0.00", "0.00", 0, 2, true, true}, - {"ignored", "0", 0, -2, true, false}, - {"1", "1", 1, 0, true, true}, - {"1.00", "1.00", 100, 2, true, true}, - {"10", "10", 10, 0, true, true}, - {"ignored", "10", 1, -1, true, false}, - // other tests - {"+0", "0", 0, 0, true, true}, - {"-0", "0", 0, 0, true, true}, - {"0.0", "0.0", 0, 1, true, true}, - {"0.1", "0.1", 1, 1, true, true}, - {"0.", "0", 0, 0, true, true}, - {"-10", "-10", -1, -1, true, true}, - {"-1", "-1", -1, 0, true, true}, - {"-0.1", "-0.1", -1, 1, true, true}, - {"-0.01", "-0.01", -1, 2, true, true}, - {"+0.", "0", 0, 0, true, true}, - {"-0.", "0", 0, 0, true, true}, - {".0", "0.0", 0, 1, true, true}, - {"+.0", "0.0", 0, 1, true, true}, - {"-.0", "0.0", 0, 1, true, true}, - {"0.0000000000", "0.0000000000", 0, 10, true, true}, - {"0.0000000001", "0.0000000001", 1, 10, true, true}, - {"-0.0000000000", "0.0000000000", 0, 10, true, true}, - {"-0.0000000001", "-0.0000000001", -1, 10, true, true}, - {"-10", "-10", -10, 0, true, true}, - {"+10", "10", 10, 0, true, true}, - {"00", "0", 0, 0, true, true}, - {"023", "23", 23, 0, true, true}, // decimal, not octal - {"-02.3", "-2.3", -23, 1, true, true}, // decimal, not octal -} - -func TestDecGetString(t *testing.T) { - z := new(inf.Dec) - for i, test := range decStringTests { - if !test.ok { - continue - } - z.SetUnscaled(test.val) - z.SetScale(test.scale) - - s := z.String() - if s != test.out { - t.Errorf("#%da got %s; want %s", i, s, test.out) - } - - s = fmt.Sprintf("%d", z) - if s != test.out { - t.Errorf("#%db got %s; want %s", i, s, test.out) - } - } -} - -func TestDecSetString(t *testing.T) { - tmp := new(inf.Dec) - for i, test := range decStringTests { - if test.scale < 0 { - // SetString only supports scale >= 0 - continue - } - // initialize to a non-zero value so that issues with parsing - // 0 are detected - tmp.Set(inf.NewDec(1234567890, 123)) - n1, ok1 := new(inf.Dec).SetString(test.in) - n2, ok2 := tmp.SetString(test.in) - expected := inf.NewDec(test.val, test.scale) - if ok1 != test.ok || ok2 != test.ok { - t.Errorf("#%d (input '%s') ok incorrect (should be %t)", i, test.in, test.ok) - continue - } - if !ok1 { - if n1 != nil { - t.Errorf("#%d (input '%s') n1 != nil", i, test.in) - } - continue - } - if !ok2 { - if n2 != nil { - t.Errorf("#%d (input '%s') n2 != nil", i, test.in) - } - continue - } - - if n1.Cmp(expected) != 0 { - t.Errorf("#%d (input '%s') got: %s want: %d", i, test.in, n1, test.val) - } - if n2.Cmp(expected) != 0 { - t.Errorf("#%d (input '%s') got: %s want: %d", i, test.in, n2, test.val) - } - } -} - -func TestDecScan(t *testing.T) { - tmp := new(inf.Dec) - for i, test := range decStringTests { - if test.scale < 0 { - // SetString only supports scale >= 0 - continue - } - // initialize to a non-zero value so that issues with parsing - // 0 are detected - tmp.Set(inf.NewDec(1234567890, 123)) - n1, n2 := new(inf.Dec), tmp - nn1, err1 := fmt.Sscan(test.in, n1) - nn2, err2 := fmt.Sscan(test.in, n2) - if !test.scanOk { - if err1 == nil || err2 == nil { - t.Errorf("#%d (input '%s') ok incorrect, should be %t", i, test.in, test.scanOk) - } - continue - } - expected := inf.NewDec(test.val, test.scale) - if nn1 != 1 || err1 != nil || nn2 != 1 || err2 != nil { - t.Errorf("#%d (input '%s') error %d %v, %d %v", i, test.in, nn1, err1, nn2, err2) - continue - } - if n1.Cmp(expected) != 0 { - t.Errorf("#%d (input '%s') got: %s want: %d", i, test.in, n1, test.val) - } - if n2.Cmp(expected) != 0 { - t.Errorf("#%d (input '%s') got: %s want: %d", i, test.in, n2, test.val) - } - } -} - -var decScanNextTests = []struct { - in string - ok bool - next rune -}{ - {"", false, 0}, - {"a", false, 'a'}, - {"z", false, 'z'}, - {"+", false, 0}, - {"-", false, 0}, - {"g", false, 'g'}, - {".", false, 0}, - {".-0", false, '-'}, - {".+0", false, '+'}, - {"0b", true, 'b'}, - {"0x", true, 'x'}, - {"0xg", true, 'x'}, - {"0.0g", true, 'g'}, -} - -func TestDecScanNext(t *testing.T) { - for i, test := range decScanNextTests { - rdr := strings.NewReader(test.in) - n1 := new(inf.Dec) - nn1, _ := fmt.Fscan(rdr, n1) - if (test.ok && nn1 == 0) || (!test.ok && nn1 > 0) { - t.Errorf("#%d (input '%s') ok incorrect should be %t", i, test.in, test.ok) - continue - } - r := rune(0) - nn2, err := fmt.Fscanf(rdr, "%c", &r) - if test.next != r { - t.Errorf("#%d (input '%s') next incorrect, got %c should be %c, %d, %v", i, test.in, r, test.next, nn2, err) - } - } -} - -var decGobEncodingTests = []string{ - "0", - "1", - "2", - "10", - "42", - "1234567890", - "298472983472983471903246121093472394872319615612417471234712061", -} - -func TestDecGobEncoding(t *testing.T) { - var medium bytes.Buffer - enc := gob.NewEncoder(&medium) - dec := gob.NewDecoder(&medium) - for i, test := range decGobEncodingTests { - for j := 0; j < 2; j++ { - for k := inf.Scale(-5); k <= 5; k++ { - medium.Reset() // empty buffer for each test case (in case of failures) - stest := test - if j != 0 { - // negative numbers - stest = "-" + test - } - var tx inf.Dec - tx.SetString(stest) - tx.SetScale(k) // test with positive, negative, and zero scale - if err := enc.Encode(&tx); err != nil { - t.Errorf("#%d%c: encoding failed: %s", i, 'a'+j, err) - } - var rx inf.Dec - if err := dec.Decode(&rx); err != nil { - t.Errorf("#%d%c: decoding failed: %s", i, 'a'+j, err) - } - if rx.Cmp(&tx) != 0 { - t.Errorf("#%d%c: transmission failed: got %s want %s", i, 'a'+j, &rx, &tx) - } - } - } - } -} diff --git a/Godeps/_workspace/src/gopkg.in/inf.v0/example_test.go b/Godeps/_workspace/src/gopkg.in/inf.v0/example_test.go deleted file mode 100644 index fa1e54d16..000000000 --- a/Godeps/_workspace/src/gopkg.in/inf.v0/example_test.go +++ /dev/null @@ -1,62 +0,0 @@ -package inf_test - -import ( - "fmt" - "log" -) - -import "gopkg.in/inf.v0" - -func ExampleDec_SetString() { - d := new(inf.Dec) - d.SetString("012345.67890") // decimal; leading 0 ignored; trailing 0 kept - fmt.Println(d) - // Output: 12345.67890 -} - -func ExampleDec_Scan() { - // The Scan function is rarely used directly; - // the fmt package recognizes it as an implementation of fmt.Scanner. - d := new(inf.Dec) - _, err := fmt.Sscan("184467440.73709551617", d) - if err != nil { - log.Println("error scanning value:", err) - } else { - fmt.Println(d) - } - // Output: 184467440.73709551617 -} - -func ExampleDec_QuoRound_scale2RoundDown() { - // 10 / 3 is an infinite decimal; it has no exact Dec representation - x, y := inf.NewDec(10, 0), inf.NewDec(3, 0) - // use 2 digits beyond the decimal point, round towards 0 - z := new(inf.Dec).QuoRound(x, y, 2, inf.RoundDown) - fmt.Println(z) - // Output: 3.33 -} - -func ExampleDec_QuoRound_scale2RoundCeil() { - // -42 / 400 is an finite decimal with 3 digits beyond the decimal point - x, y := inf.NewDec(-42, 0), inf.NewDec(400, 0) - // use 2 digits beyond decimal point, round towards positive infinity - z := new(inf.Dec).QuoRound(x, y, 2, inf.RoundCeil) - fmt.Println(z) - // Output: -0.10 -} - -func ExampleDec_QuoExact_ok() { - // 1 / 25 is a finite decimal; it has exact Dec representation - x, y := inf.NewDec(1, 0), inf.NewDec(25, 0) - z := new(inf.Dec).QuoExact(x, y) - fmt.Println(z) - // Output: 0.04 -} - -func ExampleDec_QuoExact_fail() { - // 1 / 3 is an infinite decimal; it has no exact Dec representation - x, y := inf.NewDec(1, 0), inf.NewDec(3, 0) - z := new(inf.Dec).QuoExact(x, y) - fmt.Println(z) - // Output: -} diff --git a/Godeps/_workspace/src/gopkg.in/inf.v0/rounder_example_test.go b/Godeps/_workspace/src/gopkg.in/inf.v0/rounder_example_test.go deleted file mode 100644 index 803c1d7ee..000000000 --- a/Godeps/_workspace/src/gopkg.in/inf.v0/rounder_example_test.go +++ /dev/null @@ -1,72 +0,0 @@ -package inf_test - -import ( - "fmt" - "os" - "text/tabwriter" - - "gopkg.in/inf.v0" -) - -// This example displays the results of Dec.Round with each of the Rounders. -// -func ExampleRounder() { - var vals = []struct { - x string - s inf.Scale - }{ - {"-0.18", 1}, {"-0.15", 1}, {"-0.12", 1}, {"-0.10", 1}, - {"-0.08", 1}, {"-0.05", 1}, {"-0.02", 1}, {"0.00", 1}, - {"0.02", 1}, {"0.05", 1}, {"0.08", 1}, {"0.10", 1}, - {"0.12", 1}, {"0.15", 1}, {"0.18", 1}, - } - - var rounders = []struct { - name string - rounder inf.Rounder - }{ - {"RoundDown", inf.RoundDown}, {"RoundUp", inf.RoundUp}, - {"RoundCeil", inf.RoundCeil}, {"RoundFloor", inf.RoundFloor}, - {"RoundHalfDown", inf.RoundHalfDown}, {"RoundHalfUp", inf.RoundHalfUp}, - {"RoundHalfEven", inf.RoundHalfEven}, {"RoundExact", inf.RoundExact}, - } - - fmt.Println("The results of new(inf.Dec).Round(x, s, inf.RoundXXX):\n") - w := tabwriter.NewWriter(os.Stdout, 0, 0, 1, ' ', tabwriter.AlignRight) - fmt.Fprint(w, "x\ts\t|\t") - for _, r := range rounders { - fmt.Fprintf(w, "%s\t", r.name[5:]) - } - fmt.Fprintln(w) - for _, v := range vals { - fmt.Fprintf(w, "%s\t%d\t|\t", v.x, v.s) - for _, r := range rounders { - x, _ := new(inf.Dec).SetString(v.x) - z := new(inf.Dec).Round(x, v.s, r.rounder) - fmt.Fprintf(w, "%d\t", z) - } - fmt.Fprintln(w) - } - w.Flush() - - // Output: - // The results of new(inf.Dec).Round(x, s, inf.RoundXXX): - // - // x s | Down Up Ceil Floor HalfDown HalfUp HalfEven Exact - // -0.18 1 | -0.1 -0.2 -0.1 -0.2 -0.2 -0.2 -0.2 - // -0.15 1 | -0.1 -0.2 -0.1 -0.2 -0.1 -0.2 -0.2 - // -0.12 1 | -0.1 -0.2 -0.1 -0.2 -0.1 -0.1 -0.1 - // -0.10 1 | -0.1 -0.1 -0.1 -0.1 -0.1 -0.1 -0.1 -0.1 - // -0.08 1 | 0.0 -0.1 0.0 -0.1 -0.1 -0.1 -0.1 - // -0.05 1 | 0.0 -0.1 0.0 -0.1 0.0 -0.1 0.0 - // -0.02 1 | 0.0 -0.1 0.0 -0.1 0.0 0.0 0.0 - // 0.00 1 | 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 - // 0.02 1 | 0.0 0.1 0.1 0.0 0.0 0.0 0.0 - // 0.05 1 | 0.0 0.1 0.1 0.0 0.0 0.1 0.0 - // 0.08 1 | 0.0 0.1 0.1 0.0 0.1 0.1 0.1 - // 0.10 1 | 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 - // 0.12 1 | 0.1 0.2 0.2 0.1 0.1 0.1 0.1 - // 0.15 1 | 0.1 0.2 0.2 0.1 0.1 0.2 0.2 - // 0.18 1 | 0.1 0.2 0.2 0.1 0.2 0.2 0.2 - -} diff --git a/Godeps/_workspace/src/gopkg.in/inf.v0/rounder_test.go b/Godeps/_workspace/src/gopkg.in/inf.v0/rounder_test.go deleted file mode 100644 index d7e14c58c..000000000 --- a/Godeps/_workspace/src/gopkg.in/inf.v0/rounder_test.go +++ /dev/null @@ -1,109 +0,0 @@ -package inf_test - -import ( - "math/big" - "testing" - - "gopkg.in/inf.v0" -) - -var decRounderInputs = [...]struct { - quo *inf.Dec - rA, rB *big.Int -}{ - // examples from go language spec - {inf.NewDec(1, 0), big.NewInt(2), big.NewInt(3)}, // 5 / 3 - {inf.NewDec(-1, 0), big.NewInt(-2), big.NewInt(3)}, // -5 / 3 - {inf.NewDec(-1, 0), big.NewInt(2), big.NewInt(-3)}, // 5 / -3 - {inf.NewDec(1, 0), big.NewInt(-2), big.NewInt(-3)}, // -5 / -3 - // examples from godoc - {inf.NewDec(-1, 1), big.NewInt(-8), big.NewInt(10)}, - {inf.NewDec(-1, 1), big.NewInt(-5), big.NewInt(10)}, - {inf.NewDec(-1, 1), big.NewInt(-2), big.NewInt(10)}, - {inf.NewDec(0, 1), big.NewInt(-8), big.NewInt(10)}, - {inf.NewDec(0, 1), big.NewInt(-5), big.NewInt(10)}, - {inf.NewDec(0, 1), big.NewInt(-2), big.NewInt(10)}, - {inf.NewDec(0, 1), big.NewInt(0), big.NewInt(1)}, - {inf.NewDec(0, 1), big.NewInt(2), big.NewInt(10)}, - {inf.NewDec(0, 1), big.NewInt(5), big.NewInt(10)}, - {inf.NewDec(0, 1), big.NewInt(8), big.NewInt(10)}, - {inf.NewDec(1, 1), big.NewInt(2), big.NewInt(10)}, - {inf.NewDec(1, 1), big.NewInt(5), big.NewInt(10)}, - {inf.NewDec(1, 1), big.NewInt(8), big.NewInt(10)}, -} - -var decRounderResults = [...]struct { - rounder inf.Rounder - results [len(decRounderInputs)]*inf.Dec -}{ - {inf.RoundExact, [...]*inf.Dec{nil, nil, nil, nil, - nil, nil, nil, nil, nil, nil, - inf.NewDec(0, 1), nil, nil, nil, nil, nil, nil}}, - {inf.RoundDown, [...]*inf.Dec{ - inf.NewDec(1, 0), inf.NewDec(-1, 0), inf.NewDec(-1, 0), inf.NewDec(1, 0), - inf.NewDec(-1, 1), inf.NewDec(-1, 1), inf.NewDec(-1, 1), - inf.NewDec(0, 1), inf.NewDec(0, 1), inf.NewDec(0, 1), - inf.NewDec(0, 1), - inf.NewDec(0, 1), inf.NewDec(0, 1), inf.NewDec(0, 1), - inf.NewDec(1, 1), inf.NewDec(1, 1), inf.NewDec(1, 1)}}, - {inf.RoundUp, [...]*inf.Dec{ - inf.NewDec(2, 0), inf.NewDec(-2, 0), inf.NewDec(-2, 0), inf.NewDec(2, 0), - inf.NewDec(-2, 1), inf.NewDec(-2, 1), inf.NewDec(-2, 1), - inf.NewDec(-1, 1), inf.NewDec(-1, 1), inf.NewDec(-1, 1), - inf.NewDec(0, 1), - inf.NewDec(1, 1), inf.NewDec(1, 1), inf.NewDec(1, 1), - inf.NewDec(2, 1), inf.NewDec(2, 1), inf.NewDec(2, 1)}}, - {inf.RoundHalfDown, [...]*inf.Dec{ - inf.NewDec(2, 0), inf.NewDec(-2, 0), inf.NewDec(-2, 0), inf.NewDec(2, 0), - inf.NewDec(-2, 1), inf.NewDec(-1, 1), inf.NewDec(-1, 1), - inf.NewDec(-1, 1), inf.NewDec(0, 1), inf.NewDec(0, 1), - inf.NewDec(0, 1), - inf.NewDec(0, 1), inf.NewDec(0, 1), inf.NewDec(1, 1), - inf.NewDec(1, 1), inf.NewDec(1, 1), inf.NewDec(2, 1)}}, - {inf.RoundHalfUp, [...]*inf.Dec{ - inf.NewDec(2, 0), inf.NewDec(-2, 0), inf.NewDec(-2, 0), inf.NewDec(2, 0), - inf.NewDec(-2, 1), inf.NewDec(-2, 1), inf.NewDec(-1, 1), - inf.NewDec(-1, 1), inf.NewDec(-1, 1), inf.NewDec(0, 1), - inf.NewDec(0, 1), - inf.NewDec(0, 1), inf.NewDec(1, 1), inf.NewDec(1, 1), - inf.NewDec(1, 1), inf.NewDec(2, 1), inf.NewDec(2, 1)}}, - {inf.RoundHalfEven, [...]*inf.Dec{ - inf.NewDec(2, 0), inf.NewDec(-2, 0), inf.NewDec(-2, 0), inf.NewDec(2, 0), - inf.NewDec(-2, 1), inf.NewDec(-2, 1), inf.NewDec(-1, 1), - inf.NewDec(-1, 1), inf.NewDec(0, 1), inf.NewDec(0, 1), - inf.NewDec(0, 1), - inf.NewDec(0, 1), inf.NewDec(0, 1), inf.NewDec(1, 1), - inf.NewDec(1, 1), inf.NewDec(2, 1), inf.NewDec(2, 1)}}, - {inf.RoundFloor, [...]*inf.Dec{ - inf.NewDec(1, 0), inf.NewDec(-2, 0), inf.NewDec(-2, 0), inf.NewDec(1, 0), - inf.NewDec(-2, 1), inf.NewDec(-2, 1), inf.NewDec(-2, 1), - inf.NewDec(-1, 1), inf.NewDec(-1, 1), inf.NewDec(-1, 1), - inf.NewDec(0, 1), - inf.NewDec(0, 1), inf.NewDec(0, 1), inf.NewDec(0, 1), - inf.NewDec(1, 1), inf.NewDec(1, 1), inf.NewDec(1, 1)}}, - {inf.RoundCeil, [...]*inf.Dec{ - inf.NewDec(2, 0), inf.NewDec(-1, 0), inf.NewDec(-1, 0), inf.NewDec(2, 0), - inf.NewDec(-1, 1), inf.NewDec(-1, 1), inf.NewDec(-1, 1), - inf.NewDec(0, 1), inf.NewDec(0, 1), inf.NewDec(0, 1), - inf.NewDec(0, 1), - inf.NewDec(1, 1), inf.NewDec(1, 1), inf.NewDec(1, 1), - inf.NewDec(2, 1), inf.NewDec(2, 1), inf.NewDec(2, 1)}}, -} - -func TestDecRounders(t *testing.T) { - for i, a := range decRounderResults { - for j, input := range decRounderInputs { - q := new(inf.Dec).Set(input.quo) - rA, rB := new(big.Int).Set(input.rA), new(big.Int).Set(input.rB) - res := a.rounder.Round(new(inf.Dec), q, rA, rB) - if a.results[j] == nil && res == nil { - continue - } - if (a.results[j] == nil && res != nil) || - (a.results[j] != nil && res == nil) || - a.results[j].Cmp(res) != 0 { - t.Errorf("#%d,%d Rounder got %v; expected %v", i, j, res, a.results[j]) - } - } - } -}